#[cfg(feature = "web-sys")]
use web_sys::{Performance, window};
#[cfg(feature = "web-sys")]
pub struct Timer {
performance: Performance,
start_time: Option<f64>,
}
#[cfg(feature = "web-sys")]
impl Timer {
pub fn new() -> Option<Self> {
let performance = window()?.performance()?;
Some(Self {
performance,
start_time: None,
})
}
pub fn start(&mut self) {
self.start_time = Some(self.performance.now());
}
pub fn elapsed(&self) -> Option<f64> {
let start = self.start_time?;
Some(self.performance.now() - start)
}
pub fn now(&self) -> f64 {
self.performance.now()
}
pub fn reset(&mut self) {
self.start_time = None;
}
}
#[cfg(feature = "web-sys")]
impl Default for Timer {
fn default() -> Self {
Self::new().expect("Failed to create timer")
}
}
pub mod fps {
pub const TARGET_FPS: f64 = 60.0;
pub const FRAME_TIME: f64 = 1000.0 / TARGET_FPS;
pub fn is_frame_time_acceptable(frame_time: f64) -> bool {
frame_time <= FRAME_TIME * 1.5 }
pub fn calculate_fps(frame_time: f64) -> f64 {
if frame_time > 0.0 {
1000.0 / frame_time
} else {
0.0
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_fps_calculations() {
use fps::*;
assert!((calculate_fps(16.67) - 60.0).abs() < 1.0);
assert!((calculate_fps(33.33) - 30.0).abs() < 1.0);
assert!(is_frame_time_acceptable(16.0));
assert!(is_frame_time_acceptable(20.0));
assert!(!is_frame_time_acceptable(30.0));
}
}