refactor: Simplify Timer interface

This commit is contained in:
Vsevolod Kremianskii 2021-01-16 20:55:06 +07:00
parent 76b0bab6fb
commit e2b34c51e8
6 changed files with 37 additions and 28 deletions

View file

@ -21,23 +21,25 @@
namespace reone {
Timer::Timer(float timeout) : _timeout(timeout) {
}
void Timer::update(float dt) {
_timeout = glm::max(0.0f, _timeout - dt);
Timer::Timer(float timeout) {
reset(timeout);
}
void Timer::reset(float timeout) {
_timeout = timeout;
_time = timeout;
}
bool Timer::advance(float secs) {
_time = glm::min(0.0f, _time - secs);
return isTimedOut();
}
bool Timer::isTimedOut() const {
return _time == 0.0f;
}
void Timer::cancel() {
_timeout = 0.0f;
}
bool Timer::hasTimedOut() const {
return _timeout == 0.0f;
_time = 0.0f;
}
} // namespace reone

View file

@ -19,19 +19,32 @@
namespace reone {
/**
* Utility class to handle timed events.
*/
class Timer {
public:
Timer() = default;
Timer(float timeout);
void update(float dt);
void reset(float timeout);
/**
* Advances this timer by the specified amount of seconds.
*
* @return true if timer times out, false otherwise
*/
bool advance(float secs);
/**
* Cancels this timer, putting it the timed out state.
*/
void cancel();
bool hasTimedOut() const;
bool isTimedOut() const;
private:
float _timeout { 0.0f };
float _time { 0.0f };
};
} // namespace reone

View file

@ -56,12 +56,10 @@ Combat::Combat(Game *game) : _game(game) {
}
void Combat::update(float dt) {
_heartbeatTimer.update(dt);
if (_heartbeatTimer.hasTimedOut()) {
_heartbeatTimer.reset(kHeartbeatInterval);
if (_heartbeatTimer.advance(dt)) {
updateCombatants();
updateAI();
_heartbeatTimer.reset(kHeartbeatInterval);
}
updateRounds(dt);
updateActivation();

View file

@ -874,9 +874,7 @@ void Area::checkTriggersIntersection(const shared_ptr<SpatialObject> &triggerrer
}
void Area::updateHeartbeat(float dt) {
_heartbeatTimer.update(dt);
if (_heartbeatTimer.hasTimedOut()) {
if (_heartbeatTimer.advance(dt)) {
if (!_onHeartbeat.empty()) {
_game->scriptRunner().run(_onHeartbeat, _id);
}
@ -887,7 +885,6 @@ void Area::updateHeartbeat(float dt) {
}
}
_game->party().onHeartbeat();
_heartbeatTimer.reset(kHeartbeatInterval);
}
}

View file

@ -61,8 +61,7 @@ void EmitterSceneNode::spawnParticles(float dt) {
switch (_emitter->updateType()) {
case Emitter::UpdateType::Fountain:
if (_emitter->birthrate() != 0.0f) {
_birthTimer.update(dt);
if (_birthTimer.hasTimedOut()) {
if (_birthTimer.advance(dt)) {
if (_particles.size() < kMaxParticleCount) {
doSpawnParticle();
}

View file

@ -28,11 +28,11 @@ using namespace reone;
BOOST_AUTO_TEST_CASE(test_timer_times_out) {
Timer timer(1.0f);
timer.update(0.5f);
timer.advance(0.5f);
BOOST_TEST(!timer.hasTimedOut());
BOOST_TEST(!timer.isTimedOut());
timer.update(0.6f);
timer.advance(0.6f);
BOOST_TEST(timer.hasTimedOut());
BOOST_TEST(timer.isTimedOut());
}