Skip to main content

dear_imgui_rs/context/
frame.rs

1//! Frame lifecycle APIs.
2//!
3//! Use [`Context::frame_with_result`] when a callback should also close and render the frame.
4//! The callback-only `Context::frame_with` API is intentionally unavailable because it leaves
5//! frame completion implicit:
6//!
7//! ```compile_fail
8//! # use dear_imgui_rs::Context;
9//! # let mut context = Context::create();
10//! let _ = context.frame_with(|ui| ui.text("frame"));
11//! ```
12
13use crate::sys;
14
15use super::Context;
16use super::binding::{CTX_MUTEX, with_bound_context};
17
18/// Runtime state for a Dear ImGui frame owned by an external engine schedule.
19#[derive(Copy, Clone, Debug, Eq, PartialEq)]
20pub enum FrameLifecycleState {
21    /// No Dear ImGui frame is currently open for this context.
22    Idle,
23    /// A frame was opened and can accept UI commands.
24    InFrame,
25    /// The last opened frame has been rendered and draw data is available until the next frame.
26    Rendered,
27}
28
29/// Comparable identity and native progress marker for a Context frame boundary.
30///
31/// Integrations can retain a stamp before invoking application code and require the same stamp
32/// afterward. Equality covers the Context generation, native frame sequence, and current lifecycle
33/// state, so an `Idle -> Idle` frame round trip is still observable.
34#[derive(Copy, Clone, Debug, Eq, PartialEq)]
35pub struct FrameLifecycleStamp {
36    context: super::ContextId,
37    native_frame: i32,
38    state: FrameLifecycleState,
39}
40
41impl FrameLifecycleStamp {
42    /// Return the Context generation captured by this stamp.
43    #[must_use]
44    pub const fn context_id(self) -> super::ContextId {
45        self.context
46    }
47
48    /// Return the frame lifecycle state captured by this stamp.
49    #[must_use]
50    pub const fn state(self) -> FrameLifecycleState {
51        self.state
52    }
53}
54
55/// Options used by [`Context::prepare_frame`].
56#[derive(Copy, Clone, Debug)]
57pub struct FramePrepareOptions {
58    /// Main display size in pixels.
59    pub display_size: [f32; 2],
60    /// Time elapsed since the previous frame, in seconds.
61    pub delta_time: f32,
62    /// Optional framebuffer scale for HiDPI render targets.
63    pub framebuffer_scale: Option<[f32; 2]>,
64    /// Backend capability flags to OR into the context before opening the frame.
65    pub backend_flags: crate::BackendFlags,
66}
67
68impl FramePrepareOptions {
69    /// Create frame preparation options with display size and delta time.
70    pub fn new(display_size: [f32; 2], delta_time: f32) -> Self {
71        Self {
72            display_size,
73            delta_time,
74            framebuffer_scale: None,
75            backend_flags: crate::BackendFlags::empty(),
76        }
77    }
78
79    /// Set the framebuffer scale used by the frame.
80    #[must_use]
81    pub fn framebuffer_scale(mut self, scale: [f32; 2]) -> Self {
82        self.framebuffer_scale = Some(scale);
83        self
84    }
85
86    /// OR backend capability flags into the context before opening the frame.
87    #[must_use]
88    pub fn backend_flags(mut self, flags: crate::BackendFlags) -> Self {
89        self.backend_flags |= flags;
90        self
91    }
92
93    /// Convenience for modern renderers that support ImGui 1.92 texture requests.
94    #[must_use]
95    pub fn renderer_has_textures(self) -> Self {
96        self.backend_flags(crate::BackendFlags::RENDERER_HAS_TEXTURES)
97    }
98}
99
100/// A frame opened by [`Context::begin_frame`].
101///
102/// This token is intended for engine integrations that need to make the Dear ImGui frame boundary
103/// explicit: one system opens the frame, several user systems draw through [`Self::ui`], and one
104/// system consumes the token to render or snapshot the frame. The existing [`Context::frame`] and
105/// [`Context::render`] calls remain available for traditional immediate-mode loops.
106#[must_use = "dropping FrameToken ends the frame without rendering; call render() or render_snapshot() to produce draw data"]
107#[doc(alias = "EndFrame")]
108pub struct FrameToken<'ctx> {
109    ctx: &'ctx mut Context,
110}
111
112/// Result returned by [`Context::frame_with_result`].
113#[must_use = "use the closure result and reconcile the pending frame before drawing"]
114pub struct FrameResult<'ctx, T> {
115    /// Value returned by the UI-building closure.
116    pub value: T,
117    /// Context-borrowed pending frame produced after the closure returned.
118    pub pending_frame: crate::render::PendingFrame<'ctx>,
119}
120
121impl<'ctx, T> FrameResult<'ctx, T> {
122    /// Split the closure result from the pending renderer capability.
123    pub fn into_parts(self) -> (T, crate::render::PendingFrame<'ctx>) {
124        (self.value, self.pending_frame)
125    }
126}
127
128impl Context {
129    /// Prepare IO values commonly needed before starting a frame.
130    ///
131    /// This does not call `NewFrame()`. Engine backends can call it from their input/window update
132    /// stage and then open the actual Dear ImGui frame later in the schedule with
133    /// [`Context::begin_frame`].
134    pub fn prepare_frame(&mut self, options: FramePrepareOptions) {
135        let io = self.io_mut();
136        io.set_display_size(options.display_size);
137        io.set_delta_time(options.delta_time);
138        if let Some(scale) = options.framebuffer_scale {
139            io.set_display_framebuffer_scale(scale);
140        }
141        if !options.backend_flags.is_empty() {
142            io.set_backend_flags(io.backend_flags() | options.backend_flags);
143        }
144    }
145
146    /// Return the current frame lifecycle state for this context.
147    pub fn frame_lifecycle_state(&self) -> FrameLifecycleState {
148        self.frame_lifecycle_stamp().state()
149    }
150
151    /// Capture this Context's identity and native frame progress as one comparable value.
152    ///
153    /// This is intended for engine callback boundaries that must reject both an open frame and a
154    /// frame that was opened and closed entirely inside the callback.
155    pub fn frame_lifecycle_stamp(&self) -> FrameLifecycleStamp {
156        let _guard = CTX_MUTEX.lock();
157        self.assert_current_context("Context::frame_lifecycle_stamp()");
158        self.frame_lifecycle_stamp_unlocked()
159    }
160
161    /// End an open frame without producing render data.
162    ///
163    /// Returns `true` when an open native frame was closed and `false` when the Context was
164    /// already idle or rendered. The operation is idempotent so engine teardown can revoke UI
165    /// access before detaching platform and renderer state.
166    #[doc(alias = "EndFrame")]
167    pub fn end_frame(&mut self) -> bool {
168        let _guard = CTX_MUTEX.lock();
169        self.assert_current_context("Context::end_frame()");
170        self.end_frame_for_teardown_unlocked()
171    }
172
173    pub(super) fn end_frame_for_teardown_unlocked(&mut self) -> bool {
174        if self.raw.is_null() || !unsafe { (*self.raw).WithinFrameScope } {
175            return false;
176        }
177        unsafe {
178            with_bound_context(self.raw, || {
179                let _ = crate::list_clipper::forget_context_clippers(self.raw);
180                sys::igEndFrame();
181            });
182        }
183        self.texture_registry
184            .borrow_mut()
185            .observe_native_texture_list_refresh();
186        true
187    }
188
189    /// Begin a Dear ImGui frame and return an explicit frame token.
190    ///
191    /// Engine integrations should prefer this when the frame is owned by a schedule rather than a
192    /// single function. Draw UI through [`FrameToken::ui`] and then consume the token with
193    /// [`FrameToken::render`] or [`FrameToken::render_snapshot`].
194    pub fn begin_frame(&mut self) -> FrameToken<'_> {
195        self.try_begin_frame()
196            .unwrap_or_else(|error| panic!("Context::begin_frame() rejected completion: {error}"))
197    }
198
199    /// Begin a frame while returning detached-completion failures to the caller.
200    pub fn try_begin_frame(
201        &mut self,
202    ) -> Result<FrameToken<'_>, crate::render::RendererConsumerError> {
203        let _ = self.try_frame()?;
204        Ok(FrameToken { ctx: self })
205    }
206
207    /// Creates a new frame and returns a Ui object for building the interface.
208    ///
209    /// Note: you must update `io.DisplaySize` (and usually `io.DeltaTime`) before calling this,
210    /// unless you are using a platform backend that does it for you (e.g. `dear-imgui-winit`).
211    #[doc(alias = "NewFrame")]
212    pub fn frame(&mut self) -> &mut crate::ui::Ui {
213        self.try_frame()
214            .unwrap_or_else(|error| panic!("Context::frame() rejected completion: {error}"))
215    }
216
217    /// Create a frame while returning detached-completion failures to the caller.
218    ///
219    /// Native frame-order, display-size, docking, and font-atlas programmer errors retain their
220    /// documented panic behavior. This method makes the asynchronous renderer completion boundary
221    /// fallible so event-loop and engine integrations can recover without a later panic.
222    pub fn try_frame(
223        &mut self,
224    ) -> Result<&mut crate::ui::Ui, crate::render::RendererConsumerError> {
225        let _guard = CTX_MUTEX.lock();
226        self.assert_current_context("Context::try_frame()");
227        self.assert_can_begin_frame_unlocked("Context::try_frame()");
228        self.poll_snapshot_completions_unlocked()?;
229        self.collect_retired_textures();
230
231        unsafe {
232            // Dear ImGui initializes DisplaySize to (-1, -1). Calling NewFrame() without a
233            // platform backend (or without setting DisplaySize manually) will trip an internal
234            // assertion and abort the process. Fail fast with a Rust panic to make the setup
235            // requirement obvious.
236            let io = sys::igGetIO_Nil();
237            if !io.is_null() && ((*io).DisplaySize.x < 0.0 || (*io).DisplaySize.y < 0.0) {
238                panic!(
239                    "Context::try_frame() called with invalid io.DisplaySize ({}, {}). \
240Set io.DisplaySize (and typically io.DeltaTime) before starting a frame. \
241If you are using a windowing/event-loop library, prefer a platform backend such as \
242dear-imgui-winit::WinitPlatform::prepare_frame().",
243                    (*io).DisplaySize.x,
244                    (*io).DisplaySize.y
245                );
246            }
247            self.assert_docking_config_stable_unlocked("Context::try_frame()");
248            #[cfg(feature = "multi-viewport")]
249            self.prepare_multi_viewport_new_frame_contract_unlocked("Context::try_frame()");
250            crate::fonts::assert_no_font_atlas_texture_borrows((*io).Fonts, "Context::try_frame()");
251            let renderer_has_textures =
252                ((*io).BackendFlags & sys::ImGuiBackendFlags_RendererHasTextures as i32) != 0;
253            crate::fonts::assert_font_atlas_renderer_mode(
254                (*io).Fonts,
255                renderer_has_textures,
256                "Context::try_frame()",
257            );
258            if let Some(shared_font_atlas) = &self.shared_font_atlas {
259                shared_font_atlas.prepare_frame(renderer_has_textures);
260            }
261            sys::igNewFrame();
262        }
263        Ok(&mut self.ui)
264    }
265
266    fn assert_docking_config_stable_unlocked(&self, caller: &str) {
267        let frame_count = unsafe { (*self.raw).FrameCount };
268        if frame_count == 0 {
269            return;
270        }
271
272        let io = self.io_ptr(caller);
273        let requested = unsafe { (*io).ConfigFlags } & sys::ImGuiConfigFlags_DockingEnable as i32;
274        let active = unsafe { (*self.raw).ConfigFlagsCurrFrame }
275            & sys::ImGuiConfigFlags_DockingEnable as i32;
276        assert_eq!(
277            requested, active,
278            "{caller} cannot change ConfigFlags::DOCKING_ENABLE after the first frame; Dear ImGui clears live dock nodes when docking is disabled and cannot restore them safely when it is re-enabled"
279        );
280    }
281
282    /// Begin a frame, run a UI-building closure, render the frame, and return both values.
283    ///
284    /// This is a convenience for callers that want the old callback style but also want the draw
285    /// data produced by closing the frame. Use [`Context::begin_frame`] when the UI is built across
286    /// several engine systems.
287    pub fn frame_with_result<F, R>(
288        &mut self,
289        consumer: &crate::render::SynchronousRendererConsumer,
290        f: F,
291    ) -> FrameResult<'_, R>
292    where
293        F: FnOnce(&crate::ui::Ui) -> R,
294    {
295        let frame = self.begin_frame();
296        let value = f(frame.ui());
297        let pending_frame = frame.render(consumer);
298        FrameResult {
299            value,
300            pending_frame,
301        }
302    }
303
304    /// Render a managed-texture frame and return its non-drawable pending capability.
305    #[doc(alias = "Render", alias = "GetDrawData")]
306    pub fn render(
307        &mut self,
308        consumer: &crate::render::SynchronousRendererConsumer,
309    ) -> crate::render::PendingFrame<'_> {
310        self.try_render(consumer)
311            .unwrap_or_else(|error| panic!("Context::render() failed: {error}"))
312    }
313
314    /// Render a managed-texture frame while returning capture or consumer failures.
315    pub fn try_render(
316        &mut self,
317        consumer: &crate::render::SynchronousRendererConsumer,
318    ) -> Result<crate::render::PendingFrame<'_>, crate::render::SnapshotError> {
319        self.require_managed_renderer("Context::try_render()")?;
320        let draw_data = self.render_raw();
321        let (epoch, requests) =
322            self.begin_synchronous_render(consumer, draw_data.as_ptr().cast_const())?;
323        Ok(crate::render::PendingFrame::new(
324            self, draw_data, epoch, requests,
325        ))
326    }
327
328    /// Render a frame for a legacy renderer that does not implement managed texture requests.
329    ///
330    /// # Panics
331    ///
332    /// Panics when the active renderer advertises `RENDERER_HAS_TEXTURES`; managed renderers must
333    /// use [`Self::render`] with their synchronous consumer and reconcile every request.
334    pub fn render_legacy(&mut self) -> crate::render::ReconciledFrame<'_> {
335        let renderer_has_textures = self
336            .io()
337            .backend_flags()
338            .contains(crate::BackendFlags::RENDERER_HAS_TEXTURES);
339        assert!(
340            !renderer_has_textures,
341            "Context::render_legacy() cannot bypass a managed renderer consumer"
342        );
343        let draw_data = self.render_raw();
344        crate::render::ReconciledFrame::new_legacy(self, draw_data)
345    }
346
347    fn require_managed_renderer(
348        &self,
349        caller: &'static str,
350    ) -> Result<(), crate::render::RendererConsumerError> {
351        if self
352            .io()
353            .backend_flags()
354            .contains(crate::BackendFlags::RENDERER_HAS_TEXTURES)
355        {
356            Ok(())
357        } else {
358            Err(crate::render::RendererConsumerError::RendererTexturesUnavailable { caller })
359        }
360    }
361
362    fn render_raw(&mut self) -> std::ptr::NonNull<crate::render::DrawData> {
363        let _guard = CTX_MUTEX.lock();
364        self.assert_current_context("Context::render()");
365        self.assert_can_render_unlocked("Context::render()");
366
367        let draw_data = unsafe {
368            let abandoned_clippers = crate::list_clipper::forget_context_clippers(self.raw);
369            if abandoned_clippers != 0 {
370                self.end_frame_for_teardown_unlocked();
371                panic!(
372                    "Context::render() rejected a frame with {abandoned_clippers} list clipper token(s) still active or forgotten"
373                );
374            }
375            sys::igRender();
376            let dd = sys::igGetDrawData();
377            if dd.is_null() {
378                panic!("Context::render() returned null draw data");
379            }
380            std::ptr::NonNull::new_unchecked(dd as *mut crate::render::DrawData)
381        };
382        self.texture_registry
383            .borrow_mut()
384            .observe_native_texture_list_refresh();
385        draw_data
386    }
387
388    /// Render the current frame and build a thread-safe main-viewport snapshot.
389    ///
390    /// This Context-level entry point supports engine schedules that open and close the native
391    /// frame in separate systems and therefore cannot retain a [`FrameToken`]. The snapshot is
392    /// still bound to the supplied renderer consumer, Context, generation, and ordered epoch.
393    pub fn render_snapshot(
394        &mut self,
395        consumer: &crate::render::snapshot::DetachedRendererConsumer,
396    ) -> Result<crate::render::snapshot::FrameSnapshot, crate::render::snapshot::SnapshotError>
397    {
398        let draw_data = self.render_raw();
399        self.capture_main_snapshot(consumer, draw_data.as_ptr())
400    }
401
402    /// Render the current frame and build a thread-safe snapshot for all platform viewports.
403    ///
404    /// With the `multi-viewport` feature enabled, Dear ImGui stores draw data on each viewport.
405    /// `Context::render()` and `igGetDrawData()` only expose the main viewport draw data, so
406    /// engine backends that render secondary OS windows should use this method after opening a
407    /// frame. The returned snapshot still keeps [`FrameSnapshot::draw`] as the main viewport for
408    /// compatibility and adds per-viewport draw data in
409    /// [`FrameSnapshot::viewports`](crate::render::snapshot::FrameSnapshot::viewports).
410    #[cfg(feature = "multi-viewport")]
411    pub fn render_platform_viewport_snapshot(
412        &mut self,
413        consumer: &crate::render::snapshot::DetachedRendererConsumer,
414    ) -> Result<crate::render::snapshot::FrameSnapshot, crate::render::snapshot::SnapshotError>
415    {
416        let _ = self.render_raw();
417        self.platform_viewport_snapshot(consumer)
418    }
419
420    /// Build a thread-safe snapshot from the current platform viewport draw data.
421    ///
422    /// This does not call `Render()`. Call it only after a frame has already been rendered and
423    /// before the next frame starts. Engine integrations can use this when they need to run
424    /// platform-window maintenance after `Render()` but before cloning draw data for another
425    /// render schedule.
426    #[cfg(feature = "multi-viewport")]
427    pub fn platform_viewport_snapshot(
428        &mut self,
429        consumer: &crate::render::snapshot::DetachedRendererConsumer,
430    ) -> Result<crate::render::snapshot::FrameSnapshot, crate::render::snapshot::SnapshotError>
431    {
432        let _guard = CTX_MUTEX.lock();
433        self.assert_current_context("Context::platform_viewport_snapshot()");
434        if self.frame_lifecycle_state_unlocked() != FrameLifecycleState::Rendered {
435            panic!(
436                "Context::platform_viewport_snapshot() called before rendering the current frame"
437            );
438        }
439        self.capture_platform_snapshot(consumer)
440    }
441
442    pub(super) fn frame_lifecycle_state_unlocked(&self) -> FrameLifecycleState {
443        self.frame_lifecycle_stamp_unlocked().state()
444    }
445
446    fn frame_lifecycle_stamp_unlocked(&self) -> FrameLifecycleStamp {
447        unsafe {
448            let raw = &*self.raw;
449            let state = if raw.WithinFrameScope {
450                FrameLifecycleState::InFrame
451            } else if raw.FrameCountRendered == raw.FrameCount && raw.FrameCount > 0 {
452                FrameLifecycleState::Rendered
453            } else {
454                FrameLifecycleState::Idle
455            };
456            FrameLifecycleStamp {
457                context: self.id(),
458                native_frame: raw.FrameCount,
459                state,
460            }
461        }
462    }
463
464    fn assert_can_begin_frame_unlocked(&self, caller: &str) {
465        if self.frame_lifecycle_state_unlocked() == FrameLifecycleState::InFrame {
466            panic!("{caller} called while another Dear ImGui frame is already open");
467        }
468    }
469
470    fn assert_can_render_unlocked(&self, caller: &str) {
471        if self.frame_lifecycle_state_unlocked() != FrameLifecycleState::InFrame {
472            panic!("{caller} called without an open Dear ImGui frame");
473        }
474    }
475}
476
477impl<'ctx> FrameToken<'ctx> {
478    /// Borrow the UI for this frame.
479    ///
480    /// This can be called repeatedly by an engine-owned frame runner to let multiple systems draw
481    /// into the same frame, as long as those systems are scheduled sequentially.
482    pub fn ui(&self) -> &crate::ui::Ui {
483        &self.ctx.ui
484    }
485
486    /// Return the lifecycle state while this token owns the open frame.
487    pub fn lifecycle_state(&self) -> FrameLifecycleState {
488        self.ctx.frame_lifecycle_state()
489    }
490
491    /// Render this managed-texture frame and return its pending capability.
492    pub fn render(
493        self,
494        consumer: &crate::render::SynchronousRendererConsumer,
495    ) -> crate::render::PendingFrame<'ctx> {
496        self.try_render(consumer)
497            .unwrap_or_else(|error| panic!("FrameToken::render() failed: {error}"))
498    }
499
500    /// Render this managed-texture frame while returning capture or consumer failures.
501    pub fn try_render(
502        self,
503        consumer: &crate::render::SynchronousRendererConsumer,
504    ) -> Result<crate::render::PendingFrame<'ctx>, crate::render::SnapshotError> {
505        let ctx = self.ctx as *mut Context;
506        match unsafe { (&mut *ctx).try_render(consumer) } {
507            Ok(frame) => {
508                std::mem::forget(self);
509                Ok(frame)
510            }
511            Err(error) => Err(error),
512        }
513    }
514
515    /// Render this frame through the explicit legacy renderer path.
516    pub fn render_legacy(self) -> crate::render::ReconciledFrame<'ctx> {
517        let ctx = self.ctx as *mut Context;
518        let frame = unsafe { (&mut *ctx).render_legacy() };
519        std::mem::forget(self);
520        frame
521    }
522
523    /// Render this frame and build a thread-safe snapshot from the resulting draw data.
524    ///
525    /// This is the preferred handoff shape for render-world integrations such as Bevy, where raw
526    /// ImGui pointers must not cross the engine extraction boundary.
527    pub fn render_snapshot(
528        self,
529        consumer: &crate::render::snapshot::DetachedRendererConsumer,
530    ) -> Result<crate::render::snapshot::FrameSnapshot, crate::render::snapshot::SnapshotError>
531    {
532        let ctx = self.ctx as *mut Context;
533        let draw_data = unsafe { (&mut *ctx).render_raw().as_ptr() };
534        std::mem::forget(self);
535        unsafe { (&mut *ctx).capture_main_snapshot(consumer, draw_data) }
536    }
537
538    /// Render this frame and build a thread-safe snapshot for all platform viewports.
539    #[cfg(feature = "multi-viewport")]
540    pub fn render_platform_viewport_snapshot(
541        self,
542        consumer: &crate::render::snapshot::DetachedRendererConsumer,
543    ) -> Result<crate::render::snapshot::FrameSnapshot, crate::render::snapshot::SnapshotError>
544    {
545        let ctx = self.ctx as *mut Context;
546        let snapshot = unsafe { (&mut *ctx).render_platform_viewport_snapshot(consumer) };
547        std::mem::forget(self);
548        snapshot
549    }
550}
551
552impl Drop for FrameToken<'_> {
553    fn drop(&mut self) {
554        let _guard = CTX_MUTEX.lock();
555        self.ctx.end_frame_for_teardown_unlocked();
556    }
557}