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
use crate::game_service::GameService;
use crate::key_event::KeyEvent;

use std::cell::RefCell;
use std::rc::Rc;

use wasm_bindgen::{prelude::*, JsCast};

/// This function starts a game loop.
pub fn run<T: 'static>(game_service: T, context: web_sys::CanvasRenderingContext2d)
where
    T: GameService,
{
    let game_service_rc = Rc::new(game_service);
    let context_rc = Rc::new(context);

    let key_event_rc = Rc::new(RefCell::new(KeyEvent::new()));
    KeyEvent::run(key_event_rc.clone());

    let callback_rc = Rc::new(RefCell::new(None));
    let callback = callback_rc.clone();
    *callback.borrow_mut() = Some(Closure::wrap(Box::new(move || {
        let game_service = game_service_rc.clone();
        let key_event = key_event_rc.borrow();
        let context = context_rc.clone();
        game_service.key_event(&key_event);
        game_service.update();
        game_service.draw(&context);
        request_animation_frame(
            callback_rc
                .borrow()
                .as_ref()
                .expect("No Closure in this callback."),
        );
    }) as Box<dyn FnMut()>));
    request_animation_frame(
        callback
            .borrow()
            .as_ref()
            .expect("No Closure in this callback."),
    );
}

fn request_animation_frame(f: &Closure<dyn FnMut()>) {
    web_sys::window()
        .expect("No global window.")
        .request_animation_frame(f.as_ref().unchecked_ref())
        .expect("Failed to call requestAnimationFrame.");
}