Skip to main content

crisol_plot/plot/
annotations.rs

1//! Serializable chart annotations and draggable regions of interest.
2
3use egui::{Color32, Pos2, Rect, Vec2};
4
5use super::axis::Transform;
6use super::math_text::to_unicode_math;
7use super::scene::Prim;
8
9/// A text note, arrow, span, or region drawn in data coordinates.
10#[derive(Clone, Debug, PartialEq)]
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12#[cfg_attr(feature = "serde", serde(tag = "kind", rename_all = "snake_case"))]
13#[non_exhaustive]
14pub enum PlotAnnotation {
15    /// Text at a data point.
16    Text {
17        /// Anchor.
18        at: [f64; 2],
19        /// LaTeX-subset text.
20        text: String,
21        /// Point size.
22        size: f32,
23        /// Optional color.
24        color: Option<Color32>,
25    },
26    /// An arrow from `from` to `to`.
27    Arrow {
28        /// Tail.
29        from: [f64; 2],
30        /// Head.
31        to: [f64; 2],
32        /// Optional color.
33        color: Option<Color32>,
34    },
35    /// A vertical span between two x values.
36    SpanX {
37        /// First x.
38        x0: f64,
39        /// Second x.
40        x1: f64,
41        /// Optional fill.
42        color: Option<Color32>,
43    },
44    /// A horizontal span between two y values.
45    SpanY {
46        /// First y.
47        y0: f64,
48        /// Second y.
49        y1: f64,
50        /// Optional fill.
51        color: Option<Color32>,
52    },
53    /// A rectangle region; `draggable` is honoured by the host editor.
54    Rect {
55        /// First corner.
56        min: [f64; 2],
57        /// Second corner.
58        max: [f64; 2],
59        /// Stroke color.
60        color: Option<Color32>,
61        /// Fill color.
62        fill: Option<Color32>,
63        /// Whether the region can be edited by the host.
64        draggable: bool,
65    },
66    /// An ellipse region.
67    Ellipse {
68        /// Center.
69        center: [f64; 2],
70        /// Horizontal/vertical radius.
71        radius: [f64; 2],
72        /// Stroke color.
73        color: Option<Color32>,
74        /// Fill color.
75        fill: Option<Color32>,
76        /// Whether the region can be edited by the host.
77        draggable: bool,
78    },
79    /// A polygon region.
80    Polygon {
81        /// Vertices in data coordinates.
82        points: Vec<[f64; 2]>,
83        /// Stroke color.
84        color: Option<Color32>,
85        /// Fill color.
86        fill: Option<Color32>,
87        /// Whether the region can be edited by the host.
88        draggable: bool,
89    },
90}
91
92impl PlotAnnotation {
93    /// A text note.
94    pub fn text(at: [f64; 2], text: impl Into<String>) -> Self {
95        Self::Text {
96            at,
97            text: text.into(),
98            size: 12.0,
99            color: None,
100        }
101    }
102
103    /// An arrow.
104    pub fn arrow(from: [f64; 2], to: [f64; 2]) -> Self {
105        Self::Arrow { from, to, color: None }
106    }
107
108    /// A rectangle.
109    pub fn rect(min: [f64; 2], max: [f64; 2]) -> Self {
110        Self::Rect {
111            min,
112            max,
113            color: None,
114            fill: Some(Color32::from_white_alpha(20)),
115            draggable: true,
116        }
117    }
118
119    /// An ellipse.
120    pub fn ellipse(center: [f64; 2], radius: [f64; 2]) -> Self {
121        Self::Ellipse {
122            center,
123            radius,
124            color: None,
125            fill: Some(Color32::from_white_alpha(20)),
126            draggable: true,
127        }
128    }
129
130    /// A polygon.
131    pub fn polygon(points: impl IntoIterator<Item = [f64; 2]>) -> Self {
132        Self::Polygon {
133            points: points.into_iter().collect(),
134            color: None,
135            fill: Some(Color32::from_white_alpha(20)),
136            draggable: true,
137        }
138    }
139
140    /// The color, falling back to the theme accent.
141    fn color(&self, theme: &crisol_ui_kit::theme::Theme) -> Color32 {
142        match self {
143            Self::Text { color, .. }
144            | Self::Arrow { color, .. }
145            | Self::Rect { color, .. }
146            | Self::Ellipse { color, .. }
147            | Self::Polygon { color, .. } => color.unwrap_or(theme.link),
148            Self::SpanX { color, .. } | Self::SpanY { color, .. } => color.unwrap_or(theme.warning),
149        }
150    }
151}
152
153/// Append the annotations to a scene in the data layer.
154pub(super) fn paint(
155    out: &mut Vec<Prim>,
156    transform: &Transform,
157    annotations: &[PlotAnnotation],
158    theme: &crisol_ui_kit::theme::Theme,
159) {
160    let frame = transform.frame;
161    for annotation in annotations {
162        let color = annotation.color(theme);
163        match annotation {
164            PlotAnnotation::Text { at, text, size, .. } => {
165                let position = transform.to_screen(*at);
166                if position.is_finite() {
167                    out.push(Prim::Text {
168                        pos: position,
169                        text: to_unicode_math(text),
170                        size: *size,
171                        color,
172                        baseline: size * 0.8,
173                        angle: 0.0,
174                    });
175                }
176            }
177            PlotAnnotation::Arrow { from, to, .. } => {
178                let start = transform.to_screen(*from);
179                let end = transform.to_screen(*to);
180                if start.is_finite() && end.is_finite() {
181                    out.push(Prim::Line {
182                        points: vec![start, end],
183                        width: 1.5,
184                        color,
185                        dash: super::scene::Dash::Solid,
186                    });
187                    let direction = (end - start).normalized();
188                    let normal = Vec2::new(-direction.y, direction.x);
189                    let tip = end;
190                    let left = end - direction * 9.0 + normal * 4.0;
191                    let right = end - direction * 9.0 - normal * 4.0;
192                    out.push(Prim::Polygon {
193                        points: vec![tip, left, right],
194                        color,
195                    });
196                }
197            }
198            PlotAnnotation::SpanX { x0, x1, .. } => {
199                let a = transform.to_screen([*x0, transform.view.min_y]);
200                let b = transform.to_screen([*x1, transform.view.max_y]);
201                let rect = Rect::from_two_pos(a, b).intersect(frame);
202                if rect.is_positive() {
203                    out.push(Prim::Rect {
204                        rect,
205                        radius: 0.0,
206                        fill: color.gamma_multiply(0.12),
207                        stroke: Some((1.0, color.gamma_multiply(0.7))),
208                    });
209                }
210            }
211            PlotAnnotation::SpanY { y0, y1, .. } => {
212                let a = transform.to_screen([transform.view.min_x, *y0]);
213                let b = transform.to_screen([transform.view.max_x, *y1]);
214                let rect = Rect::from_two_pos(a, b).intersect(frame);
215                if rect.is_positive() {
216                    out.push(Prim::Rect {
217                        rect,
218                        radius: 0.0,
219                        fill: color.gamma_multiply(0.12),
220                        stroke: Some((1.0, color.gamma_multiply(0.7))),
221                    });
222                }
223            }
224            PlotAnnotation::Rect { min, max, fill, .. } => {
225                let a = transform.to_screen(*min);
226                let b = transform.to_screen(*max);
227                let rect = Rect::from_two_pos(a, b).intersect(frame);
228                if rect.is_positive() {
229                    out.push(Prim::Rect {
230                        rect,
231                        radius: 0.0,
232                        fill: fill.unwrap_or(Color32::TRANSPARENT),
233                        stroke: Some((1.5, color)),
234                    });
235                }
236            }
237            PlotAnnotation::Ellipse {
238                center, radius, fill, ..
239            } => {
240                let center = transform.to_screen(*center);
241                let rx = (transform
242                    .to_screen([f64::from(center.x) + radius[0], f64::from(center.y)])
243                    .x
244                    - center.x)
245                    .abs();
246                let ry = (transform
247                    .to_screen([f64::from(center.x), f64::from(center.y) + radius[1]])
248                    .y
249                    - center.y)
250                    .abs();
251                if center.is_finite() && rx > 0.5 && ry > 0.5 {
252                    let points: Vec<Pos2> = (0..48)
253                        .map(|index| {
254                            let angle = index as f32 / 48.0 * std::f32::consts::TAU;
255                            Pos2::new(center.x + rx * angle.cos(), center.y + ry * angle.sin())
256                        })
257                        .collect();
258                    out.push(Prim::Polygon {
259                        points: points.clone(),
260                        color: fill.unwrap_or(Color32::TRANSPARENT),
261                    });
262                    for pair in points.windows(2) {
263                        out.push(Prim::Line {
264                            points: pair.to_vec(),
265                            width: 1.5,
266                            color,
267                            dash: super::scene::Dash::Solid,
268                        });
269                    }
270                }
271            }
272            PlotAnnotation::Polygon { points, fill, .. } => {
273                let points: Vec<Pos2> = points
274                    .iter()
275                    .map(|point| transform.to_screen(*point))
276                    .filter(|point| point.is_finite())
277                    .collect();
278                if points.len() >= 3 {
279                    out.push(Prim::Polygon {
280                        points: points.clone(),
281                        color: fill.unwrap_or(Color32::TRANSPARENT),
282                    });
283                    for index in 0..points.len() {
284                        out.push(Prim::Line {
285                            points: vec![points[index], points[(index + 1) % points.len()]],
286                            width: 1.5,
287                            color,
288                            dash: super::scene::Dash::Solid,
289                        });
290                    }
291                }
292            }
293        }
294    }
295}
296
297/// A rectangle's data-space width/height, useful for an editor.
298pub fn region_size(min: [f64; 2], max: [f64; 2]) -> [f64; 2] {
299    [(max[0] - min[0]).abs(), (max[1] - min[1]).abs()]
300}
301
302#[cfg(test)]
303mod tests {
304    use super::*;
305    use crate::plot::{Bounds, Scale};
306    use egui::{Rect, pos2};
307
308    fn transform() -> Transform {
309        Transform {
310            frame: Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 100.0)),
311            view: Bounds::from_corners([0.0, 0.0], [10.0, 10.0]),
312            x_scale: Scale::Linear,
313            y_scale: Scale::Linear,
314            y2: None,
315        }
316    }
317
318    #[test]
319    fn annotations_become_prims() {
320        let theme = crisol_ui_kit::theme::Theme::dark();
321        let mut prims = Vec::new();
322        let annotations = vec![
323            PlotAnnotation::text([1.0, 1.0], r"$\alpha$"),
324            PlotAnnotation::arrow([1.0, 1.0], [5.0, 5.0]),
325            PlotAnnotation::rect([2.0, 2.0], [4.0, 4.0]),
326            PlotAnnotation::ellipse([5.0, 5.0], [1.0, 2.0]),
327            PlotAnnotation::polygon([[1.0, 2.0], [3.0, 2.0], [2.0, 4.0]]),
328        ];
329        paint(&mut prims, &transform(), &annotations, &theme);
330        assert!(prims.len() > 5);
331        assert!(prims.iter().any(|prim| matches!(prim, Prim::Text { .. })));
332    }
333
334    #[test]
335    fn regions_have_serializable_geometry() {
336        assert_eq!(region_size([0.0, 0.0], [2.0, 3.0]), [2.0, 3.0]);
337    }
338}