Prompt specification
Build or customize the Three.js 3D scene "Mass-distribution counterfactual table" 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: Mass-distribution counterfactual table
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/mass-distribution-counterfactual-table-x1368
Scene Description Prompt:
Please use Three.js from cdnjs for a low-poly scene based on this idea: mass-distribution counterfactual table. Let users reposition a few weighted blocks on a beam; recompute center of mass and torque about a chosen support while preserving total mass. Return one self-contained HTML file.
Working Three.js Starter (mass-distribution-counterfactual-table-x1368):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Mass Distribution Counterfactual</title>
<style>
:root {
--ink: #172033;
--muted: #667085;
--line: rgba(23, 32, 51, 0.10);
--panel: rgba(255, 255, 255, 0.82);
--accent: #6d5dfc;
--cyan: #10b9a5;
--amber: #f59e0b;
--orange: #f97316;
--red: #ef476f;
--gold: #e9a23b;
--purple: #7c5ce5;
--shadow: 0 18px 55px rgba(35, 47, 72, 0.14);
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
color: var(--ink);
background: #e9eef5;
font-family:
Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI",
sans-serif;
}
button,
input {
font: inherit;
}
button {
color: inherit;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
outline: none;
}
.glass {
background: var(--panel);
border: 1px solid rgba(255, 255, 255, 0.72);
box-shadow: var(--shadow);
backdrop-filter: blur(18px) saturate(130%);
-webkit-backdrop-filter: blur(18px) saturate(130%);
}
.topbar {
position: fixed;
top: 18px;
left: 18px;
right: 18px;
min-height: 68px;
padding: 13px 18px;
border-radius: 19px;
display: flex;
align-items: center;
gap: 18px;
z-index: 5;
pointer-events: none;
}
.brand {
min-width: 0;
}
.eyebrow {
color: var(--accent);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.16em;
text-transform: uppercase;
margin-bottom: 3px;
}
h1 {
margin: 0;
font-size: clamp(18px, 2vw, 25px);
line-height: 1.05;
letter-spacing: -0.035em;
}
.top-spacer {
flex: 1;
}
.mass-lock {
display: inline-flex;
align-items: center;
gap: 8px;
flex: 0 0 auto;
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.72);
border-radius: 999px;
padding: 9px 13px;
font-size: 12px;
font-weight: 750;
white-space: nowrap;
}
.lock-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 0 0 4px rgba(16, 185, 165, 0.12);
}
.panel {
position: fixed;
z-index: 4;
border-radius: 20px;
overflow: auto;
scrollbar-width: thin;
scrollbar-color: rgba(23, 32, 51, 0.18) transparent;
}
.control-panel {
left: 18px;
top: 102px;
bottom: 18px;
width: 318px;
padding: 18px;
}
.right-panel {
right: 18px;
top: 102px;
bottom: 18px;
width: 430px;
padding: 18px;
}
.section + .section {
margin-top: 20px;
padding-top: 18px;
border-top: 1px solid var(--line);
}
.section-heading {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 12px;
}
.section-heading h2 {
margin: 0;
font-size: 12px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.micro {
color: var(--muted);
font-size: 11px;
line-height: 1.5;
}
.selected-card {
border: 1px solid var(--line);
background: rgba(255, 255, 255, 0.6);
border-radius: 14px;
padding: 13px;
}
.selected-top {
display: flex;
align-items: center;
gap: 10px;
margin-bottom: 11px;
}
.block-swatch {
width: 12px;
height: 12px;
border-radius: 4px;
flex: 0 0 auto;
box-shadow: inset 0 0 0 1px rgba(0, 0, 0, 0.08);
}
.selected-name {
font-size: 14px;
font-weight: 800;
}
.selected-mass {
margin-left: auto;
color: var(--muted);
font-size: 12px;
font-weight: 700;
}
.nudge-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.button {
min-height: 38px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.8);
cursor: pointer;
font-size: 12px;
font-weight: 750;
transition:
transform 120ms ease,
border-color 120ms ease,
background 120ms ease,
box-shadow 120ms ease;
}
.button:hover {
transform: translateY(-1px);
border-color: rgba(109, 93, 252, 0.35);
background: #fff;
box-shadow: 0 5px 14px rgba(35, 47, 72, 0.08);
}
.button:active {
transform: translateY(0);
}
.button.primary {
color: #fff;
border-color: transparent;
background: linear-gradient(135deg, #7565ff, #5b4bea);
box-shadow: 0 8px 18px rgba(109, 93, 252, 0.25);
}
.button.primary:hover {
background: linear-gradient(135deg, #806fff, #6453ef);
}
.button.wide {
width: 100%;
}
.support-value {
color: var(--cyan);
font-size: 18px;
font-weight: 850;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 5px;
margin: 11px 0 14px;
appearance: none;
border-radius: 99px;
outline: none;
background:
linear-gradient(90deg, var(--cyan), rgba(16, 185, 165, 0.18));
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 18px;
height: 18px;
appearance: none;
border: 3px solid #fff;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 2px 9px rgba(16, 185, 165, 0.38);
}
input[type="range"]::-moz-range-thumb {
width: 13px;
height: 13px;
border: 3px solid #fff;
border-radius: 50%;
background: var(--cyan);
box-shadow: 0 2px 9px rgba(16, 185, 165, 0.38);
}
.range-labels {
display: flex;
justify-content: space-between;
margin-top: -7px;
color: var(--muted);
font-size: 10px;
font-variant-numeric: tabular-nums;
}
.action-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
}
.mass-list {
display: grid;
gap: 7px;
}
.mass-item {
display: flex;
align-items: center;
gap: 9px;
min-height: 34px;
padding: 7px 9px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.48);
font-size: 12px;
}
.mass-item strong {
margin-left: auto;
font-variant-numeric: tabular-nums;
}
.locked {
color: var(--muted);
font-size: 9px;
font-weight: 800;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.formula {
padding: 11px 12px;
border-radius: 12px;
background: #202a3d;
color: #eef2ff;
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 11px;
line-height: 1.7;
}
.metric-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 10px;
}
.metric {
min-height: 112px;
padding: 14px;
border: 1px solid var(--line);
border-radius: 15px;
background: rgba(255, 255, 255, 0.66);
}
.metric-label {
color: var(--muted);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.metric-value {
margin-top: 8px;
font-size: 28px;
font-weight: 850;
letter-spacing: -0.045em;
font-variant-numeric: tabular-nums;
}
.metric-sub {
margin-top: 5px;
color: var(--muted);
font-size: 11px;
font-variant-numeric: tabular-nums;
}
.balance-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-top: 11px;
padding: 11px 13px;
border-radius: 12px;
background: rgba(16, 185, 165, 0.09);
border: 1px solid rgba(16, 185, 165, 0.18);
}
.balance-row[data-state="unbalanced"] {
background: rgba(249, 115, 22, 0.09);
border-color: rgba(249, 115, 22, 0.2);
}
.balance-text {
font-size: 12px;
font-weight: 750;
line-height: 1.4;
}
.balance-pill {
flex: 0 0 auto;
padding: 6px 9px;
border-radius: 999px;
color: #087d70;
background: rgba(16, 185, 165, 0.14);
font-size: 9px;
font-weight: 900;
letter-spacing: 0.08em;
text-transform: uppercase;
}
.balance-row[data-state="unbalanced"] .balance-pill {
color: #b94b08;
background: rgba(249, 115, 22, 0.14);
}
.table-wrap {
overflow-x: auto;
border: 1px solid var(--line);
border-radius: 14px;
background: rgba(255, 255, 255, 0.54);
}
table {
width: 100%;
border-collapse: collapse;
font-size: 11px;
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
th,
td {
padding: 10px 8px;
text-align: right;
border-bottom: 1px solid var(--line);
}
th {
color: var(--muted);
background: rgba(244, 246, 251, 0.72);
font-size: 9px;
font-weight: 850;
letter-spacing: 0.06em;
text-transform: uppercase;
}
th:first-child,
td:first-child {
text-align: left;
}
tbody tr:last-child td {
border-bottom: 0;
}
tfoot td {
border-top: 1px solid var(--line);
border-bottom: 0;
font-weight: 850;
background: rgba(109, 93, 252, 0.045);
}
.table-dot {
display: inline-block;
width: 8px;
height: 8px;
margin-right: 5px;
border-radius: 3px;
vertical-align: 0;
}
.compare-summary {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-top: 9px;
}
.compare-cell {
padding: 9px 10px;
border: 1px solid var(--line);
border-radius: 11px;
background: rgba(255, 255, 255, 0.48);
color: var(--muted);
font-size: 10px;
}
.compare-cell strong {
display: block;
margin-top: 3px;
color: var(--ink);
font-size: 13px;
font-variant-numeric: tabular-nums;
}
.hint {
position: fixed;
z-index: 3;
left: 50%;
bottom: 20px;
transform: translateX(-50%);
max-width: calc(100vw - 760px);
padding: 10px 14px;
border-radius: 999px;
color: #465066;
background: rgba(255, 255, 255, 0.72);
border: 1px solid rgba(255, 255, 255, 0.9);
box-shadow: 0 8px 24px rgba(35, 47, 72, 0.1);
backdrop-filter: blur(10px);
font-size: 10px;
font-weight: 700;
text-align: center;
pointer-events: none;
}
.hint span {
color: var(--accent);
}
#loading {
position: fixed;
inset: 0;
z-index: 20;
display: grid;
place-items: center;
color: var(--muted);
background: #e9eef5;
font-size: 13px;
font-weight: 700;
}
#loading.hidden {
display: none;
}
@media (max-width: 1100px) {
.control-panel {
width: 286px;
}
.right-panel {
width: 380px;
}
.hint {
display: none;
}
}
@media (max-width: 820px) {
body {
overflow: auto;
}
.topbar {
left: 10px;
right: 10px;
top: 10px;
}
.mass-lock {
display: none;
}
.control-panel {
left: 10px;
right: 10px;
top: 92px;
bottom: auto;
width: auto;
max-height: 42vh;
}
.right-panel {
left: 10px;
right: 10px;
top: auto;
bottom: 10px;
width: auto;
max-height: 43vh;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive three-dimensional beam and weighted blocks"></canvas>
<header class="topbar glass">
<div class="brand">
<div class="eyebrow">Mechanics Lab / Counterfactual 01</div>
<h1>Mass distribution counterfactual</h1>
</div>
<div class="top-spacer"></div>
<div class="mass-lock">
<span class="lock-dot"></span>
<span id="massLockText">12.0 kg total mass locked</span>
</div>
</header>
<aside class="panel control-panel glass" aria-label="Experiment controls">
<section class="section">
<div class="section-heading">
<h2>Selected block</h2>
<span class="micro">Drag in the scene</span>
</div>
<div class="selected-card">
<div class="selected-top">
<span id="selectedSwatch" class="block-swatch"></span>
<span id="selectedName" class="selected-name">Block A</span>
<span id="selectedMass" class="selected-mass">2.0 kg</span>
</div>
<div class="nudge-row">
<button id="nudgeLeft" class="button" type="button">← 0.10 m</button>
<button id="nudgeRight" class="button" type="button">0.10 m →</button>
</div>
</div>
</section>
<section class="section">
<div class="section-heading">
<h2>Chosen support</h2>
<output id="supportValue" class="support-value" for="supportRange">+0.58 m</output>
</div>
<input
id="supportRange"
type="range"
min="-3.4"
max="3.4"
step="0.01"
value="0.575"
aria-label="Support position along beam"
/>
<div class="range-labels">
<span>−3.40 m</span>
<span>beam center</span>
<span>+3.40 m</span>
</div>
<button id="alignButton" class="button primary wide" type="button" style="margin-top: 12px">
Place support under current COM
</button>
</section>
<section class="section">
<div class="section-heading">
<h2>Counterfactual controls</h2>
</div>
<div class="action-grid">
<button id="captureButton" class="button" type="button">Capture current baseline</button>
<button id="resetButton" class="button" type="button">Reset original</button>
</div>
<p class="micro" style="margin: 10px 1px 0">
Capture makes the current arrangement the “before” case. Masses never change.
</p>
</section>
<section class="section">
<div class="section-heading">
<h2>Mass inventory</h2>
<span class="locked">Locked</span>
</div>
<div id="massList" class="mass-list"></div>
</section>
<section class="section">
<div class="section-heading">
<h2>Model</h2>
</div>
<div class="formula">
x<sub>COM</sub> = Σ(m<sub>i</sub>x<sub>i</sub>) / Σm<sub>i</sub><br />
τ = −Mg(x<sub>COM</sub> − x<sub>support</sub>)
</div>
<p class="micro" style="margin: 9px 1px 0">
The uniform beam contributes 2.0 kg at x = 0. Gravity is 9.81 m/s².
</p>
</section>
</aside>
<aside class="panel right-panel glass" aria-label="Calculated results">
<section class="section">
<div class="section-heading">
<h2>Live result</h2>
<span class="micro">about the selected support</span>
</div>
<div class="metric-grid">
<div class="metric">
<div class="metric-label">Center of mass</div>
<div id="comValue" class="metric-value">+0.58 m</div>
<div id="comDelta" class="metric-sub">0.00 m vs baseline</div>
</div>
<div class="metric">
<div class="metric-label">Net torque</div>
<div id="torqueValue" class="metric-value">0.00 N·m</div>
<div id="torqueDirection" class="metric-sub">Balanced</div>
</div>
</div>
<div id="balanceRow" class="balance-row" data-state="balanced">
<div id="balanceText" class="balance-text">
The center of mass is directly above the support.
</div>
<div id="balancePill" class="balance-pill">Balanced</div>
</div>
</section>
<section class="section">
<div class="section-heading">
<h2>Baseline ↔ current</h2>
<span class="micro">positions in meters</span>
</div>
<div class="table-wrap">
<table>
<thead>
<tr>
<th>Item</th>
<th>Mass</th>
<th>Baseline</th>
<th>Current</th>
<th>Shift</th>
</tr>
</thead>
<tbody id="tableBody"></tbody>
<tfoot>
<tr>
<td>Total</td>
<td>12.00</td>
<td>—</td>
<td>12.00</td>
<td>0.00</td>
</tr>
</tfoot>
</table>
</div>
<div class="compare-summary">
<div class="compare-cell">
Baseline torque at current support
<strong id="baselineTorque">0.00 N·m</strong>
</div>
<div class="compare-cell">
Current torque at current support
<strong id="currentTorque">0.00 N·m</strong>
</div>
</div>
<p id="supportNote" class="micro" style="margin: 9px 1px 0">
Both torque values use the chosen support at +0.58 m.
</p>
</section>
</aside>
<div class="hint">
<span>Drag blocks</span> to redistribute mass ·
<span>drag cyan support</span> to move the pivot ·
drag background to orbit · scroll to zoom
</div>
<div id="loading">Loading the Three.js mechanics lab…</div>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// Physics model
// -------------------------------------------------------------------------
const GRAVITY = 9.81;
const BEAM_MASS = 2.0;
const BEAM_LENGTH = 7.4;
const BEAM_HEIGHT = 0.3;
const BEAM_DEPTH = 0.78;
const BLOCK_LIMIT = 3.35;
const BALANCE_TOLERANCE = 0.25;
const blocks = [
{
id: "A",
name: "Block A",
descriptor: "Light",
mass: 2.0,
width: 0.62,
height: 0.58,
depth: 0.76,
color: "#ef476f"
},
{
id: "B",
name: "Block B",
descriptor: "Medium",
mass: 3.0,
width: 0.84,
height: 0.74,
depth: 0.84,
color: "#e9a23b"
},
{
id: "C",
name: "Block C",
descriptor: "Heavy",
mass: 5.0,
width: 1.08,
height: 0.95,
depth: 0.94,
color: "#7c5ce5"
}
];
const TOTAL_MASS =
BEAM_MASS + blocks.reduce((sum, block) => sum + block.mass, 0);
const originalPositions = [-2.1, 0.2, 2.1];
const originalSupport = 0.575;
const state = {
positions: [...originalPositions],
baselinePositions: [...originalPositions],
support: originalSupport,
selectedIndex: 0
};
function centerOfMass(positions) {
let moment = BEAM_MASS * 0;
for (let i = 0; i < blocks.length; i++) {
moment += blocks[i].mass * positions[i];
}
return moment / TOTAL_MASS;
}
function torqueAboutSupport(comX, supportX) {
// A downward force to the right of the pivot produces clockwise torque.
return -TOTAL_MASS * GRAVITY * (comX - supportX);
}
// -------------------------------------------------------------------------
// DOM
// -------------------------------------------------------------------------
const canvas = document.getElementById("scene");
const loading = document.getElementById("loading");
const selectedSwatch = document.getElementById("selectedSwatch");
const selectedName = document.getElementById("selectedName");
const selectedMass = document.getElementById("selectedMass");
const nudgeLeft = document.getElementById("nudgeLeft");
const nudgeRight = document.getElementById("nudgeRight");
const supportRange = document.getElementById("supportRange");
const supportValue = document.getElementById("supportValue");
const alignButton = document.getElementById("alignButton");
const captureButton = document.getElementById("captureButton");
const resetButton = document.getElementById("resetButton");
const massList = document.getElementById("massList");
const tableBody = document.getElementById("tableBody");
const comValue = document.getElementById("comValue");
const comDelta = document.getElementById("comDelta");
const torqueValue = document.getElementById("torqueValue");
const torqueDirection = document.getElementById("torqueDirection");
const balanceRow = document.getElementById("balanceRow");
const balanceText = document.getElementById("balanceText");
const balancePill = document.getElementById("balancePill");
const baselineTorque = document.getElementById("baselineTorque");
const currentTorque = document.getElementById("currentTorque");
const supportNote = document.getElementById("supportNote");
const massLockText = document.getElementById("massLockText");
massLockText.textContent = `${TOTAL_MASS.toFixed(1)} kg total mass locked`;
massList.innerHTML = blocks
.map(
(block) => `
<div class="mass-item">
<span class="block-swatch" style="background:${block.color}"></span>
<span>${block.name} · ${block.descriptor}</span>
<strong>${block.mass.toFixed(1)} kg</strong>
</div>
`
)
.join("") +
`
<div class="mass-item">
<span class="block-swatch" style="background:#9aa7ba"></span>
<span>Uniform beam</span>
<strong>${BEAM_MASS.toFixed(1)} kg</strong>
</div>
`;
// -------------------------------------------------------------------------
// Renderer, camera, and lights
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
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.05;
const scene = new THREE.Scene();
scene.background = new THREE.Color("#e9eef5");
scene.fog = new THREE.Fog("#e9eef5", 15, 30);
const camera = new THREE.PerspectiveCamera(
39,
window.innerWidth / window.innerHeight,
0.1,
80
);
const cameraState = {
target: new THREE.Vector3(0, -0.12, 0),
yaw: 0.52,
pitch: 0.39,
radius: 10.8
};
function updateCamera() {
const { target, yaw, pitch, radius } = cameraState;
camera.position.set(
target.x + radius * Math.sin(yaw) * Math.cos(pitch),
target.y + radius * Math.sin(pitch),
target.z + radius * Math.cos(yaw) * Math.cos(pitch)
);
camera.lookAt(target);
}
updateCamera();
const hemi = new THREE.HemisphereLight(0xffffff, 0x9aa7ba, 2.0);
scene.add(hemi);
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(4.5, 9, 7);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -8;
keyLight.shadow.camera.right = 8;
keyLight.shadow.camera.top = 7;
keyLight.shadow.camera.bottom = -7;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 25;
keyLight.shadow.bias = -0.00025;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0xb9c7ff, 1.3);
rimLight.position.set(-6, 4, -5);
scene.add(rimLight);
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(40, 40),
new THREE.MeshStandardMaterial({
color: 0xe7ebf2,
roughness: 0.94,
metalness: 0
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -1.24;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(28, 56, 0xbac4d3, 0xd4dbe5);
grid.position.y = -1.225;
grid.material.transparent = true;
grid.material.opacity = 0.42;
scene.add(grid);
// -------------------------------------------------------------------------
// Label helper using core Three.js sprites
// -------------------------------------------------------------------------
function roundedRect(context, x, y, width, height, radius) {
const r = Math.min(radius, width / 2, height / 2);
context.beginPath();
context.moveTo(x + r, y);
context.lineTo(x + width - r, y);
context.quadraticCurveTo(x + width, y, x + width, y + r);
context.lineTo(x + width, y + height - r);
context.quadraticCurveTo(
x + width,
y + height,
x + width - r,
y + height
);
context.lineTo(x + r, y + height);
context.quadraticCurveTo(x, y + height, x, y + height - r);
context.lineTo(x, y + r);
context.quadraticCurveTo(x, y, x + r, y);
context.closePath();
}
function createLabelSprite(lines, options = {}) {
const canvasElement = document.createElement("canvas");
canvasElement.width = 512;
canvasElement.height = 256;
const context = canvasElement.getContext("2d");
const texture = new THREE.CanvasTexture(canvasElement);
texture.colorSpace = THREE.SRGBColorSpace;
texture.anisotropy = Math.min(
8,
renderer.capabilities.getMaxAnisotropy()
);
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(
options.scaleX ?? 1,
options.scaleY ?? 0.5,
1
);
sprite.renderOrder = 20;
sprite.userData.label = {
canvas: canvasElement,
context,
texture
};
setLabelSprite(sprite, lines, options);
return sprite;
}
function setLabelSprite(sprite, lines, options = {}) {
const { canvas: labelCanvas, context, texture } = sprite.userData.label;
const width = labelCanvas.width;
const height = labelCanvas.height;
context.clearRect(0, 0, width, height);
const background = options.background ?? "rgba(25, 34, 52, 0.9)";
const foreground = options.foreground ?? "#ffffff";
const border = options.border ?? "rgba(255,255,255,0.18)";
roundedRect(context, 8, 8, width - 16, height - 16, 34);
context.fillStyle = background;
context.fill();
context.lineWidth = 5;
context.strokeStyle = border;
context.stroke();
const textLines = Array.isArray(lines) ? lines : [lines];
context.textAlign = "center";
context.textBaseline = "middle";
context.fillStyle = foreground;
if (textLines.length === 1) {
context.font = "800 60px system-ui, sans-serif";
context.fillText(textLines[0], width / 2, height / 2 + 2);
} else {
context.font = "800 49px system-ui, sans-serif";
context.fillText(textLines[0], width / 2, 91);
context.font = "750 43px system-ui, sans-serif";
context.fillText(textLines[1], width / 2, 166);
}
texture.needsUpdate = true;
}
// -------------------------------------------------------------------------
// Beam, ruler, blocks, and baseline ghosts
// -------------------------------------------------------------------------
const beam = new THREE.Mesh(
new THREE.BoxGeometry(BEAM_LENGTH, BEAM_HEIGHT, BEAM_DEPTH),
new THREE.MeshStandardMaterial({
color: 0xf7f8fb,
roughness: 0.58,
metalness: 0.08
})
);
beam.castShadow = true;
beam.receiveShadow = true;
scene.add(beam);
const beamEdges = new THREE.LineSegments(
new THREE.EdgesGeometry(beam.geometry),
new THREE.LineBasicMaterial({
color: 0x8e9aad,
transparent: true,
opacity: 0.65
})
);
beam.add(beamEdges);
for (let x = -3.5; x <= 3.5; x += 0.5) {
const major = Math.abs(x % 1) < 0.01;
const tick = new THREE.Mesh(
new THREE.BoxGeometry(0.018, major ? 0.085 : 0.045, 0.025),
new THREE.MeshBasicMaterial({
color: major ? 0x7b8799 : 0xb4bdca
})
);
tick.position.set(x, -0.035, BEAM_DEPTH / 2 + 0.014);
scene.add(tick);
}
const beamLabel = createLabelSprite("BEAM · 2.0 kg", {
background: "rgba(72, 83, 103, 0.86)",
foreground: "#f7f9fc",
scaleX: 1.4,
scaleY: 0.32
});
beamLabel.position.set(0, -0.22, 0.46);
scene.add(beamLabel);
const blockMeshes = [];
const blockEdges = [];
const blockLabels = [];
const interactiveObjects = [];
function createBlock(block, index) {
const geometry = new THREE.BoxGeometry(
block.width,
block.height,
block.depth
);
const material = new THREE.MeshStandardMaterial({
color: block.color,
roughness: 0.62,
metalness: 0.04,
emissive: 0x000000,
emissiveIntensity: 0
});
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.userData = { type: "block", index };
scene.add(mesh);
const edges = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry),
new THREE.LineBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.48
})
);
mesh.add(edges);
const label = createLabelSprite(
[`BLOCK ${block.id}`, `${block.mass.toFixed(1)} kg`],
{
background: "rgba(28, 36, 53, 0.82)",
foreground: "#ffffff",
border: "rgba(255,255,255,0.2)",
scaleX: 0.72,
scaleY: 0.42
}
);
scene.add(label);
blockMeshes.push(mesh);
blockEdges.push(edges);
blockLabels.push(label);
interactiveObjects.push(mesh);
}
blocks.forEach(createBlock);
const baselineGhosts = blocks.map((block) => {
const geometry = new THREE.BoxGeometry(
block.width,
block.height,
block.depth
);
const ghost = new THREE.LineSegments(
new THREE.EdgesGeometry(geometry),
new THREE.LineBasicMaterial({
color: block.color,
transparent: true,
opacity: 0.25,
depthWrite: false
})
);
scene.add(ghost);
return ghost;
});
// -------------------------------------------------------------------------
// Support and draggable support marker
// -------------------------------------------------------------------------
const supportGroup = new THREE.Group();
scene.add(supportGroup);
const supportShape = new THREE.Shape();
supportShape.moveTo(-0.5, -0.16);
supportShape.lineTo(0.5, -0.16);
supportShape.lineTo(0, -1.07);
supportShape.closePath();
const supportMesh = new THREE.Mesh(
new THREE.ShapeGeometry(supportShape),
new THREE.MeshStandardMaterial({
color: 0x20bfa9,
roughness: 0.45,
metalness: 0.1,
side: THREE.DoubleSide
})
);
supportMesh.castShadow = true;
supportMesh.userData = { type: "support" };
supportGroup.add(supportMesh);
const supportBase = new THREE.Mesh(
new THREE.BoxGeometry(1.34, 0.12, 0.92),
new THREE.MeshStandardMaterial({
color: 0x159d8c,
roughness: 0.52,
metalness: 0.12
})
);
supportBase.position.y = -1.1;
supportBase.castShadow = true;
supportBase.receiveShadow = true;
supportBase.userData = { type: "support" };
supportGroup.add(supportBase);
const pivot = new THREE.Mesh(
new THREE.CylinderGeometry(0.14, 0.14, 0.96, 24),
new THREE.MeshStandardMaterial({
color: 0x1d293b,
roughness: 0.38,
metalness: 0.5
})
);
pivot.rotation.x = Math.PI / 2;
pivot.position.set(0, -0.15, 0);
pivot.castShadow = true;
supportGroup.add(pivot);
interactiveObjects.push(supportMesh, supportBase);
const supportLabel = createLabelSprite("SUPPORT", {
background: "rgba(10, 157, 140, 0.92)",
foreground: "#ffffff",
scaleX: 1.35,
scaleY: 0.36
});
scene.add(supportLabel);
const supportLine = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineDashedMaterial({
color: 0x10b9a5,
dashSize: 0.12,
gapSize: 0.08,
transparent: true,
opacity: 0.72
})
);
scene.add(supportLine);
// -------------------------------------------------------------------------
// Center-of-mass marker
// -------------------------------------------------------------------------
const comGroup = new THREE.Group();
scene.add(comGroup);
const comDiamond = new THREE.Mesh(
new THREE.OctahedronGeometry(0.115),
new THREE.MeshStandardMaterial({
color: 0xf59e0b,
emissive: 0xf59e0b,
emissiveIntensity: 0.22,
roughness: 0.35
})
);
comDiamond.position.z = 0.5;
comGroup.add(comDiamond);
const comRing = new THREE.Mesh(
new THREE.TorusGeometry(0.19, 0.025, 10, 40),
new THREE.MeshBasicMaterial({
color: 0xf59e0b,
transparent: true,
opacity: 0.95
})
);
comRing.position.z = 0.5;
comGroup.add(comRing);
const comLabel = createLabelSprite("COM", {
background: "rgba(255, 247, 218, 0.96)",
foreground: "#9a5a00",
border: "rgba(245, 158, 11, 0.75)",
scaleX: 1.35,
scaleY: 0.4
});
comLabel.position.set(0, 0.66, 0.56);
comGroup.add(comLabel);
const comLine = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineDashedMaterial({
color: 0xf59e0b,
dashSize: 0.12,
gapSize: 0.08,
transparent: true,
opacity: 0.72
})
);
scene.add(comLine);
// -------------------------------------------------------------------------
// Torque arc and arrowhead
// -------------------------------------------------------------------------
const torqueArc = new THREE.Line(
new THREE.BufferGeometry(),
new THREE.LineBasicMaterial({
color: 0xf97316,
transparent: true,
opacity: 0.95
})
);
scene.add(torqueArc);
const torqueArrow = new THREE.Mesh(
new THREE.ConeGeometry(0.085, 0.2, 18),
new THREE.MeshStandardMaterial({
color: 0xf97316,
roughness: 0.45
})
);
scene.add(torqueArrow);
const yAxis = new THREE.Vector3(0, 1, 0);
// -------------------------------------------------------------------------
// Helpers for updating graphics and data
// -------------------------------------------------------------------------
function signed(value, digits = 2) {
if (Math.abs(value) < 0.0000001) return (0).toFixed(digits);
return `${value > 0 ? "+" : ""}${value.toFixed(digits)}`;
}
function setLinePoints(line, points) {
line.geometry.dispose();
line.geometry = new THREE.BufferGeometry().setFromPoints(points);
if (line.material.isLineDashedMaterial) line.computeLineDistances();
}
function updateBlockGraphics() {
blocks.forEach((block, index) => {
const mesh = blockMeshes[index];
const selected = index === state.selectedIndex;
mesh.position.set(
state.positions[index],
BEAM_HEIGHT / 2 + block.height / 2,
0
);
mesh.material.emissive.set(selected ? block.color : 0x000000);
mesh.material.emissiveIntensity = selected ? 0.16 : 0;
blockEdges[index].material.color.set(selected ? 0xffffff : block.color);
blockEdges[index].material.opacity = selected ? 0.98 : 0.44;
blockLabels[index].position.set(
state.positions[index],
BEAM_HEIGHT / 2 + block.height / 2,
block.depth / 2 + 0.13
);
});
baselineGhosts.forEach((ghost, index) => {
const block = blocks[index];
ghost.position.set(
state.baselinePositions[index],
BEAM_HEIGHT / 2 + block.height / 2,
0
);
ghost.material.opacity = 0.24;
});
}
function updateSupportGraphics() {
supportGroup.position.x = state.support;
supportLabel.position.set(state.support, -1.38, 0.22);
setLabelSprite(
supportLabel,
`SUPPORT ${signed(state.support, 2)} m`,
{
background: "rgba(10, 157, 140, 0.94)",
foreground: "#ffffff",
scaleX: 1.55,
scaleY: 0.36
}
);
setLinePoints(supportLine, [
new THREE.Vector3(state.support, -0.13, 0.46),
new THREE.Vector3(state.support, -1.03, 0.46)
]);
}
function updateComGraphics(comX) {
comGroup.position.x = comX;
setLabelSprite(
comLabel,
`COM ${signed(comX, 2)} m`,
{
background: "rgba(255, 247, 218, 0.97)",
foreground: "#925600",
border: "rgba(245, 158, 11, 0.8)",
scaleX: 1.42,
scaleY: 0.4
}
);
setLinePoints(comLine, [
new THREE.Vector3(comX, 0.17, 0.47),
new THREE.Vector3(comX, -1.03, 0.47)
]);
}
function updateTorqueGraphics(torque) {
const magnitude = Math.abs(torque);
if (magnitude < 0.08) {
torqueArc.visible = false;
torqueArrow.visible = false;
return;
}
torqueArc.visible = true;
torqueArrow.visible = true;
const direction = Math.sign(torque) || 1;
const turn = THREE.MathUtils.clamp(magnitude / 75, 0.3, 2.45);
const radius = 0.59;
const pivotY = -0.15;
const z = 0.56;
const startAngle = -Math.PI / 2;
const endAngle = startAngle + direction * turn;
const points = [];
for (let i = 0; i <= 48; i++) {
const t = i / 48;
const angle = startAngle + direction * turn * t;
points.push(
new THREE.Vector3(
state.support + Math.cos(angle) * radius,
pivotY + Math.sin(angle) * radius,
z
)
);
}
setLinePoints(torqueArc, points);
const tangent = new THREE.Vector3(
-Math.sin(endAngle) * direction,
Math.cos(endAngle) * direction,
0
).normalize();
torqueArrow.position.set(
state.support + Math.cos(endAngle) * radius,
pivotY + Math.sin(endAngle) * radius,
z
);
torqueArrow.quaternion.setFromUnitVectors(yAxis, tangent);
}
function updateTable(comX, baselineComX) {
const rows = blocks
.map((block, index) => {
const shift = state.positions[index] - state.baselinePositions[index];
return `
<tr>
<td>
<span class="table-dot" style="background:${block.color}"></span>
Block ${block.id}
</td>
<td>${block.mass.toFixed(2)}</td>
<td>${signed(state.baselinePositions[index], 2)}</td>
<td>${signed(state.positions[index], 2)}</td>
<td>${signed(shift, 2)}</td>
</tr>
`;
})
.join("");
tableBody.innerHTML =
rows +
`
<tr>
<td>Beam</td>
<td>${BEAM_MASS.toFixed(2)}</td>
<td>0.00</td>
<td>0.00</td>
<td>0.00</td>
</tr>
`;
}
function updateUI(comX, baselineComX, torque) {
const selected = blocks[state.selectedIndex];
const baselineTorqueValue = torqueAboutSupport(baselineComX, state.support);
const comShift = comX - baselineComX;
const balanced = Math.abs(torque) <= BALANCE_TOLERANCE;
selectedSwatch.style.background = selected.color;
selectedName.textContent = selected.name;
selectedMass.textContent = `${selected.mass.toFixed(1)} kg`;
supportRange.value = state.support.toFixed(2);
supportValue.textContent = `${signed(state.support, 2)} m`;
comValue.textContent = `${signed(comX, 3)} m`;
comDelta.textContent = `${signed(comShift, 2)} m vs baseline`;
torqueValue.textContent = `${signed(torque, 2)} N·m`;
if (balanced) {
torqueDirection.textContent = "Balanced · no net rotation";
balanceRow.dataset.state = "balanced";
balancePill.textContent = "Balanced";
balanceText.textContent =
"The center of mass is directly above the support.";
} else {
const direction = torque < 0 ? "Clockwise" : "Counterclockwise";
const side = comX > state.support ? "right" : "left";
torqueDirection.textContent = `${direction} rotation`;
balanceRow.dataset.state = "unbalanced";
balancePill.textContent = direction;
balanceText.textContent =
`The center of mass is ${side} of the support, producing ${direction.toLowerCase()} torque.`;
}
baselineTorque.textContent = `${signed(baselineTorqueValue, 2)} N·m`;
currentTorque.textContent = `${signed(torque, 2)} N·m`;
supportNote.textContent =
`Both torque values use the chosen support at ${signed(state.support, 2)} m.`;
updateTable(comX, baselineComX);
}
function updateAll() {
const comX = centerOfMass(state.positions);
const baselineComX = centerOfMass(state.baselinePositions);
const torque = torqueAboutSupport(comX, state.support);
updateBlockGraphics();
updateSupportGraphics();
updateComGraphics(comX);
updateTorqueGraphics(torque);
updateUI(comX, baselineComX, torque);
}
// -------------------------------------------------------------------------
// Constrained block movement
// -------------------------------------------------------------------------
function constrainedPosition(index, proposed) {
const block = blocks[index];
const sortedIndices = blocks
.map((_, i) => i)
.sort((a, b) => state.positions[a] - state.positions[b]);
const orderIndex = sortedIndices.indexOf(index);
const previousIndex =
orderIndex > 0 ? sortedIndices[orderIndex - 1] : null;
const nextIndex =
orderIndex < sortedIndices.length - 1
? sortedIndices[orderIndex + 1]
: null;
let minimum = -BLOCK_LIMIT;
let maximum = BLOCK_LIMIT;
if (previousIndex !== null) {
const previous = blocks[previousIndex];
minimum =
state.positions[previousIndex] +
(previous.width + block.width) / 2 +
0.14;
}
if (nextIndex !== null) {
const next = blocks[nextIndex];
maximum =
state.positions[nextIndex] -
(next.width + block.width) / 2 -
0.14;
}
minimum = Math.max(minimum, -BLOCK_LIMIT);
maximum = Math.min(maximum, BLOCK_LIMIT);
return THREE.MathUtils.clamp(proposed, minimum, maximum);
}
function moveBlock(index, proposed) {
state.positions[index] = constrainedPosition(index, proposed);
updateAll();
}
// -------------------------------------------------------------------------
// Direct camera controls and pointer interaction
// -------------------------------------------------------------------------
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const dragPlane = new THREE.Plane(new THREE.Vector3(0, 0, 1), 0);
const planePoint = new THREE.Vector3();
let interaction = null;
function updatePointer(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 findInteractiveHit() {
return raycaster.intersectObjects(interactiveObjects, false)[0] || null;
}
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
updatePointer(event);
const hit = findInteractiveHit();
if (hit && hit.object.userData.type === "block") {
const index = hit.object.userData.index;
state.selectedIndex = index;
if (raycaster.ray.intersectPlane(dragPlane, planePoint)) {
interaction = {
type: "block",
index,
offsetX: planePoint.x - state.positions[index]
};
}
} else if (hit && hit.object.userData.type === "support") {
if (raycaster.ray.intersectPlane(dragPlane, planePoint)) {
interaction = {
type: "support",
offsetX: planePoint.x - state.support
};
}
} else {
interaction = {
type: "orbit",
x: event.clientX,
y: event.clientY
};
}
canvas.setPointerCapture(event.pointerId);
canvas.style.cursor = interaction?.type === "orbit" ? "grabbing" : "move";
updateAll();
});
canvas.addEventListener("pointermove", (event) => {
updatePointer(event);
if (!interaction) {
const hit = findInteractiveHit();
canvas.style.cursor = hit ? "move" : "grab";
return;
}
if (interaction.type === "orbit") {
const deltaX = event.clientX - interaction.x;
const deltaY = event.clientY - interaction.y;
cameraState.yaw = THREE.MathUtils.clamp(
cameraState.yaw - deltaX * 0.006,
-1.12,
1.12
);
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + deltaY * 0.005,
0.16,
1.08
);
interaction.x = event.clientX;
interaction.y = event.clientY;
updateCamera();
return;
}
if (!raycaster.ray.intersectPlane(dragPlane, planePoint)) return;
if (interaction.type === "block") {
moveBlock(
interaction.index,
planePoint.x - interaction.offsetX
);
} else if (interaction.type === "support") {
state.support = THREE.MathUtils.clamp(
planePoint.x - interaction.offsetX,
-3.4,
3.4
);
updateAll();
}
});
function endPointerInteraction(event) {
interaction = null;
canvas.style.cursor = "grab";
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endPointerInteraction);
canvas.addEventListener("pointercancel", endPointerInteraction);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.radius = THREE.MathUtils.clamp(
cameraState.radius + event.deltaY * 0.008,
6.6,
16.5
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("contextmenu", (event) => event.preventDefault());
// -------------------------------------------------------------------------
// Buttons, slider, and keyboard nudging
// -------------------------------------------------------------------------
supportRange.addEventListener("input", (event) => {
state.support = Number(event.target.value);
updateAll();
});
alignButton.addEventListener("click", () => {
state.support = centerOfMass(state.positions);
updateAll();
});
captureButton.addEventListener("click", () => {
state.baselinePositions = [...state.positions];
updateAll();
});
resetButton.addEventListener("click", () => {
state.positions = [...originalPositions];
state.baselinePositions = [...originalPositions];
state.support = originalSupport;
state.selectedIndex = 0;
updateAll();
});
nudgeLeft.addEventListener("click", () => {
moveBlock(state.selectedIndex, state.positions[state.selectedIndex] - 0.1);
});
nudgeRight.addEventListener("click", () => {
moveBlock(state.selectedIndex, state.positions[state.selectedIndex] + 0.1);
});
document.addEventListener("keydown", (event) => {
const tag = document.activeElement?.tagName;
if (tag === "INPUT" || tag === "TEXTAREA" || tag === "BUTTON") return;
if (event.key === "ArrowLeft" || event.key === "ArrowRight") {
event.preventDefault();
const amount = event.shiftKey ? 0.5 : 0.1;
const direction = event.key === "ArrowLeft" ? -1 : 1;
moveBlock(
state.selectedIndex,
state.positions[state.selectedIndex] + direction * amount
);
}
});
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
function onResize() {
const width = window.innerWidth;
const height = window.innerHeight;
camera.aspect = width / height;
camera.updateProjectionMatrix();
renderer.setSize(width, height);
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
}
window.addEventListener("resize", onResize);
updateAll();
loading.classList.add("hidden");
function animate(time) {
requestAnimationFrame(animate);
const pulse = 1 + Math.sin(time * 0.0028) * 0.045;
comRing.scale.setScalar(pulse);
comDiamond.rotation.y = time * 0.00055;
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```