1use crate::heatmap::Gradient;
24use crate::text::put_str;
25use crate::theme::{self, Theme};
26use crate::util::{
27 darken, format_compact, format_tick, mix, nice_bounds, nice_ticks, pick, to_rgb,
28};
29use ratatui::{
30 buffer::Buffer,
31 layout::Rect,
32 style::{Color, Style},
33 widgets::Block,
34};
35use std::collections::BTreeMap;
36
37const NONE: usize = usize::MAX;
39
40#[derive(Debug, Clone, PartialEq)]
42#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
43pub struct VoronoiSite {
44 pub label: String,
46 pub x: f64,
48 pub y: f64,
50 pub weight: Option<f64>,
52 pub value: Option<f64>,
54 pub category: Option<String>,
56 pub color: Option<Color>,
58}
59
60impl VoronoiSite {
61 pub fn new(label: impl Into<String>, x: f64, y: f64) -> Self {
63 Self {
64 label: label.into(),
65 x,
66 y,
67 weight: None,
68 value: None,
69 category: None,
70 color: None,
71 }
72 }
73
74 pub fn weight(mut self, w: f64) -> Self {
76 self.weight = Some(w);
77 self
78 }
79
80 pub fn value(mut self, v: f64) -> Self {
82 self.value = Some(v);
83 self
84 }
85
86 pub fn category(mut self, c: impl Into<String>) -> Self {
88 self.category = Some(c.into());
89 self
90 }
91
92 pub fn color(mut self, c: Color) -> Self {
94 self.color = Some(c);
95 self
96 }
97
98 fn finite(&self) -> bool {
99 self.x.is_finite() && self.y.is_finite()
100 }
101}
102
103#[derive(Debug, Clone, Copy, PartialEq, Default)]
105#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
106pub enum VoronoiMetric {
107 #[default]
109 Euclidean,
110 Manhattan,
112 Chebyshev,
114 Minkowski(f64),
117}
118
119impl VoronoiMetric {
120 pub fn next(self) -> Self {
122 match self {
123 Self::Euclidean => Self::Manhattan,
124 Self::Manhattan => Self::Chebyshev,
125 Self::Chebyshev => Self::Minkowski(3.0),
126 Self::Minkowski(_) => Self::Euclidean,
127 }
128 }
129
130 fn dist(self, dx: f64, dy: f64) -> f64 {
131 match self {
132 Self::Euclidean => dx.hypot(dy),
133 Self::Manhattan => dx + dy,
134 Self::Chebyshev => dx.max(dy),
135 Self::Minkowski(p) => {
136 let p = if p.is_finite() {
137 p.clamp(0.5, 16.0)
138 } else {
139 2.0
140 };
141 (dx.powf(p) + dy.powf(p)).powf(1.0 / p)
142 }
143 }
144 }
145
146 fn key(self, dx: f64, dy: f64, r: f64) -> f64 {
148 match self {
149 Self::Euclidean => dx * dx + dy * dy - r * r,
150 m => m.dist(dx, dy) - r,
151 }
152 }
153}
154
155#[derive(Debug, Clone)]
179pub struct VoronoiChart {
180 sites: Vec<VoronoiSite>,
181 metric: VoronoiMetric,
182 weighted: bool,
183 farthest: bool,
184 borders: bool,
185 show_sites: bool,
186 show_labels: bool,
187 fill_dim: f64,
188 border_color: Option<Color>,
189 gradient: Option<Gradient>,
190 merge: bool,
191 knn: usize,
192 shade: bool,
193 relax: usize,
194 delaunay: bool,
195 phase: f64,
196 probe: Option<(f64, f64)>,
197 select: Option<usize>,
198 axes: bool,
199 bounds: Option<(f64, f64, f64, f64)>,
200 square: bool,
201 clip_circle: bool,
202 theme: Option<Theme>,
203 base: Option<Style>,
204 block: Option<Block<'static>>,
205}
206
207impl Default for VoronoiChart {
208 fn default() -> Self {
209 Self {
210 sites: Vec::new(),
211 metric: VoronoiMetric::default(),
212 weighted: false,
213 farthest: false,
214 borders: true,
215 show_sites: true,
216 show_labels: false,
217 fill_dim: 0.45,
218 border_color: None,
219 gradient: None,
220 merge: true,
221 knn: 1,
222 shade: false,
223 relax: 0,
224 delaunay: false,
225 phase: 0.0,
226 probe: None,
227 select: None,
228 axes: false,
229 bounds: None,
230 square: false,
231 clip_circle: false,
232 theme: None,
233 base: None,
234 block: None,
235 }
236 }
237}
238
239struct Active {
241 orig: Option<usize>,
242 pos: (f64, f64),
243 radius: f64,
244}
245
246struct Field {
248 own: Vec<usize>,
249 dist: Vec<f64>,
250}
251
252impl VoronoiChart {
253 pub fn new(sites: impl IntoIterator<Item = VoronoiSite>) -> Self {
255 Self {
256 sites: sites.into_iter().collect(),
257 ..Self::default()
258 }
259 }
260
261 setter!(
262 metric: VoronoiMetric
264 );
265
266 setter!(
267 weighted: bool
269 );
270
271 setter!(
272 farthest: bool
274 );
275
276 setter!(
277 borders: bool
279 );
280
281 setter!(
282 show_sites: bool
284 );
285
286 setter!(
287 show_labels: bool
289 );
290
291 setter!(
292 fill_dim: f64
294 );
295
296 opt_setter!(
297 border_color: Color
299 );
300
301 opt_setter!(
302 gradient: Gradient
304 );
305
306 setter!(
307 merge_categories => merge: bool
309 );
310
311 setter!(
312 knn: usize
315 );
316
317 setter!(
318 shade_by_distance => shade: bool
321 );
322
323 setter!(
324 relax: usize
327 );
328
329 setter!(
330 delaunay: bool
333 );
334
335 setter!(
336 phase: f64
338 );
339
340 opt_setter!(
341 probe: (f64, f64)
344 );
345
346 opt_setter!(
347 select: usize
349 );
350
351 setter!(
352 axes: bool
354 );
355
356 pub fn bounds(mut self, x0: f64, x1: f64, y0: f64, y1: f64) -> Self {
358 self.bounds = Some((x0, x1, y0, y1));
359 self
360 }
361
362 setter!(
363 square: bool
365 );
366
367 setter!(
368 clip_circle: bool
370 );
371
372 theme_setter!(
373 theme
375 );
376
377 base_style_setter!(base);
378
379 block_setter!(block, 'static);
380
381 fn assign(
382 &self,
383 act: &[Active],
384 w: usize,
385 h: usize,
386 inside: &dyn Fn(usize, usize) -> bool,
387 ) -> Field {
388 let mut own = vec![NONE; w * h];
389 let mut dist = vec![0.0; w * h];
390 let m = self.metric;
391 for py in 0..h {
392 for px in 0..w {
393 if !inside(px, py) {
394 continue;
395 }
396 let (qx, qy) = (px as f64 + 0.5, py as f64 + 0.5);
397 let mut best = (if self.farthest { f64::MIN } else { f64::MAX }, 0usize, 0.0);
398 for (k, a) in act.iter().enumerate() {
399 let (dx, dy) = ((qx - a.pos.0).abs(), (qy - a.pos.1).abs());
400 if self.farthest {
401 let d = m.dist(dx, dy);
402 if d > best.0 {
403 best = (d, k, d);
404 }
405 } else {
406 let key = m.key(dx, dy, a.radius);
407 if key < best.0 {
408 best = (key, k, 0.0);
409 }
410 }
411 }
412 let a = &act[best.1];
413 own[py * w + px] = best.1;
414 dist[py * w + px] = if self.farthest {
415 best.2
416 } else {
417 m.dist((qx - a.pos.0).abs(), (qy - a.pos.1).abs())
418 };
419 }
420 }
421 Field { own, dist }
422 }
423
424 fn render_into(&self, area: Rect, buf: &mut Buffer) {
425 let area = area.intersection(buf.area);
426 let inner = theme::begin(&self.block, &self.theme, self.base, area, buf);
427 if inner.width < 2 || inner.height < 1 {
428 return;
429 }
430 let valid: Vec<usize> = (0..self.sites.len())
431 .filter(|&i| self.sites[i].finite())
432 .collect();
433 if valid.is_empty() {
434 return;
435 }
436 let (mut x0, mut x1, mut y0, mut y1) = (f64::MAX, f64::MIN, f64::MAX, f64::MIN);
438 for &i in &valid {
439 let s = &self.sites[i];
440 x0 = x0.min(s.x);
441 x1 = x1.max(s.x);
442 y0 = y0.min(s.y);
443 y1 = y1.max(s.y);
444 }
445 let ((x0, x1), (y0, y1)) = match self.bounds {
446 Some((a, b, c, d)) if [a, b, c, d].iter().all(|v| v.is_finite()) && b > a && d > c => {
447 ((a, b), (c, d))
448 }
449 _ if self.axes => (nice_bounds(x0, x1, 5), nice_bounds(y0, y1, 5)),
450 _ => {
451 let pad = |lo: f64, hi: f64| {
452 let span = hi - lo;
453 if span > f64::EPSILON {
454 (lo - span * 0.08, hi + span * 0.08)
455 } else {
456 (lo - 1.0, hi + 1.0)
457 }
458 };
459 (pad(x0, x1), pad(y0, y1))
460 }
461 };
462 let (xs, ys) = ((x1 - x0).max(f64::EPSILON), (y1 - y0).max(f64::EPSILON));
463
464 let (dim_style, text_style) = crate::util::dim_text(&self.theme);
466 let yt = nice_ticks(y0, y1, (inner.height as usize / 3).max(2));
467 let ystep = if yt.len() >= 2 { yt[1] - yt[0] } else { 1.0 };
468 let ylabels: Vec<String> = yt.iter().map(|v| format_tick(*v, ystep)).collect();
469 let gutter = if self.axes {
470 (ylabels.iter().map(|l| l.chars().count()).max().unwrap_or(1) as u16 + 1)
471 .min(inner.width / 2)
472 } else {
473 0
474 };
475 let plot = if self.axes {
476 Rect::new(
477 inner.x + gutter,
478 inner.y,
479 inner.width - gutter,
480 inner.height.saturating_sub(1),
481 )
482 } else {
483 inner
484 };
485 if plot.width < 2 || plot.height < 1 {
486 return;
487 }
488
489 let (w, h) = (usize::from(plot.width), usize::from(plot.height) * 2);
491 let (wf, hf) = (w as f64, h as f64);
492 let (sx, sy) = if self.square {
493 let s = (wf / xs).min(hf / ys);
494 (s, s)
495 } else {
496 (wf / xs, hf / ys)
497 };
498 let (ox, oy) = ((wf - sx * xs) / 2.0, (hf - sy * ys) / 2.0);
499 let to_px = |x: f64, y: f64| (ox + (x - x0) * sx, oy + (y1 - y) * sy);
500
501 let inside = |px: usize, py: usize| -> bool {
502 if !self.clip_circle {
503 return true;
504 }
505 let (cx, cy, r) = (wf / 2.0, hf / 2.0, (wf / 2.0).min(hf / 2.0));
506 let (dx, dy) = (px as f64 + 0.5 - cx, py as f64 + 0.5 - cy);
507 dx * dx + dy * dy <= r * r
508 };
509
510 let spacing = ((w * h) as f64 / valid.len() as f64).sqrt();
511 let wmax = valid
512 .iter()
513 .filter_map(|&i| self.sites[i].weight)
514 .filter(|v| v.is_finite())
515 .fold(0.0, f64::max);
516 let mut act: Vec<Active> = valid
517 .iter()
518 .map(|&i| {
519 let s = &self.sites[i];
520 let radius = match s.weight {
521 Some(v) if self.weighted && v.is_finite() && wmax > 0.0 => {
522 (v.max(0.0) / wmax).sqrt() * 0.6 * spacing
523 }
524 _ => 0.0,
525 };
526 Active {
527 orig: Some(i),
528 pos: to_px(s.x, s.y),
529 radius,
530 }
531 })
532 .collect();
533
534 for _ in 0..self.relax.min(60) {
536 let f = self.assign(&act, w, h, &inside);
537 let mut sum = vec![(0.0, 0.0, 0usize); act.len()];
538 for (p, &o) in f.own.iter().enumerate() {
539 if o != NONE {
540 let e = &mut sum[o];
541 e.0 += (p % w) as f64 + 0.5;
542 e.1 += (p / w) as f64 + 0.5;
543 e.2 += 1;
544 }
545 }
546 for (a, s) in act.iter_mut().zip(&sum) {
547 if s.2 > 0 {
548 a.pos = (s.0 / s.2 as f64, s.1 / s.2 as f64);
549 }
550 }
551 }
552 if self.phase != 0.0 && self.phase.is_finite() {
554 for (k, a) in act.iter_mut().enumerate() {
555 let (kf, amp) = (k as f64, 0.28 * spacing);
556 a.pos.0 = (a.pos.0 + amp * (self.phase + kf * 1.7).sin()).clamp(0.0, wf - 1.0);
557 a.pos.1 =
558 (a.pos.1 + amp * (self.phase * 0.8 + kf * 2.3).cos()).clamp(0.0, hf - 1.0);
559 }
560 }
561 let probe_idx = self
563 .probe
564 .filter(|(x, y)| x.is_finite() && y.is_finite())
565 .map(|(x, y)| {
566 let (px, py) = to_px(x, y);
567 act.push(Active {
568 orig: None,
569 pos: (px.clamp(0.0, wf - 1.0), py.clamp(0.0, hf - 1.0)),
570 radius: 0.0,
571 });
572 act.len() - 1
573 });
574
575 let field = self.assign(&act, w, h, &inside);
576
577 let mut cats: Vec<&str> = Vec::new();
579 let cat_of: Vec<Option<usize>> = act
580 .iter()
581 .map(|a| {
582 let c = self.sites[a.orig?].category.as_deref()?;
583 Some(cats.iter().position(|x| *x == c).unwrap_or_else(|| {
584 cats.push(c);
585 cats.len() - 1
586 }))
587 })
588 .collect();
589 let (mut vmin, mut vmax) = (f64::MAX, f64::MIN);
590 for &i in &valid {
591 if let Some(v) = self.sites[i].value.filter(|v| v.is_finite()) {
592 vmin = vmin.min(v);
593 vmax = vmax.max(v);
594 }
595 }
596 let cat_color = |c: usize| -> Color {
597 act.iter()
598 .zip(&cat_of)
599 .find(|(_, k)| **k == Some(c))
600 .and_then(|(a, _)| a.orig)
601 .and_then(|i| self.sites[i].color)
602 .unwrap_or_else(|| pick(&self.theme, c))
603 };
604 let base: Vec<Color> = act
605 .iter()
606 .enumerate()
607 .map(|(k, a)| {
608 let Some(i) = a.orig else {
609 return Color::White;
610 };
611 let s = &self.sites[i];
612 if let Some(c) = s.color {
613 c
614 } else if let Some(c) = cat_of[k] {
615 cat_color(c)
616 } else if let (Some(g), Some(v)) =
617 (&self.gradient, s.value.filter(|v| v.is_finite()))
618 {
619 let t = if vmax > vmin {
620 (v - vmin) / (vmax - vmin)
621 } else {
622 0.5
623 };
624 g.color_at(t)
625 } else if self.gradient.is_some() {
626 Color::DarkGray
627 } else {
628 pick(&self.theme, i)
629 }
630 })
631 .collect();
632
633 let voting = self.knn >= 2 && !cats.is_empty();
635 let n = w * h;
636 let mut grp = vec![NONE; n];
637 let mut fill_base: Vec<Option<Color>> = vec![None; n];
638 for p in 0..n {
639 let o = field.own[p];
640 if o == NONE {
641 continue;
642 }
643 if voting {
644 let (qx, qy) = ((p % w) as f64 + 0.5, (p / w) as f64 + 0.5);
645 let mut ds: Vec<(f64, usize)> = act
646 .iter()
647 .enumerate()
648 .filter(|(k, _)| cat_of[*k].is_some())
649 .map(|(k, a)| {
650 (
651 self.metric.dist((qx - a.pos.0).abs(), (qy - a.pos.1).abs()),
652 k,
653 )
654 })
655 .collect();
656 ds.sort_by(|a, b| a.0.total_cmp(&b.0));
657 let mut votes = vec![0usize; cats.len()];
658 for (_, k) in ds.iter().take(self.knn) {
659 if let Some(c) = cat_of[*k] {
660 votes[c] += 1;
661 }
662 }
663 let top = *votes.iter().max().unwrap_or(&0);
664 let win = ds
666 .iter()
667 .filter_map(|(_, k)| cat_of[*k])
668 .find(|c| votes[*c] == top)
669 .unwrap_or(0);
670 grp[p] = win;
671 fill_base[p] = Some(cat_color(win));
672 } else {
673 grp[p] = match (self.merge, cat_of[o]) {
674 (true, Some(c)) => c,
675 _ => cats.len() + o,
676 };
677 fill_base[p] = Some(base[o]);
678 }
679 }
680
681 let dmax = (spacing * 0.8).max(1.0);
682 let dim = self.fill_dim.clamp(0.0, 1.0);
683 let mut px: Vec<Option<Color>> = (0..n)
684 .map(|p| {
685 let b = fill_base[p]?;
686 Some(if self.shade {
687 let f = (field.dist[p] / dmax).clamp(0.0, 1.0);
688 darken(mix(b, Color::White, 0.15 * (1.0 - f)), f * 0.85)
689 } else {
690 darken(b, dim)
691 })
692 })
693 .collect();
694
695 let mut adj: BTreeMap<(usize, usize), usize> = BTreeMap::new();
697 for p in 0..n {
698 let a = field.own[p];
699 if a == NONE {
700 continue;
701 }
702 let right = (p % w + 1 < w).then(|| field.own[p + 1]);
703 let down = (p / w + 1 < h).then(|| field.own[p + w]);
704 for b in [right, down].into_iter().flatten() {
705 if b != NONE && b != a {
706 *adj.entry((a.min(b), a.max(b))).or_default() += 1;
707 }
708 }
709 }
710 let sel = self
711 .select
712 .and_then(|i| act.iter().position(|a| a.orig == Some(i)));
713
714 if let Some(s) = sel {
716 for p in 0..n {
717 if field.own[p] == s {
718 px[p] = px[p].map(|c| mix(c, Color::White, 0.28));
719 }
720 }
721 }
722
723 if self.borders {
725 let edge_of = |p: usize| -> Color {
726 self.border_color.unwrap_or_else(|| {
727 mix(fill_base[p].unwrap_or(Color::White), Color::White, 0.55)
728 })
729 };
730 let mut paint = Vec::new();
731 for p in 0..n {
732 if grp[p] == NONE {
733 continue;
734 }
735 let (x, y) = (p % w, p / w);
736 let mut differs = false;
737 let mut near_sel = false;
738 for q in [
739 (x > 0).then(|| p - 1),
740 (x + 1 < w).then(|| p + 1),
741 (y > 0).then(|| p - w),
742 (y + 1 < h).then(|| p + w),
743 ]
744 .into_iter()
745 .flatten()
746 {
747 if grp[q] == NONE || grp[q] == grp[p] {
748 continue;
749 }
750 let sel_edge = sel.is_some_and(|s| field.own[q] == s || field.own[p] == s);
751 if grp[q] > grp[p] || sel_edge {
753 differs = true;
754 if let Some(s) = sel
755 && (field.own[q] == s || field.own[p] == s)
756 {
757 near_sel = true;
758 }
759 }
760 }
761 if differs {
762 paint.push((p, if near_sel { Color::White } else { edge_of(p) }));
763 }
764 }
765 for (p, c) in paint {
766 px[p] = Some(c);
767 }
768 }
769
770 if self.delaunay {
772 for &(a, b) in adj.keys() {
773 let (p, q) = (act[a].pos, act[b].pos);
774 let steps = (q.0 - p.0).abs().max((q.1 - p.1).abs()).ceil().max(1.0) as usize;
775 for t in 0..=steps {
776 let f = t as f64 / steps as f64;
777 let (x, y) = (p.0 + (q.0 - p.0) * f, p.1 + (q.1 - p.1) * f);
778 if x >= 0.0 && y >= 0.0 && (x as usize) < w && (y as usize) < h {
779 let i = y as usize * w + x as usize;
780 if let Some(c) = px[i] {
781 px[i] = Some(mix(c, Color::White, 0.75));
782 }
783 }
784 }
785 }
786 }
787
788 paint_pixels(buf, plot, &px, w);
789
790 let at = |a: &Active| -> (u16, u16) {
792 (
793 plot.x + (a.pos.0.max(0.0) as usize).min(w - 1) as u16,
794 plot.y + ((a.pos.1.max(0.0) as usize) / 2).min(usize::from(plot.height) - 1) as u16,
795 )
796 };
797 for (k, a) in act.iter().enumerate() {
798 let (x, y) = at(a);
799 let bg = buf[(x, y)].bg;
800 let bg = if bg == Color::Reset { base[k] } else { bg };
801 let ink = contrast(bg);
802 if self.show_sites || Some(k) == probe_idx {
803 let glyph = if Some(k) == probe_idx { '◆' } else { '●' };
804 buf[(x, y)]
805 .set_char(glyph)
806 .set_style(Style::default().fg(ink).bg(bg));
807 }
808 if self.show_labels
809 && let Some(i) = a.orig
810 && !self.sites[i].label.is_empty()
811 {
812 let lx = if self.show_sites { x + 2 } else { x };
813 put_str(
814 buf,
815 lx,
816 y,
817 plot.right(),
818 &self.sites[i].label,
819 Style::default().fg(ink).bg(bg),
820 );
821 }
822 }
823
824 if self.axes {
826 for (v, l) in yt.iter().zip(&ylabels) {
827 let f = ((v - y0) / ys).clamp(0.0, 1.0);
828 let y = plot.bottom() - 1 - (f * (plot.height - 1) as f64).round() as u16;
829 let lw = l.chars().count() as u16;
830 put_str(
831 buf,
832 inner.x + gutter.saturating_sub(lw + 1),
833 y,
834 plot.x,
835 l,
836 dim_style,
837 );
838 }
839 let xt = nice_ticks(x0, x1, (plot.width as usize / 10).max(2));
840 let xstep = if xt.len() >= 2 { xt[1] - xt[0] } else { 1.0 };
841 for v in xt {
842 let f = ((v - x0) / xs).clamp(0.0, 1.0);
843 let x = plot.x + (f * (plot.width - 1) as f64).round() as u16;
844 let l = format_tick(v, xstep);
845 let lx = x.saturating_sub(l.chars().count() as u16 / 2).max(plot.x);
846 put_str(buf, lx, inner.bottom() - 1, inner.right(), &l, text_style);
847 }
848 }
849
850 if crate::interact::recording() {
852 let owners: Vec<Option<usize>> = (0..usize::from(plot.height))
853 .flat_map(|cy| (0..w).map(move |cx| (cx, cy)))
854 .map(|(cx, cy)| {
855 let o = field.own[cy * 2 * w + cx];
856 (o != NONE && act[o].orig.is_some()).then_some(o)
857 })
858 .collect();
859 let inside_total = field.own.iter().filter(|&&o| o != NONE).count().max(1);
860 crate::interact::record_grid(
861 plot,
862 &owners,
863 |k| act[k].orig.unwrap_or(0),
864 |k| {
865 let s = &self.sites[act[k].orig.unwrap_or(0)];
866 let mut lines = vec![format!(
867 "x {} y {}",
868 format_compact(s.x),
869 format_compact(s.y)
870 )];
871 if let Some(v) = s.weight {
872 lines.push(format!("weight {}", format_compact(v)));
873 }
874 if let Some(v) = s.value {
875 lines.push(format!("value {}", format_compact(v)));
876 }
877 if let Some(c) = &s.category {
878 lines.push(format!("category {c}"));
879 }
880 let owned = field.own.iter().filter(|&&o| o == k).count();
881 lines.push(format!(
882 "area {:.0}%",
883 owned as f64 / inside_total as f64 * 100.0
884 ));
885 let mut nb: Vec<(usize, usize)> = adj
887 .iter()
888 .filter_map(|(&(a, b), &c)| {
889 (a == k).then_some((b, c)).or((b == k).then_some((a, c)))
890 })
891 .collect();
892 let perim: usize = nb.iter().map(|x| x.1).sum::<usize>().max(1);
893 nb.sort_by_key(|x| std::cmp::Reverse(x.1));
894 if !nb.is_empty() {
895 let list: Vec<String> = nb
896 .iter()
897 .take(3)
898 .map(|(o, c)| {
899 let name = act[*o]
900 .orig
901 .map_or("probe", |i| self.sites[i].label.as_str());
902 format!("{name} {}%", c * 100 / perim)
903 })
904 .collect();
905 lines.push(format!("{} neighbours: {}", nb.len(), list.join(", ")));
906 }
907 (s.label.clone(), lines)
908 },
909 );
910 }
911 }
912}
913
914pub(crate) fn paint_pixels(buf: &mut Buffer, plot: Rect, px: &[Option<Color>], w: usize) {
917 for cy in 0..usize::from(plot.height) {
918 for cx in 0..w {
919 let (top, bot) = (px[cy * 2 * w + cx], px[(cy * 2 + 1) * w + cx]);
920 let cell = &mut buf[(plot.x + cx as u16, plot.y + cy as u16)];
921 match (top, bot) {
922 (None, None) => {}
923 (Some(t), Some(b)) if t == b => {
924 cell.set_char(' ').set_style(Style::default().bg(t));
925 }
926 (Some(t), Some(b)) => {
927 cell.set_char('▀').set_style(Style::default().fg(t).bg(b));
928 }
929 (Some(t), None) => {
930 cell.set_char('▀')
931 .set_style(Style::default().fg(t).bg(Color::Reset));
932 }
933 (None, Some(b)) => {
934 cell.set_char('▄')
935 .set_style(Style::default().fg(b).bg(Color::Reset));
936 }
937 }
938 }
939 }
940}
941
942pub(crate) fn contrast(bg: Color) -> Color {
944 let (r, g, b) = to_rgb(bg);
945 if 0.299 * f64::from(r) + 0.587 * f64::from(g) + 0.114 * f64::from(b) > 140.0 {
946 Color::Black
947 } else {
948 Color::White
949 }
950}
951
952pub fn voronoi_stipple(
967 density: &[Vec<f64>],
968 n: usize,
969 relax: usize,
970 seed: u64,
971) -> Vec<VoronoiSite> {
972 let rows = density.len();
973 let cols = density.iter().map(Vec::len).max().unwrap_or(0);
974 let d = |r: usize, c: usize| {
975 density
976 .get(r)
977 .and_then(|row| row.get(c))
978 .copied()
979 .filter(|v| v.is_finite() && *v > 0.0)
980 .unwrap_or(0.0)
981 };
982 let total: f64 = (0..rows)
983 .flat_map(|r| (0..cols).map(move |c| (r, c)))
984 .map(|(r, c)| d(r, c))
985 .sum();
986 if rows == 0 || cols == 0 || n == 0 || total <= 0.0 {
987 return Vec::new();
988 }
989 let mut state = seed
990 .wrapping_mul(6364136223846793005)
991 .wrapping_add(1442695040888963407);
992 let mut rnd = move || {
993 state = state
994 .wrapping_mul(6364136223846793005)
995 .wrapping_add(1442695040888963407);
996 (state >> 11) as f64 / (1u64 << 53) as f64
997 };
998 let mut cdf = Vec::with_capacity(rows * cols);
1000 let mut acc = 0.0;
1001 for r in 0..rows {
1002 for c in 0..cols {
1003 acc += d(r, c);
1004 cdf.push(acc);
1005 }
1006 }
1007 let mut pos: Vec<(f64, f64)> = (0..n)
1008 .map(|_| {
1009 let t = rnd() * total;
1010 let i = cdf.partition_point(|v| *v < t).min(cdf.len() - 1);
1011 ((i % cols) as f64 + rnd(), (i / cols) as f64 + rnd())
1012 })
1013 .collect();
1014 for _ in 0..relax.min(60) {
1015 let mut sum = vec![(0.0, 0.0, 0.0); n];
1016 for r in 0..rows {
1017 for c in 0..cols {
1018 let wgt = d(r, c);
1019 if wgt == 0.0 {
1020 continue;
1021 }
1022 let (qx, qy) = (c as f64 + 0.5, r as f64 + 0.5);
1023 let k = pos
1024 .iter()
1025 .enumerate()
1026 .min_by(|a, b| {
1027 let da = (a.1.0 - qx).powi(2) + (a.1.1 - qy).powi(2);
1028 let db = (b.1.0 - qx).powi(2) + (b.1.1 - qy).powi(2);
1029 da.total_cmp(&db)
1030 })
1031 .map_or(0, |x| x.0);
1032 sum[k].0 += qx * wgt;
1033 sum[k].1 += qy * wgt;
1034 sum[k].2 += wgt;
1035 }
1036 }
1037 for (p, s) in pos.iter_mut().zip(&sum) {
1038 if s.2 > 0.0 {
1039 *p = (s.0 / s.2, s.1 / s.2);
1040 }
1041 }
1042 }
1043 pos.into_iter()
1044 .enumerate()
1045 .map(|(i, (x, y))| {
1046 let (c, r) = ((x as usize).min(cols - 1), (y as usize).min(rows - 1));
1047 VoronoiSite::new(format!("s{i}"), x, rows as f64 - y).value(d(r, c))
1048 })
1049 .collect()
1050}
1051
1052widget_impls!(VoronoiChart);
1053
1054#[cfg(feature = "theme")]
1055impl tui_nuances::Themed for VoronoiChart {
1056 fn apply_theme(self, theme: &tui_nuances::Theme) -> Self {
1057 self.theme(theme)
1058 }
1059}
1060
1061#[cfg(test)]
1062mod tests {
1063 use super::*;
1064 use ratatui::widgets::Widget;
1065
1066 const RED: Color = Color::Rgb(200, 0, 0);
1067 const BLUE: Color = Color::Rgb(0, 0, 200);
1068
1069 fn render(c: &VoronoiChart, w: u16, h: u16) -> Buffer {
1070 let a = Rect::new(0, 0, w, h);
1071 let mut b = Buffer::empty(a);
1072 c.render(a, &mut b);
1073 b
1074 }
1075
1076 fn count_bg(b: &Buffer, c: Color) -> usize {
1077 b.content().iter().filter(|x| x.bg == c).count()
1078 }
1079
1080 fn two(a: f64, b: f64) -> [VoronoiSite; 2] {
1081 [
1082 VoronoiSite::new("a", 0.0, 0.0).color(RED).weight(a),
1083 VoronoiSite::new("b", 10.0, 0.0).color(BLUE).weight(b),
1084 ]
1085 }
1086
1087 fn flat(c: VoronoiChart) -> VoronoiChart {
1088 c.borders(false).fill_dim(0.0).show_sites(false)
1089 }
1090
1091 #[test]
1092 fn two_sites_split_plot_in_half() {
1093 let b = render(&flat(VoronoiChart::new(two(1.0, 1.0))), 40, 10);
1094 let (l, r) = (count_bg(&b, RED), count_bg(&b, BLUE));
1095 assert!(l > 100 && r > 100 && l.abs_diff(r) <= 20, "{l} vs {r}");
1096 }
1097
1098 #[test]
1099 fn heavier_site_owns_more_when_weighted() {
1100 let area = |wt: bool| {
1101 let c = flat(VoronoiChart::new(two(100.0, 1.0)).weighted(wt));
1102 count_bg(&render(&c, 60, 12), RED)
1103 };
1104 assert!(area(true) > area(false));
1105 }
1106
1107 #[test]
1108 fn every_metric_fills_the_plot() {
1109 for m in [
1110 VoronoiMetric::Euclidean,
1111 VoronoiMetric::Manhattan,
1112 VoronoiMetric::Chebyshev,
1113 VoronoiMetric::Minkowski(3.0),
1114 VoronoiMetric::Minkowski(f64::NAN),
1115 ] {
1116 let c = VoronoiChart::new(two(1.0, 1.0)).metric(m).show_labels(true);
1117 let b = render(&c, 30, 8);
1118 assert!(b.content().iter().all(|x| x.bg != Color::Reset), "{m:?}");
1119 }
1120 }
1121
1122 #[test]
1123 fn metric_next_cycles_back() {
1124 let mut m = VoronoiMetric::Euclidean;
1125 for _ in 0..4 {
1126 m = m.next();
1127 }
1128 assert_eq!(m, VoronoiMetric::Euclidean);
1129 }
1130
1131 #[test]
1132 fn minkowski_two_matches_euclidean() {
1133 let a = render(&VoronoiChart::new(two(1.0, 1.0)), 30, 8);
1134 let b = render(
1135 &VoronoiChart::new(two(1.0, 1.0)).metric(VoronoiMetric::Minkowski(2.0)),
1136 30,
1137 8,
1138 );
1139 assert_eq!(a, b);
1140 }
1141
1142 #[test]
1143 fn labels_are_drawn() {
1144 let b = render(&VoronoiChart::new(two(1.0, 1.0)).show_labels(true), 40, 10);
1145 assert!(b.content().iter().any(|x| x.symbol() == "a"));
1146 assert!(b.content().iter().any(|x| x.symbol() == "●"));
1147 }
1148
1149 #[test]
1150 fn gradient_colors_cells_by_value() {
1151 let c = flat(VoronoiChart::new([
1152 VoronoiSite::new("lo", 0.0, 0.0).value(0.0),
1153 VoronoiSite::new("hi", 10.0, 0.0).value(10.0),
1154 ]))
1155 .gradient(Gradient::Grayscale);
1156 let b = render(&c, 40, 10);
1157 assert!(count_bg(&b, Color::Rgb(0, 0, 0)) > 50);
1158 assert!(count_bg(&b, Color::Rgb(255, 255, 255)) > 50);
1159 }
1160
1161 #[test]
1162 fn categories_share_color_and_merge_borders() {
1163 let sites = || [0.0, 4.0, 8.0].map(|x| VoronoiSite::new("s", x, 0.0).category("same"));
1164 let edges = |merge: bool| {
1165 let c = VoronoiChart::new(sites())
1166 .merge_categories(merge)
1167 .show_sites(false)
1168 .fill_dim(0.0);
1169 let b = render(&c, 40, 10);
1170 let mut set: Vec<Color> = b.content().iter().map(|x| x.bg).collect();
1172 set.sort_by_key(|c| format!("{c:?}"));
1173 set.dedup();
1174 set.len()
1175 };
1176 assert!(edges(false) > edges(true));
1177 }
1178
1179 #[test]
1180 fn knn_votes_by_majority() {
1181 let sites = [
1183 VoronoiSite::new("a1", 0.0, 0.0).category("a").color(RED),
1184 VoronoiSite::new("a2", 1.0, 0.0).category("a").color(RED),
1185 VoronoiSite::new("b1", 10.0, 0.0).category("b").color(BLUE),
1186 ];
1187 let c = |k| flat(VoronoiChart::new(sites.clone()).knn(k));
1188 let b1 = render(&c(1), 40, 8);
1189 let b3 = render(&c(3), 40, 8);
1190 assert!(count_bg(&b1, BLUE) > 0);
1191 assert_eq!(count_bg(&b3, BLUE), 0);
1192 }
1193
1194 #[test]
1195 fn farthest_flips_ownership() {
1196 let sites = || two(1.0, 1.0);
1197 let at_left = |far: bool| {
1198 let b = render(&flat(VoronoiChart::new(sites()).farthest(far)), 40, 6);
1199 b[(1, 2)].bg
1200 };
1201 assert_eq!(at_left(false), RED);
1202 assert_eq!(at_left(true), BLUE);
1203 }
1204
1205 #[test]
1206 fn shade_by_distance_varies_within_a_cell() {
1207 let c = VoronoiChart::new([VoronoiSite::new("a", 0.0, 0.0).color(Color::Rgb(200, 200, 0))])
1208 .shade_by_distance(true)
1209 .borders(false)
1210 .show_sites(false);
1211 let b = render(&c, 40, 10);
1212 let mut set: Vec<Color> = b.content().iter().map(|x| x.bg).collect();
1213 set.sort_by_key(|c| format!("{c:?}"));
1214 set.dedup();
1215 assert!(set.len() > 5);
1216 }
1217
1218 #[test]
1219 fn relax_evens_out_cells() {
1220 let sites = [(0.0, 0.0), (1.0, 0.5), (2.0, 0.0), (10.0, 10.0)].map(|(x, y)| (x, y));
1221 let build = |n| {
1222 VoronoiChart::new(
1223 sites
1224 .iter()
1225 .enumerate()
1226 .map(|(i, &(x, y))| VoronoiSite::new(format!("{i}"), x, y)),
1227 )
1228 .relax(n)
1229 };
1230 let a = render(&build(0), 50, 14);
1231 let b = render(&build(12), 50, 14);
1232 assert_ne!(a, b);
1233 }
1234
1235 #[test]
1236 fn delaunay_overlay_changes_output() {
1237 let c = VoronoiChart::new(two(1.0, 1.0));
1238 assert_ne!(
1239 render(&c, 40, 10),
1240 render(&c.clone().delaunay(true), 40, 10)
1241 );
1242 }
1243
1244 #[test]
1245 fn phase_moves_sites() {
1246 let c = VoronoiChart::new(two(1.0, 1.0));
1247 assert_ne!(render(&c, 40, 10), render(&c.clone().phase(1.3), 40, 10));
1248 }
1249
1250 #[test]
1251 fn probe_steals_area_and_draws_marker() {
1252 let c = flat(VoronoiChart::new(two(1.0, 1.0)));
1253 let before = count_bg(&render(&c, 40, 10), RED);
1254 let with = render(&c.clone().probe((2.0, 0.0)), 40, 10);
1255 assert!(count_bg(&with, RED) < before);
1256 assert!(with.content().iter().any(|x| x.symbol() == "◆"));
1257 }
1258
1259 #[test]
1260 fn select_highlights_cell() {
1261 let c = flat(VoronoiChart::new(two(1.0, 1.0)));
1262 assert_ne!(render(&c, 40, 10), render(&c.clone().select(0), 40, 10));
1263 }
1264
1265 #[test]
1266 fn axes_draw_tick_labels() {
1267 let c = VoronoiChart::new(two(1.0, 1.0)).axes(true);
1268 let b = render(&c, 50, 12);
1269 let last: String = (0..50).map(|x| b[(x, 11)].symbol().to_string()).collect();
1270 assert!(last.contains('5') || last.contains('0'), "{last}");
1271 }
1272
1273 #[test]
1274 fn square_keeps_aspect_and_bounds_are_honoured() {
1275 let c = flat(VoronoiChart::new(two(1.0, 1.0)))
1276 .bounds(-5.0, 15.0, -5.0, 5.0)
1277 .square(true);
1278 render(&c, 50, 14);
1279 render(&c.clone().bounds(f64::NAN, 1.0, 0.0, 1.0), 50, 14);
1281 render(&c.bounds(3.0, 1.0, 0.0, 1.0), 50, 14);
1282 }
1283
1284 #[test]
1285 fn clip_circle_leaves_corners_untouched() {
1286 let c = flat(VoronoiChart::new(two(1.0, 1.0))).clip_circle(true);
1287 let b = render(&c, 40, 20);
1288 assert_eq!(b[(0, 0)].bg, Color::Reset);
1289 assert_ne!(b[(20, 10)].bg, Color::Reset);
1290 }
1291
1292 #[test]
1293 fn stipple_is_deterministic_and_follows_density() {
1294 let mut d = vec![vec![0.0; 20]; 10];
1295 for row in d.iter_mut() {
1296 for v in row.iter_mut().skip(10) {
1297 *v = 1.0;
1298 }
1299 }
1300 let a = voronoi_stipple(&d, 30, 4, 9);
1301 assert_eq!(a, voronoi_stipple(&d, 30, 4, 9));
1302 assert_eq!(a.len(), 30);
1303 assert!(a.iter().all(|s| s.x >= 10.0), "dots stay in the dense half");
1304 assert!(voronoi_stipple(&[], 5, 1, 1).is_empty());
1305 assert!(voronoi_stipple(&[vec![f64::NAN, -1.0]], 5, 1, 1).is_empty());
1306 }
1307
1308 #[test]
1309 fn degenerate_inputs_do_not_panic() {
1310 let one = VoronoiChart::new([VoronoiSite::new("a", 1.0, 1.0)])
1311 .weighted(true)
1312 .relax(3)
1313 .delaunay(true)
1314 .axes(true)
1315 .knn(5)
1316 .select(0);
1317 let bad = VoronoiChart::new([
1318 VoronoiSite::new("n", f64::NAN, 1.0),
1319 VoronoiSite::new("a", 2.0, 2.0)
1320 .weight(f64::NAN)
1321 .value(f64::NAN),
1322 VoronoiSite::new("b", 2.0, 2.0).weight(-3.0).category("x"),
1323 ])
1324 .weighted(true)
1325 .show_labels(true)
1326 .gradient(Gradient::Heat)
1327 .knn(2)
1328 .phase(f64::NAN)
1329 .probe((f64::NAN, 1.0))
1330 .select(99);
1331 let all = VoronoiChart::new(two(1.0, 2.0))
1332 .farthest(true)
1333 .clip_circle(true)
1334 .axes(true)
1335 .probe((100.0, -100.0))
1336 .shade_by_distance(true);
1337 for c in [&one, &bad, &all, &VoronoiChart::new([])] {
1338 render(c, 40, 12);
1339 render(c, 1, 1);
1340 render(c, 3, 2);
1341 render(c, 0, 0);
1342 }
1343 }
1344}