]> git.localhorst.tv Git - blank.git/blob - src/app/IntervalTimer.hpp
cutting corners in chunk generation
[blank.git] / src / app / IntervalTimer.hpp
1 #ifndef BLANK_APP_INTERVALTIMER_HPP
2 #define BLANK_APP_INTERVALTIMER_HPP
3
4 #include <cmath>
5
6
7 namespace blank {
8
9 /// Timer that hits every n Time units. Resolution is that of the
10 /// delta values passed to Update().
11 /// Also tracks the number of iterations as well as Time units
12 /// passed.
13 template<class Time = int>
14 class IntervalTimer {
15
16 public:
17         /// Create a timer that hits every interval Time units.
18         /// Initial state is stopped.
19         explicit IntervalTimer(Time interval_ms = Time(0)) noexcept
20         : intv(interval_ms) { }
21
22         void Start() noexcept {
23                 speed = Time(1);
24         }
25         void Stop() noexcept {
26                 value = Time(0);
27                 speed = Time(0);
28         }
29         void Reset() noexcept {
30                 value = Time(0);
31         }
32
33         bool Running() const noexcept {
34                 return speed != Time(0);
35         }
36         /// true if an interval boundary was passed by the last call to Update()
37         bool Hit() const noexcept {
38                 return Running() && IntervalElapsed() < last_dt;
39         }
40         bool HitOnce() const noexcept {
41                 return Running() && value >= intv;
42         }
43         Time Elapsed() const noexcept {
44                 return value;
45         }
46         Time Interval() const noexcept {
47                 return intv;
48         }
49         Time IntervalElapsed() const noexcept {
50                 return mod(value, intv);
51         }
52         Time IntervalRemain() const noexcept {
53                 return intv - IntervalElapsed();
54         }
55         int Iteration() const noexcept {
56                 return value / intv;
57         }
58         void PopIteration() noexcept {
59                 value -= intv;
60         }
61
62         void Update(Time dt) noexcept {
63                 value += dt * speed;
64                 last_dt = dt;
65         }
66
67         static Time mod(Time val, Time m) noexcept {
68                 return val % m;
69         }
70
71 private:
72         Time intv;
73         Time value = Time(0);
74         Time speed = Time(0);
75         Time last_dt = Time(0);
76
77 };
78
79 using CoarseTimer = IntervalTimer<int>;
80 using FineTimer = IntervalTimer<float>;
81
82 template<>
83 inline float IntervalTimer<float>::mod(float val, float m) noexcept {
84         return std::fmod(val, m);
85 }
86
87 template<>
88 inline int IntervalTimer<float>::Iteration() const noexcept {
89         return std::floor(value / intv);
90 }
91
92 }
93
94 #endif