Prompt specification
Build or customize the Three.js 3D scene "Unit-cube volume packing box" 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: Unit-cube volume packing box
Category: Algorithms & Systems · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/unit-cube-volume-packing-box-x1757
Scene Description Prompt:
Unit-cube volume packing box. Build a transparent rectangular box filled with countable unit cubes; display length, width, and height in compatible units and show their product matching cube count. Please build this with Three.js from cdnjs in one self-contained HTML file, using low-poly forms.
Working Three.js Starter (unit-cube-volume-packing-box-x1757):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Unit Cube Volume Packing Box</title>
<style>
:root{ --accent:#5eead4; --accent2:#93c5fd; --panel:rgba(9,14,23,.74); }
*{box-sizing:border-box}
html,body{margin:0;height:100%;overflow:hidden;background:#060a11;color:#e6edf7;
font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
background-image:radial-gradient(1200px 700px at 50% 25%,#132038 0%,#080d16 55%,#05080e 100%);}
#app{position:fixed;inset:0}
canvas{display:block;touch-action:none}
.panel{position:absolute;top:14px;left:14px;width:326px;padding:14px 16px;border-radius:14px;
background:var(--panel);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);
border:1px solid rgba(94,234,212,.22);box-shadow:0 14px 44px rgba(0,0,0,.5);font-size:12.5px;line-height:1.55}
h1{font-size:12.5px;letter-spacing:.15em;margin:0;color:var(--accent);text-transform:uppercase}
.sub{color:#7f95ad;font-size:11px;margin:2px 0 10px}
.row{display:flex;align-items:center;gap:8px;margin:5px 0}
.row>label{flex:0 0 84px;color:#9fb3c8}
.row>.u{color:var(--accent2);width:34px;font-size:11.5px}
input[type=number]{width:66px;background:#0c1320;color:#e6edf7;border:1px solid #27384d;border-radius:6px;
padding:4px 7px;font:inherit}
select{flex:1;background:#0c1320;color:#e6edf7;border:1px solid #27384d;border-radius:6px;padding:4px;font:inherit}
.calc{margin-top:10px;padding:10px 11px;border-radius:10px;background:rgba(94,234,212,.07);border:1px solid rgba(94,234,212,.22)}
.big{font-size:23px;color:var(--accent);font-weight:700;letter-spacing:.02em}
.big small{font-size:12px;color:#9fd8cf;font-weight:400}
.eq{color:#d3e4f6;margin-top:3px}
.eq b{color:#fff}
.muted{color:#8296ad;font-size:11px}
.checks{display:flex;align-items:center;gap:12px;margin-top:9px;font-size:11.5px;color:#9fb3c8;flex-wrap:wrap}
.checks label{cursor:pointer}
button{background:#112132;color:#bfe9e0;border:1px solid #26465c;border-radius:7px;padding:4px 10px;
font:inherit;font-size:11.5px;cursor:pointer}
button:hover{background:#173350}
.hint{position:absolute;bottom:12px;left:50%;transform:translateX(-50%);font-size:11px;color:#7d90a6;
background:var(--panel);padding:6px 14px;border-radius:999px;border:1px solid rgba(255,255,255,.07);white-space:nowrap}
@media (max-width:720px){.panel{width:calc(100% - 28px)}.hint{display:none}}
</style>
</head>
<body>
<div id="app"></div>
<div class="panel">
<h1>Unit Cube Packing Box</h1>
<div class="sub">transparent box filled with 1×1×1 unit cubes</div>
<div class="row"><label for="inL">Length L</label><input id="inL" type="number" min="1" max="14" step="1" value="8"><span class="u" id="uL">m</span></div>
<div class="row"><label for="inW">Width W</label><input id="inW" type="number" min="1" max="14" step="1" value="5"><span class="u" id="uW">m</span></div>
<div class="row"><label for="inH">Height H</label><input id="inH" type="number" min="1" max="14" step="1" value="4"><span class="u" id="uH">m</span></div>
<div class="row"><label for="inUnit">Unit</label>
<select id="inUnit">
<option value="m">meters (m)</option>
<option value="ft">feet (ft)</option>
<option value="in">inches (in)</option>
<option value="cm">centimeters (cm)</option>
</select>
</div>
<div class="calc">
<div class="big"><span id="count">0</span> <small id="cubeWord">unit cubes</small></div>
<div class="eq" id="eq"></div>
<div class="muted" id="vol"></div>
<div class="muted" id="conv"></div>
</div>
<div class="muted" id="cubeinfo"></div>
<div class="checks">
<label><input type="checkbox" id="cutaway"> cutaway</label>
<label><input type="checkbox" id="spin" checked> auto‑rotate</label>
<button id="reset">reset view</button>
</div>
</div>
<div class="hint">drag = orbit · right / shift‑drag = pan · wheel / pinch = zoom · arrows + / − + R</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
/* ---------- DOM helpers ---------- */
const $ = id => document.getElementById(id);
/* ---------- renderer / scene ---------- */
const app = $('app');
const renderer = new THREE.WebGLRenderer({ antialias:true, alpha:true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
app.appendChild(renderer.domElement);
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(45, innerWidth/innerHeight, 0.1, 600);
scene.add(new THREE.HemisphereLight(0x9ecbff, 0x141a25, 0.75));
const key = new THREE.DirectionalLight(0xffffff, 1.2);
key.position.set(7, 11, 6);
key.castShadow = true;
key.shadow.mapSize.set(1024,1024);
key.shadow.bias = -0.0016;
scene.add(key);
const rim = new THREE.DirectionalLight(0x6ea8ff, 0.45);
rim.position.set(-7, 4, -8);
scene.add(rim);
/* floor: shadow catcher + grid */
const floor = new THREE.Mesh(new THREE.PlaneGeometry(160,160), new THREE.ShadowMaterial({ opacity:0.45 }));
floor.rotation.x = -Math.PI/2;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(80, 80, 0x2a4360, 0x182634);
grid.material.transparent = true; grid.material.opacity = 0.5;
scene.add(grid);
/* ---------- hand written orbit controls (no addons) ---------- */
const orbit = { theta: 0.78, phi: 1.06, radius: 18, target: new THREE.Vector3(),
dragging:false, panning:false, lastX:0, lastY:0 };
const pointers = new Map();
let pinchPrev = 0;
function applyCamera(){
const s = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * s * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * s * Math.cos(orbit.theta));
camera.lookAt(orbit.target);
}
function pan(dx, dy){
camera.updateMatrixWorld();
const right = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 0);
const up = new THREE.Vector3().setFromMatrixColumn(camera.matrix, 1);
const sc = 2 * orbit.radius * Math.tan(THREE.MathUtils.degToRad(camera.fov/2)) / innerHeight;
orbit.target.addScaledVector(right, -dx*sc).addScaledVector(up, dy*sc);
}
const el = renderer.domElement;
el.addEventListener('contextmenu', e => e.preventDefault());
el.addEventListener('pointerdown', e => {
el.setPointerCapture(e.pointerId);
pointers.set(e.pointerId, {x:e.clientX, y:e.clientY});
orbit.dragging = true;
orbit.panning = (e.button === 2 || e.button === 1 || e.shiftKey);
orbit.lastX = e.clientX; orbit.lastY = e.clientY;
});
el.addEventListener('pointermove', e => {
if(!pointers.has(e.pointerId)) return;
if(pointers.size === 1){
const dx = e.clientX - orbit.lastX, dy = e.clientY - orbit.lastY;
if(orbit.panning){ pan(dx, dy); }
else {
orbit.theta -= dx * 0.006;
orbit.phi = THREE.MathUtils.clamp(orbit.phi - dy*0.006, 0.12, Math.PI-0.12);
}
orbit.lastX = e.clientX; orbit.lastY = e.clientY;
} else if(pointers.size === 2){
const [a,b] = [...pointers.values()];
const d = Math.hypot(a.x-b.x, a.y-b.y);
if(pinchPrev) orbit.radius = THREE.MathUtils.clamp(orbit.radius * (pinchPrev/d), 4, 140);
pinchPrev = d;
}
pointers.set(e.pointerId, {x:e.clientX, y:e.clientY});
});
function endPointer(e){
pointers.delete(e.pointerId);
if(pointers.size < 2) pinchPrev = 0;
if(pointers.size === 0) orbit.dragging = false;
}
el.addEventListener('pointerup', endPointer);
el.addEventListener('pointercancel', endPointer);
el.addEventListener('wheel', e => {
e.preventDefault();
orbit.radius = THREE.MathUtils.clamp(orbit.radius * Math.exp(e.deltaY*0.0012), 4, 140);
}, {passive:false});
window.addEventListener('keydown', e => {
const k = e.key.toLowerCase();
if(k === 'arrowleft') orbit.theta += 0.12;
else if(k === 'arrowright') orbit.theta -= 0.12;
else if(k === 'arrowup') orbit.phi = THREE.MathUtils.clamp(orbit.phi - 0.09, 0.12, Math.PI-0.12);
else if(k === 'arrowdown') orbit.phi = THREE.MathUtils.clamp(orbit.phi + 0.09, 0.12, Math.PI-0.12);
else if(k === '+' || k === '=') orbit.radius = Math.max(4, orbit.radius*0.88);
else if(k === '-') orbit.radius = Math.min(140, orbit.radius*1.14);
else if(k === 'r') resetView();
});
/* ---------- units ---------- */
const UNITS = {
m : {abbr:'m', vol:'m³', liters:1},
ft: {abbr:'ft', vol:'ft³', liters:28.316846592},
in: {abbr:'in', vol:'in³', liters:0.016387064},
cm: {abbr:'cm', vol:'cm³', liters:0.001}
};
/* ---------- state ---------- */
let L = 8, W = 5, H = 4;
let group = null, cubeMesh = null, cubeData = [];
let revealT = 0, revealDur = 1, revealing = true;
const dummy = new THREE.Object3D();
/* ---------- label sprites (canvas textures) ---------- */
function makeLabel(text, worldH = 0.6, fg = '#e8f4ff', bg = 'rgba(8,13,22,.88)', bd = '#5eead4'){
const c = document.createElement('canvas');
const ctx = c.getContext('2d');
const fontPx = 64, font = `600 ${fontPx}px ui-monospace, Menlo, Consolas, monospace`;
ctx.font = font;
const w = Math.ceil(ctx.measureText(text).width) + 56;
c.width = w; c.height = fontPx + 40;
const g = c.getContext('2d');
g.font = font; g.textAlign = 'center'; g.textBaseline = 'middle';
const r = 16, x = 2, y = 2, W2 = w-4, H2 = c.height-4;
g.beginPath();
g.moveTo(x+r,y); g.arcTo(x+W2,y,x+W2,y+H2,r); g.arcTo(x+W2,y+H2,x,y+H2,r);
g.arcTo(x,y+H2,x,y,r); g.arcTo(x,y,x+W2,y,r); g.closePath();
g.fillStyle = bg; g.fill();
g.lineWidth = 3; g.strokeStyle = bd; g.stroke();
g.fillStyle = fg; g.fillText(text, w/2, c.height/2 + 2);
const tex = new THREE.CanvasTexture(c);
tex.colorSpace = THREE.SRGBColorSpace;
tex.minFilter = THREE.LinearFilter;
tex.generateMipmaps = false;
const mat = new THREE.SpriteMaterial({ map:tex, transparent:true, depthTest:false, depthWrite:false });
const sp = new THREE.Sprite(mat);
sp.scale.set((w/c.height)*worldH, worldH, 1);
sp.renderOrder = 10;
return sp;
}
/* ---------- dimension line helper ---------- */
function dimLine(a, b, tick, color = 0x6ee7ff){
const g = new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(...a), new THREE.Vector3(...b)]);
group.add(new THREE.Line(g, new THREE.LineBasicMaterial({ color, transparent:true, opacity:0.9 })));
for(const p of [a, b]){
const tg = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(p[0]-tick[0], p[1]-tick[1], p[2]-tick[2]),
new THREE.Vector3(p[0]+tick[0], p[1]+tick[1], p[2]+tick[2])]);
group.add(new THREE.Line(tg, new THREE.LineBasicMaterial({ color, transparent:true, opacity:0.9 })));
}
}
function leader(a, b, color = 0xffc857){
const g = new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(...a), new THREE.Vector3(...b)]);
group.add(new THREE.Line(g, new THREE.LineBasicMaterial({ color, transparent:true, opacity:0.85 })));
}
/* ---------- build the scene for L x W x H ---------- */
function disposeGroup(g){
g.traverse(o => {
if(o.geometry) o.geometry.dispose();
if(o.material){
(Array.isArray(o.material) ? o.material : [o.material]).forEach(m => { if(m.map) m.map.dispose(); m.dispose(); });
}
});
}
function rebuild(){
if(group){ scene.remove(group); disposeGroup(group); }
group = new THREE.Group();
scene.add(group);
const u = UNITS[$('inUnit').value];
const cut = $('cutaway').checked;
/* transparent shell + crisp edges */
const bg = new THREE.BoxGeometry(L, H, W);
group.add(new THREE.Mesh(bg, new THREE.MeshBasicMaterial({
color:0x67e8f9, transparent:true, opacity:0.065, side:THREE.DoubleSide, depthWrite:false })));
const eg = new THREE.EdgesGeometry(bg); bg.dispose();
group.add(new THREE.LineSegments(eg, new THREE.LineBasicMaterial({ color:0x86d8fb, transparent:true, opacity:0.7 })));
/* the cubes */
const list = [];
for(let k=0;k<H;k++) for(let j=0;j<W;j++) for(let i=0;i<L;i++){
const focus = (i===0 && j===W-1 && k===H-1);
if(cut && j===W-1 && !focus) continue; /* cutaway hides front layer */
list.push({i,j,k,focus});
}
cubeMesh = new THREE.InstancedMesh(
new THREE.BoxGeometry(0.955,0.955,0.955),
new THREE.MeshLambertMaterial({ color:0xffffff }), list.length);
cubeMesh.castShadow = true; cubeMesh.receiveShadow = true;
cubeMesh.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
group.add(cubeMesh);
const col = new THREE.Color();
list.forEach((c,n) => {
if(c.focus) col.setHex(0xffc857);
else {
const hue = (0.52 + 0.30*(c.k/Math.max(1,H-1)) + 0.025*Math.sin(c.i*1.7 + c.j*2.3)) % 1;
col.setHSL(hue, 0.55, 0.52);
}
cubeMesh.setColorAt(n, col);
});
cubeMesh.instanceColor.needsUpdate = true;
const maxDelay = (H-1)*0.085 + 0.12;
cubeData = list.map(c => ({
x:-L/2 + c.i + 0.5, y:-H/2 + c.k + 0.5, z:-W/2 + c.j + 0.5,
delay: c.k*0.085 + (c.i + c.j)*0.006
}));
revealDur = maxDelay + 0.5; revealT = 0; revealing = true;
/* dimension lines (engineering style, outside the box) */
const dx = 0.62, dy = 0.58;
dimLine([-L/2, -H/2-dy, W/2+0.38], [L/2, -H/2-dy, W/2+0.38], [0,0.19,0]); /* length (X) */
dimLine([L/2+dx, -H/2-dy, -W/2], [L/2+dx, -H/2-dy, W/2], [0.19,0,0]); /* width (Z) */
dimLine([L/2+dx, -H/2, W/2+dx], [L/2+dx, H/2, W/2+dx], [0,0,0.19]); /* height (Y) */
const lab = (t,h,p) => { const s = makeLabel(t,h); s.position.set(...p); group.add(s); return s; };
lab(`L = ${L} ${u.abbr}`, 0.56, [0, -H/2-dy-0.46, W/2+0.38]);
lab(`W = ${W} ${u.abbr}`, 0.56, [L/2+dx, -H/2-dy-0.46, 0]);
lab(`H = ${H} ${u.abbr}`, 0.56, [L/2+dx+0.62, 0, W/2+dx]);
/* total callout above the box */
const total = L*W*H;
lab(`${L} × ${W} × ${H} = ${total} cubes`, 0.72, [0, H/2 + 0.95, 0]);
/* the unit cube callout (amber cube at the top front left) */
const fc = [-L/2 + 0.5, H/2 - 0.5, W/2 - 0.5];
lab(`1 cube = 1 ${u.vol}`, 0.52, [-L/2 - 1.15, H/2 + 0.28, W/2 - 0.5]);
leader([-L/2 - 0.72, H/2 + 0.1, W/2 - 0.5], [fc[0], fc[1], fc[2]], 0xffc857);
/* floor follows the box */
floor.position.y = -H/2 - 0.06;
grid.position.y = -H/2 - 0.055;
/* shadow + camera fit */
const s = Math.max(L, W, H) * 0.9 + 3;
Object.assign(key.shadow.camera, { left:-s, right:s, top:s, bottom:-s });
key.shadow.camera.updateProjectionMatrix();
orbit.radius = Math.hypot(L, W, H) * 1.55 + 1.6;
updateHUD();
}
/* ---------- HUD ---------- */
function fmt(n){
if(n >= 1000) return Math.round(n).toLocaleString();
if(n >= 10) return n.toFixed(1).replace(/\.0$/, '');
return n.toFixed(3).replace(/0+$/, '').replace(/\.$/, '');
}
function updateHUD(){
const u = UNITS[$('inUnit').value];
const n = L*W*H;
$('uL').textContent = u.abbr; $('uW').textContent = u.abbr; $('uH').textContent = u.abbr;
$('count').textContent = n.toLocaleString();
$('cubeWord').textContent = 'unit cubes';
$('eq').innerHTML = `${L} ${u.abbr} × ${W} ${u.abbr} × ${H} ${u.abbr} = <b>${n.toLocaleString()} ${u.vol}</b>`;
$('vol').textContent = `Volume = ${n.toLocaleString()} ${u.vol} = ${n.toLocaleString()} cubes × (1 ${u.vol} each)`;
$('conv').textContent = `≈ ${fmt(n*u.liters)} L ≈ ${fmt(n*u.liters/3.785411784)} US gal`;
$('cubeinfo').textContent = `Every cube has 1 ${u.abbr} edge, so it holds exactly 1 ${u.vol}. The ${n.toLocaleString()} cubes therefore fill the box exactly — no gaps, no overflow.`;
}
/* ---------- animation ---------- */
function applyReveal(t){
for(let n=0; n<cubeData.length; n++){
const c = cubeData[n];
let s = THREE.MathUtils.clamp((t - c.delay)/0.45, 0, 1);
s = 1 - Math.pow(1 - s, 3);
dummy.position.set(c.x, c.y - (1-s)*0.5, c.z);
dummy.scale.setScalar(s);
dummy.updateMatrix();
cubeMesh.setMatrixAt(n, dummy.matrix);
}
cubeMesh.instanceMatrix.needsUpdate = true;
}
const clock = new THREE.Clock();
function tick(){
requestAnimationFrame(tick);
const dt = Math.min(clock.getDelta(), 0.05);
if(revealing){
revealT += dt;
applyReveal(revealT);
const u = UNITS[$('inUnit').value];
const p = THREE.MathUtils.clamp(revealT / revealDur, 0, 1);
$('count').textContent = Math.round((L*W*H) * (1 - Math.pow(1-p,3))).toLocaleString();
if(revealT >= revealDur){ revealing = false; $('count').textContent = (L*W*H).toLocaleString(); }
}
if($('spin').checked && !orbit.dragging && !revealing) orbit.theta += dt * 0.16;
applyCamera();
renderer.render(scene, camera);
}
/* ---------- events ---------- */
function clampDim(v, cur){ v = parseInt(v, 10); if(!isFinite(v)) return cur; return Math.min(14, Math.max(1, v)); }
$('inL').addEventListener('input', e => { L = clampDim(e.target.value, L); e.target.value = L; rebuild(); });
$('inW').addEventListener('input', e => { W = clampDim(e.target.value, W); e.target.value = W; rebuild(); });
$('inH').addEventListener('input', e => { H = clampDim(e.target.value, H); e.target.value = H; rebuild(); });
$('inUnit').addEventListener('change', rebuild);
$('cutaway').addEventListener('change', rebuild);
$('reset').addEventListener('click', resetView);
function resetView(){
orbit.theta = 0.78; orbit.phi = 1.06;
orbit.target.set(0,0,0);
orbit.radius = Math.hypot(L, W, H) * 1.55 + 1.6;
}
window.addEventListener('resize', () => {
camera.aspect = innerWidth/innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
/* ---------- go ---------- */
rebuild();
applyCamera();
tick();
</script>
</body>
</html>
```