mod generated;
pub use generated::{
ALGORITHM_COUNT, CHARACTER_COUNT, Character, ENGINE_COUNT, FAMILY_COUNT, MARK_PIXEL_SIDE,
MODE_COUNT, ROUTING_COUNT, SLOTS_PER_ENGINE, VARIANT_COUNT,
};
pub use crate::pixels::Pixels;
use crate::pixels::Glyph;
use generated::{
ALGORITHMS, ENGINES, FAMILY_NAMES, GRID, MARKS, MODES, PANELS, ROUTINGS, VARIANTS,
};
use core::fmt;
use crate::error::{Error, Result};
use crate::generator::{Generator, MAX_TAPS};
use crate::param::{DEFAULT_FIRMWARE, Kind, ParamId, TableId};
use crate::program::Program;
use crate::sysex::inquiry::Version;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub enum Engine {
One,
Two,
Three,
Four,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) struct EngineParameters {
pub(crate) algorithm: ParamId,
pub(crate) gain: ParamId,
pub(crate) slots: [ParamId; SLOTS_PER_ENGINE],
}
impl Engine {
pub const ALL: [Self; ENGINE_COUNT] = [Self::One, Self::Two, Self::Three, Self::Four];
#[must_use]
pub const fn index(self) -> u8 {
match self {
Self::One => 0,
Self::Two => 1,
Self::Three => 2,
Self::Four => 3,
}
}
#[must_use]
pub const fn number(self) -> u8 {
self.index() + 1
}
pub const fn from_number(number: u8) -> Result<Self> {
Ok(match number {
1 => Self::One,
2 => Self::Two,
3 => Self::Three,
4 => Self::Four,
_ => return Err(Error::EngineOutOfRange(number)),
})
}
#[must_use]
pub fn algorithm_parameter(self) -> ParamId {
self.table().algorithm
}
#[must_use]
pub fn gain_parameter(self) -> ParamId {
self.table().gain
}
#[must_use]
pub fn slot_parameter(self, slot: u8) -> Option<ParamId> {
let index = usize::from(slot.checked_sub(1)?);
self.table().slots.get(index).copied()
}
#[must_use]
pub fn slot_parameters(self) -> &'static [ParamId; SLOTS_PER_ENGINE] {
&self.table().slots
}
#[must_use]
pub fn of(parameter: ParamId) -> Option<Self> {
Self::ALL
.into_iter()
.find(|engine| engine.table().slots.contains(¶meter))
}
fn table(self) -> &'static EngineParameters {
ENGINES
.get(usize::from(self.index()))
.unwrap_or(&ENGINES[0])
}
}
impl fmt::Display for Engine {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "FX {}", self.number())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct Algorithm {
#[cfg_attr(feature = "serde", serde(skip))]
pub(crate) index: u8,
pub name: &'static str,
pub full_name: &'static str,
pub category: &'static str,
#[cfg_attr(feature = "serde", serde(skip))]
pub(crate) family: Family,
#[cfg_attr(feature = "serde", serde(skip))]
pub(crate) variant: Option<u8>,
pub slots: &'static [FxSlot],
#[cfg_attr(feature = "serde", serde(skip))]
pub(crate) characters: &'static [Character],
}
impl Algorithm {
#[must_use]
pub fn all() -> &'static [Self; ALGORITHM_COUNT] {
&ALGORITHMS
}
#[must_use]
pub fn for_value(value: u8, firmware: Version) -> Option<&'static Self> {
let name = TableId::FxType
.table_for(firmware)
.name_of(u16::from(value))?;
Self::by_name(name)
}
#[must_use]
pub fn by_name(name: &str) -> Option<&'static Self> {
ALGORITHMS.iter().find(|algorithm| algorithm.name == name)
}
#[must_use]
pub fn value_for(&self, firmware: Version) -> Option<u8> {
TableId::FxType
.table_for(firmware)
.entries
.iter()
.find(|entry| entry.name == self.name)
.and_then(|entry| u8::try_from(entry.value).ok())
}
#[must_use]
pub fn slot(&self, slot: u8) -> Option<&'static FxSlot> {
let index = usize::from(slot.checked_sub(1)?);
self.slots.get(index)
}
#[must_use]
pub fn panel(&self) -> &'static Panel {
PANELS.get(usize::from(self.index)).unwrap_or(&PANELS[0])
}
#[must_use]
pub const fn family(&self) -> Family {
self.family
}
#[must_use]
pub const fn characters(&self) -> &'static [Character] {
self.characters
}
#[must_use]
pub fn has(&self, character: Character) -> bool {
self.characters.contains(&character)
}
#[must_use]
pub fn mark(&self) -> &'static Mark {
self.own_mark().unwrap_or_else(|| self.family.mark())
}
#[must_use]
pub fn own_mark(&self) -> Option<&'static Mark> {
VARIANTS.get(usize::from(self.variant?))
}
#[must_use]
pub fn slot_of(&self, engine: Engine, parameter: ParamId) -> Option<&'static FxSlot> {
let index = engine
.slot_parameters()
.iter()
.position(|slot| *slot == parameter)?;
self.slots.get(index)
}
}
impl fmt::Display for Algorithm {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.full_name)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub struct FxSlot {
pub slot: u8,
pub reference: &'static str,
pub title: &'static str,
pub kind: Kind,
pub values: &'static [&'static str],
pub unit: Option<&'static str>,
pub min: Option<&'static str>,
pub max: Option<&'static str>,
pub group: Option<&'static str>,
pub modulatable: bool,
#[cfg_attr(feature = "serde", serde(skip))]
pub(crate) enable: bool,
#[cfg_attr(feature = "serde", serde(skip))]
pub(crate) quantity: Quantity,
#[cfg_attr(feature = "serde", serde(skip))]
pub(crate) glyph: Glyph,
#[cfg_attr(feature = "serde", serde(skip))]
pub(crate) column: u8,
#[cfg_attr(feature = "serde", serde(skip))]
pub(crate) row: u8,
#[cfg(feature = "descriptions")]
#[cfg_attr(feature = "serde", serde(skip))]
pub(crate) description: Option<&'static str>,
}
impl FxSlot {
#[must_use]
pub const fn position(&self) -> Position {
Position {
column: self.column,
row: self.row,
}
}
#[must_use]
pub const fn is_selector(&self) -> bool {
!self.values.is_empty()
}
#[must_use]
pub const fn quantity(&self) -> Quantity {
self.quantity
}
#[must_use]
pub const fn glyph(&self) -> Glyph {
self.glyph
}
#[must_use]
pub const fn is_enable(&self) -> bool {
self.enable
}
#[must_use]
pub const fn description(&self) -> Option<&'static str> {
#[cfg(feature = "descriptions")]
{
self.description
}
#[cfg(not(feature = "descriptions"))]
{
None
}
}
}
impl fmt::Display for FxSlot {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.title)
}
}
#[must_use]
pub const fn grid() -> &'static Grid {
&GRID
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Grid {
columns: u8,
rows: u8,
display_width: f32,
display_height: f32,
first_x: f32,
first_y: f32,
column_pitch: f32,
row_pitch: f32,
control_diameter: f32,
}
impl Grid {
#[must_use]
pub const fn columns(&self) -> u8 {
self.columns
}
#[must_use]
pub const fn rows(&self) -> u8 {
self.rows
}
#[must_use]
pub const fn display_width(&self) -> f32 {
self.display_width
}
#[must_use]
pub const fn display_height(&self) -> f32 {
self.display_height
}
#[must_use]
pub const fn column_pitch(&self) -> f32 {
self.column_pitch
}
#[must_use]
pub const fn row_pitch(&self) -> f32 {
self.row_pitch
}
#[must_use]
pub const fn control_diameter(&self) -> f32 {
self.control_diameter
}
#[must_use]
pub fn centre(&self, column: u8, row: u8) -> (f32, f32) {
(
self.first_x + f32::from(column) * self.column_pitch,
self.first_y + f32::from(row) * self.row_pitch,
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Position {
column: u8,
row: u8,
}
impl Position {
#[must_use]
pub const fn column(&self) -> u8 {
self.column
}
#[must_use]
pub const fn row(&self) -> u8 {
self.row
}
#[must_use]
pub fn centre(&self) -> (f32, f32) {
GRID.centre(self.column, self.row)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum Family {
Reverb,
Delay,
Modulation,
Filter,
Dynamics,
Distortion,
Imaging,
Pitch,
Rotary,
}
impl Family {
pub const ALL: [Self; FAMILY_COUNT] = [
Self::Reverb,
Self::Delay,
Self::Modulation,
Self::Filter,
Self::Dynamics,
Self::Distortion,
Self::Imaging,
Self::Pitch,
Self::Rotary,
];
#[must_use]
pub const fn index(self) -> usize {
match self {
Self::Reverb => 0,
Self::Delay => 1,
Self::Modulation => 2,
Self::Filter => 3,
Self::Dynamics => 4,
Self::Distortion => 5,
Self::Imaging => 6,
Self::Pitch => 7,
Self::Rotary => 8,
}
}
#[must_use]
pub fn name(self) -> &'static str {
FAMILY_NAMES.get(self.index()).copied().unwrap_or("Reverb")
}
#[must_use]
pub fn mark(self) -> &'static Mark {
MARKS.get(self.index()).unwrap_or(&MARKS[0])
}
pub fn algorithms(self) -> impl Iterator<Item = &'static Algorithm> {
ALGORITHMS
.iter()
.filter(move |algorithm| algorithm.family == self)
}
}
impl fmt::Display for Family {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
impl Character {
pub fn algorithms(self) -> impl Iterator<Item = &'static Algorithm> {
ALGORITHMS
.iter()
.filter(move |algorithm| algorithm.characters.contains(&self))
}
}
impl fmt::Display for Character {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name())
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Mark {
strokes: &'static [Stroke],
pixels: Pixels,
}
impl Mark {
#[must_use]
pub const fn strokes(&self) -> &'static [Stroke] {
self.strokes
}
#[must_use]
pub const fn pixels(&self) -> &Pixels {
&self.pixels
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
#[non_exhaustive]
pub enum Stroke {
Line {
points: &'static [Point],
},
Arc {
centre: Point,
radius: f32,
start: f32,
sweep: f32,
},
Dot {
centre: Point,
radius: f32,
},
Wave {
start: Point,
end: Point,
amplitude: f32,
cycles: f32,
},
}
#[derive(Debug, Clone, Copy, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Point {
x: f32,
y: f32,
}
impl Point {
#[must_use]
pub const fn new(x: f32, y: f32) -> Self {
Self { x, y }
}
#[must_use]
pub const fn x(self) -> f32 {
self.x
}
#[must_use]
pub const fn y(self) -> f32 {
self.y
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Panel {
control: Control,
chassis: Colour,
face: Colour,
cap: Colour,
accent: Colour,
rows: &'static [Row],
}
impl Panel {
#[must_use]
pub const fn control(&self) -> Control {
self.control
}
#[must_use]
pub const fn chassis(&self) -> Colour {
self.chassis
}
#[must_use]
pub const fn face(&self) -> Colour {
self.face
}
#[must_use]
pub const fn cap(&self) -> Colour {
self.cap
}
#[must_use]
pub const fn accent(&self) -> Colour {
self.accent
}
#[must_use]
pub const fn rows(&self) -> &'static [Row] {
self.rows
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Row {
slots: &'static [u8],
align: Align,
}
impl Row {
#[must_use]
pub const fn slots(&self) -> &'static [u8] {
self.slots
}
#[must_use]
pub const fn align(&self) -> Align {
self.align
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum Control {
Knob,
Fader,
Display,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum Quantity {
Time,
Frequency,
Gain,
Feedback,
Depth,
Position,
Shape,
Switch,
Selection,
}
impl Quantity {
pub const ALL: [Self; 9] = [
Self::Time,
Self::Frequency,
Self::Gain,
Self::Feedback,
Self::Depth,
Self::Position,
Self::Shape,
Self::Switch,
Self::Selection,
];
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum Align {
#[default]
Left,
Right,
Centre,
Spread,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Colour {
red: u8,
green: u8,
blue: u8,
}
impl Colour {
#[must_use]
pub const fn new(red: u8, green: u8, blue: u8) -> Self {
Self { red, green, blue }
}
#[must_use]
pub const fn red(self) -> u8 {
self.red
}
#[must_use]
pub const fn green(self) -> u8 {
self.green
}
#[must_use]
pub const fn blue(self) -> u8 {
self.blue
}
#[must_use]
pub const fn to_rgb(self) -> [u8; 3] {
[self.red, self.green, self.blue]
}
}
impl fmt::Display for Colour {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "#{:02x}{:02x}{:02x}", self.red, self.green, self.blue)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Routing {
value: u8,
label: &'static str,
name: &'static str,
feedback: bool,
note: Option<&'static str>,
feeds: [&'static [Source]; ENGINE_COUNT],
output: &'static [Engine],
}
impl Routing {
#[must_use]
pub const fn parameter() -> ParamId {
ParamId::FxRouting
}
#[must_use]
pub fn all() -> &'static [Self; ROUTING_COUNT] {
&ROUTINGS
}
#[must_use]
pub fn for_value(value: u8) -> Option<&'static Self> {
ROUTINGS.iter().find(|routing| routing.value == value)
}
#[must_use]
pub const fn value(&self) -> u8 {
self.value
}
#[must_use]
pub const fn label(&self) -> &'static str {
self.label
}
#[must_use]
pub const fn name(&self) -> &'static str {
self.name
}
#[must_use]
pub fn feeds(&self, engine: Engine) -> &'static [Source] {
self.feeds
.get(usize::from(engine.index()))
.copied()
.unwrap_or(&[])
}
#[must_use]
pub const fn output(&self) -> &'static [Engine] {
self.output
}
#[must_use]
pub const fn is_feedback(&self) -> bool {
self.feedback
}
#[must_use]
pub const fn note(&self) -> Option<&'static str> {
self.note
}
}
impl fmt::Display for Routing {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} ({})", self.label, self.name)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum Source {
Input,
Engine(Engine),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Mode {
value: u8,
name: &'static str,
analog_path: bool,
digital_path: bool,
}
impl Mode {
#[must_use]
pub const fn parameter() -> ParamId {
ParamId::FxMode
}
#[must_use]
pub fn all() -> &'static [Self; MODE_COUNT] {
&MODES
}
#[must_use]
pub fn for_value(value: u8) -> Option<&'static Self> {
MODES.iter().find(|mode| mode.value == value)
}
#[must_use]
pub const fn value(&self) -> u8 {
self.value
}
#[must_use]
pub const fn name(&self) -> &'static str {
self.name
}
#[must_use]
pub const fn analog_path(&self) -> bool {
self.analog_path
}
#[must_use]
pub const fn digital_path(&self) -> bool {
self.digital_path
}
}
impl fmt::Display for Mode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.name)
}
}
const FACTORS: [(f32, &str); 10] = [
(0.25, "1/4"),
(1.0 / 3.0, "1/3"),
(0.5, "1/2"),
(2.0 / 3.0, "2/3"),
(0.75, "3/4"),
(1.0, "1"),
(4.0 / 3.0, "4/3"),
(1.5, "3/2"),
(2.0, "2"),
(3.0, "3"),
];
#[must_use]
pub fn response(program: &Program, engine: Engine) -> Option<Generator> {
let algorithm =
Algorithm::for_value(program.get(engine.algorithm_parameter()), DEFAULT_FIRMWARE)?;
let layout: &[(u8, Option<u8>)] = match algorithm.name {
"3TapDelay" => &[(2, None), (6, Some(5)), (9, Some(8))],
"4TapDelay" => &[(2, None), (6, Some(5)), (8, Some(7)), (10, Some(9))],
_ => return None,
};
let mut taps = [(0.0, 0.0); MAX_TAPS];
let mut used = 0;
let mut furthest = 0.0_f32;
for &(gain, factor) in layout {
let at = match factor {
None => 1.0,
Some(slot) => fraction(program, engine, slot)?,
};
let height = engine
.slot_parameter(gain)
.map_or(0.0, |parameter| f32::from(program.get(parameter)) / 255.0);
*taps.get_mut(used)? = (at, height);
furthest = furthest.max(at);
used += 1;
}
if furthest > 0.0 {
for tap in taps.iter_mut().take(used) {
tap.0 /= furthest;
}
}
Some(crate::generator::taps(taps, used))
}
fn fraction(program: &Program, engine: Engine, slot: u8) -> Option<f32> {
let raw = program.get(engine.slot_parameter(slot)?);
let index = usize::from(raw) * FACTORS.len() / 256;
FACTORS.get(index).map(|&(fraction, _)| fraction)
}
#[cfg(test)]
#[expect(
clippy::expect_used,
clippy::panic,
reason = "a failed expectation is the test failure"
)]
mod tests {
use super::{
ALGORITHM_COUNT, Algorithm, Align, Engine, Family, MARK_PIXEL_SIDE, MODE_COUNT, Mode,
Point, Quantity, ROUTING_COUNT, Routing, SLOTS_PER_ENGINE, Source, Stroke, VARIANT_COUNT,
VARIANTS, grid,
};
use crate::ids::ProtocolVersion;
use crate::param::{DEFAULT_FIRMWARE, Group, Kind, ParamId, TableId};
use crate::program::{FxType, Program};
use crate::sysex::inquiry::Version;
const FIRMWARE_1_0: Version = Version { major: 1, minor: 0 };
#[test]
fn an_engine_addresses_the_parameters_the_table_names() {
assert_eq!(Engine::One.algorithm_parameter(), ParamId::Fx1Type);
assert_eq!(Engine::One.gain_parameter(), ParamId::Fx1OutputGain);
assert_eq!(Engine::One.slot_parameter(1), Some(ParamId::Fx1Param1));
assert_eq!(Engine::Four.slot_parameter(12), Some(ParamId::Fx4Param12));
assert_eq!(Engine::One.slot_parameter(0), None);
assert_eq!(Engine::One.slot_parameter(13), None);
}
#[test]
fn every_effect_slot_parameter_belongs_to_one_engine() {
let mut seen = 0;
for parameter in ParamId::ALL.iter().copied() {
let Some(engine) = Engine::of(parameter) else {
continue;
};
assert_eq!(parameter.group(), Group::Effects);
assert!(engine.slot_parameters().contains(¶meter));
assert_eq!(
Engine::ALL
.into_iter()
.filter(|other| other.slot_parameters().contains(¶meter))
.count(),
1,
"{parameter} is in two engines"
);
seen += 1;
}
assert_eq!(seen, Engine::ALL.len() * SLOTS_PER_ENGINE);
assert_eq!(Engine::of(ParamId::Fx1Type), None);
assert_eq!(Engine::of(ParamId::Fx1OutputGain), None);
assert_eq!(Engine::of(ParamId::VcfFrequency), None);
}
#[test]
fn an_engine_number_round_trips() {
for engine in Engine::ALL {
assert_eq!(Engine::from_number(engine.number()), Ok(engine));
}
assert!(Engine::from_number(0).is_err());
assert!(Engine::from_number(5).is_err());
}
#[test]
fn one_byte_means_different_things_under_different_algorithms() {
let room = Algorithm::for_value(2, DEFAULT_FIRMWARE).expect("a Room Reverb");
let phaser = Algorithm::for_value(30, DEFAULT_FIRMWARE).expect("a Phaser");
let third = ParamId::Fx1Param3;
assert_eq!(
room.slot_of(Engine::One, third).map(|slot| slot.title),
Some("Size")
);
assert_ne!(
phaser.slot_of(Engine::One, third).map(|slot| slot.title),
Some("Size")
);
}
#[test]
fn an_algorithm_with_fewer_parameters_has_fewer_slots() {
let deep = Algorithm::for_value(0, DEFAULT_FIRMWARE).expect("a TC Deep Reverb");
assert_eq!(deep.slots.len(), 5);
assert!(deep.slot(6).is_none());
assert_eq!(Engine::One.slot_parameter(6), Some(ParamId::Fx1Param6));
assert_eq!(deep.slot_of(Engine::One, ParamId::Fx1Param6), None);
for algorithm in Algorithm::all() {
assert!(!algorithm.slots.is_empty(), "{algorithm} has no slots");
assert!(algorithm.slots.len() <= SLOTS_PER_ENGINE);
}
}
#[test]
fn the_firmware_decides_which_algorithm_a_byte_selects() {
assert_eq!(
Algorithm::for_value(33, DEFAULT_FIRMWARE).map(|a| a.name),
Some("Vintage Pitch")
);
assert_eq!(
Algorithm::for_value(33, FIRMWARE_1_0).map(|a| a.name),
Some("RotarySpkr")
);
assert_eq!(Algorithm::for_value(34, FIRMWARE_1_0), None);
}
#[test]
fn an_algorithm_says_which_byte_selects_it() {
let rotary = Algorithm::by_name("RotarySpkr").expect("the rotary speaker");
assert_eq!(rotary.value_for(DEFAULT_FIRMWARE), Some(34));
assert_eq!(rotary.value_for(FIRMWARE_1_0), Some(33));
let vintage = Algorithm::by_name("Vintage Pitch").expect("the vintage pitch shifter");
assert_eq!(vintage.value_for(DEFAULT_FIRMWARE), Some(33));
assert_eq!(
vintage.value_for(FIRMWARE_1_0),
None,
"firmware 1.0 does not offer it"
);
}
#[test]
fn every_algorithm_the_value_table_names_has_a_panel() {
for firmware in [DEFAULT_FIRMWARE, FIRMWARE_1_0] {
let table = TableId::FxType.table_for(firmware);
for entry in table.entries {
let value = u8::try_from(entry.value).expect("35 algorithms fit in a byte");
let algorithm = Algorithm::for_value(value, firmware)
.unwrap_or_else(|| panic!("{} has no panel on {firmware}", entry.name));
assert_eq!(algorithm.name, entry.name);
assert_eq!(algorithm.value_for(firmware), Some(value));
}
}
assert_eq!(Algorithm::all().len(), ALGORITHM_COUNT);
}
#[test]
fn a_slot_has_either_a_range_or_a_set_of_names() {
for algorithm in Algorithm::all() {
for slot in algorithm.slots {
assert!(!slot.reference.is_empty(), "{algorithm} {}", slot.slot);
assert!(!slot.title.is_empty(), "{algorithm} {}", slot.slot);
assert_ne!(
slot.is_selector(),
slot.min.is_some(),
"{algorithm} {} is both a range and a set of names, or neither",
slot.slot
);
assert!(matches!(slot.kind, Kind::Continuous | Kind::Switch));
}
}
}
#[test]
fn every_slot_is_placed_on_the_page() {
let grid = grid();
assert!(grid.columns() > 0 && grid.rows() > 0);
for algorithm in Algorithm::all() {
let panel = algorithm.panel();
let placed: usize = panel.rows().iter().map(|row| row.slots().len()).sum();
assert_eq!(placed, algorithm.slots.len(), "{algorithm}");
assert!(
panel.rows().len() <= usize::from(grid.rows()),
"{algorithm}"
);
for slot in algorithm.slots {
let at = slot.position();
assert!(at.column() < grid.columns(), "{algorithm} {}", slot.slot);
assert!(at.row() < grid.rows(), "{algorithm} {}", slot.slot);
let row = panel
.rows()
.get(usize::from(at.row()))
.expect("a slot is on a row the panel has");
assert_eq!(
row.slots().get(usize::from(at.column())).copied(),
Some(slot.slot),
"{algorithm} {} is not where its row puts it",
slot.slot
);
let (x, y) = at.centre();
assert!(x > 0.0 && x < grid.display_width(), "{algorithm}");
assert!(y > 0.0 && y < grid.display_height(), "{algorithm}");
}
}
}
#[test]
fn each_algorithm_carries_its_own_measured_panel() {
let mut faders = 0;
for algorithm in Algorithm::all() {
let panel = algorithm.panel();
if panel.control() == super::Control::Fader {
faders += 1;
}
let colours = [panel.chassis(), panel.face(), panel.cap(), panel.accent()];
assert!(
colours.iter().any(|colour| *colour != colours[0]),
"{algorithm} is one flat colour"
);
assert!(
panel.rows().iter().all(|row| row.align() == Align::Left),
"{algorithm} was measured as left-aligned"
);
}
assert_eq!(faders, 5, "five panels use faders, the manual's own count");
let room = Algorithm::for_value(2, DEFAULT_FIRMWARE).expect("a Room Reverb");
let phaser = Algorithm::for_value(30, DEFAULT_FIRMWARE).expect("a Phaser");
assert_ne!(room.panel().face(), phaser.panel().face());
}
#[cfg(feature = "alloc")]
#[test]
fn a_colour_prints_as_the_specification_writes_it() {
let room = Algorithm::for_value(2, DEFAULT_FIRMWARE).expect("a Room Reverb");
assert_eq!(alloc::format!("{}", room.panel().cap()), "#989388");
assert_eq!(room.panel().cap().to_rgb(), [0x98, 0x93, 0x88]);
}
#[test]
fn every_topology_is_wired_end_to_end() {
assert_eq!(Routing::all().len(), ROUTING_COUNT);
for routing in Routing::all() {
assert_eq!(Routing::for_value(routing.value()), Some(routing));
assert!(!routing.output().is_empty(), "{routing}");
for engine in Engine::ALL {
let feeds = routing.feeds(engine);
assert!(!feeds.is_empty(), "{routing} feeds {engine} from nothing");
assert!(
!feeds.contains(&Source::Engine(engine)),
"{routing}: {engine} feeds itself"
);
}
assert!(
Engine::ALL
.into_iter()
.any(|engine| routing.feeds(engine).contains(&Source::Input)),
"{routing} takes no input"
);
}
let past = u8::try_from(ROUTING_COUNT).expect("ten topologies fit in a byte");
assert_eq!(Routing::for_value(past), None);
assert_eq!(Routing::parameter(), ParamId::FxRouting);
}
#[test]
fn the_two_feedback_topologies_say_so() {
assert!(
Routing::all()
.iter()
.filter(|routing| routing.is_feedback())
.map(Routing::label)
.eq(["M-9", "M-10"]),
"the feedback topologies are M-9 and M-10"
);
for routing in Routing::all() {
assert_eq!(
routing.is_feedback(),
routing.note().is_some(),
"{routing} has a loop and no note, or the other way round"
);
}
}
#[test]
fn the_topology_says_which_engines_reach_the_output() {
let serial = Routing::for_value(0).expect("M-1");
assert_eq!(serial.output(), &[Engine::Four]);
let parallel = Routing::for_value(3).expect("M-4");
assert_eq!(parallel.output(), &Engine::ALL);
for engine in Engine::ALL {
assert_eq!(parallel.feeds(engine), &[Source::Input]);
}
}
#[test]
fn every_mode_leaves_a_path_to_the_output() {
assert_eq!(Mode::all().len(), MODE_COUNT);
for mode in Mode::all() {
assert_eq!(Mode::for_value(mode.value()), Some(mode));
assert!(
mode.analog_path() || mode.digital_path(),
"{mode} is silent"
);
}
let bypass = Mode::for_value(2).expect("a bypass");
assert_eq!(bypass.name(), "Bypass");
assert!(bypass.analog_path() && !bypass.digital_path());
let past = u8::try_from(MODE_COUNT).expect("three modes fit in a byte");
assert_eq!(Mode::for_value(past), None);
assert_eq!(Mode::parameter(), ParamId::FxMode);
}
#[test]
fn the_topologies_and_modes_match_their_value_tables() {
for routing in Routing::all() {
assert_eq!(
ParamId::FxRouting.label(u16::from(routing.value())),
Some(routing.name()),
);
}
for mode in Mode::all() {
assert_eq!(
ParamId::FxMode.label(u16::from(mode.value())),
Some(mode.name()),
);
}
}
#[test]
fn slots_are_numbered_from_one_and_in_order() {
for algorithm in Algorithm::all() {
for (index, slot) in algorithm.slots.iter().enumerate() {
let number = u8::try_from(index + 1).expect("twelve slots fit in a byte");
assert_eq!(slot.slot, number, "{algorithm}");
assert_eq!(algorithm.slot(number).map(|s| s.title), Some(slot.title));
}
}
}
#[cfg(not(feature = "descriptions"))]
#[test]
fn a_slot_describes_nothing_without_the_feature() {
for algorithm in Algorithm::all() {
for slot in algorithm.slots {
assert_eq!(slot.description(), None, "{algorithm}");
}
}
}
#[cfg(feature = "descriptions")]
#[test]
fn a_slot_carries_the_manuals_own_words() {
let room = Algorithm::for_value(2, DEFAULT_FIRMWARE).expect("a Room Reverb");
assert_eq!(
room.slot(3).and_then(super::FxSlot::description),
Some("Controls the perceived size of the space being created by the reverb."),
);
let (slots, described) = Algorithm::all().iter().fold((0, 0), |(all, some), a| {
(
all + a.slots.len(),
some + a
.slots
.iter()
.filter(|slot| slot.description().is_some())
.count(),
)
});
assert_eq!(slots, 371);
assert_eq!(described, 369);
}
#[test]
fn three_slots_switch_their_effect_out_of_circuit() {
const EXPECTED: [(&str, u8); 3] = [("EdisonEX1", 1), ("NoiseGate", 8), ("Chorus-D", 1)];
let mut found = [("", 0_u8); EXPECTED.len()];
let mut count = 0_usize;
for algorithm in Algorithm::all() {
for slot in algorithm.slots.iter().filter(|slot| slot.is_enable()) {
assert!(
count < EXPECTED.len(),
"a fourth enable: {algorithm} slot {}",
slot.slot
);
if let Some(entry) = found.get_mut(count) {
*entry = (algorithm.name, slot.slot);
}
count += 1;
}
}
assert_eq!(count, EXPECTED.len());
assert_eq!(found, EXPECTED);
}
#[test]
fn an_enable_is_a_switch_and_may_read_either_way_round() {
for algorithm in Algorithm::all() {
for slot in algorithm.slots.iter().filter(|slot| slot.is_enable()) {
assert_eq!(slot.kind, Kind::Switch, "{algorithm} {}", slot.title);
}
}
let gate = Algorithm::by_name("NoiseGate").expect("a Noise Gate");
let power = gate.slot(8).expect("a Power slot");
assert_eq!((power.min, power.max), (Some("ON"), Some("OFF")));
}
#[test]
fn every_algorithm_has_a_family_and_a_mark() {
let mut own = 0;
for algorithm in Algorithm::all() {
assert!(
!algorithm.mark().strokes().is_empty(),
"{algorithm} has an empty mark"
);
match algorithm.own_mark() {
Some(mark) => {
own += 1;
assert_eq!(algorithm.mark(), mark, "{algorithm}");
assert_ne!(mark, algorithm.family().mark(), "{algorithm}");
}
None => assert_eq!(algorithm.mark(), algorithm.family().mark(), "{algorithm}"),
}
}
assert!(
own > ALGORITHM_COUNT / 2,
"{own} algorithms with a mark of their own"
);
assert!(own < ALGORITHM_COUNT, "every algorithm has its own mark");
assert_eq!(VARIANTS.len(), VARIANT_COUNT);
let counted: usize = Family::ALL
.into_iter()
.map(|family| family.algorithms().count())
.sum();
assert_eq!(counted, ALGORITHM_COUNT);
}
#[test]
fn the_families_are_in_the_order_the_specification_declares() {
assert_eq!(
Family::ALL.map(Family::name),
[
"Reverb",
"Delay",
"Modulation",
"Filter",
"Dynamics",
"Distortion",
"Imaging",
"Pitch",
"Rotary",
]
);
for (index, family) in Family::ALL.into_iter().enumerate() {
assert_eq!(family.index(), index);
}
}
fn wave_at(start: Point, end: Point, amplitude: f32, cycles: f32, u: f32) -> (f32, f32) {
let (dx, dy) = (end.x() - start.x(), end.y() - start.y());
let length = dx.hypot(dy).max(f32::EPSILON);
let (nx, ny) = (dy / length, -dx / length);
let offset = amplitude * crate::math::sin_turns(u * cycles);
(
start.x() + dx * u + nx * offset,
start.y() + dy * u + ny * offset,
)
}
fn sin(radians: f32) -> f32 {
crate::math::sin_turns(radians / core::f32::consts::TAU)
}
fn cos(radians: f32) -> f32 {
crate::math::cos_turns(radians / core::f32::consts::TAU)
}
#[test]
fn a_mark_stays_inside_the_unit_box() {
const MARGIN: f32 = 0.08;
let inside = |x: f32, y: f32, family: Family| {
assert!(
(MARGIN..=1.0 - MARGIN).contains(&x) && (MARGIN..=1.0 - MARGIN).contains(&y),
"{family} reaches ({x}, {y})"
);
};
for family in Family::ALL {
for stroke in family.mark().strokes() {
match *stroke {
Stroke::Line { points } => {
assert!(points.len() >= 2, "{family} has a line of one point");
for point in points {
inside(point.x(), point.y(), family);
}
}
Stroke::Arc {
centre,
radius,
start,
sweep,
} => {
assert!(radius > 0.0, "{family} has an arc of no radius");
assert!(sweep.abs() > 0.0, "{family} has an arc that sweeps nothing");
for turns in [start, start + sweep] {
let radians = turns * core::f32::consts::TAU;
inside(
centre.x() + radius * cos(radians),
centre.y() + radius * sin(radians),
family,
);
}
}
Stroke::Dot { centre, radius } => {
assert!(radius > 0.0, "{family} has a dot of no radius");
inside(centre.x() - radius, centre.y() - radius, family);
inside(centre.x() + radius, centre.y() + radius, family);
}
Stroke::Wave {
start,
end,
amplitude,
cycles,
} => {
assert!(amplitude > 0.0, "{family} has a wave of no amplitude");
assert!(cycles > 0.0, "{family} has a wave of no cycles");
for step in 0..=64_u8 {
let u = f32::from(step) / 64.0;
let (x, y) = wave_at(start, end, amplitude, cycles, u);
inside(x, y, family);
}
}
}
}
}
}
#[test]
fn every_mark_has_a_pixel_grid_that_draws_something() {
let side = u8::try_from(MARK_PIXEL_SIDE).expect("a small grid");
for family in Family::ALL {
let pixels = family.mark().pixels();
assert_eq!(pixels.rows().len(), MARK_PIXEL_SIDE, "{family}");
let mut lit = 0;
for y in 0..side {
for x in 0..side {
if pixels.is_lit(x, y) {
lit += 1;
}
}
}
assert!(lit > 0, "{family} lights nothing");
assert!(lit < MARK_PIXEL_SIDE * MARK_PIXEL_SIDE, "{family} is solid");
assert!(
!pixels.is_lit(side, 0),
"{family} lights a column past the grid"
);
assert_eq!(pixels.row(side), 0, "{family} has a row past the grid");
for y in 0..side {
assert_eq!(
pixels.row(y) >> side,
0,
"{family} row {y} carries a bit past the grid"
);
}
}
}
#[test]
fn no_two_marks_blit_the_same_pixels() {
let marks = || {
Family::ALL
.iter()
.map(|family| family.mark())
.chain(VARIANTS.iter())
};
for (index, mark) in marks().enumerate() {
for other in marks().skip(index + 1) {
assert_ne!(
mark.pixels().rows(),
other.pixels().rows(),
"mark {index} draws the same grid as another"
);
}
}
}
#[test]
fn a_family_is_finer_than_the_manuals_category() {
let creative = |family: Family| {
Algorithm::all()
.iter()
.any(|algorithm| algorithm.category == "Creative" && algorithm.family() == family)
};
assert!(creative(Family::Modulation));
assert!(creative(Family::Filter));
assert!(creative(Family::Pitch));
assert!(creative(Family::Rotary));
}
#[test]
fn a_quantity_is_a_different_question_from_a_control_kind() {
let mut counts = [0_usize; Quantity::ALL.len()];
for algorithm in Algorithm::all() {
for slot in algorithm.slots {
let count = counts
.get_mut(index_of(slot.quantity()))
.expect("a quantity is in Quantity::ALL");
*count += 1;
}
}
for (quantity, count) in Quantity::ALL.into_iter().zip(counts) {
assert!(count > 0, "{quantity:?} is in the enum and on no slot");
}
assert_eq!(counts.iter().sum::<usize>(), 371);
let delay = Algorithm::by_name("3TapDelay").expect("a 3-Tap Delay");
let factor = delay.slot(5).expect("a FactorA slot");
assert!(factor.is_selector());
assert_eq!(factor.quantity(), Quantity::Time);
let gate = Algorithm::by_name("NoiseGate").expect("a Noise Gate");
let power = gate.slot(8).expect("a Power slot");
assert_eq!(power.kind, Kind::Switch);
assert_eq!(power.quantity(), Quantity::Switch);
}
fn index_of(quantity: Quantity) -> usize {
Quantity::ALL
.into_iter()
.position(|other| other == quantity)
.unwrap_or(0)
}
#[test]
fn a_unit_decides_the_quantity_wherever_there_is_one() {
for algorithm in Algorithm::all() {
for slot in algorithm.slots {
let expected = match slot.unit {
Some("ms" | "s") => Some(Quantity::Time),
Some("Hz") => Some(Quantity::Frequency),
Some("deg") => Some(Quantity::Position),
_ => None,
};
if let Some(expected) = expected {
assert_eq!(
slot.quantity(),
expected,
"{algorithm} {} is in {:?}",
slot.title,
slot.unit
);
}
}
}
}
#[test]
fn every_factor_slot_offers_the_same_ten_fractions() {
let printed = super::FACTORS.map(|(_, name)| name);
let mut found = 0;
for algorithm in Algorithm::all() {
for slot in algorithm.slots {
if !slot.title.contains("Factor") {
continue;
}
assert_eq!(
slot.values,
printed.as_slice(),
"{algorithm} {}",
slot.title
);
assert_eq!(slot.quantity(), Quantity::Time);
found += 1;
}
}
assert_eq!(found, 10);
}
#[test]
fn only_the_tap_delays_have_a_published_response() {
let mut program = Program::new(ProtocolVersion::V6);
for algorithm in Algorithm::all() {
let Some(value) = algorithm.value_for(DEFAULT_FIRMWARE) else {
continue;
};
program.set_clamped(Engine::One.algorithm_parameter(), value);
let response = super::response(&program, Engine::One);
let expected = matches!(algorithm.name, "3TapDelay" | "4TapDelay");
assert_eq!(response.is_some(), expected, "{algorithm}");
}
}
#[test]
fn a_tap_lands_where_its_factor_and_gain_put_it() {
let mut program = Program::new(ProtocolVersion::V6);
program.set_fx1_type(FxType::FourTapDelay);
for slot in [2, 6, 8, 10] {
program.set_clamped(Engine::One.slot_parameter(slot).expect("a gain slot"), 255);
}
program.set_clamped(Engine::One.slot_parameter(9).expect("FactorC"), 255);
for slot in [5, 7] {
program.set_clamped(Engine::One.slot_parameter(slot).expect("a factor"), 0);
}
let response = super::response(&program, Engine::One).expect("a 4-Tap Delay");
assert!(
response.at(1.0) > 0.9,
"the furthest tap: {}",
response.at(1.0)
);
assert!(response.at(1.0 / 3.0) > 0.9, "the master tap");
assert!(response.at(0.25 / 3.0) > 0.9, "the two quarter taps");
assert!(response.at(0.6) <= 0.0, "{}", response.at(0.6));
program.set_clamped(Engine::One.slot_parameter(2).expect("the master gain"), 0);
let quiet = super::response(&program, Engine::One).expect("a 4-Tap Delay");
assert!(quiet.at(1.0 / 3.0) <= 0.0, "{}", quiet.at(1.0 / 3.0));
}
#[test]
fn every_fx_type_value_is_an_effect() {
for firmware in [FIRMWARE_1_0, DEFAULT_FIRMWARE] {
let table = TableId::FxType.table_for(firmware);
for (value, entry) in table.entries.iter().enumerate() {
assert!(
Algorithm::by_name(entry.name).is_some(),
"{:?} names no algorithm",
entry.name
);
assert_eq!(u16::try_from(value), Ok(entry.value));
}
}
let newest = TableId::FxType.table_for(DEFAULT_FIRMWARE);
assert_eq!(newest.entries.len(), ALGORITHM_COUNT);
assert_eq!(
TableId::FxType.table_for(FIRMWARE_1_0).entries.len(),
ALGORITHM_COUNT - 1
);
}
}