Asyncify, timing experiments

This commit is contained in:
2024-04-14 19:36:55 -05:00
parent 3666baa28d
commit a564c38ec7
4 changed files with 227 additions and 58 deletions

View File

@@ -1,44 +1,42 @@
#[allow(dead_code)]
#[cfg(target_os = "emscripten")]
pub mod emscripten {
use std::cell::RefCell;
use std::os::raw::{c_float, c_int, c_void};
use std::ptr::null_mut;
#[allow(non_camel_case_types)]
type em_callback_func = unsafe extern "C" fn();
use std::os::raw::c_uint;
extern "C" {
pub fn emscripten_set_main_loop(
func: em_callback_func,
fps: c_int,
simulate_infinite_loop: c_int,
);
pub fn emscripten_cancel_main_loop();
pub fn emscripten_get_now() -> c_float;
pub fn emscripten_get_now() -> f64;
pub fn emscripten_sleep(ms: c_uint);
pub fn emscripten_run_script(script: *const u8);
pub fn emscripten_get_element_css_size(
target: *const u8,
width: *mut f64,
height: *mut f64,
) -> i32;
}
thread_local!(static MAIN_LOOP_CALLBACK: RefCell<*mut c_void> = RefCell::new(null_mut()));
pub fn set_main_loop_callback<F>(callback: F)
where
F: FnMut(),
{
MAIN_LOOP_CALLBACK.with(|log| {
*log.borrow_mut() = &callback as *const _ as *mut c_void;
});
// milliseconds since start of program
pub fn now() -> f64 {
unsafe { emscripten_get_now() }
}
pub fn sleep(ms: u32) {
unsafe {
emscripten_set_main_loop(wrapper::<F>, 0, 1);
emscripten_sleep(ms);
}
}
unsafe extern "C" fn wrapper<F>()
where
F: FnMut(),
{
MAIN_LOOP_CALLBACK.with(|z| {
let closure = *z.borrow_mut() as *mut F;
(*closure)();
});
pub fn exec(script: &str) {
unsafe {
emscripten_run_script(script.as_ptr());
}
}
pub fn get_canvas_size() -> (u32, u32) {
let mut width = 0.0;
let mut height = 0.0;
unsafe {
emscripten_get_element_css_size("canvas\0".as_ptr(), &mut width, &mut height);
}
(width as u32, height as u32)
}
}

View File

@@ -2,14 +2,42 @@ use std::cell::RefCell;
use std::process;
use std::rc::Rc;
use rand::seq::IteratorRandom;
use sdl2::event::Event;
use sdl2::image::LoadTexture;
use sdl2::keyboard::Keycode;
use sdl2::pixels::Color;
use sdl2::rect::{Point, Rect};
use web_time::{Duration, Instant};
static BLACK: Color = Color::RGB(0, 0, 0);
#[cfg(target_os = "emscripten")]
mod emscripten;
#[cfg(not(target_os = "emscripten"))]
fn sleep(ms: u32) {
std::thread::sleep(Duration::from_millis(ms as u64));
}
#[cfg(target_os = "emscripten")]
fn now() -> f64 {
emscripten::emscripten::now() / 1000f64
}
#[cfg(not(target_os = "emscripten"))]
fn now() -> f64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs_f64()
}
#[cfg(target_os = "emscripten")]
fn sleep(ms: u32) {
emscripten::emscripten::sleep(ms);
}
fn main() {
let ctx = sdl2::init().unwrap();
let video_ctx = ctx.video().unwrap();
@@ -24,7 +52,7 @@ fn main() {
Err(err) => panic!("failed to create window: {}", err),
};
let canvas = match window.into_canvas().accelerated().present_vsync().build() {
let mut canvas = match window.into_canvas().accelerated().build() {
Ok(canvas) => canvas,
Err(err) => panic!("failed to create canvas: {}", err),
};
@@ -32,19 +60,23 @@ fn main() {
let texture_creator = canvas.texture_creator();
let mut point = Point::new(0, 0);
let ctx = Rc::new(RefCell::new(ctx));
let canvas = Rc::new(RefCell::new(canvas));
let texture_creator = Rc::new(texture_creator);
// let ctx = Rc::new(RefCell::new(ctx));
// let canvas = Rc::new(RefCell::new(canvas));
// let texture_creator = Rc::new(texture_creator);
let fruit_atlas = texture_creator
.load_texture("./assets/fruit.png")
.expect("could not load texture");
let target_fps = 60;
let frame_time = Duration::from_secs_f32(1.0) / target_fps;
println!("Frame time: {:?}", frame_time);
let mut frame = 0;
loop {
let start = now();
let mut moved = false;
for event in ctx.borrow_mut().event_pump().unwrap().poll_iter() {
for event in ctx.event_pump().unwrap().poll_iter() {
match event {
Event::Quit { .. }
| Event::KeyDown {
@@ -61,6 +93,11 @@ fn main() {
if frame > 7 {
frame = 0;
}
// random number between 2 and 6
let sleep_time = (15..=500).choose(&mut rand::thread_rng()).unwrap();
println!("Sleeping for {} ms", sleep_time);
sleep(sleep_time);
}
Keycode::Left => {
point.x -= 32;
@@ -86,7 +123,7 @@ fn main() {
// Handle wrapping at the edges
if moved {
let canvas_size = canvas.borrow().window().size();
let canvas_size = canvas.window().size();
if point.x < 0 {
point.x = canvas_size.0 as i32 - 32;
} else if point.x >= 640 {
@@ -99,8 +136,6 @@ fn main() {
}
}
let mut canvas = canvas.borrow_mut();
canvas.set_draw_color(BLACK);
canvas.clear();
@@ -117,21 +152,21 @@ fn main() {
.expect("could not draw texture");
canvas.present();
let t2 = now();
let elapsed = Duration::from_secs_f64(t2 - start);
if elapsed < frame_time {
let sleep_time = frame_time - elapsed;
sleep(sleep_time.as_millis() as u32);
// println!("elapsed: {:?} sleep: {:?}ms ({:?})", elapsed, sleep_time, t2);
} else {
let excess = elapsed - frame_time;
println!("! excess: {:?} ({:?})", excess, t2);
}
let t3 = now();
let duration = Duration::from_secs_f64(t3 - start);
let fps = 1f64 / (duration.as_secs_f64());
println!("FPS: {}", fps);
}
// #[cfg(target_family = "wasm")]
// {
// use crate::emscripten::emscripten::set_main_loop_callback;
// set_main_loop_callback(main_loop);
// }
// #[cfg(not(target_family = "wasm"))]
// {
// use std::thread::sleep;
// use std::time::Duration;
// loop {
// main_loop();
// sleep(Duration::from_millis(10))
// }
// }
}