#[allow(dead_code)]
pub fn time_callback<F, R>(target: &mut f32, func: F) -> R
where
F: FnOnce() -> R,
{
let start = std::time::Instant::now();
let result = func();
*target = start.elapsed().as_secs_f32();
result
}
#[cfg(not(target_arch = "wasm32"))]
use std::time::{Duration, Instant};
#[cfg(target_arch = "wasm32")]
use web_time::{Duration, Instant};
use crate::context::Resource;
pub struct FixedTimeStep {
accumulator: f32,
fixed_dt: f32,
}
impl FixedTimeStep {
pub fn new(tps: u32) -> Self {
Self {
accumulator: 0.0,
fixed_dt: 1.0 / tps as f32,
}
}
}
pub struct Frame {
frame_count: u32,
pub start_time: Instant,
pub fps: f32,
last_frame_time: Instant,
pub time_delta: Duration,
pub time_delta_f32: f32,
pub fixed_timestep: FixedTimeStep,
}
impl Resource for Frame {}
impl Default for Frame {
fn default() -> Self {
Self::new()
}
}
impl Frame {
pub(crate) fn new() -> Self {
Frame {
frame_count: 0,
fps: 0.0,
start_time: Instant::now(),
last_frame_time: Instant::now(),
time_delta: Duration::default(),
time_delta_f32: 0.0,
fixed_timestep: FixedTimeStep::new(60),
}
}
pub(crate) fn update(&mut self) {
self.frame_count += 1;
let now = Instant::now();
self.time_delta = now.duration_since(self.last_frame_time);
self.time_delta_f32 = self.time_delta.as_secs_f32();
self.fixed_timestep.accumulator += self.time_delta_f32;
self.fps = 1.0 / self.time_delta_f32;
self.last_frame_time = now;
}
pub fn should_fixed_update(&mut self) -> bool {
if self.fixed_timestep.accumulator >= self.fixed_timestep.fixed_dt {
self.fixed_timestep.accumulator -= self.fixed_timestep.fixed_dt;
true
} else {
false
}
}
pub fn fixed_delta_time(&self) -> f32 {
self.fixed_timestep.fixed_dt
}
}