Prompt specification
Build or customize the Three.js 3D scene "Random and convenience sample comparison" inside the active workspace.
Engineering Constraints:
1. Runtime & Orbit: Use Three.js r160 with OrbitControls (damping enabled) and ACESFilmicToneMapping.
2. Frame Timing: Drive all motion strictly with clock.getDelta() so animation speed is FPS-independent.
3. Viewport Hygiene: Handle window resize cleanly, cap DPR at Math.min(window.devicePixelRatio, 2), and dispose geometries/materials/renderer on unmount.
Scene Metadata:
Scene: Random and convenience sample comparison
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/random-and-convenience-sample-comparison-x1830
Scene Description Prompt:
I'd like to see this as a stylized Three.js scene: random and convenience sample comparison. Draw equal-size samples by uniform random selection and by proximity to a booth; compare estimates against the known synthetic population value. Use cdnjs and return one self-contained HTML file.
Working Three.js Starter (random-and-convenience-sample-comparison-x1830):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Sampling Field — Random vs. Convenience</title>
<style>
:root {
color-scheme: dark;
--ink: #eef7ff;
--muted: #91a5bb;
--panel: rgba(10, 20, 34, 0.84);
--panel-border: rgba(174, 213, 241, 0.16);
--random: #ffbd66;
--near: #54dcff;
--good: #61e4b0;
--bad: #ff7e86;
--ground: #07111f;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--ground);
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#app {
position: relative;
width: 100%;
height: 100%;
isolation: isolate;
}
#scene {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
.vignette {
position: absolute;
inset: 0;
z-index: 1;
pointer-events: none;
background:
radial-gradient(circle at 48% 43%, transparent 36%, rgba(2, 8, 17, 0.28) 78%),
linear-gradient(90deg, rgba(3, 9, 17, 0.38), transparent 38%, rgba(3, 9, 17, 0.08));
}
.chrome {
position: absolute;
inset: 0;
z-index: 2;
pointer-events: none;
}
.brand {
position: absolute;
top: 30px;
left: 32px;
width: min(560px, 52vw);
text-shadow: 0 2px 24px rgba(0, 0, 0, 0.5);
}
.eyebrow {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 13px;
color: #a9bed1;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 24px;
height: 2px;
border-radius: 2px;
background: var(--near);
box-shadow: 0 0 14px rgba(84, 220, 255, 0.7);
}
h1 {
margin: 0;
max-width: 540px;
font-size: clamp(34px, 4.4vw, 62px);
line-height: 0.98;
letter-spacing: -0.055em;
font-weight: 780;
}
h1 span {
color: var(--near);
}
.brand p {
max-width: 470px;
margin: 18px 0 0;
color: #a8bacd;
font-size: 14px;
line-height: 1.65;
}
.panel {
position: absolute;
top: 22px;
right: 22px;
width: 370px;
max-height: calc(100vh - 44px);
overflow: auto;
padding: 21px;
border: 1px solid var(--panel-border);
border-radius: 22px;
background:
linear-gradient(145deg, rgba(18, 33, 51, 0.94), rgba(7, 16, 29, 0.9));
box-shadow:
0 22px 70px rgba(0, 0, 0, 0.38),
inset 0 1px rgba(255, 255, 255, 0.04);
backdrop-filter: blur(18px);
pointer-events: auto;
scrollbar-width: thin;
scrollbar-color: #30485f transparent;
}
.panel-top {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 14px;
}
.section-kicker {
margin-bottom: 7px;
color: #8097ad;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
}
.panel h2 {
margin: 0;
font-size: 24px;
line-height: 1.08;
letter-spacing: -0.035em;
}
.population-pill {
flex: 0 0 auto;
padding: 7px 9px;
border: 1px solid rgba(97, 228, 176, 0.22);
border-radius: 999px;
color: #a4f3cf;
background: rgba(97, 228, 176, 0.08);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.intro {
margin: 12px 0 16px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.control-label {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
color: #c6d4e1;
font-size: 11px;
font-weight: 750;
}
.control-label output {
color: var(--near);
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 0;
border-radius: 999px;
appearance: none;
background: linear-gradient(90deg, var(--near), rgba(84, 220, 255, 0.18));
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 17px;
height: 17px;
border: 3px solid #102236;
border-radius: 50%;
appearance: none;
background: #dff8ff;
box-shadow: 0 0 0 1px var(--near), 0 0 15px rgba(84, 220, 255, 0.55);
}
input[type="range"]::-moz-range-thumb {
width: 13px;
height: 13px;
border: 3px solid #102236;
border-radius: 50%;
background: #dff8ff;
box-shadow: 0 0 0 1px var(--near), 0 0 15px rgba(84, 220, 255, 0.55);
}
.draw-button {
position: relative;
width: 100%;
margin-top: 15px;
padding: 12px 15px;
overflow: hidden;
border: 1px solid rgba(84, 220, 255, 0.48);
border-radius: 12px;
color: #06131d;
background: linear-gradient(135deg, #7ee8ff, #45cce9);
box-shadow: 0 8px 26px rgba(44, 197, 224, 0.16);
font-size: 12px;
font-weight: 850;
cursor: pointer;
transition: transform 160ms ease, filter 160ms ease, opacity 160ms ease;
}
.draw-button:hover:not(:disabled) {
transform: translateY(-1px);
filter: brightness(1.08);
}
.draw-button:active:not(:disabled) {
transform: translateY(1px);
}
.draw-button:disabled {
cursor: wait;
opacity: 0.62;
}
.draw-button::after {
content: "";
position: absolute;
inset: 0;
transform: translateX(-105%);
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.42), transparent);
animation: sheen 2.8s infinite;
}
@keyframes sheen {
0%, 52% { transform: translateX(-105%); }
78%, 100% { transform: translateX(105%); }
}
.status {
min-height: 16px;
margin-top: 8px;
color: #7890a8;
font-size: 10px;
text-align: center;
}
.divider {
height: 1px;
margin: 17px 0;
background: linear-gradient(90deg, transparent, rgba(163, 198, 224, 0.18), transparent);
}
.truth {
padding: 14px;
border: 1px solid rgba(97, 228, 176, 0.17);
border-radius: 14px;
background:
radial-gradient(circle at 100% 0, rgba(97, 228, 176, 0.12), transparent 52%),
rgba(5, 14, 24, 0.38);
}
.truth-label {
color: #9eb1c3;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.truth-number {
margin-top: 5px;
font-size: 38px;
font-weight: 780;
line-height: 1;
letter-spacing: -0.05em;
font-variant-numeric: tabular-nums;
}
.truth-number small {
margin-left: 5px;
color: #698296;
font-size: 12px;
font-weight: 650;
letter-spacing: 0;
}
.truth-meta {
margin-top: 7px;
color: #7992a7;
font-size: 10px;
}
.comparison {
margin-top: 15px;
}
.metric {
margin-bottom: 13px;
}
.metric-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 7px;
font-size: 11px;
}
.metric-name {
display: flex;
align-items: center;
gap: 7px;
color: #d7e3ed;
font-weight: 750;
}
.metric-name i {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--random);
box-shadow: 0 0 10px currentColor;
}
.metric.near .metric-name i {
background: var(--near);
}
.metric-value {
font-size: 17px;
font-weight: 800;
font-variant-numeric: tabular-nums;
}
.metric-error {
min-width: 70px;
color: #7890a7;
font-size: 9px;
text-align: right;
font-variant-numeric: tabular-nums;
}
.metric-error.good { color: var(--good); }
.metric-error.warn { color: var(--random); }
.metric-error.bad { color: var(--bad); }
.bar-track {
position: relative;
height: 7px;
overflow: visible;
border-radius: 999px;
background: rgba(120, 151, 176, 0.12);
}
.bar-fill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, #e99157, var(--random));
box-shadow: 0 0 13px rgba(255, 189, 102, 0.3);
transition: width 650ms cubic-bezier(.2, .8, .2, 1);
}
.near .bar-fill {
background: linear-gradient(90deg, #278bb4, var(--near));
box-shadow: 0 0 13px rgba(84, 220, 255, 0.3);
}
.target-marker {
position: absolute;
top: -4px;
bottom: -4px;
width: 1px;
background: rgba(224, 255, 244, 0.9);
box-shadow: 0 0 6px rgba(97, 228, 176, 0.7);
}
.scale {
display: flex;
justify-content: space-between;
margin-top: 6px;
color: #536b81;
font-size: 8px;
}
.insight {
margin-top: 13px;
padding: 11px 12px;
border-left: 2px solid var(--near);
border-radius: 0 9px 9px 0;
color: #8fa6ba;
background: rgba(84, 220, 255, 0.055);
font-size: 10px;
line-height: 1.55;
}
.insight strong {
color: #dcebf5;
}
.methods {
display: grid;
gap: 8px;
margin-top: 15px;
}
.method {
display: flex;
align-items: flex-start;
gap: 9px;
color: #c4d1dc;
font-size: 10px;
font-weight: 750;
}
.method-dot {
flex: 0 0 auto;
width: 8px;
height: 8px;
margin-top: 2px;
border-radius: 50%;
background: var(--random);
box-shadow: 0 0 8px rgba(255, 189, 102, 0.65);
}
.method-dot.cyan {
background: var(--near);
box-shadow: 0 0 8px rgba(84, 220, 255, 0.65);
}
.method small {
display: block;
margin-top: 2px;
color: #687f94;
font-size: 9px;
font-weight: 500;
}
.utility {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 14px;
}
.equal-note {
color: #71899e;
font-size: 9px;
line-height: 1.4;
}
.reset-button {
flex: 0 0 auto;
padding: 7px 10px;
border: 1px solid rgba(148, 183, 209, 0.18);
border-radius: 8px;
color: #9eb3c5;
background: rgba(125, 157, 184, 0.06);
font-size: 9px;
cursor: pointer;
}
.reset-button:hover {
color: #e9f6ff;
background: rgba(125, 157, 184, 0.12);
}
.legend {
position: absolute;
bottom: 29px;
left: 32px;
display: flex;
align-items: flex-end;
gap: 26px;
padding: 13px 15px;
border: 1px solid rgba(156, 195, 223, 0.12);
border-radius: 14px;
background: rgba(6, 15, 27, 0.62);
backdrop-filter: blur(10px);
}
.legend-block {
min-width: 128px;
}
.legend-title {
margin-bottom: 7px;
color: #879caf;
font-size: 8px;
font-weight: 800;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.score-gradient {
width: 138px;
height: 5px;
border-radius: 99px;
background: linear-gradient(90deg, #ff6b72, #ffc766, #61e4b0);
box-shadow: 0 0 12px rgba(97, 228, 176, 0.14);
}
.legend-ends {
display: flex;
justify-content: space-between;
margin-top: 5px;
color: #627a90;
font-size: 8px;
}
.ring-key {
display: flex;
align-items: center;
gap: 9px;
margin-top: 6px;
color: #91a6b9;
font-size: 9px;
}
.ring-key i {
display: inline-block;
width: 14px;
height: 8px;
border: 2px solid var(--random);
border-radius: 50%;
}
.ring-key i.cyan {
width: 9px;
border-color: var(--near);
}
.controls-hint {
position: absolute;
right: 28px;
bottom: 31px;
color: rgba(154, 177, 197, 0.66);
font-size: 9px;
letter-spacing: 0.04em;
}
.booth-label {
position: absolute;
z-index: 4;
transform: translate(-50%, -100%);
padding: 6px 9px;
border: 1px solid rgba(84, 220, 255, 0.35);
border-radius: 999px;
color: #c9f6ff;
background: rgba(6, 23, 35, 0.82);
box-shadow: 0 6px 20px rgba(0, 0, 0, 0.25);
font-size: 8px;
font-weight: 850;
letter-spacing: 0.12em;
text-transform: uppercase;
white-space: nowrap;
pointer-events: none;
}
.tooltip {
position: absolute;
z-index: 8;
min-width: 176px;
padding: 10px 12px;
border: 1px solid rgba(165, 204, 231, 0.2);
border-radius: 10px;
color: #d8e7f1;
background: rgba(5, 14, 25, 0.94);
box-shadow: 0 12px 32px rgba(0, 0, 0, 0.35);
font-size: 10px;
line-height: 1.55;
pointer-events: none;
opacity: 0;
transform: translateY(4px);
transition: opacity 100ms ease, transform 100ms ease;
}
.tooltip.visible {
opacity: 1;
transform: translateY(0);
}
.tooltip strong {
display: block;
margin-bottom: 3px;
color: #fff;
font-size: 11px;
}
.tooltip span {
color: #8098ad;
}
button:focus-visible,
input:focus-visible {
outline: 2px solid #9ceeff;
outline-offset: 3px;
}
@media (max-width: 920px) {
.brand {
top: 20px;
left: 20px;
width: calc(100vw - 40px);
}
.brand p {
max-width: 390px;
}
.panel {
top: auto;
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
max-height: 48vh;
padding: 17px;
border-radius: 18px;
}
.panel h2 {
font-size: 21px;
}
.legend {
bottom: calc(48vh + 25px);
left: 16px;
}
.controls-hint {
display: none;
}
}
@media (max-width: 600px) {
.brand {
top: 16px;
left: 16px;
}
.brand h1 {
max-width: 330px;
font-size: 34px;
}
.brand p {
display: none;
}
.eyebrow {
margin-bottom: 8px;
font-size: 9px;
}
.panel {
max-height: 54vh;
}
.legend {
display: none;
}
.booth-label {
font-size: 7px;
}
}
</style>
</head>
<body>
<main id="app">
<canvas id="scene" aria-label="Interactive 3D comparison of random and convenience samples"></canvas>
<div class="vignette"></div>
<div class="chrome">
<header class="brand">
<div class="eyebrow">Sampling field / Experiment 01</div>
<h1>Near is not<br>the same as <span>representative.</span></h1>
<p>
Draw equal-size samples from one synthetic neighborhood. A uniform random
sample and a booth-proximity sample can tell very different stories.
</p>
</header>
<aside class="panel" aria-label="Sampling controls and results">
<div class="panel-top">
<div>
<div class="section-kicker">Sampling comparison</div>
<h2>Equal samples.<br>Different reach.</h2>
</div>
<div class="population-pill">96 residents</div>
</div>
<p class="intro">
Every resident has a synthetic support score from 0–100. The population
value below is the exact mean across all 96 people.
</p>
<label class="control-label" for="sampleSize">
<span>Sample size for both methods</span>
<output id="sampleSizeLabel">24 residents</output>
</label>
<input id="sampleSize" type="range" min="8" max="40" value="24" step="1">
<button id="drawButton" class="draw-button" type="button">
<span id="drawLabel">Draw equal samples</span>
</button>
<div id="status" class="status" aria-live="polite">Preparing the synthetic population…</div>
<div class="divider"></div>
<section class="truth" aria-label="Known population value">
<div class="truth-label">Known population value</div>
<div class="truth-number">
<span id="knownValue">—</span><small>/ 100</small>
</div>
<div id="knownMeta" class="truth-meta">Exact mean across all 96 residents</div>
</section>
<section class="comparison" aria-label="Sample estimates">
<div class="metric">
<div class="metric-head">
<div class="metric-name"><i></i>Uniform random sample</div>
<div class="metric-value" id="randomValue">—</div>
</div>
<div class="bar-track">
<div class="bar-fill" id="randomBar"></div>
<div class="target-marker" id="randomMarker"></div>
</div>
<div class="scale">
<span>0</span>
<span id="randomError" class="metric-error">waiting</span>
<span>100</span>
</div>
</div>
<div class="metric near">
<div class="metric-head">
<div class="metric-name"><i></i>Booth-proximity sample</div>
<div class="metric-value" id="nearValue">—</div>
</div>
<div class="bar-track">
<div class="bar-fill" id="nearBar"></div>
<div class="target-marker" id="nearMarker"></div>
</div>
<div class="scale">
<span>0</span>
<span id="nearError" class="metric-error">waiting</span>
<span>100</span>
</div>
</div>
</section>
<div id="insight" class="insight">
The white marker on each bar is the exact population value.
</div>
<div class="methods">
<div class="method">
<span class="method-dot"></span>
<span>Uniform random
<small>Every resident has the same chance of selection, without replacement.</small>
</span>
</div>
<div class="method">
<span class="method-dot cyan"></span>
<span>Booth proximity
<small>The selected residents are simply the nearest people to the booth.</small>
</span>
</div>
</div>
<div class="utility">
<div class="equal-note">Both methods always draw exactly<br>the same number of residents.</div>
<button id="resetView" class="reset-button" type="button">Reset view</button>
</div>
</aside>
<div class="legend">
<div class="legend-block">
<div class="legend-title">Resident support score</div>
<div class="score-gradient"></div>
<div class="legend-ends"><span>Low / 0</span><span>High / 100</span></div>
</div>
<div class="legend-block">
<div class="legend-title">Selection markers</div>
<div class="ring-key"><i></i>Uniform random</div>
<div class="ring-key"><i class="cyan"></i>Booth proximity</div>
</div>
</div>
<div class="controls-hint">Drag to orbit · Scroll to zoom · Hover a resident</div>
<div id="boothLabel" class="booth-label">Convenience booth</div>
<div id="tooltip" class="tooltip" role="status"></div>
</div>
</main>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const canvas = document.querySelector("#scene");
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.12;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111f);
scene.fog = new THREE.Fog(0x07111f, 42, 83);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
140
);
const cameraTarget = new THREE.Vector3(2, 0, 0);
const spherical = new THREE.Spherical(51, 1.04, 0.68);
function updateCamera() {
camera.position.setFromSpherical(spherical).add(cameraTarget);
camera.lookAt(cameraTarget);
}
updateCamera();
const hemi = new THREE.HemisphereLight(0xa9ddff, 0x16202a, 2.15);
scene.add(hemi);
const keyLight = new THREE.DirectionalLight(0xdaf2ff, 3.3);
keyLight.position.set(-16, 29, 20);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -31;
keyLight.shadow.camera.right = 31;
keyLight.shadow.camera.top = 27;
keyLight.shadow.camera.bottom = -27;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 75;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x3987b8, 1.5);
rimLight.position.set(25, 12, -22);
scene.add(rimLight);
const BOOTH = { x: -10.5, z: 3.5 };
const POPULATION_SIZE = 96;
const LOW_COLOR = new THREE.Color(0xff6b72);
const HIGH_COLOR = new THREE.Color(0x61e4b0);
const RANDOM_COLOR = 0xffbd66;
const NEAR_COLOR = 0x54dcff;
const population = [];
const pickables = [];
const populationGroup = new THREE.Group();
scene.add(populationGroup);
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;
};
}
const random = mulberry32(74021);
function makeGround() {
const ground = new THREE.Mesh(
new THREE.CylinderGeometry(26, 27, 1.25, 72),
new THREE.MeshStandardMaterial({
color: 0x0c1c2d,
roughness: 0.93,
metalness: 0.06
})
);
ground.position.y = -0.64;
ground.receiveShadow = true;
scene.add(ground);
const surface = new THREE.Mesh(
new THREE.CircleGeometry(25.75, 96),
new THREE.MeshStandardMaterial({
color: 0x102337,
roughness: 0.96,
metalness: 0.02
})
);
surface.rotation.x = -Math.PI / 2;
surface.position.y = 0.005;
surface.receiveShadow = true;
scene.add(surface);
const edge = new THREE.Mesh(
new THREE.TorusGeometry(26.05, 0.08, 8, 96),
new THREE.MeshBasicMaterial({
color: 0x31516d,
transparent: true,
opacity: 0.65
})
);
edge.rotation.x = Math.PI / 2;
edge.position.y = -0.08;
scene.add(edge);
const gridVertices = [];
const radius = 25.4;
for (let x = -24; x <= 24; x += 4) {
const extent = Math.sqrt(radius * radius - x * x);
gridVertices.push(x, 0.028, -extent, x, 0.028, extent);
}
for (let z = -24; z <= 24; z += 4) {
const extent = Math.sqrt(radius * radius - z * z);
gridVertices.push(-extent, 0.028, z, extent, 0.028, z);
}
const gridGeometry = new THREE.BufferGeometry();
gridGeometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(gridVertices, 3)
);
const grid = new THREE.LineSegments(
gridGeometry,
new THREE.LineBasicMaterial({
color: 0x3e607a,
transparent: true,
opacity: 0.22
})
);
scene.add(grid);
for (const distance of [4, 8, 12, 16, 20]) {
const points = [];
for (let i = 0; i <= 120; i++) {
const angle = (i / 120) * Math.PI * 2;
points.push(
new THREE.Vector3(
BOOTH.x + Math.cos(angle) * distance,
0.045,
BOOTH.z + Math.sin(angle) * distance
)
);
}
const line = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(points),
new THREE.LineDashedMaterial({
color: 0x54dcff,
transparent: true,
opacity: distance === 4 ? 0.19 : 0.085,
dashSize: 0.6,
gapSize: 0.55
})
);
line.computeLineDistances();
scene.add(line);
}
}
function addContextBlocks() {
const blockMaterial = new THREE.MeshStandardMaterial({
color: 0x142a3e,
roughness: 0.85,
metalness: 0.08
});
const roofMaterial = new THREE.MeshStandardMaterial({
color: 0x203d55,
emissive: 0x102c40,
emissiveIntensity: 0.22,
roughness: 0.7
});
for (let i = 0; i < 14; i++) {
const angle = (i / 14) * Math.PI * 2 + 0.15;
const radius = 24.25 + random() * 0.5;
const width = 1.4 + random() * 1.3;
const depth = 1.3 + random() * 1.2;
const height = 1.4 + random() * 3.5;
const block = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
blockMaterial
);
block.position.set(
Math.cos(angle) * radius,
height / 2,
Math.sin(angle) * radius
);
block.rotation.y = -angle + Math.PI / 2;
block.castShadow = true;
block.receiveShadow = true;
scene.add(block);
const roof = new THREE.Mesh(
new THREE.BoxGeometry(width * 0.74, 0.13, depth * 0.74),
roofMaterial
);
roof.position.set(block.position.x, height + 0.065, block.position.z);
roof.rotation.y = block.rotation.y;
scene.add(roof);
}
}
function signTexture() {
const signCanvas = document.createElement("canvas");
signCanvas.width = 512;
signCanvas.height = 160;
const context = signCanvas.getContext("2d");
context.fillStyle = "#0b2334";
context.fillRect(0, 0, 512, 160);
context.strokeStyle = "#54dcff";
context.lineWidth = 7;
context.strokeRect(5, 5, 502, 150);
context.fillStyle = "#d9f8ff";
context.font = "800 62px sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText("ASK HERE", 256, 82);
const texture = new THREE.CanvasTexture(signCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
function makeBooth() {
const booth = new THREE.Group();
booth.position.set(BOOTH.x, 0, BOOTH.z);
scene.add(booth);
const base = new THREE.Mesh(
new THREE.CylinderGeometry(1.75, 1.95, 0.25, 12),
new THREE.MeshStandardMaterial({
color: 0x173b50,
roughness: 0.56,
metalness: 0.15
})
);
base.position.y = 0.13;
base.receiveShadow = true;
booth.add(base);
const counter = new THREE.Mesh(
new THREE.BoxGeometry(2.35, 1.05, 1.35),
new THREE.MeshStandardMaterial({
color: 0x1d4a62,
roughness: 0.68,
metalness: 0.08
})
);
counter.position.y = 0.72;
counter.castShadow = true;
booth.add(counter);
const counterTop = new THREE.Mesh(
new THREE.BoxGeometry(2.65, 0.16, 1.62),
new THREE.MeshStandardMaterial({
color: 0x66d9ef,
emissive: 0x1a7189,
emissiveIntensity: 0.4,
roughness: 0.42
})
);
counterTop.position.y = 1.3;
counterTop.castShadow = true;
booth.add(counterTop);
for (const x of [-0.83, 0.83]) {
const pole = new THREE.Mesh(
new THREE.CylinderGeometry(0.09, 0.09, 1.25, 8),
new THREE.MeshStandardMaterial({
color: 0x8bd9e8,
roughness: 0.4,
metalness: 0.35
})
);
pole.position.set(x, 1.93, 0);
pole.castShadow = true;
booth.add(pole);
}
const roof = new THREE.Mesh(
new THREE.CylinderGeometry(1.75, 1.75, 0.38, 8),
new THREE.MeshStandardMaterial({
color: 0x27708a,
emissive: 0x0b4058,
emissiveIntensity: 0.36,
roughness: 0.52,
metalness: 0.15
})
);
roof.position.y = 2.65;
roof.castShadow = true;
booth.add(roof);
const roofTop = new THREE.Mesh(
new THREE.ConeGeometry(0.32, 0.72, 8),
new THREE.MeshStandardMaterial({
color: 0x9bf2ff,
emissive: 0x54dcff,
emissiveIntensity: 1.2,
roughness: 0.35
})
);
roofTop.position.y = 3.18;
booth.add(roofTop);
const sign = new THREE.Mesh(
new THREE.PlaneGeometry(2.2, 0.69),
new THREE.MeshBasicMaterial({
map: signTexture(),
side: THREE.DoubleSide
})
);
sign.position.set(0, 1.94, 0.08);
booth.add(sign);
const light = new THREE.PointLight(0x54dcff, 24, 9, 2);
light.position.set(0, 2.4, 0);
booth.add(light);
const pulse = new THREE.Mesh(
new THREE.TorusGeometry(2.15, 0.035, 6, 80),
new THREE.MeshBasicMaterial({
color: 0x54dcff,
transparent: true,
opacity: 0.5,
depthWrite: false
})
);
pulse.rotation.x = Math.PI / 2;
pulse.position.y = 0.07;
booth.add(pulse);
return { booth, roofTop, pulse };
}
makeGround();
addContextBlocks();
const boothObjects = makeBooth();
function createPopulation() {
const positions = [];
for (let attempt = 0; attempt < 10000 && positions.length < POPULATION_SIZE; attempt++) {
const x = (random() * 2 - 1) * 22.5;
const z = (random() * 2 - 1) * 16.2;
if ((x * x) / (22.5 * 22.5) + (z * z) / (16.2 * 16.2) > 1) {
continue;
}
if (Math.hypot(x - BOOTH.x, z - BOOTH.z) < 2.7) {
continue;
}
let tooClose = false;
for (const position of positions) {
if (Math.hypot(x - position.x, z - position.z) < 0.92) {
tooClose = true;
break;
}
}
if (!tooClose) {
positions.push({ x, z });
}
}
positions.forEach((position, index) => {
const hubDistanceSquared =
(position.x - BOOTH.x) ** 2 + (position.z - BOOTH.z) ** 2;
const score = THREE.MathUtils.clamp(
50 +
22 * Math.exp(-hubDistanceSquared / 130) +
0.16 * position.x +
(random() - 0.5) * 12,
5,
98
);
const color = LOW_COLOR.clone().lerp(
HIGH_COLOR,
THREE.MathUtils.clamp(score / 100, 0, 1)
);
const group = new THREE.Group();
group.position.set(position.x, 0, position.z);
const bodyMaterial = new THREE.MeshStandardMaterial({
color,
emissive: 0x000000,
emissiveIntensity: 0,
roughness: 0.65,
metalness: 0.03
});
const body = new THREE.Mesh(
new THREE.CylinderGeometry(0.29, 0.39, 0.78, 7),
bodyMaterial
);
body.position.y = 0.5;
body.castShadow = true;
body.receiveShadow = true;
const head = new THREE.Mesh(
new THREE.SphereGeometry(0.255, 8, 6),
new THREE.MeshStandardMaterial({
color: color.clone().offsetHSL(0, -0.08, 0.12),
roughness: 0.78
})
);
head.position.y = 1.08;
head.castShadow = true;
group.add(body, head);
populationGroup.add(group);
const agent = {
index,
id: `R-${String(index + 1).padStart(3, "0")}`,
x: position.x,
z: position.z,
score,
distance: Math.hypot(position.x - BOOTH.x, position.z - BOOTH.z),
group,
body,
head,
bodyMaterial
};
body.userData.agent = agent;
head.userData.agent = agent;
pickables.push(body, head);
population.push(agent);
});
}
createPopulation();
const knownValue = population.reduce((sum, agent) => sum + agent.score, 0) / population.length;
const dom = {
knownValue: document.querySelector("#knownValue"),
knownMeta: document.querySelector("#knownMeta"),
sampleSize: document.querySelector("#sampleSize"),
sampleSizeLabel: document.querySelector("#sampleSizeLabel"),
drawButton: document.querySelector("#drawButton"),
drawLabel: document.querySelector("#drawLabel"),
status: document.querySelector("#status"),
randomValue: document.querySelector("#randomValue"),
nearValue: document.querySelector("#nearValue"),
randomError: document.querySelector("#randomError"),
nearError: document.querySelector("#nearError"),
randomBar: document.querySelector("#randomBar"),
nearBar: document.querySelector("#nearBar"),
randomMarker: document.querySelector("#randomMarker"),
nearMarker: document.querySelector("#nearMarker"),
insight: document.querySelector("#insight"),
tooltip: document.querySelector("#tooltip"),
boothLabel: document.querySelector("#boothLabel"),
resetView: document.querySelector("#resetView")
};
dom.knownValue.textContent = knownValue.toFixed(1);
dom.knownValue.parentElement.title = `Exact mean: ${knownValue.toFixed(4)}`;
dom.knownMeta.textContent = `Exact mean across all ${POPULATION_SIZE} residents`;
dom.randomMarker.style.left = `${knownValue}%`;
dom.nearMarker.style.left = `${knownValue}%`;
const selectionFXGroup = new THREE.Group();
scene.add(selectionFXGroup);
const randomRingGeometry = new THREE.TorusGeometry(0.68, 0.065, 6, 28);
const nearRingGeometry = new THREE.TorusGeometry(0.46, 0.055, 6, 24);
const beamGeometry = new THREE.CylinderGeometry(0.035, 0.035, 1.65, 6);
let selectionFX = [];
let pathMesh = null;
let selectedRandom = new Set();
let selectedNear = new Set();
let drawState = null;
function clearSelectionFX() {
for (const fx of selectionFX) {
fx.group.removeFromParent();
for (const material of fx.materials) {
material.dispose();
}
}
selectionFX = [];
if (pathMesh) {
pathMesh.removeFromParent();
pathMesh.geometry.dispose();
pathMesh.material.dispose();
pathMesh = null;
}
}
function makeSelectionFX(agent, type, startTime) {
const isRandom = type === "random";
const color = isRandom ? RANDOM_COLOR : NEAR_COLOR;
const materials = [];
const group = new THREE.Group();
group.position.set(agent.x, 0.08, agent.z);
group.scale.setScalar(0.001);
const ringMaterial = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0,
depthWrite: false
});
materials.push(ringMaterial);
const ring = new THREE.Mesh(
isRandom ? randomRingGeometry : nearRingGeometry,
ringMaterial
);
ring.rotation.x = Math.PI / 2;
group.add(ring);
let beam = null;
if (!isRandom) {
const beamMaterial = new THREE.MeshBasicMaterial({
color,
transparent: true,
opacity: 0,
depthWrite: false
});
materials.push(beamMaterial);
beam = new THREE.Mesh(beamGeometry, beamMaterial);
beam.position.y = 0.82;
group.add(beam);
}
selectionFXGroup.add(group);
const fx = {
agent,
type,
group,
ring,
beam,
materials,
startTime,
duration: 380
};
selectionFX.push(fx);
return fx;
}
function makePaths(agents) {
const positions = [];
for (const agent of agents) {
positions.push(
BOOTH.x, 0.075, BOOTH.z,
agent.x, 0.075, agent.z
);
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.Float32BufferAttribute(positions, 3)
);
geometry.setDrawRange(0, 0);
const material = new THREE.LineBasicMaterial({
color: NEAR_COLOR,
transparent: true,
opacity: 0.19,
depthWrite: false
});
pathMesh = new THREE.LineSegments(geometry, material);
scene.add(pathMesh);
}
function shuffledPopulation() {
const copy = population.slice();
for (let i = copy.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[copy[i], copy[j]] = [copy[j], copy[i]];
}
return copy;
}
function estimateFor(agents) {
return agents.reduce((sum, agent) => sum + agent.score, 0) / agents.length;
}
function formatSigned(value) {
if (Math.abs(value) < 0.05) return "0.0";
return `${value > 0 ? "+" : "−"}${Math.abs(value).toFixed(1)}`;
}
function errorClass(error) {
const absolute = Math.abs(error);
if (absolute <= 2) return "good";
if (absolute <= 5) return "warn";
return "bad";
}
function setResult(type, value) {
const valueElement = type === "random" ? dom.randomValue : dom.nearValue;
const errorElement = type === "random" ? dom.randomError : dom.nearError;
const bar = type === "random" ? dom.randomBar : dom.nearBar;
if (value === null) {
valueElement.textContent = "—";
errorElement.textContent = "drawing…";
errorElement.className = "metric-error";
bar.style.width = "0%";
return;
}
const error = value - knownValue;
valueElement.textContent = value.toFixed(1);
errorElement.textContent = `${formatSigned(error)} pts`;
errorElement.className = `metric-error ${errorClass(error)}`;
bar.style.width = `${THREE.MathUtils.clamp(value, 0, 100)}%`;
}
function updateInsight(randomEstimate, nearEstimate) {
const randomError = Math.abs(randomEstimate - knownValue);
const nearError = Math.abs(nearEstimate - knownValue);
const signedNear = nearEstimate - knownValue;
const direction = signedNear >= 0 ? "above" : "below";
if (nearError > randomError) {
dom.insight.innerHTML =
`<strong>The booth sample is ${nearError.toFixed(1)} points ${direction} the population value.</strong> ` +
`It over-concentres on nearby residents, whose scores differ from the overall population.`;
} else {
dom.insight.innerHTML =
`<strong>On this draw, the random sample is closer to the truth.</strong> ` +
`Sampling error can change from draw to draw, but proximity bias remains structured around the booth.`;
}
}
function drawSamples() {
clearSelectionFX();
const sampleSize = Number(dom.sampleSize.value);
const randomSample = shuffledPopulation().slice(0, sampleSize);
const nearSample = population
.slice()
.sort((a, b) => a.distance - b.distance)
.slice(0, sampleSize);
selectedRandom = new Set(randomSample);
selectedNear = new Set(nearSample);
for (const agent of population) {
agent.bodyMaterial.emissive.set(0x000000);
agent.bodyMaterial.emissiveIntensity = 0;
}
for (const agent of randomSample) {
agent.bodyMaterial.emissive.set(RANDOM_COLOR);
agent.bodyMaterial.emissiveIntensity = 0.16;
}
for (const agent of nearSample) {
agent.bodyMaterial.emissive.set(NEAR_COLOR);
agent.bodyMaterial.emissiveIntensity = 0.24;
}
const now = performance.now();
const randomDuration = sampleSize * 30 + 360;
const nearDuration = sampleSize * 30 + 360;
const nearStart = 480;
randomSample.forEach((agent, index) => {
makeSelectionFX(agent, "random", now + index * 30);
});
nearSample.forEach((agent, index) => {
makeSelectionFX(agent, "near", now + nearStart + index * 30);
});
makePaths(nearSample);
drawState = {
start: now,
sampleSize,
randomSample,
nearSample,
randomDuration,
nearDuration,
nearStart,
randomRevealed: false,
nearRevealed: false,
complete: false
};
setResult("random", null);
setResult("near", null);
dom.drawButton.disabled = true;
dom.drawLabel.textContent = "Drawing samples…";
dom.status.textContent = `Selecting ${sampleSize} uniformly at random…`;
}
function updateDrawAnimation(now) {
if (!drawState) return;
const elapsed = now - drawState.start;
const nearElapsed = elapsed - drawState.nearStart;
for (const fx of selectionFX) {
const local = now - fx.startTime;
if (local <= 0) {
fx.group.visible = false;
continue;
}
fx.group.visible = true;
const progress = THREE.MathUtils.clamp(local / fx.duration, 0, 1);
const eased = 1 - Math.pow(1 - progress, 3);
fx.group.scale.setScalar(Math.max(0.001, eased));
fx.materials[0].opacity = Math.min(1, progress * 1.7) * 0.95;
if (fx.beam) {
fx.materials[1].opacity = Math.min(1, progress * 1.7) * 0.32;
}
if (progress >= 1) {
fx.ring.scale.setScalar(1 + Math.sin(now * 0.004 + fx.agent.index) * 0.035);
}
}
if (pathMesh) {
const pathProgress = THREE.MathUtils.clamp(
nearElapsed / (drawState.nearDuration * 0.82),
0,
1
);
const count = pathMesh.geometry.attributes.position.count;
pathMesh.geometry.setDrawRange(0, Math.floor(pathProgress * count));
}
if (!drawState.randomRevealed && elapsed >= drawState.randomDuration) {
drawState.randomRevealed = true;
const estimate = estimateFor(drawState.randomSample);
setResult("random", estimate);
dom.status.textContent = "Now selecting residents nearest the booth…";
}
if (!drawState.nearRevealed && nearElapsed >= drawState.nearDuration) {
drawState.nearRevealed = true;
const estimate = estimateFor(drawState.nearSample);
setResult("near", estimate);
updateInsight(estimateFor(drawState.randomSample), estimate);
}
if (
drawState.randomRevealed &&
drawState.nearRevealed &&
!drawState.complete
) {
drawState.complete = true;
dom.drawButton.disabled = false;
dom.drawLabel.textContent = "Draw again";
dom.status.textContent =
`Complete — both samples contain exactly ${drawState.sampleSize} residents.`;
}
}
dom.sampleSize.addEventListener("input", () => {
const n = Number(dom.sampleSize.value);
dom.sampleSizeLabel.textContent = `${n} residents`;
dom.sampleSize.setAttribute("aria-valuetext", `${n} residents`);
dom.status.textContent = `Ready to draw ${n} residents per method.`;
});
dom.sampleSize.addEventListener("change", drawSamples);
dom.drawButton.addEventListener("click", drawSamples);
dom.resetView.addEventListener("click", () => {
spherical.set(51, 1.04, 0.68);
cameraTarget.set(2, 0, 0);
updateCamera();
});
// Direct camera controls implemented here without any addons.
let pointerDown = false;
let pointerMoved = false;
let previousX = 0;
let previousY = 0;
canvas.addEventListener("pointerdown", (event) => {
pointerDown = true;
pointerMoved = false;
previousX = event.clientX;
previousY = event.clientY;
canvas.setPointerCapture(event.pointerId);
dom.tooltip.classList.remove("visible");
});
canvas.addEventListener("pointermove", (event) => {
if (pointerDown) {
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
if (Math.abs(dx) + Math.abs(dy) > 3) {
pointerMoved = true;
}
spherical.theta -= dx * 0.006;
spherical.phi = THREE.MathUtils.clamp(
spherical.phi - dy * 0.005,
0.46,
1.38
);
previousX = event.clientX;
previousY = event.clientY;
updateCamera();
return;
}
updateHover(event);
});
canvas.addEventListener("pointerup", (event) => {
pointerDown = false;
if (!pointerMoved) updateHover(event);
});
canvas.addEventListener("pointercancel", () => {
pointerDown = false;
});
canvas.addEventListener("pointerleave", () => {
if (!pointerDown) dom.tooltip.classList.remove("visible");
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
spherical.radius = THREE.MathUtils.clamp(
spherical.radius * Math.exp(event.deltaY * 0.001),
28,
72
);
updateCamera();
},
{ passive: false }
);
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function updateHover(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(pickables, false);
if (!hits.length) {
dom.tooltip.classList.remove("visible");
canvas.style.cursor = "grab";
return;
}
const agent = hits[0].object.userData.agent;
const inRandom = selectedRandom.has(agent);
const inNear = selectedNear.has(agent);
let selection = "Not selected";
if (inRandom && inNear) selection = "Random + proximity sample";
else if (inRandom) selection = "Uniform random sample";
else if (inNear) selection = "Booth-proximity sample";
dom.tooltip.innerHTML =
`<strong>${agent.id}</strong>` +
`Support score: ${agent.score.toFixed(1)} / 100<br>` +
`<span>${selection}<br>` +
`${agent.distance.toFixed(1)} m from the booth</span>`;
const tooltipWidth = 190;
const left = Math.min(
window.innerWidth - tooltipWidth - 10,
Math.max(10, event.clientX + 14)
);
const top = Math.min(
window.innerHeight - 92,
Math.max(10, event.clientY + 14)
);
dom.tooltip.style.left = `${left}px`;
dom.tooltip.style.top = `${top}px`;
dom.tooltip.classList.add("visible");
canvas.style.cursor = "pointer";
}
const projectedBooth = new THREE.Vector3();
function updateBoothLabel() {
projectedBooth.set(BOOTH.x, 4.05, BOOTH.z).project(camera);
const visible = projectedBooth.z < 1;
dom.boothLabel.style.display = visible ? "block" : "none";
dom.boothLabel.style.left =
`${(projectedBooth.x * 0.5 + 0.5) * window.innerWidth}px`;
dom.boothLabel.style.top =
`${(-projectedBooth.y * 0.5 + 0.5) * window.innerHeight}px`;
}
function resize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
}
window.addEventListener("resize", resize);
function animate(now) {
requestAnimationFrame(animate);
updateDrawAnimation(now);
const pulse = 1 + Math.sin(now * 0.0027) * 0.075;
boothObjects.pulse.scale.setScalar(pulse);
boothObjects.pulse.material.opacity = 0.36 + Math.sin(now * 0.0027) * 0.12;
boothObjects.roofTop.rotation.y = now * 0.00035;
updateBoothLabel();
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
setTimeout(drawSamples, 650);
</script>
</body>
</html>
```