namespace moof {
-scalar timer::next_event_ = std::numeric_limits<scalar>::max();
-hash<unsigned,timer*,hash_function> timer::timers_;
-
-
-unsigned timer::new_identifier()
-{
- static unsigned id = 1;
- return id++;
-}
-
-
-void timer::init(const function& function, scalar seconds, mode mode)
+void timer::init(const function& function,
+ scalar seconds,
+ mode mode,
+ runloop* runloop)
{
invalidate();
+ ASSERT(runloop && "can't schedule timer without a runloop");
- mode_ = mode;
-
- if (mode_ != invalid)
+ if ((mode_ = mode) != invalid)
{
function_ = function;
interval_ = seconds;
}
- id_ = new_identifier();
- timers_.insert(std::pair<unsigned,timer*>(id_, this));
-
- if (absolute_ < next_event_) next_event_ = absolute_;
+ runloop->add_timer(this);
+ runloop_ = runloop;
}
}
-bool timer::is_valid() const
-{
- return mode_ != invalid;
-}
-
void timer::invalidate()
{
if (mode_ != invalid)
{
- timers_.erase(id_);
mode_ = invalid;
+ absolute_ = SCALAR(0.0);
- if (is_equal(absolute_, next_event_))
- {
- next_event_ = find_next_event();
- }
+ runloop_->remove_timer(this);
+ runloop_ = 0;
}
}
-void timer::fire()
+void timer::fire(scalar t)
{
- scalar t = ticks();
-
if (function_) function_(*this, t);
if (is_repeating())
{
- scalar absolute = absolute_;
-
if (is_equal(absolute_, t, 1.0)) absolute_ += interval_;
else absolute_ = interval_ + t;
-
- if (is_equal(absolute, next_event_))
- {
- next_event_ = find_next_event();
- }
- }
- else
- {
- invalidate();
- }
-}
-
-
-scalar timer::find_next_event()
-{
- scalar next_fire = std::numeric_limits<scalar>::max();
-
- hash<unsigned,timer*,hash_function>::iterator it;
- for (it = timers_.begin(); it.valid(); ++it)
- {
- scalar absolute = (*it).second->absolute_;
- if (absolute < next_fire) next_fire = absolute;
- }
-
- return next_fire;
-}
-
-
-scalar timer::seconds_remaining() const
-{
- return absolute_ - ticks();
-}
-
-scalar timer::next_expiration() const
-{
- return absolute_;
-}
-
-bool timer::is_expired() const
-{
- return seconds_remaining() < 0.0;
-}
-
-bool timer::is_repeating() const
-{
- return mode_ == repeat;
-}
-
-
-void timer::fire_expired_timers(scalar t)
-{
- if (t < next_event_) return;
-
- hash<unsigned,timer*,hash_function>::iterator it;
- for (it = timers_.begin(); it.valid(); ++it)
- {
- timer* timer = (*it).second;
- if (timer->is_expired()) timer->fire();
-
- if (it.end()) break;
}
+ else invalidate();
}
-#if USE_CLOCK_GETTIME
+#if ENABLE_CLOCK_GETTIME
// Since the monotonic clock will provide us with the time since the
// computer started, the number of seconds since that time could easily
}
-#else // ! USE_CLOCK_GETTIME
+#else // ! ENABLE_CLOCK_GETTIME
// If we don't have posix timers, we'll have to use a different timing
SDL_Delay(seconds * SCALAR(1000.0));
}
-#endif // USE_CLOCK_GETTIME
+#endif // ENABLE_CLOCK_GETTIME
} // namespace moof