lf_gfx/game/
window.rs

1use std::sync::Arc;
2
3use wgpu::Device;
4use winit::{event_loop::ActiveEventLoop, window::WindowAttributes};
5
6pub struct GameWindow {
7    window: Arc<winit::window::Window>,
8
9    #[cfg(target_arch = "wasm32")]
10    canvas: web_sys::HtmlCanvasElement,
11}
12
13impl GameWindow {
14    pub(super) fn new<T: super::Game>(window_target: &ActiveEventLoop) -> Self {
15        let mut attributes = WindowAttributes::default();
16        attributes.title = T::title().into();
17
18        #[cfg(target_arch = "wasm32")]
19        let canvas = {
20            use winit::platform::web::WindowAttributesExtWebSys;
21            let canvas = crate::wasm::get_canvas();
22            attributes = attributes.with_canvas(Some(canvas.clone()));
23            canvas
24        };
25
26        let window = window_target
27            .create_window(attributes)
28            .expect("Failed to create window");
29        let window = Arc::new(window);
30
31        Self {
32            window,
33            #[cfg(target_arch = "wasm32")]
34            canvas,
35        }
36    }
37
38    #[cfg(target_arch = "wasm32")]
39    pub fn canvas(&self) -> web_sys::HtmlCanvasElement {
40        self.canvas.clone()
41    }
42
43    pub(crate) fn create_surface(
44        &self,
45        instance: &wgpu::Instance,
46    ) -> Result<wgpu::Surface<'static>, wgpu::CreateSurfaceError> {
47        instance.create_surface(Arc::clone(&self.window))
48    }
49}
50
51impl std::ops::Deref for GameWindow {
52    type Target = winit::window::Window;
53
54    fn deref(&self) -> &Self::Target {
55        &self.window
56    }
57}
58
59/// Something that needs remaking/resizing whenever the game window is resized
60pub trait WindowSizeDependent {
61    fn on_window_resize(&mut self, device: &Device, new_size: winit::dpi::PhysicalSize<u32>);
62}