Skip to main content

crisol_plot/plot/three/
types.rs

1//! Public 3D bounds, state, and response types.
2
3use egui::{Pos2, Rect, Response};
4
5use super::camera::{Camera3D, Projector};
6
7/// An axis-aligned range in 3D data space.
8#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
9#[derive(Clone, Copy, Debug, PartialEq)]
10pub struct Bounds3D {
11    /// Smallest x.
12    pub min_x: f64,
13    /// Largest x.
14    pub max_x: f64,
15    /// Smallest y.
16    pub min_y: f64,
17    /// Largest y.
18    pub max_y: f64,
19    /// Smallest z.
20    pub min_z: f64,
21    /// Largest z.
22    pub max_z: f64,
23}
24
25impl Bounds3D {
26    /// Bounds from two opposite corners in any order.
27    pub fn from_corners(a: [f64; 3], b: [f64; 3]) -> Self {
28        Self {
29            min_x: a[0].min(b[0]),
30            max_x: a[0].max(b[0]),
31            min_y: a[1].min(b[1]),
32            max_y: a[1].max(b[1]),
33            min_z: a[2].min(b[2]),
34            max_z: a[2].max(b[2]),
35        }
36    }
37
38    pub(super) const NOTHING: Self = Self {
39        min_x: f64::INFINITY,
40        max_x: f64::NEG_INFINITY,
41        min_y: f64::INFINITY,
42        max_y: f64::NEG_INFINITY,
43        min_z: f64::INFINITY,
44        max_z: f64::NEG_INFINITY,
45    };
46
47    pub(super) fn is_valid(&self) -> bool {
48        self.min_x.is_finite()
49            && self.max_x.is_finite()
50            && self.min_y.is_finite()
51            && self.max_y.is_finite()
52            && self.min_z.is_finite()
53            && self.max_z.is_finite()
54            && self.min_x <= self.max_x
55            && self.min_y <= self.max_y
56            && self.min_z <= self.max_z
57    }
58
59    pub(super) fn extend(&mut self, point: [f64; 3]) {
60        if point.iter().all(|value| value.is_finite()) {
61            self.min_x = self.min_x.min(point[0]);
62            self.max_x = self.max_x.max(point[0]);
63            self.min_y = self.min_y.min(point[1]);
64            self.max_y = self.max_y.max(point[1]);
65            self.min_z = self.min_z.min(point[2]);
66            self.max_z = self.max_z.max(point[2]);
67        }
68    }
69
70    pub(super) fn union(&mut self, other: &Self) {
71        if other.is_valid() {
72            self.extend([other.min_x, other.min_y, other.min_z]);
73            self.extend([other.max_x, other.max_y, other.max_z]);
74        }
75    }
76
77    /// Width in data units.
78    pub fn width(&self) -> f64 {
79        self.max_x - self.min_x
80    }
81
82    /// Depth in data units.
83    pub fn depth(&self) -> f64 {
84        self.max_y - self.min_y
85    }
86
87    /// Height in data units.
88    pub fn height(&self) -> f64 {
89        self.max_z - self.min_z
90    }
91
92    /// The center of the box.
93    pub fn center(&self) -> [f64; 3] {
94        [
95            (self.min_x + self.max_x) * 0.5,
96            (self.min_y + self.max_y) * 0.5,
97            (self.min_z + self.max_z) * 0.5,
98        ]
99    }
100
101    pub(super) fn corner(&self, x: bool, y: bool, z: bool) -> [f64; 3] {
102        [
103            if x { self.max_x } else { self.min_x },
104            if y { self.max_y } else { self.min_y },
105            if z { self.max_z } else { self.min_z },
106        ]
107    }
108}
109
110/// What a primary-button drag does in a 3D plot.
111#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
112#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
113#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
114#[non_exhaustive]
115pub enum Plot3DTool {
116    /// Drag turns the camera around the data.
117    #[default]
118    Orbit,
119    /// Drag moves the camera target across the view plane.
120    Pan,
121}
122
123#[derive(Clone, Copy, Debug, PartialEq)]
124pub(super) enum Drag {
125    Orbit,
126    Pan,
127}
128
129/// The interactive state of one 3D plot. Keep it in the application model.
130#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
131#[derive(Clone, Debug, Default)]
132pub struct Plot3DState {
133    camera: Option<Camera3D>,
134    /// The tool the primary button uses.
135    pub tool: Plot3DTool,
136    hidden: Vec<String>,
137    #[cfg_attr(feature = "serde", serde(skip))]
138    pub(super) drag: Option<Drag>,
139    #[cfg_attr(feature = "serde", serde(skip))]
140    pub(super) export_menu: bool,
141    /// Where the dragged legend sits: 0–1 across the room left in the frame.
142    legend_pos: Option<[f32; 2]>,
143    /// Series extents by fingerprint, so the automatic view does not walk every point.
144    #[cfg_attr(feature = "serde", serde(skip))]
145    pub(super) extents: Vec<(u64, Bounds3D)>,
146    #[cfg_attr(feature = "serde", serde(skip))]
147    legend_hover: Option<usize>,
148    #[cfg_attr(feature = "serde", serde(skip))]
149    legend_hover_start: f64,
150}
151
152impl Plot3DState {
153    /// The camera the user moved to, or `None` while the view is automatic.
154    pub fn camera(&self) -> Option<Camera3D> {
155        self.camera
156    }
157
158    /// Place the camera explicitly.
159    pub fn set_camera(&mut self, camera: Camera3D) {
160        self.camera = Some(camera);
161    }
162
163    /// Fit the data again and return to the configured camera angles.
164    pub fn reset_view(&mut self) {
165        self.camera = None;
166        self.drag = None;
167    }
168
169    /// Whether the camera follows the data (no orbit, pan, or zoom since the last reset).
170    pub fn is_auto(&self) -> bool {
171        self.camera.is_none()
172    }
173
174    /// Where the legend was dragged to, as fractions of the free room.
175    pub fn legend_position(&self) -> Option<[f32; 2]> {
176        self.legend_pos
177    }
178
179    /// Place the legend; `None` returns it to its configured corner.
180    pub fn set_legend_position(&mut self, position: Option<[f32; 2]>) {
181        self.legend_pos = position.map(|[x, y]| [x.clamp(0.0, 1.0), y.clamp(0.0, 1.0)]);
182    }
183
184    /// Whether the legend has hidden the series called `name`.
185    pub fn is_hidden(&self, name: &str) -> bool {
186        self.hidden.iter().any(|hidden| hidden == name)
187    }
188
189    /// Show or hide a series by name.
190    pub fn set_hidden(&mut self, name: &str, hidden: bool) {
191        self.hidden.retain(|entry| entry != name);
192        if hidden {
193            self.hidden.push(name.to_owned());
194        }
195    }
196
197    pub(super) fn legend_hover(&self) -> Option<usize> {
198        self.legend_hover
199    }
200
201    pub(super) fn legend_hover_start(&self) -> f64 {
202        self.legend_hover_start
203    }
204
205    pub(super) fn set_legend_hover(&mut self, series: Option<usize>, now: f64) {
206        if series != self.legend_hover {
207            self.legend_hover = series;
208            self.legend_hover_start = now;
209        }
210    }
211
212    /// The series whose legend row is under the pointer, if any.
213    pub fn hovered_series(&self) -> Option<usize> {
214        self.legend_hover
215    }
216}
217
218/// The nearest 3D data point under the pointer.
219#[derive(Clone, Debug, PartialEq)]
220pub struct Plot3DHover {
221    /// Series name.
222    pub series: String,
223    /// Index into the series data (a grid vertex for surfaces).
224    pub index: usize,
225    /// The point, in data coordinates.
226    pub point: [f64; 3],
227}
228
229/// What happened in the 3D plot this frame.
230pub struct Plot3DResponse {
231    /// The response of the whole plot area.
232    pub response: Response,
233    /// The nearest point within 12 pt of the pointer.
234    pub hovered: Option<Plot3DHover>,
235    /// A point that was clicked.
236    pub clicked: Option<Plot3DHover>,
237    /// The visible data bounds (the same box the axes draw).
238    pub view: Bounds3D,
239    /// The camera used this frame.
240    pub camera: Camera3D,
241    /// The data area on screen.
242    pub frame: Rect,
243    /// The toolbar's settings button was clicked.
244    pub settings_requested: bool,
245    /// The toolbar's export menu chose a format.
246    pub export_requested: Option<super::super::ExportFormat>,
247}
248
249impl Plot3DResponse {
250    /// Where a 3D data point lands on screen this frame.
251    pub fn screen_pos(&self, point: [f64; 3]) -> Option<Pos2> {
252        Projector::new(self.camera, self.frame)
253            .project(point)
254            .map(|(pos, _)| pos)
255    }
256}