forked from 0ad/0ad
Ykkrosh
4e5c5e2d8f
Use HFSM for unit AI. Support queuing orders. Automatically attack back when attacked. Automatically gather from farms after building them. This was SVN commit r7775.
73 lines
1.8 KiB
JavaScript
73 lines
1.8 KiB
JavaScript
function Timer() {}
|
|
|
|
Timer.prototype.Schema =
|
|
"<a:component type='system'/><empty/>";
|
|
|
|
Timer.prototype.Init = function()
|
|
{
|
|
this.id = 0;
|
|
this.time = 0;
|
|
this.timers = {};
|
|
};
|
|
|
|
Timer.prototype.GetTime = function()
|
|
{
|
|
return this.time;
|
|
}
|
|
|
|
Timer.prototype.OnUpdate = function(msg)
|
|
{
|
|
var dt = Math.round(msg.turnLength * 1000);
|
|
this.time += dt;
|
|
|
|
// Collect the timers that need to run
|
|
// (We do this in two stages to avoid deleting from the timer list while
|
|
// we're in the middle of iterating through it)
|
|
var run = [];
|
|
for (var id in this.timers)
|
|
{
|
|
if (this.timers[id][3] <= this.time)
|
|
run.push(id);
|
|
}
|
|
for each (var id in run)
|
|
{
|
|
var t = this.timers[id];
|
|
if (!t)
|
|
continue; // an earlier timer might have cancelled this one, so skip it
|
|
|
|
var cmp = Engine.QueryInterface(t[0], t[1]);
|
|
if (!cmp)
|
|
continue; // the entity was probably destroyed
|
|
|
|
try {
|
|
var lateness = this.time - t[3];
|
|
cmp[t[2]](t[4], lateness);
|
|
} catch (e) {
|
|
var stack = e.stack.trimRight().replace(/^/mg, ' '); // indent the stack trace
|
|
error("Error in timer on entity "+t[0]+", IID "+t[1]+", function "+t[2]+": "+e+"\n"+stack+"\n");
|
|
}
|
|
delete this.timers[id];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Create a new timer, which will call the 'funcname' method with arguments (data, lateness)
|
|
* on the 'iid' component of the 'ent' entity, after at least 'time' milliseconds.
|
|
* 'lateness' is how late the timer is executed after the specified time (in milliseconds).
|
|
* Returns a non-zero id that can be passed to CancelTimer.
|
|
*/
|
|
Timer.prototype.SetTimeout = function(ent, iid, funcname, time, data)
|
|
{
|
|
var id = ++this.id;
|
|
this.timers[id] = [ent, iid, funcname, this.time + time, data];
|
|
return id;
|
|
};
|
|
|
|
Timer.prototype.CancelTimer = function(id)
|
|
{
|
|
delete this.timers[id];
|
|
};
|
|
|
|
Engine.RegisterComponentType(IID_Timer, "Timer", Timer);
|
|
|