Skip to main content

tui_chart/
instruments.rs

1//! Instrument-style charts: [`Oscilloscope`], [`Spectrum`], [`DotMatrix`],
2//! [`RadarScope`] and [`HexMap`].
3//!
4//! The widgets are stateless: animated ones take a `phase` (`0..1`, wrapping)
5//! that the caller advances every frame.
6
7#![allow(
8    clippy::cast_possible_truncation,
9    clippy::cast_precision_loss,
10    clippy::cast_sign_loss,
11    clippy::cast_possible_wrap,
12    clippy::many_single_char_names,
13    clippy::similar_names,
14    clippy::too_many_lines
15)]
16
17use crate::braille::{polar, Braille};
18use crate::theme::{self, Theme};
19use crate::util::{darken, mix};
20use ratatui::{
21    buffer::Buffer,
22    layout::Rect,
23    style::{Color, Style},
24    widgets::Block,
25};
26use std::f64::consts::TAU;
27
28// ───────────────────────────── pure helpers ─────────────────────────────
29
30/// One heartbeat-shaped period (`-1..=1`) for `x` in `0..1`: P wave, QRS spike, T wave.
31pub fn ecg_beat(x: f64) -> f64 {
32    let g = |c: f64, w: f64, a: f64| a * (-((x - c) / w).powi(2)).exp();
33    g(0.18, 0.04, 0.18)
34        + g(0.36, 0.012, -0.22)
35        + g(0.39, 0.012, 1.0)
36        + g(0.42, 0.012, -0.35)
37        + g(0.62, 0.06, 0.28)
38}
39
40/// Brightness `0..=1` of a radar blip at turn-fraction `blip` while the sweep is at
41/// `sweep`: full as the beam passes, fading over one revolution.
42pub fn blip_alpha(sweep: f64, blip: f64) -> f64 {
43    let since = (sweep - blip).rem_euclid(1.0);
44    (1.0 - since).powi(2)
45}
46
47/// Centre of hex `(row, col)` for a pointy-top grid with circumradius `s`.
48pub fn hex_center(row: usize, col: usize, s: f64) -> (f64, f64) {
49    let w = 3f64.sqrt() * s;
50    let off = if row % 2 == 1 { w / 2.0 } else { 0.0 };
51    (w / 2.0 + col as f64 * w + off, s + row as f64 * 1.5 * s)
52}
53
54/// Grid size `(width, height)` of `rows × cols` hexes of circumradius `s`.
55pub fn hex_extent(rows: usize, cols: usize, s: f64) -> (f64, f64) {
56    let w = 3f64.sqrt() * s;
57    (w * (cols as f64 + 0.5), s * (1.5 * rows as f64 + 0.5))
58}
59
60/// Whether `(dx, dy)` (relative to the center) lies inside a pointy-top hex of circumradius `r`.
61fn in_hex(dx: f64, dy: f64, r: f64) -> bool {
62    let (dx, dy) = (dx.abs(), dy.abs());
63    dx <= 3f64.sqrt() / 2.0 * r && dy <= r - dx / 3f64.sqrt()
64}
65
66/// Animated bar value: `v` modulated by a per-bar sine at time `t`.
67pub fn jitter(v: f64, i: usize, t: f64) -> f64 {
68    let f = 1.7 + i as f64 * 0.37;
69    (v * (0.65 + 0.35 * (t * f + i as f64).sin())).clamp(0.0, 1.0)
70}
71
72fn unit(v: f64) -> f64 {
73    if v.is_finite() {
74        v.clamp(0.0, 1.0)
75    } else {
76        0.0
77    }
78}
79
80/// Colors shared by the instruments.
81struct Pal {
82    primary: Color,
83    danger: Color,
84    ok: Color,
85    warn: Color,
86    grid: Color,
87    fg: Color,
88}
89
90fn pal(theme: &Option<Theme>, color: Option<Color>) -> Pal {
91    match theme {
92        Some(t) => Pal {
93            primary: color.unwrap_or(t.accent),
94            danger: t.bear,
95            ok: t.bull,
96            warn: t.neutral,
97            grid: t.grid,
98            fg: t.foreground,
99        },
100        None => Pal {
101            primary: color.unwrap_or(Color::Cyan),
102            danger: Color::Red,
103            ok: Color::Green,
104            warn: Color::Yellow,
105            grid: Color::DarkGray,
106            fg: Color::White,
107        },
108    }
109}
110
111fn put(buf: &mut Buffer, x: u16, y: u16, ch: char, style: Style) {
112    if let Some(c) = buf.cell_mut((x, y)) {
113        c.set_char(ch).set_style(style);
114    }
115}
116
117/// Declares the shared `theme` / `base_style` / `block` builders and trait impls.
118macro_rules! instrument_common {
119    ($t:ty) => {
120        impl $t {
121            theme_setter!(
122                /// Apply a [`Theme`]; an explicit `.color(..)` wins.
123                theme
124            );
125            base_style_setter!(base);
126            block_setter!(block, 'static);
127        }
128        widget_impls!($t);
129        #[cfg(feature = "theme")]
130        impl tui_nuances::Themed for $t {
131            fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
132                self.theme(theme)
133            }
134        }
135    };
136}
137
138// ────────────────────────────── Oscilloscope ──────────────────────────────
139
140/// Phosphor-style trace over a divided graticule. Samples are `-1..=1`.
141///
142/// # Example
143///
144/// ```
145/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
146/// use tui_chart::Oscilloscope;
147///
148/// let scope = Oscilloscope::ecg(3, 240).phase(0.25);
149/// let area = Rect::new(0, 0, 60, 16);
150/// let mut buf = Buffer::empty(area);
151/// scope.render(area, &mut buf);
152/// ```
153#[derive(Debug, Clone, Default)]
154pub struct Oscilloscope {
155    samples: Vec<f64>,
156    phase: f64,
157    grid: bool,
158    color: Option<Color>,
159    theme: Option<Theme>,
160    base: Option<Style>,
161    block: Option<Block<'static>>,
162}
163
164impl Oscilloscope {
165    /// A trace through `samples` (`-1..=1`; other values are clamped).
166    pub fn new(samples: impl IntoIterator<Item = f64>) -> Self {
167        Self {
168            samples: samples.into_iter().collect(),
169            phase: 0.0,
170            grid: true,
171            ..Self::default()
172        }
173    }
174
175    /// A heartbeat: `beats` periods over `n` samples.
176    pub fn ecg(beats: usize, n: usize) -> Self {
177        let (beats, n) = (beats.max(1) as f64, n.max(2));
178        Self::new((0..n).map(|i| ecg_beat((i as f64 / n as f64 * beats).fract())))
179    }
180
181    /// A sum of sines: `(frequency, amplitude)` partials over `n` samples.
182    pub fn wave(partials: &[(f64, f64)], n: usize) -> Self {
183        let n = n.max(2);
184        let norm = partials.iter().map(|p| p.1.abs()).sum::<f64>().max(1e-3);
185        Self::new((0..n).map(|i| {
186            let x = i as f64 / n as f64;
187            partials
188                .iter()
189                .map(|&(f, a)| a * (x * f * TAU).sin())
190                .sum::<f64>()
191                / norm
192        }))
193    }
194
195    setter!(
196        /// Scroll position `0..1` (wraps): the trace is shifted by this fraction.
197        phase: f64
198    );
199    setter!(
200        /// Show the graticule (default on).
201        grid: bool
202    );
203    opt_setter!(
204        /// Trace color.
205        color: Color
206    );
207
208    fn render_into(&self, area: Rect, buf: &mut Buffer) {
209        let area = area.intersection(buf.area);
210        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
211        if inner.is_empty() {
212            return;
213        }
214        let p = pal(&self.theme, self.color);
215        let mut g = Braille::new(inner.width, inner.height);
216        let (w, h) = (g.dots_w(), g.dots_h());
217        if self.grid {
218            let major = mix(p.grid, p.fg, 0.4);
219            for i in 0..=10 {
220                let x = ((w - 1.0) * f64::from(i) / 10.0).round();
221                let (col, step) = if i == 5 { (major, 1) } else { (p.grid, 4) };
222                let mut y = 0.0;
223                while y < h {
224                    g.plot(x, y, col, 0);
225                    y += f64::from(step);
226                }
227            }
228            for i in 0..=8 {
229                let y = ((h - 1.0) * f64::from(i) / 8.0).round();
230                let (col, step) = if i == 4 { (major, 1) } else { (p.grid, 4) };
231                let mut x = 0.0;
232                while x < w {
233                    g.plot(x, y, col, 0);
234                    x += f64::from(step);
235                }
236            }
237        }
238        let n = self.samples.len();
239        if n >= 2 {
240            let shift = (self.phase.rem_euclid(1.0) * n as f64) as usize;
241            let pts: Vec<(f64, f64)> = (0..n)
242                .map(|i| {
243                    let s = self.samples[(i + shift) % n];
244                    let s = if s.is_finite() {
245                        s.clamp(-1.0, 1.0)
246                    } else {
247                        0.0
248                    };
249                    (
250                        (w - 1.0) * i as f64 / (n - 1) as f64,
251                        (h - 1.0) / 2.0 - s * (h - 1.0) * 0.45,
252                    )
253                })
254                .collect();
255            let halo = darken(p.primary, 0.6);
256            for pair in pts.windows(2) {
257                for dy in [-1.0, 1.0] {
258                    g.line(
259                        (pair[0].0, pair[0].1 + dy),
260                        (pair[1].0, pair[1].1 + dy),
261                        halo,
262                        1,
263                    );
264                }
265                g.line(pair[0], pair[1], p.primary, 2);
266            }
267        }
268        g.blit(inner, buf);
269    }
270}
271
272instrument_common!(Oscilloscope);
273
274// ──────────────────────────────── Spectrum ────────────────────────────────
275
276const V_EIGHTHS: [char; 9] = [' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
277
278/// Equalizer bars (`0..=1`) built from segments with zone colors and peak caps.
279///
280/// # Example
281///
282/// ```
283/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
284/// use tui_chart::Spectrum;
285///
286/// let s = Spectrum::new([0.2, 0.8, 0.5, 0.95, 0.4]).peaks([0.3, 0.9, 0.6, 1.0, 0.5]);
287/// let area = Rect::new(0, 0, 30, 10);
288/// let mut buf = Buffer::empty(area);
289/// s.render(area, &mut buf);
290/// ```
291#[derive(Debug, Clone, Default)]
292pub struct Spectrum {
293    values: Vec<f64>,
294    peaks: Vec<f64>,
295    zones: bool,
296    color: Option<Color>,
297    theme: Option<Theme>,
298    base: Option<Style>,
299    block: Option<Block<'static>>,
300}
301
302impl Spectrum {
303    /// Bars with `values` in `0..=1`.
304    pub fn new(values: impl IntoIterator<Item = f64>) -> Self {
305        Self {
306            values: values.into_iter().collect(),
307            zones: true,
308            ..Self::default()
309        }
310    }
311
312    /// Peak-hold caps (`0..=1`), one per bar.
313    pub fn peaks(mut self, peaks: impl IntoIterator<Item = f64>) -> Self {
314        self.peaks = peaks.into_iter().collect();
315        self
316    }
317
318    setter!(
319        /// Color the upper segments green / yellow / red (default on).
320        zones: bool
321    );
322    opt_setter!(
323        /// Bar color when zones are off.
324        color: Color
325    );
326
327    fn render_into(&self, area: Rect, buf: &mut Buffer) {
328        let area = area.intersection(buf.area);
329        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
330        let n = self.values.len();
331        if inner.is_empty() || n == 0 {
332            return;
333        }
334        let p = pal(&self.theme, self.color);
335        let width = usize::from(inner.width);
336        let (mut bw, mut gap) = (((width + 1) / n).saturating_sub(1).max(1), 1);
337        if n * bw + (n - 1) * gap > width {
338            bw = 1;
339            gap = usize::from(n * 2 - 1 <= width);
340        }
341        let shown = n.min((width + gap) / (bw + gap));
342        let used = shown * bw + shown.saturating_sub(1) * gap;
343        let x0 = inner.x + ((width - used) / 2) as u16;
344        let rows = usize::from(inner.height);
345        let zone_color = |frac: f64| {
346            if !self.zones {
347                p.primary
348            } else if frac < 0.6 {
349                p.ok
350            } else if frac < 0.85 {
351                p.warn
352            } else {
353                p.danger
354            }
355        };
356        for (i, v) in self.values.iter().take(shown).enumerate() {
357            let eighths = (unit(*v) * rows as f64 * 8.0).round() as i64;
358            let peak_row = self
359                .peaks
360                .get(i)
361                .map(|p| ((unit(*p) * rows as f64).ceil() as usize).clamp(1, rows) - 1);
362            let bx = x0 + (i * (bw + gap)) as u16;
363            for r in 0..rows {
364                let frac = (r as f64 + 0.5) / rows as f64;
365                let col = zone_color(frac);
366                let rem = eighths - r as i64 * 8;
367                let y = inner.bottom() - 1 - r as u16;
368                let (ch, style) = if rem >= 8 {
369                    ('█', Style::default().fg(col))
370                } else if rem > 0 {
371                    (V_EIGHTHS[rem as usize], Style::default().fg(col))
372                } else if peak_row == Some(r) && unit(self.peaks[i]) > 0.0 {
373                    ('▀', Style::default().fg(col))
374                } else {
375                    ('░', Style::default().fg(darken(col, 0.75)))
376                };
377                for dx in 0..bw {
378                    put(buf, bx + dx as u16, y, ch, style);
379                }
380            }
381        }
382    }
383}
384
385instrument_common!(Spectrum);
386
387// ─────────────────────────────── DotMatrix ────────────────────────────────
388
389/// LED dot matrix: one column of dots per value (`0..=1`), lit from the bottom.
390///
391/// # Example
392///
393/// ```
394/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
395/// use tui_chart::DotMatrix;
396///
397/// let m = DotMatrix::new([0.1, 0.4, 0.9, 0.6]).rows(8);
398/// let area = Rect::new(0, 0, 20, 8);
399/// let mut buf = Buffer::empty(area);
400/// m.render(area, &mut buf);
401/// ```
402#[derive(Debug, Clone, Default)]
403pub struct DotMatrix {
404    values: Vec<f64>,
405    rows: Option<usize>,
406    color: Option<Color>,
407    theme: Option<Theme>,
408    base: Option<Style>,
409    block: Option<Block<'static>>,
410}
411
412impl DotMatrix {
413    /// Columns with `values` in `0..=1`.
414    pub fn new(values: impl IntoIterator<Item = f64>) -> Self {
415        Self {
416            values: values.into_iter().collect(),
417            ..Self::default()
418        }
419    }
420
421    /// Number of dot rows (default: the area height; at most the area height).
422    pub fn rows(mut self, rows: usize) -> Self {
423        self.rows = Some(rows.max(2));
424        self
425    }
426
427    opt_setter!(
428        /// Dot color.
429        color: Color
430    );
431
432    fn render_into(&self, area: Rect, buf: &mut Buffer) {
433        let area = area.intersection(buf.area);
434        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
435        let n = self.values.len();
436        if inner.is_empty() || n == 0 {
437            return;
438        }
439        let p = pal(&self.theme, self.color);
440        let width = usize::from(inner.width);
441        let pitch = if n * 2 - 1 <= width { 2 } else { 1 };
442        let shown = n.min(width.div_ceil(pitch));
443        let used = (shown - 1) * pitch + 1;
444        let x0 = inner.x + ((width - used) / 2) as u16;
445        let rows = self
446            .rows
447            .unwrap_or(usize::MAX)
448            .min(usize::from(inner.height));
449        let dim = Style::default().fg(darken(p.grid, 0.2));
450        let on = Style::default().fg(p.primary);
451        let soft = Style::default().fg(mix(p.grid, p.primary, 0.55));
452        for (i, v) in self.values.iter().take(shown).enumerate() {
453            let f = unit(*v);
454            for k in 0..rows {
455                let cov = (f * rows as f64 - k as f64).clamp(0.0, 1.0);
456                let (ch, st) = if cov >= 0.99 {
457                    ('●', on)
458                } else if cov > 0.0 {
459                    ('•', soft)
460                } else {
461                    ('·', dim)
462                };
463                put(
464                    buf,
465                    x0 + (i * pitch) as u16,
466                    inner.bottom() - 1 - k as u16,
467                    ch,
468                    st,
469                );
470            }
471        }
472    }
473}
474
475instrument_common!(DotMatrix);
476
477// ─────────────────────────────── RadarScope ───────────────────────────────
478
479/// A contact on a [`RadarScope`].
480#[derive(Debug, Clone, Copy, PartialEq)]
481#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
482pub struct Blip {
483    /// Bearing in turns: `0` = up, clockwise, wraps.
484    pub bearing: f64,
485    /// Distance from the center, `0..=1` of the radius.
486    pub range: f64,
487}
488
489impl Blip {
490    /// A blip at `bearing` (turns) and `range` (`0..=1`).
491    pub fn new(bearing: f64, range: f64) -> Self {
492        Self { bearing, range }
493    }
494}
495
496/// Radar screen: range rings, a rotating beam with a fading wedge and blips
497/// that light up as the beam passes.
498///
499/// # Example
500///
501/// ```
502/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
503/// use tui_chart::{Blip, RadarScope};
504///
505/// let scope = RadarScope::new([Blip::new(0.1, 0.6), Blip::new(0.7, 0.3)]).phase(0.2);
506/// let area = Rect::new(0, 0, 40, 20);
507/// let mut buf = Buffer::empty(area);
508/// scope.render(area, &mut buf);
509/// ```
510#[derive(Debug, Clone, Default)]
511pub struct RadarScope {
512    blips: Vec<Blip>,
513    phase: f64,
514    fade: bool,
515    color: Option<Color>,
516    theme: Option<Theme>,
517    base: Option<Style>,
518    block: Option<Block<'static>>,
519}
520
521impl RadarScope {
522    /// A scope showing `blips`.
523    pub fn new(blips: impl IntoIterator<Item = Blip>) -> Self {
524        Self {
525            blips: blips.into_iter().collect(),
526            phase: 0.12,
527            fade: true,
528            ..Self::default()
529        }
530    }
531
532    setter!(
533        /// Beam position in turns (`0` = up, clockwise, wraps).
534        phase: f64
535    );
536    setter!(
537        /// Fade blips with the beam (default on); off keeps them fully lit.
538        fade: bool
539    );
540    opt_setter!(
541        /// Beam and ring color.
542        color: Color
543    );
544
545    fn render_into(&self, area: Rect, buf: &mut Buffer) {
546        let area = area.intersection(buf.area);
547        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
548        if inner.is_empty() {
549            return;
550        }
551        let p = pal(&self.theme, self.color);
552        let mut g = Braille::new(inner.width, inner.height);
553        let (w, h) = (g.dots_w(), g.dots_h());
554        let c = (w / 2.0, h / 2.0);
555        let r = w.min(h) / 2.0 - 1.0;
556        if r < 4.0 {
557            return;
558        }
559        for i in 1..=4 {
560            let ro = r * f64::from(i) / 4.0;
561            g.ring(c, (ro - 0.6, ro), (0.0, 1.0), |_| Some((p.grid, 0)));
562        }
563        for q in 0..4 {
564            g.line(c, polar(c.0, c.1, r, f64::from(q) / 4.0), p.grid, 0);
565        }
566        let tick = darken(p.primary, 0.45);
567        for i in 0..36 {
568            let a = f64::from(i) / 36.0;
569            let len = if i % 3 == 0 { 5.0 } else { 2.5 };
570            g.line(polar(c.0, c.1, r, a), polar(c.0, c.1, r - len, a), tick, 1);
571        }
572        let sweep = self.phase.rem_euclid(1.0);
573        let steps = 56;
574        for k in 0..steps {
575            let a = sweep - 0.22 * f64::from(k) / f64::from(steps);
576            let t = 1.0 - f64::from(k) / f64::from(steps);
577            g.line(
578                c,
579                polar(c.0, c.1, r, a),
580                darken(p.primary, 1.0 - 0.5 * t * t),
581                2,
582            );
583        }
584        g.line(c, polar(c.0, c.1, r, sweep), p.primary, 3);
585        for b in &self.blips {
586            let a = if self.fade {
587                blip_alpha(sweep, b.bearing.rem_euclid(1.0))
588            } else {
589                1.0
590            };
591            if a < 0.04 {
592                continue;
593            }
594            let (x, y) = polar(c.0, c.1, r * unit(b.range), b.bearing);
595            let col = darken(p.danger, 1.0 - a);
596            for dy in -1..=1 {
597                for dx in -1..=1 {
598                    g.plot(x + f64::from(dx), y + f64::from(dy), col, 4);
599                }
600            }
601        }
602        g.plot(c.0, c.1, p.primary, 5);
603        g.blit(inner, buf);
604    }
605}
606
607instrument_common!(RadarScope);
608
609// ─────────────────────────────────── HexMap ───────────────────────────────
610
611/// Honeycomb heat map: `cols` hexes per row, each colored by its value (`0..=1`).
612///
613/// # Example
614///
615/// ```
616/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
617/// use tui_chart::HexMap;
618///
619/// let m = HexMap::new(6, (0..24).map(|i| f64::from(i) / 23.0));
620/// let area = Rect::new(0, 0, 40, 16);
621/// let mut buf = Buffer::empty(area);
622/// m.render(area, &mut buf);
623/// ```
624#[derive(Debug, Clone, Default)]
625pub struct HexMap {
626    values: Vec<f64>,
627    cols: usize,
628    phase: Option<f64>,
629    color: Option<Color>,
630    theme: Option<Theme>,
631    base: Option<Style>,
632    block: Option<Block<'static>>,
633}
634
635impl HexMap {
636    /// A honeycomb with `cols` hexes per row, filled row by row from `values`.
637    pub fn new(cols: usize, values: impl IntoIterator<Item = f64>) -> Self {
638        Self {
639            values: values.into_iter().collect(),
640            cols: cols.max(1),
641            ..Self::default()
642        }
643    }
644
645    /// Pulse the cells with a phase (`0..1`, wraps); `None` is static.
646    pub fn phase(mut self, phase: f64) -> Self {
647        self.phase = Some(phase);
648        self
649    }
650
651    opt_setter!(
652        /// Color of hot cells.
653        color: Color
654    );
655
656    fn render_into(&self, area: Rect, buf: &mut Buffer) {
657        let area = area.intersection(buf.area);
658        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
659        if inner.is_empty() || self.values.is_empty() {
660            return;
661        }
662        let p = pal(&self.theme, self.color);
663        let mut g = Braille::new(inner.width, inner.height);
664        let (w, h) = (g.dots_w(), g.dots_h());
665        let rows = self.values.len().div_ceil(self.cols);
666        let s = (w / (3f64.sqrt() * (self.cols as f64 + 0.5))).min(h / (1.5 * rows as f64 + 0.5));
667        if s < 2.0 {
668            return;
669        }
670        let (gw, gh) = hex_extent(rows, self.cols, s);
671        let (ox, oy) = ((w - gw) / 2.0, (h - gh) / 2.0);
672        let base = mix(Color::Black, p.grid, 0.5);
673        for (i, v) in self.values.iter().enumerate() {
674            let (row, col) = (i / self.cols, i % self.cols);
675            let mut v = unit(*v);
676            if let Some(ph) = self.phase {
677                v = (v * (0.75 + 0.25 * (ph * TAU + i as f64 * 0.9).sin())).clamp(0.0, 1.0);
678            }
679            let color = if v > 0.8 {
680                mix(p.primary, p.danger, (v - 0.8) / 0.2)
681            } else {
682                mix(base, p.primary, v / 0.8)
683            };
684            let (cx, cy) = hex_center(row, col, s);
685            let (cx, cy) = (cx + ox, cy + oy);
686            let r = s * 0.9;
687            for py in (cy - r).floor() as i64..=(cy + r).ceil() as i64 {
688                for px in (cx - r).floor() as i64..=(cx + r).ceil() as i64 {
689                    if in_hex(px as f64 + 0.5 - cx, py as f64 + 0.5 - cy, r) {
690                        g.plot(px as f64, py as f64, color, 1);
691                    }
692                }
693            }
694        }
695        g.blit(inner, buf);
696    }
697}
698
699instrument_common!(HexMap);
700
701#[cfg(test)]
702mod tests {
703    use super::*;
704    use ratatui::widgets::Widget;
705
706    fn draw(w: impl Widget, width: u16, height: u16) -> Buffer {
707        let a = Rect::new(0, 0, width, height);
708        let mut b = Buffer::empty(a);
709        w.render(a, &mut b);
710        b
711    }
712
713    fn painted(b: &Buffer) -> usize {
714        b.content().iter().filter(|c| c.symbol() != " ").count()
715    }
716
717    #[test]
718    fn ecg_peaks_at_the_qrs_spike() {
719        assert!(ecg_beat(0.39) > 0.9);
720        assert!(ecg_beat(0.9).abs() < 0.05);
721    }
722
723    #[test]
724    fn blip_alpha_is_full_at_the_beam_and_fades() {
725        assert!((blip_alpha(0.5, 0.5) - 1.0).abs() < 1e-12);
726        assert!(blip_alpha(0.5, 0.4) > blip_alpha(0.5, 0.2));
727        assert!(blip_alpha(0.1, 0.9) > 0.0);
728    }
729
730    #[test]
731    fn hex_geometry() {
732        let (x, y) = hex_center(0, 0, 10.0);
733        assert!((x - 3f64.sqrt() * 5.0).abs() < 1e-9 && (y - 10.0).abs() < 1e-9);
734        assert!(hex_center(1, 0, 10.0).0 > x);
735        assert!(in_hex(0.0, 0.0, 5.0) && !in_hex(5.0, 0.0, 5.0) && !in_hex(0.0, 5.1, 5.0));
736    }
737
738    #[test]
739    fn jitter_stays_in_unit_range() {
740        for i in 0..8 {
741            for t in [0.0, 1.0, 55.5] {
742                assert!((0.0..=1.0).contains(&jitter(0.9, i, t)));
743            }
744        }
745    }
746
747    #[test]
748    fn oscilloscope_draws_trace_and_grid_and_scrolls() {
749        let a = draw(Oscilloscope::ecg(2, 200), 60, 16);
750        assert!(painted(&a) > 100);
751        let no_grid = draw(Oscilloscope::ecg(2, 200).grid(false), 60, 16);
752        assert!(painted(&no_grid) < painted(&a));
753        assert_ne!(a, draw(Oscilloscope::ecg(2, 200).phase(0.3), 60, 16));
754        let w = Oscilloscope::wave(&[(2.0, 1.0), (5.0, 0.5)], 100);
755        assert!(painted(&draw(w.color(Color::Magenta), 40, 10)) > 0);
756    }
757
758    #[test]
759    fn spectrum_fills_bars_with_zone_colors() {
760        let b = draw(Spectrum::new([0.2, 1.0, 0.6]), 12, 10);
761        for c in [Color::Green, Color::Red] {
762            assert!(
763                b.content().iter().any(|x| x.fg == c && x.symbol() == "█"),
764                "{c:?}"
765            );
766        }
767        let off = draw(Spectrum::new([1.0]).zones(false).color(Color::Blue), 6, 5);
768        assert!(off.content().iter().any(|x| x.fg == Color::Blue));
769    }
770
771    #[test]
772    fn spectrum_peak_cap_sits_above_the_bar() {
773        let b = draw(Spectrum::new([0.2]).peaks([0.9]), 3, 10);
774        assert!(b.content().iter().any(|c| c.symbol() == "▀"));
775    }
776
777    #[test]
778    fn dot_matrix_lights_from_the_bottom() {
779        let b = draw(DotMatrix::new([1.0, 0.0]), 3, 4);
780        assert_eq!(b[(0, 3)].symbol(), "●");
781        assert_eq!(b[(0, 0)].symbol(), "●");
782        assert_eq!(b[(2, 3)].symbol(), "·");
783        let half = draw(DotMatrix::new([0.5]), 1, 4);
784        assert_eq!(half[(0, 3)].symbol(), "●");
785        assert_eq!(half[(0, 0)].symbol(), "·");
786    }
787
788    #[test]
789    fn radar_scope_moves_with_phase_and_shows_blips() {
790        let s = |ph: f64| RadarScope::new([Blip::new(0.25, 0.7)]).phase(ph);
791        let (a, b) = (draw(s(0.26), 40, 20), draw(s(0.8), 40, 20));
792        assert!(painted(&a) > 50);
793        assert_ne!(a, b);
794        assert!(a
795            .content()
796            .iter()
797            .any(|c| c.fg != Color::Reset && c.symbol() != " "));
798        let steady = draw(s(0.8).fade(false), 40, 20);
799        assert_ne!(steady, b);
800    }
801
802    #[test]
803    fn hex_map_colors_follow_values() {
804        let cold = draw(HexMap::new(4, [0.0; 12]), 30, 12);
805        let hot = draw(HexMap::new(4, [1.0; 12]).color(Color::Cyan), 30, 12);
806        assert_ne!(cold, hot);
807        assert!(hot.content().iter().any(|c| matches!(c.fg, Color::Rgb(..))));
808        let pulsing = draw(
809            HexMap::new(4, [1.0; 12]).color(Color::Cyan).phase(0.4),
810            30,
811            12,
812        );
813        assert_ne!(pulsing, hot);
814    }
815
816    #[test]
817    fn all_instruments_survive_odd_input_and_sizes() {
818        let odd = [f64::NAN, f64::INFINITY, -3.0, 0.5, 1e300];
819        for (w, h) in [(0, 0), (1, 1), (2, 2), (5, 3), (17, 9), (80, 30)] {
820            for blk in [false, true] {
821                let b = || blk.then(Block::bordered);
822                let mut o = Oscilloscope::new(odd).phase(f64::NAN);
823                let mut s = Spectrum::new(odd.iter().cycle().take(40).copied()).peaks(odd);
824                let mut d = DotMatrix::new(odd).rows(99);
825                let mut r = RadarScope::new([Blip::new(f64::NAN, f64::NAN), Blip::new(9.0, -1.0)])
826                    .phase(f64::INFINITY);
827                let mut m = HexMap::new(0, odd).phase(f64::NAN);
828                if let Some(bl) = b() {
829                    o = o.block(bl.clone());
830                    s = s.block(bl.clone());
831                    d = d.block(bl.clone());
832                    r = r.block(bl.clone());
833                    m = m.block(bl);
834                }
835                draw(o, w, h);
836                draw(s, w, h);
837                draw(d, w, h);
838                draw(r, w, h);
839                draw(m, w, h);
840            }
841            draw(Oscilloscope::new([]), w, h);
842            draw(Spectrum::new([]), w, h);
843            draw(DotMatrix::new([]), w, h);
844            draw(RadarScope::new([]), w, h);
845            draw(HexMap::new(3, []), w, h);
846            draw(HexMap::new(1000, [1.0; 5]), w, h);
847        }
848    }
849}