Skip to main content

crisol_plot/plot/three/
export.rs

1//! SVG and PNG export from the same 3D scene the screen draws.
2
3use egui::{Color32, Context, Pos2, Rect, Vec2};
4
5use super::super::export::{png, svg};
6use super::super::scene::{Measure, Scene};
7use super::super::{ExportOptions, layout::Colors};
8use super::camera::Projector;
9use super::layout;
10use super::{Plot3D, Plot3DState};
11
12impl Plot3D<'_> {
13    fn export_scene(&self, ctx: &Context, state: &Plot3DState, options: &ExportOptions) -> (Scene, Option<Color32>) {
14        let measure = Measure {
15            ctx: ctx.clone(),
16            pixels_per_point: 1.0,
17        };
18        let rect = Rect::from_min_size(
19            Pos2::ZERO,
20            Vec2::new(options.width.max(120.0), options.height.max(120.0)),
21        );
22        let layout = layout::layout(&measure, &self.config, rect);
23        let bounds = self.auto_bounds(state);
24        let camera = self.camera(state, bounds, layout.frame);
25        let projector = Projector::new(camera, layout.frame);
26        let visuals = ctx.style_of(ctx.theme()).visuals.clone();
27        let mut colors = Colors::from_colors(&self.config.colors, &visuals);
28        let canvas = if options.transparent {
29            colors.canvas.take()
30        } else {
31            Some(colors.canvas.take().unwrap_or(visuals.panel_fill))
32        };
33        let theme = crisol_ui_kit::theme::current(ctx);
34        let (scene, _) = super::scene::build_scene(
35            &measure, self, &layout, &projector, bounds, state, &colors, &theme, true, 0.0, false,
36        );
37        (scene, canvas)
38    }
39
40    /// The 3D plot as a standalone SVG document.
41    pub fn to_svg(&self, ctx: &Context, state: &Plot3DState, options: &ExportOptions) -> String {
42        let (scene, canvas) = self.export_scene(ctx, state, options);
43        svg(&scene, canvas)
44    }
45
46    /// The 3D plot as PNG bytes at `options.scale` pixels per point.
47    ///
48    /// # Errors
49    /// When the image is too large to allocate or encoding fails.
50    pub fn to_png(&self, ctx: &Context, state: &Plot3DState, options: &ExportOptions) -> Result<Vec<u8>, String> {
51        png(&self.to_svg(ctx, state, options), options.scale)
52    }
53}