Prompt specification
Build or customize the Three.js 3D scene "Histogram boundary exploration 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: Histogram boundary exploration tool
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/histogram-boundary-exploration-tool-x1800
Scene Description Prompt:
Create a standalone low-poly scene in one HTML file using Three.js from cdnjs. Allow changing bin width and origin while showing the unchanged raw points; update counts exactly and define how observations on boundaries are assigned.
Working Three.js Starter (histogram-boundary-exploration-tool-x1800):
```html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Low-Poly Binning Explorer</title>
<style>
:root {
color-scheme: dark;
--bg: #09111d;
--panel: rgba(13, 24, 39, 0.88);
--panel-border: rgba(151, 190, 220, 0.16);
--text: #e7f0f7;
--muted: #91a7ba;
--cyan: #56d8ca;
--amber: #ffc266;
--coral: #ff7188;
--danger: #ff8d98;
}
* {
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;
}
button,
input {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
.panel {
position: fixed;
z-index: 5;
border: 1px solid var(--panel-border);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 18px 60px rgba(0, 0, 0, 0.32);
backdrop-filter: blur(16px);
-webkit-backdrop-filter: blur(16px);
}
.controls {
top: 18px;
left: 18px;
width: min(340px, calc(100vw - 36px));
padding: 18px;
}
.results {
top: 18px;
right: 18px;
width: min(360px, calc(100vw - 36px));
max-height: calc(100vh - 36px);
padding: 18px;
overflow: auto;
}
h1 {
margin: 0;
font-size: 21px;
line-height: 1.2;
letter-spacing: -0.02em;
}
.subtitle {
margin: 7px 0 18px;
color: var(--muted);
font-size: 12px;
line-height: 1.5;
}
.control-group {
padding: 14px 0;
border-top: 1px solid rgba(151, 190, 220, 0.12);
}
.control-label {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 12px;
margin-bottom: 9px;
font-size: 12px;
font-weight: 700;
letter-spacing: 0.02em;
}
output {
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
}
.input-row {
display: grid;
grid-template-columns: 88px 1fr;
align-items: center;
gap: 11px;
}
input[type="number"] {
width: 100%;
min-width: 0;
padding: 8px 9px;
border: 1px solid rgba(151, 190, 220, 0.24);
border-radius: 9px;
outline: none;
background: rgba(5, 12, 22, 0.7);
color: var(--text);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
input[type="number"]:focus {
border-color: var(--cyan);
box-shadow: 0 0 0 3px rgba(86, 216, 202, 0.12);
}
input[type="range"] {
width: 100%;
accent-color: var(--cyan);
cursor: pointer;
}
.hint {
margin-top: 7px;
color: var(--muted);
font-size: 10.5px;
line-height: 1.45;
}
.check-row {
display: flex;
align-items: center;
gap: 9px;
padding: 12px 0;
border-top: 1px solid rgba(151, 190, 220, 0.12);
color: var(--muted);
font-size: 12px;
cursor: pointer;
}
.check-row input {
width: 16px;
height: 16px;
accent-color: var(--coral);
}
button {
width: 100%;
padding: 9px 12px;
border: 1px solid rgba(86, 216, 202, 0.34);
border-radius: 10px;
background: rgba(86, 216, 202, 0.08);
color: var(--cyan);
font-size: 12px;
font-weight: 700;
cursor: pointer;
}
button:hover {
background: rgba(86, 216, 202, 0.15);
}
.status {
min-height: 30px;
margin-top: 10px;
color: var(--muted);
font-size: 10.5px;
line-height: 1.45;
}
.status.error {
color: var(--danger);
}
.stats {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
margin: 14px 0;
}
.stat {
padding: 10px;
border: 1px solid rgba(151, 190, 220, 0.11);
border-radius: 11px;
background: rgba(4, 10, 18, 0.3);
}
.stat span {
display: block;
margin-bottom: 4px;
color: var(--muted);
font-size: 9px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.stat strong {
display: block;
overflow: hidden;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 13px;
text-overflow: ellipsis;
white-space: nowrap;
}
.section-title {
margin: 16px 0 8px;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
color: var(--muted);
}
.count-list {
max-height: 300px;
overflow: auto;
padding-right: 3px;
}
.count-row {
display: grid;
grid-template-columns: minmax(0, 1fr) 66px 27px;
align-items: center;
gap: 8px;
padding: 7px 0;
border-bottom: 1px solid rgba(151, 190, 220, 0.08);
}
.interval {
min-width: 0;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 10px;
white-space: nowrap;
}
.interval small {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 8px;
}
.count-track {
height: 6px;
overflow: hidden;
border-radius: 999px;
background: rgba(151, 190, 220, 0.11);
}
.count-fill {
display: block;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--cyan), var(--amber));
}
.count-value {
text-align: right;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 11px;
}
.rule {
padding: 12px;
border: 1px solid rgba(255, 194, 102, 0.2);
border-radius: 12px;
background: rgba(255, 194, 102, 0.055);
color: #d8e3ec;
font-size: 10.5px;
line-height: 1.55;
}
.rule strong {
color: var(--amber);
}
code {
color: var(--cyan);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
.legend {
position: fixed;
z-index: 4;
left: 18px;
bottom: 18px;
display: flex;
flex-wrap: wrap;
gap: 12px;
padding: 9px 12px;
border: 1px solid var(--panel-border);
border-radius: 12px;
background: rgba(13, 24, 39, 0.78);
color: var(--muted);
font-size: 10px;
backdrop-filter: blur(12px);
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 9px;
height: 9px;
border-radius: 2px;
background: var(--cyan);
}
.swatch.raw {
background: var(--coral);
transform: rotate(45deg);
border-radius: 1px;
}
.swatch.origin {
width: 3px;
height: 13px;
background: var(--amber);
}
.camera-hint {
position: fixed;
z-index: 4;
right: 18px;
bottom: 18px;
padding: 8px 11px;
border: 1px solid var(--panel-border);
border-radius: 10px;
background: rgba(13, 24, 39, 0.72);
color: var(--muted);
font-size: 10px;
backdrop-filter: blur(12px);
}
#tooltip {
position: fixed;
z-index: 10;
min-width: 185px;
padding: 9px 11px;
border: 1px solid rgba(255, 113, 136, 0.35);
border-radius: 9px;
background: rgba(8, 15, 26, 0.94);
box-shadow: 0 10px 30px rgba(0, 0, 0, 0.35);
color: var(--text);
font-size: 10px;
line-height: 1.55;
pointer-events: none;
}
#tooltip strong {
color: var(--coral);
}
#loading {
position: fixed;
z-index: 20;
inset: 0;
display: grid;
place-items: center;
background: var(--bg);
color: var(--muted);
font-size: 13px;
}
@media (max-width: 760px) {
.controls {
top: 10px;
left: 10px;
width: calc(100vw - 20px);
padding: 13px;
}
.controls .subtitle,
.controls .hint {
display: none;
}
.control-group {
padding: 10px 0;
}
.results {
top: auto;
right: 10px;
bottom: 48px;
width: calc(100vw - 20px);
max-height: 35vh;
padding: 13px;
}
.legend {
left: 10px;
bottom: 10px;
max-width: calc(100vw - 20px);
}
.camera-hint {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive three-dimensional histogram and raw observations"></canvas>
<section class="panel controls" aria-label="Binning controls">
<h1>Low-Poly Binning Explorer</h1>
<p class="subtitle">
Change the bin geometry while the raw observation points remain fixed.
Hover a coral point to inspect its exact assignment.
</p>
<div class="control-group">
<label class="control-label" for="widthNumber">
<span>Bin width</span>
<output id="widthOutput">0.50</output>
</label>
<div class="input-row">
<input
id="widthNumber"
type="number"
min="0.05"
max="5"
step="0.01"
value="0.50"
aria-label="Bin width"
>
<input
id="widthRange"
type="range"
min="0.25"
max="2.50"
step="0.25"
value="0.50"
aria-label="Bin width slider"
>
</div>
<div class="hint">Values from 0.05 through 5 are supported.</div>
</div>
<div class="control-group">
<label class="control-label" for="originNumber">
<span>Bin origin / phase</span>
<output id="originOutput">-2.00</output>
</label>
<div class="input-row">
<input
id="originNumber"
type="number"
min="-3"
max="2"
step="0.01"
value="-2.00"
aria-label="Bin origin"
>
<input
id="originRange"
type="range"
min="-3"
max="2"
step="0.25"
value="-2.00"
aria-label="Bin origin slider"
>
</div>
<div class="hint">
The origin is a boundary phase. The displayed range expands to include
every observation. Moving the origin by one full width gives the same grid.
</div>
</div>
<label class="check-row">
<input id="rawToggle" type="checkbox" checked>
Show unchanged raw observations
</label>
<button id="resetButton" type="button">Reset binning</button>
<div id="status" class="status" aria-live="polite"></div>
</section>
<section class="panel results" aria-label="Exact bin counts">
<h1 style="font-size:17px">Exact counts</h1>
<div class="stats">
<div class="stat">
<span>Observations</span>
<strong id="statObservations">32</strong>
</div>
<div class="stat">
<span>Binned</span>
<strong id="statAssigned">32 / 32</strong>
</div>
<div class="stat">
<span>Number of bins</span>
<strong id="statBins">—</strong>
</div>
<div class="stat">
<span>Largest count</span>
<strong id="statMaximum">—</strong>
</div>
</div>
<div class="section-title">Displayed bin intervals</div>
<div id="countList" class="count-list"></div>
<div class="section-title">Boundary rule</div>
<div class="rule">
Every bin is <strong>half-open: [L, R)</strong>.
<strong>L is included</strong> and <strong>R is excluded</strong>.
Therefore, an observation exactly on a shared boundary belongs to the
bin on its <strong>right</strong>. There is no special final-bin exception:
the displayed range extends beyond the maximum observation.
<br><br>
For origin <code>o</code> and width <code>w</code>, the bin index is
<code>k = floor((x - o) / w)</code>, and the interval is
<code>[o + kw, o + (k + 1)w)</code>.
</div>
</section>
<div class="legend" aria-label="Scene legend">
<span class="legend-item"><i class="swatch"></i>Histogram bins</span>
<span class="legend-item"><i class="swatch raw"></i>Raw observations</span>
<span class="legend-item"><i class="swatch origin"></i>Origin boundary</span>
</div>
<div class="camera-hint">Drag to orbit · scroll to zoom · hover raw points to inspect</div>
<div id="tooltip" hidden></div>
<div id="loading">Loading Three.js scene…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (id) => document.getElementById(id);
const canvas = $("scene");
/*
* Fixed source data. Values are stored in integer hundredths.
* Control values are stored in integer ten-thousandths so boundary
* calculations never depend on floating-point rounding.
*/
const sourceData = [
-2.00, -1.75, -1.50, -1.25, -1.00, -0.75, -0.50, -0.25,
0.00, 0.25, 0.50, 0.75, 1.00, 1.25, 1.50, 1.75,
2.00, 2.25, 2.50, 2.75, 3.00, 3.25,
-1.00, -0.50, 0.00, 0.25, 0.75, 1.00, 1.50, 2.00, 2.75
];
const RAW_SCALE = 100;
const CONTROL_SCALE = 10000;
const WORLD_SCALE = 2;
const rawUnits = sourceData.map(
(value) => Math.round(value * RAW_SCALE) * (CONTROL_SCALE / RAW_SCALE)
);
const minRaw = Math.min(...rawUnits);
const maxRaw = Math.max(...rawUnits);
let currentBins = [];
let currentStartK = 0;
let currentWidth = 5000;
let currentOrigin = -20000;
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: false
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x09111d);
scene.fog = new THREE.Fog(0x09111d, 19, 34);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(1.15, 1.05, 0.45);
let cameraTheta = 0.78;
let cameraPhi = 1.12;
let cameraRadius = 14.5;
function updateCamera() {
const sinPhi = Math.sin(cameraPhi);
camera.position.set(
cameraTarget.x + cameraRadius * sinPhi * Math.cos(cameraTheta),
cameraTarget.y + cameraRadius * Math.cos(cameraPhi),
cameraTarget.z + cameraRadius * sinPhi * Math.sin(cameraTheta)
);
camera.lookAt(cameraTarget);
}
updateCamera();
const ambient = new THREE.HemisphereLight(0xb9ddff, 0x17202c, 1.9);
scene.add(ambient);
const keyLight = new THREE.DirectionalLight(0xfff1d7, 2.7);
keyLight.position.set(-4, 9, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -12;
keyLight.shadow.camera.right = 12;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -8;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x58d8ff, 1.15);
rimLight.position.set(8, 4, -7);
scene.add(rimLight);
// Low-poly ground and grid.
const base = new THREE.Mesh(
new THREE.BoxGeometry(13.5, 0.16, 5.8),
new THREE.MeshStandardMaterial({
color: 0x111d2b,
roughness: 0.95,
metalness: 0,
flatShading: true
})
);
base.position.set(1.15, -0.11, 0.72);
base.receiveShadow = true;
scene.add(base);
const grid = new THREE.GridHelper(18, 36, 0x36536a, 0x1c3041);
grid.position.x = 1.15;
grid.position.y = -0.015;
grid.material.transparent = true;
grid.material.opacity = 0.62;
scene.add(grid);
// Histogram baseline.
const baselineGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(minRaw / CONTROL_SCALE * WORLD_SCALE, 0.035, 0.76),
new THREE.Vector3(maxRaw / CONTROL_SCALE * WORLD_SCALE, 0.035, 0.76)
]);
scene.add(
new THREE.Line(
baselineGeometry,
new THREE.LineBasicMaterial({ color: 0x7ea8bd })
)
);
// Raw-observation rail. Its x coordinate is the observation value.
const railGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(minRaw / CONTROL_SCALE * WORLD_SCALE, 0.13, 2.42),
new THREE.Vector3(maxRaw / CONTROL_SCALE * WORLD_SCALE, 0.13, 2.42)
]);
scene.add(
new THREE.Line(
railGeometry,
new THREE.LineBasicMaterial({ color: 0x81465a })
)
);
const histogramGroup = new THREE.Group();
const rawPointsGroup = new THREE.Group();
scene.add(histogramGroup, rawPointsGroup);
/*
* Raw points are created once and are never moved when controls change.
* Equal observations are stacked vertically only to keep duplicates visible;
* their horizontal coordinate is always the exact observation value.
*/
const occurrence = new Map();
const rawMaterial = new THREE.MeshStandardMaterial({
color: 0xff7188,
roughness: 0.58,
metalness: 0.06,
flatShading: true
});
for (const valueUnits of rawUnits) {
const ordinal = occurrence.get(valueUnits) || 0;
occurrence.set(valueUnits, ordinal + 1);
const point = new THREE.Mesh(
new THREE.OctahedronGeometry(0.13, 0),
rawMaterial
);
point.position.set(
valueUnits / CONTROL_SCALE * WORLD_SCALE,
0.31 + ordinal * 0.27,
2.42
);
point.rotation.set(0.3, ordinal * 0.7, 0.15);
point.castShadow = true;
point.userData.valueUnits = valueUnits;
rawPointsGroup.add(point);
}
// Amber marker for the origin boundary.
const originMarker = new THREE.Group();
const originLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, 0.04, -0.92),
new THREE.Vector3(0, 3.12, -0.92)
]),
new THREE.LineBasicMaterial({ color: 0xffc266 })
);
const originDiamond = new THREE.Mesh(
new THREE.OctahedronGeometry(0.12, 0),
new THREE.MeshStandardMaterial({
color: 0xffc266,
emissive: 0x4c2c00,
flatShading: true
})
);
originDiamond.position.set(0, 3.18, -0.92);
originMarker.add(originLine, originDiamond);
scene.add(originMarker);
// A small canvas-based label, made with core Three.js only.
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 512;
labelCanvas.height = 96;
const labelContext = labelCanvas.getContext("2d");
const labelTexture = new THREE.CanvasTexture(labelCanvas);
labelTexture.colorSpace = THREE.SRGBColorSpace;
const originLabel = new THREE.Sprite(
new THREE.SpriteMaterial({
map: labelTexture,
transparent: true,
depthTest: false
})
);
originLabel.position.set(0, 3.57, -0.92);
originLabel.scale.set(2.35, 0.44, 1);
originMarker.add(originLabel);
function updateOriginLabel(text) {
labelContext.clearRect(0, 0, labelCanvas.width, labelCanvas.height);
labelContext.fillStyle = "rgba(8, 15, 26, 0.9)";
labelContext.beginPath();
labelContext.roundRect(4, 4, 504, 88, 18);
labelContext.fill();
labelContext.strokeStyle = "rgba(255, 194, 102, 0.55)";
labelContext.lineWidth = 3;
labelContext.stroke();
labelContext.fillStyle = "#ffc266";
labelContext.font = "600 34px monospace";
labelContext.textAlign = "center";
labelContext.textBaseline = "middle";
labelContext.fillText(text, 256, 49);
labelTexture.needsUpdate = true;
}
function formatUnits(units) {
const negative = units < 0;
const absolute = Math.abs(units);
const whole = Math.floor(absolute / CONTROL_SCALE);
const fraction = String(absolute % CONTROL_SCALE)
.padStart(4, "0")
.replace(/0+$/, "");
return `${negative ? "-" : ""}${whole}${fraction ? "." + fraction : ""}`;
}
function parseScaled(text) {
if (text.trim() === "") {
return { ok: false, message: "Enter a numeric value." };
}
const number = Number(text);
if (!Number.isFinite(number)) {
return { ok: false, message: "Enter a finite numeric value." };
}
const scaled = number * CONTROL_SCALE;
const rounded = Math.round(scaled);
if (Math.abs(scaled - rounded) > 1e-6) {
return {
ok: false,
message: "Use no more than four decimal places for exact boundaries."
};
}
return { ok: true, value: rounded };
}
function floorDivide(integerNumerator, positiveDenominator) {
return Math.floor(integerNumerator / positiveDenominator);
}
function clearHistogram() {
histogramGroup.traverse((object) => {
if (object.geometry) object.geometry.dispose();
if (object.material) object.material.dispose();
});
histogramGroup.clear();
}
function colorForCount(count, maximum) {
const low = new THREE.Color(0x48d7c8);
const high = new THREE.Color(0xffb45f);
return low.lerp(high, maximum <= 1 ? 0 : (count - 1) / (maximum - 1));
}
function buildHistogram(bins) {
clearHistogram();
const maximum = Math.max(...bins.map((bin) => bin.count), 0);
for (const bin of bins) {
const visualWidth =
((bin.rightUnits - bin.leftUnits) / CONTROL_SCALE) * WORLD_SCALE;
const height = bin.count === 0 ? 0.035 : bin.count * 0.62;
const centerX =
((bin.leftUnits + bin.rightUnits) / (2 * CONTROL_SCALE)) * WORLD_SCALE;
const material = new THREE.MeshStandardMaterial({
color:
bin.count === 0
? 0x213448
: colorForCount(bin.count, maximum),
roughness: 0.78,
metalness: 0.02,
flatShading: true
});
const box = new THREE.Mesh(
new THREE.BoxGeometry(visualWidth, height, 1.18),
material
);
box.position.set(centerX, height / 2, 0);
box.castShadow = true;
box.receiveShadow = true;
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(box.geometry),
new THREE.LineBasicMaterial({
color: 0x07111c,
transparent: true,
opacity: 0.82
})
);
edges.position.copy(box.position);
histogramGroup.add(box, edges);
}
}
function buildCountList(bins) {
const list = $("countList");
const fragment = document.createDocumentFragment();
const maximum = Math.max(...bins.map((bin) => bin.count), 0);
for (const bin of bins) {
const row = document.createElement("div");
row.className = "count-row";
const interval = document.createElement("div");
interval.className = "interval";
const intervalText = document.createElement("span");
intervalText.textContent =
`[${formatUnits(bin.leftUnits)}, ${formatUnits(bin.rightUnits)})`;
const index = document.createElement("small");
index.textContent = `k = ${bin.k}`;
interval.append(intervalText, index);
const track = document.createElement("div");
track.className = "count-track";
const fill = document.createElement("i");
fill.className = "count-fill";
fill.style.width = maximum > 0 ? `${(bin.count / maximum) * 100}%` : "0%";
track.append(fill);
const value = document.createElement("strong");
value.className = "count-value";
value.textContent = bin.count;
row.append(interval, track, value);
fragment.append(row);
}
list.replaceChildren(fragment);
list.scrollTop = 0;
}
function updateBins() {
const widthResult = parseScaled($("widthNumber").value);
const originResult = parseScaled($("originNumber").value);
if (!widthResult.ok) {
setStatus(widthResult.message, true);
return;
}
if (!originResult.ok) {
setStatus(originResult.message, true);
return;
}
const width = widthResult.value;
const origin = originResult.value;
if (width < 500) {
setStatus("Bin width must be at least 0.05.", true);
return;
}
if (width > 50000) {
setStatus("Bin width must not exceed 5.", true);
return;
}
if (origin < -30000 || origin > 20000) {
setStatus("Origin must be between -3 and 2.", true);
return;
}
currentWidth = width;
currentOrigin = origin;
/*
* All observations are binned by:
* k = floor((x - origin) / width)
*
* startK and endK expand the displayed range so every point is included.
*/
currentStartK = floorDivide(minRaw - origin, width);
const endK = floorDivide(maxRaw - origin, width);
const numberOfBins = endK - currentStartK + 1;
const counts = new Array(numberOfBins).fill(0);
for (const valueUnits of rawUnits) {
const k = floorDivide(valueUnits - origin, width);
const index = k - currentStartK;
counts[index] += 1;
}
currentBins = counts.map((count, index) => {
const k = currentStartK + index;
return {
k,
count,
leftUnits: origin + k * width,
rightUnits: origin + (k + 1) * width
};
});
// Update hover metadata without changing any raw point positions.
for (const point of rawPointsGroup.children) {
const valueUnits = point.userData.valueUnits;
const k = floorDivide(valueUnits - origin, width);
const index = k - currentStartK;
point.userData.binIndex = index;
point.userData.leftUnits = currentBins[index].leftUnits;
point.userData.rightUnits = currentBins[index].rightUnits;
point.userData.binCount = currentBins[index].count;
}
const totalAssigned = counts.reduce((sum, count) => sum + count, 0);
const maximum = Math.max(...counts, 0);
$("widthOutput").textContent = formatUnits(width);
$("originOutput").textContent = formatUnits(origin);
$("statObservations").textContent = sourceData.length;
$("statAssigned").textContent = `${totalAssigned} / ${sourceData.length}`;
$("statBins").textContent = numberOfBins;
$("statMaximum").textContent = maximum;
buildHistogram(currentBins);
buildCountList(currentBins);
originMarker.position.x = (origin / CONTROL_SCALE) * WORLD_SCALE;
updateOriginLabel(`o = ${formatUnits(origin)}`);
setStatus(
`Updated exactly: ${totalAssigned} of ${sourceData.length} observations assigned.`,
false
);
}
function setStatus(message, isError) {
const status = $("status");
status.textContent = message;
status.classList.toggle("error", isError);
}
function syncRangeFromNumber(numberInput, rangeInput) {
const value = Number(numberInput.value);
const min = Number(rangeInput.min);
const max = Number(rangeInput.max);
if (Number.isFinite(value) && value >= min && value <= max) {
rangeInput.value = String(value);
}
}
$("widthRange").addEventListener("input", () => {
$("widthNumber").value = $("widthRange").value;
updateBins();
});
$("widthNumber").addEventListener("input", () => {
syncRangeFromNumber($("widthNumber"), $("widthRange"));
updateBins();
});
$("originRange").addEventListener("input", () => {
$("originNumber").value = $("originRange").value;
updateBins();
});
$("originNumber").addEventListener("input", () => {
syncRangeFromNumber($("originNumber"), $("originRange"));
updateBins();
});
$("rawToggle").addEventListener("change", () => {
rawPointsGroup.visible = $("rawToggle").checked;
$("tooltip").hidden = true;
});
$("resetButton").addEventListener("click", () => {
$("widthNumber").value = "0.50";
$("widthRange").value = "0.50";
$("originNumber").value = "-2.00";
$("originRange").value = "-2.00";
updateBins();
});
// Direct camera controls: no OrbitControls or other addons are used.
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
$("tooltip").hidden = true;
});
canvas.addEventListener("pointerup", (event) => {
dragging = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
});
canvas.addEventListener("pointercancel", () => {
dragging = false;
});
canvas.addEventListener("pointerleave", () => {
if (!dragging) $("tooltip").hidden = true;
});
canvas.addEventListener("pointermove", (event) => {
if (dragging) {
const deltaX = event.clientX - lastPointerX;
const deltaY = event.clientY - lastPointerY;
cameraTheta -= deltaX * 0.006;
cameraPhi = THREE.MathUtils.clamp(
cameraPhi - deltaY * 0.005,
0.25,
1.48
);
lastPointerX = event.clientX;
lastPointerY = event.clientY;
updateCamera();
$("tooltip").hidden = true;
} else {
updateHover(event);
}
});
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
6,
27
);
updateCamera();
},
{ passive: false }
);
// Raycasting is used only for inspection, not for camera movement.
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function updateHover(event) {
if (!rawPointsGroup.visible) {
$("tooltip").hidden = true;
return;
}
const bounds = canvas.getBoundingClientRect();
pointer.x = ((event.clientX - bounds.left) / bounds.width) * 2 - 1;
pointer.y = -((event.clientY - bounds.top) / bounds.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
const hit = raycaster.intersectObjects(rawPointsGroup.children, false)[0];
if (!hit) {
$("tooltip").hidden = true;
return;
}
const data = hit.object.userData;
const tooltip = $("tooltip");
tooltip.innerHTML =
`<strong>Raw observation x = ${formatUnits(data.valueUnits)}</strong><br>` +
`Assigned bin: [${formatUnits(data.leftUnits)}, ${formatUnits(data.rightUnits)})<br>` +
`Observations in this bin: ${data.binCount}`;
tooltip.hidden = false;
const tooltipWidth = 205;
const left = Math.min(
event.clientX + 14,
window.innerWidth - tooltipWidth - 10
);
const top = Math.min(
event.clientY + 14,
window.innerHeight - 90
);
tooltip.style.left = `${Math.max(10, left)}px`;
tooltip.style.top = `${Math.max(10, top)}px`;
}
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
window.addEventListener("resize", resize);
updateBins();
resize();
$("loading").style.display = "none";
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```