Skip to main content

deepmind_midi/effect/
mod.rs

1//! The effect panels: what an engine's twelve bytes mean, and which algorithm
2//! decides.
3//!
4//! Four engines, twelve raw parameter bytes each. What those bytes mean depends
5//! on which of the 35 algorithms the engine is running. The parameter table can
6//! only call them `FX 1 Param 3`. This table says `FX 1 Param 3` is `Size` on a
7//! Room Reverb and `Depth` on a Phaser.
8//!
9//! ```
10//! use deepmind_midi::effect::{Algorithm, Engine};
11//! use deepmind_midi::param::{DEFAULT_FIRMWARE, ParamId};
12//!
13//! // What the engine is running, read off the byte the program stores.
14//! let room = Algorithm::for_value(2, DEFAULT_FIRMWARE).expect("a Room Reverb");
15//! assert_eq!(room.full_name, "Room Reverb");
16//! assert_eq!(room.category, "Reverb");
17//!
18//! // What its third slot is, and the parameter that addresses it.
19//! let size = room.slot(3).expect("Room Reverb uses all twelve");
20//! assert_eq!(size.title, "Size");
21//! assert_eq!(size.unit, Some("m"));
22//! assert_eq!(Engine::One.slot_parameter(3), Some(ParamId::Fx1Param3));
23//! ```
24//!
25//! # Fewer than twelve
26//!
27//! [`Algorithm::slots`] is as long as the algorithm has parameters: five for TC
28//! Deep Reverb, ten for Gated Reverb. Its length is how many controls to draw.
29//!
30//! # Firmware decides the numbering
31//!
32//! Firmware 1.1 added Vintage Pitch and moved Rotary Speaker, so the byte that
33//! selects an algorithm is not the same byte on 1.0. [`Algorithm::for_value`]
34//! looks it up in the `FX Type` value table for the firmware a device inquiry
35//! reported, and [`Algorithm::value_for`] goes the other way. There is no
36//! `value` field, because a stored number would be right for one firmware only.
37//!
38//! # What this does not carry
39//!
40//! The manual's prose, for the reason [`param`](crate::param) gives. The
41//! descriptions are in `docs/effects.md`, under the same algorithm and slot
42//! numbers.
43//!
44//! Nor the raw values a selector's names sit at, which the manual does not
45//! publish; see [`FxSlot::values`].
46//!
47//! # Drawing one
48//!
49//! [`Algorithm::panel`] is what the effect's own editor panel is made of: the
50//! control to draw for a sweep, and the four colours measured off the manual's
51//! figure. [`FxSlot::position`] is where the synthesizer's FX page puts a slot
52//! on the one [`grid`] every algorithm shares. The grid is given in the
53//! display's own pixels with the display's dimensions beside it, so a host can
54//! scale it to whatever it draws in.
55//!
56//! Nothing in the algorithm table points at any of this, so a host that draws
57//! its own panels does not carry it.
58//!
59//! # How the four are wired
60//!
61//! [`Routing`] is the ten topologies as edge lists: what reaches each engine,
62//! which engines are summed on the way out, and which two put engines in a
63//! feedback loop. It decides whether `FX 2 Output Gain` reaches the output at
64//! all, since the manual defines a slot's level as the level of an effect that
65//! is in parallel or last before the output stage. [`Mode`] is the same question
66//! one level up: what `Insert`, `Send` and `Bypass` do to the analog and digital
67//! paths.
68
69mod generated;
70
71pub use generated::{
72    ALGORITHM_COUNT, CHARACTER_COUNT, Character, ENGINE_COUNT, FAMILY_COUNT, MARK_PIXEL_SIDE,
73    MODE_COUNT, ROUTING_COUNT, SLOTS_PER_ENGINE, VARIANT_COUNT,
74};
75
76/// The grid a mark's [`pixels`](Mark::pixels) are on, which is the crate's one
77/// pixel grid: the modulation sources' cells are drawn on the same one.
78pub use crate::pixels::Pixels;
79
80use crate::pixels::Glyph;
81
82use generated::{
83    ALGORITHMS, ENGINES, FAMILY_NAMES, GRID, MARKS, MODES, PANELS, ROUTINGS, VARIANTS,
84};
85
86use core::fmt;
87
88use crate::error::{Error, Result};
89use crate::generator::{Generator, MAX_TAPS};
90use crate::param::{DEFAULT_FIRMWARE, Kind, ParamId, TableId};
91use crate::program::Program;
92use crate::sysex::inquiry::Version;
93
94/// One of the four effect engines.
95///
96/// Which one a slot belongs to is what turns "slot 3 of a Room Reverb" into a
97/// parameter a host can edit.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
99#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
100pub enum Engine {
101    /// The first engine, whose slots are `FX 1 Param 1` through `12`.
102    One,
103    /// The second engine.
104    Two,
105    /// The third engine.
106    Three,
107    /// The fourth engine.
108    Four,
109}
110
111/// What one engine addresses, which is the same whatever it is running.
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
113pub(crate) struct EngineParameters {
114    /// The parameter holding which algorithm is loaded.
115    pub(crate) algorithm: ParamId,
116    /// The parameter holding the engine's output gain.
117    pub(crate) gain: ParamId,
118    /// The twelve slot parameters, in slot order.
119    pub(crate) slots: [ParamId; SLOTS_PER_ENGINE],
120}
121
122impl Engine {
123    /// Every engine, in the order the program stores them.
124    ///
125    /// Declared as [`ENGINE_COUNT`] long, which the specification generates, so
126    /// a synthesizer with a fifth engine fails to compile here rather than
127    /// losing one.
128    pub const ALL: [Self; ENGINE_COUNT] = [Self::One, Self::Two, Self::Three, Self::Four];
129
130    /// Returns the engine's zero-based index.
131    #[must_use]
132    pub const fn index(self) -> u8 {
133        match self {
134            Self::One => 0,
135            Self::Two => 1,
136            Self::Three => 2,
137            Self::Four => 3,
138        }
139    }
140
141    /// Returns the engine's number as the display writes it, 1 through 4.
142    #[must_use]
143    pub const fn number(self) -> u8 {
144        self.index() + 1
145    }
146
147    /// Returns the engine with this number, 1 through 4.
148    ///
149    /// # Errors
150    ///
151    /// Returns [`Error::EngineOutOfRange`] for anything else.
152    pub const fn from_number(number: u8) -> Result<Self> {
153        Ok(match number {
154            1 => Self::One,
155            2 => Self::Two,
156            3 => Self::Three,
157            4 => Self::Four,
158            _ => return Err(Error::EngineOutOfRange(number)),
159        })
160    }
161
162    /// Returns the parameter holding which algorithm this engine is running.
163    #[must_use]
164    pub fn algorithm_parameter(self) -> ParamId {
165        self.table().algorithm
166    }
167
168    /// Returns the parameter holding this engine's output gain.
169    ///
170    /// The manual calls it `Level` where the modulation matrix names it, and
171    /// `FX n Output Gain` in the parameter table. What it does to a slot
172    /// depends on where the routing puts that slot, which is `spec/routing.toml`
173    /// and is not published here.
174    #[must_use]
175    pub fn gain_parameter(self) -> ParamId {
176        self.table().gain
177    }
178
179    /// Returns the parameter addressing one of this engine's slots, counting
180    /// from 1.
181    ///
182    /// `None` past [`SLOTS_PER_ENGINE`]. A slot number an algorithm does not
183    /// use still has a parameter: the engine holds twelve bytes whatever it is
184    /// running.
185    #[must_use]
186    pub fn slot_parameter(self, slot: u8) -> Option<ParamId> {
187        let index = usize::from(slot.checked_sub(1)?);
188        self.table().slots.get(index).copied()
189    }
190
191    /// Returns every slot parameter this engine addresses, in slot order.
192    #[must_use]
193    pub fn slot_parameters(self) -> &'static [ParamId; SLOTS_PER_ENGINE] {
194        &self.table().slots
195    }
196
197    /// Returns the engine whose slots include this parameter, if one does.
198    ///
199    /// The way back from a parameter a host is drawing to the engine whose
200    /// algorithm says what it is. Only the twelve slots of an engine answer;
201    /// its type and gain parameters are the engine's own settings rather than
202    /// slots.
203    #[must_use]
204    pub fn of(parameter: ParamId) -> Option<Self> {
205        Self::ALL
206            .into_iter()
207            .find(|engine| engine.table().slots.contains(&parameter))
208    }
209
210    /// Returns what this engine addresses.
211    ///
212    /// The fallback is unreachable: [`Engine::ALL`] is [`ENGINE_COUNT`] long by
213    /// declaration and `ENGINES` is the same length, so the index is always in
214    /// range. It is there so this layer holds no panic.
215    fn table(self) -> &'static EngineParameters {
216        ENGINES
217            .get(usize::from(self.index()))
218            .unwrap_or(&ENGINES[0])
219    }
220}
221
222impl fmt::Display for Engine {
223    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
224        write!(f, "FX {}", self.number())
225    }
226}
227
228/// One of the algorithms an effect engine can run.
229///
230/// Reached through [`Algorithm::for_value`], which takes the byte `FX n Type`
231/// holds and the firmware that byte is to be read against.
232///
233/// # Every value is an effect
234///
235/// There is no `Off`, `None` or `Thru`, and no engine that is running nothing.
236/// Section 7.2.4 of the manual — *"To load an effect into a slot ... select
237/// from one of the following effects"* — lists these 35 and stops, and the
238/// effects table in section 9.1 gives the same 35. `FX n Type` is declared
239/// `0..=34` to match, so there is no value outside the table either.
240///
241/// What takes effects out of circuit is the `Bypass` [`Mode`], and that is the whole
242/// block of four rather than one engine. Three algorithms carry their own
243/// bypass in one of their twelve bytes instead, which is
244/// [`FxSlot::is_enable`].
245///
246/// A host looking for the parameter that silences one engine will not find one.
247/// `FX n Output Gain` is not it: the manual defines a slot's level as the level
248/// of an effect that is in parallel or last before the output stage, so on six
249/// of the ten [`Routing`]s an engine at zero gain still feeds the next engine.
250#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
251#[cfg_attr(feature = "serde", derive(serde::Serialize))]
252#[non_exhaustive]
253pub struct Algorithm {
254    /// Where this algorithm sits in [`Algorithm::all`], which is what reaches
255    /// the panel table beside it.
256    ///
257    /// Not the `FX n Type` byte, which firmware renumbered; see
258    /// [`Algorithm::value_for`] for that.
259    #[cfg_attr(feature = "serde", serde(skip))]
260    pub(crate) index: u8,
261    /// Name as the synthesizer's display writes it, such as `RoomRev`.
262    ///
263    /// The same name the `FX Type` value table gives, which is what joins the
264    /// two across a firmware renumbering.
265    pub name: &'static str,
266    /// Name written out, such as `Room Reverb`.
267    pub full_name: &'static str,
268    /// The family the manual groups it with: `Reverb`, `Delay`, `Processing`
269    /// or `Creative`.
270    ///
271    /// The manual's own table of contents. [`Algorithm::family`] is what an
272    /// effect does to a signal, which is the finer question and the one a mark
273    /// is chosen by.
274    pub category: &'static str,
275    /// What this effect does to a signal.
276    ///
277    /// [`Algorithm::family`](Self::family) is how it is read.
278    #[cfg_attr(feature = "serde", serde(skip))]
279    pub(crate) family: Family,
280    /// Which of the variant marks is its own, where its kind is something a
281    /// symbol can carry.
282    ///
283    /// [`Algorithm::own_mark`](Self::own_mark) is how it is read, and
284    /// [`Algorithm::mark`](Self::mark) is how it is drawn.
285    #[cfg_attr(feature = "serde", serde(skip))]
286    pub(crate) variant: Option<u8>,
287    /// The slots it uses, in slot order.
288    ///
289    /// Shorter than [`SLOTS_PER_ENGINE`] where the algorithm has fewer
290    /// parameters, which is how a host learns not to draw controls that do
291    /// nothing.
292    pub slots: &'static [FxSlot],
293    /// What kind of thing it is, beside what it does.
294    ///
295    /// [`Algorithm::characters`](Self::characters) is how it is read.
296    #[cfg_attr(feature = "serde", serde(skip))]
297    pub(crate) characters: &'static [Character],
298}
299
300impl Algorithm {
301    /// Every algorithm, in the order the newest firmware numbers them.
302    #[must_use]
303    pub fn all() -> &'static [Self; ALGORITHM_COUNT] {
304        &ALGORITHMS
305    }
306
307    /// Returns the algorithm a `FX n Type` value of `value` selects on
308    /// `firmware`.
309    ///
310    /// Goes through the `FX Type` value table rather than indexing this list,
311    /// because firmware 1.1 inserted an algorithm rather than appending one:
312    /// 33 is Rotary Speaker on 1.0 and Vintage Pitch on 1.1.
313    ///
314    /// `None` for a byte the firmware's table does not list.
315    #[must_use]
316    pub fn for_value(value: u8, firmware: Version) -> Option<&'static Self> {
317        let name = TableId::FxType
318            .table_for(firmware)
319            .name_of(u16::from(value))?;
320        Self::by_name(name)
321    }
322
323    /// Returns the algorithm of this name, as the display writes it.
324    #[must_use]
325    pub fn by_name(name: &str) -> Option<&'static Self> {
326        ALGORITHMS.iter().find(|algorithm| algorithm.name == name)
327    }
328
329    /// Returns the `FX n Type` value that selects this algorithm on `firmware`.
330    ///
331    /// `None` where that firmware does not offer it, which is Vintage Pitch on
332    /// 1.0 and is the reason this is not a field.
333    #[must_use]
334    pub fn value_for(&self, firmware: Version) -> Option<u8> {
335        TableId::FxType
336            .table_for(firmware)
337            .entries
338            .iter()
339            .find(|entry| entry.name == self.name)
340            .and_then(|entry| u8::try_from(entry.value).ok())
341    }
342
343    /// Returns one of its slots, counting from 1.
344    ///
345    /// `None` for a slot this algorithm does not use, which is the same answer
346    /// as "draw nothing here".
347    #[must_use]
348    pub fn slot(&self, slot: u8) -> Option<&'static FxSlot> {
349        let index = usize::from(slot.checked_sub(1)?);
350        self.slots.get(index)
351    }
352
353    /// Returns what this algorithm's own editor panel is made of.
354    ///
355    /// Measured off the figure the manual prints beside each algorithm's FX
356    /// page in section 9.3. A Room Reverb and a Phaser are drawn differently
357    /// there, so this says which.
358    ///
359    /// ```
360    /// use deepmind_midi::effect::{Algorithm, Control};
361    /// use deepmind_midi::param::DEFAULT_FIRMWARE;
362    ///
363    /// let room = Algorithm::for_value(2, DEFAULT_FIRMWARE).expect("a Room Reverb");
364    /// assert_eq!(room.panel().control(), Control::Fader);
365    /// assert_eq!(room.panel().cap().to_rgb(), [0x98, 0x93, 0x88]);
366    /// ```
367    #[must_use]
368    pub fn panel(&self) -> &'static Panel {
369        // Unreachable fallback: the index is generated beside the algorithm and
370        // the two tables are declared the same length.
371        PANELS.get(usize::from(self.index)).unwrap_or(&PANELS[0])
372    }
373
374    /// Returns what this effect does to a signal.
375    ///
376    /// [`category`](Self::category) is the four buckets the manual's table of
377    /// contents uses, and `Creative` holds the phaser, the pitch shifter and
378    /// the rotary speaker, which do three unrelated things. This is the same
379    /// kind of published fact at the resolution a symbol needs.
380    ///
381    /// ```
382    /// use deepmind_midi::effect::{Algorithm, Family};
383    ///
384    /// let phaser = Algorithm::by_name("Phaser").expect("a Phaser");
385    /// assert_eq!(phaser.category, "Creative");
386    /// assert_eq!(phaser.family(), Family::Modulation);
387    ///
388    /// let rotary = Algorithm::by_name("RotarySpkr").expect("a Rotary Speaker");
389    /// assert_eq!(rotary.category, "Creative");
390    /// assert_eq!(rotary.family(), Family::Rotary);
391    /// ```
392    #[must_use]
393    pub const fn family(&self) -> Family {
394        self.family
395    }
396
397    /// Returns what kind of thing this effect is, beside what it does.
398    ///
399    /// Any number of [`Character`]s, in the order the specification declares
400    /// them, and empty for an algorithm with nothing to say beyond its
401    /// [`family`](Self::family): the plain reverbs and the noise gate. A host
402    /// reads these to draw a vintage unit as one, a stereo pair as a pair, two
403    /// effects in one engine as two, and it reads them here rather than
404    /// matching on `Vintage` in a name.
405    ///
406    /// ```
407    /// use deepmind_midi::effect::{Algorithm, Character};
408    ///
409    /// let tel_ray = Algorithm::by_name("T-RayDelay").expect("a Tel-Ray Delay");
410    /// assert!(tel_ray.characters().contains(&Character::Vintage));
411    /// assert!(tel_ray.characters().contains(&Character::LoFi));
412    ///
413    /// let hall = Algorithm::by_name("HallRev").expect("a Hall Reverb");
414    /// assert!(!hall.characters().contains(&Character::Vintage));
415    /// assert!(hall.has(Character::Modulated));
416    /// ```
417    #[must_use]
418    pub const fn characters(&self) -> &'static [Character] {
419        self.characters
420    }
421
422    /// Returns whether this effect has `character`.
423    #[must_use]
424    pub fn has(&self, character: Character) -> bool {
425        self.characters.contains(&character)
426    }
427
428    /// Returns the mark to draw for this effect.
429    ///
430    /// Its [own](Self::own_mark) where it has one, and its
431    /// [`family`](Self::family)'s otherwise: a plate reverb is drawn as a plate
432    /// with wavefronts leaving it, a hall as wavefronts far from their source,
433    /// and an ambient reverb, which is a reverb and nothing a symbol can add
434    /// to, as the family's source and two wavefronts. Either way it is the
435    /// same language, so the four engines read as one set whichever marks
436    /// they land on.
437    ///
438    /// ```
439    /// use deepmind_midi::effect::{Algorithm, Family};
440    ///
441    /// let plate = Algorithm::by_name("PlateRev").expect("a Plate Reverb");
442    /// let ambient = Algorithm::by_name("AmbVerb").expect("an Ambient Reverb");
443    ///
444    /// assert!(plate.own_mark().is_some());
445    /// assert!(ambient.own_mark().is_none());
446    /// assert_eq!(ambient.mark(), Family::Reverb.mark());
447    /// assert_ne!(plate.mark(), Family::Reverb.mark());
448    /// ```
449    #[must_use]
450    pub fn mark(&self) -> &'static Mark {
451        self.own_mark().unwrap_or_else(|| self.family.mark())
452    }
453
454    /// Returns the mark drawn for this effect's kind, where its kind is
455    /// something a symbol can carry.
456    ///
457    /// `None` for an algorithm whose family says everything a symbol can: a
458    /// host that wants to know whether the mark it is about to draw is the
459    /// family's or finer asks here. `spec/marks.toml` says which kinds are
460    /// drawn and why.
461    #[must_use]
462    pub fn own_mark(&self) -> Option<&'static Mark> {
463        VARIANTS.get(usize::from(self.variant?))
464    }
465
466    /// Returns the slot an engine's `parameter` is, under this algorithm.
467    ///
468    /// `None` when the parameter is not one of that engine's twelve, and when
469    /// it is one the algorithm leaves unused.
470    #[must_use]
471    pub fn slot_of(&self, engine: Engine, parameter: ParamId) -> Option<&'static FxSlot> {
472        let index = engine
473            .slot_parameters()
474            .iter()
475            .position(|slot| *slot == parameter)?;
476        self.slots.get(index)
477    }
478}
479
480impl fmt::Display for Algorithm {
481    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
482        f.write_str(self.full_name)
483    }
484}
485
486/// One slot of an effect engine, as the algorithm running it defines the slot.
487#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
488#[cfg_attr(feature = "serde", derive(serde::Serialize))]
489#[non_exhaustive]
490pub struct FxSlot {
491    /// Position within the engine's twelve parameters, counting from 1.
492    ///
493    /// [`Engine::slot_parameter`] turns it into the parameter that addresses
494    /// the byte.
495    pub slot: u8,
496    /// The short name the synthesizer's display prints, such as `PRE`.
497    pub reference: &'static str,
498    /// The same name written out, such as `Pre-Delay`.
499    ///
500    /// Expanded by this project for a panel with room to be readable, not a
501    /// spelling the hardware uses; [`reference`](Self::reference) is the
502    /// hardware's own.
503    pub title: &'static str,
504    /// How the byte is read, in the same terms a program parameter uses.
505    ///
506    /// [`Kind::Switch`] for a slot with two states and [`Kind::Continuous`] for
507    /// everything else, so that a host's "what control is this" code is one
508    /// path rather than two.
509    ///
510    /// Never [`Kind::Enumerated`]. A slot that picks from a list picks from
511    /// [`values`](Self::values), and the manual prints those names without the
512    /// bytes they sit at, so there is no value table to point at.
513    pub kind: Kind,
514    /// The names the display shows, where it shows names rather than a number.
515    ///
516    /// In the order the manual prints them. Which byte shows which name is not
517    /// published, so these are a reading rather than an address and none of them
518    /// is something to send. Empty for a slot the display shows a number on.
519    pub values: &'static [&'static str],
520    /// Unit of the displayed value, where the manual gives one.
521    pub unit: Option<&'static str>,
522    /// Lowest value the synthesizer displays, as the manual prints it.
523    ///
524    /// A display reading and not a raw byte: every slot is a byte, and the
525    /// curve between the two ends is not published. [`None`] for a slot with
526    /// names instead of a range.
527    pub min: Option<&'static str>,
528    /// Highest value the synthesizer displays, as the manual prints it.
529    pub max: Option<&'static str>,
530    /// Label shared by the slots that belong together, such as one side of a
531    /// stereo engine or one band of an equaliser.
532    ///
533    /// Derived from the parameter names by this project rather than printed by
534    /// the manual, so it is a convention for laying a panel out and not a fact
535    /// about the hardware.
536    pub group: Option<&'static str>,
537    /// `true` when the engine acts on modulation reaching this slot.
538    ///
539    /// Every slot is addressable from the modulation matrix regardless, as
540    /// `Fx n Param m`; this says the engine does something with what arrives.
541    pub modulatable: bool,
542    /// `true` when this switch takes the whole effect out of circuit.
543    ///
544    /// [`FxSlot::is_enable`](Self::is_enable) is how it is read, and says why
545    /// there are only three.
546    #[cfg_attr(feature = "serde", serde(skip))]
547    pub(crate) enable: bool,
548    /// What this slot does to a signal.
549    ///
550    /// [`FxSlot::quantity`](Self::quantity) is how it is read.
551    #[cfg_attr(feature = "serde", serde(skip))]
552    pub(crate) quantity: Quantity,
553    /// The picture of what this slot does.
554    ///
555    /// [`FxSlot::glyph`](Self::glyph) is how it is read.
556    #[cfg_attr(feature = "serde", serde(skip))]
557    pub(crate) glyph: Glyph,
558    /// Column of the FX page's grid this slot is drawn in, counting from 0.
559    #[cfg_attr(feature = "serde", serde(skip))]
560    pub(crate) column: u8,
561    /// Row of the FX page's grid this slot is drawn in, counting from 0.
562    #[cfg_attr(feature = "serde", serde(skip))]
563    pub(crate) row: u8,
564    /// What the manual says this slot does, where it says anything.
565    ///
566    /// Present only under the `descriptions` feature, so that a build without
567    /// it carries neither the prose nor a pointer to it.
568    /// [`FxSlot::description`](Self::description) is how it is read, and
569    /// answers `None` when the feature is off.
570    #[cfg(feature = "descriptions")]
571    #[cfg_attr(feature = "serde", serde(skip))]
572    pub(crate) description: Option<&'static str>,
573}
574
575impl FxSlot {
576    /// Returns where the synthesizer's own FX page draws this slot.
577    ///
578    /// On the one [`grid`] every algorithm shares: six columns and two rows,
579    /// filled in slot order from the top left. The column and the row are what
580    /// `spec/layout.toml` measured; the centre follows from the grid.
581    #[must_use]
582    pub const fn position(&self) -> Position {
583        Position {
584            column: self.column,
585            row: self.row,
586        }
587    }
588
589    /// Returns whether the display shows a name here rather than a number.
590    ///
591    /// Which is [`values`](Self::values) not being empty. Ask before drawing a
592    /// control: the names are what to print, not what to send.
593    #[must_use]
594    pub const fn is_selector(&self) -> bool {
595        !self.values.is_empty()
596    }
597
598    /// Returns what this slot does to a signal, as against what it is called.
599    ///
600    /// [`kind`](Self::kind) says what control to draw. This says what picture
601    /// the slot belongs in, which is a different question with a different
602    /// answer: a `Mix`, a `Feedback` and a `Pre-Delay` are all a byte `0..=255`
603    /// and they do three unrelated things to a drawing.
604    ///
605    /// It is what lets a host group an algorithm's slots without matching on
606    /// titles across 35 algorithms.
607    ///
608    /// ```
609    /// use deepmind_midi::effect::{Algorithm, Quantity};
610    ///
611    /// let delay = Algorithm::by_name("3TapDelay").expect("a 3-Tap Delay");
612    ///
613    /// // Drawn as a selector, because it picks from ten printed fractions.
614    /// let factor = delay.slot(5).expect("a FactorA slot");
615    /// assert!(factor.is_selector());
616    /// // And it is a time, because what it sets is when the tap lands.
617    /// assert_eq!(factor.quantity(), Quantity::Time);
618    /// ```
619    #[must_use]
620    pub const fn quantity(&self) -> Quantity {
621        self.quantity
622    }
623
624    /// Returns the picture of what this slot does, the size of a character.
625    ///
626    /// Finer than [`quantity`](Self::quantity), and for a screen rather than
627    /// for grouping: a pre-delay and a decay are both a [`Quantity::Time`],
628    /// and a host with room for a picture beside each of the twelve wants the
629    /// gap drawn on one and the tail on the other. Every slot has one, because
630    /// what a slot does is the one thing the algorithm always knows about it;
631    /// `spec/glyphs.toml` says how each was chosen.
632    ///
633    /// The same [`Glyph`] serves every slot that does the same thing, so a
634    /// `Low Cut` on a reverb and one on a delay are one picture, and so is
635    /// the [`ParamId`] a program parameter doing the same thing carries.
636    ///
637    /// ```
638    /// use deepmind_midi::effect::Algorithm;
639    /// use deepmind_midi::pixels::Glyph;
640    ///
641    /// let room = Algorithm::by_name("RoomRev").expect("a Room Reverb");
642    /// assert_eq!(room.slot(1).expect("Pre-Delay").glyph(), Glyph::PreDelay);
643    /// assert_eq!(room.slot(2).expect("Decay").glyph(), Glyph::Decay);
644    /// assert_eq!(room.slot(7).expect("Low Cut").glyph(), Glyph::LowCut);
645    ///
646    /// let amp = Algorithm::by_name("RackAmp").expect("a Rack Amplifier");
647    /// assert_eq!(amp.slot(9).expect("Cabinet").glyph(), Glyph::Cabinet);
648    /// ```
649    #[must_use]
650    pub const fn glyph(&self) -> Glyph {
651        self.glyph
652    }
653
654    /// Returns whether this slot switches the whole effect in and out of
655    /// circuit.
656    ///
657    /// True for three slots of the 35 algorithms, and it is the only
658    /// slot-level off the instrument has: Stereo Imaging and Chorus D each
659    /// spend their first slot on an `ON`, and the Noise Gate its eighth on a
660    /// `PWR`. Nothing outside those three takes one engine out on its own; see
661    /// [`Algorithm`] for what the instrument does instead.
662    ///
663    /// A host that would otherwise match on `ON` and `PWR` as strings asks
664    /// this. Which way round the switch reads is
665    /// [`min`](Self::min) and [`max`](Self::max), and the Noise Gate is the one
666    /// that reads `ON` at the bottom and `OFF` at the top.
667    ///
668    /// Not the Rack Amplifier's `CAB`, which switches its cabinet simulation
669    /// and leaves the amplifier running. That is a stage within the effect, so
670    /// it is a plain [`Kind::Switch`].
671    ///
672    /// ```
673    /// use deepmind_midi::effect::Algorithm;
674    ///
675    /// let gate = Algorithm::by_name("NoiseGate").expect("a Noise Gate");
676    /// assert!(gate.slot(8).expect("a Power slot").is_enable());
677    ///
678    /// let amp = Algorithm::by_name("RackAmp").expect("a Rack Amplifier");
679    /// assert!(!amp.slot(9).expect("a Cabinet slot").is_enable());
680    /// ```
681    #[must_use]
682    pub const fn is_enable(&self) -> bool {
683        self.enable
684    }
685
686    /// Returns what this slot does, in the manual's own words.
687    ///
688    /// [`title`](Self::title) says a slot is called `Damping`; this says what it
689    /// damps. Transcribed from section 9.3 of the manual rather than written
690    /// here, so it says what the engine's designers say it does. See NOTICE.
691    ///
692    /// # Behind a feature
693    ///
694    /// `None` unless the `descriptions` feature is on, and `None` with it on
695    /// for a slot the manual describes no further. The signature is the same
696    /// either way, so a host writes one code path and an embedded build carries
697    /// none of the prose.
698    ///
699    /// ```
700    /// use deepmind_midi::effect::Algorithm;
701    /// use deepmind_midi::param::DEFAULT_FIRMWARE;
702    ///
703    /// let room = Algorithm::for_value(2, DEFAULT_FIRMWARE).expect("a Room Reverb");
704    /// let decay = room.slot(2).expect("a Decay slot");
705    /// assert_eq!(decay.title, "Decay");
706    /// assert_eq!(decay.description().is_some(), cfg!(feature = "descriptions"));
707    /// ```
708    #[must_use]
709    pub const fn description(&self) -> Option<&'static str> {
710        #[cfg(feature = "descriptions")]
711        {
712            self.description
713        }
714        #[cfg(not(feature = "descriptions"))]
715        {
716            None
717        }
718    }
719}
720
721impl fmt::Display for FxSlot {
722    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
723        f.write_str(self.title)
724    }
725}
726
727/// Returns the grid the synthesizer draws its own FX page on.
728///
729/// Six columns and two rows, in the pixels of the 128x64 display the 35
730/// screenshots in the manual were measured on. The dimensions come with it, so a
731/// host scales a proportion rather than adopting a size.
732///
733/// The page itself draws every slot as a circle, switches and selectors
734/// included, with the slot's short name above it and its value below. What an
735/// algorithm's own editor panel draws instead is [`Panel::control`], and the two
736/// disagree for five effects: this is where a slot sits, that is what it looks
737/// like.
738///
739/// ```
740/// use deepmind_midi::effect::grid;
741///
742/// assert_eq!(grid().columns(), 6);
743/// assert_eq!(grid().rows(), 2);
744/// assert!((grid().display_width() - 128.0).abs() < f32::EPSILON);
745/// ```
746#[must_use]
747pub const fn grid() -> &'static Grid {
748    &GRID
749}
750
751/// The grid the synthesizer's FX page places every algorithm's slots on.
752///
753/// Reached through [`grid`]. Measured off the manual's own screenshots, all 35
754/// of which agree; see [`FxSlot::position`] for where one slot lands on it.
755#[derive(Debug, Clone, Copy, PartialEq)]
756#[cfg_attr(feature = "serde", derive(serde::Serialize))]
757pub struct Grid {
758    columns: u8,
759    rows: u8,
760    display_width: f32,
761    display_height: f32,
762    first_x: f32,
763    first_y: f32,
764    column_pitch: f32,
765    row_pitch: f32,
766    control_diameter: f32,
767}
768
769impl Grid {
770    /// Returns how many slots fit across a row.
771    #[must_use]
772    pub const fn columns(&self) -> u8 {
773        self.columns
774    }
775
776    /// Returns how many rows the page holds.
777    #[must_use]
778    pub const fn rows(&self) -> u8 {
779        self.rows
780    }
781
782    /// Returns the width of the display these measurements are in.
783    #[must_use]
784    pub const fn display_width(&self) -> f32 {
785        self.display_width
786    }
787
788    /// Returns the height of the display these measurements are in.
789    #[must_use]
790    pub const fn display_height(&self) -> f32 {
791        self.display_height
792    }
793
794    /// Returns the distance between the centres of two columns.
795    #[must_use]
796    pub const fn column_pitch(&self) -> f32 {
797        self.column_pitch
798    }
799
800    /// Returns the distance between the centres of two rows.
801    #[must_use]
802    pub const fn row_pitch(&self) -> f32 {
803        self.row_pitch
804    }
805
806    /// Returns the diameter of the circle the page draws for a slot.
807    #[must_use]
808    pub const fn control_diameter(&self) -> f32 {
809        self.control_diameter
810    }
811
812    /// Returns the centre of one cell, in the display's own pixels.
813    ///
814    /// The cell a left-aligned row puts its `column`th slot in, which every row
815    /// in the specification is; [`Row::align`] is what says so, and is there for
816    /// a host laying a partial row out some other way.
817    #[must_use]
818    pub fn centre(&self, column: u8, row: u8) -> (f32, f32) {
819        (
820            self.first_x + f32::from(column) * self.column_pitch,
821            self.first_y + f32::from(row) * self.row_pitch,
822        )
823    }
824}
825
826/// Where the FX page draws one slot.
827///
828/// Reached through [`FxSlot::position`].
829#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
830#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
831pub struct Position {
832    column: u8,
833    row: u8,
834}
835
836impl Position {
837    /// Returns which column of the grid, counting from 0.
838    #[must_use]
839    pub const fn column(&self) -> u8 {
840        self.column
841    }
842
843    /// Returns which row of the grid, counting from 0.
844    #[must_use]
845    pub const fn row(&self) -> u8 {
846        self.row
847    }
848
849    /// Returns the centre of this position, in the display's own pixels.
850    ///
851    /// As [`Grid::centre`], which is what it calls.
852    #[must_use]
853    pub fn centre(&self) -> (f32, f32) {
854        GRID.centre(self.column, self.row)
855    }
856}
857
858/// What an effect does to a signal, as a closed set.
859///
860/// [`Algorithm::category`] is the manual's own four buckets, chosen for a table
861/// of contents: `Creative` holds the phaser, the pitch shifter and the rotary
862/// speaker. This is the finer question, and the one [`Algorithm::mark`] is
863/// chosen by.
864///
865/// Where the two disagree is the point of having both. A host that wants to
866/// reproduce the manual's grouping reads the category; one that wants to draw a
867/// symbol, or to put the four delays together whatever page they are printed
868/// on, reads this.
869#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
870#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
871#[non_exhaustive]
872pub enum Family {
873    /// A decaying tail. Thirteen of the 35, including the three that pair a
874    /// reverb with something else.
875    Reverb,
876    /// Discrete repeats. The six the manual files under `Delay`.
877    Delay,
878    /// A swept delay: the chorus, the flanger and the phaser.
879    Modulation,
880    /// A response with a corner in it: the two equalisers and the Mood Filter.
881    Filter,
882    /// Level against level: the compressor and the noise gate.
883    Dynamics,
884    /// Harmonics added by driving a stage: the multi-band distortion and the
885    /// rack amplifier.
886    Distortion,
887    /// The stereo field: the Stereo Imaging and Auto-Panning.
888    Imaging,
889    /// An interval put beside the note: the two pitch shifters.
890    Pitch,
891    /// A horn going round: the Rotary Speaker, which is its own family because
892    /// it is its own thing.
893    Rotary,
894}
895
896impl Family {
897    /// Every family, in the order the specification declares them.
898    ///
899    /// Declared as [`FAMILY_COUNT`] long, which the specification generates, so
900    /// a family added to `spec/marks.toml` fails to compile here rather than
901    /// being left without a variant.
902    pub const ALL: [Self; FAMILY_COUNT] = [
903        Self::Reverb,
904        Self::Delay,
905        Self::Modulation,
906        Self::Filter,
907        Self::Dynamics,
908        Self::Distortion,
909        Self::Imaging,
910        Self::Pitch,
911        Self::Rotary,
912    ];
913
914    /// Returns this family's zero-based index, which is where its mark is.
915    #[must_use]
916    pub const fn index(self) -> usize {
917        match self {
918            Self::Reverb => 0,
919            Self::Delay => 1,
920            Self::Modulation => 2,
921            Self::Filter => 3,
922            Self::Dynamics => 4,
923            Self::Distortion => 5,
924            Self::Imaging => 6,
925            Self::Pitch => 7,
926            Self::Rotary => 8,
927        }
928    }
929
930    /// Returns the family's name, as the specification writes it.
931    #[must_use]
932    pub fn name(self) -> &'static str {
933        // Unreachable fallback: `ALL` and the generated table are declared the
934        // same length and this indexes by the position in `ALL`.
935        FAMILY_NAMES.get(self.index()).copied().unwrap_or("Reverb")
936    }
937
938    /// Returns the mark this family is drawn with.
939    #[must_use]
940    pub fn mark(self) -> &'static Mark {
941        // Unreachable fallback, for the same reason as [`Family::name`].
942        MARKS.get(self.index()).unwrap_or(&MARKS[0])
943    }
944
945    /// Returns every algorithm in this family, in `FX Type` order.
946    pub fn algorithms(self) -> impl Iterator<Item = &'static Algorithm> {
947        ALGORITHMS
948            .iter()
949            .filter(move |algorithm| algorithm.family == self)
950    }
951}
952
953impl fmt::Display for Family {
954    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
955        f.write_str(self.name())
956    }
957}
958
959impl Character {
960    /// Returns every algorithm that has this character, in `FX Type` order.
961    ///
962    /// ```
963    /// use deepmind_midi::effect::Character;
964    ///
965    /// let combined: Vec<&str> = Character::Combined
966    ///     .algorithms()
967    ///     .map(|algorithm| algorithm.name)
968    ///     .collect();
969    /// assert_eq!(combined, ["ChorusVerb", "DelayVerb", "FlangVerb", "ModDlyRev"]);
970    /// ```
971    pub fn algorithms(self) -> impl Iterator<Item = &'static Algorithm> {
972        ALGORITHMS
973            .iter()
974            .filter(move |algorithm| algorithm.characters.contains(&self))
975    }
976}
977
978impl fmt::Display for Character {
979    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
980        f.write_str(self.name())
981    }
982}
983
984/// A mark for an effect, drawn in the host's own materials.
985///
986/// Reached through [`Algorithm::mark`] or [`Family::mark`]. The data a drawing
987/// is generated from, not the drawing: a host cannot theme, rescale, hit-test
988/// or animate an SVG it did not lay out, and the same mark is wanted in a dark
989/// panel at twelve points and at forty.
990///
991/// [`strokes`](Self::strokes) is what to draw, in a unit box with the origin at
992/// the top left and y increasing downward. The host provides the size, the
993/// stroke width and the colour. Nothing here is filled and no path closes.
994///
995/// ```
996/// use deepmind_midi::effect::{Algorithm, Stroke};
997///
998/// let delay = Algorithm::by_name("3TapDelay").expect("a 3-Tap Delay");
999/// let strokes = delay.mark().strokes();
1000///
1001/// // A baseline and the taps standing on it, all inside the unit box.
1002/// assert!(!strokes.is_empty());
1003/// for stroke in strokes {
1004///     if let Stroke::Line { points } = stroke {
1005///         assert!(points.iter().all(|p| (0.0..=1.0).contains(&p.x())));
1006///     }
1007/// }
1008/// ```
1009///
1010/// # What it is not
1011///
1012/// Not measured off the manual, unlike [`Panel`]'s colours. These are drawn by
1013/// this project: a reading of what each family does, rather than a
1014/// reproduction of anything the manufacturer prints. No font, no raster and no
1015/// licensed symbol set.
1016///
1017/// Not a layout. Whether the mark goes beside the name, in the corner of a
1018/// panel or on a tab is the host's question, the same way the [`grid`] is data
1019/// and the pixel size is not.
1020#[derive(Debug, Clone, Copy, PartialEq)]
1021#[cfg_attr(feature = "serde", derive(serde::Serialize))]
1022pub struct Mark {
1023    strokes: &'static [Stroke],
1024    pixels: Pixels,
1025}
1026
1027impl Mark {
1028    /// Returns the strokes that make the mark up, in drawing order.
1029    #[must_use]
1030    pub const fn strokes(&self) -> &'static [Stroke] {
1031        self.strokes
1032    }
1033
1034    /// Returns the same mark on a [`MARK_PIXEL_SIDE`] square grid, one bit a
1035    /// pixel.
1036    ///
1037    /// For a display with no room to stroke anything: an LCD row beside an
1038    /// effect name, or a hardware panel. Above about sixteen pixels a host
1039    /// wants [`strokes`](Self::strokes) instead, which has no size of its own.
1040    ///
1041    /// Drawn by hand rather than reduced from the strokes, for the reason the
1042    /// [`pixels`](crate::pixels) module gives.
1043    ///
1044    /// ```
1045    /// use deepmind_midi::effect::{Algorithm, MARK_PIXEL_SIDE};
1046    ///
1047    /// let rotary = Algorithm::by_name("RotarySpkr").expect("a Rotary Speaker");
1048    /// let pixels = rotary.mark().pixels();
1049    ///
1050    /// // A ring with its centre marked, so the middle pixel is lit and the
1051    /// // ones either side of it are not.
1052    /// let middle = (MARK_PIXEL_SIDE / 2) as u8;
1053    /// assert!(pixels.is_lit(middle, middle));
1054    /// assert!(!pixels.is_lit(middle - 1, middle));
1055    /// ```
1056    #[must_use]
1057    pub const fn pixels(&self) -> &Pixels {
1058        &self.pixels
1059    }
1060}
1061
1062/// One stroke of a [`Mark`], in a unit box with the origin top left.
1063///
1064/// Two kinds, because a rotary speaker wants a circle and everything else wants
1065/// a polyline, and approximating the circle with one would put the number of
1066/// segments in this library rather than in the host that knows how big it is
1067/// drawing.
1068#[derive(Debug, Clone, Copy, PartialEq)]
1069#[cfg_attr(feature = "serde", derive(serde::Serialize))]
1070#[non_exhaustive]
1071pub enum Stroke {
1072    /// A polyline through two or more points, stroked and not closed.
1073    Line {
1074        /// The points, in order.
1075        points: &'static [Point],
1076    },
1077    /// An arc of a circle.
1078    ///
1079    /// Only the swept part is inside the box; the circle it is taken from may
1080    /// reach outside, which is what lets a shallow arc be drawn from a distant
1081    /// centre.
1082    Arc {
1083        /// Centre of the circle it is taken from.
1084        centre: Point,
1085        /// Radius of that circle.
1086        radius: f32,
1087        /// Where the arc begins, in turns clockwise from three o'clock.
1088        ///
1089        /// Clockwise because the box has y increasing downward, so a positive
1090        /// sweep turns the way a reader expects on screen.
1091        start: f32,
1092        /// How far it goes, in turns. A whole turn is a closed circle.
1093        sweep: f32,
1094    },
1095    /// A filled disc.
1096    ///
1097    /// The one thing in a mark that is filled rather than stroked, and the only
1098    /// one whose size is not the host's stroke width. Two marks use it: the
1099    /// source a reverb's wavefronts leave, and the centre of the rotary ring.
1100    Dot {
1101        /// Centre of the disc.
1102        centre: Point,
1103        /// Radius of the disc.
1104        radius: f32,
1105    },
1106    /// A sine along the line from `start` to `end`.
1107    ///
1108    /// A function rather than a set of points, so a host samples it as finely
1109    /// as the size it is drawing at deserves. The alternative is a polyline,
1110    /// and a polyline through a sine is a row of corners: how many corners is a
1111    /// question about the host's pixels, which this library does not have and
1112    /// the [`generator`](crate::generator) module refuses for the same reason.
1113    ///
1114    /// The value at `u` along `0..=1` of the centre line is that point,
1115    /// displaced perpendicular by `amplitude * sin(TAU * cycles * u)`. The
1116    /// perpendicular is the start-to-end direction turned a quarter turn
1117    /// anticlockwise, which in a box with y downward points up the screen, so a
1118    /// positive sine rises.
1119    Wave {
1120        /// Where the centre line begins.
1121        start: Point,
1122        /// Where the centre line ends.
1123        end: Point,
1124        /// Peak displacement from the centre line, perpendicular to it.
1125        amplitude: f32,
1126        /// Cycles between `start` and `end`.
1127        cycles: f32,
1128    },
1129}
1130
1131/// A point of a [`Mark`], in a unit box with the origin top left.
1132///
1133/// Unitless, so a host multiplies by whatever it is drawing into.
1134#[derive(Debug, Clone, Copy, PartialEq)]
1135#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1136pub struct Point {
1137    x: f32,
1138    y: f32,
1139}
1140
1141impl Point {
1142    /// Builds a point from its two coordinates.
1143    #[must_use]
1144    pub const fn new(x: f32, y: f32) -> Self {
1145        Self { x, y }
1146    }
1147
1148    /// Returns the distance from the left of the box, 0 to 1.
1149    #[must_use]
1150    pub const fn x(self) -> f32 {
1151        self.x
1152    }
1153
1154    /// Returns the distance from the top of the box, 0 to 1.
1155    #[must_use]
1156    pub const fn y(self) -> f32 {
1157        self.y
1158    }
1159}
1160
1161/// What an effect's own editor panel is made of.
1162///
1163/// Reached through [`Algorithm::panel`]. Measured off the figure printed beside
1164/// each algorithm's FX page in section 9.3 of the manual: the panels differ per
1165/// algorithm, so this is a fact about the effect rather than a house style.
1166///
1167/// Twelve bytes of colour and a control shape. No artwork is reproduced.
1168#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1169#[cfg_attr(feature = "serde", derive(serde::Serialize))]
1170pub struct Panel {
1171    control: Control,
1172    chassis: Colour,
1173    face: Colour,
1174    cap: Colour,
1175    accent: Colour,
1176    rows: &'static [Row],
1177}
1178
1179impl Panel {
1180    /// Returns what this panel draws for a parameter that sweeps a range.
1181    ///
1182    /// A switch or a selector is a button whatever the panel is made of, which
1183    /// is [`FxSlot::kind`] and [`FxSlot::is_selector`]; this is the shape the
1184    /// rest of the slots take.
1185    #[must_use]
1186    pub const fn control(&self) -> Control {
1187        self.control
1188    }
1189
1190    /// Returns the case around the controls.
1191    #[must_use]
1192    pub const fn chassis(&self) -> Colour {
1193        self.chassis
1194    }
1195
1196    /// Returns the surface the controls sit on.
1197    #[must_use]
1198    pub const fn face(&self) -> Colour {
1199        self.face
1200    }
1201
1202    /// Returns the part a finger moves: a knob body or a fader cap.
1203    #[must_use]
1204    pub const fn cap(&self) -> Colour {
1205        self.cap
1206    }
1207
1208    /// Returns the most saturated colour covering a visible share of the panel.
1209    ///
1210    /// A label colour on a panel that has one, an LED on one that does not, and
1211    /// [`cap`](Self::cap) again on a panel with neither.
1212    #[must_use]
1213    pub const fn accent(&self) -> Colour {
1214        self.accent
1215    }
1216
1217    /// Returns the rows this algorithm fills, in the order they are drawn.
1218    #[must_use]
1219    pub const fn rows(&self) -> &'static [Row] {
1220        self.rows
1221    }
1222}
1223
1224/// One row of an algorithm's slots on the FX page.
1225#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1226#[cfg_attr(feature = "serde", derive(serde::Serialize))]
1227pub struct Row {
1228    slots: &'static [u8],
1229    align: Align,
1230}
1231
1232impl Row {
1233    /// Returns the slots on this row, in the order they are drawn, counting
1234    /// from 1.
1235    #[must_use]
1236    pub const fn slots(&self) -> &'static [u8] {
1237        self.slots
1238    }
1239
1240    /// Returns what this row does with the space left over when it is not full.
1241    #[must_use]
1242    pub const fn align(&self) -> Align {
1243        self.align
1244    }
1245}
1246
1247/// What an effect's own editor panel draws for a parameter that sweeps a range.
1248///
1249/// 29 of the 35 algorithms use rotary knobs, five use vertical faders on a
1250/// cream surface with a lit label strip, and the Vintage Room Reverb uses
1251/// numeric displays with a single knob.
1252#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1253#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1254#[non_exhaustive]
1255pub enum Control {
1256    /// A rotary knob.
1257    Knob,
1258    /// A vertical fader.
1259    Fader,
1260    /// A numeric display.
1261    Display,
1262}
1263
1264/// What an effect slot does to a signal, as against what it is called.
1265///
1266/// Reached through [`FxSlot::quantity`]. [`Kind`] is what control to draw; this
1267/// is what picture the slot belongs in. The two are separate because they
1268/// disagree: a delay's `Factor` is drawn as a selector, because it picks from
1269/// ten printed fractions, and what it sets is when a tap lands.
1270///
1271/// Derived from the parameter rather than stated by the manual, the same way
1272/// [`FxSlot::title`] and [`FxSlot::group`] are, so it is a convention this
1273/// project chose. `spec/panels.toml` records how, and names the slots where the
1274/// manual's own description decided it against what the name suggests.
1275#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1276#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1277#[non_exhaustive]
1278pub enum Quantity {
1279    /// When something happens: a pre-delay, an envelope stage, a tap's place in
1280    /// a pattern.
1281    Time,
1282    /// Where in the spectrum: a cut, a corner, a rate, an interval.
1283    Frequency,
1284    /// How loud: an input, an output, a threshold, a band's level.
1285    Gain,
1286    /// How much of the output goes back in.
1287    Feedback,
1288    /// How much effect there is: a mix, a drive, a density.
1289    Depth,
1290    /// Where in the stereo field: a pan, a width, a spread, a phase offset.
1291    Position,
1292    /// What the response looks like: a Q, a damping, a size, a wave morph.
1293    Shape,
1294    /// In or out.
1295    Switch,
1296    /// One of a list of named kinds: a preset, a cabinet, a distortion type.
1297    ///
1298    /// Not a quantity at all, which is why it is last. A slot that picks from a
1299    /// list still has to answer, and `Shape` would have been a lie.
1300    Selection,
1301}
1302
1303impl Quantity {
1304    /// Every quantity, in the order they are declared.
1305    pub const ALL: [Self; 9] = [
1306        Self::Time,
1307        Self::Frequency,
1308        Self::Gain,
1309        Self::Feedback,
1310        Self::Depth,
1311        Self::Position,
1312        Self::Shape,
1313        Self::Switch,
1314        Self::Selection,
1315    ];
1316}
1317
1318/// What a row that is not full does with the space left over.
1319///
1320/// [`Align::Left`] on every row of every algorithm as measured. The rest of the
1321/// variants are what a host with a different panel width says instead, which is
1322/// what the field is for.
1323#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
1324#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1325#[non_exhaustive]
1326pub enum Align {
1327    /// Packed against the start of the row.
1328    #[default]
1329    Left,
1330    /// Packed against the end of the row.
1331    Right,
1332    /// Packed together in the middle.
1333    Centre,
1334    /// Spread across the whole row.
1335    Spread,
1336}
1337
1338/// One colour measured off a printed panel.
1339///
1340/// Three components rather than a string, so that no host has to parse the same
1341/// six hex characters. How the specification stores it is this library's
1342/// business.
1343#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1344#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1345pub struct Colour {
1346    red: u8,
1347    green: u8,
1348    blue: u8,
1349}
1350
1351impl Colour {
1352    /// Builds a colour from its three components.
1353    #[must_use]
1354    pub const fn new(red: u8, green: u8, blue: u8) -> Self {
1355        Self { red, green, blue }
1356    }
1357
1358    /// Returns the red component.
1359    #[must_use]
1360    pub const fn red(self) -> u8 {
1361        self.red
1362    }
1363
1364    /// Returns the green component.
1365    #[must_use]
1366    pub const fn green(self) -> u8 {
1367        self.green
1368    }
1369
1370    /// Returns the blue component.
1371    #[must_use]
1372    pub const fn blue(self) -> u8 {
1373        self.blue
1374    }
1375
1376    /// Returns the three components, in the order a `#rrggbb` string writes
1377    /// them.
1378    #[must_use]
1379    pub const fn to_rgb(self) -> [u8; 3] {
1380        [self.red, self.green, self.blue]
1381    }
1382}
1383
1384impl fmt::Display for Colour {
1385    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1386        write!(f, "#{:02x}{:02x}{:02x}", self.red, self.green, self.blue)
1387    }
1388}
1389
1390/// One of the ten ways the four engines can be wired.
1391///
1392/// The `FX Routing` byte picks one. [`enums`](crate::param::TableId) names them
1393/// the way the manual does, `Parallel 1/2, parallel 3/4`, which is for a person
1394/// to read. This is the same ten topologies as edge lists, which is what a host
1395/// draws a chain from.
1396///
1397/// ```
1398/// use deepmind_midi::effect::{Engine, Routing, Source};
1399///
1400/// // M-1 is the four in series, and only the fourth reaches the output.
1401/// let serial = Routing::for_value(0).expect("ten topologies");
1402/// assert_eq!(serial.label(), "M-1");
1403/// assert_eq!(serial.feeds(Engine::One), &[Source::Input]);
1404/// assert_eq!(serial.feeds(Engine::Two), &[Source::Engine(Engine::One)]);
1405/// assert_eq!(serial.output(), &[Engine::Four]);
1406/// assert!(!serial.is_feedback());
1407/// ```
1408#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1409#[cfg_attr(feature = "serde", derive(serde::Serialize))]
1410pub struct Routing {
1411    value: u8,
1412    label: &'static str,
1413    name: &'static str,
1414    feedback: bool,
1415    note: Option<&'static str>,
1416    feeds: [&'static [Source]; ENGINE_COUNT],
1417    output: &'static [Engine],
1418}
1419
1420impl Routing {
1421    /// Returns the parameter holding which topology is selected.
1422    #[must_use]
1423    pub const fn parameter() -> ParamId {
1424        ParamId::FxRouting
1425    }
1426
1427    /// Returns every topology, in the order the `FX Routing` byte numbers them.
1428    #[must_use]
1429    pub fn all() -> &'static [Self; ROUTING_COUNT] {
1430        &ROUTINGS
1431    }
1432
1433    /// Returns the topology the `FX Routing` byte selects.
1434    ///
1435    /// `None` for a value the parameter does not accept. A lookup rather than an
1436    /// index, so a firmware that renumbers these has somewhere to say so, the way
1437    /// the value tables already do.
1438    #[must_use]
1439    pub fn for_value(value: u8) -> Option<&'static Self> {
1440        ROUTINGS.iter().find(|routing| routing.value == value)
1441    }
1442
1443    /// Returns the `FX Routing` value that selects this topology.
1444    #[must_use]
1445    pub const fn value(&self) -> u8 {
1446        self.value
1447    }
1448
1449    /// Returns the manual's label for it, `M-1` through `M-10`.
1450    #[must_use]
1451    pub const fn label(&self) -> &'static str {
1452        self.label
1453    }
1454
1455    /// Returns the name the `FX Routing` value table gives it.
1456    #[must_use]
1457    pub const fn name(&self) -> &'static str {
1458        self.name
1459    }
1460
1461    /// Returns what reaches this engine: the block's own input, or other
1462    /// engines.
1463    #[must_use]
1464    pub fn feeds(&self, engine: Engine) -> &'static [Source] {
1465        // Unreachable fallback: the table is generated `ENGINE_COUNT` long and
1466        // an engine's index is inside it by construction.
1467        self.feeds
1468            .get(usize::from(engine.index()))
1469            .copied()
1470            .unwrap_or(&[])
1471    }
1472
1473    /// Returns the engines whose outputs are summed to leave the block.
1474    ///
1475    /// What decides whether an engine's `FX n Output Gain` reaches the output:
1476    /// the manual defines a slot's level as the level of an effect configured
1477    /// in parallel, or last before the output stage.
1478    #[must_use]
1479    pub const fn output(&self) -> &'static [Engine] {
1480        self.output
1481    }
1482
1483    /// Returns whether any engine is in a loop around the main path.
1484    ///
1485    /// Two of the ten are. A host drawing one of those without knowing it draws
1486    /// a wrong picture confidently.
1487    #[must_use]
1488    pub const fn is_feedback(&self) -> bool {
1489        self.feedback
1490    }
1491
1492    /// Returns what the specification records about this topology beyond its
1493    /// graph, which is where the loop taps on the two that have one.
1494    #[must_use]
1495    pub const fn note(&self) -> Option<&'static str> {
1496        self.note
1497    }
1498}
1499
1500impl fmt::Display for Routing {
1501    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1502        write!(f, "{} ({})", self.label, self.name)
1503    }
1504}
1505
1506/// What a signal reaching an engine came from.
1507///
1508/// An enum rather than the specification's `0` for the block input, so that no
1509/// host has to remember which engine number means "not an engine".
1510#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
1511#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1512#[non_exhaustive]
1513pub enum Source {
1514    /// The FX block's own input.
1515    Input,
1516    /// The output of another engine.
1517    Engine(Engine),
1518}
1519
1520/// What one `FX Mode` setting does to the two paths through the instrument.
1521///
1522/// The analog path carries the voices straight to the output stage; the digital
1523/// path carries them through the FX block. `Bypass` is a true bypass, with the
1524/// DSP out of circuit rather than muted, which is why a host should ask this
1525/// rather than match on the value table's name.
1526///
1527/// ```
1528/// use deepmind_midi::effect::Mode;
1529///
1530/// let bypass = Mode::for_value(2).expect("three modes");
1531/// assert_eq!(bypass.name(), "Bypass");
1532/// assert!(bypass.analog_path());
1533/// assert!(!bypass.digital_path());
1534/// ```
1535#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1536#[cfg_attr(feature = "serde", derive(serde::Serialize))]
1537pub struct Mode {
1538    value: u8,
1539    name: &'static str,
1540    analog_path: bool,
1541    digital_path: bool,
1542}
1543
1544impl Mode {
1545    /// Returns the parameter holding which mode is selected.
1546    #[must_use]
1547    pub const fn parameter() -> ParamId {
1548        ParamId::FxMode
1549    }
1550
1551    /// Returns every mode, in the order the `FX Mode` byte numbers them.
1552    #[must_use]
1553    pub fn all() -> &'static [Self; MODE_COUNT] {
1554        &MODES
1555    }
1556
1557    /// Returns the mode the `FX Mode` byte selects.
1558    ///
1559    /// `None` for a value the parameter does not accept.
1560    #[must_use]
1561    pub fn for_value(value: u8) -> Option<&'static Self> {
1562        MODES.iter().find(|mode| mode.value == value)
1563    }
1564
1565    /// Returns the `FX Mode` value that selects this mode.
1566    #[must_use]
1567    pub const fn value(&self) -> u8 {
1568        self.value
1569    }
1570
1571    /// Returns the name the `FX Mode` value table gives it.
1572    #[must_use]
1573    pub const fn name(&self) -> &'static str {
1574        self.name
1575    }
1576
1577    /// Returns whether the voices reach the output stage directly.
1578    #[must_use]
1579    pub const fn analog_path(&self) -> bool {
1580        self.analog_path
1581    }
1582
1583    /// Returns whether the voices run through the FX block.
1584    #[must_use]
1585    pub const fn digital_path(&self) -> bool {
1586        self.digital_path
1587    }
1588}
1589
1590impl fmt::Display for Mode {
1591    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1592        f.write_str(self.name)
1593    }
1594}
1595
1596/// The ten fractions a delay's `Factor` slot picks from, in the order the manual
1597/// prints them.
1598///
1599/// The same ten on every `Factor` slot of both tap delays, which
1600/// `every_factor_slot_offers_the_same_ten_fractions` holds against
1601/// [`FxSlot::values`] so that this table cannot drift from the specification.
1602const FACTORS: [(f32, &str); 10] = [
1603    (0.25, "1/4"),
1604    (1.0 / 3.0, "1/3"),
1605    (0.5, "1/2"),
1606    (2.0 / 3.0, "2/3"),
1607    (0.75, "3/4"),
1608    (1.0, "1"),
1609    (4.0 / 3.0, "4/3"),
1610    (1.5, "3/2"),
1611    (2.0, "2"),
1612    (3.0, "3"),
1613];
1614
1615/// Returns what this engine is doing to a signal, where that follows from
1616/// published parameters.
1617///
1618/// [`None`] for most of the 35, and that is the answer rather than a gap. A
1619/// reverb's impulse response is its designer's and is not published; a library
1620/// that invented a plausible one would be drawing something that looks like
1621/// information and is not. The same goes for a compressor's exact knee and a
1622/// phaser's comb.
1623///
1624/// [`Some`] for the 3-Tap and 4-Tap delays. Their panels are literally a time
1625/// and a gain per tap, and the times are ratios of the master delay that the
1626/// manual prints as fractions, so the picture follows from the parameters
1627/// rather than from anybody's DSP. The horizontal is [`Scale::Normalised`](crate::generator::Scale::Normalised), from
1628/// zero to the furthest tap: the ratios between the taps are published, and the
1629/// master delay time they are ratios *of* is a byte with no published curve, so
1630/// there is no axis to label.
1631///
1632/// Read on [`DEFAULT_FIRMWARE`], as the program's own `fx1_type` and its
1633/// siblings are, so an engine running Vintage Pitch on firmware 1.0 is read as
1634/// the algorithm 1.1 numbers there.
1635///
1636/// # Why not the other four delays
1637///
1638/// The Stereo Delay and the Tel-Ray have a master time and a feedback rather
1639/// than enumerated taps, so what they make is an endless train whose count
1640/// depends on where a host decides the repeats have died away. That is the
1641/// host's decision about its own picture, not a fact this library holds. The
1642/// Decimator Delay is the same with a decimator in front of it, and Mod, Delay
1643/// and Reverb has a reverb across the end of it.
1644///
1645/// ```
1646/// use deepmind_midi::ProtocolVersion;
1647/// use deepmind_midi::effect::{self, Engine};
1648/// use deepmind_midi::program::{FxType, Program};
1649///
1650/// let mut program = Program::new(ProtocolVersion::V6);
1651/// program.set_fx1_type(FxType::ThreeTapDelay);
1652/// program.set_fx1_param2(255);    // the first tap, at full gain
1653///
1654/// // The master tap is the furthest out here, so it lands at the end.
1655/// let response = effect::response(&program, Engine::One).expect("a 3-Tap Delay");
1656/// assert!(response.at(1.0) > 0.9);
1657/// assert_eq!(response.at(0.6), 0.0);
1658///
1659/// // And a reverb has none, which is an answer rather than a failure.
1660/// program.set_fx1_type(FxType::RoomRev);
1661/// assert!(effect::response(&program, Engine::One).is_none());
1662/// ```
1663#[must_use]
1664pub fn response(program: &Program, engine: Engine) -> Option<Generator> {
1665    let algorithm =
1666        Algorithm::for_value(program.get(engine.algorithm_parameter()), DEFAULT_FIRMWARE)?;
1667
1668    // Slot numbers of the gain and the factor for each tap, in tap order. The
1669    // first tap runs at the master time and so has no factor of its own.
1670    let layout: &[(u8, Option<u8>)] = match algorithm.name {
1671        "3TapDelay" => &[(2, None), (6, Some(5)), (9, Some(8))],
1672        "4TapDelay" => &[(2, None), (6, Some(5)), (8, Some(7)), (10, Some(9))],
1673        _ => return None,
1674    };
1675
1676    let mut taps = [(0.0, 0.0); MAX_TAPS];
1677    let mut used = 0;
1678    let mut furthest = 0.0_f32;
1679    for &(gain, factor) in layout {
1680        let at = match factor {
1681            None => 1.0,
1682            Some(slot) => fraction(program, engine, slot)?,
1683        };
1684        let height = engine
1685            .slot_parameter(gain)
1686            .map_or(0.0, |parameter| f32::from(program.get(parameter)) / 255.0);
1687        *taps.get_mut(used)? = (at, height);
1688        furthest = furthest.max(at);
1689        used += 1;
1690    }
1691
1692    // Normalised to the furthest tap, since the master time the ratios are
1693    // ratios of has no published curve to put an axis in.
1694    if furthest > 0.0 {
1695        for tap in taps.iter_mut().take(used) {
1696            tap.0 /= furthest;
1697        }
1698    }
1699    Some(crate::generator::taps(taps, used))
1700}
1701
1702/// Returns the fraction of the master delay time a `Factor` slot selects.
1703///
1704/// # A reading, not a published mapping
1705///
1706/// The ten fractions are printed in the manual and are in [`FxSlot::values`].
1707/// Which byte shows which of them is not, for the reason
1708/// [`FxSlot::values`] gives, so this divides the byte's range evenly among them.
1709/// That is the only mapping a `0..=255` byte and ten named options admit, and it
1710/// is the one thing in this function that is not off the page.
1711fn fraction(program: &Program, engine: Engine, slot: u8) -> Option<f32> {
1712    let raw = program.get(engine.slot_parameter(slot)?);
1713    let index = usize::from(raw) * FACTORS.len() / 256;
1714    FACTORS.get(index).map(|&(fraction, _)| fraction)
1715}
1716
1717#[cfg(test)]
1718#[expect(
1719    clippy::expect_used,
1720    clippy::panic,
1721    reason = "a failed expectation is the test failure"
1722)]
1723mod tests {
1724    use super::{
1725        ALGORITHM_COUNT, Algorithm, Align, Engine, Family, MARK_PIXEL_SIDE, MODE_COUNT, Mode,
1726        Point, Quantity, ROUTING_COUNT, Routing, SLOTS_PER_ENGINE, Source, Stroke, VARIANT_COUNT,
1727        VARIANTS, grid,
1728    };
1729    use crate::ids::ProtocolVersion;
1730    use crate::param::{DEFAULT_FIRMWARE, Group, Kind, ParamId, TableId};
1731    use crate::program::{FxType, Program};
1732    use crate::sysex::inquiry::Version;
1733
1734    /// Firmware 1.0, which numbers the algorithms differently.
1735    const FIRMWARE_1_0: Version = Version { major: 1, minor: 0 };
1736
1737    #[test]
1738    fn an_engine_addresses_the_parameters_the_table_names() {
1739        assert_eq!(Engine::One.algorithm_parameter(), ParamId::Fx1Type);
1740        assert_eq!(Engine::One.gain_parameter(), ParamId::Fx1OutputGain);
1741        assert_eq!(Engine::One.slot_parameter(1), Some(ParamId::Fx1Param1));
1742        assert_eq!(Engine::Four.slot_parameter(12), Some(ParamId::Fx4Param12));
1743
1744        // Slots count from one, and there are twelve of them.
1745        assert_eq!(Engine::One.slot_parameter(0), None);
1746        assert_eq!(Engine::One.slot_parameter(13), None);
1747    }
1748
1749    /// Every slot parameter in the table belongs to exactly one engine, which
1750    /// is what makes the way back from a parameter unambiguous.
1751    #[test]
1752    fn every_effect_slot_parameter_belongs_to_one_engine() {
1753        let mut seen = 0;
1754        for parameter in ParamId::ALL.iter().copied() {
1755            let Some(engine) = Engine::of(parameter) else {
1756                continue;
1757            };
1758            assert_eq!(parameter.group(), Group::Effects);
1759            assert!(engine.slot_parameters().contains(&parameter));
1760            assert_eq!(
1761                Engine::ALL
1762                    .into_iter()
1763                    .filter(|other| other.slot_parameters().contains(&parameter))
1764                    .count(),
1765                1,
1766                "{parameter} is in two engines"
1767            );
1768            seen += 1;
1769        }
1770        assert_eq!(seen, Engine::ALL.len() * SLOTS_PER_ENGINE);
1771
1772        // An engine's own settings are not slots of it.
1773        assert_eq!(Engine::of(ParamId::Fx1Type), None);
1774        assert_eq!(Engine::of(ParamId::Fx1OutputGain), None);
1775        assert_eq!(Engine::of(ParamId::VcfFrequency), None);
1776    }
1777
1778    #[test]
1779    fn an_engine_number_round_trips() {
1780        for engine in Engine::ALL {
1781            assert_eq!(Engine::from_number(engine.number()), Ok(engine));
1782        }
1783        assert!(Engine::from_number(0).is_err());
1784        assert!(Engine::from_number(5).is_err());
1785    }
1786
1787    /// The point of the table: `FX 1 Param 3` is `Size` on one algorithm and
1788    /// something else on another.
1789    #[test]
1790    fn one_byte_means_different_things_under_different_algorithms() {
1791        let room = Algorithm::for_value(2, DEFAULT_FIRMWARE).expect("a Room Reverb");
1792        let phaser = Algorithm::for_value(30, DEFAULT_FIRMWARE).expect("a Phaser");
1793
1794        let third = ParamId::Fx1Param3;
1795        assert_eq!(
1796            room.slot_of(Engine::One, third).map(|slot| slot.title),
1797            Some("Size")
1798        );
1799        assert_ne!(
1800            phaser.slot_of(Engine::One, third).map(|slot| slot.title),
1801            Some("Size")
1802        );
1803    }
1804
1805    /// A short slot list is how a host learns not to draw seven controls that
1806    /// do nothing.
1807    #[test]
1808    fn an_algorithm_with_fewer_parameters_has_fewer_slots() {
1809        let deep = Algorithm::for_value(0, DEFAULT_FIRMWARE).expect("a TC Deep Reverb");
1810        assert_eq!(deep.slots.len(), 5);
1811        assert!(deep.slot(6).is_none());
1812        // The parameter still exists; the algorithm just does nothing with it.
1813        assert_eq!(Engine::One.slot_parameter(6), Some(ParamId::Fx1Param6));
1814        assert_eq!(deep.slot_of(Engine::One, ParamId::Fx1Param6), None);
1815
1816        for algorithm in Algorithm::all() {
1817            assert!(!algorithm.slots.is_empty(), "{algorithm} has no slots");
1818            assert!(algorithm.slots.len() <= SLOTS_PER_ENGINE);
1819        }
1820    }
1821
1822    /// Firmware 1.1 inserted Vintage Pitch rather than appending it, so the
1823    /// same byte is two different algorithms.
1824    #[test]
1825    fn the_firmware_decides_which_algorithm_a_byte_selects() {
1826        assert_eq!(
1827            Algorithm::for_value(33, DEFAULT_FIRMWARE).map(|a| a.name),
1828            Some("Vintage Pitch")
1829        );
1830        assert_eq!(
1831            Algorithm::for_value(33, FIRMWARE_1_0).map(|a| a.name),
1832            Some("RotarySpkr")
1833        );
1834        // The last algorithm of the newer table is past the end of the older.
1835        assert_eq!(Algorithm::for_value(34, FIRMWARE_1_0), None);
1836    }
1837
1838    #[test]
1839    fn an_algorithm_says_which_byte_selects_it() {
1840        let rotary = Algorithm::by_name("RotarySpkr").expect("the rotary speaker");
1841        assert_eq!(rotary.value_for(DEFAULT_FIRMWARE), Some(34));
1842        assert_eq!(rotary.value_for(FIRMWARE_1_0), Some(33));
1843
1844        let vintage = Algorithm::by_name("Vintage Pitch").expect("the vintage pitch shifter");
1845        assert_eq!(vintage.value_for(DEFAULT_FIRMWARE), Some(33));
1846        assert_eq!(
1847            vintage.value_for(FIRMWARE_1_0),
1848            None,
1849            "firmware 1.0 does not offer it"
1850        );
1851    }
1852
1853    /// The value table and this one are two renderings of the same 35
1854    /// algorithms, and a byte that names one has to reach the other.
1855    #[test]
1856    fn every_algorithm_the_value_table_names_has_a_panel() {
1857        for firmware in [DEFAULT_FIRMWARE, FIRMWARE_1_0] {
1858            let table = TableId::FxType.table_for(firmware);
1859            for entry in table.entries {
1860                let value = u8::try_from(entry.value).expect("35 algorithms fit in a byte");
1861                let algorithm = Algorithm::for_value(value, firmware)
1862                    .unwrap_or_else(|| panic!("{} has no panel on {firmware}", entry.name));
1863                assert_eq!(algorithm.name, entry.name);
1864                assert_eq!(algorithm.value_for(firmware), Some(value));
1865            }
1866        }
1867        assert_eq!(Algorithm::all().len(), ALGORITHM_COUNT);
1868    }
1869
1870    /// A slot either sweeps between two printed ends or shows one of a printed
1871    /// set of names. A slot that did neither would be a control with nothing to
1872    /// draw.
1873    #[test]
1874    fn a_slot_has_either_a_range_or_a_set_of_names() {
1875        for algorithm in Algorithm::all() {
1876            for slot in algorithm.slots {
1877                assert!(!slot.reference.is_empty(), "{algorithm} {}", slot.slot);
1878                assert!(!slot.title.is_empty(), "{algorithm} {}", slot.slot);
1879                assert_ne!(
1880                    slot.is_selector(),
1881                    slot.min.is_some(),
1882                    "{algorithm} {} is both a range and a set of names, or neither",
1883                    slot.slot
1884                );
1885                // The wire values of a named set are not published, so a slot
1886                // is never pointed at a value table.
1887                assert!(matches!(slot.kind, Kind::Continuous | Kind::Switch));
1888            }
1889        }
1890    }
1891
1892    /// The grid is one measurement shared by all 35, and every slot has to land
1893    /// on it: a slot off the page would be a control drawn nowhere.
1894    #[test]
1895    fn every_slot_is_placed_on_the_page() {
1896        let grid = grid();
1897        assert!(grid.columns() > 0 && grid.rows() > 0);
1898        for algorithm in Algorithm::all() {
1899            let panel = algorithm.panel();
1900            let placed: usize = panel.rows().iter().map(|row| row.slots().len()).sum();
1901            assert_eq!(placed, algorithm.slots.len(), "{algorithm}");
1902            assert!(
1903                panel.rows().len() <= usize::from(grid.rows()),
1904                "{algorithm}"
1905            );
1906
1907            for slot in algorithm.slots {
1908                let at = slot.position();
1909                assert!(at.column() < grid.columns(), "{algorithm} {}", slot.slot);
1910                assert!(at.row() < grid.rows(), "{algorithm} {}", slot.slot);
1911
1912                // The row the panel says holds it is the row the slot claims.
1913                let row = panel
1914                    .rows()
1915                    .get(usize::from(at.row()))
1916                    .expect("a slot is on a row the panel has");
1917                assert_eq!(
1918                    row.slots().get(usize::from(at.column())).copied(),
1919                    Some(slot.slot),
1920                    "{algorithm} {} is not where its row puts it",
1921                    slot.slot
1922                );
1923
1924                let (x, y) = at.centre();
1925                assert!(x > 0.0 && x < grid.display_width(), "{algorithm}");
1926                assert!(y > 0.0 && y < grid.display_height(), "{algorithm}");
1927            }
1928        }
1929    }
1930
1931    /// Every algorithm has a panel of its own, which is the point of publishing
1932    /// them: a Room Reverb and a Phaser are different objects.
1933    #[test]
1934    fn each_algorithm_carries_its_own_measured_panel() {
1935        let mut faders = 0;
1936        for algorithm in Algorithm::all() {
1937            let panel = algorithm.panel();
1938            if panel.control() == super::Control::Fader {
1939                faders += 1;
1940            }
1941            // A measurement, not a placeholder: the four are not all one colour.
1942            let colours = [panel.chassis(), panel.face(), panel.cap(), panel.accent()];
1943            assert!(
1944                colours.iter().any(|colour| *colour != colours[0]),
1945                "{algorithm} is one flat colour"
1946            );
1947            assert!(
1948                panel.rows().iter().all(|row| row.align() == Align::Left),
1949                "{algorithm} was measured as left-aligned"
1950            );
1951        }
1952        assert_eq!(faders, 5, "five panels use faders, the manual's own count");
1953
1954        let room = Algorithm::for_value(2, DEFAULT_FIRMWARE).expect("a Room Reverb");
1955        let phaser = Algorithm::for_value(30, DEFAULT_FIRMWARE).expect("a Phaser");
1956        assert_ne!(room.panel().face(), phaser.panel().face());
1957    }
1958
1959    #[cfg(feature = "alloc")]
1960    #[test]
1961    fn a_colour_prints_as_the_specification_writes_it() {
1962        let room = Algorithm::for_value(2, DEFAULT_FIRMWARE).expect("a Room Reverb");
1963        assert_eq!(alloc::format!("{}", room.panel().cap()), "#989388");
1964        assert_eq!(room.panel().cap().to_rgb(), [0x98, 0x93, 0x88]);
1965    }
1966
1967    /// Every engine is reachable from the input and reaches the output, in all
1968    /// ten topologies. A slot fed by nothing would be a misread diagram.
1969    #[test]
1970    fn every_topology_is_wired_end_to_end() {
1971        assert_eq!(Routing::all().len(), ROUTING_COUNT);
1972        for routing in Routing::all() {
1973            assert_eq!(Routing::for_value(routing.value()), Some(routing));
1974            assert!(!routing.output().is_empty(), "{routing}");
1975            for engine in Engine::ALL {
1976                let feeds = routing.feeds(engine);
1977                assert!(!feeds.is_empty(), "{routing} feeds {engine} from nothing");
1978                assert!(
1979                    !feeds.contains(&Source::Engine(engine)),
1980                    "{routing}: {engine} feeds itself"
1981                );
1982            }
1983            // The input reaches the block through at least one engine.
1984            assert!(
1985                Engine::ALL
1986                    .into_iter()
1987                    .any(|engine| routing.feeds(engine).contains(&Source::Input)),
1988                "{routing} takes no input"
1989            );
1990        }
1991        let past = u8::try_from(ROUTING_COUNT).expect("ten topologies fit in a byte");
1992        assert_eq!(Routing::for_value(past), None);
1993        assert_eq!(Routing::parameter(), ParamId::FxRouting);
1994    }
1995
1996    /// The two loops are declared rather than discovered, and the note says
1997    /// where each one taps.
1998    #[test]
1999    fn the_two_feedback_topologies_say_so() {
2000        assert!(
2001            Routing::all()
2002                .iter()
2003                .filter(|routing| routing.is_feedback())
2004                .map(Routing::label)
2005                .eq(["M-9", "M-10"]),
2006            "the feedback topologies are M-9 and M-10"
2007        );
2008        for routing in Routing::all() {
2009            assert_eq!(
2010                routing.is_feedback(),
2011                routing.note().is_some(),
2012                "{routing} has a loop and no note, or the other way round"
2013            );
2014        }
2015    }
2016
2017    /// The topology is what says whether an engine's output gain reaches the
2018    /// output at all, which is the question the value table's name cannot
2019    /// answer.
2020    #[test]
2021    fn the_topology_says_which_engines_reach_the_output() {
2022        let serial = Routing::for_value(0).expect("M-1");
2023        assert_eq!(serial.output(), &[Engine::Four]);
2024
2025        let parallel = Routing::for_value(3).expect("M-4");
2026        assert_eq!(parallel.output(), &Engine::ALL);
2027        for engine in Engine::ALL {
2028            assert_eq!(parallel.feeds(engine), &[Source::Input]);
2029        }
2030    }
2031
2032    /// A true bypass takes the DSP out of circuit; a host matching on the value
2033    /// table's name would be re-tabulating an enum it was handed.
2034    #[test]
2035    fn every_mode_leaves_a_path_to_the_output() {
2036        assert_eq!(Mode::all().len(), MODE_COUNT);
2037        for mode in Mode::all() {
2038            assert_eq!(Mode::for_value(mode.value()), Some(mode));
2039            assert!(
2040                mode.analog_path() || mode.digital_path(),
2041                "{mode} is silent"
2042            );
2043        }
2044        let bypass = Mode::for_value(2).expect("a bypass");
2045        assert_eq!(bypass.name(), "Bypass");
2046        assert!(bypass.analog_path() && !bypass.digital_path());
2047        let past = u8::try_from(MODE_COUNT).expect("three modes fit in a byte");
2048        assert_eq!(Mode::for_value(past), None);
2049        assert_eq!(Mode::parameter(), ParamId::FxMode);
2050    }
2051
2052    /// The names the two tables give have to be the same names, or a host
2053    /// drawing a list from one and a graph from the other draws two things.
2054    #[test]
2055    fn the_topologies_and_modes_match_their_value_tables() {
2056        for routing in Routing::all() {
2057            assert_eq!(
2058                ParamId::FxRouting.label(u16::from(routing.value())),
2059                Some(routing.name()),
2060            );
2061        }
2062        for mode in Mode::all() {
2063            assert_eq!(
2064                ParamId::FxMode.label(u16::from(mode.value())),
2065                Some(mode.name()),
2066            );
2067        }
2068    }
2069
2070    #[test]
2071    fn slots_are_numbered_from_one_and_in_order() {
2072        for algorithm in Algorithm::all() {
2073            for (index, slot) in algorithm.slots.iter().enumerate() {
2074                let number = u8::try_from(index + 1).expect("twelve slots fit in a byte");
2075                assert_eq!(slot.slot, number, "{algorithm}");
2076                assert_eq!(algorithm.slot(number).map(|s| s.title), Some(slot.title));
2077            }
2078        }
2079    }
2080
2081    /// Without the feature there is no prose to reach, and the accessor says so
2082    /// rather than the caller having to ask whether it was compiled in.
2083    #[cfg(not(feature = "descriptions"))]
2084    #[test]
2085    fn a_slot_describes_nothing_without_the_feature() {
2086        for algorithm in Algorithm::all() {
2087            for slot in algorithm.slots {
2088                assert_eq!(slot.description(), None, "{algorithm}");
2089            }
2090        }
2091    }
2092
2093    /// The manual describes all but a couple of the slots, and the exceptions
2094    /// are `None` rather than a sentence this project wrote for it.
2095    #[cfg(feature = "descriptions")]
2096    #[test]
2097    fn a_slot_carries_the_manuals_own_words() {
2098        let room = Algorithm::for_value(2, DEFAULT_FIRMWARE).expect("a Room Reverb");
2099        assert_eq!(
2100            room.slot(3).and_then(super::FxSlot::description),
2101            Some("Controls the perceived size of the space being created by the reverb."),
2102        );
2103
2104        let (slots, described) = Algorithm::all().iter().fold((0, 0), |(all, some), a| {
2105            (
2106                all + a.slots.len(),
2107                some + a
2108                    .slots
2109                    .iter()
2110                    .filter(|slot| slot.description().is_some())
2111                    .count(),
2112            )
2113        });
2114        assert_eq!(slots, 371);
2115        assert_eq!(described, 369);
2116    }
2117
2118    /// Exactly three slots take an effect out of circuit, and they are the only
2119    /// slot-level off the instrument has. A fourth appearing here means either
2120    /// the specification grew one or `enable` has been read too widely.
2121    #[test]
2122    fn three_slots_switch_their_effect_out_of_circuit() {
2123        const EXPECTED: [(&str, u8); 3] = [("EdisonEX1", 1), ("NoiseGate", 8), ("Chorus-D", 1)];
2124
2125        let mut found = [("", 0_u8); EXPECTED.len()];
2126        let mut count = 0_usize;
2127        for algorithm in Algorithm::all() {
2128            for slot in algorithm.slots.iter().filter(|slot| slot.is_enable()) {
2129                assert!(
2130                    count < EXPECTED.len(),
2131                    "a fourth enable: {algorithm} slot {}",
2132                    slot.slot
2133                );
2134                if let Some(entry) = found.get_mut(count) {
2135                    *entry = (algorithm.name, slot.slot);
2136                }
2137                count += 1;
2138            }
2139        }
2140        assert_eq!(count, EXPECTED.len());
2141        assert_eq!(found, EXPECTED);
2142    }
2143
2144    /// An enable is a switch, because an effect is in circuit or it is not.
2145    /// The Noise Gate is the one that reads `ON` at the bottom of its range.
2146    #[test]
2147    fn an_enable_is_a_switch_and_may_read_either_way_round() {
2148        for algorithm in Algorithm::all() {
2149            for slot in algorithm.slots.iter().filter(|slot| slot.is_enable()) {
2150                assert_eq!(slot.kind, Kind::Switch, "{algorithm} {}", slot.title);
2151            }
2152        }
2153
2154        let gate = Algorithm::by_name("NoiseGate").expect("a Noise Gate");
2155        let power = gate.slot(8).expect("a Power slot");
2156        assert_eq!((power.min, power.max), (Some("ON"), Some("OFF")));
2157    }
2158
2159    /// Every algorithm reaches a mark, its own or its family's, and the nine
2160    /// families between them account for all 35 with none left over.
2161    #[test]
2162    fn every_algorithm_has_a_family_and_a_mark() {
2163        let mut own = 0;
2164        for algorithm in Algorithm::all() {
2165            assert!(
2166                !algorithm.mark().strokes().is_empty(),
2167                "{algorithm} has an empty mark"
2168            );
2169            match algorithm.own_mark() {
2170                Some(mark) => {
2171                    own += 1;
2172                    assert_eq!(algorithm.mark(), mark, "{algorithm}");
2173                    assert_ne!(mark, algorithm.family().mark(), "{algorithm}");
2174                }
2175                None => assert_eq!(algorithm.mark(), algorithm.family().mark(), "{algorithm}"),
2176            }
2177        }
2178        // The variants are the finer marks, and they are drawn for the kinds
2179        // a symbol can carry: most of the 35, and not all of them.
2180        assert!(
2181            own > ALGORITHM_COUNT / 2,
2182            "{own} algorithms with a mark of their own"
2183        );
2184        assert!(own < ALGORITHM_COUNT, "every algorithm has its own mark");
2185        assert_eq!(VARIANTS.len(), VARIANT_COUNT);
2186
2187        let counted: usize = Family::ALL
2188            .into_iter()
2189            .map(|family| family.algorithms().count())
2190            .sum();
2191        assert_eq!(counted, ALGORITHM_COUNT);
2192    }
2193
2194    /// `Family::ALL` is hand-written and the marks beside it are generated, so
2195    /// the two agree only as long as the order does. A family reordered or
2196    /// renamed in marks.toml fails here rather than handing out the wrong mark.
2197    #[test]
2198    fn the_families_are_in_the_order_the_specification_declares() {
2199        assert_eq!(
2200            Family::ALL.map(Family::name),
2201            [
2202                "Reverb",
2203                "Delay",
2204                "Modulation",
2205                "Filter",
2206                "Dynamics",
2207                "Distortion",
2208                "Imaging",
2209                "Pitch",
2210                "Rotary",
2211            ]
2212        );
2213        for (index, family) in Family::ALL.into_iter().enumerate() {
2214            assert_eq!(family.index(), index);
2215        }
2216    }
2217
2218    /// Returns the point `u` along a wave, the way a host drawing one would.
2219    ///
2220    /// The centre line displaced perpendicular by the sine, with the
2221    /// perpendicular a quarter turn anticlockwise from the run.
2222    fn wave_at(start: Point, end: Point, amplitude: f32, cycles: f32, u: f32) -> (f32, f32) {
2223        let (dx, dy) = (end.x() - start.x(), end.y() - start.y());
2224        let length = dx.hypot(dy).max(f32::EPSILON);
2225        let (nx, ny) = (dy / length, -dx / length);
2226        let offset = amplitude * crate::math::sin_turns(u * cycles);
2227        (
2228            start.x() + dx * u + nx * offset,
2229            start.y() + dy * u + ny * offset,
2230        )
2231    }
2232
2233    /// Sine and cosine of an angle in radians, for the arc checks below.
2234    ///
2235    /// The crate's own `math` module takes turns rather than radians; these
2236    /// wrap it so the test reads the way the geometry does.
2237    fn sin(radians: f32) -> f32 {
2238        crate::math::sin_turns(radians / core::f32::consts::TAU)
2239    }
2240
2241    fn cos(radians: f32) -> f32 {
2242        crate::math::cos_turns(radians / core::f32::consts::TAU)
2243    }
2244
2245    /// A mark is drawn in a unit box, and a host that scales it by its own size
2246    /// expects nothing to land outside. The margin is what leaves room for a
2247    /// stroke width; `spec/marks.toml` states it and this holds it.
2248    #[test]
2249    fn a_mark_stays_inside_the_unit_box() {
2250        const MARGIN: f32 = 0.08;
2251        let inside = |x: f32, y: f32, family: Family| {
2252            assert!(
2253                (MARGIN..=1.0 - MARGIN).contains(&x) && (MARGIN..=1.0 - MARGIN).contains(&y),
2254                "{family} reaches ({x}, {y})"
2255            );
2256        };
2257
2258        for family in Family::ALL {
2259            for stroke in family.mark().strokes() {
2260                match *stroke {
2261                    Stroke::Line { points } => {
2262                        assert!(points.len() >= 2, "{family} has a line of one point");
2263                        for point in points {
2264                            inside(point.x(), point.y(), family);
2265                        }
2266                    }
2267                    Stroke::Arc {
2268                        centre,
2269                        radius,
2270                        start,
2271                        sweep,
2272                    } => {
2273                        assert!(radius > 0.0, "{family} has an arc of no radius");
2274                        assert!(sweep.abs() > 0.0, "{family} has an arc that sweeps nothing");
2275                        // Only the swept part, because the circle an arc is
2276                        // taken from is allowed to reach outside the box.
2277                        for turns in [start, start + sweep] {
2278                            let radians = turns * core::f32::consts::TAU;
2279                            inside(
2280                                centre.x() + radius * cos(radians),
2281                                centre.y() + radius * sin(radians),
2282                                family,
2283                            );
2284                        }
2285                    }
2286                    Stroke::Dot { centre, radius } => {
2287                        assert!(radius > 0.0, "{family} has a dot of no radius");
2288                        inside(centre.x() - radius, centre.y() - radius, family);
2289                        inside(centre.x() + radius, centre.y() + radius, family);
2290                    }
2291                    Stroke::Wave {
2292                        start,
2293                        end,
2294                        amplitude,
2295                        cycles,
2296                    } => {
2297                        assert!(amplitude > 0.0, "{family} has a wave of no amplitude");
2298                        assert!(cycles > 0.0, "{family} has a wave of no cycles");
2299                        // Sampled the way a host would, which is the only way
2300                        // to know a published curve stays in its box.
2301                        for step in 0..=64_u8 {
2302                            let u = f32::from(step) / 64.0;
2303                            let (x, y) = wave_at(start, end, amplitude, cycles, u);
2304                            inside(x, y, family);
2305                        }
2306                    }
2307                }
2308            }
2309        }
2310    }
2311
2312    /// Every family has a pixel grid, it is the declared size, and it draws
2313    /// something. A mark that lit nothing, or everything, would blit as a blank
2314    /// or a block and tell a reader nothing.
2315    #[test]
2316    fn every_mark_has_a_pixel_grid_that_draws_something() {
2317        let side = u8::try_from(MARK_PIXEL_SIDE).expect("a small grid");
2318        for family in Family::ALL {
2319            let pixels = family.mark().pixels();
2320            assert_eq!(pixels.rows().len(), MARK_PIXEL_SIDE, "{family}");
2321
2322            let mut lit = 0;
2323            for y in 0..side {
2324                for x in 0..side {
2325                    if pixels.is_lit(x, y) {
2326                        lit += 1;
2327                    }
2328                }
2329            }
2330            assert!(lit > 0, "{family} lights nothing");
2331            assert!(lit < MARK_PIXEL_SIDE * MARK_PIXEL_SIDE, "{family} is solid");
2332
2333            // Nothing outside the grid is lit, and no row carries a bit past
2334            // its own width, which is what a host blitting a row relies on.
2335            assert!(
2336                !pixels.is_lit(side, 0),
2337                "{family} lights a column past the grid"
2338            );
2339            assert_eq!(pixels.row(side), 0, "{family} has a row past the grid");
2340            for y in 0..side {
2341                assert_eq!(
2342                    pixels.row(y) >> side,
2343                    0,
2344                    "{family} row {y} carries a bit past the grid"
2345                );
2346            }
2347        }
2348    }
2349
2350    /// The grids are all different pictures, the families' and the variants'
2351    /// together. Two marks blitting the same pixels would be a symbol that
2352    /// cannot do its one job.
2353    #[test]
2354    fn no_two_marks_blit_the_same_pixels() {
2355        let marks = || {
2356            Family::ALL
2357                .iter()
2358                .map(|family| family.mark())
2359                .chain(VARIANTS.iter())
2360        };
2361        for (index, mark) in marks().enumerate() {
2362            for other in marks().skip(index + 1) {
2363                assert_ne!(
2364                    mark.pixels().rows(),
2365                    other.pixels().rows(),
2366                    "mark {index} draws the same grid as another"
2367                );
2368            }
2369        }
2370    }
2371
2372    /// The four buckets the manual prints are not the nine a symbol needs, and    /// The four buckets the manual prints are not the nine a symbol needs, and
2373    /// `Creative` is where that shows: it holds three families at once.
2374    #[test]
2375    fn a_family_is_finer_than_the_manuals_category() {
2376        let creative = |family: Family| {
2377            Algorithm::all()
2378                .iter()
2379                .any(|algorithm| algorithm.category == "Creative" && algorithm.family() == family)
2380        };
2381        assert!(creative(Family::Modulation));
2382        assert!(creative(Family::Filter));
2383        assert!(creative(Family::Pitch));
2384        assert!(creative(Family::Rotary));
2385    }
2386
2387    /// Every slot answers what it does to a signal, and the answer is not just
2388    /// a rewording of what control to draw. A `Factor` is the case that proves
2389    /// it: drawn as a selector, and a time.
2390    #[test]
2391    fn a_quantity_is_a_different_question_from_a_control_kind() {
2392        let mut counts = [0_usize; Quantity::ALL.len()];
2393        for algorithm in Algorithm::all() {
2394            for slot in algorithm.slots {
2395                let count = counts
2396                    .get_mut(index_of(slot.quantity()))
2397                    .expect("a quantity is in Quantity::ALL");
2398                *count += 1;
2399            }
2400        }
2401        // Every one of the nine is used, or it should not be in the enum.
2402        for (quantity, count) in Quantity::ALL.into_iter().zip(counts) {
2403            assert!(count > 0, "{quantity:?} is in the enum and on no slot");
2404        }
2405        assert_eq!(counts.iter().sum::<usize>(), 371);
2406
2407        let delay = Algorithm::by_name("3TapDelay").expect("a 3-Tap Delay");
2408        let factor = delay.slot(5).expect("a FactorA slot");
2409        assert!(factor.is_selector());
2410        assert_eq!(factor.quantity(), Quantity::Time);
2411
2412        // And a switch is a switch both ways round, which is the easy case.
2413        let gate = Algorithm::by_name("NoiseGate").expect("a Noise Gate");
2414        let power = gate.slot(8).expect("a Power slot");
2415        assert_eq!(power.kind, Kind::Switch);
2416        assert_eq!(power.quantity(), Quantity::Switch);
2417    }
2418
2419    /// Returns a quantity's position in `Quantity::ALL`.
2420    fn index_of(quantity: Quantity) -> usize {
2421        Quantity::ALL
2422            .into_iter()
2423            .position(|other| other == quantity)
2424            .unwrap_or(0)
2425    }
2426
2427    /// A unit decides a quantity wherever the manual gives one, so every slot
2428    /// measured in the same unit answers the same way. A disagreement here is a
2429    /// hand edit that got out of step with the rest of the column.
2430    #[test]
2431    fn a_unit_decides_the_quantity_wherever_there_is_one() {
2432        for algorithm in Algorithm::all() {
2433            for slot in algorithm.slots {
2434                let expected = match slot.unit {
2435                    Some("ms" | "s") => Some(Quantity::Time),
2436                    Some("Hz") => Some(Quantity::Frequency),
2437                    Some("deg") => Some(Quantity::Position),
2438                    _ => None,
2439                };
2440                if let Some(expected) = expected {
2441                    assert_eq!(
2442                        slot.quantity(),
2443                        expected,
2444                        "{algorithm} {} is in {:?}",
2445                        slot.title,
2446                        slot.unit
2447                    );
2448                }
2449            }
2450        }
2451    }
2452
2453    /// The fractions `response` places taps with are the ones the manual prints,
2454    /// held against the slot's own values so the table cannot drift from the
2455    /// specification it was copied out of.
2456    #[test]
2457    fn every_factor_slot_offers_the_same_ten_fractions() {
2458        let printed = super::FACTORS.map(|(_, name)| name);
2459        let mut found = 0;
2460        for algorithm in Algorithm::all() {
2461            for slot in algorithm.slots {
2462                if !slot.title.contains("Factor") {
2463                    continue;
2464                }
2465                assert_eq!(
2466                    slot.values,
2467                    printed.as_slice(),
2468                    "{algorithm} {}",
2469                    slot.title
2470                );
2471                assert_eq!(slot.quantity(), Quantity::Time);
2472                found += 1;
2473            }
2474        }
2475        // Every algorithm that divides a master delay time offers the same ten,
2476        // which is what makes one table right for all of them.
2477        assert_eq!(found, 10);
2478    }
2479
2480    /// The two tap delays have a response and the other 33 do not, which is the
2481    /// answer rather than a gap.
2482    #[test]
2483    fn only_the_tap_delays_have_a_published_response() {
2484        let mut program = Program::new(ProtocolVersion::V6);
2485        for algorithm in Algorithm::all() {
2486            let Some(value) = algorithm.value_for(DEFAULT_FIRMWARE) else {
2487                continue;
2488            };
2489            program.set_clamped(Engine::One.algorithm_parameter(), value);
2490            let response = super::response(&program, Engine::One);
2491            let expected = matches!(algorithm.name, "3TapDelay" | "4TapDelay");
2492            assert_eq!(response.is_some(), expected, "{algorithm}");
2493        }
2494    }
2495
2496    /// A tap lands where its factor puts it, against the master tap, and stands
2497    /// as tall as its gain byte. That is the whole of what a tap delay's
2498    /// picture is, and all of it comes off the manual's page bar the byte that
2499    /// picks the fraction.
2500    #[test]
2501    fn a_tap_lands_where_its_factor_and_gain_put_it() {
2502        let mut program = Program::new(ProtocolVersion::V6);
2503        program.set_fx1_type(FxType::FourTapDelay);
2504        // Every gain up, so each tap is there to be found.
2505        for slot in [2, 6, 8, 10] {
2506            program.set_clamped(Engine::One.slot_parameter(slot).expect("a gain slot"), 255);
2507        }
2508        // The last of the ten fractions is 3, the largest, so the fourth tap is
2509        // the furthest out and the picture is normalised to it.
2510        program.set_clamped(Engine::One.slot_parameter(9).expect("FactorC"), 255);
2511        // And the first two at 1/4, the smallest.
2512        for slot in [5, 7] {
2513            program.set_clamped(Engine::One.slot_parameter(slot).expect("a factor"), 0);
2514        }
2515
2516        let response = super::response(&program, Engine::One).expect("a 4-Tap Delay");
2517        // Taps at 1, 1/4, 1/4 and 3 master times, over a furthest of 3.
2518        assert!(
2519            response.at(1.0) > 0.9,
2520            "the furthest tap: {}",
2521            response.at(1.0)
2522        );
2523        assert!(response.at(1.0 / 3.0) > 0.9, "the master tap");
2524        assert!(response.at(0.25 / 3.0) > 0.9, "the two quarter taps");
2525        // And nothing between them.
2526        assert!(response.at(0.6) <= 0.0, "{}", response.at(0.6));
2527
2528        // A tap with its gain at nothing is drawn at nothing.
2529        program.set_clamped(Engine::One.slot_parameter(2).expect("the master gain"), 0);
2530        let quiet = super::response(&program, Engine::One).expect("a 4-Tap Delay");
2531        assert!(quiet.at(1.0 / 3.0) <= 0.0, "{}", quiet.at(1.0 / 3.0));
2532    }
2533
2534    /// The `FX Type` table is 35 effects and nothing else, on both firmwares.
2535    /// This is the absence issue #30 asked to have stated somewhere a test can
2536    /// keep true: a value that stops naming an effect fails here.
2537    #[test]
2538    fn every_fx_type_value_is_an_effect() {
2539        for firmware in [FIRMWARE_1_0, DEFAULT_FIRMWARE] {
2540            let table = TableId::FxType.table_for(firmware);
2541            for (value, entry) in table.entries.iter().enumerate() {
2542                assert!(
2543                    Algorithm::by_name(entry.name).is_some(),
2544                    "{:?} names no algorithm",
2545                    entry.name
2546                );
2547                // Consecutive from zero, so there is no spare value sitting
2548                // beside the effects for an off to have been given.
2549                assert_eq!(u16::try_from(value), Ok(entry.value));
2550            }
2551        }
2552
2553        // Firmware 1.1 offers every algorithm; 1.0 is the same table without
2554        // the Vintage Pitch it had not gained yet.
2555        let newest = TableId::FxType.table_for(DEFAULT_FIRMWARE);
2556        assert_eq!(newest.entries.len(), ALGORITHM_COUNT);
2557        assert_eq!(
2558            TableId::FxType.table_for(FIRMWARE_1_0).entries.len(),
2559            ALGORITHM_COUNT - 1
2560        );
2561    }
2562}