1// Controls shared by the oscillator slides: the parameter sliders, a presets
2// dropdown, the volume control, and the mapping from slider values to the
3// physics of duffing.js.
4//
5// Parameters (the slider values, in params): x0, the initial displacement;
6// freq, the natural frequency f0 in Hz, which takes the sign of the linear
7// stiffness k (negative only where a page's slider allows it); and optionally
8// alpha, the cubic stiffness term in s^-2 (x is dimensionless), delta, the
9// damping coefficient in s^-1, F, the driving force per unit mass in s^-2,
10// and drive, the driving frequency Omega / 2 pi in Hz. The motion is
11// x'' + delta x' + (k/m) x + alpha x^3 = F cos(Omega t) (see duffing.js),
12// with k/m = sgn(f0) (2 pi f0)^2.
13//
14// alpha's lower bound moves with f0 and x0, and alpha is raised to it if
15// needed, so that without a driving force the block cannot escape (a
16// driving force can still push it over):
17// - k >= 0: a softening spring (alpha < 0) lets the block escape if it starts
18// past the barrier, that is if alpha x0^2 <= -(2 pi f0)^2. The bound is
19// ALPHA_MARGIN of that. The swing never grows past x0.
20// - k < 0 (a double well): alpha must be positive to hold the block in, and
21// large enough that the far turning point from rest at x0, where
22// x^2 = 2 |k/m| / alpha - x0^2, stays within ALPHA_MARGIN X_MAX.
23// Bounds are rounded inward to the slider's step.
25import { X_MAX } from './duffing.js';
27const ALPHA_MARGIN = 0.95;
29// The sliders, by parameter name. A slider shows params[name] / scale. label
30// is text, tex an optional symbol after it (rendered by KaTeX with the rest of
31// the page), and unit optional HTML after that. minFor(params), if given, is
32// a lower bound that depends on the other parameters, in slider units. A page
33// can override any of these per slider.
34export const SLIDERS = {
35 x0: { label: 'Initial displacement', min: 0, max: 0.5, step: 0.01, format: (v) => v.toFixed(2) },
36 freq: { label: 'Frequency', tex: 'f_0', min: 0, max: 2000, step: 5, format: (v) => `${v < 0 ? '−' : ''}${Math.abs(v)} Hz` },
37 alpha: {
38 label: 'Cubic term', tex: '\\alpha', unit: '(10<sup>7</sup> s<sup>−2</sup>)',
39 scale: 1e7, min: -10, max: 10, step: 0.1, format: (v) => v.toFixed(1),
40 minFor: ({ x0, freq }) => {
41 const w2 = (2 * Math.PI * freq) ** 2;
42 if (freq < 0) return Math.ceil((2 * w2) / ((ALPHA_MARGIN * X_MAX) ** 2 + x0 ** 2) / 1e6) / 10;
43 return x0 > 0 ? Math.ceil((-ALPHA_MARGIN * w2) / x0 ** 2 / 1e6) / 10 : -Infinity;
44 },
45 },
46 delta: {
47 label: 'Damping', tex: '\\delta', unit: '(s<sup>−1</sup>)',
48 min: 0, max: 20, step: 0.1, format: (v) => v.toFixed(1),
49 },
50 F: {
51 label: 'Forcing', tex: 'F', unit: '(10<sup>4</sup> s<sup>−2</sup>)',
52 scale: 1e4, min: 0, max: 30, step: 0.1, format: (v) => v.toFixed(1),
53 },
54 drive: { label: 'Driving frequency', tex: '\\Omega / 2\\pi', min: 0, max: 2000, step: 5, format: (v) => `${v} Hz` },
55};
57// The slider specs for a page: SLIDERS with its per-slider overrides.
58// names: the sliders the page shows, in SLIDERS order (those in params).
59export function sliderSpecs(params, overrides = {}) {
60 const names = Object.keys(SLIDERS).filter((name) => name in params);
61 const spec = (name) => ({ ...SLIDERS[name], ...overrides[name] });
62 return { names, spec };
63}
65// The physics of duffing.js for the slider values (missing ones are 0).
66export function physicsOf(params) {
67 return {
68 omega2: Math.sign(params.freq) * (2 * Math.PI * params.freq) ** 2,
69 alpha: params.alpha ?? 0,
70 delta: params.delta ?? 0,
71 F: params.F ?? 0,
72 Omega: 2 * Math.PI * (params.drive ?? 0),
73 };
74}
76// HTML for the sliders, one row each (label, slider, value).
77export function slidersHTML(names, spec) {
78 const rows = names.map((name) => {
79 const s = spec(name);
80 const tex = s.tex ? ` <span data-tex="${s.tex}"></span>` : '';
81 const unit = s.unit ? ` <span class="unit">${s.unit}</span>` : '';
82 return `<label class="row"><span>${s.label}${tex}${unit}</span>
83 <input data-param="${name}" type="range" min="${s.min}" max="${s.max}" step="${s.step}">
84 <output data-param="${name}"></output>
85 </label>`;
86 });
87 return `<div class="sliders${names.length > 4 ? ' compact' : ''}">${rows.join('')}</div>`;
88}
90// Wire up sliders built by slidersHTML inside root. onInput(name) is called
91// after a slider moves, with params (and any bounds) already updated.
92// Returns { showAll() } to show params after they change elsewhere.
93export function bindSliders({ root, names, spec, params, onInput }) {
94 const inputs = {};
95 const outputs = {};
96 const show = (name) => {
97 const { scale = 1, format } = spec(name);
98 inputs[name].value = params[name] / scale;
99 outputs[name].textContent = format(params[name] / scale);
100 };
102 // Move the sliders' parameter-dependent lower bounds, raising any value
103 // that falls below its bound.
104 function updateBounds() {
105 for (const name of names) {
106 const { scale = 1, min, max, minFor } = spec(name);
107 if (!minFor) continue;
108 const lo = Math.min(max, Math.max(min, minFor(params)));
109 inputs[name].min = lo;
110 if (params[name] / scale < lo) params[name] = lo * scale;
111 show(name);
112 }
113 }
115 for (const name of names) {
116 const { scale = 1, format } = spec(name);
117 inputs[name] = root.querySelector(`input[data-param="${name}"]`);
118 outputs[name] = root.querySelector(`output[data-param="${name}"]`);
119 show(name);
120 inputs[name].addEventListener('input', () => {
121 params[name] = Number(inputs[name].value) * scale;
122 outputs[name].textContent = format(Number(inputs[name].value));
123 updateBounds();
124 onInput(name);
125 });
126 }
127 updateBounds();
129 return {
130 showAll: () => {
131 updateBounds();
132 names.forEach(show);
133 },
134 };
135}
137// A presets dropdown built into container: presets is [{ name, group?,
138// params }], with options grouped as listed. Choosing one copies its params
139// into params and calls onChoose(preset). markCustom() shows "Custom" (call it
140// when a slider moves by hand).
141export function createPresetSelect({ container, presets, params, names, onChoose }) {
142 let html = '<option value="" disabled>Custom</option>';
143 let group = null;
144 presets.forEach((pr, i) => {
145 if ((pr.group ?? null) !== group) {
146 if (group) html += '</optgroup>';
147 group = pr.group ?? null;
148 if (group) html += `<optgroup label="${group}">`;
149 }
150 html += `<option value="${i}">${pr.name}</option>`;
151 });
152 if (group) html += '</optgroup>';
153 container.innerHTML = `<label class="preset">Preset <select>${html}</select></label>`;
154 const select = container.querySelector('select');
155 const matches = (pr) => names.every((name) => pr.params[name] === params[name]);
156 const current = presets.findIndex(matches);
157 select.value = current >= 0 ? String(current) : '';
158 select.addEventListener('change', () => {
159 const pr = presets[Number(select.value)];
160 Object.assign(params, pr.params);
161 onChoose(pr);
162 });
163 return { markCustom: () => { select.value = ''; } };
164}
166export const VOLUME_ICON = '<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 9h4l5-4v14l-5-4H4z" fill="currentColor"/><path d="M16 9a4 4 0 0 1 0 6M18.5 6.5a7.5 7.5 0 0 1 0 11" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>';
168// HTML for the subtle volume control (see sound.js).
169export const volumeHTML = () => `<label class="volume" title="Volume">${VOLUME_ICON}
170 <input data-role="volume" type="range" min="0" max="1" step="0.01" aria-label="Volume">
171</label>`;