Skip to main content

rlx_core/render/scenes/lines/
spectrum.rs

1//! Spectrum scene (Plan 0034 / ADR-0036): the analysis frame's log-spaced band
2//! array, drawn as N elements.
3//!
4//! This is a **fourth consumer of the existing line idiom**, not a fifth render
5//! idiom: N bars, an N-point polyline and a radial ring of N spokes are all
6//! segment lists, and they go out through the same shared
7//! [`LineRenderer`] the three other line scenes draw
8//! through (ADR-0007). Nothing new is uploaded, no new pipeline is built, and
9//! the `Scene` trait is untouched — `update` already receives the whole
10//! [`AnalysisFrame`], bands included.
11//!
12//! The per-frame work is a chain of small pure steps — `downsample`, the
13//! per-element ease, then one of the three [`SpectrumLayout`] builders — all
14//! free functions over preallocated buffers. They are separate from the scene so
15//! the claims that matter (low elements track low frequencies; the 64 → N
16//! reduction loses nothing) are testable without a GPU.
17//!
18//! **The composite vocabulary this scene honors**, since a silent no-op is the
19//! failure mode the shared-surface work exists to avoid:
20//!
21//! - `zoom` / `pan_x` / `pan_y` — the shared view transform (ADR-0018), applied
22//!   by the renderer exactly as for every other line scene.
23//! - `mirror_order` / `mirror_reflect` — the geometry mirror (Plan 0018 Phase
24//!   4). It replicates real geometry *before* rasterization and costs this scene
25//!   nothing, so refusing it would be a no-op the author could not see. On the
26//!   radial ring it is nearly the identity (the ring is already rotationally
27//!   symmetric, the same near-no-op the Hankin star has); on bars and polyline
28//!   it is genuinely transformative, because those figures are not centred.
29//! - `[palette]` / `[palette_b]` / `palette_mix` / `hue` / `hue_spread` /
30//!   `saturation` — the colour surface (ADR-0021), sampled on the CPU. Each line
31//!   scene walks `hue_spread` along the axis its own generator makes meaningful
32//!   (ADR-0059) — path position on [`parametric`](super::parametric), generation
33//!   depth on [`lsystem`](super::lsystem), radius on [`star`](super::star) — and
34//!   this scene's is **band index**. The default `spectrum` palette is the engine
35//!   cosine, so an author who sets no `[palette]` sees the usual colour language.
36//! - `thickness` / `brightness` / `scale` / `base` — ordinary stroke styling.
37//! - `curve` — the level-shaping exponent (ADR-0040, Plan 0038 Phase 3), applied
38//!   to the downsampled level **before** the per-element smoother so the easing
39//!   operates in the displayed domain. `1.0` is exactly linear. It is the third
40//!   per-element lever on an element's length, beside `base` and `scale`.
41//! - `glow` — the line renderer's per-segment falloff multiplier (Plan 0038),
42//!   whole-figure like on the other three line scenes. Not a post bloom.
43//! - `softness` — the across-the-stroke profile (ADR-0124), whole-figure and
44//!   shared with the other three line scenes. Default `0.25`: a solid bar with
45//!   a short shoulder. `1.0` is the pure quadratic falloff; `0` is solid with a
46//!   one-pixel edge. A different quantity from `glow`, which scales the light and
47//!   never the coverage.
48//!
49//! Three parameters are **layout-specific**, and each is a no-op on the layouts
50//! it does not describe — stated in `presets/README.md` and `docs/presets.md`
51//! rather than left for an author to discover:
52//!
53//! - `radius` is the ring's inner radius; no meaning for bars or the polyline.
54//! - `span` and `baseline` place the bars/polyline figure in **world** space; no
55//!   meaning for the ring, which `radius` sizes instead (Plan 0038 Phase 2).
56
57// Hot-path panic-denial pragma (Plan 0002 Phase 2, extended to scenes by Plan
58// 0003 Phase 0). `update`/`render` run every displayed frame.
59#![deny(
60    clippy::unwrap_used,
61    clippy::expect_used,
62    clippy::indexing_slicing,
63    clippy::panic,
64    clippy::unreachable
65)]
66
67use std::cell::RefCell;
68use std::rc::Rc;
69
70use super::super::Scene;
71use super::super::common;
72use super::renderer::{LineRenderer, SegmentInstance, StrokeMetric, miter_extension};
73use super::{
74    CapOverflow, GeneratorConfig, MirrorSpec, OverflowContext, ViewTransform, replicate_mirror,
75};
76use crate::dsp::AnalysisFrame;
77use crate::preset::Easing;
78use crate::render::palette::{self, Palette, desaturate};
79use crate::render::scenes::{ParamKind, ParamSpec, default_of};
80
81/// Largest element count a `[spectrum]` table may ask for — the band count
82/// itself, because above it the 64 → N reduction stops being a partition of the
83/// array. The loader validates against this, and the render layer sizes its
84/// per-element scratch to it (Plan 0034 Phase 4), so the two cannot disagree.
85pub const MAX_ELEMENTS: usize = crate::dsp::SPECTRUM_BINS;
86
87// Parameter defaults — a legible, calm readout when a preset binds nothing.
88const DEFAULT_THICKNESS: f32 = 6.0;
89const DEFAULT_HUE: f32 = 0.55;
90const DEFAULT_HUE_SPREAD: f32 = 0.0;
91const DEFAULT_BRIGHTNESS: f32 = 1.0;
92/// The line renderer's **per-segment falloff** multiplier (Plan 0038 Phase 1) —
93/// not a post-process bloom. `1.0` is the value this scene passed as a literal
94/// before it was bound, so the default is exactly today's look.
95const DEFAULT_GLOW: f32 = 1.0;
96const DEFAULT_SCALE: f32 = default_of(PARAMS, "scale");
97/// Minimum element length, in world units. Non-zero on purpose: a spectrum
98/// readout at rest is a comb, not an empty frame, so the figure stays on screen
99/// (and legible) through a silence instead of vanishing.
100const DEFAULT_BASE: f32 = default_of(PARAMS, "base");
101/// Inner radius of the radial ring (ignored by the other two layouts).
102const DEFAULT_RADIUS: f32 = default_of(PARAMS, "radius");
103/// World-space **half-width** the readout spans, so the figure is `2 * span`
104/// wide — `1.0` is what an unbound preset gets.
105///
106/// It is a **world** quantity, not a screen one. The renderer divides x by the
107/// target aspect on the GPU, so this scene never sees an aspect and cannot take
108/// one from the wrong place (ADR-0037). The honest consequence: *"fill the
109/// width"* is aspect-dependent — `span ≈ 1.78` fills a 16:9 frame and leaves an
110/// ultrawide short. There is deliberately no `fit` mode.
111///
112/// Applies to [`SpectrumLayout::Bars`] and [`SpectrumLayout::Polyline`]; a
113/// **no-op on [`SpectrumLayout::RadialRing`]**, which is sized by `radius`
114/// instead — the mirror image of `radius` already being a no-op on the
115/// other two.
116const DEFAULT_SPAN: f32 = default_of(PARAMS, "span");
117/// World-space y the bars and the polyline rest on — what an unbound preset
118/// gets. Also a **no-op on [`SpectrumLayout::RadialRing`]**, whose spokes start
119/// on the ring.
120///
121/// `baseline = 0` is what makes `mirror_reflect` mean what it means everywhere
122/// else: the mirror reflects across the **x-axis**, so a figure standing on the
123/// axis reflects into a symmetric "landscape and its reflection" about the
124/// frame centre, while one standing at `-0.85` throws its copy against the top
125/// edge (design-backlog 0018).
126const DEFAULT_BASELINE: f32 = default_of(PARAMS, "baseline");
127/// Level-shaping exponent (ADR-0040). `1.0` is exactly linear — `powf(x, 1.0) ==
128/// x` — `0.5` is a square root, and lower values compress harder.
129///
130/// It applies to the **downsampled level, before the per-element smoother**, so
131/// `[spectrum] smoothing` eases the displayed quantity the way meter ballistics
132/// do. That ordering is the ADR's whole content; see [`curve_level`].
133const DEFAULT_CURVE: f32 = default_of(PARAMS, "curve");
134/// The range [`curve_level`] clamps the exponent into before the `powf`.
135///
136/// **Totality is part of ADR-0040's decision, not an implementation detail.**
137/// This runs per element per frame on the render path, where a `NaN` or an
138/// infinite length must not reach the geometry. A floor strictly above zero is
139/// what rules out `pow(0, 0)` and `pow(0, -1)` for every author expression.
140const CURVE_MIN: f32 = 0.05;
141const CURVE_MAX: f32 = 4.0;
142const DEFAULT_ROTATION: f32 = default_of(PARAMS, "rotation");
143// Shared view transform (ADR-0018): identity by default.
144const DEFAULT_ZOOM: f32 = 1.0;
145// Geometry mirror (Plan 0018 Phase 4): identity by default.
146const DEFAULT_MIRROR_ORDER: f32 = 1.0;
147const DEFAULT_MIRROR_REFLECT: f32 = 0.0;
148
149/// Parameter vocabulary — see [`fragment_field::PARAMS`](crate::render::scenes::fragment_field::PARAMS).
150/// **Keep in sync with `set_param` below.**
151pub const PARAMS: &[ParamSpec] = &[
152    ParamSpec {
153        name: "base",
154        default: 0.06,
155        range: Some([0.0, 1.0]),
156        doc: "Height the readout sits at when the band is silent.",
157        kind: ParamKind::Modal,
158    },
159    ParamSpec {
160        name: "scale",
161        default: 1.2,
162        range: Some([0.0, 4.0]),
163        doc: "How far a full band pushes the readout above its base.",
164        kind: ParamKind::Modal,
165    },
166    ParamSpec {
167        name: "curve",
168        default: 1.0,
169        range: Some([CURVE_MIN, CURVE_MAX]),
170        doc: "Exponent on each band's level: 1 is linear, below 1 lifts quiet detail, above 1 pushes it down.",
171        kind: ParamKind::Modal,
172    },
173    ParamSpec {
174        name: "radius",
175        default: 0.35,
176        range: Some([0.0, 1.0]),
177        doc: "Radius of the ring the readout is drawn around, in the radial layouts.",
178        kind: ParamKind::Modal,
179    },
180    ParamSpec {
181        name: "span",
182        default: 1.0,
183        range: Some([0.0, 1.0]),
184        doc: "How much of the frequency axis is shown; below 1 the top end is cut.",
185        kind: ParamKind::Modal,
186    },
187    ParamSpec {
188        name: "baseline",
189        default: -0.85,
190        range: None,
191        doc: "Where the flat layout's zero line sits vertically.",
192        kind: ParamKind::Modal,
193    },
194    ParamSpec {
195        name: "rotation",
196        default: 0.0,
197        range: Some([0.0, 1.0]),
198        doc: "Turns the readout, as a fraction of a full turn.",
199        kind: ParamKind::Modal,
200    },
201    crate::render::scenes::lines::thickness(DEFAULT_THICKNESS),
202    crate::render::scenes::common::hue(DEFAULT_HUE),
203    crate::render::scenes::lines::hue_spread(DEFAULT_HUE_SPREAD),
204    crate::render::scenes::common::SATURATION,
205    crate::render::scenes::common::PALETTE_MIX,
206    crate::render::scenes::common::PALETTE_STEPS,
207    crate::render::scenes::common::PALETTE_CONTOUR,
208    crate::render::scenes::common::brightness(DEFAULT_BRIGHTNESS),
209    crate::render::scenes::lines::GLOW,
210    crate::render::scenes::lines::SOFTNESS,
211    crate::render::scenes::lines::STROKE_BLEND,
212    crate::render::scenes::common::zoom(1.0),
213    crate::render::scenes::common::PAN_X,
214    crate::render::scenes::common::PAN_Y,
215    crate::render::scenes::lines::MIRROR_ORDER,
216    crate::render::scenes::lines::MIRROR_REFLECT,
217];
218
219/// Which figure the elements form. Selected once at preset load through the
220/// `[spectrum]` table; an unknown name is a surfaced load error (ADR-0007).
221#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
222pub enum SpectrumLayout {
223    /// Upright bars standing on a common baseline — the classic readout.
224    #[default]
225    Bars,
226    /// A single continuous line through one point per element: the same data as
227    /// a contour rather than a comb.
228    Polyline,
229    /// Spokes radiating outward from a ring, one per element, with the frequency
230    /// axis wrapped around the circle.
231    RadialRing,
232}
233
234impl SpectrumLayout {
235    /// The accepted `[spectrum] layout` names, in the order the error message
236    /// lists them. The single source for both parsing and the message.
237    pub const NAMES: [&'static str; 3] = ["bars", "polyline", "radial_ring"];
238
239    /// Parse a `[spectrum] layout` name, or `None` if unknown.
240    pub fn from_name(name: &str) -> Option<Self> {
241        Some(match name {
242            "bars" => SpectrumLayout::Bars,
243            "polyline" => SpectrumLayout::Polyline,
244            "radial_ring" => SpectrumLayout::RadialRing,
245            _ => return None,
246        })
247    }
248}
249
250/// Where the figure sits — the scalars that belong to the **whole** readout
251/// rather than to an element, so they stay off the per-element arrays.
252#[derive(Debug, Clone, Copy)]
253pub(crate) struct Placement {
254    /// Inner radius — [`SpectrumLayout::RadialRing`] only.
255    pub radius: f32,
256    /// World-space half-width — [`SpectrumLayout::Bars`] and
257    /// [`SpectrumLayout::Polyline`] only. See [`DEFAULT_SPAN`].
258    pub span: f32,
259    /// World-space y the figure rests on — bars and polyline only. See
260    /// [`DEFAULT_BASELINE`].
261    pub baseline: f32,
262    /// Whole-figure rotation in radians, about the world origin.
263    pub rotation: f32,
264}
265
266/// The scene's own defaults rather than zeroes: a `Placement` with `span = 0`
267/// would collapse the figure to a point, which is never a sensible fallback.
268impl Default for Placement {
269    fn default() -> Self {
270        Self {
271            radius: 0.0,
272            span: DEFAULT_SPAN,
273            baseline: DEFAULT_BASELINE,
274            rotation: 0.0,
275        }
276    }
277}
278
279/// The parameters this scene accepts as a **per-element series** (Plan 0034
280/// Phase 4) — the ones whose effect is genuinely per element. Everything else in
281/// [`PARAMS`] describes the whole figure (`radius`, `rotation`, the view
282/// transform, the mirror, `hue_spread`, `palette_mix`, `saturation`), so a
283/// series aimed at one of those degrades to its `index = 0` value, which is what
284/// the trait default does.
285///
286/// **Index order matches the `SERIES_*` constants below** — the two are read
287/// together by `set_param_series` and `update`.
288const SERIES_PARAMS: [&str; 6] = ["base", "scale", "curve", "thickness", "brightness", "hue"];
289const SERIES_BASE: usize = 0;
290const SERIES_SCALE: usize = 1;
291/// `curve` sits with `base` and `scale` because it is the third lever on an
292/// element's *length*, and per-element is a shape ADR-0040 names explicitly
293/// ("walk it per element with `index`") — a series aimed at it has to reach the
294/// elements rather than degrade to its `index = 0` value.
295const SERIES_CURVE: usize = 2;
296const SERIES_THICKNESS: usize = 3;
297const SERIES_BRIGHTNESS: usize = 4;
298const SERIES_HUE: usize = 5;
299
300/// Reduce the engine's band array to `levels.len()` elements by **averaging each
301/// element's own contiguous slice of bands**.
302///
303/// Element `i` covers `[i * bands / n, (i + 1) * bands / n)`. That is a genuine
304/// partition — contiguous, non-overlapping, and complete — so no band is dropped
305/// or double-counted at any element count up to the band count (which is why the
306/// loader caps the count there). It is also deterministic: integer arithmetic on
307/// lengths, no clock and no rounding mode to disagree about.
308pub(crate) fn downsample(spectrum: &[f32], levels: &mut [f32]) {
309    let bands = spectrum.len();
310    let n = levels.len();
311    if bands == 0 || n == 0 {
312        levels.fill(0.0);
313        return;
314    }
315    for (i, level) in levels.iter_mut().enumerate() {
316        let lo = i * bands / n;
317        // `hi` is the next element's `lo`, which makes the ranges abut exactly.
318        // The `max` only bites when n > bands, where a strict partition is not
319        // available; the loader caps the count so that never happens.
320        let hi = (((i + 1) * bands / n).min(bands)).max(lo + 1);
321        let slice = spectrum.get(lo..hi).unwrap_or(&[]);
322        *level = if slice.is_empty() {
323            0.0
324        } else {
325            slice.iter().sum::<f32>() / slice.len() as f32
326        };
327    }
328}
329
330/// Shape a raw downsampled level by the exponent `curve` — ADR-0040's decision,
331/// and the step that runs **before** the per-element smoother.
332///
333/// Audio level is perceptually logarithmic, so the linear map this scene had
334/// spent most of its range on the loudest element. `curve = 1.0` is exactly the
335/// identity, which is what lets the default leave every existing preset and
336/// every golden baseline unchanged.
337///
338/// **Total by construction**, because it runs per element per frame on the
339/// render path and no author guard stands between an expression and this call:
340///
341/// - the level is floored at `0` — `f32::max` returns the non-`NaN` operand, so
342///   a `NaN` level floors to `0` too, and a negative one can never become a
343///   fractional power of a negative base;
344/// - the exponent is clamped into `[CURVE_MIN, CURVE_MAX]`, a range that
345///   excludes `0`, so neither `pow(0, 0)` nor `pow(0, -1)` is reachable. `NaN`
346///   has no clamped image (`f32::clamp` propagates it), so it is mapped to the
347///   linear default rather than allowed through.
348pub(crate) fn curve_level(level: f32, curve: f32) -> f32 {
349    let exponent = if curve.is_nan() {
350        DEFAULT_CURVE
351    } else {
352        curve.clamp(CURVE_MIN, CURVE_MAX)
353    };
354    level.max(0.0).powf(exponent)
355}
356
357/// The world-space length an element reaches, `base + scale * level`, floored at
358/// zero so a degenerate level can never invert the element.
359pub(crate) fn element_length(level: f32, base: f32, scale: f32) -> f32 {
360    (base + scale * level).max(0.0)
361}
362
363/// Build the segment list for `layout` into `out` (cleared first).
364/// Allocation-free into a preallocated buffer; the per-frame half of the scene.
365///
366/// `lengths`, `widths` and `colors` are read **positionally, per element**, which
367/// is what lets a per-element binding vary any of them across the figure (Plan
368/// 0034 Phase 4). A short list falls back to a sane constant rather than
369/// panicking — which cannot happen, since all three are sized together at load,
370/// but keeps the hot path total.
371pub(crate) fn build(
372    layout: SpectrumLayout,
373    lengths: &[f32],
374    widths: &[f32],
375    colors: &[[f32; 3]],
376    place: Placement,
377    out: &mut Vec<SegmentInstance>,
378) {
379    out.clear();
380    if lengths.is_empty() {
381        return;
382    }
383    let (sin, cos) = place.rotation.sin_cos();
384    // The whole-figure rotation is applied here, at the point where world-space
385    // endpoints are emitted, so it composes with every layout identically.
386    let turn = |p: [f32; 2]| -> [f32; 2] { [p[0] * cos - p[1] * sin, p[0] * sin + p[1] * cos] };
387    let color_of = |i: usize| colors.get(i).copied().unwrap_or([1.0, 1.0, 1.0]);
388    let width_of = |i: usize| widths.get(i).copied().unwrap_or(0.01);
389
390    match layout {
391        SpectrumLayout::Bars => {
392            let step = 2.0 * place.span / lengths.len() as f32;
393            for (i, &length) in lengths.iter().enumerate() {
394                let x = -place.span + step * (i as f32 + 0.5);
395                out.push(SegmentInstance {
396                    a: turn([x, place.baseline]),
397                    b: turn([x, place.baseline + length]),
398                    color: color_of(i),
399                    width: width_of(i),
400                    alpha: 1.0,
401                    // Isolated: one segment per element, both ends free. Bars
402                    // must keep exactly their previous geometry, or a bar would
403                    // hang below `baseline` and break the centre-mirror.
404                    ext_a: 0.0,
405                    ext_b: 0.0,
406                });
407            }
408        }
409        SpectrumLayout::Polyline => {
410            // One point per element, spanning edge to edge, joined by n-1
411            // segments. A single element has no segment to draw, which is why
412            // the loader's minimum count is 2.
413            let gaps = lengths.len().saturating_sub(1);
414            if gaps == 0 {
415                return;
416            }
417            let step = 2.0 * place.span / gaps as f32;
418            let point = |i: usize, length: f32| -> [f32; 2] {
419                turn([-place.span + step * i as f32, place.baseline + length])
420            };
421            // Point `i` of the readout, for the neighbours a joint's interior
422            // angle needs. Out of range reads as a zero length, which the two
423            // free ends never consult.
424            let pt = |i: usize| point(i, lengths.get(i).copied().unwrap_or(0.0));
425            let mut prev = point(0, lengths.first().copied().unwrap_or(0.0));
426            for (i, &length) in lengths.iter().enumerate().skip(1) {
427                let next = point(i, length);
428                // Chained (ADR-0158): consecutive segments share a point, so
429                // every interior endpoint is a joint and reaches its corner's
430                // point by the miter the two arms subtend. Only the two ends of
431                // the whole figure are free — segment `i` runs from point
432                // `i - 1` to point `i`, so its `a` is joined for every segment
433                // but the first and its `b` for every segment but the last.
434                //
435                // The extension is resolved against **this segment's own**
436                // width: `width_of` is per element, so a neighbour's is not
437                // necessarily the same number.
438                let width = width_of(i);
439                let ext_a = if i > 1 {
440                    miter_extension(width, pt(i - 2), prev, next)
441                } else {
442                    0.0
443                };
444                let ext_b = if i < gaps {
445                    miter_extension(width, prev, next, pt(i + 1))
446                } else {
447                    0.0
448                };
449                out.push(SegmentInstance {
450                    a: prev,
451                    b: next,
452                    color: color_of(i),
453                    width,
454                    alpha: 1.0,
455                    ext_a,
456                    ext_b,
457                });
458                prev = next;
459            }
460        }
461        SpectrumLayout::RadialRing => {
462            // The frequency axis wrapped around the circle: element 0 points
463            // along +x and the rest follow counter-clockwise, each spoke running
464            // outward from the ring.
465            let n = lengths.len() as f32;
466            let inner = place.radius.max(0.0);
467            for (i, &length) in lengths.iter().enumerate() {
468                let angle = place.rotation + std::f32::consts::TAU * i as f32 / n;
469                let (s, c) = angle.sin_cos();
470                let outer = inner + length;
471                out.push(SegmentInstance {
472                    a: [c * inner, s * inner],
473                    b: [c * outer, s * outer],
474                    color: color_of(i),
475                    width: width_of(i),
476                    alpha: 1.0,
477                    // Isolated, like the bars: a spoke that extended inward
478                    // would grow through `radius` and fill the inner circle.
479                    ext_a: 0.0,
480                    ext_b: 0.0,
481                });
482            }
483        }
484    }
485}
486
487/// The spectrum readout: N elements driven by the analysis frame's band array,
488/// drawn through the shared line renderer.
489pub struct SpectrumScene {
490    /// The single line renderer, shared with the other line scenes (ADR-0007:
491    /// "one line renderer"). Only the active scene draws in a frame.
492    renderer: Rc<RefCell<LineRenderer>>,
493    /// The drawn geometry, after the mirror. Preallocated to the cap.
494    segments: Vec<SegmentInstance>,
495    /// The single (pre-mirror) figure, replicated into
496    /// [`segments`](Self::segments). Preallocated to the cap.
497    single_buf: Vec<SegmentInstance>,
498    /// The active tier's segment ceiling
499    /// ([`TierConfig::max_segments`](crate::render::TierConfig::max_segments)),
500    /// resolved once at construction (Plan 0044). A field rather than a constant
501    /// so the tier can raise it; the buffers above are preallocated to it, which
502    /// is what keeps the per-frame replication allocation-free.
503    max_segments: usize,
504    /// Set when this frame's mirror replication overflowed the cap.
505    mirror_overflow: Option<CapOverflow>,
506    /// This frame's downsampled band levels, before easing.
507    raw_levels: Vec<f32>,
508    /// The **held** (eased) levels actually drawn — the per-element envelope
509    /// state. Sized at load beside [`raw_levels`](Self::raw_levels).
510    levels: Vec<f32>,
511    /// Per-element stroke colour, rebuilt each frame into a buffer sized at load.
512    colors: Vec<[f32; 3]>,
513    /// Per-element world-space length, rebuilt each frame. Sized at load.
514    lengths: Vec<f32>,
515    /// Per-element stroke half-width, rebuilt each frame. Sized at load.
516    widths: Vec<f32>,
517    /// Per-element binding overrides (Plan 0034 Phase 4), one row per
518    /// [`SERIES_PARAMS`] entry, each sized at load.
519    series: [Vec<f32>; SERIES_PARAMS.len()],
520    /// Which rows this frame's bindings actually wrote. Cleared in
521    /// `reset_params` alongside the scalars, so a series never outlives the frame
522    /// that produced it — the same lifetime rule every other param follows.
523    series_active: [bool; SERIES_PARAMS.len()],
524    /// The figure, from `[spectrum] layout`.
525    layout: SpectrumLayout,
526    /// Per-element easing, from `[spectrum] smoothing`.
527    easing: Easing,
528    /// Real elapsed seconds for this frame, injected through
529    /// [`advance`](Scene::advance) — what makes the easing frame-rate
530    /// independent (ADR-0019).
531    dt: f32,
532    /// The preset's baked colour LUT (ADR-0021), sampled on the CPU per element.
533    palette: Palette,
534    thickness: f32,
535    /// The shared palette knobs (ADR-0021).
536    colour: common::PaletteParams,
537    /// The shared view transform (ADR-0018).
538    pan: common::PanParams,
539    hue_spread: f32,
540    glow: f32,
541    softness: f32,
542    /// Whether this figure draws through the **opacity-preserving** seam
543    /// rather than the additive one, from `stroke_blend` (ADR-0138).
544    ///
545    /// At or above [`OPAQUE_BLEND`](super::OPAQUE_BLEND) the whole batch
546    /// composites over: a stroke laid on another replaces the interior of what
547    /// it covers instead of summing with it, so a quantized palette keeps its
548    /// plateaus. Below it the batch is additive light. `0` is the default, so a
549    /// preset that does not bind this draws exactly what it drew.
550    stroke_blend: f32,
551    scale: f32,
552    base: f32,
553    curve: f32,
554    radius: f32,
555    span: f32,
556    baseline: f32,
557    rotation: f32,
558    zoom: f32,
559    mirror_order: f32,
560    mirror_reflect: f32,
561}
562
563impl SpectrumScene {
564    /// Build the scene over the shared line renderer, preallocating its segment
565    /// buffers to the cap. The element buffers are sized by `configure`, which
566    /// the renderer runs on every preset switch.
567    pub fn new(renderer: Rc<RefCell<LineRenderer>>, max_segments: usize) -> Self {
568        Self {
569            renderer,
570            segments: Vec::with_capacity(max_segments),
571            single_buf: Vec::with_capacity(max_segments),
572            max_segments,
573            mirror_overflow: None,
574            raw_levels: Vec::new(),
575            levels: Vec::new(),
576            colors: Vec::new(),
577            lengths: Vec::new(),
578            widths: Vec::new(),
579            series: Default::default(),
580            series_active: [false; SERIES_PARAMS.len()],
581            layout: SpectrumLayout::default(),
582            easing: Easing::INSTANT,
583            dt: 0.0,
584            // Replaced by the preset's palette on the next switch; the default
585            // is the engine cosine, so an unconfigured scene still colours.
586            palette: Palette::default_spectrum(),
587            thickness: DEFAULT_THICKNESS,
588            colour: common::PaletteParams::new(DEFAULT_HUE, DEFAULT_BRIGHTNESS),
589            pan: common::PanParams::default(),
590            hue_spread: DEFAULT_HUE_SPREAD,
591            glow: DEFAULT_GLOW,
592            softness: super::DEFAULT_SOFTNESS,
593            stroke_blend: super::ADDITIVE_BLEND,
594            scale: DEFAULT_SCALE,
595            base: DEFAULT_BASE,
596            curve: DEFAULT_CURVE,
597            radius: DEFAULT_RADIUS,
598            span: DEFAULT_SPAN,
599            baseline: DEFAULT_BASELINE,
600            rotation: DEFAULT_ROTATION,
601            zoom: DEFAULT_ZOOM,
602            mirror_order: DEFAULT_MIRROR_ORDER,
603            mirror_reflect: DEFAULT_MIRROR_REFLECT,
604        }
605    }
606
607    /// Resize the per-element buffers and clear the envelope state. Off the hot
608    /// path (preset load only) — the scratch every frame writes into is sized
609    /// here, never per frame.
610    fn resize(&mut self, elements: usize) {
611        self.raw_levels.clear();
612        self.raw_levels.resize(elements, 0.0);
613        // Cleared rather than resized in place: a preset switch must not show
614        // the previous preset's envelope decaying under the new one.
615        self.levels.clear();
616        self.levels.resize(elements, 0.0);
617        self.colors.clear();
618        self.colors.resize(elements, [0.0; 3]);
619        self.lengths.clear();
620        self.lengths.resize(elements, 0.0);
621        self.widths.clear();
622        self.widths.resize(elements, 0.0);
623        for row in &mut self.series {
624            row.clear();
625            row.resize(elements, 0.0);
626        }
627        self.series_active = [false; SERIES_PARAMS.len()];
628    }
629
630    /// Element `i`'s value for series row `row`, or `fallback` when no binding
631    /// drove that row this frame. Total — an out-of-range row or element reads
632    /// the fallback rather than panicking on the hot path.
633    fn series_value(&self, row: usize, i: usize, fallback: f32) -> f32 {
634        if !self.series_active.get(row).copied().unwrap_or(false) {
635            return fallback;
636        }
637        self.series
638            .get(row)
639            .and_then(|values| values.get(i))
640            .copied()
641            .unwrap_or(fallback)
642    }
643}
644
645impl Scene for SpectrumScene {
646    fn name(&self) -> &'static str {
647        "spectrum"
648    }
649
650    fn advance(&mut self, dt: f32) {
651        self.dt = dt;
652    }
653
654    fn reset_params(&mut self) {
655        self.thickness = DEFAULT_THICKNESS;
656        self.colour.reset();
657        self.pan.reset();
658        self.hue_spread = DEFAULT_HUE_SPREAD;
659        self.glow = DEFAULT_GLOW;
660        self.softness = super::DEFAULT_SOFTNESS;
661        self.stroke_blend = super::ADDITIVE_BLEND;
662        self.scale = DEFAULT_SCALE;
663        self.base = DEFAULT_BASE;
664        self.curve = DEFAULT_CURVE;
665        self.radius = DEFAULT_RADIUS;
666        self.span = DEFAULT_SPAN;
667        self.baseline = DEFAULT_BASELINE;
668        self.rotation = DEFAULT_ROTATION;
669        self.zoom = DEFAULT_ZOOM;
670        self.mirror_order = DEFAULT_MIRROR_ORDER;
671        self.mirror_reflect = DEFAULT_MIRROR_REFLECT;
672        // A per-element series lives exactly one frame, like every scalar above:
673        // the rows keep their storage (sized at load) but stop being read until
674        // a binding writes them again.
675        self.series_active = [false; SERIES_PARAMS.len()];
676    }
677
678    fn set_param(&mut self, name: &str, value: f32) {
679        // The shared param blocks first, this scene's own names after
680        // (`scenes::common`).
681        if self.colour.set(name, value) || self.pan.set(name, value) {
682            return;
683        }
684        match name {
685            "base" => self.base = value,
686            "scale" => self.scale = value,
687            "curve" => self.curve = value,
688            "radius" => self.radius = value,
689            "span" => self.span = value,
690            "baseline" => self.baseline = value,
691            "rotation" => self.rotation = value,
692            "thickness" => self.thickness = value,
693            "hue_spread" => self.hue_spread = value,
694            "glow" => self.glow = value,
695            "softness" => self.softness = value,
696            "stroke_blend" => self.stroke_blend = value,
697            "zoom" => self.zoom = value,
698            "mirror_order" => self.mirror_order = value,
699            "mirror_reflect" => self.mirror_reflect = value,
700            _ => {}
701        }
702    }
703
704    fn set_param_series(&mut self, name: &str, values: &[f32]) {
705        let Some(row) = SERIES_PARAMS.iter().position(|&p| p == name) else {
706            // Not a per-element parameter on this scene (the whole-figure ones:
707            // radius, rotation, the view transform, the mirror, hue_spread,
708            // palette_mix, saturation). Fall back to the trait's rule — the
709            // element-0 value — rather than dropping the binding.
710            if let Some(&first) = values.first() {
711                self.set_param(name, first);
712            }
713            return;
714        };
715        let (Some(dst), Some(active)) = (self.series.get_mut(row), self.series_active.get_mut(row))
716        else {
717            return; // unreachable: `position` returned an in-range row
718        };
719        // Copy rather than borrow: the caller's slice is the renderer's scratch,
720        // reused by the next binding. `n` is the overlap, so a scratch sized for
721        // a different element count can neither overrun nor leave stale values
722        // beyond it (the rest of the row keeps whatever it held; only the first
723        // `n` are read, because `update` walks `lengths`, which is `n` long).
724        let n = dst.len().min(values.len());
725        if let (Some(dst), Some(src)) = (dst.get_mut(..n), values.get(..n)) {
726            dst.copy_from_slice(src);
727        }
728        *active = n > 0;
729    }
730
731    fn set_palette(&mut self, palette: &Palette) {
732        self.palette = palette.clone();
733    }
734
735    fn configure(&mut self, cfg: &GeneratorConfig) -> Option<CapOverflow> {
736        // This scene's own variant and no other. A new variant has to be
737        // acknowledged in exactly one place -- `GeneratorConfig::element_count`,
738        // which is exhaustive and must answer for every variant -- rather than
739        // in every scene that does not consume it.
740        if let GeneratorConfig::Spectrum {
741            elements,
742            layout,
743            easing,
744        } = cfg
745        {
746            self.layout = *layout;
747            self.easing = *easing;
748            self.resize(*elements);
749        }
750        // Nothing is built here — the element count is validated at load and is
751        // orders of magnitude under the segment cap — so nothing truncates.
752        None
753    }
754
755    fn mirror_overflow(&self) -> Option<&CapOverflow> {
756        self.mirror_overflow.as_ref()
757    }
758
759    fn update(&mut self, frame: &AnalysisFrame) {
760        downsample(&frame.spectrum, &mut self.raw_levels);
761        // `downsample -> curve -> ease`, in that order, which is ADR-0040's
762        // decision and not an incidental arrangement of two lines: the smoother's
763        // state **is** the displayed quantity, so a fall's time constant is
764        // exactly the `release` the preset wrote, at every value of `curve`.
765        // Easing first would have made the effective release `release / curve` —
766        // engaging `curve = 0.5` would silently double every fall time, and a
767        // fall to a non-zero floor would stop being exponential at all, so
768        // `release` would name no duration.
769        //
770        // ADR-0040 originally argued this ordering bought a perceptually *even*
771        // fall. Plan 0038 Phase 3 measured that and it is false — both orderings
772        // are exponentials of identical shape and differ only in speed. See the
773        // ADR's Outcome section; the ordering survives on the reason above.
774        //
775        // The easing itself is per element on the injected real `dt`, through the
776        // same `Easing` the `[smoothing]` table uses (ADR-0035) — so "0.2
777        // seconds" means the same thing here as on a binding, at any frame rate.
778        // The default is `INSTANT`, which passes the curved level straight
779        // through, and the default `curve` is `1.0`, which is the identity.
780        let (easing, dt) = (self.easing, self.dt);
781        for i in 0..self.levels.len() {
782            let raw = self.raw_levels.get(i).copied().unwrap_or(0.0);
783            let shaped = curve_level(raw, self.series_value(SERIES_CURVE, i, self.curve));
784            if let Some(held) = self.levels.get_mut(i) {
785                *held = easing.step(*held, shaped, dt);
786            }
787        }
788
789        // Per-element geometry and colour. Each scalar below reads its own series
790        // row when a binding drove one this frame (Plan 0034 Phase 4) and the
791        // whole-figure param otherwise — so `thickness = "0.01 + bin(index) * 5"`
792        // varies the stroke across the figure while `thickness = "2"` does not,
793        // with no branch in the preset and no second code path here.
794        let count = self.levels.len();
795        let span = count.max(1) as f32;
796        for i in 0..count {
797            let level = self.levels.get(i).copied().unwrap_or(0.0);
798            let base = self.series_value(SERIES_BASE, i, self.base);
799            let scale = self.series_value(SERIES_SCALE, i, self.scale);
800            let thickness = self.series_value(SERIES_THICKNESS, i, self.thickness);
801            let brightness = self.series_value(SERIES_BRIGHTNESS, i, self.colour.brightness);
802            // `hue_spread` walks the palette along the axis on top of whatever
803            // `hue` is — at the default spread of 0 the figure is one hue, at 1
804            // it spans the palette from the lowest element to the highest.
805            let hue = self.series_value(SERIES_HUE, i, self.colour.hue)
806                + self.hue_spread * (i as f32 / span);
807            // Hard bands on the palette coordinate (ADR-0078), the canonical
808            // `palette::band_coord` called rather than copied. `palette_steps <= 1`
809            // returns it untouched, so an unbound preset is byte-unchanged.
810            let banded = palette::band_coord(hue, self.colour.steps);
811            let rgb = desaturate(
812                self.palette.sample(banded, self.colour.mix),
813                self.colour.saturation,
814            );
815
816            if let Some(slot) = self.lengths.get_mut(i) {
817                *slot = element_length(level, base, scale);
818            }
819            if let Some(slot) = self.widths.get_mut(i) {
820                *slot = super::half_width(thickness);
821            }
822            if let Some(slot) = self.colors.get_mut(i) {
823                *slot = [
824                    rgb[0] * brightness,
825                    rgb[1] * brightness,
826                    rgb[2] * brightness,
827                ];
828            }
829        }
830
831        let place = Placement {
832            radius: self.radius,
833            span: self.span,
834            baseline: self.baseline,
835            rotation: self.rotation,
836        };
837        build(
838            self.layout,
839            &self.lengths,
840            &self.widths,
841            &self.colors,
842            place,
843            &mut self.single_buf,
844        );
845
846        let mirror = MirrorSpec::from_params(self.mirror_order, self.mirror_reflect);
847        if mirror.is_identity() {
848            // Identity replication would copy the whole set to produce exactly
849            // what it was given; swap instead (Plan 0031 Phase 4). Both buffers
850            // are preallocated to the cap, so neither can grow later.
851            std::mem::swap(&mut self.single_buf, &mut self.segments);
852            self.mirror_overflow = None;
853            return;
854        }
855        let dropped = replicate_mirror(
856            &self.single_buf,
857            mirror,
858            self.max_segments,
859            &mut self.segments,
860        );
861        self.mirror_overflow = (dropped > 0).then_some(CapOverflow {
862            dropped,
863            context: OverflowContext::Mirror(mirror.order),
864            cap: self.max_segments,
865        });
866    }
867
868    fn render(
869        &mut self,
870        queue: &wgpu::Queue,
871        encoder: &mut wgpu::CommandEncoder,
872        view: &wgpu::TextureView,
873        aspect: f32,
874    ) {
875        let xform = ViewTransform {
876            zoom: self.zoom,
877            pan: [self.pan.x, self.pan.y],
878            _pad: 0.0,
879        };
880        let mut renderer = self.renderer.borrow_mut();
881        if self.stroke_blend >= super::OPAQUE_BLEND {
882            renderer.draw_opaque(
883                queue,
884                encoder,
885                view,
886                aspect,
887                self.glow,
888                self.softness,
889                StrokeMetric::World,
890                xform,
891                &self.segments,
892                &[],
893            );
894        } else {
895            renderer.draw(
896                queue,
897                encoder,
898                view,
899                aspect,
900                self.glow,
901                self.softness,
902                StrokeMetric::World,
903                xform,
904                &self.segments,
905            );
906        }
907    }
908}
909
910#[cfg(test)]
911mod tests;