Prompt specification
Build or customize the Three.js 3D scene "Longitudinal compression spring display" 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: Longitudinal compression spring display
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/longitudinal-compression-spring-display-x1598
Scene Description Prompt:
I'd like to see this as a stylized Three.js scene: longitudinal compression spring display. Arrange particles along a line with periodic compression and rarefaction; animate displacement parallel to propagation and contrast it with an adjacent transverse-wave strip. Use cdnjs and return one self-contained HTML file.
Working Three.js Starter (longitudinal-compression-spring-display-x1598):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Longitudinal Compression Spring vs. Transverse Wave</title>
<style>
:root{
--ink:#e8eefc;
--dim:#9fb0d4;
--cyan:#22e3ff;
--pink:#ff6ad5;
--amber:#ffb347;
--hot:#ff4d3d;
--cool:#4d8cff;
--panel:rgba(12,18,34,.72);
--edge:rgba(120,160,230,.22);
}
*{box-sizing:border-box}
html,body{margin:0;height:100%;overflow:hidden;background:#06090f;color:var(--ink);
font-family:ui-sans-serif,system-ui,"Segoe UI",Roboto,Helvetica,Arial,sans-serif}
#scene{display:block;width:100%;height:100%;touch-action:none}
.panel{
position:fixed;background:var(--panel);border:1px solid var(--edge);border-radius:14px;
backdrop-filter:blur(10px);-webkit-backdrop-filter:blur(10px);
box-shadow:0 10px 40px rgba(0,0,0,.45);padding:12px 14px;
}
#title{top:16px;left:16px;max-width:min(420px,60vw)}
#title h1{margin:0;font-size:15px;letter-spacing:.14em;text-transform:uppercase;font-weight:700}
#title h1 span{color:var(--cyan)}
#title p{margin:6px 0 0;font-size:12px;line-height:1.5;color:var(--dim)}
#legend{bottom:16px;left:16px;min-width:250px}
#legend .row{display:flex;align-items:center;gap:9px;font-size:12px;margin:5px 0;color:#d6e2fb}
.chip{width:22px;height:6px;border-radius:3px;flex:0 0 auto}
.dot{width:11px;height:11px;border-radius:50%;flex:0 0 auto}
#controls{display:flex;flex-wrap:wrap;gap:10px;align-items:center;margin-top:11px;
padding-top:10px;border-top:1px solid var(--edge);font-size:12px;color:var(--dim)}
button,label.btn{cursor:pointer;color:var(--ink);background:rgba(70,110,190,.16);
border:1px solid var(--edge);border-radius:8px;padding:5px 11px;font:inherit;font-size:12px;
transition:background .15s}
button:hover,label.btn:hover{background:rgba(70,110,190,.32)}
input[type=range]{width:110px;accent-color:var(--cyan);vertical-align:middle}
input[type=checkbox]{accent-color:var(--cyan)}
#plot{bottom:16px;right:16px;padding:10px 12px 6px}
#plot h2{margin:0 0 6px;font-size:11px;letter-spacing:.12em;text-transform:uppercase;color:var(--dim);font-weight:600}
#plot canvas{display:block;border-radius:8px;background:rgba(4,8,18,.6)}
#hint{top:16px;right:16px;font-size:11px;color:var(--dim);letter-spacing:.04em;text-align:right}
#hint b{color:var(--ink);font-weight:600}
@media (max-width:820px){#plot{display:none}#hint{display:none}}
</style>
</head>
<body>
<canvas id="scene"></canvas>
<div id="title" class="panel">
<h1>Compression Spring <span>vs</span> Transverse Wave</h1>
<p>A single travelling wave drawn two ways. The upper strip is a <b style="color:var(--cyan)">longitudinal</b>
spring: beads slide <i>along</i> the line, so the coil bunches into travelling
<i>compression</i> and <i>rarefaction</i> bands. The lower strip is a
<b style="color:var(--pink)">transverse</b> wave: the rope moves <i>across</i> the line,
forming crests and troughs that travel down the strip.</p>
</div>
<div id="hint" class="panel">
<b>drag</b> orbit · <b>scroll</b> zoom · <b>space</b> pause
</div>
<div id="legend" class="panel">
<div class="row"><i class="chip" style="background:linear-gradient(90deg,#4d8cff,#ffb347,#ff4d3d)"></i>
compression spring (coil colour = local strain)</div>
<div class="row"><i class="dot" style="background:var(--cyan)"></i> longitudinal beads — motion <b>∥</b> propagation</div>
<div class="row"><i class="dot" style="background:var(--pink)"></i> transverse beads — motion <b>⊥</b> propagation</div>
<div class="row"><i class="dot" style="background:#8fa3cc;opacity:.55"></i> equilibrium (rest) positions</div>
<div id="controls">
<button id="playBtn">⏸ pause</button>
<label>speed <input id="speed" type="range" min="0.15" max="2.5" step="0.05" value="1"></label>
<label><input id="vectors" type="checkbox" checked> vectors</label>
<label class="btn" id="resetBtn">reset view</label>
</div>
</div>
<div id="plot" class="panel">
<h2>instantaneous profiles</h2>
<canvas id="plotCanvas" width="600" height="290"></canvas>
</div>
<script type="module">
import * as THREE from 'https://cdnjs.cloudflare.com/ajax/libs/three.js/0.160.0/three.module.min.js';
/* ------------------------------------------------------------------ setup */
const canvas = document.getElementById('scene');
const renderer = new THREE.WebGLRenderer({ canvas, antialias:true });
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setSize(innerWidth, innerHeight);
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.15;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x070b16);
scene.fog = new THREE.Fog(0x070b16, 18, 46);
const camera = new THREE.PerspectiveCamera(45, innerWidth/innerHeight, 0.1, 220);
camera.position.set(0, 4.2, 11.4);
/* ----------------------------------------------------------------- lights */
scene.add(new THREE.HemisphereLight(0x9fc4ff, 0x0a0f1c, 0.55));
const key = new THREE.DirectionalLight(0xffffff, 2.0);
key.position.set(6, 11, 8);
key.castShadow = true;
key.shadow.mapSize.set(2048,2048);
Object.assign(key.shadow.camera, { left:-11, right:11, top:9, bottom:-9, near:1, far:42 });
key.shadow.bias = -0.0008; key.shadow.normalBias = 0.02;
scene.add(key);
const fill = new THREE.DirectionalLight(0x4aa8ff, 0.7); fill.position.set(-8,4,-6); scene.add(fill);
const rim = new THREE.DirectionalLight(0xff7ad9, 0.45); rim.position.set(2,-3,7); scene.add(rim);
/* ------------------------------------------------------------------ floor */
const floor = new THREE.Mesh(
new THREE.PlaneGeometry(80,80),
new THREE.MeshStandardMaterial({ color:0x0b1120, roughness:0.92, metalness:0.05 })
);
floor.rotation.x = -Math.PI/2; floor.position.y = -3.12; floor.receiveShadow = true;
scene.add(floor);
const grid = new THREE.GridHelper(60, 60, 0x1f3157, 0x121d33);
grid.position.y = -3.10; grid.material.transparent = true; grid.material.opacity = 0.5;
scene.add(grid);
/* ------------------------------------------------------------- wave model */
const L = 12, HALF = L/2; // strip length
const BEADS = 33; // particles per strip
const WAVELENGTH = 2.4;
const K = Math.PI*2/WAVELENGTH;
const OMEGA = Math.PI*2*0.32; // angular frequency
const A_LONG = 0.20, A_TRANS = 0.72;
const COIL_Y = 1.95, COIL_R = 0.26, TURNS = 22;
const ROW_Y = 1.00, WAVE_Y = -1.50;
const clamp = THREE.MathUtils.clamp;
const smoothstep = t => t*t*(3-2*t);
function taper(x){ // fade the wave train at the strip ends
const a = clamp((x+HALF)/1.3,0,1), b = clamp((HALF-x)/1.3,0,1);
return smoothstep(a)*smoothstep(b);
}
let time = 0;
const phase = (x,t) => K*x - OMEGA*t;
const u = (x,t) => A_LONG * Math.sin(phase(x,t)) * taper(x); // longitudinal displacement
const v = (x,t) => A_TRANS * Math.sin(phase(x,t)) * taper(x); // transverse displacement
const strain = (x,t) => A_LONG*K*Math.cos(phase(x,t))*taper(x);// local compression (>0 = stretched)
const beadX = i => -HALF + i*(L/(BEADS-1));
/* --------------------------------------------------------------- palette */
const C_NEUTRAL = new THREE.Color(0xffb347);
const C_COMPRESS= new THREE.Color(0xff4d3d);
const C_RAREFACT= new THREE.Color(0x4d8cff);
const C_CREST = new THREE.Color(0xff7ade);
const C_TROUGH = new THREE.Color(0x6b3bc4);
const scratch = new THREE.Color();
function strainColor(s, out){ // s in [-1,1]
if(s >= 0) return out.copy(C_NEUTRAL).lerp(C_RAREFACT, s);
return out.copy(C_NEUTRAL).lerp(C_COMPRESS, -s);
}
/* ------------------------------------------------------------- tube maker */
function createTubeGeometry(tub, rad){
const count = (tub+1)*(rad+1);
const g = new THREE.BufferGeometry();
g.setAttribute('position', new THREE.BufferAttribute(new Float32Array(count*3),3));
g.setAttribute('normal', new THREE.BufferAttribute(new Float32Array(count*3),3));
g.setAttribute('color', new THREE.BufferAttribute(new Float32Array(count*3),3));
const idx = [];
for(let i=0;i<tub;i++) for(let j=0;j<rad;j++){
const a=i*(rad+1)+j, b=(i+1)*(rad+1)+j, c=(i+1)*(rad+1)+j+1, d=i*(rad+1)+j+1;
idx.push(a,b,d, b,c,d);
}
g.setIndex(idx);
g.boundingSphere = new THREE.Sphere(new THREE.Vector3(0,0.8,0), 14);
return g;
}
const _tan = new THREE.Vector3(), _nor = new THREE.Vector3(), _bin = new THREE.Vector3();
function updateTube(geo, pts, radius, rad, normalFn, colorFn){
const P = geo.attributes.position.array, N = geo.attributes.normal.array, C = geo.attributes.color.array;
const n = pts.length;
for(let i=0;i<n;i++){
const p = pts[i];
if(i===0) _tan.subVectors(pts[1],pts[0]);
else if(i===n-1) _tan.subVectors(pts[n-1],pts[n-2]);
else _tan.subVectors(pts[i+1],pts[i-1]);
_tan.normalize();
normalFn(i,p,_nor,_tan);
_bin.crossVectors(_tan,_nor).normalize();
let col = null; if(colorFn) col = colorFn(i);
for(let j=0;j<=rad;j++){
const a = j/rad*Math.PI*2, c = Math.cos(a), s = Math.sin(a);
const nx = _nor.x*c + _bin.x*s, ny = _nor.y*c + _bin.y*s, nz = _nor.z*c + _bin.z*s;
const o = (i*(rad+1)+j)*3;
P[o]=p.x+radius*nx; P[o+1]=p.y+radius*ny; P[o+2]=p.z+radius*nz;
N[o]=nx; N[o+1]=ny; N[o+2]=nz;
if(col){ C[o]=col.r; C[o+1]=col.g; C[o+2]=col.b; }
}
}
geo.attributes.position.needsUpdate = true;
geo.attributes.normal.needsUpdate = true;
geo.attributes.color.needsUpdate = true;
}
/* --------------------------------------------------------- arrow factory */
const shaftS = new THREE.CylinderGeometry(0.018,0.018,1,10);
const headS = new THREE.ConeGeometry(0.055,0.12,12);
const shaftB = new THREE.CylinderGeometry(0.042,0.042,1,12);
const headB = new THREE.ConeGeometry(0.125,0.30,14);
const arrowMats = new Map();
function arrowMat(c){
if(!arrowMats.has(c)) arrowMats.set(c, new THREE.MeshStandardMaterial({
color:c, emissive:c, emissiveIntensity:0.45, roughness:0.35, metalness:0.0 }));
return arrowMats.get(c);
}
const UP = new THREE.Vector3(0,1,0);
function makeArrow(color, big=false){
const mat = arrowMat(color), g = new THREE.Group();
const shaft = new THREE.Mesh(big?shaftB:shaftS, mat);
const head = new THREE.Mesh(big?headB:headS, mat);
g.add(shaft, head);
g.userData = { shaft, head, hl: big?0.30:0.12 };
return g;
}
function setArrow(arrow, ox,oy,oz, dx,dy,dz, length){
const {shaft,head,hl} = arrow.userData;
const len = Math.max(length, 0.03);
const h = Math.min(hl, len*0.48), s = len - h;
const dir = new THREE.Vector3(dx,dy,dz);
if(dir.lengthSq() < 1e-9) dir.set(1,0,0); else dir.normalize();
arrow.position.set(ox,oy,oz);
arrow.quaternion.setFromUnitVectors(UP, dir);
shaft.scale.set(1,s,1); shaft.position.set(0,s/2,0);
head.scale.set(1,h/hl,1); head.position.set(0,s+h/2,0);
}
/* ------------------------------------------------------------- text labels */
function makeLabel(text, color, sub, width){
const c = document.createElement('canvas');
c.width = 1024; c.height = 256;
const g = c.getContext('2d');
g.textAlign = 'center'; g.textBaseline = 'middle';
g.fillStyle = color; g.font = '700 88px ui-sans-serif, system-ui, sans-serif';
g.fillText(text, 512, sub?74:128);
if(sub){
g.fillStyle = 'rgba(196,210,238,.85)'; g.font = '500 50px ui-sans-serif, system-ui, sans-serif';
g.fillText(sub, 512, 178);
}
const tex = new THREE.CanvasTexture(c); tex.colorSpace = THREE.SRGBColorSpace;
const spr = new THREE.Sprite(new THREE.SpriteMaterial({ map:tex, transparent:true, depthTest:false }));
spr.scale.set(width, width*0.25, 1);
spr.renderOrder = 20;
return spr;
}
/* ================================================================ SCENE OBJ */
/* ---- longitudinal strip : the compression spring ----------------------- */
const COIL_PTS = 220;
const coilPts = Array.from({length:COIL_PTS+1}, ()=>new THREE.Vector3());
const coilGeo = createTubeGeometry(COIL_PTS, 6);
const coil = new THREE.Mesh(coilGeo, new THREE.MeshStandardMaterial({
vertexColors:true, metalness:0.85, roughness:0.26
}));
coil.castShadow = true; scene.add(coil);
function coilNormal(i,p,nor,tan){
const th = (i/COIL_PTS)*TURNS*Math.PI*2;
nor.set(0, Math.cos(th), Math.sin(th)); // radial direction ⊥ to helix tangent
}
function coilColor(i){
const m = i/COIL_PTS, x0 = -HALF + m*L;
return strainColor(strain(x0,time)/(A_LONG*K), scratch);
}
/* equilibrium rail */
const railGeo = new THREE.BoxGeometry(L+0.8, 0.035, 0.035);
const railMat = new THREE.MeshStandardMaterial({ color:0x2b3c60, roughness:0.5, metalness:0.4 });
const railTop = new THREE.Mesh(railGeo, railMat); railTop.position.set(0, ROW_Y, -0.22); scene.add(railTop);
const railBot = new THREE.Mesh(railGeo, railMat); railBot.position.set(0, WAVE_Y, -0.22); scene.add(railBot);
/* beads (instanced) */
const beadGeo = new THREE.SphereGeometry(0.085, 20, 14);
const longBeads = new THREE.InstancedMesh(beadGeo,
new THREE.MeshStandardMaterial({ color:0xffffff, roughness:0.3, metalness:0.15 }), BEADS);
longBeads.castShadow = true; longBeads.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
scene.add(longBeads);
const transBeads = new THREE.InstancedMesh(beadGeo,
new THREE.MeshStandardMaterial({ color:0xffffff, roughness:0.32, metalness:0.12 }), BEADS);
transBeads.castShadow = true; transBeads.instanceMatrix.setUsage(THREE.DynamicDrawUsage);
scene.add(transBeads);
/* rest-position ghosts */
const ghostGeo = new THREE.SphereGeometry(0.088, 12, 8);
const ghostMat = new THREE.MeshBasicMaterial({
color:0x93a7cc, wireframe:true, transparent:true, opacity:0.32, depthWrite:false });
const ghostsLong = new THREE.InstancedMesh(ghostGeo, ghostMat, BEADS); scene.add(ghostsLong);
const ghostsTrans= new THREE.InstancedMesh(ghostGeo, ghostMat, BEADS); scene.add(ghostsTrans);
/* ---- transverse strip : the travelling rope ---------------------------- */
const ROPE_PTS = 132;
const ropePts = Array.from({length:ROPE_PTS+1}, ()=>new THREE.Vector3());
const ropeGeo = createTubeGeometry(ROPE_PTS, 6);
const rope = new THREE.Mesh(ropeGeo, new THREE.MeshStandardMaterial({
vertexColors:true, roughness:0.38, metalness:0.25 }));
rope.castShadow = true; scene.add(rope);
function ropeNormal(i,p,nor,tan){ nor.set(0,0,1); }
function ropeColor(i){
const x = -HALF + (i/ROPE_PTS)*L;
const n = v(x,time)/A_TRANS;
return scratch.copy(C_TROUGH).lerp(C_CREST, (n+1)*0.5);
}
/* ---- vector overlay (displacement arrows) ------------------------------ */
const vectors = new THREE.Group(); scene.add(vectors);
const longArrows = [], transArrows = [];
for(let i=0;i<BEADS;i++){
if(i%3) continue;
const a = makeArrow(0x22e3ff); vectors.add(a); longArrows.push({obj:a, i});
const b = makeArrow(0xff6ad5); vectors.add(b); transArrows.push({obj:b, i});
}
/* propagation arrows */
const propTop = makeArrow(0x22e3ff, true); scene.add(propTop);
const propBot = makeArrow(0xff6ad5, true); scene.add(propBot);
/* ---- labels ------------------------------------------------------------ */
const labLong = makeLabel('LONGITUDINAL', '#22e3ff', 'displacement ∥ propagation', 2.7);
labLong.position.set(-4.7, 2.85, 0); scene.add(labLong);
const labTrans = makeLabel('TRANSVERSE', '#ff6ad5', 'displacement ⊥ propagation', 2.7);
labTrans.position.set(-4.7, -2.85, 0); scene.add(labTrans);
const labProp = makeLabel('propagation →', '#cfd9f2', '', 1.5);
labProp.position.set(7.9, 1.85, 0); scene.add(labProp);
const tagCompress = makeLabel('COMPRESSION', '#ff6b52', '', 1.35);
const tagRare = makeLabel('RAREFACTION', '#6fa4ff', '', 1.35);
scene.add(tagCompress, tagRare);
/* =============================================================== UPDATE LOOP */
const dummy = new THREE.Object3D();
function zoneX(targetPhase){
const lam = 2*K ? (Math.PI*2)/K : 0;
let x = (OMEGA*time + targetPhase)/K;
x -= Math.round(x/lam)*lam; // closest copy to the centre
return x;
}
function update(t){
/* coil geometry */
for(let i=0;i<=COIL_PTS;i++){
const m = i/COIL_PTS, x0 = -HALF + m*L, th = m*TURNS*Math.PI*2;
coilPts[i].set(x0 + u(x0,t), COIL_Y + COIL_R*Math.cos(th), COIL_R*Math.sin(th));
}
updateTube(coilGeo, coilPts, 0.045, 6, coilNormal, coilColor);
/* rope geometry */
for(let i=0;i<=ROPE_PTS;i++){
const x = -HALF + (i/ROPE_PTS)*L;
ropePts[i].set(x, WAVE_Y + v(x,t), 0);
}
updateTube(ropeGeo, ropePts, 0.055, 6, ropeNormal, ropeColor);
/* beads + ghosts + arrows */
for(let i=0;i<BEADS;i++){
const x0 = beadX(i);
/* longitudinal */
const dx = u(x0,t);
dummy.position.set(x0+dx, ROW_Y, 0); dummy.updateMatrix();
longBeads.setMatrixAt(i, dummy.matrix);
strainColor(strain(x0,t)/(A_LONG*K), scratch);
longBeads.setColorAt(i, scratch);
dummy.position.set(x0, ROW_Y, 0); dummy.updateMatrix();
ghostsLong.setMatrixAt(i, dummy.matrix);
/* transverse */
const dy = v(x0,t);
dummy.position.set(x0, WAVE_Y+dy, 0); dummy.updateMatrix();
transBeads.setMatrixAt(i, dummy.matrix);
scratch.copy(C_TROUGH).lerp(C_CREST, (dy/A_TRANS+1)*0.5);
transBeads.setColorAt(i, scratch);
dummy.position.set(x0, WAVE_Y, 0); dummy.updateMatrix();
ghostsTrans.setMatrixAt(i, dummy.matrix);
}
longBeads.instanceMatrix.needsUpdate = true;
transBeads.instanceMatrix.needsUpdate = true;
if(longBeads.instanceColor) longBeads.instanceColor.needsUpdate = true;
if(transBeads.instanceColor) transBeads.instanceColor.needsUpdate = true;
for(const a of longArrows){
const x0 = beadX(a.i), dx = u(x0,t);
setArrow(a.obj, x0, ROW_Y, 0.42, Math.sign(dx)||1, 0, 0, Math.abs(dx));
}
for(const a of transArrows){
const x0 = beadX(a.i), dy = v(x0,t);
setArrow(a.obj, x0, WAVE_Y, 0.42, 0, Math.sign(dy)||1, 0, Math.abs(dy));
}
/* propagation arrows */
setArrow(propTop, 6.35, ROW_Y, 0.42, 1,0,0, 1.5);
setArrow(propBot, 6.35, WAVE_Y, 0.42, 1,0,0, 1.5);
/* travelling strain tags */
const xc = zoneX(Math.PI), xr = zoneX(0);
tagCompress.position.set(xc, 2.48, 0);
tagRare.position.set(xr, 2.48, 0);
tagCompress.material.opacity = 1;
tagRare.material.opacity = 1;
}
/* ============================================================ CAMERA / INPUT */
const cam = { theta:0.0, phi:1.22, radius:12.4, tx:0, ty:0.25, tz:0 };
const camWant = { ...cam };
let dragging = false, lastX = 0, lastY = 0;
const pointers = new Map();
let pinchDist = 0;
canvas.addEventListener('pointerdown', e=>{
pointers.set(e.pointerId, {x:e.clientX, y:e.clientY});
if(pointers.size === 1){ dragging = true; lastX = e.clientX; lastY = e.clientY; }
else if(pointers.size === 2){
const [a,b] = [...pointers.values()];
pinchDist = Math.hypot(a.x-b.x, a.y-b.y);
}
canvas.setPointerCapture(e.pointerId);
});
canvas.addEventListener('pointermove', e=>{
if(!pointers.has(e.pointerId)) return;
pointers.set(e.pointerId, {x:e.clientX, y:e.clientY});
if(pointers.size === 1 && dragging){
camWant.theta -= (e.clientX - lastX) * 0.0055;
camWant.phi = clamp(camWant.phi - (e.clientY - lastY) * 0.0045, 0.28, 1.48);
lastX = e.clientX; lastY = e.clientY;
} else if(pointers.size === 2){
const [a,b] = [...pointers.values()];
const d = Math.hypot(a.x-b.x, a.y-b.y);
if(pinchDist) camWant.radius = clamp(camWant.radius * (pinchDist/d), 5.5, 34);
pinchDist = d;
}
});
const endPtr = e=>{ pointers.delete(e.pointerId); if(pointers.size < 2) pinchDist = 0; if(pointers.size === 0) dragging = false; };
canvas.addEventListener('pointerup', endPtr);
canvas.addEventListener('pointercancel', endPtr);
canvas.addEventListener('pointerleave', endPtr);
canvas.addEventListener('wheel', e=>{
e.preventDefault();
camWant.radius = clamp(camWant.radius * (1 + e.deltaY*0.0011), 5.5, 34);
}, {passive:false});
function updateCamera(){
cam.theta += (camWant.theta - cam.theta)*0.14;
cam.phi += (camWant.phi - cam.phi )*0.14;
cam.radius+= (camWant.radius-cam.radius)*0.12;
const sp = Math.sin(cam.phi), cp = Math.cos(cam.phi);
camera.position.set(
cam.tx + cam.radius*sp*Math.sin(cam.theta),
cam.ty + cam.radius*cp,
cam.tz + cam.radius*sp*Math.cos(cam.theta));
camera.lookAt(cam.tx, cam.ty, cam.tz);
}
/* ==================================================================== HUD */
const playBtn = document.getElementById('playBtn');
const speedIn = document.getElementById('speed');
const vecIn = document.getElementById('vectors');
const resetBtn= document.getElementById('resetBtn');
let playing = true, speed = 1;
playBtn.onclick = ()=>{ playing = !playing; playBtn.textContent = playing ? '⏸ pause' : '▶ play'; };
speedIn.oninput = ()=>{ speed = parseFloat(speedIn.value); };
vecIn.onchange = ()=>{ vectors.visible = vecIn.checked; ghostsLong.visible = ghostsTrans.visible = vecIn.checked; };
resetBtn.onclick= ()=>{ camWant.theta=0; camWant.phi=1.22; camWant.radius=12.4; camWant.tx=0; camWant.ty=0.25; camWant.tz=0; };
window.addEventListener('keydown', e=>{ if(e.code === 'Space'){ e.preventDefault(); playBtn.click(); } });
/* mini profile plot */
const pc = document.getElementById('plotCanvas'), pctx = pc.getContext('2d');
function drawPlot(){
const w = pc.width, h = pc.height, pad = 26;
pctx.clearRect(0,0,w,h);
const x2p = x => pad + (x+HALF)/L*(w-2*pad);
const rows = [
{y0:26, y1:h/2-14, amp:A_LONG, col:'#22e3ff', title:'u(x) longitudinal', dot:0},
{y0:h/2+14, y1:h-26, amp:A_TRANS, col:'#ff6ad5', title:'v(x) transverse', dot:0}
];
pctx.font = '500 20px ui-sans-serif, system-ui, sans-serif';
for(const r of rows){
const mid = (r.y0+r.y1)/2, halfH = (r.y1-r.y0)/2;
pctx.strokeStyle = 'rgba(140,160,205,.28)'; pctx.lineWidth = 2;
pctx.beginPath(); pctx.moveTo(pad, mid); pctx.lineTo(w-pad, mid); pctx.stroke();
pctx.strokeStyle = r.col; pctx.lineWidth = 4; pctx.beginPath();
for(let i=0;i<=160;i++){
const x = -HALF + (i/160)*L;
const val = (r.amp===A_LONG ? u(x,time) : v(x,time))/r.amp;
const py = mid - val*halfH*0.88;
i ? pctx.lineTo(x2p(x), py) : pctx.moveTo(x2p(x), py);
}
pctx.stroke();
pctx.fillStyle = r.col;
for(let i=0;i<BEADS;i++){
const x = beadX(i);
const val = (r.amp===A_LONG ? u(x,time) : v(x,time))/r.amp;
pctx.beginPath(); pctx.arc(x2p(x), mid - val*halfH*0.88, 5, 0, 7); pctx.fill();
}
pctx.fillStyle = 'rgba(200,214,240,.75)';
pctx.textAlign = 'left';
pctx.fillText(r.title, pad-6, r.y0 - 6);
}
pctx.textAlign='right'; pctx.fillStyle='rgba(200,214,240,.55)';
pctx.fillText('x →', w-pad, h-6);
}
/* =================================================================== LOOP */
const clock = new THREE.Clock();
function animate(){
const dt = Math.min(clock.getDelta(), 0.05);
if(playing) time += dt*speed;
update(time);
updateCamera();
drawPlot();
renderer.render(scene, camera);
requestAnimationFrame(animate);
}
animate();
window.addEventListener('resize', ()=>{
camera.aspect = innerWidth/innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(innerWidth, innerHeight);
});
</script>
</body>
</html>
```