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        Ok(())
59    }
60
61    pub(crate) fn render_surface(
62        &mut self,
63        frame: &SceneFrame,
64        size: (u32, u32),
65    ) -> Result<RendererFrameStats> {
66        self.ensure_shared(None)?;
67        self.resize_surface(frame.window_id, size)?;
68
69        let prepared = self.prepare_scene_submission(frame)?;
70
71        let Some((frame_texture, suboptimal, surface_acquire_time_us)) =
72            self.acquire_surface_texture(frame.window_id, size)?
73        else {
74            return Ok(RendererFrameStats::default());
75        };
76
77        let (format, strategy, tone_mapping, sdr_content_brightness_nits, display_sdr_white_nits) = {
78            let surface = self.surfaces.get(&frame.window_id).ok_or_else(|| {
79                Error::new(format!(
80                    "missing surface for window {}",
81                    frame.window_id.get()
82                ))
83            })?;
84            (
85                surface.config.format,
86                surface.output_strategy,
87                surface.color_management.tone_mapping,
88                surface.color_management.sdr_content_brightness_nits,
89                surface.display_capabilities.sdr_white_nits,
90            )
91        };
92        let view = frame_texture
93            .texture
94            .create_view(&wgpu::TextureViewDescriptor::default());
95
96        let mut frame_stats = if output_transform_requires_intermediate(strategy) {
97            let intermediate_view = self.ensure_intermediate_target(frame.window_id, size)?;
98            let intermediate_format = self
99                .intermediate_targets
100                .get(&frame.window_id)
101                .map(|target| target.format)
102                .ok_or_else(|| Error::new("missing HDR intermediate target after allocation"))?;
103            let mut encoder = self.frame_encoder();
104            let mut frame_stats = self.encode_prepared_scene(
105                prepared,
106                intermediate_format,
107                &intermediate_view,
108                &mut encoder,
109            )?;
110            self.encode_output_transform_pass(
111                frame.window_id,
112                &intermediate_view,
113                &view,
114                format,
115                strategy,
116                tone_mapping,
117                sdr_content_brightness_nits,
118                display_sdr_white_nits,
119                &mut frame_stats,
120                &mut encoder,
121            )?;
122            self.submit_frame_encoder(encoder, &mut frame_stats);
123            frame_stats
124        } else {
125            self.shared
126                .as_mut()
127                .expect("renderer shared state initialized")
128                .sdr_fit = crate::output::SdrFit::for_tone_mapping(tone_mapping);
129            self.submit_prepared_scene(prepared, format, &view)?
130        };
131        frame_stats.surface_acquire_time_us = surface_acquire_time_us;
132        let surface_present_started = self.runtime_diagnostics_enabled.then(Instant::now);
133        self.shared
134            .as_ref()
135            .expect("renderer shared state initialized")
136            .queue
137            .present(frame_texture);
138        frame_stats.surface_present_time_us = surface_present_started
139            .map(|started| started.elapsed().as_micros() as u64)
140            .unwrap_or(0);
141
142        if suboptimal {
143            self.configure_surface(frame.window_id, size)?;
144        }
145
146        Ok(frame_stats)
147    }
148
149    pub(crate) fn acquire_surface_texture(
150        &mut self,
151        window_id: WindowId,
152        size: (u32, u32),
153    ) -> Result<Option<(wgpu::SurfaceTexture, bool, u64)>> {
154        let surface_acquire_started = self.runtime_diagnostics_enabled.then(Instant::now);
155        let (frame_texture, suboptimal) = loop {
156            let result = {
157                let surface = self.surfaces.get(&window_id).ok_or_else(|| {
158                    Error::new(format!("missing surface for window {}", window_id.get()))
159                })?;
160                surface.surface.get_current_texture()
161            };
162
163            match result {
164                wgpu::CurrentSurfaceTexture::Success(texture) => break (texture, false),
165                wgpu::CurrentSurfaceTexture::Suboptimal(texture) => break (texture, true),
166                wgpu::CurrentSurfaceTexture::Outdated => {
167                    self.configure_surface(window_id, size)?;
168                }
169                wgpu::CurrentSurfaceTexture::Lost => {
170                    self.recreate_surface(window_id, size)?;
171                }
172                wgpu::CurrentSurfaceTexture::Timeout | wgpu::CurrentSurfaceTexture::Occluded => {
173                    return Ok(None);
174                }
175                wgpu::CurrentSurfaceTexture::Validation => {
176                    return Err(Error::new(
177                        "wgpu surface acquisition triggered a validation error",
178                    ));
179                }
180            }
181        };
182        let surface_acquire_time_us = surface_acquire_started
183            .map(|started| started.elapsed().as_micros() as u64)
184            .unwrap_or(0);
185
186        Ok(Some((frame_texture, suboptimal, surface_acquire_time_us)))
187    }
188
189    pub(crate) fn resize_surface(&mut self, window_id: WindowId, size: (u32, u32)) -> Result<()> {
190        let surface = self
191            .surfaces
192            .get(&window_id)
193            .ok_or_else(|| Error::new(format!("missing surface for window {}", window_id.get())))?;
194
195        if surface.config.width == size.0 && surface.config.height == size.1 {
196            return Ok(());
197        }
198
199        self.configure_surface(window_id, size)
200    }
201
202    pub(crate) fn configure_existing_surface(&mut self, window_id: WindowId) -> Result<()> {
203        let size = {
204            let surface = self.surfaces.get(&window_id).ok_or_else(|| {
205                Error::new(format!("missing surface for window {}", window_id.get()))
206            })?;
207            (surface.config.width.max(1), surface.config.height.max(1))
208        };
209        self.configure_surface(window_id, size)
210    }
211
212    pub(crate) fn configure_surface(
213        &mut self,
214        window_id: WindowId,
215        size: (u32, u32),
216    ) -> Result<()> {
217        let shared = self
218            .shared
219            .as_ref()
220            .expect("renderer shared state initialized");
221        let surface = self
222            .surfaces
223            .get_mut(&window_id)
224            .ok_or_else(|| Error::new(format!("missing surface for window {}", window_id.get())))?;
225
226        let available_surface_formats = surface.surface.get_capabilities(&shared.adapter).formats;
227        let (config, output_strategy) = configure_surface(
228            &surface.surface,
229            &shared.adapter,
230            &shared.device,
231            size,
232            self.vsync_enabled,
233            surface.display_capabilities.clone(),
234            surface.color_management,
235        )?;
236        surface.config = config;
237        surface.output_strategy = output_strategy;
238        surface.available_surface_formats = available_surface_formats;
239        Ok(())
240    }
241
242    pub(crate) fn recreate_surface(&mut self, window_id: WindowId, size: (u32, u32)) -> Result<()> {
243        let window = self
244            .surfaces
245            .get(&window_id)
246            .ok_or_else(|| Error::new(format!("missing surface for window {}", window_id.get())))?
247            .window
248            .clone();
249        let state = self.create_surface_state(window, size)?;
250        self.surfaces.insert(window_id, state);
251        Ok(())
252    }
253
254    pub(crate) fn create_surface_state(
255        &mut self,
256        window: Arc<Window>,
257        size: (u32, u32),
258    ) -> Result<SurfaceState> {
259        let surface = self
260            .instance
261            .create_surface(Arc::clone(&window))
262            .map_err(|error| Error::new(format!("failed to create wgpu surface: {error}")))?;
263        self.configure_new_surface(window, Arc::new(surface), size)
264    }
265
266    fn configure_new_surface(
267        &mut self,
268        window: Arc<Window>,
269        surface: Arc<wgpu::Surface<'static>>,
270        size: (u32, u32),
271    ) -> Result<SurfaceState> {
272        self.ensure_shared(Some(&surface))?;
273
274        let shared = self
275            .shared
276            .as_ref()
277            .expect("renderer shared state initialized");
278        let default_capabilities = DisplayCapabilities::default();
279        let default_color_management = ColorManagementMode::default();
280        let available_surface_formats = surface.get_capabilities(&shared.adapter).formats;
281        let (config, output_strategy) = configure_surface(
282            &surface,
283            &shared.adapter,
284            &shared.device,
285            size,
286            self.vsync_enabled,
287            default_capabilities.clone(),
288            default_color_management,
289        )?;
290
291        Ok(SurfaceState {
292            window,
293            surface,
294            config,
295            display_capabilities: default_capabilities,
296            color_management: default_color_management,
297            output_strategy,
298            available_surface_formats,
299        })
300    }
301}
302
303pub(crate) fn normalize_framebuffer_size(size: Size) -> Option<(u32, u32)> {
304    if size.is_empty() {
305        None
306    } else {
307        Some(normalize_surface_size(
308            size.width.round() as u32,
309            size.height.round() as u32,
310        ))
311    }
312}
313
314pub(crate) fn normalize_surface_size(width: u32, height: u32) -> (u32, u32) {
315    (width.max(1), height.max(1))
316}
317
318pub(crate) fn configure_surface_for_strategy(
319    surface: &wgpu::Surface<'static>,
320    adapter: &wgpu::Adapter,
321    device: &wgpu::Device,
322    size: (u32, u32),
323    vsync_enabled: bool,
324    strategy: OutputStrategy,
325) -> Result<wgpu::SurfaceConfiguration> {
326    let mut config = surface
327        .get_default_config(adapter, size.0, size.1)
328        .ok_or_else(|| Error::new("wgpu adapter does not support presenting to this surface"))?;
329    config.format = strategy.surface_format();
330    config.present_mode = if vsync_enabled {
331        wgpu::PresentMode::AutoVsync
332    } else {
333        wgpu::PresentMode::AutoNoVsync
334    };
335    let capabilities = surface.get_capabilities(adapter);
336    if capabilities
337        .alpha_modes
338        .contains(&wgpu::CompositeAlphaMode::Opaque)
339    {
340        config.alpha_mode = wgpu::CompositeAlphaMode::Opaque;
341    }
342    surface.configure(device, &config);
343    configure_native_hdr_surface_color_space(surface, strategy)?;
344    Ok(config)
345}
346
347pub(crate) fn configure_native_hdr_surface_color_space(
348    surface: &wgpu::Surface<'static>,
349    strategy: OutputStrategy,
350) -> Result<()> {
351    if !matches!(strategy, OutputStrategy::HdrNativeSurface { .. }) {
352        return Ok(());
353    }
354
355    #[cfg(target_os = "windows")]
356    {
357        windows_surface::set_native_hdr_surface_color_space(surface)
358            .map_err(|error| Error::new(format!("failed to configure native HDR surface: {error}")))
359    }
360
361    #[cfg(not(target_os = "windows"))]
362    {
363        let _ = surface;
364        Ok(())
365    }
366}
367
368pub(crate) fn configure_surface(
369    surface: &wgpu::Surface<'static>,
370    adapter: &wgpu::Adapter,
371    device: &wgpu::Device,
372    size: (u32, u32),
373    vsync_enabled: bool,
374    display_capabilities: DisplayCapabilities,
375    color_management: ColorManagementMode,
376) -> Result<(wgpu::SurfaceConfiguration, OutputStrategy)> {
377    let surface_capabilities = surface.get_capabilities(adapter);
378    let strategy = select_output_strategy(
379        &surface_capabilities.formats,
380        display_capabilities,
381        color_management,
382    );
383    let config =
384        configure_surface_for_strategy(surface, adapter, device, size, vsync_enabled, strategy)?;
385    Ok((config, strategy))
386}
387
388pub(crate) struct PreparedSurface {
389    window: Arc<Window>,
390    surface: Arc<wgpu::Surface<'static>>,
391}
392
393pub(crate) struct SurfaceState {
394    pub(crate) window: Arc<Window>,
395    pub(crate) surface: Arc<wgpu::Surface<'static>>,
396    pub(crate) config: wgpu::SurfaceConfiguration,
397    pub(crate) display_capabilities: DisplayCapabilities,
398    pub(crate) color_management: ColorManagementMode,
399    pub(crate) output_strategy: OutputStrategy,
400    pub(crate) available_surface_formats: Vec<wgpu::TextureFormat>,
401}