Prompt specification
Build or customize the Three.js 3D scene "Square-like waveform partial-sum 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: Square-like waveform partial-sum display
Category: Science & Physics · Style: Procedural Solid / Shader 3D
License: MIT · Reference: https://three3d.app/scene/square-like-waveform-partial-sum-display-x1546
Scene Description Prompt:
Build a self-contained HTML scene with Three.js from cdnjs featuring Fourier components and musical harmonics. Add odd harmonics successively to a periodic signal and show the changing approximation; label finite truncation and retain overshoot rather than falsely smoothing it away. Stylized solid forms.
Working Three.js Starter (square-like-waveform-partial-sum-display-x1546):
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Fourier Harmonics — Odd Partial Synthesis</title>
<style>
:root {
--ink: #21313b;
--paper: #f2ecdf;
--paper-dark: #ddd8cc;
--orange: #ef653b;
--red: #d94335;
--blue: #3269bd;
--muted: #68757a;
}
* {
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background: #d9dfdc;
color: var(--ink);
font-family: Inter, ui-sans-serif, system-ui, -apple-system,
BlinkMacSystemFont, "Segoe UI", sans-serif;
}
#scene {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
display: block;
touch-action: none;
cursor: grab;
}
#scene:active {
cursor: grabbing;
}
.ui {
position: fixed;
inset: 0;
pointer-events: none;
z-index: 5;
}
header {
position: absolute;
top: 25px;
left: 28px;
max-width: 470px;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.35);
}
.kicker {
display: inline-block;
margin-bottom: 12px;
padding: 6px 9px;
border: 1.5px solid var(--ink);
background: rgba(242, 236, 223, 0.84);
font: 800 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.16em;
}
h1 {
margin: 0;
font-size: clamp(34px, 4.3vw, 62px);
line-height: 0.93;
letter-spacing: -0.055em;
}
header p {
max-width: 390px;
margin: 13px 0 0;
color: #43535a;
font-size: 14px;
line-height: 1.45;
}
.status {
position: absolute;
top: 24px;
right: 25px;
display: flex;
gap: 10px;
}
.status-card {
width: 185px;
padding: 12px 14px 11px;
border: 1.5px solid var(--ink);
background: rgba(242, 236, 223, 0.92);
box-shadow: 4px 4px 0 rgba(33, 49, 59, 0.92);
}
.status-card.alert {
background: rgba(255, 231, 222, 0.95);
}
.status-card span {
display: block;
margin-bottom: 5px;
color: var(--muted);
font: 800 9px/1.2 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.13em;
}
.status-card strong {
display: block;
font-size: 20px;
line-height: 1.05;
letter-spacing: -0.035em;
}
.status-card small {
display: block;
margin-top: 5px;
color: var(--muted);
font-size: 10px;
line-height: 1.3;
}
.controls {
position: absolute;
left: 24px;
bottom: 24px;
width: min(750px, calc(100vw - 48px));
padding: 14px 16px 12px;
border: 2px solid var(--ink);
border-radius: 17px;
background: rgba(245, 239, 227, 0.95);
box-shadow: 6px 6px 0 var(--ink);
pointer-events: auto;
backdrop-filter: blur(8px);
}
.control-row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 9px;
}
.control-row + .control-row {
margin-top: 11px;
padding-top: 11px;
border-top: 1px solid rgba(33, 49, 59, 0.2);
}
button {
min-height: 36px;
padding: 8px 12px;
border: 1.5px solid var(--ink);
border-radius: 9px;
background: var(--paper);
color: var(--ink);
font: 850 11px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.045em;
cursor: pointer;
transition:
transform 120ms ease,
background 120ms ease,
opacity 120ms ease;
}
button:hover:not(:disabled) {
transform: translateY(-2px);
}
button:active:not(:disabled) {
transform: translateY(1px);
}
button.primary {
min-width: 188px;
background: var(--orange);
color: #fffaf1;
}
button.listening {
background: var(--blue);
color: white;
}
button:disabled {
cursor: not-allowed;
opacity: 0.45;
}
.partials {
display: flex;
align-items: center;
gap: 5px;
margin-left: auto;
}
.partials-label {
margin-right: 3px;
color: var(--muted);
font: 800 9px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.12em;
}
.chip {
position: relative;
width: 37px;
min-height: 34px;
padding: 4px;
border-radius: 50%;
background: transparent;
font-size: 12px;
}
.chip.active {
background: var(--ink);
color: var(--paper);
}
.chip.passed {
border-color: var(--orange);
color: var(--orange);
}
.chip.active.passed {
color: #fff6e8;
}
.frequency {
display: grid;
grid-template-columns: auto auto;
align-items: center;
gap: 2px 10px;
min-width: 220px;
margin-right: auto;
font: 800 10px/1 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.05em;
}
.frequency output {
color: var(--orange);
text-align: right;
}
.frequency input {
grid-column: 1 / -1;
width: 100%;
accent-color: var(--orange);
cursor: pointer;
}
.caveat {
display: flex;
align-items: center;
gap: 8px;
margin: 10px 0 0;
color: #536168;
font-size: 10px;
line-height: 1.35;
}
.caveat::before {
content: "";
flex: 0 0 8px;
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--red);
box-shadow: 0 0 0 3px rgba(217, 67, 53, 0.13);
}
.hint {
position: absolute;
right: 25px;
bottom: 27px;
color: rgba(33, 49, 59, 0.7);
font: 750 9px/1.3 ui-monospace, SFMono-Regular, Menlo, monospace;
letter-spacing: 0.11em;
text-align: right;
}
@media (max-width: 760px) {
header {
top: 16px;
left: 17px;
}
header p {
display: none;
}
.status {
top: 15px;
right: 15px;
gap: 6px;
}
.status-card {
width: 135px;
padding: 9px;
}
.status-card strong {
font-size: 16px;
}
.status-card small {
display: none;
}
.controls {
left: 14px;
bottom: 14px;
width: calc(100vw - 28px);
padding: 11px;
}
.partials {
margin-left: 0;
}
.frequency {
min-width: 170px;
}
.hint {
display: none;
}
}
</style>
</head>
<body>
<canvas id="scene" aria-label="Interactive Fourier harmonic visualization"></canvas>
<div class="ui">
<header>
<div class="kicker">FOURIER STUDY / 01</div>
<h1>Odd harmonics,<br>one at a time.</h1>
<p>
A finite square-wave synthesis. Add musical partials and watch the
approximation change—without hiding the ringing at the discontinuities.
</p>
</header>
<section class="status" aria-live="polite">
<div class="status-card">
<span>FINITE TRUNCATION</span>
<strong id="truncationValue">N = 1 · 1 odd term</strong>
<small id="equationValue">Σ odd n ≤ 1 bₙ sin(nt)</small>
</div>
<div class="status-card alert">
<span>GIBBS PEAK</span>
<strong id="peakValue">1.273</strong>
<small id="peakNote">target 1.000 · overshoot retained</small>
</div>
</section>
<section class="controls">
<div class="control-row">
<button class="primary" id="addHarmonic">ADD 3f HARMONIC</button>
<button id="resetHarmonics">RESET</button>
<div class="partials" aria-label="Odd harmonic partials">
<span class="partials-label">ODD PARTIALS</span>
<div id="partialButtons" style="display:flex; gap:5px"></div>
</div>
</div>
<div class="control-row">
<label class="frequency" for="fundamental">
<span>FUNDAMENTAL</span>
<output id="frequencyValue">110 Hz</output>
<input
id="fundamental"
type="range"
min="80"
max="440"
step="10"
value="110"
>
</label>
<button id="listen">LISTEN TO STACK</button>
<button id="resetView">RESET VIEW</button>
</div>
<p class="caveat">
No windowing or smoothing. This is a finite partial sum, so the
Gibbs overshoot remains visible and audibly characteristic.
</p>
</section>
<div class="hint">
DRAG TO ORBIT · WHEEL TO ZOOM<br>
SHIFT-DRAG TO PAN · DOUBLE-CLICK TO RESET
</div>
</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 constants
// -------------------------------------------------------------------------
const canvas = document.querySelector("#scene");
const addButton = document.querySelector("#addHarmonic");
const resetButton = document.querySelector("#resetHarmonics");
const resetViewButton = document.querySelector("#resetView");
const listenButton = document.querySelector("#listen");
const fundamentalInput = document.querySelector("#fundamental");
const frequencyValue = document.querySelector("#frequencyValue");
const truncationValue = document.querySelector("#truncationValue");
const equationValue = document.querySelector("#equationValue");
const peakValue = document.querySelector("#peakValue");
const peakNote = document.querySelector("#peakNote");
const partialButtons = document.querySelector("#partialButtons");
const ODD_HARMONICS = [1, 3, 5, 7, 9];
const HARMONIC_COLORS = [
0xef653b,
0x3269bd,
0xd8a126,
0x73539a,
0x2e846f
];
const WAVE_SAMPLES = 1200;
const WAVE_X0 = -8.92;
const WAVE_X1 = 1.95;
const WAVE_CENTER_Y = -0.55;
const WAVE_AMPLITUDE = 1.65;
let activeCount = 1;
let fundamental = Number(fundamentalInput.value);
// -------------------------------------------------------------------------
// Renderer, scene and lighting
// -------------------------------------------------------------------------
const renderer = new THREE.WebGLRenderer({
canvas,
antialias: true,
powerPreference: "high-performance"
});
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.outputColorSpace = THREE.SRGBColorSpace;
renderer.toneMapping = THREE.ACESFilmicToneMapping;
renderer.toneMappingExposure = 1.05;
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xd9dfdc);
const camera = new THREE.OrthographicCamera(-10, 10, 6, -6, 0.1, 100);
const cameraState = {
target: new THREE.Vector3(0.15, 0, 0),
theta: 0,
phi: 0,
zoom: 1
};
scene.add(new THREE.HemisphereLight(0xffffff, 0x87979a, 2.2));
const keyLight = new THREE.DirectionalLight(0xfff4df, 3.2);
keyLight.position.set(-5, 9, 12);
keyLight.castShadow = true;
keyLight.shadow.mapSize.set(2048, 2048);
keyLight.shadow.camera.left = -16;
keyLight.shadow.camera.right = 16;
keyLight.shadow.camera.top = 10;
keyLight.shadow.camera.bottom = -10;
keyLight.shadow.camera.near = 1;
keyLight.shadow.camera.far = 35;
keyLight.shadow.bias = -0.0004;
scene.add(keyLight);
const rimLight = new THREE.DirectionalLight(0x9fc7ff, 1.15);
rimLight.position.set(10, -4, 7);
scene.add(rimLight);
const backdrop = new THREE.Mesh(
new THREE.PlaneGeometry(54, 32),
new THREE.MeshStandardMaterial({
color: 0xd9dfdc,
roughness: 1
})
);
backdrop.position.z = -1.25;
backdrop.receiveShadow = true;
scene.add(backdrop);
// -------------------------------------------------------------------------
// Utility geometry
// -------------------------------------------------------------------------
function roundedRectangleShape(width, height, radius) {
const x = -width / 2;
const y = -height / 2;
const r = Math.min(radius, width / 2, height / 2);
const shape = new THREE.Shape();
shape.moveTo(x + r, y);
shape.lineTo(x + width - r, y);
shape.quadraticCurveTo(x + width, y, x + width, y + r);
shape.lineTo(x + width, y + height - r);
shape.quadraticCurveTo(
x + width,
y + height,
x + width - r,
y + height
);
shape.lineTo(x + r, y + height);
shape.quadraticCurveTo(x, y + height, x, y + height - r);
shape.lineTo(x, y + r);
shape.quadraticCurveTo(x, y, x + r, y);
return shape;
}
function makePanel(width, height, depth, radius, color) {
const geometry = new THREE.ExtrudeGeometry(
roundedRectangleShape(width, height, radius),
{
depth,
bevelEnabled: true,
bevelSegments: 3,
bevelSize: 0.045,
bevelThickness: 0.045,
curveSegments: 10,
steps: 1
}
);
geometry.translate(0, 0, -depth / 2);
const material = new THREE.MeshStandardMaterial({
color,
roughness: 0.82,
metalness: 0
});
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
return mesh;
}
function makeLine(
points,
color,
opacity = 1,
dashed = false,
dashSize = 0.11,
gapSize = 0.085
) {
const geometry = new THREE.BufferGeometry().setFromPoints(points);
const material = dashed
? new THREE.LineDashedMaterial({
color,
transparent: true,
opacity,
dashSize,
gapSize,
depthWrite: false
})
: new THREE.LineBasicMaterial({
color,
transparent: true,
opacity,
depthWrite: false
});
const line = new THREE.Line(geometry, material);
if (dashed) {
line.computeLineDistances();
}
return line;
}
function makeTextSprite(
text,
{
color = "#21313b",
worldWidth = 3,
fontSize = 44,
opacity = 1
} = {}
) {
const textCanvas = document.createElement("canvas");
textCanvas.width = 1024;
textCanvas.height = 160;
const context = textCanvas.getContext("2d");
const texture = new THREE.CanvasTexture(textCanvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.minFilter = THREE.LinearFilter;
texture.generateMipmaps = false;
const material = new THREE.SpriteMaterial({
map: texture,
transparent: true,
depthTest: false,
depthWrite: false,
opacity
});
const sprite = new THREE.Sprite(material);
sprite.scale.set(worldWidth, worldWidth * 160 / 1024, 1);
sprite.renderOrder = 20;
sprite.userData.context = context;
sprite.userData.texture = texture;
sprite.userData.fontSize = fontSize;
sprite.userData.color = color;
setSpriteText(sprite, text, color);
return sprite;
}
function setSpriteText(sprite, text, color = sprite.userData.color) {
const context = sprite.userData.context;
const canvas = sprite.userData.texture.image;
const fontSize = sprite.userData.fontSize;
context.clearRect(0, 0, canvas.width, canvas.height);
context.textAlign = "left";
context.textBaseline = "middle";
let size = fontSize;
do {
context.font = `800 ${size}px ui-monospace, SFMono-Regular, Menlo, monospace`;
size -= 1;
} while (
context.measureText(text).width > canvas.width - 38 &&
size > 16
);
context.fillStyle = color;
context.fillText(text, 18, canvas.height / 2 + 2);
sprite.userData.color = color;
sprite.userData.texture.needsUpdate = true;
}
// A graph ribbon with finite width and depth. Its vertices are updated when
// a new odd harmonic is added; no curve smoothing is applied.
function makeRibbon(sampleCount, color, width = 0.055) {
const positions = new Float32Array(sampleCount * 4 * 3);
const indices = [];
for (let i = 0; i < sampleCount - 1; i++) {
const a = i * 4;
const b = a + 1;
const c = a + 2;
const d = a + 3;
const A = (i + 1) * 4;
const B = A + 1;
const C = A + 2;
const D = A + 3;
indices.push(
a, b, A,
b, B, A,
c, C, d,
d, C, D,
a, A, c,
A, C, c,
b, d, B,
d, D, B
);
}
indices.push(
0, 2, 3,
0, 3, 1
);
const last = (sampleCount - 1) * 4;
indices.push(
last, last + 1, last + 3,
last, last + 3, last + 2
);
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
"position",
new THREE.BufferAttribute(positions, 3)
);
geometry.setIndex(indices);
const material = new THREE.MeshStandardMaterial({
color,
roughness: 0.38,
metalness: 0,
side: THREE.DoubleSide,
transparent: true,
opacity: 1
});
const mesh = new THREE.Mesh(geometry, material);
mesh.castShadow = true;
mesh.receiveShadow = true;
mesh.frustumCulled = false;
mesh.renderOrder = 3;
return {
mesh,
geometry,
material,
sampleCount,
width
};
}
function updateRibbon(
ribbon,
values,
x0,
x1,
centerY,
amplitudeScale,
z,
depth = 0.055
) {
const positions = ribbon.geometry.attributes.position.array;
const count = values.length;
const dx = x1 - x0;
const halfWidth = ribbon.width * 0.5;
for (let i = 0; i < count; i++) {
const previous = values[Math.max(0, i - 1)];
const next = values[Math.min(count - 1, i + 1)];
const derivative = (next - previous) / (2 * dx);
// Perpendicular to the local tangent.
let nx = -derivative;
let ny = dx;
const inverseLength = 1 / Math.hypot(nx, ny);
nx *= inverseLength;
ny *= inverseLength;
const x = x0 + (i / (count - 1)) * dx;
const y = centerY + values[i] * amplitudeScale;
const offsetX = nx * halfWidth;
const offsetY = ny * halfWidth;
const p = i * 12;
// Front upper and lower edge.
positions[p] = x + offsetX;
positions[p + 1] = y + offsetY;
positions[p + 2] = z + depth;
positions[p + 3] = x - offsetX;
positions[p + 4] = y - offsetY;
positions[p + 5] = z + depth;
// Back upper and lower edge.
positions[p + 6] = x + offsetX;
positions[p + 7] = y + offsetY;
positions[p + 8] = z - depth;
positions[p + 9] = x - offsetX;
positions[p + 10] = y - offsetY;
positions[p + 11] = z - depth;
}
ribbon.geometry.attributes.position.needsUpdate = true;
ribbon.geometry.computeVertexNormals();
ribbon.geometry.computeBoundingSphere();
}
// -------------------------------------------------------------------------
// Main signal panel
// -------------------------------------------------------------------------
const mainBack = makePanel(12.08, 6.78, 0.20, 0.20, 0x21313b);
mainBack.position.set(-3.5, -0.25, -0.28);
scene.add(mainBack);
const mainPanel = makePanel(11.88, 6.58, 0.14, 0.18, 0xf4eee1);
mainPanel.position.set(-3.5, -0.25, -0.12);
scene.add(mainPanel);
const componentBack = makePanel(6.18, 7.18, 0.20, 0.20, 0x21313b);
componentBack.position.set(6.25, 0.24, -0.32);
scene.add(componentBack);
// Background grid.
const gridBottom = -2.86;
const gridTop = 2.22;
for (let t = -2 * Math.PI; t <= 2 * Math.PI + 0.001; t += Math.PI) {
const x =
WAVE_X0 +
((t + 2 * Math.PI) / (4 * Math.PI)) * (WAVE_X1 - WAVE_X0);
scene.add(
makeLine(
[
new THREE.Vector3(x, gridBottom, 0.015),
new THREE.Vector3(x, gridTop, 0.015)
],
0x7d898b,
0.14
)
);
}
scene.add(
makeLine(
[
new THREE.Vector3(WAVE_X0, WAVE_CENTER_Y, 0.02),
new THREE.Vector3(WAVE_X1, WAVE_CENTER_Y, 0.02)
],
0x68757a,
0.28
)
);
const targetTop = WAVE_CENTER_Y + WAVE_AMPLITUDE;
const targetBottom = WAVE_CENTER_Y - WAVE_AMPLITUDE;
for (const y of [targetTop, targetBottom]) {
scene.add(
makeLine(
[
new THREE.Vector3(WAVE_X0, y, 0.025),
new THREE.Vector3(WAVE_X1, y, 0.025)
],
0x647379,
0.55,
true
)
);
}
function squareValue(x) {
const phase = ((x % (2 * Math.PI)) + 2 * Math.PI) % (2 * Math.PI);
return phase > 0 && phase < Math.PI ? 1 : -1;
}
const targetPoints = [];
for (let i = 0; i < WAVE_SAMPLES; i++) {
const x =
WAVE_X0 +
(i / (WAVE_SAMPLES - 1)) * (WAVE_X1 - WAVE_X0);
targetPoints.push(
new THREE.Vector3(
x,
WAVE_CENTER_Y + squareValue(x) * WAVE_AMPLITUDE,
0.04
)
);
}
scene.add(
makeLine(targetPoints, 0x59696f, 0.78, true, 0.13, 0.09)
);
const targetLabel = makeTextSprite("TARGET / SQUARE WAVE", {
worldWidth: 3.7,
color: "#48575d"
});
targetLabel.position.set(-8.48, 2.62, 0.45);
scene.add(targetLabel);
const truncationSprite = makeTextSprite("FINITE TRUNCATION / N = 1", {
worldWidth: 4.35,
color: "#21313b"
});
truncationSprite.position.set(-8.48, 2.12, 0.45);
scene.add(truncationSprite);
for (const [label, t] of [
["−2π", -2 * Math.PI],
["−π", -Math.PI],
["0", 0],
["π", Math.PI],
["2π", 2 * Math.PI]
]) {
const x =
WAVE_X0 +
((t + 2 * Math.PI) / (4 * Math.PI)) * (WAVE_X1 - WAVE_X0);
const axisLabel = makeTextSprite(label, {
worldWidth: 0.62,
fontSize: 38,
color: "#68757a"
});
axisLabel.position.set(x, -2.72, 0.2);
scene.add(axisLabel);
}
const plusLabel = makeTextSprite("+1", {
worldWidth: 0.48,
fontSize: 38,
color: "#68757a"
});
plusLabel.position.set(1.55, targetTop, 0.16);
scene.add(plusLabel);
const minusLabel = makeTextSprite("−1", {
worldWidth: 0.48,
fontSize: 38,
color: "#68757a"
});
minusLabel.position.set(1.55, targetBottom, 0.16);
scene.add(minusLabel);
const mainRibbon = makeRibbon(WAVE_SAMPLES, 0xef653b, 0.075);
scene.add(mainRibbon.mesh);
// Red overshoot markers.
const overshootMaterial = new THREE.LineBasicMaterial({
color: 0xd94335,
transparent: true,
opacity: 0.95,
depthTest: false,
depthWrite: false
});
const upperOvershootLine = new THREE.Line(
new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(),
new THREE.Vector3()
]),
overshootMaterial
);
upperOvershootLine.renderOrder = 15;
upperOvershootLine.frustumCulled = false;
scene.add(upperOvershootLine);
const lowerOvershootLine = upperOvershootLine.clone();
scene.add(lowerOvershootLine);
const overshootGeometry = new THREE.SphereGeometry(0.105, 16, 12);
const overshootSphereMaterial = new THREE.MeshStandardMaterial({
color: 0xd94335,
roughness: 0.42
});
const upperOvershootDot = new THREE.Mesh(
overshootGeometry,
overshootSphereMaterial
);
const lowerOvershootDot = upperOvershootDot.clone();
scene.add(upperOvershootDot, lowerOvershootDot);
const peakSprite = makeTextSprite("PEAK 1.273 > TARGET 1", {
worldWidth: 3.05,
color: "#d94335"
});
peakSprite.position.set(-4.2, 2.0, 0.5);
scene.add(peakSprite);
// -------------------------------------------------------------------------
// Harmonic component cards
// -------------------------------------------------------------------------
const harmonicHeading = makeTextSprite("HARMONIC LADDER", {
worldWidth: 3.7,
color: "#f4eee1"
});
harmonicHeading.position.set(3.72, 3.47, 0.28);
scene.add(harmonicHeading);
const harmonicRows = [];
function coefficientFor(n) {
return 4 / (n * Math.PI);
}
function formatCoefficient(n) {
return n === 1 ? "b = 4/π" : `b = 4/(${n}π)`;
}
ODD_HARMONICS.forEach((n, index) => {
const y = 2.66 - index * 1.18;
const cardBack = makePanel(5.72, 1.12, 0.12, 0.14, 0x253640);
cardBack.position.set(6.25, y, -0.12);
scene.add(cardBack);
const cardFront = makePanel(5.55, 0.98, 0.08, 0.12, 0xf4eee1);
cardFront.position.set(6.25, y, -0.02);
scene.add(cardFront);
const title = makeTextSprite(`H${n} / ${n}f`, {
worldWidth: 1.72,
fontSize: 42,
color: "#21313b"
});
title.position.set(3.72, y + 0.23, 0.25);
scene.add(title);
const coefficient = makeTextSprite(formatCoefficient(n), {
worldWidth: 2.05,
fontSize: 35,
color: "#68757a"
});
coefficient.position.set(3.72, y - 0.23, 0.25);
scene.add(coefficient);
const miniSamples = 260;
const miniValues = new Float32Array(miniSamples);
for (let i = 0; i < miniSamples; i++) {
const t = -Math.PI + (i / (miniSamples - 1)) * 2 * Math.PI;
miniValues[i] = coefficientFor(n) * Math.sin(n * t);
}
const ribbon = makeRibbon(miniSamples, HARMONIC_COLORS[index], 0.038);
updateRibbon(
ribbon,
miniValues,
5.17,
8.88,
y,
0.42,
0.14,
0.035
);
scene.add(ribbon.mesh);
harmonicRows.push({
n,
cardFront,
title,
coefficient,
ribbon
});
});
function updateHarmonicRows() {
harmonicRows.forEach((row, index) => {
const active = index < activeCount;
row.cardFront.material.color.setHex(
active ? 0xf4eee1 : 0xd9d9d1
);
row.ribbon.material.color.setHex(
active ? HARMONIC_COLORS[index] : 0x8d999b
);
row.ribbon.material.opacity = active ? 1 : 0.16;
row.ribbon.material.depthWrite = active;
row.title.material.opacity = active ? 1 : 0.42;
row.coefficient.material.opacity = active ? 0.95 : 0.30;
});
}
// -------------------------------------------------------------------------
// Decorative solid forms
// -------------------------------------------------------------------------
const orangeForm = new THREE.Mesh(
new THREE.IcosahedronGeometry(0.62, 1),
new THREE.MeshStandardMaterial({
color: 0xef653b,
roughness: 0.55,
flatShading: true
})
);
orangeForm.position.set(-9.72, -3.68, -0.1);
orangeForm.rotation.set(0.25, 0.4, 0.1);
orangeForm.castShadow = true;
scene.add(orangeForm);
const blueForm = new THREE.Mesh(
new THREE.CylinderGeometry(0.43, 0.52, 1.08, 16),
new THREE.MeshStandardMaterial({
color: 0x3269bd,
roughness: 0.5
})
);
blueForm.position.set(9.82, 3.55, -0.45);
blueForm.rotation.z = -0.28;
blueForm.castShadow = true;
scene.add(blueForm);
const yellowForm = new THREE.Mesh(
new THREE.BoxGeometry(0.72, 0.72, 0.72),
new THREE.MeshStandardMaterial({
color: 0xe2b638,
roughness: 0.58
})
);
yellowForm.position.set(10.05, -3.63, -0.18);
yellowForm.rotation.set(0.22, 0.38, 0.16);
yellowForm.castShadow = true;
scene.add(yellowForm);
// -------------------------------------------------------------------------
// Fourier signal and UI state
// -------------------------------------------------------------------------
function computePartialSum(count) {
const values = new Float32Array(WAVE_SAMPLES);
for (let i = 0; i < WAVE_SAMPLES; i++) {
const x =
WAVE_X0 +
(i / (WAVE_SAMPLES - 1)) * (WAVE_X1 - WAVE_X0);
let value = 0;
for (let j = 0; j < count; j++) {
const n = ODD_HARMONICS[j];
value += coefficientFor(n) * Math.sin(n * x);
}
values[i] = value;
}
return values;
}
let currentSamples = computePartialSum(activeCount);
let waveAnimation = null;
updateRibbon(
mainRibbon,
currentSamples,
WAVE_X0,
WAVE_X1,
WAVE_CENTER_Y,
WAVE_AMPLITUDE,
0.19,
0.07
);
ODD_HARMONICS.forEach((n, index) => {
const button = document.createElement("button");
button.className = "chip";
button.textContent = n;
button.title = `Use odd harmonics through ${n}f`;
button.setAttribute("aria-label", `Select harmonic ${n}`);
button.addEventListener("click", () => setActiveCount(index + 1));
partialButtons.appendChild(button);
});
function updateUI() {
const highest = ODD_HARMONICS[activeCount - 1];
const term = activeCount === 1 ? "term" : "terms";
truncationValue.textContent = `N = ${highest} · ${activeCount} odd ${term}`;
equationValue.textContent =
`Σ odd n ≤ ${highest} bₙ sin(nt)`;
const next = ODD_HARMONICS[activeCount];
addButton.disabled = activeCount === ODD_HARMONICS.length;
addButton.textContent =
activeCount === ODD_HARMONICS.length
? "ODD STACK COMPLETE"
: `ADD ${next}f HARMONIC`;
[...partialButtons.children].forEach((button, index) => {
button.classList.toggle("active", index < activeCount);
button.classList.toggle("passed", index < activeCount - 1);
button.setAttribute("aria-pressed", String(index < activeCount));
});
setSpriteText(
truncationSprite,
`FINITE TRUNCATION / N = ${highest}`
);
updateHarmonicRows();
}
function setActiveCount(count) {
const nextCount = Math.max(1, Math.min(count, ODD_HARMONICS.length));
if (nextCount === activeCount) {
updateUI();
return;
}
const targetSamples = computePartialSum(nextCount);
waveAnimation = {
from: currentSamples.slice(),
to: targetSamples,
start: performance.now(),
duration: 850
};
activeCount = nextCount;
updateUI();
if (isPlaying) {
restartAudio();
}
}
addButton.addEventListener("click", () => {
setActiveCount(activeCount + 1);
});
resetButton.addEventListener("click", () => {
setActiveCount(1);
});
// -------------------------------------------------------------------------
// Overshoot measurement. No peak clipping or smoothing is performed.
// -------------------------------------------------------------------------
let lastPeakText = "";
function updateOvershoot() {
let maximum = -Infinity;
let minimum = Infinity;
let maximumIndex = 0;
let minimumIndex = 0;
for (let i = 0; i < currentSamples.length; i++) {
const value = currentSamples[i];
if (value > maximum) {
maximum = value;
maximumIndex = i;
}
if (value < minimum) {
minimum = value;
minimumIndex = i;
}
}
const maximumMagnitude = Math.max(maximum, -minimum);
const jumpOvershoot = Math.max(0, (maximumMagnitude - 1) * 50);
peakValue.textContent = maximumMagnitude.toFixed(3);
peakNote.textContent =
`target 1.000 · ${jumpOvershoot.toFixed(1)}% of jump retained`;
const maximumX =
WAVE_X0 +
(maximumIndex / (currentSamples.length - 1)) *
(WAVE_X1 - WAVE_X0);
const minimumX =
WAVE_X0 +
(minimumIndex / (currentSamples.length - 1)) *
(WAVE_X1 - WAVE_X0);
const maximumY = WAVE_CENTER_Y + maximum * WAVE_AMPLITUDE;
const minimumY = WAVE_CENTER_Y + minimum * WAVE_AMPLITUDE;
const upperPositions =
upperOvershootLine.geometry.attributes.position.array;
upperPositions[0] = maximumX;
upperPositions[1] = targetTop;
upperPositions[2] = 0.35;
upperPositions[3] = maximumX;
upperPositions[4] = maximumY;
upperPositions[5] = 0.35;
upperOvershootLine.geometry.attributes.position.needsUpdate = true;
upperOvershootLine.visible = maximum > 1.0005;
upperOvershootDot.position.set(maximumX, maximumY, 0.35);
upperOvershootDot.visible = maximum > 1.0005;
const lowerPositions =
lowerOvershootLine.geometry.attributes.position.array;
lowerPositions[0] = minimumX;
lowerPositions[1] = targetBottom;
lowerPositions[2] = 0.35;
lowerPositions[3] = minimumX;
lowerPositions[4] = minimumY;
lowerPositions[5] = 0.35;
lowerOvershootLine.geometry.attributes.position.needsUpdate = true;
lowerOvershootLine.visible = minimum < -1.0005;
lowerOvershootDot.position.set(minimumX, minimumY, 0.35);
lowerOvershootDot.visible = minimum < -1.0005;
const labelText = `PEAK ${maximumMagnitude.toFixed(3)} > TARGET 1`;
if (labelText !== lastPeakText) {
setSpriteText(peakSprite, labelText, "#d94335");
lastPeakText = labelText;
}
peakSprite.position.set(
THREE.MathUtils.clamp(maximumX, -7.75, 0.9),
maximumY + 0.31,
0.5
);
}
// -------------------------------------------------------------------------
// Web Audio: audition the currently active odd partials
// -------------------------------------------------------------------------
let audioContext = null;
let audioNodes = [];
let isPlaying = false;
function stopAudio() {
if (!audioContext) {
isPlaying = false;
listenButton.textContent = "LISTEN TO STACK";
listenButton.classList.remove("listening");
return;
}
const now = audioContext.currentTime;
for (const node of audioNodes) {
try {
node.gain.gain.cancelScheduledValues(now);
node.gain.gain.setTargetAtTime(0, now, 0.012);
node.osc.stop(now + 0.06);
} catch (error) {
// A node may already have stopped.
}
}
audioNodes = [];
isPlaying = false;
listenButton.textContent = "LISTEN TO STACK";
listenButton.classList.remove("listening");
}
function startAudio() {
const AudioContextClass =
window.AudioContext || window.webkitAudioContext;
if (!AudioContextClass) {
listenButton.textContent = "AUDIO UNAVAILABLE";
return;
}
if (!audioContext) {
audioContext = new AudioContextClass();
}
if (audioContext.state === "suspended") {
audioContext.resume();
}
const master = audioContext.createGain();
master.gain.value = 0.42;
const compressor = audioContext.createDynamicsCompressor();
compressor.threshold.value = -18;
compressor.knee.value = 18;
compressor.ratio.value = 5;
compressor.attack.value = 0.003;
compressor.release.value = 0.18;
master.connect(compressor);
compressor.connect(audioContext.destination);
for (let i = 0; i < activeCount; i++) {
const n = ODD_HARMONICS[i];
const oscillator = audioContext.createOscillator();
const gain = audioContext.createGain();
oscillator.type = "sine";
oscillator.frequency.value = fundamental * n;
gain.gain.value = coefficientFor(n) * 0.14;
oscillator.connect(gain);
gain.connect(master);
oscillator.start();
audioNodes.push({ oscillator, gain });
}
isPlaying = true;
listenButton.textContent = "STOP STACK";
listenButton.classList.add("listening");
}
function restartAudio() {
stopAudio();
window.setTimeout(startAudio, 35);
}
listenButton.addEventListener("click", () => {
if (isPlaying) {
stopAudio();
} else {
startAudio();
}
});
fundamentalInput.addEventListener("input", () => {
fundamental = Number(fundamentalInput.value);
frequencyValue.textContent = `${fundamental} Hz`;
if (audioContext && isPlaying) {
const now = audioContext.currentTime;
audioNodes.forEach((node, index) => {
const n = ODD_HARMONICS[index];
node.oscillator.frequency.setTargetAtTime(
fundamental * n,
now,
0.018
);
});
}
});
// -------------------------------------------------------------------------
// Camera controls implemented directly, without an addon
// -------------------------------------------------------------------------
function updateCamera() {
const radius = 26;
const offset = new THREE.Vector3(
Math.sin(cameraState.phi) * Math.cos(cameraState.theta),
Math.sin(cameraState.phi) * Math.sin(cameraState.theta),
Math.cos(cameraState.phi)
).multiplyScalar(radius);
camera.position.copy(cameraState.target).add(offset);
camera.lookAt(cameraState.target);
camera.zoom = cameraState.zoom;
camera.updateProjectionMatrix();
camera.updateMatrixWorld();
}
function resetView() {
cameraState.target.set(0.15, 0, 0);
cameraState.theta = 0;
cameraState.phi = 0;
cameraState.zoom = 1;
updateCamera();
}
resetViewButton.addEventListener("click", resetView);
let dragging = false;
let panning = false;
let previousX = 0;
let previousY = 0;
canvas.addEventListener("pointerdown", (event) => {
if (event.button !== 0) return;
dragging = true;
panning = event.shiftKey;
previousX = event.clientX;
previousY = event.clientY;
canvas.setPointerCapture(event.pointerId);
});
canvas.addEventListener("pointermove", (event) => {
if (!dragging) return;
const dx = event.clientX - previousX;
const dy = event.clientY - previousY;
previousX = event.clientX;
previousY = event.clientY;
if (panning || event.shiftKey) {
const worldPerPixel =
(camera.top - camera.bottom) /
(canvas.clientHeight * camera.zoom);
const right = new THREE.Vector3(1, 0, 0).applyQuaternion(
camera.quaternion
);
const up = new THREE.Vector3(0, 1, 0).applyQuaternion(
camera.quaternion
);
cameraState.target
.addScaledVector(right, -dx * worldPerPixel)
.addScaledVector(up, dy * worldPerPixel);
} else {
cameraState.theta = THREE.MathUtils.clamp(
cameraState.theta - dx * 0.004,
-0.75,
0.75
);
cameraState.phi = THREE.MathUtils.clamp(
cameraState.phi + dy * 0.003,
-0.55,
0.55
);
}
updateCamera();
});
function endDrag(event) {
dragging = false;
panning = false;
if (canvas.hasPointerCapture(event.pointerId)) {
canvas.releasePointerCapture(event.pointerId);
}
}
canvas.addEventListener("pointerup", endDrag);
canvas.addEventListener("pointercancel", endDrag);
canvas.addEventListener(
"wheel",
(event) => {
event.preventDefault();
cameraState.zoom = THREE.MathUtils.clamp(
cameraState.zoom * Math.exp(-event.deltaY * 0.001),
0.68,
2.3
);
updateCamera();
},
{ passive: false }
);
canvas.addEventListener("dblclick", resetView);
// -------------------------------------------------------------------------
// Resize and render loop
// -------------------------------------------------------------------------
function resize() {
const width = window.innerWidth;
const height = window.innerHeight;
const aspect = width / height;
renderer.setSize(width, height, false);
const viewHeight = Math.max(11.4, 21.8 / aspect);
camera.left = (-viewHeight * aspect) / 2;
camera.right = (viewHeight * aspect) / 2;
camera.top = viewHeight / 2;
camera.bottom = -viewHeight / 2;
updateCamera();
}
window.addEventListener("resize", resize);
let previousTime = performance.now();
function animate(now) {
const delta = Math.min((now - previousTime) / 1000, 0.05);
previousTime = now;
if (waveAnimation) {
const raw = THREE.MathUtils.clamp(
(now - waveAnimation.start) / waveAnimation.duration,
0,
1
);
const eased = raw * raw * (3 - 2 * raw);
for (let i = 0; i < currentSamples.length; i++) {
currentSamples[i] =
waveAnimation.from[i] +
(waveAnimation.to[i] - waveAnimation.from[i]) * eased;
}
updateRibbon(
mainRibbon,
currentSamples,
WAVE_X0,
WAVE_X1,
WAVE_CENTER_Y,
WAVE_AMPLITUDE,
0.19,
0.07
);
if (raw >= 1) {
currentSamples = waveAnimation.to;
waveAnimation = null;
}
}
orangeForm.rotation.y += delta * 0.22;
orangeForm.rotation.x += delta * 0.08;
yellowForm.rotation.y += delta * 0.16;
updateOvershoot();
renderer.render(scene, camera);
}
updateUI();
updateOvershoot();
resize();
renderer.setAnimationLoop(animate);
</script>
</body>
</html>
```