diff --git a/EngineErrorMap.md b/EngineErrorMap.md index 0759dfffc8..f1314fb05f 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -396,6 +396,7 @@ cocos2d: Could not initialize cc.AtlasNode. Invalid Texture. ### 1622 + _ccsg.Node._requestDirtyFlag: failed to satisfy the request, key (%s) for flag have already been taken ### 1623 @@ -420,18 +421,22 @@ Not support for asynchronous creating node in SG ### 1628 + Renderer error: Size of the cc._RendererInSG._sgNode must be zero ### 1629 + The node '%s' has a component inherited from 'cc._RendererInSG' ### 1630 + JSB environment is not support invoke node.runAction before the 'cc._RendererInSG' component enabled. ### 1631 + Please use runAction in the method 'start' instead. ### 1632 @@ -1558,6 +1563,7 @@ _ccsg.Label._initBMFontWithString(): Impossible to create font. Please check fil ### 4002 + _ccsg.Label._initBMFontWithString(): re-init is no longer supported ### 4003 @@ -2008,26 +2014,32 @@ cc.ParticleBatchNode._addChildHelper(): child already added. It can't be added a ### 6008 + _ccsg.ParticleSystem.initWithFile(): Particles: file not found ### 6009 + _ccsg.ParticleSystem.initWithDictionary(): Invalid emitterType in config file ### 6010 + _ccsg.ParticleSystem: error decoding or ungzipping textureImageData ### 6011 + _ccsg.ParticleSystem: unknown image format with Data ### 6012 + _ccsg.ParticleSystem.initWithDictionary() : error loading the texture ### 6013 + Particle system: not enough memory ### 6014 @@ -2037,6 +2049,7 @@ Can't change blending functions when the particle is being batched ### 6015 + _ccsg.ParticleSystem.setDisplayFrame(): QuadParticle only supports SpriteFrames with no offsets ### 6016 @@ -2096,6 +2109,18 @@ Unknown Photometric Interpretation: %s Unkown error +### 6030 + +cc.ParticleSystem: error decoding or ungzipping textureImageData + +### 6031 + +cc.ParticleSystem: unknown image format with Data + +### 6032 + +cc.ParticleSystem.initWithDictionary() : error loading the texture + ### 6100 @@ -2239,26 +2264,32 @@ Property 'mapLoaded' is unused now. Please write the logic to the callback 'star ### 7204 + _ccsg.TMXLayer.getTileAt(): TMXLayer: the tiles map has been released ### 7205 + _ccsg.TMXLayer.getTileGIDAt(): TMXLayer: the tiles map has been released ### 7206 + _ccsg.TMXLayer.setTileGID(): TMXLayer: the tiles map has been released ### 7207 + _ccsg.TMXLayer.setTileGID(): invalid gid: %s ### 7208 + _ccsg.TMXLayer.getTileFlagsAt(): TMXLayer: the tiles map has been released ### 7209 + _ccsg.TMXLayer.removeTileAt(): TMXLayer: the tiles map has been released ### 7210 @@ -2271,10 +2302,12 @@ TMX invalid value ### 7212 + _ccsg.TMXTiledMap.initWithTMXFile(): Map not found. Please check the filename. ### 7213 + _ccsg.TMXTiledMap.initWithXML(): Map not found. Please check the filename. ### 7214 @@ -2316,56 +2349,93 @@ Parse %s failed. ### 7223 + _ccsg.TMXLayer.setTileGID(): pos should be non-null ### 7224 + _ccsg.TMXTiledMap.getLayer(): layerName should be non-null or non-empty string. ### 7225 + _ccsg.TMXTiledMap.getObjectGroup(): groupName should be non-null or non-empty string. ### 7226 + _ccsg.TMXLayer.getTileAt(): pos should be non-null ### 7227 + _ccsg.TMXLayer.getTileAt(): invalid position ### 7228 + _ccsg.TMXLayer.getTileGIDAt(): pos should be non-null ### 7229 + _ccsg.TMXLayer.getTileGIDAt(): invalid position ### 7230 + _ccsg.TMXLayer.setTileGID(): pos should be non-null ### 7231 + _ccsg.TMXLayer.setTileGID(): invalid position ### 7232 + _ccsg.TMXLayer.getTileFlagsAt(): pos should be non-null ### 7233 + _ccsg.TMXLayer.getTileFlagsAt(): invalid position ### 7234 + _ccsg.TMXLayer.removeTileAt(): pos should be non-null ### 7235 + _ccsg.TMXLayer.removeTileAt(): invalid position +### 7236 + +cc.TMXLayer.getTileAt(): TMXLayer: the tiles map has been released + +### 7237 + +cc.TMXLayer.getTileGIDAt(): TMXLayer: the tiles map has been released + +### 7238 + +cc.TMXLayer.setTileGID(): TMXLayer: the tiles map has been released + +### 7239 + +cc.TMXLayer.setTileGID(): invalid gid: %s + +### 7240 + +cc.TMXLayer.getTileFlagsAt(): TMXLayer: the tiles map has been released + +### 7241 + +cc.TiledMap.initWithXML(): Map not found. Please check the filename. + ### 7300 diff --git a/cocos2d/actions/CCAction.js b/cocos2d/actions/CCAction.js index a856fb067b..4d98beb3a8 100644 --- a/cocos2d/actions/CCAction.js +++ b/cocos2d/actions/CCAction.js @@ -400,17 +400,15 @@ cc.speed = function (action, speed) { * @property {Number} topBoundary - world topBoundary. * @property {Number} bottomBoundary - world bottomBoundary. * - * @param {_ccsg.Node} followedNode + * @param {cc.Node} followedNode * @param {Rect} rect * @example * // creates the action with a set boundary - * var sprite = new _ccsg.Sprite("spriteFileName"); - * var followAction = new cc.Follow(sprite, cc.rect(0, 0, s.width * 2 - 100, s.height)); + * var followAction = new cc.Follow(node, cc.rect(0, 0, s.width * 2 - 100, s.height)); * this.runAction(followAction); * * // creates the action with no boundary set - * var sprite = new _ccsg.Sprite("spriteFileName"); - * var followAction = new cc.Follow(sprite); + * var followAction = new cc.Follow(node); * this.runAction(followAction); * * @class @@ -424,7 +422,7 @@ cc.Follow = cc.Class({ * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
* creates the action with a set boundary.
* creates the action with no boundary set. - * @param {_ccsg.Node} followedNode + * @param {cc.Node} followedNode * @param {Rect} rect */ ctor:function (followedNode, rect) { @@ -478,7 +476,7 @@ cc.Follow = cc.Class({ /* * initializes the action with a set boundary. * - * @param {_ccsg.Node} followedNode + * @param {cc.Node} followedNode * @param {Rect} [rect=] * @return {Boolean} */ diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index a429457b53..866c68b28b 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -243,7 +243,7 @@ cc.Director.prototype = { var top = box.top + window.pageYOffset - container.clientTop; var x = view._devicePixelRatio * (uiPoint.x - left); var y = view._devicePixelRatio * (top + box.height - uiPoint.y); - return view._isRotated ? {x: view._viewportRect.width - y, y: x} : {x: x, y: y}; + return view._isRotated ? cc.v2(view._viewportRect.width - y, x) : cc.v2(x, y); }, /** @@ -263,7 +263,7 @@ cc.Director.prototype = { var box = container.getBoundingClientRect(); var left = box.left + window.pageXOffset - container.clientLeft; var top = box.top + window.pageYOffset - container.clientTop; - var uiPoint = {x: 0, y: 0}; + var uiPoint = cc.v2(0, 0); if (view._isRotated) { uiPoint.x = left + glPoint.y / view._devicePixelRatio; uiPoint.y = top + box.height - (view._viewportRect.width - glPoint.x) / view._devicePixelRatio; diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index 8dfabf5569..b7f97f65c2 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -610,7 +610,7 @@ var game = { if (typeof config.registerSystemEvent !== 'boolean') { config.registerSystemEvent = true; } - config.showFPS = (typeof config.showFPS !== 'undefined') ? (!!config.showFPS) : true; + config.showFPS = !!config.showFPS; // Scene parser this._sceneInfos = config.scenes || []; @@ -744,7 +744,9 @@ var game = { this._renderContext = renderer.device._gl; // Enable dynamic atlas manager by default - cc.dynamicAtlasManager.enabled = true; + if (!cc.macro.CLEANUP_IMAGE_CACHE) { + cc.dynamicAtlasManager.enabled = true; + } } if (!this._renderContext) { this.renderType = this.RENDER_TYPE_CANVAS; diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index b2a1b82639..fee8abf7e0 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -46,6 +46,8 @@ const ONE_DEGREE = Math.PI / 180; var ActionManagerExist = !!cc.ActionManager; var emptyFunc = function () {}; +var _vec2a = cc.v2(); +var _vec2b = cc.v2(); var _mat4_temp = math.mat4.create(); var _vec3_temp = math.vec3.create(); var _quat_temp = math.quat.create(); @@ -121,7 +123,7 @@ var LocalDirtyFlag = cc.Enum({ /** * !#en The event type supported by Node * !#zh Node 支持的事件类型 - * @enum Node.EventType + * @class Node.EventType * @static * @namespace Node */ @@ -708,9 +710,6 @@ var Node = cc.Class({ */ rotation: { get () { - if (this._rotationX !== this._rotationY) { - cc.logID(1602); - } return this._rotationX; }, set (value) { @@ -930,7 +929,7 @@ var Node = cc.Class({ }, set (value) { if (!this._color.equals(value)) { - this._color.fromColor(value); + this._color.set(value); if (CC_DEV && value.a !== 255) { cc.warnID(1626); } @@ -1098,7 +1097,7 @@ var Node = cc.Class({ * @method constructor * @param {String} [name] */ - ctor (name) { + ctor () { this._reorderChildDirty = false; // cache component @@ -1338,54 +1337,7 @@ var Node = cc.Class({ // EVENT TARGET - /** - * !#en - * Register a callback of a specific event type on Node.
- * Use this method to register touch or mouse event permit propagation based on scene graph,
- * These kinds of event are triggered with dispatchEvent, the dispatch process has three steps:
- * 1. Capturing phase: dispatch in capture targets (`_getCapturingTargets`), e.g. parents in node tree, from root to the real target
- * 2. At target phase: dispatch to the listeners of the real target
- * 3. Bubbling phase: dispatch in bubble targets (`_getBubblingTargets`), e.g. parents in node tree, from the real target to root
- * In any moment of the dispatching process, it can be stopped via `event.stopPropagation()` or `event.stopPropagationImmidiate()`.
- * It's the recommended way to register touch/mouse event for Node,
- * please do not use cc.eventManager directly for Node.
- * You can also register custom event and use `emit` to trigger custom event on Node.
- * For such events, there won't be capturing and bubbling phase, your event will be dispatched directly to its listeners registered on the same node.
- * You can also pass event callback parameters with `emit` by passing parameters after `type`. - * !#zh - * 在节点上注册指定类型的回调函数,也可以设置 target 用于绑定响应函数的 this 对象。
- * 鼠标或触摸事件会被系统调用 dispatchEvent 方法触发,触发的过程包含三个阶段:
- * 1. 捕获阶段:派发事件给捕获目标(通过 `_getCapturingTargets` 获取),比如,节点树中注册了捕获阶段的父节点,从根节点开始派发直到目标节点。
- * 2. 目标阶段:派发给目标节点的监听器。
- * 3. 冒泡阶段:派发事件给冒泡目标(通过 `_getBubblingTargets` 获取),比如,节点树中注册了冒泡阶段的父节点,从目标节点开始派发知道根节点。
- * 同时您可以将事件派发到父节点或者通过调用 stopPropagation 拦截它。
- * 推荐使用这种方式来监听节点上的触摸或鼠标事件,请不要在节点上直接使用 cc.eventManager。
- * 你也可以注册自定义事件到节点上,并通过 emit 方法触发此类事件,对于这类事件,不会发生捕获冒泡阶段,只会直接派发给注册在该节点上的监听器
- * 你可以通过在 emit 方法调用时在 type 之后传递额外的参数作为事件回调的参数列表 - * @method on - * @param {String} type - A string representing the event type to listen for.
- * See {{#crossLink "Node/EventTyupe/POSITION_CHANGED"}}Node Events{{/crossLink}} for all builtin events. - * @param {Function} callback - The callback that will be invoked when the event is dispatched. - * The callback is ignored if it is a duplicate (the callbacks are unique). - * @param {Event} callback.event event - * @param {Object} [target] - The target (this object) to invoke the callback, can be null - * @param {Boolean} [useCapture=false] - When set to true, the capture argument prevents callback - * from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. - * When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE. - * Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET. - * @return {Function} - Just returns the incoming callback so you can save the anonymous function easier. - * @typescript - * on(type: string, callback: (event: Event.EventCustom) => void, target?: any, useCapture?: boolean): (event: Event.EventCustom) => void - * on(type: string, callback: (event: T) => void, target?: any, useCapture?: boolean): (event: T) => void - * @example - * this.node.on(cc.Node.EventType.TOUCH_START, this.memberFunction, this); // if "this" is component and the "memberFunction" declared in CCClass. - * node.on(cc.Node.EventType.TOUCH_START, callback, this.node); - * node.on(cc.Node.EventType.TOUCH_MOVE, callback, this.node); - * node.on(cc.Node.EventType.TOUCH_END, callback, this.node); - * node.on(cc.Node.EventType.TOUCH_CANCEL, callback, this.node); - * node.on(cc.Node.EventType.ANCHOR_CHANGED, callback, this); - */ - on (type, callback, target, useCapture) { + _checknSetupSysEvent (type) { let newAdded = false; let forDispatch = false; if (_touchEvents.indexOf(type) !== -1) { @@ -1429,7 +1381,61 @@ var Node = cc.Class({ } }, this, 0, 0, 0, false); } + return forDispatch; + }, + /** + * !#en + * Register a callback of a specific event type on Node.
+ * Use this method to register touch or mouse event permit propagation based on scene graph,
+ * These kinds of event are triggered with dispatchEvent, the dispatch process has three steps:
+ * 1. Capturing phase: dispatch in capture targets (`_getCapturingTargets`), e.g. parents in node tree, from root to the real target
+ * 2. At target phase: dispatch to the listeners of the real target
+ * 3. Bubbling phase: dispatch in bubble targets (`_getBubblingTargets`), e.g. parents in node tree, from the real target to root
+ * In any moment of the dispatching process, it can be stopped via `event.stopPropagation()` or `event.stopPropagationImmidiate()`.
+ * It's the recommended way to register touch/mouse event for Node,
+ * please do not use cc.eventManager directly for Node.
+ * You can also register custom event and use `emit` to trigger custom event on Node.
+ * For such events, there won't be capturing and bubbling phase, your event will be dispatched directly to its listeners registered on the same node.
+ * You can also pass event callback parameters with `emit` by passing parameters after `type`. + * !#zh + * 在节点上注册指定类型的回调函数,也可以设置 target 用于绑定响应函数的 this 对象。
+ * 鼠标或触摸事件会被系统调用 dispatchEvent 方法触发,触发的过程包含三个阶段:
+ * 1. 捕获阶段:派发事件给捕获目标(通过 `_getCapturingTargets` 获取),比如,节点树中注册了捕获阶段的父节点,从根节点开始派发直到目标节点。
+ * 2. 目标阶段:派发给目标节点的监听器。
+ * 3. 冒泡阶段:派发事件给冒泡目标(通过 `_getBubblingTargets` 获取),比如,节点树中注册了冒泡阶段的父节点,从目标节点开始派发知道根节点。
+ * 同时您可以将事件派发到父节点或者通过调用 stopPropagation 拦截它。
+ * 推荐使用这种方式来监听节点上的触摸或鼠标事件,请不要在节点上直接使用 cc.eventManager。
+ * 你也可以注册自定义事件到节点上,并通过 emit 方法触发此类事件,对于这类事件,不会发生捕获冒泡阶段,只会直接派发给注册在该节点上的监听器
+ * 你可以通过在 emit 方法调用时在 type 之后传递额外的参数作为事件回调的参数列表 + * @method on + * @param {String|Node.EventType} type - A string representing the event type to listen for.
+ * See {{#crossLink "Node/EventTyupe/POSITION_CHANGED"}}Node Events{{/crossLink}} for all builtin events. + * @param {Function} callback - The callback that will be invoked when the event is dispatched. + * The callback is ignored if it is a duplicate (the callbacks are unique). + * @param {Event|Object} callback.event event or first argument when emit + * @param {Event} callback.arg2 arg2 + * @param {Event} callback.arg3 arg3 + * @param {Event} callback.arg4 arg4 + * @param {Event} callback.arg5 arg5 + * @param {Object} [target] - The target (this object) to invoke the callback, can be null + * @param {Boolean} [useCapture=false] - When set to true, the capture argument prevents callback + * from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. + * When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE. + * Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET. + * @return {Function} - Just returns the incoming callback so you can save the anonymous function easier. + * @typescript + * on(type: string, callback: T, target?: any, useCapture?: boolean): T + * @example + * this.node.on(cc.Node.EventType.TOUCH_START, this.memberFunction, this); // if "this" is component and the "memberFunction" declared in CCClass. + * node.on(cc.Node.EventType.TOUCH_START, callback, this); + * node.on(cc.Node.EventType.TOUCH_MOVE, callback, this); + * node.on(cc.Node.EventType.TOUCH_END, callback, this); + * node.on(cc.Node.EventType.TOUCH_CANCEL, callback, this); + * node.on(cc.Node.EventType.ANCHOR_CHANGED, callback); + */ + on (type, callback, target, useCapture) { + let forDispatch = this._checknSetupSysEvent(type); if (forDispatch) { return this._onDispatch(type, callback, target, useCapture); } @@ -1458,6 +1464,53 @@ var Node = cc.Class({ } }, + /** + * !#en + * Register an callback of a specific event type on the Node, + * the callback will remove itself after the first time it is triggered. + * !#zh + * 注册节点的特定事件类型回调,回调会在第一时间被触发后删除自身。 + * + * @method once + * @param {String} type - A string representing the event type to listen for. + * @param {Function} callback - The callback that will be invoked when the event is dispatched. + * The callback is ignored if it is a duplicate (the callbacks are unique). + * @param {Event} callback.event event or first argument when emit + * @param {Event} callback.arg2 arg2 + * @param {Event} callback.arg3 arg3 + * @param {Event} callback.arg4 arg4 + * @param {Event} callback.arg5 arg5 + * @param {Object} [target] - The target (this object) to invoke the callback, can be null + * @typescript + * once(type: string, callback: T, target?: any, useCapture?: boolean): T + * @example + * node.once(cc.Node.EventType.ANCHOR_CHANGED, callback); + */ + once (type, callback, target, useCapture) { + let forDispatch = this._checknSetupSysEvent(type); + let eventType_hasOnceListener = '__ONCE_FLAG:' + type; + + let listeners = null; + if (forDispatch && useCapture) { + listeners = this._capturingListeners = this._capturingListeners || new EventTarget(); + } + else { + listeners = this._bubblingListeners = this._bubblingListeners || new EventTarget(); + } + + let hasOnceListener = listeners.hasEventListener(eventType_hasOnceListener, callback, target); + if (!hasOnceListener) { + let self = this; + let onceWrapper = function (arg1, arg2, arg3, arg4, arg5) { + self.off(type, onceWrapper, target); + listeners.remove(eventType_hasOnceListener, callback, target); + callback.call(this, arg1, arg2, arg3, arg4, arg5); + }; + this.on(type, onceWrapper, target); + listeners.add(eventType_hasOnceListener, callback, target); + } + }, + _onDispatch (type, callback, target, useCapture) { // Accept also patameters like: (type, callback, useCapture) if (typeof target === 'boolean') { @@ -1488,26 +1541,6 @@ var Node = cc.Class({ return callback; }, - _onceDispatch (type, callback, target, useCapture) { - var eventType_hasOnceListener = '__ONCE_FLAG:' + type; - var listeners = useCapture ? this._capturingListeners : this._bubblingListeners; - var hasOnceListener = listeners && listeners.hasEventListener(eventType_hasOnceListener, callback, target); - if (!hasOnceListener) { - var self = this; - var onceWrapper = function (event) { - self._offDispatch(type, onceWrapper, target, useCapture); - listeners.remove(eventType_hasOnceListener, callback, target); - callback.call(this, event); - }; - this._onDispatch(type, onceWrapper, target, useCapture); - if (!listeners) { - // obtain new created listeners - listeners = useCapture ? this._capturingListeners : this._bubblingListeners; - } - listeners.add(eventType_hasOnceListener, callback, target); - } - }, - /** * !#en * Removes the callback previously registered with the same type, callback, target and or useCapture. @@ -1729,23 +1762,24 @@ var Node = cc.Class({ }, _hitTest (point, listener) { - var w = this.width, - h = this.height; - var testPt; + let w = this._contentSize.width, + h = this._contentSize.height, + cameraPt = _vec2a, + testPt = _vec2b; let camera = cc.Camera.findCamera(this); if (camera) { - testPt = camera.getCameraToWorldPoint(point); + camera.getCameraToWorldPoint(point, cameraPt); } else { - testPt = cc.v2(point); + cameraPt.set(point); } this._updateWorldMatrix(); math.mat4.invert(_mat4_temp, this._worldMatrix); - math.vec2.transformMat4(testPt, testPt, _mat4_temp); - testPt.x += this._anchorPoint.x * this._contentSize.width; - testPt.y += this._anchorPoint.y * this._contentSize.height; + math.vec2.transformMat4(testPt, cameraPt, _mat4_temp); + testPt.x += this._anchorPoint.x * w; + testPt.y += this._anchorPoint.y * h; if (testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h) { if (listener && listener.mask) { @@ -1756,7 +1790,7 @@ var Node = cc.Class({ // find mask parent, should hit test it if (parent === mask.node) { var comp = parent.getComponent(cc.Mask); - return (comp && comp.enabledInHierarchy) ? comp._hitTest(point) : true; + return (comp && comp.enabledInHierarchy) ? comp._hitTest(cameraPt) : true; } // mask parent no longer exists else { @@ -2367,7 +2401,7 @@ var Node = cc.Class({ let t = this._matrix; //math.mat4.fromRTS(t, this._quat, this._position, this._scale); - if (dirtyFlag & LocalDirtyFlag.RT) { + if (dirtyFlag & (LocalDirtyFlag.RT | LocalDirtyFlag.SKEW)) { let hasRotation = this._rotationX || this._rotationY; let hasSkew = this._skewX || this._skewY; let sx = this._scale.x, sy = this._scale.y; diff --git a/cocos2d/core/assets/CCSpriteFrame.js b/cocos2d/core/assets/CCSpriteFrame.js index cb573a6d0d..e68e0ff075 100644 --- a/cocos2d/core/assets/CCSpriteFrame.js +++ b/cocos2d/core/assets/CCSpriteFrame.js @@ -33,12 +33,12 @@ let temp_uvs = [{u: 0, v: 0}, {u: 0, v: 0}, {u: 0, v: 0}, {u: 0, v: 0}]; /** * !#en * A cc.SpriteFrame has:
- * - texture: A cc.Texture2D that will be used by the _ccsg.Sprite
+ * - texture: A cc.Texture2D that will be used by render components
* - rectangle: A rectangle of the texture * * !#zh * 一个 SpriteFrame 包含:
- * - 纹理:会被 Sprite 使用的 Texture2D 对象。
+ * - 纹理:会被渲染组件使用的 Texture2D 对象。
* - 矩形:在纹理中的矩形区域。 * * @class SpriteFrame @@ -102,6 +102,9 @@ let SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ * @param {Size} [originalSize] - The size of the frame in the texture */ ctor: function () { + // Init EventTarget data + EventTarget.call(this); + let filename = arguments[0]; let rect = arguments[1]; let rotated = arguments[2]; diff --git a/cocos2d/core/assets/CCTexture2D.js b/cocos2d/core/assets/CCTexture2D.js index 23eb5ecd15..d72fd494bc 100644 --- a/cocos2d/core/assets/CCTexture2D.js +++ b/cocos2d/core/assets/CCTexture2D.js @@ -536,6 +536,14 @@ var Texture2D = cc.Class({ //dispatch load event to listener. this.loaded = true; this.emit("load"); + + if (cc.macro.CLEANUP_IMAGE_CACHE && this._image instanceof HTMLImageElement) { + // wechat game platform will cache image parsed data, + // so image will consume much more memory than web, releasing it + this._image.src = ""; + // Release image in loader cache + cc.loader.removeItem(this._image.id); + } }, /** diff --git a/cocos2d/core/camera/CCCamera.js b/cocos2d/core/camera/CCCamera.js index fc986cd8a1..3605623808 100644 --- a/cocos2d/core/camera/CCCamera.js +++ b/cocos2d/core/camera/CCCamera.js @@ -36,7 +36,6 @@ const vec3 = cc.vmath.vec3; let _mat4_temp_1 = mat4.create(); let _mat4_temp_2 = mat4.create(); let _vec3_temp_1 = vec3.create(); -let _vec3_temp_2 = vec3.create(); let _cameras = []; diff --git a/cocos2d/core/components/CCAnimation.js b/cocos2d/core/components/CCAnimation.js index 55b6741eff..d110f4e85e 100644 --- a/cocos2d/core/components/CCAnimation.js +++ b/cocos2d/core/components/CCAnimation.js @@ -37,6 +37,58 @@ function equalClips (clip1, clip2) { return clip1 && clip2 && (clip1.name === clip2.name || clip1._uuid === clip2._uuid); } +/** + * !#en The event type supported by Animation + * !#zh Animation 支持的事件类型 + * @class Animation.EventType + * @static + * @namespace Animationd + */ +var EventType = cc.Enum({ + /** + * !#en Emit when begin playing animation + * !#zh 开始播放时触发 + * @property {String} PLAY + * @static + */ + PLAY: 'play', + /** + * !#en Emit when stop playing animation + * !#zh 停止播放时触发 + * @property {String} STOP + * @static + */ + STOP: 'stop', + /** + * !#en Emit when pause animation + * !#zh 暂停播放时触发 + * @property {String} PAUSE + * @static + */ + PAUSE: 'pause', + /** + * !#en Emit when resume animation + * !#zh 恢复播放时触发 + * @property {String} RESUME + * @static + */ + RESUME: 'resume', + /** + * !#en If animation repeat count is larger than 1, emit when animation play to the last frame + * !#zh 假如动画循环次数大于 1,当动画播放到最后一帧时触发 + * @property {String} LASTFRAME + * @static + */ + LASTFRAME: 'lastframe', + /** + * !#en Emit when finish playing animation + * !#zh 动画播放完成时触发 + * @property {String} FINISHED + * @static + */ + FINISHED: 'finished' +}) + /** * !#en The animation component is used to play back animations. * @@ -73,6 +125,10 @@ var Animation = cc.Class({ executeInEditMode: true, }, + statics: { + EventType + }, + ctor: function () { cc.EventTarget.call(this); diff --git a/cocos2d/core/components/CCLabel.js b/cocos2d/core/components/CCLabel.js index 48f39b850e..9b6ba277f7 100644 --- a/cocos2d/core/components/CCLabel.js +++ b/cocos2d/core/components/CCLabel.js @@ -528,6 +528,7 @@ let Label = cc.Class({ else { if (!this._ttfTexture) { this._ttfTexture = new cc.Texture2D(); + this._ttfTexture.setPremultiplyAlpha(true); this._assemblerData = this._assembler._getAssemblerData(); this._ttfTexture.initWithElement(this._assemblerData.canvas); } @@ -543,6 +544,10 @@ let Label = cc.Class({ if (!material) { material = new SpriteMaterial(); } + // Setup blend function for premultiplied ttf label texture + if (this._texture === this._ttfTexture) { + this._srcBlendFactor = cc.macro.ONE; + } material.texture = this._texture; this._updateMaterial(material); } diff --git a/cocos2d/core/components/CCMask.js b/cocos2d/core/components/CCMask.js index a5f450e465..530dabdb8c 100644 --- a/cocos2d/core/components/CCMask.js +++ b/cocos2d/core/components/CCMask.js @@ -31,8 +31,8 @@ const StencilMaterial = renderEngine.StencilMaterial; const RenderComponent = require('./CCRenderComponent'); const RenderFlow = require('../renderer/render-flow'); +let _vec2_temp = cc.v2(); let _mat4_temp = math.mat4.create(); -let _rect_temp = cc.rect(); /** * !#en the type for mask. @@ -316,30 +316,25 @@ let Mask = cc.Class({ this.markForRender(true); }, - _hitTest: function (point) { + _hitTest: function (cameraPt) { let node = this.node; let size = node.getContentSize(), w = size.width, - h = size.height; - node.getWorldMatrix(_mat4_temp); + h = size.height, + testPt = _vec2_temp; + + node._updateWorldMatrix(); + math.mat4.invert(_mat4_temp, node._worldMatrix); + math.vec2.transformMat4(testPt, cameraPt, _mat4_temp); + testPt.x += node._anchorPoint.x * w; + testPt.y += node._anchorPoint.y * h; if (this.type === MaskType.RECT || this.type === MaskType.IMAGE_STENCIL) { - _rect_temp.x = -node.anchorX * w, - _rect_temp.y = -node.anchorX * h; - _rect_temp.width = w; - _rect_temp.height = h; - _rect_temp.transformMat4(_rect_temp, _mat4_temp); - - let left = point.x - _rect_temp.x, - right = _rect_temp.x + _rect_temp.width - point.x, - bottom = point.y - _rect_temp.y, - top = _rect_temp.y + _rect_temp.height - point.y; - - return left >= 0 && right >= 0 && top >= 0 && bottom >= 0; + return testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h; } else if (this.type === MaskType.ELLIPSE) { let rx = w / 2, ry = h / 2; - let px = point.x - _mat4_temp.m12, py = point.y - _mat4_temp.m13; + let px = testPt.x - 0.5 * w, py = testPt.y - 0.5 * h; return px * px / (rx * rx) + py * py / (ry * ry) < 1; } }, diff --git a/cocos2d/core/components/CCSprite.js b/cocos2d/core/components/CCSprite.js index 1996a4cc9c..18f36f9238 100644 --- a/cocos2d/core/components/CCSprite.js +++ b/cocos2d/core/components/CCSprite.js @@ -211,10 +211,6 @@ var Sprite = cc.Class({ } } this._spriteFrame = value; - if ((this._material && this._material._texture) !== (value && value._texture)) { - // disable render flow util texture is loaded - this.markForRender(false); - } // render & update render data flag will be triggered while applying new sprite frame this.markForUpdateRenderData(false); this._applySpriteFrame(lastSprite); @@ -441,6 +437,10 @@ var Sprite = cc.Class({ if (!this._spriteFrame || !this._spriteFrame.textureLoaded()) { // Do not render when sprite frame is not ready this.disableRender(); + if (this._spriteFrame) { + this._spriteFrame.once('load', this._onTextureLoaded, this); + this._spriteFrame.ensureLoadTexture(); + } } this._updateAssembler(); @@ -587,6 +587,11 @@ var Sprite = cc.Class({ } var spriteFrame = this._spriteFrame; + if (!spriteFrame || (this._material && this._material._texture) !== (spriteFrame && spriteFrame._texture)) { + // disable render flow until texture is loaded + this.markForRender(false); + } + if (spriteFrame) { if (!oldFrame || spriteFrame._texture !== oldFrame._texture) { if (spriteFrame.textureLoaded()) { diff --git a/cocos2d/core/components/editbox/CCEditBox.js b/cocos2d/core/components/editbox/CCEditBox.js index ed3c43e55b..0238478c51 100644 --- a/cocos2d/core/components/editbox/CCEditBox.js +++ b/cocos2d/core/components/editbox/CCEditBox.js @@ -469,8 +469,11 @@ let EditBox = cc.Class({ }, _updateString (text) { - let placeholderLabel = this._placeholderLabel; let textLabel = this._textLabel; + // Not inited yet + if (!textLabel) { + return; + } let displayText = text; if (displayText) { @@ -479,6 +482,7 @@ let EditBox = cc.Class({ textLabel.string = displayText; this._impl.setString(text); + this._showLabels(); }, _updateLabelStringStyle (text, ignorePassword) { diff --git a/cocos2d/core/event-manager/CCEvent.js b/cocos2d/core/event-manager/CCEvent.js index 72b67a75f0..feb282dafa 100644 --- a/cocos2d/core/event-manager/CCEvent.js +++ b/cocos2d/core/event-manager/CCEvent.js @@ -103,7 +103,7 @@ proto.setLocation = function (x, y) { * @return {Vec2} location */ proto.getLocation = function () { - return {x: this._x, y: this._y}; + return cc.v2(this._x, this._y); }; /** @@ -113,7 +113,7 @@ proto.getLocation = function () { * @return {Vec2} */ proto.getLocationInView = function() { - return {x: this._x, y: cc.view._designResolutionSize.height - this._y}; + return cc.v2(this._x, cc.view._designResolutionSize.height - this._y); }; proto._setPrevCursor = function (x, y) { @@ -128,7 +128,7 @@ proto._setPrevCursor = function (x, y) { * @return {Vec2} */ proto.getPreviousLocation = function () { - return {x: this._prevX, y: this._prevY}; + return cc.v2(this._prevX, this._prevY); }; /** @@ -138,7 +138,7 @@ proto.getPreviousLocation = function () { * @return {Vec2} */ proto.getDelta = function () { - return {x: this._x - this._prevX, y: this._y - this._prevY}; + return cc.v2(this._x - this._prevX, this._y - this._prevY); }; /** diff --git a/cocos2d/core/event-manager/CCEventListener.js b/cocos2d/core/event-manager/CCEventListener.js index 00bd646b35..cd1ba37b1c 100644 --- a/cocos2d/core/event-manager/CCEventListener.js +++ b/cocos2d/core/event-manager/CCEventListener.js @@ -149,7 +149,7 @@ cc.EventListener.prototype = { /* * Sets scene graph priority for this listener - * @param {_ccsg.Node|Node} node + * @param {cc.Node} node * @private */ _setSceneGraphPriority: function (node) { @@ -159,7 +159,7 @@ cc.EventListener.prototype = { /* * Gets scene graph priority of this listener - * @returns {_ccsg.Node|cc.Node} if it's a fixed priority listener, non-null for scene graph priority listener + * @returns {cc.Node} if it's a fixed priority listener, non-null for scene graph priority listener * @private */ _getSceneGraphPriority: function () { diff --git a/cocos2d/core/event-manager/CCEventManager.js b/cocos2d/core/event-manager/CCEventManager.js index 501e3896df..f7ee2fc2f7 100644 --- a/cocos2d/core/event-manager/CCEventManager.js +++ b/cocos2d/core/event-manager/CCEventManager.js @@ -146,7 +146,7 @@ var eventManager = { * @param {Boolean} [recursive=false] */ pauseTarget: function (node, recursive) { - if (!(node instanceof cc._BaseNode || node instanceof _ccsg.Node)) { + if (!(node instanceof cc._BaseNode)) { cc.warnID(3506); return; } @@ -170,7 +170,7 @@ var eventManager = { * @param {Boolean} [recursive=false] */ resumeTarget: function (node, recursive) { - if (!(node instanceof cc._BaseNode || node instanceof _ccsg.Node)) { + if (!(node instanceof cc._BaseNode)) { cc.warnID(3506); return; } @@ -732,7 +732,7 @@ var eventManager = { */ addListener: function (listener, nodeOrPriority) { cc.assertID(listener && nodeOrPriority, 3503); - if (!(cc.js.isNumber(nodeOrPriority) || nodeOrPriority instanceof cc._BaseNode || nodeOrPriority instanceof _ccsg.Node)) { + if (!(cc.js.isNumber(nodeOrPriority) || nodeOrPriority instanceof cc._BaseNode)) { cc.warnID(3506); return; } @@ -902,7 +902,7 @@ var eventManager = { */ removeListeners: function (listenerType, recursive) { var i, _t = this; - if (!(cc.js.isNumber(listenerType) || listenerType instanceof cc._BaseNode || listenerType instanceof _ccsg.Node)) { + if (!(cc.js.isNumber(listenerType) || listenerType instanceof cc._BaseNode)) { cc.warnID(3506); return; } diff --git a/cocos2d/core/event/event-target.js b/cocos2d/core/event/event-target.js index cc419f6f72..888594f87e 100644 --- a/cocos2d/core/event/event-target.js +++ b/cocos2d/core/event/event-target.js @@ -81,7 +81,11 @@ var proto = EventTarget.prototype; * @param {String} type - A string representing the event type to listen for. * @param {Function} callback - The callback that will be invoked when the event is dispatched. * The callback is ignored if it is a duplicate (the callbacks are unique). - * @param {Event} callback.event event + * @param {Event} callback.arg1 arg1 + * @param {Event} callback.arg2 arg2 + * @param {Event} callback.arg3 arg3 + * @param {Event} callback.arg4 arg4 + * @param {Event} callback.arg5 arg5 * @param {Object} [target] - The target (this object) to invoke the callback, can be null * @return {Function} - Just returns the incoming callback so you can save the anonymous function easier. * @typescript @@ -165,7 +169,11 @@ proto.targetOff = proto.removeAll; * @param {String} type - A string representing the event type to listen for. * @param {Function} callback - The callback that will be invoked when the event is dispatched. * The callback is ignored if it is a duplicate (the callbacks are unique). - * @param {Event} callback.event event + * @param {Event} callback.arg1 arg1 + * @param {Event} callback.arg2 arg2 + * @param {Event} callback.arg3 arg3 + * @param {Event} callback.arg4 arg4 + * @param {Event} callback.arg5 arg5 * @param {Object} [target] - The target (this object) to invoke the callback, can be null * @example * eventTarget.once('fire', function (event) { @@ -177,10 +185,10 @@ proto.once = function (type, callback, target) { var hasOnceListener = this.hasEventListener(eventType_hasOnceListener, callback, target); if (!hasOnceListener) { var self = this; - var onceWrapper = function (event) { + var onceWrapper = function (arg1, arg2, arg3, arg4, arg5) { self.off(type, onceWrapper, target); self.remove(eventType_hasOnceListener, callback, target); - callback.call(this, event); + callback.call(this, arg1, arg2, arg3, arg4, arg5); }; this.on(type, onceWrapper, target); this.add(eventType_hasOnceListener, callback, target); diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js index aabe5b776e..d51197fd7c 100644 --- a/cocos2d/core/load-pipeline/CCLoader.js +++ b/cocos2d/core/load-pipeline/CCLoader.js @@ -656,7 +656,7 @@ proto.loadResDir = function (url, type, progressCallback, completeCallback) { } } } - completeCallback(errors, assetRes, urlRes); + completeCallback && completeCallback(errors, assetRes, urlRes); }, urls); }; diff --git a/cocos2d/core/load-pipeline/downloader.js b/cocos2d/core/load-pipeline/downloader.js index bd979f0825..6fa1b65c9b 100644 --- a/cocos2d/core/load-pipeline/downloader.js +++ b/cocos2d/core/load-pipeline/downloader.js @@ -101,6 +101,7 @@ function downloadImage (item, callback, isCrossOrigin, img) { img.removeEventListener('load', loadCallback); img.removeEventListener('error', errorCallback); + img.id = item.id; callback(null, img); } function errorCallback () { diff --git a/cocos2d/core/load-pipeline/loader.js b/cocos2d/core/load-pipeline/loader.js index 30be4c804c..1b5ef17d95 100644 --- a/cocos2d/core/load-pipeline/loader.js +++ b/cocos2d/core/load-pipeline/loader.js @@ -24,17 +24,17 @@ THE SOFTWARE. ****************************************************************************/ -var js = require('../platform/js'); -var sys = require('../platform/CCSys'); -var Pipeline = require('./pipeline'); -var Texture2D = require('../assets/CCTexture2D'); -var loadUuid = require('./uuid-loader'); +const js = require('../platform/js'); +const plistParser = require('../platform/CCSAXParser').plistParser; +const Pipeline = require('./pipeline'); +const Texture2D = require('../assets/CCTexture2D'); +const loadUuid = require('./uuid-loader'); -function loadNothing (item, callback) { +function loadNothing () { return null; } -function loadJSON (item, callback) { +function loadJSON (item) { if (typeof item.content !== 'string') { return new Error('JSON Loader: Input item doesn\'t contain string content'); } @@ -48,7 +48,7 @@ function loadJSON (item, callback) { } } -function loadImage (item, callback) { +function loadImage (item) { var loadByDeserializedAsset = (item._owner instanceof cc.Asset); if (loadByDeserializedAsset) { // already has cc.Asset @@ -58,7 +58,7 @@ function loadImage (item, callback) { var image = item.content; if (!CC_WECHATGAME && !CC_QQPLAY && !(image instanceof Image)) { return new Error('Image Loader: Input item doesn\'t contain Image content'); - } + } // load cc.Texture2D var rawUrl = item.rawUrl; @@ -85,11 +85,11 @@ function loadAudioAsAsset (item, callback) { return audioClip; } -function loadPlist (item, callback) { +function loadPlist (item) { if (typeof item.content !== 'string') { return new Error('Plist Loader: Input item doesn\'t contain string content'); } - var result = cc.plistParser.parse(item.content); + var result = plistParser.parse(item.content); if (result) { return result; } @@ -98,7 +98,7 @@ function loadPlist (item, callback) { } } -function loadBinary (item, callback) { +function loadBinary (item) { // Invoke custom handle if (item.load) { return item.load(item.content); diff --git a/cocos2d/core/load-pipeline/text-downloader.js b/cocos2d/core/load-pipeline/text-downloader.js index 79af076cbc..deb9970f35 100644 --- a/cocos2d/core/load-pipeline/text-downloader.js +++ b/cocos2d/core/load-pipeline/text-downloader.js @@ -23,10 +23,8 @@ THE SOFTWARE. ****************************************************************************/ -var sys = require('../platform/CCSys'); - if (CC_JSB) { - module.exports = function (item, callback) { + module.exports = function (item) { var url = item.url; var result = jsb.fileUtils.getStringFromFile(url); @@ -46,8 +44,7 @@ else { url = urlAppendTimestamp(url); var xhr = cc.loader.getXMLHttpRequest(), - errInfo = 'Load text file failed: ' + url, - navigator = window.navigator; + errInfo = 'Load text file failed: ' + url; xhr.open('GET', url, true); if (xhr.overrideMimeType) xhr.overrideMimeType('text\/plain; charset=utf-8'); xhr.onload = function () { diff --git a/cocos2d/core/physics/CCRigidBody.js b/cocos2d/core/physics/CCRigidBody.js index db023932e0..da71792b99 100644 --- a/cocos2d/core/physics/CCRigidBody.js +++ b/cocos2d/core/physics/CCRigidBody.js @@ -65,7 +65,7 @@ var RigidBody = cc.Class({ return this._enabled; }, set: function () { - cc.warnID('8200'); + cc.warnID(8200); }, visible: false, override: true @@ -776,7 +776,7 @@ var RigidBody = cc.Class({ b2body.SetLinearVelocity(temp); } else { - b2body.SetTransform(temp, b2body.GetAngle()); + b2body.SetTransformVec(temp, b2body.GetAngle()); } }, /** @@ -802,7 +802,7 @@ var RigidBody = cc.Class({ b2body.SetAngularVelocity((rotation - b2Rotation)*timeStep); } else { - b2body.SetTransform(b2body.GetPosition(), rotation); + b2body.SetTransformVec(b2body.GetPosition(), rotation); } }, diff --git a/cocos2d/core/physics/platform/CCPhysicsDebugDraw.js b/cocos2d/core/physics/platform/CCPhysicsDebugDraw.js index b35bff845b..19bf79397b 100644 --- a/cocos2d/core/physics/platform/CCPhysicsDebugDraw.js +++ b/cocos2d/core/physics/platform/CCPhysicsDebugDraw.js @@ -27,6 +27,9 @@ const PTM_RATIO = require('../CCPhysicsTypes').PTM_RATIO; let _tmp_vec2 = cc.v2(); +let GREEN_COLOR = cc.Color.GREEN; +let RED_COLOR = cc.Color.RED; + function PhysicsDebugDraw (drawer) { b2.Draw.call(this); this._drawer = drawer; @@ -101,6 +104,34 @@ cc.js.mixin(PhysicsDebugDraw.prototype, { drawer.stroke(); }, + DrawTransform (xf) { + var drawer = this._drawer; + + drawer.strokeColor = RED_COLOR; + + _tmp_vec2.x = _tmp_vec2.y = 0; + b2.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2); + drawer.moveTo(_tmp_vec2.x * PTM_RATIO, _tmp_vec2.y * PTM_RATIO); + + _tmp_vec2.x = 1; _tmp_vec2.y = 0; + b2.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2); + drawer.lineTo(_tmp_vec2.x * PTM_RATIO, _tmp_vec2.y * PTM_RATIO); + + drawer.stroke(); + + drawer.strokeColor = GREEN_COLOR; + + _tmp_vec2.x = _tmp_vec2.y = 0; + b2.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2); + drawer.moveTo(_tmp_vec2.x * PTM_RATIO, _tmp_vec2.y * PTM_RATIO); + + _tmp_vec2.x = 0; _tmp_vec2.y = 1; + b2.Transform.MulXV(xf, _tmp_vec2, _tmp_vec2); + drawer.lineTo(_tmp_vec2.x * PTM_RATIO, _tmp_vec2.y * PTM_RATIO); + + drawer.stroke(); + }, + DrawPoint (center, radius, color) { }, diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 25650c58a3..d3d6486b7a 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -151,6 +151,9 @@ function defineProp (cls, className, propName, val, es6) { for (var i = 0; i < attrs.length; i++) { var attr = attrs[i]; Attr.attr(cls, propName, attr); + if (attr['serializable'] === false) { + pushUnique(cls.__values__, propName); + } // register callback if (attr._onAfterProp) { onAfterProp.push(attr._onAfterProp); @@ -184,11 +187,9 @@ function defineGetSet (cls, name, propName, val, es6) { } attrs.length = 0; - const ForceSerializable = false; - if (!ForceSerializable) { - Attr.setClassAttr(cls, propName, 'serializable', false); - } - if (ForceSerializable || CC_DEV) { + Attr.setClassAttr(cls, propName, 'serializable', false); + + if (CC_DEV) { // 不论是否 visible 都要添加到 props,否则 asset watcher 不能正常工作 appendProp(cls, propName); } @@ -393,14 +394,14 @@ function normalizeClassName_DEV (className) { return DefaultName; } -function getNewValueTypeCode (value) { +function getNewValueTypeCodeJit (value) { var clsName = js.getClassName(value); var type = value.constructor; var res = 'new ' + clsName + '('; for (var i = 0; i < type.__props__.length; i++) { var prop = type.__props__[i]; var propVal = value[prop]; - if (typeof propVal === 'object') { + if (CC_DEV && typeof propVal === 'object') { cc.errorID(3641, clsName); return 'new ' + clsName + '()'; } @@ -412,23 +413,7 @@ function getNewValueTypeCode (value) { return res + ')'; } -function getNewValueType (value) { - var clsName = js.getClassName(value); - var type = value.constructor; - var res = new type(); - for (var i = 0; i < type.__props__.length; i++) { - var prop = type.__props__[i]; - var propVal = value[prop]; - if (typeof propVal === 'object') { - cc.errorID(3641, clsName); - return res; - } - res[prop] = propVal; - } - return res; -} - -// TODO - move escapeForJS, IDENTIFIER_RE, getNewValueTypeCode to misc.js or a new source file +// TODO - move escapeForJS, IDENTIFIER_RE, getNewValueTypeCodeJit to misc.js or a new source file // convert a normal string including newlines, quotes and unicode characters into a string literal // ready to use in JavaScript source @@ -459,7 +444,7 @@ function getInitPropsJit (attrs, propList) { var def = attrs[attrKey]; if (typeof def === 'object' && def) { if (def instanceof cc.ValueType) { - expression = getNewValueTypeCode(def); + expression = getNewValueTypeCodeJit(def); } else if (Array.isArray(def)) { expression = '[]'; @@ -505,53 +490,65 @@ function getInitPropsJit (attrs, propList) { } function getInitProps (attrs, propList) { - // functions for generated code + var advancedProps = []; + var advancedValues = []; + var simpleProps = []; + var simpleValues = []; - function func () { - var F = []; - - for (var i = 0; i < propList.length; i++) { - var prop = propList[i]; - var attrKey = prop + DELIMETER + 'default'; - if (attrKey in attrs) { // getter does not have default - var expression; - var def = attrs[attrKey]; - if (typeof def === 'object' && def) { - if (def instanceof cc.ValueType) { - expression = getNewValueType(def); - } - else if (Array.isArray(def)) { - expression = []; - } - else { - expression = {}; - } + for (var i = 0; i < propList.length; ++i) { + var prop = propList[i]; + var attrKey = prop + DELIMETER + 'default'; + if (attrKey in attrs) { // getter does not have default + var def = attrs[attrKey]; + if ((typeof def === 'object' && def) || typeof def === 'function') { + advancedProps.push(prop); + advancedValues.push(def); + } + else { + // number, boolean, null, undefined, string + simpleProps.push(prop); + simpleValues.push(def); + } + } + } + + return function () { + for (let i = 0; i < simpleProps.length; ++i) { + this[simpleProps[i]] = simpleValues[i]; + } + for (let i = 0; i < advancedProps.length; i++) { + let prop = advancedProps[i]; + var expression; + var def = advancedValues[i]; + if (typeof def === 'object') { + if (def instanceof cc.ValueType) { + expression = def.clone(); } - else if (typeof def === 'function') { - var index = F.length; - F.push(def); - expression = F[index](); - if (CC_EDITOR) { - try { - this[prop] = expression; - } - catch(err) { - cc._throw(e); - } + else if (Array.isArray(def)) { + expression = []; + } + else { + expression = {}; + } + } + else { + // def is function + if (CC_EDITOR) { + try { + expression = def(); + } + catch (err) { + cc._throw(e); continue; } } else { - // number, boolean, null, undefined, string - expression = def; + expression = def(); } - - this[prop] = expression; } + this[prop] = expression; } - } - - return func; + }; } // simple test variable name @@ -590,7 +587,7 @@ var _createCtor = CC_SUPPORT_JIT ? function (ctors, baseClass, className, option // call user constructors var ctorLen = ctors.length; if (ctorLen > 0) { - var useTryCatch = ! (className && className.startsWith('cc.')); + var useTryCatch = CC_DEV && ! (className && className.startsWith('cc.')); if (useTryCatch) { body += 'try{\n'; } @@ -615,46 +612,61 @@ var _createCtor = CC_SUPPORT_JIT ? function (ctors, baseClass, className, option return Function(body)(); } : function (ctors, baseClass, className, options) { var superCallBounded = baseClass && boundSuperCalls(baseClass, options, className); + var ctorLen = ctors.length; - return function CCClass () { + var Class; + + if (ctorLen > 0) { if (superCallBounded) { - this._super=null; - } - - this.__initProps__(CCClass); - - // call user constructors - var ctorLen = ctors.length; - var cs = CCClass.__ctors__; - if (ctorLen > 0) { - var useTryCatch = ! (className && className.startsWith('cc.')); - if (useTryCatch) { - try { - if (ctorLen === 1) { - cs[0].apply(this, arguments); - } - else { - for (let i = 0; i < ctorLen; i++) { - cs[i].apply(this, arguments); - } - } - } - catch(e) { - cc._throw(e); - } + if (ctorLen === 2) { + // User Component + Class = function () { + this._super = null; + this.__initProps__(Class); + ctors[0].apply(this, arguments); + ctors[1].apply(this, arguments); + }; } else { - if (ctorLen === 1) { - cs[0].apply(this, arguments); - } - else { - for (let i = 0; i < ctorLen; i++) { - cs[i].apply(this, arguments); + Class = function () { + this._super = null; + this.__initProps__(Class); + for (let i = 0; i < ctors.length; ++i) { + ctors[i].apply(this, arguments); } - } + }; } } - }; + else { + if (ctorLen === 3) { + // Node + Class = function () { + this.__initProps__(Class); + ctors[0].apply(this, arguments); + ctors[1].apply(this, arguments); + ctors[2].apply(this, arguments); + }; + } + else { + Class = function () { + this.__initProps__(Class); + var ctors = Class.__ctors__; + for (let i = 0; i < ctors.length; ++i) { + ctors[i].apply(this, arguments); + } + }; + } + } + } + else { + Class = function () { + if (superCallBounded) { + this._super = null; + } + this.__initProps__(Class); + }; + } + return Class; }; function _validateCtor_DEV (ctor, baseClass, className, options) { @@ -817,6 +829,11 @@ function declareProperties (cls, className, properties, baseClass, mixins, es6) } } } + + var attrs = Attr.getClassAttrs(cls); + cls.__values__ = cls.__props__.filter(function (prop) { + return attrs[prop + DELIMETER + 'serializable'] !== false; + }); } /** @@ -943,7 +960,7 @@ function CCClass (options) { } else { deferredInitializer.push({cls: cls, props: properties, mixins: mixins}); - cls.__props__ = null; + cls.__props__ = cls.__values__ = null; } } else { @@ -1019,7 +1036,7 @@ CCClass._isCCClass = function (constructor) { CCClass._fastDefine = function (className, constructor, serializableFields) { js.setClassName(className, constructor); //constructor.__ctors__ = constructor.__ctors__ || null; - var props = constructor.__props__ = Object.keys(serializableFields); + var props = constructor.__props__ = constructor.__values__ = Object.keys(serializableFields); var attrProtos = Attr.getClassAttrsProto(constructor); for (var i = 0; i < props.length; i++) { var key = props[i]; @@ -1229,7 +1246,7 @@ module.exports = { return Array.isArray(defaultVal); }, fastDefine: CCClass._fastDefine, - getNewValueTypeCode, + getNewValueTypeCode: CC_SUPPORT_JIT && getNewValueTypeCodeJit, IDENTIFIER_RE, escapeForJS, getDefault: getDefault diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js index 90fcbe2623..55121b8fbd 100644 --- a/cocos2d/core/platform/CCMacro.js +++ b/cocos2d/core/platform/CCMacro.js @@ -192,8 +192,8 @@ cc.macro = { * This formula prevents artifacts by using 99% of the texture.
* The "correct" way to prevent artifacts is by expand the texture's border with the same color by 1 pixel
*
- * Affected nodes:
- * - _ccsg.TMXLayer
+ * Affected component:
+ * - cc.TMXLayer
*
* Enabled by default. To disabled set it to 0.
* To modify it, in Web engine please refer to CCMacro.js, in JSB please refer to CCConfig.h @@ -325,6 +325,24 @@ cc.macro = { * @default false */ ENABLE_CULLING: false, + + /** + * !#en + * Whether or not clear dom Image object cache after uploading to gl texture. + * Concretely, we are setting image.src to empty string to release the cache. + * Normally you don't need to enable this option, because on web the Image object doesn't consume too much memory. + * But on Wechat Game platform, the current version cache decoded data in Image object, which has high memory usage. + * So we enabled this option by default on Wechat, so that we can release Image cache immediately after uploaded to GPU. + * !#zh + * 是否在将贴图上传至 GPU 之后删除 DOM Image 缓存。 + * 具体来说,我们通过设置 image.src 为空字符串来释放这部分内存。 + * 正常情况下,你不需要开启这个选项,因为在 web 平台,Image 对象所占用的内存很小。 + * 但是在微信小游戏平台的当前版本,Image 对象会缓存解码后的图片数据,它所占用的内存空间很大。 + * 所以我们在微信平台默认开启了这个选项,这样我们就可以在上传 GL 贴图之后立即释放 Image 对象的内存,避免过高的内存占用。 + * @property {Boolean} CLEANUP_IMAGE_CACHE + * @default false + */ + CLEANUP_IMAGE_CACHE: false, }; js.getset(cc.macro, 'ENABLE_3D', function () { diff --git a/cocos2d/core/platform/CCObject.js b/cocos2d/core/platform/CCObject.js index 285750db15..37eb6dddbc 100644 --- a/cocos2d/core/platform/CCObject.js +++ b/cocos2d/core/platform/CCObject.js @@ -349,9 +349,15 @@ if (CC_EDITOR || CC_TEST) { } function compileDestruct (obj, ctor) { + var shouldSkipId = obj instanceof cc._BaseNode || obj instanceof cc.Component; + var idToSkip = shouldSkipId ? '_id' : null; + var key, propsToReset = {}; for (key in obj) { if (obj.hasOwnProperty(key)) { + if (key === idToSkip) { + continue; + } switch (typeof obj[key]) { case 'string': propsToReset[key] = ''; @@ -371,6 +377,9 @@ function compileDestruct (obj, ctor) { key = propList[i]; var attrKey = key + cc.Class.Attr.DELIMETER + 'default'; if (attrKey in attrs) { + if (shouldSkipId && key === '_id') { + continue; + } switch (typeof attrs[attrKey]) { case 'string': propsToReset[key] = ''; @@ -386,15 +395,11 @@ function compileDestruct (obj, ctor) { } } } - // compile code - var skipId = obj instanceof cc._BaseNode || obj instanceof cc.Component; if (CC_SUPPORT_JIT) { + // compile code var func = ''; for (key in propsToReset) { - if (skipId && key === '_id') { - continue; - } var statement; if (CCClass.IDENTIFIER_RE.test(key)) { statement = 'o.' + key + '='; @@ -412,10 +417,7 @@ function compileDestruct (obj, ctor) { } else { return function (o) { - for (key in propsToReset) { - if (skipId && key === '_id') { - continue; - } + for (var key in propsToReset) { o[key] = propsToReset[key]; } }; diff --git a/cocos2d/core/platform/CCSAXParser.js b/cocos2d/core/platform/CCSAXParser.js index cdd5d9e1fd..1273193064 100644 --- a/cocos2d/core/platform/CCSAXParser.js +++ b/cocos2d/core/platform/CCSAXParser.js @@ -32,7 +32,7 @@ var js = require('../platform/js'); * @class saxParser */ cc.SAXParser = function () { - if (window.DOMParser) { + if (!(CC_EDITOR && Editor.isMainProcess) && window.DOMParser) { this._isSupportDOMParser = true; this._parser = new DOMParser(); } else { @@ -164,3 +164,8 @@ cc.saxParser = new cc.SAXParser(); * A Plist Parser */ cc.plistParser = new cc.PlistParser(); + +module.exports = { + saxParser: cc.saxParser, + plistParser: cc.plistParser +} diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index 1bf04bbd2e..1baf4b8c4f 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -30,10 +30,6 @@ const js = require('../platform/js'); const renderer = require('../renderer'); require('../platform/CCClass'); -function isWeChatGame () { - return window['wx']; -} - var __BrowserGetter = { init: function(){ if (!CC_WECHATGAME && !CC_QQPLAY) { @@ -77,13 +73,6 @@ if (CC_QQPLAY) { switch (__BrowserGetter.adaptationType) { case cc.sys.BROWSER_TYPE_SAFARI: __BrowserGetter.meta["minimal-ui"] = "true"; - __BrowserGetter.availWidth = function(frame){ - return frame.clientWidth; - }; - __BrowserGetter.availHeight = function(frame){ - return frame.clientHeight; - }; - break; case cc.sys.BROWSER_TYPE_SOUGOU: case cc.sys.BROWSER_TYPE_UC: __BrowserGetter.availWidth = function(frame){ diff --git a/cocos2d/core/platform/deserialize.js b/cocos2d/core/platform/deserialize.js index 00f8f4624d..1223b531cb 100644 --- a/cocos2d/core/platform/deserialize.js +++ b/cocos2d/core/platform/deserialize.js @@ -25,7 +25,6 @@ ****************************************************************************/ var js = require('./js'); -var CCObject = require('./CCObject'); var Attr = require('./attribute'); var CCClass = require('./CCClass'); var misc = require('../utils/misc'); @@ -432,7 +431,7 @@ var _Deserializer = (function () { } }; - var compileObjectType = CC_SUPPORT_JIT ? function (sources, defaultValue, accessorToSet, propNameLiteralToSet, assumeHavePropIfIsValue, stillUseUrl) { + function compileObjectTypeJit (sources, defaultValue, accessorToSet, propNameLiteralToSet, assumeHavePropIfIsValue, stillUseUrl) { if (defaultValue instanceof cc.ValueType) { // fast case if (!assumeHavePropIfIsValue) { @@ -446,55 +445,24 @@ var _Deserializer = (function () { } else { sources.push('if(prop){'); - if (CC_EDITOR || CC_TEST) { - sources.push('s._deserializeObjField(o,prop,' + propNameLiteralToSet + ',t&&o,' + !!stillUseUrl + ');'); - } - else { - sources.push('s._deserializeObjField(o,prop,' + propNameLiteralToSet + ',null,' + !!stillUseUrl + ');'); - } + sources.push('s._deserializeObjField(o,prop,' + + propNameLiteralToSet + + ((CC_EDITOR || CC_TEST) ? ',t&&o,' : ',null,') + + !!stillUseUrl + + ');'); sources.push('}else o' + accessorToSet + '=null;'); } - } : function (s, o, t, prop, defaultValue, propName, assumeHavePropIfIsValue, stillUseUrl) { - if (defaultValue instanceof cc.ValueType) { - var ctor = defaultValue.constructor; - - if (assumeHavePropIfIsValue) { - s._deserializeTypedObject(o[propName], prop, ctor); - } - else { - if (prop) { - s._deserializeTypedObject(o[propName], prop, ctor); - } - else { - o[propName] = null; - } - } - } - else { - if (prop) { - if (CC_EDITOR || CC_TEST) { - s._deserializeObjField(o, prop, propName, t&&o, stillUseUrl); - } - else { - s._deserializeObjField(o, prop, propName, null, stillUseUrl); - } - } - else { - o[propName] = null; - } - } - }; + } var compileDeserialize = CC_SUPPORT_JIT ? function (self, klass) { var TYPE = Attr.DELIMETER + 'type'; var EDITOR_ONLY = Attr.DELIMETER + 'editorOnly'; - var SERIALIZABLE = Attr.DELIMETER + 'serializable'; var DEFAULT = Attr.DELIMETER + 'default'; var SAVE_URL_AS_ASSET = Attr.DELIMETER + 'saveUrlAsAsset'; var FORMERLY_SERIALIZED_AS = Attr.DELIMETER + 'formerlySerializedAs'; var attrs = Attr.getClassAttrs(klass); - var props = klass.__props__; + var props = klass.__values__; // self, obj, serializedData, klass, target var sources = [ 'var prop;' @@ -506,9 +474,6 @@ var _Deserializer = (function () { if ((CC_PREVIEW || (CC_EDITOR && self._ignoreEditorOnly)) && attrs[propName + EDITOR_ONLY]) { continue; // skip editor only if in preview } - if (attrs[propName + SERIALIZABLE] === false) { - continue; // skip nonSerialized - } var accessorToSet, propNameLiteralToSet; if (CCClass.IDENTIFIER_RE.test(propName)) { @@ -557,14 +522,14 @@ var _Deserializer = (function () { sources.push(`o${accessorToSet}=prop;`); } else { - compileObjectType(sources, defaultValue, accessorToSet, propNameLiteralToSet, true, stillUseUrl); + compileObjectTypeJit(sources, defaultValue, accessorToSet, propNameLiteralToSet, true, stillUseUrl); } } else { sources.push(`if(typeof ${CC_JSB ? '(prop)' : 'prop'}!=="object"){` + 'o' + accessorToSet + '=prop;' + '}else{'); - compileObjectType(sources, defaultValue, accessorToSet, propNameLiteralToSet, false, stillUseUrl); + compileObjectTypeJit(sources, defaultValue, accessorToSet, propNameLiteralToSet, false, stillUseUrl); sources.push('}'); } sources.push('}'); @@ -588,76 +553,126 @@ var _Deserializer = (function () { } return Function('s', 'o', 'd', 'k', 't', sources.join('')); } : function (self, klass) { - var TYPE = Attr.DELIMETER + 'type'; - var SERIALIZABLE = Attr.DELIMETER + 'serializable'; - var DEFAULT = Attr.DELIMETER + 'default'; - var SAVE_URL_AS_ASSET = Attr.DELIMETER + 'saveUrlAsAsset'; - var FORMERLY_SERIALIZED_AS = Attr.DELIMETER + 'formerlySerializedAs'; - var attrs = Attr.getClassAttrs(klass); - - var props = klass.__props__; var fastMode = misc.BUILTIN_CLASSID_RE.test(js._getClassId(klass)); + var shouldCopyId = cc.js.isChildClassOf(klass, cc._BaseNode) || cc.js.isChildClassOf(klass, cc.Component); + var shouldCopyRawData; + + var simpleProps = []; + var simplePropsToRead = simpleProps; + var advancedProps = []; + var advancedPropsToRead = advancedProps; + var advancedPropsUseUrl = []; + var advancedPropsValueType = []; + + (function () { + var props = klass.__values__; + shouldCopyRawData = props[props.length - 1] === '_$erialized'; + + var attrs = Attr.getClassAttrs(klass); + var TYPE = Attr.DELIMETER + 'type'; + var DEFAULT = Attr.DELIMETER + 'default'; + var SAVE_URL_AS_ASSET = Attr.DELIMETER + 'saveUrlAsAsset'; + var FORMERLY_SERIALIZED_AS = Attr.DELIMETER + 'formerlySerializedAs'; - return function (s, o, d, k, t) { - var prop; for (var p = 0; p < props.length; p++) { var propName = props[p]; - if (attrs[propName + SERIALIZABLE] === false) { - continue; // skip nonSerialized - } - var propNameToRead = propName; if (attrs[propName + FORMERLY_SERIALIZED_AS]) { propNameToRead = attrs[propName + FORMERLY_SERIALIZED_AS]; } + var stillUseUrl = attrs[propName + SAVE_URL_AS_ASSET]; + // function undefined object(null) string boolean number + var defaultValue = CCClass.getDefault(attrs[propName + DEFAULT]); + var isPrimitiveType = false; + if (fastMode) { + var userType = attrs[propName + TYPE]; + if (defaultValue === undefined && userType) { + isPrimitiveType = userType === cc.String || + userType === cc.Integer || + userType === cc.Float || + userType === cc.Boolean; + } + else { + var defaultType = typeof defaultValue; + isPrimitiveType = (defaultType === 'string' && !stillUseUrl) || + defaultType === 'number' || + defaultType === 'boolean'; + } + } + if (fastMode && isPrimitiveType) { + if (propNameToRead !== propName && simplePropsToRead === simpleProps) { + simplePropsToRead = simpleProps.slice(); + } + simpleProps.push(propName); + if (simplePropsToRead !== simpleProps) { + simplePropsToRead.push(propNameToRead); + } + } + else { + if (propNameToRead !== propName && advancedPropsToRead === advancedProps) { + advancedPropsToRead = advancedProps.slice(); + } + advancedProps.push(propName); + if (advancedPropsToRead !== advancedProps) { + advancedPropsToRead.push(propNameToRead); + } + advancedPropsUseUrl.push(stillUseUrl); + advancedPropsValueType.push((defaultValue instanceof cc.ValueType) && defaultValue.constructor); + } + } + })(); - prop = d[propNameToRead]; - + return function (s, o, d, k, t) { + for (let i = 0; i < simpleProps.length; ++i) { + let prop = d[simplePropsToRead[i]]; if (prop !== undefined) { - var stillUseUrl = attrs[propName + SAVE_URL_AS_ASSET]; - // function undefined object(null) string boolean number - var defaultValue = CCClass.getDefault(attrs[propName + DEFAULT]); - if (fastMode) { - var isPrimitiveType; - var userType = attrs[propName + TYPE]; - if (defaultValue === undefined && userType) { - isPrimitiveType = userType === cc.String || - userType === cc.Integer || - userType === cc.Float || - userType === cc.Boolean; + o[simpleProps[i]] = prop; + } + } + for (let i = 0; i < advancedProps.length; ++i) { + let propName = advancedProps[i]; + var prop = d[advancedPropsToRead[i]]; + if (prop === undefined) { + continue; + } + if (!fastMode && typeof prop !== 'object') { + o[propName] = prop; + } + else { + // fastMode (so will not simpleProp) or object + var valueTypeCtor = advancedPropsValueType[i]; + if (valueTypeCtor) { + if (fastMode || prop) { + s._deserializeTypedObject(o[propName], prop, valueTypeCtor); } else { - var defaultType = typeof defaultValue; - isPrimitiveType = (defaultType === 'string' && !stillUseUrl) || - defaultType === 'number' || - defaultType === 'boolean'; - } - - if (isPrimitiveType) { - o[propName] = prop; - } - else { - compileObjectType(s, o, t, prop, defaultValue, propName, true, stillUseUrl); + o[propName] = null; } } else { - if (typeof prop !== 'object') { - o[propName] = prop; + if (prop) { + s._deserializeObjField( + o, + prop, + propName, + (CC_EDITOR || CC_TEST) ? (t && o) : null, + advancedPropsUseUrl[i], + ); } else { - compileObjectType(s, o, t, prop, defaultValue, propName, false, stillUseUrl); + o[propName] = null; } } } } - if (((o instanceof cc._BaseNode) || (o instanceof cc.Component)) && d._id) { + if (shouldCopyId && d._id) { o._id = d._id; } - if (props[props.length - 1] === '_$erialized') { + if (shouldCopyRawData) { // deep copy original serialized data - o._$erialized=JSON.parse(JSON.stringify(d)); + o._$erialized = JSON.parse(JSON.stringify(d)); // parse the serialized data as primitive javascript object, so its __id__ will be dereferenced - s._deserializePrimitiveObject(o._$erialized,d); + s._deserializePrimitiveObject(o._$erialized, d); } } }; diff --git a/cocos2d/core/platform/instantiate-jit.js b/cocos2d/core/platform/instantiate-jit.js index 02f6991214..e4cf8baa92 100644 --- a/cocos2d/core/platform/instantiate-jit.js +++ b/cocos2d/core/platform/instantiate-jit.js @@ -34,7 +34,6 @@ var js = require('./js'); var CCClass = require('./CCClass'); var Compiler = require('./compiler'); -var SERIALIZABLE = Attr.DELIMETER + 'serializable'; var DEFAULT = Attr.DELIMETER + 'default'; var IDENTIFIER_RE = CCClass.IDENTIFIER_RE; var escapeForJS = CCClass.escapeForJS; @@ -317,27 +316,25 @@ proto.setValueType = function (codeArray, defaultValue, srcValue, targetExpressi }; proto.enumerateCCClass = function (codeArray, obj, klass) { - var props = klass.__props__; + var props = klass.__values__; var attrs = Attr.getClassAttrs(klass); for (var p = 0; p < props.length; p++) { var key = props[p]; - if (attrs[key + SERIALIZABLE] !== false) { - var val = obj[key]; - var defaultValue = attrs[key + DEFAULT]; - if (equalsToDefault(defaultValue, val)) { + var val = obj[key]; + var defaultValue = attrs[key + DEFAULT]; + if (equalsToDefault(defaultValue, val)) { + continue; + } + if (typeof val === 'object' && val instanceof cc.ValueType) { + defaultValue = CCClass.getDefault(defaultValue); + if (defaultValue && defaultValue.constructor === val.constructor) { + // fast case + var targetExpression = LOCAL_OBJ + getPropAccessor(key); + this.setValueType(codeArray, defaultValue, val, targetExpression); continue; } - if (typeof val === 'object' && val instanceof cc.ValueType) { - var defaultValue = CCClass.getDefault(defaultValue); - if ((defaultValue && defaultValue.constructor) === val.constructor) { - // fast case - var targetExpression = LOCAL_OBJ + getPropAccessor(key); - this.setValueType(codeArray, defaultValue, val, targetExpression); - continue; - } - } - this.setObjProp(codeArray, obj, key, val); } + this.setObjProp(codeArray, obj, key, val); } }; diff --git a/cocos2d/core/platform/instantiate.js b/cocos2d/core/platform/instantiate.js index b16d699928..61681c5fb5 100644 --- a/cocos2d/core/platform/instantiate.js +++ b/cocos2d/core/platform/instantiate.js @@ -25,9 +25,9 @@ ****************************************************************************/ var CCObject = require('./CCObject'); +var CCValueType = require('../value-types/value-type'); var Destroyed = CCObject.Flags.Destroyed; var PersistentMask = CCObject.Flags.PersistentMask; -var Attr = require('./attribute'); var _isDomNode = require('./utils').isDomNode; /** @@ -157,23 +157,26 @@ function doInstantiate (obj, parent) { return clone; } -var SERIALIZABLE = Attr.DELIMETER + 'serializable'; // @param {Object} obj - The object to instantiate, typeof must be 'object' and should not be an array. function enumerateCCClass (klass, obj, clone, parent) { - var props = klass.__props__; - var attrs = Attr.getClassAttrs(klass); + var props = klass.__values__; for (var p = 0; p < props.length; p++) { var key = props[p]; - if (attrs[key + SERIALIZABLE] !== false) { - var value = obj[key]; - if (typeof value === 'object' && value) { - clone[key] = value._iN$t || instantiateObj(value, parent); + var value = obj[key]; + if (typeof value === 'object' && value) { + var initValue = clone[key]; + if (initValue instanceof CCValueType && + initValue.constructor === value.constructor) { + initValue.set(value); } else { - clone[key] = value; + clone[key] = value._iN$t || instantiateObj(value, parent); } } + else { + clone[key] = value; + } } } @@ -217,7 +220,7 @@ function enumerateObject (obj, clone, parent) { * @return {Object|Array} - the original non-nil object, typeof must be 'object' */ function instantiateObj (obj, parent) { - if (obj instanceof cc.ValueType) { + if (obj instanceof CCValueType) { return obj.clone(); } if (obj instanceof cc.Asset) { diff --git a/cocos2d/core/renderer/render-engine.js b/cocos2d/core/renderer/render-engine.js index 44a2ea0b3c..2a83954a7a 100644 --- a/cocos2d/core/renderer/render-engine.js +++ b/cocos2d/core/renderer/render-engine.js @@ -9431,7 +9431,7 @@ function _commitTextures(gl, cur, next) { for (var i = 0; i < next.maxTextureSlot + 1; ++i) { if (cur.textureUnits[i] !== next.textureUnits[i]) { var texture = next.textureUnits[i]; - if (texture !== undefined && texture._glID !== -1) { + if (texture && texture._glID !== -1) { gl.activeTexture(gl.TEXTURE0 + i); gl.bindTexture(texture._target, texture._glID); } @@ -13389,8 +13389,11 @@ Base.prototype._draw = function _draw (item) { node.getWorldMatrix(_m4_tmp$2); device.setUniform('model', mat4.array(_float16_pool.add(), _m4_tmp$2)); - mat3.transpose(_m3_tmp$1, mat3.invert(_m3_tmp$1, mat3.fromMat4(_m3_tmp$1, _m4_tmp$2))); - device.setUniform('normalMatrix', mat3.array(_float9_pool.add(), _m3_tmp$1)); + var inverse = mat3.invert(_m3_tmp$1, mat3.fromMat4(_m3_tmp$1, _m4_tmp$2)); + if (inverse) { + mat3.transpose(_m3_tmp$1, inverse); + device.setUniform('normalMatrix', mat3.array(_float9_pool.add(), _m3_tmp$1)); + } // } // set technique uniforms diff --git a/cocos2d/core/renderer/utils/label/ttf.js b/cocos2d/core/renderer/utils/label/ttf.js index e52ba79304..5cea483c1f 100644 --- a/cocos2d/core/renderer/utils/label/ttf.js +++ b/cocos2d/core/renderer/utils/label/ttf.js @@ -26,6 +26,7 @@ const macro = require('../../../platform/CCMacro'); const utils = require('../../../utils/text-utils'); +const Component = require('../../../components/CCComponent'); const Label = require('../../../components/CCLabel'); const LabelOutline = require('../../../components/CCLabelOutline'); const Overflow = Label.Overflow; @@ -33,6 +34,7 @@ const TextUtils = utils.TextUtils; const CustomFontLoader = utils.CustomFontLoader; const WHITE = cc.Color.WHITE; +const OUTLINE_SUPPORTED = cc.js.isChildClassOf(LabelOutline, Component); let _context = null; let _canvas = null; @@ -204,7 +206,7 @@ module.exports = { } // outline - let outline = (LabelOutline instanceof cc.Component) && comp.getComponent(LabelOutline); + let outline = OUTLINE_SUPPORTED && comp.getComponent(LabelOutline); if (outline && outline.enabled) { _isOutlined = true; _margin = _outlineWidth = outline.width; @@ -262,7 +264,6 @@ module.exports = { for (let i = 0; i < _splitedStrings.length; ++i) { if (_isOutlined) { let strokeColor = _outlineColor || WHITE; - _context.globalCompositeOperation = 'source-over'; _context.strokeStyle = `rgba(${strokeColor.r}, ${strokeColor.g}, ${strokeColor.b}, ${strokeColor.a / 255})`; _context.lineWidth = _outlineWidth * 2; _context.strokeText(_splitedStrings[i], startPosition.x, startPosition.y + i * lineHeight); diff --git a/cocos2d/core/renderer/webgl/assemblers/graphics/index.js b/cocos2d/core/renderer/webgl/assemblers/graphics/index.js index f08b1eaf08..96c2b737e4 100644 --- a/cocos2d/core/renderer/webgl/assemblers/graphics/index.js +++ b/cocos2d/core/renderer/webgl/assemblers/graphics/index.js @@ -95,12 +95,9 @@ let graphicsAssembler = { nodeA = nodeColor.a / 255; let buffer = renderer.getBuffer('mesh', vfmtPosUvColor), - vertexOffset = buffer.byteOffset >> 2, - vbuf = buffer._vData, - uintbuf = buffer._uintVData; + vertexOffset = buffer.byteOffset >> 2; - let ibuf = buffer._iData, - indiceOffset = buffer.indiceOffset, + let indiceOffset = buffer.indiceOffset, vertexId = buffer.vertexOffset; let renderDatas = graphics._impl._renderDatas; @@ -110,6 +107,11 @@ let graphicsAssembler = { buffer.request(renderData.vertexCount, renderData.indiceCount); + // buffer data may be realloc, need get reference after request. + let vbuf = buffer._vData, + ibuf = buffer._iData, + uintbuf = buffer._uintVData; + for (let i = 0, l = data.length; i < l; i++) { vbuf[vertexOffset++] = data[i].x * a + data[i].y * c + tx; vbuf[vertexOffset++] = data[i].x * b + data[i].y * d + ty; diff --git a/cocos2d/core/renderer/webgl/assemblers/label/bmfont.js b/cocos2d/core/renderer/webgl/assemblers/label/bmfont.js index 82354edda5..c4b985ee3c 100644 --- a/cocos2d/core/renderer/webgl/assemblers/label/bmfont.js +++ b/cocos2d/core/renderer/webgl/assemblers/label/bmfont.js @@ -42,12 +42,14 @@ module.exports = js.addon({ tx = matrix.m12, ty = matrix.m13; let buffer = renderer._quadBuffer, - vertexOffset = buffer.byteOffset >> 2, - vbuf = buffer._vData; + vertexOffset = buffer.byteOffset >> 2; let vertexCount = renderData.vertexCount; buffer.request(vertexCount, renderData.indiceCount); + // buffer data may be realloc, need get reference after request. + let vbuf = buffer._vData; + for (let i = 0; i < vertexCount; i++) { let vert = data[i]; vbuf[vertexOffset++] = vert.x * a + vert.y * c + tx; diff --git a/cocos2d/core/renderer/webgl/assemblers/label/ttf.js b/cocos2d/core/renderer/webgl/assemblers/label/ttf.js index 028790dfbb..0d980acdc1 100644 --- a/cocos2d/core/renderer/webgl/assemblers/label/ttf.js +++ b/cocos2d/core/renderer/webgl/assemblers/label/ttf.js @@ -54,11 +54,13 @@ module.exports = js.addon({ tx = matrix.m12, ty = matrix.m13; let buffer = renderer._quadBuffer, - vertexOffset = buffer.byteOffset >> 2, - vbuf = buffer._vData; + vertexOffset = buffer.byteOffset >> 2; buffer.request(4, 6); + // buffer data may be realloc, need get reference after request. + let vbuf = buffer._vData; + // vertex for (let i = 0; i < 4; i++) { let vert = data[i]; diff --git a/cocos2d/core/renderer/webgl/assemblers/motion-streak.js b/cocos2d/core/renderer/webgl/assemblers/motion-streak.js index 0388f18a29..f3bade69cd 100644 --- a/cocos2d/core/renderer/webgl/assemblers/motion-streak.js +++ b/cocos2d/core/renderer/webgl/assemblers/motion-streak.js @@ -197,15 +197,17 @@ var motionStreakAssembler = { let buffer = renderer.getBuffer('mesh', vfmtPosUvColor), vertexOffset = buffer.byteOffset >> 2, - vbuf = buffer._vData, - uintbuf = buffer._uintVData, vertexCount = renderData.vertexCount; - let ibuf = buffer._iData, - indiceOffset = buffer.indiceOffset, + let indiceOffset = buffer.indiceOffset, vertexId = buffer.vertexOffset; buffer.request(vertexCount, renderData.indiceCount); + + // buffer data may be realloc, need get reference after request. + let vbuf = buffer._vData, + ibuf = buffer._iData, + uintbuf = buffer._uintVData; // vertex buffer let vert; diff --git a/cocos2d/core/renderer/webgl/assemblers/sprite/bar-filled.js b/cocos2d/core/renderer/webgl/assemblers/sprite/bar-filled.js index daf6654324..3e9ac50584 100644 --- a/cocos2d/core/renderer/webgl/assemblers/sprite/bar-filled.js +++ b/cocos2d/core/renderer/webgl/assemblers/sprite/bar-filled.js @@ -229,11 +229,13 @@ module.exports = { tx = matrix.m12, ty = matrix.m13; let buffer = renderer._quadBuffer, - vertexOffset = buffer.byteOffset >> 2, - vbuf = buffer._vData; + vertexOffset = buffer.byteOffset >> 2; buffer.request(4, 6); + // buffer data may be realloc, need get reference after request. + let vbuf = buffer._vData; + // vertex for (let i = 0; i < 4; i++) { let vert = data[i]; diff --git a/cocos2d/core/renderer/webgl/assemblers/sprite/index.js b/cocos2d/core/renderer/webgl/assemblers/sprite/index.js index ab8374ef77..c59947b09c 100644 --- a/cocos2d/core/renderer/webgl/assemblers/sprite/index.js +++ b/cocos2d/core/renderer/webgl/assemblers/sprite/index.js @@ -24,7 +24,6 @@ ****************************************************************************/ const Sprite = require('../../../../components/CCSprite'); -const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); const SpriteType = Sprite.Type; const FillType = Sprite.FillType; diff --git a/cocos2d/core/renderer/webgl/assemblers/sprite/mesh.js b/cocos2d/core/renderer/webgl/assemblers/sprite/mesh.js index aa92415fe3..5b10883ba2 100644 --- a/cocos2d/core/renderer/webgl/assemblers/sprite/mesh.js +++ b/cocos2d/core/renderer/webgl/assemblers/sprite/mesh.js @@ -170,15 +170,17 @@ const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); // buffer let buffer = renderer._meshBuffer, - vertexOffset = buffer.byteOffset >> 2, - vbuf = buffer._vData; + vertexOffset = buffer.byteOffset >> 2; - let ibuf = buffer._iData, - indiceOffset = buffer.indiceOffset, + let indiceOffset = buffer.indiceOffset, vertexId = buffer.vertexOffset; buffer.request(renderData.vertexCount, renderData.indiceCount); + // buffer data may be realloc, need get reference after request. + let vbuf = buffer._vData, + ibuf = buffer._iData; + for (let i = 0, l = renderData.vertexCount; i < l; i++) { let vertice = data[i]; vbuf[vertexOffset++] = vertice.x; diff --git a/cocos2d/core/renderer/webgl/assemblers/sprite/simple.js b/cocos2d/core/renderer/webgl/assemblers/sprite/simple.js index b9e8a8b809..d583fe2555 100644 --- a/cocos2d/core/renderer/webgl/assemblers/sprite/simple.js +++ b/cocos2d/core/renderer/webgl/assemblers/sprite/simple.js @@ -23,7 +23,6 @@ THE SOFTWARE. ****************************************************************************/ -const js = require('../../../../platform/js'); const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); module.exports = { @@ -59,11 +58,13 @@ module.exports = { tx = matrix.m12, ty = matrix.m13; let buffer = renderer._quadBuffer, - vertexOffset = buffer.byteOffset >> 2, - vbuf = buffer._vData; + vertexOffset = buffer.byteOffset >> 2; buffer.request(4, 6); + // buffer data may be realloc, need get reference after request. + let vbuf = buffer._vData; + // get uv from sprite frame directly let uv = sprite._spriteFrame.uv; vbuf[vertexOffset+2] = uv[0]; diff --git a/cocos2d/core/renderer/webgl/assemblers/sprite/sliced.js b/cocos2d/core/renderer/webgl/assemblers/sprite/sliced.js index 8c1e2234bd..f8cd07c266 100644 --- a/cocos2d/core/renderer/webgl/assemblers/sprite/sliced.js +++ b/cocos2d/core/renderer/webgl/assemblers/sprite/sliced.js @@ -23,9 +23,7 @@ THE SOFTWARE. ****************************************************************************/ -const Sprite = require('../../../../components/CCSprite'); const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager'); -const FillType = Sprite.FillType; module.exports = { useModel: false, @@ -73,7 +71,6 @@ module.exports = { appx = node.anchorX * width, appy = node.anchorY * height; let frame = sprite.spriteFrame; - let rect = frame._rect; let leftWidth = frame.insetLeft; let rightWidth = frame.insetRight; let topHeight = frame.insetTop; @@ -106,22 +103,23 @@ module.exports = { } let renderData = sprite._renderData, - data = renderData._data, - node = sprite.node; + data = renderData._data; let buffer = renderer._meshBuffer, vertexOffset = buffer.byteOffset >> 2, - vbuf = buffer._vData, vertexCount = renderData.vertexCount; - let ibuf = buffer._iData, - indiceOffset = buffer.indiceOffset, + let indiceOffset = buffer.indiceOffset, vertexId = buffer.vertexOffset; let uvSliced = sprite.spriteFrame.uvSliced; buffer.request(vertexCount, renderData.indiceCount); + // buffer data may be realloc, need get reference after request. + let vbuf = buffer._vData, + ibuf = buffer._iData; + for (let i = 4; i < 20; ++i) { let vert = data[i]; let uvs = uvSliced[i - 4]; diff --git a/cocos2d/core/renderer/webgl/assemblers/sprite/tiled.js b/cocos2d/core/renderer/webgl/assemblers/sprite/tiled.js index 82d4ca87a6..029272817d 100644 --- a/cocos2d/core/renderer/webgl/assemblers/sprite/tiled.js +++ b/cocos2d/core/renderer/webgl/assemblers/sprite/tiled.js @@ -143,15 +143,17 @@ module.exports = { // buffer let buffer = renderer._meshBuffer, - vertexOffset = buffer.byteOffset >> 2, - vbuf = buffer._vData; + vertexOffset = buffer.byteOffset >> 2; - let ibuf = buffer._iData, - indiceOffset = buffer.indiceOffset, + let indiceOffset = buffer.indiceOffset, vertexId = buffer.vertexOffset; buffer.request(renderData.vertexCount, renderData.indiceCount); + // buffer data may be realloc, need get reference after request. + let vbuf = buffer._vData, + ibuf = buffer._iData; + // let rect = sprite.spriteFrame._rect; let contentWidth = Math.abs(node.width); diff --git a/cocos2d/core/renderer/webgl/render-component-walker.js b/cocos2d/core/renderer/webgl/render-component-walker.js index 8e660c054a..1141e3b253 100644 --- a/cocos2d/core/renderer/webgl/render-component-walker.js +++ b/cocos2d/core/renderer/webgl/render-component-walker.js @@ -55,10 +55,10 @@ var RenderComponentWalker = function (device, renderScene) { this._device = device; this._stencilMgr = StencilManager.sharedManager; + this.walking = false; this.material = empty_material; this.cullingMask = 1; - let defaultFormat = new gfx.VertexFormat([]); this._iaPool = new RecyclePool(function () { return new InputAssembler(); }, 16); @@ -129,7 +129,7 @@ RenderComponentWalker.prototype = { indiceStart = buffer.indiceStart, indiceOffset = buffer.indiceOffset, indiceCount = indiceOffset - indiceStart; - if (!material || indiceCount <= 0) { + if (!this.walking || !material || indiceCount <= 0) { return; } @@ -208,6 +208,7 @@ RenderComponentWalker.prototype = { visit (scene) { this.reset(); + this.walking = true; RenderFlow.render(scene); @@ -217,6 +218,7 @@ RenderComponentWalker.prototype = { for (let key in _buffers) { _buffers[key].uploadData(); } + this.walking = false; }, getBuffer (type, vertextFormat) { diff --git a/cocos2d/core/renderer/webgl/stencil-manager.js b/cocos2d/core/renderer/webgl/stencil-manager.js index d5c259305b..5e0c41776c 100644 --- a/cocos2d/core/renderer/webgl/stencil-manager.js +++ b/cocos2d/core/renderer/webgl/stencil-manager.js @@ -119,6 +119,7 @@ StencilManager.prototype = { pass.setStencilFront(func, ref, stencilMask, failOp, zFailOp, zPassOp, writeMask); pass.setStencilBack(func, ref, stencilMask, failOp, zFailOp, zPassOp, writeMask); } + return effect; }, pushMask (mask) { diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js index 037b60d7b4..c4cea7418f 100644 --- a/cocos2d/core/utils/base-node.js +++ b/cocos2d/core/utils/base-node.js @@ -554,7 +554,7 @@ var BaseNode = cc.Class({ * 对子树中的所有节点,包含当前节点,会执行两次回调,prefunc 会在访问它的子节点之前调用,postfunc 会在访问所有子节点之后调用。 * 这个函数的实现不是基于递归的,而是基于栈展开递归的方式。 * 请不要在 walk 过程中对任何其他的节点嵌套执行 walk。 - * @method Walk the child tree + * @method walk * @param {Function} prefunc The callback to process node when reach the node for the first time * @param {_BaseNode} prefunc.target The current visiting node * @param {Function} postfunc The callback to process node when re-visit the node after walked all children in its sub tree diff --git a/cocos2d/core/utils/polyfill-3d.js b/cocos2d/core/utils/polyfill-3d.js index f18d01b52c..7263669444 100644 --- a/cocos2d/core/utils/polyfill-3d.js +++ b/cocos2d/core/utils/polyfill-3d.js @@ -248,6 +248,8 @@ cc._polyfill3D = module.exports = { proto.setPosition = setPosition; proto.getScale = getScale; proto.setScale = setScale; + proto.getQuat = getQuat; + proto.setQuat = setQuat; this.enabled = true; } }, diff --git a/cocos2d/core/value-types/color.js b/cocos2d/core/value-types/color.js index 7024aa4066..ead48c05c2 100644 --- a/cocos2d/core/value-types/color.js +++ b/cocos2d/core/value-types/color.js @@ -549,7 +549,7 @@ var Color = (function () { return hsv; }; - proto.fromColor = function (color) { + proto.set = function (color) { if (color._val) { this._val = color._val; } diff --git a/cocos2d/core/value-types/quat.js b/cocos2d/core/value-types/quat.js index d5015b1842..d8dc6c9f85 100644 --- a/cocos2d/core/value-types/quat.js +++ b/cocos2d/core/value-types/quat.js @@ -119,7 +119,7 @@ proto.getRoll = function () { var sinr = 2.0 * (this.w * this.x + this.y * this.z); var cosr = 1.0 - 2.0 * (this.x * this.x + this.y * this.y); return 180 * Math.atan2(sinr, cosr) / Math.PI; -} +}; proto.getPitch = function () { var sinp = 2.0 * (this.w * this.y - this.z * this.x); @@ -127,13 +127,13 @@ proto.getPitch = function () { pitch = sinp < -1 ? -1 : sinp; pitch = 180 * Math.asin(pitch) / Math.PI; return pitch; -} +}; proto.getYaw = function () { var siny = 2.0 * (this.w * this.z + this.x * this.y); var cosy = 1.0 - 2.0 * (this.y * this.y + this.z * this.z); return 180 * Math.atan2(siny, cosy) / Math.PI; -} +}; /** * !#en The convenience method to create a new {{#crossLink "Quat"}}cc.Quat{{/crossLink}}. diff --git a/cocos2d/core/value-types/rect.js b/cocos2d/core/value-types/rect.js index 84431b715a..4c620973c6 100644 --- a/cocos2d/core/value-types/rect.js +++ b/cocos2d/core/value-types/rect.js @@ -159,6 +159,13 @@ proto.lerp = function (to, ratio, out) { return out; }; +proto.set = function (source) { + this.x = source.x; + this.y = source.y; + this.width = source.width; + this.height = source.height; +}; + /** * !#en Check whether the current rectangle intersects with the given one * !#zh 当前矩形与指定矩形是否相交。 diff --git a/cocos2d/core/value-types/size.js b/cocos2d/core/value-types/size.js index 789c58aefd..55de763f09 100644 --- a/cocos2d/core/value-types/size.js +++ b/cocos2d/core/value-types/size.js @@ -135,6 +135,11 @@ proto.lerp = function (to, ratio, out) { return out; }; +proto.set = function (source) { + this.width = source.width; + this.height = source.height; +}; + /** * !#en TODO * !#zh 转换为方便阅读的字符串。 diff --git a/cocos2d/core/value-types/value-type.js b/cocos2d/core/value-types/value-type.js index 3a633003fa..3c24c351bf 100644 --- a/cocos2d/core/value-types/value-type.js +++ b/cocos2d/core/value-types/value-type.js @@ -77,6 +77,18 @@ if (CC_EDITOR) { cc.errorID('0100', js.getClassName(this) + '.lerp'); return this.clone(); }; + + /** + * !#en + * Copys all the properties from another given object to this value. + * !#zh + * 从其它对象把所有属性复制到当前对象。 + * @method set + * @param {ValueType} source - the source to copy + */ + proto.set = function (source) { + cc.errorID('0100', js.getClassName(this) + '.set'); + }; } /** diff --git a/cocos2d/core/value-types/vec2.js b/cocos2d/core/value-types/vec2.js index 3abe4c2d67..c6ba141759 100644 --- a/cocos2d/core/value-types/vec2.js +++ b/cocos2d/core/value-types/vec2.js @@ -465,7 +465,6 @@ proto.normalizeSelf = function () { return this; if (magSqr === 0.0) { - console.warn("Can't normalize zero vector"); return this; } diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js index c31dbe7b67..dded7ff5c8 100644 --- a/cocos2d/deprecated.js +++ b/cocos2d/deprecated.js @@ -366,7 +366,7 @@ if (CC_DEV) { // SCENE var ERR = '"%s" is not defined in the Scene, it is only defined in normal nodes.'; - Object.defineProperties(cc.Scene.prototype, { + CC_EDITOR || Object.defineProperties(cc.Scene.prototype, { active: { get: function () { cc.error(ERR, 'active'); diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js index 40b9e6f321..0522bb7e38 100644 --- a/cocos2d/particle/CCParticleSystem.js +++ b/cocos2d/particle/CCParticleSystem.js @@ -130,6 +130,7 @@ var properties = { this.resetSystem(); if ( !this.preview ) { this.stopSystem(); + this.disableRender(); } cc.engine.repaintInEditMode(); }, @@ -250,7 +251,7 @@ var properties = { */ texture: { get: function () { - return this._texture ? this._texture.url : ""; + return this._texture; }, set: function (value) { cc.warnID(6017); @@ -812,7 +813,9 @@ var ParticleSystem = cc.Class({ }, onLoad () { - ParticleSystem._assembler.createIA(this); + if (!this._ia) { + ParticleSystem._assembler.createIA(this); + } }, onEnable () { @@ -920,15 +923,16 @@ var ParticleSystem = cc.Class({ } self._plistFile = file.nativeUrl; - if (self._custom) { - self._initTextureWithDictionary(content); - } - else { + if (!self._custom) { self._initWithDictionary(content); } - - if (file.texture) { - self.spriteFrame = new cc.SpriteFrame(file.texture); + if (!self.spriteFrame) { + if (file.texture) { + self.spriteFrame = new cc.SpriteFrame(file.texture); + } + else if (self._custom) { + self._initTextureWithDictionary(content); + } } }); } @@ -948,13 +952,13 @@ var ParticleSystem = cc.Class({ if (textureData && textureData.length > 0) { var buffer = codec.unzipBase64AsArray(textureData, 1); if (!buffer) { - cc.logID(6010); + cc.logID(6030); return false; } var imageFormat = getImageFormatByData(buffer); if (imageFormat !== macro.ImageFormat.TIFF && imageFormat !== macro.ImageFormat.PNG) { - cc.logID(6011); + cc.logID(6031); return false; } @@ -968,7 +972,7 @@ var ParticleSystem = cc.Class({ var tex = textureUtil.cacheImage(imgPath, canvasObj); if (!tex) - cc.logID(6012); + cc.logID(6032); // TODO: Use cc.loader to load asynchronously the SpriteFrame object, avoid using textureUtil this.spriteFrame = new cc.SpriteFrame(tex); } @@ -1091,12 +1095,9 @@ var ParticleSystem = cc.Class({ return true; }, - _onTextureLoaded: function (event) { + _onTextureLoaded: function () { this._texture = this._spriteFrame.getTexture(); - // Mark render data dirty - if (this._renderData) { - this._renderData.uvDirty = true; - } + this._simulator.updateUVs(true); // Reactivate material this._activateMaterial(); }, diff --git a/cocos2d/particle/particle-simulator.js b/cocos2d/particle/particle-simulator.js index fc69d9fc65..d27816e04d 100644 --- a/cocos2d/particle/particle-simulator.js +++ b/cocos2d/particle/particle-simulator.js @@ -191,13 +191,15 @@ Simulator.prototype.emitParticle = function (pos) { } }; -Simulator.prototype.updateUVs = function (particleCount) { +Simulator.prototype.updateUVs = function (force) { + let particleCount = this.particles.length; if (this.sys._buffer && this.sys._spriteFrame) { const FLOAT_PER_PARTICLE = 4 * this.sys._vertexFormat._bytes / 4; let vbuf = this.sys._buffer._vData; let uv = this.sys._spriteFrame.uv; - for (let i = this._uvFilled; i < particleCount; i++) { + let start = force ? 0 : this._uvFilled; + for (let i = start; i < particleCount; i++) { let offset = i * FLOAT_PER_PARTICLE; vbuf[offset+2] = uv[0]; vbuf[offset+3] = uv[1]; @@ -299,11 +301,11 @@ Simulator.prototype.step = function (dt) { let buffer = psys._buffer; let particleCount = particles.length; buffer.reset(); - buffer.request(particleCount * 4, particles.length * 6); + buffer.request(particleCount * 4, particleCount * 6); // Fill up uvs if (particleCount > this._uvFilled) { - this.updateUVs(particleCount); + this.updateUVs(); } // Used to reduce memory allocation / creation within the loop diff --git a/cocos2d/tilemap/CCTMXXMLParser.js b/cocos2d/tilemap/CCTMXXMLParser.js index da70e531d1..d473e19919 100644 --- a/cocos2d/tilemap/CCTMXXMLParser.js +++ b/cocos2d/tilemap/CCTMXXMLParser.js @@ -25,9 +25,9 @@ THE SOFTWARE. ****************************************************************************/ -var codec = require('../compression/ZipUtils'); -var zlib = require('../compression/zlib.min'); -var js = require('../core/platform/js'); +const codec = require('../compression/ZipUtils'); +const zlib = require('../compression/zlib.min'); +const js = require('../core/platform/js'); require('../core/platform/CCSAXParser'); function uint8ArrayToUint32Array (uint8Arr) { @@ -168,6 +168,7 @@ cc.TMXTilesetInfo = function () { this._tileSize = cc.size(0, 0); }; + cc.TMXTilesetInfo.prototype = { constructor: cc.TMXTilesetInfo, /** @@ -345,7 +346,7 @@ cc.TMXMapInfo.prototype = { * @return {Size} */ getMapSize () { - return cc.size(this._mapSize.width,this._mapSize.height); + return cc.size(this._mapSize.width, this._mapSize.height); }, /** @@ -357,18 +358,18 @@ cc.TMXMapInfo.prototype = { this._mapSize.height = value.height; }, - _getMapWidth () { - return this._mapSize.width; - }, - _setMapWidth (width) { - this._mapSize.width = width; - }, - _getMapHeight () { - return this._mapSize.height; - }, - _setMapHeight (height) { - this._mapSize.height = height; - }, + _getMapWidth () { + return this._mapSize.width; + }, + _setMapWidth (width) { + this._mapSize.width = width; + }, + _getMapHeight () { + return this._mapSize.height; + }, + _setMapHeight (height) { + this._mapSize.height = height; + }, /** * Tiles width & height @@ -387,18 +388,18 @@ cc.TMXMapInfo.prototype = { this._tileSize.height = value.height; }, - _getTileWidth () { - return this._tileSize.width; - }, - _setTileWidth (width) { - this._tileSize.width = width; - }, - _getTileHeight () { - return this._tileSize.height; - }, - _setTileHeight (height) { - this._tileSize.height = height; - }, + _getTileWidth () { + return this._tileSize.width; + }, + _setTileWidth (width) { + this._tileSize.width = width; + }, + _getTileHeight () { + return this._tileSize.height; + }, + _setTileHeight (height) { + this._tileSize.height = height; + }, /** * Layers @@ -450,7 +451,7 @@ cc.TMXMapInfo.prototype = { this._objectGroups.push(value); }, - getAllChildren() { + getAllChildren () { return this._allChildren; }, @@ -541,7 +542,7 @@ cc.TMXMapInfo.prototype = { * @param {Object} textures * @return {Boolean} */ - initWithXML:function (tmxString, tsxMap, textures) { + initWithXML (tmxString, tsxMap, textures) { this._tilesets.length = 0; this._layers.length = 0; @@ -562,15 +563,15 @@ cc.TMXMapInfo.prototype = { return this.parseXMLString(tmxString); }, - /** + /** * Initializes parsing of an XML string, either a tmx (Map) string or tsx (Tileset) string * @param {String} xmlString * @param {Number} tilesetFirstGid * @return {Element} */ - parseXMLString:function (xmlStr, tilesetFirstGid) { - var mapXML = this._parser._parseXML(xmlStr); - var i, j; + parseXMLString (xmlStr, tilesetFirstGid) { + let mapXML = this._parser._parseXML(xmlStr); + let i, j; // PARSE let map = mapXML.documentElement; @@ -623,7 +624,7 @@ cc.TMXMapInfo.prototype = { this.setTileSize(mapSize); // The parent element is the map - var propertyArr = getPropertyList(map); + let propertyArr = getPropertyList(map); if (propertyArr) { let aPropertyDict = {}; for (i = 0; i < propertyArr.length; i++) { @@ -645,8 +646,8 @@ cc.TMXMapInfo.prototype = { // If this is an external tileset then start parsing that let tsxName = selTileset.getAttribute('source'); if (tsxName) { - var currentFirstGID = parseInt(selTileset.getAttribute('firstgid')); - var tsxXmlString = this._tsxMap[tsxName]; + let currentFirstGID = parseInt(selTileset.getAttribute('firstgid')); + let tsxXmlString = this._tsxMap[tsxName]; if (tsxXmlString) { this.parseXMLString(tsxXmlString, currentFirstGID); } @@ -667,8 +668,8 @@ cc.TMXMapInfo.prototype = { tilesetSize.height = parseFloat(selTileset.getAttribute('tileheight')); tileset._tileSize = tilesetSize; - var image = selTileset.getElementsByTagName('image')[0]; - var imagename = image.getAttribute('source'); + let image = selTileset.getElementsByTagName('image')[0]; + let imagename = image.getAttribute('source'); imagename.replace(/\\/g, '\/'); tileset.sourceImage = this._textures[imagename]; if (!tileset.sourceImage) { @@ -691,7 +692,7 @@ cc.TMXMapInfo.prototype = { for (let tIdx = 0; tIdx < tiles.length; tIdx++) { let t = tiles[tIdx]; this.parentGID = parseInt(tileset.firstGid) + parseInt(t.getAttribute('id') || 0); - var tp = getPropertyList(t); + let tp = getPropertyList(t); if (tp) { let dict = {}; for (j = 0; j < tp.length; j++) { @@ -745,7 +746,7 @@ cc.TMXMapInfo.prototype = { layer._layerSize = layerSize; let visible = selLayer.getAttribute('visible'); - layer.visible = !(visible == "0"); + layer.visible = !(visible === "0"); let opacity = selLayer.getAttribute('opacity') || 1; if (opacity) @@ -763,7 +764,7 @@ cc.TMXMapInfo.prototype = { // Unpack the tilemap data let compression = data.getAttribute('compression'); let encoding = data.getAttribute('encoding'); - if(compression && compression !== "gzip" && compression !== "zlib"){ + if (compression && compression !== "gzip" && compression !== "zlib") { cc.logID(7218); return null; } @@ -773,7 +774,7 @@ cc.TMXMapInfo.prototype = { tiles = codec.unzipBase64AsArray(nodeValue, 4); break; case 'zlib': - var inflator = new zlib.Inflate(codec.Base64.decodeAsArray(nodeValue, 1)); + let inflator = new zlib.Inflate(codec.Base64.decodeAsArray(nodeValue, 1)); tiles = uint8ArrayToUint32Array(inflator.decompress()); break; case null: @@ -795,7 +796,7 @@ cc.TMXMapInfo.prototype = { } break; default: - if(this.layerAttrs === cc.TMXLayerInfo.ATTRIB_NONE) + if (this.layerAttrs === cc.TMXLayerInfo.ATTRIB_NONE) cc.logID(7219); break; } @@ -804,7 +805,7 @@ cc.TMXMapInfo.prototype = { } // The parent element is the last layer - var layerProps = getPropertyList(selLayer); + let layerProps = getPropertyList(selLayer); if (layerProps) { let layerProp = {}; for (let j = 0; j < layerProps.length; j++) { @@ -832,13 +833,13 @@ cc.TMXMapInfo.prototype = { let color = selGroup.getAttribute('color'); if (color) - objectGroup._color = cc.hexToColor(color); + objectGroup._color.fromHEX(color); let draworder = selGroup.getAttribute('draworder'); if (draworder) objectGroup._draworder = draworder; - var groupProps = getPropertyList(selGroup); + let groupProps = getPropertyList(selGroup); if (groupProps) { let parsedProps = {}; for (let j = 0; j < groupProps.length; j++) { @@ -848,7 +849,7 @@ cc.TMXMapInfo.prototype = { objectGroup.setProperties(parsedProps); } - var objects = selGroup.getElementsByTagName('object'); + let objects = selGroup.getElementsByTagName('object'); if (objects) { for (let j = 0; j < objects.length; j++) { let selObj = objects[j]; @@ -871,7 +872,7 @@ cc.TMXMapInfo.prototype = { objectProp["rotation"] = parseFloat(selObj.getAttribute('rotation')) || 0; - var docObjProps = getPropertyList(selObj); + let docObjProps = getPropertyList(selObj); if (docObjProps) { for (let k = 0; k < docObjProps.length; k++) objectProp[docObjProps[k].getAttribute('name')] = docObjProps[k].getAttribute('value'); @@ -879,7 +880,7 @@ cc.TMXMapInfo.prototype = { // visible let visibleAttr = selObj.getAttribute('visible'); - objectProp['visible'] = ! (visibleAttr && parseInt(visibleAttr) === 0); + objectProp['visible'] = !(visibleAttr && parseInt(visibleAttr) === 0); // image let gid = selObj.getAttribute('gid'); @@ -889,26 +890,26 @@ cc.TMXMapInfo.prototype = { } // ellipse - var ellipse = selObj.getElementsByTagName('ellipse'); + let ellipse = selObj.getElementsByTagName('ellipse'); if (ellipse && ellipse.length > 0) { objectProp['type'] = cc.TiledMap.TMXObjectType.ELLIPSE; } //polygon - var polygonProps = selObj.getElementsByTagName("polygon"); - if(polygonProps && polygonProps.length > 0) { + let polygonProps = selObj.getElementsByTagName("polygon"); + if (polygonProps && polygonProps.length > 0) { objectProp['type'] = cc.TiledMap.TMXObjectType.POLYGON; let selPgPointStr = polygonProps[0].getAttribute('points'); - if(selPgPointStr) + if (selPgPointStr) objectProp["points"] = this._parsePointsString(selPgPointStr); } //polyline - var polylineProps = selObj.getElementsByTagName("polyline"); - if(polylineProps && polylineProps.length > 0) { + let polylineProps = selObj.getElementsByTagName("polyline"); + if (polylineProps && polylineProps.length > 0) { objectProp['type'] = cc.TiledMap.TMXObjectType.POLYLINE; let selPlPointStr = polylineProps[0].getAttribute('points'); - if(selPlPointStr) + if (selPlPointStr) objectProp["polylinePoints"] = this._parsePointsString(selPlPointStr); } @@ -923,15 +924,15 @@ cc.TMXMapInfo.prototype = { return objectGroup; }, - _parsePointsString(pointsString){ - if(!pointsString) + _parsePointsString (pointsString) { + if (!pointsString) return null; let points = []; let pointsStr = pointsString.split(' '); - for(let i = 0; i < pointsStr.length; i++){ + for (let i = 0; i < pointsStr.length; i++) { let selPointStr = pointsStr[i].split(','); - points.push({'x':parseFloat(selPointStr[0]), 'y':parseFloat(selPointStr[1])}); + points.push({'x': parseFloat(selPointStr[0]), 'y': parseFloat(selPointStr[1])}); } return points; }, diff --git a/cocos2d/tilemap/CCTiledLayer.js b/cocos2d/tilemap/CCTiledLayer.js index bdb35986be..04ccd2f8fd 100644 --- a/cocos2d/tilemap/CCTiledLayer.js +++ b/cocos2d/tilemap/CCTiledLayer.js @@ -131,6 +131,15 @@ let TiledLayer = cc.Class({ return ret; }, + _isInvalidPosition (x, y) { + if (x && typeof x === 'object') { + let pos = x; + y = pos.y; + x = pos.x; + } + return x >= this._layerSize.width || y >= this._layerSize.height || x < 0 || y < 0; + }, + _positionForIsoAt (x, y) { return cc.v2( this._mapTileSize.width / 2 * ( this._layerSize.width + x - y - 1), @@ -186,17 +195,17 @@ let TiledLayer = cc.Class({ * 设置给定坐标的 tile 的 gid (gid = tile 全局 id), * tile 的 GID 可以使用方法 “tileGIDAt” 来获得。
* 如果一个 tile 已经放在那个位置,那么它将被删除。 - * @method setTileGID + * @method setTileGIDAt * @param {Number} gid * @param {Vec2|Number} posOrX position or x * @param {Number} flagsOrY flags or y * @param {Number} [flags] * @example - * tiledLayer.setTileGID(1001, 10, 10, 1) + * tiledLayer.setTileGIDAt(1001, 10, 10, 1) */ setTileGIDAt (gid, posOrX, flagsOrY, flags) { if (posOrX === undefined) { - throw new Error("_ccsg.TMXLayer.setTileGID(): pos should be non-null"); + throw new Error("cc.TiledLayer.setTileGIDAt(): pos should be non-null"); } let pos; if (flags !== undefined || !(posOrX instanceof cc.Vec2)) { @@ -209,15 +218,15 @@ let TiledLayer = cc.Class({ pos.x = Math.floor(pos.x); pos.y = Math.floor(pos.y); - if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) { - throw new Error("CCTiledLayer.setTileGID(): invalid position"); + if (this._isInvalidPosition(pos)) { + throw new Error("cc.TiledLayer.setTileGIDAt(): invalid position"); } if (!this._tiles) { - cc.logID(7206); + cc.logID(7238); return; } if (gid !== 0 && gid < this._tileset.firstGid) { - cc.logID(7207, gid); + cc.logID(7239, gid); return; } @@ -258,18 +267,18 @@ let TiledLayer = cc.Class({ */ getTileGIDAt (pos, y) { if (pos === undefined) { - throw new Error("_ccsg.TMXLayer.getTileGIDAt(): pos should be non-null"); + throw new Error("cc.TiledLayer.getTileGIDAt(): pos should be non-null"); } let x = pos; if (y === undefined) { x = pos.x; y = pos.y; } - if (x >= this._layerSize.width || y >= this._layerSize.height || x < 0 || y < 0) { - throw new Error("_ccsg.TMXLayer.getTileGIDAt(): invalid position"); + if (this._isInvalidPosition(x, y)) { + throw new Error("cc.TiledLayer.getTileGIDAt(): invalid position"); } if (!this._tiles) { - cc.logID(7205); + cc.logID(7237); return null; } @@ -281,14 +290,17 @@ let TiledLayer = cc.Class({ }, getTileFlagsAt (pos, y) { - if(!pos) - throw new Error("_ccsg.TMXLayer.getTileFlagsAt(): pos should be non-null"); - if(y !== undefined) + if (!pos) { + throw new Error("TiledLayer.getTileFlagsAt: pos should be non-null"); + } + if (y !== undefined) { pos = cc.v2(pos, y); - if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) - throw new Error("_ccsg.TMXLayer.getTileFlagsAt(): invalid position"); - if(!this._tiles){ - cc.logID(7208); + } + if (this._isInvalidPosition(pos)) { + throw new Error("TiledLayer.getTileFlagsAt: invalid position"); + } + if (!this._tiles) { + cc.logID(7240); return null; } @@ -301,61 +313,64 @@ let TiledLayer = cc.Class({ /** * !#en - * Returns the tile (_ccsg.Sprite) at a given a tile coordinate.
- * The returned _ccsg.Sprite will be already added to the _ccsg.TMXLayer. Don't add it again.
- * The _ccsg.Sprite can be treated like any other _ccsg.Sprite: rotated, scaled, translated, opacity, color, etc.
- * You can remove either by calling:
- * - layer.removeChild(sprite, cleanup);
- * - or layer.removeTileAt(ccp(x,y)); + * Get the TiledTile with the tile coordinate.
+ * If there is no tile in the specified coordinate and forceCreate parameter is true,
+ * then will create a new TiledTile at the coordinate. + * The renderer will render the tile with the rotation, scale, position and color property of the TiledTile. * !#zh - * 通过指定的 tile 坐标获取对应的 tile(Sprite)。 返回的 tile(Sprite) 应是已经添加到 TMXLayer,请不要重复添加。
- * 这个 tile(Sprite) 如同其他的 Sprite 一样,可以旋转、缩放、翻转、透明化、设置颜色等。
- * 你可以通过调用以下方法来对它进行删除:
- * 1. layer.removeChild(sprite, cleanup);
- * 2. 或 layer.removeTileAt(cc.v2(x,y)); - * @method getTileAt - * @param {Vec2|Number} pos or x - * @param {Number} [y] + * 通过指定的 tile 坐标获取对应的 TiledTile。
+ * 如果指定的坐标没有 tile,并且设置了 forceCreate 那么将会在指定的坐标创建一个新的 TiledTile 。
+ * 在渲染这个 tile 的时候,将会使用 TiledTile 的节点的旋转、缩放、位移、颜色属性。
+ * @method getTiledTileAt + * @param {Integer} x + * @param {Integer} y + * @param {Boolean} forceCreate * @return {cc.TiledTile} * @example - * let title = tiledLayer.getTileAt(100, 100); - * cc.log(title); + * let tile = tiledLayer.getTiledTileAt(100, 100, true); + * cc.log(tile); */ - getTiledTileAt (pos, y) { - if (pos === undefined) { - throw new Error("_ccsg.TMXLayer.getTileAt(): pos should be non-null"); - } - let x = pos; - if (y === undefined) { - x = pos.x; - y = pos.y; - } - if (x >= this._layerSize.width || y >= this._layerSize.height || x < 0 || y < 0) { - throw new Error("_ccsg.TMXLayer.getTileAt(): invalid position"); + getTiledTileAt (x, y, forceCreate) { + if (this._isInvalidPosition(x, y)) { + throw new Error("TiledLayer.getTiledTileAt: invalid position"); } if (!this._tiles) { - cc.logID(7204); + cc.logID(7236); return null; } let index = Math.floor(x) + Math.floor(y) * this._layerSize.width; - return this._tiledTiles[index]; + let tile = this._tiledTiles[index]; + if (!tile && forceCreate) { + let node = new cc.Node(); + tile = node.addComponent(cc.TiledTile); + tile._x = x; + tile._y = y; + tile._layer = this; + tile._updateInfo(); + node.parent = this.node; + return tile; + } + return tile; }, - setTiledTileAt (pos, y, tiledTile) { - if (pos === undefined) { - throw new Error("_ccsg.TMXLayer.getTileAt(): pos should be non-null"); - } - let x = pos; - if (y === undefined) { - x = pos.x; - y = pos.y; - } - if (x >= this._layerSize.width || y >= this._layerSize.height || x < 0 || y < 0) { - throw new Error("_ccsg.TMXLayer.getTileAt(): invalid position"); + /** + * !#en + * Change tile to TiledTile at the specified coordinate. + * !#zh + * 将指定的 tile 坐标替换为指定的 TiledTile。 + * @method setTiledTileAt + * @param {Integer} x + * @param {Integer} y + * @param {cc.TiledTile} tiledTile + * @return {cc.TiledTile} + */ + setTiledTileAt (x, y, tiledTile) { + if (this._isInvalidPosition(x, y)) { + throw new Error("TiledLayer.setTiledTileAt: invalid position"); } if (!this._tiles) { - cc.logID(7204); + cc.logID(7236); return null; } diff --git a/cocos2d/tilemap/CCTiledMap.js b/cocos2d/tilemap/CCTiledMap.js index 538465fce2..d78edc6c60 100644 --- a/cocos2d/tilemap/CCTiledMap.js +++ b/cocos2d/tilemap/CCTiledMap.js @@ -459,7 +459,7 @@ let TiledMap = cc.Class({ let mapInfo = new cc.TMXMapInfo(file.tmxXmlStr, tsxMap, textures); let tilesets = mapInfo.getTilesets(); if(!tilesets || tilesets.length === 0) - cc.logID(7213); + cc.logID(7241); this._buildWithMapInfo(mapInfo); } diff --git a/cocos2d/tilemap/CCTiledTile.js b/cocos2d/tilemap/CCTiledTile.js index bf5a172535..787160bf51 100644 --- a/cocos2d/tilemap/CCTiledTile.js +++ b/cocos2d/tilemap/CCTiledTile.js @@ -28,7 +28,7 @@ * !#en TiledTile can control the specified map tile. * It will apply the node rotation, scale, translate to the map tile. * You can change the TiledTile's gid to change the map tile's style. - * !#zh TiledTile 可以单独对某一个地图快进行操作。 + * !#zh TiledTile 可以单独对某一个地图块进行操作。 * 他会将节点的旋转,缩放,平移操作应用在这个地图块上,并可以通过更换当前地图块的 gid 来更换地图块的显示样式。 * @class TiledTile * @extends Component @@ -61,10 +61,15 @@ let TiledTile = cc.Class({ }, set (value) { if (value === this._x) return; + if (this._layer && this._layer._isInvalidPosition(value, this._y)) { + cc.warn(`Invalid x, the valid value is between [%s] ~ [%s]`, 0, this._layer._layerSize.width); + return; + } this._resetTile(); this._x = value; this._updateInfo(); - } + }, + type: cc.Integer }, /** @@ -79,10 +84,15 @@ let TiledTile = cc.Class({ }, set (value) { if (value === this._y) return; + if (this._layer && this._layer._isInvalidPosition(this._x, value)) { + cc.warn(`Invalid y, the valid value is between [%s] ~ [%s]`, 0, this._layer._layerSize.height); + return; + } this._resetTile(); this._y = value; this._updateInfo(); - } + }, + type: cc.Integer }, /** @@ -97,14 +107,14 @@ let TiledTile = cc.Class({ }, set (value) { this._gid = value; - } + }, + type: cc.Integer }, /** * !#en Specify which TiledLayer the TiledTile belong to. * !#zh 指定 TiledTile 属于哪一个 TiledLayer - * @property {TiledLayer} gid - * @default 0 + * @property {TiledLayer} layer */ layer: { type: cc.TiledLayer, @@ -121,12 +131,23 @@ let TiledTile = cc.Class({ }, onEnable () { - if (CC_EDITOR && !this._layer) { - this._layer = this.node.parent.getComponent(cc.TiledLayer); - this._updateInfo(); + if (CC_EDITOR) { + let parent = this.node.parent; + if (!this._layer && !(parent instanceof cc.Scene)) { + this._layer = parent.getComponent(cc.TiledLayer); + this._updateInfo(); + } } else if (this._layer) { - this._layer.setTiledTileAt(this._x, this._y, this); + let tile = this._layer.getTiledTileAt(this._x, this._y); + if (tile) { + if (tile !== this) { + cc.warn('There is already a TiledTile at [%s, %s]', this._x, this._x); + } + } + else { + this._layer.setTiledTileAt(this._x, this._y, this); + } } }, @@ -153,4 +174,6 @@ let TiledTile = cc.Class({ this._gid = this._layer.getTileGIDAt(x, y); this._layer.setTiledTileAt(x, y, this); }, -}); \ No newline at end of file +}); + +cc.TiledTile = module.exports = TiledTile; diff --git a/cocos2d/tilemap/tmx-layer-assembler.js b/cocos2d/tilemap/tmx-layer-assembler.js index 8e10377b68..8dd27da83a 100644 --- a/cocos2d/tilemap/tmx-layer-assembler.js +++ b/cocos2d/tilemap/tmx-layer-assembler.js @@ -65,15 +65,17 @@ let tmxAssembler = { let buffer = renderer.getBuffer('mesh', vfmtPosUvColor), vertexOffset = buffer.byteOffset >> 2, - vbuf = buffer._vData, - uintbuf = buffer._uintVData, vertexCount = renderData.vertexCount; - let ibuf = buffer._iData, - indiceOffset = buffer.indiceOffset, + let indiceOffset = buffer.indiceOffset, vertexId = buffer.vertexOffset; buffer.request(vertexCount, renderData.indiceCount); + + // buffer data may be realloc, need get reference after request. + let vbuf = buffer._vData, + ibuf = buffer._iData, + uintbuf = buffer._uintVData; for (let i = 0, l = renderData.vertexCount; i < l; i++) { let vert = data[i]; diff --git a/cocos2d/videoplayer/video-player-impl.js b/cocos2d/videoplayer/video-player-impl.js index 47338cd22d..82db656943 100644 --- a/cocos2d/videoplayer/video-player-impl.js +++ b/cocos2d/videoplayer/video-player-impl.js @@ -69,7 +69,7 @@ let VideoPlayerImpl = cc.Class({ self._dispatchEvent(VideoPlayerImpl.EventType.META_LOADED); }; cbs.ended = function () { - if (this._video !== video) return; + if (self._video !== video) return; self._playing = false; self._dispatchEvent(VideoPlayerImpl.EventType.COMPLETED); }; diff --git a/cocos2d/webview/webview-impl.js b/cocos2d/webview/webview-impl.js index 8b0f36934e..daaedb1d2e 100644 --- a/cocos2d/webview/webview-impl.js +++ b/cocos2d/webview/webview-impl.js @@ -296,7 +296,7 @@ let WebViewImpl = cc.Class({ /** * The binding event - * @param {_ccsg.WebView.EventType} event + * @param {WebViewImpl.EventType} event * @param {Function} callback */ setEventListener (event, callback) { @@ -305,7 +305,7 @@ let WebViewImpl = cc.Class({ /** * Delete events - * @param {_ccsg.WebView.EventType} event + * @param {WebViewImpl.EventType} event */ removeEventListener (event) { this._EventList[event] = null; diff --git a/extensions/dragonbones/webgl-assembler.js b/extensions/dragonbones/webgl-assembler.js index da5e0819c6..9bbdc6d36b 100644 --- a/extensions/dragonbones/webgl-assembler.js +++ b/extensions/dragonbones/webgl-assembler.js @@ -90,14 +90,16 @@ let armatureAssembler = { renderData = comp._renderData; _vertexOffset = buffer.byteOffset >> 2; - _vbuf = buffer._vData; - _uintbuf = buffer._uintVData; - _ibuf = buffer._iData; _indiceOffset = buffer.indiceOffset; _vertexId = buffer.vertexOffset; buffer.request(renderData.vertexCount, renderData.indiceCount); + // buffer data may be realloc, need get reference after request. + _vbuf = buffer._vData; + _uintbuf = buffer._uintVData; + _ibuf = buffer._iData; + let node = comp.node; let nodeColor = node.color; diff --git a/extensions/spine/Skeleton.js b/extensions/spine/Skeleton.js index 4da54b7251..dcbf3aab8b 100644 --- a/extensions/spine/Skeleton.js +++ b/extensions/spine/Skeleton.js @@ -355,7 +355,7 @@ sp.Skeleton = cc.Class({ setAnimationStateData (stateData) { var state = new spine.AnimationState(stateData); if (this._listener) { - if (this._state && this._listener) { + if (this._state) { this._state.removeListener(this._listener); } state.addListener(this._listener); @@ -881,7 +881,9 @@ sp.Skeleton = cc.Class({ _ensureListener () { if (!this._listener) { this._listener = new TrackEntryListeners(); - this._state.addListener(this._listener); + if (this._state) { + this._state.addListener(this._listener); + } } }, diff --git a/extensions/spine/spine-assembler.js b/extensions/spine/spine-assembler.js index 7f0901781c..15a5c44e40 100644 --- a/extensions/spine/spine-assembler.js +++ b/extensions/spine/spine-assembler.js @@ -188,12 +188,20 @@ var spineAssembler = { newData = false; material = _getSlotMaterial(slot, attachment.region.texture._texture, premultiAlpha); + if (!material) { + continue; + } // Check break if (currMaterial !== material) { if (currMaterial) { newData = true; + data.material = currMaterial; } - data.material = currMaterial = material; + else { + // Init data material + data.material = material; + } + currMaterial = material; } // Request new render data and new vertex content @@ -214,8 +222,8 @@ var spineAssembler = { } // Fill up indices + indices = data._indices; if (attachment instanceof spine.RegionAttachment) { - indices = data._indices; indices[indiceOffset] = vertexOffset; indices[indiceOffset + 1] = vertexOffset + 1; indices[indiceOffset + 2] = vertexOffset + 2; @@ -308,16 +316,18 @@ var spineAssembler = { let buffer = renderer.getBuffer('mesh', vfmtPosUvColor), vertexOffset = buffer.byteOffset >> 2, - vbuf = buffer._vData, - uintbuf = buffer._uintVData, vertexCount = data.vertexCount; - let ibuf = buffer._iData, - indiceOffset = buffer.indiceOffset, + let indiceOffset = buffer.indiceOffset, vertexId = buffer.vertexOffset; buffer.request(vertexCount, data.indiceCount); + // buffer data may be realloc, need get reference after request. + let vbuf = buffer._vData, + ibuf = buffer._iData, + uintbuf = buffer._uintVData; + // fill vertex buffer let vert; for (let i = 0, l = data.dataLength; i < l; i++) { diff --git a/external/box2d/box2d.js b/external/box2d/box2d.js index b840d670d1..7f31032d44 100644 --- a/external/box2d/box2d.js +++ b/external/box2d/box2d.js @@ -3614,7 +3614,9 @@ var primaryPair = this.m_pairBuffer[i]; var userDataA = primaryPair.proxyA.userData; // this.m_tree.GetUserData(primaryPair.proxyA); var userDataB = primaryPair.proxyB.userData; // this.m_tree.GetUserData(primaryPair.proxyB); - callback(userDataA, userDataB); + if (userDataA && userDataB) { + callback(userDataA, userDataB); + } ++i; // Skip any duplicate pairs. while (i < this.m_pairCount) { diff --git a/test/qunit/unit-es5/test-class.js b/test/qunit/unit-es5/test-class.js index 1609d13f8e..6bbc168e9d 100644 --- a/test/qunit/unit-es5/test-class.js +++ b/test/qunit/unit-es5/test-class.js @@ -141,6 +141,20 @@ test('define property in quick way', function () { ok(obj.vec2_one.equals(cc.Vec2.ONE), 'could define default value by using cc.Vec2.ONE'); }); +test('__values__', function () { + var Class = cc.Class({ + properties: { + p1: { + serializable: false, + default: null + }, + p2: null + } + }); + + deepEqual(Class.__values__, ['p2'], 'should not contain non-serializable properties'); +}); + test('extends', function () { var Animal = cc.Class({ name: 'cc.Animal', @@ -193,8 +207,10 @@ test('extends', function () { strictEqual(labrador.myName, 'doge', 'can inherit property with Dog.extend syntax'); deepEqual(Husky.__props__, /*CCObject.__props__.concat*/(['myName', 'weight']), 'can inherit prop list'); + deepEqual(Husky.__values__, ['myName', 'weight'], 'can inherit serializable list'); deepEqual(Labrador.__props__, /*CCObject.__props__.concat*/(['myName', 'clever']), 'can inherit prop list with Dog.extend syntax'); deepEqual(Dog.__props__, /*CCObject.__props__.concat*/(['myName']), 'base prop list not changed'); + deepEqual(Dog.__values__, ['myName'], 'base serializable list not changed'); strictEqual(husky instanceof Dog, true, 'can pass instanceof check'); strictEqual(husky instanceof Animal, true, 'can pass instanceof check for deep inheritance'); @@ -434,21 +450,23 @@ test('_isCCClass', function () { cc.js.unregisterClass(ctor); }); -test('try catch', function () { - var originThrow = cc._throw; +if (CC_SUPPORT_JIT) { + test('try catch', function () { + var originThrow = cc._throw; - cc._throw = Callback().enable(); - var Animal = cc.Class({ - ctor: function () { - null.foo(); - } + cc._throw = Callback().enable(); + var Animal = cc.Class({ + ctor: function () { + null.foo(); + } + }); + var animal = new Animal(); + ok(animal, 'should create new instance even if an exception occurs'); + cc._throw.once('should throw exception'); + + cc._throw = originThrow; }); - var animal = new Animal(); - ok(animal, 'should create new instance even if an exception occurs'); - cc._throw.once('should throw exception'); - - cc._throw = originThrow; -}); +} test('this._super', function () { var play = Callback(); @@ -588,6 +606,7 @@ test('mixins', function () { ok(BigDog.prototype.stop !== Mixin2.prototype.stop, "should override base functions"); deepEqual(BigDog.__props__, ['p3', 'p2', 'p1', 'p4'], 'should inherit properties'); + deepEqual(BigDog.__values__, ['p3', 'p2', 'p1', 'p4'], 'should inherit serializable properties'); strictEqual(cc.Class.attr(BigDog, 'p2').default, 'Defined by Mixin2', 'last mixin property should override previous'); strictEqual(cc.Class.attr(BigDog, 'p1').default, 'Defined by BigDog', "should override base property"); strictEqual(cc.js.getClassName(BigDog), 'BigDog', "should not overwrite class name"); @@ -638,8 +657,16 @@ asyncTest('instantiate properties in the next frame', function () { 'should raised error if accessing to props via Class' ); + throws( + function () { + Husky.__values__.length; + }, + 'should raise error if accessing to serializable props via Class' + ); + setTimeout(function () { deepEqual(Husky.__props__, ['like', 'weight'], 'should get properties in the correct order'); + deepEqual(Husky.__values__, ['like', 'weight'], 'should get serializable properties in the correct order'); start(); }, 0); diff --git a/test/qunit/unit-es5/test-instantiate.js b/test/qunit/unit-es5/test-instantiate.js index 85a1d888f6..b596199662 100644 --- a/test/qunit/unit-es5/test-instantiate.js +++ b/test/qunit/unit-es5/test-instantiate.js @@ -287,22 +287,24 @@ testInstantiate('Instantiate', }, cc.instantiate ); -testInstantiate('Instantiate-JIT', - function (obj, expect, info) { - var createCode = new cc._Test.IntantiateJit.compile(obj); - var res = createCode(); - deepEqual(res, expect, info); - }, - function instantiate (obj) { - var createCode = new cc._Test.IntantiateJit.compile(obj); - cc.game._isCloning = true; - var cloned = createCode(); - if (obj._instantiate) { - obj._instantiate(cloned); - } - cc.game._isCloning = false; +if (CC_SUPPORT_JIT) { + testInstantiate('Instantiate-JIT', + function (obj, expect, info) { + var createCode = new cc._Test.IntantiateJit.compile(obj); + var res = createCode(); + deepEqual(res, expect, info); + }, + function instantiate (obj) { + var createCode = new cc._Test.IntantiateJit.compile(obj); + cc.game._isCloning = true; + var cloned = createCode(); + if (obj._instantiate) { + obj._instantiate(cloned); + } + cc.game._isCloning = false; - ok(!('t1' in window), 'should not pollute globals'); - return cloned; - } -); + ok(!('t1' in window), 'should not pollute globals'); + return cloned; + } + ); +} diff --git a/test/qunit/unit/test-class.js b/test/qunit/unit/test-class.js index fbce18f9bd..334c2bd28b 100644 --- a/test/qunit/unit/test-class.js +++ b/test/qunit/unit/test-class.js @@ -257,6 +257,20 @@ largeModule('Class ES6'); strictEqual(attrs['vec2' + cc.Class.Attr.DELIMETER + 'ctor'], cc.Vec2, 'ctor is cc.Vec2'); }); + test('__values__', function () { + @ccclass + class Class { + @property({ + serializable: false + }) + p1 = null; + @property + p2 = null; + } + + deepEqual(Class.__values__, ['p2'], 'should not contain non-serializable properties'); + }); + test('extends', function () { @ccclass('cc.Animal') class Animal { @@ -302,8 +316,10 @@ largeModule('Class ES6'); strictEqual(labrador.myName, 'doge', 'can inherit property with Dog.extend syntax'); deepEqual(Husky.__props__, /*CCObject.__props__.concat*/(['myName', 'weight']), 'can inherit prop list'); + deepEqual(Husky.__values__, ['myName', 'weight'], 'can inherit serializable list'); deepEqual(Labrador.__props__, /*CCObject.__props__.concat*/(['myName', 'clever']), 'can inherit prop list with Dog.extend syntax'); deepEqual(Dog.__props__, /*CCObject.__props__.concat*/(['myName']), 'base prop list not changed'); + deepEqual(Dog.__values__, ['myName'], 'base serializable list not changed'); strictEqual(husky instanceof Dog, true, 'can pass instanceof check'); strictEqual(husky instanceof Animal, true, 'can pass instanceof check for deep inheritance'); @@ -637,6 +653,7 @@ largeModule('Class ES6'); ok(BigDog.prototype.stop !== Mixin2.prototype.stop, "should override base functions"); deepEqual(BigDog.__props__, ['p3', 'p2', 'p1', 'p4'], 'should inherit properties'); + deepEqual(BigDog.__values__, ['p3', 'p2', 'p1', 'p4'], 'should inherit serializable properties'); strictEqual(cc.Class.attr(BigDog, 'p2').default, 'Defined by Mixin2', 'last mixin property should override previous'); strictEqual(cc.Class.attr(BigDog, 'p1').default, 'Defined by BigDog', "should override base property");