diff --git a/cocos/core/data/CCClassDecorator.js b/cocos/core/data/class-decorator.js similarity index 99% rename from cocos/core/data/CCClassDecorator.js rename to cocos/core/data/class-decorator.js index 14aaf61e57..e3300b9f0b 100644 --- a/cocos/core/data/CCClassDecorator.js +++ b/cocos/core/data/class-decorator.js @@ -38,7 +38,7 @@ // inspired by toddlxt (https://github.com/toddlxt/Creator-TypeScript-Boilerplate) -require('./CCClass'); +require('./class'); const Preprocess = require('./preprocess-class'); const js = require('./js'); const isPlainEmptyObj_DEV = CC_DEV && require('./utils').isPlainEmptyObj_DEV; diff --git a/cocos/core/data/CCClass.js b/cocos/core/data/class.js similarity index 93% rename from cocos/core/data/CCClass.js rename to cocos/core/data/class.js index d3d6486b7a..5981486b6c 100644 --- a/cocos/core/data/CCClass.js +++ b/cocos/core/data/class.js @@ -24,20 +24,19 @@ THE SOFTWARE. ****************************************************************************/ -var js = require('./js'); -var Enum = require('./CCEnum'); -var utils = require('./utils'); -var _isPlainEmptyObj_DEV = utils.isPlainEmptyObj_DEV; -var _cloneable_DEV = utils.cloneable_DEV; -var Attr = require('./attribute'); -var DELIMETER = Attr.DELIMETER; +import * as js from '../utils/js'; +import {isPlainEmptyObj_DEV, cloneable_DEV} from '../utils/misc'; +import Enum from '../value-types/enum'; +import {preprocessAttrs, validateMethodWithProps} from './utils/preprocess-class'; +import * as Attr from './utils/attribute'; +import * as RF from './utils/requiring-frame'; + +const DELIMETER = Attr.DELIMETER; + var getTypeChecker = Attr.getTypeChecker; -var preprocess = require('./preprocess-class'); -require('./requiring-frame'); -var BUILTIN_ENTRIES = ['name', 'extends', 'mixins', 'ctor', '__ctor__', 'properties', 'statics', 'editor', '__ES6__']; - -var INVALID_STATICS_DEV = CC_DEV && ['name', '__ctors__', '__props__', 'arguments', 'call', 'apply', 'caller', +const BUILTIN_ENTRIES = ['name', 'extends', 'mixins', 'ctor', '__ctor__', 'properties', 'statics', 'editor', '__ES6__']; +const INVALID_STATICS_DEV = CC_DEV && ['name', '__ctors__', '__props__', 'arguments', 'call', 'apply', 'caller', 'length', 'prototype']; function pushUnique (array, item) { @@ -120,9 +119,9 @@ function defineProp (cls, className, propName, val, es6) { return; } } - else if (!_isPlainEmptyObj_DEV(defaultValue)) { + else if (!isPlainEmptyObj_DEV(defaultValue)) { // check cloneable - if (!_cloneable_DEV(defaultValue)) { + if (!cloneable_DEV(defaultValue)) { cc.errorID(3636, className, propName, propName); return; } @@ -344,7 +343,7 @@ function doDefine (className, baseClass, mixins, options) { function define (className, baseClass, mixins, options) { var Component = cc.Component; - var frame = cc._RF.peek(); + var frame = RF.peek(); if (frame && js.isChildClassOf(baseClass, Component)) { // project component if (js.isChildClassOf(frame.cls, Component)) { @@ -552,7 +551,8 @@ function getInitProps (attrs, propList) { } // simple test variable name -var IDENTIFIER_RE = /^[A-Za-z_$][0-9A-Za-z_$]*$/; +const IDENTIFIER_RE = /^[A-Za-z_$][0-9A-Za-z_$]*$/; + function compileProps (actualClass) { // init deferred properties var attrs = Attr.getClassAttrs(actualClass); @@ -817,7 +817,7 @@ function declareProperties (cls, className, properties, baseClass, mixins, es6) if (properties) { // 预处理属性 - preprocess.preprocessAttrs(properties, className, cls, es6); + preprocessAttrs(properties, className, cls, es6); for (var propName in properties) { var val = properties[propName]; @@ -929,7 +929,7 @@ function declareProperties (cls, className, properties, baseClass, mixins, es6) obj.url = 'sprite.png'; obj.load(); */ -function CCClass (options) { +export default function CCClass (options) { options = options || {}; var name = options.name; @@ -990,7 +990,7 @@ function CCClass (options) { continue; } var func = options[funcName]; - if (!preprocess.validateMethodWithProps(func, funcName, name, cls, base)) { + if (!validateMethodWithProps(func, funcName, name, cls, base)) { continue; } // use value to redefine some super method defined as getter @@ -1027,13 +1027,13 @@ CCClass._isCCClass = function (constructor) { // // Optimized define function only for internal classes // -// @method _fastDefine +// @method fastDefine // @param {String} className // @param {Function} constructor // @param {Object} serializableFields // @private // -CCClass._fastDefine = function (className, constructor, serializableFields) { +CCClass.fastDefine = function (className, constructor, serializableFields) { js.setClassName(className, constructor); //constructor.__ctors__ = constructor.__ctors__ || null; var props = constructor.__props__ = constructor.__values__ = Object.keys(serializableFields); @@ -1044,7 +1044,6 @@ CCClass._fastDefine = function (className, constructor, serializableFields) { attrProtos[key + DELIMETER + 'default'] = serializableFields[key]; } }; - CCClass.Attr = Attr; CCClass.attr = Attr.attr; @@ -1106,42 +1105,35 @@ function parseAttributes (cls, attrs, className, propName, usedInGetter) { } } else { - if (type === Attr.ScriptUuid) { - var attr = Attr.ObjectType(cc.ScriptAsset); - attr.type = 'Script'; - result.push(attr); - } - else { - if (typeof type === 'object') { - if (Enum.isEnum(type)) { - result.push({ - type: 'Enum', - enumList: Enum.getList(type) - }); - } - else if (CC_DEV) { - cc.errorID(3645, className, propName, type); - } - } - else if (typeof type === 'function') { - if (attrs.url) { - result.push({ - type: 'Object', - ctor: type, - _onAfterProp: getTypeChecker('String', 'cc.String') - }); - } - else { - result.push(attrs._short ? { - type: 'Object', - ctor: type - } : Attr.ObjectType(type)); - } + if (typeof type === 'object') { + if (Enum.isEnum(type)) { + result.push({ + type: 'Enum', + enumList: Enum.getList(type) + }); } else if (CC_DEV) { - cc.errorID(3646, className, propName, type); + cc.errorID(3645, className, propName, type); } } + else if (typeof type === 'function') { + if (attrs.url) { + result.push({ + type: 'Object', + ctor: type, + _onAfterProp: getTypeChecker('String', 'cc.String') + }); + } + else { + result.push(attrs._short ? { + type: 'Object', + ctor: type + } : Attr.ObjectType(type)); + } + } + else if (CC_DEV) { + cc.errorID(3646, className, propName, type); + } } } @@ -1238,20 +1230,14 @@ function parseAttributes (cls, attrs, className, propName, usedInGetter) { return result; } -cc.Class = CCClass; - -module.exports = { - isArray: function (defaultVal) { - defaultVal = getDefault(defaultVal); - return Array.isArray(defaultVal); - }, - fastDefine: CCClass._fastDefine, - getNewValueTypeCode: CC_SUPPORT_JIT && getNewValueTypeCodeJit, - IDENTIFIER_RE, - escapeForJS, - getDefault: getDefault -}; - -if (CC_TEST) { - js.mixin(CCClass, module.exports); +CCClass.isArray = function (defaultVal) { + defaultVal = getDefault(defaultVal); + return Array.isArray(defaultVal); } + +CCClass.getDefault = getDefault; +CCClass.escapeForJS = escapeForJS; +CCClass.IDENTIFIER_RE = IDENTIFIER_RE; +CCClass.getNewValueTypeCode = CC_SUPPORT_JIT && getNewValueTypeCodeJit; + +cc.Class = CCClass; \ No newline at end of file diff --git a/cocos/core/data/deserialize.js b/cocos/core/data/deserialize.js index 1223b531cb..bb4e867849 100644 --- a/cocos/core/data/deserialize.js +++ b/cocos/core/data/deserialize.js @@ -24,10 +24,10 @@ THE SOFTWARE. ****************************************************************************/ -var js = require('./js'); -var Attr = require('./attribute'); -var CCClass = require('./CCClass'); -var misc = require('../utils/misc'); +import * as js from '../utils/js'; +import * as misc from '../utils/misc'; +import {CCClass} from './class'; +import * as Attr from './utils/attribute'; // HELPERS @@ -37,35 +37,68 @@ var misc = require('../utils/misc'); * @class Details * */ -var Details = function () { - /** - * list of the depends assets' uuid - * @property {String[]} uuidList - */ - this.uuidList = []; - /** - * the obj list whose field needs to load asset by uuid - * @property {Object[]} uuidObjList - */ - this.uuidObjList = []; - /** - * the corresponding field name which referenced to the asset - * @property {String[]} uuidPropList - */ - this.uuidPropList = []; +class Details { + constructor () { + /** + * list of the depends assets' uuid + * @property {String[]} uuidList + */ + this.uuidList = []; + /** + * the obj list whose field needs to load asset by uuid + * @property {Object[]} uuidObjList + */ + this.uuidObjList = []; + /** + * the corresponding field name which referenced to the asset + * @property {String[]} uuidPropList + */ + this.uuidPropList = []; + + // TODO - DELME since 2.0 + this._stillUseUrl = js.createMap(true); + } + + /** + * @method reset + */ + reset () { + this.uuidList.length = 0; + this.uuidObjList.length = 0; + this.uuidPropList.length = 0; + js.clear(this._stillUseUrl); + }; + + // /** + // * @method getUuidOf + // * @param {Object} obj + // * @param {String} propName + // * @return {String} + // */ + // getUuidOf (obj, propName) { + // for (var i = 0; i < this.uuidObjList.length; i++) { + // if (this.uuidObjList[i] === obj && this.uuidPropList[i] === propName) { + // return this.uuidList[i]; + // } + // } + // return ""; + // } + /** + * @method push + * @param {Object} obj + * @param {String} propName + * @param {String} uuid + */ + push (obj, propName, uuid, _stillUseUrl) { + if (_stillUseUrl) { + this._stillUseUrl[this.uuidList.length] = true; + } + this.uuidList.push(uuid); + this.uuidObjList.push(obj); + this.uuidPropList.push(propName); + } +} - // TODO - DELME since 2.0 - this._stillUseUrl = js.createMap(true); -}; -/** - * @method reset - */ -Details.prototype.reset = function () { - this.uuidList.length = 0; - this.uuidObjList.length = 0; - this.uuidPropList.length = 0; - js.clear(this._stillUseUrl); -}; if (CC_EDITOR || CC_TEST) { Details.prototype.assignAssetsBy = function (getter) { // ignore this._stillUseUrl @@ -77,34 +110,6 @@ if (CC_EDITOR || CC_TEST) { } }; } -// /** -// * @method getUuidOf -// * @param {Object} obj -// * @param {String} propName -// * @return {String} -// */ -// Details.prototype.getUuidOf = function (obj, propName) { -// for (var i = 0; i < this.uuidObjList.length; i++) { -// if (this.uuidObjList[i] === obj && this.uuidPropList[i] === propName) { -// return this.uuidList[i]; -// } -// } -// return ""; -// }; -/** - * @method push - * @param {Object} obj - * @param {String} propName - * @param {String} uuid - */ -Details.prototype.push = function (obj, propName, uuid, _stillUseUrl) { - if (_stillUseUrl) { - this._stillUseUrl[this.uuidList.length] = true; - } - this.uuidList.push(uuid); - this.uuidObjList.push(obj); - this.uuidPropList.push(propName); -}; Details.pool = new js.Pool(function (obj) { obj.reset(); @@ -116,8 +121,344 @@ Details.pool.get = function () { // IMPLEMENT OF DESERIALIZATION -var _Deserializer = (function () { - function _Deserializer(result, target, classFinder, customEnv, ignoreEditorOnly) { +function _dereference (self) { + // 这里不采用遍历反序列化结果的方式,因为反序列化的结果如果引用到复杂的外部库,很容易堆栈溢出。 + var deserializedList = self.deserializedList; + var idPropList = self._idPropList; + var idList = self._idList; + var idObjList = self._idObjList; + var onDereferenced = self._classFinder && self._classFinder.onDereferenced; + var i, propName, id; + if (CC_EDITOR && onDereferenced) { + for (i = 0; i < idList.length; i++) { + propName = idPropList[i]; + id = idList[i]; + idObjList[i][propName] = deserializedList[id]; + onDereferenced(deserializedList, id, idObjList[i], propName); + } + } + else { + for (i = 0; i < idList.length; i++) { + propName = idPropList[i]; + id = idList[i]; + idObjList[i][propName] = deserializedList[id]; + } + } +} + +function compileObjectTypeJit (sources, defaultValue, accessorToSet, propNameLiteralToSet, assumeHavePropIfIsValue, stillUseUrl) { + if (defaultValue instanceof cc.ValueType) { + // fast case + if (!assumeHavePropIfIsValue) { + sources.push('if(prop){'); + } + var ctorCode = js.getClassName(defaultValue); + sources.push(`s._deserializeTypedObject(o${accessorToSet},prop,${ctorCode});`); + if (!assumeHavePropIfIsValue) { + sources.push('}else o' + accessorToSet + '=null;'); + } + } + else { + sources.push('if(prop){'); + sources.push('s._deserializeObjField(o,prop,' + + propNameLiteralToSet + + ((CC_EDITOR || CC_TEST) ? ',t&&o,' : ',null,') + + !!stillUseUrl + + ');'); + sources.push('}else o' + accessorToSet + '=null;'); + } +} + +var compileDeserialize = CC_SUPPORT_JIT ? function (self, klass) { + var TYPE = Attr.DELIMETER + 'type'; + var EDITOR_ONLY = Attr.DELIMETER + 'editorOnly'; + var DEFAULT = Attr.DELIMETER + 'default'; + var SAVE_URL_AS_ASSET = Attr.DELIMETER + 'saveUrlAsAsset'; + var FORMERLY_SERIALIZED_AS = Attr.DELIMETER + 'formerlySerializedAs'; + var attrs = Attr.getClassAttrs(klass); + + var props = klass.__values__; + // self, obj, serializedData, klass, target + var sources = [ + 'var prop;' + ]; + var fastMode = misc.BUILTIN_CLASSID_RE.test(js._getClassId(klass)); + // sources.push('var vb,vn,vs,vo,vu,vf;'); // boolean, number, string, object, undefined, function + for (var p = 0; p < props.length; p++) { + var propName = props[p]; + if ((CC_PREVIEW || (CC_EDITOR && self._ignoreEditorOnly)) && attrs[propName + EDITOR_ONLY]) { + continue; // skip editor only if in preview + } + + var accessorToSet, propNameLiteralToSet; + if (CCClass.IDENTIFIER_RE.test(propName)) { + propNameLiteralToSet = '"' + propName + '"'; + accessorToSet = '.' + propName; + } + else { + propNameLiteralToSet = CCClass.escapeForJS(propName); + accessorToSet = '[' + propNameLiteralToSet + ']'; + } + + var accessorToGet = accessorToSet; + if (attrs[propName + FORMERLY_SERIALIZED_AS]) { + var propNameToRead = attrs[propName + FORMERLY_SERIALIZED_AS]; + if (CCClass.IDENTIFIER_RE.test(propNameToRead)) { + accessorToGet = '.' + propNameToRead; + } + else { + accessorToGet = '[' + CCClass.escapeForJS(propNameToRead) + ']'; + } + } + + sources.push('prop=d' + accessorToGet + ';'); + sources.push(`if(typeof ${CC_JSB ? '(prop)' : 'prop'}!=="undefined"){`); + + var stillUseUrl = attrs[propName + SAVE_URL_AS_ASSET]; + // function undefined object(null) string boolean number + var defaultValue = CCClass.getDefault(attrs[propName + DEFAULT]); + if (fastMode) { + var isPrimitiveType; + var userType = attrs[propName + TYPE]; + if (defaultValue === undefined && userType) { + isPrimitiveType = userType === cc.String || + userType === cc.Integer || + userType === cc.Float || + userType === cc.Boolean; + } + else { + var defaultType = typeof defaultValue; + isPrimitiveType = (defaultType === 'string' && !stillUseUrl) || + defaultType === 'number' || + defaultType === 'boolean'; + } + + if (isPrimitiveType) { + sources.push(`o${accessorToSet}=prop;`); + } + else { + compileObjectTypeJit(sources, defaultValue, accessorToSet, propNameLiteralToSet, true, stillUseUrl); + } + } + else { + sources.push(`if(typeof ${CC_JSB ? '(prop)' : 'prop'}!=="object"){` + + 'o' + accessorToSet + '=prop;' + + '}else{'); + compileObjectTypeJit(sources, defaultValue, accessorToSet, propNameLiteralToSet, false, stillUseUrl); + sources.push('}'); + } + sources.push('}'); + } + if (cc.js.isChildClassOf(klass, cc._BaseNode) || cc.js.isChildClassOf(klass, cc.Component)) { + if (CC_PREVIEW || (CC_EDITOR && self._ignoreEditorOnly)) { + var mayUsedInPersistRoot = js.isChildClassOf(klass, cc.Node); + if (mayUsedInPersistRoot) { + sources.push('d._id&&(o._id=d._id);'); + } + } + else { + sources.push('d._id&&(o._id=d._id);'); + } + } + if (props[props.length - 1] === '_$erialized') { + // deep copy original serialized data + sources.push('o._$erialized=JSON.parse(JSON.stringify(d));'); + // parse the serialized data as primitive javascript object, so its __id__ will be dereferenced + sources.push('s._deserializePrimitiveObject(o._$erialized,d);'); + } + return Function('s', 'o', 'd', 'k', 't', sources.join('')); +} : function (self, klass) { + var fastMode = misc.BUILTIN_CLASSID_RE.test(js._getClassId(klass)); + var shouldCopyId = cc.js.isChildClassOf(klass, cc._BaseNode) || cc.js.isChildClassOf(klass, cc.Component); + var shouldCopyRawData; + + var simpleProps = []; + var simplePropsToRead = simpleProps; + var advancedProps = []; + var advancedPropsToRead = advancedProps; + var advancedPropsUseUrl = []; + var advancedPropsValueType = []; + + (function () { + var props = klass.__values__; + shouldCopyRawData = props[props.length - 1] === '_$erialized'; + + var attrs = Attr.getClassAttrs(klass); + var TYPE = Attr.DELIMETER + 'type'; + var DEFAULT = Attr.DELIMETER + 'default'; + var SAVE_URL_AS_ASSET = Attr.DELIMETER + 'saveUrlAsAsset'; + var FORMERLY_SERIALIZED_AS = Attr.DELIMETER + 'formerlySerializedAs'; + + for (var p = 0; p < props.length; p++) { + var propName = props[p]; + var propNameToRead = propName; + if (attrs[propName + FORMERLY_SERIALIZED_AS]) { + propNameToRead = attrs[propName + FORMERLY_SERIALIZED_AS]; + } + var stillUseUrl = attrs[propName + SAVE_URL_AS_ASSET]; + // function undefined object(null) string boolean number + var defaultValue = CCClass.getDefault(attrs[propName + DEFAULT]); + var isPrimitiveType = false; + if (fastMode) { + var userType = attrs[propName + TYPE]; + if (defaultValue === undefined && userType) { + isPrimitiveType = userType === cc.String || + userType === cc.Integer || + userType === cc.Float || + userType === cc.Boolean; + } + else { + var defaultType = typeof defaultValue; + isPrimitiveType = (defaultType === 'string' && !stillUseUrl) || + defaultType === 'number' || + defaultType === 'boolean'; + } + } + if (fastMode && isPrimitiveType) { + if (propNameToRead !== propName && simplePropsToRead === simpleProps) { + simplePropsToRead = simpleProps.slice(); + } + simpleProps.push(propName); + if (simplePropsToRead !== simpleProps) { + simplePropsToRead.push(propNameToRead); + } + } + else { + if (propNameToRead !== propName && advancedPropsToRead === advancedProps) { + advancedPropsToRead = advancedProps.slice(); + } + advancedProps.push(propName); + if (advancedPropsToRead !== advancedProps) { + advancedPropsToRead.push(propNameToRead); + } + advancedPropsUseUrl.push(stillUseUrl); + advancedPropsValueType.push((defaultValue instanceof cc.ValueType) && defaultValue.constructor); + } + } + })(); + + return function (s, o, d, k, t) { + for (let i = 0; i < simpleProps.length; ++i) { + let prop = d[simplePropsToRead[i]]; + if (prop !== undefined) { + o[simpleProps[i]] = prop; + } + } + for (let i = 0; i < advancedProps.length; ++i) { + let propName = advancedProps[i]; + var prop = d[advancedPropsToRead[i]]; + if (prop === undefined) { + continue; + } + if (!fastMode && typeof prop !== 'object') { + o[propName] = prop; + } + else { + // fastMode (so will not simpleProp) or object + var valueTypeCtor = advancedPropsValueType[i]; + if (valueTypeCtor) { + if (fastMode || prop) { + s._deserializeTypedObject(o[propName], prop, valueTypeCtor); + } + else { + o[propName] = null; + } + } + else { + if (prop) { + s._deserializeObjField( + o, + prop, + propName, + (CC_EDITOR || CC_TEST) ? (t && o) : null, + advancedPropsUseUrl[i], + ); + } + else { + o[propName] = null; + } + } + } + } + if (shouldCopyId && d._id) { + o._id = d._id; + } + if (shouldCopyRawData) { + // deep copy original serialized data + o._$erialized = JSON.parse(JSON.stringify(d)); + // parse the serialized data as primitive javascript object, so its __id__ will be dereferenced + s._deserializePrimitiveObject(o._$erialized, d); + } + } +}; + +function unlinkUnusedPrefab (self, serialized, obj) { + var uuid = serialized['asset'] && serialized['asset'].__uuid__; + if (uuid) { + var last = self.result.uuidList.length - 1; + if (self.result.uuidList[last] === uuid && + self.result.uuidObjList[last] === obj && + self.result.uuidPropList[last] === 'asset') { + self.result.uuidList.pop(); + self.result.uuidObjList.pop(); + self.result.uuidPropList.pop(); + } + else { + var debugEnvOnlyInfo = 'Failed to skip prefab asset while deserializing PrefabInfo'; + cc.warn(debugEnvOnlyInfo); + } + } +} + +function _deserializeFireClass (self, obj, serialized, klass, target) { + var deserialize; + if (klass.hasOwnProperty('__deserialize__')) { + deserialize = klass.__deserialize__; + } + else { + deserialize = compileDeserialize(self, klass); + // if (CC_TEST && !isPhantomJS) { + // cc.log(deserialize); + // } + js.value(klass, '__deserialize__', deserialize, true); + } + deserialize(self, obj, serialized, klass, target); + // if preview or build worker + if (CC_PREVIEW || (CC_EDITOR && self._ignoreEditorOnly)) { + if (klass === cc._PrefabInfo && !obj.sync) { + unlinkUnusedPrefab(self, serialized, obj); + } + } +} + +// function _compileTypedObject (accessor, klass, ctorCode) { +// if (klass === cc.Vec2) { +// return `{` + +// `o${accessor}.x=prop.x||0;` + +// `o${accessor}.y=prop.y||0;` + +// `}`; +// } +// else if (klass === cc.Color) { +// return `{` + +// `o${accessor}.r=prop.r||0;` + +// `o${accessor}.g=prop.g||0;` + +// `o${accessor}.b=prop.b||0;` + +// `o${accessor}.a=(prop.a===undefined?255:prop.a);` + +// `}`; +// } +// else if (klass === cc.Size) { +// return `{` + +// `o${accessor}.width=prop.width||0;` + +// `o${accessor}.height=prop.height||0;` + +// `}`; +// } +// else { +// return `s._deserializeTypedObject(o${accessor},prop,${ctorCode});`; +// } +// } + +class _Deserializer { + constructor (result, target, classFinder, customEnv, ignoreEditorOnly) { this.result = result; this.customEnv = customEnv; this.deserializedList = []; @@ -132,34 +473,7 @@ var _Deserializer = (function () { this._idPropList = []; } - function _dereference (self) { - // 这里不采用遍历反序列化结果的方式,因为反序列化的结果如果引用到复杂的外部库,很容易堆栈溢出。 - var deserializedList = self.deserializedList; - var idPropList = self._idPropList; - var idList = self._idList; - var idObjList = self._idObjList; - var onDereferenced = self._classFinder && self._classFinder.onDereferenced; - var i, propName, id; - if (CC_EDITOR && onDereferenced) { - for (i = 0; i < idList.length; i++) { - propName = idPropList[i]; - id = idList[i]; - idObjList[i][propName] = deserializedList[id]; - onDereferenced(deserializedList, id, idObjList[i], propName); - } - } - else { - for (i = 0; i < idList.length; i++) { - propName = idPropList[i]; - id = idList[i]; - idObjList[i][propName] = deserializedList[id]; - } - } - } - - var prototype = _Deserializer.prototype; - - prototype.deserialize = function (jsonObj) { + deserialize (jsonObj) { if (Array.isArray(jsonObj)) { var jsonArray = jsonObj; var refCount = jsonArray.length; @@ -205,7 +519,7 @@ var _Deserializer = (function () { _dereference(this); return this.deserializedData; - }; + } ///** // * @param {Object} serialized - The obj to deserialize, must be non-nil @@ -214,7 +528,7 @@ var _Deserializer = (function () { // * @param {Object} [owner] - debug only // * @param {String} [propName] - debug only // */ - prototype._deserializeObject = function (serialized, _stillUseUrl, target, owner, propName) { + _deserializeObject (serialized, _stillUseUrl, target, owner, propName) { var prop; var obj = null; // the obj to return var klass = null; @@ -290,10 +604,10 @@ var _Deserializer = (function () { } } return obj; - }; + } // 和 _deserializeObject 不同的地方在于会判断 id 和 uuid - prototype._deserializeObjField = function (obj, jsonObj, propName, target, _stillUseUrl) { + _deserializeObjField (obj, jsonObj, propName, target, _stillUseUrl) { var id = jsonObj.__id__; if (id === undefined) { var uuid = jsonObj.__uuid__; @@ -329,9 +643,9 @@ var _Deserializer = (function () { this._idPropList.push(propName); } } - }; + } - prototype._deserializePrimitiveObject = function (instance, serialized) { + _deserializePrimitiveObject (instance, serialized) { var self = this; for (var propName in serialized) { if (serialized.hasOwnProperty(propName)) { @@ -357,35 +671,9 @@ var _Deserializer = (function () { } } - }; + } - // function _compileTypedObject (accessor, klass, ctorCode) { - // if (klass === cc.Vec2) { - // return `{` + - // `o${accessor}.x=prop.x||0;` + - // `o${accessor}.y=prop.y||0;` + - // `}`; - // } - // else if (klass === cc.Color) { - // return `{` + - // `o${accessor}.r=prop.r||0;` + - // `o${accessor}.g=prop.g||0;` + - // `o${accessor}.b=prop.b||0;` + - // `o${accessor}.a=(prop.a===undefined?255:prop.a);` + - // `}`; - // } - // else if (klass === cc.Size) { - // return `{` + - // `o${accessor}.width=prop.width||0;` + - // `o${accessor}.height=prop.height||0;` + - // `}`; - // } - // else { - // return `s._deserializeTypedObject(o${accessor},prop,${ctorCode});`; - // } - // } - - prototype._deserializeTypedObject = function (instance, serialized, klass) { + _deserializeTypedObject (instance, serialized, klass) { if (klass === cc.Vec2) { instance.x = serialized.x || 0; instance.y = serialized.y || 0; @@ -429,326 +717,38 @@ var _Deserializer = (function () { } } } - }; - - function compileObjectTypeJit (sources, defaultValue, accessorToSet, propNameLiteralToSet, assumeHavePropIfIsValue, stillUseUrl) { - if (defaultValue instanceof cc.ValueType) { - // fast case - if (!assumeHavePropIfIsValue) { - sources.push('if(prop){'); - } - var ctorCode = js.getClassName(defaultValue); - sources.push(`s._deserializeTypedObject(o${accessorToSet},prop,${ctorCode});`); - if (!assumeHavePropIfIsValue) { - sources.push('}else o' + accessorToSet + '=null;'); - } - } - else { - sources.push('if(prop){'); - sources.push('s._deserializeObjField(o,prop,' + - propNameLiteralToSet + - ((CC_EDITOR || CC_TEST) ? ',t&&o,' : ',null,') + - !!stillUseUrl + - ');'); - sources.push('}else o' + accessorToSet + '=null;'); - } } +} - var compileDeserialize = CC_SUPPORT_JIT ? function (self, klass) { - var TYPE = Attr.DELIMETER + 'type'; - var EDITOR_ONLY = Attr.DELIMETER + 'editorOnly'; - var DEFAULT = Attr.DELIMETER + 'default'; - var SAVE_URL_AS_ASSET = Attr.DELIMETER + 'saveUrlAsAsset'; - var FORMERLY_SERIALIZED_AS = Attr.DELIMETER + 'formerlySerializedAs'; - var attrs = Attr.getClassAttrs(klass); - - var props = klass.__values__; - // self, obj, serializedData, klass, target - var sources = [ - 'var prop;' - ]; - var fastMode = misc.BUILTIN_CLASSID_RE.test(js._getClassId(klass)); - // sources.push('var vb,vn,vs,vo,vu,vf;'); // boolean, number, string, object, undefined, function - for (var p = 0; p < props.length; p++) { - var propName = props[p]; - if ((CC_PREVIEW || (CC_EDITOR && self._ignoreEditorOnly)) && attrs[propName + EDITOR_ONLY]) { - continue; // skip editor only if in preview - } - - var accessorToSet, propNameLiteralToSet; - if (CCClass.IDENTIFIER_RE.test(propName)) { - propNameLiteralToSet = '"' + propName + '"'; - accessorToSet = '.' + propName; - } - else { - propNameLiteralToSet = CCClass.escapeForJS(propName); - accessorToSet = '[' + propNameLiteralToSet + ']'; - } - - var accessorToGet = accessorToSet; - if (attrs[propName + FORMERLY_SERIALIZED_AS]) { - var propNameToRead = attrs[propName + FORMERLY_SERIALIZED_AS]; - if (CCClass.IDENTIFIER_RE.test(propNameToRead)) { - accessorToGet = '.' + propNameToRead; - } - else { - accessorToGet = '[' + CCClass.escapeForJS(propNameToRead) + ']'; - } - } - - sources.push('prop=d' + accessorToGet + ';'); - sources.push(`if(typeof ${CC_JSB ? '(prop)' : 'prop'}!=="undefined"){`); - - var stillUseUrl = attrs[propName + SAVE_URL_AS_ASSET]; - // function undefined object(null) string boolean number - var defaultValue = CCClass.getDefault(attrs[propName + DEFAULT]); - if (fastMode) { - var isPrimitiveType; - var userType = attrs[propName + TYPE]; - if (defaultValue === undefined && userType) { - isPrimitiveType = userType === cc.String || - userType === cc.Integer || - userType === cc.Float || - userType === cc.Boolean; - } - else { - var defaultType = typeof defaultValue; - isPrimitiveType = (defaultType === 'string' && !stillUseUrl) || - defaultType === 'number' || - defaultType === 'boolean'; - } - - if (isPrimitiveType) { - sources.push(`o${accessorToSet}=prop;`); - } - else { - compileObjectTypeJit(sources, defaultValue, accessorToSet, propNameLiteralToSet, true, stillUseUrl); - } - } - else { - sources.push(`if(typeof ${CC_JSB ? '(prop)' : 'prop'}!=="object"){` + - 'o' + accessorToSet + '=prop;' + - '}else{'); - compileObjectTypeJit(sources, defaultValue, accessorToSet, propNameLiteralToSet, false, stillUseUrl); - sources.push('}'); - } - sources.push('}'); - } - if (cc.js.isChildClassOf(klass, cc._BaseNode) || cc.js.isChildClassOf(klass, cc.Component)) { - if (CC_PREVIEW || (CC_EDITOR && self._ignoreEditorOnly)) { - var mayUsedInPersistRoot = js.isChildClassOf(klass, cc.Node); - if (mayUsedInPersistRoot) { - sources.push('d._id&&(o._id=d._id);'); - } - } - else { - sources.push('d._id&&(o._id=d._id);'); - } - } - if (props[props.length - 1] === '_$erialized') { - // deep copy original serialized data - sources.push('o._$erialized=JSON.parse(JSON.stringify(d));'); - // parse the serialized data as primitive javascript object, so its __id__ will be dereferenced - sources.push('s._deserializePrimitiveObject(o._$erialized,d);'); - } - return Function('s', 'o', 'd', 'k', 't', sources.join('')); - } : function (self, klass) { - var fastMode = misc.BUILTIN_CLASSID_RE.test(js._getClassId(klass)); - var shouldCopyId = cc.js.isChildClassOf(klass, cc._BaseNode) || cc.js.isChildClassOf(klass, cc.Component); - var shouldCopyRawData; - - var simpleProps = []; - var simplePropsToRead = simpleProps; - var advancedProps = []; - var advancedPropsToRead = advancedProps; - var advancedPropsUseUrl = []; - var advancedPropsValueType = []; - - (function () { - var props = klass.__values__; - shouldCopyRawData = props[props.length - 1] === '_$erialized'; - - var attrs = Attr.getClassAttrs(klass); - var TYPE = Attr.DELIMETER + 'type'; - var DEFAULT = Attr.DELIMETER + 'default'; - var SAVE_URL_AS_ASSET = Attr.DELIMETER + 'saveUrlAsAsset'; - var FORMERLY_SERIALIZED_AS = Attr.DELIMETER + 'formerlySerializedAs'; - - for (var p = 0; p < props.length; p++) { - var propName = props[p]; - var propNameToRead = propName; - if (attrs[propName + FORMERLY_SERIALIZED_AS]) { - propNameToRead = attrs[propName + FORMERLY_SERIALIZED_AS]; - } - var stillUseUrl = attrs[propName + SAVE_URL_AS_ASSET]; - // function undefined object(null) string boolean number - var defaultValue = CCClass.getDefault(attrs[propName + DEFAULT]); - var isPrimitiveType = false; - if (fastMode) { - var userType = attrs[propName + TYPE]; - if (defaultValue === undefined && userType) { - isPrimitiveType = userType === cc.String || - userType === cc.Integer || - userType === cc.Float || - userType === cc.Boolean; - } - else { - var defaultType = typeof defaultValue; - isPrimitiveType = (defaultType === 'string' && !stillUseUrl) || - defaultType === 'number' || - defaultType === 'boolean'; - } - } - if (fastMode && isPrimitiveType) { - if (propNameToRead !== propName && simplePropsToRead === simpleProps) { - simplePropsToRead = simpleProps.slice(); - } - simpleProps.push(propName); - if (simplePropsToRead !== simpleProps) { - simplePropsToRead.push(propNameToRead); - } - } - else { - if (propNameToRead !== propName && advancedPropsToRead === advancedProps) { - advancedPropsToRead = advancedProps.slice(); - } - advancedProps.push(propName); - if (advancedPropsToRead !== advancedProps) { - advancedPropsToRead.push(propNameToRead); - } - advancedPropsUseUrl.push(stillUseUrl); - advancedPropsValueType.push((defaultValue instanceof cc.ValueType) && defaultValue.constructor); - } - } - })(); - - return function (s, o, d, k, t) { - for (let i = 0; i < simpleProps.length; ++i) { - let prop = d[simplePropsToRead[i]]; - if (prop !== undefined) { - o[simpleProps[i]] = prop; - } - } - for (let i = 0; i < advancedProps.length; ++i) { - let propName = advancedProps[i]; - var prop = d[advancedPropsToRead[i]]; - if (prop === undefined) { - continue; - } - if (!fastMode && typeof prop !== 'object') { - o[propName] = prop; - } - else { - // fastMode (so will not simpleProp) or object - var valueTypeCtor = advancedPropsValueType[i]; - if (valueTypeCtor) { - if (fastMode || prop) { - s._deserializeTypedObject(o[propName], prop, valueTypeCtor); - } - else { - o[propName] = null; - } - } - else { - if (prop) { - s._deserializeObjField( - o, - prop, - propName, - (CC_EDITOR || CC_TEST) ? (t && o) : null, - advancedPropsUseUrl[i], - ); - } - else { - o[propName] = null; - } - } - } - } - if (shouldCopyId && d._id) { - o._id = d._id; - } - if (shouldCopyRawData) { - // deep copy original serialized data - o._$erialized = JSON.parse(JSON.stringify(d)); - // parse the serialized data as primitive javascript object, so its __id__ will be dereferenced - s._deserializePrimitiveObject(o._$erialized, d); - } - } - }; - - function unlinkUnusedPrefab (self, serialized, obj) { - var uuid = serialized['asset'] && serialized['asset'].__uuid__; - if (uuid) { - var last = self.result.uuidList.length - 1; - if (self.result.uuidList[last] === uuid && - self.result.uuidObjList[last] === obj && - self.result.uuidPropList[last] === 'asset') { - self.result.uuidList.pop(); - self.result.uuidObjList.pop(); - self.result.uuidPropList.pop(); - } - else { - var debugEnvOnlyInfo = 'Failed to skip prefab asset while deserializing PrefabInfo'; - cc.warn(debugEnvOnlyInfo); - } - } +_Deserializer.pool = new js.Pool(function (obj) { + obj.result = null; + obj.customEnv = null; + obj.deserializedList.length = 0; + obj.deserializedData = null; + obj._classFinder = null; + if (CC_DEV) { + obj._target = null; } - - function _deserializeFireClass (self, obj, serialized, klass, target) { - var deserialize; - if (klass.hasOwnProperty('__deserialize__')) { - deserialize = klass.__deserialize__; - } - else { - deserialize = compileDeserialize(self, klass); - // if (CC_TEST && !isPhantomJS) { - // cc.log(deserialize); - // } - js.value(klass, '__deserialize__', deserialize, true); - } - deserialize(self, obj, serialized, klass, target); - // if preview or build worker - if (CC_PREVIEW || (CC_EDITOR && self._ignoreEditorOnly)) { - if (klass === cc._PrefabInfo && !obj.sync) { - unlinkUnusedPrefab(self, serialized, obj); - } - } - } - - _Deserializer.pool = new js.Pool(function (obj) { - obj.result = null; - obj.customEnv = null; - obj.deserializedList.length = 0; - obj.deserializedData = null; - obj._classFinder = null; + obj._idList.length = 0; + obj._idObjList.length = 0; + obj._idPropList.length = 0; +}, 1); +_Deserializer.pool.get = function (result, target, classFinder, customEnv, ignoreEditorOnly) { + var cache = this._get(); + if (cache) { + cache.result = result; + cache.customEnv = customEnv; + cache._classFinder = classFinder; if (CC_DEV) { - obj._target = null; + cache._target = target; + cache._ignoreEditorOnly = ignoreEditorOnly; } - obj._idList.length = 0; - obj._idObjList.length = 0; - obj._idPropList.length = 0; - }, 1); - - _Deserializer.pool.get = function (result, target, classFinder, customEnv, ignoreEditorOnly) { - var cache = this._get(); - if (cache) { - cache.result = result; - cache.customEnv = customEnv; - cache._classFinder = classFinder; - if (CC_DEV) { - cache._target = target; - cache._ignoreEditorOnly = ignoreEditorOnly; - } - return cache; - } - else { - return new _Deserializer(result, target, classFinder, customEnv, ignoreEditorOnly); - } - }; - - return _Deserializer; -})(); + return cache; + } + else { + return new _Deserializer(result, target, classFinder, customEnv, ignoreEditorOnly); + } +}; /** * @module cc @@ -767,7 +767,7 @@ var _Deserializer = (function () { * @param {Object} [options] * @return {object} the main data(asset) */ -cc.deserialize = function (data, details, options) { +export default function deserialize (data, details, options) { options = options || {}; var classFinder = options.classFinder || js._getClassById; // 启用 createAssetRefs 后,如果有 url 属性则会被统一强制设置为 { uuid: 'xxx' },必须后面再特殊处理 @@ -810,8 +810,8 @@ cc.deserialize = function (data, details, options) { return res; }; -cc.deserialize.Details = Details; -cc.deserialize.reportMissingClass = function (id) { +deserialize.Details = Details; +deserialize.reportMissingClass = function (id) { if (CC_EDITOR && Editor.Utils.UuidUtils.isUuid(id)) { id = Editor.Utils.UuidUtils.decompressUuid(id); cc.warnID(5301, id); @@ -819,4 +819,5 @@ cc.deserialize.reportMissingClass = function (id) { else { cc.warnID(5302, id); } -}; \ No newline at end of file +}; +cc.deserialize = deserialize; \ No newline at end of file diff --git a/cocos/core/data/index.js b/cocos/core/data/index.js new file mode 100644 index 0000000000..9048d0339e --- /dev/null +++ b/cocos/core/data/index.js @@ -0,0 +1,32 @@ +/**************************************************************************** + Copyright (c) 2018 Xiamen Yaji Software Co., Ltd. + + 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. + Xiamen Yaji Software Co., Ltd. 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. + ****************************************************************************/ + +import * as decorator from './class-decorator'; +cc._decorator = decorator; + +export { default as CCClass } from './class'; +export { default as CCObject } from './object'; +export { default as deserialize } from './deserialize'; +export { default as instantiate } from './instantiate'; \ No newline at end of file diff --git a/cocos/core/data/instantiate-jit.js b/cocos/core/data/instantiate-jit.js index e4cf8baa92..4b1b0435f3 100644 --- a/cocos/core/data/instantiate-jit.js +++ b/cocos/core/data/instantiate-jit.js @@ -26,17 +26,16 @@ // 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 Compiler = require('./compiler'); +import * as js from '../utils/js'; +import CCClass from './class'; +import CCObject from './object'; +import * as Attr from './utils/attribute'; +import {flattenCodeArray} from './utils/compiler'; -var DEFAULT = Attr.DELIMETER + 'default'; -var IDENTIFIER_RE = CCClass.IDENTIFIER_RE; -var escapeForJS = CCClass.escapeForJS; +const Destroyed = CCObject.Flags.Destroyed; +const PersistentMask = CCObject.Flags.PersistentMask; +const DEFAULT = Attr.DELIMETER + 'default'; +const IDENTIFIER_RE = CCClass.IDENTIFIER_RE; const VAR = 'var '; const LOCAL_OBJ = 'o'; @@ -55,17 +54,21 @@ const DEFAULT_MODULE_CACHE = { 'cc.PrefabInfo': false }; +var escapeForJS = CCClass.escapeForJS; + // HELPER CLASSES // ('foo', 'bar') // -> 'var foo = bar;' -function Declaration (varName, expression) { - this.varName = varName; - this.expression = expression; +class Declaration { + constructor (varName, expression) { + this.varName = varName; + this.expression = expression; + } + toString () { + return VAR + this.varName + '=' + this.expression + ';'; + } } -Declaration.prototype.toString = function () { - return VAR + this.varName + '=' + this.expression + ';'; -}; // ('a =', 'var b = x') // -> 'var b = a = x'; @@ -104,30 +107,32 @@ function writeAssignment (codeArray, statement, expression) { // -> 't = targetExpression;' // -> 't.foo1 = bar1;' // -> 't.foo2 = bar2;' -function Assignments (targetExpression) { - this._exps = []; - this._targetExp = targetExpression; +class Assignments { + constructor (targetExpression) { + this._exps = []; + this._targetExp = targetExpression; + } + append (key, expression) { + this._exps.push([key, expression]); + } + writeCode (codeArray) { + var targetVar; + if (this._exps.length > 1) { + codeArray.push(LOCAL_TEMP_OBJ + '=' + this._targetExp + ';'); + targetVar = LOCAL_TEMP_OBJ; + } + else if (this._exps.length === 1) { + targetVar = this._targetExp; + } + else { + return; + } + for (var i = 0; i < this._exps.length; i++) { + var pair = this._exps[i]; + writeAssignment(codeArray, targetVar + getPropAccessor(pair[0]) + '=', pair[1]); + } + } } -Assignments.prototype.append = function (key, expression) { - this._exps.push([key, expression]); -}; -Assignments.prototype.writeCode = function (codeArray) { - var targetVar; - if (this._exps.length > 1) { - codeArray.push(LOCAL_TEMP_OBJ + '=' + this._targetExp + ';'); - targetVar = LOCAL_TEMP_OBJ; - } - else if (this._exps.length === 1) { - targetVar = this._targetExp; - } - else { - return; - } - for (var i = 0; i < this._exps.length; i++) { - var pair = this._exps[i]; - writeAssignment(codeArray, targetVar + getPropAccessor(pair[0]) + '=', pair[1]); - } -}; Assignments.pool = new js.Pool(function (obj) { obj._exps.length = 0; @@ -141,7 +146,338 @@ Assignments.pool.get = function (targetExpression) { // HELPER FUNCTIONS -function equalsToDefault (def, value) { +function getPropAccessor (key) { + return IDENTIFIER_RE.test(key) ? ('.' + key) : ('[' + escapeForJS(key) + ']'); +} + +// + +/* + * 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 + */ +class Parser { + /* + * @method constructor + * @param {Object} obj - the object to parse + * @param {Node} [parent] + */ + constructor (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 = []; + + this.funcModuleCache = js.createMap(); + js.mixin(this.funcModuleCache, DEFAULT_MODULE_CACHE); + + // {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 + ',' + LOCAL_TEMP_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(['return (function(R){', + globalVariablesDeclaration || [], + this.codeArray, + 'return o;', + '})']); + + // generate method and bind with objs + this.result = Function('O', 'F', code)(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; + } + + getFuncModule (func, usedInNew) { + var clsName = js.getClassName(func); + if (clsName) { + var cache = this.funcModuleCache[clsName]; + if (cache) { + return cache; + } + else if (cache === undefined) { + var clsNameIsModule = clsName.indexOf('.') !== -1; + if (clsNameIsModule) { + try { + // ensure is module + clsNameIsModule = (func === Function('return ' + clsName)()); + if (clsNameIsModule) { + this.funcModuleCache[clsName] = clsName; + 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 + ']'; + if (usedInNew) { + res = '(' + res + ')'; + } + this.funcModuleCache[clsName] = res; + return res; + } + + getObjRef (obj) { + var index = this.objs.indexOf(obj); + if (index < 0) { + index = this.objs.length; + this.objs.push(obj); + } + return 'O[' + index + ']'; + } + + setValueType (codeArray, defaultValue, srcValue, targetExpression) { + var assignments = Assignments.pool.get(targetExpression); + var fastDefinedProps = defaultValue.constructor.__props__; + if (!fastDefinedProps) { + fastDefinedProps = Object.keys(defaultValue); + } + for (var i = 0; i < fastDefinedProps.length; i++) { + var propName = fastDefinedProps[i]; + var prop = srcValue[propName]; + if (defaultValue[propName] === prop) { + continue; + } + var expression = this.enumerateField(srcValue, propName, prop); + assignments.append(propName, expression); + } + assignments.writeCode(codeArray); + Assignments.pool.put(assignments); + } + + enumerateCCClass (codeArray, obj, klass) { + var props = klass.__values__; + var attrs = Attr.getClassAttrs(klass); + for (var p = 0; p < props.length; p++) { + var key = props[p]; + var val = obj[key]; + var defaultValue = attrs[key + DEFAULT]; + if (equalsToDefault(defaultValue, val)) { + continue; + } + if (typeof val === 'object' && val instanceof cc.ValueType) { + defaultValue = CCClass.getDefault(defaultValue); + if (defaultValue && defaultValue.constructor === val.constructor) { + // fast case + var targetExpression = LOCAL_OBJ + getPropAccessor(key); + this.setValueType(codeArray, defaultValue, val, targetExpression); + continue; + } + } + this.setObjProp(codeArray, obj, key, val); + } + } + + instantiateArray (value) { + if (value.length === 0) { + return '[]'; + } + + var arrayVar = LOCAL_ARRAY + (++this.localVariableId); + var declaration = new Declaration(arrayVar, 'new Array(' + value.length + ')'); + var codeArray = [declaration]; + + // 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 statement = arrayVar + '[' + i + ']='; + var expression = this.enumerateField(value, i, value[i]); + writeAssignment(codeArray, statement, expression); + } + return codeArray; + } + + enumerateField (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]; + _iN$t.source[LINE_INDEX_OF_NEW_OBJ] = mergeDeclaration(globalVar + '=', line); + // if (typeof line ==='string' && 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); + // } + } + 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 escapeForJS(value); + } + else { + if (key === '_objFlags' && (obj instanceof CCObject)) { + value &= PersistentMask; + } + return value; + } + } + + setObjProp (codeArray, obj, key, value) { + var statement = LOCAL_OBJ + getPropAccessor(key) + '='; + var expression = this.enumerateField(obj, key, value); + writeAssignment(codeArray, statement, expression); + } + + // codeArray - the source code array for this object + enumerateObject (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.setObjProp(codeArray, obj, key, value); + } + } + } + + instantiateObj (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 = new Declaration(LOCAL_OBJ, 'new ' + this.getFuncModule(ctor, true) + '()'); + } + else if (ctor === Object) { + createCode = new Declaration(LOCAL_OBJ, '{}'); + } + else if (!ctor) { + createCode = new Declaration(LOCAL_OBJ, 'Object.create(null)'); + } + 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 ['(function(){', + codeArray, + 'return o;})();']; + } +} + +export function equalsToDefault (def, value) { if (typeof def === 'function') { try { def = def(); @@ -170,349 +506,12 @@ function equalsToDefault (def, value) { return false; } -function getPropAccessor (key) { - return IDENTIFIER_RE.test(key) ? ('.' + key) : ('[' + escapeForJS(key) + ']'); -} - -// - -/* - * 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 = []; - - this.funcModuleCache = js.createMap(); - js.mixin(this.funcModuleCache, DEFAULT_MODULE_CACHE); - - // {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 + ',' + LOCAL_TEMP_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 = Compiler.flattenCodeArray(['return (function(R){', - globalVariablesDeclaration || [], - this.codeArray, - 'return o;', - '})']); - - // generate method and bind with objs - this.result = Function('O', 'F', code)(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; -} - -var proto = Parser.prototype; - -proto.getFuncModule = function (func, usedInNew) { - var clsName = js.getClassName(func); - if (clsName) { - var cache = this.funcModuleCache[clsName]; - if (cache) { - return cache; - } - else if (cache === undefined) { - var clsNameIsModule = clsName.indexOf('.') !== -1; - if (clsNameIsModule) { - try { - // ensure is module - clsNameIsModule = (func === Function('return ' + clsName)()); - if (clsNameIsModule) { - this.funcModuleCache[clsName] = clsName; - 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 + ']'; - if (usedInNew) { - res = '(' + res + ')'; - } - this.funcModuleCache[clsName] = res; - return res; -}; - -proto.getObjRef = function (obj) { - var index = this.objs.indexOf(obj); - if (index < 0) { - index = this.objs.length; - this.objs.push(obj); - } - return 'O[' + index + ']'; -}; - -proto.setValueType = function (codeArray, defaultValue, srcValue, targetExpression) { - var assignments = Assignments.pool.get(targetExpression); - var fastDefinedProps = defaultValue.constructor.__props__; - if (!fastDefinedProps) { - fastDefinedProps = Object.keys(defaultValue); - } - for (var i = 0; i < fastDefinedProps.length; i++) { - var propName = fastDefinedProps[i]; - var prop = srcValue[propName]; - if (defaultValue[propName] === prop) { - continue; - } - var expression = this.enumerateField(srcValue, propName, prop); - assignments.append(propName, expression); - } - assignments.writeCode(codeArray); - Assignments.pool.put(assignments); -}; - -proto.enumerateCCClass = function (codeArray, obj, klass) { - var props = klass.__values__; - var attrs = Attr.getClassAttrs(klass); - for (var p = 0; p < props.length; p++) { - var key = props[p]; - var val = obj[key]; - var defaultValue = attrs[key + DEFAULT]; - if (equalsToDefault(defaultValue, val)) { - continue; - } - if (typeof val === 'object' && val instanceof cc.ValueType) { - defaultValue = CCClass.getDefault(defaultValue); - if (defaultValue && defaultValue.constructor === val.constructor) { - // fast case - var targetExpression = LOCAL_OBJ + getPropAccessor(key); - this.setValueType(codeArray, defaultValue, val, targetExpression); - continue; - } - } - this.setObjProp(codeArray, obj, key, val); - } -}; - -proto.instantiateArray = function (value) { - if (value.length === 0) { - return '[]'; - } - - var arrayVar = LOCAL_ARRAY + (++this.localVariableId); - var declaration = new Declaration(arrayVar, 'new Array(' + value.length + ')'); - var codeArray = [declaration]; - - // 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 statement = arrayVar + '[' + i + ']='; - var expression = this.enumerateField(value, i, value[i]); - writeAssignment(codeArray, statement, expression); - } - return codeArray; -}; - -proto.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]; - _iN$t.source[LINE_INDEX_OF_NEW_OBJ] = mergeDeclaration(globalVar + '=', line); - // if (typeof line ==='string' && 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); - // } - } - 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 escapeForJS(value); - } - else { - if (key === '_objFlags' && (obj instanceof CCObject)) { - value &= PersistentMask; - } - return value; - } -}; - -proto.setObjProp = function (codeArray, obj, key, value) { - var statement = LOCAL_OBJ + getPropAccessor(key) + '='; - var expression = this.enumerateField(obj, key, value); - writeAssignment(codeArray, statement, expression); -}; - -// codeArray - the source code array for this object -proto.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.setObjProp(codeArray, obj, key, value); - } - } -}; - -proto.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 = new Declaration(LOCAL_OBJ, 'new ' + this.getFuncModule(ctor, true) + '()'); - } - else if (ctor === Object) { - createCode = new Declaration(LOCAL_OBJ, '{}'); - } - else if (!ctor) { - createCode = new Declaration(LOCAL_OBJ, 'Object.create(null)'); - } - 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 ['(function(){', - codeArray, - 'return o;})();']; -}; - - -function compile (node) { +export 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; } diff --git a/cocos/core/data/instantiate.js b/cocos/core/data/instantiate.js index ec672f8d22..2a978447f0 100644 --- a/cocos/core/data/instantiate.js +++ b/cocos/core/data/instantiate.js @@ -24,11 +24,14 @@ THE SOFTWARE. ****************************************************************************/ -var CCObject = require('./CCObject'); -var CCValueType = require('../value-types/value-type'); -var Destroyed = CCObject.Flags.Destroyed; -var PersistentMask = CCObject.Flags.PersistentMask; -var _isDomNode = require('./utils').isDomNode; +import CCObject from './object'; +import ValueType from '../value-types/value-type'; +import {isDomNode} from '../utils/misc'; + +const Destroyed = CCObject.Flags.Destroyed; +const PersistentMask = CCObject.Flags.PersistentMask; + +var objsToClearTmpVar = []; // used to reset _iN$t variable /** * !#en Clones the object `original` and returns the clone, or instantiate a node from the Prefab. @@ -52,7 +55,7 @@ var _isDomNode = require('./utils').isDomNode; * var node = cc.instantiate(targetNode); * node.parent = scene; */ -function instantiate (original, internal_force) { +export default function instantiate (original, internal_force) { if (!internal_force) { if (typeof original !== 'object' || Array.isArray(original)) { if (CC_DEV) { @@ -106,19 +109,17 @@ function instantiate (original, internal_force) { return clone; } -var objsToClearTmpVar = []; // used to reset _iN$t variable - -///** -// * Do instantiate object, the object to instantiate must be non-nil. -// * 这是一个通用的 instantiate 方法,可能效率比较低。 -// * 之后可以给各种类型重写快速实例化的特殊实现,但应该在单元测试中将结果和这个方法的结果进行对比。 -// * 值得注意的是,这个方法不可重入。 -// * -// * @param {Object} obj - 该方法仅供内部使用,用户需负责保证参数合法。什么参数是合法的请参考 cc.instantiate 的实现。 -// * @param {Node} [parent] - 只有在该对象下的场景物体会被克隆。 -// * @return {Object} -// * @private -// */ +/* + * Do instantiate object, the object to instantiate must be non-nil. + * 这是一个通用的 instantiate 方法,可能效率比较低。 + * 之后可以给各种类型重写快速实例化的特殊实现,但应该在单元测试中将结果和这个方法的结果进行对比。 + * 值得注意的是,这个方法不可重入。 + * + * @param {Object} obj - 该方法仅供内部使用,用户需负责保证参数合法。什么参数是合法的请参考 cc.instantiate 的实现。 + * @param {Node} [parent] - 只有在该对象下的场景物体会被克隆。 + * @return {Object} + * @private + */ function doInstantiate (obj, parent) { if (Array.isArray(obj)) { if (CC_DEV) { @@ -126,7 +127,7 @@ function doInstantiate (obj, parent) { } return null; } - if (_isDomNode && _isDomNode(obj)) { + if (isDomNode && isDomNode(obj)) { if (CC_DEV) { cc.errorID(6905); } @@ -166,7 +167,7 @@ function enumerateCCClass (klass, obj, clone, parent) { var value = obj[key]; if (typeof value === 'object' && value) { var initValue = clone[key]; - if (initValue instanceof CCValueType && + if (initValue instanceof ValueType && initValue.constructor === value.constructor) { initValue.set(value); } @@ -220,7 +221,7 @@ function enumerateObject (obj, clone, parent) { * @return {Object|Array} - the original non-nil object, typeof must be 'object' */ function instantiateObj (obj, parent) { - if (obj instanceof CCValueType) { + if (obj instanceof ValueType) { return obj.clone(); } if (obj instanceof cc.Asset) { @@ -290,4 +291,3 @@ function instantiateObj (obj, parent) { instantiate._clone = doInstantiate; cc.instantiate = instantiate; -module.exports = instantiate; diff --git a/cocos/core/data/CCObject.js b/cocos/core/data/object.js similarity index 60% rename from cocos/core/data/CCObject.js rename to cocos/core/data/object.js index 37eb6dddbc..c9413a7529 100644 --- a/cocos/core/data/CCObject.js +++ b/cocos/core/data/object.js @@ -23,45 +23,124 @@ THE SOFTWARE. ****************************************************************************/ -var js = require('./js'); -var CCClass = require('./CCClass'); +import * as js from '../utils/js'; +import {CCClass} from './class'; // definitions for CCObject.Flags -var Destroyed = 1 << 0; -var RealDestroyed = 1 << 1; -var ToDestroy = 1 << 2; -var DontSave = 1 << 3; -var EditorOnly = 1 << 4; -var Dirty = 1 << 5; -var DontDestroy = 1 << 6; -var Destroying = 1 << 7; -var Deactivating = 1 << 8; -var LockedInEditor = 1 << 9; +const Destroyed = 1 << 0; +const RealDestroyed = 1 << 1; +const ToDestroy = 1 << 2; +const DontSave = 1 << 3; +const EditorOnly = 1 << 4; +const Dirty = 1 << 5; +const DontDestroy = 1 << 6; +const Destroying = 1 << 7; +const Deactivating = 1 << 8; +const LockedInEditor = 1 << 9; //var HideInGame = 1 << 9; //var HideInEditor = 1 << 10; -var IsOnEnableCalled = 1 << 11; -var IsEditorOnEnableCalled = 1 << 12; -var IsPreloadStarted = 1 << 13; -var IsOnLoadCalled = 1 << 14; -var IsOnLoadStarted = 1 << 15; -var IsStartCalled = 1 << 16; +const IsOnEnableCalled = 1 << 11; +const IsEditorOnEnableCalled = 1 << 12; +const IsPreloadStarted = 1 << 13; +const IsOnLoadCalled = 1 << 14; +const IsOnLoadStarted = 1 << 15; +const IsStartCalled = 1 << 16; -var IsRotationLocked = 1 << 17; -var IsScaleLocked = 1 << 18; -var IsAnchorLocked = 1 << 19; -var IsSizeLocked = 1 << 20; -var IsPositionLocked = 1 << 21; +const IsRotationLocked = 1 << 17; +const IsScaleLocked = 1 << 18; +const IsAnchorLocked = 1 << 19; +const IsSizeLocked = 1 << 20; +const IsPositionLocked = 1 << 21; //var Hide = HideInGame | HideInEditor; // should not clone or serialize these flags -var PersistentMask = ~(ToDestroy | Dirty | Destroying | DontDestroy | Deactivating | +const PersistentMask = ~(ToDestroy | Dirty | Destroying | DontDestroy | Deactivating | IsPreloadStarted | IsOnLoadStarted | IsOnLoadCalled | IsStartCalled | IsOnEnableCalled | IsEditorOnEnableCalled | IsRotationLocked | IsScaleLocked | IsAnchorLocked | IsSizeLocked | IsPositionLocked /*RegisteredInEditor*/); +var objectsToDestroy = []; +var deferredDestroyTimer = null; + +function compileDestruct (obj, ctor) { + var shouldSkipId = obj instanceof cc._BaseNode || obj instanceof cc.Component; + var idToSkip = shouldSkipId ? '_id' : null; + + var key, propsToReset = {}; + for (key in obj) { + if (obj.hasOwnProperty(key)) { + if (key === idToSkip) { + continue; + } + switch (typeof obj[key]) { + case 'string': + propsToReset[key] = ''; + break; + case 'object': + case 'function': + propsToReset[key] = null; + break; + } + } + } + // Overwrite propsToReset according to Class + if (CCClass._isCCClass(ctor)) { + var attrs = cc.Class.Attr.getClassAttrs(ctor); + var propList = ctor.__props__; + for (var i = 0; i < propList.length; i++) { + key = propList[i]; + var attrKey = key + cc.Class.Attr.DELIMETER + 'default'; + if (attrKey in attrs) { + if (shouldSkipId && key === '_id') { + continue; + } + switch (typeof attrs[attrKey]) { + case 'string': + propsToReset[key] = ''; + break; + case 'object': + case 'function': + propsToReset[key] = null; + break; + case 'undefined': + propsToReset[key] = undefined; + break; + } + } + } + } + + if (CC_SUPPORT_JIT) { + // compile code + var func = ''; + for (key in propsToReset) { + var statement; + if (CCClass.IDENTIFIER_RE.test(key)) { + statement = 'o.' + key + '='; + } + else { + statement = 'o[' + CCClass.escapeForJS(key) + ']='; + } + var val = propsToReset[key]; + if (val === '') { + val = '""'; + } + func += (statement + val + ';\n'); + } + return Function('o', func); + } + else { + return function (o) { + for (var key in propsToReset) { + o[key] = propsToReset[key]; + } + }; + } +} + /** * The base class of most of all the objects in Fireball. * @class Object @@ -69,26 +148,241 @@ var PersistentMask = ~(ToDestroy | Dirty | Destroying | DontDestroy | Deactivati * @main * @private */ -function CCObject () { - /** - * @property {String} _name - * @default "" - * @private - */ - this._name = ''; +export default class CCObject { + constructor () { + /** + * @property {String} _name + * @default "" + * @private + */ + this._name = ''; + + /** + * @property {Number} _objFlags + * @default 0 + * @private + */ + this._objFlags = 0; + } + + _deferredDestroy () { + var deleteCount = objectsToDestroy.length; + for (var i = 0; i < deleteCount; ++i) { + var obj = objectsToDestroy[i]; + if (!(obj._objFlags & Destroyed)) { + obj._destroyImmediate(); + } + } + // if we called b.destory() in a.onDestroy(), objectsToDestroy will be resized, + // but we only destroy the objects which called destory in this frame. + if (deleteCount === objectsToDestroy.length) { + objectsToDestroy.length = 0; + } + else { + objectsToDestroy.splice(0, deleteCount); + } + + if (CC_EDITOR) { + deferredDestroyTimer = null; + } + } + + // MEMBER /** - * @property {Number} _objFlags - * @default 0 + * !#en The name of the object. + * !#zh 该对象的名称。 + * @property {String} name + * @default "" + * @example + * obj.name = "New Obj"; + */ + get name () { + return this._name; + } + set name (value) { + this._name = value; + } + + /** + * !#en + * Indicates whether the object is not yet destroyed. (It will not be available after being destroyed)
+ * When an object's `destroy` is called, it is actually destroyed after the end of this frame. + * So `isValid` will return false from the next frame, while `isValid` in the current frame will still be true. + * If you want to determine whether the current frame has called `destroy`, use `cc.isValid(obj, true)`, + * but this is often caused by a particular logical requirements, which is not normally required. + * + * !#zh + * 表示该对象是否可用(被 destroy 后将不可用)。
+ * 当一个对象的 `destroy` 调用以后,会在这一帧结束后才真正销毁。因此从下一帧开始 `isValid` 就会返回 false,而当前帧内 `isValid` 仍然会是 true。如果希望判断当前帧是否调用过 `destroy`,请使用 `cc.isValid(obj, true)`,不过这往往是特殊的业务需求引起的,通常情况下不需要这样。 + * + * @property {Boolean} isValid + * @default true + * @readOnly + * @example + * var node = new cc.Node(); + * cc.log(node.isValid); // true + * node.destroy(); + * cc.log(node.isValid); // true, still valid in this frame + * // after a frame... + * cc.log(node.isValid); // false, destroyed in the end of last frame + */ + get isValid () { + return !(this._objFlags & Destroyed); + } + + /** + * !#en + * Destroy this Object, and release all its own references to other objects.
+ * Actual object destruction will delayed until before rendering. + * From the next frame, this object is not usable any more. + * You can use cc.isValid(obj) to check whether the object is destroyed before accessing it. + * !#zh + * 销毁该对象,并释放所有它对其它对象的引用。
+ * 实际销毁操作会延迟到当前帧渲染前执行。从下一帧开始,该对象将不再可用。 + * 您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。 + * @method destroy + * @return {Boolean} whether it is the first time the destroy being called + * @example + * obj.destroy(); + */ + destroy () { + if (this._objFlags & Destroyed) { + cc.warnID(5000); + return false; + } + if (this._objFlags & ToDestroy) { + return false; + } + this._objFlags |= ToDestroy; + objectsToDestroy.push(this); + + if (CC_EDITOR && deferredDestroyTimer === null && cc.engine && ! cc.engine._isUpdating) { + // auto destroy immediate in edit mode + deferredDestroyTimer = setImmediate(this.deferredDestroy); + } + return true; + } + + /** + * Clear all references in the instance. + * + * NOTE: this method will not clear the getter or setter functions which defined in the instance of CCObject. + * You can override the _destruct method if you need, for example: + * _destruct: function () { + * for (var key in this) { + * if (this.hasOwnProperty(key)) { + * switch (typeof this[key]) { + * case 'string': + * this[key] = ''; + * break; + * case 'object': + * case 'function': + * this[key] = null; + * break; + * } + * } + * } + * + * @method _destruct * @private */ - this._objFlags = 0; + _destruct () { + var ctor = this.constructor; + var destruct = ctor.__destruct__; + if (!destruct) { + destruct = compileDestruct(this, ctor); + js.value(ctor, '__destruct__', destruct, true); + } + destruct(this); + } + + _destroyImmediate () { + if (this._objFlags & Destroyed) { + cc.errorID(5000); + return; + } + // engine internal callback + if (this._onPreDestroy) { + this._onPreDestroy(); + } + + if ((CC_TEST ? (/* make CC_EDITOR mockable*/ Function('return !CC_EDITOR'))() : !CC_EDITOR) || cc.engine._isPlaying) { + this._destruct(); + } + + this._objFlags |= Destroyed; + } } + +let prototype = CCObject.prototype; +if (CC_EDITOR || CC_TEST) { + js.get(prototype, 'isRealValid', function () { + return !(this._objFlags & RealDestroyed); + }); + + /* + * !#en + * In fact, Object's "destroy" will not trigger the destruct operation in Firebal Editor. + * The destruct operation will be executed by Undo system later. + * !#zh + * 事实上,对象的 “destroy” 不会在编辑器中触发析构操作, + * 析构操作将在 Undo 系统中**延后**执行。 + * @method realDestroyInEditor + * @private + */ + prototype.realDestroyInEditor = function () { + if ( !(this._objFlags & Destroyed) ) { + cc.warnID(5001); + return; + } + if (this._objFlags & RealDestroyed) { + cc.warnID(5000); + return; + } + this._destruct(); + this._objFlags |= RealDestroyed; + }; +} + +if (CC_EDITOR) { + js.value(CCObject, '_clearDeferredDestroyTimer', function () { + if (deferredDestroyTimer !== null) { + clearImmediate(deferredDestroyTimer); + deferredDestroyTimer = null; + } + }); + + /** + * The customized serialization for this object. (Editor Only) + * @method _serialize + * @param {Boolean} exporting + * @return {object} the serialized json data object + * @private + */ + prototype._serialize = null; +} + +/** + * Init this object from the custom serialized data. + * @method _deserialize + * @param {Object} data - the serialized json data + * @param {_Deserializer} ctx + * @private + */ +prototype._deserialize = null; +/** + * Called before the object being destroyed. + * @method _onPreDestroy + * @private + */ +prototype._onPreDestroy = null; + CCClass.fastDefine('cc.Object', CCObject, { _name: '', _objFlags: 0 }); /** * Bit mask that controls object states. - * @enum Flags + * @enum Object.Flags * @static * @private */ @@ -194,313 +488,6 @@ js.value(CCObject, 'Flags', { IsSizeLocked, }); -var objectsToDestroy = []; - -function deferredDestroy () { - var deleteCount = objectsToDestroy.length; - for (var i = 0; i < deleteCount; ++i) { - var obj = objectsToDestroy[i]; - if (!(obj._objFlags & Destroyed)) { - obj._destroyImmediate(); - } - } - // if we called b.destory() in a.onDestroy(), objectsToDestroy will be resized, - // but we only destroy the objects which called destory in this frame. - if (deleteCount === objectsToDestroy.length) { - objectsToDestroy.length = 0; - } - else { - objectsToDestroy.splice(0, deleteCount); - } - - if (CC_EDITOR) { - deferredDestroyTimer = null; - } -} - -js.value(CCObject, '_deferredDestroy', deferredDestroy); - -if (CC_EDITOR) { - js.value(CCObject, '_clearDeferredDestroyTimer', function () { - if (deferredDestroyTimer !== null) { - clearImmediate(deferredDestroyTimer); - deferredDestroyTimer = null; - } - }); -} - -// MEMBER - -/** - * @class Object - */ - -var prototype = CCObject.prototype; - -/** - * !#en The name of the object. - * !#zh 该对象的名称。 - * @property {String} name - * @default "" - * @example - * obj.name = "New Obj"; - */ -js.getset(prototype, 'name', - function () { - return this._name; - }, - function (value) { - this._name = value; - }, - true -); - -/** - * !#en - * Indicates whether the object is not yet destroyed. (It will not be available after being destroyed)
- * When an object's `destroy` is called, it is actually destroyed after the end of this frame. - * So `isValid` will return false from the next frame, while `isValid` in the current frame will still be true. - * If you want to determine whether the current frame has called `destroy`, use `cc.isValid(obj, true)`, - * but this is often caused by a particular logical requirements, which is not normally required. - * - * !#zh - * 表示该对象是否可用(被 destroy 后将不可用)。
- * 当一个对象的 `destroy` 调用以后,会在这一帧结束后才真正销毁。因此从下一帧开始 `isValid` 就会返回 false,而当前帧内 `isValid` 仍然会是 true。如果希望判断当前帧是否调用过 `destroy`,请使用 `cc.isValid(obj, true)`,不过这往往是特殊的业务需求引起的,通常情况下不需要这样。 - * - * @property {Boolean} isValid - * @default true - * @readOnly - * @example - * var node = new cc.Node(); - * cc.log(node.isValid); // true - * node.destroy(); - * cc.log(node.isValid); // true, still valid in this frame - * // after a frame... - * cc.log(node.isValid); // false, destroyed in the end of last frame - */ -js.get(prototype, 'isValid', function () { - return !(this._objFlags & Destroyed); -}, true); - -if (CC_EDITOR || CC_TEST) { - js.get(prototype, 'isRealValid', function () { - return !(this._objFlags & RealDestroyed); - }); -} - -var deferredDestroyTimer = null; - -/** - * !#en - * Destroy this Object, and release all its own references to other objects.
- * Actual object destruction will delayed until before rendering. - * From the next frame, this object is not usable any more. - * You can use cc.isValid(obj) to check whether the object is destroyed before accessing it. - * !#zh - * 销毁该对象,并释放所有它对其它对象的引用。
- * 实际销毁操作会延迟到当前帧渲染前执行。从下一帧开始,该对象将不再可用。 - * 您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。 - * @method destroy - * @return {Boolean} whether it is the first time the destroy being called - * @example - * obj.destroy(); - */ -prototype.destroy = function () { - if (this._objFlags & Destroyed) { - cc.warnID(5000); - return false; - } - if (this._objFlags & ToDestroy) { - return false; - } - this._objFlags |= ToDestroy; - objectsToDestroy.push(this); - - if (CC_EDITOR && deferredDestroyTimer === null && cc.engine && ! cc.engine._isUpdating) { - // auto destroy immediate in edit mode - deferredDestroyTimer = setImmediate(deferredDestroy); - } - return true; -}; - -if (CC_EDITOR || CC_TEST) { - /* - * !#en - * In fact, Object's "destroy" will not trigger the destruct operation in Firebal Editor. - * The destruct operation will be executed by Undo system later. - * !#zh - * 事实上,对象的 “destroy” 不会在编辑器中触发析构操作, - * 析构操作将在 Undo 系统中**延后**执行。 - * @method realDestroyInEditor - * @private - */ - prototype.realDestroyInEditor = function () { - if ( !(this._objFlags & Destroyed) ) { - cc.warnID(5001); - return; - } - if (this._objFlags & RealDestroyed) { - cc.warnID(5000); - return; - } - this._destruct(); - this._objFlags |= RealDestroyed; - }; -} - -function compileDestruct (obj, ctor) { - var shouldSkipId = obj instanceof cc._BaseNode || obj instanceof cc.Component; - var idToSkip = shouldSkipId ? '_id' : null; - - var key, propsToReset = {}; - for (key in obj) { - if (obj.hasOwnProperty(key)) { - if (key === idToSkip) { - continue; - } - switch (typeof obj[key]) { - case 'string': - propsToReset[key] = ''; - break; - case 'object': - case 'function': - propsToReset[key] = null; - break; - } - } - } - // Overwrite propsToReset according to Class - if (cc.Class._isCCClass(ctor)) { - var attrs = cc.Class.Attr.getClassAttrs(ctor); - var propList = ctor.__props__; - for (var i = 0; i < propList.length; i++) { - key = propList[i]; - var attrKey = key + cc.Class.Attr.DELIMETER + 'default'; - if (attrKey in attrs) { - if (shouldSkipId && key === '_id') { - continue; - } - switch (typeof attrs[attrKey]) { - case 'string': - propsToReset[key] = ''; - break; - case 'object': - case 'function': - propsToReset[key] = null; - break; - case 'undefined': - propsToReset[key] = undefined; - break; - } - } - } - } - - if (CC_SUPPORT_JIT) { - // compile code - var func = ''; - for (key in propsToReset) { - var statement; - if (CCClass.IDENTIFIER_RE.test(key)) { - statement = 'o.' + key + '='; - } - else { - statement = 'o[' + CCClass.escapeForJS(key) + ']='; - } - var val = propsToReset[key]; - if (val === '') { - val = '""'; - } - func += (statement + val + ';\n'); - } - return Function('o', func); - } - else { - return function (o) { - for (var key in propsToReset) { - o[key] = propsToReset[key]; - } - }; - } -} - -/** - * Clear all references in the instance. - * - * NOTE: this method will not clear the getter or setter functions which defined in the instance of CCObject. - * You can override the _destruct method if you need, for example: - * _destruct: function () { - * for (var key in this) { - * if (this.hasOwnProperty(key)) { - * switch (typeof this[key]) { - * case 'string': - * this[key] = ''; - * break; - * case 'object': - * case 'function': - * this[key] = null; - * break; - * } - * } - * } - * - * @method _destruct - * @private - */ -prototype._destruct = function () { - var ctor = this.constructor; - var destruct = ctor.__destruct__; - if (!destruct) { - destruct = compileDestruct(this, ctor); - js.value(ctor, '__destruct__', destruct, true); - } - destruct(this); -}; - -/** - * Called before the object being destroyed. - * @method _onPreDestroy - * @private - */ -prototype._onPreDestroy = null; - -prototype._destroyImmediate = function () { - if (this._objFlags & Destroyed) { - cc.errorID(5000); - return; - } - // engine internal callback - if (this._onPreDestroy) { - this._onPreDestroy(); - } - - if ((CC_TEST ? (/* make CC_EDITOR mockable*/ Function('return !CC_EDITOR'))() : !CC_EDITOR) || cc.engine._isPlaying) { - this._destruct(); - } - - this._objFlags |= Destroyed; -}; - -if (CC_EDITOR) { - /** - * The customized serialization for this object. (Editor Only) - * @method _serialize - * @param {Boolean} exporting - * @return {object} the serialized json data object - * @private - */ - prototype._serialize = null; -} - -/** - * Init this object from the custom serialized data. - * @method _deserialize - * @param {Object} data - the serialized json data - * @param {_Deserializer} ctx - * @private - */ -prototype._deserialize = null; - /** * @module cc */ @@ -548,4 +535,4 @@ if (CC_EDITOR || CC_TEST) { }); } -cc.Object = module.exports = CCObject; +cc.Object = CCObject; diff --git a/cocos/core/data/utils/attribute.js b/cocos/core/data/utils/attribute.js index f60548fad0..9a7d97ef9d 100644 --- a/cocos/core/data/utils/attribute.js +++ b/cocos/core/data/utils/attribute.js @@ -24,12 +24,12 @@ THE SOFTWARE. ****************************************************************************/ -var js = require('./js'); -var isPlainEmptyObj = require('./utils').isPlainEmptyObj_DEV; +import * as js from '../../utils/js'; +import {isPlainEmptyObj_DEV} from '../../utils/misc'; -const DELIMETER = '$_$'; +export const DELIMETER = '$_$'; -function createAttrsSingle (owner, ownerCtor, superAttrs) { +export function createAttrsSingle (owner, ownerCtor, superAttrs) { var AttrsCtor; if (CC_DEV && CC_SUPPORT_JIT) { var ctorName = ownerCtor.name; @@ -53,7 +53,7 @@ function createAttrsSingle (owner, ownerCtor, superAttrs) { } // subclass should not have __attrs__ -function createAttrs (subclass) { +export function createAttrs (subclass) { var superClass; var chains = cc.Class.getInheritanceChain(subclass); for (var i = chains.length - 1; i >= 0; i--) { @@ -83,7 +83,7 @@ function createAttrs (subclass) { // * @param {Object} [newAttrs] - the attribute table to mark, new attributes will merged with existed attributes. Attribute whose key starts with '_' will be ignored. // * @static // * @private -function attr (ctor, propName, newAttrs) { +export function attr (ctor, propName, newAttrs) { var attrs, setter, key; if (typeof ctor === 'function') { // attributes shared between instances @@ -129,16 +129,16 @@ function attr (ctor, propName, newAttrs) { } // returns a readonly meta object -function getClassAttrs (ctor) { +export function getClassAttrs (ctor) { return (ctor.hasOwnProperty('__attrs__') && ctor.__attrs__) || createAttrs(ctor); } // returns a writable meta object, used to set multi attributes -function getClassAttrsProto (ctor) { +export function getClassAttrsProto (ctor) { return getClassAttrs(ctor).constructor.prototype; } -function setClassAttr (ctor, propName, key, value) { +export function setClassAttr (ctor, propName, key, value) { var proto = getClassAttrsProto(ctor); proto[propName + DELIMETER + key] = value; } @@ -243,7 +243,7 @@ Callbacks: { } */ -function getTypeChecker (type, attrName) { +export function getTypeChecker (type, attrName) { if (CC_DEV) { return function (constructor, mainPropName) { var propInfo = '"' + js.getClassName(constructor) + '.' + mainPropName + '"'; @@ -265,7 +265,7 @@ function getTypeChecker (type, attrName) { if (typeof defaultVal === 'undefined') { return; } - var isContainer = Array.isArray(defaultVal) || isPlainEmptyObj(defaultVal); + var isContainer = Array.isArray(defaultVal) || isPlainEmptyObj_DEV(defaultVal); if (isContainer) { return; } @@ -316,7 +316,7 @@ function getTypeChecker (type, attrName) { } } -function ObjectType (typeCtor) { +export function ObjectType (typeCtor) { return { type: 'Object', ctor: typeCtor, @@ -324,7 +324,7 @@ function ObjectType (typeCtor) { getTypeChecker('Object', 'type')(classCtor, mainPropName); // check ValueType var defaultDef = getClassAttrs(classCtor)[mainPropName + DELIMETER + 'default']; - var defaultVal = require('./CCClass').getDefault(defaultDef); + var defaultVal = cc.Class.getDefault(defaultDef); if (!Array.isArray(defaultVal) && js.isChildClassOf(typeCtor, cc.ValueType)) { var typename = js.getClassName(typeCtor); var info = cc.js.formatStr('No need to specify the "type" of "%s.%s" because %s is a child class of ValueType.', @@ -339,14 +339,3 @@ function ObjectType (typeCtor) { } }; } - -module.exports = { - attr: attr, - getClassAttrs: getClassAttrs, - getClassAttrsProto: getClassAttrsProto, - setClassAttr: setClassAttr, - DELIMETER: DELIMETER, - getTypeChecker: getTypeChecker, - ObjectType: ObjectType, - ScriptUuid: {}, // the value will be represented as a uuid string -}; diff --git a/cocos/core/data/utils/compiler.js b/cocos/core/data/utils/compiler.js index f667267420..5169b0ed9a 100644 --- a/cocos/core/data/utils/compiler.js +++ b/cocos/core/data/utils/compiler.js @@ -39,13 +39,9 @@ function deepFlatten (strList, array) { } } -function flattenCodeArray (array) { +export function flattenCodeArray (array) { var separator = CC_DEV ? '\n' : ''; var strList = []; deepFlatten(strList, array); return strList.join(separator); -} - -module.exports = { - flattenCodeArray -}; +} \ No newline at end of file diff --git a/cocos/core/data/utils/preprocess-class.js b/cocos/core/data/utils/preprocess-class.js index 89778c4b84..15ded4cc95 100644 --- a/cocos/core/data/utils/preprocess-class.js +++ b/cocos/core/data/utils/preprocess-class.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -const js = require('./js'); +import * as js from '../../utils/js'; // 增加预处理属性这个步骤的目的是降低 CCClass 的实现难度,将比较稳定的通用逻辑和一些需求比较灵活的属性需求分隔开。 @@ -160,7 +160,7 @@ function checkUrl (val, className, propName, url) { function parseType (val, type, className, propName) { if (Array.isArray(type)) { if (CC_EDITOR) { - var isArray = require('./CCClass').isArray; // require lazily to avoid circular require() calls + var isArray = cc.Class.isArray; // require lazily to avoid circular require() calls if (!isArray(val.default)) { cc.warnID(5507, className, propName); } @@ -216,7 +216,7 @@ function getBaseClassWherePropertyDefined_DEV (propName, cls) { } } -exports.getFullFormOfProperty = function (options, propname_dev, classname_dev) { +export function getFullFormOfProperty (options, propname_dev, classname_dev) { var isLiteral = options && options.constructor === Object; if ( !isLiteral ) { if (Array.isArray(options) && options.length > 0) { @@ -293,7 +293,7 @@ exports.getFullFormOfProperty = function (options, propname_dev, classname_dev) return null; }; -exports.preprocessAttrs = function (properties, className, cls, es6) { +export function preprocessAttrs (properties, className, cls, es6) { for (var propName in properties) { var val = properties[propName]; var fullForm = exports.getFullFormOfProperty(val, propName, className); @@ -353,7 +353,7 @@ exports.preprocessAttrs = function (properties, className, cls, es6) { if (CC_DEV) { const CALL_SUPER_DESTROY_REG_DEV = /\b\._super\b|destroy\s*\.\s*call\s*\(\s*\w+\s*[,|)]/; - exports.doValidateMethodWithProps_DEV = function (func, funcName, className, cls, base) { + export function doValidateMethodWithProps_DEV (func, funcName, className, cls, base) { if (cls.__props__ && cls.__props__.indexOf(funcName) >= 0) { // find class that defines this method as a property var baseClassName = js.getClassName(getBaseClassWherePropertyDefined_DEV(funcName, cls)); @@ -369,7 +369,7 @@ if (CC_DEV) { }; } -exports.validateMethodWithProps = function (func, funcName, className, cls, base) { +export function validateMethodWithProps (func, funcName, className, cls, base) { if (CC_DEV && funcName === 'constructor') { cc.errorID(3643, className); return false; diff --git a/cocos/core/data/utils/requiring-frame.js b/cocos/core/data/utils/requiring-frame.js index 2dadbe1302..d5927dd755 100644 --- a/cocos/core/data/utils/requiring-frame.js +++ b/cocos/core/data/utils/requiring-frame.js @@ -26,37 +26,43 @@ var requiringFrames = []; // the requiring frame infos -cc._RF = { - push: function (module, uuid, script) { - if (script === undefined) { - script = uuid; - uuid = ''; - } - requiringFrames.push({ - uuid: uuid, - script: script, - module: module, - exports: module.exports, // original exports - beh: null - }); - }, - pop: function () { - var frameInfo = requiringFrames.pop(); - // check exports - var module = frameInfo.module; - var exports = module.exports; - if (exports === frameInfo.exports) { - for (var anyKey in exports) { - // exported - return; - } - // auto export component - module.exports = exports = frameInfo.cls; - } - }, - peek: function () { - return requiringFrames[requiringFrames.length - 1]; +export function push (module, uuid, script) { + if (script === undefined) { + script = uuid; + uuid = ''; } + requiringFrames.push({ + uuid: uuid, + script: script, + module: module, + exports: module.exports, // original exports + beh: null + }); +} + +export function pop () { + var frameInfo = requiringFrames.pop(); + // check exports + var module = frameInfo.module; + var exports = module.exports; + if (exports === frameInfo.exports) { + for (var anyKey in exports) { + // exported + return; + } + // auto export component + module.exports = exports = frameInfo.cls; + } +} + +export function peek () { + return requiringFrames[requiringFrames.length - 1]; +} + +cc._RF = { + push, + pop, + peek }; if (CC_EDITOR) { diff --git a/cocos/core/value-types/color.js b/cocos/core/value-types/color.js index 1f7f85a805..ca0391f45d 100644 --- a/cocos/core/value-types/color.js +++ b/cocos/core/value-types/color.js @@ -25,7 +25,7 @@ ****************************************************************************/ import ValueType from './value-type'; -import Class from '../data/CCClass'; +import CCClass from '../data/class'; /** * !#en @@ -544,7 +544,7 @@ export default class Color extends ValueType { } } -Class.fastDefine('cc.Color', Color, {r: 0, g: 0, b: 0, a: 255}); +CCClass.fastDefine('cc.Color', Color, {r: 0, g: 0, b: 0, a: 255}); /** * @module cc diff --git a/cocos/core/value-types/mat4.js b/cocos/core/value-types/mat4.js index 340ac74616..c300257517 100644 --- a/cocos/core/value-types/mat4.js +++ b/cocos/core/value-types/mat4.js @@ -24,7 +24,7 @@ ****************************************************************************/ import ValueType from './value-type'; -import Class from '../data/CCClass'; +import CCClass from '../data/class'; import {mat4} from '../vmath'; /** @@ -359,7 +359,7 @@ export default class Mat4 extends ValueType { } }; -Class.fastDefine('cc.Mat4', Mat4, { +CCClass.fastDefine('cc.Mat4', Mat4, { m00: 1, m01: 0, m02: 0, m03: 0, m04: 0, m05: 1, m06: 0, m07: 0, m08: 0, m09: 0, m10: 1, m11: 0, diff --git a/cocos/core/value-types/quat.js b/cocos/core/value-types/quat.js index 96c75dc362..c21f92c47e 100644 --- a/cocos/core/value-types/quat.js +++ b/cocos/core/value-types/quat.js @@ -24,7 +24,7 @@ ****************************************************************************/ import ValueType from './value-type'; -import Class from '../data/CCClass'; +import CCClass from '../data/class'; /** * !#en Representation of 2D vectors and points. @@ -135,7 +135,7 @@ export default class Quat extends ValueType { } } -Class.fastDefine('cc.Quat', Quat, { x: 0, y: 0, z: 0, w: 1 }); +CCClass.fastDefine('cc.Quat', Quat, { x: 0, y: 0, z: 0, w: 1 }); /** * @module cc diff --git a/cocos/core/value-types/rect.js b/cocos/core/value-types/rect.js index d909ac88a9..fb837deb20 100644 --- a/cocos/core/value-types/rect.js +++ b/cocos/core/value-types/rect.js @@ -25,7 +25,7 @@ ****************************************************************************/ import ValueType from './value-type'; -import Class from '../data/CCClass'; +import CCClass from '../data/class'; /** * !#en A 2D rectangle defined by x, y position and width, height. @@ -394,7 +394,7 @@ export default class Rect extends ValueType { } } -Class.fastDefine('cc.Rect', Rect, { x: 0, y: 0, width: 0, height: 0 }); +CCClass.fastDefine('cc.Rect', Rect, { x: 0, y: 0, width: 0, height: 0 }); cc.Rect = Rect; diff --git a/cocos/core/value-types/size.js b/cocos/core/value-types/size.js index 771a8bddb4..9f78eb1cb6 100644 --- a/cocos/core/value-types/size.js +++ b/cocos/core/value-types/size.js @@ -25,7 +25,7 @@ ****************************************************************************/ import ValueType from './value-type'; -import Class from '../data/CCClass'; +import CCClass from '../data/class'; /** * !#en @@ -150,7 +150,7 @@ export default class Size extends ValueType { } } -Class.fastDefine('cc.Size', Size, { width: 0, height: 0}); +CCClass.fastDefine('cc.Size', Size, { width: 0, height: 0}); /** * @module cc diff --git a/cocos/core/value-types/vec2.js b/cocos/core/value-types/vec2.js index 691fe2c670..0ebe52761d 100644 --- a/cocos/core/value-types/vec2.js +++ b/cocos/core/value-types/vec2.js @@ -25,7 +25,7 @@ ****************************************************************************/ import ValueType from './value-type'; -import Class from '../data/CCClass'; +import CCClass from '../data/class'; import {vec2} from '../vmath'; import {clampf} from '../utils/misc'; @@ -640,7 +640,7 @@ export default class Vec2 extends ValueType { } } -Class.fastDefine('cc.Vec2', Vec2, { x: 0, y: 0 }); +CCClass.fastDefine('cc.Vec2', Vec2, { x: 0, y: 0 }); cc.Vec2 = Vec2; diff --git a/cocos/core/value-types/vec3.js b/cocos/core/value-types/vec3.js index 22dbb810f6..930781fbea 100644 --- a/cocos/core/value-types/vec3.js +++ b/cocos/core/value-types/vec3.js @@ -25,7 +25,7 @@ ****************************************************************************/ import ValueType from './value-type'; -import Class from '../data/CCClass'; +import CCClass from '../data/class'; import {vec3} from '../vmath'; import {clampf} from '../utils/misc'; diff --git a/test/qunit/unit-es5/test-class.js b/test/qunit/unit-es5/test-class.js index 6bbc168e9d..0703b427b4 100644 --- a/test/qunit/unit-es5/test-class.js +++ b/test/qunit/unit-es5/test-class.js @@ -444,7 +444,7 @@ test('_isCCClass', function () { function ctor () { this.foo = 0; } - cc.Class._fastDefine('T', ctor, ['foo']); + cc.Class.fastDefine('T', ctor, ['foo']); strictEqual(cc.Class._isCCClass(ctor), false, 'fastDefined ctor should not recognized as CCClass'); cc.js.unregisterClass(ctor); diff --git a/test/qunit/unit-es5/test-deserialize.js b/test/qunit/unit-es5/test-deserialize.js index e1566af8b8..3fc903234b 100644 --- a/test/qunit/unit-es5/test-deserialize.js +++ b/test/qunit/unit-es5/test-deserialize.js @@ -120,7 +120,7 @@ if (TestEditorExtends) { function Vec3 (x, y, z) { this.data = [x, y, z]; } - cc.Class._fastDefine('Vec3', Vec3, { x: 0, y: 0, z: 0, }); + cc.Class.fastDefine('Vec3', Vec3, { x: 0, y: 0, z: 0, }); Object.defineProperties(Vec3.prototype, { x: { diff --git a/test/qunit/unit-es5/test-serialize.js b/test/qunit/unit-es5/test-serialize.js index de860260bc..bcc7b78e01 100644 --- a/test/qunit/unit-es5/test-serialize.js +++ b/test/qunit/unit-es5/test-serialize.js @@ -242,7 +242,7 @@ function Vec3 (x, y, z) { this.data = [x, y, z]; } - cc.Class._fastDefine('Vec3', Vec3, { x: 0, y: 0, z: 0, }); + cc.Class.fastDefine('Vec3', Vec3, { x: 0, y: 0, z: 0, }); Object.defineProperties(Vec3.prototype, { x: { diff --git a/test/qunit/unit/test-class.js b/test/qunit/unit/test-class.js index 334c2bd28b..2914d2d6d6 100644 --- a/test/qunit/unit/test-class.js +++ b/test/qunit/unit/test-class.js @@ -521,7 +521,7 @@ largeModule('Class ES6'); function ctor () { this.foo = 0; } - cc.Class._fastDefine('T', ctor, ['foo']); + cc.Class.fastDefine('T', ctor, ['foo']); strictEqual(cc.Class._isCCClass(ctor), false, 'fastDefined ctor should not recognized as CCClass'); cc.js.unregisterClass(ctor);