Prompt specification
Build or customize the Three.js 3D scene "Driven oscillator frequency dial" 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: Driven oscillator frequency dial
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/driven-oscillator-frequency-dial-x1577
Scene Description Prompt:
Create a standalone low-poly scene in one HTML file using Three.js from cdnjs. Build a spring-mass oscillator with a visible periodic driver and separate displacement marker; distinguish driving motion from the resulting response under a stated damped linear model.
Working Three.js Starter (driven-oscillator-frequency-dial-x1577):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Low-Poly Damped Spring–Mass Oscillator</title>
<style>
:root {
color-scheme: dark;
--cyan: #55d8ff;
--orange: #ffb45c;
--panel: rgba(10, 18, 29, 0.9);
--border: rgba(159, 190, 216, 0.18);
--muted: #92a9bd;
--text: #edf7ff;
}
* { box-sizing: border-box; }
html, body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #0a121d;
font-family: Inter, ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
"Segoe UI", sans-serif;
color: var(--text);
}
#viewport {
position: fixed;
inset: 0;
}
#viewport canvas {
display: block;
width: 100%;
height: 100%;
touch-action: none;
cursor: grab;
}
#viewport canvas:active {
cursor: grabbing;
}
#panel {
position: fixed;
z-index: 10;
top: 16px;
right: 16px;
bottom: 16px;
width: min(370px, calc(100vw - 32px));
overflow-y: auto;
padding: 20px;
border: 1px solid var(--border);
border-radius: 18px;
background: var(--panel);
box-shadow: 0 20px 70px rgba(0, 0, 0, 0.38);
backdrop-filter: blur(16px);
}
.kicker {
color: var(--cyan);
font-size: 11px;
font-weight: 800;
letter-spacing: 0.18em;
text-transform: uppercase;
}
h1 {
margin: 7px 0 9px;
font-size: 25px;
line-height: 1.08;
letter-spacing: -0.035em;
}
.intro {
margin: 0 0 15px;
color: var(--muted);
font-size: 13px;
line-height: 1.5;
}
.model {
margin-bottom: 17px;
padding: 13px;
border: 1px solid rgba(85, 216, 255, 0.19);
border-radius: 12px;
background: rgba(85, 216, 255, 0.055);
font-size: 13px;
line-height: 1.65;
}
.equation {
color: #ffffff;
font-family: Georgia, "Times New Roman", serif;
font-size: 17px;
text-align: center;
}
.model small {
display: block;
margin-top: 7px;
color: var(--muted);
line-height: 1.45;
}
.controls-title {
margin: 17px 0 10px;
color: #c7d8e6;
font-size: 11px;
font-weight: 800;
letter-spacing: 0.14em;
text-transform: uppercase;
}
.control {
margin: 0 0 12px;
}
.control-line {
display: flex;
align-items: baseline;
justify-content: space-between;
gap: 10px;
margin-bottom: 5px;
font-size: 12px;
}
.control-line output {
color: #ffffff;
font-variant-numeric: tabular-nums;
}
input[type="range"] {
width: 100%;
height: 4px;
margin: 4px 0;
accent-color: var(--cyan);
cursor: pointer;
}
.buttons {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin: 15px 0;
}
button {
padding: 10px 12px;
border: 1px solid rgba(159, 190, 216, 0.24);
border-radius: 9px;
background: rgba(255, 255, 255, 0.055);
color: var(--text);
font: inherit;
font-size: 12px;
font-weight: 750;
cursor: pointer;
}
button:hover {
background: rgba(255, 255, 255, 0.1);
}
button.primary {
border-color: rgba(85, 216, 255, 0.35);
background: rgba(85, 216, 255, 0.11);
color: var(--cyan);
}
.stats {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
margin-bottom: 14px;
}
.stat {
padding: 9px 10px;
border: 1px solid var(--border);
border-radius: 10px;
background: rgba(255, 255, 255, 0.025);
}
.stat span {
display: block;
color: var(--muted);
font-size: 10px;
letter-spacing: 0.04em;
}
.stat strong {
display: block;
margin-top: 3px;
font-size: 14px;
font-variant-numeric: tabular-nums;
}
.legend {
display: flex;
flex-wrap: wrap;
gap: 10px 16px;
margin: 10px 0;
font-size: 11px;
color: #c8d6e2;
}
.legend-item {
display: flex;
align-items: center;
gap: 6px;
}
.swatch {
width: 17px;
height: 4px;
border-radius: 4px;
background: var(--cyan);
}
.swatch.orange { background: var(--orange); }
.swatch.dashed {
height: 0;
border-top: 2px dashed var(--orange);
background: transparent;
}
#scope {
display: block;
width: 100%;
height: auto;
border: 1px solid var(--border);
border-radius: 11px;
background: #07101a;
}
.note {
margin: 10px 0 0;
color: var(--muted);
font-size: 10.5px;
line-height: 1.5;
}
#hint {
position: fixed;
z-index: 5;
left: 16px;
bottom: 16px;
padding: 8px 11px;
border: 1px solid var(--border);
border-radius: 9px;
background: rgba(10, 18, 29, 0.68);
color: #9eb3c5;
font-size: 11px;
pointer-events: none;
}
@media (max-width: 760px) {
#panel {
top: auto;
right: 8px;
left: 8px;
bottom: 8px;
width: auto;
max-height: 47vh;
padding: 15px;
border-radius: 14px;
}
h1 { font-size: 21px; }
#hint { display: none; }
}
</style>
</head>
<body>
<div id="viewport"></div>
<aside id="panel">
<div class="kicker">Low-poly mechanics / 01</div>
<h1>Damped spring–mass oscillator</h1>
<p class="intro">
The cyan platform imposes a periodic base motion. The orange mass is the
resulting response, solved from a damped linear model.
</p>
<div class="model">
<div class="equation">
mẍ + cẋ + k(x − x<sub>d</sub>) = 0
</div>
<small>
Imposed drive: x<sub>d</sub>(t) = A sin(2πft).<br>
x(t) is the mass displacement from equilibrium.
</small>
</div>
<div class="controls-title">Model parameters</div>
<div class="control">
<div class="control-line">
<label for="amplitude">Drive amplitude A</label>
<output id="amplitudeValue"></output>
</div>
<input id="amplitude" type="range" min="0.08" max="0.65" step="0.01" value="0.35">
</div>
<div class="control">
<div class="control-line">
<label for="frequency">Drive frequency f</label>
<output id="frequencyValue"></output>
</div>
<input id="frequency" type="range" min="0.20" max="2.20" step="0.05" value="0.75">
</div>
<div class="control">
<div class="control-line">
<label for="mass">Mass m</label>
<output id="massValue"></output>
</div>
<input id="mass" type="range" min="0.5" max="3" step="0.1" value="1.2">
</div>
<div class="control">
<div class="control-line">
<label for="stiffness">Spring stiffness k</label>
<output id="stiffnessValue"></output>
</div>
<input id="stiffness" type="range" min="15" max="100" step="1" value="38">
</div>
<div class="control">
<div class="control-line">
<label for="damping">Damping c</label>
<output id="dampingValue"></output>
</div>
<input id="damping" type="range" min="0.2" max="12" step="0.1" value="2.4">
</div>
<div class="buttons">
<button id="pause" class="primary" type="button">Pause</button>
<button id="reset" type="button">Reset at rest</button>
</div>
<div class="stats">
<div class="stat">
<span>STEADY-STATE GAIN |x| / A</span>
<strong id="gainValue">—</strong>
</div>
<div class="stat">
<span>PHASE LAG</span>
<strong id="phaseValue">—</strong>
</div>
<div class="stat">
<span>DAMPING RATIO ζ</span>
<strong id="zetaValue">—</strong>
</div>
<div class="stat">
<span>STEADY-STATE |x|</span>
<strong id="responseValue">—</strong>
</div>
</div>
<div class="controls-title">Displacement scope</div>
<div class="legend">
<div class="legend-item"><i class="swatch"></i> Driver x<sub>d</sub>(t)</div>
<div class="legend-item"><i class="swatch orange"></i> Mass x(t)</div>
<div class="legend-item"><i class="swatch dashed"></i> Predicted steady state</div>
</div>
<canvas id="scope" width="640" height="220"></canvas>
<p class="note">
The simulation starts with the mass at rest. The dashed orange trace is the
eventual sinusoidal solution for the current parameters. The separate
orange displacement marker shows the computed mass displacement, not the
driver motion.
</p>
</aside>
<div id="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 model parameters
// ------------------------------------------------------------
const viewport = document.getElementById("viewport");
const scopeCanvas = document.getElementById("scope");
const scopeContext = scopeCanvas.getContext("2d");
const params = {
amplitude: 0.35,
frequency: 0.75,
mass: 1.2,
stiffness: 38,
damping: 2.4
};
const CYAN = 0x55d8ff;
const ORANGE = 0xffb45c;
const DARK = 0x172637;
const MID = 0x355064;
const PALE = 0xc9e5f2;
const driverEquilibrium = -2.8;
const massEquilibrium = 1.25;
let simulationTime = 0;
let displacement = 0;
let velocity = 0;
let running = true;
let accumulator = 0;
const history = [];
// ------------------------------------------------------------
// Renderer, camera, scene
// ------------------------------------------------------------
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x0a121d);
scene.fog = new THREE.Fog(0x0a121d, 13, 29);
const camera = new THREE.PerspectiveCamera(
43,
innerWidth / innerHeight,
0.1,
100
);
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(Math.min(devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
viewport.appendChild(renderer.domElement);
const hemisphere = new THREE.HemisphereLight(0xc9e8ff, 0x263343, 2.2);
scene.add(hemisphere);
const sun = new THREE.DirectionalLight(0xffefd5, 3.1);
sun.position.set(-5, 8, 6);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -10;
sun.shadow.camera.right = 10;
sun.shadow.camera.top = 8;
sun.shadow.camera.bottom = -8;
sun.shadow.camera.near = 0.5;
sun.shadow.camera.far = 30;
sun.shadow.normalBias = 0.025;
scene.add(sun);
const rim = new THREE.DirectionalLight(0x55d8ff, 1.25);
rim.position.set(5, 4, -6);
scene.add(rim);
// ------------------------------------------------------------
// Small geometry helpers
// ------------------------------------------------------------
function standardMaterial(color, options = {}) {
return new THREE.MeshStandardMaterial({
color,
roughness: 0.78,
metalness: 0.05,
flatShading: true,
...options
});
}
function addBox(w, h, d, material, x, y, z, parent = scene) {
const mesh = new THREE.Mesh(
new THREE.BoxGeometry(w, h, d),
material
);
mesh.position.set(x, y, z);
mesh.castShadow = true;
mesh.receiveShadow = true;
parent.add(mesh);
return mesh;
}
function addWireBox(w, h, d, color, x, y, z, parent = scene) {
const geometry = new THREE.EdgesGeometry(new THREE.BoxGeometry(w, h, d));
const material = new THREE.LineBasicMaterial({
color,
transparent: true,
opacity: 0.36
});
const lines = new THREE.LineSegments(geometry, material);
lines.position.set(x, y, z);
parent.add(lines);
return lines;
}
function makeLabel(text, color, width = 2.0) {
const canvas = document.createElement("canvas");
canvas.width = 640;
canvas.height = 120;
const context = canvas.getContext("2d");
context.clearRect(0, 0, canvas.width, canvas.height);
context.fillStyle = "rgba(8, 17, 27, 0.86)";
context.strokeStyle = `#${new THREE.Color(color).getHexString()}`;
context.lineWidth = 3;
context.beginPath();
context.roundRect(5, 5, 630, 110, 25);
context.fill();
context.stroke();
context.fillStyle = `#${new THREE.Color(color).getHexString()}`;
context.font = "700 34px system-ui, sans-serif";
context.textAlign = "center";
context.textBaseline = "middle";
context.fillText(text, 320, 61);
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthWrite: false,
depthTest: false
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(width, width * 120 / 640, 1);
sprite.renderOrder = 20;
return sprite;
}
const up = new THREE.Vector3(0, 1, 0);
const tempDirection = new THREE.Vector3();
const tempMidpoint = new THREE.Vector3();
function placeCylinder(mesh, a, b) {
tempDirection.subVectors(b, a);
const length = tempDirection.length();
if (length < 0.00001) return;
tempMidpoint.copy(a).addScaledVector(tempDirection, 0.5);
mesh.position.copy(tempMidpoint);
mesh.quaternion.setFromUnitVectors(up, tempDirection.normalize());
mesh.scale.set(1, length, 1);
}
// ------------------------------------------------------------
// Ground, rails, and low-poly scenery
// ------------------------------------------------------------
const groundMaterial = standardMaterial(0x162332, { roughness: 1 });
const ground = new THREE.Mesh(
new THREE.PlaneGeometry(30, 22),
groundMaterial
);
ground.rotation.x = -Math.PI / 2;
ground.position.y = -0.09;
ground.receiveShadow = true;
scene.add(ground);
const grid = new THREE.GridHelper(24, 24, 0x35546b, 0x213447);
grid.position.y = -0.075;
grid.material.transparent = true;
grid.material.opacity = 0.45;
scene.add(grid);
const darkMaterial = standardMaterial(DARK, { roughness: 0.9 });
const midMaterial = standardMaterial(MID, { roughness: 0.82 });
const cyanMaterial = standardMaterial(CYAN, {
metalness: 0.28,
roughness: 0.42
});
const orangeMaterial = standardMaterial(ORANGE, {
metalness: 0.18,
roughness: 0.46
});
const paleMaterial = standardMaterial(PALE, { roughness: 0.68 });
const railMaterial = standardMaterial(0x607b8e, {
metalness: 0.55,
roughness: 0.48
});
const springMaterial = standardMaterial(0xb8d1dc, {
metalness: 0.58,
roughness: 0.38
});
// Fixed support and guide rails.
addBox(2.0, 0.38, 1.35, darkMaterial, driverEquilibrium, 0.13, 0);
addBox(2.8, 0.12, 0.18, railMaterial, driverEquilibrium, 0.34, -0.38);
addBox(2.8, 0.12, 0.18, railMaterial, driverEquilibrium, 0.34, 0.38);
addBox(5.6, 0.13, 0.16, railMaterial, massEquilibrium, 0.13, -0.36);
addBox(5.6, 0.13, 0.16, railMaterial, massEquilibrium, 0.13, 0.36);
addBox(0.18, 0.38, 1.05, darkMaterial, -1.35, 0.12, 0);
addBox(0.18, 0.38, 1.05, darkMaterial, 3.85, 0.12, 0);
// Low-poly background objects.
const sceneryMaterial = standardMaterial(0x203548);
const scenery = [
[-5.4, 0.18, -2.8, 0.55],
[4.9, 0.25, -3.2, 0.72],
[-4.7, 0.13, 3.4, 0.48],
[3.8, 0.20, 4.0, 0.65]
];
for (const [x, y, z, size] of scenery) {
const rock = new THREE.Mesh(
new THREE.IcosahedronGeometry(size, 0),
sceneryMaterial
);
rock.position.set(x, y, z);
rock.scale.y = 0.65;
rock.rotation.set(0.2, x * 0.3, 0.1);
rock.castShadow = true;
rock.receiveShadow = true;
scene.add(rock);
}
// ------------------------------------------------------------
// Driver carriage
// ------------------------------------------------------------
const driverGroup = new THREE.Group();
scene.add(driverGroup);
addBox(0.76, 0.28, 1.08, cyanMaterial, 0, 0.63, 0, driverGroup);
addBox(0.16, 0.42, 0.34, midMaterial, 0.28, 0.96, 0, driverGroup);
addBox(0.48, 0.035, 0.74, paleMaterial, -0.04, 0.79, 0, driverGroup);
addWireBox(0.80, 0.32, 1.12, CYAN, driverEquilibrium, 0.63, 0);
// Motor wheel and crank.
const motor = new THREE.Group();
motor.position.set(-4.22, 1.08, -0.16);
scene.add(motor);
const wheel = new THREE.Mesh(
new THREE.TorusGeometry(0.57, 0.085, 4, 12),
standardMaterial(0x3d7188, { metalness: 0.65, roughness: 0.35 })
);
wheel.castShadow = true;
motor.add(wheel);
const hub = new THREE.Mesh(
new THREE.CylinderGeometry(0.16, 0.16, 0.24, 8),
midMaterial
);
hub.rotation.x = Math.PI / 2;
hub.castShadow = true;
motor.add(hub);
const crankArm = addBox(
1, 0.075, 0.075,
standardMaterial(0x9deaff, { metalness: 0.45 }),
0.5, 0, 0.03, motor
);
const crankPin = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.11, 0),
cyanMaterial
);
crankPin.castShadow = true;
motor.add(crankPin);
const motorStand = addBox(
0.22, 1.0, 0.3,
darkMaterial,
-4.22, 0.39, -0.18
);
motorStand.castShadow = true;
const linkage = new THREE.Mesh(
new THREE.CylinderGeometry(0.032, 0.032, 1, 6),
standardMaterial(0x83ddf3, { metalness: 0.6, roughness: 0.36 })
);
linkage.castShadow = true;
scene.add(linkage);
// ------------------------------------------------------------
// Oscillating mass
// ------------------------------------------------------------
const massGroup = new THREE.Group();
scene.add(massGroup);
addBox(0.96, 1.0, 0.92, orangeMaterial, 0, 1.05, 0, massGroup);
addBox(0.55, 0.035, 0.63, paleMaterial, 0, 1.57, 0, massGroup);
// Four faceted rollers.
for (const x of [-0.29, 0.29]) {
for (const z of [-0.35, 0.35]) {
const wheelMesh = new THREE.Mesh(
new THREE.CylinderGeometry(0.18, 0.18, 0.14, 8),
darkMaterial
);
wheelMesh.rotation.x = Math.PI / 2;
wheelMesh.position.set(x, 0.34, z);
wheelMesh.castShadow = true;
massGroup.add(wheelMesh);
}
}
addWireBox(1.00, 1.04, 0.96, ORANGE, massEquilibrium, 1.05, 0);
// ------------------------------------------------------------
// Faceted helical spring
// ------------------------------------------------------------
const springSegments = 26;
const springMeshes = [];
const springGeometry = new THREE.CylinderGeometry(0.032, 0.032, 1, 6);
for (let i = 0; i < springSegments; i++) {
const segment = new THREE.Mesh(springGeometry, springMaterial);
segment.castShadow = true;
scene.add(segment);
springMeshes.push(segment);
}
const springPoints = Array.from(
{ length: springSegments + 1 },
() => new THREE.Vector3()
);
function updateSpring(start, end) {
const turns = 3.5;
const radius = 0.13;
for (let i = 0; i <= springSegments; i++) {
const t = i / springSegments;
const taper = Math.sin(Math.PI * t);
const phase = turns * Math.PI * 2 * t;
springPoints[i].lerpVectors(start, end, t);
springPoints[i].y += radius * taper * Math.cos(phase);
springPoints[i].z += radius * taper * Math.sin(phase);
}
for (let i = 0; i < springSegments; i++) {
placeCylinder(springMeshes[i], springPoints[i], springPoints[i + 1]);
}
}
// ------------------------------------------------------------
// Separate displacement gauges and markers
// ------------------------------------------------------------
function createGauge(centerX, z, color) {
const gaugeMaterial = standardMaterial(color, {
emissive: color,
emissiveIntensity: 0.18,
roughness: 0.45
});
addBox(2.8, 0.025, 0.075, gaugeMaterial, centerX, 0.025, z);
for (let i = -2; i <= 2; i++) {
addBox(
0.025, i === 0 ? 0.25 : 0.13, 0.075,
i === 0 ? paleMaterial : gaugeMaterial,
centerX + i * 0.5,
i === 0 ? 0.12 : 0.09,
z
);
}
const marker = new THREE.Group();
marker.position.set(centerX, 0, z);
scene.add(marker);
const bead = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.105, 0),
gaugeMaterial
);
bead.position.y = 0.23;
bead.castShadow = true;
marker.add(bead);
addBox(
0.035, 0.34, 0.035,
gaugeMaterial,
0, 0.34, 0, marker
);
return marker;
}
const driverMarker = createGauge(driverEquilibrium, 1.45, CYAN);
const responseMarker = createGauge(massEquilibrium, 2.05, ORANGE);
const driverLabel = makeLabel("PERIODIC DRIVER x_d(t)", CYAN, 2.45);
driverLabel.position.set(-3.3, 2.05, 0.1);
scene.add(driverLabel);
const responseLabel = makeLabel("MASS RESPONSE x(t)", ORANGE, 2.35);
responseLabel.position.set(1.45, 2.05, 0.1);
scene.add(responseLabel);
const driveGaugeLabel = makeLabel("INPUT DISPLACEMENT", CYAN, 1.8);
driveGaugeLabel.position.set(driverEquilibrium, 0.83, 1.5);
scene.add(driveGaugeLabel);
const responseGaugeLabel = makeLabel("OUTPUT DISPLACEMENT", ORANGE, 1.9);
responseGaugeLabel.position.set(massEquilibrium, 0.83, 2.1);
scene.add(responseGaugeLabel);
// ------------------------------------------------------------
// Direct camera controls — no Three.js addons
// ------------------------------------------------------------
const cameraTarget = new THREE.Vector3(-0.85, 0.78, 0.2);
let cameraRadius = 10.8;
let cameraTheta = 0.55;
let cameraPhi = 1.08;
let dragging = false;
let previousPointerX = 0;
let previousPointerY = 0;
function updateCamera() {
camera.position.setFromSpherical(
new THREE.Spherical(cameraRadius, cameraPhi, cameraTheta)
).add(cameraTarget);
camera.lookAt(cameraTarget);
}
renderer.domElement.addEventListener("pointerdown", event => {
dragging = true;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
renderer.domElement.setPointerCapture(event.pointerId);
});
renderer.domElement.addEventListener("pointermove", event => {
if (!dragging) return;
const dx = event.clientX - previousPointerX;
const dy = event.clientY - previousPointerY;
previousPointerX = event.clientX;
previousPointerY = event.clientY;
cameraTheta -= dx * 0.006;
cameraPhi = THREE.MathUtils.clamp(cameraPhi + dy * 0.005, 0.35, 1.45);
updateCamera();
});
function stopDragging(event) {
dragging = false;
if (event.pointerId !== undefined &&
renderer.domElement.hasPointerCapture(event.pointerId)) {
renderer.domElement.releasePointerCapture(event.pointerId);
}
}
renderer.domElement.addEventListener("pointerup", stopDragging);
renderer.domElement.addEventListener("pointercancel", stopDragging);
renderer.domElement.addEventListener("wheel", event => {
event.preventDefault();
cameraRadius = THREE.MathUtils.clamp(
cameraRadius * Math.exp(event.deltaY * 0.001),
6.4,
17
);
updateCamera();
}, { passive: false });
renderer.domElement.addEventListener("dblclick", () => {
cameraRadius = 10.8;
cameraTheta = 0.55;
cameraPhi = 1.08;
updateCamera();
});
updateCamera();
// ------------------------------------------------------------
// Damped linear model
//
// m*x'' + c*x' + k*(x - x_d) = 0
// x_d(t) = A*sin(omega*t)
// ------------------------------------------------------------
const fixedTimeStep = 1 / 240;
let sampleCounter = 0;
function modelValues() {
const omega = 2 * Math.PI * params.frequency;
const real = params.stiffness - params.mass * omega * omega;
const imaginary = params.damping * omega;
const denominator = Math.hypot(real, imaginary);
return {
omega,
real,
imaginary,
denominator,
gain: params.stiffness / denominator,
phase: Math.atan2(imaginary, real),
zeta: params.damping /
(2 * Math.sqrt(params.stiffness * params.mass))
};
}
function derivatives(t, x, v) {
const drive = params.amplitude * Math.sin(modelValues().omega * t);
return {
x: v,
v: (
params.stiffness * (drive - x) -
params.damping * v
) / params.mass
};
}
function integrateStep(dt) {
const k1 = derivatives(simulationTime, displacement, velocity);
const k2 = derivatives(
simulationTime + dt * 0.5,
displacement + k1.x * dt * 0.5,
velocity + k1.v * dt * 0.5
);
const k3 = derivatives(
simulationTime + dt * 0.5,
displacement + k2.x * dt * 0.5,
velocity + k2.v * dt * 0.5
);
const k4 = derivatives(
simulationTime + dt,
displacement + k3.x * dt,
velocity + k3.v * dt
);
displacement += dt * (
k1.x + 2 * k2.x + 2 * k3.x + k4.x
) / 6;
velocity += dt * (
k1.v + 2 * k2.v + 2 * k3.v + k4.v
) / 6;
simulationTime += dt;
sampleCounter++;
if (sampleCounter % 6 === 0) {
history.push({
t: simulationTime,
drive: params.amplitude * Math.sin(modelValues().omega * simulationTime),
response: displacement
});
if (history.length > 1000) history.shift();
}
}
// ------------------------------------------------------------
// Scene updates
// ------------------------------------------------------------
const springStart = new THREE.Vector3();
const springEnd = new THREE.Vector3();
const pinWorld = new THREE.Vector3();
const carriageLink = new THREE.Vector3();
function updateScene() {
const omega = 2 * Math.PI * params.frequency;
const drive = params.amplitude * Math.sin(omega * simulationTime);
driverGroup.position.x = driverEquilibrium + drive;
massGroup.position.x = massEquilibrium + displacement;
driverMarker.position.x = driverEquilibrium + drive;
responseMarker.position.x = massEquilibrium + displacement;
// Motor crank and connecting rod.
motor.rotation.z = omega * simulationTime - Math.PI / 2;
crankArm.scale.x = params.amplitude;
crankArm.position.x = params.amplitude * 0.5;
crankPin.position.x = params.amplitude;
motor.updateMatrixWorld(true);
crankPin.getWorldPosition(pinWorld);
carriageLink.set(
driverEquilibrium + drive - 0.36,
0.73,
0
);
placeCylinder(linkage, pinWorld, carriageLink);
// Spring connects the moving driver to the mass.
springStart.set(
driverEquilibrium + drive + 0.36,
1.08,
0
);
springEnd.set(
massEquilibrium + displacement - 0.48,
1.08,
0
);
updateSpring(springStart, springEnd);
}
// ------------------------------------------------------------
// Scope plotting
// ------------------------------------------------------------
function drawScope() {
const context = scopeContext;
const width = scopeCanvas.width;
const height = scopeCanvas.height;
const padLeft = 44;
const padRight = 15;
const padTop = 17;
const padBottom = 27;
const plotWidth = width - padLeft - padRight;
const plotHeight = height - padTop - padBottom;
context.clearRect(0, 0, width, height);
context.fillStyle = "#07101a";
context.fillRect(0, 0, width, height);
const values = modelValues();
const endTime = Math.max(simulationTime, 1);
const startTime = Math.max(0, endTime - 8);
let maxAbs = Math.max(params.amplitude, 0.08);
for (const sample of history) {
if (sample.t >= startTime) {
maxAbs = Math.max(
maxAbs,
Math.abs(sample.drive),
Math.abs(sample.response)
);
}
}
const predictedAmplitude = params.amplitude * values.gain;
maxAbs = Math.max(maxAbs, predictedAmplitude * 1.08, 0.08);
maxAbs *= 1.12;
const mapX = t => padLeft +
(t - startTime) / Math.max(endTime - startTime, 0.001) * plotWidth;
const mapY = value =>
padTop + plotHeight * 0.5 -
value / maxAbs * plotHeight * 0.5;
// Grid.
context.strokeStyle = "rgba(145, 178, 201, 0.13)";
context.lineWidth = 1;
for (let i = 0; i <= 4; i++) {
const y = padTop + i * plotHeight / 4;
context.beginPath();
context.moveTo(padLeft, y);
context.lineTo(width - padRight, y);
context.stroke();
}
for (let i = 0; i <= 4; i++) {
const x = padLeft + i * plotWidth / 4;
context.beginPath();
context.moveTo(x, padTop);
context.lineTo(x, padTop + plotHeight);
context.stroke();
}
// Zero axis.
context.strokeStyle = "rgba(210, 231, 244, 0.34)";
context.beginPath();
context.moveTo(padLeft, mapY(0));
context.lineTo(width - padRight, mapY(0));
context.stroke();
// Predicted steady-state response.
context.strokeStyle = "rgba(255, 180, 92, 0.62)";
context.lineWidth = 2;
context.setLineDash([6, 6]);
context.beginPath();
for (let i = 0; i <= 160; i++) {
const t = startTime + (endTime - startTime) * i / 160;
const predicted =
predictedAmplitude * Math.sin(values.omega * t - values.phase);
const x = mapX(t);
const y = mapY(predicted);
if (i === 0) context.moveTo(x, y);
else context.lineTo(x, y);
}
context.stroke();
context.setLineDash([]);
function trace(color, field, lineWidth) {
context.strokeStyle = color;
context.lineWidth = lineWidth;
context.beginPath();
let first = true;
for (const sample of history) {
if (sample.t < startTime) continue;
const x = mapX(sample.t);
const y = mapY(sample[field]);
if (first) {
context.moveTo(x, y);
first = false;
} else {
context.lineTo(x, y);
}
}
context.stroke();
}
trace("#55d8ff", "drive", 2.4);
trace("#ffb45c", "response", 2.7);
// Labels.
context.fillStyle = "#8da6b9";
context.font = "13px system-ui, sans-serif";
context.textAlign = "left";
context.fillText(maxAbs.toFixed(1) + " m", 5, padTop + 8);
context.fillText("0", 18, mapY(0) + 4);
context.fillText("-" + maxAbs.toFixed(1), 1, padTop + plotHeight);
context.fillText("last 8 seconds", padLeft + 6, height - 7);
}
// ------------------------------------------------------------
// Controls and readouts
// ------------------------------------------------------------
function refreshControlLabels() {
document.getElementById("amplitudeValue").textContent =
params.amplitude.toFixed(2) + " m";
document.getElementById("frequencyValue").textContent =
params.frequency.toFixed(2) + " Hz";
document.getElementById("massValue").textContent =
params.mass.toFixed(1) + " kg";
document.getElementById("stiffnessValue").textContent =
params.stiffness.toFixed(0) + " N/m";
document.getElementById("dampingValue").textContent =
params.damping.toFixed(1) + " N·s/m";
}
function bindRange(id, key) {
const input = document.getElementById(id);
input.addEventListener("input", () => {
params[key] = Number(input.value);
refreshControlLabels();
});
}
bindRange("amplitude", "amplitude");
bindRange("frequency", "frequency");
bindRange("mass", "mass");
bindRange("stiffness", "stiffness");
bindRange("damping", "damping");
const pauseButton = document.getElementById("pause");
function togglePause() {
running = !running;
pauseButton.textContent = running ? "Pause" : "Resume";
}
function resetSimulation() {
simulationTime = 0;
displacement = 0;
velocity = 0;
accumulator = 0;
sampleCounter = 0;
history.length = 0;
running = true;
pauseButton.textContent = "Pause";
}
pauseButton.addEventListener("click", togglePause);
document.getElementById("reset").addEventListener("click", resetSimulation);
addEventListener("keydown", event => {
const tag = document.activeElement?.tagName;
if (tag === "INPUT" || tag === "BUTTON") return;
if (event.code === "Space") {
event.preventDefault();
togglePause();
}
if (event.code === "KeyR") {
resetSimulation();
}
});
function refreshStats() {
const values = modelValues();
document.getElementById("gainValue").textContent =
values.gain.toFixed(3);
document.getElementById("phaseValue").textContent =
THREE.MathUtils.radToDeg(values.phase).toFixed(1) + "°";
document.getElementById("zetaValue").textContent =
values.zeta.toFixed(3);
document.getElementById("responseValue").textContent =
(params.amplitude * values.gain).toFixed(3) + " m";
}
refreshControlLabels();
refreshStats();
updateScene();
// ------------------------------------------------------------
// Resize and animation loop
// ------------------------------------------------------------
addEventListener("resize", () => {
camera.aspect = innerWidth / innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
let previousFrameTime = performance.now();
let statsTimer = 0;
let scopeTimer = 0;
function animate(now) {
requestAnimationFrame(animate);
const frameDelta = Math.min((now - previousFrameTime) / 1000, 0.05);
previousFrameTime = now;
if (running) {
accumulator += frameDelta;
while (accumulator >= fixedTimeStep) {
integrateStep(fixedTimeStep);
accumulator -= fixedTimeStep;
}
}
updateScene();
statsTimer += frameDelta;
scopeTimer += frameDelta;
if (statsTimer > 0.12) {
refreshStats();
statsTimer = 0;
}
if (scopeTimer > 1 / 30) {
drawScope();
scopeTimer = 0;
}
renderer.render(scene, camera);
}
requestAnimationFrame(animate);
</script>
</body>
</html>
```