Skip to main content

dear_imgui_wgpu/renderer/
snapshot.rs

1//! Context publication stays on the UI thread; the executor owns only GPU state and metadata.
2
3use std::{
4    collections::{HashMap, HashSet},
5    num::NonZeroU64,
6    sync::Arc,
7};
8
9use dear_imgui_rs::{
10    Context, ContextId, Id,
11    platform_io::NativeWindowTarget,
12    render::{
13        DetachedRendererConsumer, FrameSnapshot, SnapshotCommitError, SnapshotEpoch,
14        TextureFeedback,
15    },
16};
17
18use super::{
19    FramebufferExtent, WgpuRenderer, core::RendererContextState, draw_source::DrawSource,
20    gpu::GpuState,
21};
22use crate::{
23    ExternalTextureBinding, ExternalTextureId, GammaMode, RendererError, RendererResult, Uniforms,
24    WgpuDrawRecording, WgpuFrameScope, WgpuFrameSkipReason, WgpuInitInfo,
25    texture::ManagedRequestOutcome, wgpu,
26};
27
28/// UI-thread publication and sole detached consumer capability for one Context.
29///
30/// Keep this value on the UI thread. Move the executor returned by [`Self::new`] to the render
31/// thread and send [`WgpuSnapshotSubmission`] values through an application-owned bounded channel.
32/// No Context binding, platform pointer, or raw draw callback enters the executor.
33///
34/// ```compile_fail
35/// fn require_send<T: Send>() {}
36/// require_send::<dear_imgui_wgpu::WgpuSnapshotRenderer>();
37/// ```
38///
39/// Dropping this UI owner clears its exact publication and starts the core consumer's draining
40/// phase. Already captured snapshots retain their own completion tickets. Join the worker and
41/// call [`Self::shutdown`] when that live Context must accept another renderer immediately.
42pub struct WgpuSnapshotRenderer {
43    state: Option<RendererContextState>,
44    consumer: Option<DetachedRendererConsumer>,
45}
46
47impl WgpuSnapshotRenderer {
48    /// Publishes the WGPU draw contract and creates its separate GPU executor.
49    pub fn new(
50        init: WgpuInitInfo,
51        context: &mut Context,
52    ) -> RendererResult<(Self, WgpuSnapshotExecutor)> {
53        WgpuRenderer::ensure_context_available(context)?;
54        let mut gpu = GpuState::empty();
55        gpu.initialize(init)?;
56        let (flags, name) = WgpuRenderer::configure_imgui_context(context)?;
57        let state = match RendererContextState::publish(context, flags) {
58            Ok(state) => state,
59            Err(error) => {
60                WgpuRenderer::clear_unbound_imgui_context(context, flags, name);
61                return Err(error);
62            }
63        };
64        let consumer = match context.create_detached_renderer_consumer() {
65            Ok(consumer) => consumer,
66            Err(error) => {
67                state.clear_with_context(context);
68                return Err(error.into());
69            }
70        };
71        let reset = match context.prepare_renderer_texture_reset(&consumer) {
72            Ok(reset) => reset,
73            Err(error) => {
74                drop(consumer);
75                state.clear_with_context(context);
76                return Err(error.into());
77            }
78        };
79        reset.commit();
80        let executor = WgpuSnapshotExecutor {
81            gpu,
82            context: consumer.context_id(),
83            generation: consumer.generation(),
84            targets: HashMap::new(),
85            next_target_generation: 1,
86            last_epoch: None,
87        };
88        Ok((
89            Self {
90                state: Some(state),
91                consumer: Some(consumer),
92            },
93            executor,
94        ))
95    }
96
97    /// Consumer passed to the core's `FrameToken::render_snapshot` or platform snapshot capture.
98    pub fn renderer_consumer(&self) -> RendererResult<&DetachedRendererConsumer> {
99        let state = self.state.as_ref().ok_or(RendererError::ContextNotBound)?;
100        state.ensure_renderer_contract()?;
101        self.consumer.as_ref().ok_or(RendererError::ContextNotBound)
102    }
103
104    /// Resets managed bindings and clears publication after the worker returns its executor.
105    ///
106    /// Outstanding snapshots reject shutdown without changing either owner. Poll the core's
107    /// completion channel first. Queue submission and GPU completion remain host responsibilities.
108    pub fn shutdown(
109        &mut self,
110        context: &mut Context,
111        executor: &mut WgpuSnapshotExecutor,
112    ) -> RendererResult<()> {
113        self.state
114            .as_ref()
115            .ok_or(RendererError::ContextNotBound)?
116            .ensure_matches(context)?;
117        let consumer = self
118            .consumer
119            .as_ref()
120            .ok_or(RendererError::ContextNotBound)?;
121        if executor.context != consumer.context_id() || executor.generation != consumer.generation()
122        {
123            return Err(RendererError::ContextMismatch);
124        }
125        let reset = context.prepare_renderer_texture_reset(consumer)?;
126        executor.gpu = GpuState::empty();
127        executor.targets.clear();
128        reset.commit();
129        self.consumer.take();
130        if let Some(state) = self.state.take() {
131            state.clear_with_context(context);
132        }
133        Ok(())
134    }
135}
136
137/// Frozen association of one viewport with an executor's target-resource generation.
138///
139/// This is pure `Send + Sync` metadata. It owns no native window, Surface, texture, or GPU lease.
140/// Host code must retain those resources while recording and submitting their commands.
141///
142/// ```compile_fail
143/// use dear_imgui_wgpu::WgpuSnapshotTarget;
144/// let forged = WgpuSnapshotTarget { resource_generation: std::num::NonZeroU64::MIN };
145/// ```
146#[derive(Clone, Copy, Debug, Eq, PartialEq)]
147pub struct WgpuSnapshotTarget {
148    context: ContextId,
149    consumer_generation: u64,
150    resource_generation: NonZeroU64,
151    viewport: Id,
152    native: Option<NativeWindowTarget>,
153}
154
155impl WgpuSnapshotTarget {
156    /// Captured viewport routing identity.
157    pub const fn viewport_id(self) -> Id {
158        self.viewport
159    }
160    /// Exact native registration, when supplied by the host integration.
161    pub const fn native_target(self) -> Option<NativeWindowTarget> {
162        self.native
163    }
164    /// Monotonic resource identity. Replacing or re-registering a target never reuses it.
165    pub const fn resource_generation(self) -> NonZeroU64 {
166        self.resource_generation
167    }
168}
169
170/// Owned core snapshot plus the target associations captured when the UI published it.
171pub struct WgpuSnapshotSubmission {
172    snapshot: FrameSnapshot,
173    targets: Vec<WgpuSnapshotTarget>,
174}
175
176impl WgpuSnapshotSubmission {
177    /// Freezes metadata without consulting the executor or a live Context.
178    ///
179    /// Supply exactly one target for a main-only snapshot, or one for each captured platform
180    /// viewport. The executor checks completeness, duplicate viewports, and resource generations.
181    pub fn new(
182        snapshot: FrameSnapshot,
183        targets: impl IntoIterator<Item = WgpuSnapshotTarget>,
184    ) -> Self {
185        Self {
186            snapshot,
187            targets: targets.into_iter().collect(),
188        }
189    }
190}
191
192/// Evidence for one target recorded from a detached snapshot.
193#[derive(Clone, Debug)]
194pub struct WgpuSnapshotTargetRecording {
195    /// Frozen association; never resolved against the current viewport registry afterwards.
196    pub target: WgpuSnapshotTarget,
197    /// Recording evidence only. Host submit, present, and GPU completion are not observed here.
198    pub draw: WgpuDrawRecording,
199}
200
201/// Owned metadata retained on success and on errors, including partially recorded snapshots.
202#[derive(Clone, Debug)]
203pub struct WgpuSnapshotReport {
204    /// Core snapshot epoch.
205    pub epoch: SnapshotEpoch,
206    /// Frozen targets in publication order. Unrecorded targets carry `recorded = false`.
207    pub targets: Vec<WgpuSnapshotTargetRecording>,
208}
209
210/// Snapshot failure with any earlier recording evidence and completion-delivery failure.
211#[derive(Debug, thiserror::Error)]
212#[error("detached WGPU snapshot failed: {error}")]
213pub struct WgpuSnapshotError {
214    /// Immediate renderer failure.
215    pub error: Arc<RendererError>,
216    /// Earlier observations, with no claim about queue submission or GPU completion.
217    pub report: WgpuSnapshotReport,
218    /// Failure to deliver feedback, usually because the Context was destroyed.
219    pub completion_error: Option<SnapshotCommitError>,
220}
221
222/// Context-free WGPU state. On native WGPU backends it is automatically `Send`.
223///
224/// Move this value to the render thread. Target generation changes, external registrations, and
225/// device resources all belong to that thread. It never binds or dereferences a live Context.
226pub struct WgpuSnapshotExecutor {
227    gpu: GpuState,
228    context: ContextId,
229    generation: u64,
230    targets: HashMap<Id, WgpuSnapshotTarget>,
231    next_target_generation: u64,
232    last_epoch: Option<u64>,
233}
234
235impl WgpuSnapshotExecutor {
236    /// Registers or replaces the resources associated with a viewport.
237    ///
238    /// Call this whenever the host replaces its render-target allocation or native registration.
239    /// Queued submissions carrying an earlier capability are rejected before texture mutation.
240    pub fn set_target(
241        &mut self,
242        viewport: Id,
243        native: Option<NativeWindowTarget>,
244    ) -> RendererResult<WgpuSnapshotTarget> {
245        if native.is_some_and(|target| {
246            target.instance_id.context_id() != self.context || target.viewport_id != viewport
247        }) {
248            return Err(RendererError::ContextMismatch);
249        }
250        let generation = NonZeroU64::new(self.next_target_generation)
251            .ok_or(RendererError::SnapshotTargetGenerationExhausted)?;
252        self.next_target_generation = self
253            .next_target_generation
254            .checked_add(1)
255            .ok_or(RendererError::SnapshotTargetGenerationExhausted)?;
256        let target = WgpuSnapshotTarget {
257            context: self.context,
258            consumer_generation: self.generation,
259            resource_generation: generation,
260            viewport,
261            native,
262        };
263        self.targets.insert(viewport, target);
264        Ok(target)
265    }
266
267    /// Retires an exact generation. Stale or foreign capabilities cannot retire a newer target.
268    pub fn retire_target(&mut self, target: WgpuSnapshotTarget) -> RendererResult<()> {
269        self.validate_target(target)?;
270        self.targets.remove(&target.viewport);
271        Ok(())
272    }
273
274    fn validate_target(&self, target: WgpuSnapshotTarget) -> RendererResult<()> {
275        if target.context != self.context
276            || target.consumer_generation != self.generation
277            || self.targets.get(&target.viewport) != Some(&target)
278        {
279            return Err(RendererError::StaleSnapshotTarget {
280                viewport: target.viewport,
281            });
282        }
283        Ok(())
284    }
285
286    /// Selects the same gamma policy used by the synchronous renderer.
287    pub fn set_gamma_mode(&mut self, mode: GammaMode) {
288        self.gpu.gamma_mode = mode;
289    }
290
291    /// Registers an external view on this executor's device. The application owns its contents.
292    pub fn register_external_texture(
293        &mut self,
294        view: &wgpu::TextureView,
295    ) -> RendererResult<ExternalTextureId> {
296        self.gpu.texture_manager.register_external_view(view)
297    }
298
299    /// Returns the current external view revision, independently of its content frame.
300    pub fn external_texture_binding(
301        &self,
302        texture: ExternalTextureId,
303    ) -> RendererResult<ExternalTextureBinding> {
304        self.gpu
305            .texture_manager
306            .external_binding(texture.texture_id())
307            .ok_or(RendererError::ExternalTextureNotFound(texture.texture_id()))
308    }
309
310    /// Replaces a view and invalidates its cached bind group after a successful revision change.
311    pub fn update_external_texture(
312        &mut self,
313        texture: ExternalTextureId,
314        view: &wgpu::TextureView,
315    ) -> RendererResult<()> {
316        self.gpu
317            .texture_manager
318            .update_external_view(texture, view)?;
319        self.gpu
320            .backend_data
321            .as_mut()
322            .ok_or(RendererError::ContextNotBound)?
323            .render_resources
324            .remove_image_bind_group(texture.texture_id());
325        Ok(())
326    }
327
328    /// Removes an external mapping. The host must retain resources used by in-flight GPU work.
329    pub fn unregister_external_texture(
330        &mut self,
331        texture: ExternalTextureId,
332    ) -> RendererResult<()> {
333        self.gpu.texture_manager.remove_external_view(texture)?;
334        self.gpu
335            .backend_data
336            .as_mut()
337            .ok_or(RendererError::ContextNotBound)?
338            .render_resources
339            .remove_image_bind_group(texture.texture_id());
340        Ok(())
341    }
342
343    /// Validates the captured identity and applies owned managed requests without recording.
344    ///
345    /// Texture feedback is committed for every request on failure. Earlier successful uploads
346    /// retain their acknowledgements; the failing and remaining requests request retry. Stale
347    /// epochs use superseded feedback so delayed work cannot resurrect retired GPU resources.
348    pub fn prepare(
349        &mut self,
350        submission: WgpuSnapshotSubmission,
351    ) -> Result<WgpuPreparedSnapshot<'_>, WgpuSnapshotError> {
352        let WgpuSnapshotSubmission { snapshot, targets } = submission;
353        let epoch = snapshot.epoch();
354        let report = WgpuSnapshotReport {
355            epoch,
356            targets: targets
357                .iter()
358                .map(|target| {
359                    let draw = snapshot
360                        .viewport_draw(target.viewport)
361                        .unwrap_or_else(|| snapshot.draw_data());
362                    WgpuSnapshotTargetRecording {
363                        target: *target,
364                        draw: WgpuDrawRecording {
365                            scope: WgpuFrameScope {
366                                context_id: epoch.context_id(),
367                                epoch: Some(epoch),
368                                frame_count: draw.frame_count,
369                            },
370                            dependencies: Default::default(),
371                            recorded: false,
372                            skip_reason: None,
373                        },
374                    }
375                })
376                .collect(),
377        };
378        let validation = (|| {
379            if epoch.context_id() != self.context {
380                return Err(RendererError::ContextMismatch);
381            }
382            if epoch.consumer_generation() != self.generation {
383                return Err(RendererError::SnapshotConsumerGeneration {
384                    expected: self.generation,
385                    actual: epoch.consumer_generation(),
386                });
387            }
388            if self.last_epoch.is_some_and(|last| epoch.sequence() <= last) {
389                return Err(RendererError::FrameEpochOutOfOrder {
390                    active: self.last_epoch.unwrap_or(0),
391                    received: epoch.sequence(),
392                });
393            }
394            let mut seen = std::collections::HashSet::new();
395            for target in &targets {
396                self.validate_target(*target)?;
397                if !seen.insert(target.viewport) {
398                    return Err(RendererError::InvalidRenderState(
399                        "duplicate detached viewport target".to_owned(),
400                    ));
401                }
402            }
403            if snapshot.viewports().is_empty() {
404                if targets.len() != 1 {
405                    return Err(RendererError::InvalidRenderState(
406                        "a main-only snapshot requires exactly one target".to_owned(),
407                    ));
408                }
409            } else if targets.len() != snapshot.viewports().len()
410                || snapshot
411                    .viewports()
412                    .iter()
413                    .any(|viewport| !seen.contains(&viewport.viewport_id))
414            {
415                return Err(RendererError::InvalidRenderState(
416                    "snapshot targets do not match captured viewports".to_owned(),
417                ));
418            }
419            for target in &targets {
420                let captured_main = snapshot
421                    .viewports()
422                    .iter()
423                    .find(|viewport| viewport.viewport_id == target.viewport)
424                    .is_none_or(|viewport| viewport.is_main());
425                if target
426                    .native
427                    .is_some_and(|native| native.is_main != captured_main)
428                {
429                    return Err(RendererError::InvalidRenderState(
430                        "native target role does not match the captured viewport".to_owned(),
431                    ));
432                }
433            }
434            let backend = self
435                .gpu
436                .backend_data
437                .as_mut()
438                .ok_or(RendererError::ContextNotBound)?;
439            let frame_count = i32::try_from(snapshot.draw_data().frame_count).map_err(|_| {
440                RendererError::DrawBufferTooLarge {
441                    buffer: "frame counter",
442                }
443            })?;
444            backend.begin_frame(epoch.sequence(), frame_count)
445        })();
446        if let Err(error) = validation {
447            let superseded = matches!(error, RendererError::FrameEpochOutOfOrder { .. });
448            let feedback = snapshot
449                .texture_requests()
450                .iter()
451                .map(|request| {
452                    if superseded {
453                        request.superseded()
454                    } else {
455                        request.retry()
456                    }
457                })
458                .collect::<Vec<_>>();
459            return Err(WgpuSnapshotError {
460                error: Arc::new(error),
461                report,
462                completion_error: snapshot.commit(feedback).err(),
463            });
464        }
465        // Every older epoch is rejected above before request application. Its destroy markers
466        // therefore no longer protect an executable frame; this is an execution-order barrier,
467        // not a claim about core completion feedback or GPU completion.
468        if let Some(previous) = self.last_epoch {
469            self.gpu
470                .texture_manager
471                .prune_destroyed_managed_textures(previous);
472        }
473        self.last_epoch = Some(epoch.sequence());
474        let (backend_data, texture_manager) =
475            (&mut self.gpu.backend_data, &mut self.gpu.texture_manager);
476        let backend = backend_data.as_mut().expect("validated GPU state");
477        let mut feedback = Vec::with_capacity(snapshot.texture_requests().len());
478        let mut failure = None;
479        for request in snapshot.texture_requests() {
480            if failure.is_some() {
481                feedback.push(request.retry());
482                continue;
483            }
484            let result = texture_manager
485                .apply_managed_request_at_epoch(
486                    request.texture(),
487                    request.operation(),
488                    epoch.sequence(),
489                    &backend.device,
490                    &backend.queue,
491                    &mut backend.render_resources,
492                )
493                .and_then(|outcome| {
494                    Ok(match outcome {
495                        ManagedRequestOutcome::Uploaded(id) => request.uploaded(id)?,
496                        ManagedRequestOutcome::Destroyed => request.destroyed()?,
497                        ManagedRequestOutcome::Superseded => request.superseded(),
498                    })
499                });
500            match result {
501                Ok(item) => feedback.push(item),
502                Err(error) => {
503                    feedback.push(request.retry());
504                    failure = Some(error);
505                }
506            }
507        }
508        if let Some(error) = failure {
509            return Err(WgpuSnapshotError {
510                error: Arc::new(error),
511                report,
512                completion_error: snapshot.commit(feedback).err(),
513            });
514        }
515        Ok(WgpuPreparedSnapshot {
516            executor: self,
517            snapshot: Some(snapshot),
518            targets,
519            feedback,
520            report,
521            failure: None,
522            attempted: HashSet::new(),
523        })
524    }
525}
526
527/// Exclusive preparation scope for one snapshot; resources cannot be replaced while it exists.
528///
529/// Record each target at most once, then finish to commit request feedback. Dropping this value
530/// also commits already-applied texture feedback; it does not submit or present any commands.
531///
532/// ```compile_fail
533/// use dear_imgui_wgpu::{WgpuSnapshotExecutor, WgpuSnapshotSubmission};
534/// fn replace_while_prepared(executor: &mut WgpuSnapshotExecutor, submission: WgpuSnapshotSubmission) {
535///     let prepared = executor.prepare(submission).unwrap();
536///     let _ = executor.set_target(dear_imgui_rs::Id::from(7_u32), None);
537///     let _ = prepared.report();
538/// }
539/// ```
540#[must_use = "record the snapshot and finish its completion feedback"]
541pub struct WgpuPreparedSnapshot<'executor> {
542    executor: &'executor mut WgpuSnapshotExecutor,
543    snapshot: Option<FrameSnapshot>,
544    targets: Vec<WgpuSnapshotTarget>,
545    feedback: Vec<TextureFeedback>,
546    report: WgpuSnapshotReport,
547    failure: Option<Arc<RendererError>>,
548    attempted: HashSet<Id>,
549}
550
551impl WgpuPreparedSnapshot<'_> {
552    /// Returns accumulated owned evidence before completion.
553    pub fn report(&self) -> &WgpuSnapshotReport {
554        &self.report
555    }
556
557    /// Records one captured viewport into the host's render pass using the shared draw executor.
558    ///
559    /// The supplied target must match the frozen association. As with synchronous rendering,
560    /// WGPU cannot inspect a pass's attachments: the host supplies their exact extent and retains
561    /// any Surface/native leases. On error the scope becomes terminal, preserving earlier records.
562    pub fn record(
563        &mut self,
564        target: WgpuSnapshotTarget,
565        pass: &mut wgpu::RenderPass<'_>,
566        extent: FramebufferExtent,
567    ) -> Result<&WgpuDrawRecording, Arc<RendererError>> {
568        if let Some(error) = &self.failure {
569            return Err(Arc::clone(error));
570        }
571        match self.record_target(target, pass, extent) {
572            Ok(recording) => {
573                let record = self
574                    .report
575                    .targets
576                    .iter_mut()
577                    .find(|record| record.target == target)
578                    .expect("validated captured target");
579                record.draw = recording;
580                Ok(&record.draw)
581            }
582            Err(error) => {
583                let error = Arc::new(error);
584                self.failure = Some(Arc::clone(&error));
585                Err(error)
586            }
587        }
588    }
589
590    fn record_target(
591        &mut self,
592        target: WgpuSnapshotTarget,
593        pass: &mut wgpu::RenderPass<'_>,
594        extent: FramebufferExtent,
595    ) -> RendererResult<WgpuDrawRecording> {
596        self.executor.validate_target(target)?;
597        if !self.targets.contains(&target) {
598            return Err(RendererError::StaleSnapshotTarget {
599                viewport: target.viewport,
600            });
601        }
602        if !self.attempted.insert(target.viewport) {
603            return Err(RendererError::InvalidRenderState(
604                "snapshot viewport was already recorded".to_owned(),
605            ));
606        }
607        let snapshot = self.snapshot.as_ref().expect("unfinished snapshot");
608        let draw = if snapshot.viewports().is_empty() {
609            snapshot.draw_data()
610        } else {
611            snapshot
612                .viewport_draw(target.viewport)
613                .ok_or(RendererError::StaleSnapshotTarget {
614                    viewport: target.viewport,
615                })?
616        };
617        let scope = WgpuFrameScope {
618            context_id: snapshot.epoch().context_id(),
619            epoch: Some(snapshot.epoch()),
620            frame_count: draw.frame_count,
621        };
622        if extent.is_empty() {
623            return Ok(WgpuDrawRecording::skipped(
624                scope,
625                WgpuFrameSkipReason::ZeroSize,
626            ));
627        }
628        let gpu = &mut self.executor.gpu;
629        let (backend_data, texture_manager) = (&mut gpu.backend_data, &gpu.texture_manager);
630        let backend = backend_data
631            .as_mut()
632            .ok_or(RendererError::ContextNotBound)?;
633        let source = DrawSource::Snapshot(draw);
634        let prepared = WgpuRenderer::prepare_draw_source(
635            texture_manager,
636            &gpu.default_texture,
637            source,
638            extent,
639            backend,
640        )?;
641        if prepared.is_empty() {
642            return Ok(WgpuDrawRecording::skipped(
643                scope,
644                WgpuFrameSkipReason::NoDrawCommands,
645            ));
646        }
647        let dependencies = prepared.dependencies().clone();
648        // Preserve successfully prepared dependencies even if a later upload or encoder step fails.
649        self.report
650            .targets
651            .iter_mut()
652            .find(|record| record.target == target)
653            .expect("validated captured target")
654            .draw
655            .dependencies = dependencies.clone();
656        let gamma = Uniforms::shader_gamma(gpu.gamma_mode, backend.render_target_format);
657        let state = WgpuRenderer::prepare_render_state_source(
658            source,
659            backend,
660            gamma,
661            prepared.has_elements(),
662        )?;
663        WgpuRenderer::execute_prepared_commands(prepared, &state, extent, pass, |_| {
664            Err(RendererError::RawDrawCallbackUnsupported)
665        })?;
666        Ok(WgpuDrawRecording {
667            scope,
668            dependencies,
669            recorded: true,
670            skip_reason: None,
671        })
672    }
673
674    /// Commits the complete request-bound feedback and returns owned recording evidence.
675    ///
676    /// Core completion means CPU-side snapshot processing has ended. It does not mean commands
677    /// were submitted or completed on the GPU. Unrecorded targets are allowed for host skip policy.
678    pub fn finish(mut self) -> Result<WgpuSnapshotReport, WgpuSnapshotError> {
679        let completion_error = self.commit();
680        let report = self.report.clone();
681        if let Some(error) = self.failure.take() {
682            return Err(WgpuSnapshotError {
683                error,
684                report,
685                completion_error,
686            });
687        }
688        if let Some(error) = completion_error {
689            return Err(WgpuSnapshotError {
690                error: Arc::new(RendererError::InvalidRenderState(
691                    "snapshot completion delivery failed".to_owned(),
692                )),
693                report,
694                completion_error: Some(error),
695            });
696        }
697        Ok(report)
698    }
699
700    fn commit(&mut self) -> Option<SnapshotCommitError> {
701        self.snapshot
702            .take()
703            .and_then(|snapshot| snapshot.commit(std::mem::take(&mut self.feedback)).err())
704    }
705}
706
707impl Drop for WgpuPreparedSnapshot<'_> {
708    fn drop(&mut self) {
709        let _ = self.commit();
710    }
711}
712
713#[cfg(test)]
714mod tests;