]> git.localhorst.tv Git - blank.git/blob - src/app/IntervalTimer.hpp
also post UI messages to graphical output
[blank.git] / src / app / IntervalTimer.hpp
1 #ifndef BLANK_APP_INTERVALTIMER_HPP
2 #define BLANK_APP_INTERVALTIMER_HPP
3
4
5 namespace blank {
6
7 /// Timer that hits every n milliseconds. Resolution is that of the
8 /// delta values passed to Update(), minimum 1ms.
9 /// Also tracks the number of iterations as well as milliseconds
10 /// passed.
11 class IntervalTimer {
12
13 public:
14         /// Create a timer that hits every interval_ms milliseconds.
15         /// Initial state is stopped.
16         explicit IntervalTimer(int interval_ms) noexcept
17         : intv(interval_ms) { }
18
19         void Start() noexcept {
20                 speed = 1;
21         }
22         void Stop() noexcept {
23                 value = 0;
24                 speed = 0;
25         }
26         void Reset() noexcept {
27                 value = 0;
28         }
29
30         bool Running() const noexcept {
31                 return speed != 0;
32         }
33         /// true if an interval boundary was passed by the last call to Update()
34         bool Hit() const noexcept {
35                 return Running() && value % intv < last_dt;
36         }
37         bool HitOnce() const noexcept {
38                 return value >= intv;
39         }
40         int Elapsed() const noexcept {
41                 return value;
42         }
43         int Iteration() const noexcept {
44                 return value / intv;
45         }
46
47         void Update(int dt) noexcept {
48                 value += dt * speed;
49                 last_dt = dt;
50         }
51
52 private:
53         int intv;
54         int value = 0;
55         int speed = 0;
56         int last_dt = 0;
57
58 };
59
60 }
61
62 #endif