Prompt specification
Build or customize the Three.js 3D scene "Small-Angle Swing Period 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: Small-Angle Swing Period Comparison
Category: Games & Play · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/small-angle-swing-period-comparison-x3622
Scene Description Prompt:
Compare two stylized ideal pendulums of different lengths under equal gravity, showing the small-angle period approximation. Three.js from cdnjs, one HTML file.
Working Three.js Starter (small-angle-swing-period-comparison-x3622):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Same Gravity. Different Clocks.</title>
<style>
:root {
color-scheme: dark;
--bg: #07111b;
--panel: rgba(10, 22, 34, 0.78);
--line: rgba(172, 210, 231, 0.14);
--text: #eef8ff;
--muted: #91a8b8;
--cyan: #56d8ff;
--amber: #ffb45f;
--green: #70e6b1;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: var(--bg);
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%;
outline: none;
touch-action: none;
}
.vignette {
position: fixed;
inset: 0;
z-index: 1;
pointer-events: none;
background:
radial-gradient(circle at 48% 42%, transparent 28%, rgba(3, 9, 15, 0.28) 76%),
linear-gradient(180deg, rgba(4, 10, 17, 0.12), rgba(4, 10, 17, 0.36));
}
.hero {
position: fixed;
z-index: 3;
top: 32px;
left: 34px;
width: min(460px, calc(100vw - 430px));
pointer-events: none;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
margin-bottom: 12px;
color: #9ec1d4;
font-size: 10px;
font-weight: 800;
letter-spacing: 0.2em;
text-transform: uppercase;
}
.eyebrow::before {
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--green);
box-shadow: 0 0 16px rgba(112, 230, 177, 0.8);
content: "";
}
h1 {
margin: 0;
font-size: clamp(38px, 4.3vw, 66px);
font-weight: 760;
letter-spacing: -0.055em;
line-height: 0.98;
text-wrap: balance;
}
h1 span {
color: #8eafc2;
font-weight: 470;
}
.hero p {
max-width: 390px;
margin: 18px 0 0;
color: #9eb4c4;
font-size: 14px;
line-height: 1.65;
}
.panel {
position: fixed;
z-index: 5;
top: 24px;
right: 24px;
width: 356px;
max-height: calc(100vh - 48px);
overflow: auto;
padding: 20px;
border: 1px solid var(--line);
border-radius: 20px;
background: var(--panel);
box-shadow:
0 24px 80px rgba(0, 0, 0, 0.32),
inset 0 1px 0 rgba(255, 255, 255, 0.035);
backdrop-filter: blur(20px) saturate(125%);
scrollbar-width: thin;
scrollbar-color: #385064 transparent;
}
.panel-head {
display: flex;
align-items: flex-start;
justify-content: space-between;
gap: 14px;
margin-bottom: 16px;
}
.panel-head .eyebrow {
margin: 0 0 5px;
font-size: 9px;
}
.panel h2 {
margin: 0;
font-size: 20px;
font-weight: 700;
letter-spacing: -0.025em;
}
.g-pill {
flex: 0 0 auto;
padding: 7px 9px;
border: 1px solid rgba(112, 230, 177, 0.24);
border-radius: 9px;
background: rgba(112, 230, 177, 0.07);
color: var(--green);
font-size: 11px;
font-variant-numeric: tabular-nums;
}
.equation {
padding: 13px 14px;
border: 1px solid rgba(86, 216, 255, 0.14);
border-radius: 13px;
background: rgba(86, 216, 255, 0.055);
}
.equation code {
display: block;
color: #dff8ff;
font-family: "SFMono-Regular", Consolas, "Liberation Mono", monospace;
font-size: 13px;
}
.equation small {
display: block;
margin-top: 7px;
color: var(--cyan);
font-family: Georgia, "Times New Roman", serif;
font-size: 16px;
font-style: italic;
}
.metrics {
display: grid;
gap: 17px;
margin: 21px 0 18px;
}
.metric-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
color: #9eb4c4;
font-size: 11px;
}
.metric-name {
display: flex;
align-items: center;
gap: 8px;
color: #dbeaf3;
font-weight: 650;
}
.swatch {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--accent);
box-shadow: 0 0 12px var(--accent);
}
.period-value {
display: flex;
align-items: baseline;
gap: 5px;
margin-top: 6px;
color: #a8bdcb;
font-size: 12px;
}
.period-value b {
color: var(--accent);
font-size: 27px;
font-weight: 720;
letter-spacing: -0.035em;
font-variant-numeric: tabular-nums;
}
.period-value span {
color: #718b9d;
}
.bar {
height: 4px;
margin-top: 9px;
overflow: hidden;
border-radius: 999px;
background: rgba(255, 255, 255, 0.07);
}
.bar i {
display: block;
width: 50%;
height: 100%;
border-radius: inherit;
background: var(--accent);
box-shadow: 0 0 14px var(--accent);
}
.ratio-card {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
padding: 12px 13px;
border: 1px solid var(--line);
border-radius: 12px;
background: rgba(255, 255, 255, 0.025);
color: #a8bdcb;
font-size: 11px;
}
.ratio-card b {
color: #eef8ff;
font-size: 15px;
font-variant-numeric: tabular-nums;
}
.reference {
margin-top: 12px;
padding: 12px 13px;
border-left: 2px solid rgba(255, 180, 95, 0.7);
border-radius: 0 10px 10px 0;
background: rgba(255, 180, 95, 0.055);
}
.reference > div {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
}
.reference span {
color: #d6aa74;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.12em;
}
.reference strong {
color: #ffe2bf;
font-size: 11px;
font-weight: 650;
font-variant-numeric: tabular-nums;
}
.reference p {
margin: 7px 0 0;
color: #9aafbd;
font-size: 10px;
line-height: 1.45;
}
.controls {
margin-top: 19px;
padding-top: 17px;
border-top: 1px solid var(--line);
}
.control-label {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 9px;
color: #a7bbc9;
font-size: 11px;
}
.control-label output {
color: #edf8ff;
font-variant-numeric: tabular-nums;
}
.control-group + .control-group {
margin-top: 15px;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 0;
border-radius: 99px;
outline: none;
background: #263b4a;
accent-color: var(--cyan);
cursor: pointer;
}
input[type="range"]::-webkit-slider-thumb {
width: 15px;
height: 15px;
border: 3px solid #0d1b27;
border-radius: 50%;
background: #dff8ff;
box-shadow: 0 0 0 1px #56d8ff, 0 0 14px rgba(86, 216, 255, 0.5);
appearance: none;
}
input[type="range"]::-moz-range-thumb {
width: 11px;
height: 11px;
border: 3px solid #0d1b27;
border-radius: 50%;
background: #dff8ff;
box-shadow: 0 0 0 1px #56d8ff, 0 0 14px rgba(86, 216, 255, 0.5);
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px;
margin-top: 18px;
}
button {
min-height: 38px;
border: 1px solid var(--line);
border-radius: 10px;
background: rgba(255, 255, 255, 0.045);
color: #dcecf5;
font-size: 11px;
font-weight: 700;
cursor: pointer;
transition:
background 150ms ease,
border-color 150ms ease,
transform 150ms ease;
}
button:hover {
border-color: rgba(86, 216, 255, 0.35);
background: rgba(86, 216, 255, 0.08);
}
button:active {
transform: translateY(1px);
}
button.primary {
border-color: rgba(86, 216, 255, 0.28);
background: rgba(86, 216, 255, 0.11);
color: #c9f4ff;
}
.clock-row {
display: flex;
align-items: baseline;
justify-content: space-between;
margin-top: 16px;
color: #6f899b;
font-size: 9px;
font-weight: 800;
letter-spacing: 0.13em;
}
.clock-row strong {
color: #c9dce8;
font-size: 12px;
letter-spacing: 0;
font-variant-numeric: tabular-nums;
}
.rig-label,
.angle-badge {
position: fixed;
z-index: 2;
pointer-events: none;
transform: translate(-50%, -100%);
}
.rig-label {
display: flex;
align-items: center;
gap: 9px;
min-width: 130px;
padding: 9px 11px;
border: 1px solid rgba(167, 207, 228, 0.14);
border-radius: 11px;
background: rgba(7, 17, 27, 0.72);
box-shadow: 0 10px 28px rgba(0, 0, 0, 0.22);
backdrop-filter: blur(10px);
}
.rig-label .swatch {
flex: 0 0 auto;
width: 7px;
height: 24px;
border-radius: 4px;
}
.rig-label b,
.rig-label small {
display: block;
}
.rig-label b {
color: #e8f5fb;
font-size: 11px;
}
.rig-label small {
margin-top: 2px;
color: #819cac;
font-size: 9px;
font-variant-numeric: tabular-nums;
}
.angle-badge {
padding: 4px 7px;
border: 1px solid color-mix(in srgb, var(--accent) 45%, transparent);
border-radius: 7px;
background: rgba(7, 17, 27, 0.78);
color: var(--accent);
font-size: 10px;
font-weight: 700;
font-variant-numeric: tabular-nums;
transform: translate(13px, -50%);
backdrop-filter: blur(8px);
}
.formula-dock {
position: fixed;
z-index: 3;
left: 50%;
bottom: 24px;
display: flex;
align-items: center;
gap: 12px;
padding: 11px 15px;
border: 1px solid rgba(167, 207, 228, 0.12);
border-radius: 12px;
background: rgba(7, 17, 27, 0.64);
color: #8da6b7;
font-size: 10px;
transform: translateX(-50%);
backdrop-filter: blur(12px);
pointer-events: none;
}
.formula-dock > span:first-child {
font-weight: 800;
letter-spacing: 0.14em;
}
.formula-dock strong {
color: var(--cyan);
font-family: Georgia, "Times New Roman", serif;
font-size: 22px;
font-style: italic;
line-height: 1;
}
.formula-dock b {
color: #e8f5fb;
}
.hint {
position: fixed;
z-index: 3;
left: 34px;
bottom: 27px;
color: #657f91;
font-size: 10px;
letter-spacing: 0.04em;
pointer-events: none;
}
#loading {
position: fixed;
inset: 0;
z-index: 20;
display: grid;
place-content: center;
gap: 8px;
background: #07111b;
color: #dceef7;
text-align: center;
transition: opacity 350ms ease;
}
#loading strong {
font-size: 18px;
}
#loading span {
color: #7e99aa;
font-size: 12px;
}
#loading.is-hidden {
opacity: 0;
pointer-events: none;
}
@media (max-width: 860px) {
.hero {
top: 18px;
left: 18px;
width: calc(100vw - 36px);
}
h1 {
max-width: 370px;
font-size: clamp(33px, 10vw, 48px);
}
.hero p {
display: none;
}
.panel {
top: auto;
right: 12px;
bottom: 12px;
left: 12px;
width: auto;
max-height: 43vh;
padding: 16px;
border-radius: 17px;
}
.formula-dock,
.hint {
display: none;
}
.rig-label {
transform: translate(-50%, -100%) scale(0.9);
}
.angle-badge {
transform: translate(9px, -50%) scale(0.9);
}
}
</style>
</head>
<body>
<div id="scene"></div>
<div class="vignette"></div>
<header class="hero">
<div class="eyebrow">Ideal motion lab · equal gravity</div>
<h1>Same gravity.<br /><span>Different clocks.</span></h1>
<p>
Two pendulums are released together. Their lengths differ, but gravity
does not—revealing the square-root relationship between length and period.
</p>
</header>
<aside class="panel" aria-label="Pendulum comparison controls and measurements">
<div class="panel-head">
<div>
<div class="eyebrow">Simulation model</div>
<h2>Small-angle period</h2>
</div>
<div class="g-pill">g = 9.81 m/s²</div>
</div>
<div class="equation">
<code>θ(t) = θ₀ cos(√(g/L) t)</code>
<small>T ≈ 2π √(L/g)</small>
</div>
<div class="metrics">
<div class="metric" style="--accent: var(--cyan)">
<div class="metric-top">
<span class="metric-name"><i class="swatch"></i>A · short</span>
<span>L = 1.00 m</span>
</div>
<div class="period-value">
T<sub>small</sub> ≈ <b id="periodA">2.006</b><span>s</span>
</div>
<div class="bar"><i id="barA"></i></div>
</div>
<div class="metric" style="--accent: var(--amber)">
<div class="metric-top">
<span class="metric-name"><i class="swatch"></i>B · long</span>
<span>L = 1.60 m</span>
</div>
<div class="period-value">
T<sub>small</sub> ≈ <b id="periodB">2.536</b><span>s</span>
</div>
<div class="bar"><i id="barB"></i></div>
</div>
</div>
<div class="ratio-card">
<span>T<sub>B</sub> / T<sub>A</sub> = √(1.60 / 1.00)</span>
<b>1.265</b>
</div>
<div class="reference">
<div>
<span>NONLINEAR REFERENCE</span>
<strong id="exactText">A 2.018 s · B 2.552 s</strong>
</div>
<p id="errorText"></p>
</div>
<div class="controls">
<div class="control-group">
<label class="control-label" for="amplitude">
<span>Release angle</span>
<output id="amplitudeValue" for="amplitude">14°</output>
</label>
<input
id="amplitude"
type="range"
min="5"
max="30"
step="1"
value="14"
/>
</div>
<div class="control-group">
<label class="control-label" for="speed">
<span>Playback speed</span>
<output id="speedValue" for="speed">0.75×</output>
</label>
<input
id="speed"
type="range"
min="0.25"
max="1.5"
step="0.05"
value="0.75"
/>
</div>
<div class="buttons">
<button id="play" class="primary" type="button">Ⅱ Pause</button>
<button id="reset" type="button">↺ Reset time</button>
</div>
</div>
<div class="clock-row">
<span>SIMULATION TIME</span>
<strong id="clock">0.00 s</strong>
</div>
</aside>
<div id="labelA" class="rig-label" style="--accent: var(--cyan)">
<i class="swatch"></i>
<div>
<b>Pendulum A</b>
<small id="metaA">1.00 m · 0 cycles</small>
</div>
</div>
<div id="labelB" class="rig-label" style="--accent: var(--amber)">
<i class="swatch"></i>
<div>
<b>Pendulum B</b>
<small id="metaB">1.60 m · 0 cycles</small>
</div>
</div>
<div id="angleA" class="angle-badge" style="--accent: var(--cyan)">14.0°</div>
<div id="angleB" class="angle-badge" style="--accent: var(--amber)">14.0°</div>
<div class="formula-dock">
<span>PERIOD SCALES WITH</span>
<strong>√L</strong>
<span>1.60 m has a <b>26.5%</b> longer period</span>
</div>
<div class="hint">Drag to orbit · scroll to zoom · double-click to reset view</div>
<div id="loading">
<strong>Loading Three.js…</strong>
<span>Preparing the pendulum laboratory</span>
</div>
<script>
window.addEventListener("error", () => {
const loading = document.getElementById("loading");
if (loading && loading.dataset.ready !== "true") {
loading.innerHTML =
"<strong>Could not load Three.js.</strong>" +
"<span>Check that the cdnjs connection is available.</span>";
}
});
</script>
<script type="module">
import * as THREE from
"https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
const GRAVITY = 9.81;
const PIVOT_Y = 3.45;
const TRAIL_POINTS = 80;
const container = document.getElementById("scene");
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x07111b);
scene.fog = new THREE.Fog(0x07111b, 9, 23);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
80
);
const renderer = new THREE.WebGLRenderer({
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.08;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.domElement.tabIndex = 0;
renderer.domElement.setAttribute(
"aria-label",
"Interactive three-dimensional pendulum comparison. Drag to orbit and scroll to zoom."
);
container.appendChild(renderer.domElement);
// Lighting
scene.add(new THREE.HemisphereLight(0xc6e8ff, 0x111923, 1.6));
const keyLight = new THREE.DirectionalLight(0xffffff, 3.2);
keyLight.position.set(4.5, 7.5, 5.5);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(1024, 1024);
keyLight.shadow.camera.left = -5;
keyLight.shadow.camera.right = 5;
keyLight.shadow.camera.top = 6;
keyLight.shadow.camera.bottom = -3;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 20;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x55caff, 2.1);
rimLight.position.set(-5, 4, -4);
scene.add(rimLight);
const warmLight = new THREE.DirectionalLight(0xffb267, 1.25);
warmLight.position.set(5, 2.5, -2);
scene.add(warmLight);
// Floor and grid
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(30, 30),
new THREE.MeshStandardMaterial({
color: 0x0a1722,
roughness: 0.86,
metalness: 0.08
})
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.005;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(14, 28, 0x284457, 0x183040);
grid.position.y = 0.008;
grid.material.transparent = true;
grid.material.opacity = 0.28;
scene.add(grid);
// A small field of deterministic particles for depth.
let randomState = 1927;
const random = () => {
randomState = (randomState * 16807) % 2147483647;
return (randomState - 1) / 2147483646;
};
const particlePositions = new Float32Array(240 * 3);
for (let i = 0; i < 240; i++) {
particlePositions[i * 3] = (random() - 0.5) * 14;
particlePositions[i * 3 + 1] = 0.2 + random() * 6.2;
particlePositions[i * 3 + 2] = -2.2 - random() * 5.5;
}
const particleGeometry = new THREE.BufferGeometry();
particleGeometry.setAttribute(
"position",
new THREE.BufferAttribute(particlePositions, 3)
);
const particles = new THREE.Points(
particleGeometry,
new THREE.PointsMaterial({
color: 0x82a5b9,
size: 0.018,
transparent: true,
opacity: 0.32,
depthWrite: false
})
);
scene.add(particles);
const metalMaterial = new THREE.MeshStandardMaterial({
color: 0xb5c8d5,
metalness: 0.82,
roughness: 0.23
});
const supportMaterial = new THREE.MeshStandardMaterial({
color: 0x233746,
metalness: 0.72,
roughness: 0.36
});
const baseMaterial = new THREE.MeshStandardMaterial({
color: 0x172836,
metalness: 0.55,
roughness: 0.48
});
function createStand(x, accentColor) {
const stand = new THREE.Group();
stand.position.x = x;
const post = new THREE.Mesh(
new THREE.CylinderGeometry(0.055, 0.075, PIVOT_Y, 18),
supportMaterial
);
post.position.set(0, PIVOT_Y / 2, -0.3);
post.castShadow = true;
stand.add(post);
const arm = new THREE.Mesh(
new THREE.CylinderGeometry(0.048, 0.048, 0.39, 16),
supportMaterial
);
arm.rotation.x = Math.PI / 2;
arm.position.set(0, PIVOT_Y, -0.16);
arm.castShadow = true;
stand.add(arm);
const foot = new THREE.Mesh(
new THREE.BoxGeometry(0.72, 0.09, 0.62),
baseMaterial
);
foot.position.set(0, 0.045, -0.3);
foot.castShadow = true;
foot.receiveShadow = true;
stand.add(foot);
const accentMaterial = new THREE.MeshStandardMaterial({
color: accentColor,
emissive: accentColor,
emissiveIntensity: 0.45,
metalness: 0.2,
roughness: 0.38
});
const strip = new THREE.Mesh(
new THREE.CylinderGeometry(0.009, 0.009, PIVOT_Y - 0.18, 10),
accentMaterial
);
strip.position.set(0.067, PIVOT_Y / 2, -0.265);
stand.add(strip);
const collar = new THREE.Mesh(
new THREE.TorusGeometry(0.105, 0.018, 10, 36),
accentMaterial
);
collar.rotation.x = Math.PI / 2;
collar.position.set(0, 0.105, -0.3);
stand.add(collar);
return stand;
}
function makeLineGeometry(pointCount) {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.BufferAttribute(new Float32Array(pointCount * 3), 3)
);
return geometry;
}
function createPendulum(config) {
const color = new THREE.Color(config.color);
const root = new THREE.Group();
root.position.set(config.x, PIVOT_Y, 0);
scene.add(root);
scene.add(createStand(config.x, config.color));
const swing = new THREE.Group();
root.add(swing);
const rod = new THREE.Mesh(
new THREE.CylinderGeometry(0.021, 0.028, config.length, 18),
metalMaterial
);
rod.position.y = -config.length / 2;
rod.castShadow = true;
swing.add(rod);
const bobGroup = new THREE.Group();
bobGroup.position.y = -config.length;
swing.add(bobGroup);
const bobMaterial = new THREE.MeshPhysicalMaterial({
color: config.color,
emissive: config.color,
emissiveIntensity: 0.16,
metalness: 0.28,
roughness: 0.2,
clearcoat: 0.9,
clearcoatRoughness: 0.15
});
const bob = new THREE.Mesh(
new THREE.SphereGeometry(0.125, 32, 24),
bobMaterial
);
bob.castShadow = true;
bobGroup.add(bob);
const haloMaterial = new THREE.MeshBasicMaterial({
color: config.color,
transparent: true,
opacity: 0.36,
depthWrite: false
});
const halo = new THREE.Mesh(
new THREE.TorusGeometry(0.165, 0.008, 8, 48),
haloMaterial
);
bobGroup.add(halo);
const bobLight = new THREE.PointLight(config.color, 0.18, 1.2, 2);
bobGroup.add(bobLight);
// Pivot hub
const hub = new THREE.Mesh(
new THREE.CylinderGeometry(0.105, 0.105, 0.12, 32),
supportMaterial
);
hub.rotation.x = Math.PI / 2;
hub.castShadow = true;
root.add(hub);
const hubCap = new THREE.Mesh(
new THREE.CylinderGeometry(0.05, 0.05, 0.135, 24),
new THREE.MeshStandardMaterial({
color: config.color,
emissive: config.color,
emissiveIntensity: 0.35,
metalness: 0.4,
roughness: 0.3
})
);
hubCap.rotation.x = Math.PI / 2;
root.add(hubCap);
// Dashed equilibrium line
const equilibrium = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, 0, -0.025),
new THREE.Vector3(0, -config.length, -0.025)
]),
new THREE.LineDashedMaterial({
color: config.color,
transparent: true,
opacity: 0.28,
dashSize: 0.09,
gapSize: 0.065
})
);
equilibrium.computeLineDistances();
root.add(equilibrium);
// Full possible bob path at the selected amplitude.
const amplitudeArc = new THREE.Line(
makeLineGeometry(65),
new THREE.LineBasicMaterial({
color: config.color,
transparent: true,
opacity: 0.28
})
);
amplitudeArc.frustumCulled = false;
root.add(amplitudeArc);
// Dynamic small-angle indicator around the pivot.
const angleArc = new THREE.Line(
makeLineGeometry(25),
new THREE.LineBasicMaterial({
color: config.color,
transparent: true,
opacity: 0.68
})
);
angleArc.frustumCulled = false;
root.add(angleArc);
const angleRay = new THREE.Line(
makeLineGeometry(2),
new THREE.LineBasicMaterial({
color: config.color,
transparent: true,
opacity: 0.5
})
);
angleRay.frustumCulled = false;
root.add(angleRay);
// Recent motion trail.
const trail = new THREE.Line(
makeLineGeometry(TRAIL_POINTS),
new THREE.LineBasicMaterial({
color: config.color,
transparent: true,
opacity: 0.34
})
);
trail.frustumCulled = false;
root.add(trail);
return {
...config,
period: 2 * Math.PI * Math.sqrt(config.length / GRAVITY),
omega: Math.sqrt(GRAVITY / config.length),
root,
swing,
bob,
bobMaterial,
halo,
bobLight,
amplitudeArc,
angleArc,
angleRay,
trail,
currentTheta: 0,
lastCycle: -1,
label: document.getElementById(config.domLabel),
angleLabel: document.getElementById(config.domAngle),
meta: document.getElementById(config.domMeta)
};
}
const pendulums = [
createPendulum({
id: "A",
name: "Pendulum A",
length: 1.0,
x: -1.42,
color: 0x56d8ff,
domLabel: "labelA",
domAngle: "angleA",
domMeta: "metaA"
}),
createPendulum({
id: "B",
name: "Pendulum B",
length: 1.6,
x: 1.12,
color: 0xffb45f,
domLabel: "labelB",
domAngle: "angleB",
domMeta: "metaB"
})
];
// Complete elliptic integral K(m), used only for the nonlinear reference.
function ellipticK(m) {
let a = 1;
let b = Math.sqrt(1 - m);
let c = Math.sqrt(m);
for (let i = 0; i < 30; i++) {
const nextA = (a + b) / 2;
const nextB = Math.sqrt(a * b);
c = (a - b) / 2;
a = nextA;
b = nextB;
if (Math.abs(c) < 1e-15) break;
}
return Math.PI / (2 * a);
}
const amplitudeInput = document.getElementById("amplitude");
const speedInput = document.getElementById("speed");
const amplitudeValue = document.getElementById("amplitudeValue");
const speedValue = document.getElementById("speedValue");
const playButton = document.getElementById("play");
const resetButton = document.getElementById("reset");
const clockElement = document.getElementById("clock");
let amplitudeDegrees = Number(amplitudeInput.value);
let amplitudeRadians = THREE.MathUtils.degToRad(amplitudeDegrees);
let playbackSpeed = Number(speedInput.value);
let simulationTime = 0;
let playing = true;
let previousTime = performance.now();
function rebuildAmplitudeArc(pendulum) {
const positions = pendulum.amplitudeArc.geometry.attributes.position.array;
const count = positions.length / 3;
for (let i = 0; i < count; i++) {
const angle =
-amplitudeRadians +
(2 * amplitudeRadians * i) / (count - 1);
positions[i * 3] = pendulum.length * Math.sin(angle);
positions[i * 3 + 1] = -pendulum.length * Math.cos(angle);
positions[i * 3 + 2] = -0.018;
}
pendulum.amplitudeArc.geometry.attributes.position.needsUpdate = true;
}
function updateMeasurements() {
const amplitudeDegrees = Number(amplitudeInput.value);
const amplitudeRadians = THREE.MathUtils.degToRad(amplitudeDegrees);
const modulus = Math.sin(amplitudeRadians / 2) ** 2;
const exactFactor = (2 * ellipticK(modulus)) / Math.PI;
amplitudeValue.textContent = `${amplitudeDegrees}°`;
const periodA = pendulums[0].period;
const periodB = pendulums[1].period;
const exactA = periodA * exactFactor;
const exactB = periodB * exactFactor;
const error = (exactFactor - 1) * 100;
document.getElementById("periodA").textContent = periodA.toFixed(3);
document.getElementById("periodB").textContent = periodB.toFixed(3);
document.getElementById("barA").style.width =
`${(periodA / periodB) * 100}%`;
document.getElementById("barB").style.width = "100%";
document.getElementById("exactText").textContent =
`A ${exactA.toFixed(3)} s · B ${exactB.toFixed(3)} s`;
document.getElementById("errorText").textContent =
`At ${amplitudeDegrees}°, the exact nonlinear period is ` +
`${error.toFixed(2)}% longer. Animation uses the small-angle model.`;
}
function resetTrails() {
for (const pendulum of pendulums) {
const positions = pendulum.trail.geometry.attributes.position.array;
const theta = pendulum.currentTheta;
const x = pendulum.length * Math.sin(theta);
const y = -pendulum.length * Math.cos(theta);
for (let i = 0; i < TRAIL_POINTS; i++) {
positions[i * 3] = x;
positions[i * 3 + 1] = y;
positions[i * 3 + 2] = 0.025;
}
pendulum.trail.geometry.attributes.position.needsUpdate = true;
}
}
amplitudeInput.addEventListener("input", () => {
amplitudeRadians = THREE.MathUtils.degToRad(
Number(amplitudeInput.value)
);
updateMeasurements();
for (const pendulum of pendulums) {
rebuildAmplitudeArc(pendulum);
}
resetTrails();
});
speedInput.addEventListener("input", () => {
playbackSpeed = Number(speedInput.value);
speedValue.textContent = `${playbackSpeed.toFixed(2)}×`;
});
playButton.addEventListener("click", () => {
playing = !playing;
playButton.textContent = playing ? "Ⅱ Pause" : "▶ Resume";
});
resetButton.addEventListener("click", () => {
simulationTime = 0;
playing = true;
playButton.textContent = "Ⅱ Pause";
resetTrails();
});
updateMeasurements();
for (const pendulum of pendulums) {
rebuildAmplitudeArc(pendulum);
}
// Direct camera controls: no external controls addon.
const cameraTarget = new THREE.Vector3(-0.12, 1.9, 0);
let azimuth = 0.18;
let polar = 1.22;
let userZoom = 1;
let fitDistance = 7.8;
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
function updateCamera() {
const radius = fitDistance * userZoom;
const horizontalRadius = Math.sin(polar) * radius;
camera.position.set(
cameraTarget.x + horizontalRadius * Math.sin(azimuth),
cameraTarget.y + Math.cos(polar) * radius,
cameraTarget.z + horizontalRadius * Math.cos(azimuth)
);
camera.lookAt(cameraTarget);
}
function resetCamera() {
azimuth = 0.18;
polar = 1.22;
userZoom = 1;
updateCamera();
}
renderer.domElement.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
renderer.domElement.style.cursor = "grabbing";
});
renderer.domElement.addEventListener("pointermove", (event) => {
if (!dragging) return;
const deltaX = event.clientX - previousPointerX;
const deltaY = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
azimuth -= deltaX * 0.006;
polar = THREE.MathUtils.clamp(polar + deltaY * 0.005, 0.72, 1.46);
updateCamera();
});
function endDrag(event) {
dragging = false;
renderer.domElement.style.cursor = "grab";
if (renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("pointerleave", (event) => {
if (dragging && event.buttons === 0) endDrag(event);
});
renderer.domElement.addEventListener(
"wheel",
(event) => {
event.preventDefault();
userZoom = THREE.MathUtils.clamp(
userZoom + event.deltaY * 0.0008,
0.72,
1.7
);
updateCamera();
},
{ passive: false }
);
renderer.domElement.addEventListener("dblclick", resetCamera);
renderer.domElement.addEventListener("keydown", (event) => {
let handled = true;
switch (event.key) {
case "ArrowLeft":
azimuth -= 0.08;
break;
case "ArrowRight":
azimuth += 0.08;
break;
case "ArrowUp":
polar = Math.max(0.72, polar - 0.06);
break;
case "ArrowDown":
polar = Math.min(1.46, polar + 0.06);
break;
case "+":
case "=":
userZoom = Math.max(0.72, userZoom * 0.92);
break;
case "-":
userZoom = Math.min(1.7, userZoom * 1.08);
break;
default:
handled = false;
}
if (handled) {
event.preventDefault();
updateCamera();
}
});
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(width, height);
camera.aspect = width / height;
camera.updateProjectionMatrix();
const halfVerticalFov = THREE.MathUtils.degToRad(camera.fov / 2);
const horizontalFit = 4.6 /
(2 * Math.tan(halfVerticalFov) * camera.aspect);
fitDistance = Math.max(7.8, horizontalFit);
updateCamera();
}
window.addEventListener("resize", resize);
resize();
renderer.domElement.style.cursor = "grab";
const projected = new THREE.Vector3();
function positionLabel(element, worldPosition, offsetY = 0) {
projected.copy(worldPosition).project(camera);
const visible = projected.z > -1 && projected.z < 1;
element.style.opacity = visible ? "1" : "0";
element.style.left = `${(projected.x * 0.5 + 0.5) * window.innerWidth}px`;
element.style.top =
`${(-projected.y * 0.5 + 0.5) * window.innerHeight + offsetY}px`;
}
function updateAngleGuides(pendulum, theta) {
const arcPositions =
pendulum.angleArc.geometry.attributes.position.array;
const rayPositions =
pendulum.angleRay.geometry.attributes.position.array;
const radius = 0.43;
for (let i = 0; i < 25; i++) {
const angle = (theta * i) / 24;
arcPositions[i * 3] = radius * Math.sin(angle);
arcPositions[i * 3 + 1] = -radius * Math.cos(angle);
arcPositions[i * 3 + 2] = 0.045;
}
rayPositions[0] = 0;
rayPositions[1] = 0;
rayPositions[2] = 0.045;
rayPositions[3] = radius * Math.sin(theta);
rayPositions[4] = -radius * Math.cos(theta);
rayPositions[5] = 0.045;
pendulum.angleArc.geometry.attributes.position.needsUpdate = true;
pendulum.angleRay.geometry.attributes.position.needsUpdate = true;
}
function updateTrail(pendulum, theta) {
const positions = pendulum.trail.geometry.attributes.position.array;
positions.copyWithin(0, 3);
positions[(TRAIL_POINTS - 1) * 3] =
pendulum.length * Math.sin(theta);
positions[(TRAIL_POINTS - 1) * 3 + 1] =
-pendulum.length * Math.cos(theta);
positions[(TRAIL_POINTS - 1) * 3 + 2] = 0.025;
pendulum.trail.geometry.attributes.position.needsUpdate = true;
}
const labelPosition = new THREE.Vector3();
const bobPosition = new THREE.Vector3();
function animate(now) {
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (playing) {
simulationTime += delta * playbackSpeed;
}
for (const pendulum of pendulums) {
const theta =
amplitudeRadians * Math.cos(pendulum.omega * simulationTime);
pendulum.currentTheta = theta;
pendulum.swing.rotation.z = theta;
updateAngleGuides(pendulum, theta);
updateTrail(pendulum, theta);
// A brief glow marks passage through the equilibrium point.
const phase = pendulum.omega * simulationTime;
const crossingPulse = Math.abs(Math.sin(phase)) ** 18;
pendulum.bobMaterial.emissiveIntensity =
0.16 + crossingPulse * 1.05;
pendulum.halo.material.opacity =
0.32 + crossingPulse * 0.42;
pendulum.halo.scale.setScalar(1 + crossingPulse * 0.075);
pendulum.bobLight.intensity = 0.18 + crossingPulse * 0.9;
labelPosition.set(
pendulum.x,
PIVOT_Y + 0.45,
0
);
positionLabel(pendulum.label, labelPosition);
bobPosition.set(
pendulum.x + pendulum.length * Math.sin(theta),
PIVOT_Y - pendulum.length * Math.cos(theta),
0
);
positionLabel(pendulum.angleLabel, bobPosition);
pendulum.angleLabel.textContent =
`${THREE.MathUtils.radToDeg(theta).toFixed(1)}°`;
const cycle = Math.floor(simulationTime / pendulum.period + 1e-9);
if (cycle !== pendulum.lastCycle) {
pendulum.lastCycle = cycle;
pendulum.meta.textContent =
`${pendulum.length.toFixed(2)} m · ` +
`${cycle} ${cycle === 1 ? "cycle" : "cycles"}`;
}
}
clockElement.textContent = `${simulationTime.toFixed(2)} s`;
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
resetTrails();
requestAnimationFrame(animate);
const loading = document.getElementById("loading");
loading.dataset.ready = "true";
loading.classList.add("is-hidden");
</script>
</body>
</html>
```