Merge pull request #1256 from jareguo/master

optimize instantiate
This commit is contained in:
Wang Nan
2016-11-08 11:23:57 +08:00
committed by GitHub
12 changed files with 752 additions and 206 deletions
+11 -10
View File
@@ -457,8 +457,7 @@ var Node = cc.Class({
}
},
ctor: function () {
var name = arguments[0];
ctor: function (name) {
this._name = typeof name !== 'undefined' ? name : 'New Node';
this._activeInHierarchy = false;
@@ -1089,27 +1088,29 @@ var Node = cc.Class({
}
},
_instantiate: function () {
var clone = cc.instantiate._clone(this, this);
clone._parent = null;
_instantiate: function (cloned) {
if (!cloned) {
cloned = cc.instantiate._clone(this, this);
}
var thisPrefabInfo = this._prefab;
var syncing = thisPrefabInfo && this === thisPrefabInfo.root && thisPrefabInfo.sync;
if (syncing) {
// copy non-serialized property
clone._prefab._synced = thisPrefabInfo._synced;
cloned._prefab._synced = thisPrefabInfo._synced;
//if (thisPrefabInfo._synced) {
// return clone;
//}
}
else if (CC_EDITOR && cc.engine._isPlaying) {
this._name += ' (Clone)';
cloned._name += ' (Clone)';
}
// init
clone._onBatchCreated();
// reset and init
cloned._parent = null;
cloned._onBatchCreated();
return clone;
return cloned;
},
// EVENTS
+40 -16
View File
@@ -23,28 +23,31 @@
THE SOFTWARE.
****************************************************************************/
function visitWrapper (wrapper, visitor) {
visitor(wrapper);
var children = wrapper._children;
for (var i = 0; i < children.length; i++) {
visitor(children[i]);
}
}
/**
* !#en Class for prefab handling.
* !#zh 预制资源类。
* @class Prefab
* @extends Asset
*
*/
var Prefab = cc.Class({
name: 'cc.Prefab',
extends: cc.Asset,
properties: {
data: null
/**
* @property {Node} data - the main cc.Node in the prefab
*/
data: null,
/**
* Cache function for fast instantiation
* @property {Function} _createFunction
* @private
*/
_createFunction: {
default: null,
serializable: false
}
},
createNode: function (cb) {
@@ -54,7 +57,21 @@ var Prefab = cc.Class({
}
},
_instantiate: function () {
/**
* Dynamically translation prefab data into minimized code.<br/>
* This method will be called automatically before the first time the prefab being instantiated,
* but you can re-call to refresh the create function once you modified the original prefab data in script.
* @method compileCreateFunction
*/
compileCreateFunction: function () {
var jit = require('../platform/instantiate-jit');
this._createFunction = jit.compile(this.data);
},
// just instantiate, will not initialize the Node, this will be called during Node's initialization.
// @param {Node} [rootToRedirect] - specify an instantiated prefabRoot that all references to prefabRoot in prefab
// will redirect to
_doInstantiate: function (rootToRedirect) {
if (this.data._prefab) {
// prefab asset is always synced
this.data._prefab._synced = true;
@@ -63,15 +80,22 @@ var Prefab = cc.Class({
// temp guard code
cc.warn('internal error: _prefab is undefined');
}
if (!this._createFunction) {
this.compileCreateFunction();
}
return this._createFunction(rootToRedirect); // this.data._instantiate();
},
// instantiate
var node = cc.instantiate(this.data);
_instantiate: function () {
// instantiate node
var node = this._doInstantiate();
// initialize node
this.data._instantiate(node);
// link prefab in editor
if (CC_EDITOR || CC_TEST) {
// This operation is not necessary, but some old prefab asset may not contain complete data.
_Scene.PrefabUtils.linkPrefab(this, node);
}
return node;
}
});
-2
View File
@@ -154,8 +154,6 @@ _ccsg.Node = cc.Class({
},
ctor: function() {
var name = arguments[0];
this.__instanceId = cc.ClassManager.getNewInstanceId();
this._running = false;
+6 -4
View File
@@ -754,10 +754,12 @@ var Component = cc.Class({
_destruct: Misc.destructIgnoreId,
_instantiate: function () {
var clone = cc.instantiate._clone(this, this);
clone.node = null;
return clone;
_instantiate: function (cloned) {
if (!cloned) {
cloned = cc.instantiate._clone(this, this);
}
cloned.node = null;
return cloned;
},
// Scheduler
+118 -46
View File
@@ -280,41 +280,6 @@ function getDefault (defaultVal) {
return defaultVal;
}
var DELIMETER = Attr.DELIMETER;
function instantiateProps (instance, itsClass) {
var attrs = Attr.getClassAttrs(itsClass);
var propList = itsClass.__props__;
if (propList === null) {
deferredInitializer.init();
propList = itsClass.__props__;
}
for (var i = 0; i < propList.length; i++) {
var prop = propList[i];
var attrKey = prop + DELIMETER + 'default';
if (attrKey in attrs) { // getter does not have default
var def = attrs[attrKey];
// default maybe 0
if (def) {
if (typeof def === 'object' && def) {
if (typeof def.clone === 'function') {
def = def.clone();
}
else if (Array.isArray(def)) {
def = [];
}
else {
def = {};
}
}
else if (typeof def === 'function') {
def = getDefault(def);
}
}
instance[prop] = def;
}
}
}
/**
* Checks whether subclass is child of superclass or equals to superclass
*
@@ -417,6 +382,8 @@ function doDefine (className, baseClass, mixins, constructor, options) {
fireClass.prototype.constructor = fireClass;
}
fireClass.prototype.__initProps__ = compileProps;
JS.setClassName(className, fireClass);
return fireClass;
}
@@ -468,7 +435,7 @@ function _checkCtor (ctor, className) {
cc.error('ctor of "%s" must be function type', className);
return;
}
if (ctor.length > 0) {
if (ctor.length > 0 && !className.startsWith('cc.')) {
// fireball-x/dev#138: To make a unified CCClass serialization process,
// we don't allow parameters for constructor when creating instances of CCClass.
// For advance user, construct arguments can still get from 'arguments'.
@@ -506,6 +473,112 @@ function normalizeClassName (className) {
}
}
function getNewValueTypeCode (value) {
var clsName = JS.getClassName(value);
var type = value.constructor;
var res = 'new ' + clsName + '(';
for (var i = 0; i < type.__props__.length; i++) {
var prop = type.__props__[i];
var propVal = value[prop];
if (typeof propVal === 'object') {
cc.error('Can not construct %s because it contains object property.', clsName);
return 'new ' + clsName + '()';
}
res += propVal;
if (i < type.__props__.length - 1) {
res += ','
}
}
return res + ')';
}
// wrap a new scope to enalbe minify
function cleanEval_F (code, F) {
// jshint evil: true
return eval(code);
// jshint evil: false
}
var NAME_IN_DOT_NOTATION_REG = /^[$A-Za-z_][0-9A-Za-z_$]*$/;
function compileProps (actualClass) {
// init deferred properties
var attrs = Attr.getClassAttrs(actualClass);
var propList = actualClass.__props__;
if (propList === null) {
deferredInitializer.init();
propList = actualClass.__props__;
}
// functions for generated code
var F = [];
var func = '(function(){\n';
for (var i = 0; i < propList.length; i++) {
var prop = propList[i];
var attrKey = prop + Attr.DELIMETER + 'default';
if (attrKey in attrs) { // getter does not have default
var statement;
if (NAME_IN_DOT_NOTATION_REG.test(prop)) {
statement = 'this.' + prop + '=';
}
else {
statement = 'this["' + prop + '"]=';
}
var expression;
var def = attrs[attrKey];
if (typeof def === 'object' && def) {
if (def instanceof cc.ValueType) {
expression = getNewValueTypeCode(def);
}
else if (Array.isArray(def)) {
expression = '[]';
}
else {
expression = '{}';
}
}
else if (typeof def === 'function') {
var index = F.length;
F.push(def);
expression = 'F[' + index + ']()';
if (CC_EDITOR) {
func += 'try {\n' + statement + expression + ';\n}\ncatch(e) {\ncc._throw(e);\n' + statement + 'undefined;\n}\n';
continue;
}
}
else if (typeof def === 'string') {
expression = '"' + def + '"';
}
else {
// number, boolean, null, undefined
expression = def;
}
statement = statement + expression + ';\n';
func += statement;
}
}
func += '})';
if (CC_TEST && !isPhantomJS) {
console.log(func);
}
// overwite __initProps__ to avoid compile again
actualClass.prototype.__initProps__ = cleanEval_F(func, F);
// call instantiateProps immediately, no need to pass actualClass into it anymore
this.__initProps__();
}
// wrap a new scope to enalbe minify
function cleanEval_fireClass (code) {
// jshint evil: true
var fireClass = eval(code);
// jshint evil: false
return fireClass;
}
function _createCtor (ctor, baseClass, mixins, className, options) {
var useTryCatch = ! (className && className.startsWith('cc.'));
var shouldAddProtoCtor;
@@ -529,7 +602,7 @@ function _createCtor (ctor, baseClass, mixins, className, options) {
}
var superCallBounded = options && baseClass && boundSuperCalls(baseClass, options);
if (ctor && CC_DEV) {
if (CC_DEV && ctor) {
_checkCtor(ctor, className);
}
// get base user constructors
@@ -566,7 +639,9 @@ function _createCtor (ctor, baseClass, mixins, className, options) {
if (superCallBounded) {
body += 'this._super=null;\n';
}
body += 'instantiateProps(this,fireClass);\n';
// instantiate props
body += 'this.__initProps__(fireClass);\n';
// call user constructors
if (ctors.length > 0) {
@@ -593,7 +668,7 @@ function _createCtor (ctor, baseClass, mixins, className, options) {
body += '})';
// jshint evil: true
var fireClass = eval(body);
var fireClass = cleanEval_fireClass(body);
// jshint evil: false
Object.defineProperty(fireClass, '__ctors__', {
@@ -778,11 +853,7 @@ function declareProperties (cls, className, properties, baseClass, mixins) {
};
*/
function CCClass (options) {
if (arguments.length === 0) {
return define();
}
if ( !options ) {
cc.error('cc.Class: Option must be non-nil');
if (!options) {
return define();
}
@@ -1091,12 +1162,13 @@ function parseAttributes (attrs, className, propName) {
cc.Class = CCClass;
module.exports = {
instantiateProps: instantiateProps,
isArray: function (defaultVal) {
defaultVal = getDefault(defaultVal);
return Array.isArray(defaultVal);
},
fastDefine: CCClass._fastDefine
fastDefine: CCClass._fastDefine,
getNewValueTypeCode: getNewValueTypeCode,
NAME_IN_DOT_NOTATION_REG: NAME_IN_DOT_NOTATION_REG,
};
if (CC_EDITOR) {
+1
View File
@@ -30,6 +30,7 @@ require('./callbacks-invoker');
require('./url');
require('./deserialize');
require('./instantiate');
require('./instantiate-jit');
require('./requiring-frame');
require('./CCSys');
require('./CCMacro');
+414
View File
@@ -0,0 +1,414 @@
/****************************************************************************
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.
****************************************************************************/
// Some helper methods for compile instantiation code
var CCObject = require('./CCObject');
var Destroyed = CCObject.Flags.Destroyed;
var PersistentMask = CCObject.Flags.PersistentMask;
var Attr = require('./attribute');
var JS = require('./js');
var CCClass = require('./CCClass');
var SERIALIZABLE = Attr.DELIMETER + 'serializable';
var DEFAULT = Attr.DELIMETER + 'default';
var NAME_IN_DOT_NOTATION_REG = CCClass.NAME_IN_DOT_NOTATION_REG;
var VAR = 'var ';
var LOCAL_OBJ = 'o';
var SCOPE_START = '(function';
var SCOPE_END = 'return o;})';
var LINE_INDEX_OF_NEW_OBJ = 0;
function equalsToDefault (def, value) {
if (typeof def === 'function') {
try {
def = def();
}
catch (e) {
return false;
}
}
if (def === value) {
return true;
}
if (def && value) {
if (def instanceof cc.ValueType && def.equals(value)) {
return true;
}
if ((Array.isArray(def) && Array.isArray(value)) ||
(def.constructor === Object && value.constructor === Object)
) {
try {
return JSON.stringify(def) === JSON.stringify(value);
}
catch (e) {
}
}
}
return false;
}
function flattenCodeArray (array, separator) {
var strList = [];
(function deepFlatten (array) {
for (var i = 0; i < array.length; i++) {
var item = array[i];
if (Array.isArray(item)) {
deepFlatten(item);
}
else {
strList.push(item);
}
}
})(array);
return strList.join(separator);
}
// wrap a new scope to enalbe minify
function cleanEval (code) {
// jshint evil: true
return eval(code);
// jshint evil: false
}
/*
* Variables:
* {Object[]} O - objs list
* {Function[]} F - constructor list
* {Node} [R] - specify an instantiated prefabRoot that all references to prefabRoot in prefab will redirect to
* {Object} o - current creating object
*/
/*
* @param {Object} obj - the object to parse
* @param {Node} [parent]
*/
function Parser (obj, parent) {
this.parent = parent;
this.objsToClear_iN$t = []; // used to reset _iN$t variable
this.codeArray = [];
// datas for generated code
this.objs = [];
this.funcs = [];
// {String[]} - variable names for circular references,
// not really global, just local variables shared between sub functions
this.globalVariables = [];
// incremental id for new global variables
this.globalVariableId = 0;
// incremental id for new local variables
this.localVariableId = 0;
// generate codeArray
//if (Array.isArray(obj)) {
// this.codeArray.push(this.instantiateArray(obj));
//}
//else {
this.codeArray.push(VAR + LOCAL_OBJ + ';',
'if(R){',
LOCAL_OBJ + '=R;',
'}else{',
LOCAL_OBJ + '=R=new ' + this.getFuncModule(obj.constructor, true) + '();',
'}');
obj._iN$t = { globalVar: 'R' };
this.objsToClear_iN$t.push(obj);
this.enumerateObject(this.codeArray, obj);
//}
// generate code
var globalVariablesDeclaration;
if (this.globalVariables.length > 0) {
globalVariablesDeclaration = VAR + this.globalVariables.join(',') + ';';
}
var code = flattenCodeArray([SCOPE_START + '(O,F,R){',
globalVariablesDeclaration || [],
this.codeArray,
SCOPE_END], CC_DEV ? '\n' : '');
// generate method and bind with objs
var createFunction = cleanEval(code);
this.result = createFunction.bind(null, this.objs, this.funcs);
if (CC_TEST && !isPhantomJS) {
console.log(code);
}
// cleanup
for (var i = 0, len = this.objsToClear_iN$t.length; i < len; ++i) {
this.objsToClear_iN$t[i]._iN$t = null;
}
this.objsToClear_iN$t.length = 0;
}
JS.mixin(Parser.prototype, {
getFuncModule: function (func, usedInNew) {
var clsName = JS.getClassName(func);
var clsNameIsModule = clsName.indexOf('.') !== -1;
if (clsNameIsModule) {
try {
// ensure is module
clsNameIsModule = (func === cleanEval(clsName));
if (clsNameIsModule) {
return clsName;
}
}
catch (e) {}
}
var index = this.funcs.indexOf(func);
if (index < 0) {
index = this.funcs.length;
this.funcs.push(func);
}
var res = 'F[' + index + ']';
return usedInNew ? '(' + res + ')' : res;
},
getObjRef: function (obj) {
var index = this.objs.indexOf(obj);
if (index < 0) {
index = this.objs.length;
this.objs.push(obj);
}
return 'O[' + index + ']';
},
enumerateCCClass: function (codeArray, obj, klass) {
var props = klass.__props__;
var attrs = Attr.getClassAttrs(klass);
for (var p = 0; p < props.length; p++) {
var key = props[p];
if (CC_EDITOR && key === '_id') {
if (obj instanceof cc._BaseNode || obj instanceof cc.Component) {
continue;
}
}
if (attrs[key + SERIALIZABLE] !== false) {
var val = obj[key];
if (equalsToDefault(attrs[key + DEFAULT], val)) {
continue;
}
this.writeField(codeArray, obj, key, val);
}
}
},
instantiateArray: function (value) {
if (value.length === 0) {
return '[]';
}
var arrayVar = 't' + (++this.localVariableId);
var codeArray = [arrayVar + '=new Array(' + value.length + ');'];
// assign a _iN$t flag to indicate that this object has been parsed.
value._iN$t = {
globalVar: '', // the name of declared global variable used to access this object
source: codeArray, // the source code array for this object
};
this.objsToClear_iN$t.push(value);
for (var i = 0; i < value.length; ++i) {
var expression = this.enumerateField(value, i, value[i]);
if (Array.isArray(expression)) {
expression[0] = arrayVar + '[' + i + ']=' + expression[0];
codeArray.push(expression);
}
else {
codeArray.push(arrayVar + '[' + i + ']=' + expression + ';');
}
}
return codeArray;
},
enumerateField: function (obj, key, value) {
if (typeof value === 'object' && value) {
var _iN$t = value._iN$t;
if (_iN$t) {
// parsed
var globalVar = _iN$t.globalVar;
if (!globalVar) {
// declare a global var
globalVar = _iN$t.globalVar = 'v' + (++this.globalVariableId);
this.globalVariables.push(globalVar);
// insert assignment statement to assign to global var
var line = _iN$t.source[LINE_INDEX_OF_NEW_OBJ];
if (line.startsWith(VAR)) {
// var o=xxx -> var o=global=xxx
var LEN_OF_VAR_O = 5;
_iN$t.source[LINE_INDEX_OF_NEW_OBJ] = line.slice(0, LEN_OF_VAR_O) + '=' + globalVar + line.slice(LEN_OF_VAR_O);
}
else {
_iN$t.source[LINE_INDEX_OF_NEW_OBJ] = globalVar + '=' + _iN$t.source[LINE_INDEX_OF_NEW_OBJ];
}
}
return globalVar;
}
else if (Array.isArray(value)) {
return this.instantiateArray(value);
}
else {
return this.instantiateObj(value);
}
}
else if (typeof value === 'function') {
return this.getFuncModule(value);
}
else if (typeof value === 'string') {
return '"' + value + '"';
}
else {
if (key === '_objFlags' && obj instanceof CCObject) {
value &= PersistentMask;
}
return value;
}
},
writeField: function (codeArray, obj, key, value) {
var statement;
if (NAME_IN_DOT_NOTATION_REG.test(key)) {
statement = LOCAL_OBJ + '.' + key + '=';
}
else {
statement = LOCAL_OBJ + '["' + key + '"]=';
}
var expression = this.enumerateField(obj, key, value);
if (Array.isArray(expression)) {
expression[0] = statement + expression[0];
codeArray.push(expression);
}
else {
codeArray.push(statement + expression + ';');
}
},
// codeArray - the source code array for this object
enumerateObject: function (codeArray, obj) {
var klass = obj.constructor;
if (cc.Class._isCCClass(klass)) {
this.enumerateCCClass(codeArray, obj, klass);
}
else {
// primitive javascript object
for (var key in obj) {
if (!obj.hasOwnProperty(key) ||
(key.charCodeAt(0) === 95 && key.charCodeAt(1) === 95 && // starts with "__"
key !== '__type__')
) {
continue;
}
var value = obj[key];
if (typeof value === 'object' && value && value === obj._iN$t) {
continue;
}
this.writeField(codeArray, obj, key, value);
}
}
},
instantiateObj: function (obj) {
if (obj instanceof cc.ValueType) {
return CCClass.getNewValueTypeCode(obj);
}
if (obj instanceof cc.Asset) {
// register to asset list and just return the reference.
return this.getObjRef(obj);
}
if (obj._objFlags & Destroyed) {
// the same as cc.isValid(obj)
return null;
}
var createCode;
var ctor = obj.constructor;
if (cc.Class._isCCClass(ctor)) {
if (this.parent) {
if (this.parent instanceof cc.Component) {
if (obj instanceof cc._BaseNode || obj instanceof cc.Component) {
return this.getObjRef(obj);
}
}
else if (this.parent instanceof cc._BaseNode) {
if (obj instanceof cc._BaseNode) {
if (!obj.isChildOf(this.parent)) {
// should not clone other nodes if not descendant
return this.getObjRef(obj);
}
}
else if (obj instanceof cc.Component) {
if (!obj.node.isChildOf(this.parent)) {
// should not clone other component if not descendant
return this.getObjRef(obj);
}
}
}
}
createCode = VAR + LOCAL_OBJ + '=new ' + this.getFuncModule(ctor, true) + '();';
}
else if (ctor === Object) {
createCode = VAR + LOCAL_OBJ + '={};'
}
else {
// do not clone unknown type
return this.getObjRef(obj);
}
var codeArray = [createCode];
// assign a _iN$t flag to indicate that this object has been parsed.
obj._iN$t = {
globalVar: '', // the name of declared global variable used to access this object
source: codeArray, // the source code array for this object
//propName: '', // the propName this object defined in its source code,
// // if defined, use LOCAL_OBJ.propName to access the obj, else just use o
};
this.objsToClear_iN$t.push(obj);
this.enumerateObject(codeArray, obj);
return [SCOPE_START + '(){',
codeArray,
SCOPE_END + '();'];
},
});
function compile (node) {
var root = (node instanceof cc._BaseNode) && node;
var parser = new Parser(node, root);
return parser.result;
}
module.exports = {
compile: compile,
equalsToDefault: equalsToDefault
};
if (CC_TEST) {
cc._Test.IntantiateJit = module.exports;
}
+97 -96
View File
@@ -24,6 +24,7 @@
****************************************************************************/
var CCObject = require('./CCObject');
var Destroyed = CCObject.Flags.Destroyed;
var PersistentMask = CCObject.Flags.PersistentMask;
var Attr = require('./attribute');
var _isDomNode = require('./utils').isDomNode;
@@ -57,7 +58,7 @@ function instantiate (original) {
}
return null;
}
if (original instanceof CCObject && !original.isValid) {
if (!cc.isValid(original)) {
if (CC_DEV) {
cc.error('The thing you want to instantiate is destroyed');
}
@@ -66,7 +67,12 @@ function instantiate (original) {
var clone;
if (original instanceof CCObject) {
// invoke _instantiate method if supplied
// Invoke _instantiate method if supplied.
// The _instantiate callback will be called only on the root object, its associated object will not be called.
// @callback associated
// @param {Object} [instantiated] - If supplied, _instantiate just need to initialize the instantiated object,
// no need to create new object by itself.
// @returns {Object} - the instantiated object
if (original._instantiate) {
cc.game._isCloning = true;
clone = original._instantiate();
@@ -88,18 +94,13 @@ function instantiate (original) {
return clone;
}
/*
* Reserved tags:
* - _iN$t: the cloned instance
*/
var objsToClearTmpVar = []; // 用于重设临时变量
var objsToClearTmpVar = []; // used to reset _iN$t variable
///**
// * Do instantiate object, the object to instantiate must be non-nil.
// * 这是一个通用的 instantiate 方法,可能效率比较低。
// * 之后可以给各种类型重写快速实例化的特殊实现,但应该在单元测试中将结果和这个方法的结果进行对比。
// * 值得注意的是,这个方法不可重入,不支持 mixin。
// * 值得注意的是,这个方法不可重入。
// *
// * @param {Object} obj - 该方法仅供内部使用,用户需负责保证参数合法。什么参数是合法的请参考 cc.instantiate 的实现。
// * @param {Node} [parent] - 只有在该对象下的场景物体会被克隆。
@@ -108,23 +109,29 @@ var objsToClearTmpVar = []; // 用于重设临时变量
// */
function doInstantiate (obj, parent) {
if (Array.isArray(obj)) {
cc.error('Can not instantiate array');
if (CC_DEV) {
cc.error('Can not instantiate array');
}
return null;
}
if (!CC_JSB && _isDomNode && _isDomNode(obj)) {
cc.error('Can not instantiate DOM element');
if (CC_DEV) {
cc.error('Can not instantiate DOM element');
}
return null;
}
var clone;
if (obj._iN$t) {
clone = obj._iN$t;
// enumerateObject will always push obj to objsToClearTmpVar
}
else {
// User can specify an existing object by assigning the "_iN$t" property
var klass = obj.constructor;
clone = new klass();
}
enumerateObject(obj, clone, parent);
for (var i = 0, len = objsToClearTmpVar.length; i < len; ++i) {
@@ -135,53 +142,56 @@ function doInstantiate (obj, parent) {
return clone;
}
var SERIALIZABLE = Attr.DELIMETER + 'serializable';
// @param {Object} obj - The object to instantiate, typeof must be 'object' and should not be an array.
function enumerateObject (obj, clone, parent) {
var value, type, key;
var klass = obj.constructor;
obj._iN$t = clone;
objsToClearTmpVar.push(obj);
if (cc.Class._isCCClass(klass)) {
var DELIMETER = Attr.DELIMETER;
var props = klass.__props__;
var attrs = Attr.getClassAttrs(klass);
for (var p = 0; p < props.length; p++) {
key = props[p];
if (attrs[key + DELIMETER + 'serializable'] !== false) {
value = obj[key];
type = typeof value;
if (type === 'object') {
clone[key] = value ? instantiateObj(value, parent, clone, key) : value;
}
else {
clone[key] = (type !== 'function') ? value : null;
}
function enumerateCCClass (klass, obj, clone, parent) {
var props = klass.__props__;
var attrs = Attr.getClassAttrs(klass);
for (var p = 0; p < props.length; p++) {
var key = props[p];
if (attrs[key + SERIALIZABLE] !== false) {
var value = obj[key];
if (typeof value === 'object' && value) {
clone[key] = value._iN$t || instantiateObj(value, parent);
}
else {
clone[key] = value;
}
}
if (CC_EDITOR && (clone instanceof cc._BaseNode || clone instanceof cc.Component)) {
clone._id = '';
}
}
if (CC_EDITOR && (obj instanceof cc._BaseNode || obj instanceof cc.Component)) {
clone._id = '';
}
}
function enumerateObject (obj, clone, parent) {
// 目前使用“_iN$t”这个特殊字段来存实例化后的对象,这样做主要是为了防止循环引用
// 注意,为了避免循环引用,所有新创建的实例,必须在赋值前被设为源对象的_iN$t
obj._iN$t = clone;
objsToClearTmpVar.push(obj);
var klass = obj.constructor;
if (cc.Class._isCCClass(klass)) {
enumerateCCClass(klass, obj, clone, parent);
}
else {
// primitive javascript object
for (key in obj) {
if ( !obj.hasOwnProperty(key) ||
// starts with "__" but not "__type__"
(key.charCodeAt(0) === 95 && key.charCodeAt(1) === 95 && key !== '__type__')
) {
for (var key in obj) {
if (!obj.hasOwnProperty(key) ||
(key.charCodeAt(0) === 95 && key.charCodeAt(1) === 95 && // starts with "__"
key !== '__type__')
) {
continue;
}
value = obj[key];
if (value === clone) {
continue; // value is obj._iN$t
}
// instantiate field
type = typeof value;
if (type === 'object') {
clone[key] = value ? instantiateObj(value, parent, clone, key) : value;
var value = obj[key];
if (typeof value === 'object' && value) {
if (value === clone) {
continue; // value is obj._iN$t
}
clone[key] = value._iN$t || instantiateObj(value, parent);
}
else {
clone[key] = (type !== 'function') ? value : null;
clone[key] = value;
}
}
}
@@ -190,80 +200,71 @@ function enumerateObject (obj, clone, parent) {
}
}
///**
// * @return {Object} - the original non-nil object, typeof must be 'object'
// */
function instantiateObj (obj, parent, ownerObj, ownerKey) {
// 目前使用“_iN$t”这个特殊字段来存实例化后的对象,这样做主要是为了防止循环引用
// 注意,为了避免循环引用,所有新创建的实例,必须在赋值前被设为源对象的_iN$t
var clone = obj._iN$t;
if (clone) {
// has been instantiated
return clone;
/*
* @param {Object|Array} obj - the original non-nil object, typeof must be 'object'
* @return {Object|Array} - the original non-nil object, typeof must be 'object'
*/
function instantiateObj (obj, parent) {
if (obj instanceof cc.ValueType) {
return obj.clone();
}
if ( !cc.isValid(obj) ) {
return null;
}
if (obj instanceof cc.Asset) {
// 所有资源直接引用,不需要拷贝
return obj;
}
else if (Array.isArray(obj)) {
var clone;
if (Array.isArray(obj)) {
var len = obj.length;
clone = new Array(len);
obj._iN$t = clone;
for (var i = 0; i < len; ++i) {
var value = obj[i];
// instantiate field
var type = typeof value;
if (type === 'object') {
clone[i] = value ? instantiateObj(value, parent, clone, '' + i) : value;
if (typeof value === 'object' && value) {
clone[i] = value._iN$t || instantiateObj(value, parent);
}
else {
clone[i] = (type !== 'function') ? value : null;
clone[i] = value;
}
}
objsToClearTmpVar.push(obj);
return clone;
}
else if (obj instanceof cc.ValueType) {
return obj.clone();
else if (obj._objFlags & Destroyed) {
// the same as cc.isValid(obj)
return null;
}
else {
var ctor = obj.constructor;
if (cc.Class._isCCClass(ctor)) {
if (parent) {
if (parent instanceof cc.Component) {
if (obj instanceof cc._BaseNode || obj instanceof cc.Component) {
var ctor = obj.constructor;
if (cc.Class._isCCClass(ctor)) {
if (parent) {
if (parent instanceof cc.Component) {
if (obj instanceof cc._BaseNode || obj instanceof cc.Component) {
return obj;
}
}
else if (parent instanceof cc._BaseNode) {
if (obj instanceof cc._BaseNode) {
if (!obj.isChildOf(parent)) {
// should not clone other nodes if not descendant
return obj;
}
}
else if (parent instanceof cc._BaseNode) {
if (obj instanceof cc._BaseNode) {
if (!obj.isChildOf(parent)) {
// should not clone other nodes if not descendant
return obj;
}
}
else if (obj instanceof cc.Component) {
if (!obj.node.isChildOf(parent)) {
// should not clone other component if not descendant
return obj;
}
else if (obj instanceof cc.Component) {
if (!obj.node.isChildOf(parent)) {
// should not clone other component if not descendant
return obj;
}
}
}
}
else if (ctor !== Object) {
// unknown type
return obj;
}
clone = new ctor();
enumerateObject(obj, clone, parent);
return clone;
}
else if (ctor !== Object) {
// unknown type
return obj;
}
clone = new ctor();
enumerateObject(obj, clone, parent);
return clone;
}
instantiate._clone = doInstantiate;
+2 -9
View File
@@ -84,16 +84,9 @@ module.exports = {
var _localZOrder = node._localZOrder;
var _globalZOrder = node._globalZOrder;
// root in prefab asset is always synced
var prefabRoot = _prefab.asset.data;
prefabRoot._prefab._synced = true;
// use node as the instantiated prefabRoot to make references to prefabRoot in prefab redirect to node
prefabRoot._iN$t = node;
// instantiate prefab and apply to node
// instantiate prefab
cc.game._isCloning = true;
cc.instantiate._clone(prefabRoot, prefabRoot);
_prefab.asset._doInstantiate(node);
cc.game._isCloning = false;
// restore preserved props
+13 -1
View File
@@ -268,11 +268,17 @@ test('prop initial times', function () {
});
var fooTester = Callback().enable();
var instanceMocker = {
ctor: Base, // mock constructor of class instance
ctor: Base, // mock constructor of class instance,
};
Object.defineProperty(instanceMocker, 'foo', {
set: fooTester
});
Object.defineProperty(instanceMocker, '__initProps__', {
get: function () {
return Base.prototype.__initProps__;
},
configurable: true
});
Base.call(instanceMocker);
fooTester.once('property should init once');
@@ -287,6 +293,12 @@ test('prop initial times', function () {
Object.defineProperty(instanceMocker, 'bar', {
set: barTester
});
Object.defineProperty(instanceMocker, '__initProps__', {
get: function () {
return Sub.prototype.__initProps__;
},
configurable: true
});
Sub.call(instanceMocker);
fooTester.once('foo prop should init once even if inherited');
barTester.once('bar prop should init once');
+43 -21
View File
@@ -1,17 +1,16 @@
largeModule('Instantiate');
(function () {
var match = function (obj, expect, info) {
deepEqual(cc.instantiate(obj), expect, info);
};
function testInstantiate (module, match, instantiate) {
largeModule(module);
test('basic', function () {
match({}, {}, 'smoke test1');
//match([], [], 'smoke test2');
match({ 1: 1, 2: [2, {3: '3'}]}, {1: 1, 2: [2, {3: '3'}]}, 'simple test1');
//match([1], [1], 'simple test2');
var obj = {};
var clone = cc.instantiate({
var clone = instantiate({
ref1: obj,
ref2: obj,
});
@@ -57,7 +56,7 @@
var expect = new MyAsset();
expect.dynamicProp = false;
var clone = cc.instantiate(asset);
var clone = instantiate(asset);
strictEqual(asset.constructor, clone.constructor, 'instantiated should has the same type');
deepEqual(clone, expect, 'can instantiate class');
@@ -69,13 +68,13 @@
var obj = new cc.Object();
obj._objFlags = cc.Object.Flags.EditorOnly;
var clone = cc.instantiate(obj);
var clone = instantiate(obj);
strictEqual(clone._objFlags, cc.Object.Flags.EditorOnly, 'can clone obj flags');
//var hashObj = new cc.HashObject();
//var id = hashObj.id; // generate id
//var clonedHashObj = cc.instantiate(hashObj);
//var clonedHashObj = instantiate(hashObj);
//
//notEqual(clonedHashObj.id, id, 'should not clone id');
//notEqual(clonedHashObj.hashCode, hashObj.hashCode, 'should not clone hashCode');
@@ -102,7 +101,7 @@
sprite.size = new cc.Vec2(32, 2);
sprite._isValid = false;
var clone = cc.instantiate(sprite);
var clone = instantiate(sprite);
strictEqual(sprite.constructor, clone.constructor, 'instantiated should has the same type');
deepEqual(clone.size, new cc.Vec2(32, 2), 'can clone variable defined by property');
@@ -116,7 +115,7 @@
var obj = {
pos: new cc.Vec2(1, 2)
};
var clone = cc.instantiate(obj);
var clone = instantiate(obj);
ok(obj.pos !== clone.pos, 'value type should be cloned');
strictEqual(obj.pos.x, clone.pos.x, 'checking x');
@@ -135,7 +134,7 @@
this.dict2 = {num: 2, other: this.dict1};
this.dict1.other = this.dict2;
}
var clone = cc.instantiate(new MyAsset());
var clone = instantiate(new MyAsset());
deepEqual(new MyAsset(), clone, 'can instantiate');
strictEqual(clone.array1[1], clone.array2, 'two arrays can circular reference each other 1');
@@ -148,7 +147,7 @@
var sprite = {};
sprite.sprite = new cc.SpriteFrame();
var clone = cc.instantiate(sprite);
var clone = instantiate(sprite);
ok(sprite.sprite === clone.sprite, 'should not clone asset');
});
@@ -159,7 +158,7 @@
child.parent = node;
cc.director.getScene().addChild(node);
var clone = cc.instantiate(node);
var clone = instantiate(node);
ok(clone.parent === null, 'root of cloned node should not have parent');
ok(clone.children[0].parent === clone, 'cloned child node should have parent');
@@ -174,7 +173,7 @@
var node = new cc.Node();
node.addComponent(Script);
var clone = cc.instantiate(node);
var clone = instantiate(node);
strictEqual(!!clone.getComponent(Script), true, 'should be added');
@@ -197,9 +196,9 @@
cc.Object._deferredDestroy();
var clone = cc.instantiate(node);
var clone = instantiate(node);
strictEqual(clone.getComponent(Script).compRef, null, 'deleted object should be nullify');
ok(clone.getComponent(Script).compRef === null, 'deleted object should be nullify');
});
test('redirect reference', function () {
@@ -242,13 +241,13 @@
childComp.nodeArrayInComp = [parent, other];
childComp.otherNodeInComp = other;
var cloneParent = cc.instantiate(parent);
var cloneParent = instantiate(parent);
var cloneChild = cloneParent._children[0];
var cloneParentComp = cloneParent.getComponent(Script);
var cloneChildComp = cloneChild.getComponent(Script);
notEqual(child, cloneChild, 'should clone child');
strictEqual(cloneChild.parent, cloneParent, 'should redirect parent reference');
ok(cloneChild.parent === cloneParent, 'should redirect parent reference');
ok(cloneParentComp.nodeInComp === cloneChild, 'should redirect child reference');
fastArrayEqual(cloneParentComp.nodeArrayInComp, [cloneChild, other], 'should redirect array of child reference');
@@ -262,4 +261,27 @@
cc.js.unregisterClass(Script);
});
})();
}
testInstantiate('Instantiate',
function (obj, expect, info) {
deepEqual(cc.instantiate(obj), expect, info);
},
cc.instantiate
);
testInstantiate('Instantiate-JIT',
function (obj, expect, info) {
var createCode = new cc._Test.IntantiateJit.compile(obj);
var res = createCode();
deepEqual(res, expect, info);
},
function instantiate (obj) {
var createCode = new cc._Test.IntantiateJit.compile(obj);
cc.game._isCloning = true;
var cloned = createCode();
if (obj._instantiate) {
obj._instantiate(cloned);
}
cc.game._isCloning = false;
return cloned;
}
);
+7 -1
View File
@@ -177,6 +177,10 @@
testNode.removeComponent(TestScript);
testNode.children[1].parent = null;
var originParent = testNode.parent = new cc.Node();
var outsideComp = originParent.addComponent(TestScript);
outsideComp.target = originParent;
testChild.x += 1;
testChild.scale = cc.Vec2.ZERO;
testChild.addComponent(TestScript);
@@ -192,6 +196,8 @@
ok(testNode.x != prefab.data.x, 'Should not revert root position');
ok(testNode.getScaleX() === 123 && testNode.getScaleY() === 432, 'Revert property of the parent node');
ok(testNode.getComponent(TestScript).constructor === TestScript, 'Restore removed component');
ok(testNode.parent === originParent, 'parent should not changed');
ok(testNode.parent.getComponent(TestScript).target === originParent, 'component property of parent should not changed');
ok(testChild.x === prefab.data.children[0].x, 'Revert child position');
ok(testChild.getScaleX() === 22 && testChild.getScaleY() === 11, 'Revert child node');
@@ -209,7 +215,7 @@
comp.resetExpect(CallbackTester.OnLoad, 'call onLoad while attaching to node');
comp.pushExpect(CallbackTester.OnEnable, 'then call onEnable if node active');
cc.director.getScene().addChild(testNode);
cc.director.getScene().addChild(testNode.parent);
comp.stopTest();