Prompt specification
Build or customize the Three.js 3D scene "Mass-independent ideal pendulum comparison" 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-independent ideal pendulum comparison
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/mass-independent-ideal-pendulum-comparison-x1414
Scene Description Prompt:
Compare stylized equal-length pendulums with different masses but equal periods under ideal small-angle assumptions. Make one HTML file using Three.js from cdnjs.
Working Three.js Starter (mass-independent-ideal-pendulum-comparison-x1414):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Equal Pendulum Periods — Different Masses</title>
<style>
:root {
color-scheme: dark;
--bg: #070b14;
--panel: rgba(13, 19, 33, 0.82);
--panel-border: rgba(255, 255, 255, 0.11);
--text: #f5f7fb;
--muted: #98a5ba;
--accent: #79e2ff;
--accent-2: #a78bfa;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 24% 18%, rgba(45, 212, 255, 0.11), transparent 33%),
radial-gradient(circle at 78% 30%, rgba(167, 139, 250, 0.12), transparent 34%),
linear-gradient(150deg, #0a1020 0%, #070b14 55%, #0b0d18 100%);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button,
input {
font: inherit;
}
#scene {
position: fixed;
inset: 0;
}
#scene canvas {
display: block;
width: 100%;
height: 100%;
cursor: grab;
touch-action: none;
outline: none;
}
#scene canvas:active {
cursor: grabbing;
}
.vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
linear-gradient(to bottom, rgba(4, 7, 14, 0.18), transparent 30%),
radial-gradient(circle at center, transparent 45%, rgba(2, 5, 10, 0.4) 100%);
z-index: 1;
}
header {
position: fixed;
z-index: 5;
top: 30px;
left: 32px;
width: min(480px, calc(100vw - 64px));
pointer-events: none;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 12px;
color: #a9b7ca;
font-size: 11px;
font-weight: 750;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
width: 24px;
height: 2px;
content: "";
border-radius: 99px;
background: linear-gradient(90deg, var(--accent), var(--accent-2));
box-shadow: 0 0 14px rgba(121, 226, 255, 0.65);
}
h1 {
margin: 0;
font-size: clamp(31px, 4vw, 52px);
font-weight: 720;
line-height: 0.98;
letter-spacing: -0.045em;
}
h1 span {
color: transparent;
background: linear-gradient(90deg, #ffffff 5%, #9cecff 48%, #bba7ff 95%);
-webkit-background-clip: text;
background-clip: text;
}
.subtitle {
max-width: 450px;
margin: 15px 0 0;
color: var(--muted);
font-size: 14px;
line-height: 1.55;
}
.metrics {
position: fixed;
z-index: 5;
top: 30px;
right: 30px;
display: flex;
flex-wrap: wrap;
justify-content: flex-end;
gap: 8px;
max-width: 420px;
}
.metric {
min-width: 112px;
padding: 11px 13px;
border: 1px solid var(--panel-border);
border-radius: 13px;
background: rgba(10, 15, 27, 0.66);
box-shadow: 0 12px 34px rgba(0, 0, 0, 0.15);
backdrop-filter: blur(14px);
}
.metric small {
display: block;
margin-bottom: 4px;
color: #8795aa;
font-size: 9px;
font-weight: 700;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.metric strong {
font-size: 16px;
font-weight: 650;
letter-spacing: -0.02em;
}
.metric strong em {
color: var(--accent);
font-size: 11px;
font-style: normal;
font-weight: 600;
}
.model-card {
position: fixed;
z-index: 5;
top: 122px;
right: 30px;
width: 300px;
padding: 18px;
border: 1px solid var(--panel-border);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 24px 60px rgba(0, 0, 0, 0.25);
backdrop-filter: blur(20px);
}
.card-title {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
margin-bottom: 15px;
}
.card-title h2 {
margin: 0;
font-size: 14px;
font-weight: 700;
letter-spacing: -0.01em;
}
.live-badge {
display: flex;
align-items: center;
gap: 6px;
color: #8be9bd;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.11em;
text-transform: uppercase;
}
.live-badge::before {
width: 6px;
height: 6px;
content: "";
border-radius: 50%;
background: #75e6ad;
box-shadow: 0 0 10px rgba(117, 230, 173, 0.9);
}
.equation {
padding: 12px 13px;
border: 1px solid rgba(121, 226, 255, 0.12);
border-radius: 12px;
background: rgba(121, 226, 255, 0.045);
color: #dce9f8;
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
font-size: 12px;
line-height: 1.65;
}
.equation strong {
color: var(--accent);
font-weight: 600;
}
.note {
margin: 11px 2px 0;
color: #8e9bb0;
font-size: 11px;
line-height: 1.5;
}
.trace-wrap {
position: relative;
margin-top: 15px;
}
#trace {
display: block;
width: 100%;
height: 86px;
}
.legend {
display: flex;
gap: 13px;
margin-top: 5px;
color: #9aa8bb;
font-size: 9px;
font-weight: 650;
}
.legend span {
display: flex;
align-items: center;
gap: 5px;
}
.legend i {
width: 13px;
height: 2px;
border-radius: 99px;
}
.energy {
margin-top: 16px;
padding-top: 14px;
border-top: 1px solid rgba(255, 255, 255, 0.08);
}
.energy-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 10px;
color: #9aa8ba;
font-size: 10px;
font-weight: 650;
}
.energy-head strong {
color: #dce5f2;
font-weight: 650;
}
.energy-values {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 7px;
}
.energy-values div {
padding: 8px 5px;
border: 1px solid rgba(255, 255, 255, 0.075);
border-radius: 9px;
background: rgba(255, 255, 255, 0.025);
text-align: center;
}
.energy-values small {
display: block;
margin-bottom: 3px;
color: #8492a6;
font-size: 9px;
}
.energy-values strong {
font-size: 11px;
font-weight: 650;
}
#labels {
position: fixed;
inset: 0;
z-index: 3;
overflow: hidden;
pointer-events: none;
}
.bob-label {
position: absolute;
min-width: 82px;
padding: 7px 9px;
border: 1px solid rgba(255, 255, 255, 0.13);
border-radius: 10px;
background: rgba(8, 13, 24, 0.78);
box-shadow: 0 9px 28px rgba(0, 0, 0, 0.3);
backdrop-filter: blur(10px);
transform: translate(-50%, -100%);
text-align: center;
white-space: nowrap;
}
.bob-label .mass {
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
font-size: 11px;
font-weight: 700;
}
.bob-label .mass i {
width: 7px;
height: 7px;
border-radius: 50%;
box-shadow: 0 0 9px currentColor;
}
.bob-label small {
display: block;
margin-top: 3px;
color: #8f9db0;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 9px;
}
.controls {
position: fixed;
z-index: 6;
bottom: 26px;
left: 50%;
width: min(720px, calc(100vw - 40px));
padding: 14px;
border: 1px solid var(--panel-border);
border-radius: 19px;
background: rgba(10, 15, 27, 0.84);
box-shadow: 0 24px 70px rgba(0, 0, 0, 0.35);
backdrop-filter: blur(22px);
transform: translateX(-50%);
}
.control-row {
display: grid;
grid-template-columns: auto minmax(200px, 1fr) auto;
align-items: center;
gap: 17px;
}
.button-group {
display: flex;
gap: 7px;
}
button {
min-height: 38px;
padding: 0 13px;
border: 1px solid rgba(255, 255, 255, 0.11);
border-radius: 10px;
background: rgba(255, 255, 255, 0.055);
color: #e5ecf5;
font-size: 11px;
font-weight: 650;
cursor: pointer;
transition: 160ms ease;
}
button:hover {
border-color: rgba(121, 226, 255, 0.35);
background: rgba(121, 226, 255, 0.09);
transform: translateY(-1px);
}
button.primary {
border-color: rgba(121, 226, 255, 0.28);
background: rgba(121, 226, 255, 0.13);
color: #bff3ff;
}
.amplitude-control {
min-width: 0;
}
.amplitude-label {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 7px;
color: #93a1b5;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.amplitude-label output {
color: #dce8f5;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 10px;
letter-spacing: 0;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
appearance: none;
border-radius: 99px;
background: linear-gradient(
90deg,
var(--accent) 0%,
var(--accent) var(--range-progress, 47%),
rgba(255, 255, 255, 0.12) var(--range-progress, 47%)
);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 14px;
height: 14px;
appearance: none;
border: 2px solid #dffaff;
border-radius: 50%;
background: #78ddf7;
box-shadow: 0 0 13px rgba(121, 226, 255, 0.65);
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 2px solid #dffaff;
border-radius: 50%;
background: #78ddf7;
box-shadow: 0 0 13px rgba(121, 226, 255, 0.65);
}
.period-readout {
min-width: 112px;
padding-left: 16px;
border-left: 1px solid rgba(255, 255, 255, 0.09);
}
.period-readout small {
display: block;
margin-bottom: 3px;
color: #8492a7;
font-size: 9px;
font-weight: 750;
letter-spacing: 0.1em;
text-transform: uppercase;
}
.period-readout strong {
font-size: 20px;
font-weight: 650;
letter-spacing: -0.04em;
}
.period-readout strong span {
color: var(--accent);
font-size: 11px;
letter-spacing: 0;
}
.phase-row {
display: flex;
align-items: center;
gap: 11px;
margin-top: 12px;
}
.phase-track {
position: relative;
flex: 1;
height: 3px;
overflow: visible;
border-radius: 99px;
background: rgba(255, 255, 255, 0.09);
}
.phase-fill {
width: 0;
height: 100%;
border-radius: inherit;
background: linear-gradient(90deg, var(--accent), var(--accent-2));
}
.phase-dot {
position: absolute;
top: 50%;
left: 0;
width: 8px;
height: 8px;
border: 2px solid #e9fbff;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 11px rgba(121, 226, 255, 0.75);
transform: translate(-50%, -50%);
}
.phase-text {
min-width: 74px;
color: #7f8da2;
font-family: "SFMono-Regular", Consolas, monospace;
font-size: 9px;
text-align: right;
}
.camera-hint {
position: fixed;
z-index: 4;
right: 31px;
bottom: 28px;
color: rgba(185, 200, 220, 0.47);
font-size: 9px;
font-weight: 650;
letter-spacing: 0.07em;
pointer-events: none;
text-transform: uppercase;
}
@media (max-width: 1050px) {
.model-card {
top: 116px;
width: 270px;
}
.camera-hint {
display: none;
}
}
@media (max-width: 780px) {
header {
top: 20px;
left: 20px;
}
.subtitle {
max-width: 330px;
font-size: 12px;
}
.metrics,
.model-card {
display: none;
}
.controls {
bottom: 14px;
width: calc(100vw - 24px);
padding: 12px;
}
.control-row {
grid-template-columns: 1fr auto;
gap: 12px;
}
.amplitude-control {
grid-column: 1 / -1;
grid-row: 1;
}
.button-group {
grid-column: 1;
grid-row: 2;
}
.period-readout {
grid-column: 2;
grid-row: 2;
}
.bob-label {
min-width: 67px;
padding: 6px 7px;
}
.bob-label .mass {
font-size: 9px;
}
}
@media (max-width: 480px) {
h1 {
font-size: 32px;
}
.subtitle {
max-width: 280px;
}
button {
padding: 0 10px;
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="vignette"></div>
<header>
<div class="eyebrow">Mechanics Lab · Pendulum Comparison</div>
<h1>Same swing.<br /><span>Different masses.</span></h1>
<p class="subtitle">
Under the ideal small-angle model, mass cancels from the equation of motion.
All three pendulums have the same length, amplitude, and period.
</p>
</header>
<div class="metrics" aria-label="Model measurements">
<div class="metric">
<small>Length · pivot to center</small>
<strong>2.00 <em>m</em></strong>
</div>
<div class="metric">
<small>Shared period</small>
<strong>2.84 <em>s</em></strong>
</div>
<div class="metric">
<small>Gravity</small>
<strong>9.81 <em>m/s²</em></strong>
</div>
</div>
<aside class="model-card">
<div class="card-title">
<h2>Why the periods match</h2>
<div class="live-badge">Live model</div>
</div>
<div class="equation">
θ(t) = A cos(√(g/L) t)<br />
T = 2π√(L/g) = <strong>2.84 s</strong><br />
<span style="color:#8090a6">mass m is not present</span>
</div>
<p class="note">
The traces coincide: changing mass changes the bob’s inertia and energy,
but not its angular acceleration.
</p>
<div class="trace-wrap">
<canvas id="trace" aria-label="Angular position traces for all three masses"></canvas>
<div class="legend">
<span><i style="background:#f4ad63"></i>0.5 kg</span>
<span><i style="background:#68d9f3"></i>2 kg</span>
<span><i style="background:#ad8cff"></i>8 kg</span>
</div>
</div>
<div class="energy">
<div class="energy-head">
<span>Approx. maximum energy</span>
<strong>scales with mass</strong>
</div>
<div class="energy-values">
<div><small>0.5 kg</small><strong id="energy-0">0.22 J</strong></div>
<div><small>2 kg</small><strong id="energy-1">0.86 J</strong></div>
<div><small>8 kg</small><strong id="energy-2">3.44 J</strong></div>
</div>
</div>
</aside>
<div id="labels" aria-hidden="true"></div>
<section class="controls" aria-label="Simulation controls">
<div class="control-row">
<div class="button-group">
<button class="primary" id="playPause" type="button">Pause</button>
<button id="reset" type="button">Reset</button>
<button id="resetView" type="button">View</button>
</div>
<div class="amplitude-control">
<label class="amplitude-label" for="amplitude">
<span>Initial amplitude</span>
<output id="amplitudeValue" for="amplitude">12°</output>
</label>
<input
id="amplitude"
type="range"
min="5"
max="18"
step="1"
value="12"
aria-label="Initial angular amplitude in degrees"
/>
</div>
<div class="period-readout">
<small>Shared period</small>
<strong>2.84 <span>seconds</span></strong>
</div>
</div>
<div class="phase-row">
<div class="phase-track" aria-hidden="true">
<div class="phase-fill" id="phaseFill"></div>
<div class="phase-dot" id="phaseDot"></div>
</div>
<div class="phase-text" id="phaseText">phase 0.00</div>
</div>
</section>
<div class="camera-hint">Drag to orbit · Scroll to zoom</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// ---------------------------------------------------------------------
// Physical model: ideal point-mass pendulum in the small-angle limit.
// θ'' + (g/L)θ = 0, so θ(t) = A cos(sqrt(g/L) t).
// ---------------------------------------------------------------------
const LENGTH = 2.0;
const GRAVITY = 9.81;
const PERIOD = 2 * Math.PI * Math.sqrt(LENGTH / GRAVITY);
const OMEGA = Math.sqrt(GRAVITY / LENGTH);
const PIVOT_Y = 2.55;
const pendulumDefs = [
{ mass: 0.5, color: 0xf4ad63, css: "#f4ad63", radius: 0.19 },
{ mass: 2.0, color: 0x68d9f3, css: "#68d9f3", radius: 0.268 },
{ mass: 8.0, color: 0xad8cff, css: "#ad8cff", radius: 0.341 }
];
const pivotXs = [-2.15, 0, 2.15];
let amplitudeDegrees = 12;
let amplitudeRadians = THREE.MathUtils.degToRad(amplitudeDegrees);
let elapsed = 0;
let running = true;
let previousTime = performance.now();
let frame = 0;
// ---------------------------------------------------------------------
// Renderer, scene, and camera.
// ---------------------------------------------------------------------
const scene = new THREE.Scene();
scene.fog = new THREE.Fog(0x080c17, 10, 19);
const camera = new THREE.PerspectiveCamera(
38,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.setClearColor(0x000000, 0);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.18;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
document.querySelector("#scene").appendChild(renderer.domElement);
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute(
"aria-label",
"Interactive three-dimensional comparison of three equal-length pendulums"
);
const orbit = {
radius: 8.7,
theta: 0,
phi: 1.12,
target: new THREE.Vector3(0, 1.35, 0)
};
const initialOrbit = { ...orbit };
function updateCamera() {
const sinPhi = Math.sin(orbit.phi);
camera.position.set(
orbit.target.x + orbit.radius * sinPhi * Math.sin(orbit.theta),
orbit.target.y + orbit.radius * Math.cos(orbit.phi),
orbit.target.z + orbit.radius * sinPhi * Math.cos(orbit.theta)
);
camera.lookAt(orbit.target);
camera.updateMatrixWorld();
}
updateCamera();
// ---------------------------------------------------------------------
// Lighting.
// ---------------------------------------------------------------------
scene.add(new THREE.HemisphereLight(0xc9e8ff, 0x151321, 2.0));
const keyLight = new THREE.DirectionalLight(0xf2f7ff, 4.0);
keyLight.position.set(4.5, 8.0, 6.0);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -7;
keyLight.shadow.camera.right = 7;
keyLight.shadow.camera.top = 7;
keyLight.shadow.camera.bottom = -3;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 20;
keyLight.shadow.bias = -0.0003;
scene.add(keyLight);
const rimLight = new THREE.PointLight(0x8b75ff, 35, 13, 2);
rimLight.position.set(-4.5, 3.0, 3.0);
scene.add(rimLight);
const cyanLight = new THREE.PointLight(0x59dfff, 26, 12, 2);
cyanLight.position.set(4.2, 2.0, 2.8);
scene.add(cyanLight);
// ---------------------------------------------------------------------
// Floor, grid, and support structure.
// ---------------------------------------------------------------------
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(18, 12),
new THREE.MeshStandardMaterial({
color: 0x0b1220,
roughness: 0.83,
metalness: 0.16,
transparent: true,
opacity: 0.92
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.015;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(14, 28, 0x42617c, 0x25354b);
grid.position.y = 0.002;
grid.material.transparent = true;
grid.material.opacity = 0.18;
scene.add(grid);
const structureMaterial = new THREE.MeshStandardMaterial({
color: 0x738296,
metalness: 0.78,
roughness: 0.3
});
const darkMetal = new THREE.MeshStandardMaterial({
color: 0x202a3b,
metalness: 0.7,
roughness: 0.34
});
const beam = new THREE.Mesh(
new THREE.BoxGeometry(7.25, 0.18, 0.28),
structureMaterial
);
beam.position.set(0, 2.93, -0.24);
beam.castShadow = true;
beam.receiveShadow = true;
scene.add(beam);
for (const x of [-3.55, 3.55]) {
const column = new THREE.Mesh(
new THREE.BoxGeometry(0.17, 2.93, 0.22),
structureMaterial
);
column.position.set(x, 1.46, -0.24);
column.castShadow = true;
column.receiveShadow = true;
scene.add(column);
const foot = new THREE.Mesh(
new THREE.BoxGeometry(0.7, 0.12, 0.58),
darkMetal
);
foot.position.set(x, 0.06, -0.24);
foot.castShadow = true;
foot.receiveShadow = true;
scene.add(foot);
}
for (const x of pivotXs) {
const connector = new THREE.Mesh(
new THREE.CylinderGeometry(0.055, 0.055, 0.34, 16),
structureMaterial
);
connector.position.set(x, 2.76, -0.05);
connector.castShadow = true;
scene.add(connector);
const pivotPin = new THREE.Mesh(
new THREE.CylinderGeometry(0.105, 0.105, 0.34, 24),
darkMetal
);
pivotPin.rotation.x = Math.PI / 2;
pivotPin.position.set(x, PIVOT_Y, -0.02);
pivotPin.castShadow = true;
scene.add(pivotPin);
const pivotCap = new THREE.Mesh(
new THREE.SphereGeometry(0.12, 24, 16),
new THREE.MeshPhysicalMaterial({
color: 0xa8b7c9,
metalness: 0.85,
roughness: 0.22,
clearcoat: 0.5
})
);
pivotCap.position.set(x, PIVOT_Y, 0.04);
pivotCap.castShadow = true;
scene.add(pivotCap);
const floorHalo = new THREE.Mesh(
new THREE.RingGeometry(0.35, 0.39, 64),
new THREE.MeshBasicMaterial({
color: 0x70dcf5,
transparent: true,
opacity: 0.11,
side: THREE.DoubleSide
})
);
floorHalo.rotation.x = -Math.PI / 2;
floorHalo.position.set(x, 0.012, 0.04);
scene.add(floorHalo);
}
// ---------------------------------------------------------------------
// Pendulum assemblies.
// ---------------------------------------------------------------------
const rodGeometry = new THREE.CylinderGeometry(0.018, 0.018, 1, 14);
const rodMaterial = new THREE.MeshStandardMaterial({
color: 0xc6d3e0,
metalness: 0.88,
roughness: 0.21
});
const up = new THREE.Vector3(0, 1, 0);
const tempDirection = new THREE.Vector3();
const tempMidpoint = new THREE.Vector3();
function placeRod(mesh, start, end) {
tempDirection.subVectors(end, start);
const length = tempDirection.length();
tempMidpoint.addVectors(start, end).multiplyScalar(0.5);
mesh.position.copy(tempMidpoint);
mesh.scale.set(1, length, 1);
mesh.quaternion.setFromUnitVectors(up, tempDirection.normalize());
}
const pendulums = [];
pendulumDefs.forEach((definition, index) => {
const pivotX = pivotXs[index];
const pivot = new THREE.Vector3(pivotX, PIVOT_Y, 0.03);
const referenceGeometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(pivotX, PIVOT_Y, -0.025),
new THREE.Vector3(pivotX, PIVOT_Y - LENGTH, -0.025)
]);
const reference = new THREE.Line(
referenceGeometry,
new THREE.LineDashedMaterial({
color: 0x8293a8,
transparent: true,
opacity: 0.25,
dashSize: 0.07,
gapSize: 0.055
})
);
reference.computeLineDistances();
scene.add(reference);
const arcPoints = [];
const arcRadius = 0.52;
for (let i = 0; i <= 48; i++) {
const angle = THREE.MathUtils.degToRad(-20 + (40 * i) / 48);
arcPoints.push(
new THREE.Vector3(
pivotX + Math.sin(angle) * arcRadius,
PIVOT_Y - Math.cos(angle) * arcRadius,
0.01
)
);
}
const arc = new THREE.Line(
new THREE.BufferGeometry().setFromPoints(arcPoints),
new THREE.LineBasicMaterial({
color: definition.color,
transparent: true,
opacity: 0.34
})
);
scene.add(arc);
const wedgeGeometry = new THREE.BufferGeometry();
wedgeGeometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(9), 3)
);
const wedge = new THREE.Mesh(
wedgeGeometry,
new THREE.MeshBasicMaterial({
color: definition.color,
transparent: true,
opacity: 0.1,
side: THREE.DoubleSide,
depthWrite: false
})
);
scene.add(wedge);
const rod = new THREE.Mesh(rodGeometry, rodMaterial);
rod.castShadow = true;
scene.add(rod);
const bobGroup = new THREE.Group();
const bobMaterial = new THREE.MeshPhysicalMaterial({
color: definition.color,
metalness: 0.38,
roughness: 0.2,
clearcoat: 0.85,
clearcoatRoughness: 0.18,
emissive: new THREE.Color(definition.color).multiplyScalar(0.07)
});
const bob = new THREE.Mesh(
new THREE.SphereGeometry(definition.radius, 48, 32),
bobMaterial
);
bob.castShadow = true;
bob.receiveShadow = true;
bobGroup.add(bob);
const ring = new THREE.Mesh(
new THREE.TorusGeometry(definition.radius * 1.055, 0.016, 12, 64),
new THREE.MeshBasicMaterial({
color: definition.color,
transparent: true,
opacity: 0.86
})
);
ring.position.z = 0.015;
bobGroup.add(ring);
const centerHighlight = new THREE.Mesh(
new THREE.SphereGeometry(definition.radius * 0.13, 18, 12),
new THREE.MeshBasicMaterial({
color: 0xffffff,
transparent: true,
opacity: 0.85
})
);
centerHighlight.position.set(
-definition.radius * 0.28,
definition.radius * 0.3,
definition.radius * 0.82
);
bobGroup.add(centerHighlight);
scene.add(bobGroup);
const label = document.createElement("div");
label.className = "bob-label";
label.innerHTML = `
<div class="mass">
<i style="background:${definition.css};color:${definition.css}"></i>
${definition.mass} kg
</div>
<small>θ +0.0°</small>
`;
document.querySelector("#labels").appendChild(label);
pendulums.push({
definition,
pivot,
rod,
bobGroup,
wedge,
label,
angleText: label.querySelector("small")
});
});
// ---------------------------------------------------------------------
// Motion trace in a regular 2D canvas.
// ---------------------------------------------------------------------
const traceCanvas = document.querySelector("#trace");
const traceContext = traceCanvas.getContext("2d");
function drawTrace() {
const rect = traceCanvas.getBoundingClientRect();
if (!rect.width || !rect.height) return;
const dpr = Math.min(devicePixelRatio || 1, 2);
const pixelWidth = Math.round(rect.width * dpr);
const pixelHeight = Math.round(rect.height * dpr);
if (traceCanvas.width !== pixelWidth || traceCanvas.height !== pixelHeight) {
traceCanvas.width = pixelWidth;
traceCanvas.height = pixelHeight;
}
const ctx = traceContext;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
const width = rect.width;
const height = rect.height;
const left = 24;
const right = 9;
const top = 10;
const bottom = 15;
const plotWidth = width - left - right;
const plotHeight = height - top - bottom;
const centerY = top + plotHeight / 2;
const maxAngle = THREE.MathUtils.degToRad(20);
ctx.clearRect(0, 0, width, height);
ctx.strokeStyle = "rgba(255,255,255,0.09)";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(left, centerY);
ctx.lineTo(width - right, centerY);
ctx.stroke();
ctx.fillStyle = "rgba(171,185,204,0.52)";
ctx.font = "8px ui-monospace, monospace";
ctx.textAlign = "right";
ctx.fillText("+20°", left - 5, top + 4);
ctx.fillText("0", left - 5, centerY + 3);
ctx.fillText("−20°", left - 5, top + plotHeight + 3);
const graph = (time) => {
const theta = amplitudeRadians * Math.cos(OMEGA * time);
return centerY - (theta / maxAngle) * (plotHeight / 2);
};
// A pale underlay makes the coincident traces readable.
ctx.strokeStyle = "rgba(225,237,250,0.35)";
ctx.lineWidth = 3;
ctx.beginPath();
for (let i = 0; i <= 240; i++) {
const time = (i / 240) * PERIOD * 2;
const x = left + (i / 240) * plotWidth;
const y = graph(time);
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.stroke();
const dashPatterns = [[7, 4], [3, 3], [11, 4, 2, 4]];
pendulumDefs.forEach((definition, index) => {
ctx.strokeStyle = definition.css;
ctx.globalAlpha = 0.88;
ctx.lineWidth = 1.4;
ctx.setLineDash(dashPatterns[index]);
ctx.beginPath();
for (let i = 0; i <= 240; i++) {
const time = (i / 240) * PERIOD * 2;
const x = left + (i / 240) * plotWidth;
const y = graph(time);
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
ctx.stroke();
});
ctx.globalAlpha = 1;
ctx.setLineDash([]);
const phase = (elapsed % PERIOD) / PERIOD;
const currentX = left + phase * plotWidth;
const currentTheta = amplitudeRadians * Math.cos(OMEGA * elapsed);
const currentY = centerY - (currentTheta / maxAngle) * (plotHeight / 2);
ctx.strokeStyle = "rgba(255,255,255,0.2)";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(currentX, top);
ctx.lineTo(currentX, top + plotHeight);
ctx.stroke();
ctx.fillStyle = "#bff5ff";
ctx.beginPath();
ctx.arc(currentX, currentY, 3.2, 0, Math.PI * 2);
ctx.fill();
}
new ResizeObserver(drawTrace).observe(traceCanvas);
// ---------------------------------------------------------------------
// UI controls.
// ---------------------------------------------------------------------
const playPauseButton = document.querySelector("#playPause");
const resetButton = document.querySelector("#reset");
const resetViewButton = document.querySelector("#resetView");
const amplitudeInput = document.querySelector("#amplitude");
const amplitudeValue = document.querySelector("#amplitudeValue");
const phaseFill = document.querySelector("#phaseFill");
const phaseDot = document.querySelector("#phaseDot");
const phaseText = document.querySelector("#phaseText");
function updateRangeProgress() {
const min = Number(amplitudeInput.min);
const max = Number(amplitudeInput.max);
const value = Number(amplitudeInput.value);
const progress = ((value - min) / (max - min)) * 100;
amplitudeInput.style.setProperty("--range-progress", `${progress}%`);
}
function updateEnergyReadout() {
const energyPerKg = 0.5 * GRAVITY * LENGTH * amplitudeRadians ** 2;
pendulumDefs.forEach((definition, index) => {
const joules = energyPerKg * definition.mass;
document.querySelector(`#energy-${index}`).textContent =
`${joules.toFixed(2)} J`;
});
}
updateRangeProgress();
updateEnergyReadout();
amplitudeInput.addEventListener("input", () => {
amplitudeDegrees = Number(amplitudeInput.value);
amplitudeRadians = THREE.MathUtils.degToRad(amplitudeDegrees);
amplitudeValue.textContent = `${amplitudeDegrees}°`;
updateRangeProgress();
updateEnergyReadout();
drawTrace();
});
playPauseButton.addEventListener("click", () => {
running = !running;
playPauseButton.textContent = running ? "Pause" : "Play";
});
resetButton.addEventListener("click", () => {
elapsed = 0;
running = true;
playPauseButton.textContent = "Pause";
});
resetViewButton.addEventListener("click", () => {
orbit.radius = initialOrbit.radius;
orbit.theta = initialOrbit.theta;
orbit.phi = initialOrbit.phi;
orbit.target.copy(initialOrbit.target);
updateCamera();
});
// ---------------------------------------------------------------------
// Direct camera controls: no addons are used.
// ---------------------------------------------------------------------
const pointer = {
active: false,
id: null,
x: 0,
y: 0
};
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
pointer.active = true;
pointer.id = event.pointerId;
pointer.x = event.clientX;
pointer.y = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!pointer.active || event.pointerId !== pointer.id) return;
const dx = event.clientX - pointer.x;
const dy = event.clientY - pointer.y;
pointer.x = event.clientX;
pointer.y = event.clientY;
orbit.theta -= dx * 0.006;
orbit.phi = THREE.MathUtils.clamp(orbit.phi + dy * 0.005, 0.72, 1.5);
});
function endPointer(event) {
if (event.pointerId !== pointer.id) return;
pointer.active = false;
pointer.id = null;
}
renderer.domElement.addEventListener("pointerup", endPointer);
renderer.domElement.addEventListener("pointercancel", endPointer);
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
orbit.radius = THREE.MathUtils.clamp(
orbit.radius + event.deltaY * 0.007,
5.2,
13
);
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", () => {
orbit.radius = initialOrbit.radius;
orbit.theta = initialOrbit.theta;
orbit.phi = initialOrbit.phi;
orbit.target.copy(initialOrbit.target);
updateCamera();
});
renderer.domElement.addEventListener("keydown", (event) => {
const key = event.key;
if (key === "ArrowLeft") orbit.theta -= 0.08;
else if (key === "ArrowRight") orbit.theta += 0.08;
else if (key === "ArrowUp") {
orbit.phi = THREE.MathUtils.clamp(orbit.phi - 0.05, 0.72, 1.5);
} else if (key === "ArrowDown") {
orbit.phi = THREE.MathUtils.clamp(orbit.phi + 0.05, 0.72, 1.5);
} else if (key === "+" || key === "=") {
orbit.radius = Math.max(5.2, orbit.radius - 0.4);
} else if (key === "-" || key === "_") {
orbit.radius = Math.min(13, orbit.radius + 0.4);
} else {
return;
}
event.preventDefault();
updateCamera();
});
// ---------------------------------------------------------------------
// Animation.
// ---------------------------------------------------------------------
const projected = new THREE.Vector3();
const bobPosition = new THREE.Vector3();
const rodEnd = new THREE.Vector3();
function updatePendulums(theta) {
const wedgePositions = [];
pendulums.forEach((pendulum, index) => {
const x =
pendulum.pivot.x + LENGTH * Math.sin(theta);
const y =
pendulum.pivot.y - LENGTH * Math.cos(theta);
bobPosition.set(x, y, 0.055);
pendulum.bobGroup.position.copy(bobPosition);
rodEnd.copy(bobPosition);
placeRod(pendulum.rod, pendulum.pivot, rodEnd);
const wedge = pendulum.wedge;
const positions = wedge.geometry.attributes.position.array;
const radius = 0.48;
positions[0] = pendulum.pivot.x;
positions[1] = pendulum.pivot.y;
positions[2] = 0.012;
positions[3] = pendulum.pivot.x;
positions[4] = pendulum.pivot.y - radius;
positions[5] = 0.012;
positions[6] = pendulum.pivot.x + Math.sin(theta) * radius;
positions[7] = pendulum.pivot.y - Math.cos(theta) * radius;
positions[8] = 0.012;
wedge.geometry.attributes.position.needsUpdate = true;
wedge.geometry.computeVertexNormals();
const angleValue = THREE.MathUtils.radToDeg(theta);
pendulum.angleText.textContent =
`θ ${angleValue >= 0 ? "+" : ""}${angleValue.toFixed(1)}°`;
});
}
function updateLabels() {
const width = innerWidth;
const height = innerHeight;
pendulums.forEach((pendulum) => {
projected.copy(pendulum.bobGroup.position).project(camera);
const x = (projected.x * 0.5 + 0.5) * width;
const y = (-projected.y * 0.5 + 0.5) * height;
const distance = camera.position.distanceTo(pendulum.bobGroup.position);
const pixelsPerUnit =
(height / (2 * Math.tan(THREE.MathUtils.degToRad(camera.fov * 0.5)))) /
distance;
const radiusPixels = pendulum.definition.radius * pixelsPerUnit;
pendulum.label.style.left = `${x}px`;
pendulum.label.style.top = `${y - radiusPixels - 7}px`;
pendulum.label.style.visibility =
projected.z > -1 && projected.z < 1 ? "visible" : "hidden";
});
}
function animate(now) {
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (running) elapsed += delta;
const theta = amplitudeRadians * Math.cos(OMEGA * elapsed);
const phase = (elapsed % PERIOD) / PERIOD;
updateCamera();
updatePendulums(theta);
updateLabels();
phaseFill.style.width = `${phase * 100}%`;
phaseDot.style.left = `${phase * 100}%`;
phaseText.textContent = `phase ${phase.toFixed(2)}`;
if (frame % 2 === 0) drawTrace();
renderer.render(scene, camera);
frame++;
}
renderer.setAnimationLoop(animate);
window.addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
drawTrace();
});
</script>
</body>
</html>
```