Skip to main content

dear_implot3d/
builder.rs

1use crate::{Plot3DContext, Plot3DFlags, Plot3DScope, Plot3DSetup, Plot3DUi, imvec2, sys};
2
3/// Configures a 3D plot in the current ImGui window and table cell.
4pub struct Plot3DBuilder<'ui> {
5    pub(crate) ui: Plot3DUi<'ui>,
6    pub(crate) title: String,
7    pub(crate) size: [f32; 2],
8    pub(crate) flags: Plot3DFlags,
9}
10
11impl Plot3DBuilder<'_> {
12    pub fn size(mut self, size: [f32; 2]) -> Self {
13        self.size = size;
14        self
15    }
16
17    pub fn flags(mut self, flags: Plot3DFlags) -> Self {
18        self.flags = flags;
19        self
20    }
21
22    /// Draws a plot with the default setup. Returns `None` if the plot is skipped.
23    pub fn build<R>(self, draw: impl FnOnce(&Plot3DScope<'_>) -> R) -> Option<R> {
24        self.build_with_setup(|_| {}, draw)
25    }
26
27    /// Configures the axes, finishes native setup, and draws the plot. A skipped plot runs
28    /// neither closure. Both closures can use other ImGui windows and must return to the host
29    /// window and table cell to operate on this plot.
30    ///
31    /// # Panics
32    ///
33    /// Starting a second plot on this ImPlot3D context while one is open panics before BeginPlot.
34    pub fn build_with_setup<R>(
35        self,
36        setup: impl FnOnce(&Plot3DSetup<'_>),
37        draw: impl FnOnce(&Plot3DScope<'_>) -> R,
38    ) -> Option<R> {
39        if self.title.is_empty() || self.title.contains('\0') {
40            return None;
41        }
42        let ui = self.ui;
43        let _exclusive = ui.context.enter_plot();
44        ui.imgui.with_native_window_scope(|host| {
45            let began = ui.with_bound_context(|| {
46                dear_imgui_rs::with_scratch_txt(&self.title, |title| unsafe {
47                    sys::ImPlot3D_BeginPlot(
48                        title,
49                        imvec2(self.size[0], self.size[1]),
50                        self.flags.bits() as i32,
51                    )
52                })
53            });
54            if !began {
55                return None;
56            }
57            let _end = EndPlot(ui.context);
58            let plot = Plot3DScope {
59                ui,
60                host,
61                next_item: Default::default(),
62            };
63            host.run(|| setup(&Plot3DSetup { plot: &plot }));
64
65            // GetPlotRectPos calls SetupLock, which pushes a second native clip rect. Install it
66            // after all setup-closure scopes have closed and before application drawing begins.
67            ui.with_bound_context(|| unsafe { sys::ImPlot3D_GetPlotRectPos() });
68            Some(host.run(|| draw(&plot)))
69        })
70    }
71}
72
73struct EndPlot<'a>(&'a Plot3DContext);
74
75impl Drop for EndPlot<'_> {
76    fn drop(&mut self) {
77        self.0
78            .with_bound_context(|| unsafe { sys::ImPlot3D_EndPlot() });
79    }
80}