Skip to main content

crisol_plot/plot/three/
mod.rs

1//! A native 3D plot: orbit camera, x/y/z axes, surfaces, bars, lines, and scatter.
2//!
3//! It shares the crate's themes, icon cache, legend hover animations, direction arrow,
4//! hover popup, and SVG/PNG export with [`super::Plot`], but has its own camera state.
5//!
6//! ```
7//! use crisol_plot::plot::{Plot3D, Plot3DState, Series3D};
8//! # let ctx = egui::Context::default();
9//! # let mut icons = crisol_plot::Icons::new();
10//! let mut state = Plot3DState::default();
11//! let points: Vec<[f64; 3]> = (0..80).map(|index| {
12//!     let angle = index as f64 * 0.2;
13//!     [angle.cos() * 2.0, angle.sin() * 2.0, index as f64 * 0.08]
14//! }).collect();
15//! # let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {
16//! Plot3D::new("helix")
17//!     .title("Helix")
18//!     .series(Series3D::line("orbit", &points))
19//!     .show(ui, &mut icons, &mut state);
20//! # });
21//! # output.textures_delta.clear();
22//! ```
23
24mod axes;
25mod builder;
26mod camera;
27mod config;
28mod export;
29mod interact;
30mod layout;
31mod legend;
32mod paint;
33mod scene;
34mod series;
35mod types;
36mod widgets;
37
38use egui::{Id, Pos2, Sense, Ui, vec2};
39
40use super::layout::Colors;
41use super::scene::Measure;
42use camera::Projector;
43pub use camera::{Camera3D, Projection};
44pub use config::{Plot3DConfig, Series3DStyle, Surface3DConfig};
45use crisol_ui_kit::Icons;
46use crisol_ui_kit::components::IconComponent;
47pub use series::{Series3D, Surface};
48pub use types::{Bounds3D, Plot3DHover, Plot3DResponse, Plot3DState, Plot3DTool};
49
50/// The 3D plot builder. Add series, then call `show` with the icon cache and a
51/// [`Plot3DState`].
52#[derive(Clone)]
53pub struct Plot3D<'a> {
54    pub(super) id: Id,
55    pub(super) series: Vec<Series3D<'a>>,
56    pub(super) config: Plot3DConfig,
57    width: Option<f32>,
58    height: Option<f32>,
59    include: Bounds3D,
60    pub(super) settings_button: bool,
61    pub(super) export_button: bool,
62}
63
64impl<'a> Plot3D<'a> {
65    /// Paint the plot and handle its interaction.
66    pub fn show(self, ui: &mut Ui, icons: &mut Icons, state: &mut Plot3DState) -> Plot3DResponse {
67        let available = ui.available_size();
68        let width = self.width.unwrap_or(available.x).max(120.0);
69        let height = self
70            .height
71            .unwrap_or(if available.y.is_finite() && available.y < 4000.0 {
72                available.y
73            } else {
74                320.0
75            })
76            .max(120.0);
77        let (rect, response) = ui.allocate_exact_size(vec2(width, height), Sense::click_and_drag());
78        let measure = Measure {
79            ctx: ui.ctx().clone(),
80            pixels_per_point: ui.ctx().pixels_per_point(),
81        };
82        self.refresh_extents(state);
83        let bounds = self.auto_bounds(state);
84        let layout = layout::layout(&measure, &self.config, rect);
85        let camera = self.camera(state, bounds, layout.frame);
86        interact::interact(ui, &response, layout.frame, state, camera);
87        let camera = self.camera(state, bounds, layout.frame);
88        let projector = Projector::new(camera, layout.frame);
89        let pointer = response.hover_pos().filter(|pos| layout.frame.contains(*pos));
90
91        let now = ui.input(|input| input.time);
92        let legend = legend::layout(&measure, &self, layout.frame, state, true);
93        let legend_rect = legend
94            .as_ref()
95            .map(|legend| widgets::legend(ui, &self, legend, layout.frame, state));
96        let motion = crisol_ui_kit::theme::motion_enabled(ui.ctx());
97        let theme = crisol_ui_kit::theme::current(ui.ctx());
98        let colors = Colors::from_colors(&self.config.colors, ui.visuals());
99        #[allow(unused_mut)]
100        let (mut scene, drawn) = scene::build_scene(
101            &measure, &self, &layout, &projector, bounds, state, &colors, &theme, false, now, motion,
102        );
103        #[cfg(feature = "gpu")]
104        if self.config.renderer == super::Renderer::Gpu {
105            let triangles = super::gpu::scene_triangles(&mut scene);
106            super::gpu::paint_triangles(ui, layout.frame, &triangles, self.id);
107        }
108        let painter = ui.painter_at(rect);
109        super::scene::paint(&painter, &painter.with_clip_rect(layout.frame), scene);
110
111        let toolbar = widgets::toolbar(ui, icons, &self, layout.frame, camera, state);
112        let blocked = |pos: Pos2| {
113            legend_rect.is_some_and(|rect| rect.contains(pos)) || toolbar.rect.is_some_and(|rect| rect.contains(pos))
114        };
115        if state.drag.is_none() && toolbar.rect.zip(pointer).is_some_and(|(rect, pos)| rect.contains(pos)) {
116            ui.ctx().set_cursor_icon(egui::CursorIcon::Default);
117        }
118        let hovered = pointer
119            .filter(|pos| !blocked(*pos) && state.drag.is_none())
120            .and_then(|pos| interact::hover(ui, &self, &projector, pos, &theme, bounds, &drawn));
121        let clicked = (response.clicked() && state.drag.is_none())
122            .then(|| hovered.clone())
123            .flatten();
124        let view = Bounds3D {
125            min_x: self.config.x.scale.inverse(bounds.min_x),
126            max_x: self.config.x.scale.inverse(bounds.max_x),
127            min_y: self.config.y.scale.inverse(bounds.min_y),
128            max_y: self.config.y.scale.inverse(bounds.max_y),
129            min_z: self.config.z.scale.inverse(bounds.min_z),
130            max_z: self.config.z.scale.inverse(bounds.max_z),
131        };
132        Plot3DResponse {
133            response,
134            hovered,
135            clicked,
136            view,
137            camera,
138            frame: layout.frame,
139            settings_requested: toolbar.settings,
140            export_requested: toolbar.export,
141        }
142    }
143}
144
145impl IconComponent for Plot3D<'_> {
146    type Output = Plot3DResponse;
147
148    fn show(self, ui: &mut Ui, icons: &mut Icons) -> Plot3DResponse {
149        let id = self.id;
150        let mut state = ui
151            .ctx()
152            .data_mut(|data| data.get_temp::<Plot3DState>(id).unwrap_or_default());
153        let response = Plot3D::show(self, ui, icons, &mut state);
154        ui.ctx().data_mut(|data| data.insert_temp(id, state));
155        response
156    }
157}
158
159#[cfg(test)]
160mod tests {
161    use super::*;
162
163    fn plot<'a>() -> Plot3D<'a> {
164        Plot3D::new("test")
165            .series(Series3D::line("a", vec![[0.0, 0.0, 0.0], [1.0, 1.0, 1.0]]))
166            .series(Series3D::line("b", vec![[0.0, 1.0, 0.0], [1.0, 0.0, 1.0]]))
167            .series(Series3D::line("c", vec![[1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]))
168    }
169
170    #[test]
171    fn the_hovered_series_draws_last_without_moving_the_legend() {
172        let plot = plot();
173        let mut state = Plot3DState::default();
174        assert_eq!(plot.draw_order(&state), [0, 1, 2]);
175        state.set_legend_hover(Some(0), 0.0);
176        assert_eq!(plot.draw_order(&state), [1, 2, 0]);
177        state.set_hidden("a", true);
178        assert_eq!(plot.draw_order(&state), [0, 1, 2]);
179    }
180
181    #[test]
182    fn auto_bounds_include_every_visible_series_and_the_include_point() {
183        let plot = plot().include([4.0, 5.0, 6.0]);
184        let mut state = Plot3DState::default();
185        state.set_hidden("c", true);
186        let bounds = plot.auto_bounds(&state);
187        assert!(bounds.max_z > 6.0);
188        assert!(bounds.max_x > 4.0 && bounds.max_y > 5.0);
189    }
190
191    #[test]
192    fn builders_write_the_config() {
193        let plot = Plot3D::new("builders")
194            .title("3D")
195            .x_label("x")
196            .y_label("y")
197            .z_label("z")
198            .projection(Projection::Orthographic)
199            .direction_arrow(true);
200        assert_eq!(plot.config.title.as_deref(), Some("3D"));
201        assert_eq!(plot.config.x.label.as_deref(), Some("x"));
202        assert_eq!(plot.config.projection, Projection::Orthographic);
203        assert!(plot.config.direction.enabled);
204    }
205
206    #[test]
207    fn the_camera_round_trips_and_stays_above_the_data() {
208        let bounds = Bounds3D::from_corners([-1.0, -1.0, -1.0], [1.0, 1.0, 1.0]);
209        let frame = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(600.0, 400.0));
210        let camera = Camera3D::auto(bounds, &Plot3DConfig::default(), frame);
211        let projector = Projector::new(camera, frame);
212        assert!(projector.project([0.0, 0.0, 0.0]).is_some());
213        assert!(projector.eye()[2] > 0.0);
214    }
215
216    #[test]
217    fn scene_primitives_stay_inside_the_frame() {
218        let ctx = egui::Context::default();
219        let mut output = ctx.run_ui(egui::RawInput::default(), |_| {});
220        output.textures_delta.clear();
221        let measure = Measure {
222            ctx: ctx.clone(),
223            pixels_per_point: 1.0,
224        };
225        let plot = Plot3D::new("scene").series(Series3D::surface_fn(
226            "terrain",
227            -2.0..=2.0,
228            -2.0..=2.0,
229            [20, 20],
230            |x, y| (x * x + y * y).sin(),
231        ));
232        let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(760.0, 520.0));
233        let layout = layout::layout(&measure, &plot.config, rect);
234        let bounds = plot.auto_bounds(&Plot3DState::default());
235        let camera = Camera3D::auto(bounds, &plot.config, layout.frame);
236        let projector = Projector::new(camera, layout.frame);
237        let colors = Colors::resolve(&super::super::PlotConfig::default(), &ctx.style_of(ctx.theme()).visuals);
238        let theme = crisol_ui_kit::theme::Theme::dark();
239        let (scene, _) = scene::build_scene(
240            &measure,
241            &plot,
242            &layout,
243            &projector,
244            bounds,
245            &Plot3DState::default(),
246            &colors,
247            &theme,
248            false,
249            0.0,
250            false,
251        );
252        let mut largest = 0.0_f32;
253        for prim in scene.under.iter().chain(&scene.data).chain(&scene.over) {
254            if let super::super::scene::Prim::Line { points, .. } = prim {
255                for pair in points.windows(2) {
256                    largest = largest.max(pair[0].distance(pair[1]));
257                }
258            }
259        }
260        assert!(largest < layout.frame.width(), "a primitive spans {largest} pt");
261    }
262
263    #[test]
264    fn edge_on_bar_faces_do_not_emit_spikes() {
265        let ctx = egui::Context::default();
266        let mut output = ctx.run_ui(egui::RawInput::default(), |_| {});
267        output.textures_delta.clear();
268        let measure = Measure {
269            ctx: ctx.clone(),
270            pixels_per_point: 1.0,
271        };
272        let cells: Vec<[f64; 3]> = (0..8)
273            .flat_map(|x| (0..8).map(move |y| [f64::from(x), f64::from(y), 1.0 + f64::from((x + y) % 5)]))
274            .collect();
275        let plot = Plot3D::new("bars").series(Series3D::bars("revenue", cells));
276        let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(1120.0, 760.0));
277        let layout = layout::layout(&measure, &plot.config, rect);
278        let bounds = plot.auto_bounds(&Plot3DState::default());
279        let camera = Camera3D {
280            projection: Projection::Orthographic,
281            yaw: 0.02,
282            pitch: 0.35,
283            ..Camera3D::auto(bounds, &plot.config, layout.frame)
284        };
285        let projector = Projector::new(camera, layout.frame);
286        let colors = Colors::resolve(&super::super::PlotConfig::default(), &ctx.style_of(ctx.theme()).visuals);
287        let theme = crisol_ui_kit::theme::Theme::dark();
288        let (scene, _) = scene::build_scene(
289            &measure,
290            &plot,
291            &layout,
292            &projector,
293            bounds,
294            &Plot3DState::default(),
295            &colors,
296            &theme,
297            false,
298            0.0,
299            false,
300        );
301        let limit = layout.frame.width().max(layout.frame.height()) * 1.5;
302        for prim in scene.data.iter() {
303            match prim {
304                super::super::scene::Prim::Polygon { .. } => panic!("bar fills use quad meshes, not polygons"),
305                super::super::scene::Prim::Line { points, .. } => {
306                    for pair in points.windows(2) {
307                        assert!(
308                            pair[0].distance(pair[1]) < limit,
309                            "a face outline spans {} pt",
310                            pair[0].distance(pair[1])
311                        );
312                    }
313                }
314                _ => {}
315            }
316        }
317    }
318}