1 /****************************************************************************
  2  Copyright (c) 2008-2010 Ricardo Quesada
  3  Copyright (c) 2011-2012 cocos2d-x.org
  4  Copyright (c) 2013-2014 Chukong Technologies Inc.
  5 
  6  http://www.cocos2d-x.org
  7 
  8  Permission is hereby granted, free of charge, to any person obtaining a copy
  9  of this software and associated documentation files (the "Software"), to deal
 10  in the Software without restriction, including without limitation the rights
 11  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 12  copies of the Software, and to permit persons to whom the Software is
 13  furnished to do so, subject to the following conditions:
 14 
 15  The above copyright notice and this permission notice shall be included in
 16  all copies or substantial portions of the Software.
 17 
 18  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 19  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 20  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 21  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 22  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 23  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 24  THE SOFTWARE.
 25  ****************************************************************************/
 26 
 27 /**
 28  * @class
 29  * @extends cc.Class
 30  * @example
 31  * var element = new cc.HashElement();
 32  */
 33 cc.HashElement = cc.Class.extend(/** @lends cc.HashElement# */{
 34     actions:null,
 35     target:null, //ccobject
 36     actionIndex:0,
 37     currentAction:null, //CCAction
 38     currentActionSalvaged:false,
 39     paused:false,
 40     hh:null, //ut hash handle
 41     /**
 42      * Constructor
 43      */
 44     ctor:function () {
 45         this.actions = [];
 46         this.target = null;
 47         this.actionIndex = 0;
 48         this.currentAction = null; //CCAction
 49         this.currentActionSalvaged = false;
 50         this.paused = false;
 51         this.hh = null; //ut hash handle
 52     }
 53 });
 54 
 55 /**
 56  * cc.ActionManager is a class that can manage actions.<br/>
 57  * Normally you won't need to use this class directly. 99% of the cases you will use the CCNode interface,
 58  * which uses this class's singleton object.
 59  * But there are some cases where you might need to use this class. <br/>
 60  * Examples:<br/>
 61  * - When you want to run an action where the target is different from a CCNode.<br/>
 62  * - When you want to pause / resume the actions<br/>
 63  * @class
 64  * @extends cc.Class
 65  * @example
 66  * var mng = new cc.ActionManager();
 67  */
 68 cc.ActionManager = cc.Class.extend(/** @lends cc.ActionManager# */{
 69     _hashTargets:null,
 70     _arrayTargets:null,
 71     _currentTarget:null,
 72     _currentTargetSalvaged:false,
 73 
 74     _searchElementByTarget:function (arr, target) {
 75         for (var k = 0; k < arr.length; k++) {
 76             if (target === arr[k].target)
 77                 return arr[k];
 78         }
 79         return null;
 80     },
 81 
 82     ctor:function () {
 83         this._hashTargets = {};
 84         this._arrayTargets = [];
 85         this._currentTarget = null;
 86         this._currentTargetSalvaged = false;
 87     },
 88 
 89     /** Adds an action with a target.
 90      * If the target is already present, then the action will be added to the existing target.
 91      * If the target is not present, a new instance of this target will be created either paused or not, and the action will be added to the newly created target.
 92      * When the target is paused, the queued actions won't be 'ticked'.
 93      * @param {cc.Action} action
 94      * @param {cc.Node} target
 95      * @param {Boolean} paused
 96      */
 97     addAction:function (action, target, paused) {
 98         if(!action)
 99             throw new Error("cc.ActionManager.addAction(): action must be non-null");
100         if(!target)
101             throw new Error("cc.ActionManager.addAction(): action must be non-null");
102 
103         //check if the action target already exists
104         var element = this._hashTargets[target.__instanceId];
105         //if doesn't exists, create a hashelement and push in mpTargets
106         if (!element) {
107             element = new cc.HashElement();
108             element.paused = paused;
109             element.target = target;
110             this._hashTargets[target.__instanceId] = element;
111             this._arrayTargets.push(element);
112         }
113         //creates a array for that eleemnt to hold the actions
114         this._actionAllocWithHashElement(element);
115 
116         element.actions.push(action);
117         action.startWithTarget(target);
118     },
119 
120     /**
121      * Removes all actions from all the targets.
122      */
123     removeAllActions:function () {
124         var locTargets = this._arrayTargets;
125         for (var i = 0; i < locTargets.length; i++) {
126             var element = locTargets[i];
127             if (element)
128                 this.removeAllActionsFromTarget(element.target, true);
129         }
130     },
131     /** Removes all actions from a certain target. <br/>
132      * All the actions that belongs to the target will be removed.
133      * @param {object} target
134      * @param {boolean} forceDelete
135      */
136     removeAllActionsFromTarget:function (target, forceDelete) {
137         // explicit null handling
138         if (target == null)
139             return;
140         var element = this._hashTargets[target.__instanceId];
141         if (element) {
142             if (element.actions.indexOf(element.currentAction) !== -1 && !(element.currentActionSalvaged))
143                 element.currentActionSalvaged = true;
144 
145             element.actions.length = 0;
146             if (this._currentTarget === element && !forceDelete) {
147                 this._currentTargetSalvaged = true;
148             } else {
149                 this._deleteHashElement(element);
150             }
151         }
152     },
153     /** Removes an action given an action reference.
154      * @param {cc.Action} action
155      */
156     removeAction:function (action) {
157         // explicit null handling
158         if (action == null)
159             return;
160         var target = action.getOriginalTarget();
161         var element = this._hashTargets[target.__instanceId];
162 
163         if (element) {
164             for (var i = 0; i < element.actions.length; i++) {
165                 if (element.actions[i] === action) {
166                     element.actions.splice(i, 1);
167                     break;
168                 }
169             }
170         } else {
171             cc.log(cc._LogInfos.ActionManager_removeAction);
172         }
173     },
174 
175     /** Removes an action given its tag and the target
176      * @param {Number} tag
177      * @param {object} target
178      */
179     removeActionByTag:function (tag, target) {
180         if(tag === cc.ACTION_TAG_INVALID)
181             cc.log(cc._LogInfos.ActionManager_addAction);
182 
183         cc.assert(target, cc._LogInfos.ActionManager_addAction);
184 
185         var element = this._hashTargets[target.__instanceId];
186 
187         if (element) {
188             var limit = element.actions.length;
189             for (var i = 0; i < limit; ++i) {
190                 var action = element.actions[i];
191                 if (action && action.getTag() === tag && action.getOriginalTarget() === target) {
192                     this._removeActionAtIndex(i, element);
193                     break;
194                 }
195             }
196         }
197     },
198 
199     /** Gets an action given its tag an a target
200      * @param {Number} tag
201      * @param {object} target
202      * @return {cc.Action|Null}  return the Action with the given tag on success
203      */
204     getActionByTag:function (tag, target) {
205         if(tag === cc.ACTION_TAG_INVALID)
206             cc.log(cc._LogInfos.ActionManager_getActionByTag);
207 
208         var element = this._hashTargets[target.__instanceId];
209         if (element) {
210             if (element.actions != null) {
211                 for (var i = 0; i < element.actions.length; ++i) {
212                     var action = element.actions[i];
213                     if (action && action.getTag() === tag)
214                         return action;
215                 }
216             }
217             cc.log(cc._LogInfos.ActionManager_getActionByTag_2, tag);
218         }
219         return null;
220     },
221 
222 
223     /** Returns the numbers of actions that are running in a certain target. <br/>
224      * Composable actions are counted as 1 action. <br/>
225      * Example: <br/>
226      * - If you are running 1 Sequence of 7 actions, it will return 1. <br/>
227      * - If you are running 7 Sequences of 2 actions, it will return 7.
228      * @param {object} target
229      * @return {Number}
230      */
231     numberOfRunningActionsInTarget:function (target) {
232         var element = this._hashTargets[target.__instanceId];
233         if (element)
234             return (element.actions) ? element.actions.length : 0;
235 
236         return 0;
237     },
238     /** Pauses the target: all running actions and newly added actions will be paused.
239      * @param {object} target
240      */
241     pauseTarget:function (target) {
242         var element = this._hashTargets[target.__instanceId];
243         if (element)
244             element.paused = true;
245     },
246     /** Resumes the target. All queued actions will be resumed.
247      * @param {object} target
248      */
249     resumeTarget:function (target) {
250         var element = this._hashTargets[target.__instanceId];
251         if (element)
252             element.paused = false;
253     },
254 
255     /**
256      * Pauses all running actions, returning a list of targets whose actions were paused.
257      * @return {Array}  a list of targets whose actions were paused.
258      */
259     pauseAllRunningActions:function(){
260         var idsWithActions = [];
261         var locTargets = this._arrayTargets;
262         for(var i = 0; i< locTargets.length; i++){
263             var element = locTargets[i];
264             if(element && !element.paused){
265                 element.paused = true;
266                 idsWithActions.push(element.target);
267             }
268         }
269         return idsWithActions;
270     },
271 
272     /**
273      * Resume a set of targets (convenience function to reverse a pauseAllRunningActions call)
274      * @param {Array} targetsToResume
275      */
276     resumeTargets:function(targetsToResume){
277         if(!targetsToResume)
278             return;
279 
280         for(var i = 0 ; i< targetsToResume.length; i++){
281             if(targetsToResume[i])
282                 this.resumeTarget(targetsToResume[i]);
283         }
284     },
285 
286     /** purges the shared action manager. It releases the retained instance. <br/>
287      * because it uses this, so it can not be static
288      */
289     purgeSharedManager:function () {
290         cc.director.getScheduler().unscheduleUpdate(this);
291     },
292 
293     //protected
294     _removeActionAtIndex:function (index, element) {
295         var action = element.actions[index];
296 
297         if ((action === element.currentAction) && (!element.currentActionSalvaged))
298             element.currentActionSalvaged = true;
299 
300         element.actions.splice(index, 1);
301 
302         // update actionIndex in case we are in tick. looping over the actions
303         if (element.actionIndex >= index)
304             element.actionIndex--;
305 
306         if (element.actions.length === 0) {
307             if (this._currentTarget === element) {
308                 this._currentTargetSalvaged = true;
309             } else {
310                 this._deleteHashElement(element);
311             }
312         }
313     },
314 
315     _deleteHashElement:function (element) {
316         var ret = false;
317         if (element) {
318             if(this._hashTargets[element.target.__instanceId]){
319                 delete this._hashTargets[element.target.__instanceId];
320                 cc.arrayRemoveObject(this._arrayTargets, element);
321                 ret = true;
322             }
323             element.actions = null;
324             element.target = null;
325         }
326         return ret;
327     },
328 
329     _actionAllocWithHashElement:function (element) {
330         // 4 actions per Node by default
331         if (element.actions == null) {
332             element.actions = [];
333         }
334     },
335 
336     /**
337      * @param {Number} dt delta time in seconds
338      */
339     update:function (dt) {
340         var locTargets = this._arrayTargets , locCurrTarget;
341         for (var elt = 0; elt < locTargets.length; elt++) {
342             this._currentTarget = locTargets[elt];
343             locCurrTarget = this._currentTarget;
344             //this._currentTargetSalvaged = false;
345             if (!locCurrTarget.paused) {
346                 // The 'actions' CCMutableArray may change while inside this loop.
347                 for (locCurrTarget.actionIndex = 0;
348                      locCurrTarget.actionIndex < (locCurrTarget.actions ? locCurrTarget.actions.length : 0);
349                      locCurrTarget.actionIndex++) {
350                     locCurrTarget.currentAction = locCurrTarget.actions[locCurrTarget.actionIndex];
351                     if (!locCurrTarget.currentAction)
352                         continue;
353 
354                     locCurrTarget.currentActionSalvaged = false;
355                     //use for speed
356                     locCurrTarget.currentAction.step(dt * ( locCurrTarget.currentAction._speedMethod ? locCurrTarget.currentAction._speed : 1 ) );
357                     if (locCurrTarget.currentActionSalvaged) {
358                         // The currentAction told the node to remove it. To prevent the action from
359                         // accidentally deallocating itself before finishing its step, we retained
360                         // it. Now that step is done, it's safe to release it.
361                         locCurrTarget.currentAction = null;//release
362                     } else if (locCurrTarget.currentAction.isDone()) {
363                         locCurrTarget.currentAction.stop();
364                         var action = locCurrTarget.currentAction;
365                         // Make currentAction nil to prevent removeAction from salvaging it.
366                         locCurrTarget.currentAction = null;
367                         this.removeAction(action);
368                     }
369 
370                     locCurrTarget.currentAction = null;
371                 }
372             }
373 
374             // elt, at this moment, is still valid
375             // so it is safe to ask this here (issue #490)
376 
377             // only delete currentTarget if no actions were scheduled during the cycle (issue #481)
378             if (this._currentTargetSalvaged && locCurrTarget.actions.length === 0) {
379                 this._deleteHashElement(locCurrTarget) && elt--;
380             }
381         }
382     }
383 });
384