Prompt specification
Build or customize the Three.js 3D scene "Horizontal and vertical spring equilibria" 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: Horizontal and vertical spring equilibria
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/horizontal-and-vertical-spring-equilibria-x1430
Scene Description Prompt:
Please use Three.js from cdnjs for a stylized scene based on this idea: horizontal and vertical spring equilibria. Compare a horizontal oscillator with a hanging mass whose equilibrium is shifted by gravity; measure oscillations relative to the correct equilibrium positions. Return one self-contained HTML file.
Working Three.js Starter (horizontal-and-vertical-spring-equilibria-x1430):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Spring Equilibria — Horizontal vs. Vertical</title>
<style>
:root {
color-scheme: dark;
--bg: #07111f;
--panel: rgba(10, 24, 39, 0.82);
--panel-border: rgba(139, 203, 231, 0.16);
--text: #e9f7ff;
--muted: #8da8b9;
--cyan: #54d8ff;
--amber: #ffb65c;
--green: #71e6bc;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background:
radial-gradient(circle at 48% 38%, #142b40 0%, #0b1726 42%, #050b14 100%);
color: var(--text);
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
}
button, input { font: inherit; }
#stage {
position: fixed;
inset: 0;
}
#stage canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#stage canvas:active { cursor: grabbing; }
#vignette {
position: fixed;
inset: 0;
pointer-events: none;
background:
linear-gradient(180deg, rgba(3, 8, 15, 0.32), transparent 24%, transparent 72%, rgba(3, 8, 15, 0.36)),
radial-gradient(ellipse at center, transparent 55%, rgba(2, 7, 13, 0.28) 100%);
z-index: 2;
}
.panel {
position: fixed;
z-index: 6;
border: 1px solid var(--panel-border);
background: var(--panel);
box-shadow: 0 18px 50px rgba(0, 0, 0, 0.26);
backdrop-filter: blur(16px) saturate(125%);
-webkit-backdrop-filter: blur(16px) saturate(125%);
}
.intro {
top: 18px;
left: 18px;
width: min(440px, calc(100vw - 36px));
padding: 18px 20px 17px;
border-radius: 18px;
}
.eyebrow {
display: flex;
align-items: center;
gap: 9px;
color: var(--cyan);
font-size: 10px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
.eyebrow::before {
content: "";
width: 22px;
height: 2px;
background: var(--cyan);
box-shadow: 0 0 12px var(--cyan);
}
h1 {
margin: 9px 0 6px;
font-size: clamp(24px, 3vw, 34px);
line-height: 1.05;
letter-spacing: -0.045em;
font-weight: 760;
}
.intro p {
margin: 0;
max-width: 390px;
color: var(--muted);
font-size: 13px;
line-height: 1.55;
}
.intro strong { color: #d9f4ff; font-weight: 650; }
.readouts {
top: 18px;
right: 18px;
width: 312px;
padding: 14px;
border-radius: 18px;
display: grid;
gap: 9px;
}
.readout {
padding: 13px 14px;
border-radius: 13px;
border: 1px solid rgba(255, 255, 255, 0.07);
background: rgba(255, 255, 255, 0.025);
}
.readout.horizontal { border-left: 3px solid var(--cyan); }
.readout.vertical { border-left: 3px solid var(--amber); }
.readout-top {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
color: var(--muted);
font-size: 10px;
font-weight: 750;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.readout-value {
margin: 5px 0 2px;
font-variant-numeric: tabular-nums;
font-size: 26px;
line-height: 1;
font-weight: 730;
letter-spacing: -0.035em;
}
.horizontal .readout-value { color: var(--cyan); }
.vertical .readout-value { color: var(--amber); }
.readout-bottom {
display: flex;
justify-content: space-between;
gap: 8px;
margin-top: 8px;
color: var(--muted);
font-size: 11px;
}
.readout-bottom b {
color: #d8eaf3;
font-weight: 650;
font-variant-numeric: tabular-nums;
}
.controls {
left: 18px;
bottom: 18px;
width: 390px;
padding: 15px;
border-radius: 18px;
}
.control-heading {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 11px;
}
.control-heading h2 {
margin: 0;
font-size: 11px;
letter-spacing: 0.14em;
text-transform: uppercase;
color: #cfe6f1;
}
.buttons { display: flex; gap: 7px; }
.button {
border: 1px solid rgba(255, 255, 255, 0.11);
border-radius: 9px;
padding: 7px 10px;
color: #dff4fc;
background: rgba(255, 255, 255, 0.045);
cursor: pointer;
font-size: 11px;
font-weight: 650;
transition: background 150ms ease, border-color 150ms ease, transform 150ms ease;
}
.button:hover {
background: rgba(84, 216, 255, 0.09);
border-color: rgba(84, 216, 255, 0.32);
transform: translateY(-1px);
}
.button.primary {
color: #06131e;
background: var(--cyan);
border-color: var(--cyan);
}
.sliders {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 9px 16px;
}
.slider-row label {
display: flex;
justify-content: space-between;
gap: 8px;
margin-bottom: 4px;
color: var(--muted);
font-size: 10px;
font-weight: 650;
letter-spacing: 0.04em;
}
.slider-row output {
color: #ecfaff;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 5px 0 0;
accent-color: var(--cyan);
cursor: pointer;
}
.equation {
margin-top: 13px;
padding: 10px 12px;
border-radius: 11px;
color: #9db7c6;
background: rgba(2, 9, 17, 0.48);
font-size: 11px;
line-height: 1.5;
}
.equation .formula {
color: #e5f8ff;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 12px;
}
.equation .cyan { color: var(--cyan); }
.equation .amber { color: var(--amber); }
.plot-panel {
right: 18px;
bottom: 18px;
width: 312px;
padding: 13px 13px 10px;
border-radius: 18px;
}
.plot-header {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-bottom: 8px;
}
.plot-header h2 {
margin: 0;
font-size: 10px;
letter-spacing: 0.14em;
text-transform: uppercase;
color: #cfe6f1;
}
.legend {
display: flex;
gap: 10px;
color: var(--muted);
font-size: 9px;
}
.legend span::before {
content: "";
display: inline-block;
width: 12px;
height: 2px;
margin: 0 5px 3px 0;
background: currentColor;
}
.legend .h { color: var(--cyan); }
.legend .v { color: var(--amber); }
#plot {
display: block;
width: 100%;
height: 132px;
border-radius: 10px;
background: rgba(2, 8, 15, 0.45);
}
.plot-foot {
display: flex;
justify-content: space-between;
margin-top: 7px;
color: var(--muted);
font-size: 9px;
}
#labels {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 4;
}
.world-label {
position: fixed;
transform: translate(-50%, -50%);
white-space: nowrap;
pointer-events: none;
transition: opacity 100ms linear;
}
.section-label {
padding: 7px 10px;
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 9px;
color: #d9edf6;
background: rgba(5, 14, 24, 0.76);
backdrop-filter: blur(10px);
font-size: 9px;
font-weight: 780;
letter-spacing: 0.12em;
text-transform: uppercase;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.2);
}
.section-label .number {
margin-right: 6px;
color: var(--cyan);
}
.section-label.vertical .number { color: var(--amber); }
.mass-label {
min-width: 134px;
padding: 8px 10px;
border: 1px solid rgba(84, 216, 255, 0.3);
border-radius: 10px;
background: rgba(5, 17, 28, 0.86);
backdrop-filter: blur(10px);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.24);
}
.mass-label.vertical { border-color: rgba(255, 182, 92, 0.35); }
.mass-label small {
display: block;
color: var(--muted);
font-size: 8px;
letter-spacing: 0.12em;
text-transform: uppercase;
}
.mass-label strong {
display: block;
margin-top: 2px;
color: var(--cyan);
font-size: 14px;
font-variant-numeric: tabular-nums;
}
.mass-label.vertical strong { color: var(--amber); }
.small-label {
padding: 4px 7px;
border-radius: 7px;
color: #a9c0cc;
background: rgba(4, 13, 22, 0.7);
border: 1px solid rgba(255, 255, 255, 0.08);
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
font-size: 9px;
}
.small-label.cyan { color: var(--cyan); }
.small-label.amber { color: var(--amber); }
.hint {
position: fixed;
left: 50%;
bottom: 22px;
transform: translateX(-50%);
z-index: 5;
padding: 7px 11px;
border-radius: 999px;
color: #7893a3;
background: rgba(5, 13, 22, 0.58);
border: 1px solid rgba(255, 255, 255, 0.06);
font-size: 9px;
letter-spacing: 0.06em;
pointer-events: none;
}
@media (max-width: 900px) {
.intro {
top: 10px;
left: 10px;
right: 10px;
width: auto;
padding: 13px 15px;
}
.intro p { display: none; }
h1 { margin-bottom: 0; font-size: 24px; }
.readouts {
top: 92px;
right: 10px;
width: 250px;
padding: 9px;
}
.readout { padding: 9px 10px; }
.readout-value { font-size: 21px; }
.controls {
left: 10px;
bottom: 10px;
width: min(390px, calc(100vw - 20px));
padding: 11px;
}
.plot-panel, .hint { display: none; }
.equation { display: none; }
}
@media (max-width: 560px) {
.readouts {
top: auto;
bottom: 238px;
left: 10px;
right: 10px;
width: auto;
grid-template-columns: 1fr 1fr;
}
.readout-bottom { flex-direction: column; gap: 2px; }
.sliders { grid-template-columns: 1fr; max-height: 130px; overflow: auto; }
.section-label { display: none; }
.mass-label { min-width: 112px; }
}
</style>
</head>
<body>
<div id="stage"></div>
<div id="vignette"></div>
<div id="labels">
<div id="label-h-section" class="world-label section-label">
<span class="number">01</span> Horizontal oscillator
</div>
<div id="label-v-section" class="world-label section-label vertical">
<span class="number">02</span> Vertical + gravity
</div>
<div id="label-h-mass" class="world-label mass-label">
<small>Relative displacement</small>
<strong id="hMassReadout">+0.000 m</strong>
</div>
<div id="label-v-mass" class="world-label mass-label vertical">
<small>Relative displacement</small>
<strong id="vMassReadout">+0.000 m</strong>
</div>
<div id="label-h-eq" class="world-label small-label cyan">x_eq</div>
<div id="label-v-eq" class="world-label small-label amber">y_eq</div>
<div id="label-natural" class="world-label small-label">no-load y</div>
<div id="label-shift" class="world-label small-label amber">Δy_eq</div>
<div id="label-gravity" class="world-label small-label amber">g</div>
</div>
<header class="panel intro">
<div class="eyebrow">Mechanics Lab · Equilibrium</div>
<h1>Same motion. Different origin.</h1>
<p>
Both masses obey <strong>q̈ + (k/m)q = 0</strong>. The horizontal spring has no
constant force shifting its equilibrium, while gravity moves the vertical
equilibrium downward by <strong>mg/k</strong>.
</p>
</header>
<section class="panel readouts">
<div class="readout horizontal">
<div class="readout-top">
<span>Horizontal</span>
<span>qₕ = x − x<sub>eq</sub></span>
</div>
<div id="hDisp" class="readout-value">+0.000 m</div>
<div class="readout-bottom">
<span>equilibrium shift</span>
<b id="hShift">0.000 m</b>
</div>
</div>
<div class="readout vertical">
<div class="readout-top">
<span>Vertical</span>
<span>qᵥ = y − y<sub>eq</sub></span>
</div>
<div id="vDisp" class="readout-value">+0.000 m</div>
<div class="readout-bottom">
<span>equilibrium shift</span>
<b id="vShift">−0.000 m</b>
</div>
</div>
</section>
<section class="panel controls">
<div class="control-heading">
<h2>Experiment parameters</h2>
<div class="buttons">
<button id="pauseButton" class="button primary">Pause</button>
<button id="resetButton" class="button">Reset</button>
<button id="viewButton" class="button" title="Reset camera">View</button>
</div>
</div>
<div class="sliders">
<div class="slider-row">
<label for="gravity">Gravity <output id="gravityValue">9.81 m/s²</output></label>
<input id="gravity" type="range" min="0" max="20" step="0.01" value="9.81" />
</div>
<div class="slider-row">
<label for="stiffness">Spring k <output id="stiffnessValue">35 N/m</output></label>
<input id="stiffness" type="range" min="15" max="80" step="1" value="35" />
</div>
<div class="slider-row">
<label for="mass">Mass m <output id="massValue">1.20 kg</output></label>
<input id="mass" type="range" min="0.5" max="3" step="0.05" value="1.2" />
</div>
<div class="slider-row">
<label for="amplitude">Amplitude A <output id="amplitudeValue">0.28 m</output></label>
<input id="amplitude" type="range" min="0.05" max="0.42" step="0.01" value="0.28" />
</div>
</div>
<div class="equation">
<div class="formula">
<span class="cyan">qₕ = x − x<sub>eq</sub></span> ·
<span class="amber">qᵥ = y − y<sub>eq</sub></span> ·
q̈ + (k/m)q = 0
</div>
<div>
Frequency: <strong id="frequency">0.86 Hz</strong>
· Vertical extension: <strong id="extension">0.337 m</strong>
</div>
</div>
</section>
<section class="panel plot-panel">
<div class="plot-header">
<h2>Relative displacement</h2>
<div class="legend">
<span class="h">horizontal</span>
<span class="v">vertical</span>
</div>
</div>
<canvas id="plot"></canvas>
<div class="plot-foot">
<span>6 second window</span>
<span>center line = correct equilibrium</span>
</div>
</section>
<div class="hint">DRAG TO ORBIT · SCROLL TO ZOOM · SPACE TO PAUSE</div>
<script type="module">
import * as THREE from "https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js";
// -------------------------------------------------------------------------
// DOM and state
// -------------------------------------------------------------------------
const $ = id => document.getElementById(id);
const gravityInput = $("gravity");
const stiffnessInput = $("stiffness");
const massInput = $("mass");
const amplitudeInput = $("amplitude");
const state = {
gravity: Number(gravityInput.value),
stiffness: Number(stiffnessInput.value),
mass: Number(massInput.value),
amplitude: Number(amplitudeInput.value),
running: true,
phase: 0,
time: 0,
extension: 0,
frequency: 0,
qH: 0,
qV: 0
};
const palette = {
cyan: 0x54d8ff,
amber: 0xffb65c,
green: 0x71e6bc,
dark: 0x07111f
};
// -------------------------------------------------------------------------
// Renderer, camera, and lighting
// -------------------------------------------------------------------------
const stage = $("stage");
const renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: 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.12;
stage.appendChild(renderer.domElement);
const scene = new THREE.Scene();
scene.fog = new THREE.FogExp2(0x07111f, 0.034);
const camera = new THREE.PerspectiveCamera(
42,
window.innerWidth / window.innerHeight,
0.1,
100
);
const cameraState = {
yaw: 0.28,
pitch: 0.27,
distance: 11.3,
target: new THREE.Vector3(0, 0.92, 0)
};
const hemisphere = new THREE.HemisphereLight(0xc8ecff, 0x07101c, 1.8);
scene.add(hemisphere);
const keyLight = new THREE.DirectionalLight(0xffffff, 2.5);
keyLight.position.set(3.5, 7.5, 6.5);
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 = -5;
keyLight.shadow.camera.near = 0.5;
keyLight.shadow.camera.far = 24;
keyLight.shadow.bias = -0.00025;
scene.add(keyLight);
const cyanLight = new THREE.PointLight(palette.cyan, 13, 8, 2);
cyanLight.position.set(-3.5, 2.0, 3.2);
scene.add(cyanLight);
const amberLight = new THREE.PointLight(palette.amber, 13, 8, 2);
amberLight.position.set(3.5, 2.1, 3.0);
scene.add(amberLight);
// -------------------------------------------------------------------------
// Materials and geometry helpers
// -------------------------------------------------------------------------
const floorMaterial = new THREE.MeshStandardMaterial({
color: 0x081522,
roughness: 0.93,
metalness: 0.05
});
const platformMaterial = new THREE.MeshStandardMaterial({
color: 0x0d2232,
roughness: 0.7,
metalness: 0.24
});
const supportMaterial = new THREE.MeshStandardMaterial({
color: 0x193447,
roughness: 0.38,
metalness: 0.7
});
function addEdges(mesh, color = 0x3a708a, opacity = 0.55) {
const edge = new THREE.LineSegments(
new THREE.EdgesGeometry(mesh.geometry, 25),
new THREE.LineBasicMaterial({
color,
transparent: true,
opacity
})
);
edge.renderOrder = 2;
mesh.add(edge);
return edge;
}
function addBox(width, height, depth, x, y, z, material, edgeColor) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(width, height, depth),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
if (edgeColor !== undefined) addEdges(mesh, edgeColor, 0.45);
scene.add(mesh);
return mesh;
}
function roundedRectangleShape(width, height, radius) {
const shape = new THREE.Shape();
const x = -width / 2;
const y = -height / 2;
shape.moveTo(x + radius, y);
shape.lineTo(x + width - radius, y);
shape.quadraticCurveTo(x + width, y, x + width, y + radius);
shape.lineTo(x + width, y + height - radius);
shape.quadraticCurveTo(
x + width,
y + height,
x + width - radius,
y + height
);
shape.lineTo(x + radius, y + height);
shape.quadraticCurveTo(x, y + height, x, y + height - radius);
shape.lineTo(x, y + radius);
shape.quadraticCurveTo(x, y, x + radius, y);
return shape;
}
function createMass(color) {
const group = new THREE.Group();
const geometry = new THREE.ExtrudeGeometry(
roundedRectangleShape(0.78, 0.64, 0.13),
{
depth: 0.42,
bevelEnabled: true,
bevelSegments: 3,
steps: 1,
bevelSize: 0.055,
bevelThickness: 0.055,
curveSegments: 10
}
);
geometry.center();
const body = new THREE.Mesh(
geometry,
new THREE.MeshPhysicalMaterial({
color,
emissive: color,
emissiveIntensity: 0.075,
roughness: 0.26,
metalness: 0.18,
clearcoat: 0.75,
clearcoatRoughness: 0.18
})
);
body.castShadow = true;
body.receiveShadow = true;
group.add(body);
addEdges(body, color, 0.72);
const panel = new THREE.Mesh(
new THREE.BoxGeometry(0.40, 0.13, 0.035),
new THREE.MeshStandardMaterial({
color: 0x07121e,
emissive: color,
emissiveIntensity: 0.2,
roughness: 0.38,
metalness: 0.45
})
);
panel.position.set(0, 0, 0.285);
group.add(panel);
const boltGeometry = new THREE.SphereGeometry(0.027, 12, 8);
const boltMaterial = new THREE.MeshStandardMaterial({
color: 0xdff7ff,
emissive: color,
emissiveIntensity: 0.16,
roughness: 0.25,
metalness: 0.72
});
for (const x of [-0.24, 0.24]) {
const bolt = new THREE.Mesh(boltGeometry, boltMaterial);
bolt.position.set(x, -0.18, 0.31);
group.add(bolt);
}
scene.add(group);
return group;
}
// -------------------------------------------------------------------------
// Stage and supports
// -------------------------------------------------------------------------
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(30, 20),
floorMaterial
);
floor.rotation.x = -Math.PI / 2;
floor.position.y = -0.78;
floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(24, 48, 0x2a6682, 0x18364a);
grid.position.y = -0.77;
grid.material.transparent = true;
grid.material.opacity = 0.24;
scene.add(grid);
addBox(8.8, 0.18, 3.2, 0, -0.68, 0, platformMaterial, 0x2c6882);
const cyanStripMaterial = new THREE.MeshStandardMaterial({
color: palette.cyan,
emissive: palette.cyan,
emissiveIntensity: 0.45,
roughness: 0.4
});
const amberStripMaterial = new THREE.MeshStandardMaterial({
color: palette.amber,
emissive: palette.amber,
emissiveIntensity: 0.45,
roughness: 0.4
});
addBox(3.55, 0.025, 0.06, -1.45, -0.575, 1.48, cyanStripMaterial);
addBox(3.55, 0.025, 0.06, 1.55, -0.575, 1.48, amberStripMaterial);
const H_ANCHOR = new THREE.Vector3(-2.82, 1.18, 0);
const V_ANCHOR = new THREE.Vector3(2.15, 2.55, 0);
const H_FREE_LENGTH = 0.95;
const V_FREE_LENGTH = 1.10;
const MASS_WIDTH = 0.78;
const MASS_HEIGHT = 0.64;
// Horizontal wall support and guide.
addBox(0.25, 2.12, 0.38, -3.10, 0.48, -0.12, supportMaterial, 0x3c7893);
const hBracket = new THREE.Mesh(
new THREE.CylinderGeometry(0.075, 0.075, 0.36, 18),
supportMaterial
);
hBracket.rotation.z = Math.PI / 2;
hBracket.position.set(-2.96, H_ANCHOR.y, -0.04);
hBracket.castShadow = true;
scene.add(hBracket);
const hRail = new THREE.Mesh(
new THREE.CylinderGeometry(0.035, 0.035, 1.72, 14),
supportMaterial
);
hRail.rotation.z = Math.PI / 2;
hRail.position.set(-1.34, 0.68, -0.12);
scene.add(hRail);
for (const x of [-2.06, -0.64]) {
addBox(0.10, 0.22, 0.22, x, 0.57, -0.12, supportMaterial);
}
// Vertical support.
addBox(0.24, 3.32, 0.38, 2.15, 1.08, -0.23, supportMaterial, 0x3c7893);
addBox(0.62, 0.16, 0.50, 2.15, 2.70, -0.18, supportMaterial, 0x3c7893);
const anchorGeometry = new THREE.SphereGeometry(0.085, 18, 12);
const hAnchor = new THREE.Mesh(
anchorGeometry,
new THREE.MeshStandardMaterial({
color: 0xc8f5ff,
emissive: palette.cyan,
emissiveIntensity: 0.32,
metalness: 0.72,
roughness: 0.22
})
);
hAnchor.position.copy(H_ANCHOR);
hAnchor.castShadow = true;
scene.add(hAnchor);
const vAnchor = new THREE.Mesh(
anchorGeometry,
new THREE.MeshStandardMaterial({
color: 0xffe2b5,
emissive: palette.amber,
emissiveIntensity: 0.32,
metalness: 0.72,
roughness: 0.22
})
);
vAnchor.position.copy(V_ANCHOR);
vAnchor.castShadow = true;
scene.add(vAnchor);
// -------------------------------------------------------------------------
// Spring construction and animation
// -------------------------------------------------------------------------
function createSpring(color, turns) {
const segments = 88;
const radius = 0.105;
const group = new THREE.Group();
const geometry = new THREE.CylinderGeometry(0.021, 0.021, 1, 7, 1, false);
const material = new THREE.MeshStandardMaterial({
color,
emissive: color,
emissiveIntensity: 0.13,
roughness: 0.25,
metalness: 0.78
});
const meshes = [];
for (let i = 0; i < segments; i++) {
const mesh = new THREE.Mesh(geometry, material);
mesh.receiveShadow = true;
group.add(mesh);
meshes.push(mesh);
}
const axis = new THREE.Vector3();
const tangent = new THREE.Vector3();
const u = new THREE.Vector3();
const v = new THREE.Vector3();
const center = new THREE.Vector3();
const reference = new THREE.Vector3();
const p0 = new THREE.Vector3();
const p1 = new THREE.Vector3();
const midpoint = new THREE.Vector3();
const direction = new THREE.Vector3();
const yAxis = new THREE.Vector3(0, 1, 0);
function sample(start, end, t, out) {
axis.subVectors(end, start).normalize();
reference.set(Math.abs(axis.y) < 0.85 ? 0 : 1, Math.abs(axis.y) < 0.85 ? 1 : 0, 0);
u.crossVectors(axis, reference).normalize();
v.crossVectors(axis, u).normalize();
center.lerpVectors(start, end, t);
let envelope = 1;
if (t < 0.08) {
envelope = Math.sin((t / 0.08) * Math.PI * 0.5);
} else if (t > 0.92) {
envelope = Math.sin(((1 - t) / 0.08) * Math.PI * 0.5);
}
const angle = t * turns * Math.PI * 2;
out.copy(center)
.addScaledVector(u, Math.cos(angle) * radius * envelope)
.addScaledVector(v, Math.sin(angle) * radius * envelope);
}
function update(start, end) {
for (let i = 0; i < segments; i++) {
const t0 = i / segments;
const t1 = (i + 1) / segments;
sample(start, end, t0, p0);
sample(start, end, t1, p1);
midpoint.addVectors(p0, p1).multiplyScalar(0.5);
direction.subVectors(p1, p0);
const length = direction.length();
const mesh = meshes[i];
mesh.position.copy(midpoint);
mesh.scale.set(1, length, 1);
tangent.copy(direction).normalize();
mesh.quaternion.setFromUnitVectors(yAxis, tangent);
}
}
scene.add(group);
return { update };
}
const hSpring = createSpring(palette.cyan, 11);
const vSpring = createSpring(palette.amber, 12);
const hMass = createMass(palette.cyan);
const vMass = createMass(palette.amber);
// -------------------------------------------------------------------------
// Equilibrium markers, measurement lines, and arrows
// -------------------------------------------------------------------------
function dashedLine(color, opacity = 0.65) {
const geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(),
new THREE.Vector3()
]);
const material = new THREE.LineDashedMaterial({
color,
dashSize: 0.08,
gapSize: 0.055,
transparent: true,
opacity,
depthTest: false
});
const line = new THREE.Line(geometry, material);
line.renderOrder = 5;
scene.add(line);
return line;
}
function updateLine(line, a, b) {
const positions = line.geometry.attributes.position;
positions.setXYZ(0, a.x, a.y, a.z);
positions.setXYZ(1, b.x, b.y, b.z);
positions.needsUpdate = true;
line.geometry.computeBoundingSphere();
line.computeLineDistances();
}
function measurementLine(color) {
const geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(),
new THREE.Vector3()
]);
const material = new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.95,
depthTest: false
});
const line = new THREE.Line(geometry, material);
line.renderOrder = 7;
scene.add(line);
return line;
}
const hEqLine = dashedLine(palette.cyan, 0.34);
const vEqLine = dashedLine(palette.amber, 0.65);
const noLoadLine = dashedLine(0x87a2b2, 0.3);
const hMeasureLine = measurementLine(palette.cyan);
const vMeasureLine = measurementLine(palette.amber);
const hEqRing = new THREE.Mesh(
new THREE.TorusGeometry(0.095, 0.012, 8, 28),
new THREE.MeshBasicMaterial({
color: palette.cyan,
transparent: true,
opacity: 0.8,
depthTest: false
})
);
hEqRing.renderOrder = 8;
scene.add(hEqRing);
const vEqRing = hEqRing.clone();
vEqRing.material = hEqRing.material.clone();
vEqRing.material.color.setHex(palette.amber);
scene.add(vEqRing);
const ghostMass = new THREE.Mesh(
new THREE.BoxGeometry(MASS_WIDTH, MASS_HEIGHT, 0.48),
new THREE.MeshBasicMaterial({
color: palette.amber,
wireframe: true,
transparent: true,
opacity: 0.22,
depthWrite: false
})
);
scene.add(ghostMass);
const shiftArrow = new THREE.ArrowHelper(
new THREE.Vector3(0, -1, 0),
new THREE.Vector3(),
0.3,
palette.amber,
0.08,
0.05
);
shiftArrow.line.material.depthTest = false;
shiftArrow.cone.material.depthTest = false;
shiftArrow.renderOrder = 8;
scene.add(shiftArrow);
const gravityArrow = new THREE.ArrowHelper(
new THREE.Vector3(0, -1, 0),
new THREE.Vector3(3.28, 1.75, 0.10),
0.62,
palette.amber,
0.11,
0.075
);
gravityArrow.line.material.depthTest = false;
gravityArrow.cone.material.depthTest = false;
gravityArrow.renderOrder = 8;
scene.add(gravityArrow);
// -------------------------------------------------------------------------
// Physical state and measurement
// -------------------------------------------------------------------------
const hEquilibrium = H_ANCHOR.x + H_FREE_LENGTH + MASS_WIDTH / 2;
const vNoLoadEquilibrium = V_ANCHOR.y - V_FREE_LENGTH - MASS_HEIGHT / 2;
let vEquilibrium = vNoLoadEquilibrium;
function updateParameters() {
state.gravity = Number(gravityInput.value);
state.stiffness = Number(stiffnessInput.value);
state.mass = Number(massInput.value);
state.amplitude = Number(amplitudeInput.value);
state.extension = state.gravity * state.mass / state.stiffness;
vEquilibrium = vNoLoadEquilibrium - state.extension;
state.frequency = Math.sqrt(state.stiffness / state.mass) / (Math.PI * 2);
$("gravityValue").textContent = `${state.gravity.toFixed(2)} m/s²`;
$("stiffnessValue").textContent = `${state.stiffness.toFixed(0)} N/m`;
$("massValue").textContent = `${state.mass.toFixed(2)} kg`;
$("amplitudeValue").textContent = `${state.amplitude.toFixed(2)} m`;
$("frequency").textContent = `${state.frequency.toFixed(2)} Hz`;
$("extension").textContent = `${state.extension.toFixed(3)} m`;
$("hShift").textContent = "0.000 m";
$("vShift").textContent = `−${state.extension.toFixed(3)} m`;
// Static equilibrium references.
updateLine(
hEqLine,
new THREE.Vector3(hEquilibrium, -0.52, 0.10),
new THREE.Vector3(hEquilibrium, 1.62, 0.10)
);
updateLine(
vEqLine,
new THREE.Vector3(1.38, vEquilibrium, 0.12),
new THREE.Vector3(2.90, vEquilibrium, 0.12)
);
updateLine(
noLoadLine,
new THREE.Vector3(1.48, vNoLoadEquilibrium, 0.08),
new THREE.Vector3(2.83, vNoLoadEquilibrium, 0.08)
);
hEqRing.position.set(hEquilibrium, H_ANCHOR.y, 0.37);
vEqRing.position.set(V_ANCHOR.x, vEquilibrium, 0.37);
ghostMass.position.set(V_ANCHOR.x, vNoLoadEquilibrium, 0);
shiftArrow.position.set(2.96, vNoLoadEquilibrium, 0.12);
shiftArrow.visible = state.extension > 0.001;
if (state.extension > 0.001) {
shiftArrow.setLength(
state.extension,
Math.min(0.09, state.extension * 0.34),
Math.min(0.055, state.extension * 0.22)
);
}
const gravityLength = 0.30 + (state.gravity / 20) * 0.48;
gravityArrow.setLength(
gravityLength,
Math.min(0.12, gravityLength * 0.24),
Math.min(0.08, gravityLength * 0.16)
);
}
function signedMeters(value) {
const safe = Math.abs(value) < 0.0005 ? 0 : value;
const sign = safe >= 0 ? "+" : "−";
return `${sign}${Math.abs(safe).toFixed(3)} m`;
}
// -------------------------------------------------------------------------
// Plot
// -------------------------------------------------------------------------
const plotCanvas = $("plot");
const plotContext = plotCanvas.getContext("2d");
const history = [];
function drawPlot() {
const cssWidth = plotCanvas.clientWidth;
const cssHeight = plotCanvas.clientHeight;
if (!cssWidth || !cssHeight) return;
const dpr = Math.min(window.devicePixelRatio, 2);
const pixelWidth = Math.round(cssWidth * dpr);
const pixelHeight = Math.round(cssHeight * dpr);
if (plotCanvas.width !== pixelWidth || plotCanvas.height !== pixelHeight) {
plotCanvas.width = pixelWidth;
plotCanvas.height = pixelHeight;
}
const ctx = plotContext;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, cssWidth, cssHeight);
const margin = { left: 31, right: 8, top: 9, bottom: 20 };
const plotWidth = cssWidth - margin.left - margin.right;
const plotHeight = cssHeight - margin.top - margin.bottom;
const yRange = 0.5;
const toY = value =>
margin.top + plotHeight * 0.5 - (value / yRange) * (plotHeight * 0.5);
ctx.font = "9px ui-monospace, SFMono-Regular, Menlo, monospace";
ctx.textAlign = "right";
ctx.textBaseline = "middle";
for (const value of [-0.5, -0.25, 0, 0.25, 0.5]) {
const y = toY(value);
ctx.beginPath();
ctx.moveTo(margin.left, y);
ctx.lineTo(margin.left + plotWidth, y);
ctx.strokeStyle = value === 0 ? "rgba(176,216,232,0.43)" : "rgba(125,166,187,0.11)";
ctx.lineWidth = value === 0 ? 1.2 : 1;
ctx.stroke();
ctx.fillStyle = value === 0 ? "#afc9d6" : "#607b8a";
ctx.fillText(value === 0 ? "0" : value.toFixed(2), margin.left - 6, y);
}
const startTime = state.time - 6;
const toX = time =>
margin.left + ((time - startTime) / 6) * plotWidth;
function drawSeries(key, color) {
ctx.beginPath();
let first = true;
for (const point of history) {
if (point.t < startTime) continue;
const x = toX(point.t);
const y = toY(point[key]);
if (first) {
ctx.moveTo(x, y);
first = false;
} else {
ctx.lineTo(x, y);
}
}
ctx.strokeStyle = color;
ctx.lineWidth = 1.8;
ctx.lineJoin = "round";
ctx.lineCap = "round";
ctx.shadowColor = color;
ctx.shadowBlur = 5;
ctx.stroke();
ctx.shadowBlur = 0;
}
drawSeries("h", "#54d8ff");
drawSeries("v", "#ffb65c");
ctx.fillStyle = "#607b8a";
ctx.textAlign = "left";
ctx.textBaseline = "bottom";
ctx.fillText("−6 s", margin.left, cssHeight - 3);
ctx.textAlign = "right";
ctx.fillText("now", cssWidth - margin.right, cssHeight - 3);
ctx.textAlign = "center";
ctx.fillText("q (m)", margin.left + plotWidth * 0.5, cssHeight - 3);
}
// -------------------------------------------------------------------------
// Projected HTML labels
// -------------------------------------------------------------------------
const projectionVector = new THREE.Vector3();
function projectLabel(element, position) {
projectionVector.copy(position).project(camera);
const visible =
projectionVector.z > -1 &&
projectionVector.z < 1 &&
Math.abs(projectionVector.x) < 1.2 &&
Math.abs(projectionVector.y) < 1.2;
element.style.opacity = visible ? "1" : "0";
if (!visible) return;
element.style.left = `${(projectionVector.x * 0.5 + 0.5) * window.innerWidth}px`;
element.style.top = `${(-projectionVector.y * 0.5 + 0.5) * window.innerHeight}px`;
}
// -------------------------------------------------------------------------
// Custom camera controls: drag to orbit and wheel/pinch distance
// -------------------------------------------------------------------------
let dragging = false;
let pointerX = 0;
let pointerY = 0;
renderer.domElement.addEventListener("pointerdown", event => {
if (event.button !== 0) return;
dragging = true;
pointerX = event.clientX;
pointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - pointerX;
const dy = event.clientY - pointerY;
pointerX = event.clientX;
pointerY = event.clientY;
cameraState.yaw -= dx * 0.006;
cameraState.pitch = THREE.MathUtils.clamp(
cameraState.pitch + dy * 0.0045,
-0.02,
0.78
);
});
function endDrag(event) {
dragging = false;
if (event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", endDrag);
renderer.domElement.addEventListener("pointercancel", endDrag);
renderer.domElement.addEventListener("dblclick", resetCamera);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraState.distance = THREE.MathUtils.clamp(
cameraState.distance + event.deltaY * 0.008,
7.7,
16.5
);
}, { passive: false });
function resetCamera() {
cameraState.yaw = 0.28;
cameraState.pitch = 0.27;
cameraState.distance = 11.3;
}
function updateCamera() {
const cosPitch = Math.cos(cameraState.pitch);
camera.position.set(
cameraState.target.x + cameraState.distance * cosPitch * Math.sin(cameraState.yaw),
cameraState.target.y + cameraState.distance * Math.sin(cameraState.pitch),
cameraState.target.z + cameraState.distance * cosPitch * Math.cos(cameraState.yaw)
);
camera.lookAt(cameraState.target);
camera.updateMatrixWorld();
}
// -------------------------------------------------------------------------
// UI controls
// -------------------------------------------------------------------------
for (const input of [
gravityInput,
stiffnessInput,
massInput,
amplitudeInput
]) {
input.addEventListener("input", updateParameters);
}
$("pauseButton").addEventListener("click", () => {
state.running = !state.running;
$("pauseButton").textContent = state.running ? "Pause" : "Resume";
$("pauseButton").classList.toggle("primary", state.running);
});
$("resetButton").addEventListener("click", () => {
state.phase = 0;
state.time = 0;
history.length = 0;
});
$("viewButton").addEventListener("click", resetCamera);
window.addEventListener("keydown", event => {
if (event.code === "Space") {
event.preventDefault();
$("pauseButton").click();
}
if (event.key.toLowerCase() === "r") {
$("resetButton").click();
}
});
window.addEventListener("resize", () => {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(window.innerWidth, window.innerHeight);
});
// -------------------------------------------------------------------------
// Animation
// -------------------------------------------------------------------------
const clock = new THREE.Clock();
const hSpringEnd = new THREE.Vector3();
const vSpringEnd = new THREE.Vector3();
const hMeasureStart = new THREE.Vector3();
const hMeasureEnd = new THREE.Vector3();
const vMeasureStart = new THREE.Vector3();
const vMeasureEnd = new THREE.Vector3();
function animate() {
requestAnimationFrame(animate);
const dt = Math.min(clock.getDelta(), 0.05);
if (state.running) {
const omega = Math.sqrt(state.stiffness / state.mass);
state.phase += omega * dt;
state.time += dt;
}
// The measured coordinate is always relative to each system's own
// correct equilibrium. Gravity affects only the vertical equilibrium
// location, not the ideal spring's oscillation frequency.
state.qH = state.amplitude * Math.cos(state.phase);
state.qV = state.amplitude * Math.cos(state.phase);
const hPosition = hEquilibrium + state.qH;
const vPosition = vEquilibrium + state.qV;
hMass.position.set(hPosition, H_ANCHOR.y, 0);
vMass.position.set(V_ANCHOR.x, vPosition, 0);
hSpringEnd.set(
hMass.position.x - MASS_WIDTH / 2,
hMass.position.y,
0
);
vSpringEnd.set(
vMass.position.x,
vMass.position.y + MASS_HEIGHT / 2,
0
);
hSpring.update(H_ANCHOR, hSpringEnd);
vSpring.update(V_ANCHOR, vSpringEnd);
// Bright measurement segments from equilibrium to current position.
hMeasureStart.set(hEquilibrium, H_ANCHOR.y, 0.39);
hMeasureEnd.set(hPosition, H_ANCHOR.y, 0.39);
updateLine(hMeasureLine, hMeasureStart, hMeasureEnd);
vMeasureStart.set(V_ANCHOR.x, vEquilibrium, 0.39);
vMeasureEnd.set(V_ANCHOR.x, vPosition, 0.39);
updateLine(vMeasureLine, vMeasureStart, vMeasureEnd);
$("hDisp").textContent = signedMeters(state.qH);
$("vDisp").textContent = signedMeters(state.qV);
$("hMassReadout").textContent = signedMeters(state.qH);
$("vMassReadout").textContent = signedMeters(state.qV);
history.push({ t: state.time, h: state.qH, v: state.qV });
while (history.length > 1000) history.shift();
updateCamera();
projectLabel(
$("label-h-section"),
new THREE.Vector3(-1.78, 2.08, 0.1)
);
projectLabel(
$("label-v-section"),
new THREE.Vector3(2.15, 3.17, 0.1)
);
projectLabel(
$("label-h-mass"),
new THREE.Vector3(hPosition - 0.05, H_ANCHOR.y - 0.66, 0.2)
);
projectLabel(
$("label-v-mass"),
new THREE.Vector3(V_ANCHOR.x + 0.68, vPosition - 0.18, 0.2)
);
projectLabel(
$("label-h-eq"),
new THREE.Vector3(hEquilibrium, 0.30, 0.4)
);
projectLabel(
$("label-v-eq"),
new THREE.Vector3(3.02, vEquilibrium, 0.2)
);
projectLabel(
$("label-natural"),
new THREE.Vector3(3.04, vNoLoadEquilibrium, 0.2)
);
projectLabel(
$("label-shift"),
new THREE.Vector3(3.12, vNoLoadEquilibrium - state.extension * 0.5, 0.2)
);
projectLabel(
$("label-gravity"),
new THREE.Vector3(3.31, 1.39, 0.2)
);
drawPlot();
renderer.render(scene, camera);
}
updateParameters();
updateCamera();
animate();
</script>
</body>
</html>
```