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 {
222                    (major, 1)
223                } else {
224                    (darken(p.grid, 0.4), 8)
225                };
226                let mut y = 0.0;
227                while y < h {
228                    g.plot(x, y, col, 0);
229                    y += f64::from(step);
230                }
231            }
232            for i in 0..=8 {
233                let y = ((h - 1.0) * f64::from(i) / 8.0).round();
234                let (col, step) = if i == 4 {
235                    (major, 1)
236                } else {
237                    (darken(p.grid, 0.4), 8)
238                };
239                let mut x = 0.0;
240                while x < w {
241                    g.plot(x, y, col, 0);
242                    x += f64::from(step);
243                }
244            }
245        }
246        let n = self.samples.len();
247        if n >= 2 {
248            let shift = (self.phase.rem_euclid(1.0) * n as f64) as usize;
249            let pts: Vec<(f64, f64)> = (0..n)
250                .map(|i| {
251                    let s = self.samples[(i + shift) % n];
252                    let s = if s.is_finite() {
253                        s.clamp(-1.0, 1.0)
254                    } else {
255                        0.0
256                    };
257                    (
258                        (w - 1.0) * i as f64 / (n - 1) as f64,
259                        (h - 1.0) / 2.0 - s * (h - 1.0) * 0.45,
260                    )
261                })
262                .collect();
263            let halo = darken(p.primary, 0.6);
264            for pair in pts.windows(2) {
265                for dy in [-1.0, 1.0] {
266                    g.line(
267                        (pair[0].0, pair[0].1 + dy),
268                        (pair[1].0, pair[1].1 + dy),
269                        halo,
270                        1,
271                    );
272                }
273                g.line(pair[0], pair[1], p.primary, 2);
274            }
275        }
276        g.blit(inner, buf);
277    }
278}
279
280instrument_common!(Oscilloscope);
281
282// ──────────────────────────────── Spectrum ────────────────────────────────
283
284const V_EIGHTHS: [char; 9] = [' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
285
286/// Equalizer bars (`0..=1`) built from segments with zone colors and peak caps.
287///
288/// # Example
289///
290/// ```
291/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
292/// use tui_chart::Spectrum;
293///
294/// 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]);
295/// let area = Rect::new(0, 0, 30, 10);
296/// let mut buf = Buffer::empty(area);
297/// s.render(area, &mut buf);
298/// ```
299#[derive(Debug, Clone, Default)]
300pub struct Spectrum {
301    values: Vec<f64>,
302    peaks: Vec<f64>,
303    zones: bool,
304    color: Option<Color>,
305    theme: Option<Theme>,
306    base: Option<Style>,
307    block: Option<Block<'static>>,
308}
309
310impl Spectrum {
311    /// Bars with `values` in `0..=1`.
312    pub fn new(values: impl IntoIterator<Item = f64>) -> Self {
313        Self {
314            values: values.into_iter().collect(),
315            zones: true,
316            ..Self::default()
317        }
318    }
319
320    /// Peak-hold caps (`0..=1`), one per bar.
321    pub fn peaks(mut self, peaks: impl IntoIterator<Item = f64>) -> Self {
322        self.peaks = peaks.into_iter().collect();
323        self
324    }
325
326    setter!(
327        /// Color the upper segments green / yellow / red (default on).
328        zones: bool
329    );
330    opt_setter!(
331        /// Bar color when zones are off.
332        color: Color
333    );
334
335    fn render_into(&self, area: Rect, buf: &mut Buffer) {
336        let area = area.intersection(buf.area);
337        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
338        let n = self.values.len();
339        if inner.is_empty() || n == 0 {
340            return;
341        }
342        let p = pal(&self.theme, self.color);
343        let width = usize::from(inner.width);
344        let (mut bw, mut gap) = (((width + 1) / n).saturating_sub(1).max(1), 1);
345        if n * bw + (n - 1) * gap > width {
346            bw = 1;
347            gap = usize::from(n * 2 - 1 <= width);
348        }
349        let shown = n.min((width + gap) / (bw + gap));
350        let used = shown * bw + shown.saturating_sub(1) * gap;
351        let x0 = inner.x + ((width - used) / 2) as u16;
352        let rows = usize::from(inner.height);
353        let zone_color = |frac: f64| {
354            if !self.zones {
355                p.primary
356            } else if frac < 0.6 {
357                p.ok
358            } else if frac < 0.85 {
359                p.warn
360            } else {
361                p.danger
362            }
363        };
364        for (i, v) in self.values.iter().take(shown).enumerate() {
365            let eighths = (unit(*v) * rows as f64 * 8.0).round() as i64;
366            let peak_row = self
367                .peaks
368                .get(i)
369                .map(|p| ((unit(*p) * rows as f64).ceil() as usize).clamp(1, rows) - 1);
370            let bx = x0 + (i * (bw + gap)) as u16;
371            for r in 0..rows {
372                let frac = (r as f64 + 0.5) / rows as f64;
373                let col = zone_color(frac);
374                let rem = eighths - r as i64 * 8;
375                let y = inner.bottom() - 1 - r as u16;
376                let (ch, style) = if rem >= 8 {
377                    ('█', Style::default().fg(col))
378                } else if rem > 0 {
379                    (V_EIGHTHS[rem as usize], Style::default().fg(col))
380                } else if peak_row == Some(r) && unit(self.peaks[i]) > 0.0 {
381                    ('▀', Style::default().fg(col))
382                } else {
383                    ('░', Style::default().fg(darken(col, 0.75)))
384                };
385                for dx in 0..bw {
386                    put(buf, bx + dx as u16, y, ch, style);
387                }
388            }
389        }
390    }
391}
392
393instrument_common!(Spectrum);
394
395// ─────────────────────────────── DotMatrix ────────────────────────────────
396
397/// LED dot matrix: one column of dots per value (`0..=1`), lit from the bottom.
398///
399/// # Example
400///
401/// ```
402/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
403/// use tui_chart::DotMatrix;
404///
405/// let m = DotMatrix::new([0.1, 0.4, 0.9, 0.6]).rows(8);
406/// let area = Rect::new(0, 0, 20, 8);
407/// let mut buf = Buffer::empty(area);
408/// m.render(area, &mut buf);
409/// ```
410#[derive(Debug, Clone, Default)]
411pub struct DotMatrix {
412    values: Vec<f64>,
413    rows: Option<usize>,
414    color: Option<Color>,
415    theme: Option<Theme>,
416    base: Option<Style>,
417    block: Option<Block<'static>>,
418}
419
420impl DotMatrix {
421    /// Columns with `values` in `0..=1`.
422    pub fn new(values: impl IntoIterator<Item = f64>) -> Self {
423        Self {
424            values: values.into_iter().collect(),
425            ..Self::default()
426        }
427    }
428
429    /// Number of dot rows (default: the area height; at most the area height).
430    pub fn rows(mut self, rows: usize) -> Self {
431        self.rows = Some(rows.max(2));
432        self
433    }
434
435    opt_setter!(
436        /// Dot color.
437        color: Color
438    );
439
440    fn render_into(&self, area: Rect, buf: &mut Buffer) {
441        let area = area.intersection(buf.area);
442        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
443        let n = self.values.len();
444        if inner.is_empty() || n == 0 {
445            return;
446        }
447        let p = pal(&self.theme, self.color);
448        let width = usize::from(inner.width);
449        let pitch = if n * 2 - 1 <= width { 2 } else { 1 };
450        let shown = n.min(width.div_ceil(pitch));
451        let used = (shown - 1) * pitch + 1;
452        let x0 = inner.x + ((width - used) / 2) as u16;
453        let rows = self
454            .rows
455            .unwrap_or(usize::MAX)
456            .min(usize::from(inner.height));
457        let dim = Style::default().fg(darken(p.grid, 0.2));
458        let on = Style::default().fg(p.primary);
459        let soft = Style::default().fg(mix(p.grid, p.primary, 0.55));
460        for (i, v) in self.values.iter().take(shown).enumerate() {
461            let f = unit(*v);
462            for k in 0..rows {
463                let cov = (f * rows as f64 - k as f64).clamp(0.0, 1.0);
464                let (ch, st) = if cov >= 0.99 {
465                    ('●', on)
466                } else if cov > 0.0 {
467                    ('•', soft)
468                } else {
469                    ('·', dim)
470                };
471                put(
472                    buf,
473                    x0 + (i * pitch) as u16,
474                    inner.bottom() - 1 - k as u16,
475                    ch,
476                    st,
477                );
478            }
479        }
480    }
481}
482
483instrument_common!(DotMatrix);
484
485// ─────────────────────────────── RadarScope ───────────────────────────────
486
487/// A contact on a [`RadarScope`].
488#[derive(Debug, Clone, Copy, PartialEq)]
489#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
490pub struct Blip {
491    /// Bearing in turns: `0` = up, clockwise, wraps.
492    pub bearing: f64,
493    /// Distance from the center, `0..=1` of the radius.
494    pub range: f64,
495}
496
497impl Blip {
498    /// A blip at `bearing` (turns) and `range` (`0..=1`).
499    pub fn new(bearing: f64, range: f64) -> Self {
500        Self { bearing, range }
501    }
502}
503
504/// Radar screen: range rings, a rotating beam with a fading wedge and blips
505/// that light up as the beam passes.
506///
507/// # Example
508///
509/// ```
510/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
511/// use tui_chart::{Blip, RadarScope};
512///
513/// let scope = RadarScope::new([Blip::new(0.1, 0.6), Blip::new(0.7, 0.3)]).phase(0.2);
514/// let area = Rect::new(0, 0, 40, 20);
515/// let mut buf = Buffer::empty(area);
516/// scope.render(area, &mut buf);
517/// ```
518#[derive(Debug, Clone, Default)]
519pub struct RadarScope {
520    blips: Vec<Blip>,
521    phase: f64,
522    fade: bool,
523    color: Option<Color>,
524    theme: Option<Theme>,
525    base: Option<Style>,
526    block: Option<Block<'static>>,
527}
528
529impl RadarScope {
530    /// A scope showing `blips`.
531    pub fn new(blips: impl IntoIterator<Item = Blip>) -> Self {
532        Self {
533            blips: blips.into_iter().collect(),
534            phase: 0.12,
535            fade: true,
536            ..Self::default()
537        }
538    }
539
540    setter!(
541        /// Beam position in turns (`0` = up, clockwise, wraps).
542        phase: f64
543    );
544    setter!(
545        /// Fade blips with the beam (default on); off keeps them fully lit.
546        fade: bool
547    );
548    opt_setter!(
549        /// Beam and ring color.
550        color: Color
551    );
552
553    fn render_into(&self, area: Rect, buf: &mut Buffer) {
554        let area = area.intersection(buf.area);
555        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
556        if inner.is_empty() {
557            return;
558        }
559        let p = pal(&self.theme, self.color);
560        let mut g = Braille::new(inner.width, inner.height);
561        let (w, h) = (g.dots_w(), g.dots_h());
562        let c = (w / 2.0, h / 2.0);
563        let r = w.min(h) / 2.0 - 1.0;
564        if r < 4.0 {
565            return;
566        }
567        for i in 1..=4 {
568            let ro = r * f64::from(i) / 4.0;
569            g.ring(c, (ro - 0.6, ro), (0.0, 1.0), |_| Some((p.grid, 0)));
570        }
571        for q in 0..4 {
572            g.line(c, polar(c.0, c.1, r, f64::from(q) / 4.0), p.grid, 0);
573        }
574        let tick = darken(p.primary, 0.45);
575        for i in 0..36 {
576            let a = f64::from(i) / 36.0;
577            let len = if i % 3 == 0 { 5.0 } else { 2.5 };
578            g.line(polar(c.0, c.1, r, a), polar(c.0, c.1, r - len, a), tick, 1);
579        }
580        let sweep = self.phase.rem_euclid(1.0);
581        let steps = 56;
582        for k in 0..steps {
583            let a = sweep - 0.22 * f64::from(k) / f64::from(steps);
584            let t = 1.0 - f64::from(k) / f64::from(steps);
585            g.line(
586                c,
587                polar(c.0, c.1, r, a),
588                darken(p.primary, 1.0 - 0.5 * t * t),
589                2,
590            );
591        }
592        g.line(c, polar(c.0, c.1, r, sweep), p.primary, 3);
593        for b in &self.blips {
594            let a = if self.fade {
595                blip_alpha(sweep, b.bearing.rem_euclid(1.0))
596            } else {
597                1.0
598            };
599            if a < 0.04 {
600                continue;
601            }
602            let (x, y) = polar(c.0, c.1, r * unit(b.range), b.bearing);
603            let col = darken(p.danger, 1.0 - a);
604            for dy in -1..=1 {
605                for dx in -1..=1 {
606                    g.plot(x + f64::from(dx), y + f64::from(dy), col, 4);
607                }
608            }
609        }
610        g.plot(c.0, c.1, p.primary, 5);
611        g.blit(inner, buf);
612    }
613}
614
615instrument_common!(RadarScope);
616
617// ─────────────────────────────────── HexMap ───────────────────────────────
618
619/// Honeycomb heat map: `cols` hexes per row, each colored by its value (`0..=1`).
620///
621/// # Example
622///
623/// ```
624/// use ratatui::{buffer::Buffer, layout::Rect, widgets::Widget};
625/// use tui_chart::HexMap;
626///
627/// let m = HexMap::new(6, (0..24).map(|i| f64::from(i) / 23.0));
628/// let area = Rect::new(0, 0, 40, 16);
629/// let mut buf = Buffer::empty(area);
630/// m.render(area, &mut buf);
631/// ```
632#[derive(Debug, Clone, Default)]
633pub struct HexMap {
634    values: Vec<f64>,
635    cols: usize,
636    phase: Option<f64>,
637    color: Option<Color>,
638    theme: Option<Theme>,
639    base: Option<Style>,
640    block: Option<Block<'static>>,
641}
642
643impl HexMap {
644    /// A honeycomb with `cols` hexes per row, filled row by row from `values`.
645    pub fn new(cols: usize, values: impl IntoIterator<Item = f64>) -> Self {
646        Self {
647            values: values.into_iter().collect(),
648            cols: cols.max(1),
649            ..Self::default()
650        }
651    }
652
653    /// Pulse the cells with a phase (`0..1`, wraps); `None` is static.
654    pub fn phase(mut self, phase: f64) -> Self {
655        self.phase = Some(phase);
656        self
657    }
658
659    opt_setter!(
660        /// Color of hot cells.
661        color: Color
662    );
663
664    fn render_into(&self, area: Rect, buf: &mut Buffer) {
665        let area = area.intersection(buf.area);
666        let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
667        if inner.is_empty() || self.values.is_empty() {
668            return;
669        }
670        let p = pal(&self.theme, self.color);
671        let mut g = Braille::new(inner.width, inner.height);
672        let (w, h) = (g.dots_w(), g.dots_h());
673        let rows = self.values.len().div_ceil(self.cols);
674        let s = (w / (3f64.sqrt() * (self.cols as f64 + 0.5))).min(h / (1.5 * rows as f64 + 0.5));
675        if s < 2.0 {
676            return;
677        }
678        let (gw, gh) = hex_extent(rows, self.cols, s);
679        let (ox, oy) = ((w - gw) / 2.0, (h - gh) / 2.0);
680        let base = mix(Color::Black, p.grid, 0.5);
681        for (i, v) in self.values.iter().enumerate() {
682            let (row, col) = (i / self.cols, i % self.cols);
683            let mut v = unit(*v);
684            if let Some(ph) = self.phase {
685                v = (v * (0.75 + 0.25 * (ph * TAU + i as f64 * 0.9).sin())).clamp(0.0, 1.0);
686            }
687            let color = if v > 0.8 {
688                mix(p.primary, p.danger, (v - 0.8) / 0.2)
689            } else {
690                mix(base, p.primary, v / 0.8)
691            };
692            let (cx, cy) = hex_center(row, col, s);
693            let (cx, cy) = (cx + ox, cy + oy);
694            let r = s * 0.9;
695            for py in (cy - r).floor() as i64..=(cy + r).ceil() as i64 {
696                for px in (cx - r).floor() as i64..=(cx + r).ceil() as i64 {
697                    if in_hex(px as f64 + 0.5 - cx, py as f64 + 0.5 - cy, r) {
698                        g.plot(px as f64, py as f64, color, 1);
699                    }
700                }
701            }
702        }
703        g.blit(inner, buf);
704    }
705}
706
707instrument_common!(HexMap);
708
709#[cfg(test)]
710mod tests {
711    use super::*;
712    use ratatui::widgets::Widget;
713
714    fn draw(w: impl Widget, width: u16, height: u16) -> Buffer {
715        let a = Rect::new(0, 0, width, height);
716        let mut b = Buffer::empty(a);
717        w.render(a, &mut b);
718        b
719    }
720
721    fn painted(b: &Buffer) -> usize {
722        b.content().iter().filter(|c| c.symbol() != " ").count()
723    }
724
725    #[test]
726    fn ecg_peaks_at_the_qrs_spike() {
727        assert!(ecg_beat(0.39) > 0.9);
728        assert!(ecg_beat(0.9).abs() < 0.05);
729    }
730
731    #[test]
732    fn blip_alpha_is_full_at_the_beam_and_fades() {
733        assert!((blip_alpha(0.5, 0.5) - 1.0).abs() < 1e-12);
734        assert!(blip_alpha(0.5, 0.4) > blip_alpha(0.5, 0.2));
735        assert!(blip_alpha(0.1, 0.9) > 0.0);
736    }
737
738    #[test]
739    fn hex_geometry() {
740        let (x, y) = hex_center(0, 0, 10.0);
741        assert!((x - 3f64.sqrt() * 5.0).abs() < 1e-9 && (y - 10.0).abs() < 1e-9);
742        assert!(hex_center(1, 0, 10.0).0 > x);
743        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));
744    }
745
746    #[test]
747    fn jitter_stays_in_unit_range() {
748        for i in 0..8 {
749            for t in [0.0, 1.0, 55.5] {
750                assert!((0.0..=1.0).contains(&jitter(0.9, i, t)));
751            }
752        }
753    }
754
755    #[test]
756    fn oscilloscope_draws_trace_and_grid_and_scrolls() {
757        let a = draw(Oscilloscope::ecg(2, 200), 60, 16);
758        assert!(painted(&a) > 100);
759        let no_grid = draw(Oscilloscope::ecg(2, 200).grid(false), 60, 16);
760        assert!(painted(&no_grid) < painted(&a));
761        assert_ne!(a, draw(Oscilloscope::ecg(2, 200).phase(0.3), 60, 16));
762        let w = Oscilloscope::wave(&[(2.0, 1.0), (5.0, 0.5)], 100);
763        assert!(painted(&draw(w.color(Color::Magenta), 40, 10)) > 0);
764    }
765
766    #[test]
767    fn spectrum_fills_bars_with_zone_colors() {
768        let b = draw(Spectrum::new([0.2, 1.0, 0.6]), 12, 10);
769        for c in [Color::Green, Color::Red] {
770            assert!(
771                b.content().iter().any(|x| x.fg == c && x.symbol() == "█"),
772                "{c:?}"
773            );
774        }
775        let off = draw(Spectrum::new([1.0]).zones(false).color(Color::Blue), 6, 5);
776        assert!(off.content().iter().any(|x| x.fg == Color::Blue));
777    }
778
779    #[test]
780    fn spectrum_peak_cap_sits_above_the_bar() {
781        let b = draw(Spectrum::new([0.2]).peaks([0.9]), 3, 10);
782        assert!(b.content().iter().any(|c| c.symbol() == "▀"));
783    }
784
785    #[test]
786    fn dot_matrix_lights_from_the_bottom() {
787        let b = draw(DotMatrix::new([1.0, 0.0]), 3, 4);
788        assert_eq!(b[(0, 3)].symbol(), "●");
789        assert_eq!(b[(0, 0)].symbol(), "●");
790        assert_eq!(b[(2, 3)].symbol(), "·");
791        let half = draw(DotMatrix::new([0.5]), 1, 4);
792        assert_eq!(half[(0, 3)].symbol(), "●");
793        assert_eq!(half[(0, 0)].symbol(), "·");
794    }
795
796    #[test]
797    fn radar_scope_moves_with_phase_and_shows_blips() {
798        let s = |ph: f64| RadarScope::new([Blip::new(0.25, 0.7)]).phase(ph);
799        let (a, b) = (draw(s(0.26), 40, 20), draw(s(0.8), 40, 20));
800        assert!(painted(&a) > 50);
801        assert_ne!(a, b);
802        assert!(a
803            .content()
804            .iter()
805            .any(|c| c.fg != Color::Reset && c.symbol() != " "));
806        let steady = draw(s(0.8).fade(false), 40, 20);
807        assert_ne!(steady, b);
808    }
809
810    #[test]
811    fn hex_map_colors_follow_values() {
812        let cold = draw(HexMap::new(4, [0.0; 12]), 30, 12);
813        let hot = draw(HexMap::new(4, [1.0; 12]).color(Color::Cyan), 30, 12);
814        assert_ne!(cold, hot);
815        assert!(hot.content().iter().any(|c| matches!(c.fg, Color::Rgb(..))));
816        let pulsing = draw(
817            HexMap::new(4, [1.0; 12]).color(Color::Cyan).phase(0.4),
818            30,
819            12,
820        );
821        assert_ne!(pulsing, hot);
822    }
823
824    #[test]
825    fn all_instruments_survive_odd_input_and_sizes() {
826        let odd = [f64::NAN, f64::INFINITY, -3.0, 0.5, 1e300];
827        for (w, h) in [(0, 0), (1, 1), (2, 2), (5, 3), (17, 9), (80, 30)] {
828            for blk in [false, true] {
829                let b = || blk.then(Block::bordered);
830                let mut o = Oscilloscope::new(odd).phase(f64::NAN);
831                let mut s = Spectrum::new(odd.iter().cycle().take(40).copied()).peaks(odd);
832                let mut d = DotMatrix::new(odd).rows(99);
833                let mut r = RadarScope::new([Blip::new(f64::NAN, f64::NAN), Blip::new(9.0, -1.0)])
834                    .phase(f64::INFINITY);
835                let mut m = HexMap::new(0, odd).phase(f64::NAN);
836                if let Some(bl) = b() {
837                    o = o.block(bl.clone());
838                    s = s.block(bl.clone());
839                    d = d.block(bl.clone());
840                    r = r.block(bl.clone());
841                    m = m.block(bl);
842                }
843                draw(o, w, h);
844                draw(s, w, h);
845                draw(d, w, h);
846                draw(r, w, h);
847                draw(m, w, h);
848            }
849            draw(Oscilloscope::new([]), w, h);
850            draw(Spectrum::new([]), w, h);
851            draw(DotMatrix::new([]), w, h);
852            draw(RadarScope::new([]), w, h);
853            draw(HexMap::new(3, []), w, h);
854            draw(HexMap::new(1000, [1.0; 5]), w, h);
855        }
856    }
857}