返回 CodeWhale
dot_whale.rs
1 use std::collections::BTreeMap;
2
3 use ratatui::{
4 buffer::Buffer,
5 layout::{Alignment, Rect},
6 style::Style,
7 widgets::{Paragraph, Widget, Wrap},
8 };
9
10 use crate::{Paint, Role, Theme, color, text};
11
12 #[derive(Clone, Copy, Debug)]
13 pub struct DotWhale<'a> {
14 points: &'a [[f64; 2]],
15 materials: &'a [[f64; 4]],
16 caption: &'a str,
17 action_id: Option<&'a str>,
18 hollow: bool,
19 }
20
21 impl<'a> DotWhale<'a> {
22 #[must_use]
23 pub const fn new(points: &'a [[f64; 2]], materials: &'a [[f64; 4]]) -> Self {
24 Self {
25 points,
26 materials,
27 caption: "Activity unobserved",
28 action_id: None,
29 hollow: false,
30 }
31 }
32
33 #[must_use]
34 pub const fn caption(mut self, caption: &'a str) -> Self {
35 self.caption = caption;
36 self
37 }
38
39 #[must_use]
40 pub const fn action_id(mut self, action_id: Option<&'a str>) -> Self {
41 self.action_id = action_id;
42 self
43 }
44
45 #[must_use]
46 pub const fn hollow(mut self, hollow: bool) -> Self {
47 self.hollow = hollow;
48 self
49 }
50
51 fn valid(&self) -> bool {
52 !self.points.is_empty()
53 && self.points.len() <= 980
54 && self.points.len() == self.materials.len()
55 && self
56 .points
57 .iter()
58 .flatten()
59 .all(|n| n.is_finite() && (-1.0..=1.0).contains(n))
60 && self.materials.iter().all(|m| {
61 m[..3]
62 .iter()
63 .all(|n| n.is_finite() && (0.0..=255.0).contains(n))
64 && m[3].is_finite()
65 && (0.0..=1.0).contains(&m[3])
66 })
67 }
68
69 fn label(&self, theme: &Theme) -> String {
70 let caption = text::display_safe(self.caption);
71 let caption = text::truncate(&caption, 192, theme.ascii());
72 let Some(action) = self.action_id.filter(|id| !id.is_empty()) else {
73 return caption.into_owned();
74 };
75 let action = text::display_safe(action);
76 let action = text::truncate(&action, 256, theme.ascii());
77 if caption.is_empty() {
78 action.into_owned()
79 } else {
80 format!(
81 "{caption} {} {action}",
82 if theme.ascii() { "/" } else { "·" }
83 )
84 }
85 }
86 }
87
88 #[derive(Default)]
89 struct DotCell {
90 bits: u8,
91 pigment: [f64; 3],
92 strength: f64,
93 }
94
95 fn caption(label: &str, area: Rect, buf: &mut Buffer, style: Style) {
96 let width = area.width.min(512);
97 if width == 0 || area.height == 0 {
98 return;
99 }
100 let paragraph = Paragraph::new(label)
101 .style(style)
102 .alignment(Alignment::Center)
103 .wrap(Wrap { trim: false });
104 let height = paragraph.line_count(width).min(usize::from(area.height)) as u16;
105 if height == 0 {
106 return;
107 }
108 let x = u32::from(area.x) + u32::from((area.width - width) / 2);
109 let y = u32::from(area.y) + u32::from((area.height - height) / 2);
110 let mut local = Buffer::empty(Rect::new(0, 0, width, height));
111 paragraph.render(local.area, &mut local);
112 for row in 0..height {
113 for col in 0..width {
114 let (Ok(x), Ok(y)) = (
115 u16::try_from(x + u32::from(col)),
116 u16::try_from(y + u32::from(row)),
117 ) else {
118 continue;
119 };
120 if let Some(cell) = buf.cell_mut((x, y)) {
121 let background = cell.bg;
122 *cell = local[(col, row)].clone();
123 cell.set_bg(background);
124 }
125 }
126 }
127 }
128
129 impl Paint for DotWhale<'_> {
130 fn height(&self, width: u16, theme: &Theme) -> u16 {
131 if width == 0 {
132 return 0;
133 }
134 let label = self.label(theme);
135 let rows = Paragraph::new(label)
136 .wrap(Wrap { trim: false })
137 .line_count(width.min(512))
138 .min(512) as u16;
139 if theme.ascii() || width < 12 || !self.valid() {
140 rows
141 } else {
142 rows.saturating_add((width / 2).clamp(4, 20))
143 }
144 }
145
146 fn paint(&self, area: Rect, buf: &mut Buffer, theme: &Theme) {
147 if area.is_empty() || area.intersection(buf.area).is_empty() {
148 return;
149 }
150 let label = self.label(theme);
151 let label_height = Paragraph::new(label.as_str())
152 .wrap(Wrap { trim: false })
153 .line_count(area.width.min(512))
154 .min(usize::from(area.height)) as u16;
155 let art_height = area.height.saturating_sub(label_height);
156 if theme.ascii() || area.width < 12 || art_height < 4 || !self.valid() {
157 caption(&label, area, buf, theme.fg(Role::Accent));
158 return;
159 }
160 let width = f64::from(area.width) * 2.0;
161 let scale = ((width - 1.0).min(f64::from(art_height) * 4.0 - 1.0) / 2.0).min(32.0);
162 let art_height = ((2.0 * scale + 1.0) / 4.0).ceil() as u16;
163 let top = area
164 .y
165 .saturating_add(area.height.saturating_sub(art_height + label_height) / 2);
166 let height = f64::from(art_height) * 4.0;
167 let bits = [[1, 8], [2, 16], [4, 32], [64, 128]];
168 let mut cells: BTreeMap<(u16, u16), DotCell> = BTreeMap::new();
169 for (point, material) in self.points.iter().zip(self.materials) {
170 if material[3] <= 0.01 {
171 continue;
172 }
173 let x = ((width - 1.0) / 2.0 + point[0] * scale).round() as u32;
174 let y = ((height - 1.0) / 2.0 + point[1] * scale).round() as u32;
175 let (Ok(col), Ok(row)) = (
176 u16::try_from(u32::from(area.x) + x / 2),
177 u16::try_from(u32::from(top) + y / 4),
178 ) else {
179 continue;
180 };
181 if !buf.area.contains((col, row).into()) {
182 continue;
183 }
184 let cell = cells.entry((col, row)).or_default();
185 cell.bits |= bits[(y % 4) as usize][(x % 2) as usize];
186 if material[3] > cell.strength {
187 cell.strength = material[3];
188 cell.pigment = [material[0], material[1], material[2]];
189 }
190 }
191 for ((x, y), dot) in cells {
192 if let Some(cell) = buf.cell_mut((x, y)) {
193 let style = if self.hollow {
194 theme.fg(Role::Muted)
195 } else {
196 color::prepared_ink(
197 dot.pigment.map(|v| v.round() as u8),
198 dot.strength as f32,
199 cell.bg,
200 theme,
201 )
202 };
203 let glyph = char::from_u32(0x2800 + u32::from(dot.bits)).unwrap_or(' ');
204 let mut encoded = [0; 4];
205 cell.set_symbol(glyph.encode_utf8(&mut encoded))
206 .set_style(style);
207 }
208 }
209 caption(
210 &label,
211 Rect::new(
212 area.x,
213 top.saturating_add(art_height),
214 area.width,
215 label_height,
216 ),
217 buf,
218 theme.fg(Role::Accent),
219 );
220 }
221 }
222
222 lines RUST