Skip to main content

wgpu_core/
present.rs

1/*! Presentation.
2
3## Lifecycle
4
5Whenever a submission detects the use of any surface texture, it adds it to the device
6tracker for the duration of the submission (temporarily, while recording).
7It's added with `UNINITIALIZED` state and transitioned into `empty()` state.
8When this texture is presented, we remove it from the device tracker as well as
9extract it from the hub.
10!*/
11
12use alloc::{boxed::Box, sync::Arc, vec::Vec};
13use core::{mem::ManuallyDrop, sync::atomic::Ordering};
14
15#[cfg(feature = "trace")]
16use crate::device::trace::{Action, IntoTrace};
17use crate::{
18    conv,
19    device::{queue::Queue, Device, DeviceError, MissingDownlevelFlags, WaitIdleError},
20    global::Global,
21    hal_label, id,
22    instance::Surface,
23    resource::{self, Labeled},
24};
25
26use thiserror::Error;
27use wgt::{
28    error::{ErrorType, WebGpuError},
29    SurfaceStatus as Status,
30};
31
32const FRAME_TIMEOUT_MS: u32 = 1000;
33
34#[derive(Debug)]
35pub(crate) struct Presentation {
36    pub(crate) device: Arc<Device>,
37    pub(crate) config: wgt::SurfaceConfiguration<Vec<wgt::TextureFormat>>,
38    pub(crate) acquired_texture: Option<Arc<resource::Texture>>,
39    /// The slot of the acquired texture's image in `images`, where the
40    /// backend tells its images apart.
41    pub(crate) acquired_image: Option<u32>,
42    /// The images the surface handed out since it was configured.
43    pub(crate) images: PresentedImages,
44}
45
46/// A presentable image a surface texture is (Cranpose fork).
47#[derive(Clone, Copy, Debug, PartialEq, Eq)]
48pub struct SurfaceImage {
49    /// The image's slot, the same each time the surface hands the image out
50    /// again until it is configured anew.
51    pub index: u32,
52    /// Whether the texture holds what the image last presented: the surface
53    /// keeps presented images and this one was presented since the surface
54    /// was configured. Otherwise its contents are undefined.
55    pub kept: bool,
56    /// How many presentable images the surface hands out: until it has
57    /// handed out that many since it was configured, or one twice, the next
58    /// may be one it never handed out.
59    pub images: u32,
60}
61
62/// The images a surface followed at once; a surface with more hands the
63/// oldest followed one's slot to the next new image, which holds nothing.
64const IMAGE_SLOTS: usize = 8;
65
66/// The presentable images a surface handed out since it was configured, by
67/// the identity their backend gives them (`image_id`), and which of them
68/// hold what they last presented (Cranpose fork).
69#[derive(Debug, Default)]
70pub(crate) struct PresentedImages {
71    /// By slot, the identity of the image in it.
72    ids: [Option<u64>; IMAGE_SLOTS],
73    /// The slots, as bits, whose image holds what it last presented.
74    kept: u8,
75    /// The slot a new image takes once every slot is taken.
76    next: usize,
77}
78
79impl PresentedImages {
80    /// The slot of the image of `id`, and whether it holds what it last
81    /// presented; an image not seen before takes a slot and holds nothing.
82    fn acquire(&mut self, id: u64) -> (u32, bool) {
83        let slot = match self.ids.iter().position(|known| *known == Some(id)) {
84            Some(slot) => slot,
85            None => {
86                let slot = self
87                    .ids
88                    .iter()
89                    .position(Option::is_none)
90                    .unwrap_or(self.next);
91                self.next = (slot + 1) % IMAGE_SLOTS;
92                self.ids[slot] = Some(id);
93                self.kept &= !(1 << slot);
94                slot
95            }
96        };
97        (slot as u32, self.kept & (1 << slot) != 0)
98    }
99
100    /// Marks the image in `slot` as holding what it presented, or not.
101    fn keep(&mut self, slot: u32, kept: bool) {
102        let bit = 1u8 << slot;
103        if kept {
104            self.kept |= bit;
105        } else {
106            self.kept &= !bit;
107        }
108    }
109}
110
111/// Forgets the acquired image of a presentation, which goes back
112/// unpresented: its pixels and layout are whatever the frame left.
113fn forget_acquired_image(acquired_image: &mut Option<u32>, images: &mut PresentedImages) {
114    if let Some(slot) = acquired_image.take() {
115        images.keep(slot, false);
116    }
117}
118
119#[derive(Clone, Debug, Error)]
120#[non_exhaustive]
121pub enum SurfaceError {
122    #[error("Surface is invalid")]
123    Invalid,
124    #[error("Surface is not configured for presentation")]
125    NotConfigured,
126    #[error(transparent)]
127    Device(#[from] DeviceError),
128    #[error("Surface image is already acquired")]
129    AlreadyAcquired,
130    #[error("No surface image is currently acquired to present")]
131    NothingToPresent,
132    #[error("Texture has been destroyed")]
133    TextureDestroyed,
134}
135
136impl WebGpuError for SurfaceError {
137    fn webgpu_error_type(&self) -> ErrorType {
138        match self {
139            Self::Device(e) => e.webgpu_error_type(),
140            Self::Invalid
141            | Self::NotConfigured
142            | Self::AlreadyAcquired
143            | Self::NothingToPresent
144            | Self::TextureDestroyed => ErrorType::Validation,
145        }
146    }
147}
148
149#[derive(Clone, Debug, Error)]
150#[non_exhaustive]
151pub enum ConfigureSurfaceError {
152    #[error(transparent)]
153    Device(#[from] DeviceError),
154    #[error("Invalid surface")]
155    InvalidSurface,
156    #[error("The view format {0:?} is not compatible with texture format {1:?}, only changing srgb-ness is allowed.")]
157    InvalidViewFormat(wgt::TextureFormat, wgt::TextureFormat),
158    #[error(transparent)]
159    MissingDownlevelFlags(#[from] MissingDownlevelFlags),
160    #[error("The `SurfaceOutput` returned by `get_current_texture` must be dropped before re-configuring via `configure` or  retrieving a new texture via `get_current_texture`.")]
161    PreviousOutputExists,
162    #[error("Failed to wait for GPU to come idle before reconfiguring the Surface")]
163    GpuWaitTimeout,
164    #[error("Both `Surface` width and height must be non-zero. Wait to recreate the `Surface` until the window has non-zero area.")]
165    ZeroArea,
166    #[error("`Surface` width and height must be within the maximum supported texture size. Requested was ({width}, {height}), maximum extent for either dimension is {max_texture_dimension_2d}.")]
167    TooLarge {
168        width: u32,
169        height: u32,
170        max_texture_dimension_2d: u32,
171    },
172    #[error("Surface does not support the adapter's queue family")]
173    UnsupportedQueueFamily,
174    #[error("Requested format {requested:?} is not in list of supported formats: {available:?}")]
175    UnsupportedFormat {
176        requested: wgt::TextureFormat,
177        available: Vec<wgt::TextureFormat>,
178    },
179    #[error("Requested color space {requested:?} is not in the list of color spaces supported for format {format:?}: {available:?}")]
180    UnsupportedColorSpace {
181        requested: wgt::SurfaceColorSpace,
182        format: wgt::TextureFormat,
183        available: wgt::SurfaceColorSpaces,
184    },
185    #[error("Requested present mode {requested:?} is not in the list of supported present modes: {available:?}")]
186    UnsupportedPresentMode {
187        requested: wgt::PresentMode,
188        available: Vec<wgt::PresentMode>,
189    },
190    #[error("Requested alpha mode {requested:?} is not in the list of supported alpha modes: {available:?}")]
191    UnsupportedAlphaMode {
192        requested: wgt::CompositeAlphaMode,
193        available: Vec<wgt::CompositeAlphaMode>,
194    },
195    #[error("Requested usage {requested:?} is not in the list of supported usages: {available:?}")]
196    UnsupportedUsage {
197        requested: wgt::TextureUses,
198        available: wgt::TextureUses,
199    },
200}
201
202impl From<WaitIdleError> for ConfigureSurfaceError {
203    fn from(e: WaitIdleError) -> Self {
204        match e {
205            WaitIdleError::Device(d) => ConfigureSurfaceError::Device(d),
206            WaitIdleError::WrongSubmissionIndex(..) => unreachable!(),
207            WaitIdleError::Timeout => ConfigureSurfaceError::GpuWaitTimeout,
208        }
209    }
210}
211
212impl WebGpuError for ConfigureSurfaceError {
213    fn webgpu_error_type(&self) -> ErrorType {
214        match self {
215            Self::Device(e) => e.webgpu_error_type(),
216            Self::MissingDownlevelFlags(e) => e.webgpu_error_type(),
217            Self::InvalidSurface
218            | Self::InvalidViewFormat(..)
219            | Self::PreviousOutputExists
220            | Self::GpuWaitTimeout
221            | Self::ZeroArea
222            | Self::TooLarge { .. }
223            | Self::UnsupportedQueueFamily
224            | Self::UnsupportedFormat { .. }
225            | Self::UnsupportedColorSpace { .. }
226            | Self::UnsupportedPresentMode { .. }
227            | Self::UnsupportedAlphaMode { .. }
228            | Self::UnsupportedUsage { .. } => ErrorType::Validation,
229        }
230    }
231}
232
233pub type ResolvedSurfaceOutput = SurfaceOutput<Arc<resource::Texture>>;
234
235#[repr(C)]
236#[derive(Debug)]
237pub struct SurfaceOutput<T = id::TextureId> {
238    pub status: Status,
239    pub texture: Option<T>,
240    /// The swapchain image the texture is, where the backend numbers them.
241    pub image: Option<SurfaceImage>,
242}
243
244impl Surface {
245    pub fn get_current_texture(&self) -> Result<ResolvedSurfaceOutput, SurfaceError> {
246        profiling::scope!("Surface::get_current_texture");
247
248        let (device, config) = if let Some(ref present) = *self.presentation.lock() {
249            present.device.check_is_valid()?;
250            (present.device.clone(), present.config.clone())
251        } else {
252            return Err(SurfaceError::NotConfigured);
253        };
254
255        let suf = self.raw(device.backend()).unwrap();
256        let mut image = None;
257        let (texture, status) = match unsafe {
258            suf.acquire_texture(
259                Some(core::time::Duration::from_millis(FRAME_TIMEOUT_MS as u64)),
260                device.fence.as_ref(),
261            )
262        } {
263            Ok(ast) => {
264                let texture_desc = wgt::TextureDescriptor {
265                    label: hal_label(
266                        Some(alloc::borrow::Cow::Borrowed("<Surface Texture>")),
267                        device.instance_flags,
268                    ),
269                    size: wgt::Extent3d {
270                        width: config.width,
271                        height: config.height,
272                        depth_or_array_layers: 1,
273                    },
274                    sample_count: 1,
275                    mip_level_count: 1,
276                    format: config.format,
277                    dimension: wgt::TextureDimension::D2,
278                    usage: config.usage,
279                    view_formats: config.view_formats,
280                };
281                let format_features = wgt::TextureFormatFeatures {
282                    allowed_usages: wgt::TextureUsages::RENDER_ATTACHMENT,
283                    flags: wgt::TextureFormatFeatureFlags::MULTISAMPLE_X4
284                        | wgt::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE,
285                };
286                let hal_usage = conv::map_texture_usage(
287                    config.usage,
288                    config.format.into(),
289                    format_features.flags,
290                );
291                let clear_view_desc = hal::TextureViewDescriptor {
292                    label: hal_label(
293                        Some("(wgpu internal) clear surface texture view"),
294                        device.instance_flags,
295                    ),
296                    format: config.format,
297                    dimension: wgt::TextureViewDimension::D2,
298                    usage: wgt::TextureUses::COLOR_TARGET,
299                    range: wgt::ImageSubresourceRange::default(),
300                };
301                let clear_view = unsafe {
302                    device
303                        .raw()
304                        .create_texture_view(ast.texture.as_ref().borrow(), &clear_view_desc)
305                }
306                .map_err(|e| device.handle_hal_error(e))?;
307
308                let image_id = ast.texture.image_id();
309                let mut presentation = self.presentation.lock();
310                let present = presentation.as_mut().unwrap();
311                let slot = image_id.map(|id| present.images.acquire(id));
312                // An image that holds what it presented stays as it is: in
313                // the layout it was presented in, and initialized, so a pass
314                // that loads it reads those pixels instead of a clear.
315                let kept = self.keep_images.load(Ordering::Acquire)
316                    && slot.is_some_and(|(_, kept)| kept);
317                let texture = resource::Texture::new(
318                    &device,
319                    resource::TextureInner::Surface { raw: ast.texture },
320                    hal_usage,
321                    &texture_desc,
322                    format_features,
323                    resource::TextureClearMode::Surface {
324                        clear_view: ManuallyDrop::new(clear_view),
325                    },
326                    !kept,
327                );
328
329                let texture = Arc::new(texture);
330
331                device.trackers.lock().textures.insert_single(
332                    &texture,
333                    if kept {
334                        wgt::TextureUses::PRESENT
335                    } else {
336                        wgt::TextureUses::UNINITIALIZED
337                    },
338                );
339
340                if present.acquired_texture.is_some() {
341                    return Err(SurfaceError::AlreadyAcquired);
342                }
343                present.acquired_texture = Some(texture.clone());
344                present.acquired_image = slot.map(|(index, _)| index);
345                image = slot.map(|(index, _)| SurfaceImage {
346                    index,
347                    kept,
348                    images: ast.images,
349                });
350
351                let status = if ast.suboptimal {
352                    Status::Suboptimal
353                } else {
354                    Status::Good
355                };
356                (Some(texture), status)
357            }
358            Err(err) => (
359                None,
360                match err {
361                    hal::SurfaceError::Timeout => Status::Timeout,
362                    hal::SurfaceError::Occluded => Status::Occluded,
363                    hal::SurfaceError::Lost => Status::Lost,
364                    hal::SurfaceError::Device(err) => {
365                        return Err(device.handle_hal_error(err).into());
366                    }
367                    hal::SurfaceError::Outdated => Status::Outdated,
368                    hal::SurfaceError::Other(msg) => {
369                        log::error!("acquire error: {msg}");
370                        Status::Lost
371                    }
372                },
373            ),
374        };
375
376        Ok(ResolvedSurfaceOutput {
377            status,
378            texture,
379            image,
380        })
381    }
382
383    /// Marks the image in `slot` as holding what it presented.
384    fn keep_image(&self, slot: Option<u32>) {
385        let Some(slot) = slot else {
386            return;
387        };
388        if let Some(present) = self.presentation.lock().as_mut() {
389            present.images.keep(slot, true);
390        }
391    }
392
393    pub fn present(&self) -> Result<Status, SurfaceError> {
394        profiling::scope!("Surface::present");
395
396        let presentation = self.presentation.lock();
397        let present = match presentation.as_ref() {
398            Some(present) => present,
399            None => return Err(SurfaceError::NotConfigured),
400        };
401
402        present.device.check_is_valid()?;
403        let queue = present
404            .device
405            .get_queue()
406            .ok_or(SurfaceError::Device(DeviceError::Lost))?;
407        drop(presentation);
408
409        queue.present(self)
410    }
411}
412
413impl Queue {
414    pub fn present(&self, surface: &Surface) -> Result<Status, SurfaceError> {
415        profiling::scope!("Queue::present");
416
417        let (texture, image) = {
418            let mut presentation = surface.presentation.lock();
419            let present = match presentation.as_mut() {
420                Some(present) => present,
421                None => return Err(SurfaceError::NotConfigured),
422            };
423
424            let device = &self.device;
425
426            // Check the surface is configured for this device.
427            if !Arc::ptr_eq(&present.device, device) {
428                return Err(SurfaceError::Device(DeviceError::DeviceMismatch(Box::new(
429                    crate::device::DeviceMismatch {
430                        res: self.error_ident(),
431                        res_device: device.error_ident(),
432                        target: None,
433                        target_device: present.device.error_ident(),
434                    },
435                ))));
436            }
437
438            let texture = present
439                .acquired_texture
440                .take()
441                .ok_or(SurfaceError::NothingToPresent)?;
442            // Kept again only once it presented.
443            let image = present.acquired_image;
444            forget_acquired_image(&mut present.acquired_image, &mut present.images);
445            (texture, image)
446        };
447
448        // If the texture was never rendered to, clear it and transition to
449        // PRESENT state before presenting.
450        // Fixes <https://github.com/gfx-rs/wgpu/issues/6748>
451        self.prepare_surface_texture_for_present(&texture)?;
452
453        let device = &self.device;
454
455        let mut exclusive_snatch_guard = device.snatchable_lock.write();
456        let inner = texture
457            .inner
458            .snatch(&mut exclusive_snatch_guard)
459            .maybe_valid();
460        drop(exclusive_snatch_guard);
461
462        let result = match inner {
463            None => return Err(SurfaceError::TextureDestroyed),
464            Some(resource::TextureInner::Surface { raw }) => {
465                let raw_surface = surface.raw(device.backend()).unwrap();
466                let raw_queue = self.raw();
467                // [`wgpu_hal::Queue::present`] requires the queue to be synchronized with submit calls and
468                // other present calls. Locking command indices prevents submits which must increment the
469                // submission index, and by `write`ing prevents other present calls.
470                let _command_indices = device.command_indices.write();
471                unsafe { raw_queue.present(raw_surface, raw) }
472            }
473            _ => unreachable!(),
474        };
475        if result.is_ok() {
476            surface.keep_image(image);
477        }
478
479        match result {
480            Ok(()) => Ok(Status::Good),
481            Err(err) => match err {
482                hal::SurfaceError::Timeout => Ok(Status::Timeout),
483                hal::SurfaceError::Occluded => Ok(Status::Occluded),
484                hal::SurfaceError::Lost => Ok(Status::Lost),
485                hal::SurfaceError::Device(err) => {
486                    Err(SurfaceError::from(device.handle_hal_error(err)))
487                }
488                hal::SurfaceError::Outdated => Ok(Status::Outdated),
489                hal::SurfaceError::Other(msg) => {
490                    log::error!("present error: {msg}");
491                    Err(SurfaceError::Invalid)
492                }
493            },
494        }
495    }
496}
497
498impl Surface {
499    pub fn discard(&self) -> Result<(), SurfaceError> {
500        profiling::scope!("Surface::discard");
501
502        let mut presentation = self.presentation.lock();
503        let present = match presentation.as_mut() {
504            Some(present) => present,
505            None => return Err(SurfaceError::NotConfigured),
506        };
507
508        let device = &present.device;
509
510        device.check_is_valid()?;
511
512        let texture = present
513            .acquired_texture
514            .take()
515            .ok_or(SurfaceError::NothingToPresent)?;
516        forget_acquired_image(&mut present.acquired_image, &mut present.images);
517
518        let mut exclusive_snatch_guard = device.snatchable_lock.write();
519        let inner = texture
520            .inner
521            .snatch(&mut exclusive_snatch_guard)
522            .maybe_valid();
523        drop(exclusive_snatch_guard);
524
525        match inner {
526            None => return Err(SurfaceError::TextureDestroyed),
527            Some(resource::TextureInner::Surface { raw }) => {
528                let raw_surface = self.raw(device.backend()).unwrap();
529                unsafe { raw_surface.discard_texture(raw) };
530            }
531            _ => unreachable!(),
532        }
533
534        Ok(())
535    }
536
537    /// Like `discard`, drops the inner texture reference, but skips the
538    /// HAL `discard_texture` call. Safe to call during unwinding
539    pub fn release(&self) -> Result<(), SurfaceError> {
540        profiling::scope!("Surface::release");
541
542        let mut presentation = self.presentation.lock();
543        let Some(present) = presentation.as_mut() else {
544            return Err(SurfaceError::NotConfigured);
545        };
546
547        // `texture` is dropped here, decrementing the refcount of
548        // Arc<SwapchainAcquireSemaphore>. If this was the last Arc, the Texture
549        // is freed, which drops NativeSurfaceTextureMetadata and
550        // its Arc<SwapchainAcquireSemaphore>.
551        _ = present
552            .acquired_texture
553            .take()
554            .ok_or(SurfaceError::NothingToPresent)?;
555        forget_acquired_image(&mut present.acquired_image, &mut present.images);
556
557        Ok(())
558    }
559}
560
561impl Global {
562    pub fn surface_get_current_texture(
563        &self,
564        surface_id: id::SurfaceId,
565        texture_id_in: Option<id::TextureId>,
566    ) -> Result<SurfaceOutput, SurfaceError> {
567        let surface = self.surfaces.get(surface_id);
568
569        let fid = self.hub.textures.prepare(texture_id_in);
570
571        let output = surface.get_current_texture()?;
572
573        #[cfg(feature = "trace")]
574        if let Some(present) = surface.presentation.lock().as_ref() {
575            if let Some(ref mut trace) = *present.device.trace.lock() {
576                if let Some(texture) = present.acquired_texture.as_ref() {
577                    trace.add(Action::GetSurfaceTexture {
578                        id: texture.to_trace(),
579                        parent: surface.to_trace(),
580                    });
581                }
582            }
583        }
584
585        let status = output.status;
586        let texture_id = output.texture.map(|texture| fid.assign(texture));
587
588        Ok(SurfaceOutput {
589            status,
590            texture: texture_id,
591            image: output.image,
592        })
593    }
594
595    /// Asks the surface to hand each presented swapchain image back as it
596    /// presented it, where the backend numbers images: an acquired image
597    /// presented since the surface was configured is then initialized and
598    /// holds its pixels, so a pass may load it and draw only what changed
599    /// (Cranpose fork). The platform must keep presented images' contents,
600    /// which Vulkan does not promise.
601    pub fn surface_keep_presented_images(&self, surface_id: id::SurfaceId, keep: bool) {
602        self.surfaces
603            .get(surface_id)
604            .keep_images
605            .store(keep, Ordering::Release);
606    }
607
608    pub fn surface_present(&self, surface_id: id::SurfaceId) -> Result<Status, SurfaceError> {
609        let surface = self.surfaces.get(surface_id);
610
611        #[cfg(feature = "trace")]
612        if let Some(present) = surface.presentation.lock().as_ref() {
613            if let Some(ref mut trace) = *present.device.trace.lock() {
614                trace.add(Action::Present(surface.to_trace()));
615            }
616        }
617
618        surface.present()
619    }
620
621    pub fn surface_texture_discard(&self, surface_id: id::SurfaceId) -> Result<(), SurfaceError> {
622        let surface = self.surfaces.get(surface_id);
623
624        #[cfg(feature = "trace")]
625        if let Some(present) = surface.presentation.lock().as_ref() {
626            if let Some(ref mut trace) = *present.device.trace.lock() {
627                trace.add(Action::DiscardSurfaceTexture(surface.to_trace()));
628            }
629        }
630
631        surface.discard()
632    }
633
634    pub fn surface_texture_release(&self, surface_id: id::SurfaceId) -> Result<(), SurfaceError> {
635        let surface = self.surfaces.get(surface_id);
636
637        #[cfg(feature = "trace")]
638        if let Some(present) = surface.presentation.lock().as_ref() {
639            if let Some(ref mut trace) = *present.device.trace.lock() {
640                trace.add(Action::ReleaseSurfaceTexture(surface.to_trace()));
641            }
642        }
643
644        surface.release()
645    }
646}