Prompt specification
Build or customize the Three.js 3D scene "Weight-distance balance challenge" 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: Weight-distance balance challenge
Category: Voxel Worlds · Style: Voxel 3D
License: MIT · Reference: https://three3d.app/scene/weight-distance-balance-challenge-x0322
Scene Description Prompt:
Create a single self-contained HTML file using Three.js from cdnjs that shows a balance scale. Place one block farther from the pivot and two nearer the opposite side; animate the beam toward balance using a simple moment rule with visible values. Voxel style.
Working Three.js Starter (weight-distance-balance-challenge-x0322):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Voxel Balance — Moment Rule</title>
<style>
* { box-sizing: border-box; }
html, body { margin:0; height:100%; overflow:hidden; background:#141a26;
font-family:"Courier New", Courier, monospace; color:#c9d4e4; }
#app { position:fixed; inset:0; }
canvas { display:block; touch-action:none; }
#hud { position:fixed; left:14px; top:14px; width:340px; padding:12px 14px 14px;
background:rgba(11,15,23,.86); border:2px solid #2b3446; box-shadow:0 0 0 2px #0b0f17;
font-size:12.5px; line-height:1.5; user-select:none; }
#hud h1 { margin:0 0 6px; font-size:15px; letter-spacing:2px; color:#eaf1fb; }
#hud .rule { font-size:11.5px; color:#8fa0b8; border-bottom:1px dashed #33405a;
padding-bottom:8px; margin-bottom:9px; }
.side { border-left:5px solid; padding:6px 0 6px 9px; margin-bottom:7px; background:#141b28; }
.side .tag { font-size:10.5px; letter-spacing:1.5px; opacity:.75; }
.side .line { font-size:13px; font-weight:bold; }
.side .sub { font-size:11px; color:#8fa0b8; }
.amber { border-color:#ff9f43; } .amber .line { color:#ffc078; }
.teal { border-color:#2ec4b6; } .teal .line { color:#5fe3d6; }
.stat { display:flex; justify-content:space-between; border-bottom:1px dotted #2b3446; padding:2px 0; }
.stat b { color:#eaf1fb; }
#status { margin-top:9px; text-align:center; padding:6px; border:2px solid #33405a;
letter-spacing:2px; font-weight:bold; font-size:12px; background:#141b28; }
#status.ok { border-color:#4ade80; color:#86efac; background:#12261a; }
#status.mid { border-color:#ff9f43; color:#ffc078; }
#controls { margin-top:11px; border-top:1px dashed #33405a; padding-top:9px; }
.ctl { margin-bottom:9px; }
.ctl label { display:flex; justify-content:space-between; font-size:11px; color:#9db0c8; }
.ctl label b { color:#eaf1fb; }
input[type=range] { width:100%; margin:3px 0 0; accent-color:#ff9f43; height:16px; }
.btns { display:flex; gap:7px; margin-top:4px; }
button { flex:1; font-family:inherit; font-size:11.5px; letter-spacing:1px; cursor:pointer;
color:#dbe6f5; background:#1d2637; border:2px solid #33405a; padding:6px 0; }
button:hover { background:#27344a; border-color:#ff9f43; color:#ffc078; }
#hint { position:fixed; right:14px; bottom:12px; font-size:11px; color:#63748c; text-align:right; }
</style>
</head>
<body>
<div id="app"></div>
<div id="hud">
<h1>VOXEL BALANCE</h1>
<div class="rule">τ = m · g · d → balance when Σ(m·d) = 0<br>
the heavy block <b>slides toward the pivot</b> until its moment matches</div>
<div class="side amber">
<div class="tag">FAR SIDE — 1 BLOCK</div>
<div class="line" id="farLine">5 kg × 3.00 m = 15.00 kg·m</div>
<div class="sub" id="farTorque">torque = 147.0 N·m</div>
</div>
<div class="side teal">
<div class="tag">NEAR SIDE — 2 BLOCKS</div>
<div class="line" id="nearLine">2 × 3 kg × 1.50 m = 9.00 kg·m</div>
<div class="sub" id="nearTorque">torque = 88.2 N·m</div>
</div>
<div class="stat"><span>Δ moment</span><b id="diffVal">6.00 kg·m</b></div>
<div class="stat"><span>beam tilt</span><b id="tiltVal">14.6°</b></div>
<div class="stat"><span>balance point d* = M₂/m₁</span><b id="targetVal">1.80 m</b></div>
<div class="stat"><span>block distance now</span><b id="d1Val">3.00 m</b></div>
<div id="status">SLIDING…</div>
<div id="controls">
<div class="ctl">
<label>near-side distance d₂ <b id="d2Out">1.50 m</b></label>
<input id="d2" type="range" min="0.60" max="2.00" step="0.05" value="1.50">
</div>
<div class="ctl">
<label>far block mass m₁ <b id="mOut">5 kg</b></label>
<input id="mass" type="range" min="2" max="8" step="1" value="5">
</div>
<div class="ctl">
<label>gravity g <b id="gOut">9.8 m/s²</b></label>
<input id="grav" type="range" min="3" max="15" step="0.1" value="9.8">
</div>
<div class="btns">
<button id="reset">RESET</button>
<button id="pause">PAUSE</button>
</div>
</div>
</div>
<div id="hint">drag = orbit · scroll = zoom<br>g changes torque (N·m) but not the balance point</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
/* ---------------- renderer / scene ---------------- */
const app = document.getElementById('app');
const renderer = new THREE.WebGLRenderer({ antialias:true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
app.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x141a26);
scene.fog = new THREE.Fog(0x141a26, 22, 48);
const camera = new THREE.PerspectiveCamera(42, innerWidth/innerHeight, 0.1, 120);
scene.add(new THREE.HemisphereLight(0xbfd4ff, 0x2b3040, 0.9));
const sun = new THREE.DirectionalLight(0xfff1d9, 1.45);
sun.position.set(6.5, 11, 7);
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 = 42;
sun.shadow.bias = -0.0013;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x86a8ff, 0.4);
rim.position.set(-8, 5.5, -6);
scene.add(rim);
/* ---------------- voxel helpers ---------------- */
const unitBox = new THREE.BoxGeometry(1, 1, 1);
function box(w, h, d, color, x, y, z, parent = scene, mat = null) {
const m = new THREE.Mesh(unitBox, mat || new THREE.MeshLambertMaterial({ color }));
m.scale.set(w, h, d);
m.position.set(x, y, z);
m.castShadow = true; m.receiveShadow = true;
parent.add(m);
return m;
}
const clamp = (v, a, b) => Math.max(a, Math.min(b, v));
/* ---------------- ground ---------------- */
box(46, 0.5, 46, 0x232a38, 0, -0.25, 0);
const N = 16, tileGeo = new THREE.BoxGeometry(1, 0.09, 1);
const tiles = new THREE.InstancedMesh(tileGeo, new THREE.MeshLambertMaterial({ color: 0xffffff }), N * N);
tiles.receiveShadow = true;
const mtx = new THREE.Matrix4(), tmpC = new THREE.Color();
let ti = 0;
for (let x = -N/2; x < N/2; x++) for (let z = -N/2; z < N/2; z++) {
const s = 0.92 + Math.random() * 0.1;
mtx.compose(new THREE.Vector3(x + 0.5, 0.045, z + 0.5),
new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0,1,0), Math.random()*0.02),
new THREE.Vector3(s, 1, s));
tiles.setMatrixAt(ti, mtx);
const v = 0.72 + Math.random() * 0.12;
tmpC.setRGB(v*0.72, v*0.80, v*0.95);
tiles.setColorAt(ti, tmpC);
ti++;
}
tiles.instanceMatrix.needsUpdate = true;
if (tiles.instanceColor) tiles.instanceColor.needsUpdate = true;
scene.add(tiles);
/* voxel scenery */
function voxelTree(x, z, h, leafColor) {
box(0.35, h, 0.35, 0x6b4a2f, x, h/2, z);
const top = h + 0.5;
for (let i = 0; i < 8; i++) {
const gx = x + (Math.random() < .5 ? -0.35 : 0.35) * (Math.random() < .4 ? 2 : 1);
const gz = z + (Math.random() < .5 ? -0.35 : 0.35) * (Math.random() < .4 ? 2 : 1);
const gy = top + Math.random() * 0.6;
box(0.55, 0.55, 0.55, leafColor, gx, gy, gz);
}
}
voxelTree(-7.2, -5.0, 2.2, 0x3f8f5a);
voxelTree(6.8, -6.4, 2.6, 0x4aa06a);
for (let i = 0; i < 7; i++) {
const rx = (Math.random() - .5) * 20, rz = (Math.random() - .5) * 20;
if (Math.hypot(rx, rz) < 7) continue;
const s = 0.4 + Math.random() * 0.7;
box(s, s * 0.7, s, 0x59637a, rx, s * 0.35, rz);
}
/* ---------------- the scale ---------------- */
const PIVOT_Y = 2.55;
box(3.7, 0.40, 2.5, 0x46505f, 0, 0.20, 0);
box(2.9, 0.30, 1.9, 0x556172, 0, 0.55, 0);
box(0.62, 1.45, 0.62, 0x6b7889, 0, 1.425, 0);
box(0.95, 0.35, 0.95, 0x7d8b9d, 0, 2.325, 0);
box(0.26, 0.26, 1.10, 0x39445a, 0, PIVOT_Y, 0); // axle
const beam = new THREE.Group();
beam.position.set(0, PIVOT_Y, 0);
scene.add(beam);
box(3.60, 0.16, 1.00, 0xc3ccd8, -1.80, 0, 0, beam); // long (far) arm
box(2.40, 0.16, 1.00, 0xc3ccd8, 1.20, 0, 0, beam); // short (near) arm
box(0.45, 0.30, 1.05, 0xff9f43, -3.37, 0.02, 0, beam); // amber end cap
box(0.40, 0.30, 1.05, 0x2ec4b6, 2.20, 0.02, 0, beam); // teal end cap
box(0.50, 0.24, 1.06, 0x556172, 0.00, 0, 0, beam); // pivot block
// distance ticks along the beam
for (let x = -3.5; x <= -0.25; x += 0.25) {
const major = Math.abs(x - Math.round(x)) < 0.01;
box(0.04, major ? 0.10 : 0.05, major ? 0.72 : 0.52, 0x7e8a9c, x, 0.11, 0, beam);
}
for (let x = 0.25; x <= 2.25; x += 0.25) {
const major = Math.abs(x - Math.round(x)) < 0.01;
box(0.04, major ? 0.10 : 0.05, major ? 0.72 : 0.52, 0x7e8a9c, x, 0.11, 0, beam);
}
// dashed level reference (static, shows where "balanced" is)
const lvlMat = new THREE.MeshLambertMaterial({ color: 0x5ef0c0, transparent: true, opacity: 0.55 });
for (let x = -3.9; x <= 3.9; x += 0.5) box(0.26, 0.04, 0.04, 0, x, PIVOT_Y + 0.02, 0.62, scene, lvlMat);
// target marker (where the far block must end up)
const markMat = new THREE.MeshLambertMaterial({ color: 0xffc078, transparent: true, opacity: 0.45 });
const targetMark = box(0.09, 0.40, 1.06, 0, 0, 0.14, 0, beam, markMat);
/* ---------------- voxel blocks ---------------- */
function makeBlock(mass, hex) {
const side = 0.34 + 0.062 * mass;
const c = side / 3;
const g = new THREE.Group();
const base = new THREE.Color(hex);
const mats = [0.80, 0.95, 1.10].map(s => new THREE.MeshLambertMaterial({ color: base.clone().multiplyScalar(s) }));
for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) for (let k = 0; k < 3; k++) {
const m = new THREE.Mesh(unitBox, mats[(i * 3 + j * 5 + k * 7) % 3]);
m.scale.set(c, c, c);
m.position.set((i - 1) * c, (j - 1) * c, (k - 1) * c);
m.castShadow = true; m.receiveShadow = true;
g.add(m);
}
g.userData.side = side;
g.userData.mats = mats;
return g;
}
/* ---------------- 3D value labels ---------------- */
function makeLabel() {
const canvas = document.createElement('canvas');
canvas.width = 340; canvas.height = 100;
const ctx = canvas.getContext('2d');
const tex = new THREE.CanvasTexture(canvas);
tex.colorSpace = THREE.SRGBColorSpace;
const sprite = new THREE.Sprite(new THREE.SpriteMaterial({ map: tex, transparent: true, depthTest: false }));
sprite.scale.set(2.35, 0.69, 1);
sprite.renderOrder = 20;
const set = (l1, l2, hex) => {
ctx.clearRect(0, 0, 340, 100);
ctx.fillStyle = 'rgba(10,14,22,0.78)';
ctx.fillRect(0, 8, 340, 84);
ctx.strokeStyle = hex; ctx.lineWidth = 4; ctx.strokeRect(2, 10, 336, 80);
ctx.fillStyle = hex; ctx.fillRect(4, 12, 9, 76);
ctx.textBaseline = 'top';
ctx.font = 'bold 25px monospace'; ctx.fillStyle = '#e8eef7'; ctx.fillText(l1, 22, 18);
ctx.font = 'bold 29px monospace'; ctx.fillStyle = hex; ctx.fillText(l2, 22, 50);
tex.needsUpdate = true;
};
return { sprite, set };
}
const labFar = makeLabel(); beam.add(labFar.sprite);
const labNear = makeLabel(); beam.add(labNear.sprite);
/* ---------------- state ---------------- */
const S = {
mFar: 5, nearMass: 3, nearCount: 2,
d2: 1.50, g: 9.8,
d1: 3.00, v1: 0,
paused: false, target: 1.8
};
const K = 7.5, C = 3.4; // spring / damper for the sliding block
const MAX_TILT = 0.42; // rad
const TILT_SCALE = 7.5; // kg·m -> tanh scale
let farBlock = makeBlock(S.mFar, 0xff9f43);
beam.add(farBlock);
const nearBlocks = [makeBlock(S.nearMass, 0x2ec4b6), makeBlock(S.nearMass, 0x2ec4b6)];
nearBlocks[0].position.z = -0.28; nearBlocks[1].position.z = 0.28;
nearBlocks.forEach(b => beam.add(b));
/* ---------------- controls ---------------- */
const d2El = document.getElementById('d2'), massEl = document.getElementById('mass'), gravEl = document.getElementById('grav');
d2El.addEventListener('input', () => { S.d2 = +d2El.value; document.getElementById('d2Out').textContent = S.d2.toFixed(2) + ' m'; });
massEl.addEventListener('input', () => {
S.mFar = +massEl.value;
document.getElementById('mOut').textContent = S.mFar + ' kg';
beam.remove(farBlock);
farBlock.userData.mats.forEach(m => m.dispose());
farBlock = makeBlock(S.mFar, 0xff9f43);
beam.add(farBlock);
});
gravEl.addEventListener('input', () => { S.g = +gravEl.value; document.getElementById('gOut').textContent = S.g.toFixed(1) + ' m/s²'; });
document.getElementById('reset').addEventListener('click', () => {
S.d1 = 3.0; S.v1 = 0; S.paused = false;
document.getElementById('pause').textContent = 'PAUSE';
});
document.getElementById('pause').addEventListener('click', e => {
S.paused = !S.paused;
e.target.textContent = S.paused ? 'RESUME' : 'PAUSE';
});
/* ---------------- orbit (custom, no addons) ---------------- */
const orbit = { theta: 0.60, phi: 1.12, radius: 12.5, target: new THREE.Vector3(0, 2.1, 0) };
function updateCamera() {
const s = new THREE.Spherical(orbit.radius, orbit.phi, orbit.theta);
camera.position.setFromSpherical(s).add(orbit.target);
camera.lookAt(orbit.target);
}
updateCamera();
let dragging = false, lx = 0, ly = 0;
renderer.domElement.addEventListener('pointerdown', e => { dragging = true; lx = e.clientX; ly = e.clientY; renderer.domElement.setPointerCapture(e.pointerId); });
renderer.domElement.addEventListener('pointermove', e => {
if (!dragging) return;
const dx = e.clientX - lx, dy = e.clientY - ly; lx = e.clientX; ly = e.clientY;
orbit.theta -= dx * 0.006;
orbit.phi = clamp(orbit.phi - dy * 0.005, 0.22, 1.46);
});
renderer.domElement.addEventListener('pointerup', e => { dragging = false; });
renderer.domElement.addEventListener('pointercancel', () => { dragging = false; });
renderer.domElement.addEventListener('wheel', e => {
e.preventDefault();
orbit.radius = clamp(orbit.radius + e.deltaY * 0.012, 6, 26);
}, { passive: false });
window.addEventListener('resize', () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
/* ---------------- HUD refs ---------------- */
const el = id => document.getElementById(id);
const hudFarLine = el('farLine'), hudFarTq = el('farTorque'), hudNearLine = el('nearLine'), hudNearTq = el('nearTorque');
const hudDiff = el('diffVal'), hudTilt = el('tiltVal'), hudTarget = el('targetVal'), hudD1 = el('d1Val'), statusEl = el('status');
/* ---------------- main loop ---------------- */
const clock = new THREE.Clock();
let hudTimer = 0;
function frame() {
requestAnimationFrame(frame);
const dt = Math.min(clock.getDelta(), 1 / 30);
if (!S.paused) {
// --- moment rule: the far block slides until m1*d1 = M2 ---
const M2 = S.nearCount * S.nearMass * S.d2;
S.target = M2 / S.mFar;
const tgt = clamp(S.target, 0.40, 3.50);
S.v1 += ((tgt - S.d1) * K - S.v1 * C) * dt;
S.d1 += S.v1 * dt;
S.d1 = clamp(S.d1, 0.32, 3.55);
}
const M1 = S.mFar * S.d1;
const M2 = S.nearCount * S.nearMass * S.d2;
const diff = M1 - M2; // kg·m
const tilt = MAX_TILT * Math.tanh(diff / TILT_SCALE); // rad, far side down when diff>0
beam.rotation.z += (tilt - beam.rotation.z) * Math.min(1, dt * 12);
// block placement on the (tilted) beam
farBlock.position.set(-S.d1, 0.08 + farBlock.userData.side / 2 + 0.02, 0);
nearBlocks.forEach(b => { b.position.x = S.d2; b.position.y = 0.08 + b.userData.side / 2 + 0.02; });
targetMark.position.x = -clamp(S.target, 0.40, 3.50);
// labels
labFar.sprite.position.set(-S.d1, 0.08 + farBlock.userData.side + 0.62, 0);
labNear.sprite.position.set(S.d2, 0.08 + nearBlocks[0].userData.side + 0.62, 0);
hudTimer += dt;
if (hudTimer > 0.06) {
hudTimer = 0;
const tq1 = S.g * M1, tq2 = S.g * M2;
hudFarLine.textContent = `${S.mFar} kg × ${S.d1.toFixed(2)} m = ${M1.toFixed(2)} kg·m`;
hudFarTq.textContent = `torque = ${tq1.toFixed(1)} N·m`;
hudNearLine.textContent = `${S.nearCount} × ${S.nearMass} kg × ${S.d2.toFixed(2)} m = ${M2.toFixed(2)} kg·m`;
hudNearTq.textContent = `torque = ${tq2.toFixed(1)} N·m`;
hudDiff.textContent = `${diff.toFixed(2)} kg·m`;
hudTilt.textContent = `${(beam.rotation.z * 180 / Math.PI).toFixed(1)}°`;
hudTarget.textContent = `${S.target.toFixed(2)} m`;
hudD1.textContent = `${S.d1.toFixed(2)} m`;
labFar.set(`${S.mFar} kg × ${S.d1.toFixed(2)} m`, `= ${M1.toFixed(2)} kg·m`, '#ffc078');
labNear.set(`${S.nearCount} × ${S.nearMass} kg × ${S.d2.toFixed(2)} m`, `= ${M2.toFixed(2)} kg·m`, '#5fe3d6');
const blocked = S.target > 3.50 || S.target < 0.40;
if (blocked) {
statusEl.textContent = S.target > 3.50 ? 'CANNOT BALANCE — TOO LIGHT' : 'CANNOT BALANCE — TOO HEAVY';
statusEl.className = 'mid';
} else if (Math.abs(diff) < 0.06) {
statusEl.textContent = 'BALANCED ✓';
statusEl.className = 'ok';
} else {
statusEl.textContent = 'SLIDING TOWARD BALANCE…';
statusEl.className = 'mid';
}
}
updateCamera();
renderer.render(scene, camera);
}
frame();
</script>
</body>
</html>
```