Skip to main content

dear_implot3d/
context.rs

1use crate::sys;
2use crate::ui::Plot3DUi;
3use dear_imgui_rs::{Context, ContextBinding, ContextThreadLease, Ui};
4use std::cell::{RefCell, RefMut};
5
6/// Plot3D context wrapper
7///
8/// Plotting requires the originating Dear ImGui context. The native plot allocation
9/// reserves its owner thread until this `Plot3DContext` is dropped.
10///
11/// # Example
12///
13/// ```no_run
14/// use dear_imgui_rs::*;
15/// use dear_implot3d::*;
16///
17/// let mut imgui_ctx = Context::create();
18/// let plot3d_ctx = Plot3DContext::create(&imgui_ctx);
19///
20/// // In your main loop:
21/// let ui = imgui_ctx.frame();
22/// let plot_ui = plot3d_ctx.get_plot_ui(ui);
23/// ```
24pub struct Plot3DContext {
25    pub(crate) raw: *mut sys::ImPlot3DContext,
26    pub(crate) imgui_binding: ContextBinding,
27    plot_scope: RefCell<()>,
28    _thread_lease: ContextThreadLease,
29}
30
31impl Plot3DContext {
32    pub(crate) fn enter_plot(&self) -> RefMut<'_, ()> {
33        self.plot_scope
34            .try_borrow_mut()
35            .expect("ImPlot3D requires a context with no open plot")
36    }
37
38    /// Try to create a new ImPlot3D context.
39    ///
40    /// This should be called once after creating your ImGui context.
41    pub fn try_create(imgui: &Context) -> dear_imgui_rs::ImGuiResult<Self> {
42        let thread_lease = ContextThreadLease::acquire()?;
43        let imgui_binding = imgui.binding();
44        let ctx = imgui_binding.with_bound_context(|| unsafe {
45            let prev_plot = sys::ImPlot3D_GetCurrentContext();
46            let ctx = sys::ImPlot3D_CreateContext();
47            if sys::ImPlot3D_GetCurrentContext() != prev_plot {
48                sys::ImPlot3D_SetCurrentContext(prev_plot);
49            }
50            ctx
51        });
52        if ctx.is_null() {
53            return Err(dear_imgui_rs::ImGuiError::context_creation(
54                "ImPlot3D_CreateContext returned null",
55            ));
56        }
57
58        Ok(Self {
59            raw: ctx,
60            imgui_binding,
61            plot_scope: RefCell::default(),
62            _thread_lease: thread_lease,
63        })
64    }
65
66    /// Create a new ImPlot3D context (panics on error).
67    pub fn create(imgui: &Context) -> Self {
68        Self::try_create(imgui).expect("Failed to create ImPlot3D context")
69    }
70
71    /// Get the raw ImPlot3D context pointer without changing the current context.
72    ///
73    /// # Safety
74    ///
75    /// Both contexts must be alive and correctly bound. Keep wrapper-owned plots, cached
76    /// items and style stacks intact. Balance raw Begin/End and Push/Pop pairs within their
77    /// own scopes. This wrapper retains sole ownership of the native allocation.
78    pub unsafe fn raw(&self) -> *mut sys::ImPlot3DContext {
79        self.raw
80    }
81
82    /// Get a per-frame plotting interface
83    ///
84    /// Call this once per frame to get access to plotting functions.
85    /// The returned `Plot3DUi` borrows both this plot context and the frame.
86    ///
87    /// ```compile_fail,E0515
88    /// use dear_imgui_rs::Ui;
89    /// use dear_implot3d::{Plot3DContext, Plot3DUi};
90    /// fn view(ui: &Ui, plot: Plot3DContext) -> Plot3DUi<'_> {
91    ///     plot.get_plot_ui(ui)
92    /// }
93    /// ```
94    pub fn get_plot_ui<'ui>(&'ui self, ui: &'ui Ui) -> Plot3DUi<'ui> {
95        assert_eq!(
96            ui.context_id(),
97            self.imgui_binding.id(),
98            "dear-implot3d: Plot3DContext::get_plot_ui() requires a Ui from the owning ImGui context"
99        );
100        Plot3DUi {
101            imgui: ui,
102            context: self,
103        }
104    }
105}
106
107impl Drop for Plot3DContext {
108    fn drop(&mut self) {
109        // DestroyContext frees the plot's own allocations and clears GImPlot3D only if current.
110        let raw = self.raw;
111        if self
112            .imgui_binding
113            .try_with_bound_context(|| unsafe { sys::ImPlot3D_DestroyContext(raw) })
114            .is_err()
115        {
116            // The thread lease still covers the allocator after the ImGui context has gone.
117            unsafe { sys::ImPlot3D_DestroyContext(raw) };
118        }
119    }
120}
121
122#[cfg(test)]
123mod tests {
124    use super::Plot3DContext;
125    use crate::{Context, sys};
126    use std::mem::{align_of, size_of};
127    use std::sync::{Mutex, OnceLock};
128
129    fn test_guard() -> std::sync::MutexGuard<'static, ()> {
130        static GUARD: OnceLock<Mutex<()>> = OnceLock::new();
131        GUARD
132            .get_or_init(|| Mutex::new(()))
133            .lock()
134            .unwrap_or_else(|err| err.into_inner())
135    }
136
137    #[test]
138    fn ffi_layout_implot3d_point_is_3_f64() {
139        assert_eq!(size_of::<sys::ImPlot3DPoint>(), 3 * size_of::<f64>());
140        assert_eq!(align_of::<sys::ImPlot3DPoint>(), align_of::<f64>());
141    }
142
143    #[test]
144    fn plot3d_ui_binds_own_context() {
145        let _guard = test_guard();
146        let imgui = Context::create();
147        let plot_a = Plot3DContext::create(&imgui);
148        let raw_a = plot_a.raw;
149        let plot_b = Plot3DContext::create(&imgui);
150        let raw_b = plot_b.raw;
151
152        unsafe { sys::ImPlot3D_SetCurrentContext(raw_b) };
153
154        plot_a.with_bound_context(|| {
155            assert_eq!(unsafe { sys::ImPlot3D_GetCurrentContext() }, raw_a);
156        });
157
158        assert_eq!(unsafe { sys::ImPlot3D_GetCurrentContext() }, raw_b);
159
160        drop(plot_b);
161        drop(plot_a);
162    }
163
164    #[test]
165    fn scoped_styles_and_plot_cleanup_bind_their_owner() {
166        let _guard = test_guard();
167        let mut imgui = Context::create();
168        {
169            let io = imgui.io_mut();
170            io.set_display_size([800.0, 600.0]);
171            io.set_delta_time(1.0 / 60.0);
172        }
173        imgui
174            .font_atlas()
175            .try_claim_legacy_renderer()
176            .expect("headless test requires the legacy font-atlas capability")
177            .build();
178        let plot_a = Plot3DContext::create(&imgui);
179        let plot_b = Plot3DContext::create(&imgui);
180        let raw_b = plot_b.raw;
181
182        {
183            let frame = imgui.begin_frame();
184            let plot_ui = plot_a.get_plot_ui(frame.ui());
185            let style = || plot_a.with_bound_context(|| unsafe { *sys::ImPlot3D_GetStyle() });
186            let initial = style();
187            plot_ui.with_style_vars(
188                &[
189                    crate::Plot3DStyleVar::FillAlpha(0.5),
190                    crate::Plot3DStyleVar::PlotPadding([3.0, 4.0]),
191                    crate::Plot3DStyleVar::Marker(crate::Marker3D::Square),
192                ],
193                || {
194                    let applied = style();
195                    assert_eq!(applied.FillAlpha, 0.5);
196                    assert_eq!([applied.PlotPadding.x, applied.PlotPadding.y], [3.0, 4.0]);
197                    assert_eq!(applied.Marker, crate::Marker3D::Square as i32);
198                    unsafe { sys::ImPlot3D_SetCurrentContext(raw_b) };
199                },
200            );
201            assert_eq!(unsafe { sys::ImPlot3D_GetCurrentContext() }, raw_b);
202            assert_eq!(style().FillAlpha, initial.FillAlpha);
203            assert_eq!(style().PlotPadding, initial.PlotPadding);
204            assert_eq!(style().Marker, initial.Marker);
205            plot_ui
206                .begin_plot("plot")
207                .build(|plot| {
208                    assert!(plot.get_frame_size()[0] > 0.0);
209                    assert_eq!(unsafe { sys::ImPlot3D_GetCurrentContext() }, raw_b);
210                })
211                .expect("visible plot");
212            assert_eq!(unsafe { sys::ImPlot3D_GetCurrentContext() }, raw_b);
213        }
214
215        drop(plot_b);
216        drop(plot_a);
217    }
218
219    #[test]
220    fn dropping_current_plot3d_context_clears_current_context() {
221        let _guard = test_guard();
222        let imgui = Context::create();
223        let plot = Plot3DContext::create(&imgui);
224        let raw = plot.raw;
225
226        unsafe { sys::ImPlot3D_SetCurrentContext(raw) };
227        drop(plot);
228
229        assert!(unsafe { sys::ImPlot3D_GetCurrentContext() }.is_null());
230    }
231
232    #[test]
233    fn plot3d_owner_keeps_its_thread_and_destroys_the_native_plot_after_imgui_drops() {
234        let _guard = test_guard();
235        let imgui = Context::create();
236        let plot = Plot3DContext::create(&imgui);
237        unsafe { sys::ImPlot3D_SetCurrentContext(plot.raw) };
238        drop(imgui);
239
240        assert_eq!(
241            plot.imgui_binding.try_with_bound_context(|| ()),
242            Err(dear_imgui_rs::ContextBindingError::NativeDestroyed)
243        );
244        std::thread::spawn(|| {
245            assert!(matches!(
246                dear_imgui_rs::ContextThreadLease::acquire(),
247                Err(dear_imgui_rs::ImGuiError::ContextThreadConflict)
248            ))
249        })
250        .join()
251        .unwrap();
252        drop(plot);
253        std::thread::spawn(|| {
254            let _lease = dear_imgui_rs::ContextThreadLease::acquire().unwrap();
255            assert!(unsafe { sys::ImPlot3D_GetCurrentContext() }.is_null());
256        })
257        .join()
258        .unwrap();
259    }
260
261    #[test]
262    fn dropping_non_current_plot3d_context_restores_previous_context() {
263        let _guard = test_guard();
264        let imgui = Context::create();
265        let plot_a = Plot3DContext::create(&imgui);
266        let plot_b = Plot3DContext::create(&imgui);
267        let raw_b = plot_b.raw;
268
269        unsafe { sys::ImPlot3D_SetCurrentContext(raw_b) };
270        drop(plot_a);
271
272        assert_eq!(unsafe { sys::ImPlot3D_GetCurrentContext() }, raw_b);
273        drop(plot_b);
274    }
275
276    #[test]
277    fn plot3d_ui_binds_owner_context() {
278        let _guard = test_guard();
279        let imgui_a = Context::create();
280        let plot_a = Plot3DContext::create(&imgui_a);
281        let imgui_a_raw = imgui_a.as_raw();
282        let suspended_a = imgui_a.suspend_or_panic();
283        let imgui_b = Context::create();
284
285        assert_eq!(
286            unsafe { dear_imgui_rs::sys::igGetCurrentContext() },
287            imgui_b.as_raw()
288        );
289        plot_a.with_bound_context(|| {
290            assert_eq!(
291                unsafe { dear_imgui_rs::sys::igGetCurrentContext() },
292                imgui_a_raw
293            );
294        });
295        assert_eq!(
296            unsafe { dear_imgui_rs::sys::igGetCurrentContext() },
297            imgui_b.as_raw()
298        );
299        drop(suspended_a);
300        drop(plot_a);
301        drop(imgui_b);
302    }
303}