/ music / double-pendulum
Sign in
music / double-pendulum
double-pendulum / src / compositions / shared / humScore.ts
63 lines · 2.8 KBBlameHistoryRaw
1// The energy hum, in the score: one held note of a sustained sound whose timbre follows the energy,
2// with a fade-in at the start and a fade-out that ends with the piece. Its overall level is the
3// output's live level (humLevel); the score sends the fades, the loudness-follow and the timbre.
5import type { Params } from "../../core/params.ts";
6import { LIVE_TARGETS, targetRange, targetValue } from "../../instruments/sounds.ts";
7import { log, pow } from "../../physics/dmath.ts";
8import type { ScoreSink } from "../../stream/score.ts";
10const CONTROL_DT = 0.05; // s of piece time between control updates
12export class HumScore {
13 private started = false;
14 private next = 0;
15 private sent: Record<string, number> = {};
17 private P: Params;
18 private stem: number;
19 private sink: ScoreSink;
21 constructor(P: Params, stem: number, sink: ScoreSink) {
22 this.P = P;
23 this.stem = stem;
24 this.sink = sink;
25 }
27 /** e: normalized energy at piece time t; end: piece time everything has faded (null until known). */
28 update(t: number, e: number, end: number | null) {
29 const { P, sink, stem } = this;
30 if (!sink.emitting || t < this.next) return;
31 this.next = t + CONTROL_DT;
32 if (!this.started) {
33 this.started = true;
34 sink.cmd(stem, { t, type: "gain", value: 0, tau: 0 });
35 sink.cmd(stem, { t, type: "noteOn", note: P.humPitch as number, vel: 1 });
36 }
37 const peak = P.energyPeak as number;
38 const rel = Math.max(0, Math.min(1, e / peak));
39 const e0 = Math.min(P.energyStart as number, 0.999 * peak);
40 const colorBase = P.humColorMode === "log" ? Math.max(0, Math.min(1, log(Math.max(e, 1e-12) / e0) / log(peak / e0))) : rel;
41 const fadeIn = P.humFadeIn as number, fadeOut = P.humFadeOut as number;
42 const fade = Math.max(0, Math.min(1, fadeIn > 0 ? t / fadeIn : 1, end !== null && fadeOut > 0 ? (end - t) / fadeOut : 1));
43 const follow = P.humFollow as number;
44 sink.cmd(stem, { t, type: "gain", value: fade * (1 - follow + follow * rel), tau: 0.08, normalize: P.humNormalize as boolean });
45 // timbre: the mapped settings, sent when they move noticeably
46 const color = pow(colorBase, P.humColorCurve as number);
47 const params: Record<string, number> = {};
48 let changed = false;
49 for (const i of [1, 2]) {
50 const target = P[`humTarget${i}`] as string;
51 if (target === "none" || !LIVE_TARGETS.includes(target)) continue;
52 const from = P[`humFrom${i}`] as number, to = P[`humTo${i}`] as number;
53 const v = targetValue(target, from + (to - from) * color, pow);
54 if (!Number.isFinite(v)) continue;
55 params[target] = v;
56 if (this.sent[target] === undefined || Math.abs(v - this.sent[target]) > 0.002 * targetRange(target)) changed = true;
57 }
58 if (changed) {
59 this.sent = params;
60 sink.cmd(stem, { t, type: "params", params });
61 }
62 }
↑↓ move↵openescclose