dear-imgui-wgpu 0.21.0

WGPU renderer backend for dear-imgui-rs (native + WebAssembly)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//! Per-viewport WGPU surface state and recovery policy.

use std::rc::Rc;

use super::platform_adapter;
use super::registry::GlobalHandles;
use super::runtime::WgpuViewportError;
use crate::WgpuViewportSurfaceConfig;
use dear_imgui_rs::ViewportFlags;
use dear_imgui_rs::platform_io::Viewport;

pub(super) struct ViewportWgpuData {
    pub(super) native_target: dear_imgui_rs::NativeWindowTarget,
    pub(super) surface: Option<Rc<wgpu::Surface<'static>>>,
    pub(super) targets: Option<ViewportRenderTargets>,
    pub(super) size: [u32; 2],
    pub(super) pending_reconfigure: bool,
}

pub(super) struct ViewportRenderTargets {
    pub(super) config: wgpu::SurfaceConfiguration,
    pub(super) multisampled_color: Option<OwnedAttachment>,
    pub(super) depth_stencil: Option<OwnedAttachment>,
}

pub(super) struct OwnedAttachment {
    _texture: wgpu::Texture,
    pub(super) view: wgpu::TextureView,
}

pub(super) fn release_surface_bundle_parts<Targets, Surface>(
    targets: &mut Option<Targets>,
    surface: &mut Option<Surface>,
) {
    drop(targets.take());
    drop(surface.take());
}

impl ViewportWgpuData {
    pub(super) fn release_surface_bundle(&mut self) {
        release_surface_bundle_parts(&mut self.targets, &mut self.surface);
        self.size = [0, 0];
        self.pending_reconfigure = false;
    }
}

impl Drop for ViewportWgpuData {
    fn drop(&mut self) {
        // Acquired work has its own Surface Rc and native lease; retire only the baseline here.
        self.release_surface_bundle();
    }
}

pub(super) fn resolve_present_mode(
    requested: wgpu::PresentMode,
    supported: &[wgpu::PresentMode],
) -> wgpu::PresentMode {
    match requested {
        wgpu::PresentMode::AutoVsync | wgpu::PresentMode::AutoNoVsync => requested,
        mode if supported.contains(&mode) => mode,
        wgpu::PresentMode::Fifo | wgpu::PresentMode::FifoRelaxed => wgpu::PresentMode::AutoVsync,
        wgpu::PresentMode::Immediate | wgpu::PresentMode::Mailbox => wgpu::PresentMode::AutoNoVsync,
    }
}

pub(super) fn resolve_alpha_mode(
    requested: wgpu::CompositeAlphaMode,
    supported: &[wgpu::CompositeAlphaMode],
) -> wgpu::CompositeAlphaMode {
    if requested == wgpu::CompositeAlphaMode::Auto || supported.contains(&requested) {
        requested
    } else {
        wgpu::CompositeAlphaMode::Auto
    }
}

#[cfg(feature = "wgpu-30")]
pub(super) fn supports_surface_format(
    capabilities: &wgpu::SurfaceCapabilities,
    format: wgpu::TextureFormat,
) -> bool {
    capabilities
        .color_spaces(format)
        .contains(wgpu::SurfaceColorSpaces::SRGB)
}

#[cfg(not(feature = "wgpu-30"))]
pub(super) fn supports_surface_format(
    capabilities: &wgpu::SurfaceCapabilities,
    format: wgpu::TextureFormat,
) -> bool {
    capabilities.formats.contains(&format)
}

pub(super) fn surface_config_from_capabilities(
    render_target_format: wgpu::TextureFormat,
    viewport_surface_config: WgpuViewportSurfaceConfig,
    capabilities: &wgpu::SurfaceCapabilities,
    size: [u32; 2],
) -> Result<Option<wgpu::SurfaceConfiguration>, WgpuViewportError> {
    let format_supported = supports_surface_format(capabilities, render_target_format);
    if !format_supported {
        return Err(WgpuViewportError::UnsupportedSurfaceFormat {
            format: render_target_format,
            #[cfg(feature = "wgpu-30")]
            color_space: "the required sRGB color space",
            #[cfg(not(feature = "wgpu-30"))]
            color_space: "the surface's automatic color space",
        });
    }
    let present_mode = resolve_present_mode(
        viewport_surface_config.present_mode,
        &capabilities.present_modes,
    );
    let alpha_mode = resolve_alpha_mode(
        viewport_surface_config.alpha_mode,
        &capabilities.alpha_modes,
    );
    if size[0] == 0 || size[1] == 0 {
        return Ok(None);
    }
    Ok(Some(wgpu::SurfaceConfiguration {
        usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
        format: render_target_format,
        #[cfg(feature = "wgpu-30")]
        color_space: wgpu::SurfaceColorSpace::Srgb,
        width: size[0],
        height: size[1],
        present_mode,
        alpha_mode,
        view_formats: vec![],
        desired_maximum_frame_latency: viewport_surface_config.desired_maximum_frame_latency,
    }))
}

