Prompt specification
Build or customize the Three.js 3D scene "Traveling merchant balance puzzle" 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: Traveling merchant balance puzzle
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/traveling-merchant-balance-puzzle-x0324
Scene Description Prompt:
Make a standalone HTML scene with Three.js from cdnjs that depicts a traveling merchant's low-poly balance puzzle. On a folding market board, place a beam with a central pivot, sliding weight hooks, and a small tray of labeled weights. The player can attach weights at marked distances on either side. Display each side's mass-times-distance total beside the beam, and tilt the beam according to the difference under an idealized static rule. Include a solvable example with unequal masses and unequal arm lengths. Use worn wood, brass-colored hooks, cloth sacks, and a compact stall backdrop. Provide a reset that returns every weight to its original tray slot.
Working Three.js Starter (traveling-merchant-balance-puzzle-x0324):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>The Traveling Merchant's Balance</title>
<style>
:root {
--parchment: #ead8ae;
--ink: #2c2118;
--brass: #c89a45;
--left: #d98252;
--right: #64a6a1;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #211b15;
font-family: Georgia, "Times New Roman", serif;
color: var(--ink);
}
#scene {
position: fixed;
inset: 0;
}
canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
.panel {
position: fixed;
z-index: 5;
pointer-events: none;
background:
linear-gradient(135deg, rgba(255,255,255,.16), transparent 45%),
rgba(234,216,174,.94);
border: 1px solid rgba(66,43,23,.55);
box-shadow:
0 10px 30px rgba(0,0,0,.28),
inset 0 0 0 3px rgba(255,255,255,.12);
border-radius: 4px;
}
#title {
top: 18px;
left: 18px;
padding: 15px 19px 13px;
max-width: 360px;
}
#title h1 {
margin: 0;
font-size: clamp(20px, 2.3vw, 31px);
line-height: .95;
letter-spacing: .025em;
font-variant: small-caps;
}
#title p {
margin: 8px 0 0;
font: 13px/1.35 system-ui, sans-serif;
color: #5b4735;
}
#challenge {
top: 18px;
right: 18px;
width: 300px;
padding: 14px 16px;
}
#challenge h2 {
margin: 0 0 7px;
font-size: 18px;
font-variant: small-caps;
}
#challenge p {
margin: 0;
font: 13px/1.45 system-ui, sans-serif;
color: #514032;
}
.equation {
margin-top: 10px !important;
padding: 8px 10px;
background: rgba(87,61,35,.10);
border-left: 3px solid var(--brass);
font-family: ui-monospace, SFMono-Regular, Menlo, monospace !important;
font-weight: 700;
}
#example-note {
display: block;
margin-top: 9px;
color: #6a5038;
font-size: 12px;
}
#status {
left: 18px;
bottom: 18px;
max-width: min(540px, calc(100vw - 36px));
padding: 11px 15px;
font: 14px/1.35 system-ui, sans-serif;
}
#status strong {
color: #7b3f22;
}
#actions {
position: fixed;
right: 18px;
bottom: 18px;
z-index: 8;
display: flex;
gap: 9px;
flex-wrap: wrap;
justify-content: flex-end;
}
button {
appearance: none;
border: 1px solid #513720;
border-radius: 3px;
padding: 10px 14px;
background: linear-gradient(#ead8ae, #cfb582);
color: #342419;
font: 700 13px system-ui, sans-serif;
cursor: pointer;
box-shadow: 0 4px 0 #765333, 0 7px 16px rgba(0,0,0,.25);
transition: transform .12s, box-shadow .12s, filter .12s;
}
button:hover {
filter: brightness(1.06);
transform: translateY(-1px);
}
button:active {
transform: translateY(3px);
box-shadow: 0 1px 0 #765333;
}
#reset {
background: linear-gradient(#b76c43, #8f4d31);
color: #fff4dc;
border-color: #63311e;
box-shadow: 0 4px 0 #5a2c1c, 0 7px 16px rgba(0,0,0,.25);
}
.torque {
position: fixed;
z-index: 6;
top: 0;
left: 0;
min-width: 145px;
padding: 8px 12px;
transform: translate(-50%, -50%);
pointer-events: none;
border-radius: 5px;
border: 1px solid rgba(255,255,255,.24);
box-shadow: 0 6px 18px rgba(0,0,0,.28);
color: white;
text-align: center;
font: 11px/1.1 system-ui, sans-serif;
letter-spacing: .12em;
text-transform: uppercase;
}
.torque strong {
display: block;
margin-top: 3px;
font: 700 19px/1.1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0;
text-transform: none;
}
#torque-left {
background: linear-gradient(135deg, rgba(161,70,35,.95), rgba(217,130,82,.95));
border-left: 4px solid #ffc08b;
}
#torque-right {
background: linear-gradient(135deg, rgba(37,96,94,.95), rgba(100,166,161,.95));
border-left: 4px solid #a7e3dd;
}
#tilt-readout {
margin-top: 9px;
color: #66503a;
font: 12px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
}
@media (max-width: 720px) {
#challenge {
top: auto;
right: 12px;
bottom: 76px;
width: min(290px, calc(100vw - 24px));
padding: 10px 12px;
}
#challenge p, #example-note {
font-size: 11px !important;
}
#title {
top: 10px;
left: 10px;
max-width: calc(100vw - 20px);
padding: 11px 13px;
}
#title p {
display: none;
}
#status {
left: 10px;
bottom: 10px;
max-width: calc(100vw - 20px);
font-size: 12px;
}
#actions {
right: 10px;
bottom: 10px;
}
button {
padding: 9px 10px;
font-size: 11px;
}
.torque {
min-width: 112px;
padding: 6px 8px;
}
.torque strong {
font-size: 15px;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<section id="title" class="panel">
<h1>The Traveling Merchant's Balance</h1>
<p>Drag a labeled weight onto a marked arm. Select a weight, then click a position, if you prefer.</p>
</section>
<section id="challenge" class="panel">
<h2>Fair Exchange</h2>
<p>Match the two arm totals. A heavier weight can balance a lighter one when it sits farther from the pivot.</p>
<p class="equation">torque = mass × arm length</p>
<span id="example-note">Example: 3 kg at 4 m balances 4 kg at 3 m.</span>
<div id="tilt-readout">Beam tilt: 0.0°</div>
</section>
<div id="torque-left" class="torque">
Left arm<strong>0 kg·m</strong>
</div>
<div id="torque-right" class="torque">
Right arm<strong>0 kg·m</strong>
</div>
<div id="status" class="panel">
<strong>Your scale is empty.</strong> Choose a weight from the tray to begin.
</div>
<div id="actions">
<button id="example" type="button">Load example</button>
<button id="reset" type="button">Reset all weights</button>
</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, and camera
// -------------------------------------------------------------------------
const sceneHost = document.getElementById("scene");
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.setAttribute("aria-label", "Interactive traveling merchant balance puzzle");
sceneHost.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x2b241c);
scene.fog = new THREE.Fog(0x2b241c, 15, 30);
const camera = new THREE.PerspectiveCamera(
43,
window.innerWidth / window.innerHeight,
0.1,
60
);
const cameraTarget = new THREE.Vector3(0, 2.25, 0.35);
let cameraYaw = 0.49;
let cameraPitch = 0.37;
let cameraRadius = 12.1;
function updateCamera() {
const horizontal = Math.cos(cameraPitch) * cameraRadius;
camera.position.set(
cameraTarget.x + Math.sin(cameraYaw) * horizontal,
cameraTarget.y + Math.sin(cameraPitch) * cameraRadius,
cameraTarget.z + Math.cos(cameraYaw) * horizontal
);
camera.lookAt(cameraTarget);
}
updateCamera();
const hemisphere = new THREE.HemisphereLight(0xffedc9, 0x49392a, 1.65);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffe2ae, 2.65);
sun.position.set(5.5, 9, 7);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -9;
sun.shadow.camera.right = 9;
sun.shadow.camera.top = 9;
sun.shadow.camera.bottom = -7;
sun.shadow.camera.near = 1;
sun.shadow.camera.far = 25;
sun.shadow.bias = -0.0005;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x94b9ba, 0.75);
rim.position.set(-7, 5, -5);
scene.add(rim);
// -------------------------------------------------------------------------
// Procedural textures: no external assets
// -------------------------------------------------------------------------
function seededRandom(seed) {
let value = seed >>> 0;
return () => {
value = 1664525 * value + 1013904223 >>> 0;
return value / 4294967296;
};
}
function makeWoodTexture() {
const canvas = document.createElement("canvas");
canvas.width = 512;
canvas.height = 512;
const ctx = canvas.getContext("2d");
const random = seededRandom(5172);
ctx.fillStyle = "#95643d";
ctx.fillRect(0, 0, 512, 512);
for (let i = 0; i < 430; i++) {
const y = random() * 512;
const alpha = 0.025 + random() * 0.12;
ctx.strokeStyle = `rgba(${random() > .45 ? "53,28,13" : "225,174,111"},${alpha})`;
ctx.lineWidth = 0.5 + random() * 2.4;
ctx.beginPath();
ctx.moveTo(-20, y);
for (let x = 0; x <= 540; x += 24) {
ctx.lineTo(x, y + Math.sin(x * .025 + i) * (1 + random() * 3));
}
ctx.stroke();
}
for (let i = 0; i < 9; i++) {
const x = random() * 512;
const y = random() * 512;
const radius = 9 + random() * 24;
for (let ring = 0; ring < 4; ring++) {
ctx.strokeStyle = `rgba(55,28,12,${.12 - ring * .018})`;
ctx.lineWidth = 2;
ctx.beginPath();
ctx.ellipse(x, y, radius + ring * 6, radius * .34 + ring * 2, 0, 0, Math.PI * 2);
ctx.stroke();
}
}
for (let i = 0; i < 150; i++) {
const x = random() * 512;
const y = random() * 512;
ctx.fillStyle = `rgba(33,19,10,${random() * .12})`;
ctx.fillRect(x, y, 1 + random() * 18, 1 + random() * 2);
}
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(1.8, 1.1);
texture.anisotropy = renderer.capabilities.getMaxAnisotropy();
return texture;
}
function makeClothTexture() {
const canvas = document.createElement("canvas");
canvas.width = 256;
canvas.height = 256;
const ctx = canvas.getContext("2d");
const random = seededRandom(881);
ctx.fillStyle = "#b7aa83";
ctx.fillRect(0, 0, 256, 256);
for (let i = 0; i < 256; i += 4) {
ctx.fillStyle = `rgba(255,255,255,${.025 + random() * .04})`;
ctx.fillRect(i, 0, 1, 256);
ctx.fillRect(0, i, 256, 1);
}
for (let i = 0; i < 550; i++) {
ctx.fillStyle = `rgba(48,38,25,${random() * .10})`;
ctx.fillRect(random() * 256, random() * 256, 1 + random() * 4, 1 + random() * 2);
}
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
texture.repeat.set(2, 2);
return texture;
}
function makeTextTexture(text, options = {}) {
const canvas = document.createElement("canvas");
canvas.width = options.width || 512;
canvas.height = options.height || 128;
const ctx = canvas.getContext("2d");
if (options.background) {
ctx.fillStyle = options.background;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = options.border || "rgba(255,255,255,.4)";
ctx.lineWidth = 5;
ctx.strokeRect(4, 4, canvas.width - 8, canvas.height - 8);
}
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = options.color || "#322317";
ctx.font = options.font || "bold 54px Georgia";
ctx.fillText(text, canvas.width / 2, canvas.height / 2);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
return texture;
}
const woodTexture = makeWoodTexture();
const clothTexture = makeClothTexture();
const woodMaterial = new THREE.MeshStandardMaterial({
map: woodTexture,
color: 0xffffff,
roughness: .88,
metalness: .03
});
const darkWoodMaterial = new THREE.MeshStandardMaterial({
map: woodTexture,
color: 0x745038,
roughness: .94,
metalness: .02
});
const brassMaterial = new THREE.MeshStandardMaterial({
color: 0xc4923f,
roughness: .36,
metalness: .68,
flatShading: true
});
const darkBrassMaterial = new THREE.MeshStandardMaterial({
color: 0x765321,
roughness: .48,
metalness: .62,
flatShading: true
});
const ironMaterial = new THREE.MeshStandardMaterial({
color: 0x353637,
roughness: .66,
metalness: .42,
flatShading: true
});
const ropeMaterial = new THREE.MeshStandardMaterial({
color: 0x9d7743,
roughness: 1
});
const clothMaterial = new THREE.MeshStandardMaterial({
map: clothTexture,
color: 0xb6a17a,
roughness: 1,
flatShading: true
});
const redClothMaterial = new THREE.MeshStandardMaterial({
map: clothTexture,
color: 0x8e4938,
roughness: 1,
flatShading: true
});
// -------------------------------------------------------------------------
// Geometry helpers
// -------------------------------------------------------------------------
function box(width, height, depth, material, x = 0, y = 0, z = 0) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function beamBetween(start, end, thickness, material) {
const direction = new THREE.Vector3().subVectors(end, start);
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(thickness, direction.length(), thickness),
material
);
mesh.position.copy(start).add(end).multiplyScalar(.5);
mesh.quaternion.setFromUnitVectors(
new THREE.Vector3(0, 1, 0),
direction.normalize()
);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function textSprite(text, width = .5, height = .22, options = {}) {
const texture = makeTextTexture(text, {
width: options.canvasWidth || 256,
height: options.canvasHeight || 96,
font: options.font || "bold 52px Georgia",
color: options.color || "#f2dfb3",
background: options.background || null,
border: options.border || null
});
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, height, 1);
return sprite;
}
// -------------------------------------------------------------------------
// Ground and compact market stall
// -------------------------------------------------------------------------
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(35, 35),
new THREE.MeshStandardMaterial({ color: 0x4b3d2d, roughness: 1 })
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -.04;
ground.receiveShadow = true;
scene.add(ground);
// Back wall made from individual worn boards.
for (let i = 0; i < 6; i++) {
const plank = box(1.25, 4.2, .22, woodMaterial, (i - 2.5) * 1.27, 2.68, -.76);
scene.add(plank);
}
// Folding side wings.
const leftWing = box(.92, 4.2, .22, darkWoodMaterial, -4.18, 2.68, -.71);
leftWing.rotation.y = -.20;
scene.add(leftWing);
const rightWing = box(.92, 4.2, .22, darkWoodMaterial, 4.18, 2.68, -.71);
rightWing.rotation.y = .20;
scene.add(rightWing);
// Visible brass hinges.
for (const x of [-3.91, 3.91]) {
const hinge = new THREE.Mesh(
new THREE.CylinderGeometry(.085, .085, .65, 10),
brassMaterial
);
hinge.position.set(x, 1.7, -.48);
scene.add(hinge);
const hingeTop = hinge.clone();
hingeTop.position.y = 3.8;
scene.add(hingeTop);
}
// Folding braces behind the board.
scene.add(beamBetween(
new THREE.Vector3(-3.5, .62, -1.15),
new THREE.Vector3(-1.8, 4.25, -.55),
.16,
darkWoodMaterial
));
scene.add(beamBetween(
new THREE.Vector3(3.5, .62, -1.15),
new THREE.Vector3(1.8, 4.25, -.55),
.16,
darkWoodMaterial
));
// Merchant's sign.
const signTexture = makeTextTexture("TRAVELING LEDGER", {
width: 1024,
height: 256,
font: "bold 78px Georgia",
color: "#3c2818",
background: "#dcc38d",
border: "#654321"
});
const signMaterial = new THREE.MeshStandardMaterial({
map: signTexture,
roughness: .86
});
const sign = new THREE.Mesh(new THREE.PlaneGeometry(4.25, 1.06), signMaterial);
sign.position.set(0, 4.27, -.625);
sign.castShadow = true;
scene.add(sign);
// Counter / folding market table.
const counter = box(9.35, .3, 2.15, woodMaterial, 0, .83, 1.03);
scene.add(counter);
scene.add(box(9.45, .18, .16, darkWoodMaterial, 0, .55, 2.08));
for (const x of [-4.1, 4.1]) {
scene.add(box(.22, .85, .22, darkWoodMaterial, x, .28, .2));
scene.add(beamBetween(
new THREE.Vector3(x, .05, 1.65),
new THREE.Vector3(x, .74, .2),
.15,
darkWoodMaterial
));
}
// Weight tray.
const tray = new THREE.Group();
tray.position.set(0, 1.0, 1.66);
scene.add(tray);
const trayBase = box(6.65, .13, .9, darkWoodMaterial, 0, 0, 0);
tray.add(trayBase);
tray.add(box(6.65, .16, .075, woodMaterial, 0, .09, -.43));
tray.add(box(6.65, .16, .075, woodMaterial, 0, .09, .43));
tray.add(box(.075, .16, .9, woodMaterial, -3.33, .09, 0));
tray.add(box(.075, .16, .9, woodMaterial, 3.33, .09, 0));
const trayLabel = textSprite("MERCHANT'S WEIGHTS", 1.85, .29, {
font: "bold 50px Georgia",
color: "#3d2917",
background: "rgba(220,195,141,.95)",
border: "#6c4a2d"
});
trayLabel.position.set(0, .02, .49);
tray.add(trayLabel);
// Canvas awning: alternating low-poly strips.
const awningCream = new THREE.MeshStandardMaterial({
color: 0xd9cbaa,
roughness: 1,
side: THREE.DoubleSide
});
const awningRed = new THREE.MeshStandardMaterial({
color: 0x884536,
roughness: 1,
side: THREE.DoubleSide
});
for (let i = 0; i < 12; i++) {
const strip = new THREE.Mesh(
new THREE.BoxGeometry(.81, .075, 2.25),
i % 2 ? awningCream : awningRed
);
strip.position.set((i - 5.5) * .81, 4.94 - .16 * (i % 2), -.35);
strip.rotation.x = .16;
strip.castShadow = true;
scene.add(strip);
}
// Scalloped awning edge.
for (let i = 0; i < 12; i++) {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.Float32BufferAttribute([
-.38, .13, 0,
.38, .13, 0,
0, -.25, 0
], 3));
geometry.computeVertexNormals();
const scallop = new THREE.Mesh(
geometry,
i % 2 ? awningCream : awningRed
);
scallop.position.set((i - 5.5) * .81, 4.70, .75);
scallop.rotation.y = Math.PI;
scene.add(scallop);
}
// Stall poles.
for (const x of [-4.75, 4.75]) {
const pole = new THREE.Mesh(
new THREE.CylinderGeometry(.10, .13, 4.9, 8),
darkWoodMaterial
);
pole.position.set(x, 2.45, -.95);
pole.castShadow = true;
scene.add(pole);
const frontPole = new THREE.Mesh(
new THREE.CylinderGeometry(.085, .11, 4.72, 8),
darkWoodMaterial
);
frontPole.position.set(x, 2.36, .78);
frontPole.castShadow = true;
scene.add(frontPole);
}
function makeSack(material, scale = 1) {
const group = new THREE.Group();
const profile = [
new THREE.Vector2(.20, 0),
new THREE.Vector2(.47, .08),
new THREE.Vector2(.56, .52),
new THREE.Vector2(.49, .92),
new THREE.Vector2(.27, 1.18),
new THREE.Vector2(.16, 1.37)
];
const geometry = new THREE.LatheGeometry(profile, 9);
const position = geometry.attributes.position;
const random = seededRandom(330);
for (let i = 0; i < position.count; i++) {
const x = position.getX(i);
const y = position.getY(i);
const wobble = Math.sin(y * 8 + x * 4) * .025 + (random() - .5) * .035;
position.setX(i, x + wobble);
position.setZ(i, position.getZ(i) - wobble * .5);
}
geometry.computeVertexNormals();
const body = new THREE.Mesh(geometry, material);
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const tie = new THREE.Mesh(
new THREE.TorusGeometry(.17, .035, 5, 10),
ropeMaterial
);
tie.position.y = 1.26;
tie.rotation.x = Math.PI / 2;
group.add(tie);
const tag = textSprite("TRADE", .55, .18, {
font: "bold 40px Georgia",
color: "#e7d3a8"
});
tag.position.set(0, .70, .49);
group.add(tag);
group.scale.setScalar(scale);
return group;
}
const leftSack = makeSack(clothMaterial, .9);
leftSack.position.set(-4.0, .05, .28);
leftSack.rotation.z = -.09;
scene.add(leftSack);
const rightSack = makeSack(redClothMaterial, .78);
rightSack.position.set(4.05, .05, .05);
rightSack.rotation.z = .10;
scene.add(rightSack);
// Small crate and pottery for stall depth.
const crate = box(.8, .65, .7, darkWoodMaterial, -4.0, .34, 1.02);
scene.add(crate);
for (const y of [.16, .5]) {
scene.add(box(.86, .08, .75, woodMaterial, -4.0, y, 1.02));
}
const potMaterial = new THREE.MeshStandardMaterial({
color: 0x81563b,
roughness: .88,
flatShading: true
});
const pot = new THREE.Mesh(
new THREE.CylinderGeometry(.19, .26, .42, 8),
potMaterial
);
pot.position.set(4.02, 1.22, .62);
pot.castShadow = true;
scene.add(pot);
// -------------------------------------------------------------------------
// Balance beam, pivot, rail, hooks, and marked slots
// -------------------------------------------------------------------------
const pivotY = 3.15;
const pivotZ = .16;
// Fixed triangular support and base.
const support = new THREE.Mesh(
new THREE.ConeGeometry(.64, 1.58, 3),
darkWoodMaterial
);
support.position.set(0, 2.30, -.12);
support.rotation.y = Math.PI / 6;
support.castShadow = true;
scene.add(support);
scene.add(box(1.65, .18, .72, woodMaterial, 0, 1.13, -.02));
const axle = new THREE.Mesh(
new THREE.CylinderGeometry(.14, .14, .88, 12),
brassMaterial
);
axle.position.set(0, pivotY, pivotZ);
axle.rotation.x = Math.PI / 2;
axle.castShadow = true;
scene.add(axle);
const axleCap = new THREE.Mesh(
new THREE.CylinderGeometry(.19, .19, .08, 12),
darkBrassMaterial
);
axleCap.position.set(0, pivotY, pivotZ + .48);
axleCap.rotation.x = Math.PI / 2;
scene.add(axleCap);
// Rotating group. Its origin is exactly at the pivot axle.
const beamPivot = new THREE.Group();
beamPivot.position.set(0, pivotY, pivotZ);
scene.add(beamPivot);
const beam = box(9.0, .25, .48, woodMaterial, 0, 0, 0);
beamPivot.add(beam);
// Brass strengthening strips.
beamPivot.add(box(8.8, .045, .035, brassMaterial, 0, .12, .265));
beamPivot.add(box(8.8, .035, .035, darkBrassMaterial, 0, -.11, .265));
for (const x of [-4.38, 4.38]) {
beamPivot.add(box(.15, .31, .54, darkWoodMaterial, x, 0, 0));
beamPivot.add(box(.17, .07, .56, brassMaterial, x, .15, 0));
}
const hookRail = box(8.55, .075, .075, brassMaterial, 0, -.07, .37);
beamPivot.add(hookRail);
const slots = [];
const dropTargets = [];
const invisibleTargetMaterial = new THREE.MeshBasicMaterial({
transparent: true,
opacity: 0,
depthWrite: false,
colorWrite: false
});
function createSlot(side, distance) {
const x = side === "left" ? -distance : distance;
const markerMaterial = brassMaterial.clone();
const marker = new THREE.Mesh(
new THREE.TorusGeometry(.12, .027, 5, 12, Math.PI * 1.5),
markerMaterial
);
marker.position.set(x, -.075, .405);
marker.rotation.z = side === "left" ? Math.PI * .5 : -Math.PI * .5;
beamPivot.add(marker);
const tick = box(.028, .11, .035, darkBrassMaterial, x, .10, .275);
beamPivot.add(tick);
const number = textSprite(String(distance), .26, .16, {
canvasWidth: 128,
canvasHeight: 96,
font: "bold 65px Georgia",
color: "#f1d9a8"
});
number.position.set(x, .18, .31);
beamPivot.add(number);
const target = new THREE.Mesh(
new THREE.BoxGeometry(.65, 1.20, .72),
invisibleTargetMaterial
);
target.position.set(x, -.46, .52);
target.userData.side = side;
target.userData.distance = distance;
target.userData.marker = marker;
target.userData.occupant = null;
beamPivot.add(target);
const slot = {
side,
distance,
x,
target,
marker,
occupant: null
};
slots.push(slot);
dropTargets.push(target);
return slot;
}
for (const distance of [1, 2, 3, 4]) {
createSlot("left", distance);
createSlot("right", distance);
}
// Fixed semicircular tilt gauge behind the axle.
const gauge = new THREE.Mesh(
new THREE.TorusGeometry(.75, .032, 6, 24, Math.PI),
brassMaterial
);
gauge.position.set(0, pivotY, -.13);
gauge.rotation.z = 0;
scene.add(gauge);
for (let i = 0; i <= 10; i++) {
const angle = Math.PI * i / 10;
const tick = box(.025, .11, .035, darkBrassMaterial, 0, 0, 0);
tick.position.set(
Math.cos(angle) * .68,
pivotY + Math.sin(angle) * .68,
-.09
);
tick.rotation.z = angle - Math.PI / 2;
scene.add(tick);
}
// -------------------------------------------------------------------------
// Tray weights
// -------------------------------------------------------------------------
const masses = [1, 2, 3, 4, 5];
const weights = [];
const weightColors = [
0x6e7772,
0x59636a,
0x806149,
0x4f5961,
0x6d5145
];
const weightX = [-2.52, -1.26, 0, 1.26, 2.52];
function makeHook() {
const group = new THREE.Group();
const stem = new THREE.Mesh(
new THREE.CylinderGeometry(.028, .028, .32, 6),
brassMaterial
);
stem.position.y = -.14;
stem.castShadow = true;
group.add(stem);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(.12, .033, 6, 12, Math.PI * 1.55),
brassMaterial
);
ring.position.y = .055;
ring.castShadow = true;
group.add(ring);
return group;
}
masses.forEach((mass, index) => {
const group = new THREE.Group();
group.userData.weightId = index;
group.userData.mass = mass;
group.userData.slot = null;
group.userData.targetLocal = null;
const radius = .20 + mass * .028;
const height = .25 + mass * .055;
const bodyMaterial = new THREE.MeshStandardMaterial({
color: weightColors[index],
roughness: .62,
metalness: .32,
flatShading: true,
emissive: 0x000000,
emissiveIntensity: 0
});
const body = new THREE.Mesh(
new THREE.CylinderGeometry(radius * .84, radius, height, 7),
bodyMaterial
);
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
const cap = new THREE.Mesh(
new THREE.CylinderGeometry(radius * .57, radius * .69, .055, 7),
brassMaterial
);
cap.position.y = height / 2 + .025;
cap.castShadow = true;
group.add(cap);
const label = textSprite(`${mass} kg`, .58, .25, {
canvasWidth: 256,
canvasHeight: 112,
font: "bold 64px Georgia",
color: "#34271b",
background: "#ddc89b",
border: "#695033"
});
label.position.set(0, 0, radius + .075);
group.add(label);
const hook = makeHook();
group.add(hook);
group.userData.bodyMaterial = bodyMaterial;
group.userData.height = height;
group.userData.hook = hook;
const home = new THREE.Vector3(
weightX[index],
1.075 + height / 2,
1.66
);
group.userData.home = home;
group.position.copy(home);
hook.position.set(0, height / 2 + .10, 0);
hook.rotation.z = Math.PI;
scene.add(group);
weights.push(group);
// Faint outline showing the original tray slot.
const slotOutline = new THREE.Mesh(
new THREE.RingGeometry(radius * .88, radius, 12),
new THREE.MeshBasicMaterial({
color: 0x3a2819,
transparent: true,
opacity: .45,
side: THREE.DoubleSide
})
);
slotOutline.rotation.x = -Math.PI / 2;
slotOutline.position.set(weightX[index], 1.073, 1.66);
scene.add(slotOutline);
});
// -------------------------------------------------------------------------
// Puzzle state and idealized static balance
// -------------------------------------------------------------------------
let selectedWeight = null;
let leftTorque = 0;
let rightTorque = 0;
let targetBeamAngle = 0;
const leftBadge = document.getElementById("torque-left");
const rightBadge = document.getElementById("torque-right");
const statusElement = document.getElementById("status");
const tiltReadout = document.getElementById("tilt-readout");
const leftAnchor = new THREE.Object3D();
leftAnchor.position.set(-2.68, .72, .58);
beamPivot.add(leftAnchor);
const rightAnchor = new THREE.Object3D();
rightAnchor.position.set(2.68, .72, .58);
beamPivot.add(rightAnchor);
function selectWeight(weight) {
selectedWeight = weight;
for (const item of weights) {
const material = item.userData.bodyMaterial;
const selected = item === weight;
material.emissive.setHex(selected ? 0x6c3b12 : 0x000000);
material.emissiveIntensity = selected ? .72 : 0;
}
if (weight) {
statusElement.innerHTML =
`<strong>${weight.userData.mass} kg selected.</strong> ` +
`Drop it on a marked position, or click a position on the beam.`;
}
}
function updateTotals(customMessage = null) {
leftTorque = 0;
rightTorque = 0;
for (const weight of weights) {
const slot = weight.userData.slot;
if (!slot) continue;
const torque = weight.userData.mass * slot.distance;
if (slot.side === "left") leftTorque += torque;
else rightTorque += torque;
}
leftBadge.innerHTML = `Left arm<strong>${leftTorque} kg·m</strong>`;
rightBadge.innerHTML = `Right arm<strong>${rightTorque} kg·m</strong>`;
// Positive rotation lowers the left end and raises the right end.
targetBeamAngle = THREE.MathUtils.clamp(
(leftTorque - rightTorque) * .048,
-.30,
.30
);
if (customMessage) {
statusElement.textContent = customMessage;
} else if (leftTorque === rightTorque && leftTorque > 0) {
statusElement.innerHTML =
`<strong>Balanced.</strong> Both arms carry ${leftTorque} kg·m.`;
} else if (leftTorque > rightTorque) {
statusElement.innerHTML =
`<strong>The left arm is heavier by ${leftTorque - rightTorque} kg·m.</strong> ` +
`Move mass outward or reduce the left load.`;
} else if (rightTorque > leftTorque) {
statusElement.innerHTML =
`<strong>The right arm is heavier by ${rightTorque - leftTorque} kg·m.</strong> ` +
`Move mass outward or reduce the right load.`;
} else {
statusElement.innerHTML =
`<strong>Your scale is empty.</strong> Choose a weight from the tray to begin.`;
}
}
function setTargetPosition(object, target) {
object.userData.targetLocal = target.clone();
}
function restoreWeight(weight) {
const slot = weight.userData.slot;
if (slot) {
if (weight.parent !== beamPivot) beamPivot.attach(weight);
if (weight.userData.hook.parent !== beamPivot) {
beamPivot.attach(weight.userData.hook);
}
weight.userData.hook.rotation.set(0, 0, 0);
setTargetPosition(weight, new THREE.Vector3(slot.x, -.65, .52));
setTargetPosition(
weight.userData.hook,
new THREE.Vector3(slot.x, -.075, .405)
);
} else {
if (weight.parent !== scene) scene.attach(weight);
if (weight.userData.hook.parent !== weight) {
weight.attach(weight.userData.hook);
}
weight.userData.hook.rotation.set(0, 0, Math.PI);
setTargetPosition(weight, weight.userData.home);
setTargetPosition(
weight.userData.hook,
new THREE.Vector3(0, weight.userData.height / 2 + .10, 0)
);
}
}
function attachWeight(weight, slot) {
const previousSlot = weight.userData.slot;
if (slot.occupant && slot.occupant !== weight) {
statusElement.innerHTML =
`<strong>That position is occupied.</strong> Choose another marked position.`;
restoreWeight(weight);
return false;
}
if (previousSlot && previousSlot !== slot) {
if (previousSlot.occupant === weight) previousSlot.occupant = null;
}
slot.occupant = weight;
weight.userData.slot = slot;
if (weight.parent !== beamPivot) beamPivot.attach(weight);
if (weight.userData.hook.parent !== beamPivot) {
beamPivot.attach(weight.userData.hook);
}
weight.userData.hook.rotation.set(0, 0, 0);
setTargetPosition(weight, new THREE.Vector3(slot.x, -.65, .52));
setTargetPosition(
weight.userData.hook,
new THREE.Vector3(slot.x, -.075, .405)
);
selectWeight(null);
updateTotals(
`${weight.userData.mass} kg placed on the ${slot.side} arm at ${slot.distance} m.`
);
return true;
}
function findSlot(side, distance) {
return slots.find(
slot => slot.side === side && slot.distance === distance
);
}
function resetAll(message = null) {
for (const weight of weights) {
const slot = weight.userData.slot;
if (slot && slot.occupant === weight) slot.occupant = null;
weight.userData.slot = null;
if (weight.parent !== scene) scene.attach(weight);
if (weight.userData.hook.parent !== weight) {
weight.attach(weight.userData.hook);
}
weight.position.copy(weight.userData.home);
weight.rotation.set(0, 0, 0);
weight.userData.targetLocal = null;
weight.userData.hook.position.set(
0,
weight.userData.height / 2 + .10,
0
);
weight.userData.hook.rotation.set(0, 0, Math.PI);
weight.userData.hook.userData.targetLocal = null;
}
beamPivot.rotation.z = 0;
targetBeamAngle = 0;
selectWeight(null);
updateTotals(message);
}
function loadExample() {
resetAll();
const threeKg = weights.find(weight => weight.userData.mass === 3);
const fourKg = weights.find(weight => weight.userData.mass === 4);
attachWeight(threeKg, findSlot("left", 4));
attachWeight(fourKg, findSlot("right", 3));
updateTotals(
"Example loaded: 3 kg × 4 m = 4 kg × 3 m = 12 kg·m. " +
"Different masses can balance at different arm lengths."
);
}
document.getElementById("example").addEventListener("click", loadExample);
document.getElementById("reset").addEventListener("click", () => {
resetAll("Every weight is back in its original tray slot.");
});
window.addEventListener("keydown", event => {
if (event.key.toLowerCase() === "r") {
resetAll("Every weight is back in its original tray slot.");
}
if (event.key.toLowerCase() === "e") {
loadExample();
}
});
// -------------------------------------------------------------------------
// Direct camera controls and drag interaction
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane();
const dragPoint = new THREE.Vector3();
const dragOffset = new THREE.Vector3();
const worldTemp = new THREE.Vector3();
let orbitState = null;
let dragState = null;
function updatePointer(event) {
const rect = renderer.domElement.getBoundingClientRect();
pointer.x = ((event.clientX - rect.left) / rect.width) * 2 - 1;
pointer.y = -((event.clientY - rect.top) / rect.height) * 2 + 1;
}
function findWeight(object) {
let current = object;
while (current) {
if (current.userData.weightId !== undefined) {
return weights[current.userData.weightId];
}
current = current.parent;
}
return null;
}
function pickWeight() {
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(weights, true);
return hits.length ? findWeight(hits[0].object) : null;
}
function pickSlot() {
raycaster.setFromCamera(pointer, camera);
const hits = raycaster.intersectObjects(dropTargets, false);
return hits.length ? hits[0].object.userData : null;
}
function clearSlotHighlights() {
for (const slot of slots) {
slot.marker.material.emissive.setHex(0x000000);
slot.marker.material.emissiveIntensity = 0;
}
}
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
updatePointer(event);
selectWeight(null);
const pickedWeight = pickWeight();
if (pickedWeight) {
selectWeight(pickedWeight);
pickedWeight.getWorldPosition(worldTemp);
const cameraNormal = new THREE.Vector3();
camera.getWorldDirection(cameraNormal);
dragPlane.setFromNormalAndCoplanarPoint(cameraNormal, worldTemp);
raycaster.setFromCamera(pointer, camera);
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
dragOffset.copy(pickedWeight.position).sub(dragPoint);
} else {
dragOffset.set(0, 0, 0);
}
if (pickedWeight.parent !== scene) scene.attach(pickedWeight);
pickedWeight.userData.targetLocal = null;
pickedWeight.userData.hook.userData.targetLocal = null;
dragState = {
weight: pickedWeight,
pointerId: event.pointerId,
moved: false
};
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
event.preventDefault();
return;
}
const slotHit = pickSlot();
if (slotHit) {
const slot = slots.find(
item => item.side === slotHit.side && item.distance === slotHit.distance
);
if (selectedWeight && slot) {
attachWeight(selectedWeight, slot);
event.preventDefault();
return;
}
}
orbitState = {
x: event.clientX,
y: event.clientY,
pointerId: event.pointerId
};
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
});
renderer.domElement.addEventListener("pointermove", event => {
updatePointer(event);
if (dragState && event.pointerId === dragState.pointerId) {
dragState.moved = true;
raycaster.setFromCamera(pointer, camera);
if (raycaster.ray.intersectPlane(dragPlane, dragPoint)) {
const weight = dragState.weight;
weight.position.copy(dragPoint).add(dragOffset);
weight.position.y = THREE.MathUtils.clamp(weight.position.y, .95, 4.15);
}
clearSlotHighlights();
const slotHit = pickSlot();
if (slotHit) {
const slot = slots.find(
item => item.side === slotHit.side && item.distance === slotHit.distance
);
if (slot) {
const occupied = slot.occupant && slot.occupant !== dragState.weight;
slot.marker.material.emissive.setHex(occupied ? 0x8b1e0d : 0x3e6b2f);
slot.marker.material.emissiveIntensity = 1.1;
}
}
return;
}
if (orbitState && event.pointerId === orbitState.pointerId) {
const dx = event.clientX - orbitState.x;
const dy = event.clientY - orbitState.y;
cameraYaw -= dx * .006;
cameraPitch = THREE.MathUtils.clamp(
cameraPitch + dy * .0045,
.12,
1.08
);
orbitState.x = event.clientX;
orbitState.y = event.clientY;
updateCamera();
return;
}
const hoverWeight = pickWeight();
renderer.domElement.style.cursor = hoverWeight ? "grab" : "default";
});
function finishPointer(event) {
if (dragState && event.pointerId === dragState.pointerId) {
updatePointer(event);
clearSlotHighlights();
const slotHit = pickSlot();
const weight = dragState.weight;
if (slotHit) {
const slot = slots.find(
item => item.side === slotHit.side && item.distance === slotHit.distance
);
if (slot) attachWeight(weight, slot);
else restoreWeight(weight);
} else {
restoreWeight(weight);
}
dragState = null;
}
if (orbitState && event.pointerId === orbitState.pointerId) {
orbitState = null;
}
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
renderer.domElement.style.cursor = "grab";
}
renderer.domElement.addEventListener("pointerup", finishPointer);
renderer.domElement.addEventListener("pointercancel", finishPointer);
renderer.domElement.addEventListener("contextmenu", event => event.preventDefault());
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * .001),
7.1,
17.5
);
updateCamera();
}, { passive: false });
// -------------------------------------------------------------------------
// Projection of the two torque displays
// -------------------------------------------------------------------------
function projectElement(element, anchor) {
anchor.getWorldPosition(worldTemp);
worldTemp.project(camera);
const x = (worldTemp.x * .5 + .5) * window.innerWidth;
const y = (-worldTemp.y * .5 + .5) * window.innerHeight;
const visible = worldTemp.z > -1 && worldTemp.z < 1;
element.style.display = visible ? "block" : "none";
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}
// -------------------------------------------------------------------------
// Animation loop
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), .05);
const smoothing = 1 - Math.exp(-dt * 9);
// Idealized static response: angle is proportional to torque difference.
beamPivot.rotation.z +=
(targetBeamAngle - beamPivot.rotation.z) * (1 - Math.exp(-dt * 6.5));
// Animated weights and sliding brass hooks.
for (const weight of weights) {
if (weight.userData.targetLocal) {
weight.position.lerp(weight.userData.targetLocal, smoothing);
}
const hook = weight.userData.hook;
if (hook.userData.targetLocal) {
hook.position.lerp(hook.userData.targetLocal, smoothing);
}
}
const degrees = THREE.MathUtils.radToDeg(beamPivot.rotation.z);
tiltReadout.textContent = `Beam tilt: ${degrees.toFixed(1)}°`;
updateCamera();
projectElement(leftBadge, leftAnchor);
projectElement(rightBadge, rightAnchor);
renderer.render(scene, camera);
}
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
updateTotals();
animate();
</script>
</body>
</html>
```