Skip to main content

dear_implot3d/
context.rs

1use crate::sys;
2use crate::ui::{Plot3DContextBinding, Plot3DUi};
3use dear_imgui_rs::{Context, ContextBinding, Ui};
4
5/// Plot3D context wrapper
6///
7/// This manages ImPlot3D state bound to one owning Dear ImGui Context. Keep it
8/// across frames and drop it before that Context. Multiple plotting contexts are
9/// supported, but native current-context access must remain serial.
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    pub(crate) owns_context: bool,
28}
29
30impl Plot3DContext {
31    pub(crate) fn binding(&self) -> Plot3DContextBinding {
32        Plot3DContextBinding {
33            plot_ctx_raw: self.raw,
34            imgui_binding: self.imgui_binding.clone(),
35        }
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 imgui_binding = imgui.binding();
43        let ctx = imgui_binding.with_bound_context(|| unsafe {
44            let prev_plot = sys::ImPlot3D_GetCurrentContext();
45            let ctx = sys::ImPlot3D_CreateContext();
46            if sys::ImPlot3D_GetCurrentContext() != prev_plot {
47                sys::ImPlot3D_SetCurrentContext(prev_plot);
48            }
49            ctx
50        });
51        if ctx.is_null() {
52            return Err(dear_imgui_rs::ImGuiError::context_creation(
53                "ImPlot3D_CreateContext returned null",
54            ));
55        }
56
57        Ok(Self {
58            raw: ctx,
59            imgui_binding,
60            owns_context: true,
61        })
62    }
63
64    /// Create a new ImPlot3D context (panics on error).
65    pub fn create(imgui: &Context) -> Self {
66        Self::try_create(imgui).expect("Failed to create ImPlot3D context")
67    }
68
69    /// Get the raw ImPlot3D context pointer without changing the current context.
70    ///
71    /// # Safety
72    ///
73    /// Use it only while this plotting context and its owning Dear ImGui Context are
74    /// alive and correctly bound. Preserve native ownership and pointer invariants; do
75    /// not destroy the context or retain the pointer beyond this wrapper's lifetime.
76    pub unsafe fn raw(&self) -> *mut sys::ImPlot3DContext {
77        self.raw
78    }
79
80    /// Get a per-frame plotting interface
81    ///
82    /// Call this once per frame to get access to plotting functions.
83    /// The returned `Plot3DUi` is tied to the lifetime of the `Ui` frame.
84    pub fn get_plot_ui<'ui>(&self, ui: &'ui Ui) -> Plot3DUi<'ui> {
85        assert_eq!(
86            ui.context_id(),
87            self.imgui_binding.id(),
88            "dear-implot3d: Plot3DContext::get_plot_ui() requires a Ui from the owning ImGui context"
89        );
90        Plot3DUi {
91            _ui: ui,
92            binding: self.binding(),
93        }
94    }
95}
96
97impl Drop for Plot3DContext {
98    fn drop(&mut self) {
99        if !self.owns_context || self.raw.is_null() {
100            return;
101        }
102
103        let _ = self.imgui_binding.try_with_bound_context(|| unsafe {
104            let prev_plot = sys::ImPlot3D_GetCurrentContext();
105            let restore_plot = if prev_plot == self.raw {
106                std::ptr::null_mut()
107            } else {
108                prev_plot
109            };
110            sys::ImPlot3D_DestroyContext(self.raw);
111            sys::ImPlot3D_SetCurrentContext(restore_plot);
112        });
113    }
114}
115
116#[cfg(test)]
117mod tests {
118    use super::Plot3DContext;
119    use crate::{Context, sys};
120    use std::mem::{align_of, size_of};
121    use std::sync::{Mutex, OnceLock};
122
123    fn test_guard() -> std::sync::MutexGuard<'static, ()> {
124        static GUARD: OnceLock<Mutex<()>> = OnceLock::new();
125        GUARD
126            .get_or_init(|| Mutex::new(()))
127            .lock()
128            .unwrap_or_else(|err| err.into_inner())
129    }
130
131    #[test]
132    fn ffi_layout_implot3d_point_is_3_f64() {
133        assert_eq!(size_of::<sys::ImPlot3DPoint>(), 3 * size_of::<f64>());
134        assert_eq!(align_of::<sys::ImPlot3DPoint>(), align_of::<f64>());
135    }
136
137    #[test]
138    fn plot3d_ui_binds_own_context() {
139        let _guard = test_guard();
140        let imgui = Context::create();
141        let plot_a = Plot3DContext::create(&imgui);
142        let raw_a = plot_a.raw;
143        let plot_b = Plot3DContext::create(&imgui);
144        let raw_b = plot_b.raw;
145
146        unsafe { sys::ImPlot3D_SetCurrentContext(raw_b) };
147
148        plot_a.binding().with_bound_context(|| {
149            assert_eq!(unsafe { sys::ImPlot3D_GetCurrentContext() }, raw_a);
150        });
151
152        assert_eq!(unsafe { sys::ImPlot3D_GetCurrentContext() }, raw_b);
153
154        drop(plot_b);
155        drop(plot_a);
156    }
157
158    #[test]
159    fn plot3d_tokens_bind_own_context_before_drop() {
160        let _guard = test_guard();
161        let mut imgui = Context::create();
162        {
163            let io = imgui.io_mut();
164            io.set_display_size([800.0, 600.0]);
165            io.set_delta_time(1.0 / 60.0);
166        }
167        imgui
168            .font_atlas()
169            .try_claim_legacy_renderer()
170            .expect("headless test requires the legacy font-atlas capability")
171            .build();
172        let plot_a = Plot3DContext::create(&imgui);
173        let plot_b = Plot3DContext::create(&imgui);
174        let raw_b = plot_b.raw;
175
176        {
177            let frame = imgui.begin_frame();
178            let plot_ui = plot_a.get_plot_ui(frame.ui());
179            let style = plot_ui.push_style_var_f32(crate::Plot3DStyleVar::FillAlpha, 0.5);
180            unsafe { sys::ImPlot3D_SetCurrentContext(raw_b) };
181            drop(style);
182            assert_eq!(unsafe { sys::ImPlot3D_GetCurrentContext() }, raw_b);
183
184            let token = plot_ui
185                .begin_plot("token")
186                .build()
187                .expect("failed to begin 3D plot");
188            unsafe { sys::ImPlot3D_SetCurrentContext(raw_b) };
189            drop(token);
190            assert_eq!(unsafe { sys::ImPlot3D_GetCurrentContext() }, raw_b);
191        }
192
193        drop(plot_b);
194        drop(plot_a);
195    }
196
197    #[test]
198    fn dropping_current_plot3d_context_clears_current_context() {
199        let _guard = test_guard();
200        let imgui = Context::create();
201        let plot = Plot3DContext::create(&imgui);
202        let raw = plot.raw;
203
204        unsafe { sys::ImPlot3D_SetCurrentContext(raw) };
205        drop(plot);
206
207        assert!(unsafe { sys::ImPlot3D_GetCurrentContext() }.is_null());
208    }
209
210    #[test]
211    fn dropping_non_current_plot3d_context_restores_previous_context() {
212        let _guard = test_guard();
213        let imgui = Context::create();
214        let plot_a = Plot3DContext::create(&imgui);
215        let plot_b = Plot3DContext::create(&imgui);
216        let raw_b = plot_b.raw;
217
218        unsafe { sys::ImPlot3D_SetCurrentContext(raw_b) };
219        drop(plot_a);
220
221        assert_eq!(unsafe { sys::ImPlot3D_GetCurrentContext() }, raw_b);
222        drop(plot_b);
223    }
224
225    #[test]
226    fn plot3d_ui_binds_owner_context() {
227        let _guard = test_guard();
228        let imgui_a = Context::create();
229        let plot_a = Plot3DContext::create(&imgui_a);
230        let imgui_a_raw = imgui_a.as_raw();
231        let suspended_a = imgui_a.suspend_or_panic();
232        let imgui_b = Context::create();
233
234        assert_eq!(
235            unsafe { dear_imgui_rs::sys::igGetCurrentContext() },
236            imgui_b.as_raw()
237        );
238        plot_a.binding().with_bound_context(|| {
239            assert_eq!(
240                unsafe { dear_imgui_rs::sys::igGetCurrentContext() },
241                imgui_a_raw
242            );
243        });
244        assert_eq!(
245            unsafe { dear_imgui_rs::sys::igGetCurrentContext() },
246            imgui_b.as_raw()
247        );
248        drop(suspended_a);
249        drop(plot_a);
250        drop(imgui_b);
251    }
252}