fn surface_config(
    globals: &GlobalHandles,
    surface: &wgpu::Surface<'static>,
    size: [u32; 2],
) -> Result<Option<wgpu::SurfaceConfiguration>, WgpuViewportError> {
    let capabilities = surface.get_capabilities(&globals.adapter);
    surface_config_from_capabilities(
        globals.render_target_format,
        globals.viewport_surface_config,
        &capabilities,
        size,
    )
}

fn configure_surface(
    globals: &GlobalHandles,
    surface: &wgpu::Surface<'static>,
    size: [u32; 2],
) -> Result<Option<ViewportRenderTargets>, WgpuViewportError> {
    let Some(config) = surface_config(globals, surface, size)? else {
        return Ok(None);
    };
    surface.configure(&globals.device, &config);
    Ok(Some(create_render_targets(globals, config)))
}

fn create_render_targets(
    globals: &GlobalHandles,
    config: wgpu::SurfaceConfiguration,
) -> ViewportRenderTargets {
    let size = [config.width, config.height];
    let sample_count = globals.multisample_state.count;
    let multisampled_color = (sample_count > 1).then(|| {
        create_attachment(
            &globals.device,
            "dear-imgui-wgpu::viewport-msaa-color",
            size,
            sample_count,
            globals.render_target_format,
        )
    });
    let depth_stencil = globals.depth_stencil_format.map(|format| {
        create_attachment(
            &globals.device,
            "dear-imgui-wgpu::viewport-depth-stencil",
            size,
            sample_count,
            format,
        )
    });
    ViewportRenderTargets {
        config,
        multisampled_color,
        depth_stencil,
    }
}

fn create_attachment(
    device: &wgpu::Device,
    label: &'static str,
    size: [u32; 2],
    sample_count: u32,
    format: wgpu::TextureFormat,
) -> OwnedAttachment {
    let texture = device.create_texture(&wgpu::TextureDescriptor {
        label: Some(label),
        size: wgpu::Extent3d {
            width: size[0],
            height: size[1],
            depth_or_array_layers: 1,
        },
        mip_level_count: 1,
        sample_count,
        dimension: wgpu::TextureDimension::D2,
        format,
        usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
        view_formats: &[],
    });
    let view = texture.create_view(&wgpu::TextureViewDescriptor::default());
    OwnedAttachment {
        _texture: texture,
        view,
    }
}

pub(super) unsafe fn create_viewport_data(
    viewport: &Viewport,
    globals: &GlobalHandles,
) -> Result<ViewportWgpuData, WgpuViewportError> {
    let (surface, size, native_target) = create_native_surface(globals, viewport, None)?;
    let targets = configure_surface(globals, &surface, size)?;
    Ok(ViewportWgpuData {
        native_target,
        surface: Some(Rc::new(surface)),
        targets,
        size,
        pending_reconfigure: false,
    })
}

fn create_native_surface(
    globals: &GlobalHandles,
    viewport: &Viewport,
    expected: Option<dear_imgui_rs::NativeWindowInstanceId>,
) -> Result<
    (
        wgpu::Surface<'static>,
        [u32; 2],
        dear_imgui_rs::NativeWindowTarget,
    ),
    WgpuViewportError,
> {
    #[cfg(feature = "multi-viewport-winit")]
    return platform_adapter::create_surface(
        &globals.instance,
        &globals.platform,
        viewport,
        expected,
    );
    #[cfg(all(not(feature = "multi-viewport-winit"), feature = "multi-viewport-sdl3"))]
    // SAFETY: renderer resources are released before SDL platform-window teardown. The exact
    // captured owner validates the registration before lending the native pointer.
    unsafe {
        platform_adapter::create_surface(&globals.instance, &globals.platform, viewport, expected)
    }
}

pub(super) fn reconfigure_surface(
    data: &mut ViewportWgpuData,
    globals: &GlobalHandles,
    size: [u32; 2],
) -> Result<(), WgpuViewportError> {
    if data
        .surface
        .as_ref()
        .is_some_and(|surface| Rc::strong_count(surface) > 1)
    {
        // Configuring while an acquired frame is retained is invalid. Preserve the current
        // bundle and refresh authoritative geometry after all pending work releases it.
        data.pending_reconfigure = true;
        return Ok(());
    }
    if size[0] == 0 || size[1] == 0 {
        drop(data.targets.take());
        data.size = size;
        data.pending_reconfigure = false;
        return Ok(());
    }
    let surface = data
        .surface
        .as_ref()
        .ok_or(WgpuViewportError::SurfaceOperationFailed {
            operation: "reconfigure a released viewport surface",
        })?;
    let targets = configure_surface(globals, surface, size)?;
    data.targets = targets;
    data.size = size;
    data.pending_reconfigure = false;
    Ok(())
}

