Skip to main content

crisol_plot_core/
transform.rs

1//! A data ↔ screen transform in plain numbers, with no egui types.
2
3use crisol_core::data::Bounds;
4
5use super::axis::Scale;
6
7/// A point in screen coordinates (points, origin at the top-left).
8#[derive(Clone, Copy, Debug, Default, PartialEq)]
9pub struct ScreenPoint {
10    /// Horizontal position.
11    pub x: f32,
12    /// Vertical position.
13    pub y: f32,
14}
15
16impl ScreenPoint {
17    /// The origin.
18    pub const ZERO: Self = Self { x: 0.0, y: 0.0 };
19
20    /// A point at `x`, `y`.
21    pub fn new(x: f32, y: f32) -> Self {
22        Self { x, y }
23    }
24
25    /// Whether both coordinates are finite.
26    pub fn is_finite(self) -> bool {
27        self.x.is_finite() && self.y.is_finite()
28    }
29
30    /// The Euclidean distance to `other`.
31    pub fn distance(self, other: Self) -> f32 {
32        ((self.x - other.x).powi(2) + (self.y - other.y).powi(2)).sqrt()
33    }
34
35    /// The squared Euclidean distance to `other`.
36    pub fn distance_sq(self, other: Self) -> f32 {
37        (self.x - other.x).powi(2) + (self.y - other.y).powi(2)
38    }
39
40    /// The squared length of the vector.
41    pub fn length_sq(self) -> f32 {
42        self.x * self.x + self.y * self.y
43    }
44
45    /// The dot product with `other`.
46    pub fn dot(self, other: Self) -> f32 {
47        self.x * other.x + self.y * other.y
48    }
49}
50
51impl std::ops::Sub for ScreenPoint {
52    type Output = Self;
53
54    fn sub(self, other: Self) -> Self {
55        Self::new(self.x - other.x, self.y - other.y)
56    }
57}
58
59impl std::ops::Mul<f32> for ScreenPoint {
60    type Output = Self;
61
62    fn mul(self, factor: f32) -> Self {
63        Self::new(self.x * factor, self.y * factor)
64    }
65}
66
67/// A rectangle in screen coordinates.
68#[derive(Clone, Copy, Debug, Default, PartialEq)]
69pub struct ScreenRect {
70    /// The top-left corner.
71    pub min: ScreenPoint,
72    /// The bottom-right corner.
73    pub max: ScreenPoint,
74}
75
76impl ScreenRect {
77    /// A rectangle from two opposite corners in any order.
78    pub fn from_min_max(a: ScreenPoint, b: ScreenPoint) -> Self {
79        Self {
80            min: ScreenPoint::new(a.x.min(b.x), a.y.min(b.y)),
81            max: ScreenPoint::new(a.x.max(b.x), a.y.max(b.y)),
82        }
83    }
84
85    /// A rectangle from its top-left corner and size.
86    pub fn from_min_size(min: ScreenPoint, width: f32, height: f32) -> Self {
87        Self {
88            min,
89            max: ScreenPoint::new(min.x + width, min.y + height),
90        }
91    }
92
93    /// The left edge.
94    pub fn left(self) -> f32 {
95        self.min.x
96    }
97
98    /// The right edge.
99    pub fn right(self) -> f32 {
100        self.max.x
101    }
102
103    /// The top edge.
104    pub fn top(self) -> f32 {
105        self.min.y
106    }
107
108    /// The bottom edge.
109    pub fn bottom(self) -> f32 {
110        self.max.y
111    }
112
113    /// The width.
114    pub fn width(self) -> f32 {
115        self.max.x - self.min.x
116    }
117
118    /// The height.
119    pub fn height(self) -> f32 {
120        self.max.y - self.min.y
121    }
122
123    /// Whether the rectangle has a positive area.
124    pub fn is_positive(self) -> bool {
125        self.width() > 0.0 && self.height() > 0.0
126    }
127
128    /// Whether `point` lies inside the rectangle (edges included).
129    pub fn contains(self, point: ScreenPoint) -> bool {
130        point.x >= self.min.x && point.x <= self.max.x && point.y >= self.min.y && point.y <= self.max.y
131    }
132
133    /// The rectangle grown by `amount` on every side.
134    pub fn expand(self, amount: f32) -> Self {
135        Self {
136            min: ScreenPoint::new(self.min.x - amount, self.min.y - amount),
137            max: ScreenPoint::new(self.max.x + amount, self.max.y + amount),
138        }
139    }
140}
141
142/// Which vertical axis a series is measured against.
143#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
144#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
145#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
146pub enum YAxis {
147    /// The primary axis on the left.
148    #[default]
149    Left,
150    /// The secondary axis on the right; it appears as soon as one series uses it.
151    Right,
152}
153
154/// Maps data to screen and back. Works in "scaled" space (log10 already applied), so
155/// zoom and pan are linear in what the user sees.
156#[derive(Clone, Copy, Debug)]
157pub struct Transform {
158    /// The data area on screen.
159    pub frame: ScreenRect,
160    /// Visible range in scaled units.
161    pub view: Bounds,
162    /// The horizontal scale.
163    pub x_scale: Scale,
164    /// The left vertical scale.
165    pub y_scale: Scale,
166    /// The right axis: its visible range in scaled units, and its scale.
167    pub y2: Option<SecondAxis>,
168}
169
170/// The visible range of the right y axis, in scaled units.
171#[derive(Clone, Copy, Debug, PartialEq)]
172pub struct SecondAxis {
173    /// Lower bound in scaled units.
174    pub min: f64,
175    /// Upper bound in scaled units.
176    pub max: f64,
177    /// The axis scale.
178    pub scale: Scale,
179}
180
181impl Transform {
182    /// The transform for series on `axis`: the right axis swaps in its range and scale.
183    pub fn for_axis(self, axis: YAxis) -> Self {
184        match (axis, self.y2) {
185            (YAxis::Right, Some(y2)) => Self {
186                view: Bounds {
187                    min_y: y2.min,
188                    max_y: y2.max,
189                    ..self.view
190                },
191                y_scale: y2.scale,
192                ..self
193            },
194            _ => self,
195        }
196    }
197
198    /// Map a data point to screen coordinates.
199    pub fn to_screen(self, point: [f64; 2]) -> ScreenPoint {
200        let x = self.x_scale.forward(point[0]);
201        let y = self.y_scale.forward(point[1]);
202        self.scaled_to_screen(x, y)
203    }
204
205    /// Map scaled coordinates to screen coordinates.
206    pub fn scaled_to_screen(&self, x: f64, y: f64) -> ScreenPoint {
207        let tx = (x - self.view.min_x) / self.view.width();
208        let ty = (y - self.view.min_y) / self.view.height();
209        ScreenPoint::new(
210            self.frame.left() + (tx * f64::from(self.frame.width())) as f32,
211            self.frame.bottom() - (ty * f64::from(self.frame.height())) as f32,
212        )
213    }
214
215    /// Map a screen position to scaled coordinates.
216    pub fn to_scaled(self, pos: ScreenPoint) -> [f64; 2] {
217        let tx = f64::from((pos.x - self.frame.left()) / self.frame.width());
218        let ty = f64::from((self.frame.bottom() - pos.y) / self.frame.height());
219        [
220            self.view.min_x + tx * self.view.width(),
221            self.view.min_y + ty * self.view.height(),
222        ]
223    }
224
225    /// Map a screen position to data coordinates.
226    pub fn to_data(self, pos: ScreenPoint) -> [f64; 2] {
227        let [x, y] = self.to_scaled(pos);
228        [self.x_scale.inverse(x), self.y_scale.inverse(y)]
229    }
230
231    /// Data units per screen point, in scaled space.
232    pub fn units_per_point(&self) -> [f64; 2] {
233        [
234            self.view.width() / f64::from(self.frame.width().max(1.0)),
235            self.view.height() / f64::from(self.frame.height().max(1.0)),
236        ]
237    }
238}