Skip to main content

oxide_renderer/
surface.rs

1//! Surface configuration and management
2
3use wgpu::{
4    PresentMode, Surface, SurfaceConfiguration, SurfaceError, SurfaceTexture, TextureFormat,
5    TextureUsages,
6};
7
8pub struct SurfaceState {
9    surface: Surface<'static>,
10    config: SurfaceConfiguration,
11}
12
13impl SurfaceState {
14    pub fn new(
15        surface: Surface<'static>,
16        adapter: &wgpu::Adapter,
17        device: &wgpu::Device,
18        width: u32,
19        height: u32,
20    ) -> Self {
21        let caps = surface.get_capabilities(adapter);
22        let format = caps
23            .formats
24            .iter()
25            .copied()
26            .find(|f| matches!(f, TextureFormat::Rgba8Unorm | TextureFormat::Bgra8Unorm))
27            .unwrap_or(caps.formats[0]);
28
29        let present_mode = caps
30            .present_modes
31            .iter()
32            .copied()
33            .find(|m| *m == PresentMode::Mailbox)
34            .unwrap_or(PresentMode::Fifo);
35
36        let config = SurfaceConfiguration {
37            usage: TextureUsages::RENDER_ATTACHMENT,
38            format,
39            width,
40            height,
41            present_mode,
42            desired_maximum_frame_latency: 2,
43            alpha_mode: caps.alpha_modes[0],
44            view_formats: vec![],
45        };
46
47        surface.configure(device, &config);
48
49        Self { surface, config }
50    }
51
52    pub fn resize(&mut self, device: &wgpu::Device, width: u32, height: u32) {
53        if width > 0 && height > 0 {
54            self.config.width = width;
55            self.config.height = height;
56            self.surface.configure(device, &self.config);
57        }
58    }
59
60    pub fn format(&self) -> TextureFormat {
61        self.config.format
62    }
63
64    pub fn width(&self) -> u32 {
65        self.config.width
66    }
67
68    pub fn height(&self) -> u32 {
69        self.config.height
70    }
71
72    pub fn acquire(&self) -> Result<SurfaceTexture, SurfaceError> {
73        self.surface.get_current_texture()
74    }
75}