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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
use std::time::Duration;
use crate::prelude::*;
use super::stopwatch::Stopwatch;
/// Tracks elapsed time. Enters the finished state once `duration` is reached.
///
/// Non repeating timers will stop tracking and stay in the finished state until reset.
/// Repeating timers will only be in the finished state on each tick `duration` is reached or
/// exceeded, and can still be reset at any given point.
///
/// Paused timers will not have elapsed time increased.
#[derive(Clone, Debug, Default, HasSchema)]
pub struct Timer {
finished: bool,
mode: TimerMode,
duration: Duration,
stopwatch: Stopwatch,
times_finished_this_tick: u32,
}
impl Timer {
/// Creates a new timer with a given duration.
///
/// See also [`Timer::from_seconds`](Timer::from_seconds).
pub fn new(duration: Duration, mode: TimerMode) -> Self {
Self {
duration,
mode,
..Default::default()
}
}
/// Creates a new timer with a given duration in seconds.
///
/// # Example
/// ```no_run
/// # use bones_framework::prelude::*;
/// let mut timer = Timer::from_seconds(1.0, TimerMode::Once);
/// ```
pub fn from_seconds(duration: f32, mode: TimerMode) -> Self {
Self {
duration: Duration::from_secs_f32(duration),
mode,
..Default::default()
}
}
/// Returns `true` if the timer has reached its duration at least once.
/// See also [`Timer::just_finished`](Timer::just_finished).
///
/// # Examples
/// ```no_run
/// # use bones_framework::prelude::*;
/// use std::time::Duration;
/// let mut timer = Timer::from_seconds(1.0, TimerMode::Once);
/// timer.tick(Duration::from_secs_f32(1.5));
/// assert!(timer.finished());
/// timer.tick(Duration::from_secs_f32(0.5));
/// assert!(timer.finished());
/// ```
#[inline]
pub fn finished(&self) -> bool {
self.finished
}
/// Returns `true` only on the tick the timer reached its duration.
///
/// # Examples
/// ```no_run
/// # use bones_framework::prelude::*;
/// use std::time::Duration;
/// let mut timer = Timer::from_seconds(1.0, TimerMode::Once);
/// timer.tick(Duration::from_secs_f32(1.5));
/// assert!(timer.just_finished());
/// timer.tick(Duration::from_secs_f32(0.5));
/// assert!(!timer.just_finished());
/// ```
#[inline]
pub fn just_finished(&self) -> bool {
self.times_finished_this_tick > 0
}
/// Returns the time elapsed on the timer. Guaranteed to be between 0.0 and `duration`.
/// Will only equal `duration` when the timer is finished and non repeating.
///
/// See also [`Stopwatch::elapsed`](Stopwatch::elapsed).
///
/// # Examples
/// ```no_run
/// # use bones_framework::prelude::*;
/// use std::time::Duration;
/// let mut timer = Timer::from_seconds(1.0, TimerMode::Once);
/// timer.tick(Duration::from_secs_f32(0.5));
/// assert_eq!(timer.elapsed(), Duration::from_secs_f32(0.5));
/// ```
#[inline]
pub fn elapsed(&self) -> Duration {
self.stopwatch.elapsed()
}
/// Returns the time elapsed on the timer as an `f32`.
/// See also [`Timer::elapsed`](Timer::elapsed).
#[inline]
pub fn elapsed_secs(&self) -> f32 {
self.stopwatch.elapsed_secs()
}
/// Sets the elapsed time of the timer without any other considerations.
///
/// # Example
/// ```no_run
/// # use bones_framework::prelude::*;
/// use std::time::Duration;
/// let mut timer = Timer::from_seconds(1.0, TimerMode::Once);
/// timer.set_elapsed(Duration::from_secs(2));
/// assert_eq!(timer.elapsed(), Duration::from_secs(2));
/// // the timer is not finished even if the elapsed time is greater than the duration.
/// assert!(!timer.finished());
/// ```
#[inline]
pub fn set_elapsed(&mut self, time: Duration) {
self.stopwatch.set_elapsed(time);
}
/// Returns the duration of the timer.
///
/// # Examples
/// ```no_run
/// # use bones_framework::prelude::*;
/// use std::time::Duration;
/// let timer = Timer::new(Duration::from_secs(1), TimerMode::Once);
/// assert_eq!(timer.duration(), Duration::from_secs(1));
/// ```
#[inline]
pub fn duration(&self) -> Duration {
self.duration
}
/// Sets the duration of the timer.
///
/// # Examples
/// ```no_run
/// # use bones_framework::prelude::*;
/// use std::time::Duration;
/// let mut timer = Timer::from_seconds(1.5, TimerMode::Once);
/// timer.set_duration(Duration::from_secs(1));
/// assert_eq!(timer.duration(), Duration::from_secs(1));
/// ```
#[inline]
pub fn set_duration(&mut self, duration: Duration) {
self.duration = duration;
}
/// Returns the mode of the timer.
///
/// # Examples
/// ```no_run
/// # use bones_framework::prelude::*;
/// let mut timer = Timer::from_seconds(1.0, TimerMode::Repeating);
/// assert_eq!(timer.mode(), TimerMode::Repeating);
/// ```
#[inline]
pub fn mode(&self) -> TimerMode {
self.mode
}
/// Sets the mode of the timer.
///
/// # Examples
/// ```no_run
/// # use bones_framework::prelude::*;
/// let mut timer = Timer::from_seconds(1.0, TimerMode::Repeating);
/// timer.set_mode(TimerMode::Once);
/// assert_eq!(timer.mode(), TimerMode::Once);
/// ```
#[doc(alias = "repeating")]
#[inline]
pub fn set_mode(&mut self, mode: TimerMode) {
if self.mode != TimerMode::Repeating && mode == TimerMode::Repeating && self.finished {
self.stopwatch.reset();
self.finished = self.just_finished();
}
self.mode = mode;
}
/// Advance the timer by `delta` seconds.
/// Non repeating timer will clamp at duration.
/// Repeating timer will wrap around.
/// Will not affect paused timers.
///
/// See also [`Stopwatch::tick`](Stopwatch::tick).
///
/// # Examples
/// ```no_run
/// # use bones_framework::prelude::*;
/// use std::time::Duration;
/// let mut timer = Timer::from_seconds(1.0, TimerMode::Once);
/// let mut repeating = Timer::from_seconds(1.0, TimerMode::Repeating);
/// timer.tick(Duration::from_secs_f32(1.5));
/// repeating.tick(Duration::from_secs_f32(1.5));
/// assert_eq!(timer.elapsed_secs(), 1.0);
/// assert_eq!(repeating.elapsed_secs(), 0.5);
/// ```
pub fn tick(&mut self, delta: Duration) -> &Self {
if self.paused() {
self.times_finished_this_tick = 0;
if self.mode == TimerMode::Repeating {
self.finished = false;
}
return self;
}
if self.mode != TimerMode::Repeating && self.finished() {
self.times_finished_this_tick = 0;
return self;
}
self.stopwatch.tick(delta);
self.finished = self.elapsed() >= self.duration();
if self.finished() {
if self.mode == TimerMode::Repeating {
self.times_finished_this_tick =
(self.elapsed().as_nanos() / self.duration().as_nanos()) as u32;
// Duration does not have a modulo
self.set_elapsed(self.elapsed() - self.duration() * self.times_finished_this_tick);
} else {
self.times_finished_this_tick = 1;
self.set_elapsed(self.duration());
}
} else {
self.times_finished_this_tick = 0;
}
self
}
/// Pauses the Timer. Disables the ticking of the timer.
///
/// See also [`Stopwatch::pause`](Stopwatch::pause).
///
/// # Examples
/// ```no_run
/// # use bones_framework::prelude::*;
/// use std::time::Duration;
/// let mut timer = Timer::from_seconds(1.0, TimerMode::Once);
/// timer.pause();
/// timer.tick(Duration::from_secs_f32(0.5));
/// assert_eq!(timer.elapsed_secs(), 0.0);
/// ```
#[inline]
pub fn pause(&mut self) {
self.stopwatch.pause();
}
/// Unpauses the Timer. Resumes the ticking of the timer.
///
/// See also [`Stopwatch::unpause()`](Stopwatch::unpause).
///
/// # Examples
/// ```no_run
/// # use bones_framework::prelude::*;
/// use std::time::Duration;
/// let mut timer = Timer::from_seconds(1.0, TimerMode::Once);
/// timer.pause();
/// timer.tick(Duration::from_secs_f32(0.5));
/// timer.unpause();
/// timer.tick(Duration::from_secs_f32(0.5));
/// assert_eq!(timer.elapsed_secs(), 0.5);
/// ```
#[inline]
pub fn unpause(&mut self) {
self.stopwatch.unpause();
}
/// Returns `true` if the timer is paused.
///
/// See also [`Stopwatch::paused`](Stopwatch::paused).
///
/// # Examples
/// ```no_run
/// # use bones_framework::prelude::*;
/// let mut timer = Timer::from_seconds(1.0, TimerMode::Once);
/// assert!(!timer.paused());
/// timer.pause();
/// assert!(timer.paused());
/// timer.unpause();
/// assert!(!timer.paused());
/// ```
#[inline]
pub fn paused(&self) -> bool {
self.stopwatch.paused()
}
/// Resets the timer. The reset doesn't affect the `paused` state of the timer.
///
/// See also [`Stopwatch::reset`](Stopwatch::reset).
///
/// Examples
/// ```no_run
/// # use bones_framework::prelude::*;
/// use std::time::Duration;
/// let mut timer = Timer::from_seconds(1.0, TimerMode::Once);
/// timer.tick(Duration::from_secs_f32(1.5));
/// timer.reset();
/// assert!(!timer.finished());
/// assert!(!timer.just_finished());
/// assert_eq!(timer.elapsed_secs(), 0.0);
/// ```
pub fn reset(&mut self) {
self.stopwatch.reset();
self.finished = false;
self.times_finished_this_tick = 0;
}
/// Returns the percentage of the timer elapsed time (goes from 0.0 to 1.0).
///
/// # Examples
/// ```no_run
/// # use bones_framework::prelude::*;
/// use std::time::Duration;
/// let mut timer = Timer::from_seconds(2.0, TimerMode::Once);
/// timer.tick(Duration::from_secs_f32(0.5));
/// assert_eq!(timer.percent(), 0.25);
/// ```
#[inline]
pub fn percent(&self) -> f32 {
self.elapsed().as_secs_f32() / self.duration().as_secs_f32()
}
/// Returns the percentage of the timer remaining time (goes from 1.0 to 0.0).
///
/// # Examples
/// ```no_run
/// # use bones_framework::prelude::*;
/// use std::time::Duration;
/// let mut timer = Timer::from_seconds(2.0, TimerMode::Once);
/// timer.tick(Duration::from_secs_f32(0.5));
/// assert_eq!(timer.percent_left(), 0.75);
/// ```
#[inline]
pub fn percent_left(&self) -> f32 {
1.0 - self.percent()
}
/// Returns the remaining time in seconds
///
/// # Examples
/// ```no_run
/// # use bones_framework::prelude::*;
/// use std::cmp::Ordering;
/// use std::time::Duration;
/// let mut timer = Timer::from_seconds(2.0, TimerMode::Once);
/// timer.tick(Duration::from_secs_f32(0.5));
/// let result = timer.remaining_secs().total_cmp(&1.5);
/// assert_eq!(Ordering::Equal, result);
/// ```
#[inline]
pub fn remaining_secs(&self) -> f32 {
self.remaining().as_secs_f32()
}
/// Returns the remaining time using Duration
///
/// # Examples
/// ```no_run
/// # use bones_framework::prelude::*;
/// use std::time::Duration;
/// let mut timer = Timer::from_seconds(2.0, TimerMode::Once);
/// timer.tick(Duration::from_secs_f32(0.5));
/// assert_eq!(timer.remaining(), Duration::from_secs_f32(1.5));
/// ```
#[inline]
pub fn remaining(&self) -> Duration {
self.duration() - self.elapsed()
}
/// Returns the number of times a repeating timer
/// finished during the last [`tick`](Timer<T>::tick) call.
///
/// For non repeating-timers, this method will only ever
/// return 0 or 1.
///
/// # Examples
/// ```no_run
/// # use bones_framework::prelude::*;
/// use std::time::Duration;
/// let mut timer = Timer::from_seconds(1.0, TimerMode::Repeating);
/// timer.tick(Duration::from_secs_f32(6.0));
/// assert_eq!(timer.times_finished_this_tick(), 6);
/// timer.tick(Duration::from_secs_f32(2.0));
/// assert_eq!(timer.times_finished_this_tick(), 2);
/// timer.tick(Duration::from_secs_f32(0.5));
/// assert_eq!(timer.times_finished_this_tick(), 0);
/// ```
#[inline]
pub fn times_finished_this_tick(&self) -> u32 {
self.times_finished_this_tick
}
}
/// Specifies [`Timer`] behavior.
#[derive(
Debug, Clone, Copy, Eq, PartialEq, Hash, Default, serde::Deserialize, serde::Serialize,
)]
pub enum TimerMode {
/// Run once and stop.
#[default]
Once,
/// Reset when finished.
Repeating,
}
// To speed up CI, only do these on miri, where they complete without waiting for time to pass.
#[cfg(all(test, miri))]
#[allow(clippy::float_cmp)]
mod tests {
use super::*;
#[test]
fn non_repeating_timer() {
let mut t = Timer::from_seconds(10.0, TimerMode::Once);
// Tick once, check all attributes
t.tick(Duration::from_secs_f32(0.25));
assert_eq!(t.elapsed_secs(), 0.25);
assert_eq!(t.duration(), Duration::from_secs_f32(10.0));
assert!(!t.finished());
assert!(!t.just_finished());
assert_eq!(t.times_finished_this_tick(), 0);
assert_eq!(t.mode(), TimerMode::Once);
assert_eq!(t.percent(), 0.025);
assert_eq!(t.percent_left(), 0.975);
// Ticking while paused changes nothing
t.pause();
t.tick(Duration::from_secs_f32(500.0));
assert_eq!(t.elapsed_secs(), 0.25);
assert_eq!(t.duration(), Duration::from_secs_f32(10.0));
assert!(!t.finished());
assert!(!t.just_finished());
assert_eq!(t.times_finished_this_tick(), 0);
assert_eq!(t.mode(), TimerMode::Once);
assert_eq!(t.percent(), 0.025);
assert_eq!(t.percent_left(), 0.975);
// Tick past the end and make sure elapsed doesn't go past 0.0 and other things update
t.unpause();
t.tick(Duration::from_secs_f32(500.0));
assert_eq!(t.elapsed_secs(), 10.0);
assert!(t.finished());
assert!(t.just_finished());
assert_eq!(t.times_finished_this_tick(), 1);
assert_eq!(t.percent(), 1.0);
assert_eq!(t.percent_left(), 0.0);
// Continuing to tick when finished should only change just_finished
t.tick(Duration::from_secs_f32(1.0));
assert_eq!(t.elapsed_secs(), 10.0);
assert!(t.finished());
assert!(!t.just_finished());
assert_eq!(t.times_finished_this_tick(), 0);
assert_eq!(t.percent(), 1.0);
assert_eq!(t.percent_left(), 0.0);
}
#[test]
fn repeating_timer() {
let mut t = Timer::from_seconds(2.0, TimerMode::Repeating);
// Tick once, check all attributes
t.tick(Duration::from_secs_f32(0.75));
assert_eq!(t.elapsed_secs(), 0.75);
assert_eq!(t.duration(), Duration::from_secs_f32(2.0));
assert!(!t.finished());
assert!(!t.just_finished());
assert_eq!(t.times_finished_this_tick(), 0);
assert_eq!(t.mode(), TimerMode::Repeating);
assert_eq!(t.percent(), 0.375);
assert_eq!(t.percent_left(), 0.625);
// Tick past the end and make sure elapsed wraps
t.tick(Duration::from_secs_f32(1.5));
assert_eq!(t.elapsed_secs(), 0.25);
assert!(t.finished());
assert!(t.just_finished());
assert_eq!(t.times_finished_this_tick(), 1);
assert_eq!(t.percent(), 0.125);
assert_eq!(t.percent_left(), 0.875);
// Continuing to tick should turn off both finished & just_finished for repeating timers
t.tick(Duration::from_secs_f32(1.0));
assert_eq!(t.elapsed_secs(), 1.25);
assert!(!t.finished());
assert!(!t.just_finished());
assert_eq!(t.times_finished_this_tick(), 0);
assert_eq!(t.percent(), 0.625);
assert_eq!(t.percent_left(), 0.375);
}
#[test]
fn times_finished_repeating() {
let mut t = Timer::from_seconds(1.0, TimerMode::Repeating);
assert_eq!(t.times_finished_this_tick(), 0);
t.tick(Duration::from_secs_f32(3.5));
assert_eq!(t.times_finished_this_tick(), 3);
assert_eq!(t.elapsed_secs(), 0.5);
assert!(t.finished());
assert!(t.just_finished());
t.tick(Duration::from_secs_f32(0.2));
assert_eq!(t.times_finished_this_tick(), 0);
}
#[test]
fn times_finished_this_tick() {
let mut t = Timer::from_seconds(1.0, TimerMode::Once);
assert_eq!(t.times_finished_this_tick(), 0);
t.tick(Duration::from_secs_f32(1.5));
assert_eq!(t.times_finished_this_tick(), 1);
t.tick(Duration::from_secs_f32(0.5));
assert_eq!(t.times_finished_this_tick(), 0);
}
#[test]
fn times_finished_this_tick_precise() {
let mut t = Timer::from_seconds(0.01, TimerMode::Repeating);
let duration = Duration::from_secs_f64(0.333);
// total duration: 0.333 => 33 times finished
t.tick(duration);
assert_eq!(t.times_finished_this_tick(), 33);
// total duration: 0.666 => 33 times finished
t.tick(duration);
assert_eq!(t.times_finished_this_tick(), 33);
// total duration: 0.999 => 33 times finished
t.tick(duration);
assert_eq!(t.times_finished_this_tick(), 33);
// total duration: 1.332 => 34 times finished
t.tick(duration);
assert_eq!(t.times_finished_this_tick(), 34);
}
#[test]
fn paused() {
let mut t = Timer::from_seconds(10.0, TimerMode::Once);
t.tick(Duration::from_secs_f32(10.0));
assert!(t.just_finished());
assert!(t.finished());
// A paused timer should change just_finished to false after a tick
t.pause();
t.tick(Duration::from_secs_f32(5.0));
assert!(!t.just_finished());
assert!(t.finished());
}
#[test]
fn paused_repeating() {
let mut t = Timer::from_seconds(10.0, TimerMode::Repeating);
t.tick(Duration::from_secs_f32(10.0));
assert!(t.just_finished());
assert!(t.finished());
// A paused repeating timer should change finished and just_finished to false after a tick
t.pause();
t.tick(Duration::from_secs_f32(5.0));
assert!(!t.just_finished());
assert!(!t.finished());
}
}