Prompt specification
Build or customize the Three.js 3D scene "Regrouping ten units into one rod" 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: Regrouping ten units into one rod
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/regrouping-ten-units-into-one-rod-x1718
Scene Description Prompt:
Please create one self-contained HTML file with Three.js from cdnjs showing place value and regrouping across number bases. Animate ten marked unit cubes joining into a tens rod and reversing the exchange; preserve total quantity and update the written numeral consistently. Stylized solid forms.
Working Three.js Starter (regrouping-ten-units-into-one-rod-x1718):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Place Value Lab — Regrouping Across Bases</title>
<style>
:root {
--bg: #07111f;
--panel: rgba(10, 25, 42, 0.88);
--panel-border: rgba(165, 226, 255, 0.16);
--text: #edf8ff;
--muted: #91abc1;
--cyan: #4be0c2;
--cyan-dark: #147d78;
--gold: #ffd166;
--orange: #ff9f68;
--danger: #ff7f86;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 72% 34%, rgba(34, 99, 125, 0.26), transparent 42%),
radial-gradient(circle at 20% 90%, rgba(75, 224, 194, 0.08), transparent 38%),
var(--bg);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
.panel {
position: fixed;
z-index: 10;
top: 22px;
left: 22px;
width: min(370px, calc(100vw - 44px));
max-height: calc(100vh - 44px);
overflow: auto;
padding: 22px;
border: 1px solid var(--panel-border);
border-radius: 24px;
background:
linear-gradient(145deg, rgba(255, 255, 255, 0.045), transparent 35%),
var(--panel);
box-shadow:
0 30px 80px rgba(0, 0, 0, 0.38),
inset 0 1px 0 rgba(255, 255, 255, 0.05);
backdrop-filter: blur(20px) saturate(130%);
scrollbar-width: thin;
scrollbar-color: rgba(75, 224, 194, 0.35) transparent;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 10px;
color: var(--cyan);
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.15em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 9px;
height: 9px;
border-radius: 3px;
background: var(--cyan);
box-shadow: 0 0 18px rgba(75, 224, 194, 0.8);
transform: rotate(12deg);
}
h1 {
margin: 0;
font-size: clamp(1.75rem, 4vw, 2.35rem);
line-height: 1.02;
letter-spacing: -0.045em;
}
.intro {
margin: 10px 0 18px;
color: var(--muted);
font-size: 0.88rem;
line-height: 1.55;
}
.section-label {
display: flex;
justify-content: space-between;
align-items: baseline;
gap: 12px;
margin: 17px 0 9px;
color: #c6d9e8;
font-size: 0.72rem;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.section-label small {
color: var(--muted);
font-size: 0.67rem;
font-weight: 600;
letter-spacing: 0;
text-transform: none;
}
.base-grid {
display: grid;
grid-template-columns: repeat(9, 1fr);
gap: 5px;
}
.base-btn {
min-width: 0;
padding: 9px 0;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 10px;
background: rgba(255, 255, 255, 0.045);
color: #a9c1d3;
font-size: 0.78rem;
font-weight: 800;
cursor: pointer;
transition: 160ms ease;
}
.base-btn:hover:not(:disabled) {
color: white;
border-color: rgba(75, 224, 194, 0.45);
background: rgba(75, 224, 194, 0.09);
transform: translateY(-1px);
}
.base-btn.active {
color: #05241f;
border-color: var(--cyan);
background: linear-gradient(135deg, #71f1d6, #32bba7);
box-shadow: 0 7px 22px rgba(75, 224, 194, 0.2);
}
.base-btn:disabled {
cursor: not-allowed;
opacity: 0.5;
}
.number-card {
position: relative;
overflow: hidden;
margin-top: 15px;
padding: 17px 18px 15px;
border: 1px solid rgba(75, 224, 194, 0.16);
border-radius: 18px;
background:
radial-gradient(circle at 100% 0, rgba(75, 224, 194, 0.11), transparent 46%),
rgba(3, 14, 26, 0.62);
}
.number-card::after {
content: "";
position: absolute;
right: -20px;
bottom: -38px;
width: 120px;
height: 120px;
border: 1px solid rgba(255, 209, 102, 0.12);
border-radius: 50%;
box-shadow:
0 0 0 18px rgba(255, 209, 102, 0.025),
0 0 0 36px rgba(255, 209, 102, 0.018);
}
.number-caption {
color: var(--muted);
font-size: 0.7rem;
font-weight: 700;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.number {
display: flex;
align-items: flex-end;
margin: 3px 0 8px;
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
font-size: clamp(3.2rem, 10vw, 5.2rem);
font-weight: 800;
line-height: 1;
letter-spacing: -0.08em;
color: white;
text-shadow: 0 0 32px rgba(75, 224, 194, 0.12);
}
.number sub {
margin: 0 0 0.28em 0.14em;
color: var(--cyan);
font-size: 0.35em;
letter-spacing: 0;
}
.number.pulse {
animation: numeral-pulse 420ms ease;
}
@keyframes numeral-pulse {
0% { transform: scale(1); color: white; }
45% { transform: scale(1.055); color: var(--gold); }
100% { transform: scale(1); color: white; }
}
.base-name {
color: var(--gold);
font-size: 0.75rem;
font-weight: 850;
letter-spacing: 0.13em;
text-transform: uppercase;
}
.quantity-row {
display: grid;
grid-template-columns: 1fr 116px;
align-items: end;
gap: 12px;
}
.quantity-copy {
color: var(--muted);
font-size: 0.78rem;
line-height: 1.45;
}
.quantity-copy strong {
display: block;
margin-bottom: 2px;
color: #dbeaf4;
font-size: 0.84rem;
}
.number-input {
width: 100%;
padding: 11px 12px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 12px;
outline: none;
background: rgba(0, 0, 0, 0.24);
color: white;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 1.05rem;
font-weight: 800;
text-align: center;
}
.number-input:focus {
border-color: var(--cyan);
box-shadow: 0 0 0 3px rgba(75, 224, 194, 0.1);
}
.number-input:disabled {
opacity: 0.5;
}
.equation {
display: grid;
grid-template-columns: auto 1fr;
align-items: center;
gap: 12px;
margin-top: 12px;
padding: 13px 14px;
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: 14px;
background: rgba(255, 255, 255, 0.035);
}
.equation-value {
color: white;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 1.1rem;
font-weight: 850;
white-space: nowrap;
}
.equation-value sub {
color: var(--cyan);
font-size: 0.65em;
}
.equation-parts {
color: var(--muted);
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 0.77rem;
line-height: 1.55;
text-align: right;
}
.equation.flash {
animation: equation-flash 500ms ease;
}
@keyframes equation-flash {
0%, 100% { border-color: rgba(255, 255, 255, 0.08); }
45% { border-color: rgba(255, 209, 102, 0.6); }
}
.actions {
display: grid;
gap: 9px;
margin-top: 12px;
}
.action-btn {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
width: 100%;
padding: 12px 14px;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 13px;
background: rgba(255, 255, 255, 0.045);
cursor: pointer;
text-align: left;
transition: 160ms ease;
}
.action-btn span {
font-size: 0.8rem;
font-weight: 800;
}
.action-btn small {
color: var(--muted);
font-size: 0.67rem;
font-weight: 650;
white-space: nowrap;
}
.action-btn:hover:not(:disabled) {
border-color: rgba(75, 224, 194, 0.5);
background: rgba(75, 224, 194, 0.09);
transform: translateY(-1px);
}
.action-btn.primary {
border-color: rgba(75, 224, 194, 0.34);
background: linear-gradient(135deg, rgba(75, 224, 194, 0.2), rgba(75, 224, 194, 0.07));
}
.action-btn.primary small {
color: var(--gold);
}
.action-btn:disabled {
cursor: not-allowed;
opacity: 0.36;
transform: none;
}
.status {
min-height: 45px;
margin-top: 12px;
padding: 11px 12px;
border-left: 3px solid var(--gold);
border-radius: 4px 11px 11px 4px;
background: rgba(255, 209, 102, 0.06);
color: #bcd0de;
font-size: 0.73rem;
line-height: 1.5;
}
.reset-btn {
width: 100%;
margin-top: 10px;
padding: 9px;
border: 0;
border-radius: 10px;
background: transparent;
color: var(--muted);
font-size: 0.71rem;
font-weight: 700;
cursor: pointer;
}
.reset-btn:hover {
color: white;
background: rgba(255, 255, 255, 0.04);
}
.scene-hud {
position: fixed;
z-index: 5;
right: 22px;
top: 22px;
display: flex;
align-items: center;
gap: 10px;
padding: 10px 13px;
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 999px;
background: rgba(6, 18, 31, 0.62);
color: #aac2d3;
font-size: 0.7rem;
font-weight: 700;
letter-spacing: 0.04em;
backdrop-filter: blur(12px);
pointer-events: none;
}
.hud-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 12px rgba(75, 224, 194, 0.8);
}
.controls-hint {
position: fixed;
z-index: 5;
right: 24px;
bottom: 20px;
color: rgba(185, 208, 224, 0.65);
font-size: 0.67rem;
font-weight: 700;
letter-spacing: 0.07em;
text-transform: uppercase;
pointer-events: none;
}
.legend {
position: fixed;
z-index: 5;
left: 50%;
bottom: 20px;
display: flex;
gap: 18px;
transform: translateX(-50%);
color: rgba(197, 218, 232, 0.72);
font-size: 0.68rem;
font-weight: 700;
pointer-events: none;
}
.legend span {
display: flex;
align-items: center;
gap: 7px;
white-space: nowrap;
}
.legend i {
width: 10px;
height: 10px;
border-radius: 3px;
background: var(--cyan);
box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.28);
}
.legend .rail-swatch {
width: 22px;
height: 5px;
border-radius: 3px;
background: var(--gold);
}
@media (max-width: 760px) {
.panel {
top: 12px;
left: 12px;
width: calc(100vw - 24px);
max-height: 55vh;
padding: 17px;
border-radius: 19px;
}
.intro {
margin-bottom: 12px;
}
.scene-hud {
top: auto;
right: 12px;
bottom: 12px;
}
.controls-hint,
.legend {
display: none;
}
.base-grid {
grid-template-columns: repeat(9, minmax(27px, 1fr));
}
}
@media (max-height: 720px) and (min-width: 761px) {
.panel {
padding: 17px;
}
h1 {
font-size: 1.8rem;
}
.intro {
margin: 7px 0 11px;
}
.section-label {
margin-top: 11px;
}
.number {
font-size: 3.4rem;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive 3D place-value model"></canvas>
<aside class="panel" aria-label="Place value controls">
<div class="eyebrow">Place Value Lab</div>
<h1>Regroup across bases</h1>
<p class="intro">
Watch marked unit cubes assemble into rods and rods return to units.
The total quantity—and the base numeral—never changes.
</p>
<div class="section-label">
Number base
<small id="baseNote">Two-place model</small>
</div>
<div class="base-grid" id="baseGrid" role="group" aria-label="Choose a number base"></div>
<div class="number-card">
<div class="number-caption">Written numeral</div>
<div class="number" id="numberDisplay" aria-live="polite">
<span id="numeral">24</span><sub id="numeralBase">10</sub>
</div>
<div class="base-name" id="baseName">Decimal</div>
</div>
<div class="section-label">
Total quantity
<small>Every solid equals one unit</small>
</div>
<div class="quantity-row">
<div class="quantity-copy">
<strong id="quantityTitle">24 unit cubes</strong>
<span id="quantityDescription">The scene always contains this many units.</span>
</div>
<input
id="quantityInput"
class="number-input"
type="number"
min="0"
max="48"
step="1"
value="24"
aria-label="Total number of unit cubes"
/>
</div>
<div class="equation" id="equationCard" aria-live="polite">
<div class="equation-value" id="equationValue">24<sub>10</sub></div>
<div class="equation-parts" id="equationParts">2 × 10 + 4 × 1</div>
</div>
<div class="actions">
<button class="action-btn" id="splitButton" type="button">
<span>Reverse exchange</span>
<small id="splitDetail">1 tens rod → 10 units</small>
</button>
<button class="action-btn primary" id="packButton" type="button">
<span>Regroup</span>
<small id="packDetail">10 units → 1 tens rod</small>
</button>
</div>
<div class="status" id="status" aria-live="polite">
Start with 24 unit cubes. Open a tens rod, then rebuild it from ten loose units.
</div>
<button class="reset-btn" id="resetCamera" type="button">Reset camera view</button>
</aside>
<div class="scene-hud">
<span class="hud-dot"></span>
<span id="sceneCount">24 cubes · base 10</span>
</div>
<div class="legend" aria-hidden="true">
<span><i></i> Unit cube = 1</span>
<span><i class="rail-swatch"></i> Rod = one base-place</span>
</div>
<div class="controls-hint">Drag to orbit · Scroll to zoom · Double-click to reset</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const $ = (selector) => document.querySelector(selector);
const canvas = $("#scene");
const baseGrid = $("#baseGrid");
const quantityInput = $("#quantityInput");
const numeral = $("#numeral");
const numeralBase = $("#numeralBase");
const numberDisplay = $("#numberDisplay");
const baseName = $("#baseName");
const baseNote = $("#baseNote");
const equationCard = $("#equationCard");
const equationValue = $("#equationValue");
const equationParts = $("#equationParts");
const splitButton = $("#splitButton");
const packButton = $("#packButton");
const splitDetail = $("#splitDetail");
const packDetail = $("#packDetail");
const status = $("#status");
const sceneCount = $("#sceneCount");
const quantityTitle = $("#quantityTitle");
const quantityDescription = $("#quantityDescription");
const CUBE_SIZE = 0.58;
const GAP = 0.07;
const SPACING = CUBE_SIZE + GAP;
const BASE_NAMES = [
"",
"",
"Twos",
"Threes",
"Fours",
"Fives",
"Sixes",
"Sevens",
"Eights",
"Nines",
"Tens"
];
const BASE_INFO = {};
for (let base = 2; base <= 10; base++) {
BASE_INFO[base] = {
base,
name: base === 10 ? "Decimal" : `Base ${base}`,
rodName: BASE_NAMES[base],
max: Math.min(48, base * base - 1)
};
}
Object.assign(BASE_INFO[2], { defaultQuantity: 3 });
Object.assign(BASE_INFO[3], { defaultQuantity: 8 });
Object.assign(BASE_INFO[4], { defaultQuantity: 12 });
Object.assign(BASE_INFO[5], { defaultQuantity: 19 });
Object.assign(BASE_INFO[6], { defaultQuantity: 23 });
Object.assign(BASE_INFO[7], { defaultQuantity: 31 });
Object.assign(BASE_INFO[8], { defaultQuantity: 27 });
Object.assign(BASE_INFO[9], { defaultQuantity: 35 });
Object.assign(BASE_INFO[10], { defaultQuantity: 24 });
const state = {
base: 10,
quantity: 24,
rods: [],
loose: [],
entries: [],
busy: false,
actionTimer: 0
};
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
// ---------------------------------------------------------------------
// Three.js scene
// ---------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
renderer.setClearColor(0x07111f, 0);
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.fog = new THREE.Fog(0x07111f, 18, 37);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const orbit = {
yaw: 0.38,
pitch: 0.59,
radius: 12.2,
target: new THREE.Vector3(0, 0.12, 0.05)
};
function updateCamera() {
const cp = Math.cos(orbit.pitch);
const sp = Math.sin(orbit.pitch);
camera.position.set(
orbit.target.x + orbit.radius * Math.sin(orbit.yaw) * cp,
orbit.target.y + orbit.radius * sp,
orbit.target.z + orbit.radius * Math.cos(orbit.yaw) * cp
);
camera.lookAt(orbit.target);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xb8efff, 0x172033, 2.15);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.1);
keyLight.position.set(5.5, 10, 7.5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -11;
keyLight.shadow.camera.right = 11;
keyLight.shadow.camera.top = 11;
keyLight.shadow.camera.bottom = -11;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 30;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x4be0c2, 1.9);
rimLight.position.set(-7, 5, -6);
scene.add(rimLight);
const warmLight = new THREE.PointLight(0xffb765, 18, 18, 2);
warmLight.position.set(5, 3.5, -5);
scene.add(warmLight);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(42, 42),
new THREE.MeshStandardMaterial({
color: 0x081626,
roughness: 0.93,
metalness: 0.03
})
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.37;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(30, 30, 0x245067, 0x173348);
grid.position.y = -0.355;
grid.material.transparent = true;
grid.material.opacity = 0.24;
scene.add(grid);
const platformRing = new THREE.Mesh(
new THREE.TorusGeometry(7.2, 0.018, 8, 120),
new THREE.MeshBasicMaterial({
color: 0xffd166,
transparent: true,
opacity: 0.18
})
);
platformRing.rotation.x = Math.PI / 2;
platformRing.position.y = -0.34;
scene.add(platformRing);
const modelRoot = new THREE.Group();
scene.add(modelRoot);
// Shared cube assets.
const cubeGeometry = new THREE.BoxGeometry(CUBE_SIZE, CUBE_SIZE, CUBE_SIZE);
const cubeMaterial = new THREE.MeshStandardMaterial({
color: 0x39c9b5,
roughness: 0.34,
metalness: 0.08
});
const edgeGeometry = new THREE.EdgesGeometry(cubeGeometry, 20);
const edgeMaterial = new THREE.LineBasicMaterial({
color: 0xa4fff0,
transparent: true,
opacity: 0.55
});
const studGeometry = new THREE.CylinderGeometry(0.075, 0.075, 0.035, 18);
const studMaterial = new THREE.MeshStandardMaterial({
color: 0xffd166,
roughness: 0.32,
metalness: 0.12,
emissive: 0x4a2c00,
emissiveIntensity: 0.16
});
const markerCanvas = document.createElement("canvas");
markerCanvas.width = 96;
markerCanvas.height = 96;
const markerContext = markerCanvas.getContext("2d");
markerContext.clearRect(0, 0, 96, 96);
markerContext.beginPath();
markerContext.arc(48, 48, 36, 0, Math.PI * 2);
markerContext.fillStyle = "#ffd166";
markerContext.fill();
markerContext.lineWidth = 5;
markerContext.strokeStyle = "#fff0af";
markerContext.stroke();
markerContext.fillStyle = "#10283b";
markerContext.font = "800 48px Arial";
markerContext.textAlign = "center";
markerContext.textBaseline = "middle";
markerContext.fillText("1", 48, 49);
const markerTexture = new THREE.CanvasTexture(markerCanvas);
markerTexture.colorSpace = THREE.SRGBColorSpace;
markerTexture.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
const markerGeometry = new THREE.PlaneGeometry(0.31, 0.31);
const markerMaterial = new THREE.MeshBasicMaterial({
map: markerTexture,
transparent: true,
depthWrite: false,
polygonOffset: true,
polygonOffsetFactor: -1,
polygonOffsetUnits: -1
});
// ---------------------------------------------------------------------
// 3D labels
// ---------------------------------------------------------------------
function makeLabel(text, accent = "#4be0c2") {
const labelCanvas = document.createElement("canvas");
labelCanvas.width = 1024;
labelCanvas.height = 192;
const context = labelCanvas.getContext("2d");
const texture = new THREE.CanvasTexture(labelCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(6.6, 1.22, 1);
sprite.renderOrder = 20;
const label = { sprite, canvas: labelCanvas, context, texture };
drawLabel(label, text, accent);
scene.add(sprite);
return label;
}
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 drawLabel(label, text, accent = "#4be0c2") {
const context = label.context;
context.clearRect(0, 0, 1024, 192);
roundedRect(context, 10, 16, 1004, 160, 34);
context.fillStyle = "rgba(7, 24, 39, 0.88)";
context.fill();
context.lineWidth = 4;
context.strokeStyle = accent;
context.globalAlpha = 0.72;
context.stroke();
context.globalAlpha = 1;
context.beginPath();
context.arc(72, 96, 27, 0, Math.PI * 2);
context.fillStyle = accent;
context.fill();
context.fillStyle = "#eefaff";
context.font = "800 42px Arial";
context.textAlign = "left";
context.textBaseline = "middle";
context.fillText(text, 120, 97);
label.texture.needsUpdate = true;
}
const rodLabel = makeLabel("10 UNIT CUBES = 1 TENS ROD", "#ffd166");
const looseLabel = makeLabel("LOOSE UNIT CUBES = VALUE 1", "#4be0c2");
// ---------------------------------------------------------------------
// Model creation and layout
// ---------------------------------------------------------------------
function createCubeEntry() {
const group = new THREE.Group();
const body = new THREE.Mesh(cubeGeometry, cubeMaterial);
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const edges = new THREE.LineSegments(edgeGeometry, edgeMaterial);
group.add(edges);
const stud = new THREE.Mesh(studGeometry, studMaterial);
stud.position.y = CUBE_SIZE / 2 + 0.015;
stud.castShadow = true;
group.add(stud);
const marker = new THREE.Mesh(markerGeometry, markerMaterial);
marker.position.z = CUBE_SIZE / 2 + 0.004;
group.add(marker);
modelRoot.add(group);
return {
group,
target: new THREE.Vector3(),
animation: null,
splitOrigin: false
};
}
function rodLength() {
return (state.base - 1) * SPACING + CUBE_SIZE;
}
function createRail(cubes, visible = true) {
const material = new THREE.MeshStandardMaterial({
color: 0x126d73,
roughness: 0.42,
metalness: 0.18,
transparent: true,
opacity: visible ? 0.92 : 0
});
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(rodLength() + 0.08, 0.08, CUBE_SIZE + 0.05),
material
);
mesh.position.y = -0.325;
mesh.castShadow = true;
mesh.receiveShadow = true;
if (!visible) {
mesh.scale.x = 0.001;
}
modelRoot.add(mesh);
return {
cubes,
mesh,
animation: null
};
}
function disposeRail(rail) {
if (!rail) return;
modelRoot.remove(rail.mesh);
rail.mesh.geometry.dispose();
rail.mesh.material.dispose();
}
function clearModel() {
window.clearTimeout(state.actionTimer);
for (const rod of state.rods) {
disposeRail(rod.rail);
}
modelRoot.clear();
state.rods = [];
state.loose = [];
state.entries = [];
state.busy = false;
}
function rebuildModel() {
clearModel();
const rodCount = Math.floor(state.quantity / state.base);
const looseCount = state.quantity % state.base;
for (let i = 0; i < state.quantity; i++) {
state.entries.push(createCubeEntry());
}
let cursor = 0;
for (let r = 0; r < rodCount; r++) {
const cubes = state.entries.slice(cursor, cursor + state.base);
cursor += state.base;
const rod = {
cubes,
rail: createRail(cubes, true)
};
state.rods.push(rod);
}
state.loose = state.entries.slice(cursor);
layoutTargets(true);
updateSceneLabels();
updateUI();
const rodWord = rodCount === 1 ? "rod" : "rods";
status.textContent =
`${state.quantity} unit cubes are arranged as ${rodCount} ${BASE_INFO[state.base].rodName.toLowerCase()} ` +
`${rodWord} and ${looseCount} loose units.`;
}
function layoutTargets(immediate = false) {
let rodIndex = 0;
for (const rod of state.rods) {
const z = -1.08 - rodIndex * 0.92;
rod.cubes.forEach((entry, index) => {
entry.target.set(
(index - (state.base - 1) / 2) * SPACING,
0,
z
);
if (immediate) {
entry.group.position.copy(entry.target);
entry.group.scale.setScalar(1);
entry.animation = null;
}
});
if (rod.rail) {
rod.rail.target = new THREE.Vector3(0, -0.325, z);
if (immediate) {
rod.rail.mesh.position.copy(rod.rail.target);
}
}
rodIndex++;
}
const looseCount = state.loose.length;
const columns = looseCount <= 5
? 5
: Math.min(10, looseCount);
state.loose.forEach((entry, index) => {
const row = Math.floor(index / columns);
const column = index % columns;
entry.target.set(
(column - (columns - 1) / 2) * SPACING,
0,
1.18 + row * SPACING
);
if (immediate) {
entry.group.position.copy(entry.target);
entry.group.scale.setScalar(1);
entry.animation = null;
}
});
}
function updateSceneLabels() {
const info = BASE_INFO[state.base];
drawLabel(
rodLabel,
`${state.base} UNIT CUBES = 1 ${info.rodName.toUpperCase()} ROD`,
"#ffd166"
);
drawLabel(
looseLabel,
"LOOSE UNIT CUBES = VALUE 1",
"#4be0c2"
);
const rodRows = Math.max(0, state.rods.length - 1);
const looseRows = Math.ceil(state.loose.length / 10);
rodLabel.sprite.position.set(0, 1.35, -1.75 - rodRows * 0.7);
looseLabel.sprite.position.set(0, 0.85, 1.75 + looseRows * 0.55);
}
// ---------------------------------------------------------------------
// Animation
// ---------------------------------------------------------------------
function animateEntries(focusEntries) {
const now = performance.now();
const duration = reduceMotion ? 30 : 900;
const focusIndex = new Map();
focusEntries.forEach((entry, index) => focusIndex.set(entry, index));
for (const entry of state.entries) {
const focus = focusIndex.has(entry);
const delay = focus
? focusIndex.get(entry) * (reduceMotion ? 0 : 22)
: 0;
entry.animation = {
from: entry.group.position.clone(),
to: entry.target.clone(),
start: now + delay,
duration,
arc: focus ? (reduceMotion ? 0 : 0.52) : (reduceMotion ? 0 : 0.12),
focus
};
}
}
function animateRail(rail, mode) {
const duration = reduceMotion ? 30 : 820;
rail.animation = {
mode,
start: performance.now() + (mode === "in" ? 180 : 0),
duration,
from: rail.mesh.position.clone(),
to: rail.target ? rail.target.clone() : rail.mesh.position.clone()
};
}
function updateAnimations(now) {
let active = false;
for (const entry of state.entries) {
const animation = entry.animation;
if (!animation) continue;
if (now < animation.start) {
active = true;
continue;
}
const raw = Math.min(1, (now - animation.start) / animation.duration);
const t = raw < 0.5
? 4 * raw * raw * raw
: 1 - Math.pow(-2 * raw + 2, 3) / 2;
entry.group.position.lerpVectors(animation.from, animation.to, t);
entry.group.position.y += Math.sin(Math.PI * t) * animation.arc;
const pulse = animation.focus
? 1 + Math.sin(Math.PI * t) * 0.065
: 1;
entry.group.scale.setScalar(pulse);
if (raw >= 1) {
entry.group.position.copy(animation.to);
entry.group.scale.setScalar(1);
entry.animation = null;
} else {
active = true;
}
}
for (const rod of state.rods) {
updateRailAnimation(rod.rail, now);
if (rod.rail?.animation) active = true;
}
// Split rails have already been removed from state.rods, so keep a
// separate list for their fade-out.
for (const rail of fadingRails) {
updateRailAnimation(rail, now);
if (rail.animation) active = true;
}
return active;
}
const fadingRails = [];
function updateRailAnimation(rail, now) {
const animation = rail.animation;
if (!animation) return;
if (now < animation.start) return;
const raw = Math.min(1, (now - animation.start) / animation.duration);
const t = raw < 0.5
? 4 * raw * raw * raw
: 1 - Math.pow(-2 * raw + 2, 3) / 2;
if (animation.mode === "out") {
rail.mesh.material.opacity = 0.92 * (1 - t);
rail.mesh.scale.x = Math.max(0.001, 1 - t);
} else {
rail.mesh.position.lerpVectors(animation.from, animation.to, t);
rail.mesh.material.opacity = 0.92 * t;
rail.mesh.scale.x = Math.max(0.001, t);
}
if (raw >= 1) {
rail.animation = null;
if (animation.mode === "out") {
const index = fadingRails.indexOf(rail);
if (index !== -1) fadingRails.splice(index, 1);
disposeRail(rail);
} else {
rail.mesh.position.copy(animation.to);
rail.mesh.scale.x = 1;
rail.mesh.material.opacity = 0.92;
}
}
}
function flashEquation() {
equationCard.classList.remove("flash");
void equationCard.offsetWidth;
equationCard.classList.add("flash");
}
function flashNumeral() {
numberDisplay.classList.remove("pulse");
void numberDisplay.offsetWidth;
numberDisplay.classList.add("pulse");
}
function splitOneRod() {
if (state.busy || state.rods.length === 0) return;
state.busy = true;
updateUI();
const rod = state.rods.pop();
const focus = rod.cubes;
state.loose.push(...focus);
for (const entry of focus) {
entry.splitOrigin = true;
}
layoutTargets(false);
animateEntries(focus);
fadingRails.push(rod.rail);
animateRail(rod.rail, "out");
const rodName = BASE_INFO[state.base].rodName.toLowerCase();
status.textContent =
`One ${rodName} rod opened into ${state.base} marked unit cubes. ` +
`The total is still ${state.quantity}, so the numeral remains unchanged.`;
flashEquation();
state.actionTimer = window.setTimeout(() => {
state.busy = false;
updateUI();
}, reduceMotion ? 80 : 1200);
}
function packOneRod() {
if (state.busy || state.loose.length < state.base) return;
state.busy = true;
updateUI();
const splitUnits = state.loose.filter((entry) => entry.splitOrigin);
const eligible = splitUnits.length >= state.base
? splitUnits
: state.loose;
const selected = eligible.slice(0, state.base);
const selectedSet = new Set(selected);
state.loose = state.loose.filter((entry) => !selectedSet.has(entry));
const average = new THREE.Vector3();
for (const entry of selected) {
average.add(entry.group.position);
}
average.multiplyScalar(1 / selected.length);
const rod = { cubes: selected, rail: createRail(selected, false) };
rod.rail.mesh.position.copy(average);
state.rods.push(rod);
for (const entry of selected) {
entry.splitOrigin = false;
}
layoutTargets(false);
animateEntries(selected);
animateRail(rod.rail, "in");
const rodName = BASE_INFO[state.base].rodName.toLowerCase();
status.textContent =
`${state.base} marked unit cubes joined into one ${rodName} rod. ` +
`Their value is unchanged, and the written numeral still represents ${state.quantity}.`;
flashEquation();
state.actionTimer = window.setTimeout(() => {
state.busy = false;
updateUI();
}, reduceMotion ? 80 : 1300);
}
// ---------------------------------------------------------------------
// Number conversion and interface
// ---------------------------------------------------------------------
function toBase(value, base) {
if (value === 0) return "0";
let remaining = value;
let result = "";
while (remaining > 0) {
result = String(remaining % base) + result;
remaining = Math.floor(remaining / base);
}
return result;
}
function updateUI() {
const info = BASE_INFO[state.base];
const digits = toBase(state.quantity, state.base);
numeral.textContent = digits;
numeralBase.textContent = state.base;
baseName.textContent = info.name;
baseNote.textContent = `Two-place model · 0–${info.max}`;
equationValue.innerHTML = `${digits}<sub>${state.base}</sub>`;
equationParts.textContent =
`${state.rods.length} × ${state.base} + ${state.loose.length} × 1`;
quantityInput.max = info.max;
quantityInput.value = state.quantity;
quantityTitle.textContent = `${state.quantity} unit cubes`;
quantityDescription.textContent = "The scene always contains this many units.";
sceneCount.textContent = `${state.quantity} cubes · base ${state.base}`;
splitDetail.textContent =
`1 ${info.rodName.toLowerCase()} rod → ${state.base} units`;
packDetail.textContent =
`${state.base} units → 1 ${info.rodName.toLowerCase()} rod`;
splitButton.disabled = state.busy || state.rods.length === 0;
packButton.disabled = state.busy || state.loose.length < state.base;
quantityInput.disabled = state.busy;
for (const button of baseGrid.querySelectorAll("button")) {
const active = Number(button.dataset.base) === state.base;
button.classList.toggle("active", active);
button.setAttribute("aria-pressed", String(active));
button.disabled = state.busy;
}
}
for (let base = 2; base <= 10; base++) {
const button = document.createElement("button");
button.type = "button";
button.className = "base-btn";
button.dataset.base = base;
button.textContent = base;
button.setAttribute("aria-label", `Use base ${base}`);
button.addEventListener("click", () => {
if (state.busy || state.base === base) return;
state.base = base;
state.quantity = BASE_INFO[base].defaultQuantity;
orbit.radius = 8 + base * 0.42;
updateCamera();
rebuildModel();
flashNumeral();
const info = BASE_INFO[base];
status.textContent =
`Base ${base}: ${state.base} marked unit cubes make one ${info.rodName.toLowerCase()} rod. ` +
`The total quantity is ${state.quantity}.`;
});
baseGrid.appendChild(button);
}
quantityInput.addEventListener("change", () => {
if (state.busy) return;
const max = BASE_INFO[state.base].max;
const parsed = Number.parseInt(quantityInput.value, 10);
const next = Number.isFinite(parsed)
? THREE.MathUtils.clamp(parsed, 0, max)
: state.quantity;
state.quantity = next;
rebuildModel();
flashNumeral();
});
quantityInput.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
quantityInput.blur();
quantityInput.dispatchEvent(new Event("change"));
}
});
splitButton.addEventListener("click", splitOneRod);
packButton.addEventListener("click", packOneRod);
// ---------------------------------------------------------------------
// Camera controls implemented directly, without Three.js addons
// ---------------------------------------------------------------------
let dragging = false;
let lastPointerX = 0;
let lastPointerY = 0;
function resetCamera() {
orbit.yaw = 0.38;
orbit.pitch = 0.59;
orbit.radius = 8 + state.base * 0.42;
orbit.target.set(0, 0.12, 0.05);
updateCamera();
}
$("#resetCamera").addEventListener("click", resetCamera);
canvas.addEventListener("pointerdown", (event) => {
dragging = true;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - lastPointerX;
const deltaY = event.clientY - lastPointerY;
lastPointerX = event.clientX;
lastPointerY = event.clientY;
orbit.yaw -= deltaX * 0.006;
orbit.pitch = THREE.MathUtils.clamp(
orbit.pitch + deltaY * 0.005,
0.25,
1.2
);
updateCamera();
});
function stopDragging(event) {
dragging = false;
if (event.pointerId !== undefined && canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", stopDragging);
canvas.addEventListener("pointercancel", stopDragging);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius * Math.exp(event.deltaY * 0.001),
5.5,
24
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetCamera);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight, false);
});
// ---------------------------------------------------------------------
// Start
// ---------------------------------------------------------------------
rebuildModel();
function animate(now) {
requestAnimationFrame(animate);
updateAnimations(now);
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```