1use 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 pub(crate) acquired_image: Option<u32>,
42 pub(crate) images: PresentedImages,
44}
45
46#[derive(Clone, Copy, Debug, PartialEq, Eq)]
48pub struct SurfaceImage {
49 pub index: u32,
52 pub kept: bool,
56}
57
58const IMAGE_SLOTS: usize = 8;
61
62#[derive(Debug, Default)]
66pub(crate) struct PresentedImages {
67 ids: [Option<u64>; IMAGE_SLOTS],
69 kept: u8,
71 next: usize,
73}
74
75impl PresentedImages {
76 fn acquire(&mut self, id: u64) -> (u32, bool) {
79 let slot = match self.ids.iter().position(|known| *known == Some(id)) {
80 Some(slot) => slot,
81 None => {
82 let slot = self
83 .ids
84 .iter()
85 .position(Option::is_none)
86 .unwrap_or(self.next);
87 self.next = (slot + 1) % IMAGE_SLOTS;
88 self.ids[slot] = Some(id);
89 self.kept &= !(1 << slot);
90 slot
91 }
92 };
93 (slot as u32, self.kept & (1 << slot) != 0)
94 }
95
96 fn keep(&mut self, slot: u32, kept: bool) {
98 let bit = 1u8 << slot;
99 if kept {
100 self.kept |= bit;
101 } else {
102 self.kept &= !bit;
103 }
104 }
105}
106
107fn forget_acquired_image(acquired_image: &mut Option<u32>, images: &mut PresentedImages) {
110 if let Some(slot) = acquired_image.take() {
111 images.keep(slot, false);
112 }
113}
114
115#[derive(Clone, Debug, Error)]
116#[non_exhaustive]
117pub enum SurfaceError {
118 #[error("Surface is invalid")]
119 Invalid,
120 #[error("Surface is not configured for presentation")]
121 NotConfigured,
122 #[error(transparent)]
123 Device(#[from] DeviceError),
124 #[error("Surface image is already acquired")]
125 AlreadyAcquired,
126 #[error("No surface image is currently acquired to present")]
127 NothingToPresent,
128 #[error("Texture has been destroyed")]
129 TextureDestroyed,
130}
131
132impl WebGpuError for SurfaceError {
133 fn webgpu_error_type(&self) -> ErrorType {
134 match self {
135 Self::Device(e) => e.webgpu_error_type(),
136 Self::Invalid
137 | Self::NotConfigured
138 | Self::AlreadyAcquired
139 | Self::NothingToPresent
140 | Self::TextureDestroyed => ErrorType::Validation,
141 }
142 }
143}
144
145#[derive(Clone, Debug, Error)]
146#[non_exhaustive]
147pub enum ConfigureSurfaceError {
148 #[error(transparent)]
149 Device(#[from] DeviceError),
150 #[error("Invalid surface")]
151 InvalidSurface,
152 #[error("The view format {0:?} is not compatible with texture format {1:?}, only changing srgb-ness is allowed.")]
153 InvalidViewFormat(wgt::TextureFormat, wgt::TextureFormat),
154 #[error(transparent)]
155 MissingDownlevelFlags(#[from] MissingDownlevelFlags),
156 #[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`.")]
157 PreviousOutputExists,
158 #[error("Failed to wait for GPU to come idle before reconfiguring the Surface")]
159 GpuWaitTimeout,
160 #[error("Both `Surface` width and height must be non-zero. Wait to recreate the `Surface` until the window has non-zero area.")]
161 ZeroArea,
162 #[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}.")]
163 TooLarge {
164 width: u32,
165 height: u32,
166 max_texture_dimension_2d: u32,
167 },
168 #[error("Surface does not support the adapter's queue family")]
169 UnsupportedQueueFamily,
170 #[error("Requested format {requested:?} is not in list of supported formats: {available:?}")]
171 UnsupportedFormat {
172 requested: wgt::TextureFormat,
173 available: Vec<wgt::TextureFormat>,
174 },
175 #[error("Requested color space {requested:?} is not in the list of color spaces supported for format {format:?}: {available:?}")]
176 UnsupportedColorSpace {
177 requested: wgt::SurfaceColorSpace,
178 format: wgt::TextureFormat,
179 available: wgt::SurfaceColorSpaces,
180 },
181 #[error("Requested present mode {requested:?} is not in the list of supported present modes: {available:?}")]
182 UnsupportedPresentMode {
183 requested: wgt::PresentMode,
184 available: Vec<wgt::PresentMode>,
185 },
186 #[error("Requested alpha mode {requested:?} is not in the list of supported alpha modes: {available:?}")]
187 UnsupportedAlphaMode {
188 requested: wgt::CompositeAlphaMode,
189 available: Vec<wgt::CompositeAlphaMode>,
190 },
191 #[error("Requested usage {requested:?} is not in the list of supported usages: {available:?}")]
192 UnsupportedUsage {
193 requested: wgt::TextureUses,
194 available: wgt::TextureUses,
195 },
196}
197
198impl From<WaitIdleError> for ConfigureSurfaceError {
199 fn from(e: WaitIdleError) -> Self {
200 match e {
201 WaitIdleError::Device(d) => ConfigureSurfaceError::Device(d),
202 WaitIdleError::WrongSubmissionIndex(..) => unreachable!(),
203 WaitIdleError::Timeout => ConfigureSurfaceError::GpuWaitTimeout,
204 }
205 }
206}
207
208impl WebGpuError for ConfigureSurfaceError {
209 fn webgpu_error_type(&self) -> ErrorType {
210 match self {
211 Self::Device(e) => e.webgpu_error_type(),
212 Self::MissingDownlevelFlags(e) => e.webgpu_error_type(),
213 Self::InvalidSurface
214 | Self::InvalidViewFormat(..)
215 | Self::PreviousOutputExists
216 | Self::GpuWaitTimeout
217 | Self::ZeroArea
218 | Self::TooLarge { .. }
219 | Self::UnsupportedQueueFamily
220 | Self::UnsupportedFormat { .. }
221 | Self::UnsupportedColorSpace { .. }
222 | Self::UnsupportedPresentMode { .. }
223 | Self::UnsupportedAlphaMode { .. }
224 | Self::UnsupportedUsage { .. } => ErrorType::Validation,
225 }
226 }
227}
228
229pub type ResolvedSurfaceOutput = SurfaceOutput<Arc<resource::Texture>>;
230
231#[repr(C)]
232#[derive(Debug)]
233pub struct SurfaceOutput<T = id::TextureId> {
234 pub status: Status,
235 pub texture: Option<T>,
236 pub image: Option<SurfaceImage>,
238}
239
240impl Surface {
241 pub fn get_current_texture(&self) -> Result<ResolvedSurfaceOutput, SurfaceError> {
242 profiling::scope!("Surface::get_current_texture");
243
244 let (device, config) = if let Some(ref present) = *self.presentation.lock() {
245 present.device.check_is_valid()?;
246 (present.device.clone(), present.config.clone())
247 } else {
248 return Err(SurfaceError::NotConfigured);
249 };
250
251 let suf = self.raw(device.backend()).unwrap();
252 let mut image = None;
253 let (texture, status) = match unsafe {
254 suf.acquire_texture(
255 Some(core::time::Duration::from_millis(FRAME_TIMEOUT_MS as u64)),
256 device.fence.as_ref(),
257 )
258 } {
259 Ok(ast) => {
260 let texture_desc = wgt::TextureDescriptor {
261 label: hal_label(
262 Some(alloc::borrow::Cow::Borrowed("<Surface Texture>")),
263 device.instance_flags,
264 ),
265 size: wgt::Extent3d {
266 width: config.width,
267 height: config.height,
268 depth_or_array_layers: 1,
269 },
270 sample_count: 1,
271 mip_level_count: 1,
272 format: config.format,
273 dimension: wgt::TextureDimension::D2,
274 usage: config.usage,
275 view_formats: config.view_formats,
276 };
277 let format_features = wgt::TextureFormatFeatures {
278 allowed_usages: wgt::TextureUsages::RENDER_ATTACHMENT,
279 flags: wgt::TextureFormatFeatureFlags::MULTISAMPLE_X4
280 | wgt::TextureFormatFeatureFlags::MULTISAMPLE_RESOLVE,
281 };
282 let hal_usage = conv::map_texture_usage(
283 config.usage,
284 config.format.into(),
285 format_features.flags,
286 );
287 let clear_view_desc = hal::TextureViewDescriptor {
288 label: hal_label(
289 Some("(wgpu internal) clear surface texture view"),
290 device.instance_flags,
291 ),
292 format: config.format,
293 dimension: wgt::TextureViewDimension::D2,
294 usage: wgt::TextureUses::COLOR_TARGET,
295 range: wgt::ImageSubresourceRange::default(),
296 };
297 let clear_view = unsafe {
298 device
299 .raw()
300 .create_texture_view(ast.texture.as_ref().borrow(), &clear_view_desc)
301 }
302 .map_err(|e| device.handle_hal_error(e))?;
303
304 let image_id = ast.texture.image_id();
305 let mut presentation = self.presentation.lock();
306 let present = presentation.as_mut().unwrap();
307 let slot = image_id.map(|id| present.images.acquire(id));
308 let kept = self.keep_images.load(Ordering::Acquire)
312 && slot.is_some_and(|(_, kept)| kept);
313 let texture = resource::Texture::new(
314 &device,
315 resource::TextureInner::Surface { raw: ast.texture },
316 hal_usage,
317 &texture_desc,
318 format_features,
319 resource::TextureClearMode::Surface {
320 clear_view: ManuallyDrop::new(clear_view),
321 },
322 !kept,
323 );
324
325 let texture = Arc::new(texture);
326
327 device.trackers.lock().textures.insert_single(
328 &texture,
329 if kept {
330 wgt::TextureUses::PRESENT
331 } else {
332 wgt::TextureUses::UNINITIALIZED
333 },
334 );
335
336 if present.acquired_texture.is_some() {
337 return Err(SurfaceError::AlreadyAcquired);
338 }
339 present.acquired_texture = Some(texture.clone());
340 present.acquired_image = slot.map(|(index, _)| index);
341 image = slot.map(|(index, _)| SurfaceImage { index, kept });
342
343 let status = if ast.suboptimal {
344 Status::Suboptimal
345 } else {
346 Status::Good
347 };
348 (Some(texture), status)
349 }
350 Err(err) => (
351 None,
352 match err {
353 hal::SurfaceError::Timeout => Status::Timeout,
354 hal::SurfaceError::Occluded => Status::Occluded,
355 hal::SurfaceError::Lost => Status::Lost,
356 hal::SurfaceError::Device(err) => {
357 return Err(device.handle_hal_error(err).into());
358 }
359 hal::SurfaceError::Outdated => Status::Outdated,
360 hal::SurfaceError::Other(msg) => {
361 log::error!("acquire error: {msg}");
362 Status::Lost
363 }
364 },
365 ),
366 };
367
368 Ok(ResolvedSurfaceOutput {
369 status,
370 texture,
371 image,
372 })
373 }
374
375 fn keep_image(&self, slot: Option<u32>) {
377 let Some(slot) = slot else {
378 return;
379 };
380 if let Some(present) = self.presentation.lock().as_mut() {
381 present.images.keep(slot, true);
382 }
383 }
384
385 pub fn present(&self) -> Result<Status, SurfaceError> {
386 profiling::scope!("Surface::present");
387
388 let presentation = self.presentation.lock();
389 let present = match presentation.as_ref() {
390 Some(present) => present,
391 None => return Err(SurfaceError::NotConfigured),
392 };
393
394 present.device.check_is_valid()?;
395 let queue = present
396 .device
397 .get_queue()
398 .ok_or(SurfaceError::Device(DeviceError::Lost))?;
399 drop(presentation);
400
401 queue.present(self)
402 }
403}
404
405impl Queue {
406 pub fn present(&self, surface: &Surface) -> Result<Status, SurfaceError> {
407 profiling::scope!("Queue::present");
408
409 let (texture, image) = {
410 let mut presentation = surface.presentation.lock();
411 let present = match presentation.as_mut() {
412 Some(present) => present,
413 None => return Err(SurfaceError::NotConfigured),
414 };
415
416 let device = &self.device;
417
418 if !Arc::ptr_eq(&present.device, device) {
420 return Err(SurfaceError::Device(DeviceError::DeviceMismatch(Box::new(
421 crate::device::DeviceMismatch {
422 res: self.error_ident(),
423 res_device: device.error_ident(),
424 target: None,
425 target_device: present.device.error_ident(),
426 },
427 ))));
428 }
429
430 let texture = present
431 .acquired_texture
432 .take()
433 .ok_or(SurfaceError::NothingToPresent)?;
434 let image = present.acquired_image;
436 forget_acquired_image(&mut present.acquired_image, &mut present.images);
437 (texture, image)
438 };
439
440 self.prepare_surface_texture_for_present(&texture)?;
444
445 let device = &self.device;
446
447 let mut exclusive_snatch_guard = device.snatchable_lock.write();
448 let inner = texture
449 .inner
450 .snatch(&mut exclusive_snatch_guard)
451 .maybe_valid();
452 drop(exclusive_snatch_guard);
453
454 let result = match inner {
455 None => return Err(SurfaceError::TextureDestroyed),
456 Some(resource::TextureInner::Surface { raw }) => {
457 let raw_surface = surface.raw(device.backend()).unwrap();
458 let raw_queue = self.raw();
459 let _command_indices = device.command_indices.write();
463 unsafe { raw_queue.present(raw_surface, raw) }
464 }
465 _ => unreachable!(),
466 };
467 if result.is_ok() {
468 surface.keep_image(image);
469 }
470
471 match result {
472 Ok(()) => Ok(Status::Good),
473 Err(err) => match err {
474 hal::SurfaceError::Timeout => Ok(Status::Timeout),
475 hal::SurfaceError::Occluded => Ok(Status::Occluded),
476 hal::SurfaceError::Lost => Ok(Status::Lost),
477 hal::SurfaceError::Device(err) => {
478 Err(SurfaceError::from(device.handle_hal_error(err)))
479 }
480 hal::SurfaceError::Outdated => Ok(Status::Outdated),
481 hal::SurfaceError::Other(msg) => {
482 log::error!("present error: {msg}");
483 Err(SurfaceError::Invalid)
484 }
485 },
486 }
487 }
488}
489
490impl Surface {
491 pub fn discard(&self) -> Result<(), SurfaceError> {
492 profiling::scope!("Surface::discard");
493
494 let mut presentation = self.presentation.lock();
495 let present = match presentation.as_mut() {
496 Some(present) => present,
497 None => return Err(SurfaceError::NotConfigured),
498 };
499
500 let device = &present.device;
501
502 device.check_is_valid()?;
503
504 let texture = present
505 .acquired_texture
506 .take()
507 .ok_or(SurfaceError::NothingToPresent)?;
508 forget_acquired_image(&mut present.acquired_image, &mut present.images);
509
510 let mut exclusive_snatch_guard = device.snatchable_lock.write();
511 let inner = texture
512 .inner
513 .snatch(&mut exclusive_snatch_guard)
514 .maybe_valid();
515 drop(exclusive_snatch_guard);
516
517 match inner {
518 None => return Err(SurfaceError::TextureDestroyed),
519 Some(resource::TextureInner::Surface { raw }) => {
520 let raw_surface = self.raw(device.backend()).unwrap();
521 unsafe { raw_surface.discard_texture(raw) };
522 }
523 _ => unreachable!(),
524 }
525
526 Ok(())
527 }
528
529 pub fn release(&self) -> Result<(), SurfaceError> {
532 profiling::scope!("Surface::release");
533
534 let mut presentation = self.presentation.lock();
535 let Some(present) = presentation.as_mut() else {
536 return Err(SurfaceError::NotConfigured);
537 };
538
539 _ = present
544 .acquired_texture
545 .take()
546 .ok_or(SurfaceError::NothingToPresent)?;
547 forget_acquired_image(&mut present.acquired_image, &mut present.images);
548
549 Ok(())
550 }
551}
552
553impl Global {
554 pub fn surface_get_current_texture(
555 &self,
556 surface_id: id::SurfaceId,
557 texture_id_in: Option<id::TextureId>,
558 ) -> Result<SurfaceOutput, SurfaceError> {
559 let surface = self.surfaces.get(surface_id);
560
561 let fid = self.hub.textures.prepare(texture_id_in);
562
563 let output = surface.get_current_texture()?;
564
565 #[cfg(feature = "trace")]
566 if let Some(present) = surface.presentation.lock().as_ref() {
567 if let Some(ref mut trace) = *present.device.trace.lock() {
568 if let Some(texture) = present.acquired_texture.as_ref() {
569 trace.add(Action::GetSurfaceTexture {
570 id: texture.to_trace(),
571 parent: surface.to_trace(),
572 });
573 }
574 }
575 }
576
577 let status = output.status;
578 let texture_id = output.texture.map(|texture| fid.assign(texture));
579
580 Ok(SurfaceOutput {
581 status,
582 texture: texture_id,
583 image: output.image,
584 })
585 }
586
587 pub fn surface_keep_presented_images(&self, surface_id: id::SurfaceId, keep: bool) {
594 self.surfaces
595 .get(surface_id)
596 .keep_images
597 .store(keep, Ordering::Release);
598 }
599
600 pub fn surface_present(&self, surface_id: id::SurfaceId) -> Result<Status, SurfaceError> {
601 let surface = self.surfaces.get(surface_id);
602
603 #[cfg(feature = "trace")]
604 if let Some(present) = surface.presentation.lock().as_ref() {
605 if let Some(ref mut trace) = *present.device.trace.lock() {
606 trace.add(Action::Present(surface.to_trace()));
607 }
608 }
609
610 surface.present()
611 }
612
613 pub fn surface_texture_discard(&self, surface_id: id::SurfaceId) -> Result<(), SurfaceError> {
614 let surface = self.surfaces.get(surface_id);
615
616 #[cfg(feature = "trace")]
617 if let Some(present) = surface.presentation.lock().as_ref() {
618 if let Some(ref mut trace) = *present.device.trace.lock() {
619 trace.add(Action::DiscardSurfaceTexture(surface.to_trace()));
620 }
621 }
622
623 surface.discard()
624 }
625
626 pub fn surface_texture_release(&self, surface_id: id::SurfaceId) -> Result<(), SurfaceError> {
627 let surface = self.surfaces.get(surface_id);
628
629 #[cfg(feature = "trace")]
630 if let Some(present) = surface.presentation.lock().as_ref() {
631 if let Some(ref mut trace) = *present.device.trace.lock() {
632 trace.add(Action::ReleaseSurfaceTexture(surface.to_trace()));
633 }
634 }
635
636 surface.release()
637 }
638}