Prompt specification
Build or customize the Three.js 3D scene "Base-system regrouping explorer" 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: Base-system regrouping explorer
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/base-system-regrouping-explorer-x1720
Scene Description Prompt:
Make a low-poly place-value explorer switching numeral bases while regrouping blocks without changing total quantity. One HTML file using Three.js from cdnjs.
Working Three.js Starter (base-system-regrouping-explorer-x1720):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Base Camp — Place-Value Explorer</title>
<style>
:root {
--ink: #17342f;
--muted: #687a75;
--paper: #f4f6ef;
--panel: rgba(255, 255, 255, 0.9);
--line: rgba(23, 52, 47, 0.12);
--coral: #ff7255;
--gold: #f1c75b;
--teal: #3eb69c;
--blue: #598ce8;
--purple: #9a78db;
--shadow: 0 18px 45px rgba(30, 58, 50, 0.1);
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
min-height: 100%;
background: #e7ede7;
color: var(--ink);
font-family:
Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
font-variant-numeric: tabular-nums;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
button:focus-visible,
input:focus-visible {
outline: 3px solid rgba(62, 182, 156, 0.4);
outline-offset: 2px;
}
.app {
min-height: 100vh;
display: grid;
grid-template-rows: 72px 1fr;
}
.topbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 24px;
padding: 0 24px;
color: white;
background:
linear-gradient(110deg, rgba(16, 58, 51, 0.98), rgba(24, 78, 67, 0.96));
box-shadow: 0 4px 20px rgba(16, 45, 39, 0.14);
z-index: 5;
}
.brand {
display: flex;
align-items: center;
gap: 13px;
min-width: 0;
}
.brand-mark {
width: 38px;
height: 38px;
position: relative;
flex: 0 0 auto;
}
.brand-mark span {
position: absolute;
width: 16px;
height: 16px;
border-radius: 4px;
transform: rotate(-8deg);
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.12);
}
.brand-mark span:nth-child(1) {
left: 1px;
bottom: 1px;
background: var(--coral);
}
.brand-mark span:nth-child(2) {
left: 13px;
bottom: 1px;
background: var(--gold);
}
.brand-mark span:nth-child(3) {
left: 7px;
top: 1px;
background: var(--teal);
}
.brand-title {
font-size: 18px;
font-weight: 800;
letter-spacing: -0.02em;
white-space: nowrap;
}
.brand-subtitle {
margin-top: 2px;
color: rgba(255, 255, 255, 0.67);
font-size: 11px;
letter-spacing: 0.08em;
text-transform: uppercase;
white-space: nowrap;
}
.top-note {
display: flex;
align-items: center;
gap: 9px;
color: rgba(255, 255, 255, 0.75);
font-size: 13px;
}
.top-note::before {
content: "";
width: 8px;
height: 8px;
border-radius: 50%;
background: #69dbad;
box-shadow: 0 0 0 5px rgba(105, 219, 173, 0.12);
}
.workspace {
min-height: 0;
display: grid;
grid-template-columns: 340px minmax(0, 1fr);
gap: 14px;
padding: 14px;
}
.panel,
.stage {
border: 1px solid rgba(255, 255, 255, 0.75);
border-radius: 22px;
box-shadow: var(--shadow);
}
.panel {
min-height: 0;
overflow: auto;
padding: 20px;
background: var(--panel);
backdrop-filter: blur(16px);
scrollbar-width: thin;
scrollbar-color: rgba(23, 52, 47, 0.18) transparent;
}
.section {
padding-bottom: 20px;
margin-bottom: 20px;
border-bottom: 1px solid var(--line);
}
.section:last-child {
padding-bottom: 0;
margin-bottom: 0;
border-bottom: 0;
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
.eyebrow {
margin: 0;
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.section-number {
color: #9ca9a5;
font-size: 11px;
font-weight: 700;
}
.quantity-row {
display: grid;
grid-template-columns: 42px 1fr 42px;
gap: 8px;
align-items: stretch;
}
.step-button,
.icon-button {
display: grid;
place-items: center;
border: 1px solid var(--line);
border-radius: 12px;
background: #f5f7f2;
cursor: pointer;
transition: 150ms ease;
}
.step-button {
font-size: 23px;
font-weight: 500;
}
.step-button:hover,
.icon-button:hover {
background: #eaf1eb;
transform: translateY(-1px);
}
.quantity-input-wrap {
position: relative;
}
#quantity {
width: 100%;
height: 100%;
min-height: 56px;
padding: 4px 48px 4px 14px;
border: 1px solid var(--line);
border-radius: 14px;
color: var(--ink);
background: white;
font-size: 28px;
font-weight: 800;
text-align: center;
appearance: textfield;
}
#quantity::-webkit-inner-spin-button,
#quantity::-webkit-outer-spin-button {
appearance: none;
margin: 0;
}
.unit-label {
position: absolute;
top: 50%;
right: 12px;
transform: translateY(-50%);
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
pointer-events: none;
}
#quantityRange {
width: 100%;
margin: 14px 0 2px;
accent-color: var(--teal);
cursor: pointer;
}
.range-labels {
display: flex;
justify-content: space-between;
color: #91a09b;
font-size: 10px;
}
.presets {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 6px;
margin-top: 13px;
}
.preset {
padding: 7px 4px;
border: 1px solid var(--line);
border-radius: 9px;
color: var(--muted);
background: transparent;
font-size: 11px;
font-weight: 700;
cursor: pointer;
transition: 140ms ease;
}
.preset:hover {
color: var(--ink);
border-color: rgba(23, 52, 47, 0.25);
background: #f2f6f1;
}
.base-grid {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 8px;
}
.base-button {
position: relative;
min-height: 52px;
border: 1px solid var(--line);
border-radius: 13px;
background: #f7f8f4;
cursor: pointer;
transition: 160ms ease;
}
.base-button strong {
display: block;
font-size: 18px;
}
.base-button span {
display: block;
margin-top: 2px;
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.base-button:hover {
transform: translateY(-2px);
border-color: rgba(23, 52, 47, 0.22);
}
.base-button.active {
color: white;
border-color: var(--ink);
background: var(--ink);
box-shadow: 0 7px 18px rgba(23, 52, 47, 0.18);
}
.base-button.active span {
color: rgba(255, 255, 255, 0.62);
}
.identity-card {
padding: 16px;
border: 1px solid rgba(62, 182, 156, 0.18);
border-radius: 16px;
background:
radial-gradient(circle at top right, rgba(62, 182, 156, 0.13), transparent 42%),
#f1f7f2;
}
.representation {
display: flex;
align-items: baseline;
gap: 6px;
margin: 5px 0 8px;
}
#representation {
font-size: clamp(27px, 3vw, 38px);
font-weight: 850;
letter-spacing: -0.045em;
overflow-wrap: anywhere;
}
#representationBase {
color: var(--teal);
font-size: 14px;
font-weight: 800;
}
#equation {
min-height: 36px;
color: var(--muted);
font-size: 12px;
line-height: 1.55;
}
.place-list {
display: grid;
gap: 7px;
max-height: 220px;
overflow: auto;
padding-right: 2px;
}
.place-row {
display: grid;
grid-template-columns: 40px minmax(0, 1fr) auto;
align-items: center;
gap: 10px;
width: 100%;
padding: 9px 10px;
border: 1px solid transparent;
border-radius: 12px;
background: #f6f7f3;
text-align: left;
cursor: pointer;
transition: 140ms ease;
}
.place-row:hover,
.place-row.active {
border-color: rgba(62, 182, 156, 0.3);
background: #edf6ef;
}
.place-digit {
display: grid;
place-items: center;
width: 34px;
height: 34px;
border-radius: 10px;
color: white;
font-size: 15px;
font-weight: 850;
}
.place-name {
font-size: 12px;
font-weight: 800;
}
.place-value {
margin-top: 2px;
color: var(--muted);
font-size: 10px;
}
.mini-blocks {
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 3px;
max-width: 92px;
}
.mini-block {
width: 7px;
height: 7px;
border-radius: 2px;
box-shadow: inset 0 -2px 0 rgba(0, 0, 0, 0.08);
}
.primary-button {
width: 100%;
min-height: 48px;
border: 0;
border-radius: 14px;
color: white;
background: var(--ink);
font-weight: 800;
cursor: pointer;
box-shadow: 0 8px 18px rgba(23, 52, 47, 0.16);
transition: 150ms ease;
}
.primary-button:hover {
background: #24564c;
transform: translateY(-1px);
}
.primary-button:disabled {
cursor: wait;
opacity: 0.55;
transform: none;
}
.panel-tip {
margin: 10px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
text-align: center;
}
.stage {
position: relative;
min-width: 0;
min-height: 0;
overflow: hidden;
background:
radial-gradient(circle at 50% 35%, #f7fbf7 0, #e2ece5 55%, #d4e0d9 100%);
}
#viewport {
position: absolute;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#viewport canvas:active {
cursor: grabbing;
}
.stage-top {
position: absolute;
top: 18px;
left: 18px;
right: 18px;
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 15px;
pointer-events: none;
z-index: 3;
}
.stage-title {
color: #6e817b;
font-size: 10px;
font-weight: 850;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.identity {
display: flex;
align-items: center;
gap: 7px;
margin-top: 6px;
color: var(--ink);
font-size: 13px;
font-weight: 700;
}
.identity strong {
font-size: 19px;
letter-spacing: -0.03em;
}
.identity .operator {
color: #98a7a2;
}
.stage-actions {
display: flex;
align-items: center;
gap: 8px;
pointer-events: auto;
}
.stage-pill {
padding: 9px 11px;
border: 1px solid rgba(255, 255, 255, 0.75);
border-radius: 11px;
color: #5f726c;
background: rgba(255, 255, 255, 0.66);
backdrop-filter: blur(10px);
font-size: 11px;
font-weight: 750;
box-shadow: 0 5px 18px rgba(40, 65, 58, 0.06);
}
.stage-pill.locked {
color: #17765f;
background: rgba(231, 250, 240, 0.84);
}
.icon-button {
width: 36px;
height: 36px;
background: rgba(255, 255, 255, 0.72);
backdrop-filter: blur(10px);
font-size: 17px;
}
.transition-status {
position: absolute;
left: 50%;
bottom: 20px;
width: min(460px, calc(100% - 32px));
padding: 12px 15px;
transform: translateX(-50%);
border: 1px solid rgba(255, 255, 255, 0.8);
border-radius: 15px;
background: rgba(255, 255, 255, 0.78);
box-shadow: 0 12px 30px rgba(38, 66, 58, 0.12);
backdrop-filter: blur(14px);
z-index: 4;
}
.status-row {
display: flex;
justify-content: space-between;
gap: 12px;
align-items: center;
}
#statusTitle {
font-size: 12px;
font-weight: 850;
}
#statusDetail {
margin-top: 3px;
color: var(--muted);
font-size: 10px;
}
.progress-track {
height: 4px;
margin-top: 10px;
overflow: hidden;
border-radius: 999px;
background: rgba(23, 52, 47, 0.1);
}
#progressBar {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--teal), #65d5b7);
transition: width 80ms linear;
}
.tooltip {
position: absolute;
max-width: 220px;
padding: 8px 10px;
border-radius: 9px;
color: white;
background: rgba(20, 45, 40, 0.9);
font-size: 10px;
line-height: 1.4;
pointer-events: none;
opacity: 0;
transform: translate(10px, 10px);
transition: opacity 100ms ease;
z-index: 8;
}
.tooltip.visible {
opacity: 1;
}
.toast {
position: absolute;
top: 82px;
left: 50%;
padding: 9px 13px;
transform: translate(-50%, -8px);
border-radius: 10px;
color: white;
background: rgba(23, 52, 47, 0.9);
font-size: 11px;
font-weight: 750;
opacity: 0;
pointer-events: none;
transition: 180ms ease;
z-index: 7;
}
.toast.visible {
opacity: 1;
transform: translate(-50%, 0);
}
.webgl-error[hidden] { display: none; }
.webgl-error {
position: absolute;
inset: 0;
display: grid;
place-items: center;
padding: 40px;
text-align: center;
color: var(--muted);
z-index: 10;
}
@media (max-width: 940px) {
.app {
grid-template-rows: 66px auto;
}
.workspace {
grid-template-columns: 1fr;
padding: 10px;
}
.stage {
order: 1;
height: 68vh;
min-height: 520px;
}
.panel {
order: 2;
overflow: visible;
}
.top-note {
display: none;
}
}
@media (max-width: 560px) {
.topbar {
padding: 0 15px;
}
.brand-subtitle {
display: none;
}
.stage {
height: 62vh;
min-height: 470px;
border-radius: 17px;
}
.stage-top {
top: 13px;
left: 13px;
right: 13px;
}
.stage-pill.instructions,
.identity .operator,
.identity .identity-word {
display: none;
}
.identity {
flex-wrap: wrap;
max-width: 170px;
}
.panel {
padding: 17px;
}
}
</style>
</head>
<body>
<div class="app">
<header class="topbar">
<div class="brand">
<div class="brand-mark" aria-hidden="true">
<span></span><span></span><span></span>
</div>
<div>
<div class="brand-title">Base Camp</div>
<div class="brand-subtitle">Place-value explorer</div>
</div>
</div>
<div class="top-note">Switching bases rearranges the blocks, never the quantity.</div>
</header>
<main class="workspace">
<aside class="panel" aria-label="Explorer controls">
<section class="section">
<div class="section-heading">
<h2 class="eyebrow">Total quantity</h2>
<span class="section-number">01</span>
</div>
<div class="quantity-row">
<button class="step-button" id="minus" aria-label="Decrease quantity">−</button>
<div class="quantity-input-wrap">
<input
id="quantity"
type="number"
min="0"
max="999"
value="128"
inputmode="numeric"
aria-label="Total quantity"
/>
<span class="unit-label">units</span>
</div>
<button class="step-button" id="plus" aria-label="Increase quantity">+</button>
</div>
<input
id="quantityRange"
type="range"
min="0"
max="999"
value="128"
aria-label="Quantity slider"
/>
<div class="range-labels"><span>0</span><span>999 units</span></div>
<div class="presets">
<button class="preset" data-quantity="24">24</button>
<button class="preset" data-quantity="64">64</button>
<button class="preset" data-quantity="125">125</button>
<button class="preset" data-quantity="255">255</button>
<button class="preset" data-quantity="512">512</button>
</div>
</section>
<section class="section">
<div class="section-heading">
<h2 class="eyebrow">Numeral base</h2>
<span class="section-number">02</span>
</div>
<div class="base-grid" id="baseGrid">
<button class="base-button" data-base="2"><strong>2</strong><span>Binary</span></button>
<button class="base-button" data-base="4"><strong>4</strong><span>Quaternary</span></button>
<button class="base-button" data-base="5"><strong>5</strong><span>Quinary</span></button>
<button class="base-button" data-base="8"><strong>8</strong><span>Octal</span></button>
<button class="base-button active" data-base="10"><strong>10</strong><span>Decimal</span></button>
<button class="base-button" data-base="16"><strong>16</strong><span>Hexadecimal</span></button>
</div>
</section>
<section class="section">
<div class="section-heading">
<h2 class="eyebrow">Place-value notation</h2>
<span class="section-number">03</span>
</div>
<div class="identity-card">
<div class="representation">
<span id="representation">128</span>
<sub id="representationBase">10</sub>
</div>
<div id="equation"></div>
</div>
</section>
<section class="section">
<div class="section-heading">
<h2 class="eyebrow">Explore each place</h2>
<span class="section-number">04</span>
</div>
<div class="place-list" id="placeList"></div>
</section>
<section class="section">
<button class="primary-button" id="regroup">Regroup the same units</button>
<p class="panel-tip">
Click a place to highlight it. Choose another base to watch the quantity
remain fixed while the blocks regroup.
</p>
</section>
</aside>
<section class="stage" aria-label="Interactive three-dimensional block model">
<div id="viewport"></div>
<div class="stage-top">
<div>
<div class="stage-title">Live quantity model</div>
<div class="identity">
<strong id="identityCount">128</strong>
<span class="identity-word">units</span>
<span class="operator">=</span>
<strong id="identityBase">128₁₀</strong>
</div>
</div>
<div class="stage-actions">
<div class="stage-pill instructions">Drag to orbit · scroll to zoom</div>
<div class="stage-pill locked" id="lockPill">Quantity locked</div>
<button class="icon-button" id="resetView" aria-label="Reset camera" title="Reset camera">⌂</button>
</div>
</div>
<div class="transition-status" aria-live="polite">
<div class="status-row">
<div>
<div id="statusTitle">Ready to explore</div>
<div id="statusDetail">Switch a base to regroup the same units.</div>
</div>
</div>
<div class="progress-track"><div id="progressBar"></div></div>
</div>
<div class="tooltip" id="tooltip"></div>
<div class="toast" id="toast"></div>
<div class="webgl-error" id="webglError" hidden>
This explorer needs WebGL. Try a browser with hardware acceleration enabled.
</div>
</section>
</main>
</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const MAX_QUANTITY = 999;
const BOARD_TOP = 0.16;
const ui = {
quantity: document.querySelector("#quantity"),
quantityRange: document.querySelector("#quantityRange"),
baseGrid: document.querySelector("#baseGrid"),
representation: document.querySelector("#representation"),
representationBase: document.querySelector("#representationBase"),
equation: document.querySelector("#equation"),
placeList: document.querySelector("#placeList"),
identityCount: document.querySelector("#identityCount"),
identityBase: document.querySelector("#identityBase"),
lockPill: document.querySelector("#lockPill"),
statusTitle: document.querySelector("#statusTitle"),
statusDetail: document.querySelector("#statusDetail"),
progressBar: document.querySelector("#progressBar"),
regroup: document.querySelector("#regroup"),
tooltip: document.querySelector("#tooltip"),
toast: document.querySelector("#toast"),
viewport: document.querySelector("#viewport"),
webglError: document.querySelector("#webglError")
};
const state = {
quantity: 128,
base: 10,
selectedLevel: null,
hoveredEntry: null,
displaySnapshot: null,
displayGroup: null,
displayEntries: null,
displayLabels: null,
transition: null
};
const levelColors = [
"#ff7255",
"#f1c75b",
"#3eb69c",
"#598ce8",
"#9a78db",
"#ef77ae",
"#48b8c8",
"#ed9346",
"#789b54"
];
function levelColor(level) {
return levelColors[level % levelColors.length];
}
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function smoothstep(value) {
const x = clamp(value, 0, 1);
return x * x * (3 - 2 * x);
}
function seededRandom(seed) {
const x = Math.sin(seed * 12.9898 + 78.233) * 43758.5453;
return x - Math.floor(x);
}
function toDigits(quantity, base) {
if (quantity === 0) return [0];
const digits = [];
let remaining = quantity;
while (remaining > 0) {
digits.push(remaining % base);
remaining = Math.floor(remaining / base);
}
return digits;
}
function superscript(number) {
const map = {
0: "⁰", 1: "¹", 2: "²", 3: "³",
4: "⁴", 5: "⁵", 6: "⁶", 7: "⁷",
8: "⁸", 9: "⁹"
};
return String(number).split("").map((digit) => map[digit]).join("");
}
function prettyPower(base, level) {
return level === 0 ? "1" : `${base}${superscript(level)}`;
}
function placeName(base, level) {
if (level === 0) return "Ones";
if (level === 1) return `${base}s`;
return `${base ** level}s`;
}
function blockDimensions(level, base) {
if (level === 0) return [0.68, 0.68, 0.68];
if (level === 1) {
const width = base <= 5 ? 1.02 : base <= 10 ? 1.14 : 1.28;
return [width, 0.52, 0.88];
}
if (level === 2) {
const depth = base <= 5 ? 1.12 : base <= 10 ? 1.28 : 1.42;
return [1.34, 0.44, depth];
}
return [1.58, 0.38, 1.58];
}
function shadeColor(hex, amount) {
const color = new THREE.Color(hex);
const hsl = {};
color.getHSL(hsl);
color.setHSL(hsl.h, hsl.s, clamp(hsl.l + amount, 0, 1));
return color;
}
// ---------------------------------------------------------------------
// Three.js scene
// ---------------------------------------------------------------------
let renderer;
try {
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
} catch (error) {
ui.webglError.hidden = false;
throw error;
}
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setClearColor(0x000000, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
ui.viewport.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0xdbe7df, 24, 52);
const camera = new THREE.PerspectiveCamera(
38,
1,
0.1,
100
);
const cameraState = {
theta: 0.66,
phi: 1.02,
radius: 12,
goalRadius: 12,
target: new THREE.Vector3(0, 1.45, 0)
};
const hemisphere = new THREE.HemisphereLight(0xf8fff9, 0x78928a, 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xfff7df, 3.2);
sun.position.set(7, 12, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -13;
sun.shadow.camera.right = 13;
sun.shadow.camera.top = 13;
sun.shadow.camera.bottom = -13;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 35;
sun.shadow.bias = -0.0005;
scene.add(sun);
const fill = new THREE.DirectionalLight(0xa7d9ff, 1.2);
fill.position.set(-8, 5, -6);
scene.add(fill);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(90, 90),
new THREE.MeshStandardMaterial({
color: 0xdde7df,
roughness: 1,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.56;
ground.receiveShadow = true;
scene.add(ground);
const platform = new THREE.Mesh(
new THREE.CylinderGeometry(9.15, 9.15, 0.24, 48),
new THREE.MeshStandardMaterial({
color: 0xf2f5ed,
roughness: 0.88,
flatShading: true
})
);
platform.position.y = -0.035;
platform.receiveShadow = true;
platform.castShadow = true;
scene.add(platform);
const platformSide = new THREE.Mesh(
new THREE.CylinderGeometry(9.05, 8.65, 0.34, 48),
new THREE.MeshStandardMaterial({
color: 0xb8ccc2,
roughness: 0.9,
flatShading: true
})
);
platformSide.position.y = -0.31;
platformSide.receiveShadow = true;
scene.add(platformSide);
const grid = new THREE.GridHelper(17, 24, 0x9cb7ab, 0xbfd0c7);
grid.position.y = 0.092;
grid.material.transparent = true;
grid.material.opacity = 0.22;
scene.add(grid);
const edgeRing = new THREE.Mesh(
new THREE.TorusGeometry(9.02, 0.035, 6, 72),
new THREE.MeshStandardMaterial({
color: 0x73aa97,
roughness: 0.7
})
);
edgeRing.rotation.x = Math.PI / 2;
edgeRing.position.y = 0.075;
scene.add(edgeRing);
const rockGeometry = new THREE.IcosahedronGeometry(0.28, 0);
const rockMaterials = [0x8eafa0, 0xa9bcae, 0x77998e].map(
(color) =>
new THREE.MeshStandardMaterial({
color,
roughness: 1,
flatShading: true
})
);
for (let index = 0; index < 18; index += 1) {
const angle = (index / 18) * Math.PI * 2 + 0.17;
const radius = 8.25 + seededRandom(index + 40) * 0.42;
const rock = new THREE.Mesh(
rockGeometry,
rockMaterials[index % rockMaterials.length]
);
const size = 0.65 + seededRandom(index + 90) * 0.85;
rock.scale.set(size, size * 0.72, size * 0.9);
rock.position.set(
Math.cos(angle) * radius,
-0.33 + size * 0.14,
Math.sin(angle) * radius
);
rock.rotation.set(
seededRandom(index + 11),
seededRandom(index + 12),
seededRandom(index + 13)
);
rock.castShadow = true;
rock.receiveShadow = true;
scene.add(rock);
}
const pulse = new THREE.Mesh(
new THREE.RingGeometry(1, 1.035, 72),
new THREE.MeshBasicMaterial({
color: 0x3eb69c,
transparent: true,
opacity: 0,
depthWrite: false,
side: THREE.DoubleSide
})
);
pulse.rotation.x = -Math.PI / 2;
pulse.position.y = BOARD_TOP + 0.012;
pulse.visible = false;
scene.add(pulse);
// ---------------------------------------------------------------------
// Canonical place-value blocks
// ---------------------------------------------------------------------
function roundedRect(context, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
context.beginPath();
context.moveTo(x + r, y);
context.lineTo(x + width - r, y);
context.quadraticCurveTo(x + width, y, x + width, y + r);
context.lineTo(x + width, y + height - r);
context.quadraticCurveTo(x + width, y + height, x + width - r, y + height);
context.lineTo(x + r, y + height);
context.quadraticCurveTo(x, y + height, x, y + height - r);
context.lineTo(x, y + r);
context.quadraticCurveTo(x, y, x + r, y);
context.closePath();
}
function makeLabelSprite(text, background, foreground = "#ffffff", width = 2.2) {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 160;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
roundedRect(context, 12, 18, 488, 124, 42);
context.fillStyle = background;
context.fill();
context.fillStyle = foreground;
context.font = "800 56px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 256, 81);
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 * 0.3125, 1);
sprite.userData.baseScale = sprite.scale.clone();
sprite.renderOrder = 10;
return sprite;
}
function buildCanonical(snapshot) {
const group = new THREE.Group();
const entries = [];
const labels = [];
const digits = snapshot.digits;
const levelCount = digits.length;
const columnGap = 2.15;
const totalWidth = (levelCount - 1) * columnGap;
for (let level = 0; level < levelCount; level += 1) {
const digit = digits[level];
const dimensions = blockDimensions(level, snapshot.base);
const [width, height, depth] = dimensions;
const color = levelColor(level);
const geometry = new THREE.BoxGeometry(width, height, depth);
const materials = [
new THREE.MeshStandardMaterial({
color: shadeColor(color, 0.035),
roughness: 0.72,
metalness: 0,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: shadeColor(color, -0.025),
roughness: 0.74,
metalness: 0,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: shadeColor(color, 0.09),
roughness: 0.68,
metalness: 0,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: shadeColor(color, -0.08),
roughness: 0.78,
metalness: 0,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: shadeColor(color, 0.02),
roughness: 0.7,
metalness: 0,
flatShading: true
}),
new THREE.MeshStandardMaterial({
color: shadeColor(color, -0.045),
roughness: 0.75,
metalness: 0,
flatShading: true
})
];
const edgeGeometry = new THREE.EdgesGeometry(geometry, 24);
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0x183b34,
transparent: true,
opacity: 0.2
});
const columnX = (levelCount - 1 - level) * columnGap - totalWidth / 2;
const mat = new THREE.Mesh(
new THREE.CylinderGeometry(
Math.max(0.45, width * 0.49),
Math.max(0.45, width * 0.49),
0.045,
24
),
new THREE.MeshStandardMaterial({
color: 0xdce8df,
roughness: 0.95
})
);
mat.position.set(columnX, 0.113, 0);
mat.receiveShadow = true;
group.add(mat);
for (let copy = 0; copy < digit; copy += 1) {
const mesh = new THREE.Mesh(geometry, materials);
const position = new THREE.Vector3(
columnX,
BOARD_TOP + height / 2 + copy * (height + 0.04),
0
);
mesh.position.copy(position);
mesh.castShadow = true;
mesh.receiveShadow = true;
const edges = new THREE.LineSegments(edgeGeometry, edgeMaterial);
edges.renderOrder = 2;
mesh.add(edges);
const entry = {
object: mesh,
finalPosition: position.clone(),
dimensions,
level,
copy,
digit,
value: snapshot.base ** level
};
mesh.userData.isBlock = true;
mesh.userData.entry = entry;
group.add(mesh);
entries.push(entry);
}
const placeLabel = makeLabelSprite(
level === 0 ? "ones" : `${snapshot.base}^${level}`,
"#17342f",
"#ffffff",
level === 0 ? 1.65 : 1.9
);
placeLabel.position.set(columnX, 0.42, 1.12);
group.add(placeLabel);
labels.push(placeLabel);
const digitLabel = makeLabelSprite(
String(digit),
color,
"#17342f",
0.82
);
digitLabel.position.set(
columnX,
BOARD_TOP + digit * (height + 0.04) + 0.43,
0
);
group.add(digitLabel);
labels.push(digitLabel);
}
return { group, entries, labels };
}
function disposeGroup(group) {
if (!group) return;
const geometries = new Set();
const materials = new Set();
const textures = new Set();
group.traverse((object) => {
if (object.geometry) geometries.add(object.geometry);
if (object.material) {
const objectMaterials = Array.isArray(object.material)
? object.material
: [object.material];
objectMaterials.forEach((material) => {
materials.add(material);
if (material.map) textures.add(material.map);
});
}
});
group.removeFromParent();
geometries.forEach((geometry) => geometry.dispose());
textures.forEach((texture) => texture.dispose());
materials.forEach((material) => material.dispose());
}
// ---------------------------------------------------------------------
// Regrouping animation
//
// During a transition, one small unit token is created for every unit.
// Tokens leave their old place blocks and enter their new place blocks.
// The token count and the place-value equations both remain exact.
// ---------------------------------------------------------------------
function pointInsideBlock(entry, seed) {
if (entry.value === 1) {
return entry.finalPosition.clone();
}
const [width, height, depth] = entry.dimensions;
const randX = seededRandom(seed + 1);
const randY = seededRandom(seed + 2);
const randZ = seededRandom(seed + 3);
return new THREE.Vector3(
entry.finalPosition.x + (randX - 0.5) * width * 0.78,
entry.finalPosition.y + (randY - 0.5) * height * 0.76,
entry.finalPosition.z + (randZ - 0.5) * depth * 0.78
);
}
function buildTokenAssignments(oldEntries, targetEntries, quantity) {
const assignments = [];
let oldIndex = 0;
let targetIndex = 0;
let oldConsumed = 0;
let targetConsumed = 0;
for (let tokenIndex = 0; tokenIndex < quantity; tokenIndex += 1) {
while (
oldIndex < oldEntries.length - 1 &&
tokenIndex >= oldConsumed + oldEntries[oldIndex].value
) {
oldConsumed += oldEntries[oldIndex].value;
oldIndex += 1;
}
while (
targetIndex < targetEntries.length - 1 &&
tokenIndex >= targetConsumed + targetEntries[targetIndex].value
) {
targetConsumed += targetEntries[targetIndex].value;
targetIndex += 1;
}
const oldEntry = oldEntries[oldIndex];
const targetEntry = targetEntries[targetIndex];
assignments.push({
start: pointInsideBlock(oldEntry, tokenIndex * 3 + 17),
end: pointInsideBlock(targetEntry, tokenIndex * 3 + 701),
arc: 0.35 + seededRandom(tokenIndex + 92) * 0.9,
level: targetEntry.level
});
}
return assignments;
}
function makeScatterPosition(entry, seed) {
const randX = seededRandom(seed + 1);
const randY = seededRandom(seed + 2);
const randZ = seededRandom(seed + 3);
const outward = new THREE.Vector3(
entry.finalPosition.x * 0.08 + (randX - 0.5) * 0.8,
0.9 + randY * 0.7,
(randZ - 0.5) * 1.2
).normalize();
return entry.finalPosition.clone().addScaledVector(
outward,
1.1 + seededRandom(seed + 4) * 1.7
);
}
function makeScatterQuaternion(seed) {
return new THREE.Quaternion().setFromEuler(
new THREE.Euler(
(seededRandom(seed + 1) - 0.5) * 2.4,
(seededRandom(seed + 2) - 0.5) * 2.4,
(seededRandom(seed + 3) - 0.5) * 2.4
)
);
}
function startTransition(oldSnapshot, targetSnapshot, quantityLocked) {
const targetBuild = buildCanonical(targetSnapshot);
const oldGroup = state.displayGroup;
const oldEntries = state.displayEntries;
const oldLabels = state.displayLabels;
oldEntries.forEach((entry) => {
entry.object.scale.setScalar(1);
});
const assignments = buildTokenAssignments(
oldEntries,
targetBuild.entries,
targetSnapshot.quantity
);
let tokenMesh = null;
if (targetSnapshot.quantity > 0) {
const tokenGeometry = new THREE.BoxGeometry(0.13, 0.13, 0.13);
const tokenMaterial = new THREE.MeshStandardMaterial({
color: 0xffffff,
roughness: 0.64,
metalness: 0,
flatShading: true
});
tokenMesh = new THREE.InstancedMesh(
tokenGeometry,
tokenMaterial,
targetSnapshot.quantity
);
tokenMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
tokenMesh.frustumCulled = false;
assignments.forEach((assignment, index) => {
tokenMesh.setColorAt(
index,
new THREE.Color(shadeColor(levelColor(assignment.level), 0.02))
);
});
if (tokenMesh.instanceColor) tokenMesh.instanceColor.needsUpdate = true;
scene.add(tokenMesh);
}
const oldScatter = oldEntries.map((entry, index) => ({
position: makeScatterPosition(entry, index * 11 + 300),
quaternion: makeScatterQuaternion(index * 11 + 301)
}));
const targetScatter = targetBuild.entries.map((entry, index) => ({
position: makeScatterPosition(entry, index * 11 + 900),
quaternion: makeScatterQuaternion(index * 11 + 901)
}));
targetBuild.entries.forEach((entry, index) => {
entry.object.position.copy(targetScatter[index].position);
entry.object.quaternion.copy(targetScatter[index].quaternion);
entry.object.scale.setScalar(0.0001);
});
targetBuild.labels.forEach((label) => {
label.scale.copy(label.userData.baseScale).multiplyScalar(0.0001);
});
scene.add(targetBuild.group);
state.transition = {
start: performance.now(),
duration: 1550,
oldSnapshot,
targetSnapshot,
quantityLocked,
oldGroup,
oldEntries,
oldLabels,
oldScatter,
targetGroup: targetBuild.group,
targetEntries: targetBuild.entries,
targetLabels: targetBuild.labels,
targetScatter,
tokenMesh,
assignments,
phase: 0
};
ui.regroup.disabled = true;
ui.lockPill.classList.toggle("locked", quantityLocked);
ui.lockPill.textContent = quantityLocked ? "Quantity locked" : "Updating quantity";
pulse.visible = true;
pulse.scale.setScalar(0.4);
pulse.material.opacity = 0.55;
fitCamera(targetSnapshot);
setStatus(
quantityLocked ? "Unpacking place blocks" : "Rebuilding the model",
`${targetSnapshot.quantity} units · base ${oldSnapshot.base} → base ${targetSnapshot.base}`,
0
);
}
const dummy = new THREE.Object3D();
const identityQuaternion = new THREE.Quaternion();
function updateTransition(now) {
const transition = state.transition;
if (!transition) return;
const raw = (now - transition.start) / transition.duration;
const t = clamp(raw, 0, 1);
const oldProgress = smoothstep(t / 0.27);
transition.oldEntries.forEach((entry, index) => {
const scatter = transition.oldScatter[index];
entry.object.position.lerpVectors(
entry.finalPosition,
scatter.position,
oldProgress
);
entry.object.quaternion.slerpQuaternions(
identityQuaternion,
scatter.quaternion,
oldProgress
);
entry.object.scale.setScalar(Math.max(0.0001, 1 - oldProgress));
});
transition.oldLabels.forEach((label) => {
label.scale
.copy(label.userData.baseScale)
.multiplyScalar(Math.max(0.0001, 1 - oldProgress));
});
const targetProgress = smoothstep((t - 0.19) / 0.63);
transition.targetEntries.forEach((entry, index) => {
const scatter = transition.targetScatter[index];
entry.object.position.lerpVectors(
scatter.position,
entry.finalPosition,
targetProgress
);
entry.object.quaternion.slerpQuaternions(
scatter.quaternion,
identityQuaternion,
targetProgress
);
entry.object.scale.setScalar(Math.max(0.0001, targetProgress));
});
const labelProgress = smoothstep((t - 0.68) / 0.2);
transition.targetLabels.forEach((label) => {
label.scale
.copy(label.userData.baseScale)
.multiplyScalar(Math.max(0.0001, labelProgress));
});
if (transition.tokenMesh) {
const movement = smoothstep((t - 0.14) / 0.69);
const appear = smoothstep((t - 0.06) / 0.12);
const disappear = 1 - smoothstep((t - 0.81) / 0.16);
const tokenScale = Math.max(0.0001, appear * disappear);
transition.assignments.forEach((assignment, index) => {
dummy.position.lerpVectors(assignment.start, assignment.end, movement);
dummy.position.y += Math.sin(movement * Math.PI) * assignment.arc;
dummy.quaternion.identity();
dummy.scale.setScalar(tokenScale);
dummy.updateMatrix();
transition.tokenMesh.setMatrixAt(index, dummy.matrix);
});
transition.tokenMesh.instanceMatrix.needsUpdate = true;
}
pulse.scale.setScalar(0.4 + smoothstep(t) * 8.2);
pulse.material.opacity = (1 - t) * 0.5;
const nextPhase = t < 0.43 ? 1 : 2;
if (nextPhase !== transition.phase) {
transition.phase = nextPhase;
if (nextPhase === 2) {
setStatus(
transition.quantityLocked
? "Quantity conserved"
: "Rebuilding place blocks",
`${transition.targetSnapshot.quantity} units remain in the model.`,
t * 100
);
}
}
setStatusProgress(t * 100);
if (t >= 1) {
completeTransition();
}
}
function completeTransition() {
const transition = state.transition;
if (!transition) return;
disposeGroup(transition.oldGroup);
disposeGroup(transition.tokenMesh);
transition.targetEntries.forEach((entry) => {
entry.object.position.copy(entry.finalPosition);
entry.object.quaternion.identity();
entry.object.scale.setScalar(1);
});
transition.targetLabels.forEach((label) => {
label.scale.copy(label.userData.baseScale);
});
state.displayGroup = transition.targetGroup;
state.displayEntries = transition.targetEntries;
state.displayLabels = transition.targetLabels;
state.displaySnapshot = transition.targetSnapshot;
state.transition = null;
pulse.visible = false;
pulse.material.opacity = 0;
ui.regroup.disabled = false;
ui.lockPill.classList.remove("locked");
ui.lockPill.textContent = "Quantity locked";
applyHighlights();
setStatus(
"Ready to explore",
`${state.displaySnapshot.quantity} units shown in base ${state.displaySnapshot.base}.`,
100
);
setTimeout(() => {
if (!state.transition) setStatusProgress(0);
}, 500);
}
function settleTransition() {
if (!state.transition) return;
const transition = state.transition;
disposeGroup(transition.oldGroup);
disposeGroup(transition.tokenMesh);
transition.targetEntries.forEach((entry) => {
entry.object.position.copy(entry.finalPosition);
entry.object.quaternion.identity();
entry.object.scale.setScalar(1);
});
transition.targetLabels.forEach((label) => {
label.scale.copy(label.userData.baseScale);
});
state.displayGroup = transition.targetGroup;
state.displayEntries = transition.targetEntries;
state.displayLabels = transition.targetLabels;
state.displaySnapshot = transition.targetSnapshot;
state.transition = null;
pulse.visible = false;
pulse.material.opacity = 0;
ui.regroup.disabled = false;
}
// ---------------------------------------------------------------------
// UI and place-value calculations
// ---------------------------------------------------------------------
function setStatus(title, detail, progress) {
ui.statusTitle.textContent = title;
ui.statusDetail.textContent = detail;
setStatusProgress(progress);
}
function setStatusProgress(progress) {
ui.progressBar.style.width = `${clamp(progress, 0, 100)}%`;
}
function updateUI(snapshot) {
const digits = snapshot.digits;
const representation = digits.slice().reverse().join("");
const terms = [];
for (let level = digits.length - 1; level >= 0; level -= 1) {
const digit = digits[level];
if (digit > 0) {
terms.push(
level === 0
? `${digit} × 1`
: `${digit} × ${prettyPower(snapshot.base, level)}`
);
}
}
ui.quantity.value = snapshot.quantity;
ui.quantityRange.value = snapshot.quantity;
ui.representation.textContent = representation;
ui.representationBase.textContent = String(snapshot.base);
ui.identityCount.textContent = snapshot.quantity;
ui.identityBase.textContent = `${representation}${subscript(snapshot.base)}`;
ui.equation.textContent = terms.length ? terms.join(" + ") : "0 units";
ui.baseGrid.querySelectorAll(".base-button").forEach((button) => {
const active = Number(button.dataset.base) === snapshot.base;
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
});
if (
state.selectedLevel !== null &&
state.selectedLevel >= digits.length
) {
state.selectedLevel = null;
}
ui.placeList.innerHTML = "";
for (let level = digits.length - 1; level >= 0; level -= 1) {
const digit = digits[level];
const color = levelColor(level);
const row = document.createElement("button");
row.className = "place-row";
row.dataset.level = String(level);
row.setAttribute("aria-label", `${placeName(snapshot.base, level)}, digit ${digit}`);
const blocks = Array.from({ length: digit }, () => {
return `<span class="mini-block" style="background:${color}"></span>`;
}).join("");
row.innerHTML = `
<span class="place-digit" style="background:${color}">${digit}</span>
<span>
<span class="place-name">${placeName(snapshot.base, level)}</span>
<span class="place-value">${digit} × ${prettyPower(snapshot.base, level)}</span>
</span>
<span class="mini-blocks">${blocks}</span>
`;
row.addEventListener("click", () => {
setSelectedLevel(level);
showToast(`${placeName(snapshot.base, level)} · ${digit} × ${prettyPower(snapshot.base, level)}`);
});
ui.placeList.appendChild(row);
}
refreshPlaceSelection();
}
function subscript(base) {
const map = {
0: "₀", 1: "₁", 2: "₂", 3: "₃",
4: "₄", 5: "₅", 6: "₆", 7: "₇",
8: "₈", 9: "₉"
};
return String(base).split("").map((digit) => map[digit]).join("");
}
function setSelectedLevel(level) {
state.selectedLevel = state.selectedLevel === level ? null : level;
refreshPlaceSelection();
applyHighlights();
}
function refreshPlaceSelection() {
ui.placeList.querySelectorAll(".place-row").forEach((row) => {
row.classList.toggle(
"active",
Number(row.dataset.level) === state.selectedLevel
);
});
}
function applyHighlights() {
if (!state.displayEntries || state.transition) return;
state.displayEntries.forEach((entry) => {
let scale = 1;
if (entry.level === state.selectedLevel) scale = 1.065;
if (entry === state.hoveredEntry) scale = 1.105;
entry.object.scale.setScalar(scale);
});
}
function setQuantity(nextQuantity) {
const quantity = clamp(Math.round(nextQuantity), 0, MAX_QUANTITY);
if (quantity === state.quantity && !state.transition) return;
settleTransition();
const oldSnapshot = state.displaySnapshot;
const targetSnapshot = {
quantity,
base: state.base,
digits: toDigits(quantity, state.base)
};
state.quantity = quantity;
updateUI(targetSnapshot);
startTransition(oldSnapshot, targetSnapshot, false);
}
function switchBase(base) {
if (base === state.base && !state.transition) return;
settleTransition();
const oldSnapshot = state.displaySnapshot;
const targetSnapshot = {
quantity: state.quantity,
base,
digits: toDigits(state.quantity, base)
};
state.base = base;
updateUI(targetSnapshot);
startTransition(oldSnapshot, targetSnapshot, true);
}
function showToast(message) {
ui.toast.textContent = message;
ui.toast.classList.add("visible");
clearTimeout(showToast.timeout);
showToast.timeout = setTimeout(() => {
ui.toast.classList.remove("visible");
}, 1700);
}
ui.quantity.addEventListener("change", () => {
const value = Number.parseInt(ui.quantity.value, 10);
setQuantity(Number.isFinite(value) ? value : 0);
});
ui.quantity.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
event.preventDefault();
ui.quantity.blur();
}
});
ui.quantityRange.addEventListener("input", () => {
setQuantity(Number(ui.quantityRange.value));
});
document.querySelector("#minus").addEventListener("click", () => {
setQuantity(state.quantity - 1);
});
document.querySelector("#plus").addEventListener("click", () => {
setQuantity(state.quantity + 1);
});
document.querySelectorAll("[data-quantity]").forEach((button) => {
button.addEventListener("click", () => {
setQuantity(Number(button.dataset.quantity));
});
});
ui.baseGrid.addEventListener("click", (event) => {
const button = event.target.closest("[data-base]");
if (button) switchBase(Number(button.dataset.base));
});
ui.regroup.addEventListener("click", () => {
settleTransition();
const oldSnapshot = state.displaySnapshot;
const targetSnapshot = {
quantity: state.quantity,
base: state.base,
digits: toDigits(state.quantity, state.base)
};
startTransition(oldSnapshot, targetSnapshot, true);
});
// ---------------------------------------------------------------------
// Custom camera controls — no Three.js addons
// ---------------------------------------------------------------------
let dragging = false;
let pointerMoved = false;
let previousX = 0;
let previousY = 0;
renderer.domElement.addEventListener("pointerdown", (event) => {
dragging = true;
pointerMoved = false;
previousX = event.clientX;
previousY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (dragging) {
const deltaX = event.clientX - previousX;
const deltaY = event.clientY - previousY;
if (Math.abs(deltaX) + Math.abs(deltaY) > 2) {
pointerMoved = true;
}
cameraState.theta -= deltaX * 0.006;
cameraState.phi = clamp(
cameraState.phi - deltaY * 0.005,
0.34,
1.42
);
previousX = event.clientX;
previousY = event.clientY;
} else {
updateHover(event);
}
});
renderer.domElement.addEventListener("pointerup", (event) => {
dragging = false;
if (!pointerMoved) {
pickBlock(event);
}
});
renderer.domElement.addEventListener("pointercancel", () => {
dragging = false;
});
renderer.domElement.addEventListener("pointerleave", () => {
state.hoveredEntry = null;
ui.tooltip.classList.remove("visible");
applyHighlights();
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.goalRadius = null;
cameraState.radius = clamp(
cameraState.radius + event.deltaY * 0.012,
7,
30
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
document.querySelector("#resetView").addEventListener("click", resetCamera);
function estimateCameraRadius(snapshot) {
const levelCount = snapshot.digits.length;
const span = (levelCount - 1) * 2.15 + 2.2;
let tallest = 0;
snapshot.digits.forEach((digit, level) => {
const dimensions = blockDimensions(level, snapshot.base);
tallest = Math.max(
tallest,
digit * (dimensions[1] + 0.04)
);
});
return Math.max(
11,
span * 1.05,
(tallest + BOARD_TOP) * 1.55
);
}
function fitCamera(snapshot) {
cameraState.goalRadius = estimateCameraRadius(snapshot);
}
function resetCamera() {
cameraState.theta = 0.66;
cameraState.phi = 1.02;
cameraState.goalRadius = estimateCameraRadius(state.displaySnapshot);
cameraState.target.set(0, 1.45, 0);
}
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
function setPointerFromEvent(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function findBlockEntry(event) {
if (!state.displayGroup || state.transition) return null;
setPointerFromEvent(event);
raycaster.setFromCamera(pointer, camera);
const intersections = raycaster.intersectObjects(
state.displayGroup.children,
true
);
for (const intersection of intersections) {
if (intersection.object.userData.isBlock) {
return intersection.object.userData.entry;
}
}
return null;
}
function updateHover(event) {
const entry = findBlockEntry(event);
if (entry !== state.hoveredEntry) {
state.hoveredEntry = entry;
applyHighlights();
}
if (!entry) {
ui.tooltip.classList.remove("visible");
renderer.domElement.style.cursor = dragging ? "grabbing" : "grab";
return;
}
renderer.domElement.style.cursor = "pointer";
const rect = ui.viewport.getBoundingClientRect();
ui.tooltip.style.left = `${event.clientX - rect.left}px`;
ui.tooltip.style.top = `${event.clientY - rect.top}px`;
ui.tooltip.textContent =
`${placeName(state.displaySnapshot.base, entry.level)} · ` +
`each block = ${entry.value} unit${entry.value === 1 ? "" : "s"}`;
ui.tooltip.classList.add("visible");
}
function pickBlock(event) {
const entry = findBlockEntry(event);
if (!entry) return;
setSelectedLevel(entry.level);
showToast(
`${placeName(state.displaySnapshot.base, entry.level)} · ` +
`${entry.digit} × ${prettyPower(state.displaySnapshot.base, entry.level)}`
);
}
// ---------------------------------------------------------------------
// Resize and render loop
// ---------------------------------------------------------------------
function resize() {
const width = ui.viewport.clientWidth;
const height = ui.viewport.clientHeight;
if (!width || !height) return;
renderer.setSize(width, height, false);
camera.aspect = width / height;
camera.updateProjectionMatrix();
}
const resizeObserver = new ResizeObserver(resize);
resizeObserver.observe(ui.viewport);
resize();
function animate(now) {
requestAnimationFrame(animate);
updateTransition(now);
if (cameraState.goalRadius !== null) {
cameraState.radius = THREE.MathUtils.lerp(
cameraState.radius,
cameraState.goalRadius,
0.065
);
if (Math.abs(cameraState.radius - cameraState.goalRadius) < 0.015) {
cameraState.radius = cameraState.goalRadius;
cameraState.goalRadius = null;
}
}
const sinPhi = Math.sin(cameraState.phi);
camera.position.set(
cameraState.target.x + cameraState.radius * sinPhi * Math.sin(cameraState.theta),
cameraState.target.y + cameraState.radius * Math.cos(cameraState.phi),
cameraState.target.z + cameraState.radius * sinPhi * Math.cos(cameraState.theta)
);
camera.lookAt(cameraState.target);
renderer.render(scene, camera);
}
// ---------------------------------------------------------------------
// Initial model
// ---------------------------------------------------------------------
state.displaySnapshot = {
quantity: state.quantity,
base: state.base,
digits: toDigits(state.quantity, state.base)
};
const initialBuild = buildCanonical(state.displaySnapshot);
state.displayGroup = initialBuild.group;
state.displayEntries = initialBuild.entries;
state.displayLabels = initialBuild.labels;
scene.add(state.displayGroup);
updateUI(state.displaySnapshot);
fitCamera(state.displaySnapshot);
cameraState.radius = cameraState.goalRadius;
requestAnimationFrame(animate);
</script>
</body>
</html>
```