diff --git a/cocos/core/utils/texture-util.js b/cocos/assets/texture-util.js similarity index 100% rename from cocos/core/utils/texture-util.js rename to cocos/assets/texture-util.js diff --git a/cocos/core/platform/js.js b/cocos/core/platform/js.js deleted file mode 100644 index fbdca5da42..0000000000 --- a/cocos/core/platform/js.js +++ /dev/null @@ -1,991 +0,0 @@ -/**************************************************************************** - Copyright (c) 2008-2010 Ricardo Quesada - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - 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. - ****************************************************************************/ - -const tempCIDGenerater = new (require('./id-generater'))('TmpCId.'); - - -function _getPropertyDescriptor (obj, name) { - while (obj) { - var pd = Object.getOwnPropertyDescriptor(obj, name); - if (pd) { - return pd; - } - obj = Object.getPrototypeOf(obj); - } - return null; -} - -function _copyprop(name, source, target) { - var pd = _getPropertyDescriptor(source, name); - Object.defineProperty(target, name, pd); -} - -/** - * This module provides some JavaScript utilities. - * All members can be accessed with "cc.js". - * @submodule js - * @module js - */ -var js = { - - /** - * Check the obj whether is number or not - * If a number is created by using 'new Number(10086)', the typeof it will be "object"... - * Then you can use this function if you care about this case. - * @method isNumber - * @param {*} obj - * @returns {Boolean} - */ - isNumber: function(obj) { - return typeof obj === 'number' || obj instanceof Number; - }, - - /** - * Check the obj whether is string or not. - * If a string is created by using 'new String("blabla")', the typeof it will be "object"... - * Then you can use this function if you care about this case. - * @method isString - * @param {*} obj - * @returns {Boolean} - */ - isString: function(obj) { - return typeof obj === 'string' || obj instanceof String; - }, - - /** - * Copy all properties not defined in obj from arguments[1...n] - * @method addon - * @param {Object} obj object to extend its properties - * @param {Object} ...sourceObj source object to copy properties from - * @return {Object} the result obj - */ - addon: function (obj) { - 'use strict'; - obj = obj || {}; - for (var i = 1, length = arguments.length; i < length; i++) { - var source = arguments[i]; - if (source) { - if (typeof source !== 'object') { - cc.errorID(5402, source); - continue; - } - for ( var name in source) { - if ( !(name in obj) ) { - _copyprop( name, source, obj); - } - } - } - } - return obj; - }, - - /** - * copy all properties from arguments[1...n] to obj - * @method mixin - * @param {Object} obj - * @param {Object} ...sourceObj - * @return {Object} the result obj - */ - mixin: function (obj) { - 'use strict'; - obj = obj || {}; - for (var i = 1, length = arguments.length; i < length; i++) { - var source = arguments[i]; - if (source) { - if (typeof source !== 'object') { - cc.errorID(5403, source); - continue; - } - for ( var name in source) { - _copyprop( name, source, obj); - } - } - } - return obj; - }, - - /** - * Derive the class from the supplied base class. - * Both classes are just native javascript constructors, not created by cc.Class, so - * usually you will want to inherit using {{#crossLink "cc/Class:method"}}cc.Class {{/crossLink}} instead. - * @method extend - * @param {Function} cls - * @param {Function} base - the baseclass to inherit - * @return {Function} the result class - */ - extend: function (cls, base) { - if (CC_DEV) { - if (!base) { - cc.errorID(5404); - return; - } - if (!cls) { - cc.errorID(5405); - return; - } - if (Object.keys(cls.prototype).length > 0) { - cc.errorID(5406); - } - } - for (var p in base) if (base.hasOwnProperty(p)) cls[p] = base[p]; - cls.prototype = Object.create(base.prototype, { - constructor: { - value: cls, - writable: true, - configurable: true - } - }); - return cls; - }, - - /** - * Get super class - * @method getSuper - * @param {Function} ctor - the constructor of subclass - * @return {Function} - */ - getSuper (ctor) { - var proto = ctor.prototype; // binded function do not have prototype - var dunderProto = proto && Object.getPrototypeOf(proto); - return dunderProto && dunderProto.constructor; - }, - - /** - * Checks whether subclass is child of superclass or equals to superclass - * - * @method isChildClassOf - * @param {Function} subclass - * @param {Function} superclass - * @return {Boolean} - */ - isChildClassOf (subclass, superclass) { - if (subclass && superclass) { - if (typeof subclass !== 'function') { - return false; - } - if (typeof superclass !== 'function') { - if (CC_DEV) { - cc.warnID(3625, superclass); - } - return false; - } - if (subclass === superclass) { - return true; - } - for (;;) { - subclass = js.getSuper(subclass); - if (!subclass) { - return false; - } - if (subclass === superclass) { - return true; - } - } - } - return false; - }, - - /** - * Removes all enumerable properties from object - * @method clear - * @param {any} obj - */ - clear: function (obj) { - var keys = Object.keys(obj); - for (var i = 0; i < keys.length; i++) { - delete obj[keys[i]]; - } - }, - - /** - * Get property descriptor in object and all its ancestors - * @method getPropertyDescriptor - * @param {Object} obj - * @param {String} name - * @return {Object} - */ - getPropertyDescriptor: _getPropertyDescriptor -}; - - -var tmpValueDesc = { - value: undefined, - enumerable: false, - writable: false, - configurable: true -}; - -/** - * Define value, just help to call Object.defineProperty.
- * The configurable will be true. - * @method value - * @param {Object} obj - * @param {String} prop - * @param {any} value - * @param {Boolean} [writable=false] - * @param {Boolean} [enumerable=false] - */ -js.value = function (obj, prop, value, writable, enumerable) { - tmpValueDesc.value = value; - tmpValueDesc.writable = writable; - tmpValueDesc.enumerable = enumerable; - Object.defineProperty(obj, prop, tmpValueDesc); - tmpValueDesc.value = undefined; -}; - -var tmpGetSetDesc = { - get: null, - set: null, - enumerable: false, -}; - -/** - * Define get set accessor, just help to call Object.defineProperty(...) - * @method getset - * @param {Object} obj - * @param {String} prop - * @param {Function} getter - * @param {Function} [setter=null] - * @param {Boolean} [enumerable=false] - * @param {Boolean} [configurable=false] - */ -js.getset = function (obj, prop, getter, setter, enumerable, configurable) { - if (typeof setter !== 'function') { - enumerable = setter; - setter = undefined; - } - tmpGetSetDesc.get = getter; - tmpGetSetDesc.set = setter; - tmpGetSetDesc.enumerable = enumerable; - tmpGetSetDesc.configurable = configurable; - Object.defineProperty(obj, prop, tmpGetSetDesc); - tmpGetSetDesc.get = null; - tmpGetSetDesc.set = null; -}; - -var tmpGetDesc = { - get: null, - enumerable: false, - configurable: false -}; - -/** - * Define get accessor, just help to call Object.defineProperty(...) - * @method get - * @param {Object} obj - * @param {String} prop - * @param {Function} getter - * @param {Boolean} [enumerable=false] - * @param {Boolean} [configurable=false] - */ -js.get = function (obj, prop, getter, enumerable, configurable) { - tmpGetDesc.get = getter; - tmpGetDesc.enumerable = enumerable; - tmpGetDesc.configurable = configurable; - Object.defineProperty(obj, prop, tmpGetDesc); - tmpGetDesc.get = null; -}; - -var tmpSetDesc = { - set: null, - enumerable: false, - configurable: false -}; - -/** - * Define set accessor, just help to call Object.defineProperty(...) - * @method set - * @param {Object} obj - * @param {String} prop - * @param {Function} setter - * @param {Boolean} [enumerable=false] - * @param {Boolean} [configurable=false] - */ -js.set = function (obj, prop, setter, enumerable, configurable) { - tmpSetDesc.set = setter; - tmpSetDesc.enumerable = enumerable; - tmpSetDesc.configurable = configurable; - Object.defineProperty(obj, prop, tmpSetDesc); - tmpSetDesc.set = null; -}; - -/** - * Get class name of the object, if object is just a {} (and which class named 'Object'), it will return "". - * (modified from the code from this stackoverflow post) - * @method getClassName - * @param {Object|Function} objOrCtor - instance or constructor - * @return {String} - */ -js.getClassName = function (objOrCtor) { - if (typeof objOrCtor === 'function') { - var prototype = objOrCtor.prototype; - if (prototype && prototype.hasOwnProperty('__classname__') && prototype.__classname__) { - return prototype.__classname__; - } - var retval = ''; - // for browsers which have name property in the constructor of the object, such as chrome - if (objOrCtor.name) { - retval = objOrCtor.name; - } - if (objOrCtor.toString) { - var arr, str = objOrCtor.toString(); - if (str.charAt(0) === '[') { - // str is "[object objectClass]" - arr = str.match(/\[\w+\s*(\w+)\]/); - } - else { - // str is function objectClass () {} for IE Firefox - arr = str.match(/function\s*(\w+)/); - } - if (arr && arr.length === 2) { - retval = arr[1]; - } - } - return retval !== 'Object' ? retval : ''; - } - else if (objOrCtor && objOrCtor.constructor) { - return js.getClassName(objOrCtor.constructor); - } - return ''; -}; - -function isTempClassId (id) { - return typeof id !== 'string' || id.startsWith(tempCIDGenerater.prefix); -} - -// id 注册 -(function () { - var _idToClass = {}; - var _nameToClass = {}; - - function getRegister (key, table) { - return function (id, constructor) { - // deregister old - if (constructor.prototype.hasOwnProperty(key)) { - delete table[constructor.prototype[key]]; - } - js.value(constructor.prototype, key, id); - // register class - if (id) { - var registered = table[id]; - if (registered && registered !== constructor) { - var error = 'A Class already exists with the same ' + key + ' : "' + id + '".'; - if (CC_TEST) { - error += ' (This may be caused by error of unit test.) \ -If you dont need serialization, you can set class id to "". You can also call \ -cc.js.unregisterClass to remove the id of unused class'; - } - cc.error(error); - } - else { - table[id] = constructor; - } - //if (id === "") { - // console.trace("", table === _nameToClass); - //} - } - }; - } - - /** - * Register the class by specified id, if its classname is not defined, the class name will also be set. - * @method _setClassId - * @param {String} classId - * @param {Function} constructor - * @private - */ - js._setClassId = getRegister('__cid__', _idToClass); - - var doSetClassName = getRegister('__classname__', _nameToClass); - - /** - * Register the class by specified name manually - * @method setClassName - * @param {String} className - * @param {Function} constructor - */ - js.setClassName = function (className, constructor) { - doSetClassName(className, constructor); - // auto set class id - if (!constructor.prototype.hasOwnProperty('__cid__')) { - var id = className || tempCIDGenerater.getNewId(); - if (id) { - js._setClassId(id, constructor); - } - } - }; - - /** - * Unregister a class from fireball. - * - * If you dont need a registered class anymore, you should unregister the class so that Fireball will not keep its reference anymore. - * Please note that its still your responsibility to free other references to the class. - * - * @method unregisterClass - * @param {Function} ...constructor - the class you will want to unregister, any number of classes can be added - */ - js.unregisterClass = function () { - for (var i = 0; i < arguments.length; i++) { - var p = arguments[i].prototype; - var classId = p.__cid__; - if (classId) { - delete _idToClass[classId]; - } - var classname = p.__classname__; - if (classname) { - delete _nameToClass[classname]; - } - } - }; - - /** - * Get the registered class by id - * @method _getClassById - * @param {String} classId - * @return {Function} constructor - * @private - */ - js._getClassById = function (classId) { - return _idToClass[classId]; - }; - - /** - * Get the registered class by name - * @method getClassByName - * @param {String} classname - * @return {Function} constructor - */ - js.getClassByName = function (classname) { - return _nameToClass[classname]; - }; - - /** - * Get class id of the object - * @method _getClassId - * @param {Object|Function} obj - instance or constructor - * @param {Boolean} [allowTempId=true] - can return temp id in editor - * @return {String} - * @private - */ - js._getClassId = function (obj, allowTempId) { - allowTempId = (typeof allowTempId !== 'undefined' ? allowTempId: true); - - var res; - if (typeof obj === 'function' && obj.prototype.hasOwnProperty('__cid__')) { - res = obj.prototype.__cid__; - if (!allowTempId && (CC_DEV || CC_EDITOR) && isTempClassId(res)) { - return ''; - } - return res; - } - if (obj && obj.constructor) { - var prototype = obj.constructor.prototype; - if (prototype && prototype.hasOwnProperty('__cid__')) { - res = obj.__cid__; - if (!allowTempId && (CC_DEV || CC_EDITOR) && isTempClassId(res)) { - return ''; - } - return res; - } - } - return ''; - }; - - if (CC_DEV) { - js.getset(js, '_registeredClassIds', - function () { - var dump = {}; - for (var id in _idToClass) { - dump[id] = _idToClass[id]; - } - return dump; - }, - function (value) { - js.clear(_idToClass); - for (var id in value) { - _idToClass[id] = value[id]; - } - } - ); - js.getset(js, '_registeredClassNames', - function () { - var dump = {}; - for (var id in _nameToClass) { - dump[id] = _nameToClass[id]; - } - return dump; - }, - function (value) { - js.clear(_nameToClass); - for (var id in value) { - _nameToClass[id] = value[id]; - } - } - ); - } - -})(); - -/** - * Defines a polyfill field for obsoleted codes. - * @method obsolete - * @param {any} obj - YourObject or YourClass.prototype - * @param {String} obsoleted - "OldParam" or "YourClass.OldParam" - * @param {String} newExpr - "NewParam" or "YourClass.NewParam" - * @param {Boolean} [writable=false] - */ -js.obsolete = function (obj, obsoleted, newExpr, writable) { - var extractPropName = /([^.]+)$/; - var oldProp = extractPropName.exec(obsoleted)[0]; - var newProp = extractPropName.exec(newExpr)[0]; - function get () { - if (CC_DEV) { - cc.warnID(5400, obsoleted, newExpr); - } - return this[newProp]; - } - if (writable) { - js.getset(obj, oldProp, - get, - function (value) { - if (CC_DEV) { - cc.warnID(5401, obsoleted, newExpr); - } - this[newProp] = value; - } - ); - } - else { - js.get(obj, oldProp, get); - } -}; - -/** - * Defines all polyfill fields for obsoleted codes corresponding to the enumerable properties of props. - * @method obsoletes - * @param {any} obj - YourObject or YourClass.prototype - * @param {any} objName - "YourObject" or "YourClass" - * @param {Object} props - * @param {Boolean} [writable=false] - */ -js.obsoletes = function (obj, objName, props, writable) { - for (var obsoleted in props) { - var newName = props[obsoleted]; - js.obsolete(obj, objName + '.' + obsoleted, newName, writable); - } -}; - -var REGEXP_NUM_OR_STR = /(%d)|(%s)/; -var REGEXP_STR = /%s/; - -/** - * A string tool to construct a string with format string. - * @method formatStr - * @param {String|any} msg - A JavaScript string containing zero or more substitution strings (%s). - * @param {any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. - * @returns {String} - * @example - * cc.js.formatStr("a: %s, b: %s", a, b); - * cc.js.formatStr(a, b, c); - */ -js.formatStr = function () { - var argLen = arguments.length; - if (argLen === 0) { - return ''; - } - var msg = arguments[0]; - if (argLen === 1) { - return '' + msg; - } - - var hasSubstitution = typeof msg === 'string' && REGEXP_NUM_OR_STR.test(msg); - if (hasSubstitution) { - for (let i = 1; i < argLen; ++i) { - var arg = arguments[i]; - var regExpToTest = typeof arg === 'number' ? REGEXP_NUM_OR_STR : REGEXP_STR; - if (regExpToTest.test(msg)) - msg = msg.replace(regExpToTest, arg); - else - msg += ' ' + arg; - } - } - else { - for (let i = 1; i < argLen; ++i) { - msg += ' ' + arguments[i]; - } - } - return msg; -}; - -// see https://github.com/petkaantonov/bluebird/issues/1389 -js.shiftArguments = function () { - var len = arguments.length - 1; - var args = new Array(len); - for(var i = 0; i < len; ++i) { - args[i] = arguments[i + 1]; - } - return args; -}; - -/** - * !#en - * A simple wrapper of `Object.create(null)` which ensures the return object have no prototype (and thus no inherited members). So we can skip `hasOwnProperty` calls on property lookups. It is a worthwhile optimization than the `{}` literal when `hasOwnProperty` calls are necessary. - * !#zh - * 该方法是对 `Object.create(null)` 的简单封装。`Object.create(null)` 用于创建无 prototype (也就无继承)的空对象。这样我们在该对象上查找属性时,就不用进行 `hasOwnProperty` 判断。在需要频繁判断 `hasOwnProperty` 时,使用这个方法性能会比 `{}` 更高。 - * - * @method createMap - * @param {Boolean} [forceDictMode=false] - Apply the delete operator to newly created map object. This causes V8 to put the object in "dictionary mode" and disables creation of hidden classes which are very expensive for objects that are constantly changing shape. - * @return {Object} - */ -js.createMap = function (forceDictMode) { - var map = Object.create(null); - if (forceDictMode) { - const INVALID_IDENTIFIER_1 = '.'; - const INVALID_IDENTIFIER_2 = '/'; - map[INVALID_IDENTIFIER_1] = true; - map[INVALID_IDENTIFIER_2] = true; - delete map[INVALID_IDENTIFIER_1]; - delete map[INVALID_IDENTIFIER_2]; - } - return map; -}; - -/** - * @class array - * @static - */ - -/** - * Removes the array item at the specified index. - * @method removeAt - * @param {any[]} array - * @param {Number} index - */ -function removeAt (array, index) { - array.splice(index, 1); -} - -/** - * Removes the array item at the specified index. - * It's faster but the order of the array will be changed. - * @method fastRemoveAt - * @param {any[]} array - * @param {Number} index - */ -function fastRemoveAt (array, index) { - var length = array.length; - if (index < 0 || index >= length) { - return; - } - array[index] = array[length - 1]; - array.length = length - 1; -} - -/** - * Removes the first occurrence of a specific object from the array. - * @method remove - * @param {any[]} array - * @param {any} value - * @return {Boolean} - */ -function remove (array, value) { - var index = array.indexOf(value); - if (index >= 0) { - removeAt(array, index); - return true; - } - else { - return false; - } -} - -/** - * Removes the first occurrence of a specific object from the array. - * It's faster but the order of the array will be changed. - * @method fastRemove - * @param {any[]} array - * @param {Number} value - */ -function fastRemove (array, value) { - var index = array.indexOf(value); - if (index >= 0) { - array[index] = array[array.length - 1]; - --array.length; - } -} - -/** - * Verify array's Type - * @method verifyType - * @param {array} array - * @param {Function} type - * @return {Boolean} - */ -function verifyType (array, type) { - if (array && array.length > 0) { - for (var i = 0; i < array.length; i++) { - if (!(array[i] instanceof type)) { - cc.logID(1300); - return false; - } - } - } - return true; -} - -/** - * Removes from array all values in minusArr. For each Value in minusArr, the first matching instance in array will be removed. - * @method removeArray - * @param {Array} array Source Array - * @param {Array} minusArr minus Array - */ -function removeArray (array, minusArr) { - for (var i = 0, l = minusArr.length; i < l; i++) { - remove(array, minusArr[i]); - } -} - -/** - * Inserts some objects at index - * @method appendObjectsAt - * @param {Array} array - * @param {Array} addObjs - * @param {Number} index - * @return {Array} - */ -function appendObjectsAt (array, addObjs, index) { - array.splice.apply(array, [index, 0].concat(addObjs)); - return array; -} - -/** - * Exact same function as Array.prototype.indexOf.
- * HACK: ugliy hack for Baidu mobile browser compatibility, stupid Baidu guys modify Array.prototype.indexOf for all pages loaded, their version changes strict comparison to non-strict comparison, it also ignores the second parameter of the original API, and this will cause event handler enter infinite loop.
- * Baidu developers, if you ever see this documentation, here is the standard: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf, Seriously! - * - * @method indexOf - * @param {any} searchElement - Element to locate in the array. - * @param {Number} [fromIndex=0] - The index to start the search at - * @return {Number} - the first index at which a given element can be found in the array, or -1 if it is not present. - */ -var indexOf = Array.prototype.indexOf; - -/** - * Determines whether the array contains a specific value. - * @method contains - * @param {any[]} array - * @param {any} value - * @return {Boolean} - */ -function contains (array, value) { - return array.indexOf(value) >= 0; -} - -/** - * Copy an array's item to a new array (its performance is better than Array.slice) - * @method copy - * @param {Array} array - * @return {Array} - */ -function copy (array) { - var i, len = array.length, arr_clone = new Array(len); - for (i = 0; i < len; i += 1) - arr_clone[i] = array[i]; - return arr_clone; -} - -js.array = { - remove, - fastRemove, - removeAt, - fastRemoveAt, - contains, - verifyType, - removeArray, - appendObjectsAt, - copy, - indexOf, - MutableForwardIterator: require('../utils/mutable-forward-iterator') -}; - -// OBJECT POOL - -/** - * !#en - * A fixed-length object pool designed for general type.
- * The implementation of this object pool is very simple, - * it can helps you to improve your game performance for objects which need frequent release and recreate operations
- * !#zh - * 长度固定的对象缓存池,可以用来缓存各种对象类型。
- * 这个对象池的实现非常精简,它可以帮助您提高游戏性能,适用于优化对象的反复创建和销毁。 - * @class Pool - * @example - * - *Example 1: - * - *function Details () { - * this.uuidList = []; - *}; - *Details.prototype.reset = function () { - * this.uuidList.length = 0; - *}; - *Details.pool = new js.Pool(function (obj) { - * obj.reset(); - *}, 5); - *Details.pool.get = function () { - * return this._get() || new Details(); - *}; - * - *var detail = Details.pool.get(); - *... - *Details.pool.put(detail); - * - *Example 2: - * - *function Details (buffer) { - * this.uuidList = buffer; - *}; - *... - *Details.pool.get = function (buffer) { - * var cached = this._get(); - * if (cached) { - * cached.uuidList = buffer; - * return cached; - * } - * else { - * return new Details(buffer); - * } - *}; - * - *var detail = Details.pool.get( [] ); - *... - */ -/** - * !#en - * Constructor for creating an object pool for the specific object type. - * You can pass a callback argument for process the cleanup logic when the object is recycled. - * !#zh - * 使用构造函数来创建一个指定对象类型的对象池,您可以传递一个回调函数,用于处理对象回收时的清理逻辑。 - * @method constructor - * @param {Function} [cleanupFunc] - the callback method used to process the cleanup logic when the object is recycled. - * @param {Object} cleanupFunc.obj - * @param {Number} size - initializes the length of the array - * @typescript - * constructor(cleanupFunc: (obj: any) => void, size: number) - * constructor(size: number) - */ -function Pool (cleanupFunc, size) { - if (size === undefined) { - size = cleanupFunc; - cleanupFunc = null; - } - this.get = null; - this.count = 0; - this._pool = new Array(size); - this._cleanup = cleanupFunc; -} - -/** - * !#en - * Get and initialize an object from pool. This method defaults to null and requires the user to implement it. - * !#zh - * 获取并初始化对象池中的对象。这个方法默认为空,需要用户自己实现。 - * @method get - * @param {any} ...params - parameters to used to initialize the object - * @returns {Object} - */ - -/** - * !#en - * The current number of available objects, the default is 0, it will gradually increase with the recycle of the object, - * the maximum will not exceed the size specified when the constructor is called. - * !#zh - * 当前可用对象数量,一开始默认是 0,随着对象的回收会逐渐增大,最大不会超过调用构造函数时指定的 size。 - * @property {Number} count - * @default 0 - */ - -/** - * !#en - * Get an object from pool, if no available object in the pool, null will be returned. - * !#zh - * 获取对象池中的对象,如果对象池没有可用对象,则返回空。 - * @method _get - * @returns {Object|null} - */ -Pool.prototype._get = function () { - if (this.count > 0) { - --this.count; - var cache = this._pool[this.count]; - this._pool[this.count] = null; - return cache; - } - return null; -}; - -/** - * !#en Put an object into the pool. - * !#zh 向对象池返还一个不再需要的对象。 - * @method put - */ -Pool.prototype.put = function (obj) { - var pool = this._pool; - if (this.count < pool.length) { - if (this._cleanup && this._cleanup(obj) === false) { - return; - } - pool[this.count] = obj; - ++this.count; - } -}; - -/** - * !#en Resize the pool. - * !#zh 设置对象池容量。 - * @method resize - */ -Pool.prototype.resize = function (length) { - if (length >= 0) { - this._pool.length = length; - if (this.count > length) { - this.count = length; - } - } -}; - -js.Pool = Pool; - -// - -cc.js = js; - -module.exports = js; - -// fix submodule pollute ... -/** - * @submodule cc - */ diff --git a/cocos/core/platform/utils.js b/cocos/core/platform/utils.js deleted file mode 100644 index 46312b0277..0000000000 --- a/cocos/core/platform/utils.js +++ /dev/null @@ -1,120 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-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. - ****************************************************************************/ - -// TODO - merge with misc.js - -module.exports = { - contains: function (refNode, otherNode) { - if(typeof refNode.contains == 'function'){ - return refNode.contains(otherNode); - }else if(typeof refNode.compareDocumentPosition == 'function' ) { - return !!(refNode.compareDocumentPosition(otherNode) & 16); - }else { - var node = otherNode.parentNode; - if (node) { - do { - if (node === refNode) { - return true; - } else { - node = node.parentNode; - } - } while (node !==null); - } - return false; - } - }, - - isDomNode: typeof window === 'object' && (typeof Node === 'function' ? - function (obj) { - // If "TypeError: Right-hand side of 'instanceof' is not callback" is thrown, - // it should because window.Node was overwritten. - return obj instanceof Node; - } : - function (obj) { - return obj && - typeof obj === 'object' && - typeof obj.nodeType === 'number' && - typeof obj.nodeName === 'string'; - } - ), - - callInNextTick: CC_EDITOR ? - function (callback, p1, p2) { - if (callback) { - process.nextTick(function () { - callback(p1, p2); - }); - } - } - : - ( - - function (callback, p1, p2) { - if (callback) { - setTimeout(function () { - callback(p1, p2); - }, 0); - } - } - ) -}; - -if (CC_DEV) { - ///** - // * @param {Object} obj - // * @return {Boolean} is {} ? - // */ - module.exports.isPlainEmptyObj_DEV = function (obj) { - if (!obj || obj.constructor !== Object) { - return false; - } - // jshint ignore: start - for (var k in obj) { - return false; - } - // jshint ignore: end - return true; - }; - module.exports.cloneable_DEV = function (obj) { - return obj && - typeof obj.clone === 'function' && - ( (obj.constructor && obj.constructor.prototype.hasOwnProperty('clone')) || obj.hasOwnProperty('clone') ); - }; -} - -if (CC_TEST) { - // editor mocks using in unit tests - if (typeof Editor === 'undefined') { - Editor = { - UuidUtils: { - NonUuidMark: '.', - uuid: function () { - return '' + ((new Date()).getTime() + Math.random()); - } - } - }; - } -} diff --git a/cocos/core/utils/CCPath.js b/cocos/core/utils/CCPath.js deleted file mode 100644 index d0089bfe45..0000000000 --- a/cocos/core/utils/CCPath.js +++ /dev/null @@ -1,184 +0,0 @@ -/**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. - Copyright (c) 2017-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. - ****************************************************************************/ - -require('../platform/CCSys'); - -var EXTNAME_RE = /(\.[^\.\/\?\\]*)(\?.*)?$/; -var DIRNAME_RE = /((.*)(\/|\\|\\\\))?(.*?\..*$)?/; -var NORMALIZE_RE = /[^\.\/]+\/\.\.\//; - -/** - * !#en The module provides utilities for working with file and directory paths - * !#zh 用于处理文件与目录的路径的模块 - * @class path - * @static - */ -cc.path = /** @lends cc.path# */{ - /** - * !#en Join strings to be a path. - * !#zh 拼接字符串为 Path - * @method join - * @example {@link cocos2d/core/utils/CCPath/join.js} - * @returns {String} - */ - join: function () { - var l = arguments.length; - var result = ""; - for (var i = 0; i < l; i++) { - result = (result + (result === "" ? "" : "/") + arguments[i]).replace(/(\/|\\\\)$/, ""); - } - return result; - }, - - /** - * !#en Get the ext name of a path including '.', like '.png'. - * !#zh 返回 Path 的扩展名,包括 '.',例如 '.png'。 - * @method extname - * @example {@link cocos2d/core/utils/CCPath/extname.js} - * @param {String} pathStr - * @returns {*} - */ - extname: function (pathStr) { - var temp = EXTNAME_RE.exec(pathStr); - return temp ? temp[1] : ''; - }, - - /** - * !#en Get the main name of a file name - * !#zh 获取文件名的主名称 - * @method mainFileName - * @param {String} fileName - * @returns {String} - * @deprecated - */ - mainFileName: function (fileName) { - if (fileName) { - var idx = fileName.lastIndexOf("."); - if (idx !== -1) - return fileName.substring(0, idx); - } - return fileName; - }, - - /** - * !#en Get the file name of a file path. - * !#zh 获取文件路径的文件名。 - * @method basename - * @example {@link cocos2d/core/utils/CCPath/basename.js} - * @param {String} pathStr - * @param {String} [extname] - * @returns {*} - */ - basename: function (pathStr, extname) { - var index = pathStr.indexOf("?"); - if (index > 0) pathStr = pathStr.substring(0, index); - var reg = /(\/|\\)([^\/\\]+)$/g; - var result = reg.exec(pathStr.replace(/(\/|\\)$/, "")); - if (!result) return null; - var baseName = result[2]; - if (extname && pathStr.substring(pathStr.length - extname.length).toLowerCase() === extname.toLowerCase()) - return baseName.substring(0, baseName.length - extname.length); - return baseName; - }, - - /** - * !#en Get dirname of a file path. - * !#zh 获取文件路径的目录名。 - * @method dirname - * @example {@link cocos2d/core/utils/CCPath/dirname.js} - * @param {String} pathStr - * @returns {*} - */ - dirname: function (pathStr) { - var temp = DIRNAME_RE.exec(pathStr); - return temp ? temp[2] : ''; - }, - - /** - * !#en Change extname of a file path. - * !#zh 更改文件路径的扩展名。 - * @method changeExtname - * @example {@link cocos2d/core/utils/CCPath/changeExtname.js} - * @param {String} pathStr - * @param {String} [extname] - * @returns {String} - */ - changeExtname: function (pathStr, extname) { - extname = extname || ""; - var index = pathStr.indexOf("?"); - var tempStr = ""; - if (index > 0) { - tempStr = pathStr.substring(index); - pathStr = pathStr.substring(0, index); - } - index = pathStr.lastIndexOf("."); - if (index < 0) return pathStr + extname + tempStr; - return pathStr.substring(0, index) + extname + tempStr; - }, - /** - * !#en Change file name of a file path. - * !#zh 更改文件路径的文件名。 - * @example {@link cocos2d/core/utils/CCPath/changeBasename.js} - * @param {String} pathStr - * @param {String} basename - * @param {Boolean} [isSameExt] - * @returns {String} - */ - changeBasename: function (pathStr, basename, isSameExt) { - if (basename.indexOf(".") === 0) return this.changeExtname(pathStr, basename); - var index = pathStr.indexOf("?"); - var tempStr = ""; - var ext = isSameExt ? this.extname(pathStr) : ""; - if (index > 0) { - tempStr = pathStr.substring(index); - pathStr = pathStr.substring(0, index); - } - index = pathStr.lastIndexOf("/"); - index = index <= 0 ? 0 : index + 1; - return pathStr.substring(0, index) + basename + ext + tempStr; - }, - //todo make public after verification - _normalize: function (url) { - var oldUrl = url = String(url); - - //removing all ../ - do { - oldUrl = url; - url = url.replace(NORMALIZE_RE, ""); - } while (oldUrl.length !== url.length); - return url; - }, - - // The platform-specific file separator. '\\' or '/'. - sep: (cc.sys.os === cc.sys.OS_WINDOWS ? '\\' : '/'), - - // @param {string} path - stripSep (path) { - return path.replace(/[\/\\]$/, ''); - } -}; - -module.exports = cc.path; \ No newline at end of file diff --git a/cocos/core/utils/array.js b/cocos/core/utils/array.js new file mode 100644 index 0000000000..6794fcca8d --- /dev/null +++ b/cocos/core/utils/array.js @@ -0,0 +1,168 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +/** + * @class js.array + * @static + */ + +/** + * Removes the array item at the specified index. + * @method removeAt + * @param {any[]} array + * @param {Number} index + */ +export function removeAt (array, index) { + array.splice(index, 1); +} + +/** + * Removes the array item at the specified index. + * It's faster but the order of the array will be changed. + * @method fastRemoveAt + * @param {any[]} array + * @param {Number} index + */ +export function fastRemoveAt (array, index) { + var length = array.length; + if (index < 0 || index >= length) { + return; + } + array[index] = array[length - 1]; + array.length = length - 1; +} + +/** + * Removes the first occurrence of a specific object from the array. + * @method remove + * @param {any[]} array + * @param {any} value + * @return {Boolean} + */ +export function remove (array, value) { + var index = array.indexOf(value); + if (index >= 0) { + removeAt(array, index); + return true; + } + else { + return false; + } +} + +/** + * Removes the first occurrence of a specific object from the array. + * It's faster but the order of the array will be changed. + * @method fastRemove + * @param {any[]} array + * @param {Number} value + */ +export function fastRemove (array, value) { + var index = array.indexOf(value); + if (index >= 0) { + array[index] = array[array.length - 1]; + --array.length; + } +} + +/** + * Verify array's Type + * @method verifyType + * @param {array} array + * @param {Function} type + * @return {Boolean} + */ +export function verifyType (array, type) { + if (array && array.length > 0) { + for (var i = 0; i < array.length; i++) { + if (!(array[i] instanceof type)) { + cc.logID(1300); + return false; + } + } + } + return true; +} + +/** + * Removes from array all values in minusArr. For each Value in minusArr, the first matching instance in array will be removed. + * @method removeArray + * @param {Array} array Source Array + * @param {Array} minusArr minus Array + */ +export function removeArray (array, minusArr) { + for (var i = 0, l = minusArr.length; i < l; i++) { + remove(array, minusArr[i]); + } +} + +/** + * Inserts some objects at index + * @method appendObjectsAt + * @param {Array} array + * @param {Array} addObjs + * @param {Number} index + * @return {Array} + */ +export function appendObjectsAt (array, addObjs, index) { + array.splice.apply(array, [index, 0].concat(addObjs)); + return array; +} + +/** + * Exact same function as Array.prototype.indexOf.
+ * HACK: ugliy hack for Baidu mobile browser compatibility, stupid Baidu guys modify Array.prototype.indexOf for all pages loaded, their version changes strict comparison to non-strict comparison, it also ignores the second parameter of the original API, and this will cause event handler enter infinite loop.
+ * Baidu developers, if you ever see this documentation, here is the standard: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf, Seriously! + * + * @method indexOf + * @param {any} searchElement - Element to locate in the array. + * @param {Number} [fromIndex=0] - The index to start the search at + * @return {Number} - the first index at which a given element can be found in the array, or -1 if it is not present. + */ +// Array.prototype.indexOf; + +/** + * Determines whether the array contains a specific value. + * @method contains + * @param {any[]} array + * @param {any} value + * @return {Boolean} + */ +export function contains (array, value) { + return array.indexOf(value) >= 0; +} + +/** + * Copy an array's item to a new array (its performance is better than Array.slice) + * @method copy + * @param {Array} array + * @return {Array} + */ +export function copy (array) { + var i, len = array.length, arr_clone = new Array(len); + for (i = 0; i < len; i += 1) + arr_clone[i] = array[i]; + return arr_clone; +} \ No newline at end of file diff --git a/cocos/core/utils/binary-search.js b/cocos/core/utils/binary-search.js index fa5b4a847a..150260c6a7 100644 --- a/cocos/core/utils/binary-search.js +++ b/cocos/core/utils/binary-search.js @@ -83,7 +83,7 @@ var EPSILON = 1e-6; // return ~l; // } -function binarySearchEpsilon (array, value) { +export default function binarySearchEpsilon (array, value) { for (var l = 0, h = array.length - 1, m = h >>> 1; l <= h; m = (l + h) >>> 1 @@ -100,9 +100,4 @@ function binarySearchEpsilon (array, value) { } } return ~l; -} - - -module.exports = { - binarySearchEpsilon -}; +} \ No newline at end of file diff --git a/cocos/core/utils/decode-uuid.js b/cocos/core/utils/decode-uuid.js index 13e96bacea..9374f99e2f 100644 --- a/cocos/core/utils/decode-uuid.js +++ b/cocos/core/utils/decode-uuid.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -var Base64Values = require('./misc').BASE64_VALUES; +import {BASE64_VALUES} from 'misc'; var HexChars = '0123456789abcdef'.split(''); @@ -33,15 +33,15 @@ var UuidTemplate = _t.concat(_t, '-', _t, '-', _t, '-', _t, '-', _t, _t, _t); var Indices = UuidTemplate.map(function (x, i) { return x === '-' ? NaN : i; }).filter(isFinite); // fcmR3XADNLgJ1ByKhqcC5Z -> fc991dd7-0033-4b80-9d41-c8a86a702e59 -module.exports = function (base64) { +export default function decodeUuid (base64) { if (base64.length !== 22) { return base64; } UuidTemplate[0] = base64[0]; UuidTemplate[1] = base64[1]; for (var i = 2, j = 2; i < 22; i += 2) { - var lhs = Base64Values[base64.charCodeAt(i)]; - var rhs = Base64Values[base64.charCodeAt(i + 1)]; + var lhs = BASE64_VALUES[base64.charCodeAt(i)]; + var rhs = BASE64_VALUES[base64.charCodeAt(i + 1)]; UuidTemplate[Indices[j++]] = HexChars[lhs >> 2]; UuidTemplate[Indices[j++]] = HexChars[((lhs & 3) << 2) | rhs >> 4]; UuidTemplate[Indices[j++]] = HexChars[rhs & 0xF]; @@ -50,5 +50,5 @@ module.exports = function (base64) { }; if (CC_TEST) { - cc._Test.decodeUuid = module.exports; + cc._Test.decodeUuid = decodeUuid; } diff --git a/cocos/core/utils/html-text-parser.js b/cocos/core/utils/html-text-parser.js index 6cdce9ec8f..9bf3143c67 100644 --- a/cocos/core/utils/html-text-parser.js +++ b/cocos/core/utils/html-text-parser.js @@ -24,24 +24,24 @@ THE SOFTWARE. ****************************************************************************/ -var eventRegx = /^(click)(\s)*=/; -var imageAttrReg = /(\s)*src(\s)*=|(\s)*height(\s)*=|(\s)*width(\s)*=|(\s)*click(\s)*=/; +const EVENT_REGX = /^(click)(\s)*=/; +const IMAGE_ATTR_REG = /(\s)*src(\s)*=|(\s)*height(\s)*=|(\s)*width(\s)*=|(\s)*click(\s)*=/; + /** * A utils class for parsing HTML texts. The parsed results will be an object array. */ -var HtmlTextParser = function() { - this._parsedObject = {}; - this._specialSymbolArray = []; - this._specialSymbolArray.push([/</g, '<']); - this._specialSymbolArray.push([/>/g, '>']); - this._specialSymbolArray.push([/&/g, '&']); - this._specialSymbolArray.push([/"/g, '"']); - this._specialSymbolArray.push([/'/g, '\'']); -}; +export default class HtmlTextParser { + constructor () { + this._parsedObject = {}; + this._specialSymbolArray = []; + this._specialSymbolArray.push([/</g, '<']); + this._specialSymbolArray.push([/>/g, '>']); + this._specialSymbolArray.push([/&/g, '&']); + this._specialSymbolArray.push([/"/g, '"']); + this._specialSymbolArray.push([/'/g, '\'']); + } -HtmlTextParser.prototype = { - constructor: HtmlTextParser, - parse: function(htmlString) { + parse (htmlString) { this._resultObjectArray = []; this._stack = []; @@ -69,12 +69,10 @@ HtmlTextParser.prototype = { } } - - return this._resultObjectArray; - }, + } - _attributeToObject: function (attribute) { + _attributeToObject (attribute) { attribute = attribute.trim(); var obj = {}; @@ -126,7 +124,7 @@ HtmlTextParser.prototype = { if(header && header[0].length > 0) { tagName = header[0].trim(); if(tagName.startsWith("img") && tagName[tagName.length-1] === "/") { - header = attribute.match(imageAttrReg); + header = attribute.match(IMAGE_ATTR_REG); var tagValue; var remainingArgument; var isValidImageTag = false; @@ -161,7 +159,7 @@ HtmlTextParser.prototype = { } else if (tagName === "click") { obj.event = this._processEventHandler(tagName + "=" + tagValue); } - header = attribute.match(imageAttrReg); + header = attribute.match(IMAGE_ATTR_REG); } if( isValidImageTag && obj.isImage ) @@ -231,15 +229,13 @@ HtmlTextParser.prototype = { eventObj = this._processEventHandler(attribute); obj.event = eventObj; } - - return obj; - }, + } - _processEventHandler: function (eventString) { + _processEventHandler (eventString) { var index = 0; var obj = {}; - var eventNames = eventString.match(eventRegx); + var eventNames = eventString.match(EVENT_REGX); var isValidTag = false; while(eventNames) { var eventName = eventNames[0]; @@ -277,13 +273,13 @@ HtmlTextParser.prototype = { } eventString = eventString.substring(index).trim(); - eventNames = eventString.match(eventRegx); + eventNames = eventString.match(EVENT_REGX); } return obj; - }, + } - _addToStack: function(attribute) { + _addToStack (attribute) { var obj = this._attributeToObject(attribute); if (this._stack.length === 0){ @@ -301,9 +297,9 @@ HtmlTextParser.prototype = { } this._stack.push(obj); } - }, + } - _processResult: function(value) { + _processResult (value) { if (value === "") { return; } @@ -314,9 +310,9 @@ HtmlTextParser.prototype = { } else { this._resultObjectArray.push({text: value}); } - }, + } - _escapeSpecialSymbol: function(str) { + _escapeSpecialSymbol (str) { for(var i = 0; i < this._specialSymbolArray.length; ++i) { var key = this._specialSymbolArray[i][0]; var value = this._specialSymbolArray[i][1]; @@ -329,6 +325,4 @@ HtmlTextParser.prototype = { if (CC_TEST) { cc._Test.HtmlTextParser = HtmlTextParser; -} - -module.exports = HtmlTextParser; \ No newline at end of file +} \ No newline at end of file diff --git a/cocos/core/data/utils/id-generater.js b/cocos/core/utils/id-generater.js similarity index 72% rename from cocos/core/data/utils/id-generater.js rename to cocos/core/utils/id-generater.js index 4a7ae2f499..c78c4f5429 100644 --- a/cocos/core/data/utils/id-generater.js +++ b/cocos/core/utils/id-generater.js @@ -1,5 +1,4 @@ /**************************************************************************** - Copyright (c) 2013-2016 Chukong Technologies Inc. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -26,30 +25,31 @@ // ID generater for runtime -var NonUuidMark = '.'; +let NonUuidMark = '.'; -/* - * @param {string} [category] - You can specify a unique category to avoid id collision with other instance of IdGenerater - */ -function IdGenerater (category) { - // init with a random id to emphasize that the returns id should not be stored in persistence data - this.id = 0 | (Math.random() * 998); - - this.prefix = category ? (category + NonUuidMark) : ''; +export default class IdGenerater { + /* + * @constructor + * @param {string} [category] - You can specify a unique category to avoid id collision with other instance of IdGenerater + */ + constructor (category) { + // init with a random id to emphasize that the returns id should not be stored in persistence data + this.id = 0 | (Math.random() * 998); + + this.prefix = category ? (category + NonUuidMark) : ''; + } + + /* + * @method getNewId + * @return {string} + */ + getNewId () { + return this.prefix + (++this.id); + } } -/* - * @method getNewId - * @return {string} - */ -IdGenerater.prototype.getNewId = function () { - return this.prefix + (++this.id); -}; - /* * The global id generater might have a conflict problem once every 365 days, * if the game runs at 60 FPS and each frame 4760273 counts of new id are requested. */ IdGenerater.global = new IdGenerater('global'); - -module.exports = IdGenerater; diff --git a/cocos/core/utils/index.js b/cocos/core/utils/index.js index e97dc29341..ae885ac676 100644 --- a/cocos/core/utils/index.js +++ b/cocos/core/utils/index.js @@ -23,10 +23,55 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - -require('./CCPath'); -if (!CC_EDITOR) { - require('./profiler/CCProfiler'); + +// ========= cc.js ========== +import * as array from './array'; +import * as js from './js'; +import Pool from './pool'; +import MutableForwardIterator from './mutable-forward-iterator'; + +js.Pool = Pool; +js.array = array; +js.array.MutableForwardIterator = MutableForwardIterator; + +if (CC_DEV) { + js.getset(js, '_registeredClassIds', + function () { + var dump = {}; + for (var id in _idToClass) { + dump[id] = _idToClass[id]; + } + return dump; + }, + function (value) { + js.clear(_idToClass); + for (var id in value) { + _idToClass[id] = value[id]; + } + } + ); + js.getset(js, '_registeredClassNames', + function () { + var dump = {}; + for (var id in _nameToClass) { + dump[id] = _nameToClass[id]; + } + return dump; + }, + function (value) { + js.clear(_nameToClass); + for (var id in value) { + _nameToClass[id] = value[id]; + } + } + ); } -require('./find'); -require('./mutable-forward-iterator'); +cc.js = js; + +// ========= cc.path ========== +import * as path from 'path'; + +get(path, 'sep', () => { + return (cc.sys.os === cc.sys.OS_WINDOWS ? '\\' : '/'); +}) +cc.path = path; \ No newline at end of file diff --git a/cocos/core/utils/js.js b/cocos/core/utils/js.js new file mode 100644 index 0000000000..d89125bc26 --- /dev/null +++ b/cocos/core/utils/js.js @@ -0,0 +1,662 @@ +/**************************************************************************** + Copyright (c) 2008-2010 Ricardo Quesada + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + 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 IDGenerater from './id-generater'; + +let tempCIDGenerater = new IDGenerater('TmpCId.'); + +const REGEXP_NUM_OR_STR = /(%d)|(%s)/; +const REGEXP_STR = /%s/; + +var _tmpValueDesc = { + value: undefined, + enumerable: false, + writable: false, + configurable: true +}; + +var _tmpGetSetDesc = { + get: null, + set: null, + enumerable: false, +}; + +var _tmpSetDesc = { + set: null, + enumerable: false, + configurable: false +}; + +/** + * This module provides some JavaScript utilities. + * All members can be accessed with "cc.js". + * @submodule js + * @module js + */ + +/** + * Check the obj whether is number or not + * If a number is created by using 'new Number(10086)', the typeof it will be "object"... + * Then you can use this function if you care about this case. + * @method isNumber + * @param {*} obj + * @returns {Boolean} + */ +export function isNumber (obj) { + return typeof obj === 'number' || obj instanceof Number; +}; + +/** + * Check the obj whether is string or not. + * If a string is created by using 'new String("blabla")', the typeof it will be "object"... + * Then you can use this function if you care about this case. + * @method isString + * @param {*} obj + * @returns {Boolean} + */ +export function isString (obj) { + return typeof obj === 'string' || obj instanceof String; +}; + +/** + * Get property descriptor in object and all its ancestors + * @method getPropertyDescriptor + * @param {Object} obj + * @param {String} name + * @return {Object} + */ +export function getPropertyDescriptor (obj, name) { + while (obj) { + var pd = Object.getOwnPropertyDescriptor(obj, name); + if (pd) { + return pd; + } + obj = Object.getPrototypeOf(obj); + } + return null; +}; + +function _copyprop(name, source, target) { + var pd = getPropertyDescriptor(source, name); + Object.defineProperty(target, name, pd); +} + +/** + * Copy all properties not defined in obj from arguments[1...n] + * @method addon + * @param {Object} obj object to extend its properties + * @param {Object} ...sourceObj source object to copy properties from + * @return {Object} the result obj + */ +export function addon (obj) { + 'use strict'; + obj = obj || {}; + for (var i = 1, length = arguments.length; i < length; i++) { + var source = arguments[i]; + if (source) { + if (typeof source !== 'object') { + cc.errorID(5402, source); + continue; + } + for ( var name in source) { + if ( !(name in obj) ) { + _copyprop( name, source, obj); + } + } + } + } + return obj; +}; + +/** + * copy all properties from arguments[1...n] to obj + * @method mixin + * @param {Object} obj + * @param {Object} ...sourceObj + * @return {Object} the result obj + */ +export function mixin (obj) { + 'use strict'; + obj = obj || {}; + for (var i = 1, length = arguments.length; i < length; i++) { + var source = arguments[i]; + if (source) { + if (typeof source !== 'object') { + cc.errorID(5403, source); + continue; + } + for ( var name in source) { + _copyprop( name, source, obj); + } + } + } + return obj; +}; + +/** + * Derive the class from the supplied base class. + * Both classes are just native javascript constructors, not created by cc.Class, so + * usually you will want to inherit using {{#crossLink "cc/Class:method"}}cc.Class {{/crossLink}} instead. + * @method extend + * @param {Function} cls + * @param {Function} base - the baseclass to inherit + * @return {Function} the result class + */ +export function extend (cls, base) { + if (CC_DEV) { + if (!base) { + cc.errorID(5404); + return; + } + if (!cls) { + cc.errorID(5405); + return; + } + if (Object.keys(cls.prototype).length > 0) { + cc.errorID(5406); + } + } + for (var p in base) if (base.hasOwnProperty(p)) cls[p] = base[p]; + cls.prototype = Object.create(base.prototype, { + constructor: { + value: cls, + writable: true, + configurable: true + } + }); + return cls; +}; + +/** + * Get super class + * @method getSuper + * @param {Function} ctor - the constructor of subclass + * @return {Function} + */ +export function getSuper (ctor) { + var proto = ctor.prototype; // binded function do not have prototype + var dunderProto = proto && Object.getPrototypeOf(proto); + return dunderProto && dunderProto.constructor; +}; + +/** + * Checks whether subclass is child of superclass or equals to superclass + * + * @method isChildClassOf + * @param {Function} subclass + * @param {Function} superclass + * @return {Boolean} + */ +export function isChildClassOf (subclass, superclass) { + if (subclass && superclass) { + if (typeof subclass !== 'function') { + return false; + } + if (typeof superclass !== 'function') { + if (CC_DEV) { + cc.warnID(3625, superclass); + } + return false; + } + if (subclass === superclass) { + return true; + } + for (;;) { + subclass = getSuper(subclass); + if (!subclass) { + return false; + } + if (subclass === superclass) { + return true; + } + } + } + return false; +}; + +/** + * Removes all enumerable properties from object + * @method clear + * @param {any} obj + */ +export function clear (obj) { + var keys = Object.keys(obj); + for (var i = 0; i < keys.length; i++) { + delete obj[keys[i]]; + } +}; + +/** + * Define value, just help to call Object.defineProperty.
+ * The configurable will be true. + * @method value + * @param {Object} obj + * @param {String} prop + * @param {any} value + * @param {Boolean} [writable=false] + * @param {Boolean} [enumerable=false] + */ +export function value (obj, prop, value, writable, enumerable) { + _tmpValueDesc.value = value; + _tmpValueDesc.writable = writable; + _tmpValueDesc.enumerable = enumerable; + Object.defineProperty(obj, prop, _tmpValueDesc); + _tmpValueDesc.value = undefined; +}; + +/** + * Define get set accessor, just help to call Object.defineProperty(...) + * @method getset + * @param {Object} obj + * @param {String} prop + * @param {Function} getter + * @param {Function} [setter=null] + * @param {Boolean} [enumerable=false] + * @param {Boolean} [configurable=false] + */ +export function getset (obj, prop, getter, setter, enumerable, configurable) { + if (typeof setter !== 'function') { + enumerable = setter; + setter = undefined; + } + _tmpGetSetDesc.get = getter; + _tmpGetSetDesc.set = setter; + _tmpGetSetDesc.enumerable = enumerable; + _tmpGetSetDesc.configurable = configurable; + Object.defineProperty(obj, prop, _tmpGetSetDesc); + _tmpGetSetDesc.get = null; + _tmpGetSetDesc.set = null; +}; + + +/** + * Define get accessor, just help to call Object.defineProperty(...) + * @method get + * @param {Object} obj + * @param {String} prop + * @param {Function} getter + * @param {Boolean} [enumerable=false] + * @param {Boolean} [configurable=false] + */ +export function get (obj, prop, getter, enumerable, configurable) { + tmpGetDesc.get = getter; + tmpGetDesc.enumerable = enumerable; + tmpGetDesc.configurable = configurable; + Object.defineProperty(obj, prop, tmpGetDesc); + tmpGetDesc.get = null; +}; + + + +/** + * Define set accessor, just help to call Object.defineProperty(...) + * @method set + * @param {Object} obj + * @param {String} prop + * @param {Function} setter + * @param {Boolean} [enumerable=false] + * @param {Boolean} [configurable=false] + */ +export function set (obj, prop, setter, enumerable, configurable) { + _tmpSetDesc.set = setter; + _tmpSetDesc.enumerable = enumerable; + _tmpSetDesc.configurable = configurable; + Object.defineProperty(obj, prop, _tmpSetDesc); + _tmpSetDesc.set = null; +}; + +/** + * Get class name of the object, if object is just a {} (and which class named 'Object'), it will return "". + * (modified from the code from this stackoverflow post) + * @method getClassName + * @param {Object|Function} objOrCtor - instance or constructor + * @return {String} + */ +export function getClassName (objOrCtor) { + if (typeof objOrCtor === 'function') { + var prototype = objOrCtor.prototype; + if (prototype && prototype.hasOwnProperty('__classname__') && prototype.__classname__) { + return prototype.__classname__; + } + var retval = ''; + // for browsers which have name property in the constructor of the object, such as chrome + if (objOrCtor.name) { + retval = objOrCtor.name; + } + if (objOrCtor.toString) { + var arr, str = objOrCtor.toString(); + if (str.charAt(0) === '[') { + // str is "[object objectClass]" + arr = str.match(/\[\w+\s*(\w+)\]/); + } + else { + // str is function objectClass () {} for IE Firefox + arr = str.match(/function\s*(\w+)/); + } + if (arr && arr.length === 2) { + retval = arr[1]; + } + } + return retval !== 'Object' ? retval : ''; + } + else if (objOrCtor && objOrCtor.constructor) { + return getClassName(objOrCtor.constructor); + } + return ''; +}; + +function isTempClassId (id) { + return typeof id !== 'string' || id.startsWith(tempCIDGenerater.prefix); +} + +// id 注册 +let _idToClass = {}; +let _nameToClass = {}; + +/** + * Register the class by specified id, if its classname is not defined, the class name will also be set. + * @method _setClassId + * @param {String} classId + * @param {Function} constructor + * @private + */ +export function _setClassId (id, constructor) { + let key = '__cid__'; + let table = _idToClass; + // deregister old + if (constructor.prototype.hasOwnProperty(key)) { + delete table[constructor.prototype[key]]; + } + value(constructor.prototype, key, id); + // register class + if (id) { + var registered = table[id]; + if (registered && registered !== constructor) { + var error = 'A Class already exists with the same ' + key + ' : "' + id + '".'; + if (CC_TEST) { + error += ' (This may be caused by error of unit test.) \ +If you dont need serialization, you can set class id to "". You can also call \ +cc.js.unregisterClass to remove the id of unused class'; + } + cc.error(error); + } + else { + table[id] = constructor; + } + //if (id === "") { + // console.trace("", table === _nameToClass); + //} + } +}; + +function doSetClassName (id, constructor) { + let key = '__classname__'; + let table = _nameToClass; + // deregister old + if (constructor.prototype.hasOwnProperty(key)) { + delete table[constructor.prototype[key]]; + } + value(constructor.prototype, key, id); + // register class + if (id) { + var registered = table[id]; + if (registered && registered !== constructor) { + var error = 'A Class already exists with the same ' + key + ' : "' + id + '".'; + if (CC_TEST) { + error += ' (This may be caused by error of unit test.) \ +If you dont need serialization, you can set class id to "". You can also call \ +cc.js.unregisterClass to remove the id of unused class'; + } + cc.error(error); + } + else { + table[id] = constructor; + } + //if (id === "") { + // console.trace("", table === _nameToClass); + //} + } +}; + +/** + * Register the class by specified name manually + * @method setClassName + * @param {String} className + * @param {Function} constructor + */ +export function setClassName (className, constructor) { + doSetClassName(className, constructor); + // auto set class id + if (!constructor.prototype.hasOwnProperty('__cid__')) { + var id = className || tempCIDGenerater.getNewId(); + if (id) { + _setClassId(id, constructor); + } + } +}; + +/** + * Unregister a class from fireball. + * + * If you dont need a registered class anymore, you should unregister the class so that Fireball will not keep its reference anymore. + * Please note that its still your responsibility to free other references to the class. + * + * @method unregisterClass + * @param {Function} ...constructor - the class you will want to unregister, any number of classes can be added + */ +export function unregisterClass () { + for (var i = 0; i < arguments.length; i++) { + var p = arguments[i].prototype; + var classId = p.__cid__; + if (classId) { + delete _idToClass[classId]; + } + var classname = p.__classname__; + if (classname) { + delete _nameToClass[classname]; + } + } +}; + +/** + * Get the registered class by id + * @method _getClassById + * @param {String} classId + * @return {Function} constructor + * @private + */ +export function _getClassById (classId) { + return _idToClass[classId]; +}; + +/** + * Get the registered class by name + * @method getClassByName + * @param {String} classname + * @return {Function} constructor + */ +export function getClassByName (classname) { + return _nameToClass[classname]; +}; + +/** + * Get class id of the object + * @method _getClassId + * @param {Object|Function} obj - instance or constructor + * @param {Boolean} [allowTempId=true] - can return temp id in editor + * @return {String} + * @private + */ +export function _getClassId (obj, allowTempId) { + allowTempId = (typeof allowTempId !== 'undefined' ? allowTempId: true); + + var res; + if (typeof obj === 'function' && obj.prototype.hasOwnProperty('__cid__')) { + res = obj.prototype.__cid__; + if (!allowTempId && (CC_DEV || CC_EDITOR) && isTempClassId(res)) { + return ''; + } + return res; + } + if (obj && obj.constructor) { + var prototype = obj.constructor.prototype; + if (prototype && prototype.hasOwnProperty('__cid__')) { + res = obj.__cid__; + if (!allowTempId && (CC_DEV || CC_EDITOR) && isTempClassId(res)) { + return ''; + } + return res; + } + } + return ''; +}; + +/** + * Defines a polyfill field for obsoleted codes. + * @method obsolete + * @param {any} obj - YourObject or YourClass.prototype + * @param {String} obsoleted - "OldParam" or "YourClass.OldParam" + * @param {String} newExpr - "NewParam" or "YourClass.NewParam" + * @param {Boolean} [writable=false] + */ +export function obsolete (obj, obsoleted, newExpr, writable) { + var extractPropName = /([^.]+)$/; + var oldProp = extractPropName.exec(obsoleted)[0]; + var newProp = extractPropName.exec(newExpr)[0]; + function get () { + if (CC_DEV) { + cc.warnID(5400, obsoleted, newExpr); + } + return this[newProp]; + } + if (writable) { + getset(obj, oldProp, + get, + function (value) { + if (CC_DEV) { + cc.warnID(5401, obsoleted, newExpr); + } + this[newProp] = value; + } + ); + } + else { + get(obj, oldProp, get); + } +}; + +/** + * Defines all polyfill fields for obsoleted codes corresponding to the enumerable properties of props. + * @method obsoletes + * @param {any} obj - YourObject or YourClass.prototype + * @param {any} objName - "YourObject" or "YourClass" + * @param {Object} props + * @param {Boolean} [writable=false] + */ +export function obsoletes (obj, objName, props, writable) { + for (var obsoleted in props) { + var newName = props[obsoleted]; + obsolete(obj, objName + '.' + obsoleted, newName, writable); + } +}; + +/** + * A string tool to construct a string with format string. + * @method formatStr + * @param {String|any} msg - A JavaScript string containing zero or more substitution strings (%s). + * @param {any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. + * @returns {String} + * @example + * cc.js.formatStr("a: %s, b: %s", a, b); + * cc.js.formatStr(a, b, c); + */ +export function formatStr () { + var argLen = arguments.length; + if (argLen === 0) { + return ''; + } + var msg = arguments[0]; + if (argLen === 1) { + return '' + msg; + } + + var hasSubstitution = typeof msg === 'string' && REGEXP_NUM_OR_STR.test(msg); + if (hasSubstitution) { + for (let i = 1; i < argLen; ++i) { + var arg = arguments[i]; + var regExpToTest = typeof arg === 'number' ? REGEXP_NUM_OR_STR : REGEXP_STR; + if (regExpToTest.test(msg)) + msg = msg.replace(regExpToTest, arg); + else + msg += ' ' + arg; + } + } + else { + for (let i = 1; i < argLen; ++i) { + msg += ' ' + arguments[i]; + } + } + return msg; +}; + +// see https://github.com/petkaantonov/bluebird/issues/1389 +export function shiftArguments () { + var len = arguments.length - 1; + var args = new Array(len); + for(var i = 0; i < len; ++i) { + args[i] = arguments[i + 1]; + } + return args; +}; + +/** + * !#en + * A simple wrapper of `Object.create(null)` which ensures the return object have no prototype (and thus no inherited members). So we can skip `hasOwnProperty` calls on property lookups. It is a worthwhile optimization than the `{}` literal when `hasOwnProperty` calls are necessary. + * !#zh + * 该方法是对 `Object.create(null)` 的简单封装。`Object.create(null)` 用于创建无 prototype (也就无继承)的空对象。这样我们在该对象上查找属性时,就不用进行 `hasOwnProperty` 判断。在需要频繁判断 `hasOwnProperty` 时,使用这个方法性能会比 `{}` 更高。 + * + * @method createMap + * @param {Boolean} [forceDictMode=false] - Apply the delete operator to newly created map object. This causes V8 to put the object in "dictionary mode" and disables creation of hidden classes which are very expensive for objects that are constantly changing shape. + * @return {Object} + */ +export function createMap (forceDictMode) { + var map = Object.create(null); + if (forceDictMode) { + const INVALID_IDENTIFIER_1 = '.'; + const INVALID_IDENTIFIER_2 = '/'; + map[INVALID_IDENTIFIER_1] = true; + map[INVALID_IDENTIFIER_2] = true; + delete map[INVALID_IDENTIFIER_1]; + delete map[INVALID_IDENTIFIER_2]; + } + return map; +}; + +// fix submodule pollute ... +/** + * @submodule cc + */ diff --git a/cocos/core/utils/math-pools.js b/cocos/core/utils/math-pools.js deleted file mode 100644 index 23697c4d4c..0000000000 --- a/cocos/core/utils/math-pools.js +++ /dev/null @@ -1,87 +0,0 @@ -/**************************************************************************** - Copyright (c) 2017-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. - ****************************************************************************/ - -const js = require('../platform/js'); -const renderEngine = require('../renderer/render-engine'); -// const Vec2 = require('../value-types/vec2'); -// const Vec3 = require('../value-types/vec3'); -// const Quat = require('../value-types/quat'); -const math = renderEngine.math; - -var mat4Pool = new js.Pool(128); -mat4Pool.get = function () { - var matrix = this._get(); - if (matrix) { - math.mat4.identity(matrix); - } - else { - matrix = math.mat4.create(); - } - return matrix; -}; - -// var vec2Pool = new js.Pool(128); -// vec2Pool.get = function () { -// var vec2 = this._get(); -// if (vec2) { -// vec2.x = vec2.y = 0; -// } -// else { -// vec2 = new Vec2(); -// } -// return vec2; -// }; - -// var vec3Pool = new js.Pool(128); -// vec3Pool.get = function () { -// var vec3 = this._get(); -// if (vec3) { -// vec3.x = vec3.y = vec3.z = 0; -// } -// else { -// vec3 = new Vec3(); -// } -// return vec3; -// }; - -var quatPool = new js.Pool(64); -quatPool.get = function () { - var quat = this._get(); - if (quat) { - quat.x = quat.y = quat.z = 0; - quat.w = 1; - } - else { - quat = math.quat.create(); - } - return quat; -}; - -module.exports = { - mat4: mat4Pool, - // vec2: vec2Pool, - // vec3: vec3Pool, - quat: quatPool -}; \ No newline at end of file diff --git a/cocos/core/utils/misc.js b/cocos/core/utils/misc.js index ea5e4fef24..3d5dc6ea79 100644 --- a/cocos/core/utils/misc.js +++ b/cocos/core/utils/misc.js @@ -24,16 +24,31 @@ THE SOFTWARE. ****************************************************************************/ -var js = require('../platform/js'); +import {getset, getClassName} from './js'; + +export const BUILTIN_CLASSID_RE = /^(?:cc|dragonBones|sp|ccsg)\..+/; + +var BASE64_KEYS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; +var values = new Array(123); // max char code in base64Keys +for (let i = 0; i < 123; ++i) values[i] = 64; // fill with placeholder('=') index +for (let i = 0; i < 64; ++i) values[BASE64_KEYS.charCodeAt(i)] = i; + +// decoded value indexed by base64 char code +export const BASE64_VALUES = values; /** * misc utilities * @class misc * @static */ -var misc = {}; -misc.propertyDefine = function (ctor, sameNameGetSets, diffNameGetSets) { +/** + * @method propertyDefine + * @param {Function} ctor + * @param {Array} sameNameGetSets + * @param {Object} diffNameGetSets + */ +export function propertyDefine (ctor, sameNameGetSets, diffNameGetSets) { function define (np, propName, getter, setter) { var pd = Object.getOwnPropertyDescriptor(np, propName); if (pd) { @@ -43,13 +58,13 @@ misc.propertyDefine = function (ctor, sameNameGetSets, diffNameGetSets) { else { var getterFunc = np[getter]; if (CC_DEV && !getterFunc) { - var clsName = (cc.Class._isCCClass(ctor) && js.getClassName(ctor)) || - ctor.name || - '(anonymous class)'; + var clsName = (cc.Class._isCCClass(ctor) && getClassName(ctor)) || + ctor.name || + '(anonymous class)'; cc.warnID(5700, propName, getter, clsName); } else { - js.getset(np, propName, getterFunc, np[setter]); + getset(np, propName, getterFunc, np[setter]); } } } @@ -60,17 +75,17 @@ misc.propertyDefine = function (ctor, sameNameGetSets, diffNameGetSets) { define(np, propName, 'get' + suffix, 'set' + suffix); } for (propName in diffNameGetSets) { - var getset = diffNameGetSets[propName]; - define(np, propName, getset[0], getset[1]); + var gs = diffNameGetSets[propName]; + define(np, propName, gs[0], gs[1]); } -}; +} /** + * @method nextPOT * @param {Number} x * @return {Number} - * Constructor */ -misc.NextPOT = function (x) { +export function nextPOT (x) { x = x - 1; x = x | (x >> 1); x = x | (x >> 2); @@ -80,57 +95,8 @@ misc.NextPOT = function (x) { return x + 1; }; -//var DirtyFlags = m.DirtyFlags = { -// TRANSFORM: 1 << 0, -// SIZE: 1 << 1, -// //Visible: -// //Color: -// //Opacity -// //Cache -// //Order -// //Text -// //Gradient -// ALL: (1 << 2) - 1 -//}; -// -//DirtyFlags.WIDGET = DirtyFlags.TRANSFORM | DirtyFlags.SIZE; - -if (CC_EDITOR) { - // use anonymous function here to ensure it will not being hoisted without CC_EDITOR - - misc.tryCatchFunctor_EDITOR = function (funcName, forwardArgs, afterCall, bindArg) { - function call_FUNC_InTryCatch (_R_ARGS_) { - try { - target._FUNC_(_U_ARGS_); - } - catch (e) { - cc._throw(e); - } - _AFTER_CALL_ - } - // use evaled code to generate named function - return Function('arg', 'return ' + call_FUNC_InTryCatch - .toString() - .replace(/_FUNC_/g, funcName) - .replace('_R_ARGS_', 'target' + (forwardArgs ? ', ' + forwardArgs : '')) - .replace('_U_ARGS_', forwardArgs || '') - .replace('_AFTER_CALL_', afterCall || ''))(bindArg); - }; -} - -misc.BUILTIN_CLASSID_RE = /^(?:cc|dragonBones|sp|ccsg)\..+/; - - -var BASE64_KEYS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; -var BASE64_VALUES = new Array(123); // max char code in base64Keys -for (let i = 0; i < 123; ++i) BASE64_VALUES[i] = 64; // fill with placeholder('=') index -for (let i = 0; i < 64; ++i) BASE64_VALUES[BASE64_KEYS.charCodeAt(i)] = i; - -// decoded value indexed by base64 char code -misc.BASE64_VALUES = BASE64_VALUES; - // set value to map, if key exists, push to array -misc.pushToMap = function (map, key, value, pushFront) { +export function pushToMap (map, key, value, pushFront) { var exists = map[key]; if (exists) { if (Array.isArray(exists)) { @@ -168,7 +134,7 @@ misc.pushToMap = function (map, key, value, pushFront) { * var v2 = cc.misc.clampf(-1, 0, 20); // 0; * var v3 = cc.misc.clampf(10, 0, 20); // 10; */ -misc.clampf = function (value, min_inclusive, max_inclusive) { +export function clampf (value, min_inclusive, max_inclusive) { if (min_inclusive > max_inclusive) { var temp = min_inclusive; min_inclusive = max_inclusive; @@ -188,7 +154,7 @@ misc.clampf = function (value, min_inclusive, max_inclusive) { * var v2 = cc.misc.clamp01(-1); // 0; * var v3 = cc.misc.clamp01(0.5); // 0.5; */ -misc.clamp01 = function (value) { +export function clamp01 (value) { return value < 0 ? 0 : value < 1 ? value : 1; }; @@ -201,7 +167,7 @@ misc.clamp01 = function (value) { * @return {Number} * @example {@link utils/api/engine/docs/cocos2d/core/platform/CCMacro/lerp.js} */ -misc.lerp = function (a, b, r) { +export function lerp (a, b, r) { return a + (b - a) * r; }; @@ -211,7 +177,7 @@ misc.lerp = function (a, b, r) { * @return {Number} * @method degreesToRadians */ -misc.degreesToRadians = function (angle) { +export function degreesToRadians (angle) { return angle * cc.macro.RAD; }; @@ -221,8 +187,131 @@ misc.degreesToRadians = function (angle) { * @return {Number} * @method radiansToDegrees */ -misc.radiansToDegrees = function (angle) { +export function radiansToDegrees (angle) { return angle * cc.macro.DEG; }; -cc.misc = module.exports = misc; \ No newline at end of file +export function contains (refNode, otherNode) { + if(typeof refNode.contains == 'function'){ + return refNode.contains(otherNode); + }else if(typeof refNode.compareDocumentPosition == 'function' ) { + return !!(refNode.compareDocumentPosition(otherNode) & 16); + }else { + var node = otherNode.parentNode; + if (node) { + do { + if (node === refNode) { + return true; + } else { + node = node.parentNode; + } + } while (node !==null); + } + return false; + } +} + +export function isDomNode (obj) { + if (typeof window === 'object' && typeof Node === 'function') { + // If "TypeError: Right-hand side of 'instanceof' is not callback" is thrown, + // it should because window.Node was overwritten. + return obj instanceof Node; + } + else { + return obj && + typeof obj === 'object' && + typeof obj.nodeType === 'number' && + typeof obj.nodeName === 'string'; + } +} + +export function callInNextTick (callback, p1, p2) { + if (CC_EDITOR) { + if (callback) { + process.nextTick(function () { + callback(p1, p2); + }); + } + } + else { + if (callback) { + setTimeout(function () { + callback(p1, p2); + }, 0); + } + } +} + +if (CC_EDITOR) { + // use anonymous function here to ensure it will not being hoisted without CC_EDITOR + + export function tryCatchFunctor_EDITOR (funcName, forwardArgs, afterCall, bindArg) { + function call_FUNC_InTryCatch (_R_ARGS_) { + try { + target._FUNC_(_U_ARGS_); + } + catch (e) { + cc._throw(e); + } + _AFTER_CALL_ + } + // use evaled code to generate named function + return Function('arg', 'return ' + call_FUNC_InTryCatch + .toString() + .replace(/_FUNC_/g, funcName) + .replace('_R_ARGS_', 'target' + (forwardArgs ? ', ' + forwardArgs : '')) + .replace('_U_ARGS_', forwardArgs || '') + .replace('_AFTER_CALL_', afterCall || ''))(bindArg); + }; + + export function isPlainEmptyObj_DEV (obj) { + if (!obj || obj.constructor !== Object) { + return false; + } + // jshint ignore: start + for (var k in obj) { + return false; + } + // jshint ignore: end + return true; + }; + + export function cloneable_DEV (obj) { + return obj && + typeof obj.clone === 'function' && + ( (obj.constructor && obj.constructor.prototype.hasOwnProperty('clone')) || obj.hasOwnProperty('clone') ); + }; +} + +if (CC_TEST) { + // editor mocks using in unit tests + if (typeof Editor === 'undefined') { + window.Editor = { + UuidUtils: { + NonUuidMark: '.', + uuid: function () { + return '' + ((new Date()).getTime() + Math.random()); + } + } + }; + } +} + +cc.misc = { + BUILTIN_CLASSID_RE, + BASE64_VALUES, + propertyDefine, + NextPOT, + pushToMap, + clampf, + clamp01, + lerp, + degreesToRadians, + radiansToDegrees, + contains, + isDomNode, + callInNextTick, + tryCatchFunctor_EDITOR, + isPlainEmptyObj_DEV, + cloneable_DEV +}; \ No newline at end of file diff --git a/cocos/core/utils/mutable-forward-iterator.js b/cocos/core/utils/mutable-forward-iterator.js index 6581ee9969..58ec4133d1 100644 --- a/cocos/core/utils/mutable-forward-iterator.js +++ b/cocos/core/utils/mutable-forward-iterator.js @@ -33,46 +33,45 @@ * ... * } */ -function MutableForwardIterator (array) { - this.i = 0; - this.array = array; +export default class MutableForwardIterator { + constructor (array) { + this.i = 0; + this.array = array; + } + + remove (value) { + var index = this.array.indexOf(value); + if (index >= 0) { + this.removeAt(index); + } + } + removeAt (i) { + this.array.splice(i, 1); + + if (i <= this.i) { + --this.i; + } + } + fastRemove (value) { + var index = this.array.indexOf(value); + if (index >= 0) { + this.fastRemoveAt(index); + } + } + fastRemoveAt (i) { + var array = this.array; + array[i] = array[array.length - 1]; + --array.length; + + if (i <= this.i) { + --this.i; + } + } + push (item) { + this.array.push(item); + } } -var proto = MutableForwardIterator.prototype; - -proto.remove = function (value) { - var index = this.array.indexOf(value); - if (index >= 0) { - this.removeAt(index); - } -}; -proto.removeAt = function (i) { - this.array.splice(i, 1); - - if (i <= this.i) { - --this.i; - } -}; -proto.fastRemove = function (value) { - var index = this.array.indexOf(value); - if (index >= 0) { - this.fastRemoveAt(index); - } -}; -proto.fastRemoveAt = function (i) { - var array = this.array; - array[i] = array[array.length - 1]; - --array.length; - - if (i <= this.i) { - --this.i; - } -}; - -proto.push = function (item) { - this.array.push(item); -}; - //js.getset(proto, 'length', // function () { // return this.array.length; @@ -83,6 +82,4 @@ proto.push = function (item) { // this.i = len - 1; // } // } -//); - -module.exports = MutableForwardIterator; +//); \ No newline at end of file diff --git a/cocos/core/utils/path.js b/cocos/core/utils/path.js new file mode 100644 index 0000000000..9cc1e8669b --- /dev/null +++ b/cocos/core/utils/path.js @@ -0,0 +1,190 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + Copyright (c) 2017-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. + ****************************************************************************/ + +const EXTNAME_RE = /(\.[^\.\/\?\\]*)(\?.*)?$/; +const DIRNAME_RE = /((.*)(\/|\\|\\\\))?(.*?\..*$)?/; +const NORMALIZE_RE = /[^\.\/]+\/\.\.\//; + +/** + * !#en The module provides utilities for working with file and directory paths + * !#zh 用于处理文件与目录的路径的模块 + * @class path + * @static + */ + +/** + * !#en Join strings to be a path. + * !#zh 拼接字符串为 Path + * @method join + * @example {@link cocos2d/core/utils/CCPath/join.js} + * @returns {String} + */ +export function join () { + let l = arguments.length; + let result = ""; + for (let i = 0; i < l; i++) { + result = (result + (result === "" ? "" : "/") + arguments[i]).replace(/(\/|\\\\)$/, ""); + } + return result; +} + +/** + * !#en Get the ext name of a path including '.', like '.png'. + * !#zh 返回 Path 的扩展名,包括 '.',例如 '.png'。 + * @method extname + * @example {@link cocos2d/core/utils/CCPath/extname.js} + * @param {String} pathStr + * @returns {*} + */ +export function extname (pathStr) { + let temp = EXTNAME_RE.exec(pathStr); + return temp ? temp[1] : ''; +} + +/** + * !#en Get the main name of a file name + * !#zh 获取文件名的主名称 + * @method mainFileName + * @param {String} fileName + * @returns {String} + * @deprecated + */ +export function mainFileName (fileName) { + if (fileName) { + let idx = fileName.lastIndexOf("."); + if (idx !== -1) + return fileName.substring(0, idx); + } + return fileName; +} + +/** + * !#en Get the file name of a file path. + * !#zh 获取文件路径的文件名。 + * @method basename + * @example {@link cocos2d/core/utils/CCPath/basename.js} + * @param {String} pathStr + * @param {String} [extname] + * @returns {*} + */ +export function basename (pathStr, extname) { + let index = pathStr.indexOf("?"); + if (index > 0) pathStr = pathStr.substring(0, index); + let reg = /(\/|\\)([^\/\\]+)$/g; + let result = reg.exec(pathStr.replace(/(\/|\\)$/, "")); + if (!result) return null; + let baseName = result[2]; + if (extname && pathStr.substring(pathStr.length - extname.length).toLowerCase() === extname.toLowerCase()) + return baseName.substring(0, baseName.length - extname.length); + return baseName; +} + +/** + * !#en Get dirname of a file path. + * !#zh 获取文件路径的目录名。 + * @method dirname + * @example {@link cocos2d/core/utils/CCPath/dirname.js} + * @param {String} pathStr + * @returns {*} + */ +export function dirname (pathStr) { + let temp = DIRNAME_RE.exec(pathStr); + return temp ? temp[2] : ''; +} + +/** + * !#en Change extname of a file path. + * !#zh 更改文件路径的扩展名。 + * @method changeExtname + * @example {@link cocos2d/core/utils/CCPath/changeExtname.js} + * @param {String} pathStr + * @param {String} [extname] + * @returns {String} + */ +export function changeExtname (pathStr, extname) { + extname = extname || ""; + let index = pathStr.indexOf("?"); + let tempStr = ""; + if (index > 0) { + tempStr = pathStr.substring(index); + pathStr = pathStr.substring(0, index); + } + index = pathStr.lastIndexOf("."); + if (index < 0) return pathStr + extname + tempStr; + return pathStr.substring(0, index) + extname + tempStr; +} + +/** + * !#en Change file name of a file path. + * !#zh 更改文件路径的文件名。 + * @example {@link cocos2d/core/utils/CCPath/changeBasename.js} + * @param {String} pathStr + * @param {String} basename + * @param {Boolean} [isSameExt] + * @returns {String} + */ +export function changeBasename (pathStr, basename, isSameExt) { + if (basename.indexOf(".") === 0) return this.changeExtname(pathStr, basename); + let index = pathStr.indexOf("?"); + let tempStr = ""; + let ext = isSameExt ? this.extname(pathStr) : ""; + if (index > 0) { + tempStr = pathStr.substring(index); + pathStr = pathStr.substring(0, index); + } + index = pathStr.lastIndexOf("/"); + index = index <= 0 ? 0 : index + 1; + return pathStr.substring(0, index) + basename + ext + tempStr; +} + +//todo make public after verification +export function _normalize (url) { + let oldUrl = url = String(url); + + //removing all ../ + do { + oldUrl = url; + url = url.replace(NORMALIZE_RE, ""); + } while (oldUrl.length !== url.length); + return url; +} + +// @param {string} path +export function stripSep (path) { + return path.replace(/[\/\\]$/, ''); +} + +cc.path = { + join, + extname, + mainFileName, + basename, + dirname, + changeExtname, + changeBasename, + _normalize, + stripSep +}; diff --git a/cocos/core/utils/pool.js b/cocos/core/utils/pool.js new file mode 100644 index 0000000000..4d6c811d66 --- /dev/null +++ b/cocos/core/utils/pool.js @@ -0,0 +1,169 @@ +/**************************************************************************** + 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. + ****************************************************************************/ + +/** + * !#en + * A fixed-length object pool designed for general type.
+ * The implementation of this object pool is very simple, + * it can helps you to improve your game performance for objects which need frequent release and recreate operations
+ * !#zh + * 长度固定的对象缓存池,可以用来缓存各种对象类型。
+ * 这个对象池的实现非常精简,它可以帮助您提高游戏性能,适用于优化对象的反复创建和销毁。 + * @class js.Pool + * @example + * + *Example 1: + * + *function Details () { + * this.uuidList = []; + *}; + *Details.prototype.reset = function () { + * this.uuidList.length = 0; + *}; + *Details.pool = new js.Pool(function (obj) { + * obj.reset(); + *}, 5); + *Details.pool.get = function () { + * return this._get() || new Details(); + *}; + * + *var detail = Details.pool.get(); + *... + *Details.pool.put(detail); + * + *Example 2: + * + *function Details (buffer) { + * this.uuidList = buffer; + *}; + *... + *Details.pool.get = function (buffer) { + * var cached = this._get(); + * if (cached) { + * cached.uuidList = buffer; + * return cached; + * } + * else { + * return new Details(buffer); + * } + *}; + * + *var detail = Details.pool.get( [] ); + *... + */ +export default class Pool { + /** + * !#en + * Constructor for creating an object pool for the specific object type. + * You can pass a callback argument for process the cleanup logic when the object is recycled. + * !#zh + * 使用构造函数来创建一个指定对象类型的对象池,您可以传递一个回调函数,用于处理对象回收时的清理逻辑。 + * @constructor + * @param {Function} [cleanupFunc] - the callback method used to process the cleanup logic when the object is recycled. + * @param {Object} cleanupFunc.obj + * @param {Number} size - initializes the length of the array + * @typescript + * constructor(cleanupFunc: (obj: any) => void, size: number) + * constructor(size: number) + */ + constructor (cleanupFunc, size) { + if (size === undefined) { + size = cleanupFunc; + cleanupFunc = null; + } + this.get = null; + this.count = 0; + this._pool = new Array(size); + this._cleanup = cleanupFunc; + } + + /** + * !#en + * Get an object from pool, if no available object in the pool, null will be returned. + * !#zh + * 获取对象池中的对象,如果对象池没有可用对象,则返回空。 + * @method _get + * @returns {Object|null} + */ + _get () { + if (this.count > 0) { + --this.count; + var cache = this._pool[this.count]; + this._pool[this.count] = null; + return cache; + } + return null; + } + + /** + * !#en Put an object into the pool. + * !#zh 向对象池返还一个不再需要的对象。 + * @method put + */ + put (obj) { + var pool = this._pool; + if (this.count < pool.length) { + if (this._cleanup && this._cleanup(obj) === false) { + return; + } + pool[this.count] = obj; + ++this.count; + } + } + + /** + * !#en Resize the pool. + * !#zh 设置对象池容量。 + * @method resize + */ + resize (length) { + if (length >= 0) { + this._pool.length = length; + if (this.count > length) { + this.count = length; + } + } + } +} + +/** + * !#en + * Get and initialize an object from pool. This method defaults to null and requires the user to implement it. + * !#zh + * 获取并初始化对象池中的对象。这个方法默认为空,需要用户自己实现。 + * @method get + * @param {any} ...params - parameters to used to initialize the object + * @returns {Object} + */ + +/** + * !#en + * The current number of available objects, the default is 0, it will gradually increase with the recycle of the object, + * the maximum will not exceed the size specified when the constructor is called. + * !#zh + * 当前可用对象数量,一开始默认是 0,随着对象的回收会逐渐增大,最大不会超过调用构造函数时指定的 size。 + * @property {Number} count + * @default 0 + */ diff --git a/cocos/core/utils/prefab-helper.js b/cocos/core/utils/prefab-helper.js index 65c587bcff..9b8d4c486b 100644 --- a/cocos/core/utils/prefab-helper.js +++ b/cocos/core/utils/prefab-helper.js @@ -24,7 +24,7 @@ THE SOFTWARE. ****************************************************************************/ -var math = require("../renderer").renderEngine.math; +import math from './vmath'; cc._PrefabInfo = cc.Class({ name: 'cc.PrefabInfo', @@ -62,70 +62,67 @@ cc._PrefabInfo = cc.Class({ // } }); -// prefab helper function -module.exports = { - // update node to make it sync with prefab - syncWithPrefab: function (node) { - var _prefab = node._prefab; - // non-reentrant - _prefab._synced = true; - // - if (!_prefab.asset) { - if (CC_EDITOR) { - var NodeUtils = Editor.require('scene://utils/node'); - var PrefabUtils = Editor.require('scene://utils/prefab'); +// update node to make it sync with prefab +export default function syncWithPrefab (node) { + var _prefab = node._prefab; + // non-reentrant + _prefab._synced = true; + // + if (!_prefab.asset) { + if (CC_EDITOR) { + var NodeUtils = Editor.require('scene://utils/node'); + var PrefabUtils = Editor.require('scene://utils/prefab'); - cc.warn(Editor.T('MESSAGE.prefab.missing_prefab', { node: NodeUtils.getNodePath(node) })); - node.name += PrefabUtils.MISSING_PREFAB_SUFFIX; - } - else { - cc.errorID(3701, node.name); - } - node._prefab = null; - return; - } - - // save root's preserved props to avoid overwritten by prefab - var _objFlags = node._objFlags; - var _parent = node._parent; - var _id = node._id; - var _name = node._name; - var _active = node._active; - var x = node._position.x; - var y = node._position.y; - var _quat = node._quat; - var _localZOrder = node._localZOrder; - var _globalZOrder = node._globalZOrder; - - // instantiate prefab - cc.game._isCloning = true; - if (CC_SUPPORT_JIT) { - _prefab.asset._doInstantiate(node); + cc.warn(Editor.T('MESSAGE.prefab.missing_prefab', { node: NodeUtils.getNodePath(node) })); + node.name += PrefabUtils.MISSING_PREFAB_SUFFIX; } else { - // root in prefab asset is always synced - var prefabRoot = _prefab.asset.data; - prefabRoot._prefab._synced = true; - - // use node as the instantiated prefabRoot to make references to prefabRoot in prefab redirect to node - prefabRoot._iN$t = node; - - // instantiate prefab and apply to node - cc.instantiate._clone(prefabRoot, prefabRoot); + cc.errorID(3701, node.name); } - cc.game._isCloning = false; - - // restore preserved props - node._objFlags = _objFlags; - node._parent = _parent; - node._id = _id; - node._prefab = _prefab; - node._name = _name; - node._active = _active; - node._position.x = x; - node._position.y = y; - math.quat.copy(node._quat, _quat); - node._localZOrder = _localZOrder; - node._globalZOrder = _globalZOrder; + node._prefab = null; + return; } -}; + + // save root's preserved props to avoid overwritten by prefab + var _objFlags = node._objFlags; + var _parent = node._parent; + var _id = node._id; + var _name = node._name; + var _active = node._active; + var x = node._position.x; + var y = node._position.y; + var _quat = node._quat; + var _localZOrder = node._localZOrder; + var _globalZOrder = node._globalZOrder; + + // instantiate prefab + cc.game._isCloning = true; + if (CC_SUPPORT_JIT) { + _prefab.asset._doInstantiate(node); + } + else { + // root in prefab asset is always synced + var prefabRoot = _prefab.asset.data; + prefabRoot._prefab._synced = true; + + // use node as the instantiated prefabRoot to make references to prefabRoot in prefab redirect to node + prefabRoot._iN$t = node; + + // instantiate prefab and apply to node + cc.instantiate._clone(prefabRoot, prefabRoot); + } + cc.game._isCloning = false; + + // restore preserved props + node._objFlags = _objFlags; + node._parent = _parent; + node._id = _id; + node._prefab = _prefab; + node._name = _name; + node._active = _active; + node._position.x = x; + node._position.y = y; + math.quat.copy(node._quat, _quat); + node._localZOrder = _localZOrder; + node._globalZOrder = _globalZOrder; +} \ No newline at end of file diff --git a/cocos/core/utils/text-utils.js b/cocos/core/utils/text-utils.js index 6714142a8f..652b79fbc3 100644 --- a/cocos/core/utils/text-utils.js +++ b/cocos/core/utils/text-utils.js @@ -24,131 +24,127 @@ THE SOFTWARE. ****************************************************************************/ -var textUtils = { - label_wordRex : /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûа-яА-ЯЁё]+|\S)/, - label_symbolRex : /^[!,.:;'}\]%\?>、‘“》?。,!]/, - label_lastWordRex : /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁё]+|\S)$/, - label_lastEnglish : /[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁё]+$/, - label_firstEnglish : /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁё]/, - label_wrapinspection : true, +const WORD_REG = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûа-яА-ЯЁё]+|\S)/; +const SYMBOL_REG = /^[!,.:;'}\]%\?>、‘“》?。,!]/; +const LAST_WORD_REG = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁё]+|\S)$/; +const LAST_ENGLISH_REG = /[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁё]+$/; +const FIRST_ENGLISH_REG = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁё]/; +const WRAP_INSPECTION = true; - isUnicodeCJK: function(ch) { - var __CHINESE_REG = /^[\u4E00-\u9FFF\u3400-\u4DFF]+$/; - var __JAPANESE_REG = /[\u3000-\u303F]|[\u3040-\u309F]|[\u30A0-\u30FF]|[\uFF00-\uFFEF]|[\u4E00-\u9FAF]|[\u2605-\u2606]|[\u2190-\u2195]|\u203B/g; - var __KOREAN_REG = /^[\u1100-\u11FF]|[\u3130-\u318F]|[\uA960-\uA97F]|[\uAC00-\uD7AF]|[\uD7B0-\uD7FF]+$/; - return __CHINESE_REG.test(ch) || __JAPANESE_REG.test(ch) || __KOREAN_REG.test(ch); - }, +export function isUnicodeCJK (ch) { + var __CHINESE_REG = /^[\u4E00-\u9FFF\u3400-\u4DFF]+$/; + var __JAPANESE_REG = /[\u3000-\u303F]|[\u3040-\u309F]|[\u30A0-\u30FF]|[\uFF00-\uFFEF]|[\u4E00-\u9FAF]|[\u2605-\u2606]|[\u2190-\u2195]|\u203B/g; + var __KOREAN_REG = /^[\u1100-\u11FF]|[\u3130-\u318F]|[\uA960-\uA97F]|[\uAC00-\uD7AF]|[\uD7B0-\uD7FF]+$/; + return __CHINESE_REG.test(ch) || __JAPANESE_REG.test(ch) || __KOREAN_REG.test(ch); +} - //Checking whether the character is a whitespace - isUnicodeSpace: function(ch) { - ch = ch.charCodeAt(0); - return ((ch >= 9 && ch <= 13) || ch === 32 || ch === 133 || ch === 160 || ch === 5760 || (ch >= 8192 && ch <= 8202) || ch === 8232 || ch === 8233 || ch === 8239 || ch === 8287 || ch === 12288); - }, +//Checking whether the character is a whitespace +export function isUnicodeSpace (ch) { + ch = ch.charCodeAt(0); + return ((ch >= 9 && ch <= 13) || ch === 32 || ch === 133 || ch === 160 || ch === 5760 || (ch >= 8192 && ch <= 8202) || ch === 8232 || ch === 8233 || ch === 8239 || ch === 8287 || ch === 12288); +} - safeMeasureText: function (ctx, string) { - var metric = ctx.measureText(string); - return metric && metric.width || 0; - }, +export function safeMeasureText (ctx, string) { + var metric = ctx.measureText(string); + return metric && metric.width || 0; +} - fragmentText: function (stringToken, allWidth, maxWidth, measureText) { - //check the first character - var wrappedWords = []; - //fast return if strArr is empty - if(stringToken.length === 0 || maxWidth < 0) { - wrappedWords.push(''); - return wrappedWords; +export function fragmentText (stringToken, allWidth, maxWidth, measureText) { + //check the first character + var wrappedWords = []; + //fast return if strArr is empty + if(stringToken.length === 0 || maxWidth < 0) { + wrappedWords.push(''); + return wrappedWords; + } + + var text = stringToken; + while (allWidth > maxWidth && text.length > 1) { + + var fuzzyLen = text.length * ( maxWidth / allWidth ) | 0; + var tmpText = text.substr(fuzzyLen); + var width = allWidth - measureText(tmpText); + var sLine = tmpText; + var pushNum = 0; + + var checkWhile = 0; + var checkCount = 10; + + //Exceeded the size + while (width > maxWidth && checkWhile++ < checkCount) { + fuzzyLen *= maxWidth / width; + fuzzyLen = fuzzyLen | 0; + tmpText = text.substr(fuzzyLen); + width = allWidth - measureText(tmpText); } - var text = stringToken; - while (allWidth > maxWidth && text.length > 1) { + checkWhile = 0; - var fuzzyLen = text.length * ( maxWidth / allWidth ) | 0; - var tmpText = text.substr(fuzzyLen); - var width = allWidth - measureText(tmpText); - var sLine = tmpText; - var pushNum = 0; - - var checkWhile = 0; - var checkCount = 10; - - //Exceeded the size - while (width > maxWidth && checkWhile++ < checkCount) { - fuzzyLen *= maxWidth / width; - fuzzyLen = fuzzyLen | 0; - tmpText = text.substr(fuzzyLen); - width = allWidth - measureText(tmpText); + //Find the truncation point + while (width <= maxWidth && checkWhile++ < checkCount) { + if (tmpText) { + var exec = WORD_REG.exec(tmpText); + pushNum = exec ? exec[0].length : 1; + sLine = tmpText; } - checkWhile = 0; - - //Find the truncation point - while (width <= maxWidth && checkWhile++ < checkCount) { - if (tmpText) { - var exec = this.label_wordRex.exec(tmpText); - pushNum = exec ? exec[0].length : 1; - sLine = tmpText; - } - - fuzzyLen = fuzzyLen + pushNum; - tmpText = text.substr(fuzzyLen); - width = allWidth - measureText(tmpText); - } - - fuzzyLen -= pushNum; - if (fuzzyLen === 0) { - fuzzyLen = 1; - sLine = sLine.substr(1); - } - - var sText = text.substr(0, fuzzyLen), result; - - //symbol in the first - if (this.label_wrapinspection) { - if (this.label_symbolRex.test(sLine || tmpText)) { - result = this.label_lastWordRex.exec(sText); - fuzzyLen -= result ? result[0].length : 0; - if (fuzzyLen === 0) fuzzyLen = 1; - - sLine = text.substr(fuzzyLen); - sText = text.substr(0, fuzzyLen); - } - } - - //To judge whether a English words are truncated - if (this.label_firstEnglish.test(sLine)) { - result = this.label_lastEnglish.exec(sText); - if (result && sText !== result[0]) { - fuzzyLen -= result[0].length; - sLine = text.substr(fuzzyLen); - sText = text.substr(0, fuzzyLen); - } - } - - // The first line And do not wrap should not remove the space - if (wrappedWords.length === 0) { - wrappedWords.push(sText); - } - else { - sText = sText.trim(); - if (sText.length > 0) { - wrappedWords.push(sText); - } - } - text = sLine || tmpText; - allWidth = measureText(text); + fuzzyLen = fuzzyLen + pushNum; + tmpText = text.substr(fuzzyLen); + width = allWidth - measureText(tmpText); } + fuzzyLen -= pushNum; + if (fuzzyLen === 0) { + fuzzyLen = 1; + sLine = sLine.substr(1); + } + + var sText = text.substr(0, fuzzyLen), result; + + //symbol in the first + if (WRAP_INSPECTION) { + if (SYMBOL_REG.test(sLine || tmpText)) { + result = LAST_WORD_REG.exec(sText); + fuzzyLen -= result ? result[0].length : 0; + if (fuzzyLen === 0) fuzzyLen = 1; + + sLine = text.substr(fuzzyLen); + sText = text.substr(0, fuzzyLen); + } + } + + //To judge whether a English words are truncated + if (FIRST_ENGLISH_REG.test(sLine)) { + result = LAST_ENGLISH_REG.exec(sText); + if (result && sText !== result[0]) { + fuzzyLen -= result[0].length; + sLine = text.substr(fuzzyLen); + sText = text.substr(0, fuzzyLen); + } + } + + // The first line And do not wrap should not remove the space if (wrappedWords.length === 0) { - wrappedWords.push(text); + wrappedWords.push(sText); } else { - text = text.trim(); - if (text.length > 0) { - wrappedWords.push(text); + sText = sText.trim(); + if (sText.length > 0) { + wrappedWords.push(sText); } } - return wrappedWords; - }, -}; + text = sLine || tmpText; + allWidth = measureText(text); + } -module.exports = textUtils; + if (wrappedWords.length === 0) { + wrappedWords.push(text); + } + else { + text = text.trim(); + if (text.length > 0) { + wrappedWords.push(text); + } + } + return wrappedWords; +} diff --git a/cocos/assets/url.js b/cocos/load-pipeline/url.js similarity index 100% rename from cocos/assets/url.js rename to cocos/load-pipeline/url.js diff --git a/cocos/scene-graph/CCNode.js b/cocos/scene-graph/CCNode.js index 68bb86426d..41478fb49f 100644 --- a/cocos/scene-graph/CCNode.js +++ b/cocos/scene-graph/CCNode.js @@ -27,12 +27,10 @@ const BaseNode = require('./utils/base-node'); const PrefabHelper = require('./utils/prefab-helper'); -const mathPools = require('./utils/math-pools'); const math = require('./renderer/render-engine').math; const AffineTrans = require('./utils/affine-transform'); const eventManager = require('./event-manager'); const macro = require('./platform/CCMacro'); -const misc = require('./utils/misc'); const js = require('./platform/js'); const Event = require('./event/event'); const EventTarget = require('./event/event-target'); @@ -55,13 +53,24 @@ var _globalOrderOfArrival = 1; var _cachedArray = new Array(16); _cachedArray.length = 0; +var _mat4Pool = new js.Pool(128); +_mat4Pool.get = function () { + var matrix = this._get(); + if (matrix) { + math.mat4.identity(matrix); + } + else { + matrix = math.mat4.create(); + } + return matrix; +}; + const POSITION_ON = 1 << 0; const SCALE_ON = 1 << 1; const ROTATION_ON = 1 << 2; const SIZE_ON = 1 << 3; const ANCHOR_ON = 1 << 4; - let BuiltinGroupIndex = cc.Enum({ DEBUG: 31 }) @@ -1139,8 +1148,8 @@ var Node = cc.Class({ this._scale.y = 1; this._scale.z = 1; - this._matrix = mathPools.mat4.get(); - this._worldMatrix = mathPools.mat4.get(); + this._matrix = _mat4Pool.get(); + this._worldMatrix = _mat4Pool.get(); this._localMatDirty = LocalDirtyFlag.ALL; this._worldMatDirty = true; @@ -1205,8 +1214,8 @@ var Node = cc.Class({ } // Recycle math objects - mathPools.mat4.put(this._matrix); - mathPools.mat4.put(this._worldMatrix); + _mat4Pool.put(this._matrix); + _mat4Pool.put(this._worldMatrix); this._matrix = this._worldMatrix = null; if (this._reorderChildDirty) { @@ -3011,10 +3020,10 @@ var Node = cc.Class({ * but it will be reserved and reused for undo. */ if (!this._matrix) { - this._matrix = mathPools.mat4.get(); + this._matrix = _mat4Pool.get(); } if (!this._worldMatrix) { - this._worldMatrix = mathPools.mat4.get(); + this._worldMatrix = _mat4Pool.get(); } this._localMatDirty = LocalDirtyFlag.ALL; diff --git a/cocos/core/utils/find.js b/cocos/scene-graph/find.js similarity index 97% rename from cocos/core/utils/find.js rename to cocos/scene-graph/find.js index ea42a19c2f..d876294532 100644 --- a/cocos/core/utils/find.js +++ b/cocos/scene-graph/find.js @@ -36,7 +36,7 @@ * @param {Node} [referenceNode] * @return {Node|null} the node or null if not found */ -cc.find = module.exports = function (path, referenceNode) { +export default function find (path, referenceNode) { if (path == null) { cc.errorID(5600); return null; @@ -83,3 +83,5 @@ cc.find = module.exports = function (path, referenceNode) { return match; }; + +cc.find = find; \ No newline at end of file