1#![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
28pub 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
40pub 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
47pub 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
54pub 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
60fn 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
66pub 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
80struct 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
117macro_rules! instrument_common {
119 ($t:ty) => {
120 impl $t {
121 theme_setter!(
122 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#[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 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 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 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 phase: f64
198 );
199 setter!(
200 grid: bool
202 );
203 opt_setter!(
204 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
295const V_EIGHTHS: [char; 9] = [' ', '▁', '▂', '▃', '▄', '▅', '▆', '▇', '█'];
298
299#[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 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 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 zones: bool
342 );
343 opt_setter!(
344 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#[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 pub fn new(values: impl IntoIterator<Item = f64>) -> Self {
448 Self {
449 values: values.into_iter().collect(),
450 ..Self::default()
451 }
452 }
453
454 pub fn rows(mut self, rows: usize) -> Self {
456 self.rows = Some(rows.max(2));
457 self
458 }
459
460 opt_setter!(
461 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#[derive(Debug, Clone, Copy, PartialEq)]
520#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
521pub struct Blip {
522 pub bearing: f64,
524 pub range: f64,
526}
527
528impl Blip {
529 pub fn new(bearing: f64, range: f64) -> Self {
531 Self { bearing, range }
532 }
533}
534
535#[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 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 phase: f64
574 );
575 setter!(
576 fade: bool
578 );
579 opt_setter!(
580 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#[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 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 pub fn phase(mut self, phase: f64) -> Self {
705 self.phase = Some(phase);
706 self
707 }
708
709 opt_setter!(
710 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!(a
867 .content()
868 .iter()
869 .any(|c| c.fg != Color::Reset && c.symbol() != " "));
870 let steady = draw(s(0.8).fade(false), 40, 20);
871 assert_ne!(steady, b);
872 }
873
874 #[test]
875 fn hex_map_colors_follow_values() {
876 let cold = draw(HexMap::new(4, [0.0; 12]), 30, 12);
877 let hot = draw(HexMap::new(4, [1.0; 12]).color(Color::Cyan), 30, 12);
878 assert_ne!(cold, hot);
879 assert!(hot.content().iter().any(|c| matches!(c.fg, Color::Rgb(..))));
880 let pulsing = draw(
881 HexMap::new(4, [1.0; 12]).color(Color::Cyan).phase(0.4),
882 30,
883 12,
884 );
885 assert_ne!(pulsing, hot);
886 }
887
888 #[test]
889 fn all_instruments_survive_odd_input_and_sizes() {
890 let odd = [f64::NAN, f64::INFINITY, -3.0, 0.5, 1e300];
891 for (w, h) in [(0, 0), (1, 1), (2, 2), (5, 3), (17, 9), (80, 30)] {
892 for blk in [false, true] {
893 let b = || blk.then(Block::bordered);
894 let mut o = Oscilloscope::new(odd).phase(f64::NAN);
895 let mut s = Spectrum::new(odd.iter().cycle().take(40).copied()).peaks(odd);
896 let mut d = DotMatrix::new(odd).rows(99);
897 let mut r = RadarScope::new([Blip::new(f64::NAN, f64::NAN), Blip::new(9.0, -1.0)])
898 .phase(f64::INFINITY);
899 let mut m = HexMap::new(0, odd).phase(f64::NAN);
900 if let Some(bl) = b() {
901 o = o.block(bl.clone());
902 s = s.block(bl.clone());
903 d = d.block(bl.clone());
904 r = r.block(bl.clone());
905 m = m.block(bl);
906 }
907 draw(o, w, h);
908 draw(s, w, h);
909 draw(d, w, h);
910 draw(r, w, h);
911 draw(m, w, h);
912 }
913 draw(Oscilloscope::new([]), w, h);
914 draw(Spectrum::new([]), w, h);
915 draw(DotMatrix::new([]), w, h);
916 draw(RadarScope::new([]), w, h);
917 draw(HexMap::new(3, []), w, h);
918 draw(HexMap::new(1000, [1.0; 5]), w, h);
919 }
920 }
921}