diff --git a/CHANGELOG.md b/CHANGELOG.md index 29f02ebe..630524a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,3 +31,6 @@ Nothing has been released yet. The first release, 0.1.0, will cover what is on ` for a new instrument track; double-clicking an instrument with no instrument track selected adds one. - Expanded windows for Auto Filter, Channel EQ and Character EQ, with a large display, a live analyser (Pre, Post or Off, and Hold view), In and Out meters and every control laid out in rows, including Character EQ's band Drive. +- Expanded windows for Tremolo, Auto-Panner, Chorus, Flanger, Phaser and Ring Mod: a large plot of the effect's + motion or frequency response with a time or frequency axis, units and a legend, which you can drag to set its + rate and depth (or feedback or bias), In and Out meters, and every control on one row. diff --git a/README.md b/README.md index edb60752..d34f2387 100644 --- a/README.md +++ b/README.md @@ -121,7 +121,9 @@ framed by tools/art/render.mjs. Device comes with 44 devices of its own. Each one is a single declarative definition (parameters, panel layout and factory presets) that the model, undo, saving, automation, engine and panel all derive from, with a C++ DSP kernel behind it. Auto Filter, Channel EQ and Character EQ also open an expanded window with a large display and live analyser, -In and Out meters and every control laid out in rows; the other devices open their card in a window for now. +In and Out meters and every control laid out in rows, and so do Tremolo, Auto-Panner, Chorus, Flanger, Phaser and +Ring Mod, whose window plots their motion or response with a time or frequency axis and a legend; the other devices +open their card in a window for now. [docs/devices.md](docs/devices.md) explains how they work and how to add one. | Kind | Devices | diff --git a/crates/dstudio-app/src/device_canvas.rs b/crates/dstudio-app/src/device_canvas.rs index ba6aead7..8b7590f3 100644 --- a/crates/dstudio-app/src/device_canvas.rs +++ b/crates/dstudio-app/src/device_canvas.rs @@ -51,11 +51,11 @@ fn model(v: Vec) -> ModelRc { ModelRc::from(Rc::new(VecModel::from(v))) } -fn rgba(c: Color, a: f32) -> Color { +pub(crate) fn rgba(c: Color, a: f32) -> Color { Color::from_argb_u8((a.clamp(0.0, 1.0) * 255.0).round() as u8, c.red(), c.green(), c.blue()) } -fn white(a: f32) -> Color { +pub(crate) fn white(a: f32) -> Color { rgba(Color::from_rgb_u8(255, 255, 255), a) } @@ -152,7 +152,7 @@ impl Plot { } } -fn path(pts: &[(f32, f32)]) -> String { +pub(crate) fn path(pts: &[(f32, f32)]) -> String { use std::fmt::Write; let mut out = String::with_capacity(pts.len() * 16); for (i, (x, y)) in pts.iter().enumerate() { @@ -171,7 +171,7 @@ fn area(pts: &[(f32, f32)], base: f32) -> String { } /// A polyline as dashes of `on` px with `off` px gaps along its length. -fn dashed(pts: &[(f32, f32)], on: f32, off: f32) -> String { +pub(crate) fn dashed(pts: &[(f32, f32)], on: f32, off: f32) -> String { use std::fmt::Write; let mut out = String::new(); let mut phase = 0.0f32; // distance into the current on + off period @@ -211,16 +211,16 @@ fn hline(y: f32, x0: f32, x1: f32) -> String { format!("M{x0:.1} {y:.1} L{x1:.1} {y:.1}") } -fn stroke(commands: String, color: Color, width: f32) -> PanelPath { +pub(crate) fn stroke(commands: String, color: Color, width: f32) -> PanelPath { PanelPath { commands: s(commands), stroke: color, width, fill: Color::from_argb_u8(0, 0, 0, 0), fill2: Color::from_argb_u8(0, 0, 0, 0) } } -fn fill(commands: String, color: Color) -> PanelPath { +pub(crate) fn fill(commands: String, color: Color) -> PanelPath { PanelPath { commands: s(commands), stroke: Color::from_argb_u8(0, 0, 0, 0), width: 0.0, fill: color, fill2: color } } /// Text whose x is its left (align 0), centre (1) or right (2) edge and y its centre line. -fn text(x: f32, y: f32, w: f32, t: impl Into, color: Color, size: f32, align: i32) -> PanelText { +pub(crate) fn text(x: f32, y: f32, w: f32, t: impl Into, color: Color, size: f32, align: i32) -> PanelText { let left = match align { 0 => x, 1 => x - w / 2.0, @@ -404,7 +404,7 @@ fn win_legend(p: &Plot, entries: &[(Legend, &str)], accent: Color, paths: &mut V } } -const MUTE_TEXT: Color = Color::from_rgb_u8(0xa6, 0xa8, 0xad); +pub(crate) const MUTE_TEXT: Color = Color::from_rgb_u8(0xa6, 0xa8, 0xad); // ---------------------------------------------------------------- EQ diff --git a/crates/dstudio-app/src/device_fields.rs b/crates/dstudio-app/src/device_fields.rs index 81a016f4..49f5fb7a 100644 --- a/crates/dstudio-app/src/device_fields.rs +++ b/crates/dstudio-app/src/device_fields.rs @@ -63,8 +63,38 @@ pub struct Plot { /// Width of the first trace at rest and while the field is hot (pt). pub widths: (f32, f32), pub live: Option, + /// Expanded window only (Input::win): the axis row under the plot and the legend. + pub axis: Axis, + pub legend: Vec<(Mark, String)>, } +/// The axis row under a window's plot. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Axis { + /// (x 0..1, label, strong rule); an empty label draws the rule only. + pub ticks: Vec<(f32, String, bool)>, + /// Name of the left ruler, at its foot on the axis row ("dB gain"). + pub foot: String, + /// Unit named at the row's left end ("Hz"). + pub start: String, + /// Unit at the row's right end ("s"). + pub end: String, + /// The legend sits at the right end of the caption row instead of under the axis. + pub legend_in_caption: bool, +} + +/// Legend glyph of a series. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Mark { + Line(Style), + /// The accent wash between the first trace and the rest line. + Band, +} + +/// A window's right-channel series and a sweep's far end. +const WIN_RIGHT: Style = Style::Dash { on: 5.0, off: 4.0, alpha: 0.5 }; +const WIN_SWEEP: Style = Style::Dash { on: 2.0, off: 3.0, alpha: 0.34 }; + pub struct Input<'a> { /// Plain value of a parameter (0 when the device has no such parameter). pub get: &'a dyn Fn(&str) -> f32, @@ -74,6 +104,8 @@ pub struct Input<'a> { /// Elapsed LFO cycles while the transport plays (its fraction is the /// engine's LFO phase); None draws no live overlay. pub cycles: Option, + /// The expanded window's picture: its own rulers, axis row and legend. + pub win: bool, } impl Input<'_> { @@ -136,6 +168,37 @@ fn motion_dot(i: &Input, span: f32, ys: &[f32]) -> Option { Some(Live::Dot { x, y: sample(ys, x), trail: Vec::new() }) } +/// A time on a motion window's axis: whole milliseconds under a second. +fn time_text(sec: f32) -> String { + if sec < 1.0 { + format!("{} ms", (sec * 1000.0).round()) + } else if sec < 10.0 { + format!("{sec:.2} s") + } else { + format!("{sec:.1} s") + } +} + +/// A motion window's time axis: one rule per cycle boundary, numbered with its time. +fn motion_axis(span: f32, hz: f32, foot: &str) -> Axis { + let period = 1.0 / hz.max(1e-3); + let ticks = (0..=(span + 1e-4).floor() as usize) + .map(|c| (c as f32 / span, if c == 0 { String::new() } else { time_text(c as f32 * period) }, c > 0)) + .collect(); + Axis { ticks, foot: foot.into(), end: if period < 1.0 { "ms" } else { "s" }.into(), ..Axis::default() } +} + +/// Signed dB rung label: +12, 0, -12 (with a minus sign). +fn rung(db: f32) -> String { + if db > 0.5 { + format!("+{db:.0}") + } else if db < -0.5 { + format!("{MINUS}{:.0}", -db) + } else { + "0".into() + } +} + /// Small deterministic generator (display only). struct Lcg(u32); impl Lcg { @@ -162,25 +225,43 @@ fn trem_shape(shape: usize, p: f32) -> f32 { fn tremolo(i: &Input) -> Plot { let (depth, mix, shape) = (i.get("depth") / 100.0, i.get("mix") / 100.0, i.idx("shape")); let stereo = i.get("stereo_phase") / 180.0; - let span = motion_span(i.lfo_hz("rate", "rate_sync", DIVISION_QUARTERS)); + let hz = i.lfo_hz("rate", "rate_sync", DIVISION_QUARTERS); + let span = motion_span(hz); + // The window's ladder runs to -18 dB (the default 70 % dip lands at 58 % of it); the card's to -14. + let floor = if i.win { -18.0 } else { -14.0 }; let curve = |off: f32| -> Vec { - i.xs().map(|x| lin(db(1.0 - mix + mix * (1.0 - depth * (1.0 - trem_shape(shape, x * span + off)))), 0.0, -14.0)).collect() + i.xs().map(|x| lin(db(1.0 - mix + mix * (1.0 - depth * (1.0 - trem_shape(shape, x * span + off)))), 0.0, floor)).collect() }; let main = curve(0.0); - let live = motion_dot(i, span, &main); + let live = if i.win { None } else { motion_dot(i, span, &main) }; let mut traces = vec![Trace { ys: main, style: Style::Solid }]; - if stereo > 0.0005 { - traces.push(Trace { ys: curve(stereo * 0.5), style: Style::Dash { on: 4.0, off: 3.0, alpha: 0.5 } }); + let split = stereo > 0.0005; + if split { + let style = if i.win { WIN_RIGHT } else { Style::Dash { on: 4.0, off: 3.0, alpha: 0.5 } }; + traces.push(Trace { ys: curve(stereo * 0.5), style }); } let att = -db(1.0 - depth * mix); + let ticks = if i.win { + // A rule every 3 dB, a numeral every 6. + (0..=6).map(|k| (k as f32 / 6.0, if k % 2 == 0 { rung(-3.0 * k as f32) } else { String::new() })).collect() + } else { + vec![(0.0, "0".into()), (0.5, format!("{MINUS}7")), (1.0, format!("{MINUS}14"))] + }; + let mut legend = vec![(Mark::Line(Style::Solid), if split { "Left" } else { "Gain" }.to_string())]; + if split { + legend.push((Mark::Line(WIN_RIGHT), "Right".into())); + } + legend.push((Mark::Band, "Modulation".into())); Plot { readout: if att >= 90.0 { "\u{221e} dB".into() } else { format!("{att:.1} dB") }, - ticks: vec![(0.0, "0".into()), (0.5, format!("{MINUS}7")), (1.0, format!("{MINUS}14"))], + ticks, rest: Some(0.0), traces, fill: Fill::ToRest, widths: (1.6, 2.35), live, + axis: motion_axis(span, hz, "dB gain"), + legend, } } @@ -211,24 +292,30 @@ fn autopanner(i: &Input) -> Plot { let lead = (2.0 / dc).ceil() as usize; let mut v = raw(phase - lead as f32 * dc) * depth; let mut ys = Vec::with_capacity(n); + let mut peak = 0.0f32; for k in 0..lead + n { v += a * (raw(phase + (k as f32 - lead as f32) * dc) * depth - v); if k >= lead { let pos = (0.5 + 0.5 * v) * PI / 2.0; let (l, r) = ((1.0 - mix) + pos.cos() * std::f32::consts::SQRT_2 * mix, (1.0 - mix) + pos.sin() * std::f32::consts::SQRT_2 * mix); - ys.push(lin(r.atan2(l) / (PI / 2.0) * 2.0 - 1.0, -1.0, 1.0)); + let pan = r.atan2(l) / (PI / 2.0) * 2.0 - 1.0; + peak = peak.max(pan.abs()); + ys.push(lin(pan, -1.0, 1.0)); } } - let live = motion_dot(i, span, &ys); + let live = if i.win { None } else { motion_dot(i, span, &ys) }; Plot { - readout: String::new(), + // The window quotes the excursion the line reaches: the glide and Mix take travel off Depth. + readout: if i.win { format!("\u{b1}{}%", (peak * 100.0).round()) } else { String::new() }, ticks: vec![(0.0, "L".into()), (0.25, String::new()), (0.5, "C".into()), (0.75, String::new()), (1.0, "R".into())], rest: Some(0.5), traces: vec![Trace { ys, style: Style::Solid }], fill: Fill::ToRest, widths: (1.6, 2.35), live, + axis: motion_axis(span, hz, "pan"), + legend: vec![(Mark::Line(Style::Solid), "Pan".into()), (Mark::Band, "Off center".into())], } } @@ -276,6 +363,38 @@ fn hz_text(f: f32) -> String { } } +/// A window's notch frequency: 385 Hz, 1.3 kHz, 12 kHz. +fn hz_unit(f: f32) -> String { + if f >= 10_000.0 { + format!("{:.0} kHz", f / 1000.0) + } else if f >= 1000.0 { + format!("{:.1} kHz", f / 1000.0) + } else { + format!("{} Hz", f.round()) + } +} + +/// A window's notch travel: one frequency, low to high, or open at the top (no notch). +fn hz_travel(a: Option, b: Option) -> String { + match (a, b) { + (Some(a), Some(b)) if (a - b).abs() >= 1.0 => format!("{} \u{2013} {}", hz_unit(a.min(b)), hz_unit(a.max(b))), + (Some(f), Some(_)) => hz_unit(f), + (Some(f), None) | (None, Some(f)) => format!("{} \u{2192} open", hz_unit(f)), + (None, None) => "\u{2014}".into(), + } +} + +/// Step of a linear frequency axis: off a 1-2-5 ladder, at most eight rules across. +fn hz_step(span: f32) -> f32 { + const LADDER: [f32; 12] = [10.0, 20.0, 25.0, 50.0, 100.0, 200.0, 250.0, 500.0, 1000.0, 2000.0, 2500.0, 5000.0]; + LADDER.into_iter().find(|s| span / s <= 8.0).unwrap_or(5000.0) +} + +/// Frequency label of an axis rule: 500, 1k, 2.5k. +fn hz_tick(f: f32) -> String { + if f >= 1000.0 { format!("{}k", f / 1000.0) } else { format!("{}", f.round()) } +} + fn hz_range(a: Option, b: Option) -> String { match (a, b) { (Some(a), Some(b)) if (a - b).abs() >= 1.0 => format!("{}\u{2013}{} Hz", hz_text(a.min(b)), hz_text(a.max(b))), @@ -387,22 +506,65 @@ fn response(name: &str, i: &Input) -> Plot { ) } }; - let curve = |p: f32| -> Vec { (0..n).map(|k| lin(db(resp(p, freq(k as f32 / (n - 1) as f32))) + out_db, 12.0, -24.0)).collect() }; - let mut traces = vec![ - Trace { ys: curve(snap), style: Style::Solid }, - Trace { ys: curve(sweep), style: Style::Dash { on: 2.0, off: 3.0, alpha: 0.34 } }, + // The window's ladder: +-24 dB in 6 dB rungs (the phaser's from +30), the card's +12 .. -24. + let (top, bottom) = match (i.win, name) { + (false, _) => (12.0, -24.0), + (true, "phaser") => (30.0, -24.0), + (true, _) => (24.0, -24.0), + }; + let curve = |p: f32| -> Vec { (0..n).map(|k| lin(db(resp(p, freq(k as f32 / (n - 1) as f32))) + out_db, top, bottom)).collect() }; + let mut traces = vec![Trace { ys: curve(snap), style: Style::Solid }, Trace { ys: curve(sweep), style: WIN_SWEEP }]; + let split = width > 0.0005; + if split { + traces.push(Trace { ys: curve(right), style: WIN_RIGHT }); + } + if !i.win { + return Plot { + readout: hz_range(notch(snap), notch(sweep)), + ticks: vec![(0.0, "+12".into()), (1.0 / 3.0, "0".into()), (2.0 / 3.0, format!("{MINUS}12")), (1.0, format!("{MINUS}24"))], + rest: Some(1.0 / 3.0), + traces, + fill: Fill::None, + widths: (1.5, 2.25), + live: i.cycles.map(|c| Live::Curve(curve(c.rem_euclid(1.0) as f32))), + axis: Axis::default(), + legend: Vec::new(), + }; + } + let rungs = ((top - bottom) / 6.0).round() as usize; + let ticks = (0..=rungs) + .map(|k| { + let db = top - 6.0 * k as f32; + (k as f32 / rungs as f32, if k == 0 { format!("{} dB", rung(db)) } else { rung(db) }) + }) + .collect(); + // Comb filters read on a linear axis (their teeth are evenly spaced), the phaser's notches on a log one. + let axis_ticks = if name == "phaser" { + [50.0f32, 100.0, 200.0, 500.0, 1000.0, 2000.0, 5000.0, 10_000.0] + .map(|f| ((f / 20.0).ln() / 1000f32.ln(), hz_tick(f), false)) + .to_vec() + } else { + let span = freq(1.0); + let step = hz_step(span); + (1..=(span / step + 1e-3).floor() as usize).map(|k| ((k as f32 * step / span).min(1.0), hz_tick(k as f32 * step), false)).collect() + }; + let mut legend = vec![ + (Mark::Line(Style::Solid), if name == "phaser" { "Notches" } else { "Comb" }.to_string()), + (Mark::Line(WIN_SWEEP), "Sweep".into()), ]; - if width > 0.0005 { - traces.push(Trace { ys: curve(right), style: Style::Dash { on: 5.0, off: 4.0, alpha: 0.5 } }); + if split { + legend.push((Mark::Line(WIN_RIGHT), "Right".into())); } Plot { - readout: hz_range(notch(snap), notch(sweep)), - ticks: vec![(0.0, "+12".into()), (1.0 / 3.0, "0".into()), (2.0 / 3.0, format!("{MINUS}12")), (1.0, format!("{MINUS}24"))], - rest: Some(1.0 / 3.0), + readout: hz_travel(notch(snap), notch(sweep)), + ticks, + rest: Some(top / (top - bottom)), traces, fill: Fill::None, - widths: (1.5, 2.25), - live: i.cycles.map(|c| Live::Curve(curve(c.rem_euclid(1.0) as f32))), + widths: (1.75, 2.5), + live: None, + axis: Axis { ticks: axis_ticks, start: "Hz".into(), ..Axis::default() }, + legend, } } @@ -490,19 +652,85 @@ fn ring_mod(i: &Input) -> Plot { }) .collect() }; - let mut traces = vec![Trace { ys: curve(0, 2f32.powf(-s / 12.0)), style: Style::Solid }]; - if m >= 4 || s > 0.0005 { - traces.push(Trace { ys: curve(1, 2f32.powf(s / 12.0)), style: Style::Dash { on: 4.0, off: 3.0, alpha: 0.5 } }); + let (lo, hi) = (2f32.powf(-s / 12.0), 2f32.powf(s / 12.0)); + let mut traces = vec![Trace { ys: curve(0, lo), style: Style::Solid }]; + let split = m >= 4 || s > 0.0005; + if split { + let style = if i.win { WIN_RIGHT } else { Style::Dash { on: 4.0, off: 3.0, alpha: 0.5 } }; + traces.push(Trace { ys: curve(1, hi), style }); + } + if !i.win { + return Plot { + readout: String::new(), + ticks: vec![(0.0, "1".into()), (0.5, "0".into()), (1.0, format!("{MINUS}1"))], + rest: Some(0.5), + traces, + fill: Fill::ToRest, + widths: (1.6, 2.35), + live: None, + axis: Axis::default(), + legend: Vec::new(), + }; } + let legend = + if split { vec![(Mark::Line(Style::Solid), "Left".to_string()), (Mark::Line(WIN_RIGHT), "Right".into())] } else { Vec::new() }; Plot { - readout: String::new(), - ticks: vec![(0.0, "1".into()), (0.5, "0".into()), (1.0, format!("{MINUS}1"))], + readout: if s > 0.0005 { ring_hz_span(f * lo, f * hi) } else { ring_hz(f).join(" ") }, + ticks: vec![(0.0, "1".into()), (0.25, String::new()), (0.5, "0".into()), (0.75, String::new()), (1.0, format!("{MINUS}1"))], rest: Some(0.5), traces, fill: Fill::ToRest, - widths: (1.6, 2.35), + widths: (1.75, 2.5), live: None, + axis: ring_axis(cycles, 1.0 / f), + legend, + } +} + +/// A modulator frequency to three figures: [number, unit]. +fn ring_hz(hz: f32) -> [String; 2] { + if hz >= 10_000.0 { + [format!("{:.1}", hz / 1000.0), "kHz".into()] + } else if hz >= 1000.0 { + [format!("{:.2}", hz / 1000.0), "kHz".into()] + } else if hz >= 100.0 { + [format!("{}", hz.round()), "Hz".into()] + } else if hz >= 10.0 { + [format!("{hz:.1}"), "Hz".into()] + } else { + [format!("{hz:.2}"), "Hz".into()] + } +} + +/// The two sides' frequencies with Spread on, low to high in the higher one's unit. +fn ring_hz_span(lo: f32, hi: f32) -> String { + let [h, unit] = ring_hz(hi); + let l = if unit == "kHz" { format!("{:.*}", if hi >= 10_000.0 { 1 } else { 2 }, lo / 1000.0) } else { ring_hz(lo)[0].clone() }; + format!("{l}\u{2013}{h} {unit}") +} + +/// Ring Mod's time axis: one rule per modulator cycle, numbered in the unit that keeps the +/// longest under four digits, with as few decimals as the row needs. +fn ring_axis(span: f32, period: f32) -> Axis { + let last = (span + 1e-4).floor().max(1.0) as usize; + let longest = period * last as f32; + let (scale, unit) = if longest < 1e-3 { + (1e6, "\u{b5}s") + } else if longest < 1.0 { + (1e3, "ms") + } else { + (1.0, "s") + }; + let step = period * scale; + let mut places = (2 - step.log10().floor() as i32).max(0) as usize; + let all = |d: usize| (1..=last).map(|c| format!("{:.*}", d, c as f32 * step)).collect::>(); + while places > 0 && all(places).iter().all(|t| t.ends_with('0')) { + places -= 1; } + let labels = all(places); + let mut ticks = vec![(0.0, String::new(), false)]; + ticks.extend(labels.into_iter().enumerate().map(|(k, t)| ((k + 1) as f32 / span, t, true))); + Axis { ticks, foot: "gain".into(), end: unit.into(), legend_in_caption: true, ..Axis::default() } } // ---------------------------------------------------------------- character mod @@ -694,7 +922,17 @@ fn character_mod(i: &Input) -> Plot { let trail = (0..=24).map(|k| t0 + (x - t0) * k as f32 / 24.0).map(|tx| (tx, y_of(f(tx * SPAN)))).collect(); Live::Dot { x, y: y_of(f(p)), trail } }); - Plot { readout, ticks, rest, traces, fill: if band { Fill::Band } else { Fill::None }, widths: (1.6, 2.35), live } + Plot { + readout, + ticks, + rest, + traces, + fill: if band { Fill::Band } else { Fill::None }, + widths: (1.6, 2.35), + live, + axis: Axis::default(), + legend: Vec::new(), + } } #[cfg(test)] @@ -713,7 +951,47 @@ mod tests { Some(builtin::View::Field(f)) => f.plot, _ => panic!("{id} has no field"), }; - plot(name, &Input { get: &get, bpm: 120.0, n: 300, cycles }).unwrap() + plot(name, &Input { get: &get, bpm: 120.0, n: 300, cycles, win: false }).unwrap() + } + + fn window_plot_of(id: &str) -> Plot { + let def = builtin::find(id).unwrap(); + let d = def.instantiate(); + let get = |p: &str| def.param(p).map_or(0.0, |q| def.value(&d, q)); + let Some(builtin::View::Field(f)) = def.layout.view else { panic!("{id} has no field") }; + plot(f.plot, &Input { get: &get, bpm: 120.0, n: 400, cycles: None, win: true }).unwrap() + } + + /// The window form adds an axis row and a legend naming every series it draws. + #[test] + fn window_plots_carry_an_axis_and_a_legend() { + for id in ["tremolo", "autopanner", "chorus", "flanger", "phaser", "ring-mod"] { + let p = window_plot_of(id); + assert!(!p.axis.ticks.is_empty(), "{id}: no axis ticks"); + assert!(p.axis.ticks.iter().all(|t| (0.0..=1.0).contains(&t.0)), "{id}: tick off the plot"); + assert!(id == "ring-mod" || !p.legend.is_empty(), "{id}: no legend"); + assert!(p.ticks.len() >= 5, "{id}: window ladder is taller than the card's"); + } + // Response windows read in Hz along a +24 dB ladder. + let f = window_plot_of("flanger"); + assert_eq!(f.axis.start, "Hz"); + assert_eq!(f.axis.ticks.last().map(|t| t.1.as_str()), Some("2k")); + assert_eq!(f.ticks.first().map(|t| t.1.as_str()), Some("+24 dB")); + let names: Vec<&str> = f.legend.iter().map(|l| l.1.as_str()).collect(); + assert_eq!(names, ["Comb", "Sweep", "Right"]); + // Ring Mod draws one series (no legend entries) and reads its time axis in ms. + let r = window_plot_of("ring-mod"); + assert!(r.axis.legend_in_caption); + assert_eq!(r.axis.end, "ms"); + // The card form stays as it was: no axis, no legend. + assert!(plot_of("flanger", &[], None).axis.ticks.is_empty()); + } + + #[test] + fn window_time_labels() { + assert_eq!(time_text(0.25), "250 ms"); + assert_eq!(time_text(1.5), "1.50 s"); + assert_eq!(time_text(12.0), "12.0 s"); } #[test] @@ -721,7 +999,7 @@ mod tests { for def in builtin::all() { if let Some(builtin::View::Field(f)) = def.layout.view { let get = |p: &str| def.param(p).map_or(0.0, |q| q.default); - let p = plot(f.plot, &Input { get: &get, bpm: 120.0, n: 64, cycles: Some(0.3) }) + let p = plot(f.plot, &Input { get: &get, bpm: 120.0, n: 64, cycles: Some(0.3), win: false }) .unwrap_or_else(|| panic!("{} has no model", def.id)); assert!( !p.traces.is_empty() && p.traces.iter().all(|t| t.ys.len() >= 64 && t.ys.iter().all(|y| y.is_finite())), diff --git a/crates/dstudio-app/src/device_panel.rs b/crates/dstudio-app/src/device_panel.rs index 96e3b70a..c3c9f449 100644 --- a/crates/dstudio-app/src/device_panel.rs +++ b/crates/dstudio-app/src/device_panel.rs @@ -1068,7 +1068,7 @@ impl Controller { } /// The first of a field axis' parameters that is shown (Rate or Rate Sync). - fn field_axis(d: &Device, def: &DeviceDef, ids: &[&'static str]) -> Option { + pub(crate) fn field_axis(d: &Device, def: &DeviceDef, ids: &[&'static str]) -> Option { ids.iter().find(|id| def.is_shown(d, id)).and_then(|id| def.index_of(id)) } @@ -1084,6 +1084,7 @@ impl Controller { bpm: self.project().transport.bpm as f32, n: (pw.round() as usize).max(64), cycles: self.devices.panel.lfo.get(&d.id).map(|l| l.1), + win: false, }; let Some(plot) = device_fields::plot(f.plot, &input) else { return PanelField::default() }; let at = |x: f32, y: f32| (px + x * pw, py + y * ph); diff --git a/crates/dstudio-app/src/device_window.rs b/crates/dstudio-app/src/device_window.rs index 6e693e2c..ca4f7d29 100644 --- a/crates/dstudio-app/src/device_window.rs +++ b/crates/dstudio-app/src/device_window.rs @@ -84,25 +84,57 @@ pub(crate) const MENU_ANALYZER: i32 = -4; /// Devices with an expanded window. pub(crate) fn has_window(def: &DeviceDef) -> bool { - matches!(def.id, "auto-filter" | "channeleq" | "character-eq") + matches!(def.id, "auto-filter" | "channeleq" | "character-eq") || is_field_window(def) } -/// Size of the display plot of a device's window (px at the panel zoom). -pub(crate) fn plot_size(def: &DeviceDef) -> Option<(f32, f32)> { - has_window(def).then(|| { - let (_, _, w, h) = display_rect(def); - ((w - PLOT_L - PLOT_R) * Z, (h - PLOT_T - PLOT_B) * Z) - }) +/// Windows of the plotted-field family (motion and response pictures). +fn is_field_window(def: &DeviceDef) -> bool { + matches!(def.id, "tremolo" | "autopanner" | "chorus" | "flanger" | "phaser" | "ring-mod") +} + +/// The frame of a device's window: content width, display box (x, y, w, h), the +/// display's plot insets (left, top, right, bottom) and its meter strip. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Kit { + pub w: f32, + pub display: (f32, f32, f32, f32), + pub plot: (f32, f32, f32, f32), + /// The narrow strip (114 wide, columns of 54) of the field windows; else the EQs' 136. + narrow: bool, +} + +/// Field windows: a display 152 narrower than the window, a 12 pt gap to the control card. +fn field_kit(w: f32, display_h: f32, left: f32, bottom: f32) -> Kit { + Kit { w, display: (INSET, 52.0, w - 152.0, display_h), plot: (left, 25.0, 8.0, bottom), narrow: true } } -/// Display box in content points: x, y, w, h. -fn display_rect(def: &DeviceDef) -> (f32, f32, f32, f32) { +pub(crate) fn kit(def: &DeviceDef) -> Kit { + let eq = |y: f32, h: f32| Kit { + w: WIN_W, + display: (INSET, y, WIN_W - 2.0 * INSET - METERS_W - METERS_GAP, h), + plot: (PLOT_L, PLOT_T, PLOT_R, PLOT_B), + narrow: false, + }; match def.id { - "character-eq" => (INSET, 52.0, WIN_W - 2.0 * INSET - METERS_W - METERS_GAP, 346.0), - _ => (INSET, 56.0, WIN_W - 2.0 * INSET - METERS_W - METERS_GAP, 394.0), + "character-eq" => eq(52.0, 346.0), + "tremolo" => field_kit(WIN_W, 234.0, 60.0, 44.0), + "autopanner" => field_kit(WIN_W, 234.0, 40.0, 44.0), + "chorus" | "flanger" => field_kit(WIN_W, 354.0, 56.0, 44.0), + "phaser" => field_kit(WIN_W, 374.0, 56.0, 44.0), + "ring-mod" => field_kit(860.0, 254.0, 40.0, 29.0), + _ => eq(56.0, 394.0), } } +/// Size of the display plot of a device's window (px at the panel zoom). +pub(crate) fn plot_size(def: &DeviceDef) -> Option<(f32, f32)> { + has_window(def).then(|| { + let k = kit(def); + let (_, _, w, h) = k.display; + ((w - k.plot.0 - k.plot.2) * Z, (h - k.plot.1 - k.plot.3) * Z) + }) +} + /// Window UI state that is not part of the device (not saved). #[derive(Debug, Default)] pub(crate) struct WinUi { @@ -357,6 +389,8 @@ fn pill_w(label: &str) -> f32 { /// A window being built: everything in content points until `finish` scales it. struct Builder { accent: Color, + /// Window content width. + w: f32, boxes: Vec, pills: Vec, knobs: Vec, @@ -369,8 +403,8 @@ fn accent_of(b: &Builder) -> Color { } impl Builder { - fn new(accent: Color) -> Self { - Builder { accent, boxes: Vec::new(), pills: Vec::new(), knobs: Vec::new(), texts: Vec::new(), square: PanelCanvas::default() } + fn new(accent: Color, w: f32) -> Self { + Builder { accent, w, boxes: Vec::new(), pills: Vec::new(), knobs: Vec::new(), texts: Vec::new(), square: PanelCanvas::default() } } fn rect(&mut self, kind: i32, x: f32, y: f32, w: f32, h: f32) { @@ -486,25 +520,28 @@ impl Controller { if !has_window(def) { return None; } - let mut b = Builder::new(accent); - let (dx, dy, dw, dh) = display_rect(def); + let k = kit(def); + let mut b = Builder::new(accent, k.w); + let (dx, dy, dw, dh) = k.display; b.rect(BOX_DISPLAY, dx, dy, dw, dh); let mut display = match def.layout.view { Some(View::Eq(v)) => self.eq_window_field(d, def, v, accent), Some(View::Custom("auto-filter")) => self.auto_filter_window_field(d, def, accent), + Some(View::Field(f)) => self.field_window_canvas(d, def, f, &k, accent), _ => PanelCanvas::default(), }; - display.x = (dx + PLOT_L) * Z; - display.y = (dy + PLOT_T) * Z; + display.x = (dx + k.plot.0) * Z; + display.y = (dy + k.plot.1) * Z; let height = match def.id { "auto-filter" => self.auto_filter_window(d, def, &mut b), "channeleq" => self.channel_eq_window(d, def, &mut b), - _ => self.character_eq_window(d, def, &mut b), + "character-eq" => self.character_eq_window(d, def, &mut b), + _ => self.field_window(d, def, &mut b, dy + dh + 12.0), }; - let (meters, ticks) = self.window_meters(d.id, dx + dw + METERS_GAP, dy, dh); + let (meters, ticks, ticks_x) = self.window_meters(d.id, &k); Some(WinView { visible: true, - w: WIN_W * Z, + w: k.w * Z, h: height * Z, title: s(d.display_name()), display, @@ -515,19 +552,27 @@ impl Controller { texts: model(b.texts), meters: model(meters), ticks: model(ticks), - ticks_x: (dx + dw + METERS_GAP + 126.0) * Z, + ticks_x: ticks_x * Z, }) } - /// In / Out meter columns in the strip at x (content points). - fn window_meters(&self, id: DeviceId, x: f32, y: f32, h: f32) -> (Vec, Vec) { + /// In / Out meter columns in the strip right of the display, and the x of the ruler's + /// numerals (content points). The EQs' strip is 136 wide with each bar under its label; + /// the field windows' is 114, two 54 pt columns with the bar at the left of each. + fn window_meters(&self, id: DeviceId, k: &Kit) -> (Vec, Vec, f32) { let m = self.devices.wins.meters.get(&id).cloned().unwrap_or_else(Meters::new); - let (top, bar_h) = (y + 22.0, h - 44.0); + let (dx, y, dw, h) = k.display; + let (top, bar_h) = if k.narrow { (y + 26.2, h - 48.2) } else { (y + 22.0, h - 44.0) }; + let x = dx + dw + if k.narrow { 6.0 } else { METERS_GAP }; + // (bar x, label centre) of each column. + let cols = if k.narrow { [(x + 8.0, x + 27.0), (x + 68.0, x + 87.0)] } else { [(x + 19.0, x + 27.0), (x + 85.0, x + 93.0)] }; + let ticks_x = if k.narrow { x + 93.0 } else { x + 126.0 }; let span = METER_TOP_DB - METER_MIN_DB; let zero_h = bar_h * METER_TOP_DB / span; - let meters = [("In", 0usize, x + 19.0), ("Out", 1, x + 85.0)] + let meters = [("In", 0usize, cols[0]), ("Out", 1, cols[1])] .into_iter() - .map(|(label, k, mx)| WinMeter { + .map(|(label, k, (mx, lx))| WinMeter { + label_x: lx * Z, x: mx * Z, y: top * Z, w: 16.0 * Z, @@ -556,7 +601,7 @@ impl Controller { rule: true, }) .collect(); - (meters, ticks) + (meters, ticks, ticks_x) } /// Engine peaks -> meter ballistics of every open window (each poll tick). @@ -680,12 +725,12 @@ impl Controller { /// A row of clusters in a card: places every item, the card and its rules. fn win_card(&self, d: &Device, def: &'static DeviceDef, b: &mut Builder, row: Row, clusters: Vec<(Vec, f32)>) { - b.rect(BOX_CARD, INSET, row.y, WIN_W - 2.0 * INSET, row.h); + b.rect(BOX_CARD, INSET, row.y, b.w - 2.0 * INSET, row.h); let widths: Vec = clusters .iter() .map(|(items, gap)| items.iter().map(Item::width).sum::() + gap * (items.len().saturating_sub(1)) as f32) .collect(); - let (xs, rules) = gutter(INSET, WIN_W - 2.0 * INSET, &widths); + let (xs, rules) = gutter(INSET, b.w - 2.0 * INSET, &widths); let rule_h = row.h - 24.0; for rx in rules { b.rect(BOX_RULE, rx, row.y + 12.0, 1.0, rule_h); @@ -748,7 +793,7 @@ impl Controller { .map(|(_, _, items, gap, _)| Builder::row_w(&items.iter().map(|(l, _, _)| l.as_str()).collect::>(), *gap)) .collect(); let total: f32 = widths.iter().sum::() + 34.0 * (groups.len().saturating_sub(1)) as f32; - let mut x = WIN_W - INSET - total; + let mut x = b.w - INSET - total; for (i, ((kind, param, items, gap, track), w)) in groups.into_iter().zip(widths).enumerate() { if i > 0 { b.rect(BOX_HEADER_RULE, x - 17.0, 11.5, 1.0, 20.0); @@ -842,6 +887,68 @@ impl Controller { 584.0 } + // ------------------------------------------------------------ Field family + + /// Control card of a field window (one row at y): the LFO's Timebase, Rate and Depth + /// (Ring Mod: its modulator), the device's own selector, then its secondary knobs. + /// Returns the window's content height. + fn field_window(&self, d: &Device, def: &'static DeviceDef, b: &mut Builder, y: f32) -> f32 { + let val = |id: &str| def.param(id).map_or(0.0, |p| self.panel_value(d, def, p)); + let rate = if val("sync") >= 0.5 { "rate_sync" } else { "rate" }; + let lfo = || { + vec![ + Item::Pills("sync", vec![("Free", 0.0), ("Sync", 1.0)], "Timebase", 108.0), + Item::Knob(rate, "Rate", 2, 70.0, false), + Item::Knob("depth", "Depth", 2, 70.0, false), + ] + }; + let tail = || { + vec![ + Item::Knob("feedback", "Feedback", 1, 66.0, false), + Item::Knob("width", "Width", 1, 52.0, false), + Item::Knob("mix", "Mix", 1, 52.0, false), + Item::Knob("output_gain", "Output", 1, 52.0, false), + ] + }; + let clusters = match def.id { + "tremolo" => vec![ + lfo(), + vec![Item::Pills("shape", vec![("Sine", 0.0), ("Triangle", 1.0), ("Square", 2.0), ("Saw Down", 3.0)], "Shape", 278.0)], + vec![Item::Knob("stereo_phase", "Stereo Phase", 1, 84.0, false), Item::Knob("mix", "Mix", 1, 52.0, false)], + ], + "autopanner" => vec![ + lfo(), + vec![Item::Pills("shape", vec![("Sine", 0.0), ("Triangle", 1.0), ("Square", 2.0), ("Random", 3.0)], "Shape", 250.0)], + vec![Item::Knob("phase", "Phase", 1, 52.0, false), Item::Knob("mix", "Mix", 1, 52.0, false)], + ], + "chorus" => { + vec![lfo(), vec![Item::Pills("voices", vec![("1", 0.0), ("2", 1.0), ("3", 2.0), ("4", 3.0)], "Voices", 186.0)], tail()] + } + "flanger" => { + vec![lfo(), vec![Item::Pills("mode", vec![("Classic", 0.0), ("Jet", 1.0), ("Thru-Zero", 2.0)], "Mode", 238.0)], tail()] + } + "phaser" => { + vec![lfo(), vec![Item::Pills("stages", vec![("2", 0.0), ("4", 1.0), ("6", 2.0), ("12", 3.0)], "Stages", 186.0)], tail()] + } + _ => { + let idx = def.index_of("modulator").map_or(-1, |i| i as i32); + let shape = def.param("modulator").map(|p| p.format(val("modulator"))).unwrap_or_default(); + vec![ + vec![ + Item::Picker(idx, shape, "Modulator", 118.0, false), + Item::Knob("frequency", "Frequency", 2, 70.0, false), + Item::Knob("spread", "Spread", 1, 60.0, false), + ], + vec![Item::Knob("bias", "Bias", 1, 60.0, false), Item::Knob("rectify", "Rectify", 1, 60.0, false)], + vec![Item::Knob("mix", "Mix", 1, 60.0, false), Item::Knob("output", "Output", 1, 60.0, false)], + ] + } + }; + let row = Row::main(y); + self.win_card(d, def, b, row, clusters.into_iter().map(|c| (c, 14.0)).collect()); + y + row.h + 16.0 + } + // ------------------------------------------------------------ EQs /// Band pills of an EQ header: the selected band lit, bands out of the chain dimmed. @@ -1304,6 +1411,52 @@ mod tests { assert_eq!(names, ["Freq", "Reso", "Drive", "Env", "Attack", "Release", "LFO", "Rate", "Stereo", "Mix"]); } + /// The modulation family: a plotted display with a drag zone, both meters, and one + /// control per parameter on a single card row. + #[test] + fn field_windows_show_the_plot_and_every_control() { + use slint::Model; + for id in ["tremolo", "autopanner", "chorus", "flanger", "phaser", "ring-mod"] { + let (c, did, def) = controller_with(id); + assert!(has_window(def), "{id}"); + let v = view(&c, did, def); + assert!(v.visible && v.w > 0.0 && v.h > 0.0, "{id}"); + assert_eq!(v.meters.row_count(), 2, "{id}: In and Out"); + let mut params = std::collections::HashSet::new(); + for k in v.knobs.iter() { + assert!(k.x >= 0.0 && k.x <= v.w && k.y > 0.0 && k.y < v.h, "{id}: {} outside", k.label); + assert!(params.insert(k.param), "{id}: {} shown twice", k.label); + } + } + let (c, did, def) = controller_with("flanger"); + assert_eq!(knob_names(&view(&c, did, def)), ["Rate", "Depth", "Feedback", "Width", "Mix", "Output"]); + let (c, did, def) = controller_with("ring-mod"); + assert_eq!(knob_names(&view(&c, did, def)), ["Frequency", "Spread", "Bias", "Rectify", "Mix", "Output"]); + } + + /// Cost of rebuilding a field window against its card, per device + /// (`cargo test -p dstudio-app --release bench_field_windows -- --ignored --nocapture`). + #[test] + #[ignore] + fn bench_field_windows() { + let n = 500; + for id in ["tremolo", "autopanner", "chorus", "flanger", "phaser", "ring-mod"] { + let (c, did, def) = controller_with(id); + let d = c.project().device(did).unwrap().clone(); + let t0 = std::time::Instant::now(); + for _ in 0..n { + std::hint::black_box(c.builtin_card(&d, def)); + } + let card = t0.elapsed().as_secs_f64() * 1e6 / n as f64; + let t0 = std::time::Instant::now(); + for _ in 0..n { + std::hint::black_box(view(&c, did, def)); + } + let win = t0.elapsed().as_secs_f64() * 1e6 / n as f64; + println!("{id:<11} card {card:7.1} us window {win:7.1} us"); + } + } + /// Character EQ's lower card shows one section at a time. #[test] fn character_eq_sections_switch_the_lower_card() { diff --git a/crates/dstudio-app/src/device_window_fields.rs b/crates/dstudio-app/src/device_window_fields.rs new file mode 100644 index 00000000..a38fc0cd --- /dev/null +++ b/crates/dstudio-app/src/device_window_fields.rs @@ -0,0 +1,210 @@ +//! Expanded windows of the plotted-field family (View::Field: Tremolo, Auto-Panner, +//! Chorus, Flanger, Phaser, Ring Mod): the display picture and the control card. +//! +//! The picture is the card's own curve model (src/device_fields.rs) asked for its +//! window form (`Input::win`): the window's taller ladders, the time or frequency +//! axis under the plot with its units, and a legend that names every series on +//! screen. It is drawn here in plot-local px; the caption sits in the band above +//! the plot and the rulers in the margins around it. Dragging the plot moves the +//! same two parameters as the card's field (across: Rate or Frequency; up: Depth, +//! Feedback or Bias). + +use crate::controller::Controller; +use crate::device_canvas::{MUTE_TEXT, dashed, fill, path, rgba, stroke, text, white}; +use crate::device_fields::{self, Fill, Mark, Style}; +use crate::device_panel::Z; +use crate::device_window::Kit; +use crate::{PanelCanvas, PanelPath, PanelText, PanelZone}; +use dstudio_core::Device; +use dstudio_core::builtin::{DeviceDef, Field}; +use slint::{Color, ModelRc, VecModel}; +use std::rc::Rc; + +fn model(v: Vec) -> ModelRc { + ModelRc::from(Rc::new(VecModel::from(v))) +} + +/// Inks of the window plots. +const FAINT: f32 = 0.05; +const STRONG: f32 = 0.13; +const INK_LO: f32 = 0.3; +const INK_HI: f32 = 0.92; +const LEGEND_INK: f32 = 0.7; +/// The accent wash under a motion curve. +const WASH: f32 = 0.28; +/// Series widths: the subject, and a dashed second series. +const W_MAIN: f32 = 1.75; +const W_DASH: f32 = 1.25; +/// Caption band: the baseline 16.73 pt under the display's top edge. +const CAPTION_BASELINE: f32 = 16.73; +const CAPTION_GAP: f32 = 12.0; + +/// Window caption of each field device (the card's caption where it has one). +fn caption(def: &DeviceDef, f: &Field) -> &'static str { + match def.id { + "autopanner" => "Pan", + "ring-mod" => "Modulation", + _ => f.caption, + } +} + +/// Width of 12 pt bold chrome text (the caption's label). +fn label_w(t: &str) -> f32 { + crate::text_measure::value_width(t) * 1.2 +} + +impl Controller { + /// The display of a field window: caption, rulers, axis row, wash, series and legend, + /// with a drag zone over the plot. + pub(crate) fn field_window_canvas(&self, d: &Device, def: &'static DeviceDef, f: Field, k: &Kit, accent: Color) -> PanelCanvas { + let (_, _, dw, dh) = k.display; + let (l, t, r, b) = k.plot; + let (pw, ph) = ((dw - l - r) * Z, (dh - t - b) * Z); + let get = |id: &str| def.param(id).map_or(0.0, |p| self.panel_value(d, def, p)); + let input = device_fields::Input { + get: &get, + bpm: self.project().transport.bpm as f32, + n: (pw.round() as usize).max(64), + cycles: None, + win: true, + }; + let Some(plot) = device_fields::plot(f.plot, &input) else { return PanelCanvas::default() }; + let mut paths: Vec = Vec::new(); + let mut texts: Vec = Vec::new(); + let at = |x: f32, y: f32| (x * pw, y.clamp(0.0, 1.0) * ph); + let points = |ys: &[f32]| -> Vec<(f32, f32)> { + ys.iter().enumerate().map(|(i, y)| at(i as f32 / (ys.len() - 1).max(1) as f32, *y)).collect() + }; + + // Caption: the name and the picture's one value, on the band above the plot. + let base = (CAPTION_BASELINE - t) * Z; + let label = caption(def, &f); + let lx = if def.id == "ring-mod" { 0.0 } else { 2.0 * Z }; + texts.push(PanelText { weight: 700, ..text(lx, base - 4.4 * Z, 140.0 * Z, label, MUTE_TEXT, 12.0 * Z, 0) }); + let vx = lx + (label_w(label) + CAPTION_GAP) * Z; + texts.push(text(vx, base - 4.7 * Z, 260.0 * Z, plot.readout.clone(), white(INK_HI), 13.0 * Z, 0)); + + // The ladder: a rule per rung (the rest line stronger), numerals in the left margin. + let response = plot.axis.start == "Hz"; + let rest = plot.rest; + let (first, last) = (plot.ticks.first().map(|t| t.0), plot.ticks.last().map(|t| t.0)); + for (y, label) in &plot.ticks { + let py = (y * ph).round() + 0.5; + let is_rest = rest.is_some_and(|r| (r - y).abs() < 1e-4); + // A response ladder leaves its end rungs to the frame's own edges. + let edge = response && (Some(*y) == first || Some(*y) == last); + if !edge { + paths.push(stroke(format!("M0 {py:.1} L{pw:.1} {py:.1}"), white(if is_rest { STRONG } else { FAINT }), 1.0)); + } + if !label.is_empty() { + let gap = if response { 6.0 } else { 8.0 }; + texts.push(text(-gap * Z, y * ph, 60.0 * Z, label.clone(), white(INK_LO), 11.0 * Z, 2)); + } + } + if response { + for e in [0.5, ph.round() - 0.5] { + paths.push(stroke(format!("M0 {e:.1} L{pw:.1} {e:.1}"), white(FAINT), 1.0)); + } + } + + // The axis row: a rule per tick, its numeral under the plot, the units at its ends. + let ring = k.plot.3 < 40.0; + let (num_y, num_size) = if ring { + (ph + 13.0 * Z, 11.0) + } else if response { + (ph + 12.0 * Z, 10.0) + } else { + (ph + 15.5 * Z, 11.0) + }; + let unit_w = crate::text_measure::value_width(&plot.axis.end) * Z; + for (x, label, strong) in &plot.axis.ticks { + let px = (x * pw).round() + 0.5; + paths.push(stroke(format!("M{px:.1} 0 L{px:.1} {ph:.1}"), white(if *strong { STRONG } else { FAINT }), 1.0)); + if label.is_empty() { + continue; + } + // Ring Mod drops a numeral that would run into the unit at the row's end. + let half = crate::text_measure::value_width(label) * 1.1 * Z / 2.0; + if ring && px + half > pw - unit_w - 10.0 * Z { + continue; + } + texts.push(text(px, num_y, 80.0 * Z, label.clone(), white(INK_LO), num_size * Z, 1)); + } + let unit_y = num_y - if response { 0.0 } else { 0.5 * Z }; + if !plot.axis.foot.is_empty() { + texts.push(text(-8.0 * Z, unit_y, 60.0 * Z, plot.axis.foot.clone(), white(INK_LO), 10.0 * Z, 2)); + } + if !plot.axis.start.is_empty() { + texts.push(text(0.0, unit_y, 30.0 * Z, plot.axis.start.clone(), white(INK_LO), 10.0 * Z, 0)); + } + if !plot.axis.end.is_empty() { + texts.push(text(pw, unit_y, 30.0 * Z, plot.axis.end.clone(), white(INK_LO), 10.0 * Z, 2)); + } + + // The wash between the subject and the rest line, then the dashed series, then the subject. + let main = plot.traces.first().map(|t| points(&t.ys)).unwrap_or_default(); + if let (Fill::ToRest, Some(r)) = (plot.fill, rest) + && main.len() > 1 + { + let ry = r * ph; + paths.push(fill( + format!("{} L{:.1} {ry:.1} L{:.1} {ry:.1} Z", path(&main), main[main.len() - 1].0, main[0].0), + rgba(accent, WASH), + )); + } + for tr in plot.traces.iter().skip(1) { + if let Style::Dash { on, off, alpha } = tr.style { + paths.push(stroke(dashed(&points(&tr.ys), on * Z, off * Z), white(alpha), W_DASH * Z)); + } + } + paths.push(stroke(path(&main), white(1.0), W_MAIN * Z)); + + // Legend: a glyph and a name per series on screen. + let (glyph, gap, entry_gap) = (16.0 * Z, 6.0 * Z, 14.0 * Z); + let widths: Vec = plot.legend.iter().map(|(_, n)| crate::text_measure::value_width(n) * Z).collect(); + let (mut x, y, ink) = if plot.axis.legend_in_caption { + let total: f32 = widths.iter().map(|w| glyph + gap + w).sum::() + entry_gap * widths.len().saturating_sub(1) as f32; + (pw - total, base - 3.5 * Z, MUTE_TEXT) + } else { + (0.0, ph + 31.0 * Z, white(LEGEND_INK)) + }; + for ((mark, name), w) in plot.legend.iter().zip(widths) { + match mark { + Mark::Band => { + paths + .push(fill(format!("M{x:.1} {:.1} h{glyph:.1} v{:.1} h{:.1} Z", y - 4.0 * Z, 8.0 * Z, -glyph), rgba(accent, WASH))); + } + Mark::Line(Style::Solid) => paths.push(stroke(format!("M{x:.1} {y:.1} L{:.1} {y:.1}", x + glyph), white(1.0), W_MAIN * Z)), + &Mark::Line(Style::Dash { on, off, alpha }) => { + paths.push(stroke(dashed(&[(x, y), (x + glyph, y)], on * Z, off * Z), white(alpha), W_DASH * Z)); + } + } + texts.push(text(x + glyph + gap, y, w + 10.0 * Z, name.clone(), ink, 10.0 * Z, 0)); + x += glyph + gap + w + entry_gap; + } + + // Drag the plot: across the card field's horizontal parameter, up its vertical one. + let axis = |ids: &[&'static str]| Self::field_axis(d, def, ids).map_or(-1, |i| i as i32); + let zone = PanelZone { + x: 0.0, + y: 0.0, + w: pw, + h: ph, + param_x: axis(f.x), + param_y: axis(f.y), + rate_x: 1.0 / pw.max(1.0), + rate_y: 1.0 / ph.max(1.0), + }; + PanelCanvas { + visible: true, + w: pw, + h: ph + b * Z, + paths: model(paths), + texts: model(texts), + zones: model(vec![zone]), + label: label.into(), + value: plot.readout.into(), + ..Default::default() + } + } +} diff --git a/crates/dstudio-app/src/main.rs b/crates/dstudio-app/src/main.rs index 52642a2d..7f4ffcf4 100644 --- a/crates/dstudio-app/src/main.rs +++ b/crates/dstudio-app/src/main.rs @@ -55,6 +55,7 @@ mod device_mod; mod device_panel; mod device_views; mod device_window; +mod device_window_fields; mod devices; mod devminimap; mod dialogs; diff --git a/crates/dstudio-app/ui/device_window.slint b/crates/dstudio-app/ui/device_window.slint index 93d17837..4bc3ee50 100644 --- a/crates/dstudio-app/ui/device_window.slint +++ b/crates/dstudio-app/ui/device_window.slint @@ -223,7 +223,7 @@ component WinMeterView inherits Rectangle { property bar-w: (root.m.w - 1px) / 2; property main-h: root.m.h - root.m.zero-h; Text { - x: root.m.x - 19px * zm; y: root.m.y - 22px * zm; width: root.m.w + 38px * zm; height: 16px * zm; + x: root.m.label-x - 27px * zm; y: root.m.y - 22px * zm; width: 54px * zm; height: 16px * zm; text: root.m.label; color: WinStyle.mute; font-size: 12px * zm; font-weight: 700; letter-spacing: -0.04 * 12px * zm; horizontal-alignment: center; vertical-alignment: center; } @@ -251,7 +251,7 @@ component WinMeterView inherits Rectangle { x: root.m.x + root.m.w - 3px * zm; y: root.m.y + t.y - 0.5px; width: 6px * zm; height: 1px; background: #ffffff24; } Text { - x: root.m.x - 19px * zm; y: root.m.y + root.m.h + 6px * zm; width: root.m.w + 38px * zm; height: 16px * zm; + x: root.m.label-x - 27px * zm; y: root.m.y + root.m.h + 6px * zm; width: 54px * zm; height: 16px * zm; text: root.m.value; color: WinStyle.text; font-size: 12px * zm; font-weight: 600; letter-spacing: -0.04 * 12px * zm; horizontal-alignment: center; vertical-alignment: center; } diff --git a/crates/dstudio-app/ui/studio.slint b/crates/dstudio-app/ui/studio.slint index e08031aa..df69eaa7 100644 --- a/crates/dstudio-app/ui/studio.slint +++ b/crates/dstudio-app/ui/studio.slint @@ -239,7 +239,8 @@ export struct WinBox { kind: int, x: length, y: length, w: length, h: length } // In / Out meter column: the bar's box (+12 dB at the top, -50 dB at the foot; zero-h down // to 0 dB), the left and right levels and holds (0..1 of the -50..0 dB part), the overs // light, the label over it and the readout under it. -export struct WinMeter { x: length, y: length, w: length, h: length, zero-h: length, l: float, r: float, hold-l: float, hold-r: float, clip: bool, label: string, value: string } +// label-x: centre of the label and readout over / under the column. +export struct WinMeter { label-x: length, x: length, y: length, w: length, h: length, zero-h: length, l: float, r: float, hold-l: float, hold-r: float, clip: bool, label: string, value: string } export struct WinView { visible: bool, w: length, h: length, diff --git a/docs/devices.md b/docs/devices.md index 3091be7e..78a2ffe8 100644 --- a/docs/devices.md +++ b/docs/devices.md @@ -62,12 +62,17 @@ flowchart LR returns the frame's sequence number so a poll can skip unchanged frames. - **Expanded windows.** The window button on a card opens the device's expanded window (`device_window.rs`, `ui/device_window.slint`) when the - device has one (`device_window::has_window`; Auto Filter, Channel EQ and - Character EQ so far), otherwise the card itself in a window. A window is a - 960 pt wide face: a top bar (power, presets, the device's header pills), a + device has one (`device_window::has_window`; Auto Filter, Channel EQ, + Character EQ and the plotted-field family: Tremolo, Auto-Panner, Chorus, + Flanger, Phaser and Ring Mod), otherwise the card itself in a window. A + window is a face 960 pt wide (Ring Mod 860): a top bar (power, presets, the device's header pills), a large display (the card's canvas drawn at window size with its axis and legend), In / Out meters, and rows of controls laid out with the same - gutter rule (fixed clusters, even gaps, a rule in each inner gap). The + gutter rule (fixed clusters, even gaps, a rule in each inner gap). A field + window's display (`device_window_fields.rs`) asks the card's curve model in + `device_fields.rs` for its window form (`Input::win`): a taller ladder, a + time or frequency axis with units under the plot, and a legend naming each + series; dragging the plot moves the card field's two parameters. The meters read `se_builtin_set_metering` / `se_builtin_levels` (`Engine::builtin_levels(id, &mut [f32; 4])`): while a window is open the audio thread keeps the input and output peak of each block, and the app