37c919df90
size_t interval should've been a double, but was being implicitly converted, so it worked, compiled. but not like I intended.
64 lines
1.9 KiB
C++
64 lines
1.9 KiB
C++
// calls callbackfunc on specified interval based on accumulated deltatime
|
|
#include "timer.hpp"
|
|
#include <algorithm>
|
|
#include <chrono>
|
|
#include <cstddef>
|
|
#include <memory>
|
|
#include <ncurses.h>
|
|
#include <string>
|
|
#include <vector>
|
|
|
|
// infinite timer
|
|
timer::timer(std::string name_input, double interval_input,
|
|
std::unique_ptr<timeraction> action_input)
|
|
: time_interval(interval_input), name(name_input), is_infinite(true),
|
|
action(std::move(action_input)) {}
|
|
|
|
// limited timer
|
|
timer::timer(std::string name, double interval_input, int triggeramount,
|
|
std::unique_ptr<timeraction> action_input)
|
|
: triggeramount(triggeramount), time_interval(interval_input), name(name),
|
|
action(std::move(action_input)) {}
|
|
|
|
// callbackfunc once enough time has accumulated
|
|
void timer::updatetime(double DeltaTime) {
|
|
accumulator += DeltaTime;
|
|
if (!is_expired) {
|
|
if (accumulator >= time_interval) {
|
|
action->update(*this);
|
|
accumulator -= time_interval;
|
|
triggercounter++;
|
|
if (!is_infinite && triggercounter >= triggeramount) {
|
|
is_expired = true;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
void timermanager::addtimer(std::unique_ptr<timer> input_timer) {
|
|
timers.push_back(std::move(input_timer));
|
|
}
|
|
|
|
void timermanager::updatetimers() {
|
|
//get dtime
|
|
auto currenttime = std::chrono::steady_clock::now();
|
|
std::chrono::duration<double> myDeltaTime = currenttime - prevtime;
|
|
double dtime = myDeltaTime.count();
|
|
|
|
//update timers with dtime
|
|
for (auto &mytimer : timers) {
|
|
mytimer->updatetime(dtime);
|
|
mvprintw(12, 0, "updated timer %s", mytimer->name.c_str());
|
|
}
|
|
//reset for next tick
|
|
prevtime = currenttime;
|
|
timers.erase(std::remove_if(timers.begin(), timers.end(),
|
|
[](auto &timer) { return timer->is_expired; }),
|
|
timers.end());
|
|
// implement delete timers
|
|
refresh();
|
|
}
|
|
|
|
timermanager::timermanager(): prevtime(std::chrono::steady_clock::now()){}
|
|
|