Skip to main content

sui_render_wgpu/
surface.rs

1#[cfg(target_os = "windows")]
2#[allow(unsafe_code)]
3#[path = "surface/windows.rs"]
4mod windows_surface;
5
6use crate::WgpuRenderer;
7use crate::diagnostics::RendererFrameStats;
8use crate::output::ColorManagementMode;
9use crate::output::DisplayCapabilities;
10use crate::output::OutputStrategy;
11use crate::output::output_transform_requires_intermediate;
12use crate::output::select_output_strategy;
13use std::sync::Arc;
14use sui_core::Error;
15use sui_core::Result;
16use sui_core::Size;
17use sui_core::WindowId;
18use sui_scene::SceneFrame;
19use web_time::Instant;
20use winit::window::Window;
21
22impl WgpuRenderer {
23    /// Begin device setup using this native surface before the first CPU layout.
24    /// Call `register_window` afterwards to finish configuration. Preparation is
25    /// optional, idempotent, and cancelled when the window/renderer is removed.
26    pub fn prepare_window(&mut self, window_id: WindowId, window: Arc<Window>) -> Result<()> {
27        #[cfg(any(target_os = "linux", target_os = "windows", target_os = "macos"))]
28        if self.shared.is_none() && !self.prepared_surfaces.contains_key(&window_id) {
29            let surface = Arc::new(
30                self.instance
31                    .create_surface(Arc::clone(&window))
32                    .map_err(|error| {
33                        Error::new(format!("failed to create wgpu surface: {error}"))
34                    })?,
35            );
36            self.start_device_preparation(Some(window_id), Some(surface.clone()));
37            self.prepared_surfaces
38                .insert(window_id, PreparedSurface { window, surface });
39        }
40        #[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
41        let _ = (window_id, window);
42        Ok(())
43    }
44
45    pub fn register_window(&mut self, window_id: WindowId, window: Arc<Window>) -> Result<()> {
46        let physical_size = window.inner_size();
47        let size = normalize_surface_size(physical_size.width, physical_size.height);
48        let state = match self.prepared_surfaces.remove(&window_id) {
49            Some(prepared) if Arc::ptr_eq(&prepared.window, &window) => {
50                self.configure_new_surface(window, prepared.surface, size)?
51            }
52            _ => self.create_surface_state(window, size)?,
53        };
54
55        self.surfaces.insert(window_id, state);
56        self.offscreen_targets.remove(&window_id);
57        self.intermediate_targets.remove(&window_id);
58        self.swapchain_frames.remove(&window_id);
59        Ok(())
60    }
61
62    pub(crate) fn render_surface(
63        &mut self,
64        frame: &SceneFrame,
65        size: (u32, u32),
66    ) -> Result<RendererFrameStats> {
67        self.ensure_shared(None)?;
68        self.resize_surface(frame.window_id, size)?;
69
70        let prepared = self.prepare_scene_submission(frame)?;
71
72        let Some((frame_texture, suboptimal, surface_acquire_time_us)) =
73            self.acquire_surface_texture(frame.window_id, size)?
74        else {
75            return Ok(RendererFrameStats::default());
76        };
77
78        let (format, strategy, tone_mapping, sdr_content_brightness_nits, display_sdr_white_nits) = {
79            let surface = self.surfaces.get(&frame.window_id).ok_or_else(|| {
80                Error::new(format!(
81                    "missing surface for window {}",
82                    frame.window_id.get()
83                ))
84            })?;
85            (
86                surface.config.format,
87                surface.output_strategy,
88                surface.color_management.tone_mapping,
89                surface.color_management.sdr_content_brightness_nits,
90                surface.display_capabilities.sdr_white_nits,
91            )
92        };
93        let view = frame_texture
94            .texture
95            .create_view(&wgpu::TextureViewDescriptor::default());
96
97        let mut frame_stats = if output_transform_requires_intermediate(strategy) {
98            let intermediate_view = self.ensure_intermediate_target(frame.window_id, size)?;
99            let (intermediate_format, intermediate_texture) = self
100                .intermediate_targets
101                .get(&frame.window_id)
102                .map(|target| (target.format, target.texture.clone()))
103                .ok_or_else(|| Error::new("missing HDR intermediate target after allocation"))?;
104            let mut encoder = self.frame_encoder();
105            let mut frame_stats = self.encode_prepared_scene(
106                prepared,
107                intermediate_format,
108                &intermediate_view,
109                &mut encoder,
110                Some((frame.window_id, &intermediate_texture)),
111            )?;
112            self.encode_output_transform_pass(
113                frame.window_id,
114                &intermediate_view,
115                &view,
116                format,
117                strategy,
118                tone_mapping,
119                sdr_content_brightness_nits,
120                display_sdr_white_nits,
121                &mut frame_stats,
122                &mut encoder,
123            )?;
124            self.submit_frame_encoder(encoder, &mut frame_stats);
125            frame_stats
126        } else if crate::damage::PERSISTENT_SWAPCHAIN_REDRAW
127            && frame_texture
128                .texture
129                .usage()
130                .contains(wgpu::TextureUsages::COPY_DST)
131        {
132            // The swapchain does not keep pixels between frames, so redraw
133            // only what changed in a persistent frame and copy it over.
134            self.shared
135                .as_mut()
136                .expect("renderer shared state initialized")
137                .sdr_fit = crate::output::SdrFit::for_tone_mapping(tone_mapping);
138            let (persistent_view, persistent_texture) =
139                self.ensure_swapchain_frame(frame.window_id, size, format)?;
140            let mut encoder = self.frame_encoder();
141            let mut frame_stats = self.encode_prepared_scene(
142                prepared,
143                format,
144                &persistent_view,
145                &mut encoder,
146                Some((frame.window_id, &persistent_texture)),
147            )?;
148            encoder.copy_texture_to_texture(
149                persistent_texture.as_image_copy(),
150                frame_texture.texture.as_image_copy(),
151                wgpu::Extent3d {
152                    width: size.0,
153                    height: size.1,
154                    depth_or_array_layers: 1,
155                },
156            );
157            self.submit_frame_encoder(encoder, &mut frame_stats);
158            frame_stats
159        } else {
160            self.shared
161                .as_mut()
162                .expect("renderer shared state initialized")
163                .sdr_fit = crate::output::SdrFit::for_tone_mapping(tone_mapping);
164            // The swapchain does not keep pixels between frames, and the
165            // persistent target no longer shows the latest frame.
166            self.frame_resources
167                .target_contents
168                .remove(&frame.window_id);
169            self.submit_prepared_scene(prepared, format, &view)?
170        };
171        frame_stats.surface_acquire_time_us = surface_acquire_time_us;
172        let surface_present_started = self.runtime_diagnostics_enabled.then(Instant::now);
173        self.shared
174            .as_ref()
175            .expect("renderer shared state initialized")
176            .queue
177            .present(frame_texture);
178        frame_stats.surface_present_time_us = surface_present_started
179            .map(|started| started.elapsed().as_micros() as u64)
180            .unwrap_or(0);
181
182        if suboptimal {
183            self.configure_surface(frame.window_id, size)?;
184        }
185
186        Ok(frame_stats)
187    }
188
189    pub(crate) fn acquire_surface_texture(
190        &mut self,
191        window_id: WindowId,
192        size: (u32, u32),
193    ) -> Result<Option<(wgpu::SurfaceTexture, bool, u64)>> {
194        let surface_acquire_started = self.runtime_diagnostics_enabled.then(Instant::now);
195        let (frame_texture, suboptimal) = loop {
196            let result = {
197                let surface = self.surfaces.get(&window_id).ok_or_else(|| {
198                    Error::new(format!("missing surface for window {}", window_id.get()))
199                })?;
200                surface.surface.get_current_texture()
201            };
202
203            match result {
204                wgpu::CurrentSurfaceTexture::Success(texture) => break (texture, false),
205                wgpu::CurrentSurfaceTexture::Suboptimal(texture) => break (texture, true),
206                wgpu::CurrentSurfaceTexture::Outdated => {
207                    self.configure_surface(window_id, size)?;
208                }
209                wgpu::CurrentSurfaceTexture::Lost => {
210                    self.recreate_surface(window_id, size)?;
211                }
212                wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => {
213                    return Ok(None);
214                }
215                wgpu::CurrentSurfaceTexture::Validation => {
216                    return Err(Error::new(
217                        "wgpu surface acquisition triggered a validation error",
218                    ));
219                }
220            }
221        };
222        let surface_acquire_time_us = surface_acquire_started
223            .map(|started| started.elapsed().as_micros() as u64)
224            .unwrap_or(0);
225
226        Ok(Some((frame_texture, suboptimal, surface_acquire_time_us)))
227    }
228
229    pub(crate) fn resize_surface(&mut self, window_id: WindowId, size: (u32, u32)) -> Result<()> {
230        let surface = self
231            .surfaces
232            .get(&window_id)
233            .ok_or_else(|| Error::new(format!("missing surface for window {}", window_id.get())))?;
234
235        if surface.config.width == size.0 && surface.config.height == size.1 {
236            return Ok(());
237        }
238
239        self.configure_surface(window_id, size)
240    }
241
242    pub(crate) fn configure_existing_surface(&mut self, window_id: WindowId) -> Result<()> {
243        let size = {
244            let surface = self.surfaces.get(&window_id).ok_or_else(|| {
245                Error::new(format!("missing surface for window {}", window_id.get()))
246            })?;
247            (surface.config.width.max(1), surface.config.height.max(1))
248        };
249        self.configure_surface(window_id, size)
250    }
251
252    pub(crate) fn configure_surface(
253        &mut self,
254        window_id: WindowId,
255        size: (u32, u32),
256    ) -> Result<()> {
257        let shared = self
258            .shared
259            .as_ref()
260            .expect("renderer shared state initialized");
261        let surface = self
262            .surfaces
263            .get_mut(&window_id)
264            .ok_or_else(|| Error::new(format!("missing surface for window {}", window_id.get())))?;
265
266        let available_surface_formats = surface.surface.get_capabilities(&shared.adapter).formats;
267        let (config, output_strategy) = configure_surface(
268            &surface.surface,
269            &shared.adapter,
270            &shared.device,
271            size,
272            self.vsync_enabled,
273            surface.display_capabilities.clone(),
274            surface.color_management,
275        )?;
276        surface.config = config;
277        surface.output_strategy = output_strategy;
278        surface.available_surface_formats = available_surface_formats;
279        Ok(())
280    }
281
282    pub(crate) fn recreate_surface(&mut self, window_id: WindowId, size: (u32, u32)) -> Result<()> {
283        let window = self
284            .surfaces
285            .get(&window_id)
286            .ok_or_else(|| Error::new(format!("missing surface for window {}", window_id.get())))?
287            .window
288            .clone();
289        let state = self.create_surface_state(window, size)?;
290        self.surfaces.insert(window_id, state);
291        Ok(())
292    }
293
294    pub(crate) fn create_surface_state(
295        &mut self,
296        window: Arc<Window>,
297        size: (u32, u32),
298    ) -> Result<SurfaceState> {
299        let surface = self
300            .instance
301            .create_surface(Arc::clone(&window))
302            .map_err(|error| Error::new(format!("failed to create wgpu surface: {error}")))?;
303        self.configure_new_surface(window, Arc::new(surface), size)
304    }
305
306    fn configure_new_surface(
307        &mut self,
308        window: Arc<Window>,
309        surface: Arc<wgpu::Surface<'static>>,
310        size: (u32, u32),
311    ) -> Result<SurfaceState> {
312        self.ensure_shared(Some(&surface))?;
313
314        let shared = self
315            .shared
316            .as_ref()
317            .expect("renderer shared state initialized");
318        let default_capabilities = DisplayCapabilities::default();
319        let default_color_management = ColorManagementMode::default();
320        let available_surface_formats = surface.get_capabilities(&shared.adapter).formats;
321        let (config, output_strategy) = configure_surface(
322            &surface,
323            &shared.adapter,
324            &shared.device,
325            size,
326            self.vsync_enabled,
327            default_capabilities.clone(),
328            default_color_management,
329        )?;
330
331        Ok(SurfaceState {
332            window,
333            surface,
334            config,
335            display_capabilities: default_capabilities,
336            color_management: default_color_management,
337            output_strategy,
338            available_surface_formats,
339        })
340    }
341}
342
343pub(crate) fn normalize_framebuffer_size(size: Size) -> Option<(u32, u32)> {
344    if size.is_empty() {
345        None
346    } else {
347        Some(normalize_surface_size(
348            size.width.round() as u32,
349            size.height.round() as u32,
350        ))
351    }
352}
353
354pub(crate) fn normalize_surface_size(width: u32, height: u32) -> (u32, u32) {
355    (width.max(1), height.max(1))
356}
357
358pub(crate) fn configure_surface_for_strategy(
359    surface: &wgpu::Surface<'static>,
360    adapter: &wgpu::Adapter,
361    device: &wgpu::Device,
362    size: (u32, u32),
363    vsync_enabled: bool,
364    strategy: OutputStrategy,
365) -> Result<wgpu::SurfaceConfiguration> {
366    let mut config = surface
367        .get_default_config(adapter, size.0, size.1)
368        .ok_or_else(|| Error::new("wgpu adapter does not support presenting to this surface"))?;
369    config.format = strategy.surface_format();
370    config.present_mode = if vsync_enabled {
371        wgpu::PresentMode::AutoVsync
372    } else {
373        wgpu::PresentMode::AutoNoVsync
374    };
375    let capabilities = surface.get_capabilities(adapter);
376    if capabilities
377        .alpha_modes
378        .contains(&wgpu::CompositeAlphaMode::Opaque)
379    {
380        config.alpha_mode = wgpu::CompositeAlphaMode::Opaque;
381    }
382    // Lets a frame redrawn partially in a persistent texture be copied in.
383    if crate::damage::PERSISTENT_SWAPCHAIN_REDRAW
384        && capabilities.usages.contains(wgpu::TextureUsages::COPY_DST)
385    {
386        config.usage |= wgpu::TextureUsages::COPY_DST;
387    }
388    surface.configure(device, &config);
389    configure_native_hdr_surface_color_space(surface, strategy)?;
390    Ok(config)
391}
392
393pub(crate) fn configure_native_hdr_surface_color_space(
394    surface: &wgpu::Surface<'static>,
395    strategy: OutputStrategy,
396) -> Result<()> {
397    if !matches!(strategy, OutputStrategy::HdrNativeSurface { .. }) {
398        return Ok(());
399    }
400
401    #[cfg(target_os = "windows")]
402    {
403        windows_surface::set_native_hdr_surface_color_space(surface)
404            .map_err(|error| Error::new(format!("failed to configure native HDR surface: {error}")))
405    }
406
407    #[cfg(not(target_os = "windows"))]
408    {
409        let _ = surface;
410        Ok(())
411    }
412}
413
414pub(crate) fn configure_surface(
415    surface: &wgpu::Surface<'static>,
416    adapter: &wgpu::Adapter,
417    device: &wgpu::Device,
418    size: (u32, u32),
419    vsync_enabled: bool,
420    display_capabilities: DisplayCapabilities,
421    color_management: ColorManagementMode,
422) -> Result<(wgpu::SurfaceConfiguration, OutputStrategy)> {
423    let surface_capabilities = surface.get_capabilities(adapter);
424    let strategy = select_output_strategy(
425        &surface_capabilities.formats,
426        display_capabilities,
427        color_management,
428    );
429    let config =
430        configure_surface_for_strategy(surface, adapter, device, size, vsync_enabled, strategy)?;
431    Ok((config, strategy))
432}
433
434pub(crate) struct PreparedSurface {
435    window: Arc<Window>,
436    surface: Arc<wgpu::Surface<'static>>,
437}
438
439pub(crate) struct SurfaceState {
440    pub(crate) window: Arc<Window>,
441    pub(crate) surface: Arc<wgpu::Surface<'static>>,
442    pub(crate) config: wgpu::SurfaceConfiguration,
443    pub(crate) display_capabilities: DisplayCapabilities,
444    pub(crate) color_management: ColorManagementMode,
445    pub(crate) output_strategy: OutputStrategy,
446    pub(crate) available_surface_formats: Vec<wgpu::TextureFormat>,
447}