/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Chukong Aipu reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/**
* @module cc
*/
//data structures
/*
* A list double-linked list used for "updates with priority"
* @class ListEntry
* @param {ListEntry} prev
* @param {ListEntry} next
* @param {function} callback
* @param {Object} target not retained (retained by hashUpdateEntry)
* @param {Number} priority
* @param {Boolean} paused
* @param {Boolean} markedForDeletion selector will no longer be called and entry will be removed at end of the next tick
*/
var ListEntry = function (prev, next, callback, target, priority, paused, markedForDeletion) {
this.prev = prev;
this.next = next;
this.callback = callback;
this.target = target;
this.priority = priority;
this.paused = paused;
this.markedForDeletion = markedForDeletion;
};
ListEntry.prototype.trigger = function (dt) {
this.callback.call(this.target, dt);
};
/*
* A update entry list
* @class HashUpdateEntry
* @param {Array} list Which list does it belong to ?
* @param {ListEntry} entry entry in the list
* @param {Object} target hash key (retained)
* @param {function} callback
* @param {Array} hh
*/
var HashUpdateEntry = function (list, entry, target, callback, hh) {
this.list = list;
this.entry = entry;
this.target = target;
this.callback = callback;
this.hh = hh;
};
//
/*
* Hash Element used for "selectors with interval"
* @class HashTimerEntry
* @param {Array} timers
* @param {Object} target hash key (retained)
* @param {Number} timerIndex
* @param {Timer} currentTimer
* @param {Boolean} currentTimerSalvaged
* @param {Boolean} paused
* @param {Array} hh
*/
var HashTimerEntry = function (timers, target, timerIndex, currentTimer, currentTimerSalvaged, paused, hh) {
var _t = this;
_t.timers = timers;
_t.target = target;
_t.timerIndex = timerIndex;
_t.currentTimer = currentTimer;
_t.currentTimerSalvaged = currentTimerSalvaged;
_t.paused = paused;
_t.hh = hh;
};
/*
* Light weight timer.
* @class Timer
*/
var Timer = cc._Class.extend({
getInterval : function(){return this._interval;},
setInterval : function(interval){this._interval = interval;},
setupTimerWithInterval: function(seconds, repeat, delay){
this._elapsed = -1;
this._interval = seconds;
this._delay = delay;
this._useDelay = (this._delay > 0);
this._repeat = repeat;
this._runForever = (this._repeat === cc.macro.REPEAT_FOREVER);
},
trigger: function(){
return 0;
},
cancel: function(){
return 0;
},
ctor:function () {
this._scheduler = null;
this._elapsed = -1;
this._runForever = false;
this._useDelay = false;
this._timesExecuted = 0;
this._repeat = 0;
this._delay = 0;
this._interval = 0;
},
update:function (dt) {
if (this._elapsed === -1) {
this._elapsed = 0;
this._timesExecuted = 0;
} else {
this._elapsed += dt;
if (this._runForever && !this._useDelay) {//standard timer usage
if (this._elapsed >= this._interval) {
this.trigger();
this._elapsed = 0;
}
} else {//advanced usage
if (this._useDelay) {
if (this._elapsed >= this._delay) {
this.trigger();
this._elapsed -= this._delay;
this._timesExecuted += 1;
this._useDelay = false;
}
} else {
if (this._elapsed >= this._interval) {
this.trigger();
this._elapsed = 0;
this._timesExecuted += 1;
}
}
if (!this._runForever && this._timesExecuted > this._repeat)
this.cancel();
}
}
}
});
var TimerTargetSelector = Timer.extend({
ctor: function(){
this._target = null;
this._selector = null;
},
initWithSelector: function(scheduler, target, selector, seconds, repeat, delay){
this._scheduler = scheduler;
this._target = target;
this._selector = selector;
this.setupTimerWithInterval(seconds, repeat, delay);
return true;
},
getSelector: function(){
return this._selector;
},
trigger: function(){
//override
if (this._selector && this._target){
this._selector.call(this._target, this._elapsed);
}
},
cancel: function(){
//override
this._scheduler.unschedule(this._selector, this._target);
}
});
var getTargetId = function (target) {
return target.__instanceId || target.uuid;
};
/**
* !#en
* Scheduler is responsible of triggering the scheduled callbacks.
* You should not use NSTimer. Instead use this class.
*
* There are 2 different types of callbacks (selectors):
* - update callback: the 'update' callback will be called every frame. You can customize the priority.
* - custom callback: A custom callback will be called every frame, or with a custom interval of time
*
* The 'custom selectors' should be avoided when possible. It is faster,
* and consumes less memory to use the 'update callback'. *
* !#zh
* Scheduler 是负责触发回调函数的类。
* 通常情况下,建议使用 cc.director.getScheduler() 来获取系统定时器。
* 有两种不同类型的定时器:
* - update 定时器:每一帧都会触发。您可以自定义优先级。
* - 自定义定时器:自定义定时器可以每一帧或者自定义的时间间隔触发。
* 如果希望每帧都触发,应该使用 update 定时器,使用 update 定时器更快,而且消耗更少的内存。
*
* @class Scheduler
*/
cc.Scheduler = cc._Class.extend({
_timeScale:1.0,
//_updates : null, //_updates[0] list of priority < 0, _updates[1] list of priority == 0, _updates[2] list of priority > 0,
_updatesNegList: null,
_updates0List: null,
_updatesPosList: null,
_hashForTimers:null, //Used for "selectors with interval"
_arrayForTimers:null, //Speed up indexing
_hashForUpdates:null, // hash used to fetch quickly the list entries for pause,delete,etc
//_arrayForUpdates:null, //Speed up indexing
_currentTarget:null,
_currentTargetSalvaged:false,
_updateHashLocked:false, //If true unschedule will not remove anything from a hash. Elements will only be marked for deletion.
ctor:function () {
this._timeScale = 1.0;
this._updatesNegList = [];
this._updates0List = [];
this._updatesPosList = [];
this._hashForUpdates = {};
this._hashForTimers = {};
this._currentTarget = null;
this._currentTargetSalvaged = false;
this._updateHashLocked = false;
this._arrayForTimers = [];
//this._arrayForUpdates = [];
},
//-----------------------private method----------------------
_schedulePerFrame: function(callback, target, priority, paused){
var hashElement = this._hashForUpdates[getTargetId(target)];
if (hashElement && hashElement.entry){
// check if priority has changed
if (hashElement.entry.priority !== priority){
if (this._updateHashLocked){
cc.log("warning: you CANNOT change update priority in scheduled function");
hashElement.entry.markedForDeletion = false;
hashElement.entry.paused = paused;
return;
}else{
// will be added again outside if (hashElement).
this.unscheduleUpdate(target);
}
}else{
hashElement.entry.markedForDeletion = false;
hashElement.entry.paused = paused;
return;
}
}
// most of the updates are going to be 0, that's way there
// is an special list for updates with priority 0
if (priority === 0){
this._appendIn(this._updates0List, callback, target, paused);
}else if (priority < 0){
this._priorityIn(this._updatesNegList, callback, target, priority, paused);
}else{
// priority > 0
this._priorityIn(this._updatesPosList, callback, target, priority, paused);
}
},
_removeHashElement:function (element) {
delete this._hashForTimers[getTargetId(element.target)];
cc.js.array.remove(this._arrayForTimers, element);
element.Timer = null;
element.target = null;
element = null;
},
_removeUpdateFromHash:function (entry) {
var self = this, element = self._hashForUpdates[getTargetId(entry.target)];
if (element) {
//list entry
cc.js.array.remove(element.list, element.entry);
delete self._hashForUpdates[getTargetId(element.target)];
//cc.js.array.remove(self._hashForUpdates, element);
element.entry = null;
//hash entry
element.target = null;
}
},
_priorityIn:function (ppList, callback, target, priority, paused) {
var self = this,
listElement = new ListEntry(null, null, callback, target, priority, paused, false);
// empey list ?
if (!ppList) {
ppList = [];
ppList.push(listElement);
} else {
var index2Insert = ppList.length - 1;
for(var i = 0; i <= index2Insert; i++){
if (priority < ppList[i].priority) {
index2Insert = i;
break;
}
}
ppList.splice(i, 0, listElement);
}
//update hash entry for quick access
self._hashForUpdates[getTargetId(target)] = new HashUpdateEntry(ppList, listElement, target, null);
return ppList;
},
_appendIn:function (ppList, callback, target, paused) {
var self = this, listElement = new ListEntry(null, null, callback, target, 0, paused, false);
ppList.push(listElement);
//update hash entry for quicker access
self._hashForUpdates[getTargetId(target)] = new HashUpdateEntry(ppList, listElement, target, null, null);
},
//-----------------------public method-------------------------
/**
* !#en
* Modifies the time of all scheduled callbacks.
* You can use this property to create a 'slow motion' or 'fast forward' effect.
* Default is 1.0. To create a 'slow motion' effect, use values below 1.0.
* To create a 'fast forward' effect, use values higher than 1.0.
* Note:It will affect EVERY scheduled selector / action.
* !#zh
* 设置时间间隔的缩放比例。
* 您可以使用这个方法来创建一个 “slow motion(慢动作)” 或 “fast forward(快进)” 的效果。
* 默认是 1.0。要创建一个 “slow motion(慢动作)” 效果,使用值低于 1.0。
* 要使用 “fast forward(快进)” 效果,使用值大于 1.0。
* 注意:它影响该 Scheduler 下管理的所有定时器。
* @method setTimeScale
* @param {Number} timeScale
*/
setTimeScale:function (timeScale) {
this._timeScale = timeScale;
},
/**
* !#en Returns time scale of scheduler.
* !#zh 获取时间间隔的缩放比例。
* @method getTimeScale
* @return {Number}
*/
getTimeScale:function () {
return this._timeScale;
},
/**
* !#en 'update' the scheduler. (You should NEVER call this method, unless you know what you are doing.)
* !#zh update 调度函数。(不应该直接调用这个方法,除非完全了解这么做的结果)
* @method update
* @param {Number} dt delta time
*/
update:function (dt) {
this._updateHashLocked = true;
if(this._timeScale !== 1)
dt *= this._timeScale;
var i, list, len, entry;
for(i=0,list=this._updatesNegList, len = list.length; i
* If 'interval' is 0, it will be called every frame, but if so, it recommended to use 'scheduleUpdateForTarget:' instead.
* If the callback function is already scheduled, then only the interval parameter will be updated without re-scheduling it again.
* repeat let the action be repeated repeat + 1 times, use cc.macro.REPEAT_FOREVER to let the action run continuously
* delay is the amount of time the action will wait before it'll start
*