Merge pull request #1502 from jareguo/master

重构组件生命周期方法调用
This commit is contained in:
Jare Guo
2017-02-17 18:17:33 +08:00
committed by GitHub
22 changed files with 575 additions and 450 deletions
+15 -23
View File
@@ -27,6 +27,7 @@
var EventTarget = require('./event/event-target');
var Class = require('./platform/_CCClass');
var AutoReleaseUtils = require('./load-pipeline/auto-release-utils');
var ComponentScheduler = require('./component-scheduler');
cc.g_NumberOfDraws = 0;
@@ -140,6 +141,8 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
// Scheduler for user registration update
self._scheduler = null;
// Scheduler for life-cycle methods in component
self._compScheduler = null;
// Action manager
self._actionManager = null;
@@ -180,6 +183,8 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
* All platform independent init process should be occupied here.
*/
sharedInit: function () {
this._compScheduler = new ComponentScheduler();
// Animation manager
if (cc.AnimationManager) {
this._animationManager = new cc.AnimationManager();
@@ -414,6 +419,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
purgeDirector: function () {
//cleanup scheduler
this.getScheduler().unscheduleAll();
this._compScheduler.unscheduleAll();
// Disable event dispatching
if (cc.eventManager)
@@ -1256,24 +1262,6 @@ cc.Director.EVENT_AFTER_SCENE_LAUNCH = "director_after_scene_launch";
*/
cc.Director.EVENT_BEFORE_UPDATE = "director_before_update";
/**
* !#en The event which will be triggered after components update.
* !#zh 组件 “update” 时所触发的事件。
* @event cc.Director.EVENT_COMPONENT_UPDATE
* @param {Event} event
* @param {Vec2} event.detail - The delta time from last frame
*/
cc.Director.EVENT_COMPONENT_UPDATE = "director_component_update";
/**
* !#en The event which will be triggered after components late update.
* !#zh 组件 “late update” 时所触发的事件。
* @event cc.Director.EVENT_COMPONENT_LATE_UPDATE
* @param {Event} event
* @param {Vec2} event.detail - The delta time from last frame
*/
cc.Director.EVENT_COMPONENT_LATE_UPDATE = "director_component_late_update";
/**
* !#en The event which will be triggered after engine and components update logic.
* !#zh 将在引擎和组件 “update” 逻辑之后所触发的事件。
@@ -1328,13 +1316,16 @@ cc.DisplayLinkDirector = cc.Director.extend(/** @lends cc.Director# */{
mainLoop: CC_EDITOR ? function (deltaTime, updateAnimate) {
if (!this._paused) {
this.emit(cc.Director.EVENT_BEFORE_UPDATE);
this.emit(cc.Director.EVENT_COMPONENT_UPDATE, deltaTime);
this._compScheduler.startPhase();
this._compScheduler.updatePhase(deltaTime);
if (updateAnimate) {
this._scheduler.update(deltaTime);
}
this.emit(cc.Director.EVENT_COMPONENT_LATE_UPDATE, deltaTime);
this._compScheduler.lateUpdatePhase(deltaTime);
this.emit(cc.Director.EVENT_AFTER_UPDATE);
}
@@ -1362,14 +1353,15 @@ cc.DisplayLinkDirector = cc.Director.extend(/** @lends cc.Director# */{
this.calculateDeltaTime();
if (!this._paused) {
// Call start for new added components
this.emit(cc.Director.EVENT_BEFORE_UPDATE);
// Call start for new added components
this._compScheduler.startPhase();
// Update for components
this.emit(cc.Director.EVENT_COMPONENT_UPDATE, this._deltaTime);
this._compScheduler.updatePhase(this._deltaTime);
// Engine update with scheduler
this._scheduler.update(this._deltaTime);
// Late update for components
this.emit(cc.Director.EVENT_COMPONENT_LATE_UPDATE, this._deltaTime);
this._compScheduler.lateUpdatePhase(this._deltaTime);
// User can use this event to do things after update
this.emit(cc.Director.EVENT_AFTER_UPDATE);
// Destroy entities that have been removed recently
+1 -1
View File
@@ -1,5 +1,5 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos.com
+1 -4
View File
@@ -444,10 +444,7 @@ var widgetManager = cc._widgetManager = module.exports = {
},
remove: function (widget) {
widget.node._widget = null;
var index = activeWidgets.indexOf(widget);
if (index > -1) {
this._activeWidgetsIterator.removeAt(index);
}
this._activeWidgetsIterator.remove(widget);
if (CC_EDITOR && !cc.engine.isPlaying) {
widget.node.off('position-changed', adjustWidgetToAllowMovingInEditor, widget);
widget.node.off('size-changed', adjustWidgetToAllowResizingInEditor, widget);
+373
View File
@@ -0,0 +1,373 @@
/****************************************************************************
Copyright (c) 2013-2017 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.
****************************************************************************/
require('./platform/CCClass');
var CCObject = require('./platform/CCObject');
var JsArray = require('./platform/js').array;
var Flags = CCObject.Flags;
var IsStartCalled = Flags.IsStartCalled;
var IsOnEnableCalled = Flags.IsOnEnableCalled;
var IsEditorOnEnableCalled = Flags.IsEditorOnEnableCalled;
var IsPreloadCalled = Flags.IsPreloadCalled;
var IsOnLoadStarted = Flags.IsOnLoadStarted;
var IsOnLoadCalled = Flags.IsOnLoadCalled;
var callerFunctor;
if (CC_EDITOR) {
callerFunctor = require('./utils/misc').tryCatchFunctor_EDITOR;
}
var callPreloadInTryCatch = CC_EDITOR && callerFunctor('__preload');
var callOnLoadInTryCatch = CC_EDITOR && callerFunctor('onLoad');
var callOnEnableInTryCatch = CC_EDITOR && callerFunctor('onEnable');
var callStartInTryCatch = CC_EDITOR && callerFunctor('start');
var callUpdateInTryCatch = CC_EDITOR && callerFunctor('update', 'dt', 'dt');
var callLateUpdateInTryCatch = CC_EDITOR && callerFunctor('lateUpdate', 'dt', 'dt');
var callOnDisableInTryCatch = CC_EDITOR && callerFunctor('onDisable');
var callOnDestroyInTryCatch = CC_EDITOR && callerFunctor('onDestroy');
var callResetInTryCatch = CC_EDITOR && callerFunctor('resetInEditor');
var callOnFocusInTryCatch = CC_EDITOR && callerFunctor('onFocusInEditor');
var callOnLostFocusInTryCatch = CC_EDITOR && callerFunctor('onLostFocusInEditor');
function preloadNode (node) {
// set _activeInHierarchy to true before invoking onLoad
// to allow preload triggered on nodes which created in parent's onLoad dynamically.
node._activeInHierarchy = true;
var comps = node._components;
var i = 0, len = comps.length;
for (; i < len; ++i) {
var comp = comps[i];
if (comp && !(comp._objFlags & IsPreloadCalled) && typeof comp.__preload === 'function') {
if (CC_EDITOR) {
callPreloadInTryCatch(comp);
}
else {
comp.__preload();
}
comp._objFlags |= IsPreloadCalled;
}
}
var children = node._children;
for (i = 0, len = children.length; i < len; ++i) {
var child = children[i];
if (child._active) {
preloadNode(child);
}
}
}
function ctor () {
// during a loop
this._updating = false;
// component lists
this.startsZero = new JsArray.MutableForwardIterator([]); // components which priority === 0 (default)
// this.startsPos = []; // components which priority > 0
// this.startsNeg = []; // components which priority < 0
this.updatesZero = new JsArray.MutableForwardIterator([]);
this.lateUpdatesZero = new JsArray.MutableForwardIterator([]);
this.scheduleInNextFrame = []; // components deferred to next frame
}
/**
* The Manager for Component's life-cycle methods.
*/
var ComponentScheduler = cc.Class({
ctor: ctor,
unscheduleAll: ctor,
enableComp: CC_EDITOR ? function (comp) {
if (cc.engine.isPlaying || comp.constructor._executeInEditMode) {
if (!(comp._objFlags & IsOnEnableCalled)) {
if (comp.onEnable) {
callOnEnableInTryCatch(comp);
var deactivatedDuringOnEnable = !comp.node._activeInHierarchy;
if (deactivatedDuringOnEnable) {
return;
}
}
cc.director.getScheduler().resumeTarget(comp);
this.schedule(comp);
comp._objFlags |= IsOnEnableCalled;
}
}
if (!(comp._objFlags & IsEditorOnEnableCalled)) {
cc.engine.emit('component-enabled', comp.uuid);
comp._objFlags |= IsEditorOnEnableCalled;
}
} : function (comp) {
if (!(comp._objFlags & IsOnEnableCalled)) {
if (comp.onEnable) {
comp.onEnable();
var deactivatedDuringOnEnable = !comp.node._activeInHierarchy;
if (deactivatedDuringOnEnable) {
return;
}
}
cc.director.getScheduler().resumeTarget(comp);
this.schedule(comp);
comp._objFlags |= IsOnEnableCalled;
}
},
disableComp: CC_EDITOR ? function (comp) {
if (cc.engine.isPlaying || comp.constructor._executeInEditMode) {
if (comp._objFlags & IsOnEnableCalled) {
if (comp.onDisable) {
callOnDisableInTryCatch(comp);
}
cc.director.getScheduler().pauseTarget(comp);
this.unschedule(comp);
comp._objFlags &= ~IsOnEnableCalled;
}
}
if (comp._objFlags & IsEditorOnEnableCalled) {
cc.engine.emit('component-disabled', comp.uuid);
comp._objFlags &= ~IsEditorOnEnableCalled;
}
} : function (comp) {
if (comp._objFlags & IsOnEnableCalled) {
if (comp.onDisable) {
comp.onDisable();
}
cc.director.getScheduler().pauseTarget(comp);
this.unschedule(comp);
comp._objFlags &= ~IsOnEnableCalled;
}
},
preloadNode: preloadNode,
doPreloadComp: CC_EDITOR ? function (comp) {
callPreloadInTryCatch(comp);
comp._objFlags |= IsPreloadCalled;
} : function (comp) {
comp.__preload();
comp._objFlags |= IsPreloadCalled;
},
activateComp: CC_EDITOR ? function (comp) {
if (!(comp._objFlags & IsOnLoadStarted) &&
(cc.engine._isPlaying || comp.constructor._executeInEditMode)) {
comp._objFlags |= IsOnLoadStarted;
if (comp.onLoad) {
callOnLoadInTryCatch(comp);
}
comp._objFlags |= IsOnLoadCalled;
if (comp.onLoad && !cc.engine._isPlaying) {
var focused = Editor.Selection.curActivate('node') === comp.node.uuid;
if (focused && comp.onFocusInEditor) {
callOnFocusInTryCatch(comp);
}
else if (comp.onLostFocusInEditor) {
callOnLostFocusInTryCatch(comp);
}
}
if ( !CC_TEST ) {
_Scene.AssetsWatcher.start(comp);
}
}
if (comp._enabled) {
var deactivatedOnLoading = !comp.node._activeInHierarchy;
if (deactivatedOnLoading) {
return;
}
this.enableComp(comp);
}
} : function (comp) {
if (!(comp._objFlags & IsOnLoadStarted)) {
comp._objFlags |= IsOnLoadStarted;
if (comp.onLoad) {
comp.onLoad();
}
comp._objFlags |= IsOnLoadCalled;
}
if (comp._enabled) {
var deactivatedOnLoading = !comp.node._activeInHierarchy;
if (deactivatedOnLoading) {
return;
}
this.enableComp(comp);
}
},
destroyComp: CC_EDITOR ? function (comp) {
// ensure onDisable called
this.disableComp(comp);
if (comp.onDestroy && (comp._objFlags & IsOnLoadCalled)) {
if (cc.engine._isPlaying || comp.constructor._executeInEditMode) {
callOnDestroyInTryCatch(comp);
}
}
} : function (comp) {
// ensure onDisable called
this.disableComp(comp);
if (comp.onDestroy && (comp._objFlags & IsOnLoadCalled)) {
comp.onDestroy();
}
},
resetComp: CC_EDITOR && function (comp) {
if (typeof comp.resetInEditor === 'function') {
callResetInTryCatch(comp);
}
},
schedule (comp) {
if (this._updating) {
this.scheduleInNextFrame.push(comp);
return;
}
this._scheduleImmediate(comp);
},
unschedule (comp) {
// cancel schedule task
var index = this.scheduleInNextFrame.indexOf(comp);
if (index >= 0) {
JsArray.fastRemoveAt(this.scheduleInNextFrame, index);
return;
}
// unschedule
if (comp.start && !(comp._objFlags & IsStartCalled)) {
this.startsZero.fastRemove(comp);
}
if (comp.update) {
this.updatesZero.fastRemove(comp);
}
if (comp.lateUpdate) {
this.lateUpdatesZero.fastRemove(comp);
}
},
_scheduleImmediate (comp) {
if (comp.start && !(comp._objFlags & IsStartCalled)) {
this.startsZero.array.push(comp);
}
if (comp.update) {
this.updatesZero.array.push(comp);
}
if (comp.lateUpdate) {
this.lateUpdatesZero.array.push(comp);
}
},
_deferredSchedule () {
var comps = this.scheduleInNextFrame;
for (var i = 0, len = comps.length; i < len; i++) {
var comp = comps[i];
this._scheduleImmediate(comp);
}
comps.length = 0;
},
startPhase () {
// Start of this frame
this._updating = true;
if (this.scheduleInNextFrame.length > 0) {
this._deferredSchedule();
}
// call start
var iterator = this.startsZero;
var array = iterator.array;
if (CC_EDITOR) {
for (iterator.i = 0; iterator.i < array.length; ++iterator.i) {
let comp = array[iterator.i];
callStartInTryCatch(comp);
comp._objFlags |= IsStartCalled;
}
}
else {
for (iterator.i = 0; iterator.i < array.length; ++iterator.i) {
let comp = array[iterator.i];
comp.start();
comp._objFlags |= IsStartCalled;
}
}
array.length = 0;
},
updatePhase (dt) {
// call update
var iterator = this.updatesZero;
var array = iterator.array;
if (CC_EDITOR) {
for (iterator.i = 0; iterator.i < array.length; ++iterator.i) {
let comp = array[iterator.i];
callUpdateInTryCatch(comp, dt);
}
}
else {
for (iterator.i = 0; iterator.i < array.length; ++iterator.i) {
let comp = array[iterator.i];
comp.update(dt);
}
}
},
lateUpdatePhase (dt) {
// call lateUpdate
var iterator = this.lateUpdatesZero;
var array = iterator.array;
if (CC_EDITOR) {
for (iterator.i = 0; iterator.i < array.length; ++iterator.i) {
let comp = array[iterator.i];
callLateUpdateInTryCatch(comp, dt);
}
}
else {
for (iterator.i = 0; iterator.i < array.length; ++iterator.i) {
let comp = array[iterator.i];
comp.lateUpdate(dt);
}
}
// End of this frame
this._updating = false;
}
});
module.exports = ComponentScheduler;
+19 -308
View File
@@ -1,5 +1,5 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2013-2017 Chukong Technologies Inc.
http://www.cocos.com
@@ -23,216 +23,11 @@
THE SOFTWARE.
****************************************************************************/
require('../platform/CCObject');
require('../CCNode');
var CCObject = require('../platform/CCObject');
var idGenerater = new (require('../platform/id-generater'))('Comp');
var Flags = cc.Object.Flags;
var IsOnEnableCalled = Flags.IsOnEnableCalled;
var IsEditorOnEnableCalled = Flags.IsEditorOnEnableCalled;
var IsPreloadCalled = Flags.IsPreloadCalled;
var IsOnLoadStarted = Flags.IsOnLoadStarted;
var IsOnLoadCalled = Flags.IsOnLoadCalled;
var IsStartCalled = Flags.IsStartCalled;
var callPreloadInTryCatch;
var callOnLoadInTryCatch;
var callOnEnableInTryCatch;
var callStartInTryCatch;
var callOnDisableInTryCatch;
var callOnDestroyInTryCatch;
var callOnFocusInTryCatch;
var callOnLostFocusInTryCatch;
var callResetInTryCatch;
if (CC_EDITOR) {
// yes we use assignment expression here to avoid callerFunctor still being hoisted without CC_EDITOR
var callerFunctor = function (funcName) {
function call_FUNC_InTryCatch (comp) {
try {
comp._FUNC_();
}
catch (e) {
cc._throw(e);
}
}
return eval(('(' + call_FUNC_InTryCatch + ')').replace(/_FUNC_/g, funcName));
};
callPreloadInTryCatch = callerFunctor('__preload');
callOnLoadInTryCatch = callerFunctor('onLoad');
callOnEnableInTryCatch = callerFunctor('onEnable');
callStartInTryCatch = callerFunctor('start');
callOnDisableInTryCatch = callerFunctor('onDisable');
callOnDestroyInTryCatch = callerFunctor('onDestroy');
callOnFocusInTryCatch = callerFunctor('onFocusInEditor');
callOnLostFocusInTryCatch = callerFunctor('onLostFocusInEditor');
callResetInTryCatch = callerFunctor('resetInEditor');
}
function callOnEnable (self, enable) {
if (!CC_EDITOR || (cc.engine.isPlaying || self.constructor._executeInEditMode) ) {
var enableCalled = self._objFlags & IsOnEnableCalled;
if (enable) {
if (!enableCalled) {
if (self.onEnable) {
if (CC_EDITOR) {
callOnEnableInTryCatch(self);
}
else {
self.onEnable();
}
}
var deactivatedDuringOnEnable = !self.node._activeInHierarchy;
if (deactivatedDuringOnEnable) {
return;
}
cc.director.getScheduler().resumeTarget(self);
_registerEvent(self);
self._objFlags |= IsOnEnableCalled;
}
}
else if (enableCalled) {
if (self.onDisable) {
if (CC_EDITOR) {
callOnDisableInTryCatch(self);
}
else {
self.onDisable();
}
}
cc.director.getScheduler().pauseTarget(self);
_unregisterEvent(self);
self._objFlags &= ~IsOnEnableCalled;
}
}
if (CC_EDITOR) {
if (enable) {
if ( !(self._objFlags & IsEditorOnEnableCalled) ) {
cc.engine.emit('component-enabled', self.uuid);
self._objFlags |= IsEditorOnEnableCalled;
}
}
else {
if (self._objFlags & IsEditorOnEnableCalled) {
cc.engine.emit('component-disabled', self.uuid);
self._objFlags &= ~IsEditorOnEnableCalled;
}
}
}
}
var Director = cc.Director;
function _registerEvent (self) {
if (CC_EDITOR && !(self.constructor._executeInEditMode || cc.engine._isPlaying)) {
return;
}
if (self.start && !(self._objFlags & IsStartCalled)) {
cc.director.__fastOn(Director.EVENT_BEFORE_UPDATE, _callStart, self, self.__eventTargets);
}
if (self.update || self.lateUpdate) {
cc.director.__fastOn(Director.EVENT_BEFORE_UPDATE, _registerUpdateEvent, self, self.__eventTargets);
}
}
function _unregisterEvent (self) {
if (CC_EDITOR && !(self.constructor._executeInEditMode || cc.engine._isPlaying)) {
return;
}
if (self.start && !(self._objFlags & IsStartCalled)) {
cc.director.__fastOff(Director.EVENT_BEFORE_UPDATE, _callStart, self, self.__eventTargets);
}
var hasUpdate = self.update;
var hasLateUpdate = self.lateUpdate;
if (hasUpdate || hasLateUpdate) {
cc.director.__fastOff(Director.EVENT_BEFORE_UPDATE, _registerUpdateEvent, self, self.__eventTargets);
if (hasUpdate) {
cc.director.__fastOff(Director.EVENT_COMPONENT_UPDATE, _callUpdate, self, self.__eventTargets);
}
if (hasLateUpdate) {
cc.director.__fastOff(Director.EVENT_COMPONENT_LATE_UPDATE, _callLateUpdate, self, self.__eventTargets);
}
}
}
function _registerUpdateEvent () {
var eventTargets = this.__eventTargets;
var director = cc.director;
director.__fastOff(Director.EVENT_BEFORE_UPDATE, _registerUpdateEvent, this, eventTargets);
if (this.update) {
director.__fastOn(Director.EVENT_COMPONENT_UPDATE, _callUpdate, this, eventTargets);
}
if (this.lateUpdate) {
director.__fastOn(Director.EVENT_COMPONENT_LATE_UPDATE, _callLateUpdate, this, eventTargets);
}
}
var _callStart = CC_EDITOR ? function () {
cc.director.__fastOff(Director.EVENT_BEFORE_UPDATE, _callStart, this, this.__eventTargets);
callStartInTryCatch(this);
this._objFlags |= IsStartCalled;
} : function () {
cc.director.__fastOff(Director.EVENT_BEFORE_UPDATE, _callStart, this, this.__eventTargets);
this.start();
this._objFlags |= IsStartCalled;
};
var _callUpdate = CC_EDITOR ? function (event) {
try {
this.update(event.detail);
}
catch (e) {
cc._throw(e);
}
} : function (event) {
this.update(event.detail);
};
var _callLateUpdate = CC_EDITOR ? function (event) {
try {
this.lateUpdate(event.detail);
}
catch (e) {
cc._throw(e);
}
} : function (event) {
this.lateUpdate(event.detail);
};
function _callPreloadOnNode (node) {
// set _activeInHierarchy to true before invoking onLoad
// to allow preload triggered on nodes which created in parent's onLoad dynamically.
node._activeInHierarchy = true;
var comps = node._components;
var i = 0, len = comps.length;
for (; i < len; ++i) {
var component = comps[i];
if (component && !(component._objFlags & IsPreloadCalled) && typeof component.__preload === 'function') {
if (CC_EDITOR) {
callPreloadInTryCatch(component);
}
else {
component.__preload();
}
component._objFlags |= IsPreloadCalled;
}
}
var children = node._children;
for (i = 0, len = children.length; i < len; ++i) {
var child = children[i];
if (child._active) {
_callPreloadOnNode(child);
}
}
}
var IsOnEnableCalled = CCObject.Flags.IsOnEnableCalled;
var IsOnLoadCalled = CCObject.Flags.IsOnLoadCalled;
/**
* !#en
@@ -250,7 +45,7 @@ function _callPreloadOnNode (node) {
*/
var Component = cc.Class({
name: 'cc.Component',
extends: cc.Object,
extends: CCObject,
ctor: CC_EDITOR ? function () {
if (window._Scene && _Scene.AssetsWatcher) {
@@ -382,7 +177,12 @@ var Component = cc.Class({
if (this._enabled !== value) {
this._enabled = value;
if (this.node._activeInHierarchy) {
callOnEnable(this, value);
if (value) {
cc.director._compScheduler.enableComp(this);
}
else {
cc.director._compScheduler.disableComp(this);
}
}
}
},
@@ -406,13 +206,13 @@ var Component = cc.Class({
},
/**
* !#en TODO
* !#zh onLoad 是否被调用。
* !#en Returns a value which used to indicate the onLoad get called or not.
* !#zh 返回一个值用来判断 onLoad 是否被调用过,不等于 0 时调用过,等于 0 时未调用。
* @property _isOnLoadCalled
* @type {Boolean}
* @type {Number}
* @readOnly
* @example
* cc.log(_isOnLoadCalled);
* cc.log(_isOnLoadCalled > 0);
*/
_isOnLoadCalled: {
get: function () {
@@ -654,74 +454,18 @@ var Component = cc.Class({
}
if (this._super()) {
if (this._enabled && this.node._activeInHierarchy) {
callOnEnable(this, false);
cc.director._compScheduler.disableComp(this);
}
}
},
__onNodeActivated: CC_EDITOR ? function (active) {
if (active && !(this._objFlags & IsOnLoadStarted) &&
(cc.engine._isPlaying || this.constructor._executeInEditMode)) {
this._objFlags |= IsOnLoadStarted;
if (this.onLoad) {
callOnLoadInTryCatch(this);
}
this._objFlags |= IsOnLoadCalled;
if (this.onLoad && !cc.engine._isPlaying) {
var focused = Editor.Selection.curActivate('node') === this.node.uuid;
if (focused && this.onFocusInEditor) {
callOnFocusInTryCatch(this);
}
else if (this.onLostFocusInEditor) {
callOnLostFocusInTryCatch(this);
}
}
if ( !CC_TEST ) {
_Scene.AssetsWatcher.start(this);
}
}
if (this._enabled) {
if (active) {
var deactivatedOnLoading = !this.node._activeInHierarchy;
if (deactivatedOnLoading) {
return;
}
}
callOnEnable(this, active);
}
} : function (active) {
if (active && !(this._objFlags & IsOnLoadStarted)) {
this._objFlags |= IsOnLoadStarted;
if (this.onLoad) {
this.onLoad();
}
this._objFlags |= IsOnLoadCalled;
}
if (this._enabled) {
if (active) {
var deactivatedOnLoading = !this.node._activeInHierarchy;
if (deactivatedOnLoading) {
return;
}
}
callOnEnable(this, active);
}
},
_onPreDestroy: function () {
var i, l, target;
// ensure onDisable called
callOnEnable(this, false);
// Schedules
this.unscheduleAllCallbacks();
// Remove all listeners
for (i = 0, l = this.__eventTargets.length; i < l; ++i) {
target = this.__eventTargets[i];
for (var i = 0, l = this.__eventTargets.length; i < l; ++i) {
var target = this.__eventTargets[i];
target && target.targetOff(this);
}
this.__eventTargets.length = 0;
@@ -732,16 +476,7 @@ var Component = cc.Class({
}
// onDestroy
if (this.onDestroy && (this._objFlags & IsOnLoadCalled)) {
if (CC_EDITOR) {
if (cc.engine._isPlaying || this.constructor._executeInEditMode) {
callOnDestroyInTryCatch(this);
}
}
else {
this.onDestroy();
}
}
cc.director._compScheduler.destroyComp(this);
// do remove component
this.node._removeComponent(this);
@@ -932,30 +667,6 @@ Object.defineProperty(Component, '_registerEditorProps', {
}
});
Object.defineProperties(Component, {
_callPreloadOnNode: {
value: _callPreloadOnNode
},
_callPreloadOnComponent: {
value: function (component) {
if (CC_EDITOR) {
callPreloadInTryCatch(component);
}
else {
component.__preload();
}
component._objFlags |= IsPreloadCalled;
}
},
_callResetOnComponent: {
value: CC_EDITOR && function (comp) {
if (typeof comp.resetInEditor === 'function') {
callResetInTryCatch(comp);
}
}
}
});
Component.prototype.__scriptUuid = '';
cc.Component = module.exports = Component;
+17 -28
View File
@@ -51,38 +51,27 @@ EventListeners.prototype.invoke = function (event, captureListeners) {
}
else {
endIndex = list.length - 1;
if (key === cc.Director.EVENT_COMPONENT_UPDATE) {
var dt = event.detail;
for (i = 1; i <= endIndex; i += 2) {
target = list[i];
if (target !== REMOVE_PLACEHOLDER) {
target.update(dt);
for (i = 0; i <= endIndex;) {
callingFunc = list[i];
var increment = 1;
// cheap detection for function
if (callingFunc !== REMOVE_PLACEHOLDER) {
target = list[i+1];
hasTarget = target && typeof target === 'object';
if (hasTarget) {
callingFunc.call(target, event, captureListeners);
increment = 2;
}
}
}
else {
for (i = 0; i <= endIndex;) {
callingFunc = list[i];
var increment = 1;
// cheap detection for function
if (callingFunc !== REMOVE_PLACEHOLDER) {
target = list[i+1];
hasTarget = target && typeof target === 'object';
if (hasTarget) {
callingFunc.call(target, event, captureListeners);
increment = 2;
}
else {
callingFunc.call(event.currentTarget, event, captureListeners);
}
if (event._propagationImmediateStopped || i + increment > endIndex) {
break;
}
else {
callingFunc.call(event.currentTarget, event, captureListeners);
}
i += increment;
if (event._propagationImmediateStopped || i + increment > endIndex) {
break;
}
}
i += increment;
}
}
}
+4 -3
View File
@@ -379,14 +379,14 @@ function normalizeClassName (className) {
}).join('');
try {
// validate name
eval('function ' + className + '(){}');
Function('function ' + className + '(){}')();
return className;
}
catch (e) {
className = DefaultName + '_' + className;
}
try {
eval('function ' + className + '(){}');
Function('function ' + className + '(){}')();
return className;
}
catch (e) {
@@ -505,7 +505,8 @@ function compileProps (actualClass) {
// console.log(func);
// }
// overwite __initProps__ to avoid compile again
// Overwite __initProps__ to avoid compile again.
// Use eval to bind scoped variable just in one function, so that we don't have to bind this.
actualClass.prototype.__initProps__ = Misc.cleanEval_F(func, F);
// call instantiateProps immediately, no need to pass actualClass into it anymore
+2 -5
View File
@@ -1,6 +1,5 @@
var JS = require('./js');
var CCClass = require('./CCClass');
var cleanEval = require('../utils/misc').cleanEval;
// definitions for CCObject.Flags
@@ -341,7 +340,7 @@ function compileDestruct (obj, ctor) {
}
// compile code
var skipId = obj instanceof cc._BaseNode || obj instanceof cc.Component;
var func = '(function(o){\n';
var func = '';
for (key in propsToReset) {
if (skipId && key === '_id') {
continue;
@@ -359,9 +358,7 @@ function compileDestruct (obj, ctor) {
}
func += (statement + val + ';\n');
}
func += '})';
return cleanEval(func);
return Function('o', func);
}
/**
+14 -13
View File
@@ -75,26 +75,27 @@ Class.extend = function (props) {
var desc = {writable: true, enumerable: false, configurable: true};
// The dummy Class constructor
var TheCls;
var TheClass;
if (cc.game && cc.game.config && cc.game.config[cc.game.CONFIG_KEY.exposeClassName]) {
var ctor =
"(function " + (props._className || "Class") + "(arg0,arg1,arg2,arg3,arg4,arg5) {\n" +
"this.__instanceId = ClassManager.getNewInstanceId();\n" +
"return (function " + (props._className || "Class") + "(arg0,arg1,arg2,arg3,arg4) {\n" +
"this.__instanceId = cc.ClassManager.getNewInstanceId();\n" +
"if (this.ctor) {\n" +
"switch (arguments.length) {\n" +
"case 0: this.ctor(); break;\n" +
"case 1: this.ctor(arg0); break;\n" +
"case 2: this.ctor(arg0,arg1); break;\n" +
"case 3: this.ctor(arg0,arg1,arg2); break;\n" +
"case 4: this.ctor(arg0,arg1,arg2,arg3); break;\n" +
"case 5: this.ctor(arg0,arg1,arg2,arg3,arg4); break;\n" +
"default: this.ctor.apply(this, arguments);\n" +
"}\n" +
"}\n" +
"})";
TheCls = eval(ctor);
"});";
TheClass = Function(ctor)();
}
else {
TheCls = function (arg0, arg1, arg2, arg3, arg4) {
TheClass = function (arg0, arg1, arg2, arg3, arg4) {
this.__instanceId = ClassManager.getNewInstanceId();
if (this.ctor) {
switch (arguments.length) {
@@ -114,15 +115,15 @@ Class.extend = function (props) {
Object.defineProperty(proto, '__pid', desc);
// Populate our constructed prototype object
TheCls.prototype = proto;
TheClass.prototype = proto;
// Enforce the constructor to be what we expect
desc.value = TheCls;
desc.value = TheClass;
Object.defineProperty(proto, 'constructor', desc);
// Copy getter/setter
this.__getters__ && (TheCls.__getters__ = cc.clone(this.__getters__));
this.__setters__ && (TheCls.__setters__ = cc.clone(this.__setters__));
this.__getters__ && (TheClass.__getters__ = cc.clone(this.__getters__));
this.__setters__ && (TheClass.__setters__ = cc.clone(this.__setters__));
for (var idx = 0, li = arguments.length; idx < li; ++idx) {
var prop = arguments[idx];
@@ -184,15 +185,15 @@ Class.extend = function (props) {
}
// And make this Class extendable
TheCls.extend = Class.extend;
TheClass.extend = Class.extend;
//add implementation method
TheCls.implement = function (prop) {
TheClass.implement = function (prop) {
for (var name in prop) {
proto[name] = prop[name];
}
};
return TheCls;
return TheClass;
};
/**
+1 -1
View File
@@ -33,7 +33,7 @@ function createAttrsSingle (owner, ownerCtor, superAttrs) {
if (owner !== ownerCtor) {
ctorName += '_INSTANCE';
}
AttrsCtor = eval('(function ' + ctorName + '(){})');
AttrsCtor = Function('return (function ' + ctorName + '(){});')();
}
else {
AttrsCtor = function () {};
+2 -5
View File
@@ -27,7 +27,6 @@ var JS = require('./js');
var CCObject = require('./CCObject');
var Attr = require('./attribute');
var CCClass = require('./CCClass');
var cleanEval = require('../utils/misc').cleanEval;
// HELPERS
@@ -362,8 +361,7 @@ var _Deserializer = (function () {
var props = klass.__props__;
// self, obj, serializedData, klass, target
var sources = [
'(function(s,o,d,k,t){',
'var prop;'
'var prop;'
];
// sources.push('var vb,vn,vs,vo,vu,vf;'); // boolean, number, string, object, undefined, function
for (var p = 0; p < props.length; p++) {
@@ -427,8 +425,7 @@ var _Deserializer = (function () {
// parse the serialized data as primitive javascript object, so its __id__ will be dereferenced
sources.push('s._deserializePrimitiveObject(o._$erialized,d);');
}
sources.push('})');
return cleanEval(sources.join(''));
return Function('s', 'o', 'd', 'k', 't', sources.join(''));
}
function unlinkUnusedPrefab (self, serialized, obj) {
+5 -7
View File
@@ -30,7 +30,6 @@ var Destroyed = CCObject.Flags.Destroyed;
var PersistentMask = CCObject.Flags.PersistentMask;
var Attr = require('./attribute');
var JS = require('./js');
var cleanEval = require('../utils/misc').cleanEval;
var CCClass = require('./CCClass');
var SERIALIZABLE = Attr.DELIMETER + 'serializable';
@@ -158,13 +157,12 @@ function Parser (obj, parent) {
if (this.globalVariables.length > 0) {
globalVariablesDeclaration = VAR + this.globalVariables.join(',') + ';';
}
var code = flattenCodeArray(['(function(O,F,R){',
globalVariablesDeclaration || [],
this.codeArray,
'return o;})'], CC_DEV ? '\n' : '');
var code = flattenCodeArray([globalVariablesDeclaration || [],
this.codeArray,
'return o;'], CC_DEV ? '\n' : '');
// generate method and bind with objs
var createFunction = cleanEval(code);
var createFunction = Function('O', 'F', 'R', code);
this.result = createFunction.bind(null, this.objs, this.funcs);
if (CC_TEST && !isPhantomJS) {
@@ -186,7 +184,7 @@ JS.mixin(Parser.prototype, {
if (clsNameIsModule) {
try {
// ensure is module
clsNameIsModule = (func === cleanEval(clsName));
clsNameIsModule = (func === Function('return ' + clsName)());
if (clsNameIsModule) {
return clsName;
}
+3 -3
View File
@@ -582,7 +582,7 @@ function fastRemoveAt (array, index) {
*/
function remove (array, value) {
var index = array.indexOf(value);
if (index !== -1) {
if (index >= 0) {
removeAt(array, index);
return true;
}
@@ -600,7 +600,7 @@ function remove (array, value) {
*/
function fastRemove (array, value) {
var index = array.indexOf(value);
if (index !== -1) {
if (index >= 0) {
array[index] = array[array.length - 1];
--array.length;
}
@@ -676,7 +676,7 @@ var indexOf = Array.prototype.indexOf;
* @return {Boolean}
*/
function contains (array, value) {
return indexOf.call(array, value) !== -1;
return indexOf.call(array, value) >= 0;
}
/**
+18 -11
View File
@@ -853,10 +853,10 @@ var BaseNode = cc.Class({
if (this._activeInHierarchy) {
if (typeof component.__preload === 'function') {
cc.Component._callPreloadOnComponent(component);
cc.director._compScheduler.doPreloadComp(component);
}
// call onLoad/onEnable
component.__onNodeActivated(true);
cc.director._compScheduler.activateComp(component);
}
return component;
@@ -906,10 +906,10 @@ var BaseNode = cc.Class({
if (this._activeInHierarchy) {
if (typeof comp.__preload === 'function' &&
!(comp._objFlags & cc.Object.Flags.IsPreloadCalled)) {
cc.Component._callPreloadOnComponent(comp);
cc.director._compScheduler.doPreloadComp(comp);
}
// call onLoad/onEnable
comp.__onNodeActivated(true);
cc.director._compScheduler.activateComp(comp);
}
},
@@ -980,7 +980,7 @@ var BaseNode = cc.Class({
_onActivatedInHierarchy: function (newActive) {
if (newActive) {
cc.Component._callPreloadOnNode(this);
cc.director._compScheduler.preloadNode(this);
}
this._activeRecursively(newActive);
},
@@ -1008,11 +1008,16 @@ var BaseNode = cc.Class({
for (var c = 0; c < originCount; ++c) {
var component = this._components[c];
if (component instanceof cc.Component) {
component.__onNodeActivated(newActive);
if (newActive && !this._activeInHierarchy) {
// deactivated during activating
this._objFlags &= ~Activating;
return;
if (newActive) {
cc.director._compScheduler.activateComp(component);
if (!this._activeInHierarchy) {
// deactivated during activating
this._objFlags &= ~Activating;
return;
}
}
else if (component._enabled) {
cc.director._compScheduler.disableComp(component);
}
}
else {
@@ -1056,7 +1061,9 @@ var BaseNode = cc.Class({
var originCount = this._components.length;
for (var c = 0; c < originCount; ++c) {
var component = this._components[c];
component.__onNodeActivated(false);
if (component._enabled) {
cc.director._compScheduler.disableComp(component);
}
}
// deactivate children recursively
for (var i = 0, len = this._children.length; i < len; ++i) {
+25 -6
View File
@@ -23,6 +23,8 @@
THE SOFTWARE.
****************************************************************************/
// jshint evil: true
// should not use long variable name because eval breaks uglify's mangle operation in this file
var m = {};
@@ -88,20 +90,37 @@ m.NextPOT = function (x) {
//
//DirtyFlags.WIDGET = DirtyFlags.TRANSFORM | DirtyFlags.SIZE;
// wrap a new scope to enalbe minify
// wrap a new scope to avoid uglify's mangle process broken by eval in caller's scope
// jshint evil: true
m.cleanEval = function (code) {
return eval(code);
};
m.cleanEval_F = function (code, F) {
return eval(code);
};
m.cleanEval_fireClass = function (code) {
var fireClass = eval(code);
return fireClass;
};
// jshint evil: false
if (CC_EDITOR) {
// use anonymous function here to ensure it will not being hoisted without CC_EDITOR
m.tryCatchFunctor_EDITOR = function (funcName, receivedArgs, usedArgs) {
function call_FUNC_InTryCatch (_R_ARGS_) {
try {
target._FUNC_(_U_ARGS_);
}
catch (e) {
cc._throw(e);
}
}
// use evaled code to generate named function
return Function(('return ' + call_FUNC_InTryCatch).
replace(/_FUNC_/g, funcName).
replace('_R_ARGS_', 'target' + (receivedArgs ? ', ' + receivedArgs : '')).
replace('_U_ARGS_', usedArgs || ''))();
};
}
module.exports = m;
// jshint evil: false
@@ -39,8 +39,30 @@ function MutableForwardIterator (array) {
var proto = MutableForwardIterator.prototype;
proto.remove = function (value) {
var index = this.array.indexOf(value);
if (index >= 0) {
this.removeAt(index);
}
};
proto.removeAt = function (i) {
this.array.splice(i, 1);
if (i <= this.i) {
--this.i;
}
};
proto.fastRemove = function (value) {
var index = this.array.indexOf(value);
if (index >= 0) {
this.fastRemoveAt(index);
}
};
proto.fastRemoveAt = function (i) {
var array = this.array;
array[i] = array[array.length - 1];
--array.length;
if (i <= this.i) {
--this.i;
}
+1 -1
View File
@@ -253,7 +253,7 @@ if (CC_DEV) {
function deprecateEnum (obj, oldPath, newPath, hasTypePrefixBefore) {
hasTypePrefixBefore = hasTypePrefixBefore !== false;
var enumDef = eval(newPath);
var enumDef = Function('return ' + newPath)();
var entries = cc.Enum.getList(enumDef);
var delimiter = hasTypePrefixBefore ? '_' : '.';
for (var i = 0; i < entries.length; i++) {
+3 -3
View File
@@ -27,8 +27,8 @@
// if "global_defs" not preprocessed by uglify, just declare them globally,
// this may happened in release version's preview page.
eval(
/* use EVAL to prevent the uglify from renaming symbols */
Function(
/* use evaled code to prevent the uglify from renaming symbols */
'if(typeof CC_TEST=="undefined")' +
'CC_TEST=typeof tap=="object"||typeof QUnit=="object";' +
'if(typeof CC_EDITOR=="undefined")' +
@@ -37,7 +37,7 @@ eval(
'CC_DEV=CC_EDITOR||CC_TEST;' + /* CC_DEV contains CC_TEST and CC_EDITOR */
'if(typeof CC_JSB=="undefined")' +
'CC_JSB=false;'
);
)();
// PREDEFINE
+3 -3
View File
@@ -75,8 +75,8 @@ catch (e) {
}
// Macros, if "global_defs" not preprocessed by uglify, just declare them globally
eval(
/* use EVAL to prevent the uglify from renaming symbols */
Function(
/* use evaled code to prevent the uglify from renaming symbols */
'if(typeof CC_TEST=="undefined")' +
'window.CC_TEST=typeof describe!="undefined"||typeof QUnit=="object";' +
'if(typeof CC_EDITOR=="undefined")' +
@@ -85,7 +85,7 @@ eval(
'window.CC_DEV=CC_EDITOR||CC_TEST;' +
'if(typeof CC_JSB=="undefined")' +
'window.CC_JSB=true;'
);
)();
require('./jsb-predefine');
require('./jsb-loader');
+16 -7
View File
@@ -26,6 +26,9 @@
'use strict';
var AutoReleaseUtils = require('../cocos2d/core/load-pipeline/auto-release-utils');
var ComponentScheduler = require('../cocos2d/core/component-scheduler');
cc.director._purgeDirector = cc.director.purgeDirector;
// cc.director
cc.js.mixin(cc.director, {
@@ -34,6 +37,8 @@ cc.js.mixin(cc.director, {
* All platform independent init process should be occupied here.
*/
sharedInit: function () {
this._compScheduler = new ComponentScheduler();
// Animation manager
if (cc.AnimationManager) {
this._animationManager = new cc.AnimationManager();
@@ -56,6 +61,11 @@ cc.js.mixin(cc.director, {
cc._widgetManager.init(this);
},
purgeDirector: function () {
this._compScheduler.unscheduleAll();
this._purgeDirector();
},
/**
* Reset the cc.director, can be used to restart the director after purge
*/
@@ -396,20 +406,19 @@ cc.Director.EVENT_AFTER_UPDATE = 'director_after_update';
cc.Director.EVENT_BEFORE_SCENE_LOADING = "director_before_scene_loading";
cc.Director.EVENT_BEFORE_SCENE_LAUNCH = 'director_before_scene_launch';
cc.Director.EVENT_AFTER_SCENE_LAUNCH = "director_after_scene_launch";
cc.Director.EVENT_COMPONENT_UPDATE = 'director_component_update';
cc.Director.EVENT_COMPONENT_LATE_UPDATE = 'director_component_late_update';
cc.eventManager.addCustomListener(cc.Director.EVENT_BEFORE_UPDATE, function () {
var dt = cc.director.getDeltaTime();
// Call start for new added components
cc.director.emit(cc.Director.EVENT_BEFORE_UPDATE);
// Call start for new added components
cc.director._compScheduler.startPhase();
// Update for components
cc.director.emit(cc.Director.EVENT_COMPONENT_UPDATE, dt);
var dt = cc.director.getDeltaTime();
cc.director._compScheduler.updatePhase(dt);
});
cc.eventManager.addCustomListener(cc.Director.EVENT_AFTER_UPDATE, function () {
var dt = cc.director.getDeltaTime();
// Late update for components
cc.director.emit(cc.Director.EVENT_COMPONENT_LATE_UPDATE, dt);
var dt = cc.director.getDeltaTime();
cc.director._compScheduler.lateUpdatePhase(dt);
// User can use this event to do things after update
cc.director.emit(cc.Director.EVENT_AFTER_UPDATE);
// Destroy entities that have been removed recently
+5
View File
@@ -91,6 +91,11 @@ test('start', function () {
test.addComponent(TestComp);
this.node.addChild(test);
};
comp.update = function () {
var test = new cc.Node();
test.addComponent(TestComp);
this.node.addChild(test);
};
cc.director.getScene().addChild(node);
// run comp
cc.game.step();
+25 -18
View File
@@ -41,24 +41,31 @@ test('enum', function () {
"Can define enum name as index value" );
});
test('foreach mutable array', function () {
var array = [0, 1, 2, 3, 4];
var iterator = new cc.js.array.MutableForwardIterator(array);
(function () {
function testRemove (title, removeOperation) {
test(title, function () {
var array = [0, 1, 2, 3, 4];
var iterator = new cc.js.array.MutableForwardIterator(array);
function removeOperation (index) {
iterator.i = 0;
removeOperation(iterator, 0);
strictEqual(iterator.i, 0 - 1, 'should decrease the index if remove current item, otherwise iterator will out of sync');
iterator.i = 1;
removeOperation(iterator, 0);
strictEqual(iterator.i, 1 - 1, 'should decrease the index if remove previous item');
iterator.i = 0;
removeOperation(iterator, 1);
strictEqual(iterator.i, 0, 'should not decrease the index if remove subsequent item');
});
}
testRemove('foreach mutable array - removeAt', function (iterator, index) {
// can not directly change loop index outside loop scope
iterator.removeAt(index);
}
iterator.i = 0;
removeOperation(0);
strictEqual(iterator.i, 0 - 1, 'should decrease the index if remove current item, otherwise iterator will out of sync');
iterator.i = 1;
removeOperation(0);
strictEqual(iterator.i, 1 - 1, 'should decrease the index if remove previous item');
iterator.i = 0;
removeOperation(1);
strictEqual(iterator.i, 0, 'should not decrease the index if remove subsequent item');
});
});
testRemove('foreach mutable array - fastRemoveAt', function (iterator, index) {
// can not directly change loop index outside loop scope
iterator.fastRemoveAt(index);
});
})();