Prompt specification
Build or customize the Three.js 3D scene "Lever equilibrium 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: Lever equilibrium challenge
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/lever-equilibrium-challenge-x1412
Scene Description Prompt:
Balance known weights on a low-poly lever until net torque is zero; display the calculation. Three.js from cdnjs, one HTML file.
Working Three.js Starter (lever-equilibrium-challenge-x1412):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Low-Poly Lever Balance</title>
<style>
:root {
--ink: #18312f;
--muted: #647775;
--paper: rgba(250, 252, 247, 0.92);
--line: rgba(24, 49, 47, 0.12);
--accent: #ef8354;
--teal: #238b7d;
--shadow: 0 18px 50px rgba(31, 55, 52, 0.16);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
color: var(--ink);
background: #dce8e4;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#scene,
#scene canvas {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
}
#scene canvas {
display: block;
touch-action: none;
cursor: grab;
}
#scene canvas.dragging {
cursor: grabbing;
}
.topbar {
position: fixed;
z-index: 10;
top: 20px;
left: 22px;
right: 22px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 18px;
pointer-events: none;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
}
.brand-mark {
display: grid;
place-items: center;
width: 42px;
height: 42px;
color: white;
background: var(--ink);
border-radius: 13px;
box-shadow: var(--shadow);
font-size: 24px;
transform: rotate(-4deg);
}
.brand h1 {
margin: 0;
font-size: clamp(18px, 2.4vw, 28px);
letter-spacing: -0.035em;
}
.brand p {
margin: 2px 0 0;
color: var(--muted);
font-size: 12px;
}
.status {
display: flex;
align-items: center;
gap: 9px;
padding: 10px 15px;
border: 1px solid rgba(255, 255, 255, 0.65);
border-radius: 999px;
background: rgba(250, 252, 247, 0.85);
box-shadow: var(--shadow);
backdrop-filter: blur(12px);
font-size: 12px;
font-weight: 800;
letter-spacing: 0.08em;
}
.status-dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 0 4px rgba(239, 131, 84, 0.15);
}
.status.balanced .status-dot {
background: #2a9d72;
box-shadow: 0 0 0 4px rgba(42, 157, 114, 0.15);
}
.panel {
position: fixed;
z-index: 10;
border: 1px solid rgba(255, 255, 255, 0.72);
border-radius: 22px;
background: var(--paper);
box-shadow: var(--shadow);
backdrop-filter: blur(18px);
}
#controls {
top: 92px;
left: 22px;
width: 340px;
max-height: calc(100vh - 114px);
padding: 20px;
overflow: auto;
}
.eyebrow {
margin: 0 0 5px;
color: var(--teal);
font-size: 10px;
font-weight: 850;
letter-spacing: 0.14em;
text-transform: uppercase;
}
h2 {
margin: 0;
font-size: 21px;
letter-spacing: -0.03em;
}
.intro {
margin: 8px 0 17px;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.section-title {
display: flex;
align-items: center;
justify-content: space-between;
margin: 18px 0 10px;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.09em;
text-transform: uppercase;
}
.section-title span:last-child {
color: var(--muted);
font-weight: 650;
letter-spacing: 0;
text-transform: none;
}
.mass-grid {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 7px;
}
.mass-button {
position: relative;
min-width: 0;
padding: 12px 4px 10px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255, 255, 255, 0.62);
cursor: pointer;
transition: 160ms ease;
}
.mass-button::before {
content: "";
display: block;
width: 13px;
height: 13px;
margin: 0 auto 7px;
border-radius: 4px;
background: var(--mass-color);
box-shadow: inset 0 -3px 0 rgba(0, 0, 0, 0.12);
}
.mass-button:hover {
transform: translateY(-2px);
border-color: rgba(24, 49, 47, 0.25);
}
.mass-button.selected {
border-color: var(--ink);
background: white;
box-shadow: 0 5px 14px rgba(24, 49, 47, 0.11);
transform: translateY(-2px);
}
.button-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 11px;
}
.action {
padding: 10px 11px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.65);
cursor: pointer;
font-size: 12px;
font-weight: 750;
transition: 150ms ease;
}
.action:hover {
background: white;
border-color: rgba(24, 49, 47, 0.28);
}
.action.primary {
grid-column: 1 / -1;
border-color: var(--ink);
color: white;
background: var(--ink);
}
.action.primary:hover {
background: #244844;
}
#weightList {
display: grid;
gap: 8px;
max-height: 285px;
overflow: auto;
padding-right: 3px;
}
.weight-row {
padding: 10px;
border: 1px solid var(--line);
border-radius: 13px;
background: rgba(255, 255, 255, 0.58);
transition: 140ms ease;
}
.weight-row.selected {
border-color: rgba(24, 49, 47, 0.42);
background: white;
box-shadow: 0 5px 15px rgba(24, 49, 47, 0.08);
}
.weight-meta {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 9px;
}
.weight-swatch {
width: 11px;
height: 11px;
border-radius: 3px;
background: var(--weight-color);
}
.weight-meta strong {
font-size: 12px;
}
.side-label {
margin-left: auto;
color: var(--muted);
font-size: 10px;
font-weight: 750;
}
.delete-weight {
width: 23px;
height: 23px;
padding: 0;
border: 0;
border-radius: 7px;
color: var(--muted);
background: transparent;
cursor: pointer;
}
.delete-weight:hover {
color: #b84837;
background: rgba(184, 72, 55, 0.1);
}
.position-row {
display: flex;
align-items: center;
gap: 9px;
}
.position-row input {
width: 100%;
accent-color: var(--ink);
cursor: ew-resize;
}
.position-row output {
min-width: 62px;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
text-align: right;
}
.small-note {
margin: 13px 0 0;
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
#calc {
right: 22px;
bottom: 22px;
width: min(455px, calc(100vw - 44px));
padding: 20px;
}
.calc-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.formula {
padding: 6px 9px;
border-radius: 9px;
color: var(--teal);
background: rgba(35, 139, 125, 0.09);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
font-weight: 750;
}
.torque-columns {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
margin-top: 15px;
}
.torque-side {
min-width: 0;
padding: 12px;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255, 255, 255, 0.55);
}
.torque-side h3 {
display: flex;
justify-content: space-between;
margin: 0 0 9px;
font-size: 11px;
letter-spacing: 0.06em;
text-transform: uppercase;
}
.torque-side h3 span:last-child {
color: var(--muted);
font-size: 10px;
letter-spacing: 0;
text-transform: none;
}
.equation {
margin: 6px 0;
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
line-height: 1.5;
}
.equation b {
color: var(--ink);
font-weight: 750;
}
.empty-equation {
color: #96a4a1;
font-size: 10px;
font-style: italic;
}
.net-row {
display: flex;
align-items: flex-end;
justify-content: space-between;
gap: 15px;
margin-top: 13px;
padding-top: 13px;
border-top: 1px solid var(--line);
}
.net-label {
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.08em;
text-transform: uppercase;
}
#netValue {
margin-top: 3px;
font-size: 26px;
font-weight: 850;
letter-spacing: -0.045em;
}
#netValue.balanced {
color: #218764;
}
.angle {
color: var(--muted);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 10px;
text-align: right;
}
.balance-track {
position: relative;
height: 7px;
margin-top: 13px;
border-radius: 999px;
background: linear-gradient(
90deg,
rgba(239, 131, 84, 0.32),
rgba(42, 157, 114, 0.25),
rgba(239, 131, 84, 0.32)
);
}
.balance-track::after {
content: "";
position: absolute;
top: -3px;
bottom: -3px;
left: 50%;
width: 1px;
background: rgba(24, 49, 47, 0.55);
}
#balanceDot {
position: absolute;
top: 50%;
left: 50%;
width: 13px;
height: 13px;
border: 2px solid white;
border-radius: 50%;
background: var(--ink);
box-shadow: 0 2px 8px rgba(24, 49, 47, 0.28);
transform: translate(-50%, -50%);
transition: left 220ms ease;
}
.controls-hint {
position: fixed;
z-index: 5;
left: 50%;
bottom: 22px;
padding: 9px 13px;
border: 1px solid rgba(255, 255, 255, 0.6);
border-radius: 999px;
color: rgba(24, 49, 47, 0.72);
background: rgba(250, 252, 247, 0.72);
backdrop-filter: blur(10px);
font-size: 10px;
font-weight: 700;
transform: translateX(-50%);
pointer-events: none;
white-space: nowrap;
}
#hint {
position: fixed;
z-index: 30;
top: 78px;
left: 50%;
max-width: min(470px, calc(100vw - 30px));
padding: 11px 15px;
border-radius: 12px;
color: white;
background: var(--ink);
box-shadow: var(--shadow);
font-size: 12px;
line-height: 1.45;
opacity: 0;
transform: translate(-50%, -8px);
transition: 180ms ease;
pointer-events: none;
}
#hint.visible {
opacity: 1;
transform: translate(-50%, 0);
}
#loading {
position: fixed;
z-index: 100;
inset: 0;
display: grid;
place-items: center;
color: var(--ink);
background: #dce8e4;
font-size: 13px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
@media (max-width: 850px) {
.topbar {
top: 12px;
left: 12px;
right: 12px;
}
.brand p {
display: none;
}
#controls {
top: 66px;
left: 10px;
width: min(330px, calc(100vw - 20px));
max-height: 39vh;
padding: 15px;
}
#calc {
right: 10px;
bottom: 10px;
width: calc(100vw - 20px);
max-height: 43vh;
padding: 15px;
overflow: auto;
}
.controls-hint {
display: none;
}
.formula {
display: none;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<header class="topbar">
<div class="brand">
<div class="brand-mark">⚖</div>
<div>
<h1>Lever Lab</h1>
<p>Balance known masses by balancing the net torque.</p>
</div>
</div>
<div id="status" class="status" aria-live="polite">
<span class="status-dot"></span>
<span id="statusText">LEFT HEAVY</span>
</div>
</header>
<aside id="controls" class="panel">
<p class="eyebrow">Weight rack</p>
<h2>Choose a known mass</h2>
<p class="intro">
Select a mass, then click the lever to place it. Drag blocks along the beam
or use the position sliders.
</p>
<div class="mass-grid" id="massGrid">
<button class="mass-button" data-mass="1" style="--mass-color:#4f7df3">1 kg</button>
<button class="mass-button selected" data-mass="2" style="--mass-color:#ef8354">2 kg</button>
<button class="mass-button" data-mass="3" style="--mass-color:#2a9d8f">3 kg</button>
<button class="mass-button" data-mass="4" style="--mass-color:#e9b949">4 kg</button>
<button class="mass-button" data-mass="5" style="--mass-color:#9b5de5">5 kg</button>
</div>
<div class="button-row">
<button id="placeButton" class="action primary">Place 2 kg on the right</button>
<button id="challengeButton" class="action">Reset challenge</button>
<button id="clearButton" class="action">Clear lever</button>
</div>
<div class="section-title">
<span>Weights on lever</span>
<span id="weightCount">0 blocks</span>
</div>
<div id="weightList"></div>
<div class="button-row">
<button id="hintButton" class="action">Show hint</button>
<button id="resetViewButton" class="action">Reset camera</button>
</div>
<p class="small-note">
Positions are measured from the pivot. Negative positions are on the left;
positive positions are on the right.
</p>
</aside>
<section id="calc" class="panel">
<div class="calc-heading">
<div>
<p class="eyebrow">Live calculation</p>
<h2>Net torque</h2>
</div>
<div class="formula">τ = m · g · r</div>
</div>
<div class="torque-columns">
<div class="torque-side">
<h3><span>Left side</span><span id="leftTotal">0.00 N·m</span></h3>
<div id="leftEquations"></div>
</div>
<div class="torque-side">
<h3><span>Right side</span><span id="rightTotal">0.00 N·m</span></h3>
<div id="rightEquations"></div>
</div>
</div>
<div class="net-row">
<div>
<div class="net-label">Net torque · right − left</div>
<div id="netValue">0.00 N·m</div>
</div>
<div class="angle">
gravitational acceleration<br>
g = 9.81 m/s²<br>
beam angle = <span id="angleValue">0.0°</span>
</div>
</div>
<div class="balance-track">
<div id="balanceDot"></div>
</div>
</section>
<div class="controls-hint">
Drag a block · Click beam to place · Drag background to orbit · Scroll to zoom
</div>
<div id="hint" role="status"></div>
<div id="loading">Loading the lever…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const G = 9.81;
const BEAM_LENGTH = 9;
const BEAM_HALF = BEAM_LENGTH / 2;
const BEAM_HEIGHT = 0.32;
const SNAP = 0.05;
const MAX_WEIGHTS = 10;
const massColors = {
1: "#4f7df3",
2: "#ef8354",
3: "#2a9d8f",
4: "#e9b949",
5: "#9b5de5"
};
const sceneHost = document.getElementById("scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color("#dce8e4");
scene.fog = new THREE.Fog("#dce8e4", 18, 34);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
sceneHost.appendChild(renderer.domElement);
const camera = new THREE.PerspectiveCamera(
38,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraTarget = new THREE.Vector3(0, 1.55, 0);
const cameraState = {
radius: 12.8,
theta: 0.66,
phi: 1.02
};
function updateCamera() {
const spherical = new THREE.Spherical(
cameraState.radius,
cameraState.phi,
cameraState.theta
);
camera.position.setFromSpherical(spherical).add(cameraTarget);
camera.lookAt(cameraTarget);
}
function resetCamera() {
cameraState.radius = 12.8;
cameraState.theta = 0.66;
cameraState.phi = 1.02;
updateCamera();
}
updateCamera();
const hemisphere = new THREE.HemisphereLight("#f7fff9", "#58706a", 2.15);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight("#fff8df", 3.3);
sun.position.set(-5, 11, 8);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -9;
sun.shadow.camera.right = 9;
sun.shadow.camera.top = 8;
sun.shadow.camera.bottom = -5;
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 30;
sun.shadow.bias = -0.0008;
scene.add(sun);
const fill = new THREE.DirectionalLight("#8edbd0", 1.1);
fill.position.set(8, 5, -6);
scene.add(fill);
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(60, 60),
new THREE.MeshStandardMaterial({
color: "#cfddd8",
roughness: 0.96,
metalness: 0
})
);
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(34, 34, "#8ca9a1", "#a9bdb7");
grid.position.y = 0.012;
grid.material.transparent = true;
grid.material.opacity = 0.32;
scene.add(grid);
const base = new THREE.Mesh(
new THREE.CylinderGeometry(1.05, 1.25, 0.25, 8),
new THREE.MeshStandardMaterial({
color: "#315a53",
flatShading: true,
roughness: 0.82
})
);
base.position.y = 0.125;
base.castShadow = true;
base.receiveShadow = true;
scene.add(base);
const fulcrum = new THREE.Mesh(
new THREE.ConeGeometry(0.67, 2.2, 3, 1, false),
new THREE.MeshStandardMaterial({
color: "#e7b84b",
flatShading: true,
roughness: 0.72
})
);
fulcrum.position.y = 1.22;
fulcrum.rotation.y = Math.PI / 6;
fulcrum.castShadow = true;
fulcrum.receiveShadow = true;
scene.add(fulcrum);
const pivot = new THREE.Mesh(
new THREE.CylinderGeometry(0.23, 0.23, 1.05, 12),
new THREE.MeshStandardMaterial({
color: "#244743",
flatShading: true,
roughness: 0.48,
metalness: 0.18
})
);
pivot.rotation.x = Math.PI / 2;
pivot.position.set(0, 2.35, 0);
pivot.castShadow = true;
scene.add(pivot);
const beamGroup = new THREE.Group();
beamGroup.position.y = 2.35;
scene.add(beamGroup);
const beamBody = new THREE.Mesh(
new THREE.BoxGeometry(BEAM_LENGTH, BEAM_HEIGHT, 0.62),
new THREE.MeshStandardMaterial({
color: "#254f49",
flatShading: true,
roughness: 0.67,
metalness: 0.05
})
);
beamBody.castShadow = true;
beamBody.receiveShadow = true;
beamGroup.add(beamBody);
const beamEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(beamBody.geometry),
new THREE.LineBasicMaterial({
color: "#173a36",
transparent: true,
opacity: 0.7
})
);
beamGroup.add(beamEdges);
const tickMaterial = new THREE.MeshBasicMaterial({ color: "#b9d3ca" });
for (let x = -4; x <= 4; x += 0.5) {
const major = Math.abs(x % 1) < 0.01;
const tick = new THREE.Mesh(
new THREE.BoxGeometry(major ? 0.045 : 0.025, major ? 0.12 : 0.075, 0.018),
tickMaterial
);
tick.position.set(x, BEAM_HEIGHT / 2 + 0.003, 0.319);
beamGroup.add(tick);
}
const pivotMarker = new THREE.Mesh(
new THREE.BoxGeometry(0.08, 0.22, 0.64),
new THREE.MeshStandardMaterial({
color: "#ef8354",
flatShading: true
})
);
pivotMarker.position.y = 0.01;
beamGroup.add(pivotMarker);
const weights = [];
const pickMeshes = [];
let nextWeightId = 1;
let selectedWeightId = null;
let selectedMass = 2;
let targetBeamAngle = 0;
function makeLabelTexture(text, color) {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 128;
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#fffdf7";
ctx.beginPath();
const x = 14;
const y = 18;
const w = 228;
const h = 88;
const r = 20;
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
ctx.fill();
ctx.fillStyle = color;
ctx.fillRect(20, 30, 18, 68);
ctx.fillStyle = "#18312f";
ctx.font = "800 54px system-ui, sans-serif";
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(text, 142, 63);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(4, renderer.capabilities.getMaxAnisotropy());
return texture;
}
function addWeight(mass, x) {
if (weights.length >= MAX_WEIGHTS) {
showHint("The lever can hold up to 10 weight blocks.");
return null;
}
const id = nextWeightId++;
const color = massColors[mass] || massColors[2];
const width = 0.48 + mass * 0.035;
const height = 0.47 + mass * 0.045;
const depth = 0.54;
const group = new THREE.Group();
group.position.set(
THREE.MathUtils.clamp(x, -4, 4),
BEAM_HEIGHT / 2 + height / 2,
0
);
const bodyMaterial = new THREE.MeshStandardMaterial({
color,
flatShading: true,
roughness: 0.6,
metalness: 0.04,
emissive: color,
emissiveIntensity: 0
});
const body = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
bodyMaterial
);
body.castShadow = true;
body.receiveShadow = true;
body.userData.weightId = id;
group.add(body);
const edge = new THREE.LineSegments(
new THREE.EdgesGeometry(body.geometry),
new THREE.LineBasicMaterial({
color: "#173a36",
transparent: true,
opacity: 0.58
})
);
group.add(edge);
const handle = new THREE.Mesh(
new THREE.BoxGeometry(width * 0.38, 0.075, 0.12),
new THREE.MeshStandardMaterial({
color: "#173a36",
flatShading: true,
roughness: 0.8
})
);
handle.position.y = height / 2 + 0.035;
handle.castShadow = true;
group.add(handle);
const label = new THREE.Mesh(
new THREE.PlaneGeometry(width * 0.9, height * 0.48),
new THREE.MeshBasicMaterial({
map: makeLabelTexture(`${mass} kg`, color),
transparent: true,
toneMapped: false
})
);
label.position.set(0, -0.01, depth / 2 + 0.008);
group.add(label);
beamGroup.add(group);
const weight = {
id,
mass,
x,
group,
body,
bodyMaterial,
edge
};
weights.push(weight);
pickMeshes.push(body);
return weight;
}
function removeWeight(weight) {
beamGroup.remove(weight.group);
weight.bodyMaterial.dispose();
weight.edge.material.dispose();
const weightIndex = weights.indexOf(weight);
if (weightIndex !== -1) weights.splice(weightIndex, 1);
const pickIndex = pickMeshes.indexOf(weight.body);
if (pickIndex !== -1) pickMeshes.splice(pickIndex, 1);
if (selectedWeightId === weight.id) {
selectedWeightId = weights.length ? weights[weights.length - 1].id : null;
}
}
function clearWeights() {
[...weights].forEach(removeWeight);
selectedWeightId = null;
}
function selectWeight(id) {
selectedWeightId = id;
updateSelection();
}
function updateSelection() {
for (const weight of weights) {
const selected = weight.id === selectedWeightId;
weight.bodyMaterial.emissiveIntensity = selected ? 0.13 : 0;
weight.edge.material.color.set(selected ? "#fffdf7" : "#173a36");
weight.edge.material.opacity = selected ? 0.95 : 0.58;
}
document.querySelectorAll(".weight-row").forEach((row) => {
row.classList.toggle(
"selected",
Number(row.dataset.id) === selectedWeightId
);
});
}
function setWeightPosition(weight, x) {
weight.x = Math.round(
THREE.MathUtils.clamp(x, -4, 4) / SNAP
) * SNAP;
weight.x = THREE.MathUtils.clamp(weight.x, -4, 4);
weight.group.position.x = weight.x;
}
function renderWeightList() {
const list = document.getElementById("weightList");
list.innerHTML = weights.map((weight) => {
const side =
weight.x < -0.001 ? "Left" :
weight.x > 0.001 ? "Right" : "Pivot";
return `
<div class="weight-row ${
weight.id === selectedWeightId ? "selected" : ""
}" data-id="${weight.id}">
<div class="weight-meta">
<span class="weight-swatch" style="--weight-color:${
massColors[weight.mass]
}"></span>
<strong>${weight.mass} kg</strong>
<span class="side-label">${side}</span>
<button class="delete-weight" data-delete="${weight.id}"
aria-label="Remove ${weight.mass} kilogram weight">×</button>
</div>
<div class="position-row">
<input
type="range"
min="-4"
max="4"
step="${SNAP}"
value="${weight.x}"
data-position="${weight.id}"
aria-label="Position of ${weight.mass} kilogram weight"
>
<output data-output="${weight.id}">
${formatPosition(weight.x)}
</output>
</div>
</div>
`;
}).join("");
document.getElementById("weightCount").textContent =
`${weights.length} block${weights.length === 1 ? "" : "s"}`;
updateSelection();
}
function formatPosition(x) {
if (Math.abs(x) < 0.001) return "0.00 m";
return `${x > 0 ? "+" : ""}${x.toFixed(2)} m`;
}
function syncWeightControls() {
for (const weight of weights) {
const range = document.querySelector(
`[data-position="${weight.id}"]`
);
const output = document.querySelector(
`[data-output="${weight.id}"]`
);
if (range) range.value = weight.x;
if (output) output.textContent = formatPosition(weight.x);
const row = document.querySelector(`.weight-row[data-id="${weight.id}"]`);
if (row) {
const side = row.querySelector(".side-label");
side.textContent =
weight.x < -0.001 ? "Left" :
weight.x > 0.001 ? "Right" : "Pivot";
}
}
}
function torqueFor(weight) {
return weight.mass * G * Math.abs(weight.x);
}
function updateCalculation() {
const leftWeights = weights.filter((weight) => weight.x < -0.001);
const rightWeights = weights.filter((weight) => weight.x >= 0.001);
const leftTorque = leftWeights.reduce(
(sum, weight) => sum + torqueFor(weight),
0
);
const rightTorque = rightWeights.reduce(
(sum, weight) => sum + torqueFor(weight),
0
);
const netTorque = rightTorque - leftTorque;
const balanced = weights.length > 0 && Math.abs(netTorque) < 0.001;
function equations(items) {
if (!items.length) {
return `<div class="empty-equation">No weights on this side</div>`;
}
return items.map((weight) => {
const value = torqueFor(weight);
return `
<div class="equation">
${weight.mass}.00 × 9.81 × ${Math.abs(weight.x).toFixed(2)}
= <b>${value.toFixed(2)} N·m</b>
</div>
`;
}).join("");
}
document.getElementById("leftEquations").innerHTML =
equations(leftWeights);
document.getElementById("rightEquations").innerHTML =
equations(rightWeights);
document.getElementById("leftTotal").textContent =
`${leftTorque.toFixed(2)} N·m`;
document.getElementById("rightTotal").textContent =
`${rightTorque.toFixed(2)} N·m`;
const netValue = document.getElementById("netValue");
netValue.textContent =
`${netTorque >= 0 && Math.abs(netTorque) > 0.001 ? "+" : ""}${netTorque.toFixed(2)} N·m`;
netValue.classList.toggle("balanced", balanced);
const status = document.getElementById("status");
const statusText = document.getElementById("statusText");
if (!weights.length) {
statusText.textContent = "EMPTY LEVER";
status.classList.remove("balanced");
} else if (balanced) {
statusText.textContent = "BALANCED";
status.classList.add("balanced");
} else {
statusText.textContent = netTorque > 0 ? "RIGHT HEAVY" : "LEFT HEAVY";
status.classList.remove("balanced");
}
const total = Math.max(leftTorque + rightTorque, 0.001);
const normalized = THREE.MathUtils.clamp(netTorque / total, -1, 1);
document.getElementById("balanceDot").style.left =
`${50 + normalized * 45}%`;
targetBeamAngle = balanced
? 0
: -THREE.MathUtils.clamp(
(netTorque / total) * 0.2,
-0.16,
0.16
);
syncWeightControls();
}
const massButtons = [...document.querySelectorAll(".mass-button")];
function selectMass(mass) {
selectedMass = mass;
massButtons.forEach((button) => {
button.classList.toggle(
"selected",
Number(button.dataset.mass) === selectedMass
);
});
document.getElementById("placeButton").textContent =
`Place ${selectedMass} kg on the right`;
}
massButtons.forEach((button) => {
button.addEventListener("click", () => {
selectMass(Number(button.dataset.mass));
});
});
document.getElementById("placeButton").addEventListener("click", () => {
const weight = addWeight(selectedMass, 0.5);
if (!weight) return;
selectedWeightId = weight.id;
renderWeightList();
updateCalculation();
});
document.getElementById("weightList").addEventListener("input", (event) => {
const id = Number(event.target.dataset.position);
const weight = weights.find((item) => item.id === id);
if (!weight) return;
setWeightPosition(weight, Number(event.target.value));
updateCalculation();
});
document.getElementById("weightList").addEventListener("click", (event) => {
const deleteButton = event.target.closest("[data-delete]");
if (deleteButton) {
const id = Number(deleteButton.dataset.delete);
const weight = weights.find((item) => item.id === id);
if (weight) removeWeight(weight);
renderWeightList();
updateCalculation();
return;
}
const row = event.target.closest(".weight-row");
if (row) selectWeight(Number(row.dataset.id));
});
document.getElementById("clearButton").addEventListener("click", () => {
clearWeights();
renderWeightList();
updateCalculation();
});
function loadChallenge() {
clearWeights();
addWeight(2, -0.8);
addWeight(4, 0.2);
selectedWeightId = weights[1].id;
renderWeightList();
updateCalculation();
}
document.getElementById("challengeButton").addEventListener("click", () => {
loadChallenge();
showHint("Challenge reset. Balance the 2 kg and 4 kg weights.");
});
document.getElementById("resetViewButton").addEventListener("click", () => {
resetCamera();
});
let hintTimer;
function showHint(message) {
const hint = document.getElementById("hint");
hint.textContent = message;
hint.classList.add("visible");
clearTimeout(hintTimer);
hintTimer = setTimeout(() => hint.classList.remove("visible"), 6000);
}
document.getElementById("hintButton").addEventListener("click", () => {
const left = weights
.filter((weight) => weight.x < 0)
.reduce((sum, weight) => sum + torqueFor(weight), 0);
const right = weights
.filter((weight) => weight.x > 0)
.reduce((sum, weight) => sum + torqueFor(weight), 0);
const difference = right - left;
if (Math.abs(difference) < 0.001) {
showHint("Balanced! Both sides have equal turning torque.");
} else if (
weights.length === 2 &&
weights.some((weight) => weight.mass === 2 && weight.x === -0.8) &&
weights.some((weight) => weight.mass === 4 && weight.x === 0.2)
) {
showHint("Try moving the 4 kg weight to +0.40 m.");
} else if (difference > 0) {
showHint(
`The right side is heavy by ${difference.toFixed(2)} N·m. Move a right weight outward or a left weight inward.`
);
} else {
showHint(
`The left side is heavy by ${Math.abs(difference).toFixed(2)} N·m. Move a left weight outward or a right weight inward.`
);
}
});
// Raycasting and direct camera controls.
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane();
const canvas = renderer.domElement;
const interaction = {
mode: null,
pointerId: null,
weight: null,
downX: 0,
downY: 0,
lastX: 0,
lastY: 0,
moved: false,
beamX: null
};
function setRayFromEvent(event) {
const rect = canvas.getBoundingClientRect();
pointer.x =
((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y =
-((event.clientY - rect.top) / rect.height) * 2 + 1;
raycaster.setFromCamera(pointer, camera);
}
function localBeamHit() {
scene.updateMatrixWorld(true);
const hits = raycaster.intersectObject(beamBody, false);
if (!hits.length) return null;
const local = beamGroup.worldToLocal(hits[0].point.clone());
return local.x;
}
function weightAtPointer() {
const hits = raycaster.intersectObjects(pickMeshes, false);
if (!hits.length) return null;
const id = hits[0].object.userData.weightId;
return weights.find((weight) => weight.id === id) || null;
}
function beginWeightDrag(weight) {
const normal = new THREE.Vector3(0, 1, 0);
const worldQuaternion = beamGroup.getWorldQuaternion(
new THREE.Quaternion()
);
normal.applyQuaternion(worldQuaternion);
const planePoint = beamGroup.localToWorld(
new THREE.Vector3(0, weight.group.position.y, 0)
);
dragPlane.setFromNormalAndCoplanarPoint(normal, planePoint);
}
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0 && event.button !== 2) return;
setRayFromEvent(event);
scene.updateMatrixWorld(true);
interaction.pointerId = event.pointerId;
interaction.downX = event.clientX;
interaction.downY = event.clientY;
interaction.lastX = event.clientX;
interaction.lastY = event.clientY;
interaction.moved = false;
interaction.beamX = localBeamHit();
const weight = weightAtPointer();
if (weight) {
interaction.mode = "weight";
interaction.weight = weight;
selectWeight(weight.id);
beginWeightDrag(weight);
} else {
interaction.mode = "camera";
}
canvas.setPointerCapture(event.pointerId);
canvas.classList.add("dragging");
event.preventDefault();
});
canvas.addEventListener("pointermove", (event) => {
if (!interaction.pointerId) return;
const dx = event.clientX - interaction.lastX;
const dy = event.clientY - interaction.lastY;
if (
Math.hypot(
event.clientX - interaction.downX,
event.clientY - interaction.downY
) > 4
) {
interaction.moved = true;
}
if (interaction.mode === "camera") {
cameraState.theta -= dx * 0.006;
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi - dy * 0.006,
0.38,
1.42
);
updateCamera();
} else if (interaction.mode === "weight") {
setRayFromEvent(event);
const intersection = new THREE.Vector3();
if (raycaster.ray.intersectPlane(dragPlane, intersection)) {
const local = beamGroup.worldToLocal(intersection);
setWeightPosition(interaction.weight, local.x);
updateCalculation();
}
}
interaction.lastX = event.clientX;
interaction.lastY = event.clientY;
});
function endPointer(event) {
if (interaction.pointerId !== event.pointerId) return;
if (
interaction.mode === "camera" &&
!interaction.moved &&
interaction.beamX !== null &&
weights.length < MAX_WEIGHTS
) {
const snappedX =
Math.round(interaction.beamX / SNAP) * SNAP;
const weight = addWeight(selectedMass, snappedX);
if (weight) {
selectedWeightId = weight.id;
renderWeightList();
updateCalculation();
}
}
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
interaction.mode = null;
interaction.pointerId = null;
interaction.weight = null;
interaction.beamX = null;
canvas.classList.remove("dragging");
}
canvas.addEventListener("pointerup", endPointer);
canvas.addEventListener("pointercancel", endPointer);
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius * Math.exp(event.deltaY * 0.001),
7,
20
);
updateCamera();
},
{ passive: false }
);
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
});
loadChallenge();
document.getElementById("loading").remove();
function animate() {
requestAnimationFrame(animate);
beamGroup.rotation.z +=
(targetBeamAngle - beamGroup.rotation.z) * 0.075;
document.getElementById("angleValue").textContent =
`${THREE.MathUtils.radToDeg(beamGroup.rotation.z).toFixed(1)}°`;
renderer.render(scene, camera);
}
animate();
</script>
</body>
</html>
```