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
use crate::{
    DynDevice, DynFence, DynResource, DynSurfaceTexture, Surface, SurfaceConfiguration,
    SurfaceError,
};

use super::DynResourceExt as _;

#[derive(Debug)]
pub struct DynAcquiredSurfaceTexture {
    pub texture: Box<dyn DynSurfaceTexture>,
    /// The presentation configuration no longer matches
    /// the surface properties exactly, but can still be used to present
    /// to the surface successfully.
    pub suboptimal: bool,
}

pub trait DynSurface: DynResource {
    unsafe fn configure(
        &self,
        device: &dyn DynDevice,
        config: &SurfaceConfiguration,
    ) -> Result<(), SurfaceError>;

    unsafe fn unconfigure(&self, device: &dyn DynDevice);

    unsafe fn acquire_texture(
        &self,
        timeout: Option<std::time::Duration>,
        fence: &dyn DynFence,
    ) -> Result<Option<DynAcquiredSurfaceTexture>, SurfaceError>;

    unsafe fn discard_texture(&self, texture: Box<dyn DynSurfaceTexture>);
}

impl<S: Surface + DynResource> DynSurface for S {
    unsafe fn configure(
        &self,
        device: &dyn DynDevice,
        config: &SurfaceConfiguration,
    ) -> Result<(), SurfaceError> {
        let device = device.expect_downcast_ref();
        unsafe { S::configure(self, device, config) }
    }

    unsafe fn unconfigure(&self, device: &dyn DynDevice) {
        let device = device.expect_downcast_ref();
        unsafe { S::unconfigure(self, device) }
    }

    unsafe fn acquire_texture(
        &self,
        timeout: Option<std::time::Duration>,
        fence: &dyn DynFence,
    ) -> Result<Option<DynAcquiredSurfaceTexture>, SurfaceError> {
        let fence = fence.expect_downcast_ref();
        unsafe { S::acquire_texture(self, timeout, fence) }.map(|acquired| {
            acquired.map(|ast| {
                let texture = Box::new(ast.texture);
                let suboptimal = ast.suboptimal;
                DynAcquiredSurfaceTexture {
                    texture,
                    suboptimal,
                }
            })
        })
    }

    unsafe fn discard_texture(&self, texture: Box<dyn DynSurfaceTexture>) {
        unsafe { S::discard_texture(self, texture.unbox()) }
    }
}