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