unsafe fn recreate_surface(
    viewport: &Viewport,
    data: &mut ViewportWgpuData,
    globals: &GlobalHandles,
) -> Result<(), WgpuViewportError> {
    data.release_surface_bundle();
    let (surface, size, native_target) =
        create_native_surface(globals, viewport, Some(data.native_target.instance_id))?;
    let targets = configure_surface(globals, &surface, size)?;
    data.surface = Some(Rc::new(surface));
    data.native_target = native_target;
    data.targets = targets;
    data.size = size;
    Ok(())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum SurfaceEvent {
    Success,
    Suboptimal,
    Outdated,
    Lost,
    Timeout,
    #[cfg(any(feature = "wgpu-29", feature = "wgpu-30", test))]
    Occluded,
    #[cfg(any(feature = "wgpu-29", feature = "wgpu-30", test))]
    Validation,
    #[cfg(any(feature = "wgpu-27", feature = "wgpu-28", test))]
    OutOfMemory,
    #[cfg(any(feature = "wgpu-27", feature = "wgpu-28", test))]
    Other,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum SurfaceAction {
    Render,
    RenderThenReconfigure,
    Reconfigure,
    Recreate,
    Skip,
    Reject,
}

pub(super) const fn surface_action(event: SurfaceEvent) -> SurfaceAction {
    match event {
        SurfaceEvent::Success => SurfaceAction::Render,
        SurfaceEvent::Suboptimal => SurfaceAction::RenderThenReconfigure,
        SurfaceEvent::Outdated => SurfaceAction::Reconfigure,
        SurfaceEvent::Lost => SurfaceAction::Recreate,
        SurfaceEvent::Timeout => SurfaceAction::Skip,
        #[cfg(any(feature = "wgpu-29", feature = "wgpu-30", test))]
        SurfaceEvent::Occluded => SurfaceAction::Skip,
        #[cfg(any(feature = "wgpu-29", feature = "wgpu-30", test))]
        SurfaceEvent::Validation => SurfaceAction::Reject,
        #[cfg(any(feature = "wgpu-27", feature = "wgpu-28", test))]
        SurfaceEvent::OutOfMemory | SurfaceEvent::Other => SurfaceAction::Reject,
    }
}

impl SurfaceEvent {
    pub(super) const fn name(self) -> &'static str {
        match self {
            Self::Success => "success",
            Self::Suboptimal => "suboptimal",
            Self::Outdated => "outdated",
            Self::Lost => "lost",
            Self::Timeout => "timeout",
            #[cfg(any(feature = "wgpu-29", feature = "wgpu-30", test))]
            Self::Occluded => "occluded",
            #[cfg(any(feature = "wgpu-29", feature = "wgpu-30", test))]
            Self::Validation => "validation",
            #[cfg(any(feature = "wgpu-27", feature = "wgpu-28", test))]
            Self::OutOfMemory => "out of memory",
            #[cfg(any(feature = "wgpu-27", feature = "wgpu-28", test))]
            Self::Other => "other",
        }
    }
}

pub(super) unsafe fn handle_non_renderable_surface_event(
    event: SurfaceEvent,
    viewport: &mut Viewport,
    data: &mut ViewportWgpuData,
    globals: &GlobalHandles,
) -> Result<(), WgpuViewportError> {
    match surface_action(event) {
        SurfaceAction::Reconfigure => {
            let size = platform_adapter::framebuffer_size(
                &globals.platform,
                data.native_target.instance_id,
            )?;
            reconfigure_surface(data, globals, size)
        }
        SurfaceAction::Recreate => {
            let result = unsafe { recreate_surface(viewport, data, globals) };
            if result.is_err() {
                request_close_after_surface_creation_failure(viewport);
            }
            result
        }
        SurfaceAction::Skip => Ok(()),
        SurfaceAction::Reject => Err(WgpuViewportError::SurfaceRejected {
            event: event.name(),
        }),
        SurfaceAction::Render | SurfaceAction::RenderThenReconfigure => {
            debug_assert!(false, "renderable surface event reached recovery path");
            Ok(())
        }
    }
}

pub(super) fn request_close_after_surface_creation_failure(viewport: &mut Viewport) {
    viewport.set_platform_request_close(true);
}

pub(super) fn should_clear_viewport(flags: ViewportFlags) -> bool {
    !flags.contains(ViewportFlags::NO_RENDERER_CLEAR)
}