TrackManiaControl/application/core/Callbacks/TimerManager.php

106 lines
2.6 KiB
PHP
Raw Normal View History

2014-01-30 22:35:32 +01:00
<?php
/**
2014-01-30 23:34:36 +01:00
* Class for managing Timers
*
* @author steeffeen & kremsy
2014-01-30 22:35:32 +01:00
*/
namespace ManiaControl\Callbacks;
use ManiaControl\ManiaControl;
class TimerManager {
private $maniaControl = null;
private $timerListenings = array();
2014-01-30 23:34:36 +01:00
/**
* Construct a new Timer Manager
*
* @param \ManiaControl\ManiaControl $maniaControl
*/
2014-01-30 22:35:32 +01:00
public function __construct(ManiaControl $maniaControl) {
$this->maniaControl = $maniaControl;
}
2014-01-30 23:34:36 +01:00
/**
* Registers a One Time Listening
*
* @param TimerListener $listener
* @param $method
* @param $time
*/
public function registerOneTimeListening(TimerListener $listener, $method, $time) {
$this->registerTimerListening($listener, $method, $time, true);
}
2014-01-30 22:35:32 +01:00
/**
* Registers a Timing Listening, note < 10ms it can get inaccurate
*
* @param TimerListener $listener
* @param $method
* @param $time
* @return bool
*/
2014-01-30 23:34:36 +01:00
public function registerTimerListening(TimerListener $listener, $method, $time, $oneTime = false) {
2014-01-30 22:35:32 +01:00
if (!method_exists($listener, $method)) {
trigger_error("Given listener (" . get_class($listener) . ") can't handle timer (no method '{$method}')!");
return false;
}
2014-01-30 23:34:36 +01:00
//Init the Timer Listening
$listening = new \stdClass();
$listening->listener = $listener;
$listening->method = $method;
$listening->deltaTime = $time / 1000;
$listening->lastTrigger = -1;
$listening->oneTime = $oneTime;
array_push($this->timerListenings, $listening);
2014-01-30 22:35:32 +01:00
return true;
2014-01-30 23:34:36 +01:00
}
2014-01-30 22:35:32 +01:00
2014-01-30 23:34:36 +01:00
/**
* Remove a Script Callback Listener
*
* @param CallbackListener $listener
* @return bool
*/
public function unregisterTimerListenings(CallbackListener $listener) {
$removed = false;
foreach($this->timerListenings as $key => &$listening) {
if ($listening->listener != $listener) {
continue;
}
unset($this->timerListenings[$key]);
$removed = true;
}
return $removed;
2014-01-30 22:35:32 +01:00
}
/**
* Manage the Timings on every ms
*/
public function manageTimings() {
$time = microtime(true);
2014-01-30 23:34:36 +01:00
foreach($this->timerListenings as $key => &$listening) {
if (($listening->lastTrigger + $listening->deltaTime) <= $time) {
call_user_func(array($listening->listener, $listening->method), $time);
//Unregister one time Listening
if ($listening->oneTime == true) {
unset($this->timerListenings[$key]);
continue;
}
if ($listening->lastTrigger != -1) {
$listening->lastTrigger += $listening->deltaTime;
} else {
//Initial Time Initialize (self increment needed to improve accuracy)
$listening->lastTrigger = microtime(true);
}
2014-01-30 22:35:32 +01:00
}
}
}
}