X-Git-Url: http://git.localhorst.tv/?a=blobdiff_plain;f=src%2Fapp%2FIntervalTimer.hpp;h=2f465ad92880787aa42c4f7f07e4494e30433819;hb=fda38181732e58537331c919dd699eaa830ead50;hp=e5d02481e676d9c618388b626b9931f8caf6fc5a;hpb=b7d09e1e35ef90282c97509e0020b20db3c7ea9f;p=blank.git diff --git a/src/app/IntervalTimer.hpp b/src/app/IntervalTimer.hpp index e5d0248..2f465ad 100644 --- a/src/app/IntervalTimer.hpp +++ b/src/app/IntervalTimer.hpp @@ -1,49 +1,94 @@ #ifndef BLANK_APP_INTERVALTIMER_HPP #define BLANK_APP_INTERVALTIMER_HPP +#include + namespace blank { +/// Timer that hits every n Time units. Resolution is that of the +/// delta values passed to Update(). +/// Also tracks the number of iterations as well as Time units +/// passed. +template class IntervalTimer { public: - explicit IntervalTimer(int interval_ms) noexcept + /// Create a timer that hits every interval Time units. + /// Initial state is stopped. + explicit IntervalTimer(Time interval_ms = Time(0)) noexcept : intv(interval_ms) { } void Start() noexcept { - speed = 1; + speed = Time(1); } void Stop() noexcept { - value = 0; - speed = 0; + value = Time(0); + speed = Time(0); + } + void Reset() noexcept { + value = Time(0); } bool Running() const noexcept { - return speed != 0; + return speed != Time(0); } + /// true if an interval boundary was passed by the last call to Update() bool Hit() const noexcept { - return Running() && value % intv < last_dt; + return Running() && IntervalElapsed() < last_dt; } - int Elapsed() const noexcept { + bool HitOnce() const noexcept { + return Running() && value >= intv; + } + Time Elapsed() const noexcept { return value; } + Time Interval() const noexcept { + return intv; + } + Time IntervalElapsed() const noexcept { + return mod(value, intv); + } + Time IntervalRemain() const noexcept { + return intv - IntervalElapsed(); + } int Iteration() const noexcept { return value / intv; } + void PopIteration() noexcept { + value -= intv; + } - void Update(int dt) noexcept { + void Update(Time dt) noexcept { value += dt * speed; last_dt = dt; } + static Time mod(Time val, Time m) noexcept { + return val % m; + } + private: - int intv; - int value = 0; - int speed = 0; - int last_dt = 0; + Time intv; + Time value = Time(0); + Time speed = Time(0); + Time last_dt = Time(0); }; +using CoarseTimer = IntervalTimer; +using FineTimer = IntervalTimer; + +template<> +inline float IntervalTimer::mod(float val, float m) noexcept { + return std::fmod(val, m); +} + +template<> +inline int IntervalTimer::Iteration() const noexcept { + return std::floor(value / intv); +} + } #endif