cas_graph/graph/
point.rs

1/// A pair of `(x, y)` values in **graph** units.
2#[derive(Clone, Copy, Debug, Default, PartialEq)]
3pub struct GraphPoint<T>(pub T, pub T);
4
5impl<T> From<(T, T)> for GraphPoint<T> {
6    fn from((x, y): (T, T)) -> GraphPoint<T> {
7        GraphPoint(x, y)
8    }
9}
10
11impl<T> GraphPoint<T>
12where
13    T: Into<f64> + Copy,
14{
15    /// Returns the distance between two points.
16    pub fn distance(self, other: GraphPoint<T>) -> f64 {
17        (self.0.into() - other.0.into()).hypot(self.1.into() - other.1.into())
18    }
19}
20
21/// A pair of `(x, y)` values in **canvas** units.
22#[derive(Clone, Copy, Debug, Default, PartialEq)]
23pub struct CanvasPoint<T>(pub T, pub T);
24
25impl<T> From<(T, T)> for CanvasPoint<T> {
26    fn from((x, y): (T, T)) -> CanvasPoint<T> {
27        CanvasPoint(x, y)
28    }
29}
30
31/// A point to draw in a graph with style information.
32///
33/// The default point color is red.
34#[derive(Clone, Debug, PartialEq)]
35pub struct Point<T> {
36    /// The coordinates of the point to draw.
37    pub coordinates: GraphPoint<T>,
38
39    /// The color of the point, given as an RGB tuple with each value in the
40    /// range 0.0 to 1.0.
41    ///
42    /// The default color is a solid red.
43    pub color: (f64, f64, f64),
44
45    /// The label of the point. If omitted, the point will be labeled with its
46    /// coordinates, to a maximum of 3 decimal places for each coordinate.
47    pub label: Option<String>,
48}
49
50impl Default for Point<f64> {
51    fn default() -> Point<f64> {
52        Point {
53            coordinates: (0.0, 0.0).into(),
54            color: (1.0, 0.0, 0.0),
55            label: None,
56        }
57    }
58}
59
60impl<T> Point<T>
61where
62    T: Into<f64> + Copy,
63    Point<T>: Default,
64{
65    /// Creates a new point with the given coordinates.
66    pub fn new(coordinates: impl Into<GraphPoint<T>>) -> Point<T> {
67        Point {
68            coordinates: coordinates.into(),
69            ..Default::default()
70        }
71    }
72
73    /// Sets the color of the point.
74    ///
75    /// Returns the point itself to allow chaining.
76    pub fn with_color(mut self, color: (f64, f64, f64)) -> Point<T> {
77        self.color = color;
78        self
79    }
80
81    /// Sets the label of the point.
82    ///
83    /// Returns the point itself to allow chaining.
84    pub fn with_label(mut self, label: String) -> Point<T> {
85        self.label = Some(label);
86        self
87    }
88}
89
90impl<T> From<(T, T)> for Point<T>
91where
92    Point<T>: Default,
93{
94    fn from((x, y): (T, T)) -> Point<T> {
95        Point {
96            coordinates: GraphPoint(x, y),
97            ..Default::default()
98        }
99    }
100}