Skip to main content

dear_implot3d/
builder.rs

1use std::marker::PhantomData;
2
3use crate::ui::{Plot3DContextBinding, Plot3DToken};
4use crate::{Plot3DFlags, debug_begin_plot, imvec2, sys};
5use dear_imgui_rs::Ui;
6
7/// Plot builder for configuring the 3D plot
8pub struct Plot3DBuilder<'ui> {
9    pub(crate) binding: Plot3DContextBinding,
10    pub(crate) ui: &'ui Ui,
11    pub(crate) title: String,
12    pub(crate) size: Option<[f32; 2]>,
13    pub(crate) flags: Plot3DFlags,
14    pub(crate) _lifetime: PhantomData<&'ui Ui>,
15}
16
17impl<'ui> Plot3DBuilder<'ui> {
18    pub fn size(mut self, size: [f32; 2]) -> Self {
19        self.size = Some(size);
20        self
21    }
22    pub fn flags(mut self, flags: Plot3DFlags) -> Self {
23        self.flags = flags;
24        self
25    }
26    pub fn build(self) -> Option<Plot3DToken<'ui>> {
27        self.binding.with_bound_context(|| {
28            if self.title.contains('\0') {
29                return None;
30            }
31            let title = self.title;
32            let size = self.size.unwrap_or([0.0, 0.0]);
33            let ok = dear_imgui_rs::with_scratch_txt(&title, |title_ptr| unsafe {
34                // Defensive: ensure style.Colormap is in range before plotting
35                let style = sys::ImPlot3D_GetStyle();
36                if !style.is_null() {
37                    let count = sys::ImPlot3D_GetColormapCount();
38                    if count > 0 && ((*style).Colormap < 0 || (*style).Colormap >= count) {
39                        (*style).Colormap = 0;
40                    }
41                }
42                sys::ImPlot3D_BeginPlot(
43                    title_ptr,
44                    imvec2(size[0], size[1]),
45                    self.flags.bits() as i32,
46                )
47            });
48            if ok {
49                debug_begin_plot();
50                Some(Plot3DToken {
51                    binding: self.binding.clone(),
52                    ui: self.ui,
53                    _lifetime: PhantomData,
54                })
55            } else {
56                None
57            }
58        })
59    }
60}