lf_gfx/
game.rs

1//! A 'Game' in this context is a program that uses both wgpu and winit.
2pub(crate) mod input;
3mod surface;
4pub(crate) mod window;
5
6use std::sync::{atomic::AtomicBool, Arc};
7
8use log::info;
9use winit::{
10    dpi::PhysicalPosition,
11    event::{DeviceEvent, Event, WindowEvent},
12    event_loop::{ActiveEventLoop, EventLoop},
13    keyboard::PhysicalKey,
14    window::Window,
15};
16
17use crate::{game::window::GameWindow, LfLimitsExt};
18
19use self::input::{InputMap, MouseInputType, VectorInputActivation, VectorInputType};
20
21/// A cloneable and distributable flag that can be cheaply queried to see if the game has exited.
22///
23/// The idea is to clone this into in every thread you spawn so that they can gracefully exit when the game does.
24#[derive(Clone)]
25pub struct ExitFlag {
26    inner: Arc<AtomicBool>,
27}
28
29impl ExitFlag {
30    fn new() -> Self {
31        Self {
32            inner: Arc::new(AtomicBool::new(false)),
33        }
34    }
35
36    pub fn get(&self) -> bool {
37        self.inner.load(std::sync::atomic::Ordering::SeqCst)
38    }
39
40    fn set(&self) {
41        self.inner.store(true, std::sync::atomic::Ordering::SeqCst)
42    }
43}
44
45#[derive(Debug, Clone, Copy)]
46pub enum InputMode {
47    /// Indicates that any keyboard, mouse or gamepad input should be captured by the input management system,
48    /// no raw input events should be passed to the game implementation, and the cursor should be hidden.
49    Exclusive,
50    /// Indicates that any keyboard, mouse or gamepad input should not be captured by the input management system,
51    /// all raw input events should be passed to the game implementation, and the cursor should be shown.
52    UI,
53    /// Indicates that keyboard, mouse or gamepad input should be captured both by the input management system,
54    /// and raw input events should be passed to the game implementation, and the cursor should be shown.
55    Unified,
56}
57impl InputMode {
58    fn should_hide_cursor(self) -> bool {
59        match self {
60            InputMode::Exclusive => true,
61            InputMode::UI => false,
62            InputMode::Unified => false,
63        }
64    }
65    fn should_handle_input(self) -> bool {
66        match self {
67            InputMode::Exclusive => true,
68            InputMode::UI => false,
69            InputMode::Unified => true,
70        }
71    }
72    fn should_propogate_raw_input(self) -> bool {
73        match self {
74            InputMode::Exclusive => false,
75            InputMode::UI => true,
76            InputMode::Unified => true,
77        }
78    }
79    fn should_lock_cursor(self) -> bool {
80        match self {
81            InputMode::Exclusive => true,
82            InputMode::UI => false,
83            InputMode::Unified => false,
84        }
85    }
86}
87
88/// A command sent to the game to change the game state
89pub enum GameCommand {
90    Exit,
91    SetInputMode(InputMode),
92    SetMouseSensitivity(f32),
93}
94
95pub struct GameData {
96    pub command_sender: flume::Sender<GameCommand>,
97    pub surface_format: wgpu::TextureFormat,
98    pub limits: wgpu::Limits,
99    pub size: winit::dpi::PhysicalSize<u32>,
100    pub window: GameWindow,
101    pub device: wgpu::Device,
102    pub queue: wgpu::Queue,
103    pub exit_flag: ExitFlag,
104}
105
106/// All of the callbacks required to implement a game. This API is built on top of a message passing
107/// event system, and so calls to the below methods may be made concurrently, in any order, and on
108/// different threads.
109pub trait Game: Sized {
110    /// Data processed before the window exists. This should be minimal and kept to `mpsc` message reception from initialiser threads.
111    type InitData;
112
113    type LinearInputType;
114    type VectorInputType;
115
116    fn title() -> impl Into<String>;
117
118    fn target_limits() -> wgpu::Limits {
119        wgpu::Limits::downlevel_webgl2_defaults()
120    }
121    fn default_inputs(&self) -> InputMap<Self::LinearInputType, Self::VectorInputType>;
122
123    fn init(data: &GameData, init: Self::InitData) -> anyhow::Result<Self>;
124
125    /// Allows you to intercept and cancel events, before passing them off to the standard event handler,
126    /// to allow for egui integration, among others.
127    ///
128    /// This method only receives input events if the cursor is not captured, to avoid UI glitches.
129    fn process_raw_event<'a, T>(&mut self, _: &GameData, event: Event<T>) -> Option<Event<T>> {
130        Some(event)
131    }
132
133    fn window_resize(&mut self, data: &GameData, new_size: winit::dpi::PhysicalSize<u32>);
134
135    fn handle_linear_input(
136        &mut self,
137        data: &GameData,
138        input: &Self::LinearInputType,
139        activation: input::LinearInputActivation,
140    );
141
142    fn handle_vector_input(
143        &mut self,
144        data: &GameData,
145        input: &Self::VectorInputType,
146        activation: input::VectorInputActivation,
147    );
148
149    /// Requests that the next frame is drawn into the view, pretty please :)
150    fn render_to(&mut self, data: &GameData, view: wgpu::TextureView);
151
152    /// Invoked when the window is told to close (i.e. x pressed, sigint, etc.) but not when
153    /// a synthetic exit is triggered by enqueuing `GameCommand::Exit`. To actually do something with the
154    /// user's request to quit, this method must enqueue `GameCommand::Exit`
155    fn user_exit_requested(&mut self, data: &GameData) {
156        let _ = data.command_sender.send(GameCommand::Exit);
157    }
158
159    /// Invoked right at the end of the program life, after the final frame is rendered.
160    fn finished(self, _: GameData) {}
161}
162
163/// All the data held by a program/game while running. `T` gives the top-level state for the game
164/// implementation
165pub(crate) struct GameState<T: Game> {
166    data: GameData,
167    game: T,
168    input_map: input::InputMap<T::LinearInputType, T::VectorInputType>,
169    command_receiver: flume::Receiver<GameCommand>,
170
171    surface: surface::ResizableSurface<'static>,
172
173    // While true, disallows cursor movement
174    input_mode: InputMode,
175    // The last position we saw the cursor at
176    last_cursor_position: PhysicalPosition<f64>,
177    // A multiplier, from pixels moved to intensity, clamped at 1.0
178    mouse_sensitivity: f32,
179}
180
181impl<T: Game + 'static> GameState<T> {
182    // Creating some of the wgpu types requires async code
183    async fn new(init: T::InitData, window: GameWindow) -> anyhow::Result<Self> {
184        let size = (&window).inner_size();
185
186        #[cfg(debug_assertions)]
187        let flags = wgpu::InstanceFlags::DEBUG | wgpu::InstanceFlags::VALIDATION;
188        #[cfg(not(debug_assertions))]
189        let flags = wgpu::InstanceFlags::DISCARD_HAL_LABELS;
190
191        let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor {
192            backends: wgpu::Backends::from_env().unwrap_or_default(),
193            flags,
194            backend_options: wgpu::BackendOptions {
195                gl: wgpu::GlBackendOptions {
196                    gles_minor_version: wgpu::Gles3MinorVersion::Automatic,
197                },
198                dx12: wgpu::Dx12BackendOptions::from_env_or_default(),
199            },
200        });
201
202        let surface = window.create_surface(&instance)?;
203
204        let adapter = instance
205            .request_adapter(&wgpu::RequestAdapterOptions {
206                power_preference: wgpu::PowerPreference::HighPerformance,
207                force_fallback_adapter: false,
208                compatible_surface: Some(&surface),
209            })
210            .await
211            .ok_or(anyhow::Error::msg("failed to request adapter"))?;
212
213        let available_limits = if cfg!(target_arch = "wasm32") {
214            wgpu::Limits::downlevel_webgl2_defaults()
215        } else {
216            adapter.limits()
217        };
218
219        let target_limits = T::target_limits();
220        let required_limits = available_limits.intersection(&target_limits);
221
222        let mut required_features = wgpu::Features::empty();
223        // Assume integrated and virtual GPUs, and CPUs, are UMA
224        if adapter
225            .features()
226            .contains(wgpu::Features::MAPPABLE_PRIMARY_BUFFERS)
227            && matches!(
228                adapter.get_info().device_type,
229                wgpu::DeviceType::IntegratedGpu
230                    | wgpu::DeviceType::Cpu
231                    | wgpu::DeviceType::VirtualGpu
232            )
233        {
234            required_features |= wgpu::Features::MAPPABLE_PRIMARY_BUFFERS;
235        }
236        // Things that are always helpful
237        required_features |= adapter.features().intersection(
238            wgpu::Features::TIMESTAMP_QUERY | wgpu::Features::TIMESTAMP_QUERY_INSIDE_PASSES,
239        );
240
241        info!("info: {:#?}", adapter.get_info());
242        info!("limits: {:#?}", adapter.limits());
243
244        let (device, queue) = adapter
245            .request_device(
246                &wgpu::DeviceDescriptor {
247                    required_features,
248                    required_limits: required_limits.clone(),
249                    label: None,
250                    memory_hints: wgpu::MemoryHints::Performance,
251                },
252                None,
253            )
254            .await
255            .map_err(|err| anyhow::Error::msg(format!("failed to get device: {err}")))?;
256
257        // Configure surface
258        let mut surface_config = surface
259            .get_default_config(&adapter, size.width, size.height)
260            .ok_or(anyhow::Error::msg("failed to get surface configuration"))?;
261        surface_config.present_mode = wgpu::PresentMode::AutoVsync;
262        surface.configure(&device, &surface_config);
263
264        let surface_caps = surface.get_capabilities(&adapter);
265
266        let surface_format = surface_caps
267            .formats
268            .iter()
269            .copied()
270            .filter(|f| f.is_srgb())
271            .next()
272            .unwrap_or(surface_caps.formats[0]);
273
274        let config = wgpu::SurfaceConfiguration {
275            usage: wgpu::TextureUsages::RENDER_ATTACHMENT,
276            format: surface_format,
277            width: size.width,
278            height: size.height,
279            present_mode: surface_caps.present_modes[0],
280            alpha_mode: surface_caps.alpha_modes[0],
281            view_formats: vec![],
282            desired_maximum_frame_latency: 2,
283        };
284        let surface = surface::ResizableSurface::new(surface, &device, config);
285
286        let (command_sender, command_receiver) = flume::unbounded();
287
288        // Some state can be set by commands to ensure valid initial state.
289        command_sender
290            .try_send(GameCommand::SetInputMode(InputMode::Unified))
291            .expect("unbounded queue held by this thread should send immediately");
292
293        let data = GameData {
294            command_sender,
295            surface_format,
296            limits: required_limits,
297            size,
298            window,
299            device,
300            queue,
301            exit_flag: ExitFlag::new(),
302        };
303        let game = T::init(&data, init)?;
304
305        // Gather inputs as a combination of registered user preferences and defaults.
306        let input_map = game.default_inputs();
307
308        Ok(Self {
309            data,
310            game,
311            surface,
312            command_receiver,
313            input_map,
314            input_mode: InputMode::Unified,
315            last_cursor_position: PhysicalPosition { x: 0.0, y: 0.0 },
316            mouse_sensitivity: 0.01,
317        })
318    }
319
320    pub(crate) fn run(init: T::InitData) {
321        let event_loop = EventLoop::new().expect("could not create game loop");
322
323        // Built on first `Event::Resumed`
324        // Taken out on `Event::LoopDestroyed`
325        let mut state: Option<Self> = None;
326        let (state_transmission, state_reception) = flume::bounded(1);
327        let mut init = Some((init, state_transmission));
328
329        event_loop
330            .run(move |event, window_target| {
331                if event == Event::LoopExiting {
332                    state.take().expect("loop is destroyed once").finished();
333                    return;
334                }
335
336                // Resume always emmitted to begin with - use it to begin an async method to create the game state.
337                if state.is_none() && event == Event::Resumed {
338                    if let Some((init, state_transmission)) = init.take() {
339                        async fn build_state<T: Game + 'static>(
340                            init: T::InitData,
341                            window: GameWindow,
342                            state_transmission: flume::Sender<GameState<T>>,
343                        ) {
344                            let state = GameState::<T>::new(init, window).await;
345                            let state = match state {
346                                Ok(state) => state,
347                                Err(err) => {
348                                    crate::alert_dialogue(&format!(
349                                        "Initialisation failure:\n{err}"
350                                    ));
351                                    panic!("{err}");
352                                }
353                            };
354                            state_transmission.try_send(state).unwrap();
355                        }
356
357                        let window = GameWindow::new::<T>(window_target);
358                        crate::block_on(build_state::<T>(init, window, state_transmission));
359                    }
360                }
361
362                // On any future events, check if the game state has been created and receive it.
363                let state = match state.as_mut() {
364                    None => {
365                        if let Ok(new_state) = state_reception.try_recv() {
366                            state = Some(new_state);
367                            state.as_mut().unwrap()
368                        } else {
369                            return;
370                        }
371                    }
372                    Some(state) => state,
373                };
374
375                state.receive_event(event, window_target);
376            })
377            .expect("run err");
378    }
379
380    fn is_input_event(event: &Event<()>) -> bool {
381        match event {
382            winit::event::Event::WindowEvent { event, .. } => match event {
383                WindowEvent::CursorMoved { .. }
384                | WindowEvent::CursorEntered { .. }
385                | WindowEvent::CursorLeft { .. }
386                | WindowEvent::MouseWheel { .. }
387                | WindowEvent::MouseInput { .. }
388                | WindowEvent::TouchpadPressure { .. }
389                | WindowEvent::AxisMotion { .. }
390                | WindowEvent::Touch(_)
391                | WindowEvent::KeyboardInput { .. }
392                | WindowEvent::ModifiersChanged(_)
393                | WindowEvent::Ime(_) => true,
394                _ => false,
395            },
396            winit::event::Event::DeviceEvent { event, .. } => match event {
397                DeviceEvent::MouseMotion { .. }
398                | DeviceEvent::MouseWheel { .. }
399                | DeviceEvent::Motion { .. }
400                | DeviceEvent::Button { .. }
401                | DeviceEvent::Key(_) => true,
402                _ => false,
403            },
404            _ => false,
405        }
406    }
407
408    fn receive_event(&mut self, mut event: Event<()>, window_target: &ActiveEventLoop) {
409        // Discard events that aren't for us
410        event = match event {
411            Event::WindowEvent { window_id, .. } if window_id != self.window().id() => return,
412            event => event,
413        };
414
415        // We filter all window events through the game to allow it to integrate with other libraries, such as egui.
416        // But only send keyboard and mouse input events to UI if the mouse isn't captured.
417        let should_send_input = self.input_mode.should_propogate_raw_input();
418        if should_send_input || !Self::is_input_event(&event) {
419            event = match self.game.process_raw_event(&self.data, event) {
420                None => return,
421                Some(event) => event,
422            };
423        }
424
425        self.process_event(event, window_target)
426    }
427
428    fn process_event(&mut self, event: Event<()>, window_target: &ActiveEventLoop) {
429        match event {
430            Event::WindowEvent { event, window_id } if window_id == self.window().id() => {
431                match event {
432                    WindowEvent::CloseRequested | WindowEvent::Destroyed => self.request_exit(),
433                    // (0, 0) means minimized on Windows.
434                    WindowEvent::Resized(winit::dpi::PhysicalSize {
435                        width: 0,
436                        height: 0,
437                    }) => {}
438                    WindowEvent::Resized(physical_size) => {
439                        log::debug!("Resized: {:?}", physical_size);
440                        self.resize(physical_size);
441                    }
442                    WindowEvent::ScaleFactorChanged { scale_factor, .. } => {
443                        log::debug!("Scale Factor Changed: {:?}", scale_factor);
444                        //self.resize(*new_inner_size);
445                    }
446                    WindowEvent::KeyboardInput {
447                        device_id: _device_id,
448                        event,
449                        is_synthetic,
450                    } if !is_synthetic && !event.repeat => {
451                        if let PhysicalKey::Code(key) = event.physical_key {
452                            let activation = match event.state {
453                                winit::event::ElementState::Pressed => 1.0,
454                                winit::event::ElementState::Released => 0.0,
455                            };
456                            let activation = input::LinearInputActivation::try_from(activation)
457                                .expect("from const");
458                            self.linear_input(
459                                input::LinearInputType::KnownKeyboard(key.into()),
460                                activation,
461                            );
462                        } else {
463                            eprintln!("unknown key code, scan code: {:?}", event.physical_key)
464                        }
465                    }
466                    WindowEvent::CursorMoved {
467                        device_id: _device_id,
468                        position,
469                        ..
470                    } => {
471                        let delta_x = position.x - self.last_cursor_position.x;
472                        let delta_y = position.y - self.last_cursor_position.y;
473
474                        // Only trigger a single linear event, depending on the largest movement
475                        if delta_x.abs() > 2.0 || delta_y.abs() > 2.0 {
476                            self.process_linear_mouse_movement(delta_x, delta_y);
477                        }
478
479                        // Also trigger a vector input
480                        self.vector_input(
481                            VectorInputType::MouseMove,
482                            VectorInputActivation::clamp(
483                                delta_x as f32 * self.mouse_sensitivity,
484                                delta_y as f32 * self.mouse_sensitivity,
485                            ),
486                        );
487
488                        self.last_cursor_position = position.cast();
489
490                        // Winit doesn't support cursor locking on a lot of platforms, so do it manually.
491                        let should_lock_cursor = self.input_mode.should_lock_cursor();
492                        if should_lock_cursor {
493                            let mut center = self.data.window.inner_size();
494                            center.width /= 2;
495                            center.height /= 2;
496
497                            let old_pos = position.cast::<u32>();
498                            let new_pos = PhysicalPosition::new(center.width, center.height);
499
500                            if old_pos != new_pos {
501                                // Ignore result - if it doesn't work then there's not much we can do.
502                                let _ = self.data.window.set_cursor_position(new_pos);
503                            }
504
505                            self.last_cursor_position = new_pos.cast();
506                        }
507                    }
508                    WindowEvent::RedrawRequested => {
509                        self.data.device.poll(wgpu::MaintainBase::Poll);
510
511                        self.pre_frame_update();
512
513                        // Check everything the game implementation can send to us
514                        if self.data.exit_flag.get() {
515                            window_target.exit();
516                        }
517
518                        let res = self.render();
519                        match res {
520                            Ok(_) => {}
521                            Err(wgpu::SurfaceError::Lost) => self.resize(self.data.size),
522                            Err(wgpu::SurfaceError::OutOfMemory) => {
523                                window_target.exit();
524                            }
525                            // All other errors (Outdated, Timeout) should be resolved by the next frame
526                            Err(e) => eprintln!("{:?}", e),
527                        }
528                    }
529                    _ => {}
530                }
531            }
532            Event::DeviceEvent { device_id, event } => {
533                log::debug!("device event: {device_id:?}::{event:?}");
534            }
535            Event::AboutToWait => {
536                self.window().request_redraw();
537            }
538            _ => {}
539        }
540    }
541
542    pub fn window(&self) -> &Window {
543        &self.data.window
544    }
545
546    fn resize(&mut self, new_size: winit::dpi::PhysicalSize<u32>) {
547        if new_size.width > 0 && new_size.height > 0 {
548            self.data.size = new_size;
549
550            self.surface.resize(new_size, &self.data.queue);
551
552            self.game.window_resize(&self.data, new_size)
553        }
554    }
555
556    fn process_linear_mouse_movement(&mut self, delta_x: f64, delta_y: f64) {
557        if delta_x.abs() > delta_y.abs() {
558            if delta_x > 0.0 {
559                self.linear_input(
560                    input::LinearInputType::Mouse(MouseInputType::MoveRight),
561                    input::LinearInputActivation::clamp(delta_x as f32 * self.mouse_sensitivity),
562                );
563            } else {
564                self.linear_input(
565                    input::LinearInputType::Mouse(MouseInputType::MoveLeft),
566                    input::LinearInputActivation::clamp(-delta_x as f32 * self.mouse_sensitivity),
567                );
568            }
569        } else {
570            if delta_y > 0.0 {
571                self.linear_input(
572                    input::LinearInputType::Mouse(MouseInputType::MoveUp),
573                    input::LinearInputActivation::clamp(delta_y as f32 * self.mouse_sensitivity),
574                );
575            } else {
576                self.linear_input(
577                    input::LinearInputType::Mouse(MouseInputType::MoveDown),
578                    input::LinearInputActivation::clamp(-delta_y as f32 * self.mouse_sensitivity),
579                );
580            }
581        }
582    }
583
584    fn linear_input(
585        &mut self,
586        inputted: input::LinearInputType,
587        activation: input::LinearInputActivation,
588    ) {
589        if !self.input_mode.should_handle_input() {
590            return;
591        }
592        let input_value = self.input_map.get_linear(inputted);
593        if let Some(input_value) = input_value {
594            self.game
595                .handle_linear_input(&self.data, input_value, activation)
596        }
597    }
598
599    fn vector_input(
600        &mut self,
601        inputted: input::VectorInputType,
602        activation: input::VectorInputActivation,
603    ) {
604        if !self.input_mode.should_handle_input() {
605            return;
606        }
607        let input_value = self.input_map.get_vector(inputted);
608        if let Some(input_value) = input_value {
609            self.game
610                .handle_vector_input(&self.data, input_value, activation)
611        }
612    }
613
614    fn request_exit(&mut self) {
615        self.data.exit_flag.set();
616        self.game.user_exit_requested(&self.data);
617    }
618
619    fn pre_frame_update(&mut self) {
620        // Get all the things the game wants to do before the next frame
621        while let Ok(cmd) = self.command_receiver.try_recv() {
622            match cmd {
623                GameCommand::Exit => self.data.exit_flag.set(),
624                GameCommand::SetInputMode(input_mode) => {
625                    self.input_mode = input_mode;
626
627                    let should_show_cursor = !input_mode.should_hide_cursor();
628                    self.data.window.set_cursor_visible(should_show_cursor);
629                }
630                GameCommand::SetMouseSensitivity(new_sensitivity) => {
631                    self.mouse_sensitivity = new_sensitivity;
632                }
633            }
634        }
635    }
636
637    fn render(&mut self) -> Result<(), wgpu::SurfaceError> {
638        // If we are in the process of resizing, don't do anything
639        if let Some(surface) = self.surface.get(&self.data.device) {
640            let was_suboptimal = {
641                let output = surface.get_current_texture()?;
642                let view = output
643                    .texture
644                    .create_view(&wgpu::TextureViewDescriptor::default());
645
646                self.game.render_to(&self.data, view);
647
648                let was_suboptimal = output.suboptimal;
649
650                output.present();
651
652                was_suboptimal
653            };
654
655            if was_suboptimal {
656                // Force recreation
657                return Err(wgpu::SurfaceError::Lost);
658            }
659        }
660        Ok(())
661    }
662
663    fn finished(self) {
664        self.game.finished(self.data)
665    }
666}