1// Composition 4: descent — the score (runs in the score worker).
2//
3// One double pendulum, balanced straight up and nudged by a calibrated amount so it tips at about
4// `fallAfter` seconds. Short piano notes mark the outer bob's height as it passes a ladder of
5// levels (higher level, higher note), so you hear it come down. Whenever the pendulum is fully
6// extended (the arms pass through a straight line, at any angle) there is an extension note: a
7// short violin note at a fixed pitch, its strength from the bob's speed, the first one accented.
8// The outer bob sweeping past the pivot (a folded pendulum) is a click. Slight friction
9// throughout, growing toward the end until it comes to rest; the last extension note rings out
10// and the piece ends with the fade.
11//
12// Drawing data: track 0 = [θ1, θ2] (480 per piece second); events "ring" where notes happen.
14import type { Params } from "../../core/params.ts";
15import { mulberry32 } from "../../core/rng.ts";
16import { NOTE_NAMES, quantize } from "../../music/scales.ts";
17import { cos, hypot, pow, sin, wrap } from "../../physics/dmath.ts";
18import type { NoteRef, ScoreFactory } from "../../stream/score.ts";
19import { DT, bob, inverted, nudgeForTip } from "./fall.ts";
20import { CLICK, EXT, HEIGHT } from "./layout.ts";
22const MAX_SETTLE = 15; // s after the damping: count the pendulum as at rest regardless
23const FRAME_DT = 1 / 480; // piece-time spacing of drawing rows
24const INFO_DT = 0.1;
25const EXT_ARM = 0.05; // rad: the arms must bend this far from straight before the next extension note
26const HEIGHT_HYST = 0.3; // a level sounds once the position is this fraction of a level gap past it
28export const descentScore: ScoreFactory = (P: Params, seed: number, sink) => {
29 const cfg = { m1: 1, l1: 1, g: 1, m2: P.massRatio as number, l2: P.lengthRatio as number };
30 const speed = P.speed as number;
31 const rand = mulberry32(seed);
32 const side = rand() < 0.5 ? -1 : 1;
33 const ratio = 0.6 + 0.8 * rand();
34 const cal = nudgeForTip(cfg, ratio, (P.fallAfter as number) * speed, (P.tipThreshold as number) * (cfg.l1 + cfg.l2));
35 const p = inverted(cfg, cal.nudge, ratio, side);
36 const L = cfg.l1 + cfg.l2;
37 const E0 = p.energy();
38 const vmax = Math.sqrt((2 * E0) / cfg.m2);
39 const end = (P.freeTime as number) + (P.dampTime as number);
40 const restE = P.restEnergy as number;
41 const minY = (P.minDepth as number) * L;
42 const nudgeInfo = `${cal.nudge.toExponential(2)} rad ${side > 0 ? "→" : "←"} (shape ${ratio.toFixed(2)}), tips at ${(cal.tipsAt / speed).toFixed(1)} s`;
44 // the height ladder: scale notes between the low and high pitch, every `step`-th
45 const levels: number[] = (() => {
46 if (!P.heightNotes) return [];
47 const lo = P.heightLow as number, hi = P.heightHigh as number;
48 const root = NOTE_NAMES.indexOf(P.root as string);
49 const all: number[] = [];
50 for (let m = Math.ceil(lo); m <= hi; m++) if (P.scale === "continuous" || Math.abs(quantize(m, P.scale as string, root) - m) < 1e-6) all.push(m);
51 const step = Math.max(1, Math.round(P.heightStep as number));
52 return all.filter((_, i) => i % step === 0);
53 })();
54 const pitchPos = (y: number) => (P.heightLow as number) + ((P.heightHigh as number) - (P.heightLow as number)) * ((L - y) / (2 * L));
55 const countBelow = (q: number) => {
56 let i = 0;
57 while (i < levels.length && levels[i] < q) i++;
58 return i;
59 };
60 const hyst = HEIGHT_HYST * (levels.length > 1 ? (levels[levels.length - 1] - levels[0]) / (levels.length - 1) : 1);
62 let time = 0;
63 let prevX = bob(cfg, p.y)[0];
64 let prevPhi = wrap(p.y[1] - p.y[0]);
65 let extArmed = false;
66 let levelIdx = countBelow(pitchPos(bob(cfg, p.y)[1]));
67 let restAt: number | null = null;
68 let lastNote: NoteRef | null = null;
69 let extCount = 0, clickCount = 0, heightCount = 0;
70 let nextFrame = 0, nextInfo = 0;
72 /** Friction now (per sim second): slight throughout, growing smoothly over the damping section. */
73 const damping = (t: number) => {
74 const u = Math.max(0, Math.min(1, (t - (P.freeTime as number)) / (P.dampTime as number)));
75 const s = u * u * (3 - 2 * u);
76 return (P.dampBase as number) + ((P.dampEnd as number) - (P.dampBase as number)) * s;
77 };
79 /** 0..1 from the outer bob's speed now (loudness floor and curve applied). */
80 const speedStrength = () => {
81 const w = p.derived(), y = p.y;
82 const vx = cfg.l1 * cos(y[0]) * w.w1 + cfg.l2 * cos(y[1]) * w.w2;
83 const vy = cfg.l1 * sin(y[0]) * w.w1 + cfg.l2 * sin(y[1]) * w.w2;
84 const x = Math.min(1, hypot(vx, vy) / ((P.loudRef as number) * vmax));
85 const floor = P.loudFloor as number;
86 return floor + (1 - floor) * pow(x, P.loudCurve as number);
87 };
89 const heightNote = (t: number, midi: number) => {
90 // strength: ramps in over the opening, fades with the energy at the end
91 const ru = (P.heightRamp as number) > 0 ? Math.max(0, Math.min(1, t / (P.heightRamp as number))) : 1;
92 const from = P.heightRampFrom as number;
93 const ramp = from + (1 - from) * ru * ru * (3 - 2 * ru);
94 const e = Math.min(1, Math.max(0, p.energy()) / E0);
95 sink.note(HEIGHT, t, midi, (P.heightVel as number) * ramp * pow(e, P.heightFollow as number), P.heightLength as number);
96 heightCount++;
97 };
99 function step() {
100 const t0 = time;
101 time += DT / speed;
102 p.damping = damping(t0);
103 p.step(DT);
104 const [x, y] = bob(cfg, p.y);
105 // height levels passed since the last step (with hysteresis)
106 if (restAt === null && levels.length) {
107 const pos = pitchPos(y);
108 while (levelIdx < levels.length && pos > levels[levelIdx] + hyst) heightNote(time, levels[levelIdx++]);
109 while (levelIdx > 0 && pos < levels[levelIdx - 1] - hyst) heightNote(time, levels[--levelIdx]);
110 }
111 // the outer bob sweeping past the pivot (crossing the vertical close to it): a click
112 if (restAt === null && Math.abs(y) <= minY && ((prevX < 0 && x >= 0) || (prevX > 0 && x <= 0))) {
113 const tc = t0 + (prevX / (prevX - x)) * (time - t0);
114 clickCount++;
115 if (P.click) {
116 const vel = (P.clickMaxVel as number) * speedStrength();
117 sink.note(CLICK, tc, P.clickPitch as number, vel, P.clickLength as number);
118 sink.event({ t: tc, kind: "ring", x: 0, y, strength: vel, click: 1 });
119 }
120 }
121 prevX = x;
122 // full extension: the arms pass through a straight line (relative angle crosses 0, not ±π),
123 // at any orientation. It re-arms once the arms bend at least EXT_ARM away from straight.
124 const phi = wrap(p.y[1] - p.y[0]);
125 if (Math.abs(phi) > EXT_ARM) extArmed = true;
126 if (restAt === null && extArmed && ((prevPhi < 0 && phi >= 0) || (prevPhi > 0 && phi <= 0)) && Math.abs(phi - prevPhi) < Math.PI) {
127 const tc = t0 + (prevPhi / (prevPhi - phi)) * (time - t0);
128 extArmed = false;
129 extCount++;
130 // the first extension note is the accent; later ones follow the bob's speed
131 const vel = extCount === 1 ? (P.firstVel as number) : (P.maxVel as number) * speedStrength();
132 lastNote = sink.note(EXT, tc, P.extPitch as number, vel, P.extLength as number) ?? lastNote;
133 sink.event({ t: tc, kind: "ring", x, y, strength: vel, click: 0 });
134 }
135 prevPhi = phi;
136 if (restAt === null && time >= end && (p.energyNorm() < restE || time >= end + MAX_SETTLE)) {
137 restAt = time;
138 // the last extension note rings: sustain, then fade; the piece ends with it
139 if (lastNote) sink.hold(lastNote, lastNote.t, P.finalHold as number, P.finalFade as number);
140 sink.end(time + (P.finalHold as number) + (P.finalFade as number) + 0.3);
141 }
142 if (time >= nextFrame) {
143 sink.frame(0, time, [p.y[0], p.y[1]]);
144 nextFrame = time + FRAME_DT;
145 }
146 if (time >= nextInfo) {
147 nextInfo = time + INFO_DT;
148 const free = P.freeTime as number;
149 const phase = restAt !== null ? "at rest" : extCount === 0 ? "falling" : time < free ? "swinging" : time < end ? "damping" : "settling";
150 sink.info(time, {
151 phase,
152 energy: `${(p.energy() / E0).toFixed(3)} of start`,
153 "extension notes": String(extCount),
154 clicks: String(clickCount),
155 "height notes": String(heightCount),
156 nudge: nudgeInfo,
157 friction: `${damping(time).toFixed(4)} /sim s`,
158 });
159 }
160 }
162 if (sink.emitting) sink.frame(0, 0, [p.y[0], p.y[1]]);
163 return {
164 get time() {
165 return time;
166 },
167 advance(t: number) {
168 while (time < t) step();
169 },
170 };
171};