From 5a8fb716833858513e3c4a880b79cba2c248a10a Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Fri, 21 Jul 2017 18:04:39 +0800 Subject: [PATCH 001/127] refine Texture2D (+1 squashed commit) Squashed commits: [84eb8b3] refine Texture2D --- cocos2d/core/assets/CCBitmapFont.js | 2 +- cocos2d/core/assets/CCFont.js | 2 +- cocos2d/core/assets/CCSpriteAtlas.js | 2 +- cocos2d/core/textures/CCTexture2D.js | 275 ++++++++++++--------------- 4 files changed, 125 insertions(+), 156 deletions(-) diff --git a/cocos2d/core/assets/CCBitmapFont.js b/cocos2d/core/assets/CCBitmapFont.js index 6007c5ef48..20c2f0df02 100644 --- a/cocos2d/core/assets/CCBitmapFont.js +++ b/cocos2d/core/assets/CCBitmapFont.js @@ -30,7 +30,7 @@ * !#en Class for BitmapFont handling. * !#zh 位图字体资源类。 * @class BitmapFont - * @extends RawAsset + * @extends Font * */ var BitmapFont = cc.Class({ diff --git a/cocos2d/core/assets/CCFont.js b/cocos2d/core/assets/CCFont.js index f3993d1bbe..a845289cc6 100644 --- a/cocos2d/core/assets/CCFont.js +++ b/cocos2d/core/assets/CCFont.js @@ -30,7 +30,7 @@ * !#en Class for Font handling. * !#zh 字体资源类。 * @class Font - * @extends RawAsset + * @extends Asset * */ var Font = cc.Class({ diff --git a/cocos2d/core/assets/CCSpriteAtlas.js b/cocos2d/core/assets/CCSpriteAtlas.js index 15966f6dbe..0d65529fe7 100644 --- a/cocos2d/core/assets/CCSpriteAtlas.js +++ b/cocos2d/core/assets/CCSpriteAtlas.js @@ -27,7 +27,7 @@ * !#en Class for sprite atlas handling. * !#zh 精灵图集资源类。 * @class SpriteAtlas - * @extends RawAsset + * @extends Asset * */ var SpriteAtlas = cc.Class({ diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 309139a464..0f6064ee5a 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -28,7 +28,6 @@ var sys = require('../platform/CCSys'); var JS = require('../platform/js'); var misc = require('../utils/misc'); var game = require('../CCGame'); -require('../platform/_CCClass'); require('../platform/CCClass'); /** @@ -60,18 +59,17 @@ var WrapMode = cc.Enum({ }); /** - *

- * This class allows to easily create OpenGL or Canvas 2D textures from images, text or raw data.
- * The created cc.Texture2D object will always have power-of-two dimensions.
+ * This class allows to easily create OpenGL or Canvas 2D textures from images, text or raw data.
+ * The created cc.Texture2D object will always have power-of-two dimensions.
* Depending on how you create the cc.Texture2D object, the actual image area of the texture might be smaller than the texture dimensions
- * i.e. "contentSize" != (pixelsWide, pixelsHigh) and (maxS, maxT) != (1.0, 1.0).
- * Be aware that the content of the generated textures will be upside-down!

- + * i.e. "contentSize" != (pixelsWide, pixelsHigh) and (maxS, maxT) != (1.0, 1.0).
+ * Be aware that the content of the generated textures will be upside-down! + * * @class Texture2D * @uses EventTarget * @extends RawAsset */ -var Texture2D = cc.Class(/** @lends cc.Texture2D# */{ +var Texture2D = cc.Class({ name: 'cc.Texture2D', extends: require('../assets/CCRawAsset'), @@ -82,7 +80,14 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{ }, ctor: function () { + /** + * The source file's url for the texture, it could be empty if the texture wasn't created via a file. + * @property url + * @type {String} + * @readonly + */ this.url = null; + this._textureLoaded = false; this._htmlElementObj = null; this._contentSize = cc.size(0, 0); @@ -105,6 +110,29 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{ } }, + properties: { + /** + * Content width in points. + * @property width + * @type {Number} + */ + width: { + get () { + return this._contentSize.width; + } + }, + /** + * Content height in points. + * @property height + * @type {Number} + */ + height: { + get () { + return this._contentSize.height; + } + } + }, + /** * Get width in pixels. * @method getPixelWidth @@ -132,13 +160,6 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{ return cc.size(this._contentSize.width, this._contentSize.height); }, - _getWidth: function () { - return this._contentSize.width; - }, - _getHeight: function () { - return this._contentSize.height; - }, - /** * Get content size in pixels. * @method getContentSizeInPixels @@ -365,156 +386,151 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{ } }); -Texture2D.WrapMode = WrapMode; - -var _c = Texture2D; - /** * 32-bit texture: RGBA8888 - * @property PIXEL_FORMAT_RGBA8888 + * @property {Number} PIXEL_FORMAT_RGBA8888 * @static - * @type {Number} */ -_c.PIXEL_FORMAT_RGBA8888 = 2; +Texture2D.PIXEL_FORMAT_RGBA8888 = 2; /** * 24-bit texture: RGB888, not supported yet - * @property PIXEL_FORMAT_RGB888 + * @property {Number} PIXEL_FORMAT_RGB888 * @static - * @type {Number} */ -_c.PIXEL_FORMAT_RGB888 = 3; +Texture2D.PIXEL_FORMAT_RGB888 = 3; /** * 16-bit texture without Alpha channel, not supported yet - * @property PIXEL_FORMAT_RGB565 + * @property {Number} PIXEL_FORMAT_RGB565 * @static - * @type {Number} */ -_c.PIXEL_FORMAT_RGB565 = 4; +Texture2D.PIXEL_FORMAT_RGB565 = 4; /** * 8-bit textures used as masks, not supported yet - * @property PIXEL_FORMAT_A8 + * @property {Number} PIXEL_FORMAT_A8 * @static - * @type {Number} */ -_c.PIXEL_FORMAT_A8 = 5; +Texture2D.PIXEL_FORMAT_A8 = 5; /** * 8-bit intensity texture, not supported yet - * @property PIXEL_FORMAT_I8 + * @property {Number} PIXEL_FORMAT_I8 * @static - * @type {Number} */ -_c.PIXEL_FORMAT_I8 = 6; +Texture2D.PIXEL_FORMAT_I8 = 6; /** * 16-bit textures used as masks, not supported yet - * @property PIXEL_FORMAT_AI88 + * @property {Number} PIXEL_FORMAT_AI88 * @static - * @type {Number} */ -_c.PIXEL_FORMAT_AI88 = 7; +Texture2D.PIXEL_FORMAT_AI88 = 7; /** * 16-bit textures: RGBA4444, not supported yet - * @property PIXEL_FORMAT_RGBA4444 + * @property {Number} PIXEL_FORMAT_RGBA4444 * @static - * @type {Number} */ -_c.PIXEL_FORMAT_RGBA4444 = 8; +Texture2D.PIXEL_FORMAT_RGBA4444 = 8; /** * 16-bit textures: RGB5A1, not supported yet - * @property PIXEL_FORMAT_RGB5A1 + * @property {Number} PIXEL_FORMAT_RGB5A1 * @static - * @type {Number} */ -_c.PIXEL_FORMAT_RGB5A1 = 7; +Texture2D.PIXEL_FORMAT_RGB5A1 = 7; /** * 4-bit PVRTC-compressed texture: PVRTC4, not supported yet - * @property PIXEL_FORMAT_PVRTC4 + * @property {Number} PIXEL_FORMAT_PVRTC4 * @static - * @type {Number} */ -_c.PIXEL_FORMAT_PVRTC4 = 9; +Texture2D.PIXEL_FORMAT_PVRTC4 = 9; /** * 2-bit PVRTC-compressed texture: PVRTC2, not supported yet - * @property PIXEL_FORMAT_PVRTC2 + * @property {Number} PIXEL_FORMAT_PVRTC2 * @static - * @type {Number} */ -_c.PIXEL_FORMAT_PVRTC2 = 10; +Texture2D.PIXEL_FORMAT_PVRTC2 = 10; /** * Default texture format: RGBA8888 - * @property PIXEL_FORMAT_DEFAULT + * @property {Number} PIXEL_FORMAT_DEFAULT * @static - * @type {Number} */ -_c.PIXEL_FORMAT_DEFAULT = _c.PIXEL_FORMAT_RGBA8888; +Texture2D.PIXEL_FORMAT_DEFAULT = Texture2D.PIXEL_FORMAT_RGBA8888; /** * The default pixel format - * @property defaultPixelFormat + * @property {Number} defaultPixelFormat * @static - * @type {Number} */ -_c.defaultPixelFormat = _c.PIXEL_FORMAT_DEFAULT; +Texture2D.defaultPixelFormat = Texture2D.PIXEL_FORMAT_DEFAULT; -var _M = Texture2D._M = {}; -_M[_c.PIXEL_FORMAT_RGBA8888] = "RGBA8888"; -_M[_c.PIXEL_FORMAT_RGB888] = "RGB888"; -_M[_c.PIXEL_FORMAT_RGB565] = "RGB565"; -_M[_c.PIXEL_FORMAT_A8] = "A8"; -_M[_c.PIXEL_FORMAT_I8] = "I8"; -_M[_c.PIXEL_FORMAT_AI88] = "AI88"; -_M[_c.PIXEL_FORMAT_RGBA4444] = "RGBA4444"; -_M[_c.PIXEL_FORMAT_RGB5A1] = "RGB5A1"; -_M[_c.PIXEL_FORMAT_PVRTC4] = "PVRTC4"; -_M[_c.PIXEL_FORMAT_PVRTC2] = "PVRTC2"; +var PIXEL_FORMAT_NAMES = {}; +PIXEL_FORMAT_NAMES[Texture2D.PIXEL_FORMAT_RGBA8888] = "RGBA8888"; +PIXEL_FORMAT_NAMES[Texture2D.PIXEL_FORMAT_RGB888] = "RGB888"; +PIXEL_FORMAT_NAMES[Texture2D.PIXEL_FORMAT_RGB565] = "RGB565"; +PIXEL_FORMAT_NAMES[Texture2D.PIXEL_FORMAT_A8] = "A8"; +PIXEL_FORMAT_NAMES[Texture2D.PIXEL_FORMAT_I8] = "I8"; +PIXEL_FORMAT_NAMES[Texture2D.PIXEL_FORMAT_AI88] = "AI88"; +PIXEL_FORMAT_NAMES[Texture2D.PIXEL_FORMAT_RGBA4444] = "RGBA4444"; +PIXEL_FORMAT_NAMES[Texture2D.PIXEL_FORMAT_RGB5A1] = "RGB5A1"; +PIXEL_FORMAT_NAMES[Texture2D.PIXEL_FORMAT_PVRTC4] = "PVRTC4"; +PIXEL_FORMAT_NAMES[Texture2D.PIXEL_FORMAT_PVRTC2] = "PVRTC2"; -var _B = Texture2D._B = {}; -_B[_c.PIXEL_FORMAT_RGBA8888] = 32; -_B[_c.PIXEL_FORMAT_RGB888] = 24; -_B[_c.PIXEL_FORMAT_RGB565] = 16; -_B[_c.PIXEL_FORMAT_A8] = 8; -_B[_c.PIXEL_FORMAT_I8] = 8; -_B[_c.PIXEL_FORMAT_AI88] = 16; -_B[_c.PIXEL_FORMAT_RGBA4444] = 16; -_B[_c.PIXEL_FORMAT_RGB5A1] = 16; -_B[_c.PIXEL_FORMAT_PVRTC4] = 4; -_B[_c.PIXEL_FORMAT_PVRTC2] = 3; +var BITS_PER_PIXELS = {}; +BITS_PER_PIXELS[Texture2D.PIXEL_FORMAT_RGBA8888] = 32; +BITS_PER_PIXELS[Texture2D.PIXEL_FORMAT_RGB888] = 24; +BITS_PER_PIXELS[Texture2D.PIXEL_FORMAT_RGB565] = 16; +BITS_PER_PIXELS[Texture2D.PIXEL_FORMAT_A8] = 8; +BITS_PER_PIXELS[Texture2D.PIXEL_FORMAT_I8] = 8; +BITS_PER_PIXELS[Texture2D.PIXEL_FORMAT_AI88] = 16; +BITS_PER_PIXELS[Texture2D.PIXEL_FORMAT_RGBA4444] = 16; +BITS_PER_PIXELS[Texture2D.PIXEL_FORMAT_RGB5A1] = 16; +BITS_PER_PIXELS[Texture2D.PIXEL_FORMAT_PVRTC4] = 4; +BITS_PER_PIXELS[Texture2D.PIXEL_FORMAT_PVRTC2] = 3; var _p = Texture2D.prototype; // Extended properties -/** @expose */ -_p.name; -cc.defineGetterSetter(_p, "name", _p.getName); -/** @expose */ -_p.pixelFormat; -cc.defineGetterSetter(_p, "pixelFormat", _p.getPixelFormat); -/** @expose */ -_p.pixelWidth; -cc.defineGetterSetter(_p, "pixelWidth", _p.getPixelWidth); -/** @expose */ -_p.pixelHeight; -cc.defineGetterSetter(_p, "pixelHeight", _p.getPixelHeight); -/** @expose */ -_p.width; -cc.defineGetterSetter(_p, "width", _p._getWidth); -/** @expose */ -_p.height; -cc.defineGetterSetter(_p, "height", _p._getHeight); + +/** + * WebGLTexture Object. + * @property name + * @type {WebGLTexture} + * @readonly + */ +JS.get(_p, "name", _p.getName); +/** + * Pixel format of the texture. + * @property pixelFormat + * @type {Number} + * @readonly + */ +JS.get(_p, "pixelFormat", _p.getPixelFormat); +/** + * Width in pixels. + * @property pixelWidth + * @type {Number} + * @readonly + */ +JS.get(_p, "pixelWidth", _p.getPixelWidth); +/** + * Height in pixels. + * @property pixelHeight + * @type {Number} + * @readonly + */ +JS.get(_p, "pixelHeight", _p.getPixelHeight); game.once(game.EVENT_RENDERER_INITED, function () { if(cc._renderType === game.RENDER_TYPE_CANVAS) { - var renderToCache = function(image, cache){ + function renderToCache (image, cache){ var w = image.width; var h = image.height; @@ -546,9 +562,9 @@ game.once(game.EVENT_RENDERER_INITED, function () { ctx.putImageData(to, 0, 0); } image.onload = null; - }; + } - var generateGrayTexture = function(texture, rect, renderCanvas){ + function generateGrayTexture (texture, rect, renderCanvas){ if (texture === null) return null; renderCanvas = renderCanvas || document.createElement("canvas"); @@ -565,7 +581,7 @@ game.once(game.EVENT_RENDERER_INITED, function () { } context.putImageData(imgData, 0, 0); return renderCanvas; - }; + } _p._generateTextureCacheForColor = function(){ if (this.channelCache) @@ -600,7 +616,7 @@ game.once(game.EVENT_RENDERER_INITED, function () { _p._generateGrayTexture = function() { if(!this._textureLoaded) return null; - var grayElement = generateGrayTexture(this._htmlElementObj);; + var grayElement = generateGrayTexture(this._htmlElementObj); var newTexture = new Texture2D(); newTexture.initWithElement(grayElement); newTexture.handleLoadedTexture(); @@ -688,14 +704,14 @@ game.once(game.EVENT_RENDERER_INITED, function () { newTexture.handleLoadedTexture(); return newTexture; }; - - } else if (cc._renderType === game.RENDER_TYPE_WEBGL) { + } + else if (cc._renderType === game.RENDER_TYPE_WEBGL) { _p.initWithData = function (data, pixelFormat, pixelsWide, pixelsHigh, contentSize) { var self = this, tex2d = Texture2D; var gl = cc._renderContext; var format = gl.RGBA, type = gl.UNSIGNED_BYTE; - var bitsPerPixel = Texture2D._B[pixelFormat]; + var bitsPerPixel = BITS_PER_PIXELS[pixelFormat]; var bytesPerRow = pixelsWide * bitsPerPixel / 8; if (bytesPerRow % 8 === 0) { @@ -897,12 +913,12 @@ game.once(game.EVENT_RENDERER_INITED, function () { }; _p.stringForFormat = function () { - return Texture2D._M[this._pixelFormat]; + return PIXEL_FORMAT_NAMES[this._pixelFormat]; }; _p.bitsPerPixelForFormat = function (format) {//TODO I want to delete the format argument, use this._pixelFormat format = format || this._pixelFormat; - var value = Texture2D._B[format]; + var value = BITS_PER_PIXELS[format]; if (value != null) return value; cc.logID(3110, format); return -1; @@ -1014,51 +1030,4 @@ game.once(game.EVENT_RENDERER_INITED, function () { } }); -/** - * WebGLTexture Object. - * @property name - * @type {WebGLTexture} - * @readonly - */ - -/** - * The source file's url for the texture, it could be empty if the texture wasn't created via a file. - * @property url - * @type {String} - * @readonly - */ - -/** - * Pixel format of the texture. - * @property pixelFormat - * @type {Number} - * @readonly - */ - -/** - * Width in pixels. - * @property pixelWidth - * @type {Number} - * @readonly - */ - -/** - * Height in pixels. - * @property pixelHeight - * @type {Number} - * @readonly - */ - -/** - * Content width in points. - * @property width - * @type {Number} - */ - -/** - * Content height in points. - * @property height - * @type {Number} - */ - -cc.Texture2D = module.exports = Texture2D; \ No newline at end of file +cc.Texture2D = module.exports = Texture2D; From efa57bb48f29dfdde3b323af98fd15151dc63207 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Mon, 24 Jul 2017 11:50:22 +0800 Subject: [PATCH 002/127] make texture as common asset --- cocos2d/core/assets/CCAsset.js | 6 +++--- cocos2d/core/textures/CCTexture2D.js | 16 +++++++++++++--- jsb/jsb-tex-sprite-frame.js | 5 ++++- 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/cocos2d/core/assets/CCAsset.js b/cocos2d/core/assets/CCAsset.js index 269c4c659c..556dafe67e 100644 --- a/cocos2d/core/assets/CCAsset.js +++ b/cocos2d/core/assets/CCAsset.js @@ -122,7 +122,7 @@ cc.Asset = cc.Class({ * @static * @private */ - deserialize: function (data) { + deserialize: CC_EDITOR && function (data) { return cc.deserialize(data); }, @@ -144,7 +144,7 @@ cc.Asset = cc.Class({ * @return {String} * @private */ - serialize: function () { + serialize: CC_EDITOR && function () { return Editor.serialize(this); }, @@ -169,7 +169,7 @@ cc.Asset = cc.Class({ * @param {String[]} rawFiles * @private */ - _setRawFiles: function (rawFiles) { + _setRawFiles: CC_EDITOR && function (rawFiles) { this._rawFiles = rawFiles.length > 0 ? rawFiles : null; }, diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 0f6064ee5a..35b920801b 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -62,17 +62,17 @@ var WrapMode = cc.Enum({ * This class allows to easily create OpenGL or Canvas 2D textures from images, text or raw data.
* The created cc.Texture2D object will always have power-of-two dimensions.
* Depending on how you create the cc.Texture2D object, the actual image area of the texture might be smaller than the texture dimensions
- * i.e. "contentSize" != (pixelsWide, pixelsHigh) and (maxS, maxT) != (1.0, 1.0).
+ * i.e. "contentSize" != (pixelsWidth, pixelsHight) and (maxS, maxT) != (1.0, 1.0).
* Be aware that the content of the generated textures will be upside-down! * * @class Texture2D * @uses EventTarget - * @extends RawAsset + * @extends Asset */ var Texture2D = cc.Class({ name: 'cc.Texture2D', - extends: require('../assets/CCRawAsset'), + extends: require('../assets/CCAsset'), mixins: [EventTarget], statics: { @@ -133,6 +133,16 @@ var Texture2D = cc.Class({ } }, + /** + * Returns the texture's url.
+ * The Texture object overrides the toString() method of the Object object; it does not inherit Object.prototype.toString(). For Texture objects, the toString() method returns a string representation of the object. JavaScript calls the toString() method automatically when a texture is to be represented as a text value or when a texture is referred to in a string concatenation. + * @method toString + * @return {String} + */ + toString () { + return this.url || ''; + }, + /** * Get width in pixels. * @method getPixelWidth diff --git a/jsb/jsb-tex-sprite-frame.js b/jsb/jsb-tex-sprite-frame.js index 09914e8b8e..c6067960eb 100644 --- a/jsb/jsb-tex-sprite-frame.js +++ b/jsb/jsb-tex-sprite-frame.js @@ -89,7 +89,7 @@ cc.textureCache.removeTextureForKey = function (key) { // cc.Texture2D cc.Class._fastDefine('cc.Texture2D', cc.Texture2D, []); -cc.js.value(cc.Texture2D, '$super', cc.RawAsset); // not inheritable in JSB and TypeScript +cc.js.value(cc.Texture2D, '$super', cc.Asset); // not inheritable in JSB and TypeScript cc.Texture2D.WrapMode = cc.Enum({ REPEAT: 0x2901, @@ -99,6 +99,9 @@ cc.Texture2D.WrapMode = cc.Enum({ var prototype = cc.Texture2D.prototype; +prototype.toString = function () { + return this.url || ''; +}; prototype.isLoaded = function () { return true; }; From d9884053775a82b5bbeee7be36ffee6d46e348c7 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Sat, 2 Sep 2017 21:45:00 +0800 Subject: [PATCH 003/127] add warning if use Texture2D object instead of url in some api --- cocos2d/core/textures/CCTextureCache.js | 32 ++++++++----------------- cocos2d/deprecated.js | 2 ++ 2 files changed, 12 insertions(+), 22 deletions(-) diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js index 7e4bb385db..4cf841d591 100644 --- a/cocos2d/core/textures/CCTextureCache.js +++ b/cocos2d/core/textures/CCTextureCache.js @@ -61,19 +61,6 @@ var textureCache = /** @lends cc.textureCache# */{ return ""; }, - /** - * Returns an already created texture. Returns null if the texture doesn't exist. - * @method textureForKey - * @param {String} textureKeyName - * @return {Texture2D|Null} - * @deprecated - * @example {@link utils/api/engine/docs/cocos2d/core/textures/textureForKey.js} - */ - textureForKey: function (textureKeyName) { - cc.logID(3002); - return this.getTextureForKey(textureKeyName); - }, - /** * Returns an already created texture. Returns null if the texture doesn't exist. * @method getTextureForKey @@ -229,11 +216,9 @@ var textureCache = /** @lends cc.textureCache# */{ }, /** - *

Returns a Texture2D object given an UIImage image
- * If the image was not previously loaded, it will create a new Texture2D object and it will return it.
- * Otherwise it will return a reference of a previously loaded image
- * The "key" parameter will be used as the "key" for the cache.
- * If "key" is null, then a new texture will be created each time.

+ * Returns a Texture2D object given an UIImage image
+ * If the image was not previously loaded, it will create a new Texture2D object and it will return it. Otherwise it will return a reference of a previously loaded image.
+ * The "key" parameter will be used as the "key" for the cache. If "key" is null, then a new texture will be created each time. * @method addUIImage * @param {HTMLImageElement|HTMLCanvasElement} image * @param {String} key @@ -257,8 +242,8 @@ var textureCache = /** @lends cc.textureCache# */{ }, /** - *

Output to cc.log the current contents of this TextureCache
- * This will attempt to calculate the size of each texture, and the total texture memory in use.

+ * Output to cc.log the current contents of this TextureCache.
+ * This will attempt to calculate the size of each texture, and the total texture memory in use. */ dumpCachedTextureInfo: function () { var count = 0; @@ -369,6 +354,10 @@ game.once(game.EVENT_RENDERER_INITED, function () { }; _p.addImage = function (url, cb, target) { + if (CC_DEBUG && url instanceof cc.Texture2D) { + cc.warn('textureCache.addImage(url) - The type of the url should be string, not Texture2D. You don\'t need to call addImage if you already have the texture object.'); + } + cc.assertID(url, 3112); var locTexs = this._textures; @@ -382,8 +371,7 @@ game.once(game.EVENT_RENDERER_INITED, function () { cb && cb.call(target, tex); return tex; } - else - { + else { tex.once("load", function(){ cb && cb.call(target, tex); }, target); diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js index 2c7f620613..ae657e43a0 100644 --- a/cocos2d/deprecated.js +++ b/cocos2d/deprecated.js @@ -8,6 +8,8 @@ if (CC_DEV) { cc.errorID(1404); }); + js.obsolete(cc.textureCache, 'cc.textureCache.textureForKey', 'getTextureForKey'); + // Label if (cc.Label) { js.obsolete(cc.Label.prototype, 'cc.Label.file', 'font', true); From ebd794bd6dc8fe0f6b46d2f3391dd0f9681f3cbd Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 6 Sep 2017 16:37:48 +0800 Subject: [PATCH 004/127] remove unused texture (path) support for constructor of sgNodes --- cocos2d/core/sprites/CCSGSprite.js | 45 +++++++---------------- cocos2d/core/sprites/CCScale9Sprite.js | 9 ++--- cocos2d/core/sprites/CCSpriteBatchNode.js | 15 ++------ 3 files changed, 19 insertions(+), 50 deletions(-) diff --git a/cocos2d/core/sprites/CCSGSprite.js b/cocos2d/core/sprites/CCSGSprite.js index 04d696325d..e748d241be 100644 --- a/cocos2d/core/sprites/CCSGSprite.js +++ b/cocos2d/core/sprites/CCSGSprite.js @@ -52,19 +52,15 @@ var Misc = require('../utils/misc'); * @class * @extends _ccsg.Node * - * @param {String|cc.SpriteFrame|HTMLImageElement|cc.Texture2D} fileName The string which indicates a path to image file, e.g., "scene1/monster.png". + * @param {cc.SpriteFrame|cc.Texture2D} textureOrSpriteFrame * @param {Rect} rect Only the contents inside rect of pszFileName's texture will be applied for this sprite. * @param {Boolean} [rotated] Whether or not the texture rectangle is rotated. * @example * - * 1.Create a sprite with image path and rect - * var sprite1 = new _ccsg.Sprite("res/HelloHTML5World.png"); - * var sprite2 = new _ccsg.Sprite("res/HelloHTML5World.png",cc.rect(0,0,480,320)); - * - * 2.Create a sprite with a sprite frame + * 1.Create a sprite with a sprite frame * var sprite = new _ccsg.Sprite(spriteFrame); * - * 3.Create a sprite with an existing texture contained in a CCTexture2D object + * 2.Create a sprite with an existing texture contained in a CCTexture2D object * After creation, the rect will be the size of the texture, and the offset will be (0,0). * var texture = cc.textureCache.addImage("HelloHTML5World.png"); * var sprite1 = new _ccsg.Sprite(texture); @@ -113,7 +109,7 @@ _ccsg.Sprite = _ccsg.Node.extend({ _textureLoaded:false, _className:"Sprite", - ctor: function (fileName, rect, rotated) { + ctor: function (textureOrSpriteFrame, rect, rotated) { var self = this; _ccsg.Node.prototype.ctor.call(self); EventTarget.call(self); @@ -124,7 +120,7 @@ _ccsg.Sprite = _ccsg.Node.extend({ self._blendFunc = {src: cc.macro.BLEND_SRC, dst: cc.macro.BLEND_DST}; self._rect = cc.rect(0, 0, 0, 0); - self._softInit(fileName, rect, rotated); + self._softInit(textureOrSpriteFrame, rect, rotated); }, /** @@ -367,30 +363,15 @@ _ccsg.Sprite = _ccsg.Node.extend({ return this._texture; }, - _softInit: function (fileName, rect, rotated) { - if (fileName === undefined) + _softInit: function (textureOrSpriteFrame, rect, rotated) { + if (textureOrSpriteFrame === undefined) _ccsg.Sprite.prototype.init.call(this); - else if (cc.js.isString(fileName)) { - if (fileName[0] === "#") { - cc.logID(2728, fileName); - } else { - // Init with filename and rect - _ccsg.Sprite.prototype.init.call(this, fileName, rect); - } - } else if (typeof fileName === "object") { - if (fileName instanceof cc.Texture2D) { - // Init with texture and rect - this.initWithTexture(fileName, rect, rotated); - } else if (fileName instanceof cc.SpriteFrame) { - // Init with a sprite frame - this.initWithSpriteFrame(fileName); - } else if ((fileName instanceof HTMLImageElement) || (fileName instanceof HTMLCanvasElement)) { - // Init with a canvas or image element - var texture2d = new cc.Texture2D(); - texture2d.initWithElement(fileName); - texture2d.handleLoadedTexture(); - this.initWithTexture(texture2d); - } + else if (textureOrSpriteFrame instanceof cc.Texture2D) { + // Init with texture and rect + this.initWithTexture(textureOrSpriteFrame, rect, rotated); + } else if (textureOrSpriteFrame instanceof cc.SpriteFrame) { + // Init with a sprite frame + this.initWithSpriteFrame(textureOrSpriteFrame); } }, diff --git a/cocos2d/core/sprites/CCScale9Sprite.js b/cocos2d/core/sprites/CCScale9Sprite.js index 72fefaa378..9c6149b2ab 100644 --- a/cocos2d/core/sprites/CCScale9Sprite.js +++ b/cocos2d/core/sprites/CCScale9Sprite.js @@ -1101,7 +1101,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ _distortionTiling: null, _meshPolygonInfo: null, - ctor: function (textureOrSpriteFrame) { + ctor: function (spiteFrame) { _ccsg.Node.prototype.ctor.call(this); this._renderCmd.setState(this._brightState); this._blendFunc = cc.BlendFunc._alphaNonPremultiplied(); @@ -1113,11 +1113,8 @@ cc.Scale9Sprite = _ccsg.Node.extend({ this._vertices = dataPool.get(8) || new Float32Array(8); this._uvs = dataPool.get(8) || new Float32Array(8); // Init sprite frame - if (typeof textureOrSpriteFrame === 'string' || textureOrSpriteFrame instanceof cc.Texture2D) { - this.initWithTexture(textureOrSpriteFrame); - } - else if (textureOrSpriteFrame instanceof cc.SpriteFrame) { - this.initWithSpriteFrame(textureOrSpriteFrame); + if (spiteFrame) { + this.initWithSpriteFrame(spiteFrame); } if (webgl === undefined) { diff --git a/cocos2d/core/sprites/CCSpriteBatchNode.js b/cocos2d/core/sprites/CCSpriteBatchNode.js index bd963cea68..6d604cc662 100644 --- a/cocos2d/core/sprites/CCSpriteBatchNode.js +++ b/cocos2d/core/sprites/CCSpriteBatchNode.js @@ -58,19 +58,10 @@ cc.SpriteBatchNode = _ccsg.Node.extend(/** @lends cc.SpriteBatchNode# */{ _texture: null, _className: "SpriteBatchNode", - ctor: function (fileImage) { + ctor: function (texture) { _ccsg.Node.prototype.ctor.call(this); this._blendFunc = new cc.BlendFunc(cc.macro.BLEND_SRC, cc.macro.BLEND_DST); - - var texture2D; - if (cc.js.isString(fileImage)) { - texture2D = cc.textureCache.getTextureForKey(fileImage); - if (!texture2D) - texture2D = cc.textureCache.addImage(fileImage); - }else if (fileImage instanceof cc.Texture2D) - texture2D = fileImage; - - texture2D && this.initWithTexture(texture2D); + texture && this.initWithTexture(texture); }, // property @@ -153,7 +144,7 @@ cc.SpriteBatchNode = _ccsg.Node.extend(/** @lends cc.SpriteBatchNode# */{ appendChild: function (sprite) { this.sortAllChildren(); var lastLocalZOrder = this._children[this._children.length-1]._localZOrder; - this.addChild(sprite. lastLocalZOrder + 1); + this.addChild(sprite, lastLocalZOrder + 1); }, /** From fbd473117c8fd7759c9ef25e0df1962dc4ab722e Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Sat, 9 Sep 2017 22:49:56 +0800 Subject: [PATCH 005/127] tweaks --- DebugInfos.js | 2 +- cocos2d/core/platform/CCClassDecorator.js | 2 +- cocos2d/motion-streak/CCSGMotionStreak.js | 44 ++++++++++------------- cocos2d/shaders/CCShaderCache.js | 26 +++++--------- extensions/dragonbones/CCTextureData.js | 32 +++++++++++------ jsb/jsb-tex-sprite-frame.js | 5 +-- 6 files changed, 51 insertions(+), 60 deletions(-) diff --git a/DebugInfos.js b/DebugInfos.js index 2efd3fe0c0..e0f71d9ea8 100644 --- a/DebugInfos.js +++ b/DebugInfos.js @@ -319,7 +319,7 @@ if (CC_DEBUG) { " type: cc.Integer\n" + " })\n" + " value = 0; // <--", - "3654": "Please specifiy a default value for \"%s\" property at its declaration: \uD83D\uDE02\n" + + "3654": "Please specifiy a default value for \"%s.%s\" at its declaration: \uD83D\uDE02\n" + " // Before:\n" + " @property(...)\n" + " value;\n\n" + diff --git a/cocos2d/core/platform/CCClassDecorator.js b/cocos2d/core/platform/CCClassDecorator.js index 71cc94c678..fd85c2f04a 100644 --- a/cocos2d/core/platform/CCClassDecorator.js +++ b/cocos2d/core/platform/CCClassDecorator.js @@ -214,7 +214,7 @@ function genProperty (ctor, properties, propName, options, desc, cache) { // prop.default = options.default; } else if (!isDefaultValueSpecified) { - cc.warnID(3654, propName); + cc.warnID(3654, JS.getClassName(ctor), propName); // prop.default = fullOptions.hasOwnProperty('default') ? fullOptions.default : undefined; } } diff --git a/cocos2d/motion-streak/CCSGMotionStreak.js b/cocos2d/motion-streak/CCSGMotionStreak.js index bbf58b5bb9..0bb29cb193 100644 --- a/cocos2d/motion-streak/CCSGMotionStreak.js +++ b/cocos2d/motion-streak/CCSGMotionStreak.js @@ -151,23 +151,23 @@ function vertexLineIntersect (Ax, Ay, Bx, By, Cx, Cy, Dx, Dy) { return {isSuccess:true, value:t}; } -/** - * returns wheter or not polygon defined by vertex list is clockwise - * @param {Array} verts - * @return {Boolean} - */ -function vertexListIsClockwise (verts) { - for (var i = 0, len = verts.length; i < len; i++) { - var a = verts[i]; - var b = verts[(i + 1) % len]; - var c = verts[(i + 2) % len]; - - if (cc.pCross(cc.pSub(b, a), cc.pSub(c, b)) > 0) - return false; - } - - return true; -} +// /** +// * returns wheter or not polygon defined by vertex list is clockwise +// * @param {Array} verts +// * @return {Boolean} +// */ +// function vertexListIsClockwise (verts) { +// for (var i = 0, len = verts.length; i < len; i++) { +// var a = verts[i]; +// var b = verts[(i + 1) % len]; +// var c = verts[(i + 2) % len]; +// +// if (cc.pCross(cc.pSub(b, a), cc.pSub(c, b)) > 0) +// return false; +// } +// +// return true; +// } /** * cc.MotionStreak manages a Ribbon based on it's motion in absolute space.
@@ -219,13 +219,8 @@ _ccsg.MotionStreak = _ccsg.Node.extend({ /** * creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture filename or texture
* Constructor of cc.MotionStreak - * @param {Number} fade time to fade - * @param {Number} minSeg minimum segment size - * @param {Number} stroke stroke's width - * @param {Number} color - * @param {string|cc.Texture2D} texture texture filename or texture */ - ctor: function (fade, minSeg, stroke, color, texture) { + ctor: function () { _ccsg.Node.prototype.ctor.call(this); this._positionR = cc.p(0, 0); this._blendFunc = new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA); @@ -255,9 +250,6 @@ _ccsg.MotionStreak = _ccsg.Node.extend({ this._verticesBuffer = null; this._colorPointerBuffer = null; this._texCoordsBuffer = null; - - if(texture !== undefined) - this.initWithFade(fade, minSeg, stroke, color, texture); }, /** diff --git a/cocos2d/shaders/CCShaderCache.js b/cocos2d/shaders/CCShaderCache.js index 153e316cba..33b8447e89 100644 --- a/cocos2d/shaders/CCShaderCache.js +++ b/cocos2d/shaders/CCShaderCache.js @@ -35,42 +35,49 @@ var macro = cc.macro; cc.shaderCache = /** @lends cc.shaderCache# */{ /** + * Position Texture Color shader * @public * @constant * @type {Number} */ TYPE_POSITION_TEXTURECOLOR: 0, /** + * Position Texture Color alpha test * @public * @constant * @type {Number} */ TYPE_POSITION_TEXTURECOLOR_ALPHATEST: 1, /** + * Position, Color shader * @public * @constant * @type {Number} */ TYPE_POSITION_COLOR: 2, /** + * Position Texture shader * @public * @constant * @type {Number} */ TYPE_POSITION_TEXTURE: 3, /** + * Position, Texture attribs, 1 Color as uniform shader * @public * @constant * @type {Number} */ TYPE_POSITION_TEXTURE_UCOLOR: 4, /** + * Position Texture A8 Color shader * @public * @constant * @type {Number} */ TYPE_POSITION_TEXTURE_A8COLOR: 5, /** + * Position and 1 color passed as a uniform (to similate glColor4ub ) * @public * @constant * @type {Number} @@ -83,12 +90,14 @@ cc.shaderCache = /** @lends cc.shaderCache# */{ */ TYPE_POSITION_LENGTH_TEXTURECOLOR: 7, /** + * Sprite Position Texture Color shader * @public * @constant * @type {Number} */ TYPE_SPRITE_POSITION_TEXTURECOLOR: 8, /** + * Sprite Position Texture Color alpha shader * @public * @constant * @type {Number} @@ -211,31 +220,14 @@ cc.shaderCache = /** @lends cc.shaderCache# */{ */ reloadDefaultShaders: function () { // reset all default programs and reload them - // Position Texture Color shader this._reloadShader(macro.SHADER_POSITION_TEXTURECOLOR); - - // Sprite Position Texture Color shader this._reloadShader(macro.SHADER_SPRITE_POSITION_TEXTURECOLOR); - - // Position Texture Color alpha test this._reloadShader(macro.SHADER_POSITION_TEXTURECOLORALPHATEST); - - // Sprite Position Texture Color alpha shader this._reloadShader(macro.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST); - - // Position, Color shader this._reloadShader(macro.SHADER_POSITION_COLOR); - - // Position Texture shader this._reloadShader(macro.SHADER_POSITION_TEXTURE); - - // Position, Texture attribs, 1 Color as uniform shader this._reloadShader(macro.SHADER_POSITION_TEXTURE_UCOLOR); - - // Position Texture A8 Color shader this._reloadShader(macro.SHADER_POSITION_TEXTUREA8COLOR); - - // Position and 1 color passed as a uniform (to similate glColor4ub ) this._reloadShader(macro.SHADER_POSITION_UCOLOR); }, diff --git a/extensions/dragonbones/CCTextureData.js b/extensions/dragonbones/CCTextureData.js index 7c14aa3ad9..cc6b8dc226 100644 --- a/extensions/dragonbones/CCTextureData.js +++ b/extensions/dragonbones/CCTextureData.js @@ -23,38 +23,48 @@ ****************************************************************************/ dragonBones.CCTextureAtlasData = cc.Class({ - name: 'dragonBones.CCTextureAtlasData', extends: dragonBones.TextureAtlasData, - texture : null, - statics : { - toString : function() { + properties: { + texture: { + default: null, + serializable: false + }, + }, + + statics: { + toString: function () { return "[class dragonBones.CCTextureAtlasData]"; } }, - _onClear : function() { + _onClear: function () { dragonBones.TextureAtlasData.prototype._onClear.call(this); this.texture = null; }, - generateTextureData : function() { + generateTextureData: function () { return dragonBones.BaseObject.borrowObject(dragonBones.CCTextureData); } }); dragonBones.CCTextureData = cc.Class({ - name: 'dragonBones.CCTextureData', extends: dragonBones.TextureData, - texture: null, - statics : { - toString : function() { + properties: { + texture: { + default: null, + serializable: false + }, + }, + + statics: { + toString: function () { return "[class dragonBones.CCTextureData]"; } }, - _onClear : function() { + _onClear: function () { dragonBones.TextureData.prototype._onClear.call(this); if (this.texture) { this.texture.dispose(); diff --git a/jsb/jsb-tex-sprite-frame.js b/jsb/jsb-tex-sprite-frame.js index c6067960eb..31b259787d 100644 --- a/jsb/jsb-tex-sprite-frame.js +++ b/jsb/jsb-tex-sprite-frame.js @@ -74,10 +74,7 @@ cc.textureCache.cacheImage = function (key, texture) { }; cc.textureCache._getTextureForKey = cc.textureCache.getTextureForKey; cc.textureCache.getTextureForKey = function (key) { - var tex = this._getTextureForKey(key); - if (!tex) - tex = this._textures[key]; - return tex || null; + return this._getTextureForKey(key) || this._textures[key] || null; }; cc.textureCache._removeTextureForKey = cc.textureCache.removeTextureForKey; cc.textureCache.removeTextureForKey = function (key) { From 40c6f1829b1d898ebd0966291596805e3bc55bd4 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Mon, 11 Sep 2017 18:24:57 +0800 Subject: [PATCH 006/127] deprecate `@property(cc.Texture2D) value = null;` in class defined by using ES6 or TypeScript --- DebugInfos.js | 1 + cocos2d/core/assets/CCRawAsset.js | 7 ++ cocos2d/core/platform/CCClassDecorator.js | 17 ++-- cocos2d/core/platform/deserialize.js | 2 +- cocos2d/core/platform/preprocess-class.js | 5 +- cocos2d/core/platform/url.js | 16 ++-- .../unit-es5/test-migrating-raw-asset.js | 82 +++++++++++++++++++ 7 files changed, 115 insertions(+), 15 deletions(-) create mode 100644 test/qunit/unit-es5/test-migrating-raw-asset.js diff --git a/DebugInfos.js b/DebugInfos.js index e0f71d9ea8..de8705c82c 100644 --- a/DebugInfos.js +++ b/DebugInfos.js @@ -336,6 +336,7 @@ if (CC_DEBUG) { " set %s (value) {\n" + " ...\n" + " }", + "3656": "The default value of %s.%s must be an empty string. (changed since 1.7)", //getTypeChecker_4 //Prefab: 3700 "3700": "internal error: _prefab is undefined", //_doInstantiate "3701": "Failed to load prefab asset for node '%s'", //syncWithPrefab diff --git a/cocos2d/core/assets/CCRawAsset.js b/cocos2d/core/assets/CCRawAsset.js index b078669ae7..0201de9354 100644 --- a/cocos2d/core/assets/CCRawAsset.js +++ b/cocos2d/core/assets/CCRawAsset.js @@ -88,4 +88,11 @@ Object.defineProperty(cc.RawAsset, 'isRawAssetType', { // enumerable is false by default }); +// TODO - DELME after 2.0 +Object.defineProperty(cc.RawAsset, 'wasRawAssetType', { + value: function (ctor) { + return ctor === cc.Texture2D; + } +}); + module.exports = cc.RawAsset; diff --git a/cocos2d/core/platform/CCClassDecorator.js b/cocos2d/core/platform/CCClassDecorator.js index fd85c2f04a..a91d8021de 100644 --- a/cocos2d/core/platform/CCClassDecorator.js +++ b/cocos2d/core/platform/CCClassDecorator.js @@ -217,6 +217,13 @@ function genProperty (ctor, properties, propName, options, desc, cache) { cc.warnID(3654, JS.getClassName(ctor), propName); // prop.default = fullOptions.hasOwnProperty('default') ? fullOptions.default : undefined; } + if (cc.RawAsset.wasRawAssetType(prop.url) && + prop._short && + isDefaultValueSpecified && + defaultValue == null + ) { + cc.warnID(3656, JS.getClassName(ctor), propName); + } } prop.default = defaultValue; } @@ -355,8 +362,8 @@ var ccclass = checkCtorArgument(function (ctor, name) { * @property(cc.Vec2) * offsets = []; * - * @property(cc.Texture2D) - * texture = ""; + * @property(cc.SpriteFrame) + * frame = null; * } * * // above is equivalent to (上面的代码相当于): @@ -396,9 +403,9 @@ var ccclass = checkCtorArgument(function (ctor, name) { * type: cc.Vec2 * } * - * texture: { - * default: "", - * url: cc.Texture2D + * frame: { + * default: null, + * type: cc.SpriteFrame * }, * } * }); diff --git a/cocos2d/core/platform/deserialize.js b/cocos2d/core/platform/deserialize.js index 0289609d85..5afd6aeabe 100644 --- a/cocos2d/core/platform/deserialize.js +++ b/cocos2d/core/platform/deserialize.js @@ -77,7 +77,7 @@ Details.prototype.reset = function () { //this.rawObjList.length = 0; //this.rawPropList.length = 0; }; -if (CC_EDITOR) { +if (CC_EDITOR || CC_TEST) { Details.prototype.assignAssetsBy = function (getter) { for (var i = 0, len = this.uuidList.length; i < len; i++) { var uuid = this.uuidList[i]; diff --git a/cocos2d/core/platform/preprocess-class.js b/cocos2d/core/platform/preprocess-class.js index b30ad221fe..3fe086eef1 100644 --- a/cocos2d/core/platform/preprocess-class.js +++ b/cocos2d/core/platform/preprocess-class.js @@ -98,7 +98,7 @@ function checkUrl (val, className, propName, url) { if (typeof url !== 'function' || !cc.isChildClassOf(url, cc.RawAsset)) { return cc.errorID(5504, className, propName); } - if (cc.isChildClassOf(url, cc.Asset)) { + if (cc.isChildClassOf(url, cc.Asset) && !cc.RawAsset.wasRawAssetType(url)) { return cc.errorID(5505, className, propName, cc.js.getClassName(url)); } if (val.type) { @@ -168,6 +168,7 @@ function getBaseClassWherePropertyDefined_DEV (propName, cls) { } exports.getFullFormOfProperty = function (options) { + // TODO - deprecate `variable: cc.Texture2D,` from 1.7 var isLiteral = options && options.constructor === Object; if ( !isLiteral ) { if (Array.isArray(options) && options.length > 0) { @@ -179,7 +180,7 @@ exports.getFullFormOfProperty = function (options) { } else if (typeof options === 'function') { var type = options; - if (cc.RawAsset.isRawAssetType(type)) { + if (cc.RawAsset.isRawAssetType(type) || cc.RawAsset.wasRawAssetType(type)) { return { default: '', url: type, diff --git a/cocos2d/core/platform/url.js b/cocos2d/core/platform/url.js index e1ed218f9f..8a4f2a834d 100644 --- a/cocos2d/core/platform/url.js +++ b/cocos2d/core/platform/url.js @@ -49,13 +49,15 @@ cc.url = { _builtinRawAssets: '', normalize: function (url) { - if (url.charCodeAt(0) === 46 && url.charCodeAt(1) === 47) { - // strip './' - url = url.slice(2); - } - else if (url.charCodeAt(0) === 47) { - // strip '/' - url = url.slice(1); + if (url) { + if (url.charCodeAt(0) === 46 && url.charCodeAt(1) === 47) { + // strip './' + url = url.slice(2); + } + else if (url.charCodeAt(0) === 47) { + // strip '/' + url = url.slice(1); + } } return url; }, diff --git a/test/qunit/unit-es5/test-migrating-raw-asset.js b/test/qunit/unit-es5/test-migrating-raw-asset.js new file mode 100644 index 0000000000..c06c7245b9 --- /dev/null +++ b/test/qunit/unit-es5/test-migrating-raw-asset.js @@ -0,0 +1,82 @@ +if (TestEditorExtends) { + (function () { + + module('Migrating Raw Assets'); + + test('serialization if declared in the OLD way', function () { + // setup + var MyAsset = cc.Class({ + name: 'MyAsset', + properties: { + ref_full: { + url: cc.Texture2D, + default: "", + }, + ref_brief: cc.Texture2D, + } + }); + var asset = new MyAsset(); + asset.ref_full = 'foo'; + asset.ref_brief = 'foo'; + + // serialize + var restore = Editor.Utils.UuidCache.urlToUuid; + Editor.Utils.UuidCache.urlToUuid = function (url) { + return { + foo: '01', + }[url]; + }; + var serializedAsset = Editor.serialize(asset); + Editor.Utils.UuidCache.urlToUuid = restore; + + // deserialize + var deserializedAsset = cc.deserialize(serializedAsset, null, {createAssetRefs: true}); + + // test + ok(deserializedAsset.ref_full._uuid === '01', 'should support serialization if declared in full form'); + ok(deserializedAsset.ref_brief._uuid === '01', 'should support serialization if declared in brief form'); + + //teardown + cc.js.unregisterClass(MyAsset); + }); + + test('serialization if declared in the NEW way', function () { + // setup + var MyAsset = cc.Class({ + name: 'MyAsset', + properties: { + ref_full: { + type: cc.Texture2D, + default: null, + }, + // TODO - uncomment in 2.0 + // ref_brief: cc.Texture2D, + } + }); + var asset = new MyAsset(); + asset.ref_full = new cc.Texture2D(); + asset.ref_full._uuid = '01'; + // asset.ref_brief = asset.ref_full; + + // serialize + var restore = Editor.Utils.UuidCache.urlToUuid; + Editor.Utils.UuidCache.urlToUuid = function (url) { + return { + foo: '01', + }[url]; + }; + var serializedAsset = Editor.serialize(asset); + Editor.Utils.UuidCache.urlToUuid = restore; + + // deserialize + var deserializedAsset = cc.deserialize(serializedAsset, null, {createAssetRefs: true}); + + // test + ok(deserializedAsset.ref_full._uuid === '01', 'should support serialization if declared in full form'); + // ok(deserializedAsset.ref_brief._uuid === '01', 'should support serialization if declared in brief form'); + + //teardown + cc.js.unregisterClass(MyAsset); + }); + })(); +} From afabe198a9f287b4e4a27a49243c23a7e916f385 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 14 Sep 2017 00:45:16 +0800 Subject: [PATCH 007/127] support loading texture assets from packs --- cocos2d/core/assets/CCAsset.js | 21 ++++- cocos2d/core/load-pipeline/downloader.js | 4 +- cocos2d/core/load-pipeline/index.js | 1 - cocos2d/core/load-pipeline/pack-downloader.js | 72 +++++++++------ .../{json-unpacker.js => unpackers.js} | 52 +++++++++-- cocos2d/core/textures/CCTexture2D.js | 44 ++++++++- test/qunit/unit-es5/_init.js | 1 + test/qunit/unit-es5/test-json-pack-unpack.js | 65 ------------- test/qunit/unit-es5/test-pack-unpack.js | 91 +++++++++++++++++++ test/qunit/unit-es5/test-serialize.js | 4 +- test/qunit/unit-es5/test-texture.js | 58 ++++++++++++ 11 files changed, 301 insertions(+), 112 deletions(-) rename cocos2d/core/load-pipeline/{json-unpacker.js => unpackers.js} (61%) delete mode 100644 test/qunit/unit-es5/test-json-pack-unpack.js create mode 100644 test/qunit/unit-es5/test-pack-unpack.js create mode 100644 test/qunit/unit-es5/test-texture.js diff --git a/cocos2d/core/assets/CCAsset.js b/cocos2d/core/assets/CCAsset.js index 556dafe67e..13936f655c 100644 --- a/cocos2d/core/assets/CCAsset.js +++ b/cocos2d/core/assets/CCAsset.js @@ -24,6 +24,18 @@ ****************************************************************************/ var RawAsset = require('./CCRawAsset'); + +function joinRawUrl (base, filename) { + if (filename.charCodeAt(0) === 46) { // '.' + // imported in dir where json exist + return base + filename; + } + else { + // imported in an independent dir + return base + '/' + filename; + } +} + /** * !#en * Base class for handling assets used in Fireball. This class can be instantiate. @@ -60,7 +72,8 @@ cc.Asset = cc.Class({ get: function () { if (this._rawFiles) { if (cc.AssetLibrary) { - return cc.AssetLibrary.getLibUrlNoExt(this._uuid) + '/' + this._rawFiles[0]; + var base = cc.AssetLibrary.getLibUrlNoExt(this._uuid); + return joinRawUrl(base, this._rawFiles[0]); } else { cc.errorID(6400); @@ -84,9 +97,9 @@ cc.Asset = cc.Class({ get: function () { if (this._rawFiles) { if (cc.AssetLibrary) { - var dir = cc.AssetLibrary.getLibUrlNoExt(this._uuid) + '/'; + var base = cc.AssetLibrary.getLibUrlNoExt(this._uuid); return this._rawFiles.map(function (filename) { - return dir + filename; + return joinRawUrl(base, filename); }); } else { @@ -169,7 +182,7 @@ cc.Asset = cc.Class({ * @param {String[]} rawFiles * @private */ - _setRawFiles: CC_EDITOR && function (rawFiles) { + _setRawFiles: (CC_EDITOR || CC_TEST) && function (rawFiles) { this._rawFiles = rawFiles.length > 0 ? rawFiles : null; }, diff --git a/cocos2d/core/load-pipeline/downloader.js b/cocos2d/core/load-pipeline/downloader.js index af59c3b0bc..e6553591a5 100644 --- a/cocos2d/core/load-pipeline/downloader.js +++ b/cocos2d/core/load-pipeline/downloader.js @@ -188,9 +188,7 @@ function downloadUuid (item, callback) { if (result === undefined) { return this.extMap['json'](item, callback); } - else if (!!result) { - return result; - } + return result || undefined; } diff --git a/cocos2d/core/load-pipeline/index.js b/cocos2d/core/load-pipeline/index.js index 723436168d..eb05db7209 100644 --- a/cocos2d/core/load-pipeline/index.js +++ b/cocos2d/core/load-pipeline/index.js @@ -25,7 +25,6 @@ require('./downloader'); require('./loader'); -require('./json-unpacker'); require('./loading-items'); require('./pipeline'); diff --git a/cocos2d/core/load-pipeline/pack-downloader.js b/cocos2d/core/load-pipeline/pack-downloader.js index 4fd1c52b8a..739ba23f77 100644 --- a/cocos2d/core/load-pipeline/pack-downloader.js +++ b/cocos2d/core/load-pipeline/pack-downloader.js @@ -23,21 +23,9 @@ THE SOFTWARE. ****************************************************************************/ -var JsonUnpacker = require('./json-unpacker'); +var Unpackers = require('./unpackers'); var pushToMap = require('../utils/misc').pushToMap; -// {assetUuid: packUuid|[packUuid]} -// If value is array of packUuid, then the first one will be prioritized for download, -// so the smallest pack must be at the beginning of the array. -var uuidToPack = {}; - -// {packUuid: assetIndices} -var packIndices = {}; - -// {packUuid: JsonUnpacker} -// We have to cache all packs in global because for now there's no operation context in loader. -var globalUnpackers = {}; - // when more than one package contains the required asset, // choose to load from the package with the largest state value. var PackState = { @@ -47,6 +35,24 @@ var PackState = { Loaded: 3, }; +function UnpackerData () { + this.unpacker = null; + this.state = PackState.Invalid; +} + +// {assetUuid: packUuid|[packUuid]} +// If value is array of packUuid, then the first one will be prioritized for download, +// so the smallest pack must be at the beginning of the array. +var uuidToPack = {}; + +// {packUuid: assetIndices} +var packIndices = {}; + +// {packUuid: UnpackerData} +// We have to cache all packs in global because for now there's no operation context in loader. +var globalUnpackers = {}; + + function error (uuid, packUuid) { return new Error('Can not retrieve ' + uuid + ' from packer ' + packUuid); } @@ -83,15 +89,25 @@ module.exports = { }); }, - _doLoadNewPack: function (uuid, packUuid, packJson) { - var unpacker = globalUnpackers[packUuid]; + _doLoadNewPack: function (uuid, packUuid, packedJson) { + var unpackerData = globalUnpackers[packUuid]; // double check cache after load - if (unpacker.state !== PackState.Loaded) { - unpacker.read(packIndices[packUuid], packJson); - unpacker.state = PackState.Loaded; + if (unpackerData.state !== PackState.Loaded) { + // init unpacker + if (typeof packedJson === 'string') { + packedJson = JSON.parse(packedJson); + } + if (Array.isArray(packedJson)) { + unpackerData.unpacker = new Unpackers.JsonUnpacker(); + } + else if (packedJson.type === TextureUnpacker.ID) { + unpackerData.unpacker = new Unpackers.TextureUnpacker(); + } + unpackerData.unpacker.load(packIndices[packUuid], packedJson); + unpackerData.state = PackState.Loaded; } - return unpacker.retrieve(uuid); + return unpackerData.unpacker.retrieve(uuid); }, _selectLoadedPack: function (packUuids) { @@ -99,9 +115,9 @@ module.exports = { var existsPackUuid = ''; for (var i = 0; i < packUuids.length; i++) { var packUuid = packUuids[i]; - var unpacker = globalUnpackers[packUuid]; - if (unpacker) { - var state = unpacker.state; + var unpackerData = globalUnpackers[packUuid]; + if (unpackerData) { + var state = unpackerData.state; if (state === PackState.Loaded) { return packUuid; } @@ -132,10 +148,10 @@ module.exports = { packUuid = this._selectLoadedPack(packUuid); } - var unpacker = globalUnpackers[packUuid]; - if (unpacker && unpacker.state === PackState.Loaded) { + var unpackerData = globalUnpackers[packUuid]; + if (unpackerData && unpackerData.state === PackState.Loaded) { // ensure async - var json = unpacker.retrieve(uuid); + var json = unpackerData.unpacker.retrieve(uuid); if (json) { return json; } @@ -144,12 +160,12 @@ module.exports = { } } else { - if (!unpacker) { + if (!unpackerData) { if (!CC_TEST) { console.log('Create unpacker %s for %s', packUuid, uuid); } - unpacker = globalUnpackers[packUuid] = new JsonUnpacker(); - unpacker.state = PackState.Downloading; + unpackerData = globalUnpackers[packUuid] = new UnpackerData(); + unpackerData.state = PackState.Downloading; } this._loadNewPack(uuid, packUuid, callback); } diff --git a/cocos2d/core/load-pipeline/json-unpacker.js b/cocos2d/core/load-pipeline/unpackers.js similarity index 61% rename from cocos2d/core/load-pipeline/json-unpacker.js rename to cocos2d/core/load-pipeline/unpackers.js index 7ccc7220f9..3cacbd4e6d 100644 --- a/cocos2d/core/load-pipeline/json-unpacker.js +++ b/cocos2d/core/load-pipeline/unpackers.js @@ -23,23 +23,24 @@ THE SOFTWARE. ****************************************************************************/ +var Texture2D = require('../textures/CCTexture2D'); +var JS = require('../platform/js'); + function JsonUnpacker () { this.jsons = {}; - this.state = -1; } /** * @param {String[]} indices - * @param {String} data + * @param {Object[]} packedJson */ -JsonUnpacker.prototype.read = function (indices, data) { - var jsons = typeof data === 'string' ? JSON.parse(data) : data; - if (jsons.length !== indices.length) { +JsonUnpacker.prototype.load = function (indices, packedJson) { + if (packedJson.length !== indices.length) { cc.errorID(4915); } for (var i = 0; i < indices.length; i++) { var key = indices[i]; - var json = jsons[i]; + var json = packedJson[i]; this.jsons[key] = json; } }; @@ -48,8 +49,45 @@ JsonUnpacker.prototype.retrieve = function (key) { return this.jsons[key] || null; }; + +function TextureUnpacker () { + this.contents = {}; +} +TextureUnpacker.ID = JS._getClassId(Texture2D); + +/** + * @param {String[]} indices + * @param {Object[]} packedJson + */ +TextureUnpacker.prototype.load = function (indices, packedJson) { + var datas = packedJson.data.split('|'); + if (datas.length !== indices.length) { + cc.errorID(4915); + } + for (var i = 0; i < indices.length; i++) { + this.contents[indices[i]] = datas[i]; + } +}; + +TextureUnpacker.prototype.retrieve = function (key) { + var content = this.contents[key]; + if (content) { + return { + __type__: TextureUnpacker.ID, + content: content + }; + } + else { + return null; + } +}; + if (CC_TEST) { cc._Test.JsonUnpacker = JsonUnpacker; + cc._Test.TextureUnpacker = TextureUnpacker; } -module.exports = JsonUnpacker; +module.exports = { + JsonUnpacker, + TextureUnpacker, +}; diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 35b920801b..8344ba4d4a 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -76,7 +76,9 @@ var Texture2D = cc.Class({ mixins: [EventTarget], statics: { - WrapMode: WrapMode + WrapMode: WrapMode, + // predefined most common extnames + extnames: ['.png', '.jpg', '.jpeg', '.bmp', '.webp'] }, ctor: function () { @@ -86,7 +88,7 @@ var Texture2D = cc.Class({ * @type {String} * @readonly */ - this.url = null; + this.url = ""; this._textureLoaded = false; this._htmlElementObj = null; @@ -393,6 +395,44 @@ var Texture2D = cc.Class({ bitsPerPixelForFormat: function (format) { //support only in WebGl rendering mode return -1; + }, + + // SERIALIZATION + + // extname, + _serialize: (CC_EDITOR || CC_TEST) && function () { + var extId = ""; + if (this._rawFiles) { + // encode extname + var ext = cc.path.extname(this._rawFiles[0]); + if (ext) { + extId = Texture2D.extnames.indexOf(ext); + if (extId < 0) { + extId = ext; + } + } + } + return "" + extId; + }, + + _deserialize: function (data, handle) { + var fields = data.split(','); + // decode extname + var extIdStr = fields[0]; + if (extIdStr) { + const CHAR_CODE_0 = 48; // '0' + var extId = extIdStr.charCodeAt(0) - CHAR_CODE_0; + var ext = Texture2D.extnames[extId]; + this._setRawFiles([ext || extIdStr]); + + // preset uuid to get correct rawUrl + var loadingItem = handle.customEnv; + var uuid = loadingItem && loadingItem.uuid; + if (uuid) { + this._uuid = uuid; + this.url = this.rawUrl; + } + } } }); diff --git a/test/qunit/unit-es5/_init.js b/test/qunit/unit-es5/_init.js index 58dc51bf54..6371a665c9 100644 --- a/test/qunit/unit-es5/_init.js +++ b/test/qunit/unit-es5/_init.js @@ -169,6 +169,7 @@ function _resetGame (w, h) { id: 'test-canvas', debugMode: cc.DebugMode.INFO }); + cc.director.setDisplayStats(false); } else { var view = cc.view; diff --git a/test/qunit/unit-es5/test-json-pack-unpack.js b/test/qunit/unit-es5/test-json-pack-unpack.js deleted file mode 100644 index 878abd24a5..0000000000 --- a/test/qunit/unit-es5/test-json-pack-unpack.js +++ /dev/null @@ -1,65 +0,0 @@ -module('JSON packer/unpacker'); - -(function () { - - if (!TestEditorExtends) { - return; - } - - var KEY1 = 'amitabha'; - var JSON1 = { - __born__: 1985, - $$: 'Amoy' - }; - var KEY2 = 'hallelujah'; - var JSON2 = [{ - text: 'hallelujah\nalujah\\alujah...\uD83D\uDE02' - }]; - - test('pack nothing', function () { - var packer = new Editor.JsonPacker(); - var res = packer.pack(); - ok(res.indices, 'should pack empty indices'); - ok(res.data && typeof res.data === 'string', 'should pack empty data'); - }); - - test('unpack nothing', function () { - var unpacker = new cc._Test.JsonUnpacker(); - var res = unpacker.retrieve('non-exists key'); - ok(!res, 'chould not unpack if key is invalid'); - }); - - test('pack something', function () { - var packer = new Editor.JsonPacker(); - packer.add(KEY2, JSON2); - packer.add(KEY1, JSON1); - var res = packer.pack(); - - ok(res.indices.indexOf(KEY1) !== -1 && res.indices.indexOf(KEY2) !== -1, 'should generate index data when packing'); - - var unpacker = new cc._Test.JsonUnpacker(); - unpacker.read(res.indices, res.data); - deepEqual(unpacker.retrieve(KEY1), JSON1, 'should unpack JSON1'); - deepEqual(unpacker.retrieve(KEY2), JSON2, 'should unpack JSON2'); - }); - - //test('unpack speed', function () { - // var bigJson = Editor.serialize(new cc.Node()); - // var packer = new Editor.JsonPacker(); - // for (var i = 0; i < 100; ++i) { - // packer.add('' + i, bigJson); - // } - // var res = packer.pack(); - // - // console.time('unpack time'); - // - // var unpacker = new cc._Test.JsonUnpacker(); - // unpacker.read(res.indices, res.data); - // for (var i = 0; i < 100; ++i) { - // unpacker.retrieve('' + i); - // } - // - // console.timeEnd('unpack time'); - // ok(true); - //}); -})(); diff --git a/test/qunit/unit-es5/test-pack-unpack.js b/test/qunit/unit-es5/test-pack-unpack.js new file mode 100644 index 0000000000..267c555998 --- /dev/null +++ b/test/qunit/unit-es5/test-pack-unpack.js @@ -0,0 +1,91 @@ +(function () { + + module('JSON packer/unpacker'); + + test('unpack from empty package', function () { + var unpacker = new cc._Test.JsonUnpacker(); + var res = unpacker.retrieve('non-exists key'); + ok(!res, 'chould not unpack if key is invalid'); + }); + + if (!TestEditorExtends) { + return; + } + + test('pack nothing', function () { + var packer = new Editor.JsonPacker(); + var res = packer.pack(); + ok(res.indices, 'should pack empty indices'); + ok(res.data && typeof res.data === 'string', 'should pack empty data'); + }); + + var KEY1 = 'amitabha'; + var JSON1 = { + __born__: 1985, + $$: 'Amoy' + }; + var KEY2 = 'hallelujah'; + var JSON2 = [{ + text: 'hallelujah\nalujah\\alujah...\uD83D\uDE02' + }]; + + test('pack and unpack something', function () { + var packer = new Editor.JsonPacker(); + packer.add(KEY2, JSON2); + packer.add(KEY1, JSON1); + var res = packer.pack(); + + ok(res.indices.indexOf(KEY1) !== -1 && res.indices.indexOf(KEY2) !== -1, 'should generate index data when packing'); + + var unpacker = new cc._Test.JsonUnpacker(); + unpacker.load(res.indices, JSON.parse(res.data)); + deepEqual(unpacker.retrieve(KEY1), JSON1, 'should unpack JSON1'); + deepEqual(unpacker.retrieve(KEY2), JSON2, 'should unpack JSON2'); + }); +})(); + +(function () { + + module('Texture packer/unpacker'); + + test('unpack from empty package', function () { + var unpacker = new cc._Test.TextureUnpacker(); + var res = unpacker.retrieve('non-exists key'); + ok(!res, 'chould not unpack if key is invalid'); + }); + + if (!TestEditorExtends) { + return; + } + + test('pack nothing', function () { + var packer = new Editor.TextureAssetPacker(); + var res = packer.pack(); + ok(res.indices, 'should pack empty indices'); + ok(res.data && typeof res.data === 'string', 'should pack empty data'); + }); + + var tex1 = new cc.Texture2D(); + tex1._uuid = '555AC'; + tex1._setRawFiles(['.png']); + var tex1Json = Editor.serialize(tex1, { stringify: false }); + + var tex2 = new cc.Texture2D(); + tex2._uuid = '08T18'; + tex2._setRawFiles(['.jare']); + var tex2Json = Editor.serialize(tex2, { stringify: false }); + + test('pack and unpack something', function () { + var packer = new Editor.TextureAssetPacker(); + packer.add(tex1._uuid, tex1Json); + packer.add(tex2._uuid, tex2Json); + var res = packer.pack(); + + ok(res.indices.indexOf(tex1._uuid) !== -1 && res.indices.indexOf(tex2._uuid) !== -1, 'should generate index data when packing'); + + var unpacker = new cc._Test.TextureUnpacker(); + unpacker.load(res.indices, JSON.parse(res.data)); + deepEqual(unpacker.retrieve(tex1._uuid), tex1Json, 'should unpack tex1'); + deepEqual(unpacker.retrieve(tex2._uuid), tex2Json, 'should unpack tex2'); + }); +})(); diff --git a/test/qunit/unit-es5/test-serialize.js b/test/qunit/unit-es5/test-serialize.js index 1c418ff9bd..9ae5fcb376 100644 --- a/test/qunit/unit-es5/test-serialize.js +++ b/test/qunit/unit-es5/test-serialize.js @@ -2,10 +2,10 @@ largeModule('Serialize'); - var match = function (obj, expect, info) { + function match (obj, expect, info) { deepEqual(JSON.parse(Editor.serialize(obj)), expect, info); //deepEqual(Editor.serialize(obj, {stringify: false}), expect, info); - }; + } test('basic test', function() { match({}, {}, 'smoke test1'); diff --git a/test/qunit/unit-es5/test-texture.js b/test/qunit/unit-es5/test-texture.js new file mode 100644 index 0000000000..f529082091 --- /dev/null +++ b/test/qunit/unit-es5/test-texture.js @@ -0,0 +1,58 @@ +(function () { + + module('Texture'); + + if (TestEditorExtends) { + + function serializedAs (obj, expect, info) { + deepEqual(JSON.parse(Editor.serialize(obj)), expect, info); + } + + test('rawUrl', function () { + var tex = new cc.Texture2D(); + tex._uuid = '555AC'; + tex._setRawFiles(['.png']); + ok(tex.rawUrl.endsWith('.png'), 'rawUrl should contains extname'); + }); + + test('(de)serialize empty texture', function () { + var tex = new cc.Texture2D(); + var expected = { + __type__: 'cc.Texture2D', + content: '' + }; + serializedAs(tex, expected, 'should be serialized'); + + var deserialized = cc.deserialize(expected); + strictEqual(deserialized.rawUrl, '', 'rawUrl should be empty string by default'); + strictEqual(deserialized.url, '', 'url should be empty string by default'); + }); + + function testSerializationOfUrl (extname) { + test('(de)serialize ' + extname + ' texture asset', function () { + var tex = new cc.Texture2D(); + + tex._uuid = '555AC'; + tex._setRawFiles(['.png']); + tex.url = tex.rawUrl; + ok(tex.url.endsWith('.png'), 'url should contains extname'); + + var expected = { + __type__: 'cc.Texture2D', + content: '0' + }; + serializedAs(tex, expected, 'should be serialized'); + + var deserialized = cc.deserialize(expected, null, { + customEnv: { uuid: tex._uuid } + }); + deserialized._uuid = tex._uuid; + strictEqual(deserialized.rawUrl, tex.rawUrl, 'rawUrl should be deserialized'); + strictEqual(deserialized.url, tex.url, 'url should be deserialized'); + }); + } + testSerializationOfUrl('.png'); + testSerializationOfUrl('.jareguo'); + } + +})(); \ No newline at end of file From 301f4e709ad7679d9e9f4f1e7574e9e40f6bc62f Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Fri, 15 Sep 2017 00:42:50 +0800 Subject: [PATCH 008/127] refactoring API of cc.Asset: rawUrl -> nativeUrl, _rawFile -> _native, _setRawFile(s) -> _setRawAsset, rawType -> _nativeObject --- DebugInfos.js | 4 +- cocos2d/core/assets/CCAsset.js | 112 +++++++--------- cocos2d/core/assets/CCFont.js | 4 +- cocos2d/core/assets/CCTTFFont.js | 10 +- cocos2d/core/components/CCRichText.js | 2 +- cocos2d/core/label/CCSGLabel.js | 6 +- cocos2d/core/load-pipeline/CCLoader.js | 15 +-- cocos2d/core/load-pipeline/uuid-loader.js | 23 ++-- cocos2d/core/platform/CCClass.js | 15 --- cocos2d/core/platform/attribute.js | 40 ------ cocos2d/core/platform/deserialize.js | 123 +++++++----------- cocos2d/core/platform/preprocess-class.js | 1 - cocos2d/core/textures/CCTexture2D.js | 12 +- extensions/spine/Skeleton.js | 2 +- extensions/spine/SkeletonData.js | 3 +- extensions/spine/editor/spine-meta.js | 4 +- jsb/jsb-label.js | 4 +- test/fixtures/library/22/223459.json | 2 +- test/qunit/assets/library/65/6545543 | 2 +- .../library/deferred-loading/12/1232218.json | 2 +- .../library/deferred-loading/74/748321.json | 2 +- test/qunit/unit-es5/test-loader.js | 4 +- test/qunit/unit-es5/test-pack-unpack.js | 4 +- test/qunit/unit-es5/test-serialize.js | 2 +- test/qunit/unit-es5/test-texture.js | 14 +- 25 files changed, 150 insertions(+), 262 deletions(-) diff --git a/DebugInfos.js b/DebugInfos.js index de8705c82c..a4b624d828 100644 --- a/DebugInfos.js +++ b/DebugInfos.js @@ -508,8 +508,8 @@ if (CC_DEBUG) { "6301": "Stencil buffer is not enabled.", //initStencilBits "6302": "Nesting more than %d stencils is not supported. Everything will be drawn without stencil for this node and its children.", //visit //CCAsset: 6400 - "6400": "asset.url is not usable in core process", //rawUrl - "6401": "asset.urls is not usable in core process", //rawUrls + "6400": "asset.rawUrl is not usable in core process", //rawUrl + "6401": "asset.rawUrls is not usable in core process", //rawUrls "6402": "AssetLibrary has already been initialized!", //AssetLibrary.init //Widget: 6500 "6500": "Widget target must be one of the parent nodes of it", //visitNode diff --git a/cocos2d/core/assets/CCAsset.js b/cocos2d/core/assets/CCAsset.js index 13936f655c..6bf2177692 100644 --- a/cocos2d/core/assets/CCAsset.js +++ b/cocos2d/core/assets/CCAsset.js @@ -25,27 +25,16 @@ var RawAsset = require('./CCRawAsset'); -function joinRawUrl (base, filename) { - if (filename.charCodeAt(0) === 46) { // '.' - // imported in dir where json exist - return base + filename; - } - else { - // imported in an independent dir - return base + '/' + filename; - } -} - /** * !#en - * Base class for handling assets used in Fireball. This class can be instantiate. + * Base class for handling assets used in Creator.
* * You may want to override:
* - createNode
* - cc.Object._serialize
* - cc.Object._deserialize
* !#zh - * 资源基类,该类可以被实例化。
+ * Creator 中的资源基类。
* * 您可能需要重写:
* - createNode
@@ -64,16 +53,24 @@ cc.Asset = cc.Class({ * Returns the url of this asset's first raw file, if none of rawFile exists, * it will returns an empty string. * !#zh 返回该资源的原始文件的 URL,如果不支持 RAW 文件,它将返回一个空字符串。 - * @property rawUrl + * @property nativeUrl * @type {String} * @readOnly */ - rawUrl: { + nativeUrl: { get: function () { - if (this._rawFiles) { + if (this._native) { if (cc.AssetLibrary) { var base = cc.AssetLibrary.getLibUrlNoExt(this._uuid); - return joinRawUrl(base, this._rawFiles[0]); + var name = this._native; + if (name.charCodeAt(0) === 46) { // '.' + // imported in dir where json exist + return base + name; + } + else { + // imported in an independent dir + return base + '/' + name; + } } else { cc.errorID(6400); @@ -84,45 +81,31 @@ cc.Asset = cc.Class({ visible: false }, - /** - * !#en - * Returns the url of this asset's raw files, if none of rawFile exists, - * it will returns an empty array. - * !#zh 返回该资源的原文件的 URL 数组,如果不支持 RAW 文件,它将返回一个空数组。 - * @property rawUrls - * @type {String[]} - * @readOnly - */ - rawUrls: { - get: function () { - if (this._rawFiles) { - if (cc.AssetLibrary) { - var base = cc.AssetLibrary.getLibUrlNoExt(this._uuid); - return this._rawFiles.map(function (filename) { - return joinRawUrl(base, filename); - }); - } - else { - cc.errorID(6401); - } - } - return []; - }, - visible: false - }, - /** * 在 lite 版的 Fireball 里,raw asset 并不仅仅是在 properties 里声明了 rawType 才有, * 而是每个 asset 都能指定自己的 raw file url。这些 url 就存在 _rawFiles 字段中。 * AssetLibrary 并不会帮你加载这些 url,除非你声明了 rawType。 * 在 Creator 里,_rawFiles 保留了下来,为了复用 cocos 引擎原有实现,直接用 _rawFiles 来加载 Asset 在 import 之前的源文件。 * - * @property _rawFiles - * @type {String[]} + * @property _native + * @type {String} + * @default "" + * @private + */ + _native: "", + + /** + * The underlying native object of this asset if one is available. + * The object can be used to access additional details or functionality releated to the asset. + * The object will be initialized by the loader if `_native` is available. + * @property {Object} _nativeObject * @default null * @private */ - _rawFiles: null + _nativeObject: { + default: null, + serializable: false + }, }, statics: { @@ -147,7 +130,17 @@ cc.Asset = cc.Class({ * @default false * @static */ - preventDeferredLoadDependents: false + preventDeferredLoadDependents: false, + + /** + * !#en Indicates whether its native object should be preloaded from native url. + * !#zh 禁止预加载原生对象。 + * + * @property {Boolean} preventPreloadNativeObject + * @default false + * @static + */ + preventPreloadNativeObject: false }, /** @@ -168,6 +161,7 @@ cc.Asset = cc.Class({ * !#zh * 使用该资源在场景中创建一个新节点。
* 如果这类资源没有相应的节点类型,该方法应该是空的。 + * * @method createNode * @param {Function} callback * @param {String} callback.error - null or the error info @@ -176,25 +170,15 @@ cc.Asset = cc.Class({ createNode: null, /** - * Set raw file names for this asset. + * Set native file name for this asset. * - * @method _setRawFiles - * @param {String[]} rawFiles + * @method _setRawAsset + * @param {String} filename * @private */ - _setRawFiles: (CC_EDITOR || CC_TEST) && function (rawFiles) { - this._rawFiles = rawFiles.length > 0 ? rawFiles : null; - }, - - /** - * Preload raw files when loading scene. - * - * @method _preloadRawFiles - * @param {Function} callback - * @param {Error} callback.error - * @private - */ - _preloadRawFiles: null, + _setRawAsset: (CC_EDITOR || CC_TEST) && function (filename) { + this._native = filename || ""; + } }); module.exports = cc.Asset; diff --git a/cocos2d/core/assets/CCFont.js b/cocos2d/core/assets/CCFont.js index a845289cc6..b8c0d747ed 100644 --- a/cocos2d/core/assets/CCFont.js +++ b/cocos2d/core/assets/CCFont.js @@ -31,12 +31,10 @@ * !#zh 字体资源类。 * @class Font * @extends Asset - * */ var Font = cc.Class({ name: 'cc.Font', extends: cc.Asset }); -cc.Font = Font; -module.exports = Font; +cc.Font = module.exports = Font; diff --git a/cocos2d/core/assets/CCTTFFont.js b/cocos2d/core/assets/CCTTFFont.js index 7e314eda3d..c496679846 100644 --- a/cocos2d/core/assets/CCTTFFont.js +++ b/cocos2d/core/assets/CCTTFFont.js @@ -30,13 +30,15 @@ * !#en Class for TTFFont handling. * !#zh TTF 字体资源类。 * @class TTFFont - * @extends Asset + * @extends Font * */ var TTFFont = cc.Class({ name: 'cc.TTFFont', - extends: cc.Font + extends: cc.Font, + statics: { + preventPreloadNativeObject: true, + }, }); -cc.TTFFont = TTFFont; -module.exports = TTFFont; +cc.TTFFont = module.exports = TTFFont; diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index 05c8592d78..488db96d74 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -247,7 +247,7 @@ var RichText = cc.Class({ _getFontRawUrl: function() { var isAsset = this.font instanceof cc.TTFFont; - var fntRawUrl = isAsset ? this.font.rawUrl : ''; + var fntRawUrl = isAsset ? this.font.nativeUrl : ''; return fntRawUrl; }, diff --git a/cocos2d/core/label/CCSGLabel.js b/cocos2d/core/label/CCSGLabel.js index a9042a403d..ea7c938b0c 100644 --- a/cocos2d/core/label/CCSGLabel.js +++ b/cocos2d/core/label/CCSGLabel.js @@ -146,7 +146,7 @@ _ccsg.Label = _ccsg.Node.extend({ ctor: function(string, fontAsset) { EventTarget.call(this); var isAsset = fontAsset instanceof cc.Font; - var fontHandle = isAsset ? fontAsset.rawUrl : ''; + var fontHandle = isAsset ? fontAsset.nativeUrl : ''; this._fontHandle = fontHandle; if (typeof string !== 'string') { @@ -468,7 +468,7 @@ _ccsg.Label = _ccsg.Node.extend({ this.setFontFamily(''); return; } - var fontHandle = isAsset ? fontAsset.rawUrl : ''; + var fontHandle = isAsset ? fontAsset.nativeUrl : ''; var extName = cc.path.extname(fontHandle); this._resetBMFont(); @@ -1272,7 +1272,7 @@ _ccsg.Label.pool.get = function (string, fontAsset) { var label = this._get(); if (label) { var isAsset = fontAsset instanceof cc.Font; - var fontHandle = isAsset ? fontAsset.rawUrl : ''; + var fontHandle = isAsset ? fontAsset.nativeUrl : ''; label._fontHandle = fontHandle; if (typeof string !== 'string') { string = '' + string; diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js index 7cc9be0305..2a97fe32b0 100644 --- a/cocos2d/core/load-pipeline/CCLoader.js +++ b/cocos2d/core/load-pipeline/CCLoader.js @@ -765,19 +765,12 @@ proto.release = function (asset) { var removed = this.removeItem(id); asset = item.content; // TODO: AUDIO - if (asset instanceof cc.Asset) { - if (CC_JSB && asset instanceof cc.SpriteFrame && removed) { - // for the "Temporary solution" in deserialize.js - asset.release(); - } - var urls = asset.rawUrls; - for (let i = 0; i < urls.length; i++) { - this.release(urls[i]); - } - } - else if (asset instanceof cc.Texture2D) { + if (asset instanceof cc.Texture2D) { cc.textureCache.removeTextureForKey(item.url); } + else if (asset instanceof cc.Asset && asset.nativeUrl) { + this.release(asset.nativeUrl); + } if (CC_DEBUG && removed) { this._releasedAssetChecker_DEBUG.setReleased(item, id); } diff --git a/cocos2d/core/load-pipeline/uuid-loader.js b/cocos2d/core/load-pipeline/uuid-loader.js index 8eab54ba15..cff9ad58bb 100644 --- a/cocos2d/core/load-pipeline/uuid-loader.js +++ b/cocos2d/core/load-pipeline/uuid-loader.js @@ -85,21 +85,14 @@ function loadDepends (pipeline, item, asset, tdInfo, deferredLoadRawAssetsInRunt }; } } - // declare raw - if (tdInfo.rawProp) { - objList.push(asset); - propList.push(tdInfo.rawProp); - depends.push(item.url); - } - // preload raw files - if (asset._preloadRawFiles) { - var finalCallback = callback; - callback = function () { - asset._preloadRawFiles(function (err) { - finalCallback(err || null, asset); - }); - }; - } + + // // declare raw + // if (tdInfo.rawProp) { + // objList.push(asset); + // propList.push(tdInfo.rawProp); + // depends.push(item.url); + // } + // fast path if (depends.length === 0) { cc.deserialize.Details.pool.put(tdInfo); diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 4118d0cc5b..e796e3075b 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -1065,21 +1065,6 @@ function parseAttributes (cls, attrs, className, propName, usedInGetter) { } } - // if (attrs.rawType) { - // if (CC_DEV && usedInGetter) { - // cc.errorID(3613, "rawType", name, propName); - // } - // else { - // var val = attrs.rawType; - // if (typeof val === 'string') { - // result.push(Attr.RawType(val)); - // } - // else if (CC_DEV) { - // cc.error(ERR_Type, "rawType", className, propName, 'string'); - // } - // } - // } - if (attrs.editorOnly) { if (CC_DEV && usedInGetter) { cc.errorID(3613, "editorOnly", name, propName); diff --git a/cocos2d/core/platform/attribute.js b/cocos2d/core/platform/attribute.js index d4a809aa71..0120d36f5c 100644 --- a/cocos2d/core/platform/attribute.js +++ b/cocos2d/core/platform/attribute.js @@ -339,45 +339,6 @@ function ObjectType (typeCtor) { }; } -// function RawType (typename) { -// var NEED_EXT_TYPES = ['image', 'json', 'text', 'audio']; // the types need to specify exact extname -// return { -// // type: 'raw', -// rawType: typename, -// serializable: false, -// // hideInInspector: true, - -// _onAfterProp: function (constructor, mainPropName) { -// // check raw object -// var checked = !CC_DEV || (function checkRawType(constructor) { -// if (! cc.isChildClassOf(constructor, cc.Asset)) { -// cc.errorID(3630); -// return false; -// } -// var attrs = getClassAttrs(constructor); -// var found = false; -// for (var p = 0; p < constructor.__props__.length; p++) { -// var propName = constructor.__props__[p]; -// var rawType = attrs[propName + DELIMETER + 'rawType']; -// if (rawType) { -// var containsUppercase = (rawType.toLowerCase() !== rawType); -// if (containsUppercase) { -// cc.errorID(3631); -// return false; -// } -// if (found) { -// cc.errorID(3632); -// return false; -// } -// found = true; -// } -// } -// return true; -// })(constructor); -// } -// }; -// } - module.exports = { attr: attr, getClassAttrs: getClassAttrs, @@ -386,6 +347,5 @@ module.exports = { DELIMETER: DELIMETER, getTypeChecker: getTypeChecker, ObjectType: ObjectType, - // RawType: RawType, ScriptUuid: {}, // the value will be represented as a uuid string }; diff --git a/cocos2d/core/platform/deserialize.js b/cocos2d/core/platform/deserialize.js index 5afd6aeabe..46a5482ab9 100644 --- a/cocos2d/core/platform/deserialize.js +++ b/cocos2d/core/platform/deserialize.js @@ -59,12 +59,6 @@ var Details = function () { * @property {String[]} uuidPropList */ this.uuidPropList = []; - - /** - * the corresponding field name which referenced to the raw object - * @property {String} rawProp - */ - this.rawProp = ''; }; /** * @method reset @@ -73,9 +67,6 @@ Details.prototype.reset = function () { this.uuidList.length = 0; this.uuidObjList.length = 0; this.uuidPropList.length = 0; - this.rawProp = ''; - //this.rawObjList.length = 0; - //this.rawPropList.length = 0; }; if (CC_EDITOR || CC_TEST) { Details.prototype.assignAssetsBy = function (getter) { @@ -521,7 +512,6 @@ var _Deserializer = (function () { } function compileDeserialize (self, klass) { - var RAW_TYPE = Attr.DELIMETER + 'rawType'; var EDITOR_ONLY = Attr.DELIMETER + 'editorOnly'; var SERIALIZABLE = Attr.DELIMETER + 'serializable'; var DEFAULT = Attr.DELIMETER + 'default'; @@ -538,79 +528,62 @@ var _Deserializer = (function () { // sources.push('var vb,vn,vs,vo,vu,vf;'); // boolean, number, string, object, undefined, function for (var p = 0; p < props.length; p++) { var propName = props[p]; - var propNameLiteralToSet; - var rawType = attrs[propName + RAW_TYPE]; - if (!rawType) { - if ((CC_PREVIEW || (CC_EDITOR && self._ignoreEditorOnly)) && attrs[propName + EDITOR_ONLY]) { - var mayUsedInPersistRoot = (propName === '_id' && cc.isChildClassOf(klass, cc.Node)); - if (!mayUsedInPersistRoot) { - continue; // skip editor only if in preview - } - } - if (attrs[propName + SERIALIZABLE] === false) { - continue; // skip nonSerialized + if ((CC_PREVIEW || (CC_EDITOR && self._ignoreEditorOnly)) && attrs[propName + EDITOR_ONLY]) { + var mayUsedInPersistRoot = (propName === '_id' && cc.isChildClassOf(klass, cc.Node)); + if (!mayUsedInPersistRoot) { + continue; // skip editor only if in preview } + } + if (attrs[propName + SERIALIZABLE] === false) { + continue; // skip nonSerialized + } - var accessorToSet; - if (CCClass.IDENTIFIER_RE.test(propName)) { - propNameLiteralToSet = '"' + propName + '"'; - accessorToSet = '.' + propName; - } - else { - propNameLiteralToSet = CCClass.escapeForJS(propName); - accessorToSet = '[' + propNameLiteralToSet + ']'; - } - - var accessorToGet = accessorToSet; - if (attrs[propName + FORMERLY_SERIALIZED_AS]) { - var propNameToRead = attrs[propName + FORMERLY_SERIALIZED_AS]; - if (CCClass.IDENTIFIER_RE.test(propNameToRead)) { - accessorToGet = '.' + propNameToRead; - } - else { - accessorToGet = '[' + CCClass.escapeForJS(propNameToRead) + ']'; - } - } - - sources.push('prop=d' + accessorToGet + ';'); - sources.push(`if(typeof ${CC_JSB ? '(prop)' : 'prop'}!=="undefined"){`); - - // function undefined object(null) string boolean number - var defaultValue = CCClass.getDefault(attrs[propName + DEFAULT]); - if (fastMode) { - var defaultType = typeof defaultValue; - var isPrimitiveType = (defaultType === 'string' && !attrs[propName + SAVE_URL_AS_ASSET]) || - defaultType === 'number' || - defaultType === 'boolean'; - if (isPrimitiveType) { - sources.push(`o${accessorToSet}=prop;`); - } - else { - compileObjectType(sources, defaultValue, accessorToSet, propNameLiteralToSet, true); - } - } - else { - sources.push(`if(typeof ${CC_JSB ? '(prop)' : 'prop'}!=="object"){` + - 'o' + accessorToSet + '=prop;' + - '}else{'); - compileObjectType(sources, defaultValue, accessorToSet, propNameLiteralToSet, false); - sources.push('}'); - } - sources.push('}'); + var accessorToSet, propNameLiteralToSet; + if (CCClass.IDENTIFIER_RE.test(propName)) { + propNameLiteralToSet = '"' + propName + '"'; + accessorToSet = '.' + propName; } else { - if (CCClass.IDENTIFIER_RE.test(propName)) { - propNameLiteralToSet = '"' + propName + '"'; + propNameLiteralToSet = CCClass.escapeForJS(propName); + accessorToSet = '[' + propNameLiteralToSet + ']'; + } + + var accessorToGet = accessorToSet; + if (attrs[propName + FORMERLY_SERIALIZED_AS]) { + var propNameToRead = attrs[propName + FORMERLY_SERIALIZED_AS]; + if (CCClass.IDENTIFIER_RE.test(propNameToRead)) { + accessorToGet = '.' + propNameToRead; } else { - propNameLiteralToSet = CCClass.escapeForJS(propName); + accessorToGet = '[' + CCClass.escapeForJS(propNameToRead) + ']'; } - // always load raw objects even if property not serialized - // 这里假定每个asset都有uuid,每个json只能包含一个asset,只能包含一个rawProp - sources.push('if(s.result.rawProp)\n' + - 'cc.error("not support multi raw object in a file");'); - sources.push('s.result.rawProp=' + propNameLiteralToSet + ';'); } + + sources.push('prop=d' + accessorToGet + ';'); + sources.push(`if(typeof ${CC_JSB ? '(prop)' : 'prop'}!=="undefined"){`); + + // function undefined object(null) string boolean number + var defaultValue = CCClass.getDefault(attrs[propName + DEFAULT]); + if (fastMode) { + var defaultType = typeof defaultValue; + var isPrimitiveType = (defaultType === 'string' && !attrs[propName + SAVE_URL_AS_ASSET]) || + defaultType === 'number' || + defaultType === 'boolean'; + if (isPrimitiveType) { + sources.push(`o${accessorToSet}=prop;`); + } + else { + compileObjectType(sources, defaultValue, accessorToSet, propNameLiteralToSet, true); + } + } + else { + sources.push(`if(typeof ${CC_JSB ? '(prop)' : 'prop'}!=="object"){` + + 'o' + accessorToSet + '=prop;' + + '}else{'); + compileObjectType(sources, defaultValue, accessorToSet, propNameLiteralToSet, false); + sources.push('}'); + } + sources.push('}'); } if (props[props.length - 1] === '_$erialized') { // deep copy original serialized data diff --git a/cocos2d/core/platform/preprocess-class.js b/cocos2d/core/platform/preprocess-class.js index 3fe086eef1..796e5af344 100644 --- a/cocos2d/core/platform/preprocess-class.js +++ b/cocos2d/core/platform/preprocess-class.js @@ -32,7 +32,6 @@ var SerializableAttrs = { default: {}, serializable: {}, editorOnly: {}, - rawType: {}, }; var TYPO_TO_CORRECT_DEV = CC_DEV && { diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 8344ba4d4a..f651481fcf 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -402,9 +402,9 @@ var Texture2D = cc.Class({ // extname, _serialize: (CC_EDITOR || CC_TEST) && function () { var extId = ""; - if (this._rawFiles) { + if (this._native) { // encode extname - var ext = cc.path.extname(this._rawFiles[0]); + var ext = cc.path.extname(this._native); if (ext) { extId = Texture2D.extnames.indexOf(ext); if (extId < 0) { @@ -423,17 +423,17 @@ var Texture2D = cc.Class({ const CHAR_CODE_0 = 48; // '0' var extId = extIdStr.charCodeAt(0) - CHAR_CODE_0; var ext = Texture2D.extnames[extId]; - this._setRawFiles([ext || extIdStr]); + this._setRawAsset(ext || extIdStr); - // preset uuid to get correct rawUrl + // preset uuid to get correct nativeUrl var loadingItem = handle.customEnv; var uuid = loadingItem && loadingItem.uuid; if (uuid) { this._uuid = uuid; - this.url = this.rawUrl; + this.url = this.nativeUrl; } } - } + }, }); /** diff --git a/extensions/spine/Skeleton.js b/extensions/spine/Skeleton.js index 91f1d1a726..17fdec539f 100644 --- a/extensions/spine/Skeleton.js +++ b/extensions/spine/Skeleton.js @@ -409,7 +409,7 @@ sp.Skeleton = cc.Class({ cc.errorID(7504); return null; } - var jsonFile = this.skeletonData.rawUrl; + var jsonFile = this.skeletonData.nativeUrl; var atlasFile = this.skeletonData.atlasUrl; if (atlasFile) { if (typeof atlasFile !== 'string') { diff --git a/extensions/spine/SkeletonData.js b/extensions/spine/SkeletonData.js index 0af8718880..f5e1dcc646 100644 --- a/extensions/spine/SkeletonData.js +++ b/extensions/spine/SkeletonData.js @@ -148,7 +148,8 @@ var SkeletonData = cc.Class({ }, statics: { - preventDeferredLoadDependents: true + preventDeferredLoadDependents: true, + preventPreloadNativeObject: true, }, // PUBLIC diff --git a/extensions/spine/editor/spine-meta.js b/extensions/spine/editor/spine-meta.js index b70f7a260b..34153fcce9 100644 --- a/extensions/spine/editor/spine-meta.js +++ b/extensions/spine/editor/spine-meta.js @@ -104,7 +104,7 @@ class SpineMeta extends CustomAssetMeta { //this.textures[0] = value; } - static version () { return '1.0.2'; } + static version () { return '1.1.0'; } static defaultType () { return 'spine'; } @@ -197,7 +197,7 @@ class SpineMeta extends CustomAssetMeta { db.mkdirForAsset(this.uuid); var rawJsonPath = Path.join(db._uuidToImportPathNoExt(this.uuid), RAW_SKELETON_FILE); Fs.copySync(fspath, rawJsonPath); - asset._setRawFiles([RAW_SKELETON_FILE]); + asset._setRawAsset(RAW_SKELETON_FILE); this.atlas = atlasUuid; // save for dest() diff --git a/jsb/jsb-label.js b/jsb/jsb-label.js index b3ccac2136..15c2a4a155 100644 --- a/jsb/jsb-label.js +++ b/jsb/jsb-label.js @@ -157,7 +157,7 @@ jsbLabel.prototype.setFontAsset = function (fontAsset) { this.setFontFamily('Arial'); return; } - var fontHandle = isAsset ? fontAsset.rawUrl : ''; + var fontHandle = isAsset ? fontAsset.nativeUrl : ''; var extName = cc.path.extname(fontHandle); if (extName === '.ttf') { @@ -300,6 +300,6 @@ cc.Label.pool.get = function (string, fontAsset, spriteFrame, fontSize) { if (!isAsset) { return new _ccsg.Label(string, null, null, fontSize); } - var fontHandle = isAsset ? fontAsset.rawUrl : ''; + var fontHandle = isAsset ? fontAsset.nativeUrl : ''; return new _ccsg.Label(string, fontHandle, spriteFrame, fontSize); }; diff --git a/test/fixtures/library/22/223459.json b/test/fixtures/library/22/223459.json index 3f9907c032..5722cc771b 100644 --- a/test/fixtures/library/22/223459.json +++ b/test/fixtures/library/22/223459.json @@ -1,5 +1,5 @@ { "__type__": "cc.TTFFont", - "_rawFiles": ["1.ttf"], + "_native": "1.ttf", "fontFamily": "Abberancy" } diff --git a/test/qunit/assets/library/65/6545543 b/test/qunit/assets/library/65/6545543 index 1f27113f6e..8764392690 100644 --- a/test/qunit/assets/library/65/6545543 +++ b/test/qunit/assets/library/65/6545543 @@ -2,5 +2,5 @@ "__type__": "TestTexture", "width": 512, "height": 512, - "_rawFiles": ["png"] + "_native": "png" } \ No newline at end of file diff --git a/test/qunit/assets/library/deferred-loading/12/1232218.json b/test/qunit/assets/library/deferred-loading/12/1232218.json index c518a8d336..2008296b59 100644 --- a/test/qunit/assets/library/deferred-loading/12/1232218.json +++ b/test/qunit/assets/library/deferred-loading/12/1232218.json @@ -4,7 +4,7 @@ "texture": { "__uuid__": "748321" }, - "_rawFiles": ["JareWontTellYou"], + "_native": "JareWontTellYou", "rotated": false, "trim": false, "trimThreshold": 1, diff --git a/test/qunit/assets/library/deferred-loading/74/748321.json b/test/qunit/assets/library/deferred-loading/74/748321.json index 765e48411c..461e630732 100644 --- a/test/qunit/assets/library/deferred-loading/74/748321.json +++ b/test/qunit/assets/library/deferred-loading/74/748321.json @@ -1,7 +1,7 @@ { "__type__": "Test.TextureNeedsDeferredLoad", "name": "", - "_rawFiles": ["YouKnowEverything"], + "_native": "YouKnowEverything", "width": 321, "height": 123 } \ No newline at end of file diff --git a/test/qunit/unit-es5/test-loader.js b/test/qunit/unit-es5/test-loader.js index 45fa34c6ed..7edb50be3c 100644 --- a/test/qunit/unit-es5/test-loader.js +++ b/test/qunit/unit-es5/test-loader.js @@ -20,7 +20,7 @@ asyncTest('Load', function () { strictEqual(item.content.width, 89, 'should give correct js object as result of JSON'); } else if (item.id === json2) { - strictEqual(item.content._rawFiles[0], 'YouKnowEverything', 'should give correct js object as result of JSON'); + strictEqual(item.content._native, 'YouKnowEverything', 'should give correct js object as result of JSON'); } else { ok(false, 'should not load an unknown url'); @@ -108,7 +108,7 @@ asyncTest('Load with dependencies', function () { strictEqual(item.content.__type__, 'TestTexture', 'should give correct js object as result of deps type'); } else if (item.id === json2) { - strictEqual(item.content._rawFiles[0], 'YouKnowEverything', 'should give correct js object as result of JSON'); + strictEqual(item.content._native, 'YouKnowEverything', 'should give correct js object as result of JSON'); } else if (item.id === audio) { // Test environment doesn't support audio diff --git a/test/qunit/unit-es5/test-pack-unpack.js b/test/qunit/unit-es5/test-pack-unpack.js index 267c555998..712e0f15f1 100644 --- a/test/qunit/unit-es5/test-pack-unpack.js +++ b/test/qunit/unit-es5/test-pack-unpack.js @@ -67,12 +67,12 @@ var tex1 = new cc.Texture2D(); tex1._uuid = '555AC'; - tex1._setRawFiles(['.png']); + tex1._setRawAsset('.png'); var tex1Json = Editor.serialize(tex1, { stringify: false }); var tex2 = new cc.Texture2D(); tex2._uuid = '08T18'; - tex2._setRawFiles(['.jare']); + tex2._setRawAsset('.jare'); var tex2Json = Editor.serialize(tex2, { stringify: false }); test('pack and unpack something', function () { diff --git a/test/qunit/unit-es5/test-serialize.js b/test/qunit/unit-es5/test-serialize.js index 9ae5fcb376..de860260bc 100644 --- a/test/qunit/unit-es5/test-serialize.js +++ b/test/qunit/unit-es5/test-serialize.js @@ -119,7 +119,7 @@ __type__: 'MyAsset', _name: '', _objFlags: 0, - _rawFiles: null, + _native: "", emptyArray: [], array: [1, '2', {a:3}, [4, [5]], true], string: 'unknown', diff --git a/test/qunit/unit-es5/test-texture.js b/test/qunit/unit-es5/test-texture.js index f529082091..689d6a0fea 100644 --- a/test/qunit/unit-es5/test-texture.js +++ b/test/qunit/unit-es5/test-texture.js @@ -8,11 +8,11 @@ deepEqual(JSON.parse(Editor.serialize(obj)), expect, info); } - test('rawUrl', function () { + test('nativeUrl', function () { var tex = new cc.Texture2D(); tex._uuid = '555AC'; - tex._setRawFiles(['.png']); - ok(tex.rawUrl.endsWith('.png'), 'rawUrl should contains extname'); + tex._setRawAsset('.png'); + ok(tex.nativeUrl.endsWith('.png'), 'nativeUrl should contains extname'); }); test('(de)serialize empty texture', function () { @@ -24,7 +24,7 @@ serializedAs(tex, expected, 'should be serialized'); var deserialized = cc.deserialize(expected); - strictEqual(deserialized.rawUrl, '', 'rawUrl should be empty string by default'); + strictEqual(deserialized.nativeUrl, '', 'nativeUrl should be empty string by default'); strictEqual(deserialized.url, '', 'url should be empty string by default'); }); @@ -33,8 +33,8 @@ var tex = new cc.Texture2D(); tex._uuid = '555AC'; - tex._setRawFiles(['.png']); - tex.url = tex.rawUrl; + tex._setRawAsset('.png'); + tex.url = tex.nativeUrl; ok(tex.url.endsWith('.png'), 'url should contains extname'); var expected = { @@ -47,7 +47,7 @@ customEnv: { uuid: tex._uuid } }); deserialized._uuid = tex._uuid; - strictEqual(deserialized.rawUrl, tex.rawUrl, 'rawUrl should be deserialized'); + strictEqual(deserialized.nativeUrl, tex.nativeUrl, 'nativeUrl should be deserialized'); strictEqual(deserialized.url, tex.url, 'url should be deserialized'); }); } From 6ddb0eac7dc9c7e1b9f1f9ce9deaf262f3f33469 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Sat, 16 Sep 2017 01:22:03 +0800 Subject: [PATCH 009/127] load texture as url or object and deprecate spriteFrame._textureLoaded --- DebugInfos.js | 2 + cocos2d/core/assets/CCAsset.js | 33 ++++++-- cocos2d/core/load-pipeline/loader.js | 27 +++--- cocos2d/core/load-pipeline/uuid-loader.js | 77 +++++++++-------- cocos2d/core/platform/deserialize.js | 62 +++++++------- .../core/sprites/CCSGSpriteWebGLRenderCmd.js | 5 +- cocos2d/core/sprites/CCScale9Sprite.js | 2 +- cocos2d/core/sprites/CCSpriteFrame.js | 80 +++++++++--------- cocos2d/core/textures/CCTexture2D.js | 31 ++++--- cocos2d/core/value-types/CCValueType.js | 9 +- cocos2d/deprecated.js | 37 ++++---- jsb/jsb-tex-sprite-frame.js | 34 ++++---- test/qunit/assets/library/00/0000000.json | 4 + .../grossini.png => library/00/0000000.png} | Bin test/qunit/assets/library/00/0000001.json | 4 + .../grossini.png => library/00/0000001.png} | Bin test/qunit/unit-es5/_init.js | 4 +- test/qunit/unit-es5/test-resources-loader.js | 7 +- 18 files changed, 236 insertions(+), 182 deletions(-) create mode 100644 test/qunit/assets/library/00/0000000.json rename test/qunit/assets/{resources/grossini.png => library/00/0000000.png} (100%) create mode 100644 test/qunit/assets/library/00/0000001.json rename test/qunit/assets/{resources/grossini/grossini.png => library/00/0000001.png} (100%) diff --git a/DebugInfos.js b/DebugInfos.js index a4b624d828..9237534ad0 100644 --- a/DebugInfos.js +++ b/DebugInfos.js @@ -1,5 +1,7 @@ if (CC_DEBUG) { var logs = { + // Common + "0100": "%s not yet implemented.", //ActionManager: 1000 "1000": "cc.ActionManager.addAction(): action must be non-null", //addAction "1001": "cocos2d: removeAction: Target not found", //removeAction diff --git a/cocos2d/core/assets/CCAsset.js b/cocos2d/core/assets/CCAsset.js index 6bf2177692..6a36da2597 100644 --- a/cocos2d/core/assets/CCAsset.js +++ b/cocos2d/core/assets/CCAsset.js @@ -31,6 +31,7 @@ var RawAsset = require('./CCRawAsset'); * * You may want to override:
* - createNode
+ * - getset functions of _nativeAsset
* - cc.Object._serialize
* - cc.Object._deserialize
* !#zh @@ -38,6 +39,7 @@ var RawAsset = require('./CCRawAsset'); * * 您可能需要重写:
* - createNode
+ * - _nativeAsset 的 getset 方法
* - cc.Object._serialize
* - cc.Object._deserialize
* @@ -94,17 +96,32 @@ cc.Asset = cc.Class({ */ _native: "", + // __nativeAsset: { + // default: null, + // serializable: false + // }, + /** - * The underlying native object of this asset if one is available. - * The object can be used to access additional details or functionality releated to the asset. - * The object will be initialized by the loader if `_native` is available. - * @property {Object} _nativeObject + * The underlying native asset of this asset if one is available. + * This property can be used to access additional details or functionality releated to the asset. + * This property will be initialized by the loader if `_native` is available. + * @property {Object} _nativeAsset * @default null * @private */ - _nativeObject: { - default: null, - serializable: false + _nativeAsset: { + get () { + if (CC_EDITOR) { + cc.errorID('0100', 'getter of ' + JS.getClassName(this) + '._nativeAsset'); + } + // return this.__nativeAsset; + }, + set (obj) { + if (CC_EDITOR) { + cc.errorID('0100', 'setter of ' + JS.getClassName(this) + '._nativeAsset'); + } + // this.__nativeAsset = obj; + } }, }, @@ -176,7 +193,7 @@ cc.Asset = cc.Class({ * @param {String} filename * @private */ - _setRawAsset: (CC_EDITOR || CC_TEST) && function (filename) { + _setRawAsset: function (filename) { this._native = filename || ""; } }); diff --git a/cocos2d/core/load-pipeline/loader.js b/cocos2d/core/load-pipeline/loader.js index 595e7c0b87..b9abb747d4 100644 --- a/cocos2d/core/load-pipeline/loader.js +++ b/cocos2d/core/load-pipeline/loader.js @@ -27,7 +27,6 @@ var JS = require('../platform/js'); var Pipeline = require('./pipeline'); var Texture2D = require('../textures/CCTexture2D'); var loadUuid = require('./uuid-loader'); -var misc = require('../utils/misc'); function loadNothing (item, callback) { return null; @@ -48,20 +47,24 @@ function loadJSON (item, callback) { } function loadImage (item, callback) { - if (!(item.content instanceof Image)) { + var image = item.content; + if (!(image instanceof Image)) { return new Error('Image Loader: Input item doesn\'t contain Image content'); } - var rawUrl = item.rawUrl; - var tex = cc.textureCache.getTextureForKey(rawUrl) || new Texture2D(); - tex.url = rawUrl; - tex.initWithElement(item.content); - tex.handleLoadedTexture(); - if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { - // Image element no longer needed - misc.imagePool.put(item.content); + var loadNativeImageByTexture = item._owner instanceof cc.Texture2D; + if (loadNativeImageByTexture) { + // load Image + return image; + } + else { + // load cc.Texture2D + var rawUrl = item.rawUrl; + var tex = cc.textureCache.getTextureForKey(rawUrl) || new Texture2D(); + tex.url = rawUrl; + tex._nativeAsset = image; + cc.textureCache.cacheImage(rawUrl, tex); + return tex; } - cc.textureCache.cacheImage(rawUrl, tex); - return tex; } function loadPlist (item, callback) { diff --git a/cocos2d/core/load-pipeline/uuid-loader.js b/cocos2d/core/load-pipeline/uuid-loader.js index cff9ad58bb..3743c19769 100644 --- a/cocos2d/core/load-pipeline/uuid-loader.js +++ b/cocos2d/core/load-pipeline/uuid-loader.js @@ -37,70 +37,75 @@ function isSceneObj (json) { ); } -function loadDepends (pipeline, item, asset, tdInfo, deferredLoadRawAssetsInRuntime, callback) { +function parseDepends (item, asset, tdInfo, deferredLoadRawAssetsInRuntime) { var uuidList = tdInfo.uuidList; - var objList, propList, depends; + var objList = tdInfo.uuidObjList; + var propList = tdInfo.uuidPropList; + var stillUseUrl = tdInfo._stillUseUrl; + var depends; var i, dependUuid; // cache dependencies for auto release var dependKeys = item.dependKeys = []; if (deferredLoadRawAssetsInRuntime) { - objList = []; - propList = []; depends = []; // parse depends assets for (i = 0; i < uuidList.length; i++) { dependUuid = uuidList[i]; - var obj = tdInfo.uuidObjList[i]; - var prop = tdInfo.uuidPropList[i]; + var obj = objList[i]; + var prop = propList[i]; var info = cc.AssetLibrary._getAssetInfoInRuntime(dependUuid); if (info.raw) { // skip preloading raw assets + // TODO - skip preloading native texture var url = info.url; obj[prop] = url; dependKeys.push(url); } else { - objList.push(obj); - propList.push(prop); // declare depends assets depends.push({ type: 'uuid', uuid: dependUuid, deferredLoadRaw: true, + _owner: obj, + _ownerProp: prop, + _stillUseUrl: stillUseUrl[i] }); } } } else { - objList = tdInfo.uuidObjList; - propList = tdInfo.uuidPropList; depends = new Array(uuidList.length); // declare depends assets for (i = 0; i < uuidList.length; i++) { dependUuid = uuidList[i]; depends[i] = { type: 'uuid', - uuid: dependUuid + uuid: dependUuid, + _owner: objList[i], + _ownerProp: propList[i], + _stillUseUrl: stillUseUrl[i] }; } } - // // declare raw - // if (tdInfo.rawProp) { - // objList.push(asset); - // propList.push(tdInfo.rawProp); - // depends.push(item.url); - // } - - // fast path - if (depends.length === 0) { - cc.deserialize.Details.pool.put(tdInfo); - return callback(null, asset); + // parse native + if (asset._native && !asset.constructor.preventPreloadNativeObject) { + depends.push({ + url: asset.nativeUrl, + _owner: asset, + _ownerProp: '_nativeAsset', + }); } + return depends; +} + +function loadDepends (pipeline, item, asset, depends, callback) { // Predefine content for dependencies usage item.content = asset; + var dependKeys = item.dependKeys; pipeline.flowInDeps(item, depends, function (errors, items) { var item, missingAssetReporter; for (var src in items.map) { @@ -110,19 +115,17 @@ function loadDepends (pipeline, item, asset, tdInfo, deferredLoadRawAssetsInRunt } } for (var i = 0; i < depends.length; i++) { - var dependSrc = depends[i].uuid; - var dependUrl = depends[i].url; - var dependObj = objList[i]; - var dependProp = propList[i]; + var dep = depends[i]; + var dependSrc = dep.uuid; + var dependUrl = dep.url; + var dependObj = dep._owner; + var dependProp = dep._ownerProp; item = items.map[dependUrl]; if (item) { - var thisOfLoadCallback = { - obj: dependObj, - prop: dependProp - }; + var thisOfLoadCallback = dep; function loadCallback (item) { - var value = item.isRawAsset ? item.rawUrl : item.content; - this.obj[this.prop] = value; + var value = this._stillUseUrl ? item.rawUrl : item.content; + this._owner[this._ownerProp] = value; if (item.uuid !== asset._uuid && dependKeys.indexOf(item.id) < 0) { dependKeys.push(item.id); } @@ -161,7 +164,6 @@ function loadDepends (pipeline, item, asset, tdInfo, deferredLoadRawAssetsInRunt if (CC_EDITOR && missingAssetReporter) { missingAssetReporter.reportByOwner(); } - cc.deserialize.Details.pool.put(tdInfo); callback(null, asset); }); } @@ -264,7 +266,14 @@ function loadUuid (item, callback) { } var deferredLoad = canDeferredLoad(asset, item, isScene); - loadDepends(this.pipeline, item, asset, tdInfo, deferredLoad, callback); + var depends = parseDepends(item, asset, tdInfo, deferredLoad); + + cc.deserialize.Details.pool.put(tdInfo); + + if (depends.length === 0) { + return callback(null, asset); + } + loadDepends(this.pipeline, item, asset, depends, callback); } module.exports = loadUuid; diff --git a/cocos2d/core/platform/deserialize.js b/cocos2d/core/platform/deserialize.js index 46a5482ab9..4d374ac101 100644 --- a/cocos2d/core/platform/deserialize.js +++ b/cocos2d/core/platform/deserialize.js @@ -38,12 +38,6 @@ var Misc = require('../utils/misc'); * */ var Details = function () { - - //this.urlList = []; - //this.callbackList = []; - - // uuids(assets) need to load - /** * list of the depends assets' uuid * @property {String[]} uuidList @@ -59,6 +53,9 @@ var Details = function () { * @property {String[]} uuidPropList */ this.uuidPropList = []; + + // TODO - DELME + this._stillUseUrl = JS.createMap(true); }; /** * @method reset @@ -67,6 +64,7 @@ Details.prototype.reset = function () { this.uuidList.length = 0; this.uuidObjList.length = 0; this.uuidPropList.length = 0; + JS.clear(this._stillUseUrl); }; if (CC_EDITOR || CC_TEST) { Details.prototype.assignAssetsBy = function (getter) { @@ -78,27 +76,30 @@ if (CC_EDITOR || CC_TEST) { } }; } -/** - * @method getUuidOf - * @param {Object} obj - * @param {String} propName - * @return {String} - */ -Details.prototype.getUuidOf = function (obj, propName) { - for (var i = 0; i < this.uuidObjList.length; i++) { - if (this.uuidObjList[i] === obj && this.uuidPropList[i] === propName) { - return this.uuidList[i]; - } - } - return ""; -}; +// /** +// * @method getUuidOf +// * @param {Object} obj +// * @param {String} propName +// * @return {String} +// */ +// Details.prototype.getUuidOf = function (obj, propName) { +// for (var i = 0; i < this.uuidObjList.length; i++) { +// if (this.uuidObjList[i] === obj && this.uuidPropList[i] === propName) { +// return this.uuidList[i]; +// } +// } +// return ""; +// }; /** * @method push * @param {Object} obj * @param {String} propName * @param {String} uuid */ -Details.prototype.push = function (obj, propName, uuid) { +Details.prototype.push = function (obj, propName, uuid, _stillUseUrl) { + if (_stillUseUrl) { + this._stillUseUrl[this.uuidList.length] = true; + } this.uuidList.push(uuid); this.uuidObjList.push(obj); this.uuidPropList.push(propName); @@ -290,7 +291,7 @@ var _Deserializer = (function () { }; // 和 _deserializeObject 不同的地方在于会判断 id 和 uuid - prototype._deserializeObjField = function (obj, jsonObj, propName, target) { + prototype._deserializeObjField = function (obj, jsonObj, propName, target, _stillUseUrl) { var id = jsonObj.__id__; if (typeof id === 'undefined') { var uuid = jsonObj.__uuid__; @@ -304,9 +305,7 @@ var _Deserializer = (function () { // return; // } // } - this.result.uuidList.push(uuid); - this.result.uuidObjList.push(obj); - this.result.uuidPropList.push(propName); + this.result.push(obj, propName, uuid, _stillUseUrl); } else { if (CC_EDITOR || CC_TEST) { @@ -487,7 +486,7 @@ var _Deserializer = (function () { // } // } - function compileObjectType (sources, defaultValue, accessorToSet, propNameLiteralToSet, assumeHavePropIfIsValue) { + function compileObjectType (sources, defaultValue, accessorToSet, propNameLiteralToSet, assumeHavePropIfIsValue, stillUseUrl) { if (defaultValue instanceof cc.ValueType) { // fast case if (!assumeHavePropIfIsValue) { @@ -502,10 +501,10 @@ var _Deserializer = (function () { else { sources.push('if(prop){'); if (CC_EDITOR || CC_TEST) { - sources.push('s._deserializeObjField(o,prop,' + propNameLiteralToSet + ',t&&o);'); + sources.push('s._deserializeObjField(o,prop,' + propNameLiteralToSet + ',t&&o,' + !!stillUseUrl + ');'); } else { - sources.push('s._deserializeObjField(o,prop,' + propNameLiteralToSet + ');'); + sources.push('s._deserializeObjField(o,prop,' + propNameLiteralToSet + ',null,' + !!stillUseUrl + ');'); } sources.push('}else o' + accessorToSet + '=null;'); } @@ -562,25 +561,26 @@ var _Deserializer = (function () { sources.push('prop=d' + accessorToGet + ';'); sources.push(`if(typeof ${CC_JSB ? '(prop)' : 'prop'}!=="undefined"){`); + var stillUseUrl = attrs[propName + SAVE_URL_AS_ASSET]; // function undefined object(null) string boolean number var defaultValue = CCClass.getDefault(attrs[propName + DEFAULT]); if (fastMode) { var defaultType = typeof defaultValue; - var isPrimitiveType = (defaultType === 'string' && !attrs[propName + SAVE_URL_AS_ASSET]) || + var isPrimitiveType = (defaultType === 'string' && !stillUseUrl) || defaultType === 'number' || defaultType === 'boolean'; if (isPrimitiveType) { sources.push(`o${accessorToSet}=prop;`); } else { - compileObjectType(sources, defaultValue, accessorToSet, propNameLiteralToSet, true); + compileObjectType(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); + compileObjectType(sources, defaultValue, accessorToSet, propNameLiteralToSet, false, stillUseUrl); sources.push('}'); } sources.push('}'); diff --git a/cocos2d/core/sprites/CCSGSpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCSGSpriteWebGLRenderCmd.js index 92b04b0fb8..f52c633804 100644 --- a/cocos2d/core/sprites/CCSGSpriteWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCSGSpriteWebGLRenderCmd.js @@ -68,8 +68,9 @@ proto._handleTextureForRotatedTexture = function (texture) { proto.isFrameDisplayed = function (frame) { var node = this._node; - return (cc.rectEqualToRect(frame.getRect(), node._rect) && frame.getTexture().getName() === node._texture.getName() - && cc.pointEqualToPoint(frame.getOffset(), node._unflippedOffsetPositionFromCenter)); + return (cc.rectEqualToRect(frame.getRect(), node._rect) && + frame.getTexture().getWebGLTexture() === node._texture.getWebGLTexture() && + cc.pointEqualToPoint(frame.getOffset(), node._unflippedOffsetPositionFromCenter)); }; proto._updateForSetSpriteFrame = function () {}; diff --git a/cocos2d/core/sprites/CCScale9Sprite.js b/cocos2d/core/sprites/CCScale9Sprite.js index 9c6149b2ab..b37dcd9b9b 100644 --- a/cocos2d/core/sprites/CCScale9Sprite.js +++ b/cocos2d/core/sprites/CCScale9Sprite.js @@ -1423,7 +1423,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ }, _rebuildQuads: function () { - if (!this._spriteFrame || !this._spriteFrame._textureLoaded) { + if (!this._spriteFrame || !this._spriteFrame.textureLoaded()) { this._renderCmd._needDraw = false; return; } diff --git a/cocos2d/core/sprites/CCSpriteFrame.js b/cocos2d/core/sprites/CCSpriteFrame.js index 83906cd6c2..a4e9a9084f 100644 --- a/cocos2d/core/sprites/CCSpriteFrame.js +++ b/cocos2d/core/sprites/CCSpriteFrame.js @@ -57,24 +57,30 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ mixins: [EventTarget], properties: { - /** - * Use this property to set raw texture url during loading - * @property {String} _textureFilenameSetter - * @readOnly - * @private - */ - _textureFilenameSetter: { - set: function (url) { - this._textureFilename = url; - if (url) { - if (CC_EDITOR && url instanceof cc.Asset) { - // just packing + // Use this property to set texture when loading dependency + _textureSetter: { + set: function (texture) { + if (texture) { + if (CC_EDITOR && !(texture instanceof cc.Texture2D)) { + // just building + this._texture = texture; return; } - this._loadTexture(); + this._refreshTexture(texture); + this._textureFilename = texture.url; } } - } + }, + + // _textureFilename: { + // get () { + // return (this._texture && this._texture.url) || ""; + // }, + // set (url) { + // var texture = cc.textureCache.addImage(url); + // this._refreshTexture(texture); + // } + // } }, /** @@ -145,7 +151,6 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ this._texture = null; this._textureFilename = ''; - this._textureLoaded = false; if (CC_EDITOR) { // Atlas asset uuid @@ -166,7 +171,7 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ * @returns {boolean} */ textureLoaded: function () { - return this._textureLoaded; + return this._texture && this._texture.isLoaded(); }, /** @@ -265,14 +270,12 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ var self = this; if (self._texture !== texture) { var locLoaded = texture.isLoaded(); - this._textureLoaded = locLoaded; this._texture = texture; function textureLoadedCallback () { if (!self._texture) { // clearTexture called while loading texture... return; } - self._textureLoaded = true; var w = texture.width, h = texture.height; if (self._rotated && cc._renderType === cc.game.RENDER_TYPE_CANVAS) { @@ -391,16 +394,12 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ // loading texture var texture = textureOrTextureFile; - if (cc.js.isString(texture)) { - this._textureFilename = texture; - this._loadTexture(); + if (typeof texture === 'string' && texture) { + texture = cc.textureCache.addImage(texture); } - else if (texture instanceof cc.Texture2D) { + if (texture instanceof cc.Texture2D) { this._refreshTexture(texture); } - else { - // todo log error - } return true; }, @@ -434,6 +433,9 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ if (!this._texture) { this._loadTexture(); } + else { + // TODO - load native texture + } }, /** @@ -450,8 +452,7 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ * spriteFrame.ensureLoadTexture(); */ clearTexture: function () { - this._textureLoaded = false; - this._texture = null; + this._texture = null; // TODO - release texture }, _checkRect: function (texture) { @@ -484,17 +485,18 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ var offset = this._offset; var size = this._originalSize; var uuid; - var url = this._textureFilename; - if (url) { - if (url instanceof cc.Asset) { - uuid = url._uuid; - } - else { + var texture = this._texture; + if (texture) { + uuid = texture._uuid; + } + if (!uuid) { + var url = this._textureFilename; + if (url) { uuid = Editor.Utils.UuidCache.urlToUuid(url); } - if (exporting) { - uuid = Editor.Utils.UuidUtils.compressUuid(uuid, true); - } + } + if (uuid && exporting) { + uuid = Editor.Utils.UuidUtils.compressUuid(uuid, true); } var capInsets; if (this.insetLeft !== 0 || @@ -539,12 +541,10 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ this._atlasUuid = data.atlas; } - // load texture via _textureFilenameSetter + // load texture via _textureSetter var textureUuid = data.texture; if (textureUuid) { - var dontLoadTexture = (handle.customEnv && handle.customEnv.deferredLoadRaw); - var receiver = dontLoadTexture ? '_textureFilename' : '_textureFilenameSetter'; - handle.result.push(this, receiver, textureUuid); + handle.result.push(this, '_textureSetter', textureUuid); } } }); diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index f651481fcf..2fc3c8f873 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -132,7 +132,22 @@ var Texture2D = cc.Class({ get () { return this._contentSize.height; } - } + }, + + _nativeAsset: { + get () { + return this._htmlElementObj; + }, + set (image) { + this.initWithElement(image); + this.handleLoadedTexture(); + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + // Image element no longer needed + misc.imagePool.put(image); + } + }, + override: true + }, }, /** @@ -285,7 +300,7 @@ var Texture2D = cc.Class({ } }, - getName: function () { + getWebGLTexture: function () { return this._webTextureObj || null; }, @@ -430,7 +445,10 @@ var Texture2D = cc.Class({ var uuid = loadingItem && loadingItem.uuid; if (uuid) { this._uuid = uuid; - this.url = this.nativeUrl; + this.nativeUrl; + var url = this.nativeUrl; + this.url = url; + cc.textureCache.cacheImage(url, this); } } }, @@ -548,13 +566,6 @@ var _p = Texture2D.prototype; // Extended properties -/** - * WebGLTexture Object. - * @property name - * @type {WebGLTexture} - * @readonly - */ -JS.get(_p, "name", _p.getName); /** * Pixel format of the texture. * @property pixelFormat diff --git a/cocos2d/core/value-types/CCValueType.js b/cocos2d/core/value-types/CCValueType.js index 7d9c1e445e..7c2fb624ed 100644 --- a/cocos2d/core/value-types/CCValueType.js +++ b/cocos2d/core/value-types/CCValueType.js @@ -44,7 +44,7 @@ if (CC_EDITOR) { * @return {ValueType} */ proto.clone = function () { - cc.errorID(5801, JS.getClassName(this)); + cc.errorID('0100', JS.getClassName(this) + '.clone'); return null; }; @@ -56,7 +56,7 @@ if (CC_EDITOR) { * @return {Boolean} */ proto.equals = function (other) { - cc.errorID(5802, JS.getClassName(this)); + cc.errorID('0100', JS.getClassName(this) + '.equals'); return false; }; @@ -73,7 +73,7 @@ if (CC_EDITOR) { * @return {ValueType} */ proto.lerp = function (to, ratio) { - cc.warnID(5800, JS.getClassName(this)); + cc.errorID('0100', JS.getClassName(this) + '.lerp'); return this.clone(); }; } @@ -88,5 +88,4 @@ proto.toString = function () { return '' + {}; }; -cc.ValueType = ValueType; -module.exports = ValueType; +cc.ValueType = module.exports = ValueType; diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js index ae657e43a0..db2e07a48b 100644 --- a/cocos2d/deprecated.js +++ b/cocos2d/deprecated.js @@ -10,6 +10,11 @@ if (CC_DEV) { js.obsolete(cc.textureCache, 'cc.textureCache.textureForKey', 'getTextureForKey'); + js.get(cc.SpriteFrame.prototype, '_textureLoaded', function () { + cc.errorID(1400, 'spriteFrame._textureLoaded', 'spriteFrame.textureLoaded()'); + return this.textureLoaded(); + }); + // Label if (cc.Label) { js.obsolete(cc.Label.prototype, 'cc.Label.file', 'font', true); @@ -25,7 +30,7 @@ if (CC_DEV) { * @returns {object} */ js.get(cc, "inject", function () { - cc.warnID(1400, 'cc.inject', 'cc.js.mixin'); + cc.errorID(1400, 'cc.inject', 'cc.js.mixin'); cc.warnID(1401); return function (lhs, rhs) { return js.mixin(rhs, lhs); @@ -42,7 +47,7 @@ if (CC_DEV) { * @returns {object} */ js.get(cc, "extend", function () { - cc.warnID(1400, 'cc.extend', 'cc.js.mixin'); + cc.errorID(1400, 'cc.extend', 'cc.js.mixin'); return js.mixin; }); @@ -54,12 +59,12 @@ if (CC_DEV) { * @returns {object} */ js.get(cc, "newElement", function () { - cc.warnID(1400, 'cc.newElement', 'document.createElement'); + cc.errorID(1400, 'cc.newElement', 'document.createElement'); return document.createElement; }); js.get(cc, "isFunction", function () { - cc.warnID(1400, 'cc.isFunction', '"typeof obj === \'function\'"'); + cc.errorID(1400, 'cc.isFunction', '"typeof obj === \'function\'"'); return function(obj) { return typeof obj === 'function'; }; @@ -74,7 +79,7 @@ if (CC_DEV) { * @returns {boolean} */ js.get(cc, "isNumber", function () { - cc.warnID(1400, 'cc.isNumber', 'cc.js.isNumber'); + cc.errorID(1400, 'cc.isNumber', 'cc.js.isNumber'); return js.isNumber; }); @@ -87,26 +92,26 @@ if (CC_DEV) { * @returns {boolean} */ js.get(cc, "isString", function () { - cc.warnID(1400, 'cc.isString', 'cc.js.isString'); + cc.errorID(1400, 'cc.isString', 'cc.js.isString'); return js.isString; }); js.get(cc, "isArray", function () { - cc.warnID(1400, 'cc.isArray', 'cc.js.isArray'); + cc.errorID(1400, 'cc.isArray', 'cc.js.isArray'); return function(obj) { return Array.isArray(obj); }; }); js.get(cc, "isUndefined", function () { - cc.warnID(1400, 'cc.isUndefined', '"typeof obj === \'undefined\'"'); + cc.errorID(1400, 'cc.isUndefined', '"typeof obj === \'undefined\'"'); return function(obj) { return typeof obj === 'undefined'; }; }); js.get(cc, "isObject", function () { - cc.warnID(1400, 'cc.isObject', '"typeof obj === \'object\'"'); + cc.errorID(1400, 'cc.isObject', '"typeof obj === \'object\'"'); return function(obj) { return typeof obj === 'object'; }; @@ -135,7 +140,7 @@ if (CC_DEV) { * @function */ js.get(cc, 'arrayVerifyType', function () { - cc.warnID(1400, 'cc.arrayVerifyType', 'cc.js.array.verifyType'); + cc.errorID(1400, 'cc.arrayVerifyType', 'cc.js.array.verifyType'); return cc.js.array.verifyType; }); @@ -148,7 +153,7 @@ if (CC_DEV) { * @param {*} delObj remove object */ js.get(cc, 'arrayRemoveObject', function () { - cc.warnID(1400, 'cc.arrayRemoveObject', 'cc.js.array.remove'); + cc.errorID(1400, 'cc.arrayRemoveObject', 'cc.js.array.remove'); return cc.js.array.remove; }); @@ -161,7 +166,7 @@ if (CC_DEV) { * @param {Array} minusArr minus Array */ js.get(cc, 'arrayRemoveArray', function () { - cc.warnID(1400, 'cc.arrayRemoveArray', 'cc.js.array.removeArray'); + cc.errorID(1400, 'cc.arrayRemoveArray', 'cc.js.array.removeArray'); return cc.js.array.removeArray; }); @@ -176,7 +181,7 @@ if (CC_DEV) { * @return {Array} */ js.get(cc, 'arrayAppendObjectsToIndex', function() { - cc.warnID(1400, 'cc.arrayAppendObjectsToIndex', 'cc.js.array.appendObjectsAt'); + cc.errorID(1400, 'cc.arrayAppendObjectsToIndex', 'cc.js.array.appendObjectsAt'); return cc.js.array.appendObjectsAt; }); @@ -188,12 +193,12 @@ if (CC_DEV) { * @return {Array} */ js.get(cc, 'copyArray', function() { - cc.warnID(1400, 'cc.copyArray', 'cc.js.array.copy'); + cc.errorID(1400, 'cc.copyArray', 'cc.js.array.copy'); return cc.js.array.copy; }); js.get(cc, 'PI', function () { - cc.warnID(1400, 'cc.PI', 'Math.PI'); + cc.errorID(1400, 'cc.PI', 'Math.PI'); return Math.PI; }); @@ -244,7 +249,7 @@ if (CC_DEV) { oldPropName = entry; } js.get(obj, oldPropName, function (entry) { - cc.warnID(1400, oldPath + delimiter + entry, newPath + '.' + entry); + cc.errorID(1400, oldPath + delimiter + entry, newPath + '.' + entry); return enumDef[entry]; }.bind(null, entry)); } diff --git a/jsb/jsb-tex-sprite-frame.js b/jsb/jsb-tex-sprite-frame.js index 31b259787d..37c08443f9 100644 --- a/jsb/jsb-tex-sprite-frame.js +++ b/jsb/jsb-tex-sprite-frame.js @@ -68,6 +68,7 @@ cc.TextureCache.prototype.addImage = function (url, cb, target) { cc.textureCache._textures = {}; cc.textureCache.cacheImage = function (key, texture) { + cc.log('cacheImage ' + texture.url); if (texture instanceof cc.Texture2D) { this._textures[key] = texture; } @@ -149,17 +150,14 @@ prototype.setTexture = function (textureOrTextureFile, rect, rotated, offset, or this.setRotated(rotated || false); + // loading texture var texture = textureOrTextureFile; - if (cc.js.isString(textureOrTextureFile)) { - this._textureFilename = textureOrTextureFile; - this._loadTexture(); + if (typeof texture === 'string' && texture) { + texture = cc.textureCache.addImage(texture); } - else if (texture instanceof cc.Texture2D) { + if (texture instanceof cc.Texture2D) { this._refreshTexture(texture); } - else { - //todo log error - } return true; }; @@ -177,6 +175,9 @@ prototype.ensureLoadTexture = function () { if (!this._texture) { this._loadTexture(); } + else { + // TODO - load native texture + } }; prototype.clearTexture = function () { @@ -234,12 +235,10 @@ prototype._deserialize = function (data, handle) { this.insetBottom = capInsets[3]; } - // load texture via _textureFilenameSetter + // load texture via _textureSetter var textureUuid = data.texture; if (textureUuid) { - var dontLoadTexture = (handle.customEnv && handle.customEnv.deferredLoadRaw); - var receiver = dontLoadTexture ? '_textureFilename' : '_textureFilenameSetter'; - handle.result.push(this, receiver, textureUuid); + handle.result.push(this, '_textureSetter', textureUuid); } }; prototype._checkRect = function (texture) { @@ -279,10 +278,15 @@ prototype.clone = function () { return cloned; }; -cc.js.set(prototype, '_textureFilenameSetter', function (url) { - this._textureFilename = url; - if (url) { - this._loadTexture(); +cc.js.set(prototype, '_textureSetter', function (texture) { + if (texture) { + if (CC_EDITOR && !(texture instanceof cc.Texture2D)) { + // just building + this._texture = texture; + return; + } + this._refreshTexture(texture); + this._textureFilename = texture.url; } }); diff --git a/test/qunit/assets/library/00/0000000.json b/test/qunit/assets/library/00/0000000.json new file mode 100644 index 0000000000..957b2a7d7f --- /dev/null +++ b/test/qunit/assets/library/00/0000000.json @@ -0,0 +1,4 @@ +{ + "__type__": "cc.Texture2D", + "content": "0" +} \ No newline at end of file diff --git a/test/qunit/assets/resources/grossini.png b/test/qunit/assets/library/00/0000000.png similarity index 100% rename from test/qunit/assets/resources/grossini.png rename to test/qunit/assets/library/00/0000000.png diff --git a/test/qunit/assets/library/00/0000001.json b/test/qunit/assets/library/00/0000001.json new file mode 100644 index 0000000000..957b2a7d7f --- /dev/null +++ b/test/qunit/assets/library/00/0000001.json @@ -0,0 +1,4 @@ +{ + "__type__": "cc.Texture2D", + "content": "0" +} \ No newline at end of file diff --git a/test/qunit/assets/resources/grossini/grossini.png b/test/qunit/assets/library/00/0000001.png similarity index 100% rename from test/qunit/assets/resources/grossini/grossini.png rename to test/qunit/assets/library/00/0000001.png diff --git a/test/qunit/unit-es5/_init.js b/test/qunit/unit-es5/_init.js index 6371a665c9..d22988ba1a 100644 --- a/test/qunit/unit-es5/_init.js +++ b/test/qunit/unit-es5/_init.js @@ -65,8 +65,8 @@ var TestSprite = cc.Class({ width: 0, height: 0, texture: { - default: '', - url: TestTexture, + default: null, + type: TestTexture, }, rotated: false, trimLeft: 0, diff --git a/test/qunit/unit-es5/test-resources-loader.js b/test/qunit/unit-es5/test-resources-loader.js index 9420a9df87..f31925da95 100644 --- a/test/qunit/unit-es5/test-resources-loader.js +++ b/test/qunit/unit-es5/test-resources-loader.js @@ -65,16 +65,11 @@ asyncTest('load main asset and sub asset by loadResDir', function () { cc.loader.loadResDir('grossini', function (err, results) { ok(Array.isArray(results), 'result should be an array'); - ['123200', '1232218', '123201'].forEach(function (uuid) { + ['123200', '1232218', '123201', '0000000', '0000001'].forEach(function (uuid) { ok(results.some(function (item) { return item._uuid === uuid; }), 'checking uuid ' + uuid); }); - ['resources/grossini/grossini.png', 'resources/grossini.png',].forEach(function (url) { - ok(results.some(function (item) { - return item.url && item.url.endsWith(url); - }), 'checking url ' + url); - }); start(); }); }); From a39f58d9162038b4934c202376f79a3dd597f84a Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Fri, 22 Sep 2017 00:36:54 +0800 Subject: [PATCH 010/127] reviewed --- cocos2d/core/assets/CCAsset.js | 21 ++++++++------------- cocos2d/core/load-pipeline/loader.js | 22 ++++++++-------------- cocos2d/core/load-pipeline/uuid-loader.js | 6 ++++-- cocos2d/core/textures/CCTexture2D.js | 19 +------------------ 4 files changed, 21 insertions(+), 47 deletions(-) diff --git a/cocos2d/core/assets/CCAsset.js b/cocos2d/core/assets/CCAsset.js index 6a36da2597..a1604a0b72 100644 --- a/cocos2d/core/assets/CCAsset.js +++ b/cocos2d/core/assets/CCAsset.js @@ -52,9 +52,9 @@ cc.Asset = cc.Class({ properties: { /** * !#en - * Returns the url of this asset's first raw file, if none of rawFile exists, - * it will returns an empty string. - * !#zh 返回该资源的原始文件的 URL,如果不支持 RAW 文件,它将返回一个空字符串。 + * Returns the url of this asset's native object, if none it will returns an empty string. + * !#zh + * 返回该资源对应的目标平台资源的 URL,如果没有将返回一个空字符串。 * @property nativeUrl * @type {String} * @readOnly @@ -84,17 +84,12 @@ cc.Asset = cc.Class({ }, /** - * 在 lite 版的 Fireball 里,raw asset 并不仅仅是在 properties 里声明了 rawType 才有, - * 而是每个 asset 都能指定自己的 raw file url。这些 url 就存在 _rawFiles 字段中。 - * AssetLibrary 并不会帮你加载这些 url,除非你声明了 rawType。 - * 在 Creator 里,_rawFiles 保留了下来,为了复用 cocos 引擎原有实现,直接用 _rawFiles 来加载 Asset 在 import 之前的源文件。 - * - * @property _native - * @type {String} - * @default "" + * Serializable url for native asset. + * @property {String} _native + * @default undefined * @private */ - _native: "", + _native: undefined, // __nativeAsset: { // default: null, @@ -194,7 +189,7 @@ cc.Asset = cc.Class({ * @private */ _setRawAsset: function (filename) { - this._native = filename || ""; + this._native = filename || undefined; } }); diff --git a/cocos2d/core/load-pipeline/loader.js b/cocos2d/core/load-pipeline/loader.js index b9abb747d4..d38a830dd7 100644 --- a/cocos2d/core/load-pipeline/loader.js +++ b/cocos2d/core/load-pipeline/loader.js @@ -51,20 +51,14 @@ function loadImage (item, callback) { if (!(image instanceof Image)) { return new Error('Image Loader: Input item doesn\'t contain Image content'); } - var loadNativeImageByTexture = item._owner instanceof cc.Texture2D; - if (loadNativeImageByTexture) { - // load Image - return image; - } - else { - // load cc.Texture2D - var rawUrl = item.rawUrl; - var tex = cc.textureCache.getTextureForKey(rawUrl) || new Texture2D(); - tex.url = rawUrl; - tex._nativeAsset = image; - cc.textureCache.cacheImage(rawUrl, tex); - return tex; - } + + // load cc.Texture2D + var rawUrl = item.rawUrl; + var tex = cc.textureCache.getTextureForKey(rawUrl) || new Texture2D(); + tex.url = rawUrl; + tex._nativeAsset = image; + cc.textureCache.cacheImage(rawUrl, tex); + return tex; } function loadPlist (item, callback) { diff --git a/cocos2d/core/load-pipeline/uuid-loader.js b/cocos2d/core/load-pipeline/uuid-loader.js index 3743c19769..50a4933806 100644 --- a/cocos2d/core/load-pipeline/uuid-loader.js +++ b/cocos2d/core/load-pipeline/uuid-loader.js @@ -37,7 +37,7 @@ function isSceneObj (json) { ); } -function parseDepends (item, asset, tdInfo, deferredLoadRawAssetsInRuntime) { +function parseDepends (loader, item, asset, tdInfo, deferredLoadRawAssetsInRuntime) { var uuidList = tdInfo.uuidList; var objList = tdInfo.uuidObjList; var propList = tdInfo.uuidPropList; @@ -94,6 +94,8 @@ function parseDepends (item, asset, tdInfo, deferredLoadRawAssetsInRuntime) { if (asset._native && !asset.constructor.preventPreloadNativeObject) { depends.push({ url: asset.nativeUrl, + // For image, we should skip loader otherwise it will load a new texture + skips: [ loader.id ], _owner: asset, _ownerProp: '_nativeAsset', }); @@ -266,7 +268,7 @@ function loadUuid (item, callback) { } var deferredLoad = canDeferredLoad(asset, item, isScene); - var depends = parseDepends(item, asset, tdInfo, deferredLoad); + var depends = parseDepends(this, item, asset, tdInfo, deferredLoad); cc.deserialize.Details.pool.put(tdInfo); diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 7efc642c3d..d85600156a 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -581,26 +581,9 @@ var Texture2D = cc.Class({ var _p = Texture2D.prototype; -// Extended properties - -/** - * Pixel format of the texture. - * @property pixelFormat - * @type {Number} - * @readonly - */ +// deprecated properties JS.get(_p, "pixelFormat", _p.getPixelFormat); -/** - * Width in pixels. - * @property {Number} pixelWidth - * @deprecated use width or height property instead - */ JS.get(_p, "pixelWidth", _p.getPixelWidth); -/** - * Height in pixels. - * @property {Number} pixelHeight - * @deprecated use width or height property instead - */ JS.get(_p, "pixelHeight", _p.getPixelHeight); game.once(game.EVENT_RENDERER_INITED, function () { From 64c13c7dabc92e3446b9b00e26569717b3263189 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Fri, 22 Sep 2017 10:38:22 +0800 Subject: [PATCH 011/127] sync jsb --- cocos2d/core/assets/CCAsset.js | 2 +- cocos2d/core/platform/CCClass.js | 2 +- cocos2d/core/platform/CCObject.js | 5 +- cocos2d/core/sprites/CCSpriteFrame.js | 16 ++-- cocos2d/core/textures/CCTexture2D.js | 8 +- gulpfile.js | 4 +- jsb/jsb-loader.js | 107 +++++++++++++--------- jsb/jsb-tex-sprite-frame.js | 122 ++++++++++++++------------ 8 files changed, 155 insertions(+), 111 deletions(-) diff --git a/cocos2d/core/assets/CCAsset.js b/cocos2d/core/assets/CCAsset.js index a1604a0b72..2bf06afd3b 100644 --- a/cocos2d/core/assets/CCAsset.js +++ b/cocos2d/core/assets/CCAsset.js @@ -89,7 +89,7 @@ cc.Asset = cc.Class({ * @default undefined * @private */ - _native: undefined, + _native: "", // __nativeAsset: { // default: null, diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index e796e3075b..84c15bffd1 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -304,7 +304,7 @@ function doDefine (className, baseClass, mixins, options) { JS.extend(fireClass, baseClass); // 这里会把父类的 __props__ 复制给子类 prototype = fireClass.prototype; // get extended prototype } - JS.value(fireClass, '$super', baseClass); // not inheritable in JSB and TypeScript + fireClass.$super = baseClass; if (CC_DEV && shouldAddProtoCtor) { prototype.ctor = function () {}; } diff --git a/cocos2d/core/platform/CCObject.js b/cocos2d/core/platform/CCObject.js index 8c7d193d48..7af15f5092 100644 --- a/cocos2d/core/platform/CCObject.js +++ b/cocos2d/core/platform/CCObject.js @@ -216,7 +216,8 @@ JS.getset(prototype, 'name', }, function (value) { this._name = value; - } + }, + true ); /** @@ -230,7 +231,7 @@ JS.getset(prototype, 'name', */ JS.get(prototype, 'isValid', function () { return !(this._objFlags & Destroyed); -}); +}, true); if (CC_EDITOR || CC_TEST) { JS.get(prototype, 'isRealValid', function () { diff --git a/cocos2d/core/sprites/CCSpriteFrame.js b/cocos2d/core/sprites/CCSpriteFrame.js index 80d90bc7de..6eab9cc49c 100644 --- a/cocos2d/core/sprites/CCSpriteFrame.js +++ b/cocos2d/core/sprites/CCSpriteFrame.js @@ -51,7 +51,7 @@ var EventTarget = require("../event/event-target"); * node.parent = self.node * }); */ -cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ +var SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ name: 'cc.SpriteFrame', extends: require('../assets/CCAsset'), mixins: [EventTarget], @@ -354,7 +354,7 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ * @return {SpriteFrame} */ clone: function () { - return new cc.SpriteFrame(this._texture || this._textureFilename, this._rect, this._rotated, this._offset, this._originalSize); + return new SpriteFrame(this._texture || this._textureFilename, this._rect, this._rotated, this._offset, this._originalSize); }, /** @@ -474,10 +474,6 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ } }, - // _instantiate () { - // var clone = new cc.SpriteFrame(); - // }, - // SERIALIZATION _serialize: CC_EDITOR && function (exporting) { @@ -549,8 +545,14 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ } }); -var proto = cc.SpriteFrame.prototype; +var proto = SpriteFrame.prototype; proto.copyWithZone = proto.clone; proto.copy = proto.clone; proto.initWithTexture = proto.setTexture; + +if (!CC_JSB) { + cc.SpriteFrame = SpriteFrame; +} + +module.exports = SpriteFrame; diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index d85600156a..4b63dc5566 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -586,7 +586,7 @@ JS.get(_p, "pixelFormat", _p.getPixelFormat); JS.get(_p, "pixelWidth", _p.getPixelWidth); JS.get(_p, "pixelHeight", _p.getPixelHeight); -game.once(game.EVENT_RENDERER_INITED, function () { +!CC_JSB && game.once(game.EVENT_RENDERER_INITED, function () { if (cc._renderType === game.RENDER_TYPE_CANVAS) { function renderToCache (image, cache) { @@ -1000,4 +1000,8 @@ game.once(game.EVENT_RENDERER_INITED, function () { * @deprecated please use height instead */ -cc.Texture2D = module.exports = Texture2D; +if (!CC_JSB) { + cc.Texture2D = Texture2D; +} + +module.exports = Texture2D; diff --git a/gulpfile.js b/gulpfile.js index fe7c7150b5..d0f2a7c74c 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -55,8 +55,8 @@ gulp.task('build-html5', ['build-html5-preview', 'build-html5-dev', 'build-html5 var jsbSkipModules = [ '../../cocos2d/core/CCGame', '../../cocos2d/core/CCDrawingPrimitives.js', - '../../cocos2d/core/textures/CCTexture2D', - '../../cocos2d/core/sprites/CCSpriteFrame', + // '../../cocos2d/core/textures/CCTexture2D', + // '../../cocos2d/core/sprites/CCSpriteFrame', '../../cocos2d/core/load-pipeline/audio-downloader', '../../cocos2d/core/physics/platform/CCPhysicsDebugDraw.js', '../../cocos2d/core/physics/platform/CCPhysicsUtils.js', diff --git a/jsb/jsb-loader.js b/jsb/jsb-loader.js index 0df24411f4..8b4cd5197b 100644 --- a/jsb/jsb-loader.js +++ b/jsb/jsb-loader.js @@ -45,15 +45,15 @@ cc.loader.addDownloadHandlers({ 'jsc' : downloadScript, // Images - 'png' : empty, - 'jpg' : empty, - 'bmp' : empty, - 'jpeg' : empty, - 'gif' : empty, - 'ico' : empty, - 'tiff' : empty, - 'webp' : empty, - 'image' : empty, + 'png' : loadImage, + 'jpg' : loadImage, + 'bmp' : loadImage, + 'jpeg' : loadImage, + 'gif' : loadImage, + 'ico' : loadImage, + 'tiff' : loadImage, + 'webp' : loadImage, + 'image' : loadImage, // Audio 'mp3' : downloadAudio, @@ -74,46 +74,69 @@ cc.loader.addDownloadHandlers({ function loadImage (item, callback) { var url = item.url; - - var cachedTex = cc.textureCache.getTextureForKey(url); - if (cachedTex) { - return cachedTex; - } - else if (url.match(jsb.urlRegExp)) { - jsb.loadRemoteImg(url, function(succeed, tex) { - if (succeed) { - callback && callback(null, tex); - } - else { - callback && callback(new Error('Load image failed: ' + url)); - } - }); + var loadByDeserializedTexture = item._owner instanceof cc.Texture2D; + if (loadByDeserializedTexture) { + // load Image + if (url.match(jsb.urlRegExp)) { + jsb.initRemoteImg(item._owner, url, function(succeed) { + if (succeed) { + callback && callback(null); + } + else { + callback && callback(new Error('Load image failed: ' + url)); + } + }); + } + else { + cc.textureCache.initImageAsync(item._owner, url, function (tex) { + if (tex) { + callback && callback(null); + } + else { + callback && callback(new Error('Load image failed: ' + url)); + } + }); + } } else { - var addImageCallback = function (tex) { - if (tex instanceof cc.Texture2D) { - callback && callback(null, tex); - } - else { - callback && callback(new Error('Load image failed: ' + url)); - } - jsb.unregisterNativeRef(cc.textureCache, addImageCallback); - }; - cc.textureCache._addImageAsync(url, addImageCallback); + var cachedTex = cc.textureCache.getTextureForKey(url); + if (cachedTex) { + return cachedTex; + } + else if (url.match(jsb.urlRegExp)) { + jsb.loadRemoteImg(url, function(succeed, tex) { + if (succeed) { + callback && callback(null, tex); + } + else { + callback && callback(new Error('Load image failed: ' + url)); + } + }); + } + else { + cc.textureCache._addImageAsync(url, function (tex) { + if (tex instanceof cc.Texture2D) { + callback && callback(null, tex); + } + else { + callback && callback(new Error('Load image failed: ' + url)); + } + }); + } } } cc.loader.addLoadHandlers({ // Images - 'png' : loadImage, - 'jpg' : loadImage, - 'bmp' : loadImage, - 'jpeg' : loadImage, - 'gif' : loadImage, - 'ico' : loadImage, - 'tiff' : loadImage, - 'webp' : loadImage, - 'image' : loadImage, + 'png' : empty, + 'jpg' : empty, + 'bmp' : empty, + 'jpeg' : empty, + 'gif' : empty, + 'ico' : empty, + 'tiff' : empty, + 'webp' : empty, + 'image' : empty, 'default' : empty }); \ No newline at end of file diff --git a/jsb/jsb-tex-sprite-frame.js b/jsb/jsb-tex-sprite-frame.js index 65a01b3807..d962f7c409 100644 --- a/jsb/jsb-tex-sprite-frame.js +++ b/jsb/jsb-tex-sprite-frame.js @@ -27,9 +27,10 @@ require('../cocos2d/core/platform/CCClass'); require('../cocos2d/core/assets/CCAsset'); +var WebTexture = require('../cocos2d/core/textures/CCTexture2D'); +var WebSpriteFrame = require('../cocos2d/core/sprites/CCSpriteFrame'); -// cc.spriteFrameAnimationCache = cc.animationCache; -// cc.SpriteFrameAnimation = cc.Animation; +cc.js.unregisterClass(WebTexture, WebSpriteFrame); // TextureCache addImage @@ -51,6 +52,10 @@ if (!cc.TextureCache.prototype._addImage) { cc.TextureCache.prototype._addImage = cc.TextureCache.prototype.addImage; } cc.TextureCache.prototype.addImage = function (url, cb, target) { + if (CC_DEBUG && url instanceof cc.Texture2D) { + cc.warn('textureCache.addImage(url) - The type of the url should be string, not Texture2D. You don\'t need to call addImage if you already have the texture object.'); + url = url.url; + } if (typeof cb === "function") { return this.addImageAsync(url, cb, target); } @@ -64,7 +69,7 @@ cc.TextureCache.prototype.addImage = function (url, cb, target) { } }; -// cc.textureCache.cacheImage +// cc.textureCache cc.textureCache._textures = {}; cc.textureCache.cacheImage = function (key, texture) { @@ -87,41 +92,40 @@ cc.textureCache.removeTextureForKey = function (key) { // cc.Texture2D cc.Class._fastDefine('cc.Texture2D', cc.Texture2D, []); -cc.js.value(cc.Texture2D, '$super', cc.Asset); // not inheritable in JSB and TypeScript +cc.Texture2D.$super = cc.Asset; -const GL_NEAREST = 9728; // gl.NEAREST -const GL_LINEAR = 9729; // gl.LINEAR -const GL_REPEAT = 10497; // gl.REPEAT -const GL_CLAMP_TO_EDGE = 33071; // gl.CLAMP_TO_EDGE -const GL_MIRRORED_REPEAT = 33648; // gl.MIRRORED_REPEAT - -cc.Texture2D.PixelFormat = cc.Enum({ - RGB565: cc.Texture2D.PIXEL_FORMAT_RGB565, - RGB5A1: cc.Texture2D.PIXEL_FORMAT_RGB5A1, - RGBA4444: cc.Texture2D.PIXEL_FORMAT_RGBA4444, - RGB888: cc.Texture2D.PIXEL_FORMAT_RGB888, - RGBA8888: cc.Texture2D.PIXEL_FORMAT_RGBA8888, - A8: cc.Texture2D.PIXEL_FORMAT_A8, - I8: cc.Texture2D.PIXEL_FORMAT_I8, - AI8: cc.Texture2D.PIXEL_FORMAT_AI8 -}); - -cc.Texture2D.WrapMode = cc.Enum({ - REPEAT: GL_REPEAT, - CLAMP_TO_EDGE: GL_CLAMP_TO_EDGE, - MIRRORED_REPEAT: GL_MIRRORED_REPEAT -}); - -cc.Texture2D.Filter = cc.Enum({ - LINEAR: GL_LINEAR, - NEAREST: GL_NEAREST +[ + 'WrapMode', + 'PixelFormat', + 'Filter', + 'extnames', + 'preventDeferredLoadDependents', + 'preventPreloadNativeObject', +].forEach(function (key) { + cc.Texture2D[key] = WebTexture[key]; }); var prototype = cc.Texture2D.prototype; -prototype.toString = function () { - return this.url || ''; +cc.js.addon(prototype, WebTexture.prototype); +// [ +// 'toString', +// '_deserialize', +// '_setRawAsset', +// 'nativeUrl', +// 'name', +// 'isValid', +// 'destroy', +// '_destruct', +// '_destroyImmediate', +// ].forEach(function (key) { +// Object.defineProperty(prototype, key, cc.js.getPropertyDescriptor(WebTexture.prototype, key)); +// }); + +prototype._ctor = function () { + cc.Asset.call(this); }; + prototype.loaded = true; prototype.update = function (options) { var updateTexParam = false; @@ -153,10 +157,39 @@ prototype.update = function (options) { if (genMipmap) { this.generateMipmap(); } -} +}; prototype.isLoaded = function () { return true; }; +cc.js.getset(prototype, '_nativeAsset', + function () { + return this; + }, + function (item) { + // var actualUrl = item.url; + // if (actualUrl.match(jsb.urlRegExp)) { + // jsb.initRemoteImg(this, actualUrl, function(succeed) { + // if (succeed) { + // callback && callback(null, true); + // } + // else { + // callback && callback(new Error('Load image failed: ' + actualUrl)); + // } + // }); + // } + // else { + // cc.textureCache._addImageAsync(actualUrl, function (tex) { + // if (tex instanceof cc.Texture2D) { + // callback && callback(null, tex); + // } + // else { + // callback && callback(new Error('Load image failed: ' + actualUrl)); + // } + // }); + // } + } +); + prototype.getPixelWidth = prototype.getPixelsWide; prototype.getPixelHeight = prototype.getPixelsHigh; prototype.description = prototype.getDescription; @@ -166,7 +199,7 @@ cc.js.get(prototype, 'pixelHeight', prototype.getPixelHeight); // cc.SpriteFrame cc.Class._fastDefine('cc.SpriteFrame', cc.SpriteFrame, []); -cc.js.value(cc.SpriteFrame, '$super', cc.Asset); // not inheritable in JSB and TypeScript +cc.SpriteFrame.$super = cc.Asset; prototype = cc.SpriteFrame.prototype; prototype._setTexture = prototype.setTexture; @@ -332,23 +365,4 @@ prototype.clone = function () { return cloned; }; -cc.js.set(prototype, '_textureSetter', function (texture) { - if (texture) { - if (CC_EDITOR && !(texture instanceof cc.Texture2D)) { - // just building - this._texture = texture; - return; - } - this._refreshTexture(texture); - this._textureFilename = texture.url; - } -}); - -cc.js.getset(prototype, 'name', - function () { - return this._name; - }, - function (value) { - this._name = value; - } -); +cc.js.addon(prototype, WebSpriteFrame.prototype); From e27666cfac4b17200cac64f62b861ac2faf60e08 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Mon, 25 Sep 2017 17:19:12 +0800 Subject: [PATCH 012/127] update jsb --- cocos2d/core/textures/CCTexture2D.js | 2 +- jsb/jsb-loader.js | 32 ++++++++++------------------ 2 files changed, 12 insertions(+), 22 deletions(-) diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 4b63dc5566..9d5155afc1 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -255,7 +255,7 @@ var Texture2D = cc.Class({ properties: { _nativeAsset: { get () { - return this._image; + // returned to pool }, set (image) { this.initWithElement(image); diff --git a/jsb/jsb-loader.js b/jsb/jsb-loader.js index 8b4cd5197b..35fad6933e 100644 --- a/jsb/jsb-loader.js +++ b/jsb/jsb-loader.js @@ -74,36 +74,26 @@ cc.loader.addDownloadHandlers({ function loadImage (item, callback) { var url = item.url; + var isRemote = jsb.urlRegExp.test(url); var loadByDeserializedTexture = item._owner instanceof cc.Texture2D; if (loadByDeserializedTexture) { // load Image - if (url.match(jsb.urlRegExp)) { - jsb.initRemoteImg(item._owner, url, function(succeed) { - if (succeed) { - callback && callback(null); - } - else { - callback && callback(new Error('Load image failed: ' + url)); - } - }); - } - else { - cc.textureCache.initImageAsync(item._owner, url, function (tex) { - if (tex) { - callback && callback(null); - } - else { - callback && callback(new Error('Load image failed: ' + url)); - } - }); - } + var loader = isRemote ? jsb.initRemoteImg : jsb.initTextureAsync; + loader(item._owner, url, function(succeed) { + if (succeed) { + callback && callback(null); + } + else { + callback && callback(new Error('Load image failed: ' + url)); + } + }); } else { var cachedTex = cc.textureCache.getTextureForKey(url); if (cachedTex) { return cachedTex; } - else if (url.match(jsb.urlRegExp)) { + else if (isRemote) { jsb.loadRemoteImg(url, function(succeed, tex) { if (succeed) { callback && callback(null, tex); From bca9d854acf37a262d6981825dcf8f814fec13a0 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 28 Sep 2017 22:55:59 +0800 Subject: [PATCH 013/127] deprecate texture.releaseTexture(), use texture.destroy() instead --- cocos2d/core/load-pipeline/CCLoader.js | 2 +- cocos2d/core/platform/CCObject.js | 4 ++-- cocos2d/core/platform/js.js | 20 +++++++++-------- cocos2d/core/textures/CCTexture2D.js | 25 ++++++++++++++++----- cocos2d/core/textures/CCTextureCache.js | 17 ++++++++++----- cocos2d/deprecated.js | 3 +++ jsb/jsb-tex-sprite-frame.js | 29 +++++++++++++++---------- 7 files changed, 65 insertions(+), 35 deletions(-) diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js index 2a97fe32b0..a744b04c2b 100644 --- a/cocos2d/core/load-pipeline/CCLoader.js +++ b/cocos2d/core/load-pipeline/CCLoader.js @@ -766,7 +766,7 @@ proto.release = function (asset) { asset = item.content; // TODO: AUDIO if (asset instanceof cc.Texture2D) { - cc.textureCache.removeTextureForKey(item.url); + asset.destroy(); } else if (asset instanceof cc.Asset && asset.nativeUrl) { this.release(asset.nativeUrl); diff --git a/cocos2d/core/platform/CCObject.js b/cocos2d/core/platform/CCObject.js index 7af15f5092..aa75891e03 100644 --- a/cocos2d/core/platform/CCObject.js +++ b/cocos2d/core/platform/CCObject.js @@ -246,11 +246,11 @@ var deferredDestroyTimer = null; * Destroy this Object, and release all its own references to other objects.
* Actual object destruction will delayed until before rendering. *
- * After destroy, this CCObject is not usable any more. + * After destroy, this object is not usable any more. * You can use cc.isValid(obj) to check whether the object is destroyed before accessing it. * !#zh * 销毁该对象,并释放所有它对其它对象的引用。
- * 销毁后,CCObject 不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。 + * 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。 * 实际销毁操作会延迟到当前帧渲染前执行。 * @method destroy * @return {Boolean} whether it is the first time the destroy being called diff --git a/cocos2d/core/platform/js.js b/cocos2d/core/platform/js.js index 19f69cbaab..6728e55f16 100644 --- a/cocos2d/core/platform/js.js +++ b/cocos2d/core/platform/js.js @@ -526,30 +526,32 @@ cc.js.unregisterClass to remove the id of unused class'; * @method obsolete * @param {any} obj - YourObject or YourClass.prototype * @param {String} obsoleted - "OldParam" or "YourClass.OldParam" - * @param {String} newPropName - "NewParam" + * @param {String} newExpr - "NewParam" or "YourClass.NewParam" * @param {Boolean} [writable=false] */ -js.obsolete = function (obj, obsoleted, newPropName, writable) { - var oldName = /([^.]+)$/.exec(obsoleted)[0]; +js.obsolete = function (obj, obsoleted, newExpr, writable) { + var extractPropName = /([^.]+)$/; + var oldProp = extractPropName.exec(obsoleted)[0]; + var newProp = extractPropName.exec(newExpr)[0]; function get () { if (CC_DEV) { - cc.warnID(5400, obsoleted, newPropName); + cc.warnID(5400, obsoleted, newExpr); } - return this[newPropName]; + return this[newProp]; } if (writable) { - js.getset(obj, oldName, + js.getset(obj, oldProp, get, function (value) { if (CC_DEV) { - cc.warnID(5401, obsoleted, newPropName); + cc.warnID(5401, obsoleted, newExpr); } - this[newPropName] = value; + this[newProp] = value; } ); } else { - js.get(obj, oldName, get); + js.get(obj, oldProp, get); } }; diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 9d5155afc1..58dc7117b8 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -446,16 +446,29 @@ var Texture2D = cc.Class({ return ""; }, - /** - * Release texture. - * @method releaseTexture - */ - releaseTexture: function () { + _releaseTexture () { if (this._gl && this._glID !== null) { this._gl.deleteTexture(this._glID); + this._glID = null; } }, + /** + * !#en + * Destory this texture and immediately release its video memory. (Inherit from cc.Object.destroy)
+ * After destroy, this object is not usable any more. + * You can use cc.isValid(obj) to check whether the object is destroyed before accessing it. + * !#zh + * 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)
+ * 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。 + * @method destroy + */ + destroy () { + this._releaseTexture(); + cc.textureCache.removeTextureForKey(this.url); + this._super(); + }, + /** * Pixel format of the texture. * @method getPixelFormat @@ -839,7 +852,7 @@ JS.get(_p, "pixelHeight", _p.getPixelHeight); if (this._image) { if (updateImage) { // Release previous gl texture if existed - this.releaseTexture(); + this._releaseTexture(); this._glID = gl.createTexture(); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, this._glID); diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js index 3235dadbdd..6a65328b91 100644 --- a/cocos2d/core/textures/CCTextureCache.js +++ b/cocos2d/core/textures/CCTextureCache.js @@ -126,7 +126,7 @@ var textureCache = /** @lends cc.textureCache# */{ var locTextures = this._textures; for (var selKey in locTextures) { if (locTextures[selKey]) - locTextures[selKey].releaseTexture(); + locTextures[selKey]._releaseTexture(); } this._textures = {}; }, @@ -144,7 +144,7 @@ var textureCache = /** @lends cc.textureCache# */{ var locTextures = this._textures; for (var selKey in locTextures) { if (locTextures[selKey] === texture) { - locTextures[selKey].releaseTexture(); + locTextures[selKey]._releaseTexture(); delete(locTextures[selKey]); } } @@ -157,12 +157,17 @@ var textureCache = /** @lends cc.textureCache# */{ * @example {@link utils/api/engine/docs/cocos2d/core/textures/removeTextureForKey.js} */ removeTextureForKey: function (textureKeyName) { + if (CC_DEBUG && textureKeyName instanceof cc.Texture2D) { + cc.warn('textureCache.removeTextureForKey(key) - The type of the key should be string, not Texture2D. You should call texture.destroy() if you already have the texture object.'); + } + if (typeof textureKeyName !== 'string') return; - var locTextures = this._textures; - if (locTextures[textureKeyName]) { - locTextures[textureKeyName].releaseTexture(); - delete(locTextures[textureKeyName]); + + var texture = this._textures[textureKeyName]; + if (texture) { + texture._releaseTexture(); + delete this._textures[textureKeyName]; } }, diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js index db2e07a48b..be3fb75533 100644 --- a/cocos2d/deprecated.js +++ b/cocos2d/deprecated.js @@ -10,6 +10,9 @@ if (CC_DEV) { js.obsolete(cc.textureCache, 'cc.textureCache.textureForKey', 'getTextureForKey'); + // Texture + js.obsolete(cc.Texture2D.prototype, 'texture.releaseTexture', 'texture.destroy'); + js.get(cc.SpriteFrame.prototype, '_textureLoaded', function () { cc.errorID(1400, 'spriteFrame._textureLoaded', 'spriteFrame.textureLoaded()'); return this.textureLoaded(); diff --git a/jsb/jsb-tex-sprite-frame.js b/jsb/jsb-tex-sprite-frame.js index d962f7c409..9af31c1769 100644 --- a/jsb/jsb-tex-sprite-frame.js +++ b/jsb/jsb-tex-sprite-frame.js @@ -32,12 +32,14 @@ var WebSpriteFrame = require('../cocos2d/core/sprites/CCSpriteFrame'); cc.js.unregisterClass(WebTexture, WebSpriteFrame); -// TextureCache addImage +// TextureCache addImage/addImageAsync -if (!cc.TextureCache.prototype._addImageAsync) { - cc.TextureCache.prototype._addImageAsync = cc.TextureCache.prototype.addImageAsync; +var prototype = cc.TextureCache.prototype; + +if (!prototype._addImageAsync) { + prototype._addImageAsync = prototype.addImageAsync; } -cc.TextureCache.prototype.addImageAsync = function (url, cb, target) { +prototype.addImageAsync = function (url, cb, target) { var localTex = null; cc.loader.load(url, function(err, tex) { if (err) tex = null; @@ -48,10 +50,10 @@ cc.TextureCache.prototype.addImageAsync = function (url, cb, target) { }); return localTex; }; -if (!cc.TextureCache.prototype._addImage) { - cc.TextureCache.prototype._addImage = cc.TextureCache.prototype.addImage; +if (!prototype._addImage) { + prototype._addImage = prototype.addImage; } -cc.TextureCache.prototype.addImage = function (url, cb, target) { +prototype.addImage = function (url, cb, target) { if (CC_DEBUG && url instanceof cc.Texture2D) { cc.warn('textureCache.addImage(url) - The type of the url should be string, not Texture2D. You don\'t need to call addImage if you already have the texture object.'); url = url.url; @@ -73,7 +75,6 @@ cc.TextureCache.prototype.addImage = function (url, cb, target) { cc.textureCache._textures = {}; cc.textureCache.cacheImage = function (key, texture) { - cc.log('cacheImage ' + texture.url); if (texture instanceof cc.Texture2D) { this._textures[key] = texture; } @@ -84,8 +85,12 @@ cc.textureCache.getTextureForKey = function (key) { }; cc.textureCache._removeTextureForKey = cc.textureCache.removeTextureForKey; cc.textureCache.removeTextureForKey = function (key) { - if (this._textures[key]) - delete this._textures[key]; + if (CC_DEBUG && key instanceof cc.Texture2D) { + cc.warn('textureCache.removeTextureForKey(key) - The type of the key should be string, not Texture2D. You should call texture.destroy() if you already have the texture object.'); + key = key.url; + } + + delete this._textures[key]; this._removeTextureForKey(key); }; @@ -105,7 +110,8 @@ cc.Texture2D.$super = cc.Asset; cc.Texture2D[key] = WebTexture[key]; }); -var prototype = cc.Texture2D.prototype; +prototype = cc.Texture2D.prototype; +prototype._releaseTexture = prototype.releaseTexture; cc.js.addon(prototype, WebTexture.prototype); // [ @@ -124,6 +130,7 @@ cc.js.addon(prototype, WebTexture.prototype); prototype._ctor = function () { cc.Asset.call(this); + this.url = ""; }; prototype.loaded = true; From 5c443fecd298f7055c64c3b6d0dc894a564da433 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Sun, 1 Oct 2017 12:55:09 +0800 Subject: [PATCH 014/127] remove comments --- cocos2d/tilemap/CCSGTMXLayer.js | 4 ++-- jsb/jsb-tex-sprite-frame.js | 34 --------------------------------- 2 files changed, 2 insertions(+), 36 deletions(-) diff --git a/cocos2d/tilemap/CCSGTMXLayer.js b/cocos2d/tilemap/CCSGTMXLayer.js index e339f92262..645d8ce2ae 100644 --- a/cocos2d/tilemap/CCSGTMXLayer.js +++ b/cocos2d/tilemap/CCSGTMXLayer.js @@ -130,8 +130,8 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ } var tw = tileset._tileSize.width, th = tileset._tileSize.height, - imageW = tex._contentSize.width, - imageH = tex._contentSize.height, + imageW = tex.width, + imageH = tex.height, spacing = tileset.spacing, margin = tileset.margin, diff --git a/jsb/jsb-tex-sprite-frame.js b/jsb/jsb-tex-sprite-frame.js index 9af31c1769..bd25adb9a3 100644 --- a/jsb/jsb-tex-sprite-frame.js +++ b/jsb/jsb-tex-sprite-frame.js @@ -114,19 +114,6 @@ prototype = cc.Texture2D.prototype; prototype._releaseTexture = prototype.releaseTexture; cc.js.addon(prototype, WebTexture.prototype); -// [ -// 'toString', -// '_deserialize', -// '_setRawAsset', -// 'nativeUrl', -// 'name', -// 'isValid', -// 'destroy', -// '_destruct', -// '_destroyImmediate', -// ].forEach(function (key) { -// Object.defineProperty(prototype, key, cc.js.getPropertyDescriptor(WebTexture.prototype, key)); -// }); prototype._ctor = function () { cc.Asset.call(this); @@ -173,27 +160,6 @@ cc.js.getset(prototype, '_nativeAsset', return this; }, function (item) { - // var actualUrl = item.url; - // if (actualUrl.match(jsb.urlRegExp)) { - // jsb.initRemoteImg(this, actualUrl, function(succeed) { - // if (succeed) { - // callback && callback(null, true); - // } - // else { - // callback && callback(new Error('Load image failed: ' + actualUrl)); - // } - // }); - // } - // else { - // cc.textureCache._addImageAsync(actualUrl, function (tex) { - // if (tex instanceof cc.Texture2D) { - // callback && callback(null, tex); - // } - // else { - // callback && callback(new Error('Load image failed: ' + actualUrl)); - // } - // }); - // } } ); From a1c535c6bb0e9592ddb6595b72892e039fc9b02c Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Fri, 29 Sep 2017 18:05:38 +0800 Subject: [PATCH 015/127] update texture in property --- DebugInfos.js | 6 ++++ cocos2d/core/textures/CCTextureCache.js | 2 ++ cocos2d/motion-streak/CCMotionStreak.js | 18 +++++++----- cocos2d/motion-streak/CCSGMotionStreak.js | 6 +--- cocos2d/particle/CCParticleSystem.js | 29 ++++++++++--------- cocos2d/tilemap/CCTiledMapAsset.js | 2 +- cocos2d/tilemap/editor/tiled-map.js | 5 +++- extensions/dragonbones/ArmatureDisplay.js | 14 ++++----- .../dragonbones/DragonBonesAtlasAsset.js | 4 +-- .../editor/dragonbones-atlas-meta.js | 2 +- extensions/spine/SkeletonData.js | 10 +++---- jsb/jsb-tex-sprite-frame.js | 2 ++ 12 files changed, 58 insertions(+), 42 deletions(-) diff --git a/DebugInfos.js b/DebugInfos.js index 9237534ad0..7476d4896c 100644 --- a/DebugInfos.js +++ b/DebugInfos.js @@ -339,6 +339,12 @@ if (CC_DEBUG) { " ...\n" + " }", "3656": "The default value of %s.%s must be an empty string. (changed since 1.7)", //getTypeChecker_4 + "3657": "The value assigned to %s should be Texture2D type, not url. Since 1.7,\n" + + "you can declare a texture directly in properties by using:\n" + + "{\n" + + " default: null,\n" + + " type: cc.Texture2D // use 'type:' instead of 'url:'\n" + + "}", //Prefab: 3700 "3700": "internal error: _prefab is undefined", //_doInstantiate "3701": "Failed to load prefab asset for node '%s'", //syncWithPrefab diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js index 6a65328b91..493c73a950 100644 --- a/cocos2d/core/textures/CCTextureCache.js +++ b/cocos2d/core/textures/CCTextureCache.js @@ -158,6 +158,7 @@ var textureCache = /** @lends cc.textureCache# */{ */ removeTextureForKey: function (textureKeyName) { if (CC_DEBUG && textureKeyName instanceof cc.Texture2D) { + // TODO - remove at 2.0 cc.warn('textureCache.removeTextureForKey(key) - The type of the key should be string, not Texture2D. You should call texture.destroy() if you already have the texture object.'); } @@ -315,6 +316,7 @@ game.once(game.EVENT_RENDERER_INITED, function () { _p.addImage = function (url, cb, target) { if (CC_DEBUG && url instanceof cc.Texture2D) { + // TODO - remove at 2.0 cc.warn('textureCache.addImage(url) - The type of the url should be string, not Texture2D. You don\'t need to call addImage if you already have the texture object.'); } diff --git a/cocos2d/motion-streak/CCMotionStreak.js b/cocos2d/motion-streak/CCMotionStreak.js index ffc7d41489..57ebfdb394 100644 --- a/cocos2d/motion-streak/CCMotionStreak.js +++ b/cocos2d/motion-streak/CCMotionStreak.js @@ -154,8 +154,8 @@ var MotionStreak = cc.Class({ * motionStreak.texture = newTexture; */ _texture: { - default: '', - url: cc.Texture2D + default: null, + type: cc.Texture2D }, texture: { get: function () { @@ -164,13 +164,17 @@ var MotionStreak = cc.Class({ set: function (value) { this._texture = value; if (this._motionStreak) { - if (value && cc.js.isString(value)) - value = cc.textureCache.addImage(value); - + if (CC_DEBUG && typeof value === 'string') { + // TODO - remove at 2.0 + cc.warnID(3657, 'motionStreak.texture'); + if (value) { + value = cc.textureCache.addImage(value); + } + } this._motionStreak.setTexture(value); } }, - url: cc.Texture2D, + type: cc.Texture2D, animatable: false, tooltip: CC_DEV && 'i18n:COMPONENT.motionStreak.texture' }, @@ -256,7 +260,7 @@ var MotionStreak = cc.Class({ } this._root = new _ccsg.Node(); var motionStreak = new _ccsg.MotionStreak(); - motionStreak.initWithFade(this._fadeTime, this._minSeg, this._stroke, this.node.color, this._texture || null); + motionStreak.initWithFade(this._fadeTime, this._minSeg, this._stroke, this.node.color, this._texture); motionStreak.setFastMode(this._fastMode); this._root.addChild(motionStreak); var sgNode = this.node._sgNode; diff --git a/cocos2d/motion-streak/CCSGMotionStreak.js b/cocos2d/motion-streak/CCSGMotionStreak.js index 0bb29cb193..4a4d12e5d9 100644 --- a/cocos2d/motion-streak/CCSGMotionStreak.js +++ b/cocos2d/motion-streak/CCSGMotionStreak.js @@ -258,14 +258,10 @@ _ccsg.MotionStreak = _ccsg.Node.extend({ * @param {Number} minSeg minimum segment size * @param {Number} stroke stroke's width * @param {Number} color - * @param {string|cc.Texture2D} texture texture filename or texture + * @param {cc.Texture2D} texture * @return {Boolean} */ initWithFade:function (fade, minSeg, stroke, color, texture) { - - if (cc.js.isString(texture)) - texture = cc.textureCache.addImage(texture); - this.anchorX = 0; this.anchorY = 0; this.ignoreAnchor = true; diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js index 540fcb5f4c..05c0ec39c6 100644 --- a/cocos2d/particle/CCParticleSystem.js +++ b/cocos2d/particle/CCParticleSystem.js @@ -184,22 +184,29 @@ var properties = { * @property {Texture2D} texture. */ _texture: { - default: '', - url: cc.Texture2D + default: null, + type: cc.Texture2D }, texture: { get: function () { return this._texture; }, set: function (value) { + if (CC_DEBUG && typeof value === 'string') { + // TODO - remove at 2.0 + cc.warnID(3657, 'particleSystem.texture'); + if (value) { + value = cc.textureCache.addImage(value); + } + } this._texture = value; - this._sgNode.texture = value ? cc.textureCache.addImage( value ) : null; + this._sgNode.texture = value; if (!value && this._file) { // fallback to plist this._applyFile(); } }, - url: cc.Texture2D, + type: cc.Texture2D, tooltip: CC_DEV && 'i18n:COMPONENT.particle_system.texture' }, @@ -882,7 +889,7 @@ var ParticleSystem = cc.Class({ var texture = spriteFrame.getTexture(); if (texture) { - this._texture = texture.url; + this._texture = texture; } this._sgNode.setDisplayFrame(spriteFrame); }, @@ -895,9 +902,7 @@ var ParticleSystem = cc.Class({ * @param {Rect} rect */ setTextureWithRect: function (texture, rect) { - if (texture instanceof cc.Texture2D) { - this._texture = texture.url; - } + this._texture = texture; this._sgNode.setTextureWithRect(texture, rect); }, @@ -931,12 +936,12 @@ var ParticleSystem = cc.Class({ // To avoid it export custom particle data textureImageData too large, // so use the texutreUuid instead of textureImageData if (content.textureUuid) { - cc.AssetLibrary.queryAssetInfo(content.textureUuid, function (err, url, raw) { + cc.loader.load({ uuid: content.textureUuid, type: 'uuid' }, function (err, texture) { if (err) { cc.error(err); return; } - self.texture = url; + self.texture = texture; }); } @@ -977,9 +982,7 @@ var ParticleSystem = cc.Class({ this._blendFunc.dst = this._dstBlendFactor; sgNode.setBlendFunc(this._blendFunc); - if (this._texture) { - sgNode.texture = cc.textureCache.addImage(this._texture); - } + sgNode.texture = this._texture; // recover sgNode properties if (!active) { diff --git a/cocos2d/tilemap/CCTiledMapAsset.js b/cocos2d/tilemap/CCTiledMapAsset.js index bf008e0db3..978ddd638c 100644 --- a/cocos2d/tilemap/CCTiledMapAsset.js +++ b/cocos2d/tilemap/CCTiledMapAsset.js @@ -44,7 +44,7 @@ var TiledMapAsset = cc.Class({ textures: { default: [], - url: [cc.Texture2D] + type: [cc.Texture2D] }, tsxFiles: { diff --git a/cocos2d/tilemap/editor/tiled-map.js b/cocos2d/tilemap/editor/tiled-map.js index df5a70d4f8..a4fcf795dd 100644 --- a/cocos2d/tilemap/editor/tiled-map.js +++ b/cocos2d/tilemap/editor/tiled-map.js @@ -95,7 +95,10 @@ class TiledMapMeta extends CustomAssetMeta { asset.tmxXmlStr = this._tmxData; asset.tmxFolderPath = Path.relative(AssetRootUrl, Url.dirname(db.fspathToUrl(fspath))); asset.tmxFolderPath = asset.tmxFolderPath.replace(/\\/g, '/'); - asset.textures = this._textures.map(p => db.fspathToUrl(p)); + asset.textures = this._textures.map(p => { + var uuid = db.fspathToUuid(p); + return uuid ? Editor.serialize.asAsset(uuid) : null; + }); asset.tsxFiles = this._tsxFiles.map(p => db.fspathToUrl(p)); db.saveAssetToLibrary(this.uuid, asset); cb(); diff --git a/extensions/dragonbones/ArmatureDisplay.js b/extensions/dragonbones/ArmatureDisplay.js index 585b276ee4..c5f2b752d1 100644 --- a/extensions/dragonbones/ArmatureDisplay.js +++ b/extensions/dragonbones/ArmatureDisplay.js @@ -347,17 +347,18 @@ dragonBones.ArmatureDisplay = cc.Class({ }, _parseDragonAtlasAsset : function() { - if (this.dragonAtlasAsset) { + var asset = this.dragonAtlasAsset; + if (asset) { if (CC_JSB) { // TODO parse the texture atlas data from json string & texture path - this._factory.parseTextureAtlasData(this.dragonAtlasAsset.atlasJson, this.dragonAtlasAsset.texture); + this._factory.parseTextureAtlasData(asset.atlasJson, asset.texture && asset.texture.url); } else { - var atlasJsonObj = JSON.parse(this.dragonAtlasAsset.atlasJson); + var atlasJsonObj = JSON.parse(asset.atlasJson); var atlasName = atlasJsonObj.name; var existedAtlasData = null; var atlasDataList = this._factory.getTextureAtlasData(atlasName); - var texturePath = this.dragonAtlasAsset.texture; if (atlasDataList && atlasDataList.length > 0) { + var texturePath = asset.texture && asset.texture.url; for (var idx in atlasDataList) { var data = atlasDataList[idx]; if (data && data.texture && data.texture.url === texturePath) { @@ -367,11 +368,10 @@ dragonBones.ArmatureDisplay = cc.Class({ } } - var texture = cc.textureCache.getTextureForKey(texturePath); if (existedAtlasData) { - existedAtlasData.texture = texture; + existedAtlasData.texture = asset.texture; } else { - this._factory.parseTextureAtlasData(atlasJsonObj, texture); + this._factory.parseTextureAtlasData(atlasJsonObj, asset.texture); } } } diff --git a/extensions/dragonbones/DragonBonesAtlasAsset.js b/extensions/dragonbones/DragonBonesAtlasAsset.js index 4e5a186cbf..1c5cb1ef30 100644 --- a/extensions/dragonbones/DragonBonesAtlasAsset.js +++ b/extensions/dragonbones/DragonBonesAtlasAsset.js @@ -56,8 +56,8 @@ var DragonBonesAtlasAsset = cc.Class({ * @property {Texture2D} texture */ texture: { - default: '', - url: cc.Texture2D + default: null, + type: cc.Texture2D }, }, diff --git a/extensions/dragonbones/editor/dragonbones-atlas-meta.js b/extensions/dragonbones/editor/dragonbones-atlas-meta.js index 413e3aea32..6b01a1ef17 100644 --- a/extensions/dragonbones/editor/dragonbones-atlas-meta.js +++ b/extensions/dragonbones/editor/dragonbones-atlas-meta.js @@ -88,7 +88,7 @@ class DragonBonesAtlasMeta extends CustomAssetMeta { var asset = new dragonBones.DragonBonesAtlasAsset(); asset.name = Path.basenameNoExt(fspath); asset.atlasJson = this.atlasJson; - asset.texture = Editor.assetdb.uuidToUrl(this.texture); + asset.texture = Editor.serialize.asAsset(this.texture); this._assetdb.saveAssetToLibrary(this.uuid, asset); cb(); }); diff --git a/extensions/spine/SkeletonData.js b/extensions/spine/SkeletonData.js index f5e1dcc646..fbc761ce13 100644 --- a/extensions/spine/SkeletonData.js +++ b/extensions/spine/SkeletonData.js @@ -42,11 +42,11 @@ var TextureLoader = !CC_JSB && cc.Class({ // return tex; // } //} - var urls = this.asset.textures; - for (var i = 0; i < urls.length; i++) { - var url = urls[i]; + var textures = this.asset.textures; + for (var i = 0; i < textures.length; i++) { + var texture = textures[i]; + var url = texture && texture.url; if (url.endsWith(line)) { - var texture = cc.textureCache.addImage(url); var tex = new sp.SkeletonTexture({ width: texture.getPixelWidth(), height: texture.getPixelHeight() }); tex.setRealTexture(texture); return tex; @@ -129,7 +129,7 @@ var SkeletonData = cc.Class({ */ textures: { default: [], - url: [cc.Texture2D] + type: [cc.Texture2D] }, /** diff --git a/jsb/jsb-tex-sprite-frame.js b/jsb/jsb-tex-sprite-frame.js index bd25adb9a3..ab67336d4e 100644 --- a/jsb/jsb-tex-sprite-frame.js +++ b/jsb/jsb-tex-sprite-frame.js @@ -55,6 +55,7 @@ if (!prototype._addImage) { } prototype.addImage = function (url, cb, target) { if (CC_DEBUG && url instanceof cc.Texture2D) { + // TODO - remove at 2.0 cc.warn('textureCache.addImage(url) - The type of the url should be string, not Texture2D. You don\'t need to call addImage if you already have the texture object.'); url = url.url; } @@ -86,6 +87,7 @@ cc.textureCache.getTextureForKey = function (key) { cc.textureCache._removeTextureForKey = cc.textureCache.removeTextureForKey; cc.textureCache.removeTextureForKey = function (key) { if (CC_DEBUG && key instanceof cc.Texture2D) { + // TODO - remove at 2.0 cc.warn('textureCache.removeTextureForKey(key) - The type of the key should be string, not Texture2D. You should call texture.destroy() if you already have the texture object.'); key = key.url; } From 36f2767e410b1f59b3b4a3f795ce623315f8ae15 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Fri, 29 Sep 2017 15:40:32 +0800 Subject: [PATCH 016/127] tweaks (+1 squashed commit) Squashed commits: [f2bb64e] tweaks --- cocos2d/core/platform/CCMacro.js | 7 +- cocos2d/core/sprites/CCSGSprite.js | 10 +- .../core/sprites/CCSGSpriteCanvasRenderCmd.js | 23 +-- cocos2d/core/sprites/CCScale9Sprite.js | 43 +---- cocos2d/core/sprites/CCSpriteFrame.js | 7 +- cocos2d/core/textures/CCTexture2D.js | 4 +- cocos2d/core/textures/CCTextureCache.js | 167 ++++++------------ extensions/dragonbones/CCFactory.js | 4 +- 8 files changed, 83 insertions(+), 182 deletions(-) diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js index 44d42c33ab..4e5df2d767 100644 --- a/cocos2d/core/platform/CCMacro.js +++ b/cocos2d/core/platform/CCMacro.js @@ -1704,10 +1704,9 @@ cc.macro = { SPRITEBATCHNODE_RENDER_SUBPIXEL: 1, /** - *

- * Automatically premultiply alpha for PNG resources - *

- * @property {Number} AUTO_PREMULTIPLIED_ALPHA_FOR_PNG + * Automatically premultiply alpha for remote PNG resources. + * @property {Boolean} AUTO_PREMULTIPLIED_ALPHA_FOR_PNG + * @default false */ AUTO_PREMULTIPLIED_ALPHA_FOR_PNG: 0, diff --git a/cocos2d/core/sprites/CCSGSprite.js b/cocos2d/core/sprites/CCSGSprite.js index fc0f1b0dd5..e79e013a27 100644 --- a/cocos2d/core/sprites/CCSGSprite.js +++ b/cocos2d/core/sprites/CCSGSprite.js @@ -375,14 +375,6 @@ _ccsg.Sprite = _ccsg.Node.extend({ } }, - /** - * Returns the quad (tex coords, vertex coords and color) information. - * @return {cc.V3F_C4B_T2F_Quad|null} Returns a cc.V3F_C4B_T2F_Quad object when render mode is WebGL, returns null when render mode is Canvas. - */ - getQuad:function () { - return null; - }, - /** * conforms to cc.TextureProtocol protocol * @function @@ -693,7 +685,7 @@ _ccsg.Sprite = _ccsg.Node.extend({ cc.js.addon(_ccsg.Sprite.prototype, EventTarget.prototype); -var SameNameGetSets = ['opacity', 'color', 'texture', 'quad']; +var SameNameGetSets = ['opacity', 'color', 'texture']; var DiffNameGetSets = { opacityModifyRGB: ['isOpacityModifyRGB', 'setOpacityModifyRGB'], flippedX: ['isFlippedX', 'setFlippedX'], diff --git a/cocos2d/core/sprites/CCSGSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSGSpriteCanvasRenderCmd.js index 8c74441a06..2ea12388b1 100644 --- a/cocos2d/core/sprites/CCSGSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSGSpriteCanvasRenderCmd.js @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ -_ccsg.Sprite.CanvasRenderCmd = function (renderable) { +function CanvasRenderCmd (renderable) { this._rootCtor(renderable); this._needDraw = true; this._textureCoord = { @@ -40,8 +40,8 @@ _ccsg.Sprite.CanvasRenderCmd = function (renderable) { this._textureToRender = null; }; -var proto = _ccsg.Sprite.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); -proto.constructor = _ccsg.Sprite.CanvasRenderCmd; +var proto = CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); +proto.constructor = CanvasRenderCmd; proto.setDirtyRecursively = function (value) {}; @@ -74,12 +74,7 @@ proto.updateBlendFunc = function (blendFunc) { proto._handleTextureForRotatedTexture = function (texture, rect, rotated, counterclockwise) { if (rotated && texture.isLoaded()) { - var tempElement = texture.getHtmlElementObj(); - tempElement = _ccsg.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, rect, counterclockwise); - var tempTexture = new cc.Texture2D(); - tempTexture.initWithElement(tempElement); - tempTexture.handleLoadedTexture(); - texture = tempTexture; + texture = CanvasRenderCmd._createRotatedTexture(texture, rect, counterclockwise); rect.x = rect.y = 0; this._node._rect = cc.rect(0, 0, rect.width, rect.height); } @@ -234,7 +229,7 @@ proto._setTextureCoords = function (rect) { locTextureRect.validRect = !(locTextureRect.width === 0 || locTextureRect.height === 0 || locTextureRect.x < 0 || locTextureRect.y < 0); }; -_ccsg.Sprite.CanvasRenderCmd._cutRotateImageToCanvas = function (texture, rect, counterclockwise) { +CanvasRenderCmd._cutRotateImageToCanvas = function (texture, rect, counterclockwise) { if (!texture) return null; @@ -255,3 +250,11 @@ _ccsg.Sprite.CanvasRenderCmd._cutRotateImageToCanvas = function (texture, rect, ctx.drawImage(texture, rect.x, rect.y, rect.height, rect.width, -rect.height / 2, -rect.width / 2, rect.height, rect.width); return nCanvas; }; + +CanvasRenderCmd._createRotatedTexture = function (texture, rect, counterclockwise) { + var rotatedTexture = new cc.Texture2D(); + rotatedTexture._nativeAsset = CanvasRenderCmd._cutRotateImageToCanvas(texture._nativeAsset, rect, counterclockwise); + return rotatedTexture; +}; + +_ccsg.Sprite.CanvasRenderCmd = CanvasRenderCmd; diff --git a/cocos2d/core/sprites/CCScale9Sprite.js b/cocos2d/core/sprites/CCScale9Sprite.js index 60ede7e42c..f39c67378d 100644 --- a/cocos2d/core/sprites/CCScale9Sprite.js +++ b/cocos2d/core/sprites/CCScale9Sprite.js @@ -26,7 +26,7 @@ var EventTarget = require("../event/event-target"); function sortIndex (a, b) { return a - b; -}; +} var dataPool = { _pool: {}, @@ -60,8 +60,7 @@ var dataPool = { }; var macro = cc.macro, - webgl, - vl, vb, vt, vr; + webgl; /* *

@@ -220,17 +219,14 @@ var scale9QuadGenerator = { //build vertices var vertices = sprite._vertices; var wt = sprite._renderCmd._worldTransform; - var leftWidth, centerWidth, rightWidth; - var topHeight, centerHeight, bottomHeight; - var rect = spriteFrame._rect; + var leftWidth, rightWidth; + var topHeight, bottomHeight; var corner = sprite._corner; leftWidth = insetLeft; rightWidth = insetRight; - centerWidth = rect.width - leftWidth - rightWidth; topHeight = insetTop; bottomHeight = insetBottom; - centerHeight = rect.height - topHeight - bottomHeight; var preferSize = contentSize; var sizableWidth = preferSize.width - leftWidth - rightWidth; @@ -1004,8 +1000,7 @@ var meshQuadGenerator = { return; } - var spriteFrame = sprite._spriteFrame, - polygonInfo = sprite._meshPolygonInfo + var polygonInfo = sprite._meshPolygonInfo; if (!polygonInfo) { return; @@ -1114,7 +1109,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({ this._uvs = dataPool.get(8) || new Float32Array(8); // Init sprite frame if (spiteFrame) { - this.initWithSpriteFrame(spiteFrame); + this.setSpriteFrame(spiteFrame); } if (webgl === undefined) { @@ -1132,23 +1127,6 @@ cc.Scale9Sprite = _ccsg.Node.extend({ } }, - /** - * Initializes a 9-slice sprite with a texture file - * - * @param textureOrTextureFile The name of the texture file. - */ - initWithTexture: function (textureOrTextureFile) { - this.setTexture(textureOrTextureFile); - }, - - /** - * Initializes a 9-slice sprite with an sprite frame - * @param spriteFrameOrSFName The sprite frame object. - */ - initWithSpriteFrame: function (spriteFrameOrSFName) { - this.setSpriteFrame(spriteFrameOrSFName); - }, - /** * Change the texture file of 9 slice sprite * @@ -1171,13 +1149,13 @@ cc.Scale9Sprite = _ccsg.Node.extend({ this._uvsDirty = true; this._renderCmd._needDraw = false; var self = this; - var onResourceDataLoaded = function () { - if (cc.sizeEqualToSize(self._contentSize, cc.size(0, 0))) { + function onResourceDataLoaded () { + if (self._contentSize.width === 0 && self._contentSize.height === 0) { self.setContentSize(self._spriteFrame._rect); } self._renderCmd._needDraw = true; self._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); - }; + } if (spriteFrame.textureLoaded()) { onResourceDataLoaded(); } else { @@ -1235,9 +1213,6 @@ cc.Scale9Sprite = _ccsg.Node.extend({ } }, - isTrimmedContentSizeEnabled: function () { - return this._isTrimmedContentSize; - }, /** * Change the state of 9-slice sprite. * @see `State` diff --git a/cocos2d/core/sprites/CCSpriteFrame.js b/cocos2d/core/sprites/CCSpriteFrame.js index 6eab9cc49c..4dbbd33a30 100644 --- a/cocos2d/core/sprites/CCSpriteFrame.js +++ b/cocos2d/core/sprites/CCSpriteFrame.js @@ -279,12 +279,7 @@ var SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ var w = texture.width, h = texture.height; if (self._rotated && cc._renderType === cc.game.RENDER_TYPE_CANVAS) { - var tempElement = texture.getHtmlElementObj(); - tempElement = _ccsg.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, self.getRect()); - var tempTexture = new cc.Texture2D(); - tempTexture.initWithElement(tempElement); - tempTexture.handleLoadedTexture(); - self._texture = tempTexture; + self._texture = _ccsg.Sprite.CanvasRenderCmd._createRotatedTexture(texture, self.getRect()); self._rotated = false; w = self._texture.width; h = self._texture.height; diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 58dc7117b8..cfae2e44b3 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -255,7 +255,8 @@ var Texture2D = cc.Class({ properties: { _nativeAsset: { get () { - // returned to pool + // maybe returned to pool in webgl + return this._image; }, set (image) { this.initWithElement(image); @@ -583,7 +584,6 @@ var Texture2D = cc.Class({ var uuid = loadingItem && loadingItem.uuid; if (uuid) { this._uuid = uuid; - this.nativeUrl; var url = this.nativeUrl; this.url = url; cc.textureCache.cacheImage(url, this); diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js index 493c73a950..47a8e80a6f 100644 --- a/cocos2d/core/textures/CCTextureCache.js +++ b/cocos2d/core/textures/CCTextureCache.js @@ -23,7 +23,6 @@ THE SOFTWARE. ****************************************************************************/ -var game = require('../CCGame'); var Texture2D = require('./CCTexture2D'); /** @@ -173,11 +172,11 @@ var textureCache = /** @lends cc.textureCache# */{ }, /** - *

Returns a Texture2D object given an file image
- * If the file image was not previously loaded, it will create a new Texture2D
- * object and it will return it. It will use the filename as a key.
+ * Returns a Texture2D object given an file image
+ * If the file image was not previously loaded, it will create a new Texture2D + * object and it will return it. It will use the filename as a key. * Otherwise it will return a reference of a previously loaded image.
- * Supported image extensions: .png, .jpg, .gif

+ * Supported image extensions: .png, .jpg, .gif * @method addImage * @param {String} url * @param {Function} cb @@ -185,7 +184,43 @@ var textureCache = /** @lends cc.textureCache# */{ * @return {Texture2D} * @example {@link utils/api/engine/docs/cocos2d/core/textures/addImage.js} */ - addImage: null, + addImage (url, cb, target) { + if (CC_DEBUG && url instanceof cc.Texture2D) { + // TODO - remove at 2.0 + cc.warn('textureCache.addImage(url) - The type of the url should be string, not Texture2D. You don\'t need to call addImage if you already have the texture object.'); + } + + cc.assertID(url, 3103); + + var locTexs = this._textures; + var tex = locTexs[url]; + if (tex) { + if(tex.isLoaded()) { + cb && cb.call(target, tex); + return tex; + } + else { + tex.once("load", function(){ + cb && cb.call(target, tex); + }, target); + return tex; + } + } + + tex = locTexs[url] = new Texture2D(); + tex.url = url; + cc.loader.load(url, function (err, texture) { + if (err) { + return cb && cb.call(target, err || new Error('Unknown error')); + } + + textureCache.handleLoadedTexture(url); + + cb && cb.call(target, tex); + }); + + return tex; + }, addImageAsync: null, /** @@ -244,116 +279,20 @@ var textureCache = /** @lends cc.textureCache# */{ this._textures = {}; this._textureColorsCache = {}; this._textureKeySeq = (0 | Math.random() * 1000); + }, + + handleLoadedTexture (url) { + var locTexs = this._textures; + var tex = locTexs[url]; + if (!tex) { + cc.assertID(url, 3009); + tex = locTexs[url] = new Texture2D(); + tex.url = url; + } + tex.handleLoadedTexture(); } }; -game.once(game.EVENT_RENDERER_INITED, function () { - var _p = textureCache; - if (cc._renderType === game.RENDER_TYPE_CANVAS) { - _p.handleLoadedTexture = function (url) { - var locTexs = this._textures; - //remove judge - var tex = locTexs[url]; - if (!tex) { - cc.assertID(url, 3009); - tex = locTexs[url] = new Texture2D(); - tex.url = url; - } - tex.handleLoadedTexture(); - }; - - _p.addImage = function (url, cb, target) { - - cc.assertID(url, 3103); - - var locTexs = this._textures; - //remove judge - var tex = locTexs[url]; - if (tex) { - if(tex.isLoaded()) { - cb && cb.call(target, tex); - return tex; - } - else - { - tex.once("load", function(){ - cb && cb.call(target, tex); - }, target); - return tex; - } - } - - tex = locTexs[url] = new Texture2D(); - tex.url = url; - cc.loader.load(url, function (err, texture) { - if (err) { - return cb && cb.call(target, err || new Error('Unknown error')); - } - - textureCache.handleLoadedTexture(url); - - cb && cb.call(target, tex); - }); - - return tex; - }; - - _p.addImageAsync = _p.addImage; - - } else if (cc._renderType === game.RENDER_TYPE_WEBGL) { - - _p.handleLoadedTexture = function (url) { - var locTexs = this._textures, tex, premultiplied; - tex = locTexs[url]; - if (!tex) { - cc.assertID(url, 3009); - tex = locTexs[url] = new Texture2D(); - tex.url = url; - } - premultiplied = cc.macro.AUTO_PREMULTIPLIED_ALPHA_FOR_PNG && (cc.path.extname(url) === ".png"); - tex.handleLoadedTexture(premultiplied); - }; - - _p.addImage = function (url, cb, target) { - if (CC_DEBUG && url instanceof cc.Texture2D) { - // TODO - remove at 2.0 - cc.warn('textureCache.addImage(url) - The type of the url should be string, not Texture2D. You don\'t need to call addImage if you already have the texture object.'); - } - - cc.assertID(url, 3112); - - var locTexs = this._textures; - var tex = locTexs[url]; - if (tex) { - if(tex.isLoaded()) { - cb && cb.call(target, tex); - return tex; - } - else { - tex.once("load", function(){ - cb && cb.call(target, tex); - }, target); - return tex; - } - } - - tex = locTexs[url] = new Texture2D(); - tex.url = url; - cc.loader.load(url, function (err, texture) { - if (err) { - return cb && cb.call(target, err || new Error('Unknown error')); - } - - textureCache.handleLoadedTexture(url); - - cb && cb.call(target, tex); - }); - - return tex; - }; - - _p.addImageAsync = _p.addImage; - } -}); +textureCache.addImageAsync = textureCache.addImage; cc.textureCache = module.exports = textureCache; \ No newline at end of file diff --git a/extensions/dragonbones/CCFactory.js b/extensions/dragonbones/CCFactory.js index 5cdea5abfa..ead1eb90a6 100644 --- a/extensions/dragonbones/CCFactory.js +++ b/extensions/dragonbones/CCFactory.js @@ -144,9 +144,7 @@ dragonBones.CCFactory = cc.Class({ textureData.texture.setTexture(textureAtlasTexture, rect, textureData.rotated, offset, originSize); // TODO multiply textureAtlas } - var ret = new cc.Scale9Sprite(); - ret.initWithSpriteFrame(textureData.texture); - return ret; + return new cc.Scale9Sprite(textureData.texture); } return null; From ccc91746cbbf4b34f2e79f4c245e4524bf2ba2da Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Sat, 30 Sep 2017 10:26:09 +0800 Subject: [PATCH 017/127] support deferred load texture in runtime --- cocos2d/core/load-pipeline/uuid-loader.js | 25 ++--- cocos2d/core/sprites/CCSpriteFrame.js | 109 ++++++++++------------ cocos2d/core/textures/CCTexture2D.js | 39 +++++++- cocos2d/core/textures/CCTextureCache.js | 23 +++-- jsb/jsb-tex-sprite-frame.js | 69 ++++++-------- 5 files changed, 139 insertions(+), 126 deletions(-) diff --git a/cocos2d/core/load-pipeline/uuid-loader.js b/cocos2d/core/load-pipeline/uuid-loader.js index 50a4933806..52f41ac67f 100644 --- a/cocos2d/core/load-pipeline/uuid-loader.js +++ b/cocos2d/core/load-pipeline/uuid-loader.js @@ -37,7 +37,7 @@ function isSceneObj (json) { ); } -function parseDepends (loader, item, asset, tdInfo, deferredLoadRawAssetsInRuntime) { +function parseDepends (item, asset, tdInfo, deferredLoadRawAssetsInRuntime) { var uuidList = tdInfo.uuidList; var objList = tdInfo.uuidObjList; var propList = tdInfo.uuidPropList; @@ -77,6 +77,7 @@ function parseDepends (loader, item, asset, tdInfo, deferredLoadRawAssetsInRunti } else { depends = new Array(uuidList.length); + // declare depends assets for (i = 0; i < uuidList.length; i++) { dependUuid = uuidList[i]; @@ -88,17 +89,17 @@ function parseDepends (loader, item, asset, tdInfo, deferredLoadRawAssetsInRunti _stillUseUrl: stillUseUrl[i] }; } - } - // parse native - if (asset._native && !asset.constructor.preventPreloadNativeObject) { - depends.push({ - url: asset.nativeUrl, - // For image, we should skip loader otherwise it will load a new texture - skips: [ loader.id ], - _owner: asset, - _ownerProp: '_nativeAsset', - }); + // parse native + if (asset._native && !asset.constructor.preventPreloadNativeObject) { + depends.push({ + url: asset.nativeUrl, + // For image, we should skip loader otherwise it will load a new texture + skips: [ 'Loader' ], + _owner: asset, + _ownerProp: '_nativeAsset', + }); + } } return depends; @@ -268,7 +269,7 @@ function loadUuid (item, callback) { } var deferredLoad = canDeferredLoad(asset, item, isScene); - var depends = parseDepends(this, item, asset, tdInfo, deferredLoad); + var depends = parseDepends(item, asset, tdInfo, deferredLoad); cc.deserialize.Details.pool.put(tdInfo); diff --git a/cocos2d/core/sprites/CCSpriteFrame.js b/cocos2d/core/sprites/CCSpriteFrame.js index 4dbbd33a30..f7c1da354b 100644 --- a/cocos2d/core/sprites/CCSpriteFrame.js +++ b/cocos2d/core/sprites/CCSpriteFrame.js @@ -66,7 +66,9 @@ var SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ this._texture = texture; return; } - this._refreshTexture(texture); + if (this._texture !== texture) { + this._refreshTexture(texture); + } this._textureFilename = texture.url; } } @@ -261,65 +263,55 @@ var SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ }, /* - * !#en Sets the texture of the frame, the texture is retained automatically. - * !#zh 设置使用的纹理实例,会被 retain。 + * !#en Sets the texture of the frame. + * !#zh 设置使用的纹理实例。 * @method _refreshTexture * @param {Texture2D} texture */ _refreshTexture: function (texture) { var self = this; - if (self._texture !== texture) { - var locLoaded = texture.loaded; - this._texture = texture; - function textureLoadedCallback () { - if (!self._texture) { - // clearTexture called while loading texture... - return; - } - var w = texture.width, h = texture.height; + this._texture = texture; - if (self._rotated && cc._renderType === cc.game.RENDER_TYPE_CANVAS) { - self._texture = _ccsg.Sprite.CanvasRenderCmd._createRotatedTexture(texture, self.getRect()); - self._rotated = false; - w = self._texture.width; - h = self._texture.height; - self.setRect(cc.rect(0, 0, w, h)); - } + function textureLoadedCallback () { + if (!self._texture) { + // clearTexture called while loading texture... + return; + } + var w = texture.width, h = texture.height; - if (self._rect) { - self._checkRect(self._texture); - } - else { - self.setRect(cc.rect(0, 0, w, h)); - } - - if (!self._originalSize) { - self.setOriginalSize(cc.size(w, h)); - } - - if (!self._offset) { - self.setOffset(cc.v2(0, 0)); - } - - // dispatch 'load' event of cc.SpriteFrame - self.emit("load"); + if (self._rotated && cc._renderType === cc.game.RENDER_TYPE_CANVAS) { + self._texture = _ccsg.Sprite.CanvasRenderCmd._createRotatedTexture(texture, self.getRect()); + self._rotated = false; + w = self._texture.width; + h = self._texture.height; + self.setRect(cc.rect(0, 0, w, h)); } - if (locLoaded) { - textureLoadedCallback(); + if (self._rect) { + self._checkRect(self._texture); } else { - texture.once("load", textureLoadedCallback); + self.setRect(cc.rect(0, 0, w, h)); } + + if (!self._originalSize) { + self.setOriginalSize(cc.size(w, h)); + } + + if (!self._offset) { + self.setOffset(cc.v2(0, 0)); + } + + // dispatch 'load' event of cc.SpriteFrame + self.emit("load"); + } + + if (texture.loaded) { + textureLoadedCallback(); + } + else { + texture.once("load", textureLoadedCallback); } - //if (texture && texture.url && texture.isLoaded()) { - // if (self._rect) { - // self._checkRect(texture); - // } - // else { - // self.setRect(cc.rect(0, 0, texture.width, texture.height)); - // } - //} }, /** @@ -392,20 +384,13 @@ var SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ if (typeof texture === 'string' && texture) { texture = cc.textureCache.addImage(texture); } - if (texture instanceof cc.Texture2D) { + if (texture instanceof cc.Texture2D && this._texture !== texture) { this._refreshTexture(texture); } return true; }, - _loadTexture: function () { - if (this._textureFilename) { - var texture = cc.textureCache.addImage(this._textureFilename); - this._refreshTexture(texture); - } - }, - /** * !#en If a loading scene (or prefab) is marked as `asyncLoadAssets`, all the textures of the SpriteFrame which * associated by user's custom Components in the scene, will not preload automatically. @@ -425,11 +410,17 @@ var SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ * } */ ensureLoadTexture: function () { - if (!this._texture) { - this._loadTexture(); + if (this._texture) { + if (!this._texture.isLoaded()) { + // load exists texture + this._refreshTexture(this._texture); + this._texture.load(); + } } - else { - // TODO - load native texture + else if (this._textureFilename) { + // load new texture + var texture = cc.textureCache.addImage(this._textureFilename); + this._refreshTexture(texture); } }, diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index cfae2e44b3..7055a208c1 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -410,6 +410,35 @@ var Texture2D = cc.Class({ return this._image; }, + // load a texture + load (callback) { + if (this.loaded) { + callback && callback(); + return; + } + if (!this.url) { + callback && callback(); + return; + } + // load image + var self = this; + cc.loader.load({ + url: this.url, + // For image, we should skip loader otherwise it will load a new texture + skips: [ 'Loader' ], + }, function (err, image) { + if (image) { + if (CC_DEBUG && image instanceof cc.Texture2D) { + return cc.error('internal error: loader handle pipe must be skipped'); + } + if (!self.loaded) { + self._nativeAsset = image; + } + } + callback && callback(err); + }); + }, + /** * Check whether texture is loaded. * @method isLoaded @@ -423,7 +452,6 @@ var Texture2D = cc.Class({ /** * Handler of texture loaded event. * @method handleLoadedTexture - * @param {Boolean} [premultiplied] */ handleLoadedTexture: function () { if (!this._image || !this._image.width || !this._image.height) @@ -948,8 +976,12 @@ JS.get(_p, "pixelHeight", _p.getPixelHeight); return true; }; - // [premultiplied=false] - _p.handleLoadedTexture = function (premultiplied) { + _p.handleLoadedTexture = function () { + // TODO: remove AUTO_PREMULTIPLIED_ALPHA_FOR_PNG + // if (this.premultiplied === undefined) { + // this.premultiplied = cc.macro.AUTO_PREMULTIPLIED_ALPHA_FOR_PNG && + // (this.url && this.url.endsWith(".png")); + // } if (!this._image || !this._image.width || !this._image.height) { return; } @@ -959,7 +991,6 @@ JS.get(_p, "pixelHeight", _p.getPixelHeight); opts.format = PixelFormat.RGBA8888; opts.width = this._image.width; opts.height = this._image.height; - opts.premultiplyAlpha = !!premultiplied; opts.minFilter = cc.view._antiAliasEnabled ? Filter.LINEAR : Filter.NEAREST; this.update(opts); diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js index 47a8e80a6f..13e70544be 100644 --- a/cocos2d/core/textures/CCTextureCache.js +++ b/cocos2d/core/textures/CCTextureCache.js @@ -197,27 +197,26 @@ var textureCache = /** @lends cc.textureCache# */{ if (tex) { if(tex.isLoaded()) { cb && cb.call(target, tex); - return tex; } else { tex.once("load", function(){ cb && cb.call(target, tex); }, target); - return tex; } } + else { + tex = locTexs[url] = new Texture2D(); + tex.url = url; + cc.loader.load(url, function (err, texture) { + if (err) { + return cb && cb.call(target, err || new Error('Unknown error')); + } - tex = locTexs[url] = new Texture2D(); - tex.url = url; - cc.loader.load(url, function (err, texture) { - if (err) { - return cb && cb.call(target, err || new Error('Unknown error')); - } + textureCache.handleLoadedTexture(url); - textureCache.handleLoadedTexture(url); - - cb && cb.call(target, tex); - }); + cb && cb.call(target, tex); + }); + } return tex; }, diff --git a/jsb/jsb-tex-sprite-frame.js b/jsb/jsb-tex-sprite-frame.js index ab67336d4e..e8cc167547 100644 --- a/jsb/jsb-tex-sprite-frame.js +++ b/jsb/jsb-tex-sprite-frame.js @@ -178,20 +178,18 @@ cc.SpriteFrame.$super = cc.Asset; prototype = cc.SpriteFrame.prototype; prototype._setTexture = prototype.setTexture; -prototype._initWithTexture = prototype.initWithTexture; cc.js.mixin(prototype, cc.EventTarget.prototype); prototype._ctor = function (filename, rect, rotated, offset, originalSize) { - this._name = ''; this.insetTop = 0; this.insetBottom = 0; this.insetLeft = 0; this.insetRight = 0; + this._name = ''; + this._texture = null; if (filename !== undefined) { this.initWithTexture(filename, rect, rotated, offset, originalSize); - } else { - //todo log Error } }; @@ -217,7 +215,7 @@ prototype.setTexture = function (textureOrTextureFile, rect, rotated, offset, or if (typeof texture === 'string' && texture) { texture = cc.textureCache.addImage(texture); } - if (texture instanceof cc.Texture2D) { + if (texture instanceof cc.Texture2D && this.getTexture() !== texture) { this._refreshTexture(texture); } @@ -226,52 +224,45 @@ prototype.setTexture = function (textureOrTextureFile, rect, rotated, offset, or prototype.initWithTexture = prototype.setTexture; -prototype._loadTexture = function () { - if (this._textureFilename) { +prototype.ensureLoadTexture = function () { + if (this._texture) { + if (!this._texture.isLoaded()) { + // load exists texture + this._refreshTexture(this._texture); + this._texture.load(); + } + } + else if (this._textureFilename) { + // load new texture var texture = cc.textureCache.addImage(this._textureFilename); this._refreshTexture(texture); } }; -prototype.ensureLoadTexture = function () { - if (!this._texture) { - this._loadTexture(); - } - else { - // TODO - load native texture - } -}; - prototype.clearTexture = function () { this._setTexture(null); }; prototype._refreshTexture = function (texture) { + var w = texture.width, h = texture.height; - if (this.getTexture() !== texture) { - - var w = texture.width, h = texture.height; - - var rect = this.getRect(); - if (rect.width === 0 || rect.height === 0) { - rect = cc.rect(0, 0, w, h); - } - else { - this._checkRect(texture); - } - - var originalSize = this.getOriginalSize(); - if (originalSize.width === 0 || originalSize.height === 0) { - originalSize = cc.size(w, h); - } - var offset = this.getOffset(); - var rotated = this.isRotated(); - - this._initWithTexture(texture, rect, rotated, offset, originalSize); - - //dispatch 'load' event of cc.SpriteFrame - this.emit("load"); + var rect = this.getRect(); + if (rect.width === 0 || rect.height === 0) { + this.setRect(cc.rect(0, 0, w, h)); } + else { + this._checkRect(texture); + } + + var originalSize = this.getOriginalSize(); + if (originalSize.width === 0 || originalSize.height === 0) { + this.setOriginalSize(cc.size(w, h)); + } + + this._setTexture(texture); + + //dispatch 'load' event of cc.SpriteFrame + this.emit("load"); }; prototype._deserialize = function (data, handle) { From c592141bc75197932225db87baf073597108a2d4 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Sun, 8 Oct 2017 13:30:11 +0800 Subject: [PATCH 018/127] fixes --- cocos2d/core/load-pipeline/CCLoader.js | 12 +++++++----- extensions/spine/SkeletonData.js | 2 +- extensions/spine/editor/spine-meta.js | 10 +++------- 3 files changed, 11 insertions(+), 13 deletions(-) diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js index a744b04c2b..434203d816 100644 --- a/cocos2d/core/load-pipeline/CCLoader.js +++ b/cocos2d/core/load-pipeline/CCLoader.js @@ -765,11 +765,13 @@ proto.release = function (asset) { var removed = this.removeItem(id); asset = item.content; // TODO: AUDIO - if (asset instanceof cc.Texture2D) { - asset.destroy(); - } - else if (asset instanceof cc.Asset && asset.nativeUrl) { - this.release(asset.nativeUrl); + if (asset instanceof cc.Asset) { + if (asset instanceof cc.Texture2D) { + asset.destroy(); + } + if (asset.nativeUrl) { + this.release(asset.nativeUrl); + } } if (CC_DEBUG && removed) { this._releasedAssetChecker_DEBUG.setReleased(item, id); diff --git a/extensions/spine/SkeletonData.js b/extensions/spine/SkeletonData.js index fbc761ce13..6b76d9b9b6 100644 --- a/extensions/spine/SkeletonData.js +++ b/extensions/spine/SkeletonData.js @@ -277,7 +277,7 @@ var SkeletonData = cc.Class({ return null; } - var loader = new TextureLoader(this); + var loader = new TextureLoader(this); return this._atlasCache = new sp.spine.TextureAtlas(this.atlasText, loader.load.bind(loader)); } }); diff --git a/extensions/spine/editor/spine-meta.js b/extensions/spine/editor/spine-meta.js index 34153fcce9..1a60e36d54 100644 --- a/extensions/spine/editor/spine-meta.js +++ b/extensions/spine/editor/spine-meta.js @@ -64,8 +64,7 @@ class TextureParser { var uuid = Editor.assetdb.fspathToUuid(path); if (uuid) { console.log('UUID is initialized for "%s".', path); - var url = Editor.assetdb.uuidToUrl(uuid); - this.textures.push(url); + this.textures.push(uuid); var tex = new Spine.Texture({}); tex.setFilters = function() {}; tex.setWraps = function() {}; @@ -179,12 +178,9 @@ class SpineMeta extends CustomAssetMeta { return cb(new Error(`Failed to load atlas file: "${res.atlasPath}". ${err.stack || err}`)); } if (textureParser.textures.length > 0) { - asset.textures = textureParser.textures; - this.textures = textureParser.textures.map(url => Editor.assetdb.urlToUuid(url)); - } - else { - asset.textures = this.textures.map(uuid => Editor.assetdb.uuidToUrl(uuid)); + this.textures = textureParser.textures; } + asset.textures = this.textures.map(Editor.serialize.asAsset); // asset.atlasText = res.data; From 2fa9571205fa54fc8c4547b388080318ccbf1d3b Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Tue, 10 Oct 2017 01:04:43 +0800 Subject: [PATCH 019/127] reviewed --- cocos2d/core/sprites/CCSpriteFrame.js | 76 +++++++++++++-------------- 1 file changed, 38 insertions(+), 38 deletions(-) diff --git a/cocos2d/core/sprites/CCSpriteFrame.js b/cocos2d/core/sprites/CCSpriteFrame.js index f7c1da354b..08365ad974 100644 --- a/cocos2d/core/sprites/CCSpriteFrame.js +++ b/cocos2d/core/sprites/CCSpriteFrame.js @@ -262,6 +262,42 @@ var SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ return this._texture; }, + _textureLoadedCallback () { + var self = this; + var texture = this._texture; + if (!texture) { + // clearTexture called while loading texture... + return; + } + var w = texture.width, h = texture.height; + + if (self._rotated && cc._renderType === cc.game.RENDER_TYPE_CANVAS) { + self._texture = _ccsg.Sprite.CanvasRenderCmd._createRotatedTexture(texture, self.getRect()); + self._rotated = false; + w = self._texture.width; + h = self._texture.height; + self.setRect(cc.rect(0, 0, w, h)); + } + + if (self._rect) { + self._checkRect(self._texture); + } + else { + self.setRect(cc.rect(0, 0, w, h)); + } + + if (!self._originalSize) { + self.setOriginalSize(cc.size(w, h)); + } + + if (!self._offset) { + self.setOffset(cc.v2(0, 0)); + } + + // dispatch 'load' event of cc.SpriteFrame + self.emit("load"); + }, + /* * !#en Sets the texture of the frame. * !#zh 设置使用的纹理实例。 @@ -269,48 +305,12 @@ var SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ * @param {Texture2D} texture */ _refreshTexture: function (texture) { - var self = this; this._texture = texture; - - function textureLoadedCallback () { - if (!self._texture) { - // clearTexture called while loading texture... - return; - } - var w = texture.width, h = texture.height; - - if (self._rotated && cc._renderType === cc.game.RENDER_TYPE_CANVAS) { - self._texture = _ccsg.Sprite.CanvasRenderCmd._createRotatedTexture(texture, self.getRect()); - self._rotated = false; - w = self._texture.width; - h = self._texture.height; - self.setRect(cc.rect(0, 0, w, h)); - } - - if (self._rect) { - self._checkRect(self._texture); - } - else { - self.setRect(cc.rect(0, 0, w, h)); - } - - if (!self._originalSize) { - self.setOriginalSize(cc.size(w, h)); - } - - if (!self._offset) { - self.setOffset(cc.v2(0, 0)); - } - - // dispatch 'load' event of cc.SpriteFrame - self.emit("load"); - } - if (texture.loaded) { - textureLoadedCallback(); + this._textureLoadedCallback(); } else { - texture.once("load", textureLoadedCallback); + texture.once('load', this._textureLoadedCallback, this); } }, From 145b2fcecf103da9fbb44b77ec24f4bc9ea8dede Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Mon, 9 Oct 2017 14:59:19 +0800 Subject: [PATCH 020/127] support spine --- extensions/spine/Skeleton.js | 47 ++++++++++------ extensions/spine/SkeletonData.js | 77 +++++++++------------------ extensions/spine/editor/spine-meta.js | 22 ++++---- 3 files changed, 66 insertions(+), 80 deletions(-) diff --git a/extensions/spine/Skeleton.js b/extensions/spine/Skeleton.js index 17fdec539f..e1c1469317 100644 --- a/extensions/spine/Skeleton.js +++ b/extensions/spine/Skeleton.js @@ -402,33 +402,46 @@ sp.Skeleton = cc.Class({ }, _createSgNode: function () { - if (this.skeletonData/* && self.atlasFile*/) { + var skeletonData = this.skeletonData; + if (skeletonData/* && self.atlasFile*/) { if (CC_JSB) { - var uuid = this.skeletonData._uuid; + var uuid = skeletonData._uuid; if ( !uuid ) { cc.errorID(7504); return null; } - var jsonFile = this.skeletonData.nativeUrl; - var atlasFile = this.skeletonData.atlasUrl; - if (atlasFile) { - if (typeof atlasFile !== 'string') { - cc.errorID(7505); - return null; - } - try { - return new sp._SGSkeletonAnimation(jsonFile, atlasFile, this.skeletonData.scale); - } - catch (e) { - cc._throw(e); - } + var jsonFile = skeletonData.nativeUrl; + var atlasText = skeletonData.atlasText; + if (!atlasText) { + cc.errorID(7508, skeletonData.name); + return null; } + var texValues = skeletonData.textures; + var texKeys = skeletonData.textureNames; + if ( !(texValues && texValues.length > 0 && texKeys && texKeys.length > 0) ) { + cc.errorID(7507, skeletonData.name); + return null; + } + var textures = {}; + for (var i = 0; i < texValues.length; ++i) { + textures[texKeys[i]] = texValues[i]; + } + + var sgNode = new sp._SGSkeletonAnimation(); + try { + sp._initSkeletonRenderer(sgNode, jsonFile, atlasText, textures, skeletonData.scale); + } + catch (e) { + cc._throw(e); + return null; + } + return sgNode; } else { - var data = this.skeletonData.getRuntimeData(); + var data = skeletonData.getRuntimeData(); if (data) { try { - return new sp._SGSkeletonAnimation(data, null, this.skeletonData.scale); + return new sp._SGSkeletonAnimation(data, null, skeletonData.scale); } catch (e) { cc._throw(e); diff --git a/extensions/spine/SkeletonData.js b/extensions/spine/SkeletonData.js index 6b76d9b9b6..4b9204cbf7 100644 --- a/extensions/spine/SkeletonData.js +++ b/extensions/spine/SkeletonData.js @@ -27,48 +27,6 @@ * @module sp */ -// implements a simple texture loader like sp._atlasLoader -var TextureLoader = !CC_JSB && cc.Class({ - ctor: function () { - // {SkeletonData} - this.asset = arguments[0]; - }, - getTexture: function (line) { - //var name = cc.path.mainFileName(line); - //var textures = this.asset.textures; - //for (var i = 0; i < textures.length; i++) { - // var tex = textures[i]; - // if (tex.name === name) { - // return tex; - // } - //} - var textures = this.asset.textures; - for (var i = 0; i < textures.length; i++) { - var texture = textures[i]; - var url = texture && texture.url; - if (url.endsWith(line)) { - var tex = new sp.SkeletonTexture({ width: texture.getPixelWidth(), height: texture.getPixelHeight() }); - tex.setRealTexture(texture); - return tex; - } - } - return null; - }, - load: function (line) { - var texture = this.getTexture(line); - if (texture) { - return texture; - } - else { - cc.errorID(7506, line); - return null; - } - }, - unload: function (obj) { - //page.rendererObject.release(); - } -}); - /** * !#en The skeleton data of spine. * !#zh Spine 的 骨骼数据。 @@ -117,13 +75,6 @@ var SkeletonData = cc.Class({ } }, - // Fallback to raw asset for JSB ------------------- - atlasUrl: { - default: '', - url: cc.RawAsset - }, - // ------------------------------------------------- - /** * @property {Texture2D[]} textures */ @@ -132,6 +83,15 @@ var SkeletonData = cc.Class({ type: [cc.Texture2D] }, + /** + * @property {String[]} textureNames + * @private + */ + textureNames: { + default: [], + type: [cc.String] + }, + /** * !#en * A scale can be specified on the JSON or binary loader which will scale the bone positions, @@ -199,7 +159,7 @@ var SkeletonData = cc.Class({ } - if ( !(this.textures && this.textures.length > 0) ) { + if ( !(this.textures && this.textures.length > 0 && this.textureNames && this.textureNames.length > 0) ) { if ( !quiet ) { cc.errorID(7507, this.name); } @@ -259,6 +219,20 @@ var SkeletonData = cc.Class({ // PRIVATE + _getTexture: !CC_JSB && function (line) { + var names = this.textureNames; + for (var i = 0; i < names.length; i++) { + if (names[i] === line) { + var texture = this.textures[i]; + var tex = new sp.SkeletonTexture({ width: texture.getPixelWidth(), height: texture.getPixelHeight() }); + tex.setRealTexture(texture); + return tex; + } + } + cc.errorID(7506, line); + return null; + }, + /** * @method _getAtlas * @param {boolean} [quiet=false] @@ -277,8 +251,7 @@ var SkeletonData = cc.Class({ return null; } - var loader = new TextureLoader(this); - return this._atlasCache = new sp.spine.TextureAtlas(this.atlasText, loader.load.bind(loader)); + return this._atlasCache = new sp.spine.TextureAtlas(this.atlasText, this._getTexture.bind(this)); } }); diff --git a/extensions/spine/editor/spine-meta.js b/extensions/spine/editor/spine-meta.js index 1a60e36d54..5e9fdb63eb 100644 --- a/extensions/spine/editor/spine-meta.js +++ b/extensions/spine/editor/spine-meta.js @@ -54,8 +54,10 @@ function loadAtlasText (skeletonPath, callback) { class TextureParser { constructor (atlasPath) { this.atlasPath = atlasPath; - // the loaded texture array + // array of loaded texture uuid this.textures = []; + // array of corresponding line + this.textureNames = []; } load (line) { var name = Path.basename(line); @@ -65,6 +67,7 @@ class TextureParser { if (uuid) { console.log('UUID is initialized for "%s".', path); this.textures.push(uuid); + this.textureNames.push(line); var tex = new Spine.Texture({}); tex.setFilters = function() {}; tex.setWraps = function() {}; @@ -80,7 +83,6 @@ class TextureParser { return null; } - unload () {} } const RAW_SKELETON_FILE = 'raw-skeleton.json'; @@ -103,7 +105,7 @@ class SpineMeta extends CustomAssetMeta { //this.textures[0] = value; } - static version () { return '1.1.0'; } + static version () { return '1.2.0'; } static defaultType () { return 'spine'; } @@ -171,30 +173,28 @@ class SpineMeta extends CustomAssetMeta { // parse atlas textures var textureParser = new TextureParser(res.atlasPath); + try { new Spine.TextureAtlas(res.data, textureParser.load.bind(textureParser)); } catch (err) { return cb(new Error(`Failed to load atlas file: "${res.atlasPath}". ${err.stack || err}`)); } - if (textureParser.textures.length > 0) { - this.textures = textureParser.textures; - } - asset.textures = this.textures.map(Editor.serialize.asAsset); + this.textures = textureParser.textures; + asset.textures = textureParser.textures.map(Editor.serialize.asAsset); + asset.textureNames = textureParser.textureNames; // asset.atlasText = res.data; // save raw assets for JSB.. - var atlasUuid = db.fspathToUuid(res.atlasPath); - asset.atlasUrl = db.uuidToUrl(atlasUuid); - db.mkdirForAsset(this.uuid); var rawJsonPath = Path.join(db._uuidToImportPathNoExt(this.uuid), RAW_SKELETON_FILE); Fs.copySync(fspath, rawJsonPath); asset._setRawAsset(RAW_SKELETON_FILE); - + + var atlasUuid = db.fspathToUuid(res.atlasPath); this.atlas = atlasUuid; // save for dest() // From e0cf0a1533d6015c3cc77a202dccd778a3c96a00 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Mon, 23 Oct 2017 15:35:36 +0800 Subject: [PATCH 021/127] refine --- DebugInfos.js | 4 ++-- cocos2d/core/sprites/CCSpriteFrame.js | 8 ++++---- jsb/jsb-tex-sprite-frame.js | 1 + package.json | 1 - 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/DebugInfos.js b/DebugInfos.js index 7476d4896c..ef9bda2064 100644 --- a/DebugInfos.js +++ b/DebugInfos.js @@ -241,9 +241,9 @@ if (CC_DEBUG) { "3116": "WebGLRenderingContext.CLAMP_TO_EDGE should be used in NPOT textures", //setTexParameters "3117": "Mimpap texture only works in POT textures", //generateMipmap //RectWidth: 3300 - "3300": "Rect width exceeds maximum margin: %s", //RectWidth + "3300": "Rect width exceeds maximum margin: %s, max x: %s, texture width: %s", //RectWidth //RectHeight: 3400 - "3400": "Rect height exceeds maximum margin: %s", //RectHeight + "3400": "Rect height exceeds maximum margin: %s, max y: %s, texture height: %s", //RectHeight //EventManager: 3500 "3500": "0 priority is forbidden for fixed priority since it's used for scene graph based priority.", //addListener "3501": "Invalid listener type!", //removeListeners diff --git a/cocos2d/core/sprites/CCSpriteFrame.js b/cocos2d/core/sprites/CCSpriteFrame.js index 08365ad974..1a855272c8 100644 --- a/cocos2d/core/sprites/CCSpriteFrame.js +++ b/cocos2d/core/sprites/CCSpriteFrame.js @@ -452,11 +452,11 @@ var SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ maxX += rect.width; maxY += rect.height; } - if (maxX > texture.getPixelWidth()) { - cc.errorID(3300, texture.url + '/' + this.name); + if (maxX > texture.width) { + cc.errorID(3300, texture.url + '/' + this.name, maxX, texture.width); } - if (maxY > texture.getPixelHeight()) { - cc.errorID(3400, texture.url + '/' + this.name); + if (maxY > texture.height) { + cc.errorID(3400, texture.url + '/' + this.name, maxY, texture.height); } }, diff --git a/jsb/jsb-tex-sprite-frame.js b/jsb/jsb-tex-sprite-frame.js index e8cc167547..172c5d3250 100644 --- a/jsb/jsb-tex-sprite-frame.js +++ b/jsb/jsb-tex-sprite-frame.js @@ -331,4 +331,5 @@ prototype.clone = function () { return cloned; }; +cc.js.getset(prototype, 'texture', prototype.getTexture, prototype.setTexture); cc.js.addon(prototype, WebSpriteFrame.prototype); diff --git a/package.json b/package.json index 7b9ece30df..7a5745c08f 100644 --- a/package.json +++ b/package.json @@ -44,7 +44,6 @@ "jshint-stylish": "2.1.0", "multipipe": "0.3.0", "persistify": "^1.1.1", - "require-dir": "0.3.0", "uglify-es": "^3.0.26", "vinyl": "1.1.0", "vinyl-buffer": "1.0.0", From 2a1ad289e3b5a18e99c1b0019132a1ca1044895f Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Tue, 24 Oct 2017 17:02:02 +0800 Subject: [PATCH 022/127] escape Unicode characters in strings and regexps --- gulp/util/utils.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/gulp/util/utils.js b/gulp/util/utils.js index a41839f33d..c6e288a952 100644 --- a/gulp/util/utils.js +++ b/gulp/util/utils.js @@ -43,6 +43,9 @@ exports.getUglifyOptions = function (platform, isJSB, isDebugBuild) { return { compress: { global_defs: global_defs, + }, + output: { + ascii_only: true, } }; } @@ -54,6 +57,7 @@ exports.getUglifyOptions = function (platform, isJSB, isDebugBuild) { // http://lisperator.net/uglifyjs/codegen beautify: true, indent_level: 2, + ascii_only: true, }, compress: { // https://github.com/mishoo/UglifyJS2#compressor-options From 6eb5d3bb943e545b52da48a5df2e0d12a093c06e Mon Sep 17 00:00:00 2001 From: Olivier Bouton Date: Wed, 25 Oct 2017 16:33:55 +0200 Subject: [PATCH 023/127] Fix sys.os being undefined on Ubuntu Mate, now equals to sys.OS_LINUX --- cocos2d/core/platform/CCSys.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCSys.js b/cocos2d/core/platform/CCSys.js index f9949dcca1..732fe77234 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -198,6 +198,11 @@ sys.OS_MARMALADE = "Marmalade"; * @readOnly */ sys.OS_LINUX = "Linux"; +/** + * @property {String} OS_UNIX + * @readOnly + */ +sys.OS_UNIX = "Unix"; /** * @property {String} OS_BADA * @readOnly @@ -561,9 +566,9 @@ else { if (nav.appVersion.indexOf("Win") !== -1) osName = sys.OS_WINDOWS; else if (iOS) osName = sys.OS_IOS; else if (nav.appVersion.indexOf("Mac") !== -1) osName = sys.OS_OSX; - else if (nav.appVersion.indexOf("X11") !== -1 && nav.appVersion.indexOf("Linux") === -1) osName = sys.OS_UNIX; else if (isAndroid) osName = sys.OS_ANDROID; else if (nav.appVersion.indexOf("Linux") !== -1 || ua.indexOf("ubuntu") !== -1) osName = sys.OS_LINUX; + else if (nav.appVersion.indexOf("X11") !== -1 && nav.appVersion.indexOf("Linux") === -1) osName = sys.OS_UNIX; /** * Indicate the running os name From e3a588169cd85a4340f087a6e44f311ad7cbffe5 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 26 Oct 2017 10:48:13 +0800 Subject: [PATCH 024/127] working on texture --- cocos2d/core/assets/CCAsset.js | 1 + cocos2d/core/load-pipeline/pack-downloader.js | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/assets/CCAsset.js b/cocos2d/core/assets/CCAsset.js index 2bf06afd3b..96655a46ee 100644 --- a/cocos2d/core/assets/CCAsset.js +++ b/cocos2d/core/assets/CCAsset.js @@ -183,6 +183,7 @@ cc.Asset = cc.Class({ /** * Set native file name for this asset. + * @seealso nativeUrl * * @method _setRawAsset * @param {String} filename diff --git a/cocos2d/core/load-pipeline/pack-downloader.js b/cocos2d/core/load-pipeline/pack-downloader.js index 739ba23f77..0dbd87ff13 100644 --- a/cocos2d/core/load-pipeline/pack-downloader.js +++ b/cocos2d/core/load-pipeline/pack-downloader.js @@ -100,7 +100,7 @@ module.exports = { if (Array.isArray(packedJson)) { unpackerData.unpacker = new Unpackers.JsonUnpacker(); } - else if (packedJson.type === TextureUnpacker.ID) { + else if (packedJson.type === Unpackers.TextureUnpacker.ID) { unpackerData.unpacker = new Unpackers.TextureUnpacker(); } unpackerData.unpacker.load(packIndices[packUuid], packedJson); From d11eacb0fe8708c5bd4d512226b2ffe8e4871fcf Mon Sep 17 00:00:00 2001 From: feijing566 Date: Mon, 30 Oct 2017 10:41:42 +0800 Subject: [PATCH 025/127] [dragonbones]miss clone _hasListenerCache --- extensions/dragonbones/ArmatureDisplay.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/extensions/dragonbones/ArmatureDisplay.js b/extensions/dragonbones/ArmatureDisplay.js index 585b276ee4..1503dfaa44 100644 --- a/extensions/dragonbones/ArmatureDisplay.js +++ b/extensions/dragonbones/ArmatureDisplay.js @@ -381,9 +381,10 @@ dragonBones.ArmatureDisplay = cc.Class({ var self = this; // discard exists sgNode - var listenersBefore = null; + var listenersBefore = null, listenerCacheBefore = null; if (self._sgNode) { listenersBefore = self._sgNode._bubblingListeners; // get the listeners added before + listenerCacheBefore = self._sgNode._hasListenerCache; if ( self.node._sizeProvider === self._sgNode ) { self.node._sizeProvider = null; } @@ -403,6 +404,7 @@ dragonBones.ArmatureDisplay = cc.Class({ if (listenersBefore) { sgNode._bubblingListeners = listenersBefore; // using the listeners added before + sgNode._hasListenerCache = listenerCacheBefore; if (CC_JSB && !sgNode.hasEventCallback()) { // In JSB, should set event callback of the new sgNode // to make the listeners work well. From 64c96b937163e7fe4cc3e8795f693f7aeb676ac5 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 2 Nov 2017 21:36:46 +0800 Subject: [PATCH 026/127] Adaptation WeChatGame --- cocos2d/audio/CCAudio.js | 16 ++-- cocos2d/core/CCGame.js | 78 +++++++++++-------- .../core/load-pipeline/audio-downloader.js | 11 ++- cocos2d/core/load-pipeline/downloader.js | 7 ++ cocos2d/core/load-pipeline/loader.js | 3 +- cocos2d/core/platform/CCInputManager.js | 43 +++++++--- cocos2d/core/platform/CCSys.js | 21 ++++- cocos2d/core/platform/CCView.js | 64 ++++++++++----- 8 files changed, 168 insertions(+), 75 deletions(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index a62b732a6f..2a899f4a1f 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -137,7 +137,7 @@ Audio.State = { }; proto.mount = function (elem) { - if (elem instanceof HTMLElement) { + if (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME || elem instanceof HTMLElement) { this._element = document.createElement('audio'); this._element.src = elem.src; this._audioType = Audio.Type.DOM; @@ -156,7 +156,9 @@ Audio.State = { this.emit('play'); this._state = Audio.State.PLAYING; - if (this._audioType === Audio.Type.DOM && this._element.paused) { + if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME && + this._audioType === Audio.Type.DOM && + this._element.paused) { touchPlayList.push({ instance: this, offset: 0, audio: this._element }); } @@ -225,9 +227,11 @@ Audio.State = { proto.setCurrentTime = function (num) { if (!this._element) return; this._unbindEnded(); - this._bindEnded(function () { - this._bindEnded(); - }.bind(this)); + if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME) { + this._bindEnded(function () { + this._bindEnded(); + }.bind(this)); + } try { this._element.currentTime = num; } catch (err) { @@ -347,7 +351,7 @@ var WebAudioElement = function (buffer, audio) { var self = this; clearTimeout(this._currextTimer); this._currextTimer = setTimeout(function () { - if (self._context.currentTime === 0) { + if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME && self._context.currentTime === 0) { touchPlayList.push({ instance: self._audio, offset: offset, diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index a004c5dac6..4d98daea70 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -647,52 +647,62 @@ var game = { var el = this.config[game.CONFIG_KEY.id], win = window, - element = (el instanceof HTMLElement) ? el : (document.querySelector(el) || document.querySelector('#' + el)), - localCanvas, localContainer; - - if (element.tagName === "CANVAS") { - width = width || element.width; - height = height || element.height; - - //it is already a canvas, we wrap it around with a div - this.canvas = cc._canvas = localCanvas = element; + localCanvas, localContainer, + isWeChatGame = cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME; + + if (isWeChatGame) { this.container = cc.container = localContainer = document.createElement("DIV"); - if (localCanvas.parentNode) - localCanvas.parentNode.insertBefore(localContainer, localCanvas); - } else { - //we must make a new canvas and place into this element - if (element.tagName !== "DIV") { - cc.warnID(3819); - } - width = width || element.clientWidth; - height = height || element.clientHeight; - this.canvas = cc._canvas = localCanvas = document.createElement("CANVAS"); - this.container = cc.container = localContainer = document.createElement("DIV"); - element.appendChild(localContainer); + this.frame = localContainer.parentNode === document.body ? document.documentElement : localContainer.parentNode; + this.canvas = cc._canvas = localCanvas = window['canvas']; } - localContainer.setAttribute('id', 'Cocos2dGameContainer'); - localContainer.appendChild(localCanvas); - this.frame = (localContainer.parentNode === document.body) ? document.documentElement : localContainer.parentNode; + else { + var element = (el instanceof HTMLElement) ? el : (document.querySelector(el) || document.querySelector('#' + el)); - function addClass (element, name) { - var hasClass = (' ' + element.className + ' ').indexOf(' ' + name + ' ') > -1; - if (!hasClass) { - if (element.className) { - element.className += " "; + if (element.tagName === "CANVAS") { + width = width || element.width; + height = height || element.height; + + //it is already a canvas, we wrap it around with a div + this.canvas = cc._canvas = localCanvas = element; + this.container = cc.container = localContainer = document.createElement("DIV"); + if (localCanvas.parentNode) + localCanvas.parentNode.insertBefore(localContainer, localCanvas); + } else { + //we must make a new canvas and place into this element + if (element.tagName !== "DIV") { + cc.warnID(3819); } - element.className += name; + width = width || element.clientWidth; + height = height || element.clientHeight; + this.canvas = cc._canvas = localCanvas = document.createElement("CANVAS"); + this.container = cc.container = localContainer = document.createElement("DIV"); + element.appendChild(localContainer); } + localContainer.setAttribute('id', 'Cocos2dGameContainer'); + localContainer.appendChild(localCanvas); + this.frame = (localContainer.parentNode === document.body) ? document.documentElement : localContainer.parentNode; + + function addClass (element, name) { + var hasClass = (' ' + element.className + ' ').indexOf(' ' + name + ' ') > -1; + if (!hasClass) { + if (element.className) { + element.className += " "; + } + element.className += name; + } + } + addClass(localCanvas, "gameCanvas"); + localCanvas.setAttribute("width", width || 480); + localCanvas.setAttribute("height", height || 320); + localCanvas.setAttribute("tabindex", 99); } - addClass(localCanvas, "gameCanvas"); - localCanvas.setAttribute("width", width || 480); - localCanvas.setAttribute("height", height || 320); - localCanvas.setAttribute("tabindex", 99); if (cc._renderType === game.RENDER_TYPE_WEBGL) { this._renderContext = cc._renderContext = cc.webglContext = cc.create3DContext(localCanvas, { 'stencil': true, 'alpha': cc.macro.ENABLE_TRANSPARENT_CANVAS, + 'preserveDrawingBuffer': isWeChatGame }); } // WebGL context created successfully diff --git a/cocos2d/core/load-pipeline/audio-downloader.js b/cocos2d/core/load-pipeline/audio-downloader.js index b8d12615a3..9cee1057bd 100644 --- a/cocos2d/core/load-pipeline/audio-downloader.js +++ b/cocos2d/core/load-pipeline/audio-downloader.js @@ -24,17 +24,24 @@ ****************************************************************************/ var Path = require('../utils/CCPath'); -var Sys = require('../platform/CCSys'); +var sys = require('../platform/CCSys'); var Pipeline = require('./pipeline'); var audioEngine = require('../../audio/CCAudioEngine'); -var __audioSupport = Sys.__audioSupport; +var __audioSupport = sys.__audioSupport; var formatSupport = __audioSupport.format; var context = __audioSupport.context; function loadDomAudio (item, callback) { var dom = document.createElement('audio'); dom.src = item.url; + + if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { + item.element = dom; + callback(null, item.url); + return; + } + var clearEvent = function () { clearTimeout(timer); dom.removeEventListener("canplaythrough", success, false); diff --git a/cocos2d/core/load-pipeline/downloader.js b/cocos2d/core/load-pipeline/downloader.js index af59c3b0bc..53bc9ed6ba 100644 --- a/cocos2d/core/load-pipeline/downloader.js +++ b/cocos2d/core/load-pipeline/downloader.js @@ -23,6 +23,7 @@ THE SOFTWARE. ****************************************************************************/ var JS = require('../platform/js'); +var sys = require('../platform/CCSys'); var Path = require('../utils/CCPath'); var misc = require('../utils/misc'); var Pipeline = require('./pipeline'); @@ -41,6 +42,12 @@ else { } function downloadScript (item, callback, isAsync) { + if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { + require(item.url); + callback(null, item.url); + return; + } + var url = item.url, d = document, s = document.createElement('script'); diff --git a/cocos2d/core/load-pipeline/loader.js b/cocos2d/core/load-pipeline/loader.js index 595e7c0b87..f6399995c3 100644 --- a/cocos2d/core/load-pipeline/loader.js +++ b/cocos2d/core/load-pipeline/loader.js @@ -24,6 +24,7 @@ ****************************************************************************/ var JS = require('../platform/js'); +var sys = require('../platform/CCSys'); var Pipeline = require('./pipeline'); var Texture2D = require('../textures/CCTexture2D'); var loadUuid = require('./uuid-loader'); @@ -48,7 +49,7 @@ function loadJSON (item, callback) { } function loadImage (item, callback) { - if (!(item.content instanceof Image)) { + if (sys.browserType !== sys.BROWSER_TYPE_WECHAT_GAME && !(item.content instanceof Image)) { return new Error('Image Loader: Input item doesn\'t contain Image content'); } var rawUrl = item.rawUrl; diff --git a/cocos2d/core/platform/CCInputManager.js b/cocos2d/core/platform/CCInputManager.js index fea9a16b73..45c6b0b00d 100644 --- a/cocos2d/core/platform/CCInputManager.js +++ b/cocos2d/core/platform/CCInputManager.js @@ -24,6 +24,7 @@ ****************************************************************************/ var macro = require('./CCMacro'); +var sys = require('./CCSys'); var TOUCH_TIMEOUT = macro.TOUCH_TIMEOUT; @@ -96,7 +97,7 @@ var inputManager = { handleTouchesBegin: function (touches) { var selTouch, index, curTouch, touchID, handleTouches = [], locTouchIntDict = this._touchesIntegerDict, - now = cc.sys.now(); + now = sys.now(); for(var i = 0, len = touches.length; i< len; i ++){ selTouch = touches[i]; touchID = selTouch.getID(); @@ -131,7 +132,7 @@ var inputManager = { handleTouchesMove: function(touches){ var selTouch, index, touchID, handleTouches = [], locTouches = this._touches, - now = cc.sys.now(); + now = sys.now(); for(var i = 0, len = touches.length; i< len; i ++){ selTouch = touches[i]; touchID = selTouch.getID(); @@ -216,6 +217,15 @@ var inputManager = { * @return {Object} */ getHTMLElementPosition: function (element) { + if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { + return { + left: 0, + top: 0, + width: window.innerWidth, + height: window.innerHeight + }; + } + var docElem = document.documentElement; var leftOffset = window.pageXOffset - docElem.clientLeft; var topOffset = window.pageYOffset - docElem.clientTop; @@ -338,8 +348,14 @@ var inputManager = { if (event.pageX != null) //not avalable in <= IE8 return {x: event.pageX, y: event.pageY}; - pos.left -= document.body.scrollLeft; - pos.top -= document.body.scrollTop; + if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { + pos.left = 0; + pos.top = 0; + } + else { + pos.left -= document.body.scrollLeft; + pos.top -= document.body.scrollTop; + } return {x: event.clientX, y: event.clientY}; }, @@ -359,7 +375,7 @@ var inputManager = { touch_event = event.changedTouches[i]; if (touch_event) { var location; - if (cc.sys.BROWSER_TYPE_FIREFOX === cc.sys.browserType) + if (sys.BROWSER_TYPE_FIREFOX === sys.browserType) location = locView.convertToLocationInView(touch_event.pageX, touch_event.pageY, pos); else location = locView.convertToLocationInView(touch_event.clientX, touch_event.clientY, pos); @@ -391,7 +407,16 @@ var inputManager = { this._glView = cc.view; var selfPointer = this; - var supportMouse = ('mouse' in cc.sys.capabilities); + var prohibition = sys.isMobile; + var supportMouse = ('mouse' in sys.capabilities); + var supportTouches = ('touches' in sys.capabilities); + + if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { + prohibition = false; + supportTouches = true; + supportMouse = false; + } + if (supportMouse) { //HACK // - At the same time to trigger the ontouch event and onmouse event @@ -400,7 +425,6 @@ var inputManager = { // liebiao // miui // WECHAT - var prohibition = cc.sys.isMobile; if (!prohibition) { window.addEventListener('mousedown', function () { selfPointer._mousePressed = true; @@ -493,12 +517,13 @@ var inputManager = { } //register touch event - var supportTouches = ('touches' in cc.sys.capabilities); if (supportTouches) { var _touchEventsMap = { "touchstart": function (touchesToHandle) { selfPointer.handleTouchesBegin(touchesToHandle); - element.focus(); + if (sys.browserType !== sys.BROWSER_TYPE_WECHAT_GAME) { + element.focus(); + } }, "touchmove": function (touchesToHandle) { selfPointer.handleTouchesMove(touchesToHandle); diff --git a/cocos2d/core/platform/CCSys.js b/cocos2d/core/platform/CCSys.js index 319b9a35af..ee884a4cf5 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -341,6 +341,13 @@ sys.EDITOR_CORE = 103; * @default "wechat" */ sys.BROWSER_TYPE_WECHAT = "wechat"; +/** + * BROWSER_TYPE_WECHAT_GAME + * @property {String} BROWSER_TYPE_WECHAT_GAME + * @readOnly + * @default "wechatgame" + */ +sys.BROWSER_TYPE_WECHAT_GAME = "wechatgame"; /** * * @property {String} BROWSER_TYPE_ANDROID @@ -487,6 +494,10 @@ sys.isNative = false; */ sys.isBrowser = typeof window === 'object' && typeof document === 'object'; +function isWeChatGame () { + return window['wx']; +} + if (CC_EDITOR && Editor.isMainProcess) { sys.isMobile = false; sys.platform = sys.EDITOR_CORE; @@ -593,7 +604,9 @@ else { var browserTypes = typeReg1.exec(ua); if(!browserTypes) browserTypes = typeReg2.exec(ua); var browserType = browserTypes ? browserTypes[0].toLowerCase() : sys.BROWSER_TYPE_UNKNOWN; - if (browserType === 'micromessenger') + if (isWeChatGame()) + browserType = sys.BROWSER_TYPE_WECHAT_GAME; + else if (browserType === 'micromessenger') browserType = sys.BROWSER_TYPE_WECHAT; else if (browserType === "safari" && isAndroid) browserType = sys.BROWSER_TYPE_ANDROID; @@ -761,6 +774,9 @@ else { } } } + else if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { + _supportWebGL = true; + } /** * The capabilities of the current platform @@ -803,7 +819,8 @@ else { // check if browser supports Web Audio // check Web Audio's context - var supportWebAudio = !!(window.AudioContext || window.webkitAudioContext || window.mozAudioContext); + var supportWebAudio = sys.browserType !== sys.BROWSER_TYPE_WECHAT_GAME && + !!(window.AudioContext || window.webkitAudioContext || window.mozAudioContext); __audioSupport = { ONLY_ONE: false, WEB_AUDIO: supportWebAudio, DELAY_CREATE_CTX: false }; diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index 7133a3b434..0e67ff9316 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -24,18 +24,24 @@ THE SOFTWARE. ****************************************************************************/ +function isWeChatGame () { + return window['wx']; +} + var __BrowserGetter = { init: function(){ - this.html = document.getElementsByTagName("html")[0]; + if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME) { + this.html = document.getElementsByTagName("html")[0]; + } }, availWidth: function(frame){ - if(!frame || frame === this.html) + if (!frame || frame === this.html) return window.innerWidth; else return frame.clientWidth; }, availHeight: function(frame){ - if(!frame || frame === this.html) + if (!frame || frame === this.html) return window.innerHeight; else return frame.clientHeight; @@ -46,13 +52,17 @@ var __BrowserGetter = { adaptationType: cc.sys.browserType }; -if(window.navigator.userAgent.indexOf("OS 8_1_") > -1) //this mistake like MIUI, so use of MIUI treatment method +if (window.navigator.userAgent.indexOf("OS 8_1_") > -1) //this mistake like MIUI, so use of MIUI treatment method __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_MIUI; -if(cc.sys.os === cc.sys.OS_IOS) // All browsers are WebView +if (cc.sys.os === cc.sys.OS_IOS) // All browsers are WebView __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_SAFARI; -switch(__BrowserGetter.adaptationType){ +if (isWeChatGame()) { + __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_WECHAT_GAME; +} + +switch (__BrowserGetter.adaptationType) { case cc.sys.BROWSER_TYPE_SAFARI: __BrowserGetter.meta["minimal-ui"] = "true"; __BrowserGetter.availWidth = function(frame){ @@ -90,6 +100,14 @@ switch(__BrowserGetter.adaptationType){ window.addEventListener("resize", resize, false); }; break; + case cc.sys.BROWSER_TYPE_WECHAT_GAME: + __BrowserGetter.availWidth = function(frame){ + return frame.innerWidth; + }; + __BrowserGetter.availHeight = function(frame){ + return frame.innerHeight; + }; + break; } var _scissorRect = null; @@ -377,7 +395,7 @@ var View = cc._Class.extend({ }, _adjustViewportMeta: function () { - if (this._isAdjustViewPort) { + if (this._isAdjustViewPort && cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME) { this._setViewportMeta(__BrowserGetter.meta, false); this._isAdjustViewPort = false; } @@ -810,14 +828,16 @@ var View = cc._Class.extend({ * @param {ResolutionPolicy|Number} resolutionPolicy The resolution policy desired */ setRealPixelResolution: function (width, height, resolutionPolicy) { - // Set viewport's width - this._setViewportMeta({"width": width}, true); + if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME) { + // Set viewport's width + this._setViewportMeta({"width": width}, true); - // Set body width to the exact pixel resolution - document.documentElement.style.width = width + "px"; - document.body.style.width = width + "px"; - document.body.style.left = "0px"; - document.body.style.top = "0px"; + // Set body width to the exact pixel resolution + document.documentElement.style.width = width + "px"; + document.body.style.width = width + "px"; + document.body.style.left = "0px"; + document.body.style.top = "0px"; + } // Reset the resolution size and policy this.setDesignResolutionSize(width, height, resolutionPolicy); @@ -1043,14 +1063,16 @@ cc.ContainerStrategy = cc._Class.extend(/** @lends cc.ContainerStrategy# */{ _setupContainer: function (view, w, h) { var locCanvas = cc.game.canvas, locContainer = cc.game.container; - if (cc.sys.os === cc.sys.OS_ANDROID) { - document.body.style.width = (view._isRotated ? h : w) + 'px'; - document.body.style.height = (view._isRotated ? w : h) + 'px'; - } - // Setup style - locContainer.style.width = locCanvas.style.width = w + 'px'; - locContainer.style.height = locCanvas.style.height = h + 'px'; + if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME) { + if (cc.sys.os === cc.sys.OS_ANDROID) { + document.body.style.width = (view._isRotated ? h : w) + 'px'; + document.body.style.height = (view._isRotated ? w : h) + 'px'; + } + // Setup style + locContainer.style.width = locCanvas.style.width = w + 'px'; + locContainer.style.height = locCanvas.style.height = h + 'px'; + } // Setup pixel ratio for retina display var devicePixelRatio = view._devicePixelRatio = 1; if (view.isRetinaEnabled()) From afd6f4c2da35ad1eb7ef88b447a245d8c5feff20 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 3 Nov 2017 16:43:13 +0800 Subject: [PATCH 027/127] Running on wechatgame --- cocos2d/core/CCDrawingPrimitivesWebGL.js | 2 +- cocos2d/core/CCGame.js | 2 +- cocos2d/core/load-pipeline/text-downloader.js | 36 ++++++++++++++++--- cocos2d/core/platform/CCInputManager.js | 4 +-- cocos2d/core/platform/CCSys.js | 16 ++++----- cocos2d/core/platform/CCView.js | 8 ++--- cocos2d/core/textures/CCTexture2D.js | 1 + cocos2d/core/videoplayer/CCSGVideoPlayer.js | 18 ++++++---- 8 files changed, 60 insertions(+), 27 deletions(-) diff --git a/cocos2d/core/CCDrawingPrimitivesWebGL.js b/cocos2d/core/CCDrawingPrimitivesWebGL.js index 54b3adeeda..b88de5c44d 100644 --- a/cocos2d/core/CCDrawingPrimitivesWebGL.js +++ b/cocos2d/core/CCDrawingPrimitivesWebGL.js @@ -43,7 +43,7 @@ var DrawingPrimitiveWebGL = cc._Class.extend({ * @param ctx rendercontext */ ctor:function (ctx) { - if (!ctx instanceof WebGLRenderingContext) + if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME && !ctx instanceof WebGLRenderingContext) throw new Error("Can't initialise DrawingPrimitiveWebGL. context need is WebGLRenderingContext"); this._renderContext = ctx; diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index 4d98daea70..aff9b7ac2a 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -653,7 +653,7 @@ var game = { if (isWeChatGame) { this.container = cc.container = localContainer = document.createElement("DIV"); this.frame = localContainer.parentNode === document.body ? document.documentElement : localContainer.parentNode; - this.canvas = cc._canvas = localCanvas = window['canvas']; + this.canvas = cc._canvas = localCanvas = canvas; } else { var element = (el instanceof HTMLElement) ? el : (document.querySelector(el) || document.querySelector('#' + el)); diff --git a/cocos2d/core/load-pipeline/text-downloader.js b/cocos2d/core/load-pipeline/text-downloader.js index e7150ad425..d4c6689784 100644 --- a/cocos2d/core/load-pipeline/text-downloader.js +++ b/cocos2d/core/load-pipeline/text-downloader.js @@ -1,3 +1,5 @@ +var sys = require('../platform/CCSys'); + if (CC_JSB) { module.exports = function (item, callback) { var url = item.url; @@ -15,13 +17,39 @@ else { var urlAppendTimestamp = require('./utils').urlAppendTimestamp; module.exports = function (item, callback) { - var url = item.url, - xhr = cc.loader.getXMLHttpRequest(), - errInfo = 'Load ' + url + ' failed!', - navigator = window.navigator; + var url = item.url; url = urlAppendTimestamp(url); + if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { + var fs = wx.getFileSystemManager(); + var filePath = url; + // var localPath = wx.env.USER_DATA_PATH + '/' + filePath; + // Read from package + fs.accessSync(filePath); + fs.readFile({ + filePath: filePath, + encoding: 'utf8', + success: function (res) { + if (res.data) { + // console.error('read file success'); + callback(null, res.data); + } + }, + fail: function (res) { + if (res.errMsg) { + console.error('read file path' + filePath + ' failed!'); + cc.game.emit('xhr-load-error:', res.errMsg); + callback({status:0, errorMessage: res.errMsg}); + } + } + }); + return; + } + + var xhr = cc.loader.getXMLHttpRequest(), + errInfo = 'Load ' + url + ' failed!', + navigator = window.navigator; xhr.open('GET', url, true); if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) { // IE-specific logic here diff --git a/cocos2d/core/platform/CCInputManager.js b/cocos2d/core/platform/CCInputManager.js index 45c6b0b00d..cc454c5c08 100644 --- a/cocos2d/core/platform/CCInputManager.js +++ b/cocos2d/core/platform/CCInputManager.js @@ -543,8 +543,8 @@ var inputManager = { var pos = selfPointer.getHTMLElementPosition(element); var body = document.body; - pos.left -= body.scrollLeft; - pos.top -= body.scrollTop; + pos.left -= body.scrollLeft || 0; + pos.top -= body.scrollTop || 0; handler(selfPointer.getTouchesByEvent(event, pos)); diff --git a/cocos2d/core/platform/CCSys.js b/cocos2d/core/platform/CCSys.js index ee884a4cf5..4b0dd30421 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -482,6 +482,10 @@ sys.BROWSER_TYPE_SOUGOU = "sogou"; */ sys.BROWSER_TYPE_UNKNOWN = "unknown"; +function isWeChatGame () { + return window['wx']; +} + /** * Is native ? This is set to be true in jsb auto. * @property {Boolean} isNative @@ -494,10 +498,6 @@ sys.isNative = false; */ sys.isBrowser = typeof window === 'object' && typeof document === 'object'; -function isWeChatGame () { - return window['wx']; -} - if (CC_EDITOR && Editor.isMainProcess) { sys.isMobile = false; sys.platform = sys.EDITOR_CORE; @@ -731,7 +731,10 @@ else { var _supportWebp = _tmpCanvas1.toDataURL('image/webp').startsWith('data:image/webp'); var _supportCanvas = !!_tmpCanvas1.getContext("2d"); var _supportWebGL = false; - if (win.WebGLRenderingContext) { + if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { + _supportWebGL = true; + } + else if (win.WebGLRenderingContext) { if (cc.create3DContext(document.createElement("CANVAS"))) { _supportWebGL = true; } @@ -774,9 +777,6 @@ else { } } } - else if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { - _supportWebGL = true; - } /** * The capabilities of the current platform diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index 0e67ff9316..8c1652c136 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -101,11 +101,11 @@ switch (__BrowserGetter.adaptationType) { }; break; case cc.sys.BROWSER_TYPE_WECHAT_GAME: - __BrowserGetter.availWidth = function(frame){ - return frame.innerWidth; + __BrowserGetter.availWidth = function(){ + return window.innerWidth; }; - __BrowserGetter.availHeight = function(frame){ - return frame.innerHeight; + __BrowserGetter.availHeight = function(){ + return window.innerHeight; }; break; } diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index e0eb73b367..0cdb1ea19a 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -803,6 +803,7 @@ game.once(game.EVENT_RENDERER_INITED, function () { var gl = this._gl; gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha); if ( + sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME || img instanceof HTMLCanvasElement || img instanceof HTMLImageElement || img instanceof HTMLVideoElement diff --git a/cocos2d/core/videoplayer/CCSGVideoPlayer.js b/cocos2d/core/videoplayer/CCSGVideoPlayer.js index d770e74b87..783d385437 100644 --- a/cocos2d/core/videoplayer/CCSGVideoPlayer.js +++ b/cocos2d/core/videoplayer/CCSGVideoPlayer.js @@ -20,6 +20,8 @@ ****************************************************************************/ var Utils = require('../platform/utils'); +var sys = require('../platform/CCSys'); + /** * @class * @extends _ccsg.Node @@ -219,14 +221,16 @@ _ccsg.VideoPlayer.EventType = { * so it is best to provide mp4 and webm or ogv file */ var dom = document.createElement("video"); - if(dom.canPlayType("video/ogg")){ - video._polyfill.canPlayType.push(".ogg"); - video._polyfill.canPlayType.push(".ogv"); + if (sys.browserType !== sys.BROWSER_TYPE_WECHAT_GAME) { + if(dom.canPlayType("video/ogg")){ + video._polyfill.canPlayType.push(".ogg"); + video._polyfill.canPlayType.push(".ogv"); + } + if(dom.canPlayType("video/mp4")) + video._polyfill.canPlayType.push(".mp4"); + if(dom.canPlayType("video/webm")) + video._polyfill.canPlayType.push(".webm"); } - if(dom.canPlayType("video/mp4")) - video._polyfill.canPlayType.push(".mp4"); - if(dom.canPlayType("video/webm")) - video._polyfill.canPlayType.push(".webm"); })(); if(cc.sys.browserType === cc.sys.BROWSER_TYPE_FIREFOX){ From bb52f98da31031471fb7c64fdc3affbab58a0e39 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 6 Nov 2017 15:17:06 +0800 Subject: [PATCH 028/127] Solve touch onebyone dispatching issue --- cocos2d/core/event-manager/CCEventManager.js | 3 +-- cocos2d/core/platform/CCInputManager.js | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/event-manager/CCEventManager.js b/cocos2d/core/event-manager/CCEventManager.js index 74bd402172..ce11e4fc6e 100644 --- a/cocos2d/core/event-manager/CCEventManager.js +++ b/cocos2d/core/event-manager/CCEventManager.js @@ -546,9 +546,8 @@ cc.eventManager = { if (oneByOneListeners) { for (var i = 0; i < originalTouches.length; i++) { event.currentTouch = originalTouches[i]; + event._propagationStopped = event._propagationImmediateStopped = false; this._dispatchEventToListeners(oneByOneListeners, this._onTouchEventCallback, oneByOneArgsObj); - if (event.isStopped()) - return; } } diff --git a/cocos2d/core/platform/CCInputManager.js b/cocos2d/core/platform/CCInputManager.js index cc454c5c08..5e5dbefce1 100644 --- a/cocos2d/core/platform/CCInputManager.js +++ b/cocos2d/core/platform/CCInputManager.js @@ -133,7 +133,7 @@ var inputManager = { var selTouch, index, touchID, handleTouches = [], locTouches = this._touches, now = sys.now(); - for(var i = 0, len = touches.length; i< len; i ++){ + for(var i = 0, len = touches.length; i < len; i++){ selTouch = touches[i]; touchID = selTouch.getID(); index = this._touchesIntegerDict[touchID]; From 593686cf5618caea47d32070b8fd822c20e2a7c5 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 6 Nov 2017 20:50:51 +0800 Subject: [PATCH 029/127] forbid supportJit in wx environment --- index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.js b/index.js index 3e08bad500..18295ef15e 100644 --- a/index.js +++ b/index.js @@ -142,7 +142,7 @@ defineMacro('CC_BUILD', false); cc = {}; // check whether support jit -cc.supportJit = typeof Function('') === 'function'; +cc.supportJit = !window.wx && typeof Function('') === 'function'; // The namespace for original nodes rendering in scene graph. _ccsg = {}; From d231188f0c694b462ac4b165d32e7b9b487b0449 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 6 Nov 2017 20:51:14 +0800 Subject: [PATCH 030/127] Fix parentNode undefined issue in wx --- cocos2d/core/platform/utils.js | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/cocos2d/core/platform/utils.js b/cocos2d/core/platform/utils.js index b0528365f6..a88aa4bd17 100644 --- a/cocos2d/core/platform/utils.js +++ b/cocos2d/core/platform/utils.js @@ -33,13 +33,15 @@ module.exports = { return !!(refNode.compareDocumentPosition(otherNode) & 16); }else { var node = otherNode.parentNode; - do { - if(node === refNode){ - return true; - }else{ - node = node.parentNode; - } - }while(node !==null); + if (node) { + do { + if (node === refNode) { + return true; + } else { + node = node.parentNode; + } + } while (node !==null); + } return false; } }, From 9626c28485416d8f0a1c5455a37456055ede38da Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 7 Nov 2017 15:18:23 +0800 Subject: [PATCH 031/127] Improve TMXXMLParser error log --- DebugInfos.js | 1 + cocos2d/tilemap/CCTMXXMLParser.js | 4 +++- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/DebugInfos.js b/DebugInfos.js index 602043725d..e2ba46ce95 100644 --- a/DebugInfos.js +++ b/DebugInfos.js @@ -558,6 +558,7 @@ if (CC_DEBUG) { "7217": "cocos2d: TMXFomat: Unsupported orientation: %s", //parseXMLFile "7218": "cc.TMXMapInfo.parseXMLFile(): unsupported compression method", //_parseLayer "7219": "cc.TMXMapInfo.parseXMLFile(): Only base64 and/or gzip/zlib maps are supported", //_parseLayer + "7220": "TMX Parser: please load the xml resource first: %s", // parseXMLFile //Wrapper: 7300 "7300": "The new selected must be number", //CheckBox.selected "7301": "The new bake must be boolean", //layer diff --git a/cocos2d/tilemap/CCTMXXMLParser.js b/cocos2d/tilemap/CCTMXXMLParser.js index e49ebe648a..e6bd5ac64b 100644 --- a/cocos2d/tilemap/CCTMXXMLParser.js +++ b/cocos2d/tilemap/CCTMXXMLParser.js @@ -566,7 +566,9 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ parseXMLFile:function (tmxFile, isXmlString, tilesetFirstGid) { isXmlString = isXmlString || false; var xmlStr = isXmlString ? tmxFile : cc.loader.getRes(tmxFile); - if(!xmlStr) throw new Error("Please load the resource first : " + tmxFile); + if (!xmlStr) { + cc.errorID(7220, tmxFile); + } var mapXML = this._parseXML(xmlStr); var i, j; From ea9665bad7438d7eb2d94836e7f6e1dd43c1d3d3 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 7 Nov 2017 16:20:19 +0800 Subject: [PATCH 032/127] Remove queryAllSelector dependencies --- cocos2d/tilemap/CCTMXXMLParser.js | 30 +++++++++++++++++++++--------- 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/cocos2d/tilemap/CCTMXXMLParser.js b/cocos2d/tilemap/CCTMXXMLParser.js index e6bd5ac64b..6bfb77dabf 100644 --- a/cocos2d/tilemap/CCTMXXMLParser.js +++ b/cocos2d/tilemap/CCTMXXMLParser.js @@ -189,6 +189,18 @@ cc.TMXTilesetInfo = cc._Class.extend(/** @lends cc.TMXTilesetInfo# */{ } }); +function getPropertyList (node) { + let res = []; + let properties = node.getElementsByTagName("properties"); + for (let i = 0; i < properties.length; ++i) { + let property = properties[i].getElementsByTagName("property"); + for (let j = 0; j < property.length; ++j) { + res.push(property[j]); + } + } + return res.length ? res : null; +} + /** *

cc.TMXMapInfo contains the information about the map like:
*- Map orientation (hexagonal, isometric or orthogonal)
@@ -624,7 +636,7 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ this.setTileSize(mapSize); // The parent element is the map - var propertyArr = map.querySelectorAll("map > properties > property"); + var propertyArr = getPropertyList(map); if (propertyArr) { var aPropertyDict = {}; for (i = 0; i < propertyArr.length; i++) { @@ -694,7 +706,7 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ for (var tIdx = 0; tIdx < tiles.length; tIdx++) { var t = tiles[tIdx]; this.parentGID = parseInt(tileset.firstGid) + parseInt(t.getAttribute('id') || 0); - var tp = t.querySelectorAll("properties > property"); + var tp = getPropertyList(t); if (tp) { var dict = {}; for (j = 0; j < tp.length; j++) { @@ -807,7 +819,7 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ } // The parent element is the last layer - var layerProps = selLayer.querySelectorAll("properties > property"); + var layerProps = getPropertyList(selLayer); if (layerProps) { var layerProp = {}; for (let j = 0; j < layerProps.length; j++) { @@ -841,7 +853,7 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ if (draworder) objectGroup._draworder = draworder; - var groupProps = selGroup.querySelectorAll("objectgroup > properties > property"); + var groupProps = getPropertyList(selGroup); if (groupProps) { var parsedProps = {}; for (let j = 0; j < groupProps.length; j++) { @@ -851,7 +863,7 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ objectGroup.setProperties(parsedProps); } - var objects = selGroup.querySelectorAll('object'); + var objects = selGroup.getElementsByTagName('object'); var getContentScaleFactor = cc.director.getContentScaleFactor(); if (objects) { for (let j = 0; j < objects.length; j++) { @@ -875,7 +887,7 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ objectProp["rotation"] = parseFloat(selObj.getAttribute('rotation')) || 0; - var docObjProps = selObj.querySelectorAll("properties > property"); + var docObjProps = getPropertyList(selObj); if (docObjProps) { for (var k = 0; k < docObjProps.length; k++) objectProp[docObjProps[k].getAttribute('name')] = docObjProps[k].getAttribute('value'); @@ -893,13 +905,13 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ } // ellipse - var ellipse = selObj.querySelectorAll('ellipse'); + var ellipse = selObj.getElementsByTagName('ellipse'); if (ellipse && ellipse.length > 0) { objectProp['type'] = cc.TiledMap.TMXObjectType.ELLIPSE; } //polygon - var polygonProps = selObj.querySelectorAll("polygon"); + var polygonProps = selObj.getElementsByTagName("polygon"); if(polygonProps && polygonProps.length > 0) { objectProp['type'] = cc.TiledMap.TMXObjectType.POLYGON; var selPgPointStr = polygonProps[0].getAttribute('points'); @@ -908,7 +920,7 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ } //polyline - var polylineProps = selObj.querySelectorAll("polyline"); + var polylineProps = selObj.getElementsByTagName("polyline"); if(polylineProps && polylineProps.length > 0) { objectProp['type'] = cc.TiledMap.TMXObjectType.POLYLINE; var selPlPointStr = polylineProps[0].getAttribute('points'); From d84f0712c3b432caccc157991bb3c35ca4674a73 Mon Sep 17 00:00:00 2001 From: Olivier Bouton Date: Wed, 8 Nov 2017 14:26:06 +0100 Subject: [PATCH 033/127] Removed Unix support --- cocos2d/core/platform/CCSys.js | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/cocos2d/core/platform/CCSys.js b/cocos2d/core/platform/CCSys.js index 732fe77234..5625e568e6 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -198,11 +198,6 @@ sys.OS_MARMALADE = "Marmalade"; * @readOnly */ sys.OS_LINUX = "Linux"; -/** - * @property {String} OS_UNIX - * @readOnly - */ -sys.OS_UNIX = "Unix"; /** * @property {String} OS_BADA * @readOnly @@ -567,8 +562,7 @@ else { else if (iOS) osName = sys.OS_IOS; else if (nav.appVersion.indexOf("Mac") !== -1) osName = sys.OS_OSX; else if (isAndroid) osName = sys.OS_ANDROID; - else if (nav.appVersion.indexOf("Linux") !== -1 || ua.indexOf("ubuntu") !== -1) osName = sys.OS_LINUX; - else if (nav.appVersion.indexOf("X11") !== -1 && nav.appVersion.indexOf("Linux") === -1) osName = sys.OS_UNIX; + else if (nav.appVersion.indexOf("Linux") !== -1 || ua.indexOf("ubuntu") !== -1 || nav.appVersion.indexOf("X11") !== -1) osName = sys.OS_LINUX; /** * Indicate the running os name From 1300c60ce805f55896f0cf04845fbb0b7feb5658 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 8 Nov 2017 23:06:01 +0800 Subject: [PATCH 034/127] Support editbox on wxgame Editbox end editing in wx complete callback --- cocos2d/core/editbox/CCSGEditBox.js | 95 +++++++++++++++++++++++++---- 1 file changed, 83 insertions(+), 12 deletions(-) diff --git a/cocos2d/core/editbox/CCSGEditBox.js b/cocos2d/core/editbox/CCSGEditBox.js index 1dd914b28f..8f298debd8 100644 --- a/cocos2d/core/editbox/CCSGEditBox.js +++ b/cocos2d/core/editbox/CCSGEditBox.js @@ -33,6 +33,7 @@ var DELAY_TIME = 400; var FOCUS_DELAY_UC = 400; var FOCUS_DELAY_FIREFOX = 0; var Utils = require('../platform/utils'); +var sys = require('../platform/CCSys'); function adjustEditBoxPosition (editBox) { var worldPos = editBox.convertToWorldSpace(cc.p(0,0)); @@ -543,9 +544,9 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; zoomInvalid: false }; - if (cc.sys.OS_ANDROID === cc.sys.os - && (cc.sys.browserType === cc.sys.BROWSER_TYPE_SOUGOU - || cc.sys.browserType === cc.sys.BROWSER_TYPE_360)) { + if (sys.OS_ANDROID === sys.os + && (sys.browserType === sys.BROWSER_TYPE_SOUGOU + || sys.browserType === sys.BROWSER_TYPE_360)) { editbox._polyfill.zoomInvalid = true; } })(_ccsg.EditBox); @@ -696,7 +697,6 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; tmpEdTxt.addEventListener('input', function () { var editBox = thisPointer._editBox; - if (this.value.length > this.maxLength) { this.value = this.value.slice(0, this.maxLength); } @@ -737,7 +737,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; this.style.color = cc.colorToHex(editBox._textColor); thisPointer._hiddenLabels(); - if (cc.sys.isMobile) { + if (sys.isMobile) { thisPointer._onFocusOnMobile(editBox); } @@ -812,7 +812,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; this.style.fontSize = thisPointer._edFontSize + 'px'; this.style.color = cc.colorToHex(editBox._textColor); - if (cc.sys.isMobile) { + if (sys.isMobile) { thisPointer._onFocusOnMobile(editBox); } @@ -853,6 +853,73 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; return tmpEdTxt; }; + proto._createWXInput = function (multiline) { + this.removeDom(); + var thisPointer = this; + var tmpEdTxt = this._edTxt = document.createElement(multiline ? "textarea" : "input"); + tmpEdTxt.type = "text"; + tmpEdTxt.style.fontSize = this._edFontSize + "px"; + tmpEdTxt.style.color = "#000000"; + tmpEdTxt.style.border = 0; + tmpEdTxt.style.background = "transparent"; + tmpEdTxt.style.width = "100%"; + tmpEdTxt.style.height = "100%"; + tmpEdTxt.style.active = 0; + tmpEdTxt.style.outline = "medium"; + tmpEdTxt.style.padding = "0"; + tmpEdTxt.style.textTransform = "uppercase"; + tmpEdTxt.style.display = "none"; + tmpEdTxt.style.position = "absolute"; + tmpEdTxt.style.bottom = "0px"; + tmpEdTxt.style.left = LEFT_PADDING + "px"; + tmpEdTxt.style["-moz-appearance"] = "textfield"; + tmpEdTxt.style.className = "cocosEditBox"; + + tmpEdTxt.focus = function() { + var editBox = thisPointer._editBox; + wx.showKeyboard({ + defaultValue: editBox._text, + maxLength: 140, + multiple: multiline, + confirmHold: true, + confirmType: "done", + success: function (res) { + editBox._delegate && editBox._delegate.editBoxEditingDidBegan && editBox._delegate.editBoxEditingDidBegan(editBox); + }, + fail: function (res) { + cc.warn(res.errMsg); + thisPointer._endEditing(); + } + }); + wx.onKeyboardConfirm(function (res) { + editBox._text = res.value; + thisPointer._updateDomTextCases(); + editBox._delegate && editBox._delegate.editBoxEditingReturn && editBox._delegate.editBoxEditingReturn(editBox); + wx.hideKeyboard({ + success: function (res) { + editBox._delegate && editBox._delegate.editBoxEditingDidEnded && editBox._delegate.editBoxEditingDidEnded(editBox); + }, + fail: function (res) { + cc.warn(res.errMsg); + } + }); + }); + wx.onKeyboardInput(function (res) { + if (editBox._delegate && editBox._delegate.editBoxTextChanged && editBox._text !== res.value) { + editBox._text = res.value; + thisPointer._updateDomTextCases(); + editBox._delegate.editBoxTextChanged(editBox, editBox._text); + } + }); + wx.onKeyboardComplete(function () { + thisPointer._endEditing(); + wx.offKeyboardConfirm(); + wx.offKeyboardInput(); + wx.offKeyboardComplete(); + }); + } + }; + proto._createLabels = function () { var editBoxSize = this._editBox.getContentSize(); if(!this._textLabel) { @@ -953,7 +1020,8 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; proto._showLabels = function () { this._hiddenLabels(); - if (this._edTxt.value === '') { + var text = sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME ? this._editBox._text : this._edTxt.value; + if (text === '') { if(this._placeholderLabel) { this._placeholderLabel.setVisible(true); this._placeholderLabel.setString(this._editBox._placeholderText); @@ -978,10 +1046,10 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; self._edTxt.focus(); } - if (cc.sys.browserType === cc.sys.BROWSER_TYPE_UC) { + if (sys.browserType === sys.BROWSER_TYPE_UC) { setTimeout(startFocus, FOCUS_DELAY_UC); } - else if (cc.sys.browserType === cc.sys.BROWSER_TYPE_FIREFOX) { + else if (sys.browserType === sys.BROWSER_TYPE_FIREFOX) { setTimeout(startFocus, FOCUS_DELAY_FIREFOX); } else { @@ -990,7 +1058,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; } } - if (cc.sys.isMobile && !self._editingMode) { + if (sys.isMobile && !self._editingMode) { // Pre adaptation and self._beginEditingOnMobile(self._editBox); } @@ -1002,7 +1070,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; this._edTxt.style.display = 'none'; } this._showLabels(); - if (cc.sys.isMobile && this._editingMode) { + if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME && sys.isMobile && this._editingMode) { var self = this; // Delay end editing adaptation to ensure virtual keyboard is disapeared setTimeout(function () { @@ -1109,7 +1177,10 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; }; proto.setInputMode = function (inputMode) { - if (inputMode === InputMode.ANY) { + if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { + this._createWXInput(inputMode === InputMode.ANY); + } + else if (inputMode === InputMode.ANY) { this._createDomTextArea(); } else { From 19b378222c0dde29bed41b1c1d5eb07d11bdd20a Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 9 Nov 2017 11:23:39 +0800 Subject: [PATCH 035/127] Avoid iOS permission issue --- cocos2d/core/load-pipeline/text-downloader.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/load-pipeline/text-downloader.js b/cocos2d/core/load-pipeline/text-downloader.js index d4c6689784..1197535101 100644 --- a/cocos2d/core/load-pipeline/text-downloader.js +++ b/cocos2d/core/load-pipeline/text-downloader.js @@ -26,7 +26,7 @@ else { var filePath = url; // var localPath = wx.env.USER_DATA_PATH + '/' + filePath; // Read from package - fs.accessSync(filePath); + // fs.accessSync(filePath); fs.readFile({ filePath: filePath, encoding: 'utf8', From c050e7a0132af90a69077dbc0417741710fd43b2 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sun, 12 Nov 2017 23:13:11 +0800 Subject: [PATCH 036/127] Fix multiple line editbox --- cocos2d/core/editbox/CCSGEditBox.js | 28 +++++++--------------------- 1 file changed, 7 insertions(+), 21 deletions(-) diff --git a/cocos2d/core/editbox/CCSGEditBox.js b/cocos2d/core/editbox/CCSGEditBox.js index 8f298debd8..b8397bd02b 100644 --- a/cocos2d/core/editbox/CCSGEditBox.js +++ b/cocos2d/core/editbox/CCSGEditBox.js @@ -284,8 +284,8 @@ _ccsg.EditBox = _ccsg.Node.extend({ }, createDomElementIfNeeded: function () { - if(!this._renderCmd._edTxt) { - this._renderCmd._createDomTextArea(); + if (!this._renderCmd._edTxt) { + this._renderCmd.setInputMode(this._editBoxInputMode); } }, @@ -856,24 +856,8 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; proto._createWXInput = function (multiline) { this.removeDom(); var thisPointer = this; - var tmpEdTxt = this._edTxt = document.createElement(multiline ? "textarea" : "input"); + var tmpEdTxt = this._edTxt = document.createElement("input"); tmpEdTxt.type = "text"; - tmpEdTxt.style.fontSize = this._edFontSize + "px"; - tmpEdTxt.style.color = "#000000"; - tmpEdTxt.style.border = 0; - tmpEdTxt.style.background = "transparent"; - tmpEdTxt.style.width = "100%"; - tmpEdTxt.style.height = "100%"; - tmpEdTxt.style.active = 0; - tmpEdTxt.style.outline = "medium"; - tmpEdTxt.style.padding = "0"; - tmpEdTxt.style.textTransform = "uppercase"; - tmpEdTxt.style.display = "none"; - tmpEdTxt.style.position = "absolute"; - tmpEdTxt.style.bottom = "0px"; - tmpEdTxt.style.left = LEFT_PADDING + "px"; - tmpEdTxt.style["-moz-appearance"] = "textfield"; - tmpEdTxt.style.className = "cocosEditBox"; tmpEdTxt.focus = function() { var editBox = thisPointer._editBox; @@ -1038,7 +1022,10 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; proto._beginEditing = function () { var self = this; - if (!self._editBox._alwaysOnTop) { + if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { + this._edTxt.focus(); + } + else if (!self._editBox._alwaysOnTop) { if (self._edTxt.style.display === 'none') { self._edTxt.style.display = ''; @@ -1154,7 +1141,6 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; } } - if (this._editBox._editBoxInputFlag === InputFlag.PASSWORD) { this._edTxt.type = 'password'; } From 7c2e7f852d3aedf57163476c7011678045f99ae4 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 13 Nov 2017 16:30:28 +0800 Subject: [PATCH 037/127] Remove wrong isBrowser usage --- cocos2d/core/platform/index.js | 11 +++++------ test/lib/init.js | 5 +---- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/cocos2d/core/platform/index.js b/cocos2d/core/platform/index.js index d7b7756cea..34c0523e28 100644 --- a/cocos2d/core/platform/index.js +++ b/cocos2d/core/platform/index.js @@ -37,10 +37,9 @@ require('./requiring-frame'); require('./CCSys'); require('./CCMacro'); -if (CC_JSB || cc.sys.isBrowser) { +if (!(CC_EDITOR && Editor.isMainProcess)) { require('./CCAssetLibrary'); -} - -if (!CC_JSB && !(CC_EDITOR && Editor.isMainProcess)) { - require('./CCVisibleRect'); -} + if (!CC_JSB) { + require('./CCVisibleRect'); + } +} \ No newline at end of file diff --git a/test/lib/init.js b/test/lib/init.js index 36af511944..74f44a2e5c 100644 --- a/test/lib/init.js +++ b/test/lib/init.js @@ -24,7 +24,4 @@ var AssetLibrary = cc.AssetLibrary; var FO = cc.Object; var V2 = cc.Vec2; var v2 = cc.v2; -var color = cc.fireColor; - -if (cc.isBrowser) { -} +var color = cc.fireColor; \ No newline at end of file From 917b75e65a56ab349cbfab03e32feed6659ce923 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 13 Nov 2017 16:31:01 +0800 Subject: [PATCH 038/127] Structured wechat game environment detection --- cocos2d/core/platform/CCSys.js | 95 ++++++++++++++++++++++++---------- 1 file changed, 68 insertions(+), 27 deletions(-) diff --git a/cocos2d/core/platform/CCSys.js b/cocos2d/core/platform/CCSys.js index 4b0dd30421..09d6d18b29 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -319,6 +319,12 @@ sys.MOBILE_BROWSER = 100; * @default 101 */ sys.DESKTOP_BROWSER = 101; +/** + * @property {Number} WECHAT_GAME + * @readOnly + * @default 102 + */ +sys.WECHAT_GAME = 102; /** * Indicates whether executes in editor's window process (Electron's renderer context) @@ -496,7 +502,25 @@ sys.isNative = false; * Is web browser ? * @property {Boolean} isBrowser */ -sys.isBrowser = typeof window === 'object' && typeof document === 'object'; +sys.isBrowser = typeof window === 'object' && typeof document === 'object' && !isWeChatGame(); + +function detectAudioFormat () { + var formatSupport = []; + var audio = document.createElement('audio'); + if(audio.canPlayType) { + var ogg = audio.canPlayType('audio/ogg; codecs="vorbis"'); + if (ogg) formatSupport.push('.ogg'); + var mp3 = audio.canPlayType('audio/mpeg'); + if (mp3) formatSupport.push('.mp3'); + var wav = audio.canPlayType('audio/wav; codecs="1"'); + if (wav) formatSupport.push('.wav'); + var mp4 = audio.canPlayType('audio/mp4'); + if (mp4) formatSupport.push('.mp4'); + var m4a = audio.canPlayType('audio/x-m4a'); + if (m4a) formatSupport.push('.m4a'); + } + return formatSupport; +} if (CC_EDITOR && Editor.isMainProcess) { sys.isMobile = false; @@ -515,6 +539,46 @@ if (CC_EDITOR && Editor.isMainProcess) { }; sys.__audioSupport = {}; } +else if (isWeChatGame()) { + var env = wx.getSystemInfoSync(); + sys.isMobile = true; + sys.platform = sys.WECHAT_GAME; + sys.language = env.language.substr(0, 2); + if (env.platform === "android") { + sys.os = sys.OS_ANDROID; + } + else if (env.platform === "ios") { + sys.os = sys.OS_IOS; + } + + var version = /[\d\.]+/.exec(env.system); + sys.osVersion = version[0]; + sys.osMainVersion = parseInt(sys.osVersion); + sys.browserType = sys.BROWSER_TYPE_WECHAT_GAME; + sys.browserVersion = env.version; + + var w = env.windowWidth; + var h = env.windowHeight; + var ratio = env.pixelRatio || 1; + sys.windowPixelResolution = { + width: ratio * w, + height: ratio * h + }; + + sys.localStorage = win.localStorage; + + sys.capabilities = { + "canvas": true, + "opengl": true, + "webp": false + }; + sys.__audioSupport = { + ONLY_ONE: false, + WEB_AUDIO: false, + DELAY_CREATE_CTX: false, + format: detectAudioFormat() + }; +} else { // browser or runtime var win = window, nav = win.navigator, doc = document, docEle = doc.documentElement; @@ -731,10 +795,7 @@ else { var _supportWebp = _tmpCanvas1.toDataURL('image/webp').startsWith('data:image/webp'); var _supportCanvas = !!_tmpCanvas1.getContext("2d"); var _supportWebGL = false; - if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { - _supportWebGL = true; - } - else if (win.WebGLRenderingContext) { + if (win.WebGLRenderingContext) { if (cc.create3DContext(document.createElement("CANVAS"))) { _supportWebGL = true; } @@ -819,8 +880,7 @@ else { // check if browser supports Web Audio // check Web Audio's context - var supportWebAudio = sys.browserType !== sys.BROWSER_TYPE_WECHAT_GAME && - !!(window.AudioContext || window.webkitAudioContext || window.mozAudioContext); + var supportWebAudio = !!(window.AudioContext || window.webkitAudioContext || window.mozAudioContext); __audioSupport = { ONLY_ONE: false, WEB_AUDIO: supportWebAudio, DELAY_CREATE_CTX: false }; @@ -864,26 +924,7 @@ else { __audioSupport.WEB_AUDIO = false; cc.logID(5201); } - - var formatSupport = []; - - (function(){ - var audio = document.createElement('audio'); - if(audio.canPlayType) { - var ogg = audio.canPlayType('audio/ogg; codecs="vorbis"'); - if (ogg) formatSupport.push('.ogg'); - var mp3 = audio.canPlayType('audio/mpeg'); - if (mp3) formatSupport.push('.mp3'); - var wav = audio.canPlayType('audio/wav; codecs="1"'); - if (wav) formatSupport.push('.wav'); - var mp4 = audio.canPlayType('audio/mp4'); - if (mp4) formatSupport.push('.mp4'); - var m4a = audio.canPlayType('audio/x-m4a'); - if (m4a) formatSupport.push('.m4a'); - } - })(); - __audioSupport.format = formatSupport; - + __audioSupport.format = detectAudioFormat(); sys.__audioSupport = __audioSupport; } From 90b9637d66d657a1c5fc92ecd7b875604d23bdf2 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 13 Nov 2017 16:46:01 +0800 Subject: [PATCH 039/127] Remove audio format detection in wechat game --- cocos2d/core/platform/CCSys.js | 39 +++++++++++++++++----------------- 1 file changed, 19 insertions(+), 20 deletions(-) diff --git a/cocos2d/core/platform/CCSys.js b/cocos2d/core/platform/CCSys.js index 09d6d18b29..2c92df2e3e 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -504,24 +504,6 @@ sys.isNative = false; */ sys.isBrowser = typeof window === 'object' && typeof document === 'object' && !isWeChatGame(); -function detectAudioFormat () { - var formatSupport = []; - var audio = document.createElement('audio'); - if(audio.canPlayType) { - var ogg = audio.canPlayType('audio/ogg; codecs="vorbis"'); - if (ogg) formatSupport.push('.ogg'); - var mp3 = audio.canPlayType('audio/mpeg'); - if (mp3) formatSupport.push('.mp3'); - var wav = audio.canPlayType('audio/wav; codecs="1"'); - if (wav) formatSupport.push('.wav'); - var mp4 = audio.canPlayType('audio/mp4'); - if (mp4) formatSupport.push('.mp4'); - var m4a = audio.canPlayType('audio/x-m4a'); - if (m4a) formatSupport.push('.m4a'); - } - return formatSupport; -} - if (CC_EDITOR && Editor.isMainProcess) { sys.isMobile = false; sys.platform = sys.EDITOR_CORE; @@ -575,8 +557,7 @@ else if (isWeChatGame()) { sys.__audioSupport = { ONLY_ONE: false, WEB_AUDIO: false, - DELAY_CREATE_CTX: false, - format: detectAudioFormat() + DELAY_CREATE_CTX: false }; } else { @@ -924,6 +905,24 @@ else { __audioSupport.WEB_AUDIO = false; cc.logID(5201); } + + function detectAudioFormat () { + var formatSupport = []; + var audio = document.createElement('audio'); + if(audio.canPlayType) { + var ogg = audio.canPlayType('audio/ogg; codecs="vorbis"'); + if (ogg) formatSupport.push('.ogg'); + var mp3 = audio.canPlayType('audio/mpeg'); + if (mp3) formatSupport.push('.mp3'); + var wav = audio.canPlayType('audio/wav; codecs="1"'); + if (wav) formatSupport.push('.wav'); + var mp4 = audio.canPlayType('audio/mp4'); + if (mp4) formatSupport.push('.mp4'); + var m4a = audio.canPlayType('audio/x-m4a'); + if (m4a) formatSupport.push('.m4a'); + } + return formatSupport; + } __audioSupport.format = detectAudioFormat(); sys.__audioSupport = __audioSupport; } From a42bafe56176e0b7a0a2fbc5dfad74bc4478f12b Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 13 Nov 2017 17:10:35 +0800 Subject: [PATCH 040/127] Fix WECHAT_GAME constant, create3DContext & localStorage --- cocos2d/core/platform/CCSys.js | 49 +++++++++++++++++----------------- 1 file changed, 25 insertions(+), 24 deletions(-) diff --git a/cocos2d/core/platform/CCSys.js b/cocos2d/core/platform/CCSys.js index 2c92df2e3e..0416cc2d4d 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -319,12 +319,6 @@ sys.MOBILE_BROWSER = 100; * @default 101 */ sys.DESKTOP_BROWSER = 101; -/** - * @property {Number} WECHAT_GAME - * @readOnly - * @default 102 - */ -sys.WECHAT_GAME = 102; /** * Indicates whether executes in editor's window process (Electron's renderer context) @@ -340,6 +334,13 @@ sys.EDITOR_PAGE = 102; * @default 103 */ sys.EDITOR_CORE = 103; +/** + * @property {Number} WECHAT_GAME + * @readOnly + * @default 104 + */ +sys.WECHAT_GAME = 104; + /** * BROWSER_TYPE_WECHAT * @property {String} BROWSER_TYPE_WECHAT @@ -504,6 +505,23 @@ sys.isNative = false; */ sys.isBrowser = typeof window === 'object' && typeof document === 'object' && !isWeChatGame(); +cc.create3DContext = function (canvas, opt_attribs, opt_contextType) { + if (opt_contextType) { + try { + return canvas.getContext(opt_contextType, opt_attribs); + } catch (e) { + return null; + } + } + else { + return cc.create3DContext(canvas, opt_attribs, "webgl") || + cc.create3DContext(canvas, opt_attribs, "experimental-webgl") || + cc.create3DContext(canvas, opt_attribs, "webkit-3d") || + cc.create3DContext(canvas, opt_attribs, "moz-webgl") || + null; + } +}; + if (CC_EDITOR && Editor.isMainProcess) { sys.isMobile = false; sys.platform = sys.EDITOR_CORE; @@ -547,7 +565,7 @@ else if (isWeChatGame()) { height: ratio * h }; - sys.localStorage = win.localStorage; + sys.localStorage = window.localStorage; sys.capabilities = { "canvas": true, @@ -704,23 +722,6 @@ else { var _tmpCanvas1 = document.createElement("canvas"), _tmpCanvas2 = document.createElement("canvas"); - cc.create3DContext = function (canvas, opt_attribs, opt_contextType) { - if (opt_contextType) { - try { - return canvas.getContext(opt_contextType, opt_attribs); - } catch (e) { - return null; - } - } - else { - return cc.create3DContext(canvas, opt_attribs, "webgl") || - cc.create3DContext(canvas, opt_attribs, "experimental-webgl") || - cc.create3DContext(canvas, opt_attribs, "webkit-3d") || - cc.create3DContext(canvas, opt_attribs, "moz-webgl") || - null; - } - }; - //Whether or not the Canvas BlendModes are supported. sys._supportCanvasNewBlendModes = (function(){ var canvas = _tmpCanvas1; From e01dcbdb3a26f8e6c0f7b9026222505c79c538fc Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 13 Nov 2017 17:10:52 +0800 Subject: [PATCH 041/127] Check wechat game with platform instead of browser type --- cocos2d/audio/CCAudio.js | 13 +++++++------ cocos2d/core/CCDrawingPrimitivesWebGL.js | 2 +- cocos2d/core/CCGame.js | 2 +- cocos2d/core/editbox/CCSGEditBox.js | 8 ++++---- cocos2d/core/load-pipeline/audio-downloader.js | 2 +- cocos2d/core/load-pipeline/downloader.js | 2 +- cocos2d/core/load-pipeline/loader.js | 2 +- cocos2d/core/load-pipeline/text-downloader.js | 2 +- cocos2d/core/platform/CCInputManager.js | 8 ++++---- cocos2d/core/platform/CCView.js | 8 ++++---- cocos2d/core/textures/CCTexture2D.js | 2 +- cocos2d/core/videoplayer/CCSGVideoPlayer.js | 2 +- 12 files changed, 27 insertions(+), 26 deletions(-) diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 2a899f4a1f..d7e1b4e892 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -25,6 +25,7 @@ ****************************************************************************/ var EventTarget = require('../core/event/event-target'); +var sys = require('../core/platform/CCSys'); var touchBinded = false; var touchPlayList = [ @@ -137,7 +138,7 @@ Audio.State = { }; proto.mount = function (elem) { - if (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME || elem instanceof HTMLElement) { + if (sys.platform === sys.WECHAT_GAME || elem instanceof HTMLElement) { this._element = document.createElement('audio'); this._element.src = elem.src; this._audioType = Audio.Type.DOM; @@ -156,7 +157,7 @@ Audio.State = { this.emit('play'); this._state = Audio.State.PLAYING; - if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME && + if (sys.platform !== sys.WECHAT_GAME && this._audioType === Audio.Type.DOM && this._element.paused) { touchPlayList.push({ instance: this, offset: 0, audio: this._element }); @@ -227,7 +228,7 @@ Audio.State = { proto.setCurrentTime = function (num) { if (!this._element) return; this._unbindEnded(); - if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME) { + if (sys.platform !== sys.WECHAT_GAME) { this._bindEnded(function () { this._bindEnded(); }.bind(this)); @@ -279,7 +280,7 @@ Audio.State = { // Encapsulated WebAudio interface var WebAudioElement = function (buffer, audio) { this._audio = audio; - this._context = cc.sys.__audioSupport.context; + this._context = sys.__audioSupport.context; this._buffer = buffer; this._volume = this._context['createGain'](); this._volume['gain'].value = 1; @@ -351,7 +352,7 @@ var WebAudioElement = function (buffer, audio) { var self = this; clearTimeout(this._currextTimer); this._currextTimer = setTimeout(function () { - if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME && self._context.currentTime === 0) { + if (sys.platform === sys.WECHAT_GAME && self._context.currentTime === 0) { touchPlayList.push({ instance: self._audio, offset: offset, @@ -400,7 +401,7 @@ var WebAudioElement = function (buffer, audio) { proto.__defineGetter__('volume', function () { return this._volume['gain'].value; }); proto.__defineSetter__('volume', function (num) { this._volume['gain'].value = num; - if (cc.sys.os === cc.sys.OS_IOS && !this.paused && this._currentSource) { + if (sys.os === sys.OS_IOS && !this.paused && this._currentSource) { // IOS must be stop webAudio this._currentSource.onended = null; this.pause(); diff --git a/cocos2d/core/CCDrawingPrimitivesWebGL.js b/cocos2d/core/CCDrawingPrimitivesWebGL.js index b88de5c44d..1c1c914c4d 100644 --- a/cocos2d/core/CCDrawingPrimitivesWebGL.js +++ b/cocos2d/core/CCDrawingPrimitivesWebGL.js @@ -43,7 +43,7 @@ var DrawingPrimitiveWebGL = cc._Class.extend({ * @param ctx rendercontext */ ctor:function (ctx) { - if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME && !ctx instanceof WebGLRenderingContext) + if (cc.sys.platform !== cc.sys.WECHAT_GAME && !ctx instanceof WebGLRenderingContext) throw new Error("Can't initialise DrawingPrimitiveWebGL. context need is WebGLRenderingContext"); this._renderContext = ctx; diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index aff9b7ac2a..b68130a7c2 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -648,7 +648,7 @@ var game = { var el = this.config[game.CONFIG_KEY.id], win = window, localCanvas, localContainer, - isWeChatGame = cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME; + isWeChatGame = cc.sys.platform === cc.sys.WECHAT_GAME; if (isWeChatGame) { this.container = cc.container = localContainer = document.createElement("DIV"); diff --git a/cocos2d/core/editbox/CCSGEditBox.js b/cocos2d/core/editbox/CCSGEditBox.js index b8397bd02b..14bc0c5de4 100644 --- a/cocos2d/core/editbox/CCSGEditBox.js +++ b/cocos2d/core/editbox/CCSGEditBox.js @@ -1004,7 +1004,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; proto._showLabels = function () { this._hiddenLabels(); - var text = sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME ? this._editBox._text : this._edTxt.value; + var text = sys.platform === sys.WECHAT_GAME ? this._editBox._text : this._edTxt.value; if (text === '') { if(this._placeholderLabel) { this._placeholderLabel.setVisible(true); @@ -1022,7 +1022,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; proto._beginEditing = function () { var self = this; - if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { + if (sys.platform === sys.WECHAT_GAME) { this._edTxt.focus(); } else if (!self._editBox._alwaysOnTop) { @@ -1057,7 +1057,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; this._edTxt.style.display = 'none'; } this._showLabels(); - if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME && sys.isMobile && this._editingMode) { + if (sys.platform !== sys.WECHAT_GAME && sys.isMobile && this._editingMode) { var self = this; // Delay end editing adaptation to ensure virtual keyboard is disapeared setTimeout(function () { @@ -1163,7 +1163,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; }; proto.setInputMode = function (inputMode) { - if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { + if (sys.platform === sys.WECHAT_GAME) { this._createWXInput(inputMode === InputMode.ANY); } else if (inputMode === InputMode.ANY) { diff --git a/cocos2d/core/load-pipeline/audio-downloader.js b/cocos2d/core/load-pipeline/audio-downloader.js index 9cee1057bd..48ccf7abce 100644 --- a/cocos2d/core/load-pipeline/audio-downloader.js +++ b/cocos2d/core/load-pipeline/audio-downloader.js @@ -36,7 +36,7 @@ function loadDomAudio (item, callback) { var dom = document.createElement('audio'); dom.src = item.url; - if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { + if (sys.platform === sys.WECHAT_GAME) { item.element = dom; callback(null, item.url); return; diff --git a/cocos2d/core/load-pipeline/downloader.js b/cocos2d/core/load-pipeline/downloader.js index 53bc9ed6ba..7ce3f66301 100644 --- a/cocos2d/core/load-pipeline/downloader.js +++ b/cocos2d/core/load-pipeline/downloader.js @@ -42,7 +42,7 @@ else { } function downloadScript (item, callback, isAsync) { - if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { + if (sys.platform === sys.WECHAT_GAME) { require(item.url); callback(null, item.url); return; diff --git a/cocos2d/core/load-pipeline/loader.js b/cocos2d/core/load-pipeline/loader.js index f6399995c3..ff70e72241 100644 --- a/cocos2d/core/load-pipeline/loader.js +++ b/cocos2d/core/load-pipeline/loader.js @@ -49,7 +49,7 @@ function loadJSON (item, callback) { } function loadImage (item, callback) { - if (sys.browserType !== sys.BROWSER_TYPE_WECHAT_GAME && !(item.content instanceof Image)) { + if (sys.platform !== sys.WECHAT_GAME && !(item.content instanceof Image)) { return new Error('Image Loader: Input item doesn\'t contain Image content'); } var rawUrl = item.rawUrl; diff --git a/cocos2d/core/load-pipeline/text-downloader.js b/cocos2d/core/load-pipeline/text-downloader.js index 1197535101..2f997e658d 100644 --- a/cocos2d/core/load-pipeline/text-downloader.js +++ b/cocos2d/core/load-pipeline/text-downloader.js @@ -21,7 +21,7 @@ else { url = urlAppendTimestamp(url); - if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { + if (sys.platform === sys.WECHAT_GAME) { var fs = wx.getFileSystemManager(); var filePath = url; // var localPath = wx.env.USER_DATA_PATH + '/' + filePath; diff --git a/cocos2d/core/platform/CCInputManager.js b/cocos2d/core/platform/CCInputManager.js index 5e5dbefce1..c8ffcb7894 100644 --- a/cocos2d/core/platform/CCInputManager.js +++ b/cocos2d/core/platform/CCInputManager.js @@ -217,7 +217,7 @@ var inputManager = { * @return {Object} */ getHTMLElementPosition: function (element) { - if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { + if (sys.platform === sys.WECHAT_GAME) { return { left: 0, top: 0, @@ -348,7 +348,7 @@ var inputManager = { if (event.pageX != null) //not avalable in <= IE8 return {x: event.pageX, y: event.pageY}; - if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { + if (sys.platform === sys.WECHAT_GAME) { pos.left = 0; pos.top = 0; } @@ -411,7 +411,7 @@ var inputManager = { var supportMouse = ('mouse' in sys.capabilities); var supportTouches = ('touches' in sys.capabilities); - if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) { + if (sys.platform === sys.WECHAT_GAME) { prohibition = false; supportTouches = true; supportMouse = false; @@ -521,7 +521,7 @@ var inputManager = { var _touchEventsMap = { "touchstart": function (touchesToHandle) { selfPointer.handleTouchesBegin(touchesToHandle); - if (sys.browserType !== sys.BROWSER_TYPE_WECHAT_GAME) { + if (sys.platform !== sys.WECHAT_GAME) { element.focus(); } }, diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index 8c1652c136..28a1f931ec 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -30,7 +30,7 @@ function isWeChatGame () { var __BrowserGetter = { init: function(){ - if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME) { + if (cc.sys.platform !== cc.sys.WECHAT_GAME) { this.html = document.getElementsByTagName("html")[0]; } }, @@ -395,7 +395,7 @@ var View = cc._Class.extend({ }, _adjustViewportMeta: function () { - if (this._isAdjustViewPort && cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME) { + if (this._isAdjustViewPort && cc.sys.platform !== cc.sys.WECHAT_GAME) { this._setViewportMeta(__BrowserGetter.meta, false); this._isAdjustViewPort = false; } @@ -828,7 +828,7 @@ var View = cc._Class.extend({ * @param {ResolutionPolicy|Number} resolutionPolicy The resolution policy desired */ setRealPixelResolution: function (width, height, resolutionPolicy) { - if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME) { + if (cc.sys.platform !== cc.sys.WECHAT_GAME) { // Set viewport's width this._setViewportMeta({"width": width}, true); @@ -1064,7 +1064,7 @@ cc.ContainerStrategy = cc._Class.extend(/** @lends cc.ContainerStrategy# */{ _setupContainer: function (view, w, h) { var locCanvas = cc.game.canvas, locContainer = cc.game.container; - if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME) { + if (cc.sys.platform !== cc.sys.WECHAT_GAME) { if (cc.sys.os === cc.sys.OS_ANDROID) { document.body.style.width = (view._isRotated ? h : w) + 'px'; document.body.style.height = (view._isRotated ? w : h) + 'px'; diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 0cdb1ea19a..281e693bc6 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -803,7 +803,7 @@ game.once(game.EVENT_RENDERER_INITED, function () { var gl = this._gl; gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, premultiplyAlpha); if ( - sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME || + sys.platform === sys.WECHAT_GAME || img instanceof HTMLCanvasElement || img instanceof HTMLImageElement || img instanceof HTMLVideoElement diff --git a/cocos2d/core/videoplayer/CCSGVideoPlayer.js b/cocos2d/core/videoplayer/CCSGVideoPlayer.js index 783d385437..b88a520d45 100644 --- a/cocos2d/core/videoplayer/CCSGVideoPlayer.js +++ b/cocos2d/core/videoplayer/CCSGVideoPlayer.js @@ -221,7 +221,7 @@ _ccsg.VideoPlayer.EventType = { * so it is best to provide mp4 and webm or ogv file */ var dom = document.createElement("video"); - if (sys.browserType !== sys.BROWSER_TYPE_WECHAT_GAME) { + if (sys.platform !== sys.WECHAT_GAME) { if(dom.canPlayType("video/ogg")){ video._polyfill.canPlayType.push(".ogg"); video._polyfill.canPlayType.push(".ogv"); From e63e1aa1d26e09bd55aadbabe0074b575365f621 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 15 Nov 2017 16:05:21 +0800 Subject: [PATCH 042/127] Fix window access in editor environment --- index.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/index.js b/index.js index 18295ef15e..eee5acd80b 100644 --- a/index.js +++ b/index.js @@ -142,7 +142,7 @@ defineMacro('CC_BUILD', false); cc = {}; // check whether support jit -cc.supportJit = !window.wx && typeof Function('') === 'function'; +cc.supportJit = !defined('wx') && typeof Function('') === 'function'; // The namespace for original nodes rendering in scene graph. _ccsg = {}; From fc1a6dd25be66ab84756bdd82a4ca3e5aa7d6bac Mon Sep 17 00:00:00 2001 From: pandamicro Date: Wed, 15 Nov 2017 17:59:54 +0800 Subject: [PATCH 043/127] Fix audio format support in wechat game --- cocos2d/core/platform/CCSys.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCSys.js b/cocos2d/core/platform/CCSys.js index 0416cc2d4d..eb224a7279 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -575,7 +575,8 @@ else if (isWeChatGame()) { sys.__audioSupport = { ONLY_ONE: false, WEB_AUDIO: false, - DELAY_CREATE_CTX: false + DELAY_CREATE_CTX: false, + format: ['.mp3'] }; } else { From ceef20384a539593f337faa278ca896406d0d284 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 16 Nov 2017 11:38:00 +0800 Subject: [PATCH 044/127] Remove text downloader polyfill for wechat game --- cocos2d/core/load-pipeline/text-downloader.js | 27 ------------------- 1 file changed, 27 deletions(-) diff --git a/cocos2d/core/load-pipeline/text-downloader.js b/cocos2d/core/load-pipeline/text-downloader.js index 2f997e658d..39ac5a3e7e 100644 --- a/cocos2d/core/load-pipeline/text-downloader.js +++ b/cocos2d/core/load-pipeline/text-downloader.js @@ -18,35 +18,8 @@ else { module.exports = function (item, callback) { var url = item.url; - url = urlAppendTimestamp(url); - if (sys.platform === sys.WECHAT_GAME) { - var fs = wx.getFileSystemManager(); - var filePath = url; - // var localPath = wx.env.USER_DATA_PATH + '/' + filePath; - // Read from package - // fs.accessSync(filePath); - fs.readFile({ - filePath: filePath, - encoding: 'utf8', - success: function (res) { - if (res.data) { - // console.error('read file success'); - callback(null, res.data); - } - }, - fail: function (res) { - if (res.errMsg) { - console.error('read file path' + filePath + ' failed!'); - cc.game.emit('xhr-load-error:', res.errMsg); - callback({status:0, errorMessage: res.errMsg}); - } - } - }); - return; - } - var xhr = cc.loader.getXMLHttpRequest(), errInfo = 'Load ' + url + ' failed!', navigator = window.navigator; From 1f1b04d5673e5289ed06ba0f41194c5307052de0 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 16 Nov 2017 17:02:58 +0800 Subject: [PATCH 045/127] Expose PackDownloader to user (for wechat environment) --- cocos2d/core/load-pipeline/downloader.js | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos2d/core/load-pipeline/downloader.js b/cocos2d/core/load-pipeline/downloader.js index 7ce3f66301..a0a9da2a27 100644 --- a/cocos2d/core/load-pipeline/downloader.js +++ b/cocos2d/core/load-pipeline/downloader.js @@ -286,6 +286,7 @@ var Downloader = function (extMap) { this.extMap = JS.mixin(extMap, defaultMap); }; Downloader.ID = ID; +Downloader.PackDownloader = PackDownloader; /** * Add custom supported types handler or modify existing type handler. From 000f4c1fc9516a62124b18a68419b0680f1ca063 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 16 Nov 2017 21:53:37 +0800 Subject: [PATCH 046/127] prefab should not resync if is instantiated by its parent (which is not a prefab) --- cocos2d/core/CCNode.js | 31 +++++++++++++++++++++---- cocos2d/core/CCScene.js | 11 ++++++++- cocos2d/core/utils/base-node.js | 19 +++++++++------ cocos2d/core/utils/prefab-helper.js | 15 +++++++++++- test/qunit/unit-es5/test-prefab-sync.js | 2 +- 5 files changed, 64 insertions(+), 14 deletions(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index fbc77b8cfc..35006eadb0 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -1061,11 +1061,12 @@ var Node = cc.Class({ */ _onBatchCreated () { var prefabInfo = this._prefab; - if (prefabInfo && prefabInfo.sync && !prefabInfo._synced) { - // checks to ensure no recursion, recursion will caused only on old data. - if (prefabInfo.root === this) { - PrefabHelper.syncWithPrefab(this); + if (prefabInfo && prefabInfo.sync && prefabInfo.root === this) { + if (CC_DEV) { + // TODO - remove all usage of _synced + cc.assert(!prefabInfo._synced, 'prefab should not synced'); } + PrefabHelper.syncWithPrefab(this); } this._updateDummySgNode(); @@ -1088,6 +1089,28 @@ var Node = cc.Class({ } }, + // the same as _onBatchCreated but untouch prefab + _onBatchRestored () { + this._updateDummySgNode(); + + if (this._parent) { + this._parent._sgNode.addChild(this._sgNode); + } + + if (!this._activeInHierarchy) { + // deactivate ActionManager and EventManager by default + if (ActionManagerExist) { + cc.director.getActionManager().pauseTarget(this); + } + cc.eventManager.pauseTarget(this); + } + + var children = this._children; + for (var i = 0, len = children.length; i < len; i++) { + children[i]._onBatchRestored(); + } + }, + // EVENTS /** diff --git a/cocos2d/core/CCScene.js b/cocos2d/core/CCScene.js index 6c044f80f3..a3a76e2d57 100644 --- a/cocos2d/core/CCScene.js +++ b/cocos2d/core/CCScene.js @@ -62,6 +62,10 @@ cc.Scene = cc.Class({ this._activeInHierarchy = false; this._inited = !cc.game._isCloning; + if (CC_EDITOR) { + this._prefabSyncedInLiveReload = false; + } + // cache all depend assets for auto release this.dependAssets = null; }, @@ -79,7 +83,12 @@ cc.Scene = cc.Class({ if (CC_TEST) { cc.assert(!this._activeInHierarchy, 'Should deactivate ActionManager and EventManager by default'); } - this._onBatchCreated(); + if (CC_EDITOR && this._prefabSyncedInLiveReload) { + this._onBatchRestored(); + } + else { + this._onBatchCreated(); + } this._inited = true; } }, diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js index d60fffff61..e4acdfb5f2 100644 --- a/cocos2d/core/utils/base-node.js +++ b/cocos2d/core/utils/base-node.js @@ -23,6 +23,7 @@ THE SOFTWARE. ****************************************************************************/ +var PrefabHelper = require('./prefab-helper'); var Flags = require('../platform/CCObject').Flags; var Misc = require('./misc'); var IdGenerater = require('../platform/id-generater'); @@ -1055,6 +1056,12 @@ var BaseNode = cc.Class({ _onSetParent (value) {}, _onPostActivated () {}, + _onBatchRestored () { + var children = this._children; + for (var i = 0, len = children.length; i < len; i++) { + children[i]._onBatchRestored(); + } + }, _onHierarchyChanged (oldParent) { var newParent = this._parent; @@ -1107,11 +1114,11 @@ var BaseNode = cc.Class({ _onBatchCreated () { var prefabInfo = this._prefab; - if (prefabInfo && prefabInfo.sync && !prefabInfo._synced) { - // checks to ensure no recursion, recursion will caused only on old data. - if (prefabInfo.root === this) { - PrefabHelper.syncWithPrefab(this); + if (prefabInfo && prefabInfo.sync && prefabInfo.root === this) { + if (CC_DEV && prefabInfo._synced) { + cc.error('Internal error: prefab already synced'); } + PrefabHelper.syncWithPrefab(this); } var children = this._children; @@ -1133,8 +1140,6 @@ var BaseNode = cc.Class({ } var syncing = thisPrefabInfo && this === thisPrefabInfo.root && thisPrefabInfo.sync; if (syncing) { - // copy non-serialized property - cloned._prefab._synced = thisPrefabInfo._synced; //if (thisPrefabInfo._synced) { // return clone; //} @@ -1145,7 +1150,7 @@ var BaseNode = cc.Class({ // reset and init cloned._parent = null; - cloned._onBatchCreated(); + cloned._onBatchRestored(); return cloned; }, diff --git a/cocos2d/core/utils/prefab-helper.js b/cocos2d/core/utils/prefab-helper.js index 9ee8248e5e..a2086f361d 100644 --- a/cocos2d/core/utils/prefab-helper.js +++ b/cocos2d/core/utils/prefab-helper.js @@ -25,11 +25,13 @@ cc._PrefabInfo = cc.Class({ name: 'cc.PrefabInfo', + // extends: require('../platform/CCObject'), properties: { // the most top node of this prefab in the scene root: null, // 所属的 prefab 资源对象 (cc.Prefab) + // In Editor, only asset._uuid is usable because asset will be changed. asset: null, // 用来标识别该节点在 prefab 资源中的位置,因此这个 ID 只需要保证在 Assets 里不重复就行 @@ -43,7 +45,18 @@ cc._PrefabInfo = cc.Class({ default: false, serializable: false }, - } + }, + // _instantiate (cloned) { + // if (!cloned) { + // cloned = new cc._PrefabInfo(); + // } + // cloned.root = this.root; + // cloned.asset = this.asset; + // cloned.fileId = this.fileId; + // cloned.sync = this.sync; + // cloned._synced = this._synced; + // return cloned; + // } }); // prefab helper function diff --git a/test/qunit/unit-es5/test-prefab-sync.js b/test/qunit/unit-es5/test-prefab-sync.js index 9f076a7960..801476d987 100644 --- a/test/qunit/unit-es5/test-prefab-sync.js +++ b/test/qunit/unit-es5/test-prefab-sync.js @@ -127,7 +127,7 @@ var newNode = cc.instantiate(nodeToCreatePrefab); testInstantiatedNode(newNode); ok(newNode._prefab.sync === true, "sync should be instantiated"); - ok(newNode._prefab._synced === true, "instantiated node should be _synced"); + // ok(newNode._prefab._synced === true, "instantiated node should be _synced"); }); test('load and sync scene', function () { From fee3a0a7bd76bbb1eef3239bc8d03852a7109419 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Tue, 21 Nov 2017 10:37:05 +0800 Subject: [PATCH 047/127] support playMusic --- cocos2d/audio/CCAudioEngine.js | 248 +++++++++++++++++++++++++++++++++ cocos2d/audio/deprecated.js | 178 +---------------------- jsb/jsb-audio.js | 88 +++++++++++- 3 files changed, 336 insertions(+), 178 deletions(-) diff --git a/cocos2d/audio/CCAudioEngine.js b/cocos2d/audio/CCAudioEngine.js index 3dd6f0c986..410bebf020 100644 --- a/cocos2d/audio/CCAudioEngine.js +++ b/cocos2d/audio/CCAudioEngine.js @@ -504,6 +504,254 @@ var audioEngine = { audio.resume(); } this._breakCache = null; + }, + + /////////////////////////////// + // Classification of interface + + _music: { + id: -1, + loop: false, + volume: 1, + }, + + _effect: { + volume: 1, + pauseCache: [], + }, + + /** + * !#en Play background music + * !#zh 播放背景音乐 + * @method playMusic + * @param {String} filePath - The path of the audio file without filename extension. + * @param {Boolean} loop - Whether the music loop or not. + * @return {Number} audioId + * @example + * var audioID = cc.audioEngine.playMusic(path, false); + */ + playMusic: function (filePath, loop) { + var music = this._music; + this.stop(music.id); + music.id = this.play(filePath, loop, music.volume); + music.loop = loop; + return music.id; + }, + + /** + * !#en Stop background music. + * !#zh 停止播放背景音乐。 + * @method stopMusic + * @example + * cc.audioEngine.stopMusic(); + */ + stopMusic: function () { + this.stop(this._music.id); + }, + + /** + * !#en Pause the background music. + * !#zh 暂停播放背景音乐。 + * @method pauseMusic + * @example + * cc.audioEngine.pauseMusic(); + */ + pauseMusic: function () { + this.pause(this._music.id); + return this._music.id; + }, + + /** + * !#en Resume playing background music. + * !#zh 恢复播放背景音乐。 + * @method resumeMusic + * //example + * cc.audioEngine.resumeMusic(); + */ + resumeMusic: function () { + this.resume(this._music.id); + return this._music.id; + }, + + /** + * !#en Get the volume(0.0 ~ 1.0). + * !#zh 获取音量(0.0 ~ 1.0)。 + * @method getMusicVolume + * @return {Number} + * @example + * var volume = cc.audioEngine.getMusicVolume(); + */ + getMusicVolume: function () { + return this._music.volume; + }, + + /** + * !#en Set the background music volume. + * !#zh 设置背景音乐音量(0.0 ~ 1.0)。 + * @method setMusicVolume + * @param {Number} volume - Volume must be in 0.0~1.0. + * @example + * cc.audioEngine.setMusicVolume(0.5); + */ + setMusicVolume: function (volume) { + var music = this._music; + music.volume = volume; + this.setVolume(music.id, music.volume); + return music.volume; + }, + + /** + * !#en Background music playing state + * !#zh 背景音乐是否正在播放 + * @method isMusicPlaying + * @return {Boolean} + * @example + * cc.audioEngine.isMusicPlaying(); + */ + isMusicPlaying: function () { + return this.getState(this._music.id) === this.AudioState.PLAYING; + }, + + /** + * !#en Play effect audio. + * !#zh 播放音效 + * @method playEffect + * @param {String} filePath - The path of the audio file without filename extension. + * @param {Boolean} loop - Whether the music loop or not. + * @return {Number} audioId + * @example + * var audioID = cc.audioEngine.playEffect(path, false); + */ + playEffect: function (filePath, loop) { + var effect = this._effect; + return this.play(filePath, loop || false, effect.volume); + }, + + /** + * !#en Set the volume of effect audio. + * !#zh 设置音效音量(0.0 ~ 1.0)。 + * @method setEffectsVolume + * @param {Number} volume - Volume must be in 0.0~1.0. + * @example + * cc.audioEngine.setEffectsVolume(0.5); + */ + setEffectsVolume: function (volume) { + this._effect.volume = volume; + var id2audio = audioEngine._id2audio; + for (var id in id2audio) { + if (id === musicId) continue; + audioEngine.setVolume(id, volume); + } + }, + + /** + * !#en The volume of the effect audio max value is 1.0,the min value is 0.0 . + * !#zh 获取音效音量(0.0 ~ 1.0)。 + * @method getEffectsVolume + * @return {Number} + * @example + * var volume = cc.audioEngine.getEffectsVolume(); + */ + getEffectsVolume: function () { + return this._effect.volume; + }, + + /** + * !#en Pause effect audio. + * !#zh 暂停播放音效。 + * @method pauseEffect + * @param {Number} audioID - audio id. + * @example + * cc.audioEngine.pauseEffect(audioID); + */ + pauseEffect: function (audioID) { + return this.pause(audioID); + }, + + /** + * !#en Stop playing all the sound effects. + * !#zh 暂停播放所有音效。 + * @method pauseAllEffects + * @example + * cc.audioEngine.pauseAllEffects(); + */ + pauseAllEffects: function () { + var musicId = this._music.id; + var effect = this._effect; + var id2audio = this._id2audio; + effect.pauseCache.length = 0; + + for (var id in id2audio) { + if (id === musicId) continue; + var audio = id2audio[id]; + var state = audio.getState(); + if (state === this.AudioState.PLAYING) { + effect.pauseCache.push(id); + audio.pause(); + } + } + }, + + /** + * !#en Resume effect audio. + * !#zh 恢复播放音效音频。 + * @method resumeEffect + * @param {Number} audioID - The return value of function play. + * //example + * cc.audioEngine.resumeEffect(audioID); + */ + resumeEffect: function (id) { + this.resume(id); + }, + + /** + * !#en Resume all effect audio. + * !#zh 恢复播放所有之前暂停的音效。 + * @method resumeAllEffects + * @example + * cc.audioEngine.resumeAllEffects(); + */ + resumeAllEffects: function () { + var pauseIDCache = this._effect.pauseCache; + var id2audio = this._id2audio; + while (pauseIDCache.length > 0) { + var id = pauseIDCache.pop(); + var audio = id2audio[id]; + if (audio && audio.resume) + audio.resume(); + } + }, + + /** + * !#en Stop playing the effect audio. + * !#zh 停止播放音效。 + * @method stopEffect + * @param {Number} audioID - audio id. + * @example + * cc.audioEngine.stopEffect(id); + */ + stopEffect: function (audioID) { + return this.stop(audioID); + }, + + /** + * !#en Stop playing all the effects. + * !#zh 停止播放所有音效。 + * @method stopAllEffects + * @example + * cc.audioEngine.stopAllEffects(); + */ + stopAllEffects: function () { + var musicId = this._music.id; + var id2audio = this._id2audio; + for (var id in id2audio) { + if (id === musicId) continue; + var audio = id2audio[id]; + var state = audio.getState(); + if (state === audioEngine.AudioState.PLAYING) { + audio.stop(); + } + } } }; diff --git a/cocos2d/audio/deprecated.js b/cocos2d/audio/deprecated.js index 4a96eb914d..6e0b459c4d 100644 --- a/cocos2d/audio/deprecated.js +++ b/cocos2d/audio/deprecated.js @@ -25,7 +25,7 @@ ****************************************************************************/ var js = cc.js; -// var INFO = cc._LogInfos.deprecated; +var INFO = cc._LogInfos.deprecated; exports.removed = function (audioEngine) { function willPlayMusicError () { @@ -42,185 +42,15 @@ exports.deprecated = function (audioEngine) { var musicVolume = 1; var effectsVolume = 1; var pauseIDCache = []; - js.get(audioEngine, 'playMusic', function () { - // cc.warn(INFO, 'audioEngine.playMusic', 'audioEngine.play'); - return function (url, loop) { - audioEngine.stop(musicId); - musicId = audioEngine.play(url, loop, musicVolume); - musicPath = url; - musicLoop = loop; - return musicId; - } - }); - js.get(audioEngine, 'stopMusic', function () { - // cc.warn(INFO, 'audioEngine.stopMusic', 'audioEngine.stop'); - return function () { - audioEngine.stop(musicId); - return musicId; - } - }); - js.get(audioEngine, 'pauseMusic', function () { - // cc.warn(INFO, 'audioEngine.pauseMusic', 'audioEngine.pause'); - return function () { - audioEngine.pause(musicId); - return musicId; - } - }); - js.get(audioEngine, 'resumeMusic', function () { - // cc.warn(INFO, 'audioEngine.resumeMusic', 'audioEngine.resume'); - return function () { - audioEngine.resume(musicId); - return musicId; - } - }); js.get(audioEngine, 'rewindMusic', function () { - // cc.warn(INFO, 'audioEngine.rewindMusic', 'audioEngine.setCurrentTime'); + cc.warn(INFO, 'audioEngine.rewindMusic', 'audioEngine.setCurrentTime'); return function () { audioEngine.setCurrentTime(musicId, 0); return musicId; } }); - js.get(audioEngine, 'getMusicVolume', function () { - // cc.warn(INFO, 'audioEngine.getMusicVolume', 'audioEngine.getVolume'); - return function () { - return musicVolume; - } - }); - js.get(audioEngine, 'setMusicVolume', function () { - // cc.warn(INFO, 'audioEngine.setMusicVolume', 'audioEngine.setVolume'); - return function (volume) { - musicVolume = volume; - audioEngine.setVolume(musicId, musicVolume); - return musicVolume; - } - }); - js.get(audioEngine, 'isMusicPlaying', function () { - // cc.warn(INFO, 'audioEngine.isMusicPlaying', 'audioEngine.getState'); - return function () { - return audioEngine.getState(musicId) === audioEngine.AudioState.PLAYING; - } - }); - js.get(audioEngine, 'playEffect', function () { - // cc.warn(INFO, 'audioEngine.playEffect', 'audioEngine.play'); - return function (url, loop, volume) { - return audioEngine.play(url, loop || false, volume === undefined ? effectsVolume : volume); - } - }); - js.get(audioEngine, 'setEffectsVolume', function (volume) { - // cc.warn(INFO, 'audioEngine.setEffectsVolume', 'audioEngine.setVolume'); - return function (volume) { - effectsVolume = volume; - var id2audio = audioEngine._id2audio; - for (var id in id2audio) { - if (id === musicId) continue; - audioEngine.setVolume(id, volume); - } - } - }); - js.get(audioEngine, 'getEffectsVolume', function () { - // cc.warn(INFO, 'audioEngine.getEffectsVolume', 'audioEngine.getVolume'); - return function () { - return effectsVolume; - } - }); - js.get(audioEngine, 'pauseEffect', function () { - // cc.warn(INFO, 'audioEngine.pauseEffect', 'audioEngine.pause'); - - return function (id) { - return audioEngine.pause(id); - } - }); - js.get(audioEngine, 'pauseAllEffects', function () { - // cc.warn(INFO, 'audioEngine.pauseAllEffects', 'audioEngine.pauseAll'); - - if (CC_JSB) { - return function () { - var musicPlay = audioEngine.getState(musicId) === audioEngine.AudioState.PLAYING; - audioEngine.pauseAll(); - if (musicPlay) { - audioEngine.resume(musicId); - } - } - } - - return function () { - pauseIDCache.length = 0; - var id2audio = audioEngine._id2audio; - for (var id in id2audio) { - if (id === musicId) continue; - var audio = id2audio[id]; - var state = audio.getState(); - if (state === audioEngine.AudioState.PLAYING) { - pauseIDCache.push(id); - audio.pause(); - } - } - } - }); - js.get(audioEngine, 'resumeEffect', function () { - // cc.warn(INFO, 'audioEngine.resumeEffect', 'audioEngine.resume'); - return function (id) { - audioEngine.resume(id); - } - }); - js.get(audioEngine, 'resumeAllEffects', function () { - // cc.warn(INFO, 'audioEngine.resumeEffect', 'audioEngine.resume'); - - if (CC_JSB) { - return function () { - var musicPaused = audioEngine.getState(musicId) === audioEngine.AudioState.PAUSED; - audioEngine.resumeAll(); - if (musicPaused && audioEngine.getState(musicId) === audioEngine.AudioState.PLAYING) { - audioEngine.pause(musicId); - } - }; - } - - return function () { - var id2audio = audioEngine._id2audio; - while (pauseIDCache.length > 0) { - var id = pauseIDCache.pop(); - var audio = id2audio[id]; - if (audio && audio.resume) - audio.resume(); - } - } - }); - js.get(audioEngine, 'stopEffect', function () { - // cc.warn(INFO, 'audioEngine.stopEffect', 'audioEngine.stop'); - return function (id) { - return audioEngine.stop(id); - } - }); - js.get(audioEngine, 'stopAllEffects', function () { - // cc.warn(INFO, 'audioEngine.stopAllEffects', 'audioEngine.stopAll'); - - if (CC_JSB) { - return function () { - var musicPlay = audioEngine.getState(musicId) === audioEngine.AudioState.PLAYING; - var currentTime = audioEngine.getCurrentTime(musicId); - audioEngine.stopAll(); - if (musicPlay) { - musicId = audioEngine.play(musicPath, musicLoop); - audioEngine.setCurrentTime(musicId, currentTime); - } - } - } - - return function () { - var id2audio = audioEngine._id2audio; - for (var id in id2audio) { - if (id === musicId) continue; - var audio = id2audio[id]; - var state = audio.getState(); - if (state === audioEngine.AudioState.PLAYING) { - audio.stop(); - } - } - } - }); js.get(audioEngine, 'unloadEffect', function () { - // cc.warn(INFO, 'audioEngine.unloadEffect', 'audioEngine.stop'); + cc.warn(INFO, 'audioEngine.unloadEffect', 'audioEngine.stop'); return function (id) { return audioEngine.stop(id); } @@ -228,7 +58,7 @@ exports.deprecated = function (audioEngine) { if (!CC_JSB) { js.get(audioEngine, 'end', function () { - // cc.warn(INFO, 'audioEngine.end', 'audioEngine.stopAll'); + cc.warn(INFO, 'audioEngine.end', 'audioEngine.stopAll'); return function () { return audioEngine.stopAll(); } diff --git a/jsb/jsb-audio.js b/jsb/jsb-audio.js index c97d58e13d..a2a7449b1c 100644 --- a/jsb/jsb-audio.js +++ b/jsb/jsb-audio.js @@ -47,10 +47,6 @@ cc.Audio.Type = { cc.audioEngine = audioEngine; audioEngine.play = audioEngine.play2d; audioEngine.setMaxWebAudioSize = function () {}; - // deprecated - var Module = require('../cocos2d/audio/deprecated'); - Module.removed(audioEngine); - Module.deprecated(audioEngine); proto.State = audioEngine.AudioState; @@ -148,4 +144,88 @@ cc.Audio.Type = { return true; }; + var _music = { + id: -1, + url: '', + volume: 1 + }; + var _effect = { + volume: 1 + }; + audioEngine.playMusic = function (filePath, loop) { + audioEngine.stop(_music.id); + _music.id = audioEngine.play(filePath, loop, _music.volume); + _music.loop = loop; + _music.url = filePath; + return _music.id; + }; + audioEngine.stopMusic = function () { + audioEngine.stop(_music.id); + }; + audioEngine.pauseMusic = function () { + audioEngine.pause(_music.id); + return _music.id; + }; + audioEngine.resumeMusic = function () { + audioEngine.resume(_music.id); + return _music.id; + }; + audioEngine.getMusicVolume = function () { + return _music.volume; + }; + audioEngine.setMusicVolume = function (volume) { + _music.volume = volume; + audioEngine.setVolume(_music.id, _music.volume); + return _music.volume; + }; + audioEngine.isMusicPlaying = function () { + return audioEngine.getState(_music.id) === audioEngine.AudioState.PLAYING; + }; + audioEngine.playEffect = function (filePath, loop) { + return audioEngine.play(filePath, loop || false, _effect.volume); + }; + audioEngine.setEffectsVolume = function (volume) { + _effect.volume = volume; + }; + audioEngine.getEffectsVolume = function () { + return _effect.volume; + }; + audioEngine.pauseEffect = function (audioID) { + return audioEngine.pause(audioID); + }; + audioEngine.pauseAllEffects = function () { + var musicPlay = audioEngine.getState(_music.id) === audioEngine.AudioState.PLAYING; + audioEngine.pauseAll(); + if (musicPlay) { + audioEngine.resume(_music.id); + } + }; + audioEngine.resumeEffect = function (id) { + audioEngine.resume(id); + }; + audioEngine.resumeAllEffects = function () { + var musicPaused = audioEngine.getState(_music.id) === audioEngine.AudioState.PAUSED; + audioEngine.resumeAll(); + if (musicPaused && audioEngine.getState(_music.id) === audioEngine.AudioState.PLAYING) { + audioEngine.pause(_music.id); + } + }; + audioEngine.stopEffect = function (id) { + return audioEngine.stop(id); + }; + audioEngine.stopAllEffects = function () { + var musicPlay = audioEngine.getState(_music.id) === audioEngine.AudioState.PLAYING; + var currentTime = audioEngine.getCurrentTime(_music.id); + audioEngine.stopAll(); + if (musicPlay) { + _music.id = audioEngine.play(_music.url, _music.loop); + audioEngine.setCurrentTime(_music.id, currentTime); + } + }; + + // deprecated + var Module = require('../cocos2d/audio/deprecated'); + Module.removed(audioEngine); + Module.deprecated(audioEngine); + })(cc.Audio.prototype, jsb.AudioEngine); \ No newline at end of file From e4a989c107ee524099e76bf978b205b8c198a8dc Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Tue, 21 Nov 2017 10:52:13 +0800 Subject: [PATCH 048/127] comp.schedule should not use enabledInHierarchy to judge whether paused, because enabledInHierarchy is assigned after onEnable --- cocos2d/core/components/CCComponent.js | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/components/CCComponent.js b/cocos2d/core/components/CCComponent.js index 5a982739b9..7882750f55 100644 --- a/cocos2d/core/components/CCComponent.js +++ b/cocos2d/core/components/CCComponent.js @@ -544,8 +544,8 @@ var Component = cc.Class({ * 如果回调函数已调度,那么将不会重复调度它,只会更新时间间隔参数。 * @method schedule * @param {function} callback The callback function - * @param {Number} [interval=0] Tick interval in seconds. 0 means tick every frame. If interval = 0, it's recommended to use scheduleUpdate() instead. - * @param {Number} [repeat=cc.macro.REPEAT_FOREVER] The selector will be executed (repeat + 1) times, you can use kCCRepeatForever for tick infinitely. + * @param {Number} [interval=0] Tick interval in seconds. 0 means tick every frame. + * @param {Number} [repeat=cc.macro.REPEAT_FOREVER] The selector will be executed (repeat + 1) times, you can use cc.macro.REPEAT_FOREVER for tick infinitely. * @param {Number} [delay=0] The amount of time that the first tick will wait before execution. * @example * var timeCallback = function (dt) { @@ -561,7 +561,15 @@ var Component = cc.Class({ repeat = isNaN(repeat) ? cc.macro.REPEAT_FOREVER : repeat; delay = delay || 0; - cc.director.getScheduler().schedule(callback, this, interval, repeat, delay, !this.enabledInHierarchy); + var scheduler = cc.director.getScheduler(); + + // should not use enabledInHierarchy to judge whether paused, + // because enabledInHierarchy is assigned after onEnable. + // Actually, if not yet scheduled, resumeTarget/pauseTarget has no effect on component, + // therefore there is no way to guarantee the paused state other than isTargetPaused. + var paused = scheduler.isTargetPaused(); + + scheduler.schedule(callback, this, interval, repeat, delay, paused); }, /** From a595b8b6db51f175fd6e5a96ac8991aaa90ee2d6 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 20 Nov 2017 14:41:41 +0800 Subject: [PATCH 049/127] half pixel correction in tilemap --- cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js index 64de43bcc5..e896954868 100644 --- a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js @@ -150,7 +150,8 @@ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset) { colOffset = startRow * cols, z, gid, grid, i, top, left, bottom, right, gt, gl, gb, gr, - wa = a, wb = b, wc = c, wd = d, wtx = tx, wty = ty, // world + wa = a, wb = b, wc = c, wd = d, + wtx = Math.floor(tx) + 0.5, wty = Math.floor(ty) + 0.5, // world flagged = false, flippedX = false, flippedY = false, vertices = this._vertices, axis, tileOffset, diffX1, diffY1, odd_even; From ed145df2282675cb5547dd266fa702fa72d1dfc0 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 20 Nov 2017 14:40:33 +0800 Subject: [PATCH 050/127] Improve ortho tilemap culling calculation --- cocos2d/core/base-nodes/CCSGNode.js | 8 ++-- cocos2d/core/value-types/CCAffineTransform.js | 6 +-- cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js | 42 ++++++++++++++----- 3 files changed, 39 insertions(+), 17 deletions(-) diff --git a/cocos2d/core/base-nodes/CCSGNode.js b/cocos2d/core/base-nodes/CCSGNode.js index 76782a42bb..5c06277a94 100644 --- a/cocos2d/core/base-nodes/CCSGNode.js +++ b/cocos2d/core/base-nodes/CCSGNode.js @@ -1695,9 +1695,9 @@ _ccsg.Node = cc.Class({ * @return {cc.AffineTransform} */ getNodeToWorldTransform: function () { - var t = this.getNodeToParentTransform(); + var t = cc.affineTransformClone(this.getNodeToParentTransform()); for (var p = this._parent; p !== null; p = p.parent) - t = cc.affineTransformConcat(t, p.getNodeToParentTransform()); + t = cc.affineTransformConcatIn(t, p.getNodeToParentTransform()); return t; }, @@ -1715,7 +1715,9 @@ _ccsg.Node = cc.Class({ * @return {cc.AffineTransform} */ getWorldToNodeTransform: function () { - return cc.affineTransformInvert(this.getNodeToWorldTransform()); + var trans = this.getNodeToWorldTransform(); + cc.affineTransformInvertOut(trans, trans); + return trans; }, /** diff --git a/cocos2d/core/value-types/CCAffineTransform.js b/cocos2d/core/value-types/CCAffineTransform.js index 27c2c4fdf5..d02b7c86be 100644 --- a/cocos2d/core/value-types/CCAffineTransform.js +++ b/cocos2d/core/value-types/CCAffineTransform.js @@ -382,12 +382,12 @@ cc.affineTransformInvert = function (t) { * @param {AffineTransform} out */ cc.affineTransformInvertOut = function (t, out) { - var a = t.a, b = t.b, c = t.c, d = t.d; + var a = t.a, b = t.b, c = t.c, d = t.d, tx = t.tx, ty = t.ty; var determinant = 1 / (a * d - b * c); out.a = determinant * d; out.b = -determinant * b; out.c = -determinant * c; out.d = determinant * a; - out.tx = determinant * (c * t.ty - d * t.tx); - out.ty = determinant * (b * t.tx - a * t.ty); + out.tx = determinant * (c * ty - d * tx); + out.ty = determinant * (b * tx - a * ty); }; diff --git a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js index e896954868..f3a2555cff 100644 --- a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js @@ -118,24 +118,45 @@ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset) { var cullingA = a, cullingD = d, cullingMapx = mapx, cullingMapy = mapy, cullingW = w, cullingH = h; - var enabledCulling = cc.macro.ENABLE_TILEDMAP_CULLING; + var enabledCulling = cc.macro.ENABLE_TILEDMAP_CULLING, + vertices = this._vertices; if (enabledCulling) { + var trans; if (this._cameraFlag > 0) { - var tmpt = cc.affineTransformConcat(wt, cc.Camera.main.viewMatrix); - cullingA = tmpt.a; - cullingD = tmpt.d; - cullingMapx = ox * cullingA + oy * tmpt.c + tmpt.tx; - cullingMapy = ox * tmpt.b + oy * cullingD + tmpt.ty; + trans = cc.affineTransformConcat(wt, cc.Camera.main.viewMatrix); + cullingA = trans.a; + cullingD = trans.d; + cullingMapx = ox * cullingA + oy * trans.c + trans.tx; + cullingMapy = ox * trans.b + oy * cullingD + trans.ty; cullingW = tilew * cullingA; cullingH = tileh * cullingD; } if (layerOrientation === Orientation.ORTHO) { - startCol = Math.floor(-(cullingMapx - extw * cullingA) / (maptw * cullingA)); - startRow = Math.floor((cullingMapy - exth * cullingD + mapth * rows * cullingD - winh) / (mapth * cullingD)); - maxCol = Math.ceil((winw - cullingMapx + extw * cullingA) / (maptw * cullingA)); - maxRow = rows - Math.floor(-(cullingMapy + exth * cullingD) / (mapth * cullingD)); + // In case trans is not created yet + if (this._cameraFlag <= 0) { + trans = cc.affineTransformClone(wt); + } + cc.affineTransformInvertOut(trans, trans); + var world = cc.visibleRect; + vertices[0].x = world.topLeft.x * trans.a + world.topLeft.y * trans.c + trans.tx; + vertices[0].y = world.topLeft.x * trans.b + world.topLeft.y * trans.d + trans.ty; + vertices[1].x = world.bottomLeft.x * trans.a + world.bottomLeft.y * trans.c + trans.tx; + vertices[1].y = world.bottomLeft.x * trans.b + world.bottomLeft.y * trans.d + trans.ty; + vertices[2].x = world.topRight.x * trans.a + world.topRight.y * trans.c + trans.tx; + vertices[2].y = world.topRight.x * trans.b + world.topRight.y * trans.d + trans.ty; + vertices[3].x = world.bottomRight.x * trans.a + world.bottomRight.y * trans.c + trans.tx; + vertices[3].y = world.bottomRight.x * trans.b + world.bottomRight.y * trans.d + trans.ty; + var minx = Math.min(vertices[0].x, vertices[1].x, vertices[2].x, vertices[3].x), + maxx = Math.max(vertices[0].x, vertices[1].x, vertices[2].x, vertices[3].x), + miny = Math.min(vertices[0].y, vertices[1].y, vertices[2].y, vertices[3].y), + maxy = Math.max(vertices[0].y, vertices[1].y, vertices[2].y, vertices[3].y); + + startCol = Math.floor(minx / maptw); + startRow = rows - Math.ceil(maxy / mapth); + maxCol = Math.ceil((maxx + extw) / maptw); + maxRow = rows - Math.floor((miny - exth) / mapth); // Adjustment if (startCol < 0) startCol = 0; @@ -153,7 +174,6 @@ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset) { wa = a, wb = b, wc = c, wd = d, wtx = Math.floor(tx) + 0.5, wty = Math.floor(ty) + 0.5, // world flagged = false, flippedX = false, flippedY = false, - vertices = this._vertices, axis, tileOffset, diffX1, diffY1, odd_even; if (layerOrientation === Orientation.HEX) { From fad401913be21101e9af35270db27253c2321236 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 23 Nov 2017 12:19:51 +0800 Subject: [PATCH 051/127] Fix mouse event dispatched to brother node issue --- cocos2d/core/CCNode.js | 65 +++++++++++++++++++++++++++++++++++------- 1 file changed, 55 insertions(+), 10 deletions(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index fbc77b8cfc..5bfe7728d3 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -146,17 +146,20 @@ var _mouseEvents = [ var _currentHovered = null; var _touchStartHandler = function (touch, event) { - if (CC_JSB) { - event = Event.EventTouch.pool.get(event); - } var pos = touch.getLocation(); var node = this.owner; if (node._hitTest(pos, this)) { + if (CC_JSB) { + event = Event.EventTouch.pool.get(event); + } event.type = EventType.TOUCH_START; event.touch = touch; event.bubbles = true; node.dispatchEvent(event); + if (CC_JSB) { + Event.EventTouch.pool.put(event); + } return true; } return false; @@ -170,6 +173,9 @@ var _touchMoveHandler = function (touch, event) { event.touch = touch; event.bubbles = true; node.dispatchEvent(event); + if (CC_JSB) { + Event.EventTouch.pool.put(event); + } }; var _touchEndHandler = function (touch, event) { if (CC_JSB) { @@ -187,6 +193,9 @@ var _touchEndHandler = function (touch, event) { event.touch = touch; event.bubbles = true; node.dispatchEvent(event); + if (CC_JSB) { + Event.EventTouch.pool.put(event); + } }; var _mouseDownHandler = function (event) { @@ -195,20 +204,31 @@ var _mouseDownHandler = function (event) { if (node._hitTest(pos, this)) { if (CC_JSB) { + // jsb event will be replaced so can be stopped immediately + event.stopPropagation(); event = Event.EventMouse.pool.get(event); } event.type = EventType.MOUSE_DOWN; event.bubbles = true; node.dispatchEvent(event); + if (CC_JSB) { + Event.EventTouch.pool.put(event); + } + else { + event.stopPropagation(); + } } }; var _mouseMoveHandler = function (event) { var pos = event.getLocation(); var node = this.owner; - if (node._hitTest(pos, this)) { - if (CC_JSB) { - event = Event.EventMouse.pool.get(event); - } + var hit = node._hitTest(pos, this); + if (CC_JSB && (hit || this._previousIn)) { + // jsb event will be replaced so can be stopped immediately + event.stopPropagation(); + event = Event.EventMouse.pool.get(event); + } + if (hit) { if (!this._previousIn) { // Fix issue when hover node switched, previous hovered node won't get MOUSE_LEAVE notification if (_currentHovered) { @@ -226,14 +246,23 @@ var _mouseMoveHandler = function (event) { node.dispatchEvent(event); } else if (this._previousIn) { - if (CC_JSB) { - event = Event.EventMouse.pool.get(event); - } event.type = EventType.MOUSE_LEAVE; node.dispatchEvent(event); this._previousIn = false; _currentHovered = null; } + else { + // continue dispatching + return; + } + + // Event processed, cleanup + if (CC_JSB) { + Event.EventTouch.pool.put(event); + } + else { + event.stopPropagation(); + } }; var _mouseUpHandler = function (event) { var pos = event.getLocation(); @@ -241,11 +270,19 @@ var _mouseUpHandler = function (event) { if (node._hitTest(pos, this)) { if (CC_JSB) { + // jsb event will be replaced so can be stopped immediately + event.stopPropagation(); event = Event.EventMouse.pool.get(event); } event.type = EventType.MOUSE_UP; event.bubbles = true; node.dispatchEvent(event); + if (CC_JSB) { + Event.EventTouch.pool.put(event); + } + else { + event.stopPropagation(); + } } }; var _mouseWheelHandler = function (event) { @@ -255,11 +292,19 @@ var _mouseWheelHandler = function (event) { if (node._hitTest(pos, this)) { //FIXME: separate wheel event and other mouse event. if (CC_JSB) { + // jsb event will be replaced so can be stopped immediately + event.stopPropagation(); event = Event.EventMouse.pool.get(event); } event.type = EventType.MOUSE_WHEEL; event.bubbles = true; node.dispatchEvent(event); + if (CC_JSB) { + Event.EventTouch.pool.put(event); + } + else { + event.stopPropagation(); + } } }; From a03232fd8283a5ad438940bcce7682e07f6cedbe Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 23 Nov 2017 14:14:24 +0800 Subject: [PATCH 052/127] Fix typo --- cocos2d/core/CCNode.js | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 5bfe7728d3..c50ab0af36 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -212,7 +212,7 @@ var _mouseDownHandler = function (event) { event.bubbles = true; node.dispatchEvent(event); if (CC_JSB) { - Event.EventTouch.pool.put(event); + Event.EventMouse.pool.put(event); } else { event.stopPropagation(); @@ -258,7 +258,7 @@ var _mouseMoveHandler = function (event) { // Event processed, cleanup if (CC_JSB) { - Event.EventTouch.pool.put(event); + Event.EventMouse.pool.put(event); } else { event.stopPropagation(); @@ -278,7 +278,7 @@ var _mouseUpHandler = function (event) { event.bubbles = true; node.dispatchEvent(event); if (CC_JSB) { - Event.EventTouch.pool.put(event); + Event.EventMouse.pool.put(event); } else { event.stopPropagation(); @@ -300,7 +300,7 @@ var _mouseWheelHandler = function (event) { event.bubbles = true; node.dispatchEvent(event); if (CC_JSB) { - Event.EventTouch.pool.put(event); + Event.EventMouse.pool.put(event); } else { event.stopPropagation(); From dc798caa854c9fd1e586ed033b27d42c1855f3f5 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Tue, 28 Nov 2017 16:30:01 +0800 Subject: [PATCH 053/127] bump --- cocos2d/core/components/CCComponent.js | 2 +- package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/components/CCComponent.js b/cocos2d/core/components/CCComponent.js index 7882750f55..eca392761a 100644 --- a/cocos2d/core/components/CCComponent.js +++ b/cocos2d/core/components/CCComponent.js @@ -567,7 +567,7 @@ var Component = cc.Class({ // because enabledInHierarchy is assigned after onEnable. // Actually, if not yet scheduled, resumeTarget/pauseTarget has no effect on component, // therefore there is no way to guarantee the paused state other than isTargetPaused. - var paused = scheduler.isTargetPaused(); + var paused = scheduler.isTargetPaused(this); scheduler.schedule(callback, this, interval, repeat, delay, paused); }, diff --git a/package.json b/package.json index 7b9ece30df..8f74448c04 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "cocos-creator-js", - "version": "1.6.0", + "version": "1.7.0", "description": "Cocos2d-html5 is a cross-platform 2D game engine written in Javascript, based on Cocos2d-X and licensed under MIT. It incorporates the same high level api as “Cocos2d JS-binding engine” and compatible with Cocos2d-X. It currently supports canvas and WebGL renderering.", "homepage": "http://www.cocos2d-x.org", "authors": [ From 7de9e243401ccf84099a825fc70d5475aa8e735a Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Wed, 29 Nov 2017 17:29:49 +0800 Subject: [PATCH 054/127] perfect native md5 cache to JSB for fireball/issues/6656 --- cocos2d/particle/CCParticleSystem.js | 4 +++- jsb/jsb-particle.js | 9 +++++++++ jsb/jsb-tex-sprite-frame.js | 6 ++++++ 3 files changed, 18 insertions(+), 1 deletion(-) diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js index 05c0ec39c6..6b7f2d3867 100644 --- a/cocos2d/particle/CCParticleSystem.js +++ b/cocos2d/particle/CCParticleSystem.js @@ -982,7 +982,9 @@ var ParticleSystem = cc.Class({ this._blendFunc.dst = this._dstBlendFactor; sgNode.setBlendFunc(this._blendFunc); - sgNode.texture = this._texture; + if (this._texture) { + sgNode.texture = this._texture; + } // recover sgNode properties if (!active) { diff --git a/jsb/jsb-particle.js b/jsb/jsb-particle.js index ad8440628a..77f04f70e6 100644 --- a/jsb/jsb-particle.js +++ b/jsb/jsb-particle.js @@ -82,6 +82,15 @@ function getReplacer (oldFunc, mode) { var proto = cc.ParticleSystem.prototype; +proto._initWithFile = proto.initWithFile; +proto.initWithFile = function (plistFile) { + var md5Pipe = cc.loader.md5Pipe; + if (md5Pipe) { + plistFile = md5Pipe.transformURL(plistFile); + } + this._initWithFile(plistFile); +}; + for (var mode = 0; mode < funcNames.length; mode++) { var modeFuncs = funcNames[mode]; for (var propName in modeFuncs) { diff --git a/jsb/jsb-tex-sprite-frame.js b/jsb/jsb-tex-sprite-frame.js index 8dd0938b4f..eef749b73a 100644 --- a/jsb/jsb-tex-sprite-frame.js +++ b/jsb/jsb-tex-sprite-frame.js @@ -59,6 +59,12 @@ prototype.addImage = function (url, cb, target) { cc.warn('textureCache.addImage(url) - The type of the url should be string, not Texture2D. You don\'t need to call addImage if you already have the texture object.'); url = url.url; } + + var md5Pipe = cc.loader.md5Pipe; + if (md5Pipe) { + url = md5Pipe.transformURL(url); + } + if (typeof cb === "function") { return this.addImageAsync(url, cb, target); } From 96e51fbee257d506e01e9b6d784c21c6f927752c Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Thu, 30 Nov 2017 11:19:32 +0800 Subject: [PATCH 055/127] gradually remove eventManager and inputManager for fireball/issues/6240 --- cocos2d/core/CCDirector.js | 11 +++-- cocos2d/core/CCDirectorCanvas.js | 5 +- cocos2d/core/CCDirectorWebGL.js | 5 +- cocos2d/core/CCNode.js | 49 ++++++++++---------- cocos2d/core/base-nodes/CCSGNode.js | 11 +++-- cocos2d/core/components/CCCanvas.js | 9 ++-- cocos2d/core/event-manager/CCEventManager.js | 21 ++++++--- cocos2d/core/event-manager/CCSystemEvent.js | 40 +++++++++++++--- cocos2d/core/event-manager/index.js | 17 +++++-- cocos2d/core/platform/CCInputExtension.js | 5 +- cocos2d/core/platform/CCInputManager.js | 22 +++++---- cocos2d/core/platform/CCView.js | 3 +- cocos2d/core/utils/base-node.js | 3 +- cocos2d/core/videoplayer/CCSGVideoPlayer.js | 4 +- cocos2d/core/webview/CCSGWebView.js | 4 +- 15 files changed, 136 insertions(+), 73 deletions(-) diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index c18a0cbacd..83def371a7 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -30,6 +30,7 @@ var AutoReleaseUtils = require('./load-pipeline/auto-release-utils'); var ComponentScheduler = require('./component-scheduler'); var NodeActivator = require('./node-activator'); var EventListeners = require('./event/event-listeners'); +var eventManager = require('./event-manager'); cc.g_NumberOfDraws = 0; @@ -441,8 +442,8 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ this._nodeActivator.reset(); // Disable event dispatching - if (cc.eventManager) - cc.eventManager.setEnabled(false); + if (eventManager) + eventManager.setEnabled(false); // don't release the event handlers // They are needed in case the director is run again @@ -477,8 +478,8 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ reset: function () { this.purgeDirector(); - if (cc.eventManager) - cc.eventManager.setEnabled(true); + if (eventManager) + eventManager.setEnabled(true); // Action manager if (this._actionManager){ @@ -1494,7 +1495,7 @@ cc.DisplayLinkDirector = cc.Director.extend(/** @lends cc.Director# */{ this._totalFrames++; this.emit(cc.Director.EVENT_AFTER_DRAW); - cc.eventManager.frameUpdateListeners(); + eventManager.frameUpdateListeners(); } }, diff --git a/cocos2d/core/CCDirectorCanvas.js b/cocos2d/core/CCDirectorCanvas.js index 773a612d3d..ad03c86ec8 100644 --- a/cocos2d/core/CCDirectorCanvas.js +++ b/cocos2d/core/CCDirectorCanvas.js @@ -26,6 +26,7 @@ require('./CCDirector'); require('./CCGame'); +var eventManager = require('./event-manager'); cc.game.once(cc.game.EVENT_RENDERER_INITED, function () { @@ -54,8 +55,8 @@ cc.game.once(cc.game.EVENT_RENDERER_INITED, function () { this._winSizeInPoints.width = cc._canvas.width; //this._openGLView.getDesignResolutionSize(); this._winSizeInPoints.height = cc._canvas.height; this._openGLView = openGLView || cc.view; - if (cc.eventManager) - cc.eventManager.setEnabled(true); + if (eventManager) + eventManager.setEnabled(true); }; _p.getVisibleSize = function () { diff --git a/cocos2d/core/CCDirectorWebGL.js b/cocos2d/core/CCDirectorWebGL.js index 0b9c9cc347..245f120342 100644 --- a/cocos2d/core/CCDirectorWebGL.js +++ b/cocos2d/core/CCDirectorWebGL.js @@ -27,6 +27,7 @@ require('./CCDirector'); require('./CCGame'); require('../kazmath'); +var eventManager = require('./event-manager'); var math = cc.math; @@ -164,8 +165,8 @@ cc.game.once(cc.game.EVENT_RENDERER_INITED, function () { }*/ //} - if (cc.eventManager) - cc.eventManager.setEnabled(true); + if (eventManager) + eventManager.setEnabled(true); }; _p.getVisibleSize = function () { diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index fbc77b8cfc..dd077cc3e7 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -26,6 +26,7 @@ var PrefabHelper = require('./utils/prefab-helper'); var SgHelper = require('./utils/scene-graph-helper'); +var eventManager = require('./event-manager'); var Flags = cc.Object.Flags; var Destroying = Flags.Destroying; @@ -283,7 +284,7 @@ function _searchMaskInParent (node) { function updateOrder (node) { node._parent._delaySort(); if (!CC_JSB) { - cc.eventManager._setDirtyForNode(node); + eventManager._setDirtyForNode(node); } } @@ -882,7 +883,7 @@ var Node = cc.Class({ _ccsg.Node.prototype.onEnter.call(this); if (this._entity && !this._entity._active) { ActionManagerExist && cc.director.getActionManager().pauseTarget(this); - cc.eventManager.pauseTarget(this); + eventManager.pauseTarget(this); } }; } @@ -967,7 +968,7 @@ var Node = cc.Class({ for (; i < len; i++) { sibling = siblings[i]._sgNode; sibling._arrivalOrder = i; - cc.eventManager._setDirtyForNode(sibling); + eventManager._setDirtyForNode(sibling); } cc.renderer.childrenOrderDirty = true; parent._sgNode._reorderChildDirty = true; @@ -1010,7 +1011,7 @@ var Node = cc.Class({ cc.director.__fastOff(cc.Director.EVENT_AFTER_UPDATE, this.sortAllChildren, this); } - cc.eventManager.removeListeners(this); + eventManager.removeListeners(this); if (!destroyByParent) { this._removeSgNode(); @@ -1031,7 +1032,7 @@ var Node = cc.Class({ if (active) { // activate actionManager && actionManager.resumeTarget(this); - cc.eventManager.resumeTarget(this); + eventManager.resumeTarget(this); if (this._touchListener) { var mask = this._touchListener.mask = _searchMaskInParent(this); if (this._mouseListener) { @@ -1045,7 +1046,7 @@ var Node = cc.Class({ else { // deactivate actionManager && actionManager.pauseTarget(this); - cc.eventManager.pauseTarget(this); + eventManager.pauseTarget(this); } }, @@ -1079,7 +1080,7 @@ var Node = cc.Class({ if (ActionManagerExist) { cc.director.getActionManager().pauseTarget(this); } - cc.eventManager.pauseTarget(this); + eventManager.pauseTarget(this); } var children = this._children; @@ -1140,7 +1141,7 @@ var Node = cc.Class({ if (CC_JSB) { this._touchListener.retain(); } - cc.eventManager.addListener(this._touchListener, this); + eventManager.addListener(this._touchListener, this); newAdded = true; } } @@ -1159,14 +1160,14 @@ var Node = cc.Class({ if (CC_JSB) { this._mouseListener.retain(); } - cc.eventManager.addListener(this._mouseListener, this); + eventManager.addListener(this._mouseListener, this); newAdded = true; } } if (newAdded && !this._activeInHierarchy) { cc.director.getScheduler().schedule(function () { if (!this._activeInHierarchy) { - cc.eventManager.pauseTarget(this); + eventManager.pauseTarget(this); } }, this, 0, 0, 0, false); } @@ -1231,7 +1232,7 @@ var Node = cc.Class({ * node.pauseSystemEvents(true); */ pauseSystemEvents (recursive) { - cc.eventManager.pauseTarget(this, recursive); + eventManager.pauseTarget(this, recursive); }, /** @@ -1247,7 +1248,7 @@ var Node = cc.Class({ * node.resumeSystemEvents(true); */ resumeSystemEvents (recursive) { - cc.eventManager.resumeTarget(this, recursive); + eventManager.resumeTarget(this, recursive); }, _checkTouchListeners () { @@ -1268,7 +1269,7 @@ var Node = cc.Class({ } } - cc.eventManager.removeListener(this._touchListener); + eventManager.removeListener(this._touchListener); this._touchListener = null; } }, @@ -1294,7 +1295,7 @@ var Node = cc.Class({ _currentHovered = null; } - cc.eventManager.removeListener(this._mouseListener); + eventManager.removeListener(this._mouseListener); this._mouseListener = null; } }, @@ -2321,7 +2322,7 @@ var Node = cc.Class({ // actions ActionManagerExist && cc.director.getActionManager().removeAllActionsFromTarget(this); // event - cc.eventManager.removeListeners(this); + eventManager.removeListeners(this); // children var i, len = this._children.length, node; @@ -2415,11 +2416,11 @@ var Node = cc.Class({ var actionManager = ActionManagerExist ? cc.director.getActionManager() : null; if (this._activeInHierarchy) { actionManager && actionManager.resumeTarget(this); - cc.eventManager.resumeTarget(this); + eventManager.resumeTarget(this); } else { actionManager && actionManager.pauseTarget(this); - cc.eventManager.pauseTarget(this); + eventManager.pauseTarget(this); } }, @@ -2458,11 +2459,11 @@ var Node = cc.Class({ var actionManager = cc.director.getActionManager(); if (this._activeInHierarchy) { actionManager && actionManager.resumeTarget(this); - cc.eventManager.resumeTarget(this); + eventManager.resumeTarget(this); } else { actionManager && actionManager.pauseTarget(this); - cc.eventManager.pauseTarget(this); + eventManager.pauseTarget(this); } }, @@ -2475,7 +2476,7 @@ var Node = cc.Class({ if (CC_JSB) { var updateListeners = function () { if (!this._activeInHierarchy) { - cc.eventManager.pauseTarget(this); + eventManager.pauseTarget(this); } }; @@ -2488,14 +2489,14 @@ if (CC_JSB) { if (this._touchListener || this._mouseListener) { if (this._touchListener) { this._touchListener.retain(); - cc.eventManager.removeListener(this._touchListener); - cc.eventManager.addListener(this._touchListener, this); + eventManager.removeListener(this._touchListener); + eventManager.addListener(this._touchListener, this); this._touchListener.release(); } if (this._mouseListener) { this._mouseListener.retain(); - cc.eventManager.removeListener(this._mouseListener); - cc.eventManager.addListener(this._mouseListener, this); + eventManager.removeListener(this._mouseListener); + eventManager.addListener(this._mouseListener, this); this._mouseListener.release(); } cc.director.once(cc.Director.EVENT_BEFORE_UPDATE, updateListeners, this); diff --git a/cocos2d/core/base-nodes/CCSGNode.js b/cocos2d/core/base-nodes/CCSGNode.js index 76782a42bb..452643fe77 100644 --- a/cocos2d/core/base-nodes/CCSGNode.js +++ b/cocos2d/core/base-nodes/CCSGNode.js @@ -25,6 +25,7 @@ ****************************************************************************/ var Misc = require('../utils/misc'); +var eventManager = require('../event-manager'); var ActionManagerExist = !!cc.ActionManager; var emptyFunc = function () {}; @@ -274,7 +275,7 @@ _ccsg.Node = cc.Class({ this._parent.reorderChild(this, localZOrder); else this._localZOrder = localZOrder; - cc.eventManager._setDirtyForNode(this); + eventManager._setDirtyForNode(this); }, //Helper function used by `setLocalZOrder`. Don't use it unless you know what you are doing. @@ -339,7 +340,7 @@ _ccsg.Node = cc.Class({ setGlobalZOrder: function (globalZOrder) { if (this._globalZOrder !== globalZOrder) { this._globalZOrder = globalZOrder; - cc.eventManager._setDirtyForNode(this); + eventManager._setDirtyForNode(this); } }, @@ -964,7 +965,7 @@ _ccsg.Node = cc.Class({ this.unscheduleAllCallbacks(); // event - cc.eventManager.removeListeners(this); + eventManager.removeListeners(this); }, // composition: GET @@ -1646,7 +1647,7 @@ _ccsg.Node = cc.Class({ resume: function () { this.scheduler.resumeTarget(this); ActionManagerExist && cc.director.getActionManager().resumeTarget(this); - cc.eventManager.resumeTarget(this); + eventManager.resumeTarget(this); }, /** @@ -1668,7 +1669,7 @@ _ccsg.Node = cc.Class({ pause: function () { this.scheduler.pauseTarget(this); ActionManagerExist && cc.director.getActionManager().pauseTarget(this); - cc.eventManager.pauseTarget(this); + eventManager.pauseTarget(this); }, /** diff --git a/cocos2d/core/components/CCCanvas.js b/cocos2d/core/components/CCCanvas.js index 9ac8f4d198..0f71867ec4 100644 --- a/cocos2d/core/components/CCCanvas.js +++ b/cocos2d/core/components/CCCanvas.js @@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +var eventManager = require('../event-manager'); var designResolutionWrapper = { getContentSize: function () { @@ -186,11 +187,11 @@ var Canvas = cc.Class({ window.addEventListener('resize', this._thisOnResized); } else { - cc.eventManager.addCustomListener('canvas-resize', this._thisOnResized); + eventManager.addCustomListener('canvas-resize', this._thisOnResized); } } else { - cc.eventManager.addListener(this._thisOnResized, 1); + eventManager.addListener(this._thisOnResized, 1); } this.applySettings(); @@ -212,11 +213,11 @@ var Canvas = cc.Class({ window.removeEventListener('resize', this._thisOnResized); } else { - cc.eventManager.removeCustomListeners('canvas-resize', this._thisOnResized); + eventManager.removeCustomListeners('canvas-resize', this._thisOnResized); } } else { - cc.eventManager.removeListener(this._thisOnResized); + eventManager.removeListener(this._thisOnResized); this._thisOnResized.release(); } diff --git a/cocos2d/core/event-manager/CCEventManager.js b/cocos2d/core/event-manager/CCEventManager.js index 74bd402172..91b148d2ff 100644 --- a/cocos2d/core/event-manager/CCEventManager.js +++ b/cocos2d/core/event-manager/CCEventManager.js @@ -22,6 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +var js = require('../platform/js'); var _EventListenerVector = cc._Class.extend({ @@ -84,7 +85,7 @@ var __getListenerID = function (event) { return ""; }; -/** +/* * !#en *

* cc.eventManager is a singleton object which manages event listener subscriptions and event dispatching.
@@ -101,7 +102,7 @@ var __getListenerID = function (event) { * @static * @example {@link utils/api/engine/docs/cocos2d/core/event-manager/CCEventManager/addListener.js} */ -cc.eventManager = { +var eventManager = { //Priority dirty flag DIRTY_NONE: 0, DIRTY_FIXED_PRIORITY: 1 << 0, @@ -323,7 +324,7 @@ cc.eventManager = { }, _sortEventListenersOfSceneGraphPriorityDes: function (l1, l2) { - var locNodePriorityMap = cc.eventManager._nodePriorityMap, + var locNodePriorityMap = eventManager._nodePriorityMap, node1 = l1._getSceneGraphPriority(), node2 = l2._getSceneGraphPriority(); if (!l2 || !node2 || !locNodePriorityMap[node2.__instanceId]) @@ -514,7 +515,7 @@ cc.eventManager = { // If the event was stopped, return directly. if (event.isStopped()) { - cc.eventManager._updateTouchListeners(event); + eventManager._updateTouchListeners(event); return true; } @@ -581,7 +582,7 @@ cc.eventManager = { // If the event was stopped, return directly. if (event.isStopped()) { - cc.eventManager._updateTouchListeners(event); + eventManager._updateTouchListeners(event); return true; } return false; @@ -818,7 +819,7 @@ cc.eventManager = { isFound = this._removeListenerInVector(sceneGraphPriorityListeners, listener); if (isFound){ // fixed #4160: Dirty flag need to be updated after listeners were removed. - this._setDirty(listener._getListenerID(), this.DIRTY_SCENE_GRAPH_PRIORITY); + this._setDirty(listener._getListenerID(), this.DIRTY_SCENE_GRAPH_PRIORITY); }else{ isFound = this._removeListenerInVector(fixedPriorityListeners, listener); if (isFound) @@ -1090,3 +1091,11 @@ cc.eventManager = { this.dispatchEvent(ev); } }; + + +js.get(cc, 'eventManager', function () { + cc.warnID(1405, 'cc.eventManager', 'cc.EventTarget or cc.systemEvent'); + return eventManager; +}); + +module.exports = eventManager; diff --git a/cocos2d/core/event-manager/CCSystemEvent.js b/cocos2d/core/event-manager/CCSystemEvent.js index 4f00ba1218..e2301fae37 100644 --- a/cocos2d/core/event-manager/CCSystemEvent.js +++ b/cocos2d/core/event-manager/CCSystemEvent.js @@ -24,6 +24,14 @@ ****************************************************************************/ var EventTarget = require('../event/event-target'); +var eventManager = require('../event-manager'); +var inputManger; +if (CC_JSB) { + inputManger = cc.inputManager; +} +else { + inputManger = require('../platform/CCInputManager'); +} /** * !#en The event type supported by SystemEvent @@ -78,6 +86,26 @@ var SystemEvent = cc.Class({ EventType: EventType }, + /** + * !#en whether enable accelerometer event + * !#zh 是否启用加速度计事件 + * @method setAccelerometerEnabled + * @param {Boolean} isEnable + */ + setAccelerometerEnabled: function (isEnable) { + inputManger.setAccelerometerEnabled(isEnable); + }, + + /** + * !#en set accelerometer interval value + * !#zh 设置加速度计间隔值 + * @method setAccelerometerInterval + * @param {Number} interval + */ + setAccelerometerInterval: function(interval) { + inputManger.setAccelerometerInterval(interval); + }, + on: function (type, callback, target, useCapture) { this._super(type, callback, target, useCapture); @@ -104,10 +132,10 @@ var SystemEvent = cc.Class({ } }); } - if (!cc.eventManager.hasEventListener(cc._EventListenerKeyboard.LISTENER_ID)) { + if (!eventManager.hasEventListener(cc._EventListenerKeyboard.LISTENER_ID)) { var currentFrame = cc.director.getTotalFrames(); if (currentFrame !== keyboardListenerAddFrame) { - cc.eventManager.addListener(keyboardListener, 1); + eventManager.addListener(keyboardListener, 1); keyboardListenerAddFrame = currentFrame; } } @@ -127,8 +155,8 @@ var SystemEvent = cc.Class({ } }); } - if (!cc.eventManager.hasEventListener(cc._EventListenerAcceleration.LISTENER_ID)) { - cc.eventManager.addListener(accelerationListener, 1); + if (!eventManager.hasEventListener(cc._EventListenerAcceleration.LISTENER_ID)) { + eventManager.addListener(accelerationListener, 1); } } }, @@ -142,13 +170,13 @@ var SystemEvent = cc.Class({ var hasKeyDownEventListener = this.hasEventListener(EventType.KEY_DOWN); var hasKeyUpEventListener = this.hasEventListener(EventType.KEY_UP); if (!hasKeyDownEventListener && !hasKeyUpEventListener) { - cc.eventManager.removeListener(keyboardListener); + eventManager.removeListener(keyboardListener); } } // Acceleration if (accelerationListener && type === EventType.DEVICEMOTION) { - cc.eventManager.removeListener(accelerationListener); + eventManager.removeListener(accelerationListener); } } diff --git a/cocos2d/core/event-manager/index.js b/cocos2d/core/event-manager/index.js index 1777126e01..cae4b0390a 100644 --- a/cocos2d/core/event-manager/index.js +++ b/cocos2d/core/event-manager/index.js @@ -22,9 +22,18 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - -require('./CCTouch'); -require('./CCEventListener'); -require('./CCEventManager'); + +var eventManager; +if (CC_JSB) { + eventManager = cc.eventManager; +} +else { + require('./CCTouch'); + require('./CCEventListener'); + eventManager = require('./CCEventManager'); +} +module.exports = eventManager; + require('./CCEvent'); require('./CCSystemEvent'); + diff --git a/cocos2d/core/platform/CCInputExtension.js b/cocos2d/core/platform/CCInputExtension.js index 155c195dff..9f4a1c76fc 100644 --- a/cocos2d/core/platform/CCInputExtension.js +++ b/cocos2d/core/platform/CCInputExtension.js @@ -27,6 +27,7 @@ if (!cc.ClassManager) { require("./_CCClass"); } +var eventManager = require('../event-manager'); var inputManager = require("./CCInputManager"); inputManager.__instanceId = cc.ClassManager.getNewInstanceId(); @@ -65,12 +66,12 @@ inputManager.setAccelerometerInterval = function(interval){ inputManager._registerKeyboardEvent = function(){ cc.game.canvas.addEventListener("keydown", function (e) { - cc.eventManager.dispatchEvent(new cc.Event.EventKeyboard(e.keyCode, true)); + eventManager.dispatchEvent(new cc.Event.EventKeyboard(e.keyCode, true)); e.stopPropagation(); e.preventDefault(); }, false); cc.game.canvas.addEventListener("keyup", function (e) { - cc.eventManager.dispatchEvent(new cc.Event.EventKeyboard(e.keyCode, false)); + eventManager.dispatchEvent(new cc.Event.EventKeyboard(e.keyCode, false)); e.stopPropagation(); e.preventDefault(); }, false); diff --git a/cocos2d/core/platform/CCInputManager.js b/cocos2d/core/platform/CCInputManager.js index fea9a16b73..f00abb8db1 100644 --- a/cocos2d/core/platform/CCInputManager.js +++ b/cocos2d/core/platform/CCInputManager.js @@ -23,7 +23,9 @@ THE SOFTWARE. ****************************************************************************/ +var js = require('../platform/js'); var macro = require('./CCMacro'); +var eventManager = require('../event-manager'); var TOUCH_TIMEOUT = macro.TOUCH_TIMEOUT; @@ -120,7 +122,7 @@ var inputManager = { this._glView._convertTouchesWithScale(handleTouches); var touchEvent = new cc.Event.EventTouch(handleTouches); touchEvent._eventCode = cc.Event.EventTouch.BEGAN; - cc.eventManager.dispatchEvent(touchEvent); + eventManager.dispatchEvent(touchEvent); } }, @@ -152,7 +154,7 @@ var inputManager = { this._glView._convertTouchesWithScale(handleTouches); var touchEvent = new cc.Event.EventTouch(handleTouches); touchEvent._eventCode = cc.Event.EventTouch.MOVED; - cc.eventManager.dispatchEvent(touchEvent); + eventManager.dispatchEvent(touchEvent); } }, @@ -166,7 +168,7 @@ var inputManager = { this._glView._convertTouchesWithScale(handleTouches); var touchEvent = new cc.Event.EventTouch(handleTouches); touchEvent._eventCode = cc.Event.EventTouch.ENDED; - cc.eventManager.dispatchEvent(touchEvent); + eventManager.dispatchEvent(touchEvent); } }, @@ -180,7 +182,7 @@ var inputManager = { this._glView._convertTouchesWithScale(handleTouches); var touchEvent = new cc.Event.EventTouch(handleTouches); touchEvent._eventCode = cc.Event.EventTouch.CANCELLED; - cc.eventManager.dispatchEvent(touchEvent); + eventManager.dispatchEvent(touchEvent); } }, @@ -419,7 +421,7 @@ var inputManager = { var mouseEvent = selfPointer.getMouseEvent(location,pos,cc.Event.EventMouse.UP); mouseEvent.setButton(event.button); - cc.eventManager.dispatchEvent(mouseEvent); + eventManager.dispatchEvent(mouseEvent); } }, false); } @@ -464,7 +466,7 @@ var inputManager = { handler(event, mouseEvent, location, pos); - cc.eventManager.dispatchEvent(mouseEvent); + eventManager.dispatchEvent(mouseEvent); event.stopPropagation(); event.preventDefault(); }, false); @@ -549,11 +551,15 @@ var inputManager = { update:function(dt){ if(this._accelCurTime > this._accelInterval){ this._accelCurTime -= this._accelInterval; - cc.eventManager.dispatchEvent(new cc.Event.EventAcceleration(this._acceleration)); + eventManager.dispatchEvent(new cc.Event.EventAcceleration(this._acceleration)); } this._accelCurTime += dt; } }; -cc.inputManager = inputManager; +js.get(cc, 'inputManager', function () { + cc.warnID(1405, 'cc.inputManager', 'cc.systemEvent'); + return inputManager; +}); + module.exports = inputManager; diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index 7133a3b434..4dbe7df653 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -23,6 +23,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ +var eventManager = require('../event-manager'); var __BrowserGetter = { init: function(){ @@ -206,7 +207,7 @@ var View = cc._Class.extend({ view.setDesignResolutionSize(width, height, view._resolutionPolicy); view._resizing = false; - cc.eventManager.dispatchCustomEvent('canvas-resize'); + eventManager.dispatchCustomEvent('canvas-resize'); if (view._resizeCallback) { view._resizeCallback.call(); } diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js index d60fffff61..18bede714f 100644 --- a/cocos2d/core/utils/base-node.js +++ b/cocos2d/core/utils/base-node.js @@ -26,6 +26,7 @@ var Flags = require('../platform/CCObject').Flags; var Misc = require('./misc'); var IdGenerater = require('../platform/id-generater'); +var eventManager = require('../event-manager'); var JS = cc.js; var Destroying = Flags.Destroying; @@ -365,7 +366,7 @@ var BaseNode = cc.Class({ if (value) { if (!CC_JSB) { - cc.eventManager._setDirtyForNode(this); + eventManager._setDirtyForNode(this); } value._children.push(this); value.emit(CHILD_ADDED, this); diff --git a/cocos2d/core/videoplayer/CCSGVideoPlayer.js b/cocos2d/core/videoplayer/CCSGVideoPlayer.js index d770e74b87..2874863a61 100644 --- a/cocos2d/core/videoplayer/CCSGVideoPlayer.js +++ b/cocos2d/core/videoplayer/CCSGVideoPlayer.js @@ -20,6 +20,8 @@ ****************************************************************************/ var Utils = require('../platform/utils'); +var eventManager = require('../event-manager'); + /** * @class * @extends _ccsg.Node @@ -170,7 +172,7 @@ _ccsg.VideoPlayer.elements = []; // video 在 game_hide 事件中被自动暂停的队列,用于回复的时候重新开始播放 _ccsg.VideoPlayer.pauseElements = []; -cc.eventManager.addCustomListener(cc.game.EVENT_HIDE, function () { +eventManager.addCustomListener(cc.game.EVENT_HIDE, function () { var list = _ccsg.VideoPlayer.elements; for(var node, i=0; i Date: Thu, 30 Nov 2017 11:31:48 +0800 Subject: [PATCH 056/127] refine code --- cocos2d/core/event-manager/index.js | 7 +++---- cocos2d/core/predefine.js | 1 + 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/event-manager/index.js b/cocos2d/core/event-manager/index.js index cae4b0390a..1f56749caa 100644 --- a/cocos2d/core/event-manager/index.js +++ b/cocos2d/core/event-manager/index.js @@ -23,6 +23,8 @@ THE SOFTWARE. ****************************************************************************/ +require('./CCEvent'); + var eventManager; if (CC_JSB) { eventManager = cc.eventManager; @@ -32,8 +34,5 @@ else { require('./CCEventListener'); eventManager = require('./CCEventManager'); } + module.exports = eventManager; - -require('./CCEvent'); -require('./CCSystemEvent'); - diff --git a/cocos2d/core/predefine.js b/cocos2d/core/predefine.js index 06adc9bb9f..8137142619 100644 --- a/cocos2d/core/predefine.js +++ b/cocos2d/core/predefine.js @@ -44,5 +44,6 @@ if (!(CC_EDITOR && Editor.isMainProcess)) { require('./platform/CCScreen'); require('./CCScheduler'); require('./event-manager'); + require('./event-manager/CCSystemEvent'); require('./renderer'); } From c2dd872f5cd6ec5cca1dc3866dfd8b64554b48ca Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Thu, 30 Nov 2017 11:43:34 +0800 Subject: [PATCH 057/127] refine code --- cocos2d/core/event/index.js | 3 ++- .../{event-manager/CCSystemEvent.js => event/system-event.js} | 0 cocos2d/core/predefine.js | 1 - jsb/index.js | 1 - 4 files changed, 2 insertions(+), 3 deletions(-) rename cocos2d/core/{event-manager/CCSystemEvent.js => event/system-event.js} (100%) diff --git a/cocos2d/core/event/index.js b/cocos2d/core/event/index.js index f275852a85..1c946a8fef 100644 --- a/cocos2d/core/event/index.js +++ b/cocos2d/core/event/index.js @@ -25,4 +25,5 @@ require('./event'); require('./event-listeners'); -require('./event-target'); \ No newline at end of file +require('./event-target'); +require('./system-event'); diff --git a/cocos2d/core/event-manager/CCSystemEvent.js b/cocos2d/core/event/system-event.js similarity index 100% rename from cocos2d/core/event-manager/CCSystemEvent.js rename to cocos2d/core/event/system-event.js diff --git a/cocos2d/core/predefine.js b/cocos2d/core/predefine.js index 8137142619..06adc9bb9f 100644 --- a/cocos2d/core/predefine.js +++ b/cocos2d/core/predefine.js @@ -44,6 +44,5 @@ if (!(CC_EDITOR && Editor.isMainProcess)) { require('./platform/CCScreen'); require('./CCScheduler'); require('./event-manager'); - require('./event-manager/CCSystemEvent'); require('./renderer'); } diff --git a/jsb/index.js b/jsb/index.js index df61f5f14d..81cd0bf33e 100644 --- a/jsb/index.js +++ b/jsb/index.js @@ -76,7 +76,6 @@ require('../cocos2d/core/utils/find'); require('../cocos2d/core/utils/mutable-forward-iterator'); require('../cocos2d/core/event'); require('../cocos2d/core/event-manager/CCEvent'); -require('../cocos2d/core/event-manager/CCSystemEvent'); require('../CCDebugger'); if (CC_DEBUG) { From e8b6d937d2f807871865b3c7e19ec1140ff96c45 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Thu, 30 Nov 2017 14:08:54 +0800 Subject: [PATCH 058/127] fix layout child node change in sequence, not update bug --- cocos2d/core/CCDirector.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index c18a0cbacd..8429d6be1b 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -1524,12 +1524,14 @@ cc.DisplayLinkDirector = cc.Director.extend(/** @lends cc.Director# */{ listeners = this._bubblingListeners = new EventListeners(); } listeners.add(type, callback, target); + this._addEventFlag(type, listeners, false); }, __fastOff: function (type, callback, target) { var listeners = this._bubblingListeners; if (listeners) { listeners.remove(type, callback, target); + this._purgeEventFlag(type, listeners, false); } }, }); From 5d394c5ce627863e12eaf49c026bb823db61191b Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Thu, 30 Nov 2017 16:52:54 +0800 Subject: [PATCH 059/127] fix Persist Root Node set local Z Order invalid --- cocos2d/core/CCNode.js | 4 ++++ jsb/jsb-director.js | 2 ++ 2 files changed, 6 insertions(+) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index c50ab0af36..67f446cb95 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -1001,7 +1001,11 @@ var Node = cc.Class({ parent._sgNode.removeChild(this._sgNode, false); if (index + 1 < siblings.length) { var nextSibling = siblings[index + 1]; + var oldZOrder = this._sgNode.getLocalZOrder(); parent._sgNode.insertChildBefore(this._sgNode, nextSibling._sgNode); + if (oldZOrder !== this._sgNode.getLocalZOrder()) { + this._sgNode.setLocalZOrder(oldZOrder); + } } else { parent._sgNode.addChild(this._sgNode); diff --git a/jsb/jsb-director.js b/jsb/jsb-director.js index b26870e0f9..36a33cbd77 100644 --- a/jsb/jsb-director.js +++ b/jsb/jsb-director.js @@ -457,12 +457,14 @@ cc.js.mixin(cc.director, { listeners = this._bubblingListeners = new EventListeners(); } listeners.add(type, callback, target); + this._addEventFlag(type, listeners, false); }, __fastOff: function (type, callback, target) { var listeners = this._bubblingListeners; if (listeners) { listeners.remove(type, callback, target); + this._purgeEventFlag(type, listeners, false); } }, }); From 39c454d6bffa2e287640ad55c1bc5dbe87b99171 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Thu, 30 Nov 2017 17:08:23 +0800 Subject: [PATCH 060/127] Set preserveDrawingBuffer only for wechat game environment --- cocos2d/core/CCGame.js | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index 8186d761eb..c740e7735c 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -698,13 +698,16 @@ var game = { } if (cc._renderType === game.RENDER_TYPE_WEBGL) { - this._renderContext = cc._renderContext = cc.webglContext - = cc.create3DContext(localCanvas, { + var opts = { 'stencil': true, 'alpha': cc.macro.ENABLE_TRANSPARENT_CANVAS, 'antialias': cc.macro.ENABLE_WEBGL_ANTIALIAS - 'preserveDrawingBuffer': isWeChatGame - }); + }; + if (isWeChatGame) { + opts['preserveDrawingBuffer'] = true; + } + this._renderContext = cc._renderContext = cc.webglContext + = cc.create3DContext(localCanvas, opts); } // WebGL context created successfully if (this._renderContext) { From 1f7bf44b259b9015c39f988ebf22fdb8434a14e5 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Thu, 30 Nov 2017 17:13:46 +0800 Subject: [PATCH 061/127] add VideoPlayer EventType api --- cocos2d/core/components/CCVideoPlayer.js | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/cocos2d/core/components/CCVideoPlayer.js b/cocos2d/core/components/CCVideoPlayer.js index 8c341f5997..a47007d4b9 100644 --- a/cocos2d/core/components/CCVideoPlayer.js +++ b/cocos2d/core/components/CCVideoPlayer.js @@ -46,6 +46,21 @@ require('../videoplayer/CCSGVideoPlayer'); * !#zh 播放结束 * @property {Number} COMPLETED */ +/** + * !#en meta data is loaded + * !#zh 视频的元信息已加载完成,你可以调用 getDuration 来获取视频总时长 + * @property {Number} META_LOADED + */ +/** + * !#en clicked by the user + * !#zh 视频被用户点击了 + * @property {Number} CLICKED + */ +/** + * !#en ready to play + * !#zh 视频准备好了,可以开始播放了 + * @property {Number} READY_TO_PLAY + */ var EventType = _ccsg.VideoPlayer.EventType; From 1d6bdc5c3612515bcab900c485c8c9d9ff8803fa Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Mon, 4 Dec 2017 16:19:21 +0800 Subject: [PATCH 062/127] fix label warp bug for cocos-creator/engine/issues/2151 --- cocos2d/core/label/CCTextUtils.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/label/CCTextUtils.js b/cocos2d/core/label/CCTextUtils.js index 1253f43ce7..26c1621340 100644 --- a/cocos2d/core/label/CCTextUtils.js +++ b/cocos2d/core/label/CCTextUtils.js @@ -296,12 +296,14 @@ var TextUtils = { sText = text.substr(0, fuzzyLen); } } - if (sText.trim().length > 0) { + sText = sText.trim(); + if (sText.length > 0) { wrappedWords.push(sText); } text = sLine || tmpText; allWidth = measureText(text); } + text = text.trim(); if (text.length > 0) { wrappedWords.push(text); } From 785adc5cfd97a25ba973e847fcfe2a1697a5ed52 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Tue, 5 Dec 2017 11:09:06 +0800 Subject: [PATCH 063/127] fix ToggleContainer allowSwitchOff invalid for fireball/issues/6702 --- cocos2d/core/components/CCToggleContainer.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/components/CCToggleContainer.js b/cocos2d/core/components/CCToggleContainer.js index 230b089404..601a94f992 100644 --- a/cocos2d/core/components/CCToggleContainer.js +++ b/cocos2d/core/components/CCToggleContainer.js @@ -58,7 +58,9 @@ var ToggleContainer = cc.Class({ updateToggles: function (toggle) { this.toggleItems.forEach(function (item) { - item.isChecked = (item === toggle); + if (toggle.isChecked && item !== toggle) { + item.isChecked = false; + } }); }, From 6607f4de945f69ad68ff3bd7015cef75ce37be82 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Tue, 5 Dec 2017 14:29:39 +0800 Subject: [PATCH 064/127] fix label warp bug for cocos-creator/engine/issues/2151 --- cocos2d/core/label/CCTextUtils.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/label/CCTextUtils.js b/cocos2d/core/label/CCTextUtils.js index 26c1621340..0a698e0058 100644 --- a/cocos2d/core/label/CCTextUtils.js +++ b/cocos2d/core/label/CCTextUtils.js @@ -204,10 +204,10 @@ var CustomFontLoader = { var TextUtils = { label_wordRex : /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûа-яА-ЯЁё]+|\S)/, - label_symbolRex : /^[!,.:;}\]%\?>、‘“》?。,!]/, + label_symbolRex : /^[!,.:;'}\]%\?>、‘“》?。,!]/, label_lastWordRex : /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁё]+|\S)$/, label_lastEnglish : /[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁё]+$/, - label_firsrEnglish : /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁё]/, + label_firstEnglish : /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁё]/, label_wrapinspection : true, isUnicodeCJK: function(ch) { @@ -288,7 +288,7 @@ var TextUtils = { } //To judge whether a English words are truncated - if (this.label_firsrEnglish.test(sLine)) { + if (this.label_firstEnglish.test(sLine)) { result = this.label_lastEnglish.exec(sText); if (result && sText !== result[0]) { fuzzyLen -= result[0].length; From 05f65853d21c54c238495aed0bfd267ceaf2ad85 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Tue, 5 Dec 2017 15:35:47 +0800 Subject: [PATCH 065/127] fix EditBox bug for fireball/issues/6705 --- cocos2d/core/editbox/CCSGEditBox.js | 57 +++++++++++++++++++++++------ 1 file changed, 46 insertions(+), 11 deletions(-) diff --git a/cocos2d/core/editbox/CCSGEditBox.js b/cocos2d/core/editbox/CCSGEditBox.js index 1dd914b28f..b9fb87076b 100644 --- a/cocos2d/core/editbox/CCSGEditBox.js +++ b/cocos2d/core/editbox/CCSGEditBox.js @@ -693,22 +693,40 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; tmpEdTxt.style['-moz-appearance'] = 'textfield'; tmpEdTxt.style.className = "cocosEditBox"; - tmpEdTxt.addEventListener('input', function () { + + function _inputValueHandle (target) { var editBox = thisPointer._editBox; - - if (this.value.length > this.maxLength) { - this.value = this.value.slice(0, this.maxLength); + if (target.value.length > target.maxLength) { + target.value = target.value.slice(0, target.maxLength); } if (editBox._delegate && editBox._delegate.editBoxTextChanged) { - if (editBox._text !== this.value) { - editBox._text = this.value; + if (editBox._text !== target.value) { + editBox._text = target.value; thisPointer._updateDomTextCases(); editBox._delegate.editBoxTextChanged(editBox, editBox._text); } } + } + + var inputLock = false; + tmpEdTxt.addEventListener('compositionstart', function () { + inputLock = true; }); + + tmpEdTxt.addEventListener('compositionend', function () { + inputLock = false; + _inputValueHandle(this); + }); + + tmpEdTxt.addEventListener('input', function () { + if (inputLock) { + return; + } + _inputValueHandle(this); + }); + tmpEdTxt.addEventListener('keypress', function (e) { var editBox = thisPointer._editBox; @@ -790,19 +808,36 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType; tmpEdTxt.style.left = LEFT_PADDING + "px"; tmpEdTxt.style.className = "cocosEditBox"; - tmpEdTxt.addEventListener('input', function () { - if (this.value.length > this.maxLength) { - this.value = this.value.slice(0, this.maxLength); + function _inputValueHandle (target) { + if (target.value.length > target.maxLength) { + target.value = target.value.slice(0, target.maxLength); } var editBox = thisPointer._editBox; if (editBox._delegate && editBox._delegate.editBoxTextChanged) { - if(editBox._text.toLowerCase() !== this.value.toLowerCase()) { - editBox._text = this.value; + if(editBox._text.toLowerCase() !== target.value.toLowerCase()) { + editBox._text = target.value; thisPointer._updateDomTextCases(); editBox._delegate.editBoxTextChanged(editBox, editBox._text); } } + } + + var inputLock = false; + tmpEdTxt.addEventListener('compositionstart', function () { + inputLock = true; + }); + + tmpEdTxt.addEventListener('compositionend', function () { + inputLock = false; + _inputValueHandle(this); + }); + + tmpEdTxt.addEventListener('input', function () { + if (inputLock) { + return; + } + _inputValueHandle(this); }); tmpEdTxt.addEventListener('focus', function () { From c47aff321dc87103fed61b2c345598f7c8f45c57 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Wed, 6 Dec 2017 09:26:14 +0800 Subject: [PATCH 066/127] fix CCAudioEngine api --- cocos2d/audio/CCAudioEngine.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/audio/CCAudioEngine.js b/cocos2d/audio/CCAudioEngine.js index 3dd6f0c986..8ed026746f 100644 --- a/cocos2d/audio/CCAudioEngine.js +++ b/cocos2d/audio/CCAudioEngine.js @@ -321,7 +321,7 @@ var audioEngine = { * !#zh 恢复播放指定的音频。 * @method resume * @param {Number} audioID - The return value of function play. - * //example + * @example * cc.audioEngine.resume(audioID); */ resume: function (audioID) { From bf6f79c17569e29996024d029f66cd07c06b78d8 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Wed, 6 Dec 2017 17:58:03 +0800 Subject: [PATCH 067/127] fix CCTilemap bug for cocos-creator/engine/issues/2046 --- cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js index 64de43bcc5..fa60ed27ef 100644 --- a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js @@ -67,14 +67,15 @@ var proto = _ccsg.TMXLayer.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.W proto.constructor = _ccsg.TMXLayer.WebGLRenderCmd; proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset) { - // enable Depth Test - cc.renderer.setDepthTest(true); - var node = this._node, layerOrientation = node.layerOrientation, tiles = node.tiles, alpha = node._opacity / 255; + // enable Depth Test (fix cocos-creator/engine/issues/2046, + // but it's not perfect, and the follow-up needs to be improved) + cc.renderer.setDepthTest(node.layerOrientation === Orientation.ORTHO); + if (!tiles || alpha <= 0 || !node.tileset) { return 0; } From fff343f63400be66c172b83b6dfd7f9fbbad9e4e Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 8 Dec 2017 14:29:03 +0800 Subject: [PATCH 068/127] Remove antialias config due to performance dropdown --- cocos2d/core/CCGame.js | 3 +-- cocos2d/core/platform/CCMacro.js | 16 ---------------- 2 files changed, 1 insertion(+), 18 deletions(-) diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index 39910567d2..c28aa3dce0 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -692,8 +692,7 @@ var game = { this._renderContext = cc._renderContext = cc.webglContext = cc.create3DContext(localCanvas, { 'stencil': true, - 'alpha': cc.macro.ENABLE_TRANSPARENT_CANVAS, - 'antialias': cc.macro.ENABLE_WEBGL_ANTIALIAS + 'alpha': cc.macro.ENABLE_TRANSPARENT_CANVAS }); } // WebGL context created successfully diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js index ecedc15121..cec60923da 100644 --- a/cocos2d/core/platform/CCMacro.js +++ b/cocos2d/core/platform/CCMacro.js @@ -1915,22 +1915,6 @@ cc.macro = { * @default false */ ENABLE_TRANSPARENT_CANVAS: false, - - /** - * !#en - * Boolean that indicates if the WebGL context is created with `antialias` option turned on, - * default value is true, most game need it for the picture to eliminate the hard edges, - * but in some case, if you are trying to apply pixel art or using tilemaps, then you may need to turn it off. - * You can set it to false before `cc.game.run`. - * Web only. - * !#zh - * 用于设置在创建 WebGL Context 时是否开启 `antialias` 选项,默认值是 true,大多数游戏都更适合这样的效果, - * 但是如果你需要实现像素风格,或是使用 Tiledmap,那么你可能需要手动设置这个值为 false,你可以在 `cc.game.run` 之前设置这个值,否则它不会生效。 - * 仅支持 Web - * @property {Boolean} ENABLE_WEBGL_ANTIALIAS - * @default true - */ - ENABLE_WEBGL_ANTIALIAS: true }; /** From f31830e5743c0789e30e55eb22a31a27096c4607 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Sat, 25 Nov 2017 16:31:32 +0800 Subject: [PATCH 069/127] fix api --- cocos2d/core/platform/CCClass.js | 2 +- cocos2d/core/platform/js.js | 4 ++-- cocos2d/core/sprites/CCSpriteFrame.js | 4 ++-- cocos2d/core/textures/CCTextureCache.js | 4 ++-- 4 files changed, 7 insertions(+), 7 deletions(-) diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 1f7d159a96..5378010097 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -832,7 +832,7 @@ function declareProperties (cls, className, properties, baseClass, mixins, es6) * @param {String} [options.name] - The class name used for serialization. * @param {Function} [options.extends] - The base class. * @param {Function} [options.ctor] - The constructor. - * @param {Function} [options.__ctor__] - The same as ctor, but less encapsulated. + * @param {Function} [options.__ctor__] - The same as ctor, but less encapsulated. * @param {Object} [options.properties] - The property definitions. * @param {Object} [options.statics] - The static members. * @param {Function[]} [options.mixins] diff --git a/cocos2d/core/platform/js.js b/cocos2d/core/platform/js.js index 19f69cbaab..3c99593e6f 100644 --- a/cocos2d/core/platform/js.js +++ b/cocos2d/core/platform/js.js @@ -621,9 +621,9 @@ js.shiftArguments = function () { }; /** - * #en + * !#en * A simple wrapper of `Object.create(null)` which ensures the return object have no prototype (and thus no inherited members). So we can skip `hasOwnProperty` calls on property lookups. It is a worthwhile optimization than the `{}` literal when `hasOwnProperty` calls are necessary. - * #zh + * !#zh * 该方法是对 `Object.create(null)` 的简单封装。`Object.create(null)` 用于创建无 prototype (也就无继承)的空对象。这样我们在该对象上查找属性时,就不用进行 `hasOwnProperty` 判断。在需要频繁判断 `hasOwnProperty` 时,使用这个方法性能会比 `{}` 更高。 * * @method createMap diff --git a/cocos2d/core/sprites/CCSpriteFrame.js b/cocos2d/core/sprites/CCSpriteFrame.js index 81064582e2..c7d71e0d7d 100644 --- a/cocos2d/core/sprites/CCSpriteFrame.js +++ b/cocos2d/core/sprites/CCSpriteFrame.js @@ -355,8 +355,8 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ }, /** - * #en Set SpriteFrame with Texture, rect, rotated, offset and originalSize.
- * #zh 通过 Texture,rect,rotated,offset 和 originalSize 设置 SpriteFrame + * !#en Set SpriteFrame with Texture, rect, rotated, offset and originalSize.
+ * !#zh 通过 Texture,rect,rotated,offset 和 originalSize 设置 SpriteFrame * @method setTexture * @param {String|Texture2D} textureOrTextureFile * @param {Rect} [rect=null] diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js index 517ea2a159..6b80f6d7a5 100644 --- a/cocos2d/core/textures/CCTextureCache.js +++ b/cocos2d/core/textures/CCTextureCache.js @@ -112,8 +112,8 @@ var textureCache = /** @lends cc.textureCache# */{ }, /** - * #en get all textures - * #zh 获取所有贴图 + * !#en get all textures + * !#zh 获取所有贴图 * @method getAllTextures * @return {Texture2D[]} */ From 49dc28b459b888f2de91e6652d189b004fdee393 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sun, 10 Dec 2017 22:33:05 +0800 Subject: [PATCH 070/127] Remove antialias option in gl init --- cocos2d/core/CCGame.js | 3 +-- cocos2d/core/platform/CCMacro.js | 18 +----------------- 2 files changed, 2 insertions(+), 19 deletions(-) diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index c740e7735c..64af425c48 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -700,8 +700,7 @@ var game = { if (cc._renderType === game.RENDER_TYPE_WEBGL) { var opts = { 'stencil': true, - 'alpha': cc.macro.ENABLE_TRANSPARENT_CANVAS, - 'antialias': cc.macro.ENABLE_WEBGL_ANTIALIAS + 'alpha': cc.macro.ENABLE_TRANSPARENT_CANVAS }; if (isWeChatGame) { opts['preserveDrawingBuffer'] = true; diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js index ecedc15121..91b7c0221d 100644 --- a/cocos2d/core/platform/CCMacro.js +++ b/cocos2d/core/platform/CCMacro.js @@ -1914,23 +1914,7 @@ cc.macro = { * @property {Boolean} ENABLE_TRANSPARENT_CANVAS * @default false */ - ENABLE_TRANSPARENT_CANVAS: false, - - /** - * !#en - * Boolean that indicates if the WebGL context is created with `antialias` option turned on, - * default value is true, most game need it for the picture to eliminate the hard edges, - * but in some case, if you are trying to apply pixel art or using tilemaps, then you may need to turn it off. - * You can set it to false before `cc.game.run`. - * Web only. - * !#zh - * 用于设置在创建 WebGL Context 时是否开启 `antialias` 选项,默认值是 true,大多数游戏都更适合这样的效果, - * 但是如果你需要实现像素风格,或是使用 Tiledmap,那么你可能需要手动设置这个值为 false,你可以在 `cc.game.run` 之前设置这个值,否则它不会生效。 - * 仅支持 Web - * @property {Boolean} ENABLE_WEBGL_ANTIALIAS - * @default true - */ - ENABLE_WEBGL_ANTIALIAS: true + ENABLE_TRANSPARENT_CANVAS: false }; /** From c374c97567a6e6674aca0576a76748b83caa7866 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sun, 10 Dec 2017 22:33:34 +0800 Subject: [PATCH 071/127] Improve game EVENT_SHOW & EVENT_HIDE doc --- cocos2d/core/CCGame.js | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index 64af425c48..02535924b3 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -41,8 +41,12 @@ var inputManager = require('./platform/CCInputManager'); var game = { /** - * Event triggered when game hide to background. - * Please note that this event is not 100% guaranteed to be fired. + * !#en Event triggered when game hide to background. + * Please note that this event is not 100% guaranteed to be fired on Web platform, + * on native platforms, it corresponds to enter background event, os status bar or notification center may not trigger this event. + * !#zh 游戏进入后台时触发的事件。 + * 请注意,在 WEB 平台,这个事件不一定会 100% 触发,这完全取决于浏览器的回调行为。 + * 在原生平台,它对应的是应用被切换到后台事件,下拉菜单和上拉状态栏等不一定会触发这个事件,这取决于系统行为。 * @property EVENT_HIDE * @type {String} * @example @@ -55,7 +59,11 @@ var game = { /** * Event triggered when game back to foreground - * Please note that this event is not 100% guaranteed to be fired. + * Please note that this event is not 100% guaranteed to be fired on Web platform, + * on native platforms, it corresponds to enter foreground event. + * !#zh 游戏进入前台运行时触发的事件。 + * 请注意,在 WEB 平台,这个事件不一定会 100% 触发,这完全取决于浏览器的回调行为。 + * 在原生平台,它对应的是应用被切换到前台事件。 * @property EVENT_SHOW * @type {String} */ From f0b6fa6e77bb38b9414de0b30b98d81191128711 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 11 Dec 2017 19:16:39 +0800 Subject: [PATCH 072/127] Fix native recycling touch not correctly inited issue --- cocos2d/core/CCNode.js | 6 ++++++ jsb/jsb-event.js | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 67f446cb95..e176721ab3 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -158,6 +158,8 @@ var _touchStartHandler = function (touch, event) { event.bubbles = true; node.dispatchEvent(event); if (CC_JSB) { + event.touch = null; + event._touches = null; Event.EventTouch.pool.put(event); } return true; @@ -174,6 +176,8 @@ var _touchMoveHandler = function (touch, event) { event.bubbles = true; node.dispatchEvent(event); if (CC_JSB) { + event.touch = null; + event._touches = null; Event.EventTouch.pool.put(event); } }; @@ -194,6 +198,8 @@ var _touchEndHandler = function (touch, event) { event.bubbles = true; node.dispatchEvent(event); if (CC_JSB) { + event.touch = null; + event._touches = null; Event.EventTouch.pool.put(event); } }; diff --git a/jsb/jsb-event.js b/jsb/jsb-event.js index 2e37eb3e8f..e806ccb3ca 100644 --- a/jsb/jsb-event.js +++ b/jsb/jsb-event.js @@ -56,11 +56,11 @@ Event.EventTouch.pool = new Pool(5); Event.EventTouch.pool.get = function (fromEvt) { var touchArr = fromEvt.getTouches(); var event = this._get() || new Event.EventTouch(touchArr, true); + event.eventPhase = cc.Event.NONE; event._eventCode = fromEvt.getEventCode(); - + event._touches = touchArr; event._target = null; event._currentTarget = null; - event.eventPhase = cc.Event.NONE; event._propagationStopped = false; event._propagationImmediateStopped = false; return event; From 8c0220fce21cbef43cf1dedd7eb4e24b19ede1f2 Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Tue, 12 Dec 2017 17:32:04 +0800 Subject: [PATCH 073/127] fixed rigidbody allowSleep --- cocos2d/core/physics/CCRigidBody.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/physics/CCRigidBody.js b/cocos2d/core/physics/CCRigidBody.js index 9218781571..71e355d417 100644 --- a/cocos2d/core/physics/CCRigidBody.js +++ b/cocos2d/core/physics/CCRigidBody.js @@ -213,7 +213,7 @@ var RigidBody = cc.Class({ this._allowSleep = value; if (this._b2Body) { - this._b2Body.SetAllowSleeping(value); + this._b2Body.SetSleepingAllowed(value); } } }, From 9d7a70d41aa9653ffba4d5a065ee3b957d3571e4 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Wed, 13 Dec 2017 11:41:54 +0800 Subject: [PATCH 074/127] fix always show toggleGroup tips bug --- cocos2d/core/components/CCToggle.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/components/CCToggle.js b/cocos2d/core/components/CCToggle.js index f039995298..abe95d41eb 100644 --- a/cocos2d/core/components/CCToggle.js +++ b/cocos2d/core/components/CCToggle.js @@ -64,7 +64,7 @@ var Toggle = cc.Class({ toggleGroup: { default: null, tooltip: CC_DEV && 'i18n:COMPONENT.toggle.toggleGroup', - type: cc.ToggleGroup + type: require('./CCToggleGroup') }, /** From be71b8848d762e2b8ea4eb998dd5b2d1c5bcbc90 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Wed, 13 Dec 2017 11:49:40 +0800 Subject: [PATCH 075/127] adjust toggle in modules.json --- modules.json | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/modules.json b/modules.json index 207e0cbdd2..3a09324285 100644 --- a/modules.json +++ b/modules.json @@ -96,13 +96,9 @@ { "name": "Toggle", "entries": [ - "./cocos2d/core/components/CCToggle.js" - ] - }, - { - "name": "ToggleGroup", - "entries": [ - "./cocos2d/core/components/CCToggleGroup.js" + "./cocos2d/core/components/CCToggle.js", + "./cocos2d/core/components/CCToggleGroup.js", + "./cocos2d/core/components/CCToggleContainer.js" ] }, { From f4f20ff06748226a300fe61869af25af94da2a32 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 13 Dec 2017 15:22:01 +0800 Subject: [PATCH 076/127] fix merge --- cocos2d/core/CCGame.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index ee62372c23..0d03ec477d 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -709,7 +709,7 @@ var game = { var opts = { 'stencil': true, 'alpha': cc.macro.ENABLE_TRANSPARENT_CANVAS - }); + }; if (isWeChatGame) { opts['preserveDrawingBuffer'] = true; } From 012c97152e81bab909b3e4e281215765e4207c59 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 14 Dec 2017 16:55:35 +0800 Subject: [PATCH 077/127] remove unused property of _ccsg.TMXTiledMap --- cocos2d/tilemap/CCSGTMXTiledMap.js | 36 +----------------- cocos2d/tilemap/CCTMXXMLParser.js | 60 ++---------------------------- 2 files changed, 5 insertions(+), 91 deletions(-) diff --git a/cocos2d/tilemap/CCSGTMXTiledMap.js b/cocos2d/tilemap/CCSGTMXTiledMap.js index 5c6d91b93a..f978f47bf8 100644 --- a/cocos2d/tilemap/CCSGTMXTiledMap.js +++ b/cocos2d/tilemap/CCSGTMXTiledMap.js @@ -114,19 +114,11 @@ _ccsg.TMXTiledMap = _ccsg.Node.extend(/** @lends _ccsg.TMXTiledMap# */{ /** * Creates a TMX Tiled Map with a TMX file or content string.
* Constructor of _ccsg.TMXTiledMap - * @param {String} tmxFile tmxFile fileName or content string - * @param {String} resourcePath If tmxFile is a file name ,it is not required.If tmxFile is content string ,it is must required. */ - ctor:function(tmxFile,resourcePath){ + ctor:function(){ _ccsg.Node.prototype.ctor.call(this); this._mapSize = cc.size(0, 0); this._tileSize = cc.size(0, 0); - - if(resourcePath !== undefined){ - this.initWithXML(tmxFile,resourcePath); - }else if(tmxFile !== undefined){ - this.initWithTMXFile(tmxFile); - } }, /** @@ -235,32 +227,6 @@ _ccsg.TMXTiledMap = _ccsg.Node.extend(/** @lends _ccsg.TMXTiledMap# */{ this.properties = Var; }, - /** - * Initializes the instance of _ccsg.TMXTiledMap with tmxFile - * @param {String} tmxFile - * @return {Boolean} Whether the initialization was successful. - * @example - * //example - * var map = new _ccsg.TMXTiledMap() - * map.initWithTMXFile("hello.tmx"); - */ - initWithTMXFile:function (tmxFile) { - if(!tmxFile || tmxFile.length === 0) { - return false; - } - this.width = 0; - this.height = 0; - var mapInfo = new cc.TMXMapInfo(tmxFile); - if (!mapInfo) - return false; - - var locTilesets = mapInfo.getTilesets(); - if(!locTilesets || locTilesets.length === 0) - cc.logID(7212); - this._buildWithMapInfo(mapInfo); - return true; - }, - /** * Initializes the instance of _ccsg.TMXTiledMap with tmxString * @param {String} tmxString diff --git a/cocos2d/tilemap/CCTMXXMLParser.js b/cocos2d/tilemap/CCTMXXMLParser.js index 6bfb77dabf..3860b179ba 100644 --- a/cocos2d/tilemap/CCTMXXMLParser.js +++ b/cocos2d/tilemap/CCTMXXMLParser.js @@ -222,7 +222,6 @@ function getPropertyList (node) { * @property {Number} parentGID - Parent GID. * @property {Object} layerAttrs - Layer attributes. * @property {Boolean} storingCharacters - Is reading storing characters stream. - * @property {String} tmxFileName - TMX file name. * @property {String} currentString - Current string stored from characters stream. * @property {Number} mapWidth - Width of the map * @property {Number} mapHeight - Height of the map @@ -249,7 +248,6 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ parentGID:null, layerAttrs:0, storingCharacters:false, - tmxFileName:null, currentString:null, _objectGroups:null, @@ -270,8 +268,8 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ /** * Creates a TMX Format with a tmx file or content string
* Constructor of cc.TMXMapInfo - * @param {String} tmxFile fileName or content string - * @param {String} resourcePath If tmxFile is a file name ,it is not required.If tmxFile is content string ,it is must required. + * @param {String} tmxFile content string + * @param {String} resourcePath */ ctor:function (tmxFile, resourcePath) { cc.SAXParser.prototype.ctor.apply(this); @@ -284,11 +282,7 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ this.properties = []; this._tileProperties = {}; - if (resourcePath !== undefined) { - this.initWithXML(tmxFile,resourcePath); - } else if(tmxFile !== undefined){ - this.initWithTMXFile(tmxFile); - } + this.initWithXML(tmxFile,resourcePath); }, /** * Gets Map orientation. @@ -548,16 +542,6 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ this.properties = value; }, - /** - * Initializes a TMX format with a tmx file - * @param {String} tmxFile - * @return {Element} - */ - initWithTMXFile:function (tmxFile) { - this._internalInit(tmxFile, null); - return this.parseXMLFile(tmxFile); - }, - /** * initializes a TMX format with an XML string and a TMX resource path * @param {String} tmxString @@ -680,15 +664,7 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ var image = selTileset.getElementsByTagName('image')[0]; var imagename = image.getAttribute('source'); - var num = -1; - if(this.tmxFileName) - num = this.tmxFileName.lastIndexOf("/"); - if (num !== -1) { - var dir = this.tmxFileName.substr(0, num + 1); - tileset.sourceImage = dir + imagename; - } else { - tileset.sourceImage = this._resources + (this._resources ? "/" : "") + imagename; - } + tileset.sourceImage = this._resources + (this._resources ? "/" : "") + imagename; this.setTilesets(tileset); @@ -993,22 +969,6 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ this.currentString = currentString; }, - /** - * Gets the tmxFileName - * @return {String} - */ - getTMXFileName:function () { - return this.tmxFileName; - }, - - /** - * Set the tmxFileName - * @param {String} fileName - */ - setTMXFileName:function (fileName) { - this.tmxFileName = fileName; - }, - _internalInit:function (tmxFileName, resourcePath) { this._tilesets.length = 0; this._layers.length = 0; @@ -1047,18 +1007,6 @@ _p.tileHeight; cc.defineGetterSetter(_p, "tileHeight", _p._getTileHeight, _p._setTileHeight); -/** - * Creates a TMX Format with a tmx file or content string - * @deprecated since v3.0 please use new cc.TMXMapInfo(tmxFile, resourcePath) instead. - * @param {String} tmxFile fileName or content string - * @param {String} resourcePath If tmxFile is a file name ,it is not required.If tmxFile is content string ,it is must required. - * @return {cc.TMXMapInfo} - */ -cc.TMXMapInfo.create = function (tmxFile, resourcePath) { - return new cc.TMXMapInfo(tmxFile, resourcePath); -}; - - /** * @constant * @type Number From 57d19ebe28f1acad85d3919d1bacb69e2d3b7ac5 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 14 Dec 2017 18:55:35 +0800 Subject: [PATCH 078/127] use preloaded texture asset for tiled map --- DebugInfos.js | 3 +- cocos2d/tilemap/CCSGTMXLayer.js | 13 +++--- cocos2d/tilemap/CCSGTMXObject.js | 6 ++- cocos2d/tilemap/CCSGTMXTiledMap.js | 5 ++- cocos2d/tilemap/CCTMXXMLParser.js | 64 ++++++++++++++++------------- cocos2d/tilemap/CCTiledMap.js | 13 ++++-- cocos2d/tilemap/CCTiledMapAsset.js | 25 +++++------ cocos2d/tilemap/editor/tiled-map.js | 3 +- 8 files changed, 74 insertions(+), 58 deletions(-) diff --git a/DebugInfos.js b/DebugInfos.js index 055ab814c5..f4272d6356 100644 --- a/DebugInfos.js +++ b/DebugInfos.js @@ -569,7 +569,8 @@ if (CC_DEBUG) { "7217": "cocos2d: TMXFomat: Unsupported orientation: %s", //parseXMLFile "7218": "cc.TMXMapInfo.parseXMLFile(): unsupported compression method", //_parseLayer "7219": "cc.TMXMapInfo.parseXMLFile(): Only base64 and/or gzip/zlib maps are supported", //_parseLayer - "7220": "TMX Parser: please load the xml resource first: %s", // parseXMLFile + "7220": "cc.TMXMapInfo.parseXMLFile(): please load the xml resource first: %s", // parseXMLFile + "7221": "cc.TMXMapInfo.parseXMLFile(): Texture '%s' not found.", //Wrapper: 7300 "7300": "The new selected must be number", //CheckBox.selected "7301": "The new bake must be boolean", //layer diff --git a/cocos2d/tilemap/CCSGTMXLayer.js b/cocos2d/tilemap/CCSGTMXLayer.js index 53e8a5865f..0afcb7eccf 100644 --- a/cocos2d/tilemap/CCSGTMXLayer.js +++ b/cocos2d/tilemap/CCSGTMXLayer.js @@ -209,13 +209,14 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ this._texGrids = []; for (i = 0; i < len; ++i) { tileset = tilesets[i]; - tex = cc.textureCache.addImage(tileset.sourceImage, function (tex) { + tex = tileset.sourceImage; + if (tex) { tex.setAliasTexParameters(); - }); - this._textures[i] = tex; - this._fillTextureGrids(tileset, i); - if (tileset === tilesetInfo) { - this._texture = tex; + this._textures[i] = tex; + this._fillTextureGrids(tileset, i); + if (tileset === tilesetInfo) { + this._texture = tex; + } } } } diff --git a/cocos2d/tilemap/CCSGTMXObject.js b/cocos2d/tilemap/CCSGTMXObject.js index e48524ba91..c85c1a9418 100644 --- a/cocos2d/tilemap/CCSGTMXObject.js +++ b/cocos2d/tilemap/CCSGTMXObject.js @@ -147,8 +147,10 @@ _ccsg.TMXObjectImage = _ccsg.Sprite.extend(/** @lends cc.TMXObjectImage# */{ this.setVisible(this._container.objectVisible); // init the image - var texture = cc.textureCache.addImage(cc.path._normalize(tileset.sourceImage)); - this._initWithTileset(texture, useTileset); + var texture = tileset.sourceImage; + if (texture) { + this._initWithTileset(texture, useTileset); + } // init the position & anchor point with map info this._initPosWithMapInfo(mapInfo); diff --git a/cocos2d/tilemap/CCSGTMXTiledMap.js b/cocos2d/tilemap/CCSGTMXTiledMap.js index f978f47bf8..532a84dd00 100644 --- a/cocos2d/tilemap/CCSGTMXTiledMap.js +++ b/cocos2d/tilemap/CCSGTMXTiledMap.js @@ -231,13 +231,14 @@ _ccsg.TMXTiledMap = _ccsg.Node.extend(/** @lends _ccsg.TMXTiledMap# */{ * Initializes the instance of _ccsg.TMXTiledMap with tmxString * @param {String} tmxString * @param {String} resourcePath + * @param {Object} textures * @return {Boolean} Whether the initialization was successful. */ - initWithXML:function(tmxString, resourcePath){ + initWithXML: function(tmxString, resourcePath, textures){ this.width = 0; this.height = 0; - var mapInfo = new cc.TMXMapInfo(tmxString, resourcePath); + var mapInfo = new cc.TMXMapInfo(tmxString, resourcePath, textures); var locTilesets = mapInfo.getTilesets(); if(!locTilesets || locTilesets.length === 0) cc.logID(7213); diff --git a/cocos2d/tilemap/CCTMXXMLParser.js b/cocos2d/tilemap/CCTMXXMLParser.js index 3860b179ba..4ec00b3360 100644 --- a/cocos2d/tilemap/CCTMXXMLParser.js +++ b/cocos2d/tilemap/CCTMXXMLParser.js @@ -147,7 +147,7 @@ cc.TMXObjectGroupInfo = cc._Class.extend(/** @lends cc.TMXObjectGroupInfo# */{ * @property {number} firstGid - First grid * @property {number} spacing - Spacing * @property {number} margin - Margin - * @property {string} sourceImage - Filename containing the tiles (should be sprite sheet / texture atlas) + * @property {null} sourceImage - Texture containing the tiles (should be sprite sheet / texture atlas) * @property {cc.Size} imageSize - Size in pixels of the image */ cc.TMXTilesetInfo = cc._Class.extend(/** @lends cc.TMXTilesetInfo# */{ @@ -161,8 +161,8 @@ cc.TMXTilesetInfo = cc._Class.extend(/** @lends cc.TMXTilesetInfo# */{ this.spacing = 0; // Margin this.margin = 0; - // Filename containing the tiles (should be sprite sheet / texture atlas) - this.sourceImage = ""; + // Texture containing the tiles (should be sprite sheet / texture atlas) + this.sourceImage = null; // Size in pixels of the image this.imageSize = cc.size(0, 0); @@ -258,7 +258,10 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ _tilesets:null, // tile properties _tileProperties:null, - _resources:"", + _resources: "", // used to load relative tsx + + // map of textures indexed by name + _textures: null, // hex map values _staggerAxis: null, @@ -270,8 +273,9 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ * Constructor of cc.TMXMapInfo * @param {String} tmxFile content string * @param {String} resourcePath + * @param {Object} textures */ - ctor:function (tmxFile, resourcePath) { + ctor: function (tmxFile, resourcePath, textures) { cc.SAXParser.prototype.ctor.apply(this); this._mapSize = cc.size(0, 0); this._tileSize = cc.size(0, 0); @@ -282,7 +286,7 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ this.properties = []; this._tileProperties = {}; - this.initWithXML(tmxFile,resourcePath); + this.initWithXML(tmxFile, resourcePath, textures); }, /** * Gets Map orientation. @@ -546,10 +550,29 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ * initializes a TMX format with an XML string and a TMX resource path * @param {String} tmxString * @param {String} resourcePath + * @param {Object} textures * @return {Boolean} */ - initWithXML:function (tmxString, resourcePath) { - this._internalInit(null, resourcePath); + initWithXML:function (tmxString, resourcePath, textures) { + + this._tilesets.length = 0; + this._layers.length = 0; + + if (resourcePath) + this._resources = resourcePath; + this._textures = textures; + + this._objectGroups.length = 0; + this._allChildren.length = 0; + this.properties.length = 0; + this._tileProperties.length = 0; + + // tmp vars + this.currentString = ""; + this.storingCharacters = false; + this.layerAttrs = cc.TMXLayerInfo.ATTRIB_NONE; + this.parentElement = cc.TiledMap.NONE; + return this.parseXMLString(tmxString); }, @@ -664,7 +687,10 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ var image = selTileset.getElementsByTagName('image')[0]; var imagename = image.getAttribute('source'); - tileset.sourceImage = this._resources + (this._resources ? "/" : "") + imagename; + tileset.sourceImage = this._textures[imagename]; + if (!tileset.sourceImage) { + cc.errorID(7221, imagename); + } this.setTilesets(tileset); @@ -967,26 +993,6 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ */ setCurrentString:function (currentString) { this.currentString = currentString; - }, - - _internalInit:function (tmxFileName, resourcePath) { - this._tilesets.length = 0; - this._layers.length = 0; - - this.tmxFileName = tmxFileName; - if (resourcePath) - this._resources = resourcePath; - - this._objectGroups.length = 0; - this._allChildren.length = 0; - this.properties.length = 0; - this._tileProperties.length = 0; - - // tmp vars - this.currentString = ""; - this.storingCharacters = false; - this.layerAttrs = cc.TMXLayerInfo.ATTRIB_NONE; - this.parentElement = cc.TiledMap.NONE; } }); diff --git a/cocos2d/tilemap/CCTiledMap.js b/cocos2d/tilemap/CCTiledMap.js index f752064209..7175e7b145 100644 --- a/cocos2d/tilemap/CCTiledMap.js +++ b/cocos2d/tilemap/CCTiledMap.js @@ -853,7 +853,14 @@ var TiledMap = cc.Class({ resPath = resPath.replace(/\\/g, '/'); } - var ret = sgNode.initWithXML(file.tmxXmlStr, resPath); + var texValues = file.textures; + var texKeys = file.textureNames; + var textures = {}; + for (let i = 0; i < texValues.length; ++i) { + textures[texKeys[i]] = texValues[i]; + } + + var ret = sgNode.initWithXML(file.tmxXmlStr, resPath, textures); if (ret) { // Asset is changed, the layers are recreated. // The layers of pre asset should be cleaned. @@ -864,11 +871,11 @@ var TiledMap = cc.Class({ // tmx file is cleared // 1. hide the tmx layers & groups in _sgNode var layers = sgNode.allLayers(); - for (var i = 0, n = layers.length; i < n; i++) { + for (let i = 0, n = layers.length; i < n; i++) { sgNode.removeChild(layers[i]); } var groups = sgNode.getObjectGroups(); - for (i = 0, n = groups.length; i < n; i++) { + for (let i = 0, n = groups.length; i < n; i++) { sgNode.removeChild(groups[i]); } diff --git a/cocos2d/tilemap/CCTiledMapAsset.js b/cocos2d/tilemap/CCTiledMapAsset.js index 978ddd638c..2038d6fab4 100644 --- a/cocos2d/tilemap/CCTiledMapAsset.js +++ b/cocos2d/tilemap/CCTiledMapAsset.js @@ -34,23 +34,20 @@ var TiledMapAsset = cc.Class({ extends: cc.Asset, properties: { - tmxXmlStr: { - default: '' - }, + tmxXmlStr: '', + tmxFolderPath: '', - tmxFolderPath : { - default: '' - }, + /** + * @property {Texture2D[]} textures + */ + textures: [cc.Texture2D], - textures: { - default: [], - type: [cc.Texture2D] - }, + /** + * @property {String[]} textureNames + */ + textureNames: [cc.String], - tsxFiles: { - default: [], - url: [cc.RawAsset] - } + tsxFiles: [cc.RawAsset] }, statics: { diff --git a/cocos2d/tilemap/editor/tiled-map.js b/cocos2d/tilemap/editor/tiled-map.js index a4fcf795dd..43a9e16802 100644 --- a/cocos2d/tilemap/editor/tiled-map.js +++ b/cocos2d/tilemap/editor/tiled-map.js @@ -65,7 +65,7 @@ class TiledMapMeta extends CustomAssetMeta { this._tsxFiles = []; } - static version () { return '1.0.4'; } + static version () { return '2.0.0'; } static defaultType() { return 'tiled-map'; } import (fspath, cb) { @@ -99,6 +99,7 @@ class TiledMapMeta extends CustomAssetMeta { var uuid = db.fspathToUuid(p); return uuid ? Editor.serialize.asAsset(uuid) : null; }); + asset.textureNames = this._textures.map(p => Path.basename(p)); asset.tsxFiles = this._tsxFiles.map(p => db.fspathToUrl(p)); db.saveAssetToLibrary(this.uuid, asset); cb(); From cf512dd06e79077ae6a018349b1abae8c436fe58 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Fri, 15 Dec 2017 17:21:06 +0800 Subject: [PATCH 079/127] remove error info from the engine release for fireball/issues/6721 --- DebugInfos.js | 92 +++++++++++++++++++ cocos2d/actions/CCAction.js | 4 +- cocos2d/actions/CCActionCatmullRom.js | 2 +- cocos2d/actions/CCActionEase.js | 2 +- cocos2d/actions/CCActionInterval.js | 12 +-- cocos2d/actions/CCActionManager.js | 4 +- cocos2d/animation/playable.js | 2 +- cocos2d/core/CCConfiguration.js | 2 +- cocos2d/core/CCDrawingPrimitivesCanvas.js | 4 +- cocos2d/core/CCDrawingPrimitivesWebGL.js | 2 +- cocos2d/core/CCGame.js | 2 +- cocos2d/core/components/CCRendererInSG.js | 2 +- cocos2d/core/event-manager/CCEventManager.js | 2 +- cocos2d/core/load-pipeline/asset-loader.js | 2 +- .../core/load-pipeline/audio-downloader.js | 4 +- cocos2d/core/load-pipeline/downloader.js | 6 +- cocos2d/core/load-pipeline/uuid-loader.js | 6 +- cocos2d/core/platform/CCSys.js | 2 +- cocos2d/core/platform/_CCClass.js | 2 +- cocos2d/kazmath/gl/matrix.js | 4 +- cocos2d/kazmath/quaternion.js | 2 +- cocos2d/particle/CCPNGReader.js | 4 +- cocos2d/particle/CCParticleSystem.js | 2 +- cocos2d/particle/CCTIFFReader.js | 22 ++--- cocos2d/render-texture/CCRenderTexture.js | 4 +- .../CCRenderTextureCanvasRenderCmd.js | 2 +- .../CCRenderTextureWebGLRenderCmd.js | 4 +- cocos2d/shaders/CCGLProgram.js | 10 +- cocos2d/tilemap/CCSGTMXLayer.js | 20 ++-- cocos2d/tilemap/CCSGTMXTiledMap.js | 4 +- cocos2d/tilemap/CCTiledLayer.js | 2 +- cocos2d/tilemap/editor/tiled-map.js | 2 +- 32 files changed, 164 insertions(+), 72 deletions(-) diff --git a/DebugInfos.js b/DebugInfos.js index f4272d6356..5d3b748a4f 100644 --- a/DebugInfos.js +++ b/DebugInfos.js @@ -24,9 +24,20 @@ if (CC_DEBUG) { "1018": "Grid size must be (1,1)", //ActionGrid3D.initWithSize "1019": "Failed to construct, Sequence construction needs two or more actions", //ActionInterval.sequence "1020": "Failed to construct, Spawn construction needs two or more actions", //ActionInterval.spawn + "1021": "cc.Speed.initWithAction(): action must be non nil", //cc.Speed.initWithAction + "1022": "cc.Follow.initWithAction(): followedNode must be non nil", //cc.Follow.initWithAction + "1023": "cc.ActionEase.initWithAction(): action must be non nil", //cc.ActionEase.initWithAction + "1024": "Invalid configuration. It must at least have one control point", //cc.CardinalSplineTo.initWithDuration + "1025": "cc.Sequence.initWithTwoActions(): arguments must all be non nil", //cc.Sequence.initWithTwoActions + "1026": "cc.RepeatForever.initWithAction(): action must be non null", //cc.RepeatForever.initWithAction + "1027": "cc.Spawn.initWithTwoActions(): arguments must all be non null", //cc.Spawn.initWithAction + "1028": "cc.ReverseTime.initWithAction(): action must be non null", //cc.ReverseTime.initWithAction + "1029": "cc.ReverseTime.initWithAction(): the action was already passed in.", //cc.ReverseTime.initWithAction + "1030": "cc.Animate.initWithAnimation(): animation must be non-NULL", //cc.Animate.initWithAction //configuration: 1100 "1100": "Expected 'data' dict, but not found. Config file: %s", //loadConfigFile "1101": "Please load the resource first : %s", //loadConfigFile_2 + "1102": "Please load the resource first : %s", // loadConfigFile //Director: 1200 "1200": "cocos2d: Director: Error in gettimeofday", //resume "1201": "cocos2d: Director: unrecognized projection", //setProjection @@ -103,6 +114,7 @@ if (CC_DEBUG) { "1633": "Internal error, should not remove unknown node from parent.", //parent "1634": "addChild: The child to add must be instance of cc.Node, not %s.", //addChild "1635": "reorderChild: this child is not in children list", // reorderChild + "1636": "Invalid sgNode. It must be an instance of _ccsg.Node", // RendererInSG //AtlasNode: 1700 "1700": "cc.AtlasNode.updateAtlasValues(): Shall be overridden in subclasses", //_updateAtlasValues "1701": "", //_initWithTileFile @@ -257,6 +269,7 @@ if (CC_DEBUG) { "3508": "If program goes here, there should be event in dispatch.", //_updateListeners "3509": "_inDispatch should be 1 here.", //_updateListeners_2 "3510": "%s's scene graph node not contains in the parent's children", //SceneGraphHelper._getChildrenOffset + "3511": "event is undefined", //Class: 3600 "3600": "cc.Class will automatically call super constructor of %s, you should not call it manually.", //Class.callSuperCtor "3601": "The editor property 'playOnFocus' should be used with 'executeInEditMode' in class '%s'", //playOnFocus @@ -346,6 +359,7 @@ if (CC_DEBUG) { " default: null,\n" + " type: cc.Texture2D // use 'type:' instead of 'url:'\n" + "}", + "3658": "browser does not support getters",//defineGetterSetter //Prefab: 3700 "3700": "internal error: _prefab is undefined", //_doInstantiate "3701": "Failed to load prefab asset for node '%s'", //syncWithPrefab @@ -370,6 +384,7 @@ if (CC_DEBUG) { "3817": "Sorry, the component of '%s' which with an index of %s is corrupted! It has been removed.", "3818": "Failed to read or parse project.json", //_loadConfig "3819": "Warning: target element is not a DIV or CANVAS", //_initRenderer + "3820": "The renderer doesn't support the renderMode %s", //_initRenderer //Animation: 3900 "3900": "Invalid clip to add", //addClip "3901": "Invalid clip to remove", //removeClip @@ -383,6 +398,7 @@ if (CC_DEBUG) { "3909": "[animate] keyFrames must be non-nil", //animate "3910": "[animate] ratio should >= 0!", //_doAnimate "3911": "[animate] ratio should in the order of smallest to largest!", //_doAnimate_2 + "3912": "already-playing", //playable play //Label: 4000 "4000": "Sorry, the cc.Font has been modified from Raw Asset to Asset. Please load the font asset before using.", //font "4001": "_ccsg.Label._initBMFontWithString(): Impossible to create font. Please check file", //_setBMFontFile @@ -437,6 +453,15 @@ if (CC_DEBUG) { "4920": "Sorry, you shouldn\'t use id as item identity any more, please use url or uuid instead, the current id is being set as url: (%s)", // load "4921": "Invalid pipe or invalid index provided!", //pipeline.insertPipe "4922": "The pipe to be inserted is already in the pipeline!", //pipeline.insertPipe + "4923": "Uuid Loader: Parse asset [ %s ] failed : %s", // uuid-loader + "4924": "JSON Loader: Input item doesn\\'t contain string content",// uuid-loader + "4925": "Uuid Loader: Deserialize asset [ %s ] failed : %s",// uuid-loader + "4926": "Audio Downloader: no web audio context.",// audio-downloader + "4927": "Audio Downloader: audio not supported on this browser!",// audio-downloader + "4928": "Load %s failed!",// downloadScript + "4929": "Load Webp ( %s ) failed",// downloadWebp + "4930": "Load image ( %s ) failed",// downloadImage + "4931": "Download Uuid: can not find type of raw asset[ %s ]: %s",//asset-loader //CCObject: 5000 "5000": "object already destroyed", //destroy "5001": "object not yet destroyed", //realDestroyInEditor @@ -445,6 +470,7 @@ if (CC_DEBUG) { //CCSys: 5200 "5200": "Warning: localStorage isn't enabled. Please confirm browser cookie or privacy option", //localStorage "5201": "browser don't support web audio", //audio + "5202": "This feature supports WebGL render mode only.", //_checkWebGLRenderMode //Deserialize: 5300 "5300": "Type of target to deserialize not matched with data: target is %s, data is %s", //_deserializeObject "5301": "Can not find script '%s'", //reportMissingClass @@ -509,6 +535,19 @@ if (CC_DEBUG) { "6014": "Can't change blending functions when the particle is being batched", //_updateBlendFunc "6015": "_ccsg.ParticleSystem.setDisplayFrame(): QuadParticle only supports SpriteFrames with no offsets", //setDisplayFrame "6016": "_ccsg.ParticleSystem._allocMemory(): Memory should not be allocated when not using batchNode", //WebGLRenderCmd._allocMemory + "6017": "Incomplete or corrupt PNG file", //CCPNGReader + "6018": "Invalid filter algorithm: %s",//CCPNGReader + "6019": "Invalid byte order value.", //CCTIFFReader checkLittleEndian + "6020": "You forgot your towel!", //CCTIFFReader hasTowel + "6021": "Unknown Field Tag: %s", //CCTIFFReader hasTowel + "6022": "Too many bits requested", //CCTIFFReader getBits + "6023": "No bits requested", //CCTIFFReader getBits + "6024": "Cannot recover from missing StripByteCounts", //CCTIFFReader parseTIFF + "6025": "Cannot handle sub-byte bits per sample", //CCTIFFReader parseTIFF + "6026": "Cannot handle sub-byte bits per pixel", //CCTIFFReader parseTIFF + "6027": "Palette image missing color map", //CCTIFFReader parseTIFF + "6028": "Unknown Photometric Interpretation: %s", //CCTIFFReader parseTIFF + "6029": "Unkown error", //CCParticleSystem _applyFile //Compatible: 6100 "6100": "Not supported file types, Please try use the ccs.load", //widgetFromJsonFile //CCFactory: 6200 @@ -530,6 +569,9 @@ if (CC_DEBUG) { "6700": "Can't init canvas '%s' because it conflicts with the existing '%s', the scene should only have one active canvas at the same time", //__preload "6701": "Should not add Canvas to a node which already contains a renderer component (%s).", //__preload_2 "6702": "Should not add Canvas to a node which size is already used by its other component.", //__preload_3 + "6703": "Can't initialise DrawingPrimitiveWebGL. context need is WebGLRenderingContext",//DrawingPrimitiveWebGL + "6704": "Polygon's point must greater than 2",//DrawingPrimitiveCanvas drawPoly + "6705": "Argument must be non-nil",//DrawingPrimitiveCanvas drawPoly //EventTarget: 6800 "6800": "Callback of event must be non-nil", //on "6801": "The message must be provided", //emit @@ -571,6 +613,23 @@ if (CC_DEBUG) { "7219": "cc.TMXMapInfo.parseXMLFile(): Only base64 and/or gzip/zlib maps are supported", //_parseLayer "7220": "cc.TMXMapInfo.parseXMLFile(): please load the xml resource first: %s", // parseXMLFile "7221": "cc.TMXMapInfo.parseXMLFile(): Texture '%s' not found.", + "7222": "Parse %s failed.",// tiled-map + "7223": "_ccsg.TMXLayer.setTileGID(): pos should be non-null",//CCTiledLayer setTileGID + "7224": "_ccsg.TMXTiledMap.getLayer(): layerName should be non-null or non-empty string.",//CCSGTMXTiledMap getLayer + "7225": "_ccsg.TMXTiledMap.getObjectGroup(): groupName should be non-null or non-empty string.",//CCSGTMXTiledMap getObjectGroup + "7226": "_ccsg.TMXLayer.getTileAt(): pos should be non-null",//CCSGTMXLayer getTileAt + "7227": "_ccsg.TMXLayer.getTileAt(): invalid position",//CCSGTMXLayer getTileAt + "7228": "_ccsg.TMXLayer.getTileGIDAt(): pos should be non-null",//CCSGTMXLayer getTileGIDAt + "7229": "_ccsg.TMXLayer.getTileGIDAt(): invalid position",//CCSGTMXLayer getTileGIDAt + "7230": "_ccsg.TMXLayer.setTileGID(): pos should be non-null",//CCSGTMXLayer setTileGID + "7231": "_ccsg.TMXLayer.setTileGID(): invalid position",//CCSGTMXLayer setTileGID + "7232": "_ccsg.TMXLayer.getTileFlagsAt(): pos should be non-null",//CCSGTMXLayer getTileFlagsAt + "7233": "_ccsg.TMXLayer.getTileFlagsAt(): invalid position",//CCSGTMXLayer getTileFlagsAt + "7234": "_ccsg.TMXLayer.removeTileAt(): pos should be non-null",//CCSGTMXLayer removeTileAt + "7235": "_ccsg.TMXLayer.removeTileAt(): invalid position",//CCSGTMXLayer removeTileAt + "7236": "_ccsg.TMXLayer.getTileAt(): pos should be non-null",//CCSGTMXLayer getTileAt + "7237": "_ccsg.TMXLayer.getTileAt(): pos should be non-null",//CCSGTMXLayer getTileAt + //Wrapper: 7300 "7300": "The new selected must be number", //CheckBox.selected "7301": "The new bake must be boolean", //layer @@ -592,6 +651,12 @@ if (CC_DEBUG) { "7510": "Spine: Animation not found: %s", //addAnimation //Render: 7600 "7600": "The context of RenderTexture is invalid.", //_renderingToCacheCanvas + "7601": "cc.RenderTexture._initWithWidthAndHeightForWebGL() : only RGB and RGBA formats are valid for a render texture;", //CCRenderTextureWebGLRenderCmd initWithWidthAndHeight + "7602": "Could not attach texture to the framebuffer",//CCRenderTextureWebGLRenderCmd initWithWidthAndHeight + "7603": "clearDepth isn't supported on Cocos2d-Html5",//CCRenderTextureWebGLRenderCmd clearDepth + "7604": "saveToFile isn't supported on Cocos2d-Html5",//CCRenderTexture saveToFile + "7605": "newCCImage isn't supported on Cocos2d-Html5",//CCRenderTexture newCCImage + //VideoPlayer: 7700 "7700": "On the web is always keep the aspect ratio", //setKeepAspectRatioEnabled "7701": "Can't know status", //isFullScreenEnabled @@ -612,6 +677,8 @@ if (CC_DEBUG) { "7905": "cc.math.mat4Assign(): pOut equals pIn", //mat4AssignSIMD "7906": "cc.mat.Matrix4.assignFrom(): mat4 equals current matrix", //assignFromSIMD "7907": "cc.math.Matrix4 equals: pMat1 and pMat2 are same object.", //equalsSIMD + "7908": "Invalid matrix mode specified", //glGetMatrix glMatrixMode + "7909": "current quaternion is an invalid value",// quaternion.js normalize //Reader: 8000 "8000": "Can't handle this field type or size", //TIFF.getFieldValues "8001": "No bytes requested", //TIFF.getBytes @@ -624,6 +691,10 @@ if (CC_DEBUG) { "8103": "cc.GLProgram.link(): Cannot link invalid program", //link "8104": "cocos2d: ERROR: Failed to link program: %s", //link "8105": "cocos2d: cc.shaderCache._loadDefaultShader, error shader type", //_loadDefaultShader + "8106": "Please load the resource firset : %s", //CCGLProgram initWithVertexShaderFilename + "8107": "cc.GLProgram.getUniformLocationForName(): uniform name should be non-null", //CCGLProgram getUniformLocationForName + "8108": "cc.GLProgram.getUniformLocationForName(): Invalid operation. Cannot get uniform location when program is not initialized", //CCGLProgram getUniformLocationForName + "8109": "modelView matrix is undefined.", //CCGLProgram _setUniformForMVPMatrixWithMat4 //Physics: 8200 "8200": "Please set node\'s active instead of rigidbody\'s enabled.", //cc.RigidBody.enabled //Camera: 8300 @@ -633,6 +704,27 @@ if (CC_DEBUG) { "8400": "Wrong type arguments, 'filePath' must be a String.", // cc.audioEngine.play }; cc._LogInfos = logs; + + var errorMapUrl = 'https://github.com/cocos-creator/engine/blob/master/EngineErrorMap.md'; + + cc._LogInfos.format = function (id) { + var type = 'error'; + if (arguments.length === 1) { + return CC_DEBUG ? cc._LogInfos[id] : type + ' ' + id + ', please go to ' + errorMapUrl + '#' + id + ' to see details.' + } + if (CC_DEBUG) { + let argsArr = cc.js.shiftArguments.apply(null, arguments); + return cc._LogInfos[id].concat(argsArr); + } else { + var msg = ''; + if (arguments.length === 2) { + msg = 'Arguments: ' + arguments[1]; + } else if (arguments.length > 2) { + msg = 'Arguments: ' + cc.js.shiftArguments.apply(null, arguments).join(', '); + } + return type + ' ' + id + ', please go to ' + errorMapUrl + '#' + id + ' to see details. ' + msg; + } + }; } // module.exports = false; diff --git a/cocos2d/actions/CCAction.js b/cocos2d/actions/CCAction.js index 5e362ef7fd..9d766d32a2 100644 --- a/cocos2d/actions/CCAction.js +++ b/cocos2d/actions/CCAction.js @@ -300,7 +300,7 @@ cc.Speed = cc.Action.extend({ */ initWithAction:function (action, speed) { if(!action) - throw new Error("cc.Speed.initWithAction(): action must be non nil"); + throw new Error(cc._LogInfos.format(1021)); this._innerAction = action; this._speed = speed; @@ -489,7 +489,7 @@ cc.Follow = cc.Action.extend({ */ initWithTarget:function (followedNode, rect) { if(!followedNode) - throw new Error("cc.Follow.initWithAction(): followedNode must be non nil"); + throw new Error(cc._LogInfos.format(1022)); var _this = this; rect = rect || cc.rect(0, 0, 0, 0); diff --git a/cocos2d/actions/CCActionCatmullRom.js b/cocos2d/actions/CCActionCatmullRom.js index 20e2d2a2b4..a065f8d5ae 100644 --- a/cocos2d/actions/CCActionCatmullRom.js +++ b/cocos2d/actions/CCActionCatmullRom.js @@ -129,7 +129,7 @@ cc.CardinalSplineTo = cc.ActionInterval.extend({ initWithDuration:function (duration, points, tension) { if(!points || points.length === 0) - throw new Error("Invalid configuration. It must at least have one control point"); + throw new Error(cc._LogInfos.format(1024)); if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this.setPoints(points); diff --git a/cocos2d/actions/CCActionEase.js b/cocos2d/actions/CCActionEase.js index e33b3f6251..cead0e1139 100644 --- a/cocos2d/actions/CCActionEase.js +++ b/cocos2d/actions/CCActionEase.js @@ -51,7 +51,7 @@ cc.ActionEase = cc.ActionInterval.extend({ */ initWithAction:function (action) { if(!action) - throw new Error("cc.ActionEase.initWithAction(): action must be non nil"); + throw new Error(cc._LogInfos.format(1023)); if (this.initWithDuration(action.getDuration())) { this._inner = action; diff --git a/cocos2d/actions/CCActionInterval.js b/cocos2d/actions/CCActionInterval.js index f293913dfa..f724d0bb4b 100644 --- a/cocos2d/actions/CCActionInterval.js +++ b/cocos2d/actions/CCActionInterval.js @@ -341,7 +341,7 @@ cc.Sequence = cc.ActionInterval.extend({ */ initWithTwoActions:function (actionOne, actionTwo) { if(!actionOne || !actionTwo) - throw new Error("cc.Sequence.initWithTwoActions(): arguments must all be non nil"); + throw new Error(cc._LogInfos.format(1025)); var d = actionOne._duration + actionTwo._duration; this.initWithDuration(d); @@ -649,7 +649,7 @@ cc.RepeatForever = cc.ActionInterval.extend({ */ initWithAction:function (action) { if(!action) - throw new Error("cc.RepeatForever.initWithAction(): action must be non null"); + throw new Error(cc._LogInfos.format(1026)); this._innerAction = action; return true; @@ -767,7 +767,7 @@ cc.Spawn = cc.ActionInterval.extend({ */ initWithTwoActions:function (action1, action2) { if(!action1 || !action2) - throw new Error("cc.Spawn.initWithTwoActions(): arguments must all be non null"); + throw new Error(cc._LogInfos.format(1027)); var ret = false; @@ -2473,9 +2473,9 @@ cc.ReverseTime = cc.ActionInterval.extend({ */ initWithAction:function (action) { if(!action) - throw new Error("cc.ReverseTime.initWithAction(): action must be non null"); + throw new Error(cc._LogInfos.format(1028)); if(action === this._other) - throw new Error("cc.ReverseTime.initWithAction(): the action was already passed in."); + throw new Error(cc._LogInfos.format(1029)); if (cc.ActionInterval.prototype.initWithDuration.call(this, action._duration)) { // Don't leak if action is reused @@ -2580,7 +2580,7 @@ cc.Animate = cc.ActionInterval.extend({ */ initWithAnimation:function (animation) { if(!animation) - throw new Error("cc.Animate.initWithAnimation(): animation must be non-NULL"); + throw new Error(cc._LogInfos.format(1030)); var singleDuration = animation.getDuration(); if (this.initWithDuration(singleDuration * animation.getLoops())) { this._nextFrame = 0; diff --git a/cocos2d/actions/CCActionManager.js b/cocos2d/actions/CCActionManager.js index 55185d3fa3..d0e3e14582 100644 --- a/cocos2d/actions/CCActionManager.js +++ b/cocos2d/actions/CCActionManager.js @@ -114,9 +114,9 @@ cc.ActionManager = cc._Class.extend(/** @lends cc.ActionManager# */{ */ addAction:function (action, target, paused) { if(!action) - throw new Error("cc.ActionManager.addAction(): action must be non-null"); + throw new Error(cc._LogInfos.format(1000)); if(!target) - throw new Error("cc.ActionManager.addAction(): action must be non-null"); + throw new Error(cc._LogInfos.format(1000)); //check if the action target already exists var element = this._hashTargets[target.__instanceId]; diff --git a/cocos2d/animation/playable.js b/cocos2d/animation/playable.js index 648e8680a3..5ae9660ecf 100644 --- a/cocos2d/animation/playable.js +++ b/cocos2d/animation/playable.js @@ -80,7 +80,7 @@ prototype.play = function () { this.onResume(); } else { - this.onError('already-playing'); + this.onError(cc._LogInfos.format(3912)); } } else { diff --git a/cocos2d/core/CCConfiguration.js b/cocos2d/core/CCConfiguration.js index e87b9acdfb..d4334e0b91 100644 --- a/cocos2d/core/CCConfiguration.js +++ b/cocos2d/core/CCConfiguration.js @@ -267,7 +267,7 @@ cc.configuration = /** @lends cc.configuration# */{ if(!this._inited) this._init(); var dict = cc.loader.getRes(url); - if(!dict) throw new Error("Please load the resource first : " + url); + if(!dict) throw new Error(cc._LogInfos.format(1102, url)); cc.assertID(dict, 1101, url); var getDatas = dict["data"]; diff --git a/cocos2d/core/CCDrawingPrimitivesCanvas.js b/cocos2d/core/CCDrawingPrimitivesCanvas.js index a8470d38b4..d7c16e1001 100644 --- a/cocos2d/core/CCDrawingPrimitivesCanvas.js +++ b/cocos2d/core/CCDrawingPrimitivesCanvas.js @@ -143,7 +143,7 @@ var DrawingPrimitiveCanvas = cc._Class.extend({ return; if (vertices.length < 3) - throw new Error("Polygon's point must greater than 2"); + throw new Error(cc._LogInfos.format(6704)); var firstPoint = vertices[0], locContext = this._renderContext.getContext(); var locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY(); @@ -319,7 +319,7 @@ var DrawingPrimitiveCanvas = cc._Class.extend({ destSize.width, destSize.height); break; default: - throw new Error("Argument must be non-nil"); + throw new Error(cc._LogInfos.format(6705)); break; } }, diff --git a/cocos2d/core/CCDrawingPrimitivesWebGL.js b/cocos2d/core/CCDrawingPrimitivesWebGL.js index 1c1c914c4d..3112d22af9 100644 --- a/cocos2d/core/CCDrawingPrimitivesWebGL.js +++ b/cocos2d/core/CCDrawingPrimitivesWebGL.js @@ -44,7 +44,7 @@ var DrawingPrimitiveWebGL = cc._Class.extend({ */ ctor:function (ctx) { if (cc.sys.platform !== cc.sys.WECHAT_GAME && !ctx instanceof WebGLRenderingContext) - throw new Error("Can't initialise DrawingPrimitiveWebGL. context need is WebGLRenderingContext"); + throw new Error(cc._LogInfos.format(6703)); this._renderContext = ctx; this._colorArray = new Float32Array([1.0, 1.0, 1.0, 1.0]); diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index 0d03ec477d..8ed336ec85 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -650,7 +650,7 @@ var game = { if (this._rendererInitialized) return; if (!cc._supportRender) { - throw new Error("The renderer doesn't support the renderMode " + this.config[this.CONFIG_KEY.renderMode]); + throw new Error(cc._LogInfos.format(3820, this.config[this.CONFIG_KEY.renderMode])); } var el = this.config[game.CONFIG_KEY.id], diff --git a/cocos2d/core/components/CCRendererInSG.js b/cocos2d/core/components/CCRendererInSG.js index 7adaed58e1..620679cfca 100644 --- a/cocos2d/core/components/CCRendererInSG.js +++ b/cocos2d/core/components/CCRendererInSG.js @@ -96,7 +96,7 @@ var RendererInSG = cc.Class({ _replaceSgNode: function (sgNode) { if (CC_EDITOR && !(sgNode instanceof _ccsg.Node)) { - throw new Error("Invalid sgNode. It must be an instance of _ccsg.Node"); + throw new Error(cc._LogInfos.format(1636)); } var node = this.node; diff --git a/cocos2d/core/event-manager/CCEventManager.js b/cocos2d/core/event-manager/CCEventManager.js index ee65db2fff..f03992bdd8 100644 --- a/cocos2d/core/event-manager/CCEventManager.js +++ b/cocos2d/core/event-manager/CCEventManager.js @@ -1053,7 +1053,7 @@ var eventManager = { this._updateDirtyFlagForSceneGraph(); this._inDispatch++; if(!event || !event.getType) - throw new Error("event is undefined"); + throw new Error(cc._LogInfos.format(3511)); if (event.getType().startsWith(cc.Event.TOUCH)) { this._dispatchTouchEvent(event); this._inDispatch--; diff --git a/cocos2d/core/load-pipeline/asset-loader.js b/cocos2d/core/load-pipeline/asset-loader.js index 266ec35d1b..af28842956 100644 --- a/cocos2d/core/load-pipeline/asset-loader.js +++ b/cocos2d/core/load-pipeline/asset-loader.js @@ -54,7 +54,7 @@ AssetLoader.prototype.handle = function (item, callback) { if (isRawAsset) { var ext = Path.extname(url).toLowerCase(); if (!ext) { - callback(new Error('Download Uuid: can not find type of raw asset[' + uuid + ']: ' + url)); + callback(new Error(cc._LogInfos.format(4931, uuid, url))); return; } ext = ext.substr(1); diff --git a/cocos2d/core/load-pipeline/audio-downloader.js b/cocos2d/core/load-pipeline/audio-downloader.js index 48ccf7abce..dc36f49c7c 100644 --- a/cocos2d/core/load-pipeline/audio-downloader.js +++ b/cocos2d/core/load-pipeline/audio-downloader.js @@ -73,7 +73,7 @@ function loadDomAudio (item, callback) { } function loadWebAudio (item, callback) { - if (!context) callback(new Error('Audio Downloader: no web audio context.')); + if (!context) callback(new Error(cc._LogInfos.format(4926))); var request = cc.loader.getXMLHttpRequest(); request.open("GET", item.url, true); @@ -100,7 +100,7 @@ function loadWebAudio (item, callback) { function downloadAudio (item, callback) { if (formatSupport.length === 0) { - return new Error('Audio Downloader: audio not supported on this browser!'); + return new Error(cc._LogInfos.format(4927)); } item.content = item.url; diff --git a/cocos2d/core/load-pipeline/downloader.js b/cocos2d/core/load-pipeline/downloader.js index 5cc438eeee..8be727d791 100644 --- a/cocos2d/core/load-pipeline/downloader.js +++ b/cocos2d/core/load-pipeline/downloader.js @@ -63,7 +63,7 @@ function downloadScript (item, callback, isAsync) { s.parentNode.removeChild(s); s.removeEventListener('load', loadHandler, false); s.removeEventListener('error', errorHandler, false); - callback(new Error('Load ' + url + ' failed!'), url); + callback(new Error(cc._LogInfos.format(4928, url))); } s.addEventListener('load', loadHandler, false); s.addEventListener('error', errorHandler, false); @@ -72,7 +72,7 @@ function downloadScript (item, callback, isAsync) { function downloadWebp (item, callback, isCrossOrigin, img) { if (!cc.sys.capabilities.webp) { - return new Error('Load Webp ( ' + item.url + ' ) failed'); + return new Error(cc._LogInfos.format(4929, item.url)); } return downloadImage(item, callback, isCrossOrigin, img); } @@ -111,7 +111,7 @@ function downloadImage (item, callback, isCrossOrigin, img) { downloadImage(item, callback, false, img); } else { - callback(new Error('Load image (' + url + ') failed')); + callback(new Error(cc._LogInfos.format(4930, url))); } } diff --git a/cocos2d/core/load-pipeline/uuid-loader.js b/cocos2d/core/load-pipeline/uuid-loader.js index 52f41ac67f..d0adb86533 100644 --- a/cocos2d/core/load-pipeline/uuid-loader.js +++ b/cocos2d/core/load-pipeline/uuid-loader.js @@ -207,14 +207,14 @@ function loadUuid (item, callback) { json = JSON.parse(item.content); } catch (e) { - return new Error('Uuid Loader: Parse asset [' + item.id + '] failed : ' + e.stack); + return new Error(cc._LogInfos.format(4923, item.id, e.stack)); } } else if (typeof item.content === 'object') { json = item.content; } else { - return new Error('JSON Loader: Input item doesn\'t contain string content'); + return new Error(cc._LogInfos.format(4924)); } var classFinder; @@ -259,7 +259,7 @@ function loadUuid (item, callback) { catch (e) { cc.deserialize.Details.pool.put(tdInfo); var err = CC_JSB ? (e + '\n' + e.stack) : e.stack; - return new Error('Uuid Loader: Deserialize asset [' + item.id + '] failed : ' + err); + return new Error(cc._LogInfos.format(4925, item.id, err)); } asset._uuid = item.uuid; diff --git a/cocos2d/core/platform/CCSys.js b/cocos2d/core/platform/CCSys.js index 46cc1bdbda..777ce45a0a 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -716,7 +716,7 @@ else { sys._checkWebGLRenderMode = function () { if (cc._renderType !== cc.game.RENDER_TYPE_WEBGL) - throw new Error("This feature supports WebGL render mode only."); + throw new Error(cc._LogInfos.format(5202)); }; var _tmpCanvas1 = document.createElement("canvas"), diff --git a/cocos2d/core/platform/_CCClass.js b/cocos2d/core/platform/_CCClass.js index d66de087d1..f27d141901 100644 --- a/cocos2d/core/platform/_CCClass.js +++ b/cocos2d/core/platform/_CCClass.js @@ -174,7 +174,7 @@ cc.defineGetterSetter = function (proto, prop, getter, setter, getterName, sette setter && (desc.set = setter); Object.defineProperty(proto, prop, desc); } else { - throw new Error("browser does not support getters"); + throw new Error(cc._LogInfos.format(3658)); } }; diff --git a/cocos2d/kazmath/gl/matrix.js b/cocos2d/kazmath/gl/matrix.js index 4182cb78c2..0f6647ed6e 100644 --- a/cocos2d/kazmath/gl/matrix.js +++ b/cocos2d/kazmath/gl/matrix.js @@ -106,7 +106,7 @@ math.glMatrixMode = function (mode) { cc.current_stack = math.texture_matrix_stack; break; default: - throw new Error("Invalid matrix mode specified"); //TODO: Proper error handling + throw new Error(cc._LogInfos.format(7908)); //TODO: Proper error handling break; } }; @@ -169,7 +169,7 @@ math.glGetMatrix = function (mode, pOut) { pOut.assignFrom(math.texture_matrix_stack.top); break; default: - throw new Error("Invalid matrix mode specified"); //TODO: Proper error handling + throw new Error(cc._LogInfos.format(7908)); //TODO: Proper error handling break; } }; diff --git a/cocos2d/kazmath/quaternion.js b/cocos2d/kazmath/quaternion.js index fcd9c98b75..18aa9284c5 100644 --- a/cocos2d/kazmath/quaternion.js +++ b/cocos2d/kazmath/quaternion.js @@ -153,7 +153,7 @@ proto.multiply = function(quaternion) { //cc.kmQuaternionMultiply proto.normalize = function(){ //=cc.kmQuaternionNormalize var length = this.length(); if (Math.abs(length) <= cc.math.EPSILON) - throw new Error("current quaternion is an invalid value"); + throw new Error(cc._LogInfos.format(7909)); this.scale(1.0 / length); return this; }; diff --git a/cocos2d/particle/CCPNGReader.js b/cocos2d/particle/CCPNGReader.js index 99da8de84a..1016730039 100644 --- a/cocos2d/particle/CCPNGReader.js +++ b/cocos2d/particle/CCPNGReader.js @@ -161,7 +161,7 @@ var PNGReader = cc._Class.extend({ } this.pos += 4; if (this.pos > this.data.length) { - throw new Error("Incomplete or corrupt PNG file"); + throw new Error(cc._LogInfos.format(6017)); } } }, @@ -262,7 +262,7 @@ var PNGReader = cc._Class.extend({ } break; default: - throw new Error("Invalid filter algorithm: " + data[pos - 1]); + throw new Error(cc._LogInfos.format(6018, data[pos - 1])); } row++; } diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js index 6b7f2d3867..d7f2ee116f 100644 --- a/cocos2d/particle/CCParticleSystem.js +++ b/cocos2d/particle/CCParticleSystem.js @@ -914,7 +914,7 @@ var ParticleSystem = cc.Class({ var self = this; cc.loader.load(file, function (err, content) { if (err || !content) { - throw err || new Error('Unkown error'); + throw err || new Error(cc._LogInfos.format(6029)); } if (!self.isValid) { return; diff --git a/cocos2d/particle/CCTIFFReader.js b/cocos2d/particle/CCTIFFReader.js index 54c16f9420..5113e8e507 100644 --- a/cocos2d/particle/CCTIFFReader.js +++ b/cocos2d/particle/CCTIFFReader.js @@ -65,7 +65,7 @@ var tiffReader = /** @lends tiffReader# */{ this.littleEndian = false; } else { console.log(BOM); - throw TypeError("Invalid byte order value."); + throw TypeError(cc._LogInfos.format(6019)); } return this.littleEndian; @@ -74,7 +74,7 @@ var tiffReader = /** @lends tiffReader# */{ hasTowel: function () { // Check for towel. if (this.getUint16(2) !== 42) { - throw RangeError("You forgot your towel!"); + throw RangeError(cc._LogInfos.format(6020)); return false; } @@ -95,7 +95,7 @@ var tiffReader = /** @lends tiffReader# */{ if (fieldTag in tagNames) { return tagNames[fieldTag]; } else { - console.log("Unknown Field Tag:", fieldTag); + cc.logID(6021, fieldTag); return "Tag" + fieldTag; } }, @@ -175,7 +175,7 @@ var tiffReader = /** @lends tiffReader# */{ var shiftLeft,rawBits; if (totalBits <= 0) { - console.log("No bits requested"); + cc.logID(6023); } else if (totalBits <= 8) { shiftLeft = 24 + bitOffset; rawBits = this.getUint8(newByteOffset); @@ -186,7 +186,7 @@ var tiffReader = /** @lends tiffReader# */{ shiftLeft = bitOffset; rawBits = this.getUint32(newByteOffset); } else { - console.log( "Too many bits requested" ); + cc.logID(6022); } return { @@ -302,7 +302,7 @@ var tiffReader = /** @lends tiffReader# */{ if (numStripOffsetValues === 1) { var stripByteCountValues = [Math.ceil((imageWidth * imageLength * bitsPerPixel) / 8)]; } else { - throw Error("Cannot recover from missing StripByteCounts"); + throw Error(cc._LogInfos.format(6024)); } } @@ -332,7 +332,7 @@ var tiffReader = /** @lends tiffReader# */{ byteOffset = sampleInfo.byteOffset - stripOffset; bitOffset = sampleInfo.bitOffset; - throw RangeError("Cannot handle sub-byte bits per sample"); + throw RangeError(cc._LogInfos.format(6025)); } } @@ -342,7 +342,7 @@ var tiffReader = /** @lends tiffReader# */{ jIncrement = bytesPerPixel; } else { jIncrement = 0; - throw RangeError("Cannot handle sub-byte bits per pixel"); + throw RangeError(cc._LogInfos.format(6026)); } break; @@ -412,7 +412,7 @@ var tiffReader = /** @lends tiffReader# */{ sample++; } } else { - throw RangeError("Cannot handle sub-byte bits per sample"); + throw RangeError(cc._LogInfos.format(6025)); } // Is our pixel complete? @@ -535,7 +535,7 @@ var tiffReader = /** @lends tiffReader# */{ // RGB Color Palette case 3: if (colorMapValues === undefined) { - throw Error("Palette image missing color map"); + throw Error(cc._LogInfos.format(6027)); } var colorMapIndex = pixelSamples[0]; @@ -547,7 +547,7 @@ var tiffReader = /** @lends tiffReader# */{ // Unknown Photometric Interpretation default: - throw RangeError('Unknown Photometric Interpretation:', photometricInterpretation); + throw RangeError(cc._LogInfos.format(6028, photometricInterpretation)); break; } diff --git a/cocos2d/render-texture/CCRenderTexture.js b/cocos2d/render-texture/CCRenderTexture.js index 72f8b336bc..369aa1bd97 100644 --- a/cocos2d/render-texture/CCRenderTexture.js +++ b/cocos2d/render-texture/CCRenderTexture.js @@ -343,7 +343,7 @@ cc.RenderTexture = _ccsg.Node.extend(/** @lends cc.RenderTexture# */{ * @param {Number} format */ saveToFile: function (filePath, format) { - cc.log("saveToFile isn't supported on Cocos2d-Html5"); + cc.logID(7604); }, /** @@ -351,7 +351,7 @@ cc.RenderTexture = _ccsg.Node.extend(/** @lends cc.RenderTexture# */{ * @return {*} */ newCCImage: function (flipImage) { - cc.log("saveToFile isn't supported on cocos2d-html5"); + cc.logID(7605); return null; }, diff --git a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js index 71e1262f75..3e635cd8e6 100644 --- a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js +++ b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js @@ -95,5 +95,5 @@ proto.clearRect = function(x, y, width, height){ }; proto.clearDepth = function(depthValue){ - cc.log("clearDepth isn't supported on Cocos2d-Html5"); + cc.logID(7603); }; diff --git a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js index e2768b6a7d..28e04922e3 100644 --- a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js +++ b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js @@ -136,7 +136,7 @@ proto.updateClearColor = function(clearColor){ }; proto.initWithWidthAndHeight = function(width, height, format, depthStencilFormat){ var node = this._node; if(format === cc.Texture2D.PixelFormat.A8) - cc.log( "cc.RenderTexture._initWithWidthAndHeightForWebGL() : only RGB and RGBA formats are valid for a render texture;"); + cc.logID(7601); var gl = cc._renderContext; this._fullRect = new cc.Rect(0,0, width, height); @@ -206,7 +206,7 @@ proto.initWithWidthAndHeight = function(width, height, format, depthStencilForma // check if it worked (probably worth doing :) ) if(gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE) - cc.log("Could not attach texture to the framebuffer"); + cc.logID(7602); locTexture.setAliasTexParameters(); diff --git a/cocos2d/shaders/CCGLProgram.js b/cocos2d/shaders/CCGLProgram.js index 004b1f23d7..75b95a18e1 100644 --- a/cocos2d/shaders/CCGLProgram.js +++ b/cocos2d/shaders/CCGLProgram.js @@ -194,9 +194,9 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ */ initWithVertexShaderFilename: function (vShaderFilename, fShaderFileName) { var vertexSource = cc.loader.getRes(vShaderFilename); - if (!vertexSource) throw new Error("Please load the resource firset : " + vShaderFilename); + if (!vertexSource) throw new Error(cc._LogInfos.format(8106, vShaderFilename)); var fragmentSource = cc.loader.getRes(fShaderFileName); - if (!fragmentSource) throw new Error("Please load the resource firset : " + fShaderFileName); + if (!fragmentSource) throw new Error(cc._LogInfos.format(8106, fShaderFileName)); return this.initWithVertexShaderByteArray(vertexSource, fragmentSource); }, @@ -296,9 +296,9 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ */ getUniformLocationForName: function (name) { if (!name) - throw new Error("cc.GLProgram.getUniformLocationForName(): uniform name should be non-null"); + throw new Error(cc._LogInfos.format(8107)); if (!this._programObj) - throw new Error("cc.GLProgram.getUniformLocationForName(): Invalid operation. Cannot get uniform location when program is not initialized"); + throw new Error(cc._LogInfos.format(8108)); var location = this._uniforms[name] || this._glContext.getUniformLocation(this._programObj, name); return location; @@ -682,7 +682,7 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ _setUniformForMVPMatrixWithMat4: function(modelViewMatrix){ if(!modelViewMatrix) - throw new Error("modelView matrix is undefined."); + throw new Error(cc._LogInfos.format(8109)); this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_MVMATRIX], false, modelViewMatrix.mat); this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_PMATRIX], false, math.projection_matrix_stack.top.mat); }, diff --git a/cocos2d/tilemap/CCSGTMXLayer.js b/cocos2d/tilemap/CCSGTMXLayer.js index 0afcb7eccf..29b44aaef8 100644 --- a/cocos2d/tilemap/CCSGTMXLayer.js +++ b/cocos2d/tilemap/CCSGTMXLayer.js @@ -473,7 +473,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ */ getTileAt: function (pos, y) { if (pos === undefined) { - throw new Error("_ccsg.TMXLayer.getTileAt(): pos should be non-null"); + throw new Error(cc._LogInfos.format(7226)); } var x = pos; if (y === undefined) { @@ -481,7 +481,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ y = pos.y; } if (x >= this._layerSize.width || y >= this._layerSize.height || x < 0 || y < 0) { - throw new Error("_ccsg.TMXLayer.getTileAt(): invalid position"); + throw new Error(cc._LogInfos.format(7227)); } if (!this.tiles) { cc.logID(7204); @@ -523,7 +523,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ */ getTileGIDAt:function (pos, y) { if (pos === undefined) { - throw new Error("_ccsg.TMXLayer.getTileGIDAt(): pos should be non-null"); + throw new Error(cc._LogInfos.format(7228)); } var x = pos; if (y === undefined) { @@ -531,7 +531,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ y = pos.y; } if (x >= this._layerSize.width || y >= this._layerSize.height || x < 0 || y < 0) { - throw new Error("_ccsg.TMXLayer.getTileGIDAt(): invalid position"); + throw new Error(cc._LogInfos.format(7229)); } if (!this.tiles) { cc.logID(7205); @@ -558,7 +558,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ */ setTileGID: function(gid, posOrX, flagsOrY, flags) { if (posOrX === undefined) { - throw new Error("_ccsg.TMXLayer.setTileGID(): pos should be non-null"); + throw new Error(cc._LogInfos.format(7230)); } var pos; if (flags !== undefined || !(posOrX instanceof cc.Vec2)) { @@ -572,7 +572,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ 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("_ccsg.TMXLayer.setTileGID(): invalid position"); + throw new Error(cc._LogInfos.format(7231)); } if (!this.tiles) { cc.logID(7206); @@ -638,11 +638,11 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ */ getTileFlagsAt:function (pos, y) { if(!pos) - throw new Error("_ccsg.TMXLayer.getTileFlagsAt(): pos should be non-null"); + throw new Error(cc._LogInfos.format(7232)); if(y !== undefined) pos = cc.p(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"); + throw new Error(cc._LogInfos.format(7233)); if(!this.tiles){ cc.logID(7208); return null; @@ -664,13 +664,13 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ */ removeTileAt:function (pos, y) { if (!pos) { - throw new Error("_ccsg.TMXLayer.removeTileAt(): pos should be non-null"); + throw new Error(cc._LogInfos.format(7234)); } if (y !== undefined) { pos = cc.p(pos, y); } if (pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) { - throw new Error("_ccsg.TMXLayer.removeTileAt(): invalid position"); + throw new Error(cc._LogInfos.format(7235)); } if (!this.tiles) { cc.logID(7209); diff --git a/cocos2d/tilemap/CCSGTMXTiledMap.js b/cocos2d/tilemap/CCSGTMXTiledMap.js index 532a84dd00..08f2e7a4e3 100644 --- a/cocos2d/tilemap/CCSGTMXTiledMap.js +++ b/cocos2d/tilemap/CCSGTMXTiledMap.js @@ -307,7 +307,7 @@ _ccsg.TMXTiledMap = _ccsg.Node.extend(/** @lends _ccsg.TMXTiledMap# */{ */ getLayer:function (layerName) { if(!layerName || layerName.length === 0) - throw new Error("_ccsg.TMXTiledMap.getLayer(): layerName should be non-null or non-empty string."); + throw new Error(cc._LogInfos.format(7224)); var locChildren = this._children; for (var i = 0; i < locChildren.length; i++) { var layer = locChildren[i]; @@ -325,7 +325,7 @@ _ccsg.TMXTiledMap = _ccsg.Node.extend(/** @lends _ccsg.TMXTiledMap# */{ */ getObjectGroup:function (groupName) { if(!groupName || groupName.length === 0) - throw new Error("_ccsg.TMXTiledMap.getObjectGroup(): groupName should be non-null or non-empty string."); + throw new Error(cc._LogInfos.format(7225)); var locChildren = this._children; for (var i = 0; i < locChildren.length; i++) { var group = locChildren[i]; diff --git a/cocos2d/tilemap/CCTiledLayer.js b/cocos2d/tilemap/CCTiledLayer.js index 39e256c1b6..7818ef55cd 100644 --- a/cocos2d/tilemap/CCTiledLayer.js +++ b/cocos2d/tilemap/CCTiledLayer.js @@ -201,7 +201,7 @@ var TiledLayer = cc.Class({ setTileGID: function(gid, posOrX, flagsOrY, flags) { if (this._sgNode) { if(posOrX === undefined) - throw new Error("_ccsg.TMXLayer.setTileGID(): pos should be non-null"); + throw new Error(cc._LogInfos.format(7223)); var pos; if (flags !== undefined || !(posOrX instanceof cc.Vec2)) { // four parameters or posOrX is not a Vec2 object diff --git a/cocos2d/tilemap/editor/tiled-map.js b/cocos2d/tilemap/editor/tiled-map.js index 43a9e16802..5cf4244ff0 100644 --- a/cocos2d/tilemap/editor/tiled-map.js +++ b/cocos2d/tilemap/editor/tiled-map.js @@ -12,7 +12,7 @@ const TMX_ENCODING = { encoding: 'utf-8' }; function searchDependFiles(tmxFile, tmxFileData, cb) { var doc = new DOMParser().parseFromString(tmxFileData); if (!doc) { - return cb(new Error(`Parse ${tmxFile} failed.`)); + return cb(new Error(cc._LogInfos.format(7222, tmxFile))); } var textures = []; From c89c1e49763120c03842987c96cbdd4e0fcaacc6 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Fri, 15 Dec 2017 18:03:14 +0800 Subject: [PATCH 080/127] update eventManager code for CCNode --- cocos2d/core/CCNode.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 4f6594c908..35afd45c5d 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -1158,7 +1158,7 @@ var Node = cc.Class({ if (ActionManagerExist) { cc.director.getActionManager().pauseTarget(this); } - cc.eventManager.pauseTarget(this); + eventManager.pauseTarget(this); } var children = this._children; From 2223dcd0c89b805d2a13caacf17bf959c993dc5a Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Mon, 18 Dec 2017 11:09:48 +0800 Subject: [PATCH 081/127] refine code --- CCDebugger.js | 22 ++++--------- DebugInfos.js | 33 +++++++++---------- cocos2d/actions/CCAction.js | 4 +-- cocos2d/actions/CCActionCatmullRom.js | 2 +- cocos2d/actions/CCActionEase.js | 2 +- cocos2d/actions/CCActionInterval.js | 12 +++---- cocos2d/actions/CCActionManager.js | 4 +-- cocos2d/animation/playable.js | 2 +- cocos2d/core/CCConfiguration.js | 2 +- cocos2d/core/CCDrawingPrimitivesCanvas.js | 4 +-- cocos2d/core/CCDrawingPrimitivesWebGL.js | 2 +- cocos2d/core/CCGame.js | 2 +- cocos2d/core/components/CCRendererInSG.js | 2 +- cocos2d/core/event-manager/CCEventManager.js | 2 +- cocos2d/core/load-pipeline/asset-loader.js | 2 +- .../core/load-pipeline/audio-downloader.js | 4 +-- cocos2d/core/load-pipeline/downloader.js | 6 ++-- cocos2d/core/load-pipeline/uuid-loader.js | 6 ++-- cocos2d/core/platform/CCSys.js | 2 +- cocos2d/core/platform/_CCClass.js | 2 +- cocos2d/kazmath/gl/matrix.js | 4 +-- cocos2d/kazmath/quaternion.js | 2 +- cocos2d/particle/CCPNGReader.js | 4 +-- cocos2d/particle/CCParticleSystem.js | 2 +- cocos2d/particle/CCTIFFReader.js | 16 ++++----- cocos2d/shaders/CCGLProgram.js | 10 +++--- cocos2d/tilemap/CCSGTMXLayer.js | 20 +++++------ cocos2d/tilemap/CCSGTMXTiledMap.js | 4 +-- cocos2d/tilemap/CCTiledLayer.js | 2 +- cocos2d/tilemap/editor/tiled-map.js | 2 +- 30 files changed, 86 insertions(+), 97 deletions(-) diff --git a/CCDebugger.js b/CCDebugger.js index b7e4ef1a0e..7e8598e559 100644 --- a/CCDebugger.js +++ b/CCDebugger.js @@ -329,26 +329,18 @@ cc._throw = CC_EDITOR ? Editor.error : function (error) { } }; -var errorMapUrl = 'https://github.com/cocos-creator/engine/blob/master/EngineErrorMap.md'; - function genLogFunc(func, type) { return function (id) { 'use strict'; + var msg = cc._LogInfos.raw(id, type); if (arguments.length === 1) { - CC_DEBUG ? func(cc._LogInfos[id]) : func(type + ' ' + id + ', please go to ' + errorMapUrl + '#' + id + ' to see details.'); - return; + func(msg); } - if (CC_DEBUG) { - let argsArr = cc.js.shiftArguments.apply(null, arguments); - func.apply(cc, [cc._LogInfos[id]].concat(argsArr)); - } else { - var msg = ''; - if (arguments.length === 2) { - msg = 'Arguments: ' + arguments[1]; - } else if (arguments.length > 2) { - msg = 'Arguments: ' + cc.js.shiftArguments.apply(null, arguments).join(', '); - } - func(type + ' ' + id + ', please go to ' + errorMapUrl + '#' + id + ' to see details. ' + msg); + else if (arguments.length === 2) { + func(CC_DEBUG ? cc.js.formatStr(msg, arguments[1]) : msg + ' Arguments: ' + arguments[1]); + } + else { + func(cc._LogInfos.e(msg, cc.js.shiftArguments.apply(null, arguments))); } }; } diff --git a/DebugInfos.js b/DebugInfos.js index 5d3b748a4f..960c57b5ed 100644 --- a/DebugInfos.js +++ b/DebugInfos.js @@ -37,7 +37,6 @@ if (CC_DEBUG) { //configuration: 1100 "1100": "Expected 'data' dict, but not found. Config file: %s", //loadConfigFile "1101": "Please load the resource first : %s", //loadConfigFile_2 - "1102": "Please load the resource first : %s", // loadConfigFile //Director: 1200 "1200": "cocos2d: Director: Error in gettimeofday", //resume "1201": "cocos2d: Director: unrecognized projection", //setProjection @@ -627,9 +626,6 @@ if (CC_DEBUG) { "7233": "_ccsg.TMXLayer.getTileFlagsAt(): invalid position",//CCSGTMXLayer getTileFlagsAt "7234": "_ccsg.TMXLayer.removeTileAt(): pos should be non-null",//CCSGTMXLayer removeTileAt "7235": "_ccsg.TMXLayer.removeTileAt(): invalid position",//CCSGTMXLayer removeTileAt - "7236": "_ccsg.TMXLayer.getTileAt(): pos should be non-null",//CCSGTMXLayer getTileAt - "7237": "_ccsg.TMXLayer.getTileAt(): pos should be non-null",//CCSGTMXLayer getTileAt - //Wrapper: 7300 "7300": "The new selected must be number", //CheckBox.selected "7301": "The new bake must be boolean", //layer @@ -707,24 +703,25 @@ if (CC_DEBUG) { var errorMapUrl = 'https://github.com/cocos-creator/engine/blob/master/EngineErrorMap.md'; - cc._LogInfos.format = function (id) { - var type = 'error'; + function raw (id, type) { + return CC_DEBUG ? cc._LogInfos[id] : `${type} ${id}, please go to ${errorMapUrl}#${id} to see details.`; + } + + function format (msg, argsArray) { + return CC_DEBUG ? cc.js.formatStr.apply(null, [msg].concat(argsArray)) : msg + ' Arguments: ' + argsArray.join(', '); + } + + cc._LogInfos.e = function () { + var msg = raw(arguments[0], 'ERROR'); if (arguments.length === 1) { - return CC_DEBUG ? cc._LogInfos[id] : type + ' ' + id + ', please go to ' + errorMapUrl + '#' + id + ' to see details.' + return msg; } - if (CC_DEBUG) { - let argsArr = cc.js.shiftArguments.apply(null, arguments); - return cc._LogInfos[id].concat(argsArr); - } else { - var msg = ''; - if (arguments.length === 2) { - msg = 'Arguments: ' + arguments[1]; - } else if (arguments.length > 2) { - msg = 'Arguments: ' + cc.js.shiftArguments.apply(null, arguments).join(', '); - } - return type + ' ' + id + ', please go to ' + errorMapUrl + '#' + id + ' to see details. ' + msg; + else { + return format(msg, cc.js.shiftArguments.apply(null, arguments)); } }; + cc._LogInfos.raw = raw; + cc._LogInfos.format = format; } // module.exports = false; diff --git a/cocos2d/actions/CCAction.js b/cocos2d/actions/CCAction.js index 9d766d32a2..5f4c168970 100644 --- a/cocos2d/actions/CCAction.js +++ b/cocos2d/actions/CCAction.js @@ -300,7 +300,7 @@ cc.Speed = cc.Action.extend({ */ initWithAction:function (action, speed) { if(!action) - throw new Error(cc._LogInfos.format(1021)); + throw new Error(cc._LogInfos.e(1021)); this._innerAction = action; this._speed = speed; @@ -489,7 +489,7 @@ cc.Follow = cc.Action.extend({ */ initWithTarget:function (followedNode, rect) { if(!followedNode) - throw new Error(cc._LogInfos.format(1022)); + throw new Error(cc._LogInfos.e(1022)); var _this = this; rect = rect || cc.rect(0, 0, 0, 0); diff --git a/cocos2d/actions/CCActionCatmullRom.js b/cocos2d/actions/CCActionCatmullRom.js index a065f8d5ae..22c2cdb6c0 100644 --- a/cocos2d/actions/CCActionCatmullRom.js +++ b/cocos2d/actions/CCActionCatmullRom.js @@ -129,7 +129,7 @@ cc.CardinalSplineTo = cc.ActionInterval.extend({ initWithDuration:function (duration, points, tension) { if(!points || points.length === 0) - throw new Error(cc._LogInfos.format(1024)); + throw new Error(cc._LogInfos.e(1024)); if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this.setPoints(points); diff --git a/cocos2d/actions/CCActionEase.js b/cocos2d/actions/CCActionEase.js index cead0e1139..86ef3a55ee 100644 --- a/cocos2d/actions/CCActionEase.js +++ b/cocos2d/actions/CCActionEase.js @@ -51,7 +51,7 @@ cc.ActionEase = cc.ActionInterval.extend({ */ initWithAction:function (action) { if(!action) - throw new Error(cc._LogInfos.format(1023)); + throw new Error(cc._LogInfos.e(1023)); if (this.initWithDuration(action.getDuration())) { this._inner = action; diff --git a/cocos2d/actions/CCActionInterval.js b/cocos2d/actions/CCActionInterval.js index f724d0bb4b..8b11190582 100644 --- a/cocos2d/actions/CCActionInterval.js +++ b/cocos2d/actions/CCActionInterval.js @@ -341,7 +341,7 @@ cc.Sequence = cc.ActionInterval.extend({ */ initWithTwoActions:function (actionOne, actionTwo) { if(!actionOne || !actionTwo) - throw new Error(cc._LogInfos.format(1025)); + throw new Error(cc._LogInfos.e(1025)); var d = actionOne._duration + actionTwo._duration; this.initWithDuration(d); @@ -649,7 +649,7 @@ cc.RepeatForever = cc.ActionInterval.extend({ */ initWithAction:function (action) { if(!action) - throw new Error(cc._LogInfos.format(1026)); + throw new Error(cc._LogInfos.e(1026)); this._innerAction = action; return true; @@ -767,7 +767,7 @@ cc.Spawn = cc.ActionInterval.extend({ */ initWithTwoActions:function (action1, action2) { if(!action1 || !action2) - throw new Error(cc._LogInfos.format(1027)); + throw new Error(cc._LogInfos.e(1027)); var ret = false; @@ -2473,9 +2473,9 @@ cc.ReverseTime = cc.ActionInterval.extend({ */ initWithAction:function (action) { if(!action) - throw new Error(cc._LogInfos.format(1028)); + throw new Error(cc._LogInfos.e(1028)); if(action === this._other) - throw new Error(cc._LogInfos.format(1029)); + throw new Error(cc._LogInfos.e(1029)); if (cc.ActionInterval.prototype.initWithDuration.call(this, action._duration)) { // Don't leak if action is reused @@ -2580,7 +2580,7 @@ cc.Animate = cc.ActionInterval.extend({ */ initWithAnimation:function (animation) { if(!animation) - throw new Error(cc._LogInfos.format(1030)); + throw new Error(cc._LogInfos.e(1030)); var singleDuration = animation.getDuration(); if (this.initWithDuration(singleDuration * animation.getLoops())) { this._nextFrame = 0; diff --git a/cocos2d/actions/CCActionManager.js b/cocos2d/actions/CCActionManager.js index d0e3e14582..ad5ead35f5 100644 --- a/cocos2d/actions/CCActionManager.js +++ b/cocos2d/actions/CCActionManager.js @@ -114,9 +114,9 @@ cc.ActionManager = cc._Class.extend(/** @lends cc.ActionManager# */{ */ addAction:function (action, target, paused) { if(!action) - throw new Error(cc._LogInfos.format(1000)); + throw new Error(cc._LogInfos.e(1000)); if(!target) - throw new Error(cc._LogInfos.format(1000)); + throw new Error(cc._LogInfos.e(1000)); //check if the action target already exists var element = this._hashTargets[target.__instanceId]; diff --git a/cocos2d/animation/playable.js b/cocos2d/animation/playable.js index 5ae9660ecf..3a3240e1a4 100644 --- a/cocos2d/animation/playable.js +++ b/cocos2d/animation/playable.js @@ -80,7 +80,7 @@ prototype.play = function () { this.onResume(); } else { - this.onError(cc._LogInfos.format(3912)); + this.onError(cc._LogInfos.e(3912)); } } else { diff --git a/cocos2d/core/CCConfiguration.js b/cocos2d/core/CCConfiguration.js index d4334e0b91..63979b6ca9 100644 --- a/cocos2d/core/CCConfiguration.js +++ b/cocos2d/core/CCConfiguration.js @@ -267,7 +267,7 @@ cc.configuration = /** @lends cc.configuration# */{ if(!this._inited) this._init(); var dict = cc.loader.getRes(url); - if(!dict) throw new Error(cc._LogInfos.format(1102, url)); + if(!dict) throw new Error(cc._LogInfos.e(1102, url)); cc.assertID(dict, 1101, url); var getDatas = dict["data"]; diff --git a/cocos2d/core/CCDrawingPrimitivesCanvas.js b/cocos2d/core/CCDrawingPrimitivesCanvas.js index d7c16e1001..ed0de2ab15 100644 --- a/cocos2d/core/CCDrawingPrimitivesCanvas.js +++ b/cocos2d/core/CCDrawingPrimitivesCanvas.js @@ -143,7 +143,7 @@ var DrawingPrimitiveCanvas = cc._Class.extend({ return; if (vertices.length < 3) - throw new Error(cc._LogInfos.format(6704)); + throw new Error(cc._LogInfos.e(6704)); var firstPoint = vertices[0], locContext = this._renderContext.getContext(); var locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY(); @@ -319,7 +319,7 @@ var DrawingPrimitiveCanvas = cc._Class.extend({ destSize.width, destSize.height); break; default: - throw new Error(cc._LogInfos.format(6705)); + throw new Error(cc._LogInfos.e(6705)); break; } }, diff --git a/cocos2d/core/CCDrawingPrimitivesWebGL.js b/cocos2d/core/CCDrawingPrimitivesWebGL.js index 3112d22af9..2f8ccf6a6d 100644 --- a/cocos2d/core/CCDrawingPrimitivesWebGL.js +++ b/cocos2d/core/CCDrawingPrimitivesWebGL.js @@ -44,7 +44,7 @@ var DrawingPrimitiveWebGL = cc._Class.extend({ */ ctor:function (ctx) { if (cc.sys.platform !== cc.sys.WECHAT_GAME && !ctx instanceof WebGLRenderingContext) - throw new Error(cc._LogInfos.format(6703)); + throw new Error(cc._LogInfos.e(6703)); this._renderContext = ctx; this._colorArray = new Float32Array([1.0, 1.0, 1.0, 1.0]); diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index 8ed336ec85..bc1b88e0c3 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -650,7 +650,7 @@ var game = { if (this._rendererInitialized) return; if (!cc._supportRender) { - throw new Error(cc._LogInfos.format(3820, this.config[this.CONFIG_KEY.renderMode])); + throw new Error(cc._LogInfos.e(3820, this.config[this.CONFIG_KEY.renderMode])); } var el = this.config[game.CONFIG_KEY.id], diff --git a/cocos2d/core/components/CCRendererInSG.js b/cocos2d/core/components/CCRendererInSG.js index 620679cfca..81d9fe5156 100644 --- a/cocos2d/core/components/CCRendererInSG.js +++ b/cocos2d/core/components/CCRendererInSG.js @@ -96,7 +96,7 @@ var RendererInSG = cc.Class({ _replaceSgNode: function (sgNode) { if (CC_EDITOR && !(sgNode instanceof _ccsg.Node)) { - throw new Error(cc._LogInfos.format(1636)); + throw new Error(cc._LogInfos.e(1636)); } var node = this.node; diff --git a/cocos2d/core/event-manager/CCEventManager.js b/cocos2d/core/event-manager/CCEventManager.js index f03992bdd8..346ba3291b 100644 --- a/cocos2d/core/event-manager/CCEventManager.js +++ b/cocos2d/core/event-manager/CCEventManager.js @@ -1053,7 +1053,7 @@ var eventManager = { this._updateDirtyFlagForSceneGraph(); this._inDispatch++; if(!event || !event.getType) - throw new Error(cc._LogInfos.format(3511)); + throw new Error(cc._LogInfos.e(3511)); if (event.getType().startsWith(cc.Event.TOUCH)) { this._dispatchTouchEvent(event); this._inDispatch--; diff --git a/cocos2d/core/load-pipeline/asset-loader.js b/cocos2d/core/load-pipeline/asset-loader.js index af28842956..1e0f65550b 100644 --- a/cocos2d/core/load-pipeline/asset-loader.js +++ b/cocos2d/core/load-pipeline/asset-loader.js @@ -54,7 +54,7 @@ AssetLoader.prototype.handle = function (item, callback) { if (isRawAsset) { var ext = Path.extname(url).toLowerCase(); if (!ext) { - callback(new Error(cc._LogInfos.format(4931, uuid, url))); + callback(new Error(cc._LogInfos.e(4931, uuid, url))); return; } ext = ext.substr(1); diff --git a/cocos2d/core/load-pipeline/audio-downloader.js b/cocos2d/core/load-pipeline/audio-downloader.js index dc36f49c7c..822587cfe5 100644 --- a/cocos2d/core/load-pipeline/audio-downloader.js +++ b/cocos2d/core/load-pipeline/audio-downloader.js @@ -73,7 +73,7 @@ function loadDomAudio (item, callback) { } function loadWebAudio (item, callback) { - if (!context) callback(new Error(cc._LogInfos.format(4926))); + if (!context) callback(new Error(cc._LogInfos.e(4926))); var request = cc.loader.getXMLHttpRequest(); request.open("GET", item.url, true); @@ -100,7 +100,7 @@ function loadWebAudio (item, callback) { function downloadAudio (item, callback) { if (formatSupport.length === 0) { - return new Error(cc._LogInfos.format(4927)); + return new Error(cc._LogInfos.e(4927)); } item.content = item.url; diff --git a/cocos2d/core/load-pipeline/downloader.js b/cocos2d/core/load-pipeline/downloader.js index 8be727d791..1cb0d9b120 100644 --- a/cocos2d/core/load-pipeline/downloader.js +++ b/cocos2d/core/load-pipeline/downloader.js @@ -63,7 +63,7 @@ function downloadScript (item, callback, isAsync) { s.parentNode.removeChild(s); s.removeEventListener('load', loadHandler, false); s.removeEventListener('error', errorHandler, false); - callback(new Error(cc._LogInfos.format(4928, url))); + callback(new Error(cc._LogInfos.e(4928, url))); } s.addEventListener('load', loadHandler, false); s.addEventListener('error', errorHandler, false); @@ -72,7 +72,7 @@ function downloadScript (item, callback, isAsync) { function downloadWebp (item, callback, isCrossOrigin, img) { if (!cc.sys.capabilities.webp) { - return new Error(cc._LogInfos.format(4929, item.url)); + return new Error(cc._LogInfos.e(4929, item.url)); } return downloadImage(item, callback, isCrossOrigin, img); } @@ -111,7 +111,7 @@ function downloadImage (item, callback, isCrossOrigin, img) { downloadImage(item, callback, false, img); } else { - callback(new Error(cc._LogInfos.format(4930, url))); + callback(new Error(cc._LogInfos.e(4930, url))); } } diff --git a/cocos2d/core/load-pipeline/uuid-loader.js b/cocos2d/core/load-pipeline/uuid-loader.js index d0adb86533..0718d61759 100644 --- a/cocos2d/core/load-pipeline/uuid-loader.js +++ b/cocos2d/core/load-pipeline/uuid-loader.js @@ -207,14 +207,14 @@ function loadUuid (item, callback) { json = JSON.parse(item.content); } catch (e) { - return new Error(cc._LogInfos.format(4923, item.id, e.stack)); + return new Error(cc._LogInfos.e(4923, item.id, e.stack)); } } else if (typeof item.content === 'object') { json = item.content; } else { - return new Error(cc._LogInfos.format(4924)); + return new Error(cc._LogInfos.e(4924)); } var classFinder; @@ -259,7 +259,7 @@ function loadUuid (item, callback) { catch (e) { cc.deserialize.Details.pool.put(tdInfo); var err = CC_JSB ? (e + '\n' + e.stack) : e.stack; - return new Error(cc._LogInfos.format(4925, item.id, err)); + return new Error(cc._LogInfos.e(4925, item.id, err)); } asset._uuid = item.uuid; diff --git a/cocos2d/core/platform/CCSys.js b/cocos2d/core/platform/CCSys.js index 777ce45a0a..e2a1ecb5ac 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -716,7 +716,7 @@ else { sys._checkWebGLRenderMode = function () { if (cc._renderType !== cc.game.RENDER_TYPE_WEBGL) - throw new Error(cc._LogInfos.format(5202)); + throw new Error(cc._LogInfos.e(5202)); }; var _tmpCanvas1 = document.createElement("canvas"), diff --git a/cocos2d/core/platform/_CCClass.js b/cocos2d/core/platform/_CCClass.js index f27d141901..6ae66ef933 100644 --- a/cocos2d/core/platform/_CCClass.js +++ b/cocos2d/core/platform/_CCClass.js @@ -174,7 +174,7 @@ cc.defineGetterSetter = function (proto, prop, getter, setter, getterName, sette setter && (desc.set = setter); Object.defineProperty(proto, prop, desc); } else { - throw new Error(cc._LogInfos.format(3658)); + throw new Error(cc._LogInfos.e(3658)); } }; diff --git a/cocos2d/kazmath/gl/matrix.js b/cocos2d/kazmath/gl/matrix.js index 0f6647ed6e..0d0a4b50ab 100644 --- a/cocos2d/kazmath/gl/matrix.js +++ b/cocos2d/kazmath/gl/matrix.js @@ -106,7 +106,7 @@ math.glMatrixMode = function (mode) { cc.current_stack = math.texture_matrix_stack; break; default: - throw new Error(cc._LogInfos.format(7908)); //TODO: Proper error handling + throw new Error(cc._LogInfos.e(7908)); //TODO: Proper error handling break; } }; @@ -169,7 +169,7 @@ math.glGetMatrix = function (mode, pOut) { pOut.assignFrom(math.texture_matrix_stack.top); break; default: - throw new Error(cc._LogInfos.format(7908)); //TODO: Proper error handling + throw new Error(cc._LogInfos.e(7908)); //TODO: Proper error handling break; } }; diff --git a/cocos2d/kazmath/quaternion.js b/cocos2d/kazmath/quaternion.js index 18aa9284c5..4d8ce63cb6 100644 --- a/cocos2d/kazmath/quaternion.js +++ b/cocos2d/kazmath/quaternion.js @@ -153,7 +153,7 @@ proto.multiply = function(quaternion) { //cc.kmQuaternionMultiply proto.normalize = function(){ //=cc.kmQuaternionNormalize var length = this.length(); if (Math.abs(length) <= cc.math.EPSILON) - throw new Error(cc._LogInfos.format(7909)); + throw new Error(cc._LogInfos.e(7909)); this.scale(1.0 / length); return this; }; diff --git a/cocos2d/particle/CCPNGReader.js b/cocos2d/particle/CCPNGReader.js index 1016730039..6a9a8a0e8b 100644 --- a/cocos2d/particle/CCPNGReader.js +++ b/cocos2d/particle/CCPNGReader.js @@ -161,7 +161,7 @@ var PNGReader = cc._Class.extend({ } this.pos += 4; if (this.pos > this.data.length) { - throw new Error(cc._LogInfos.format(6017)); + throw new Error(cc._LogInfos.e(6017)); } } }, @@ -262,7 +262,7 @@ var PNGReader = cc._Class.extend({ } break; default: - throw new Error(cc._LogInfos.format(6018, data[pos - 1])); + throw new Error(cc._LogInfos.e(6018, data[pos - 1])); } row++; } diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js index d7f2ee116f..66eaf411ca 100644 --- a/cocos2d/particle/CCParticleSystem.js +++ b/cocos2d/particle/CCParticleSystem.js @@ -914,7 +914,7 @@ var ParticleSystem = cc.Class({ var self = this; cc.loader.load(file, function (err, content) { if (err || !content) { - throw err || new Error(cc._LogInfos.format(6029)); + throw err || new Error(cc._LogInfos.e(6029)); } if (!self.isValid) { return; diff --git a/cocos2d/particle/CCTIFFReader.js b/cocos2d/particle/CCTIFFReader.js index 5113e8e507..7a53999419 100644 --- a/cocos2d/particle/CCTIFFReader.js +++ b/cocos2d/particle/CCTIFFReader.js @@ -65,7 +65,7 @@ var tiffReader = /** @lends tiffReader# */{ this.littleEndian = false; } else { console.log(BOM); - throw TypeError(cc._LogInfos.format(6019)); + throw TypeError(cc._LogInfos.e(6019)); } return this.littleEndian; @@ -74,7 +74,7 @@ var tiffReader = /** @lends tiffReader# */{ hasTowel: function () { // Check for towel. if (this.getUint16(2) !== 42) { - throw RangeError(cc._LogInfos.format(6020)); + throw RangeError(cc._LogInfos.e(6020)); return false; } @@ -302,7 +302,7 @@ var tiffReader = /** @lends tiffReader# */{ if (numStripOffsetValues === 1) { var stripByteCountValues = [Math.ceil((imageWidth * imageLength * bitsPerPixel) / 8)]; } else { - throw Error(cc._LogInfos.format(6024)); + throw Error(cc._LogInfos.e(6024)); } } @@ -332,7 +332,7 @@ var tiffReader = /** @lends tiffReader# */{ byteOffset = sampleInfo.byteOffset - stripOffset; bitOffset = sampleInfo.bitOffset; - throw RangeError(cc._LogInfos.format(6025)); + throw RangeError(cc._LogInfos.e(6025)); } } @@ -342,7 +342,7 @@ var tiffReader = /** @lends tiffReader# */{ jIncrement = bytesPerPixel; } else { jIncrement = 0; - throw RangeError(cc._LogInfos.format(6026)); + throw RangeError(cc._LogInfos.e(6026)); } break; @@ -412,7 +412,7 @@ var tiffReader = /** @lends tiffReader# */{ sample++; } } else { - throw RangeError(cc._LogInfos.format(6025)); + throw RangeError(cc._LogInfos.e(6025)); } // Is our pixel complete? @@ -535,7 +535,7 @@ var tiffReader = /** @lends tiffReader# */{ // RGB Color Palette case 3: if (colorMapValues === undefined) { - throw Error(cc._LogInfos.format(6027)); + throw Error(cc._LogInfos.e(6027)); } var colorMapIndex = pixelSamples[0]; @@ -547,7 +547,7 @@ var tiffReader = /** @lends tiffReader# */{ // Unknown Photometric Interpretation default: - throw RangeError(cc._LogInfos.format(6028, photometricInterpretation)); + throw RangeError(cc._LogInfos.e(6028, photometricInterpretation)); break; } diff --git a/cocos2d/shaders/CCGLProgram.js b/cocos2d/shaders/CCGLProgram.js index 75b95a18e1..4e5161b359 100644 --- a/cocos2d/shaders/CCGLProgram.js +++ b/cocos2d/shaders/CCGLProgram.js @@ -194,9 +194,9 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ */ initWithVertexShaderFilename: function (vShaderFilename, fShaderFileName) { var vertexSource = cc.loader.getRes(vShaderFilename); - if (!vertexSource) throw new Error(cc._LogInfos.format(8106, vShaderFilename)); + if (!vertexSource) throw new Error(cc._LogInfos.e(8106, vShaderFilename)); var fragmentSource = cc.loader.getRes(fShaderFileName); - if (!fragmentSource) throw new Error(cc._LogInfos.format(8106, fShaderFileName)); + if (!fragmentSource) throw new Error(cc._LogInfos.e(8106, fShaderFileName)); return this.initWithVertexShaderByteArray(vertexSource, fragmentSource); }, @@ -296,9 +296,9 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ */ getUniformLocationForName: function (name) { if (!name) - throw new Error(cc._LogInfos.format(8107)); + throw new Error(cc._LogInfos.e(8107)); if (!this._programObj) - throw new Error(cc._LogInfos.format(8108)); + throw new Error(cc._LogInfos.e(8108)); var location = this._uniforms[name] || this._glContext.getUniformLocation(this._programObj, name); return location; @@ -682,7 +682,7 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ _setUniformForMVPMatrixWithMat4: function(modelViewMatrix){ if(!modelViewMatrix) - throw new Error(cc._LogInfos.format(8109)); + throw new Error(cc._LogInfos.e(8109)); this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_MVMATRIX], false, modelViewMatrix.mat); this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_PMATRIX], false, math.projection_matrix_stack.top.mat); }, diff --git a/cocos2d/tilemap/CCSGTMXLayer.js b/cocos2d/tilemap/CCSGTMXLayer.js index 29b44aaef8..0ba37797b9 100644 --- a/cocos2d/tilemap/CCSGTMXLayer.js +++ b/cocos2d/tilemap/CCSGTMXLayer.js @@ -473,7 +473,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ */ getTileAt: function (pos, y) { if (pos === undefined) { - throw new Error(cc._LogInfos.format(7226)); + throw new Error(cc._LogInfos.e(7226)); } var x = pos; if (y === undefined) { @@ -481,7 +481,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ y = pos.y; } if (x >= this._layerSize.width || y >= this._layerSize.height || x < 0 || y < 0) { - throw new Error(cc._LogInfos.format(7227)); + throw new Error(cc._LogInfos.e(7227)); } if (!this.tiles) { cc.logID(7204); @@ -523,7 +523,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ */ getTileGIDAt:function (pos, y) { if (pos === undefined) { - throw new Error(cc._LogInfos.format(7228)); + throw new Error(cc._LogInfos.e(7228)); } var x = pos; if (y === undefined) { @@ -531,7 +531,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ y = pos.y; } if (x >= this._layerSize.width || y >= this._layerSize.height || x < 0 || y < 0) { - throw new Error(cc._LogInfos.format(7229)); + throw new Error(cc._LogInfos.e(7229)); } if (!this.tiles) { cc.logID(7205); @@ -558,7 +558,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ */ setTileGID: function(gid, posOrX, flagsOrY, flags) { if (posOrX === undefined) { - throw new Error(cc._LogInfos.format(7230)); + throw new Error(cc._LogInfos.e(7230)); } var pos; if (flags !== undefined || !(posOrX instanceof cc.Vec2)) { @@ -572,7 +572,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ 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(cc._LogInfos.format(7231)); + throw new Error(cc._LogInfos.e(7231)); } if (!this.tiles) { cc.logID(7206); @@ -638,11 +638,11 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ */ getTileFlagsAt:function (pos, y) { if(!pos) - throw new Error(cc._LogInfos.format(7232)); + throw new Error(cc._LogInfos.e(7232)); if(y !== undefined) pos = cc.p(pos, y); if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) - throw new Error(cc._LogInfos.format(7233)); + throw new Error(cc._LogInfos.e(7233)); if(!this.tiles){ cc.logID(7208); return null; @@ -664,13 +664,13 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ */ removeTileAt:function (pos, y) { if (!pos) { - throw new Error(cc._LogInfos.format(7234)); + throw new Error(cc._LogInfos.e(7234)); } if (y !== undefined) { pos = cc.p(pos, y); } if (pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) { - throw new Error(cc._LogInfos.format(7235)); + throw new Error(cc._LogInfos.e(7235)); } if (!this.tiles) { cc.logID(7209); diff --git a/cocos2d/tilemap/CCSGTMXTiledMap.js b/cocos2d/tilemap/CCSGTMXTiledMap.js index 08f2e7a4e3..4dffc2f9c1 100644 --- a/cocos2d/tilemap/CCSGTMXTiledMap.js +++ b/cocos2d/tilemap/CCSGTMXTiledMap.js @@ -307,7 +307,7 @@ _ccsg.TMXTiledMap = _ccsg.Node.extend(/** @lends _ccsg.TMXTiledMap# */{ */ getLayer:function (layerName) { if(!layerName || layerName.length === 0) - throw new Error(cc._LogInfos.format(7224)); + throw new Error(cc._LogInfos.e(7224)); var locChildren = this._children; for (var i = 0; i < locChildren.length; i++) { var layer = locChildren[i]; @@ -325,7 +325,7 @@ _ccsg.TMXTiledMap = _ccsg.Node.extend(/** @lends _ccsg.TMXTiledMap# */{ */ getObjectGroup:function (groupName) { if(!groupName || groupName.length === 0) - throw new Error(cc._LogInfos.format(7225)); + throw new Error(cc._LogInfos.e(7225)); var locChildren = this._children; for (var i = 0; i < locChildren.length; i++) { var group = locChildren[i]; diff --git a/cocos2d/tilemap/CCTiledLayer.js b/cocos2d/tilemap/CCTiledLayer.js index 7818ef55cd..46a38d3e8e 100644 --- a/cocos2d/tilemap/CCTiledLayer.js +++ b/cocos2d/tilemap/CCTiledLayer.js @@ -201,7 +201,7 @@ var TiledLayer = cc.Class({ setTileGID: function(gid, posOrX, flagsOrY, flags) { if (this._sgNode) { if(posOrX === undefined) - throw new Error(cc._LogInfos.format(7223)); + throw new Error(cc._LogInfos.e(7223)); var pos; if (flags !== undefined || !(posOrX instanceof cc.Vec2)) { // four parameters or posOrX is not a Vec2 object diff --git a/cocos2d/tilemap/editor/tiled-map.js b/cocos2d/tilemap/editor/tiled-map.js index 5cf4244ff0..cf0f513cc1 100644 --- a/cocos2d/tilemap/editor/tiled-map.js +++ b/cocos2d/tilemap/editor/tiled-map.js @@ -12,7 +12,7 @@ const TMX_ENCODING = { encoding: 'utf-8' }; function searchDependFiles(tmxFile, tmxFileData, cb) { var doc = new DOMParser().parseFromString(tmxFileData); if (!doc) { - return cb(new Error(cc._LogInfos.format(7222, tmxFile))); + return cb(new Error(cc._LogInfos.e(7222, tmxFile))); } var textures = []; From 5843fdcb6940e7e20bb5f10a5c2aaa7f439663dd Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Mon, 18 Dec 2017 11:18:48 +0800 Subject: [PATCH 082/127] refine code --- DebugInfos.js | 1 - cocos2d/core/components/CCRendererInSG.js | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/DebugInfos.js b/DebugInfos.js index 960c57b5ed..3b51bd2f74 100644 --- a/DebugInfos.js +++ b/DebugInfos.js @@ -113,7 +113,6 @@ if (CC_DEBUG) { "1633": "Internal error, should not remove unknown node from parent.", //parent "1634": "addChild: The child to add must be instance of cc.Node, not %s.", //addChild "1635": "reorderChild: this child is not in children list", // reorderChild - "1636": "Invalid sgNode. It must be an instance of _ccsg.Node", // RendererInSG //AtlasNode: 1700 "1700": "cc.AtlasNode.updateAtlasValues(): Shall be overridden in subclasses", //_updateAtlasValues "1701": "", //_initWithTileFile diff --git a/cocos2d/core/components/CCRendererInSG.js b/cocos2d/core/components/CCRendererInSG.js index 81d9fe5156..7adaed58e1 100644 --- a/cocos2d/core/components/CCRendererInSG.js +++ b/cocos2d/core/components/CCRendererInSG.js @@ -96,7 +96,7 @@ var RendererInSG = cc.Class({ _replaceSgNode: function (sgNode) { if (CC_EDITOR && !(sgNode instanceof _ccsg.Node)) { - throw new Error(cc._LogInfos.e(1636)); + throw new Error("Invalid sgNode. It must be an instance of _ccsg.Node"); } var node = this.node; From 0fa0c98fa5e5b7cff29e9d24bb313d6deb9935ce Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Mon, 18 Dec 2017 14:19:46 +0800 Subject: [PATCH 083/127] fix getDisplayedColor api --- cocos2d/core/CCNode.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index e176721ab3..7da9f198e4 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -1974,8 +1974,10 @@ var Node = cc.Class({ * Returns the displayed color of Node, * the difference between displayed color and color is that displayed color is calculated based on color and parent node's color when cascade color enabled. * !#zh - * 获取节点的显示透明度, - * 显示透明度和透明度之间的不同之处在于显示透明度是基于透明度和父节点透明度启用级连透明度时计算的。 + * 获取节点的显示颜色, + * 显示颜色和颜色之间的不同之处在于当启用级连颜色时, + * 显示颜色是基于自身颜色和父节点颜色计算的。 + * * @method getDisplayedColor * @returns {Color} * @example From ebd147890e53a9ad7e3521cee0cecedb3e19905b Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Tue, 19 Dec 2017 10:42:14 +0800 Subject: [PATCH 084/127] fix ArmatureDisplay addEventListener invalid for fireball/issues/6718 --- extensions/dragonbones/ArmatureDisplay.js | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/extensions/dragonbones/ArmatureDisplay.js b/extensions/dragonbones/ArmatureDisplay.js index 4b873bdf57..1485ddeaae 100644 --- a/extensions/dragonbones/ArmatureDisplay.js +++ b/extensions/dragonbones/ArmatureDisplay.js @@ -398,9 +398,10 @@ dragonBones.ArmatureDisplay = cc.Class({ var self = this; // discard exists sgNode - var listenersBefore = null; + var listenersBefore = null, listenersCacheBefore = null; if (self._sgNode) { listenersBefore = self._sgNode._bubblingListeners; // get the listeners added before + listenersCacheBefore = self._sgNode._hasListenerCache; if (self.node._sizeProvider === self._sgNode) { self.node._sizeProvider = null; } @@ -420,6 +421,7 @@ dragonBones.ArmatureDisplay = cc.Class({ if (listenersBefore) { sgNode._bubblingListeners = listenersBefore; // using the listeners added before + sgNode._hasListenerCache = listenersCacheBefore; if (CC_JSB && !sgNode.hasEventCallback()) { // In JSB, should set event callback of the new sgNode // to make the listeners work well. From 81d0bd8f957430deabb9c55553520144b7c174ba Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Tue, 19 Dec 2017 16:22:20 +0800 Subject: [PATCH 085/127] update getWinSizeInPixels API for fireball/issues/6717 --- cocos2d/core/CCDirector.js | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index 8429d6be1b..244e118e51 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -346,7 +346,10 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ * Returns the size of the OpenGL view in pixels.
* It takes into account any possible rotation (device orientation) of the window.
* On Mac winSize and winSizeInPixels return the same value. - * !#zh 获取视图大小,以像素为单位。 + * (The pixel here refers to the resource resolution. If you want to get the physics resolution of device, you need to use cc.view.getFrameSize()) + * !#zh + * 获取视图大小,以像素为单位(这里的像素指的是资源分辨率。 + * 如果要获取屏幕物理分辨率,需要用 cc.view.getFrameSize()) * @method getWinSizeInPixels * @return {Size} */ From 320a6cfae6a9b5c39f493be8d99fbdfea58a8b3a Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Tue, 19 Dec 2017 17:53:47 +0800 Subject: [PATCH 086/127] fix Container scale strategys bug for fireball/issues/6733 --- cocos2d/core/platform/CCView.js | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index 28a1f931ec..6206572cc0 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -1181,6 +1181,7 @@ cc.ContentStrategy = cc._Class.extend(/** @lends cc.ContentStrategy# */{ else { containerStyle.margin = '0px'; } + containerStyle.padding = "0px"; } }); From 7798ad818b84791bcbc85f289fdf2ba199cd39f0 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Wed, 20 Dec 2017 16:28:45 +0800 Subject: [PATCH 087/127] fix button bug --- cocos2d/core/components/CCButton.js | 8 ++++++++ cocos2d/core/platform/preprocess-class.js | 1 + 2 files changed, 9 insertions(+) diff --git a/cocos2d/core/components/CCButton.js b/cocos2d/core/components/CCButton.js index a4f053c847..cb161d7bf3 100644 --- a/cocos2d/core/components/CCButton.js +++ b/cocos2d/core/components/CCButton.js @@ -311,6 +311,10 @@ var Button = cc.Class({ type: cc.SpriteFrame, displayName: 'Pressed', tooltip: CC_DEV && 'i18n:COMPONENT.button.pressed_sprite', + formerlySerializedAs: 'pressedSprite', + notify: function () { + this._updateState(); + } }, /** @@ -323,6 +327,10 @@ var Button = cc.Class({ type: cc.SpriteFrame, displayName: 'Hover', tooltip: CC_DEV && 'i18n:COMPONENT.button.hover_sprite', + formerlySerializedAs: 'hoverSprite', + notify: function () { + this._updateState(); + } }, /** diff --git a/cocos2d/core/platform/preprocess-class.js b/cocos2d/core/platform/preprocess-class.js index b30ad221fe..19deed93ee 100644 --- a/cocos2d/core/platform/preprocess-class.js +++ b/cocos2d/core/platform/preprocess-class.js @@ -33,6 +33,7 @@ var SerializableAttrs = { serializable: {}, editorOnly: {}, rawType: {}, + formerlySerializedAs: {} }; var TYPO_TO_CORRECT_DEV = CC_DEV && { From f85d440371c55f9665a7a389854c5fc80a47814f Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Thu, 21 Dec 2017 10:07:22 +0800 Subject: [PATCH 088/127] add deprecated to getWinSizeInPixels --- cocos2d/core/CCDirector.js | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index 244e118e51..89ae045750 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -352,6 +352,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ * 如果要获取屏幕物理分辨率,需要用 cc.view.getFrameSize()) * @method getWinSizeInPixels * @return {Size} + * @deprecated */ getWinSizeInPixels: function () { return cc.size(this._winSizeInPoints.width * this._contentScaleFactor, this._winSizeInPoints.height * this._contentScaleFactor); From 1af150c107c4bf67eb1c5ac262aaafa1513953da Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Thu, 21 Dec 2017 11:11:46 +0800 Subject: [PATCH 089/127] fix eventManager error for unit test --- cocos2d/core/event-manager/index.js | 5 +++++ test/qunit/unit-es5/_init.js | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/cocos2d/core/event-manager/index.js b/cocos2d/core/event-manager/index.js index 1f56749caa..a90e2c50b5 100644 --- a/cocos2d/core/event-manager/index.js +++ b/cocos2d/core/event-manager/index.js @@ -36,3 +36,8 @@ else { } module.exports = eventManager; + +if (CC_TEST) { + cc._Test.eventManager = eventManager; +} + diff --git a/test/qunit/unit-es5/_init.js b/test/qunit/unit-es5/_init.js index d22988ba1a..4d2926c200 100644 --- a/test/qunit/unit-es5/_init.js +++ b/test/qunit/unit-es5/_init.js @@ -201,7 +201,7 @@ function _resetGame (w, h) { var size = view.getDesignResolutionSize(); view.setDesignResolutionSize(size.width, size.height, cc.ResolutionPolicy.SHOW_ALL); - cc.eventManager.dispatchCustomEvent('canvas-resize'); + cc._Test.eventManager.dispatchCustomEvent('canvas-resize'); } cc.director.purgeDirector(); cc.loader.releaseAll(); From 2d0bf722ee4ed60fa3bc5e313d0caa0cf396ba7f Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 21 Dec 2017 00:00:12 +0800 Subject: [PATCH 090/127] refine web hide event and support Taobao --- cocos2d/core/CCGame.js | 69 +++++++++++++++++++++++++----------------- 1 file changed, 41 insertions(+), 28 deletions(-) diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index bc1b88e0c3..253a616929 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -739,58 +739,71 @@ var game = { }, _initEvents: function () { - var win = window, hidden, visibilityChange, _undef = "undefined"; + var win = window, hiddenPropName; // register system events if (this.config[this.CONFIG_KEY.registerSystemEvent]) inputManager.registerSystemEvent(this.canvas); if (typeof document.hidden !== 'undefined') { - hidden = "hidden"; + hiddenPropName = "hidden"; } else if (typeof document.mozHidden !== 'undefined') { - hidden = "mozHidden"; + hiddenPropName = "mozHidden"; } else if (typeof document.msHidden !== 'undefined') { - hidden = "msHidden"; + hiddenPropName = "msHidden"; } else if (typeof document.webkitHidden !== 'undefined') { - hidden = "webkitHidden"; + hiddenPropName = "webkitHidden"; } - var changeList = [ - "visibilitychange", - "mozvisibilitychange", - "msvisibilitychange", - "webkitvisibilitychange", - "qbrowserVisibilityChange" - ]; - var onHidden = function () { - game.emit(game.EVENT_HIDE, game); - }; - var onShow = function () { - game.emit(game.EVENT_SHOW, game); - }; + var hidden = false; - if (hidden) { + function onHidden () { + if (!hidden) { + hidden = true; + game.emit(game.EVENT_HIDE, game); + } + } + function onShown () { + if (hidden) { + hidden = false; + game.emit(game.EVENT_SHOW, game); + } + } + + if (hiddenPropName) { + var changeList = [ + "visibilitychange", + "mozvisibilitychange", + "msvisibilitychange", + "webkitvisibilitychange", + "qbrowserVisibilityChange" + ]; for (var i = 0; i < changeList.length; i++) { document.addEventListener(changeList[i], function (event) { - var visible = document[hidden]; + var visible = document[hiddenPropName]; // QQ App visible = visible || event["hidden"]; - if (visible) onHidden(); - else onShow(); - }, false); + if (visible) + onHidden(); + else + onShown(); + }); } } else { - win.addEventListener("blur", onHidden, false); - win.addEventListener("focus", onShow, false); + win.addEventListener("blur", onHidden); + win.addEventListener("focus", onShown); } if (navigator.userAgent.indexOf("MicroMessenger") > -1) { - win.onfocus = function(){ onShow() }; + win.onfocus = onShown; } if ("onpageshow" in window && "onpagehide" in window) { - win.addEventListener("pagehide", onHidden, false); - win.addEventListener("pageshow", onShow, false); + win.addEventListener("pagehide", onHidden); + win.addEventListener("pageshow", onShown); + // Taobao UIWebKit + document.addEventListener("pagehide", onHidden); + document.addEventListener("pageshow", onShown); } this.on(game.EVENT_HIDE, function () { From 0e93e98c281485086c52e49d7135d40f31c5b7f9 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Fri, 22 Dec 2017 09:57:09 +0800 Subject: [PATCH 091/127] fix label warp bug, The first line should not remove the space --- cocos2d/core/label/CCTextUtils.js | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/cocos2d/core/label/CCTextUtils.js b/cocos2d/core/label/CCTextUtils.js index 0a698e0058..83679d63c1 100644 --- a/cocos2d/core/label/CCTextUtils.js +++ b/cocos2d/core/label/CCTextUtils.js @@ -296,18 +296,30 @@ var TextUtils = { sText = text.substr(0, fuzzyLen); } } - sText = sText.trim(); - if (sText.length > 0) { + + // The first line And do not wrap should not remove the space + if (wrappedWords.length === 0 && (sLine === '' && tmpText === '')) { wrappedWords.push(sText); } + else { + sText = sText.trim(); + if (sText.length > 0) { + wrappedWords.push(sText); + } + } text = sLine || tmpText; allWidth = measureText(text); } - text = text.trim(); - if (text.length > 0) { + + if (wrappedWords.length === 0) { wrappedWords.push(text); } - + else { + text = text.trim(); + if (text.length > 0) { + wrappedWords.push(text); + } + } return wrappedWords; }, From 20e9a1020c7423cbab3e28de44aa839e67548b55 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Fri, 22 Dec 2017 18:06:34 +0800 Subject: [PATCH 092/127] add gulp build-html5-preview-dev to optimize build time for development preview --- gulp/tasks/engine.js | 37 +++++++++++++++++++++++-------------- gulpfile.js | 4 ++++ 2 files changed, 27 insertions(+), 14 deletions(-) diff --git a/gulp/tasks/engine.js b/gulp/tasks/engine.js index ef30009c4a..47c835300f 100644 --- a/gulp/tasks/engine.js +++ b/gulp/tasks/engine.js @@ -182,26 +182,35 @@ exports.buildCocosJsMin = function (sourceFile, outputFile, excludes, callback, return bundler.on('end', callback); }; -exports.buildPreview = function (sourceFile, outputFile, callback) { +exports.buildPreview = function (sourceFile, outputFile, callback, devMode) { + var cacheDir = devMode && Path.resolve(Path.dirname(outputFile), '.cache/preview-compile-cache'); var outFile = Path.basename(outputFile); var outDir = Path.dirname(outputFile); - var bundler = createBundler(sourceFile); - bundler.bundle() + var bundler = createBundler(sourceFile, { + cacheDir: cacheDir, + sourcemaps: !devMode + }); + var bundler = bundler + .bundle() .on('error', HandleErrors.handler) .pipe(HandleErrors()) .pipe(Source(outFile)) - .pipe(Buffer()) - .pipe(Sourcemaps.init({loadMaps: true})) - .pipe(Minify(Utils.getUglifyOptions('preview', false, false))) - .pipe(Optimizejs({ - sourceMap: false - })) - .pipe(Sourcemaps.write('./', { - sourceRoot: '../', - includeContent: false, - addComment: true - })) + .pipe(Buffer()); + if (!devMode) { + bundler = bundler + .pipe(Sourcemaps.init({loadMaps: true})) + .pipe(Minify(Utils.getUglifyOptions('preview', false, false))) + .pipe(Optimizejs({ + sourceMap: false + })) + .pipe(Sourcemaps.write('./', { + sourceRoot: '../', + includeContent: false, + addComment: true + })); + } + bundler .pipe(Gulp.dest(outDir)) .on('end', callback); }; diff --git a/gulpfile.js b/gulpfile.js index 7667e7ea61..0eaee3737c 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -50,6 +50,10 @@ gulp.task('build-html5-preview', function (done) { Engine.buildPreview('./index.js', './bin/cocos2d-js-for-preview.js', done); }); +gulp.task('build-html5-preview-dev', function (done) { + Engine.buildPreview('./index.js', './bin/cocos2d-js-for-preview.js', done, true); +}); + gulp.task('build-html5', ['build-html5-preview', 'build-html5-dev', 'build-html5-min']); gulp.task('build-jsb-dev', function (done) { From b254c4991b70145c8c8250dba81dfdcb8c255835 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Sun, 24 Dec 2017 00:22:40 +0800 Subject: [PATCH 093/127] add prefab option to optimize instantiation --- cocos2d/core/assets/CCPrefab.js | 102 +++++++++++++++++++++++++++---- cocos2d/core/platform/CCClass.js | 2 + 2 files changed, 92 insertions(+), 12 deletions(-) diff --git a/cocos2d/core/assets/CCPrefab.js b/cocos2d/core/assets/CCPrefab.js index 201c623bea..7e1d7333d3 100644 --- a/cocos2d/core/assets/CCPrefab.js +++ b/cocos2d/core/assets/CCPrefab.js @@ -23,6 +23,51 @@ THE SOFTWARE. ****************************************************************************/ +/** + * !#zh + * Prefab 创建实例所用的优化策略,配合 {{#crossLink "Prefab.optimizationPolicy"}}cc.Prefab#optimizationPolicy{{/crossLink}} 使用。 + * !#en + * An enumeration used with the {{#crossLink "Prefab.optimizationPolicy"}}cc.Prefab#optimizationPolicy{{/crossLink}} + * to specify how to optimize the instantiate operation. + * + * @enum Prefab.OptimizationPolicy + * @since 1.8.0 + */ +var OptimizationPolicy = cc.Enum({ + /** + * !#zh + * 根据创建次数自动调整优化策略。初次创建实例时,行为等同 SINGLE_INSTANCE,多次创建后将自动采用 MULTI_INSTANCE。 + * !#en + * The optimization policy is automatically chosen based on the number of instantiations. + * When you first create an instance, the behavior is the same as SINGLE_INSTANCE. MULTI_INSTANCE will be automatically used after multiple creation. + * @property {Number} AUTO + */ + AUTO: 0, + /** + * !#zh + * 优化单次创建性能。
+ * 该选项会跳过针对这个 prefab 的代码生成优化操作。当该 prefab 加载后,一般只会创建一个实例时,请选择此项。 + * !#en + * Optimize for single instance creation.
+ * This option skips code generation for this prefab. + * When this prefab will usually create only one instances, please select this option. + * @property {Number} SINGLE_INSTANCE + */ + SINGLE_INSTANCE: 1, + /** + * !#zh + * 优化多次创建性能。
+ * 该选项会启用针对这个 prefab 的代码生成优化操作。当该 prefab 加载后,一般会创建多个实例时,请选择此项。如果该 prefab 在场景中的节点启用了自动关联,并且在场景中有多份实例,也建议选择此项。 + * !#en + * Optimize for creating instances multiple times.
+ * This option enables code generation for this prefab. + * When this prefab will usually create multiple instances, please select this option. + * It is also recommended to select this option if the prefab instance in the scene has Auto Sync enabled and there are multiple instances in the scene. + * @property {Number} MULTI_INSTANCE + */ + MULTI_INSTANCE: 2, +}); + /** * !#en Class for prefab handling. * !#zh 预制资源类。 @@ -32,6 +77,16 @@ var Prefab = cc.Class({ name: 'cc.Prefab', extends: cc.Asset, + ctor () { + /** + * Cache function to optimize instance creaton. + * @property {Function} _createFunction + * @private + */ + this._createFunction = null; + + this._instantiatedTimes = 0; + }, properties: { /** @@ -39,23 +94,33 @@ var Prefab = cc.Class({ */ data: null, + /** + * !#zh + * 设置实例化这个 prefab 时所用的优化策略。根据使用情况设置为合适的值,能优化该 prefab 实例化所用的时间。 + * !#en + * Indicates the optimization policy for instantiating this prefab. + * Set to a suitable value based on usage, can optimize the time it takes to instantiate this prefab. + * + * @property {Prefab.OptimizationPolicy} optimizationPolicy + * @default Prefab.OptimizationPolicy.AUTO + * @since 1.8.0 + * @example + * prefab.optimizationPolicy = cc.Prefab.OptimizationPolicy.MULTI_INSTANCE; + */ + optimizationPolicy: OptimizationPolicy.AUTO, + /** * !#en Indicates the raw assets of this prefab can be load after prefab loaded. * !#zh 指示该 Prefab 依赖的资源可否在 Prefab 加载后再延迟加载。 * @property {Boolean} asyncLoadAssets * @default false */ - asyncLoadAssets: undefined, + asyncLoadAssets: false, + }, - /** - * Cache function for fast instantiation - * @property {Function} _createFunction - * @private - */ - _createFunction: { - default: null, - serializable: false - } + statics: { + OptimizationPolicy, + OptimizationPolicyThreshold: 3, }, createNode: CC_EDITOR && function (cb) { @@ -94,8 +159,20 @@ var Prefab = cc.Class({ }, _instantiate: function () { - var node; + var node, useJit = false; if (cc.supportJit) { + if (this.optimizationPolicy === OptimizationPolicy.SINGLE_INSTANCE) { + useJit = false; + } + else if (this.optimizationPolicy === OptimizationPolicy.MULTI_INSTANCE) { + useJit = true; + } + else { + // auto + useJit = (this._instantiatedTimes + 1) >= Prefab.OptimizationPolicyThreshold; + } + } + if (useJit) { // instantiate node node = this._doInstantiate(); // initialize node @@ -107,7 +184,8 @@ var Prefab = cc.Class({ // instantiate node node = this.data._instantiate(); } - + ++this._instantiatedTimes; + // link prefab in editor if (CC_EDITOR || CC_TEST) { // This operation is not necessary, but some old prefab asset may not contain complete data. diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index f60561fed9..49d525753d 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -864,6 +864,7 @@ function declareProperties (cls, className, properties, baseClass, mixins, es6) * @return {Function} - the created class * * @example + // define base class var Node = cc.Class(); @@ -871,6 +872,7 @@ function declareProperties (cls, className, properties, baseClass, mixins, es6) var Sprite = cc.Class({ name: 'Sprite', extends: Node, + ctor: function () { this.url = ""; this.id = 0; From 498ea2666cf1b53138ac7cfbffa0aaf2f97facc5 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Mon, 25 Dec 2017 10:18:28 +0800 Subject: [PATCH 094/127] restore toggleGroup --- cocos2d/core/components/CCToggleGroup.js | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos2d/core/components/CCToggleGroup.js b/cocos2d/core/components/CCToggleGroup.js index 7b5c8a32f5..114e2b37b1 100644 --- a/cocos2d/core/components/CCToggleGroup.js +++ b/cocos2d/core/components/CCToggleGroup.js @@ -38,6 +38,7 @@ var ToggleGroup = cc.Class({ this._toggleItems = []; }, editor: CC_EDITOR && { + menu: 'i18n:MAIN_MENU.component.ui/ToggleGroup (Legacy)', help: 'i18n:COMPONENT.help_url.toggleGroup' }, From e3b7190cd6bd13cbb52897215f6e5d7c2bcb4357 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Mon, 25 Dec 2017 18:09:40 +0800 Subject: [PATCH 095/127] support migration for texture array --- DebugInfos.js | 6 +- cocos2d/core/load-pipeline/uuid-loader.js | 8 +- cocos2d/core/platform/CCClassDecorator.js | 7 +- cocos2d/core/platform/deserialize.js | 79 +++--------------- cocos2d/core/platform/preprocess-class.js | 81 +++++++++++++++---- cocos2d/tilemap/CCTiledMapAsset.js | 5 +- test/qunit/unit-es5/test-class.js | 2 - .../unit-es5/test-migrating-raw-asset.js | 37 ++++++++- test/qunit/unit/test-class.js | 2 - 9 files changed, 130 insertions(+), 97 deletions(-) diff --git a/DebugInfos.js b/DebugInfos.js index 3b51bd2f74..38affb9609 100644 --- a/DebugInfos.js +++ b/DebugInfos.js @@ -350,9 +350,9 @@ if (CC_DEBUG) { " set %s (value) {\n" + " ...\n" + " }", - "3656": "The default value of %s.%s must be an empty string. (changed since 1.7)", //getTypeChecker_4 - "3657": "The value assigned to %s should be Texture2D type, not url. Since 1.7,\n" + - "you can declare a texture directly in properties by using:\n" + + "3656": "The default value of %s.%s must be an empty string. (changed since 1.8)", + "3657": "The value assigned to %s should be Texture2D object, not url string. Since 1.8,\n" + + "you can declare a texture object directly in properties by using:\n" + "{\n" + " default: null,\n" + " type: cc.Texture2D // use 'type:' instead of 'url:'\n" + diff --git a/cocos2d/core/load-pipeline/uuid-loader.js b/cocos2d/core/load-pipeline/uuid-loader.js index 0718d61759..a883a3674c 100644 --- a/cocos2d/core/load-pipeline/uuid-loader.js +++ b/cocos2d/core/load-pipeline/uuid-loader.js @@ -127,7 +127,13 @@ function loadDepends (pipeline, item, asset, depends, callback) { if (item) { var thisOfLoadCallback = dep; function loadCallback (item) { - var value = this._stillUseUrl ? item.rawUrl : item.content; + var value; + if (this._stillUseUrl) { + value = (item.content instanceof cc.Texture2D) ? item.content.nativeUrl : item.rawUrl + } + else { + value = item.content; + } this._owner[this._ownerProp] = value; if (item.uuid !== asset._uuid && dependKeys.indexOf(item.id) < 0) { dependKeys.push(item.id); diff --git a/cocos2d/core/platform/CCClassDecorator.js b/cocos2d/core/platform/CCClassDecorator.js index 33a785c11a..1f07b0eb67 100644 --- a/cocos2d/core/platform/CCClassDecorator.js +++ b/cocos2d/core/platform/CCClassDecorator.js @@ -146,7 +146,12 @@ function extractActualDefaultValues (ctor) { } function genProperty (ctor, properties, propName, options, desc, cache) { - var fullOptions = options && (Preprocess.getFullFormOfProperty(options) || options); + var fullOptions; + if (options) { + fullOptions = CC_DEV ? Preprocess.getFullFormOfProperty(options, propName, JS.getClassName(ctor)) : + Preprocess.getFullFormOfProperty(options); + fullOptions = fullOptions || options; + } var existsProperty = properties[propName]; var prop = JS.mixin(existsProperty || {}, fullOptions || {}); diff --git a/cocos2d/core/platform/deserialize.js b/cocos2d/core/platform/deserialize.js index 0aca3132f7..c35eb1a505 100644 --- a/cocos2d/core/platform/deserialize.js +++ b/cocos2d/core/platform/deserialize.js @@ -54,7 +54,7 @@ var Details = function () { */ this.uuidPropList = []; - // TODO - DELME + // TODO - DELME since 2.0 this._stillUseUrl = JS.createMap(true); }; /** @@ -68,6 +68,7 @@ Details.prototype.reset = function () { }; if (CC_EDITOR || CC_TEST) { Details.prototype.assignAssetsBy = function (getter) { + // ignore this._stillUseUrl for (var i = 0, len = this.uuidList.length; i < len; i++) { var uuid = this.uuidList[i]; var obj = this.uuidObjList[i]; @@ -168,10 +169,10 @@ var _Deserializer = (function () { if (jsonArray[i]) { if (CC_EDITOR || CC_TEST) { var mainTarget = (i === 0 && this._target); - this.deserializedList[i] = this._deserializeObject(jsonArray[i], mainTarget, this.deserializedList, '' + i); + this.deserializedList[i] = this._deserializeObject(jsonArray[i], false, mainTarget, this.deserializedList, '' + i); } else { - this.deserializedList[i] = this._deserializeObject(jsonArray[i]); + this.deserializedList[i] = this._deserializeObject(jsonArray[i], false); } } } @@ -187,10 +188,10 @@ var _Deserializer = (function () { else { this.deserializedList.length = 1; if (CC_EDITOR || CC_TEST) { - this.deserializedData = jsonObj ? this._deserializeObject(jsonObj, this._target, this.deserializedList, '0') : null; + this.deserializedData = jsonObj ? this._deserializeObject(jsonObj, false, this._target, this.deserializedList, '0') : null; } else { - this.deserializedData = jsonObj ? this._deserializeObject(jsonObj) : null; + this.deserializedData = jsonObj ? this._deserializeObject(jsonObj, false) : null; } this.deserializedList[0] = this.deserializedData; @@ -208,11 +209,12 @@ var _Deserializer = (function () { ///** // * @param {Object} serialized - The obj to deserialize, must be non-nil + // * @param {Boolean} _stillUseUrl // * @param {Object} [target=null] - editor only // * @param {Object} [owner] - debug only // * @param {String} [propName] - debug only // */ - prototype._deserializeObject = function (serialized, target, owner, propName) { + prototype._deserializeObject = function (serialized, _stillUseUrl, target, owner, propName) { var prop; var obj = null; // the obj to return var klass = null; @@ -276,10 +278,10 @@ var _Deserializer = (function () { prop = serialized[i]; if (typeof prop === 'object' && prop) { if (CC_EDITOR || CC_TEST) { - this._deserializeObjField(obj, prop, '' + i, target && obj); + this._deserializeObjField(obj, prop, '' + i, target && obj, _stillUseUrl); } else { - this._deserializeObjField(obj, prop, '' + i); + this._deserializeObjField(obj, prop, '' + i, null, _stillUseUrl); } } else { @@ -309,10 +311,10 @@ var _Deserializer = (function () { } else { if (CC_EDITOR || CC_TEST) { - obj[propName] = this._deserializeObject(jsonObj, target && target[propName], obj, propName); + obj[propName] = this._deserializeObject(jsonObj, _stillUseUrl, target && target[propName], obj, propName); } else { - obj[propName] = this._deserializeObject(jsonObj); + obj[propName] = this._deserializeObject(jsonObj, _stillUseUrl); } } } @@ -429,63 +431,6 @@ var _Deserializer = (function () { } }; - // function _deserializeFireClass(self, obj, serialized, klass, target) { - // var RAW_TYPE = Attr.DELIMETER + 'rawType'; - // var EDITOR_ONLY = Attr.DELIMETER + 'editorOnly'; - // var SERIALIZABLE = Attr.DELIMETER + 'serializable'; - // var props = klass.__props__; - // var attrs = Attr.getClassAttrs(klass); - // for (var p = 0; p < props.length; p++) { - // var propName = props[p]; - // var rawType = attrs[propName + RAW_TYPE]; - // if (!rawType) { - // if (((CC_EDITOR && self._ignoreEditorOnly) || CC_PREVIEW) && attrs[propName + EDITOR_ONLY]) { - // var mayUsedInPersistRoot = (cc.Node.isNode(obj) && propName === '_id'); - // if ( !mayUsedInPersistRoot ) { - // continue; // skip editor only if in preview - // } - // } - // if (attrs[propName + SERIALIZABLE] === false) { - // continue; // skip nonSerialized - // } - // var prop = serialized[propName]; - // if (typeof prop === 'undefined') { - // continue; - // } - // if (typeof prop !== 'object') { - // obj[propName] = prop; - // } - // else { - // if (prop) { - // if (CC_EDITOR || CC_TEST) { - // self._deserializeObjField(obj, prop, propName, target && obj); - // } - // else { - // self._deserializeObjField(obj, prop, propName); - // } - // } - // else { - // obj[propName] = null; - // } - // } - // } - // else { - // // always load raw objects even if property not serialized - // if (self.result.rawProp) { - // cc.error('not support multi raw object in a file'); - // // 这里假定每个asset都有uuid,每个json只能包含一个asset,只能包含一个rawProp - // } - // self.result.rawProp = propName; - // } - // } - // if (props[props.length - 1] === '_$erialized') { - // // deep copy original serialized data - // obj._$erialized = JSON.parse(JSON.stringify(serialized)); - // // parse the serialized data as primitive javascript object, so its __id__ will be dereferenced - // self._deserializePrimitiveObject(obj._$erialized, serialized); - // } - // } - var compileObjectType = cc.supportJit ? function (sources, defaultValue, accessorToSet, propNameLiteralToSet, assumeHavePropIfIsValue, stillUseUrl) { if (defaultValue instanceof cc.ValueType) { // fast case diff --git a/cocos2d/core/platform/preprocess-class.js b/cocos2d/core/platform/preprocess-class.js index 5f9d7246f7..95226385e8 100644 --- a/cocos2d/core/platform/preprocess-class.js +++ b/cocos2d/core/platform/preprocess-class.js @@ -167,11 +167,37 @@ function getBaseClassWherePropertyDefined_DEV (propName, cls) { } } -exports.getFullFormOfProperty = function (options) { - // TODO - deprecate `variable: cc.Texture2D,` from 1.7 +exports.getFullFormOfProperty = function (options, propname_dev, classname_dev) { var isLiteral = options && options.constructor === Object; if ( !isLiteral ) { if (Array.isArray(options) && options.length > 0) { + var type = options[0]; + if (CC_DEV && cc.RawAsset.wasRawAssetType(type)) { + // deprecate `myProp: [cc.Texture2D]` since 1.8 + cc.warn('Please change the definition of property \'%s\' in class \'%s\'. Starting from v1.8,\n' + + 'properties in CCClass can not be abbreviated if they are of type RawAsset.\n' + + 'Please use the complete form.\n' + + 'For example, if property is Texture2D\'s url array, the previous definition is:\n' + + ' %s: [cc.Texture2D]\n' + + 'now it should be changed to:\n' + + ' %s: {\n' + + ' url: cc.Texture2D, // use \'url:\' to define a url array for Texture2D\n' + + ' default: []\n' + + ' }\n' + + 'or more preferably:\n' + + ' %s: {\n' + + ' type: cc.Texture2D, // use \'type:\' to define an array of Texture2D objects\n' + + ' default: []\n' + + ' }\n' + + '(This helps us to successfully refactor all RawAssets at v2.0, ' + + 'sorry for the inconvenience. \uD83D\uDE30 )', + propname_dev, classname_dev, propname_dev, propname_dev, propname_dev); + return { + default: [], + url: options, + _short: true + }; + } return { default: [], type: options, @@ -180,20 +206,43 @@ exports.getFullFormOfProperty = function (options) { } else if (typeof options === 'function') { var type = options; - if (cc.RawAsset.isRawAssetType(type) || cc.RawAsset.wasRawAssetType(type)) { - return { - default: '', - url: type, - _short: true - }; - } - else { - return { - default: cc.isChildClassOf(type, cc.ValueType) ? new type() : null, - type: type, - _short: true - }; + if (!cc.RawAsset.isRawAssetType(type)) { + if (cc.RawAsset.wasRawAssetType(type)) { + // deprecate `myProp: cc.Texture2D` since 1.8 + if (CC_DEV) { + cc.warn('Please change the definition of property \'%s\' in class \'%s\'. Starting from v1.8,\n' + + 'properties in CCClass can not be abbreviated if they are of type RawAsset.\n' + + 'Please use the complete form.\n' + + 'For example, if the type is Texture2D, the previous definition is:\n' + + ' %s: cc.Texture2D\n' + + 'now it should be changed to:\n' + + ' %s: {\n' + + ' url: cc.Texture2D // use \'url:\' to define url for Texture2D\n' + + ' default: "", // url\'s default value is empty string\n' + + ' }\n' + + 'or more preferably:\n' + + ' %s: {\n' + + ' type: cc.Texture2D // use \'type:\' to define Texture2D object directly\n' + + ' default: null, // object\'s default value of is null\n' + + ' }\n' + + '(This helps us to successfully refactor all RawAssets at v2.0, ' + + 'sorry for the inconvenience. \uD83D\uDE30 )', + propname_dev, classname_dev, propname_dev, propname_dev, propname_dev); + } + } + else { + return { + default: cc.isChildClassOf(type, cc.ValueType) ? new type() : null, + type: type, + _short: true + }; + } } + return { + default: '', + url: type, + _short: true + }; } else { return { @@ -208,7 +257,7 @@ exports.getFullFormOfProperty = function (options) { exports.preprocessAttrs = function (properties, className, cls, es6) { for (var propName in properties) { var val = properties[propName]; - var fullForm = exports.getFullFormOfProperty(val); + var fullForm = exports.getFullFormOfProperty(val, propName, className); if (fullForm) { val = properties[propName] = fullForm; } diff --git a/cocos2d/tilemap/CCTiledMapAsset.js b/cocos2d/tilemap/CCTiledMapAsset.js index 2038d6fab4..e6e1c1042f 100644 --- a/cocos2d/tilemap/CCTiledMapAsset.js +++ b/cocos2d/tilemap/CCTiledMapAsset.js @@ -40,7 +40,10 @@ var TiledMapAsset = cc.Class({ /** * @property {Texture2D[]} textures */ - textures: [cc.Texture2D], + textures: { + default: [], + type: [cc.Texture2D] + }, /** * @property {String[]} textureNames diff --git a/test/qunit/unit-es5/test-class.js b/test/qunit/unit-es5/test-class.js index 3057bb91e4..853df77a20 100644 --- a/test/qunit/unit-es5/test-class.js +++ b/test/qunit/unit-es5/test-class.js @@ -124,7 +124,6 @@ test('define property in quick way', function () { string: '...', array: [], node: cc.Node, - rawAsset: cc.Texture2D, asset: cc.SpriteFrame, vec2: cc.Vec2, vec2_one: cc.Vec2.ONE, @@ -137,7 +136,6 @@ test('define property in quick way', function () { strictEqual(obj.string, '...', 'could define default value of string'); deepEqual(obj.array, [], 'could define default value of array'); strictEqual(obj.node, null, 'could define default value of cc.Node'); - strictEqual(obj.rawAsset, '', 'could define default value of raw asset'); strictEqual(obj.asset, null, 'could define default value of asset'); ok(obj.vec2.equals(cc.Vec2.ZERO), 'could define default value by using cc.Vec2'); ok(obj.vec2_one.equals(cc.Vec2.ONE), 'could define default value by using cc.Vec2.ONE'); diff --git a/test/qunit/unit-es5/test-migrating-raw-asset.js b/test/qunit/unit-es5/test-migrating-raw-asset.js index c06c7245b9..382f53651f 100644 --- a/test/qunit/unit-es5/test-migrating-raw-asset.js +++ b/test/qunit/unit-es5/test-migrating-raw-asset.js @@ -5,6 +5,8 @@ if (TestEditorExtends) { test('serialization if declared in the OLD way', function () { // setup + var sysWarn = cc.warn; + cc.warn = Callback().enable(); var MyAsset = cc.Class({ name: 'MyAsset', properties: { @@ -12,29 +14,47 @@ if (TestEditorExtends) { url: cc.Texture2D, default: "", }, + ref_full_array: { + url: cc.Texture2D, + default: [], + }, ref_brief: cc.Texture2D, + ref_brief_array: [cc.Texture2D], } }); + strictEqual(cc.warn.calledCount, 2, 'should trigger warnings if declared in deprecated way'); + cc.warn = sysWarn; + var asset = new MyAsset(); asset.ref_full = 'foo'; + asset.ref_full_array = ['foo']; asset.ref_brief = 'foo'; + asset.ref_brief_array = ['foo']; // serialize - var restore = Editor.Utils.UuidCache.urlToUuid; + var sysUrlToUuid = Editor.Utils.UuidCache.urlToUuid; Editor.Utils.UuidCache.urlToUuid = function (url) { return { foo: '01', }[url]; }; var serializedAsset = Editor.serialize(asset); - Editor.Utils.UuidCache.urlToUuid = restore; + Editor.Utils.UuidCache.urlToUuid = sysUrlToUuid; // deserialize - var deserializedAsset = cc.deserialize(serializedAsset, null, {createAssetRefs: true}); + var details = new cc.deserialize.Details(); + var deserializedAsset = cc.deserialize(serializedAsset, details, {createAssetRefs: true}); // test + ok(details._stillUseUrl[0] && + details._stillUseUrl[1] && + details._stillUseUrl[2] && + details._stillUseUrl[3], 'should deserialize them as url'); + ok(deserializedAsset.ref_full._uuid === '01', 'should support serialization if declared in full form'); - ok(deserializedAsset.ref_brief._uuid === '01', 'should support serialization if declared in brief form'); + ok(deserializedAsset.ref_full_array[0]._uuid === '01', 'should support serialization if array declared in full form'); + ok(deserializedAsset.ref_brief._uuid === '01', 'should still support serialization if declared in deprecated form'); + ok(deserializedAsset.ref_brief_array[0]._uuid === '01', 'should still support serialization if array declared in deprecated form'); //teardown cc.js.unregisterClass(MyAsset); @@ -49,14 +69,21 @@ if (TestEditorExtends) { type: cc.Texture2D, default: null, }, + ref_full_array: { + type: cc.Texture2D, + default: [] + }, // TODO - uncomment in 2.0 // ref_brief: cc.Texture2D, + // ref_brief_array: [cc.Texture2D], } }); var asset = new MyAsset(); asset.ref_full = new cc.Texture2D(); asset.ref_full._uuid = '01'; + asset.ref_full_array.push(asset.ref_full); // asset.ref_brief = asset.ref_full; + // asset.ref_brief_array.push(asset.ref_full); // serialize var restore = Editor.Utils.UuidCache.urlToUuid; @@ -73,7 +100,9 @@ if (TestEditorExtends) { // test ok(deserializedAsset.ref_full._uuid === '01', 'should support serialization if declared in full form'); + ok(deserializedAsset.ref_full_array[0]._uuid === '01', 'should support serialization if array declared in full form'); // ok(deserializedAsset.ref_brief._uuid === '01', 'should support serialization if declared in brief form'); + // ok(deserializedAsset.ref_brief_array[0]._uuid === '01', 'should support serialization if declared in brief form'); //teardown cc.js.unregisterClass(MyAsset); diff --git a/test/qunit/unit/test-class.js b/test/qunit/unit/test-class.js index e631cbc078..4b127c7b62 100644 --- a/test/qunit/unit/test-class.js +++ b/test/qunit/unit/test-class.js @@ -227,7 +227,6 @@ largeModule('Class ES6'); @property string = '...'; @property array = []; @property(cc.Node) node = null; - @property(cc.Texture2D) rawAsset = ''; @property(cc.SpriteFrame) asset = null; @property vec2 = cc.Vec2.ZERO; @property vec2_one = cc.Vec2.ONE; @@ -239,7 +238,6 @@ largeModule('Class ES6'); strictEqual(obj.string, '...', 'could define default value of string'); deepEqual(obj.array, [], 'could define default value of array'); strictEqual(obj.node, null, 'could define default value of cc.Node'); - strictEqual(obj.rawAsset, '', 'could define default value of raw asset'); strictEqual(obj.asset, null, 'could define default value of asset'); ok(obj.vec2.equals(cc.Vec2.ZERO), 'could define default value by using cc.Vec2'); ok(obj.vec2_one.equals(cc.Vec2.ONE), 'could define default value by using cc.Vec2.ONE'); From 575391b481b4c19b961336c9c4956f77b8c804e8 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 27 Dec 2017 01:09:40 +0800 Subject: [PATCH 096/127] fix CCDebugger --- CCDebugger.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CCDebugger.js b/CCDebugger.js index 7e8598e559..3fdb0cb1f2 100644 --- a/CCDebugger.js +++ b/CCDebugger.js @@ -340,7 +340,7 @@ function genLogFunc(func, type) { func(CC_DEBUG ? cc.js.formatStr(msg, arguments[1]) : msg + ' Arguments: ' + arguments[1]); } else { - func(cc._LogInfos.e(msg, cc.js.shiftArguments.apply(null, arguments))); + func(cc._LogInfos.format(msg, cc.js.shiftArguments.apply(null, arguments))); } }; } From dc533d28114dcd60cfd454274100b9149f0a424e Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 27 Dec 2017 01:50:37 +0800 Subject: [PATCH 097/127] merge message formater for logger --- CCDebugger.js | 19 ++++++------------- DebugInfos.js | 48 ++++++++++++++++++++++-------------------------- index.js | 4 +--- jsb/index.js | 6 +----- 4 files changed, 30 insertions(+), 47 deletions(-) diff --git a/CCDebugger.js b/CCDebugger.js index 3fdb0cb1f2..8dbe061d8a 100644 --- a/CCDebugger.js +++ b/CCDebugger.js @@ -24,9 +24,11 @@ ****************************************************************************/ // for cc.DebugMode.INFO_FOR_WEB_PAGE -var logList; var Enum = require('./cocos2d/core/platform/CCEnum'); +var getTypedFormatter = require('./DebugInfos').getTypedFormatter; + +var logList; /** * !#en Enum for debug modes. @@ -330,17 +332,8 @@ cc._throw = CC_EDITOR ? Editor.error : function (error) { }; function genLogFunc(func, type) { - return function (id) { - 'use strict'; - var msg = cc._LogInfos.raw(id, type); - if (arguments.length === 1) { - func(msg); - } - else if (arguments.length === 2) { - func(CC_DEBUG ? cc.js.formatStr(msg, arguments[1]) : msg + ' Arguments: ' + arguments[1]); - } - else { - func(cc._LogInfos.format(msg, cc.js.shiftArguments.apply(null, arguments))); - } + var formatter = getTypedFormatter(type); + return function () { + func(formatter.apply(null, arguments)); }; } diff --git a/DebugInfos.js b/DebugInfos.js index 3b51bd2f74..a9ceee9509 100644 --- a/DebugInfos.js +++ b/DebugInfos.js @@ -1,5 +1,7 @@ +var logs; + if (CC_DEBUG) { - var logs = { + logs = { // Common "0100": "%s not yet implemented.", //ActionManager: 1000 @@ -698,38 +700,32 @@ if (CC_DEBUG) { // AudioEngine: 8400 "8400": "Wrong type arguments, 'filePath' must be a String.", // cc.audioEngine.play }; - cc._LogInfos = logs; +} +else { + logs = {}; +} - var errorMapUrl = 'https://github.com/cocos-creator/engine/blob/master/EngineErrorMap.md'; +const ERROR_MAP_URL = 'https://github.com/cocos-creator/engine/blob/master/EngineErrorMap.md'; - function raw (id, type) { - return CC_DEBUG ? cc._LogInfos[id] : `${type} ${id}, please go to ${errorMapUrl}#${id} to see details.`; - } - - function format (msg, argsArray) { - return CC_DEBUG ? cc.js.formatStr.apply(null, [msg].concat(argsArray)) : msg + ' Arguments: ' + argsArray.join(', '); - } - - cc._LogInfos.e = function () { - var msg = raw(arguments[0], 'ERROR'); +function getTypedFormatter (type) { + return function () { + var id = arguments[0]; + var msg = CC_DEBUG ? (logs[id] || 'unknown id') : `${type} ${id}, please go to ${ERROR_MAP_URL}#${id} to see details.`; if (arguments.length === 1) { return msg; } + else if (arguments.length === 2) { + return CC_DEBUG ? cc.js.formatStr(msg, arguments[1]) : + msg + ' Arguments: ' + arguments[1]; + } else { - return format(msg, cc.js.shiftArguments.apply(null, arguments)); + var argsArray = cc.js.shiftArguments.apply(null, arguments); + return CC_DEBUG ? cc.js.formatStr.apply(null, [msg].concat(argsArray)) : + msg + ' Arguments: ' + argsArray.join(', '); } }; - cc._LogInfos.raw = raw; - cc._LogInfos.format = format; } -// module.exports = false; - -// // Only Node.JS has a process variable that is of [[Class]] process -// try { -// module.exports = Object.prototype.toString.call(global.process) === '[object process]'; -// module.exports = logs; -// } catch (e) { - -// cc._LogInfos = logs; -// } +logs.e = getTypedFormatter('ERROR'); +logs.getTypedFormatter = getTypedFormatter; +module.exports = cc._LogInfos = logs; diff --git a/index.js b/index.js index eee5acd80b..cafb809e25 100644 --- a/index.js +++ b/index.js @@ -156,11 +156,9 @@ if (CC_DEV) { } // output all info before initialized +require('./DebugInfos'); require('./CCDebugger'); cc._initDebugSetting(cc.DebugMode.INFO); -if (CC_DEBUG) { - require('./DebugInfos'); -} // polyfills /* require('./polyfill/bind'); */ diff --git a/jsb/index.js b/jsb/index.js index 81cd0bf33e..c105efbc9e 100644 --- a/jsb/index.js +++ b/jsb/index.js @@ -76,13 +76,9 @@ require('../cocos2d/core/utils/find'); require('../cocos2d/core/utils/mutable-forward-iterator'); require('../cocos2d/core/event'); require('../cocos2d/core/event-manager/CCEvent'); +require('../DebugInfos'); require('../CCDebugger'); -if (CC_DEBUG) { - //Debug Info ID map - require('../DebugInfos'); -} - // Mark memory model var macro = require('../cocos2d/core/platform/CCMacro'); From b805ff88dc2f9719d85962e97fc0688418dad60c Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Wed, 27 Dec 2017 10:06:47 +0800 Subject: [PATCH 098/127] fix VideoPlayer Can not trigger EVENT_HIDE event and refine code --- cocos2d/core/videoplayer/CCSGVideoPlayer.js | 75 +++++++++++---------- 1 file changed, 38 insertions(+), 37 deletions(-) diff --git a/cocos2d/core/videoplayer/CCSGVideoPlayer.js b/cocos2d/core/videoplayer/CCSGVideoPlayer.js index d9a523a16b..53a9806e21 100644 --- a/cocos2d/core/videoplayer/CCSGVideoPlayer.js +++ b/cocos2d/core/videoplayer/CCSGVideoPlayer.js @@ -21,7 +21,6 @@ var Utils = require('../platform/utils'); var sys = require('../platform/CCSys'); -var eventManager = require('../event-manager'); /** * @class @@ -173,11 +172,11 @@ _ccsg.VideoPlayer.elements = []; // video 在 game_hide 事件中被自动暂停的队列,用于回复的时候重新开始播放 _ccsg.VideoPlayer.pauseElements = []; -eventManager.addCustomListener(cc.game.EVENT_HIDE, function () { +cc.game.on(cc.game.EVENT_HIDE, function () { var list = _ccsg.VideoPlayer.elements; - for(var node, i=0; i Date: Wed, 27 Dec 2017 10:55:34 +0800 Subject: [PATCH 099/127] remove cc._LogInfos, use cc._getError instead --- CCBoot.js | 2 - CCDebugger.js | 87 ++++++++++++------- DebugInfos.js | 32 +------ cocos2d/actions/CCAction.js | 4 +- cocos2d/actions/CCActionCatmullRom.js | 2 +- cocos2d/actions/CCActionEase.js | 2 +- cocos2d/actions/CCActionInterval.js | 12 +-- cocos2d/actions/CCActionManager.js | 4 +- cocos2d/animation/playable.js | 2 +- cocos2d/audio/deprecated.js | 7 +- cocos2d/core/CCConfiguration.js | 2 +- cocos2d/core/CCDrawingPrimitivesCanvas.js | 4 +- cocos2d/core/CCDrawingPrimitivesWebGL.js | 2 +- cocos2d/core/CCGame.js | 2 +- cocos2d/core/event-manager/CCEventManager.js | 2 +- cocos2d/core/load-pipeline/asset-loader.js | 2 +- .../core/load-pipeline/audio-downloader.js | 4 +- cocos2d/core/load-pipeline/downloader.js | 6 +- cocos2d/core/load-pipeline/uuid-loader.js | 6 +- cocos2d/core/platform/CCSys.js | 2 +- cocos2d/core/platform/_CCClass.js | 2 +- cocos2d/kazmath/gl/matrix.js | 4 +- cocos2d/kazmath/quaternion.js | 2 +- cocos2d/particle/CCPNGReader.js | 4 +- cocos2d/particle/CCParticleSystem.js | 2 +- cocos2d/particle/CCTIFFReader.js | 16 ++-- cocos2d/shaders/CCGLProgram.js | 10 +-- cocos2d/tilemap/CCSGTMXLayer.js | 20 ++--- cocos2d/tilemap/CCSGTMXTiledMap.js | 4 +- cocos2d/tilemap/CCTiledLayer.js | 2 +- cocos2d/tilemap/editor/tiled-map.js | 2 +- index.js | 8 +- jsb/index.js | 1 - jsb/jsb-game.js | 10 --- 34 files changed, 123 insertions(+), 150 deletions(-) diff --git a/CCBoot.js b/CCBoot.js index 98fc89518c..e06066efeb 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -23,8 +23,6 @@ THE SOFTWARE. ****************************************************************************/ -cc._LogInfos = cc._LogInfos || {}; - /** * The current version of Cocos2d being used.
* Please DO NOT remove this String, it is an important flag for bug tracking.
diff --git a/CCDebugger.js b/CCDebugger.js index 8dbe061d8a..e538769256 100644 --- a/CCDebugger.js +++ b/CCDebugger.js @@ -23,11 +23,9 @@ THE SOFTWARE. ****************************************************************************/ -// for cc.DebugMode.INFO_FOR_WEB_PAGE - var Enum = require('./cocos2d/core/platform/CCEnum'); -var getTypedFormatter = require('./DebugInfos').getTypedFormatter; +// the html element displays log in web page (cc.DebugMode.INFO_FOR_WEB_PAGE) var logList; /** @@ -94,10 +92,6 @@ cc.DebugMode = Enum({ ERROR_FOR_WEB_PAGE: 6 }); -/** - * @module cc - */ - /** * !#en Init Debug setting. * !#zh 设置调试模式。 @@ -106,7 +100,7 @@ cc.DebugMode = Enum({ */ cc._initDebugSetting = function (mode) { // reset - cc.log = cc.logID = cc.warn = cc.warnID = cc.error = cc.errorID = cc._throw = cc.assert = cc.assertID = function () { }; + cc.log = cc.warn = cc.error = cc._throw = cc.assert = function () { }; if (mode === cc.DebugMode.NONE) return; @@ -294,33 +288,15 @@ cc._initDebugSetting = function (mode) { cc.info = (scriptEngineType === "JavaScriptCore") ? function () { (console.info || console.log).apply(console, arguments); } : (console.info || console.log); - } else { + } + else { cc.info = function () { (console.info || console.log).apply(console, arguments); }; } - } - - cc.warnID = genLogFunc(cc.warn, 'Warning'); - cc.errorID = genLogFunc(cc.error, 'Error'); - cc.logID = genLogFunc(cc.log, 'Log'); - var assertFailed = genLogFunc(function () { - // actually no need to protect arguments leak here in case of an error... - var argsArr = [false]; - for (var i = 0; i < arguments.length; ++i) { - argsArr.push(arguments[i]); - } - cc.assert.apply(null, argsArr); - }, 'Assert'); - cc.assertID = function (cond) { - 'use strict'; - if (cond) { - return; - } - assertFailed.apply(null, cc.js.shiftArguments.apply(null, arguments)); - }; }; + cc._throw = CC_EDITOR ? Editor.error : function (error) { var stack = error.stack; if (stack) { @@ -331,9 +307,56 @@ cc._throw = CC_EDITOR ? Editor.error : function (error) { } }; -function genLogFunc(func, type) { - var formatter = getTypedFormatter(type); +// define log methods to lookup message ID + +const debugInfos = CC_DEBUG && require('./DebugInfos'); +const ERROR_MAP_URL = 'https://github.com/cocos-creator/engine/blob/master/EngineErrorMap.md'; + +function getTypedFormatter (type) { return function () { - func(formatter.apply(null, arguments)); + var id = arguments[0]; + var msg = CC_DEBUG ? (debugInfos[id] || 'unknown id') : `${type} ${id}, please go to ${ERROR_MAP_URL}#${id} to see details.`; + if (arguments.length === 1) { + return msg; + } + else if (arguments.length === 2) { + return CC_DEBUG ? cc.js.formatStr(msg, arguments[1]) : + msg + ' Arguments: ' + arguments[1]; + } + else { + var argsArray = cc.js.shiftArguments.apply(null, arguments); + return CC_DEBUG ? cc.js.formatStr.apply(null, [msg].concat(argsArray)) : + msg + ' Arguments: ' + argsArray.join(', '); + } }; } + +var logFormatter = getTypedFormatter('Log'); +cc.logID = function () { + cc.log(logFormatter.apply(null, arguments)); +}; + +var warnFormatter = getTypedFormatter('Warning'); +cc.warnID = function () { + cc.warn(warnFormatter.apply(null, arguments)); +}; + +var errorFormatter = getTypedFormatter('Error'); +cc.errorID = function () { + cc.error(errorFormatter.apply(null, arguments)); +}; + +var assertFormatter = getTypedFormatter('Assert'); +cc.assertID = function (cond) { + 'use strict'; + if (cond) { + return; + } + cc.assert(false, assertFormatter.apply(null, cc.js.shiftArguments.apply(null, arguments))); +}; + +cc._getError = getTypedFormatter('ERROR'); + +// output all info by default before initialized + +cc._initDebugSetting(cc.DebugMode.INFO); diff --git a/DebugInfos.js b/DebugInfos.js index a9ceee9509..44834dadca 100644 --- a/DebugInfos.js +++ b/DebugInfos.js @@ -1,7 +1,5 @@ -var logs; - if (CC_DEBUG) { - logs = { + module.exports = { // Common "0100": "%s not yet implemented.", //ActionManager: 1000 @@ -701,31 +699,3 @@ if (CC_DEBUG) { "8400": "Wrong type arguments, 'filePath' must be a String.", // cc.audioEngine.play }; } -else { - logs = {}; -} - -const ERROR_MAP_URL = 'https://github.com/cocos-creator/engine/blob/master/EngineErrorMap.md'; - -function getTypedFormatter (type) { - return function () { - var id = arguments[0]; - var msg = CC_DEBUG ? (logs[id] || 'unknown id') : `${type} ${id}, please go to ${ERROR_MAP_URL}#${id} to see details.`; - if (arguments.length === 1) { - return msg; - } - else if (arguments.length === 2) { - return CC_DEBUG ? cc.js.formatStr(msg, arguments[1]) : - msg + ' Arguments: ' + arguments[1]; - } - else { - var argsArray = cc.js.shiftArguments.apply(null, arguments); - return CC_DEBUG ? cc.js.formatStr.apply(null, [msg].concat(argsArray)) : - msg + ' Arguments: ' + argsArray.join(', '); - } - }; -} - -logs.e = getTypedFormatter('ERROR'); -logs.getTypedFormatter = getTypedFormatter; -module.exports = cc._LogInfos = logs; diff --git a/cocos2d/actions/CCAction.js b/cocos2d/actions/CCAction.js index 5f4c168970..57e49ea6b7 100644 --- a/cocos2d/actions/CCAction.js +++ b/cocos2d/actions/CCAction.js @@ -300,7 +300,7 @@ cc.Speed = cc.Action.extend({ */ initWithAction:function (action, speed) { if(!action) - throw new Error(cc._LogInfos.e(1021)); + throw new Error(cc._getError(1021)); this._innerAction = action; this._speed = speed; @@ -489,7 +489,7 @@ cc.Follow = cc.Action.extend({ */ initWithTarget:function (followedNode, rect) { if(!followedNode) - throw new Error(cc._LogInfos.e(1022)); + throw new Error(cc._getError(1022)); var _this = this; rect = rect || cc.rect(0, 0, 0, 0); diff --git a/cocos2d/actions/CCActionCatmullRom.js b/cocos2d/actions/CCActionCatmullRom.js index 22c2cdb6c0..63fb9b1dfe 100644 --- a/cocos2d/actions/CCActionCatmullRom.js +++ b/cocos2d/actions/CCActionCatmullRom.js @@ -129,7 +129,7 @@ cc.CardinalSplineTo = cc.ActionInterval.extend({ initWithDuration:function (duration, points, tension) { if(!points || points.length === 0) - throw new Error(cc._LogInfos.e(1024)); + throw new Error(cc._getError(1024)); if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) { this.setPoints(points); diff --git a/cocos2d/actions/CCActionEase.js b/cocos2d/actions/CCActionEase.js index 86ef3a55ee..809b55085d 100644 --- a/cocos2d/actions/CCActionEase.js +++ b/cocos2d/actions/CCActionEase.js @@ -51,7 +51,7 @@ cc.ActionEase = cc.ActionInterval.extend({ */ initWithAction:function (action) { if(!action) - throw new Error(cc._LogInfos.e(1023)); + throw new Error(cc._getError(1023)); if (this.initWithDuration(action.getDuration())) { this._inner = action; diff --git a/cocos2d/actions/CCActionInterval.js b/cocos2d/actions/CCActionInterval.js index 8b11190582..97d3f71d0e 100644 --- a/cocos2d/actions/CCActionInterval.js +++ b/cocos2d/actions/CCActionInterval.js @@ -341,7 +341,7 @@ cc.Sequence = cc.ActionInterval.extend({ */ initWithTwoActions:function (actionOne, actionTwo) { if(!actionOne || !actionTwo) - throw new Error(cc._LogInfos.e(1025)); + throw new Error(cc._getError(1025)); var d = actionOne._duration + actionTwo._duration; this.initWithDuration(d); @@ -649,7 +649,7 @@ cc.RepeatForever = cc.ActionInterval.extend({ */ initWithAction:function (action) { if(!action) - throw new Error(cc._LogInfos.e(1026)); + throw new Error(cc._getError(1026)); this._innerAction = action; return true; @@ -767,7 +767,7 @@ cc.Spawn = cc.ActionInterval.extend({ */ initWithTwoActions:function (action1, action2) { if(!action1 || !action2) - throw new Error(cc._LogInfos.e(1027)); + throw new Error(cc._getError(1027)); var ret = false; @@ -2473,9 +2473,9 @@ cc.ReverseTime = cc.ActionInterval.extend({ */ initWithAction:function (action) { if(!action) - throw new Error(cc._LogInfos.e(1028)); + throw new Error(cc._getError(1028)); if(action === this._other) - throw new Error(cc._LogInfos.e(1029)); + throw new Error(cc._getError(1029)); if (cc.ActionInterval.prototype.initWithDuration.call(this, action._duration)) { // Don't leak if action is reused @@ -2580,7 +2580,7 @@ cc.Animate = cc.ActionInterval.extend({ */ initWithAnimation:function (animation) { if(!animation) - throw new Error(cc._LogInfos.e(1030)); + throw new Error(cc._getError(1030)); var singleDuration = animation.getDuration(); if (this.initWithDuration(singleDuration * animation.getLoops())) { this._nextFrame = 0; diff --git a/cocos2d/actions/CCActionManager.js b/cocos2d/actions/CCActionManager.js index ad5ead35f5..0d92bb2558 100644 --- a/cocos2d/actions/CCActionManager.js +++ b/cocos2d/actions/CCActionManager.js @@ -114,9 +114,9 @@ cc.ActionManager = cc._Class.extend(/** @lends cc.ActionManager# */{ */ addAction:function (action, target, paused) { if(!action) - throw new Error(cc._LogInfos.e(1000)); + throw new Error(cc._getError(1000)); if(!target) - throw new Error(cc._LogInfos.e(1000)); + throw new Error(cc._getError(1000)); //check if the action target already exists var element = this._hashTargets[target.__instanceId]; diff --git a/cocos2d/animation/playable.js b/cocos2d/animation/playable.js index 3a3240e1a4..b0bf1bf459 100644 --- a/cocos2d/animation/playable.js +++ b/cocos2d/animation/playable.js @@ -80,7 +80,7 @@ prototype.play = function () { this.onResume(); } else { - this.onError(cc._LogInfos.e(3912)); + this.onError(cc._getError(3912)); } } else { diff --git a/cocos2d/audio/deprecated.js b/cocos2d/audio/deprecated.js index 6e0b459c4d..747f283fa5 100644 --- a/cocos2d/audio/deprecated.js +++ b/cocos2d/audio/deprecated.js @@ -25,7 +25,6 @@ ****************************************************************************/ var js = cc.js; -var INFO = cc._LogInfos.deprecated; exports.removed = function (audioEngine) { function willPlayMusicError () { @@ -43,14 +42,14 @@ exports.deprecated = function (audioEngine) { var effectsVolume = 1; var pauseIDCache = []; js.get(audioEngine, 'rewindMusic', function () { - cc.warn(INFO, 'audioEngine.rewindMusic', 'audioEngine.setCurrentTime'); + cc.warnID(1400, 'audioEngine.rewindMusic', 'audioEngine.setCurrentTime'); return function () { audioEngine.setCurrentTime(musicId, 0); return musicId; } }); js.get(audioEngine, 'unloadEffect', function () { - cc.warn(INFO, 'audioEngine.unloadEffect', 'audioEngine.stop'); + cc.warnID(1400, 'audioEngine.unloadEffect', 'audioEngine.stop'); return function (id) { return audioEngine.stop(id); } @@ -58,7 +57,7 @@ exports.deprecated = function (audioEngine) { if (!CC_JSB) { js.get(audioEngine, 'end', function () { - cc.warn(INFO, 'audioEngine.end', 'audioEngine.stopAll'); + cc.warnID(1400, 'audioEngine.end', 'audioEngine.stopAll'); return function () { return audioEngine.stopAll(); } diff --git a/cocos2d/core/CCConfiguration.js b/cocos2d/core/CCConfiguration.js index 63979b6ca9..c9b58841f2 100644 --- a/cocos2d/core/CCConfiguration.js +++ b/cocos2d/core/CCConfiguration.js @@ -267,7 +267,7 @@ cc.configuration = /** @lends cc.configuration# */{ if(!this._inited) this._init(); var dict = cc.loader.getRes(url); - if(!dict) throw new Error(cc._LogInfos.e(1102, url)); + if(!dict) throw new Error(cc._getError(1102, url)); cc.assertID(dict, 1101, url); var getDatas = dict["data"]; diff --git a/cocos2d/core/CCDrawingPrimitivesCanvas.js b/cocos2d/core/CCDrawingPrimitivesCanvas.js index ed0de2ab15..5129ba8500 100644 --- a/cocos2d/core/CCDrawingPrimitivesCanvas.js +++ b/cocos2d/core/CCDrawingPrimitivesCanvas.js @@ -143,7 +143,7 @@ var DrawingPrimitiveCanvas = cc._Class.extend({ return; if (vertices.length < 3) - throw new Error(cc._LogInfos.e(6704)); + throw new Error(cc._getError(6704)); var firstPoint = vertices[0], locContext = this._renderContext.getContext(); var locScaleX = cc.view.getScaleX(), locScaleY = cc.view.getScaleY(); @@ -319,7 +319,7 @@ var DrawingPrimitiveCanvas = cc._Class.extend({ destSize.width, destSize.height); break; default: - throw new Error(cc._LogInfos.e(6705)); + throw new Error(cc._getError(6705)); break; } }, diff --git a/cocos2d/core/CCDrawingPrimitivesWebGL.js b/cocos2d/core/CCDrawingPrimitivesWebGL.js index 2f8ccf6a6d..3b614c619b 100644 --- a/cocos2d/core/CCDrawingPrimitivesWebGL.js +++ b/cocos2d/core/CCDrawingPrimitivesWebGL.js @@ -44,7 +44,7 @@ var DrawingPrimitiveWebGL = cc._Class.extend({ */ ctor:function (ctx) { if (cc.sys.platform !== cc.sys.WECHAT_GAME && !ctx instanceof WebGLRenderingContext) - throw new Error(cc._LogInfos.e(6703)); + throw new Error(cc._getError(6703)); this._renderContext = ctx; this._colorArray = new Float32Array([1.0, 1.0, 1.0, 1.0]); diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index 253a616929..35a5c6bcd6 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -650,7 +650,7 @@ var game = { if (this._rendererInitialized) return; if (!cc._supportRender) { - throw new Error(cc._LogInfos.e(3820, this.config[this.CONFIG_KEY.renderMode])); + throw new Error(cc._getError(3820, this.config[this.CONFIG_KEY.renderMode])); } var el = this.config[game.CONFIG_KEY.id], diff --git a/cocos2d/core/event-manager/CCEventManager.js b/cocos2d/core/event-manager/CCEventManager.js index 346ba3291b..aadd316e9e 100644 --- a/cocos2d/core/event-manager/CCEventManager.js +++ b/cocos2d/core/event-manager/CCEventManager.js @@ -1053,7 +1053,7 @@ var eventManager = { this._updateDirtyFlagForSceneGraph(); this._inDispatch++; if(!event || !event.getType) - throw new Error(cc._LogInfos.e(3511)); + throw new Error(cc._getError(3511)); if (event.getType().startsWith(cc.Event.TOUCH)) { this._dispatchTouchEvent(event); this._inDispatch--; diff --git a/cocos2d/core/load-pipeline/asset-loader.js b/cocos2d/core/load-pipeline/asset-loader.js index 1e0f65550b..b4a6ab0cf5 100644 --- a/cocos2d/core/load-pipeline/asset-loader.js +++ b/cocos2d/core/load-pipeline/asset-loader.js @@ -54,7 +54,7 @@ AssetLoader.prototype.handle = function (item, callback) { if (isRawAsset) { var ext = Path.extname(url).toLowerCase(); if (!ext) { - callback(new Error(cc._LogInfos.e(4931, uuid, url))); + callback(new Error(cc._getError(4931, uuid, url))); return; } ext = ext.substr(1); diff --git a/cocos2d/core/load-pipeline/audio-downloader.js b/cocos2d/core/load-pipeline/audio-downloader.js index 822587cfe5..b6d536433f 100644 --- a/cocos2d/core/load-pipeline/audio-downloader.js +++ b/cocos2d/core/load-pipeline/audio-downloader.js @@ -73,7 +73,7 @@ function loadDomAudio (item, callback) { } function loadWebAudio (item, callback) { - if (!context) callback(new Error(cc._LogInfos.e(4926))); + if (!context) callback(new Error(cc._getError(4926))); var request = cc.loader.getXMLHttpRequest(); request.open("GET", item.url, true); @@ -100,7 +100,7 @@ function loadWebAudio (item, callback) { function downloadAudio (item, callback) { if (formatSupport.length === 0) { - return new Error(cc._LogInfos.e(4927)); + return new Error(cc._getError(4927)); } item.content = item.url; diff --git a/cocos2d/core/load-pipeline/downloader.js b/cocos2d/core/load-pipeline/downloader.js index 1cb0d9b120..b433c84f1f 100644 --- a/cocos2d/core/load-pipeline/downloader.js +++ b/cocos2d/core/load-pipeline/downloader.js @@ -63,7 +63,7 @@ function downloadScript (item, callback, isAsync) { s.parentNode.removeChild(s); s.removeEventListener('load', loadHandler, false); s.removeEventListener('error', errorHandler, false); - callback(new Error(cc._LogInfos.e(4928, url))); + callback(new Error(cc._getError(4928, url))); } s.addEventListener('load', loadHandler, false); s.addEventListener('error', errorHandler, false); @@ -72,7 +72,7 @@ function downloadScript (item, callback, isAsync) { function downloadWebp (item, callback, isCrossOrigin, img) { if (!cc.sys.capabilities.webp) { - return new Error(cc._LogInfos.e(4929, item.url)); + return new Error(cc._getError(4929, item.url)); } return downloadImage(item, callback, isCrossOrigin, img); } @@ -111,7 +111,7 @@ function downloadImage (item, callback, isCrossOrigin, img) { downloadImage(item, callback, false, img); } else { - callback(new Error(cc._LogInfos.e(4930, url))); + callback(new Error(cc._getError(4930, url))); } } diff --git a/cocos2d/core/load-pipeline/uuid-loader.js b/cocos2d/core/load-pipeline/uuid-loader.js index 0718d61759..c081dc48d2 100644 --- a/cocos2d/core/load-pipeline/uuid-loader.js +++ b/cocos2d/core/load-pipeline/uuid-loader.js @@ -207,14 +207,14 @@ function loadUuid (item, callback) { json = JSON.parse(item.content); } catch (e) { - return new Error(cc._LogInfos.e(4923, item.id, e.stack)); + return new Error(cc._getError(4923, item.id, e.stack)); } } else if (typeof item.content === 'object') { json = item.content; } else { - return new Error(cc._LogInfos.e(4924)); + return new Error(cc._getError(4924)); } var classFinder; @@ -259,7 +259,7 @@ function loadUuid (item, callback) { catch (e) { cc.deserialize.Details.pool.put(tdInfo); var err = CC_JSB ? (e + '\n' + e.stack) : e.stack; - return new Error(cc._LogInfos.e(4925, item.id, err)); + return new Error(cc._getError(4925, item.id, err)); } asset._uuid = item.uuid; diff --git a/cocos2d/core/platform/CCSys.js b/cocos2d/core/platform/CCSys.js index e2a1ecb5ac..08f5a41788 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -716,7 +716,7 @@ else { sys._checkWebGLRenderMode = function () { if (cc._renderType !== cc.game.RENDER_TYPE_WEBGL) - throw new Error(cc._LogInfos.e(5202)); + throw new Error(cc._getError(5202)); }; var _tmpCanvas1 = document.createElement("canvas"), diff --git a/cocos2d/core/platform/_CCClass.js b/cocos2d/core/platform/_CCClass.js index 6ae66ef933..17a20cd535 100644 --- a/cocos2d/core/platform/_CCClass.js +++ b/cocos2d/core/platform/_CCClass.js @@ -174,7 +174,7 @@ cc.defineGetterSetter = function (proto, prop, getter, setter, getterName, sette setter && (desc.set = setter); Object.defineProperty(proto, prop, desc); } else { - throw new Error(cc._LogInfos.e(3658)); + throw new Error(cc._getError(3658)); } }; diff --git a/cocos2d/kazmath/gl/matrix.js b/cocos2d/kazmath/gl/matrix.js index 0d0a4b50ab..0de4623e3a 100644 --- a/cocos2d/kazmath/gl/matrix.js +++ b/cocos2d/kazmath/gl/matrix.js @@ -106,7 +106,7 @@ math.glMatrixMode = function (mode) { cc.current_stack = math.texture_matrix_stack; break; default: - throw new Error(cc._LogInfos.e(7908)); //TODO: Proper error handling + throw new Error(cc._getError(7908)); //TODO: Proper error handling break; } }; @@ -169,7 +169,7 @@ math.glGetMatrix = function (mode, pOut) { pOut.assignFrom(math.texture_matrix_stack.top); break; default: - throw new Error(cc._LogInfos.e(7908)); //TODO: Proper error handling + throw new Error(cc._getError(7908)); //TODO: Proper error handling break; } }; diff --git a/cocos2d/kazmath/quaternion.js b/cocos2d/kazmath/quaternion.js index 4d8ce63cb6..1035f3fb27 100644 --- a/cocos2d/kazmath/quaternion.js +++ b/cocos2d/kazmath/quaternion.js @@ -153,7 +153,7 @@ proto.multiply = function(quaternion) { //cc.kmQuaternionMultiply proto.normalize = function(){ //=cc.kmQuaternionNormalize var length = this.length(); if (Math.abs(length) <= cc.math.EPSILON) - throw new Error(cc._LogInfos.e(7909)); + throw new Error(cc._getError(7909)); this.scale(1.0 / length); return this; }; diff --git a/cocos2d/particle/CCPNGReader.js b/cocos2d/particle/CCPNGReader.js index 6a9a8a0e8b..9cee60f59f 100644 --- a/cocos2d/particle/CCPNGReader.js +++ b/cocos2d/particle/CCPNGReader.js @@ -161,7 +161,7 @@ var PNGReader = cc._Class.extend({ } this.pos += 4; if (this.pos > this.data.length) { - throw new Error(cc._LogInfos.e(6017)); + throw new Error(cc._getError(6017)); } } }, @@ -262,7 +262,7 @@ var PNGReader = cc._Class.extend({ } break; default: - throw new Error(cc._LogInfos.e(6018, data[pos - 1])); + throw new Error(cc._getError(6018, data[pos - 1])); } row++; } diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js index 66eaf411ca..4b4f88ca59 100644 --- a/cocos2d/particle/CCParticleSystem.js +++ b/cocos2d/particle/CCParticleSystem.js @@ -914,7 +914,7 @@ var ParticleSystem = cc.Class({ var self = this; cc.loader.load(file, function (err, content) { if (err || !content) { - throw err || new Error(cc._LogInfos.e(6029)); + throw err || new Error(cc._getError(6029)); } if (!self.isValid) { return; diff --git a/cocos2d/particle/CCTIFFReader.js b/cocos2d/particle/CCTIFFReader.js index 7a53999419..38f33dcafa 100644 --- a/cocos2d/particle/CCTIFFReader.js +++ b/cocos2d/particle/CCTIFFReader.js @@ -65,7 +65,7 @@ var tiffReader = /** @lends tiffReader# */{ this.littleEndian = false; } else { console.log(BOM); - throw TypeError(cc._LogInfos.e(6019)); + throw TypeError(cc._getError(6019)); } return this.littleEndian; @@ -74,7 +74,7 @@ var tiffReader = /** @lends tiffReader# */{ hasTowel: function () { // Check for towel. if (this.getUint16(2) !== 42) { - throw RangeError(cc._LogInfos.e(6020)); + throw RangeError(cc._getError(6020)); return false; } @@ -302,7 +302,7 @@ var tiffReader = /** @lends tiffReader# */{ if (numStripOffsetValues === 1) { var stripByteCountValues = [Math.ceil((imageWidth * imageLength * bitsPerPixel) / 8)]; } else { - throw Error(cc._LogInfos.e(6024)); + throw Error(cc._getError(6024)); } } @@ -332,7 +332,7 @@ var tiffReader = /** @lends tiffReader# */{ byteOffset = sampleInfo.byteOffset - stripOffset; bitOffset = sampleInfo.bitOffset; - throw RangeError(cc._LogInfos.e(6025)); + throw RangeError(cc._getError(6025)); } } @@ -342,7 +342,7 @@ var tiffReader = /** @lends tiffReader# */{ jIncrement = bytesPerPixel; } else { jIncrement = 0; - throw RangeError(cc._LogInfos.e(6026)); + throw RangeError(cc._getError(6026)); } break; @@ -412,7 +412,7 @@ var tiffReader = /** @lends tiffReader# */{ sample++; } } else { - throw RangeError(cc._LogInfos.e(6025)); + throw RangeError(cc._getError(6025)); } // Is our pixel complete? @@ -535,7 +535,7 @@ var tiffReader = /** @lends tiffReader# */{ // RGB Color Palette case 3: if (colorMapValues === undefined) { - throw Error(cc._LogInfos.e(6027)); + throw Error(cc._getError(6027)); } var colorMapIndex = pixelSamples[0]; @@ -547,7 +547,7 @@ var tiffReader = /** @lends tiffReader# */{ // Unknown Photometric Interpretation default: - throw RangeError(cc._LogInfos.e(6028, photometricInterpretation)); + throw RangeError(cc._getError(6028, photometricInterpretation)); break; } diff --git a/cocos2d/shaders/CCGLProgram.js b/cocos2d/shaders/CCGLProgram.js index 4e5161b359..80b14d74e1 100644 --- a/cocos2d/shaders/CCGLProgram.js +++ b/cocos2d/shaders/CCGLProgram.js @@ -194,9 +194,9 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ */ initWithVertexShaderFilename: function (vShaderFilename, fShaderFileName) { var vertexSource = cc.loader.getRes(vShaderFilename); - if (!vertexSource) throw new Error(cc._LogInfos.e(8106, vShaderFilename)); + if (!vertexSource) throw new Error(cc._getError(8106, vShaderFilename)); var fragmentSource = cc.loader.getRes(fShaderFileName); - if (!fragmentSource) throw new Error(cc._LogInfos.e(8106, fShaderFileName)); + if (!fragmentSource) throw new Error(cc._getError(8106, fShaderFileName)); return this.initWithVertexShaderByteArray(vertexSource, fragmentSource); }, @@ -296,9 +296,9 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ */ getUniformLocationForName: function (name) { if (!name) - throw new Error(cc._LogInfos.e(8107)); + throw new Error(cc._getError(8107)); if (!this._programObj) - throw new Error(cc._LogInfos.e(8108)); + throw new Error(cc._getError(8108)); var location = this._uniforms[name] || this._glContext.getUniformLocation(this._programObj, name); return location; @@ -682,7 +682,7 @@ cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{ _setUniformForMVPMatrixWithMat4: function(modelViewMatrix){ if(!modelViewMatrix) - throw new Error(cc._LogInfos.e(8109)); + throw new Error(cc._getError(8109)); this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_MVMATRIX], false, modelViewMatrix.mat); this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_PMATRIX], false, math.projection_matrix_stack.top.mat); }, diff --git a/cocos2d/tilemap/CCSGTMXLayer.js b/cocos2d/tilemap/CCSGTMXLayer.js index 0ba37797b9..b8bb77f611 100644 --- a/cocos2d/tilemap/CCSGTMXLayer.js +++ b/cocos2d/tilemap/CCSGTMXLayer.js @@ -473,7 +473,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ */ getTileAt: function (pos, y) { if (pos === undefined) { - throw new Error(cc._LogInfos.e(7226)); + throw new Error(cc._getError(7226)); } var x = pos; if (y === undefined) { @@ -481,7 +481,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ y = pos.y; } if (x >= this._layerSize.width || y >= this._layerSize.height || x < 0 || y < 0) { - throw new Error(cc._LogInfos.e(7227)); + throw new Error(cc._getError(7227)); } if (!this.tiles) { cc.logID(7204); @@ -523,7 +523,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ */ getTileGIDAt:function (pos, y) { if (pos === undefined) { - throw new Error(cc._LogInfos.e(7228)); + throw new Error(cc._getError(7228)); } var x = pos; if (y === undefined) { @@ -531,7 +531,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ y = pos.y; } if (x >= this._layerSize.width || y >= this._layerSize.height || x < 0 || y < 0) { - throw new Error(cc._LogInfos.e(7229)); + throw new Error(cc._getError(7229)); } if (!this.tiles) { cc.logID(7205); @@ -558,7 +558,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ */ setTileGID: function(gid, posOrX, flagsOrY, flags) { if (posOrX === undefined) { - throw new Error(cc._LogInfos.e(7230)); + throw new Error(cc._getError(7230)); } var pos; if (flags !== undefined || !(posOrX instanceof cc.Vec2)) { @@ -572,7 +572,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ 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(cc._LogInfos.e(7231)); + throw new Error(cc._getError(7231)); } if (!this.tiles) { cc.logID(7206); @@ -638,11 +638,11 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ */ getTileFlagsAt:function (pos, y) { if(!pos) - throw new Error(cc._LogInfos.e(7232)); + throw new Error(cc._getError(7232)); if(y !== undefined) pos = cc.p(pos, y); if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) - throw new Error(cc._LogInfos.e(7233)); + throw new Error(cc._getError(7233)); if(!this.tiles){ cc.logID(7208); return null; @@ -664,13 +664,13 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{ */ removeTileAt:function (pos, y) { if (!pos) { - throw new Error(cc._LogInfos.e(7234)); + throw new Error(cc._getError(7234)); } if (y !== undefined) { pos = cc.p(pos, y); } if (pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) { - throw new Error(cc._LogInfos.e(7235)); + throw new Error(cc._getError(7235)); } if (!this.tiles) { cc.logID(7209); diff --git a/cocos2d/tilemap/CCSGTMXTiledMap.js b/cocos2d/tilemap/CCSGTMXTiledMap.js index 4dffc2f9c1..ab121404a9 100644 --- a/cocos2d/tilemap/CCSGTMXTiledMap.js +++ b/cocos2d/tilemap/CCSGTMXTiledMap.js @@ -307,7 +307,7 @@ _ccsg.TMXTiledMap = _ccsg.Node.extend(/** @lends _ccsg.TMXTiledMap# */{ */ getLayer:function (layerName) { if(!layerName || layerName.length === 0) - throw new Error(cc._LogInfos.e(7224)); + throw new Error(cc._getError(7224)); var locChildren = this._children; for (var i = 0; i < locChildren.length; i++) { var layer = locChildren[i]; @@ -325,7 +325,7 @@ _ccsg.TMXTiledMap = _ccsg.Node.extend(/** @lends _ccsg.TMXTiledMap# */{ */ getObjectGroup:function (groupName) { if(!groupName || groupName.length === 0) - throw new Error(cc._LogInfos.e(7225)); + throw new Error(cc._getError(7225)); var locChildren = this._children; for (var i = 0; i < locChildren.length; i++) { var group = locChildren[i]; diff --git a/cocos2d/tilemap/CCTiledLayer.js b/cocos2d/tilemap/CCTiledLayer.js index 46a38d3e8e..60222ddefb 100644 --- a/cocos2d/tilemap/CCTiledLayer.js +++ b/cocos2d/tilemap/CCTiledLayer.js @@ -201,7 +201,7 @@ var TiledLayer = cc.Class({ setTileGID: function(gid, posOrX, flagsOrY, flags) { if (this._sgNode) { if(posOrX === undefined) - throw new Error(cc._LogInfos.e(7223)); + throw new Error(cc._getError(7223)); var pos; if (flags !== undefined || !(posOrX instanceof cc.Vec2)) { // four parameters or posOrX is not a Vec2 object diff --git a/cocos2d/tilemap/editor/tiled-map.js b/cocos2d/tilemap/editor/tiled-map.js index cf0f513cc1..5d82a3235d 100644 --- a/cocos2d/tilemap/editor/tiled-map.js +++ b/cocos2d/tilemap/editor/tiled-map.js @@ -12,7 +12,7 @@ const TMX_ENCODING = { encoding: 'utf-8' }; function searchDependFiles(tmxFile, tmxFileData, cb) { var doc = new DOMParser().parseFromString(tmxFileData); if (!doc) { - return cb(new Error(cc._LogInfos.e(7222, tmxFile))); + return cb(new Error(cc._getError(7222, tmxFile))); } var textures = []; diff --git a/index.js b/index.js index cafb809e25..a747248ee0 100644 --- a/index.js +++ b/index.js @@ -155,10 +155,7 @@ if (CC_DEV) { cc._Test = {}; } -// output all info before initialized -require('./DebugInfos'); require('./CCDebugger'); -cc._initDebugSetting(cc.DebugMode.INFO); // polyfills /* require('./polyfill/bind'); */ @@ -177,10 +174,7 @@ cp = {}; // LOAD COCOS2D ENGINE CODE -if (CC_EDITOR && Editor.isMainProcess) { - cc._initDebugSetting(1); // DEBUG_MODE_INFO -} -else { +if (!(CC_EDITOR && Editor.isMainProcess)) { require('./cocos2d/shaders'); require('./CCBoot'); require('./cocos2d'); diff --git a/jsb/index.js b/jsb/index.js index c105efbc9e..b198bf2b56 100644 --- a/jsb/index.js +++ b/jsb/index.js @@ -76,7 +76,6 @@ require('../cocos2d/core/utils/find'); require('../cocos2d/core/utils/mutable-forward-iterator'); require('../cocos2d/core/event'); require('../cocos2d/core/event-manager/CCEvent'); -require('../DebugInfos'); require('../CCDebugger'); // Mark memory model diff --git a/jsb/jsb-game.js b/jsb/jsb-game.js index 99d326690b..d7d43b6f7c 100644 --- a/jsb/jsb-game.js +++ b/jsb/jsb-game.js @@ -28,14 +28,6 @@ // cc.game cc.game = { - DEBUG_MODE_NONE: 0, - DEBUG_MODE_INFO: 1, - DEBUG_MODE_WARN: 2, - DEBUG_MODE_ERROR: 3, - DEBUG_MODE_INFO_FOR_WEB_PAGE: 4, - DEBUG_MODE_WARN_FOR_WEB_PAGE: 5, - DEBUG_MODE_ERROR_FOR_WEB_PAGE: 6, - EVENT_HIDE: "game_on_hide", EVENT_SHOW: "game_on_show", EVENT_RESIZE: "game_on_resize", @@ -328,5 +320,3 @@ cc.game._onHideListener = cc.eventManager.addCustomListener(cc.game.EVENT_HIDE, cc.game._onShowListener = cc.eventManager.addCustomListener(cc.game.EVENT_SHOW, function () { cc.game.emit(cc.game.EVENT_SHOW, cc.game); }); - -cc._initDebugSetting(cc.game.DEBUG_MODE_INFO); \ No newline at end of file From f17ff242f865ae5232be3042e70c71eff14979ef Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Wed, 27 Dec 2017 10:58:27 +0800 Subject: [PATCH 100/127] refine code --- cocos2d/core/videoplayer/CCSGVideoPlayer.js | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/cocos2d/core/videoplayer/CCSGVideoPlayer.js b/cocos2d/core/videoplayer/CCSGVideoPlayer.js index 53a9806e21..fb59246616 100644 --- a/cocos2d/core/videoplayer/CCSGVideoPlayer.js +++ b/cocos2d/core/videoplayer/CCSGVideoPlayer.js @@ -174,21 +174,21 @@ _ccsg.VideoPlayer.pauseElements = []; cc.game.on(cc.game.EVENT_HIDE, function () { var list = _ccsg.VideoPlayer.elements; - for (var node, i = 0; i < list.length; i++) { - node = list[i]; - if (node.isPlaying()) { - node.pause(); - _ccsg.VideoPlayer.pauseElements.push(node); + for (var element, i = 0; i < list.length; i++) { + element = list[i]; + if (element.isPlaying()) { + element.pause(); + _ccsg.VideoPlayer.pauseElements.push(element); } } }); cc.game.on(cc.game.EVENT_SHOW, function () { var list = _ccsg.VideoPlayer.pauseElements; - var node = list.pop(); - while (node) { - node.play(); - node = list.pop(); + var element = list.pop(); + while (element) { + element.play(); + element = list.pop(); } }); From b5c4f2fae6fc0b033e71aeaad6ec8244cc5aac19 Mon Sep 17 00:00:00 2001 From: shay_chen <641278529@qq.com> Date: Wed, 27 Dec 2017 18:34:35 +0800 Subject: [PATCH 101/127] Delete the calls for object.retain() and object.release() --- cocos2d/core/CCNode.js | 37 ------------------- cocos2d/core/CCScene.js | 3 -- cocos2d/core/collider/CCCollisionManager.js | 1 - cocos2d/core/components/CCCanvas.js | 3 -- cocos2d/core/components/CCLabel.js | 4 -- cocos2d/core/components/CCMask.js | 4 -- cocos2d/core/components/CCRendererInSG.js | 9 ----- cocos2d/core/graphics/graphics-webgl-cmd.js | 1 - .../physics/platform/CCPhysicsDebugDraw.js | 1 - cocos2d/tilemap/CCTiledLayer.js | 4 -- cocos2d/tilemap/CCTiledObjectGroup.js | 4 -- extensions/ccpool/CCPool.js | 8 ---- extensions/dragonbones/ArmatureDisplay.js | 3 -- extensions/spine/Skeleton.js | 3 -- 14 files changed, 85 deletions(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index e6086f79c5..68bd218d11 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -928,7 +928,6 @@ var Node = cc.Class({ */ var sgNode = this._sgNode = new _ccsg.Node(); if (CC_JSB) { - sgNode.retain(); sgNode._entity = this; sgNode.onEnter = function () { _ccsg.Node.prototype.onEnter.call(this); @@ -962,11 +961,6 @@ var Node = cc.Class({ // Mouse event listener this._mouseListener = null; - - // Retained actions for JSB - if (CC_JSB) { - this._retainedActions = []; - } }, statics: { @@ -1045,17 +1039,12 @@ var Node = cc.Class({ } if (CC_JSB) { - if (!cc.macro.ENABLE_GC_FOR_NATIVE_OBJECTS) { - this._releaseAllActions(); - } if (this._touchListener) { - this._touchListener.release(); this._touchListener.owner = null; this._touchListener.mask = null; this._touchListener = null; } if (this._mouseListener) { - this._mouseListener.release(); this._mouseListener.owner = null; this._mouseListener.mask = null; this._mouseListener = null; @@ -1216,9 +1205,6 @@ var Node = cc.Class({ onTouchMoved: _touchMoveHandler, onTouchEnded: _touchEndHandler }); - if (CC_JSB) { - this._touchListener.retain(); - } eventManager.addListener(this._touchListener, this); newAdded = true; } @@ -1235,9 +1221,6 @@ var Node = cc.Class({ onMouseUp: _mouseUpHandler, onMouseScroll: _mouseWheelHandler, }); - if (CC_JSB) { - this._mouseListener.retain(); - } eventManager.addListener(this._mouseListener, this); newAdded = true; } @@ -1589,22 +1572,6 @@ var Node = cc.Class({ return 0; }, - _retainAction (action) { - if (CC_JSB && action instanceof cc.Action && this._retainedActions.indexOf(action) === -1) { - this._retainedActions.push(action); - action.retain(); - } - }, - - _releaseAllActions () { - if (CC_JSB) { - for (var i = 0; i < this._retainedActions.length; ++i) { - this._retainedActions[i].release(); - } - this._retainedActions.length = 0; - } - }, - setTag (value) { this._tag = value; this._sgNode.tag = value; @@ -2568,16 +2535,12 @@ if (CC_JSB) { this.__sgNode = value; if (this._touchListener || this._mouseListener) { if (this._touchListener) { - this._touchListener.retain(); eventManager.removeListener(this._touchListener); eventManager.addListener(this._touchListener, this); - this._touchListener.release(); } if (this._mouseListener) { - this._mouseListener.retain(); eventManager.removeListener(this._mouseListener); eventManager.addListener(this._mouseListener, this); - this._mouseListener.release(); } cc.director.once(cc.Director.EVENT_BEFORE_UPDATE, updateListeners, this); } diff --git a/cocos2d/core/CCScene.js b/cocos2d/core/CCScene.js index a3a76e2d57..3e9ee97d21 100644 --- a/cocos2d/core/CCScene.js +++ b/cocos2d/core/CCScene.js @@ -52,9 +52,6 @@ cc.Scene = cc.Class({ ctor: function () { var sgNode = this._sgNode = new _ccsg.Scene(); - if (CC_JSB) { - sgNode.retain(); - } sgNode.setAnchorPoint(0.0, 0.0); this._anchorPoint.x = 0.0; this._anchorPoint.y = 0.0; diff --git a/cocos2d/core/collider/CCCollisionManager.js b/cocos2d/core/collider/CCCollisionManager.js index ea618f846f..d050d93846 100644 --- a/cocos2d/core/collider/CCCollisionManager.js +++ b/cocos2d/core/collider/CCCollisionManager.js @@ -417,7 +417,6 @@ cc.js.getset(CollisionManager.prototype, 'enabledDebugDraw', if (value && !this._enabledDebugDraw) { if (!this._debugDrawer) { this._debugDrawer = new _ccsg.GraphicsNode(); - this._debugDrawer.retain(); } cc.director.getScene()._sgNode.addChild(this._debugDrawer); diff --git a/cocos2d/core/components/CCCanvas.js b/cocos2d/core/components/CCCanvas.js index 0f71867ec4..280442c533 100644 --- a/cocos2d/core/components/CCCanvas.js +++ b/cocos2d/core/components/CCCanvas.js @@ -144,8 +144,6 @@ var Canvas = cc.Class({ eventName: "window-resize", callback: this.onResized.bind(this) }); - - this._thisOnResized.retain(); } else { this._thisOnResized = this.onResized.bind(this); @@ -218,7 +216,6 @@ var Canvas = cc.Class({ } else { eventManager.removeListener(this._thisOnResized); - this._thisOnResized.release(); } if (Canvas.instance === this) { diff --git a/cocos2d/core/components/CCLabel.js b/cocos2d/core/components/CCLabel.js index 7da167c676..419e9c22eb 100644 --- a/cocos2d/core/components/CCLabel.js +++ b/cocos2d/core/components/CCLabel.js @@ -528,10 +528,6 @@ var Label = cc.Class({ sgNode = this._sgNode = _ccsg.Label.pool.get(this.string, font, null, this._fontSize); } - if (CC_JSB) { - sgNode.retain(); - } - if (font instanceof cc.BitmapFont) { this._bmFontOriginalSize = font.fontSize; } diff --git a/cocos2d/core/components/CCMask.js b/cocos2d/core/components/CCMask.js index cb5bf34a2e..37eb61f655 100644 --- a/cocos2d/core/components/CCMask.js +++ b/cocos2d/core/components/CCMask.js @@ -295,9 +295,6 @@ var Mask = cc.Class({ var isDrawNode = stencil instanceof cc.DrawNode; if (!isDrawNode) { stencil = new cc.DrawNode(); - if (CC_JSB) { - stencil.retain(); - } this._sgNode.setStencil(stencil); } var width = contentSize.width; @@ -336,7 +333,6 @@ if (CC_JSB) { Mask.prototype.onDestroy = function () { this.__superOnDestroy(); if (this._clippingStencil) { - this._clippingStencil.release(); this._clippingStencil = null; } }; diff --git a/cocos2d/core/components/CCRendererInSG.js b/cocos2d/core/components/CCRendererInSG.js index 7adaed58e1..0c5e2b836f 100644 --- a/cocos2d/core/components/CCRendererInSG.js +++ b/cocos2d/core/components/CCRendererInSG.js @@ -46,17 +46,9 @@ var RendererInSG = cc.Class({ if (CC_EDITOR && !sgNode) { cc.errorID(1627); } - if (CC_JSB) { - // retain immediately - // will be released in onDestroy - sgNode.retain(); - } // The replacement node used when this component disabled this._plainNode = new _ccsg.Node(); - if (CC_JSB) { - this._plainNode.retain(); - } }, __preload: function () { @@ -88,7 +80,6 @@ var RendererInSG = cc.Class({ if (CC_JSB) { var releasedByNode = this.node._sgNode; if (this._plainNode !== releasedByNode) { - this._plainNode.release(); this._plainNode = null; } } diff --git a/cocos2d/core/graphics/graphics-webgl-cmd.js b/cocos2d/core/graphics/graphics-webgl-cmd.js index dd0f08f17e..20f8aa664e 100644 --- a/cocos2d/core/graphics/graphics-webgl-cmd.js +++ b/cocos2d/core/graphics/graphics-webgl-cmd.js @@ -207,7 +207,6 @@ function WebGLRenderCmd (renderable) { // init shader var shader = new cc.GLProgram(); shader.initWithVertexShaderByteArray(cc.PresetShaders.POSITION_COLOR_VERT, cc.PresetShaders.POSITION_COLOR_FRAG); - shader.retain(); shader.addAttribute(cc.macro.ATTRIBUTE_NAME_POSITION, cc.macro.VERTEX_ATTRIB_POSITION); shader.addAttribute(cc.macro.ATTRIBUTE_NAME_COLOR, cc.macro.VERTEX_ATTRIB_COLOR); shader.link(); diff --git a/cocos2d/core/physics/platform/CCPhysicsDebugDraw.js b/cocos2d/core/physics/platform/CCPhysicsDebugDraw.js index 8a1c763ec9..288c3829c6 100644 --- a/cocos2d/core/physics/platform/CCPhysicsDebugDraw.js +++ b/cocos2d/core/physics/platform/CCPhysicsDebugDraw.js @@ -6,7 +6,6 @@ var PhysicsDebugDraw = cc.Class({ ctor: function () { this._drawer = new _ccsg.GraphicsNode(); - this._drawer.retain(); }, getDrawer: function () { diff --git a/cocos2d/tilemap/CCTiledLayer.js b/cocos2d/tilemap/CCTiledLayer.js index 60222ddefb..650e8d4904 100644 --- a/cocos2d/tilemap/CCTiledLayer.js +++ b/cocos2d/tilemap/CCTiledLayer.js @@ -81,10 +81,6 @@ var TiledLayer = cc.Class({ if (sgNode && sgNode instanceof _ccsg.TMXLayer) { this._sgNode = sgNode; - if (CC_JSB) { - // retain the new sgNode, it will be released in _removeSgNode - sgNode.retain(); - } this._initSgNode(); } else { diff --git a/cocos2d/tilemap/CCTiledObjectGroup.js b/cocos2d/tilemap/CCTiledObjectGroup.js index 009932e59f..15d82f50a2 100644 --- a/cocos2d/tilemap/CCTiledObjectGroup.js +++ b/cocos2d/tilemap/CCTiledObjectGroup.js @@ -75,10 +75,6 @@ var TiledObjectGroup = cc.Class({ if (sgNode && sgNode instanceof _ccsg.TMXObjectGroup) { this._sgNode = sgNode; - if (CC_JSB) { - // retain the new sgNode, it will be released in _removeSgNode - sgNode.retain(); - } this._initSgNode(); } else { diff --git a/extensions/ccpool/CCPool.js b/extensions/ccpool/CCPool.js index 7d06cd207b..8424fbe1b6 100644 --- a/extensions/ccpool/CCPool.js +++ b/extensions/ccpool/CCPool.js @@ -69,8 +69,6 @@ cc.pool = /** @lends cc.pool# */{ if (!this._pool[cid]) { this._pool[cid] = []; } - // JSB retain to avoid being auto released - CC_JSB && obj.retain && obj.retain(); // User implementation for disable the object obj.unuse && obj.unuse(); this._pool[cid].push(obj); @@ -104,8 +102,6 @@ cc.pool = /** @lends cc.pool# */{ if (list) { for (var i = 0; i < list.length; i++) { if (obj === list[i]) { - // JSB release to avoid memory leak - CC_JSB && obj.release && obj.release(); list.splice(i, 1); } } @@ -130,8 +126,6 @@ cc.pool = /** @lends cc.pool# */{ var obj = list.pop(); // User implementation for re-enable the object obj.reuse && obj.reuse.apply(obj, _args); - // JSB release to avoid memory leak - CC_JSB && obj.release && this._autoRelease(obj); _args.length = 0; return obj; } @@ -147,8 +141,6 @@ cc.pool = /** @lends cc.pool# */{ for (var i in this._pool) { for (var j = 0; j < this._pool[i].length; j++) { var obj = this._pool[i][j]; - // JSB release to avoid memory leak - obj.release && obj.release(); } } } diff --git a/extensions/dragonbones/ArmatureDisplay.js b/extensions/dragonbones/ArmatureDisplay.js index 7da61faa73..6904d3adc4 100644 --- a/extensions/dragonbones/ArmatureDisplay.js +++ b/extensions/dragonbones/ArmatureDisplay.js @@ -412,9 +412,6 @@ dragonBones.ArmatureDisplay = cc.Class({ // recreate sgNode... var sgNode = self._sgNode = self._createSgNode(); if (sgNode) { - if (CC_JSB) { - sgNode.retain(); - } if (!self.enabledInHierarchy) { sgNode.setVisible(false); } diff --git a/extensions/spine/Skeleton.js b/extensions/spine/Skeleton.js index ba09fe5eea..a39fb5b43b 100644 --- a/extensions/spine/Skeleton.js +++ b/extensions/spine/Skeleton.js @@ -1059,9 +1059,6 @@ sp.Skeleton = cc.Class({ // recreate sgNode... var sgNode = self._sgNode = self._createSgNode(); if (sgNode) { - if (CC_JSB) { - sgNode.retain(); - } if ( !self.enabledInHierarchy ) { sgNode.setVisible(false); } From 55319542d96f32d3093238de79a2602cea709db3 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 28 Dec 2017 10:21:39 +0800 Subject: [PATCH 102/127] fix incompatibility when upgrading uglify-es from 3.2 to 3.3 --- gulp/util/utils.js | 1 - 1 file changed, 1 deletion(-) diff --git a/gulp/util/utils.js b/gulp/util/utils.js index a41839f33d..6de32cab5d 100644 --- a/gulp/util/utils.js +++ b/gulp/util/utils.js @@ -75,7 +75,6 @@ exports.getUglifyOptions = function (platform, isJSB, isDebugBuild) { if_return: false, // optimize if-s followed by return/continue inline: false, // embed simple functions join_vars: false, // join var declarations - cascade: false, // try to cascade `right` into `left` in sequences collapse_vars: false, // Collapse single-use non-constant variables - side effects permitting. reduce_vars: false, // Improve optimization on variables assigned with and used as constant values. //warnings: true, From c068b988813d345fd121e89611489190cb384c05 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 28 Dec 2017 19:40:54 +0800 Subject: [PATCH 103/127] lock uglifyjs to new version --- .github/PULL_REQUEST_TEMPLATE.md | 9 ++++++--- gulp/util/utils.js | 18 ++++++++++++------ package.json | 2 +- 3 files changed, 19 insertions(+), 10 deletions(-) diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 407619de4a..0f7b215960 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -3,11 +3,14 @@ Re: cocos-creator/fireball# Changelog: * -> Makes sure these boxes are checked before submitting your PR - thank you! -> + \ No newline at end of file diff --git a/gulp/util/utils.js b/gulp/util/utils.js index fddfd7b6e1..289dca4ce8 100644 --- a/gulp/util/utils.js +++ b/gulp/util/utils.js @@ -35,6 +35,7 @@ exports.getUglifyOptions = function (platform, isJSB, isDebugBuild) { sequences: false, keep_infinity: true, // reduce jsc file size typeofs: false, + inline: false, // embed simple functions, disable temporarily due to https://github.com/mishoo/UglifyJS2/issues/2683 } }; } @@ -43,6 +44,7 @@ exports.getUglifyOptions = function (platform, isJSB, isDebugBuild) { return { compress: { global_defs: global_defs, + inline: false // embed simple functions, disable temporarily due to https://github.com/mishoo/UglifyJS2/issues/2683 }, output: { ascii_only: true, @@ -60,26 +62,30 @@ exports.getUglifyOptions = function (platform, isJSB, isDebugBuild) { ascii_only: true, }, compress: { - // https://github.com/mishoo/UglifyJS2#compressor-options + // https://github.com/mishoo/UglifyJS2/tree/harmony#compress-options global_defs: global_defs, sequences: false, // join consecutive statements with the “comma operator” properties: false, // optimize property access: a["foo"] → a.foo - //dead_code: true, // discard unreachable code + // dead_code: true, // discard unreachable code drop_debugger: false, // discard “debugger” statements + // ecma: 5, // transform ES5 code into smaller ES6+ equivalent forms + // evaluate: true, // evaluate constant expressions unsafe: false, // some unsafe optimizations (see below) - //conditionals: false, // optimize if-s and conditional expressions + // computed_props: true, + // conditionals: false, // optimize if-s and conditional expressions comparisons: false, // optimize comparisons - //evaluate: true, // evaluate constant expressions booleans: false, // optimize boolean expressions typeofs: false, // Transforms typeof foo == "undefined" into foo === void 0. Note: recommend to set this value to false for IE10 and earlier versions due to known issues. loops: false, // optimize loops unused: false, // drop unused variables/functions hoist_funs: false, // hoist function declarations + hoist_props: false, hoist_vars: false, // hoist variable declarations if_return: false, // optimize if-s followed by return/continue - inline: false, // embed simple functions + inline: false, // embed simple functions, disable temporarily due to https://github.com/mishoo/UglifyJS2/issues/2683 join_vars: false, // join var declarations collapse_vars: false, // Collapse single-use non-constant variables - side effects permitting. + reduce_funcs: false, reduce_vars: false, // Improve optimization on variables assigned with and used as constant values. //warnings: true, negate_iife: false, @@ -90,7 +96,7 @@ exports.getUglifyOptions = function (platform, isJSB, isDebugBuild) { keep_fargs: true, keep_fnames: true, keep_infinity: true, // Pass true to prevent Infinity from being compressed into 1/0, which may cause performance issues on Chrome. - side_effects: false // drop side-effect-free statements + side_effects: false, // drop side-effect-free statements } }; } diff --git a/package.json b/package.json index 633584b877..54846f1467 100644 --- a/package.json +++ b/package.json @@ -44,7 +44,7 @@ "jshint-stylish": "2.1.0", "multipipe": "0.3.0", "persistify": "^1.1.1", - "uglify-es": "^3.0.26", + "uglify-es": "~3.3.2", "vinyl": "1.1.0", "vinyl-buffer": "1.0.0", "vinyl-source-stream": "1.0.0", From a96ac0d0bb395d5bfae53980118e76c285d46b8c Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 28 Dec 2017 20:39:01 +0800 Subject: [PATCH 104/127] add issue template --- .github/ISSUE_TEMPLATE.md | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE.md diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000000..893374c0a7 --- /dev/null +++ b/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,32 @@ + + +### Creator version?(版本号) + + +### Affected platform?(受影响的平台) + + +### How to reproduce?(如何重现) + + +### JavaScript output or error produced?(报错信息和调用栈) + + +### Demo project?(demo 项目) + + + From bad036fbf8c4b78b8e16603ca0de6b4084585784 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Fri, 29 Dec 2017 18:49:54 +0800 Subject: [PATCH 105/127] encapsulate uglify pipe for editor --- gulp/tasks/engine.js | 19 ++++++------------- gulp/tasks/test.js | 5 +---- gulp/util/utils.js | 9 ++++++++- 3 files changed, 15 insertions(+), 18 deletions(-) diff --git a/gulp/tasks/engine.js b/gulp/tasks/engine.js index 47c835300f..a429333202 100644 --- a/gulp/tasks/engine.js +++ b/gulp/tasks/engine.js @@ -32,9 +32,6 @@ const Path = require('path'); const Source = require('vinyl-source-stream'); const Gulp = require('gulp'); const Buffer = require('vinyl-buffer'); -const Composer = require('gulp-uglify/composer'); -const Uglify = require('uglify-es'); -const Minify = Composer(Uglify, console); const Sourcemaps = require('gulp-sourcemaps'); const EventStream = require('event-stream'); const Chalk = require('chalk'); @@ -106,13 +103,11 @@ exports.buildCocosJs = function (sourceFile, outputFile, excludes, callback) { bundler.ignore(file); }); - var uglifyOption = Utils.getUglifyOptions('build', false, true); - bundler = bundler.bundle(); bundler = bundler.pipe(Source(outFile)); bundler = bundler.pipe(Buffer()); bundler = bundler.pipe(Sourcemaps.init({loadMaps: true})); - bundler = bundler.pipe(Minify(uglifyOption)); + bundler = bundler.pipe(Utils.uglify('build', false, true)); bundler = bundler.pipe(Optimizejs({ sourceMap: false })); @@ -134,8 +129,6 @@ exports.buildCocosJsMin = function (sourceFile, outputFile, excludes, callback, bundler.ignore(file); }); - var uglifyOption = Utils.getUglifyOptions('build', false, false); - var Size = null; try { Size = require('gulp-size'); @@ -155,7 +148,7 @@ exports.buildCocosJsMin = function (sourceFile, outputFile, excludes, callback, console.error('Can not use sourcemap with optimize-js'); bundler = bundler.pipe(Sourcemaps.init({loadMaps: true})); } - bundler = bundler.pipe(Minify(uglifyOption)); + bundler = bundler.pipe(Utils.uglify('build', false, false)); bundler = bundler.pipe(Optimizejs({ sourceMap: false })); @@ -200,7 +193,7 @@ exports.buildPreview = function (sourceFile, outputFile, callback, devMode) { if (!devMode) { bundler = bundler .pipe(Sourcemaps.init({loadMaps: true})) - .pipe(Minify(Utils.getUglifyOptions('preview', false, false))) + .pipe(Utils.uglify('preview', false, false)) .pipe(Optimizejs({ sourceMap: false })) @@ -233,7 +226,7 @@ exports.buildJsbPreview = function (sourceFile, outputFile, excludes, callback) .pipe(Source(outFile)) .pipe(Buffer()) .pipe(FixJavaScriptCore()) - .pipe(Minify(Utils.getUglifyOptions('preview', true, false))) + .pipe(Utils.uglify('preview', true, false)) .pipe(Optimizejs({ sourceMap: false })) @@ -259,7 +252,7 @@ exports.buildJsb = function (sourceFile, outputFile, excludes, callback) { .pipe(Source(outFile)) .pipe(Buffer()) .pipe(FixJavaScriptCore()) - .pipe(Minify(Utils.getUglifyOptions('build', true, true))) + .pipe(Utils.uglify('build', true, true)) .pipe(Optimizejs({ sourceMap: false })) @@ -285,7 +278,7 @@ exports.buildJsbMin = function (sourceFile, outputFile, excludes, callback) { .pipe(Source(outFile)) .pipe(Buffer()) .pipe(FixJavaScriptCore()) - .pipe(Minify(Utils.getUglifyOptions('build', true, false))) + .pipe(Utils.uglify('build', true, false)) .pipe(Optimizejs({ sourceMap: false })) diff --git a/gulp/tasks/test.js b/gulp/tasks/test.js index 45fee2cae9..d6ee86d2a9 100644 --- a/gulp/tasks/test.js +++ b/gulp/tasks/test.js @@ -38,9 +38,6 @@ const HandleErrors = require('../util/handleErrors'); const Es = require('event-stream'); const Sourcemaps = require('gulp-sourcemaps'); -const Composer = require('gulp-uglify/composer'); -const Uglify = require('uglify-es'); -const Minify = Composer(Uglify, console); const Utils = require('../util/utils'); const createBundler = require('../util/create-bundler'); @@ -63,7 +60,7 @@ exports.build = function (sourceFile, outputFile, sourceFileForExtends, outputFi } // remove `...args` used in CC_JSB - engine = engine.pipe(Minify(Utils.getUglifyOptions('test', false, false))); + engine = engine.pipe(Utils.uglify('test', false, false)); if (sourcemaps) { engine = engine.pipe(Sourcemaps.write('./', { diff --git a/gulp/util/utils.js b/gulp/util/utils.js index 289dca4ce8..e194dd7e45 100644 --- a/gulp/util/utils.js +++ b/gulp/util/utils.js @@ -19,6 +19,7 @@ exports.getMacros = function (platform, isJSB, isDebugBuild) { return res; }; +// see https://github.com/mishoo/UglifyJS2/tree/harmony#compress-options exports.getUglifyOptions = function (platform, isJSB, isDebugBuild) { var global_defs = exports.getMacros(platform, isJSB, isDebugBuild); var releaseMode = !global_defs['CC_DEBUG']; @@ -62,7 +63,6 @@ exports.getUglifyOptions = function (platform, isJSB, isDebugBuild) { ascii_only: true, }, compress: { - // https://github.com/mishoo/UglifyJS2/tree/harmony#compress-options global_defs: global_defs, sequences: false, // join consecutive statements with the “comma operator” properties: false, // optimize property access: a["foo"] → a.foo @@ -101,3 +101,10 @@ exports.getUglifyOptions = function (platform, isJSB, isDebugBuild) { }; } }; + +exports.uglify = function (platform, isJSB, isDebugBuild) { + const Composer = require('gulp-uglify/composer'); + const Uglify = require('uglify-es'); + const minify = Composer(Uglify); + return minify(exports.getUglifyOptions(platform, isJSB, isDebugBuild)); +}; From cc5dcab175f39a098b14c8fef9d263398fa74509 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Sat, 30 Dec 2017 14:44:16 +0800 Subject: [PATCH 106/127] update uglify-es to fix regex problem (mishoo/UglifyJS2#2242) and inline problem --- gulp/util/utils.js | 4 +--- package.json | 2 +- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/gulp/util/utils.js b/gulp/util/utils.js index e194dd7e45..f0f16b168a 100644 --- a/gulp/util/utils.js +++ b/gulp/util/utils.js @@ -36,7 +36,6 @@ exports.getUglifyOptions = function (platform, isJSB, isDebugBuild) { sequences: false, keep_infinity: true, // reduce jsc file size typeofs: false, - inline: false, // embed simple functions, disable temporarily due to https://github.com/mishoo/UglifyJS2/issues/2683 } }; } @@ -45,7 +44,6 @@ exports.getUglifyOptions = function (platform, isJSB, isDebugBuild) { return { compress: { global_defs: global_defs, - inline: false // embed simple functions, disable temporarily due to https://github.com/mishoo/UglifyJS2/issues/2683 }, output: { ascii_only: true, @@ -82,7 +80,7 @@ exports.getUglifyOptions = function (platform, isJSB, isDebugBuild) { hoist_props: false, hoist_vars: false, // hoist variable declarations if_return: false, // optimize if-s followed by return/continue - inline: false, // embed simple functions, disable temporarily due to https://github.com/mishoo/UglifyJS2/issues/2683 + inline: false, // embed simple functions join_vars: false, // join var declarations collapse_vars: false, // Collapse single-use non-constant variables - side effects permitting. reduce_funcs: false, diff --git a/package.json b/package.json index 54846f1467..34f1691165 100644 --- a/package.json +++ b/package.json @@ -44,7 +44,7 @@ "jshint-stylish": "2.1.0", "multipipe": "0.3.0", "persistify": "^1.1.1", - "uglify-es": "~3.3.2", + "uglify-es": "~3.3.3", "vinyl": "1.1.0", "vinyl-buffer": "1.0.0", "vinyl-source-stream": "1.0.0", From 7a49509dc2347f606705ead1cf81020d32911a01 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 28 Dec 2017 10:19:46 +0800 Subject: [PATCH 107/127] refactor dragonbones asset managment --- cocos2d/core/load-pipeline/CCLoader.js | 4 +- extensions/dragonbones/ArmatureDisplay.js | 77 ++-------------- extensions/dragonbones/CCArmatureDisplay.js | 6 +- extensions/dragonbones/CCFactory.js | 27 ++++-- extensions/dragonbones/CCSlot.js | 5 +- extensions/dragonbones/CCTextureData.js | 6 +- extensions/dragonbones/DragonBonesAsset.js | 91 +++++++++++++++---- .../dragonbones/DragonBonesAtlasAsset.js | 61 ++++++++++++- 8 files changed, 168 insertions(+), 109 deletions(-) diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js index 434203d816..4c5b567f7f 100644 --- a/cocos2d/core/load-pipeline/CCLoader.js +++ b/cocos2d/core/load-pipeline/CCLoader.js @@ -766,12 +766,10 @@ proto.release = function (asset) { asset = item.content; // TODO: AUDIO if (asset instanceof cc.Asset) { - if (asset instanceof cc.Texture2D) { - asset.destroy(); - } if (asset.nativeUrl) { this.release(asset.nativeUrl); } + asset.destroy(); } if (CC_DEBUG && removed) { this._releasedAssetChecker_DEBUG.setReleased(item, id); diff --git a/extensions/dragonbones/ArmatureDisplay.js b/extensions/dragonbones/ArmatureDisplay.js index 7da61faa73..717354e5ab 100644 --- a/extensions/dragonbones/ArmatureDisplay.js +++ b/extensions/dragonbones/ArmatureDisplay.js @@ -69,12 +69,6 @@ dragonBones.ArmatureDisplay = cc.Class({ serializable: false, }, - _dragonBonesData: { - default: null, - type: dragonBones.DragonBonesData, - serializable: false, - }, - /** * !#en * The DragonBones data contains the armatures information (bind pose bones, slots, draw order, @@ -303,7 +297,7 @@ dragonBones.ArmatureDisplay = cc.Class({ _createSgNode: function () { if (this.dragonAsset && this.dragonAtlasAsset && this.armatureName) { - return this._factory.buildArmatureDisplay(this.armatureName, this._dragonBonesData.name); + return this._factory.buildArmatureDisplay(this.armatureName, this.dragonAsset._dragonBonesData.name); } return null; }, @@ -332,65 +326,13 @@ dragonBones.ArmatureDisplay = cc.Class({ _parseDragonAsset: function () { if (this.dragonAsset) { - if (CC_JSB) { - // The '_factory' create a new one every time in JSB, they can't use getDragonBonesData - // to get cached data, and only parse data every time - this._dragonBonesData = this._factory.parseDragonBonesData(this.dragonAsset.dragonBonesJson); - } - else { - var jsonObj = JSON.parse(this.dragonAsset.dragonBonesJson); - var data = this._factory.getDragonBonesData(jsonObj.name); - if (data) { - // already added asset - var armature, dragonBonesData; - for (var i = 0, len = jsonObj.armature.length; i < len; i++) { - armature = jsonObj.armature[i]; - if (!data.armatures[armature.name]) { - //add new armature - if (!dragonBonesData) { - dragonBonesData = this._factory._dataParser.parseDragonBonesData(jsonObj); - } - data.addArmature(dragonBonesData.armatures[armature.name]); - } - } - this._dragonBonesData = data; - return; - } - this._dragonBonesData = this._factory.parseDragonBonesData(jsonObj); - } + this.dragonAsset.init(this._factory); } }, _parseDragonAtlasAsset: function () { - var asset = this.dragonAtlasAsset; - if (asset) { - if (CC_JSB) { - // TODO parse the texture atlas data from json string & texture path - this._factory.parseTextureAtlasData(asset.atlasJson, asset.texture && asset.texture.url); - } - else { - var atlasJsonObj = JSON.parse(asset.atlasJson); - var atlasName = atlasJsonObj.name; - var existedAtlasData = null; - var atlasDataList = this._factory.getTextureAtlasData(atlasName); - if (atlasDataList && atlasDataList.length > 0) { - var texturePath = asset.texture && asset.texture.url; - for (var idx in atlasDataList) { - var data = atlasDataList[idx]; - if (data && data.texture && data.texture.url === texturePath) { - existedAtlasData = data; - break; - } - } - } - - if (existedAtlasData) { - existedAtlasData.texture = asset.texture; - } - else { - this._factory.parseTextureAtlasData(atlasJsonObj, asset.texture); - } - } + if (this.dragonAtlasAsset) { + this.dragonAtlasAsset.init(this._factory); } }, @@ -507,11 +449,8 @@ dragonBones.ArmatureDisplay = cc.Class({ * @returns {Array} */ getArmatureNames: function () { - if (this._dragonBonesData) { - return this._dragonBonesData.armatureNames; - } - - return []; + var dragonBonesData = this.dragonAsset && this.dragonAsset._dragonBonesData; + return (dragonBonesData && dragonBonesData.armatureNames) || []; }, /** @@ -525,8 +464,8 @@ dragonBones.ArmatureDisplay = cc.Class({ */ getAnimationNames: function (armatureName) { var ret = []; - if (this._dragonBonesData) { - var armatureData = this._dragonBonesData.getArmature(armatureName); + if (this.dragonAsset && this.dragonAsset._dragonBonesData) { + var armatureData = this.dragonAsset._dragonBonesData.getArmature(armatureName); if (armatureData) { for (var animName in armatureData.animations) { if (armatureData.animations.hasOwnProperty(animName)) { diff --git a/extensions/dragonbones/CCArmatureDisplay.js b/extensions/dragonbones/CCArmatureDisplay.js index 07a96a6048..c92f39ba77 100644 --- a/extensions/dragonbones/CCArmatureDisplay.js +++ b/extensions/dragonbones/CCArmatureDisplay.js @@ -30,8 +30,10 @@ dragonBones.CCArmatureDisplay = cc.Class({ extends: _ccsg.Node, mixins: [EventTarget], - _armature : null, - _debugDrawer : null, + ctor () { + this._armature = null; + this._debugDrawer = null; + }, _onClear : function () { this._armature = null; diff --git a/extensions/dragonbones/CCFactory.js b/extensions/dragonbones/CCFactory.js index ead1eb90a6..fa2e5285d4 100644 --- a/extensions/dragonbones/CCFactory.js +++ b/extensions/dragonbones/CCFactory.js @@ -24,10 +24,20 @@ var BaseObject = dragonBones.BaseObject; -dragonBones.CCFactory = cc.Class({ +var CCFactory = dragonBones.CCFactory = cc.Class({ name: 'dragonBones.CCFactory', extends: dragonBones.BaseFactory, + statics: { + _factory: null, + getFactory () { + if (!CCFactory._factory) { + CCFactory._factory = new CCFactory(); + } + return CCFactory._factory; + } + }, + buildArmatureDisplay : function (armatureName, dragonBonesName, skinName) { var armature = this.buildArmature(armatureName, dragonBonesName, skinName); var armatureDisplay = armature ? armature._display : null; @@ -38,6 +48,11 @@ dragonBones.CCFactory = cc.Class({ return armatureDisplay; }, + parseTextureAtlasData (jsonString, texture) { + var atlasJsonObj = JSON.parse(jsonString); + return this._super(atlasJsonObj, texture); + }, + _generateTextureAtlasData : function (textureAtlasData, texture) { if (! textureAtlasData) { textureAtlasData = BaseObject.borrowObject(dragonBones.CCTextureAtlasData); @@ -141,7 +156,7 @@ dragonBones.CCFactory = cc.Class({ var offset = cc.p(0, 0); var originSize = cc.size(textureData.region.width, textureData.region.height); textureData.texture = new cc.SpriteFrame(); - textureData.texture.setTexture(textureAtlasTexture, rect, textureData.rotated, offset, originSize); // TODO multiply textureAtlas + textureData.texture.setTexture(textureAtlasTexture, rect, textureData.rotated, offset, originSize); } return new cc.Scale9Sprite(textureData.texture); @@ -150,11 +165,3 @@ dragonBones.CCFactory = cc.Class({ return null; } }); - -dragonBones.CCFactory._factory = null; -dragonBones.CCFactory.getFactory = function() { - if (!dragonBones.CCFactory._factory) { - dragonBones.CCFactory._factory = new dragonBones.CCFactory(); - } - return dragonBones.CCFactory._factory; -}; diff --git a/extensions/dragonbones/CCSlot.js b/extensions/dragonbones/CCSlot.js index d4051d909b..6c37807fce 100644 --- a/extensions/dragonbones/CCSlot.js +++ b/extensions/dragonbones/CCSlot.js @@ -25,7 +25,10 @@ dragonBones.CCSlot = cc.Class({ name: 'dragonBones.CCSlot', extends: dragonBones.Slot, - _renderDisplay : null, + + ctor () { + this._renderDisplay = null; + }, statics : { toString: function () { diff --git a/extensions/dragonbones/CCTextureData.js b/extensions/dragonbones/CCTextureData.js index cc6b8dc226..0278222a2e 100644 --- a/extensions/dragonbones/CCTextureData.js +++ b/extensions/dragonbones/CCTextureData.js @@ -52,6 +52,7 @@ dragonBones.CCTextureData = cc.Class({ extends: dragonBones.TextureData, properties: { + // SpriteFrame texture: { default: null, serializable: false @@ -66,9 +67,6 @@ dragonBones.CCTextureData = cc.Class({ _onClear: function () { dragonBones.TextureData.prototype._onClear.call(this); - if (this.texture) { - this.texture.dispose(); - this.texture = null; - } + this.texture = null; } }); diff --git a/extensions/dragonbones/DragonBonesAsset.js b/extensions/dragonbones/DragonBonesAsset.js index cb4b36fff9..6f463882c6 100644 --- a/extensions/dragonbones/DragonBonesAsset.js +++ b/extensions/dragonbones/DragonBonesAsset.js @@ -37,6 +37,10 @@ var DragonBonesAsset = cc.Class({ name: 'dragonBones.DragonBonesAsset', extends: cc.Asset, + ctor () { + this.reset(); + }, + properties: { _dragonBonesJson : '', @@ -68,32 +72,74 @@ var DragonBonesAsset = cc.Class({ return callback(null, node); }, - reset : function() { + reset () { + this._dragonBonesData = null; if (CC_EDITOR) { - this._dragonBonesDataCache = null; this._armaturesEnum = null; } }, + init: function (factory) { + if (CC_EDITOR) { + factory = factory || new dragonBones.CCFactory(); + } + if (this._dragonBonesData) { + let sameNamedDragonBonesData = factory.getDragonBonesData(this._dragonBonesData.name); + if (sameNamedDragonBonesData) { + // already added asset, see #2002 + for (let i = 0; i < this._dragonBonesData.armatureNames.length; i++) { + let armatureName = this._dragonBonesData.armatureNames[i]; + if (!sameNamedDragonBonesData.armatures[armatureName]) { + // merge with new armature + sameNamedDragonBonesData.addArmature(this._dragonBonesData.armatures[armatureName]); + } + } + this._dragonBonesData = sameNamedDragonBonesData; + } + else { + factory.addDragonBonesData(this._dragonBonesData); + } + } + else { + if (CC_JSB) { + // The 'factory' create a new one every time in JSB, they can't use getDragonBonesData + // to get cached data, and don't need to merge armatures. + this._dragonBonesData = factory.parseDragonBonesData(this._dragonBonesJson); + } + else { + let jsonObj = JSON.parse(this._dragonBonesJson); + let sameNamedDragonBonesData = factory.getDragonBonesData(jsonObj.name); + if (sameNamedDragonBonesData) { + // already added asset, see #2002 + let dragonBonesData; + for (let i = 0; i < jsonObj.armature.length; i++) { + let armatureName = jsonObj.armature[i].name; + if (!sameNamedDragonBonesData.armatures[armatureName]) { + // add new armature + if (!dragonBonesData) { + dragonBonesData = factory._dataParser.parseDragonBonesData(jsonObj); + } + sameNamedDragonBonesData.addArmature(dragonBonesData.armatures[armatureName]); + } + } + this._dragonBonesData = sameNamedDragonBonesData; + } + else { + this._dragonBonesData = factory.parseDragonBonesData(jsonObj); + } + } + } + }, + // EDITOR - getRuntimeData: CC_EDITOR && function () { - if (!this._dragonBonesDataCache) { - var factory = new dragonBones.CCFactory(); - var jsonObj = JSON.parse(this._dragonBonesJson); - this._dragonBonesDataCache = factory.parseDragonBonesData(jsonObj); - } - - return this._dragonBonesDataCache; - }, - getArmatureEnum: CC_EDITOR && function () { if (this._armaturesEnum) { return this._armaturesEnum; } - var data = this.getRuntimeData(); - if (data) { - var armatureNames = data.armatureNames; + this.init(); + if (this._dragonBonesData) { + var armatureNames = this._dragonBonesData.armatureNames; var enumDef = {}; for (var i = 0; i < armatureNames.length; i++) { var name = armatureNames[i]; @@ -105,9 +151,9 @@ var DragonBonesAsset = cc.Class({ }, getAnimsEnum: CC_EDITOR && function (armatureName) { - var data = this.getRuntimeData(true); - if (data) { - var armature = data.getArmature(armatureName); + this.init(); + if (this._dragonBonesData) { + var armature = this._dragonBonesData.getArmature(armatureName); if (!armature) { return null; } @@ -125,6 +171,15 @@ var DragonBonesAsset = cc.Class({ } return null; }, + + destroy () { + var useGlobalFactory = !CC_JSB; + if (useGlobalFactory && this._dragonBonesData) { + var factory = dragonBones.CCFactory.getFactory(); + factory.removeDragonBonesData(this._dragonBonesData.name, true); + } + this._super(); + }, }); dragonBones.DragonBonesAsset = module.exports = DragonBonesAsset; diff --git a/extensions/dragonbones/DragonBonesAtlasAsset.js b/extensions/dragonbones/DragonBonesAtlasAsset.js index 1c5cb1ef30..4ca8e088b0 100644 --- a/extensions/dragonbones/DragonBonesAtlasAsset.js +++ b/extensions/dragonbones/DragonBonesAtlasAsset.js @@ -37,6 +37,10 @@ var DragonBonesAtlasAsset = cc.Class({ name: 'dragonBones.DragonBonesAtlasAsset', extends: cc.Asset, + ctor () { + this.reset(); + }, + properties: { _atlasJson : '', @@ -49,15 +53,27 @@ var DragonBonesAtlasAsset = cc.Class({ }, set: function (value) { this._atlasJson = value; + this.reset(); } }, + _texture: { + default: null, + type: cc.Texture2D, + formerlySerializedAs: 'texture' + }, + /** * @property {Texture2D} texture */ texture: { - default: null, - type: cc.Texture2D + get () { + return this._texture; + }, + set (value) { + this._texture = value; + this.reset(); + } }, }, @@ -65,6 +81,10 @@ var DragonBonesAtlasAsset = cc.Class({ preventDeferredLoadDependents: true }, + reset () { + this._textureAtlasData = null; // instance of CCTextureAtlasData + }, + createNode: CC_EDITOR && function (callback) { var node = new cc.Node(this.name); var armatureDisplay = node.addComponent(dragonBones.ArmatureDisplay); @@ -72,6 +92,43 @@ var DragonBonesAtlasAsset = cc.Class({ return callback(null, node); }, + + init (factory) { + if (this._textureAtlasData) { + cc.log('Has textureAtlasData'); + factory.addTextureAtlasData(this._textureAtlasData); + } + else { + this._textureAtlasData = factory.parseTextureAtlasData(this.atlasJson, this.texture); + } + //// solve the error effect of DragonBones when re-enter an auto-released scene (#5053) + // var atlasName = atlasJsonObj.name; + // var atlasDataList = factory.getTextureAtlasData(atlasName); + // if (atlasDataList && atlasDataList.length > 0) { + // var texturePath = this.texture && this.texture.url; + // for (var idx in atlasDataList) { + // var data = atlasDataList[idx]; + // if (data && data.texture && data.texture.url === texturePath) { + // // found same named atlas, renew texture + // data.texture = this.texture; + // return; + // } + // } + // } + }, + + destroy () { + var useGlobalFactory = !CC_JSB; + if (useGlobalFactory && this._textureAtlasData) { + var factory = dragonBones.CCFactory.getFactory(); + // If the texture still referenced by any DragonBonesData in the factory, + // remember to remove them at the same time! + var name = this._textureAtlasData.name; + factory.removeTextureAtlasData(name, true); + factory.removeDragonBonesData(name, true); + } + this._super(); + }, }); dragonBones.DragonBonesAtlasAsset = module.exports = DragonBonesAtlasAsset; From 6b97d4d6cfa2cebb8ac484a4abb7c875c986e2d4 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 3 Jan 2018 00:30:30 +0800 Subject: [PATCH 108/127] remove unused modules from jsb_polyfill --- gulp/tasks/engine.js | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/gulp/tasks/engine.js b/gulp/tasks/engine.js index f8f0e9829d..254f0a472a 100644 --- a/gulp/tasks/engine.js +++ b/gulp/tasks/engine.js @@ -46,12 +46,17 @@ var jsbSkipModules = [ '../../cocos2d/core/CCDrawingPrimitives.js', '../../cocos2d/core/textures/CCTexture2D', '../../cocos2d/core/sprites/CCSpriteFrame', + '../../cocos2d/core/event-manager/CCTouch.js', + '../../cocos2d/core/event-manager/CCEventListener.js', + '../../cocos2d/core/event-manager/CCEventManager.js', '../../cocos2d/core/load-pipeline/audio-downloader', '../../cocos2d/core/physics/platform/CCPhysicsDebugDraw.js', '../../cocos2d/core/physics/platform/CCPhysicsUtils.js', + '../../cocos2d/core/physics/platform/CCPhysicsContactListner.js', '../../cocos2d/core/physics/platform/CCPhysicsAABBQueryCallback.js', '../../cocos2d/core/physics/platform/CCPhysicsRayCastCallback.js', - '../../cocos2d/core/physics/platform/CCPhysicsContactListner.js', + '../../cocos2d/core/platform/CCInputManager.js', + '../../cocos2d/core/platform/CCVisibleRect.js', '../../cocos2d/core/camera/CCSGCameraNode.js', '../../cocos2d/core/label/CCSGLabel.js', '../../cocos2d/core/label/CCSGLabelCanvasRenderCmd.js', @@ -64,6 +69,7 @@ var jsbSkipModules = [ '../../cocos2d/core/graphics/graphics-canvas-cmd.js', '../../cocos2d/core/graphics/earcut.js', '../../cocos2d/core/graphics/helper.js', + '../../cocos2d/actions/index.js', '../../cocos2d/audio/CCAudio', '../../cocos2d/shape-nodes/CCDrawNode.js', '../../cocos2d/clipping-nodes/CCClippingNode.js', @@ -84,6 +90,7 @@ var jsbSkipModules = [ '../../cocos2d/render-texture/CCRenderTexture.js', '../../cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js', '../../cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js', + '../../extensions/spine/SGSkeletonTexture', '../../extensions/spine/SGSkeleton', '../../extensions/spine/SGSkeletonAnimation', '../../extensions/spine/SGSkeletonCanvasRenderCmd', @@ -91,10 +98,11 @@ var jsbSkipModules = [ '../../extensions/spine/lib/spine', '../../extensions/dragonbones/lib/dragonBones', '../../extensions/dragonbones/CCFactory', - '../../extensions/dragonbones/CCArmatureDisplay', '../../extensions/dragonbones/CCSlot', '../../extensions/dragonbones/CCTextureData', + '../../extensions/dragonbones/CCArmatureDisplay', '../../external/box2d/box2d.js', + '../../external/chipmunk/chipmunk.js', ]; exports.buildCocosJs = function (sourceFile, outputFile, excludes, callback) { From 298ab19d19ca2ea8b225b89a3fadf68d843f9a4a Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 3 Jan 2018 00:27:16 +0800 Subject: [PATCH 109/127] fix bug of asset type on JSB --- cocos2d/core/assets/CCRawAsset.js | 14 +++---- cocos2d/core/load-pipeline/CCLoader.js | 2 +- .../core/load-pipeline/auto-release-utils.js | 6 +-- cocos2d/core/load-pipeline/uuid-loader.js | 2 +- cocos2d/core/platform/CCClass.js | 17 +++++++- cocos2d/core/platform/instantiate-jit.js | 4 +- cocos2d/core/platform/instantiate.js | 8 ++-- gulp/tasks/engine.js | 4 +- gulp/util/check-jsb-instanceof.js | 41 +++++++++++++++++++ gulp/util/fix-jsb-javascriptcore.js | 5 ++- 10 files changed, 80 insertions(+), 23 deletions(-) create mode 100644 gulp/util/check-jsb-instanceof.js diff --git a/cocos2d/core/assets/CCRawAsset.js b/cocos2d/core/assets/CCRawAsset.js index 0201de9354..1ad6a8f458 100644 --- a/cocos2d/core/assets/CCRawAsset.js +++ b/cocos2d/core/assets/CCRawAsset.js @@ -24,6 +24,7 @@ ****************************************************************************/ var CCObject = require('../platform/CCObject'); +var JS = require('../platform/js'); /** * !#en @@ -81,18 +82,13 @@ cc.RawAsset = cc.Class({ * @static * @private */ -Object.defineProperty(cc.RawAsset, 'isRawAssetType', { - value: function (ctor) { - return cc.isChildClassOf(ctor, cc.RawAsset) && !cc.isChildClassOf(ctor, cc.Asset); - } - // enumerable is false by default +JS.value(cc.RawAsset, 'isRawAssetType', function (ctor) { + return cc.isChildClassOf(ctor, cc.RawAsset) && !cc.isChildClassOf(ctor, cc.Asset); }); // TODO - DELME after 2.0 -Object.defineProperty(cc.RawAsset, 'wasRawAssetType', { - value: function (ctor) { - return ctor === cc.Texture2D; - } +JS.value(cc.RawAsset, 'wasRawAssetType', function (ctor) { + return ctor === cc.Texture2D; }); module.exports = cc.RawAsset; diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js index 4c5b567f7f..841eac5b94 100644 --- a/cocos2d/core/load-pipeline/CCLoader.js +++ b/cocos2d/core/load-pipeline/CCLoader.js @@ -765,7 +765,7 @@ proto.release = function (asset) { var removed = this.removeItem(id); asset = item.content; // TODO: AUDIO - if (asset instanceof cc.Asset) { + if (cc.Class.isInstanceOf(asset, cc.Asset)) { if (asset.nativeUrl) { this.release(asset.nativeUrl); } diff --git a/cocos2d/core/load-pipeline/auto-release-utils.js b/cocos2d/core/load-pipeline/auto-release-utils.js index 3f93cea456..0958e1988c 100644 --- a/cocos2d/core/load-pipeline/auto-release-utils.js +++ b/cocos2d/core/load-pipeline/auto-release-utils.js @@ -57,7 +57,7 @@ function visitComponent (comp, excludeMap) { if (Array.isArray(value)) { for (let j = 0; j < value.length; j++) { let val = value[j]; - if (val instanceof cc.RawAsset) { + if (cc.Class.isInstanceOf(val, cc.RawAsset)) { visitAsset(val, excludeMap); } } @@ -66,12 +66,12 @@ function visitComponent (comp, excludeMap) { let keys = Object.getOwnPropertyNames(value); for (let j = 0; j < keys.length; j++) { let val = value[keys[j]]; - if (val instanceof cc.RawAsset) { + if (cc.Class.isInstanceOf(val, cc.RawAsset)) { visitAsset(val, excludeMap); } } } - else if (value instanceof cc.RawAsset) { + else if (cc.Class.isInstanceOf(value, cc.RawAsset)) { visitAsset(value, excludeMap); } } diff --git a/cocos2d/core/load-pipeline/uuid-loader.js b/cocos2d/core/load-pipeline/uuid-loader.js index cb38ae4e6c..c08d595f09 100644 --- a/cocos2d/core/load-pipeline/uuid-loader.js +++ b/cocos2d/core/load-pipeline/uuid-loader.js @@ -185,7 +185,7 @@ function canDeferredLoad (asset, item, isScene) { var res = item.deferredLoadRaw; if (res) { // check if asset support deferred - if (asset instanceof cc.Asset && asset.constructor.preventDeferredLoadDependents) { + if (cc.Class.isInstanceOf(asset, cc.Asset) && asset.constructor.preventDeferredLoadDependents) { res = false; } } diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 49d525753d..1200fc8a04 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -1060,7 +1060,7 @@ cc.isChildClassOf = function (subclass, superclass) { return false; }; -/** +/* * Return all super classes * @method getInheritanceChain * @param {Function} constructor @@ -1080,6 +1080,21 @@ CCClass.getInheritanceChain = function (klass) { return chain; }; +/* + * Is instance of for JSB. + * `obj` can be native object such as cc.Texture2D or cc.SpriteFrame. + * `klass` can be base class of native object such as cc.Asset, cc.RawAsset or cc.Object. + * @method isInstanceOf + * @param {Object} obj + * @param {Function} klass + * @returns {Boolean} + */ +CCClass.isInstanceOf = CC_JSB ? function (obj, klass) { + return obj && cc.isChildClassOf(obj.constructor, klass); +} : function (obj__skip_jsb_warning, klass) { + return obj__skip_jsb_warning instanceof klass; +}; + var PrimitiveTypes = { // Specify that the input value must be integer in Properties. // Also used to indicates that the type of elements in array or the type of value in dictionary is integer. diff --git a/cocos2d/core/platform/instantiate-jit.js b/cocos2d/core/platform/instantiate-jit.js index a53c631a9f..534ae708eb 100644 --- a/cocos2d/core/platform/instantiate-jit.js +++ b/cocos2d/core/platform/instantiate-jit.js @@ -404,7 +404,7 @@ proto.enumerateField = function (obj, key, value) { return escapeForJS(value); } else { - if (key === '_objFlags' && obj instanceof CCObject) { + if (key === '_objFlags' && cc.Class.isInstanceOf(obj, CCObject)) { value &= PersistentMask; } return value; @@ -445,7 +445,7 @@ proto.instantiateObj = function (obj) { if (obj instanceof cc.ValueType) { return CCClass.getNewValueTypeCode(obj); } - if (obj instanceof cc.Asset) { + if (cc.Class.isInstanceOf(obj, cc.Asset)) { // register to asset list and just return the reference. return this.getObjRef(obj); } diff --git a/cocos2d/core/platform/instantiate.js b/cocos2d/core/platform/instantiate.js index c68b3ac32e..ed2a115ced 100644 --- a/cocos2d/core/platform/instantiate.js +++ b/cocos2d/core/platform/instantiate.js @@ -77,7 +77,7 @@ function instantiate (original, internal_force) { } var clone; - if (original instanceof CCObject) { + if (cc.Class.isInstanceOf(original, CCObject)) { // Invoke _instantiate method if supplied. // The _instantiate callback will be called only on the root object, its associated object will not be called. // @callback associated @@ -90,7 +90,7 @@ function instantiate (original, internal_force) { cc.game._isCloning = false; return clone; } - else if (original instanceof cc.Asset) { + else if (cc.Class.isInstanceOf(original, cc.Asset)) { // 不允许用通用方案实例化资源 if (CC_DEV) { cc.errorID(6903); @@ -209,7 +209,7 @@ function enumerateObject (obj, clone, parent) { } } } - if (obj instanceof CCObject) { + if (cc.Class.isInstanceOf(obj, CCObject)) { clone._objFlags &= PersistentMask; } } @@ -222,7 +222,7 @@ function instantiateObj (obj, parent) { if (obj instanceof cc.ValueType) { return obj.clone(); } - if (obj instanceof cc.Asset) { + if (cc.Class.isInstanceOf(obj, cc.Asset)) { // 所有资源直接引用,不需要拷贝 return obj; } diff --git a/gulp/tasks/engine.js b/gulp/tasks/engine.js index a429333202..13999a7f86 100644 --- a/gulp/tasks/engine.js +++ b/gulp/tasks/engine.js @@ -210,6 +210,7 @@ exports.buildPreview = function (sourceFile, outputFile, callback, devMode) { exports.buildJsbPreview = function (sourceFile, outputFile, excludes, callback) { var FixJavaScriptCore = require('../util/fix-jsb-javascriptcore'); + var CheckInstanceof = require('../util/check-jsb-instanceof'); var outFile = Path.basename(outputFile); var outDir = Path.dirname(outputFile); @@ -220,7 +221,8 @@ exports.buildJsbPreview = function (sourceFile, outputFile, excludes, callback) excludes.forEach(function (module) { bundler.ignore(require.resolve(module)); }); - bundler.bundle() + bundler.transform(CheckInstanceof) + .bundle() .on('error', HandleErrors.handler) .pipe(HandleErrors()) .pipe(Source(outFile)) diff --git a/gulp/util/check-jsb-instanceof.js b/gulp/util/check-jsb-instanceof.js new file mode 100644 index 0000000000..1cd7b6ea7f --- /dev/null +++ b/gulp/util/check-jsb-instanceof.js @@ -0,0 +1,41 @@ + +// A browserify transform that check instanceof expression for polyfilled native constructor + +const ES = require('event-stream'); + +const BaseClassesToCheck = ['cc.Asset', 'cc.RawAsset', 'cc.Object']; +const IgnoreVarSuffix = 'skip_jsb_warning'; + +var re = (function () { + const types = BaseClassesToCheck.map(x => x.match(/[^.]+$/)[0]).join('|'); + // console.log(types); + return RegExp(`(${IgnoreVarSuffix})?\\s+(instanceof\\s+\\w*\\.?(${types}))`, 'gi'); +})(); + +module.exports = function (file) { + const Path = require('path'); + return ES.through(function (buff, encode) { + // console.log('parsing ' + file); + var code = buff.toString(encode); + + re.lastIndex = 0; + var execRes; + while ((execRes = re.exec(code)) !== null) { + if (execRes[1] === IgnoreVarSuffix) { + continue; + } + var exp = execRes[2]; + var type = execRes[3]; + var hasLowerCaseInstanceOf = execRes[0].indexOf('instanceof') !== -1; + if (hasLowerCaseInstanceOf) { + var path = Path.relative(process.cwd(), file); + console.warn( + `Checking \`${exp}\` will fail on JSB if the object is native asset such as cc.Texture2D and cc.SpriteFrame.\n` + + ` Use \`${type}.is***(obj)\` instead please.\n` + + ` You can also use \`***_${IgnoreVarSuffix} instanceof ${type}\` to suppress this warning.\n` + + ` File: ${path}`); + } + } + this.emit('data', buff); + }); +}; diff --git a/gulp/util/fix-jsb-javascriptcore.js b/gulp/util/fix-jsb-javascriptcore.js index 8d28be5be6..c6cde82bd0 100644 --- a/gulp/util/fix-jsb-javascriptcore.js +++ b/gulp/util/fix-jsb-javascriptcore.js @@ -1,3 +1,6 @@ + +// fix `typeof constructor` on JavaScriptCore + const ES = require('event-stream'); const Path = require('path'); @@ -34,4 +37,4 @@ module.exports = function () { } this.emit('data', file); }); -}; \ No newline at end of file +}; From d6f4918e3804f6285a616fc59463015e0f1e0f42 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 3 Jan 2018 14:31:47 +0800 Subject: [PATCH 110/127] reviewed --- cocos2d/core/platform/CCClass.js | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 1200fc8a04..9eaca0e51d 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -1089,6 +1089,7 @@ CCClass.getInheritanceChain = function (klass) { * @param {Function} klass * @returns {Boolean} */ +// TODO - remove at 2.0 if all assets implemented in pure js CCClass.isInstanceOf = CC_JSB ? function (obj, klass) { return obj && cc.isChildClassOf(obj.constructor, klass); } : function (obj__skip_jsb_warning, klass) { From 8dab61d7d6631239fdbf9746abd4a9e4f0c2f7c2 Mon Sep 17 00:00:00 2001 From: simon129 Date: Wed, 3 Jan 2018 14:53:03 +0800 Subject: [PATCH 111/127] CCWebView.destroy() should have a return value CCWebView.destroy() inherent from CCObject, it's destroy() should return true or false. Add return value to improve creator.d.ts --- cocos2d/core/components/CCWebView.js | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos2d/core/components/CCWebView.js b/cocos2d/core/components/CCWebView.js index bad9bd0812..71073d3fbd 100644 --- a/cocos2d/core/components/CCWebView.js +++ b/cocos2d/core/components/CCWebView.js @@ -273,4 +273,5 @@ cc.WebView = module.exports = WebView; * // when you don't need webview anymore * webview.node.destroy(); * @method destroy + * @return {Boolean} whether it is the first time the destroy being called */ From 1143c84522cc948566cdee7e09d7d08779dff7ce Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 3 Jan 2018 17:15:03 +0800 Subject: [PATCH 112/127] support compile with CC_WECHATGAME macro --- gulp/tasks/engine.js | 12 ++++++------ gulp/tasks/test.js | 2 +- gulp/util/utils.js | 39 ++++++++++++++++++++++++++++++--------- 3 files changed, 37 insertions(+), 16 deletions(-) diff --git a/gulp/tasks/engine.js b/gulp/tasks/engine.js index f8f0e9829d..119d76c085 100644 --- a/gulp/tasks/engine.js +++ b/gulp/tasks/engine.js @@ -106,7 +106,7 @@ exports.buildCocosJs = function (sourceFile, outputFile, excludes, callback) { bundler.ignore(file); }); - var uglifyOption = Utils.getUglifyOptions('build', false, true); + var uglifyOption = Utils.getUglifyOptions('build', { debug: true }); bundler = bundler.bundle(); bundler = bundler.pipe(Source(outFile)); @@ -134,7 +134,7 @@ exports.buildCocosJsMin = function (sourceFile, outputFile, excludes, callback, bundler.ignore(file); }); - var uglifyOption = Utils.getUglifyOptions('build', false, false); + var uglifyOption = Utils.getUglifyOptions('build'); var Size = null; try { @@ -193,7 +193,7 @@ exports.buildPreview = function (sourceFile, outputFile, callback) { .pipe(Source(outFile)) .pipe(Buffer()) .pipe(Sourcemaps.init({loadMaps: true})) - .pipe(Minify(Utils.getUglifyOptions('preview', false, false))) + .pipe(Minify(Utils.getUglifyOptions('preview'))) .pipe(Optimizejs({ sourceMap: false })) @@ -224,7 +224,7 @@ exports.buildJsbPreview = function (sourceFile, outputFile, excludes, callback) .pipe(Source(outFile)) .pipe(Buffer()) .pipe(FixJavaScriptCore()) - .pipe(Minify(Utils.getUglifyOptions('preview', true, false))) + .pipe(Minify(Utils.getUglifyOptions('preview', { jsb: true }))) .pipe(Optimizejs({ sourceMap: false })) @@ -250,7 +250,7 @@ exports.buildJsb = function (sourceFile, outputFile, excludes, callback) { .pipe(Source(outFile)) .pipe(Buffer()) .pipe(FixJavaScriptCore()) - .pipe(Minify(Utils.getUglifyOptions('build', true, true))) + .pipe(Minify(Utils.getUglifyOptions('build', { jsb: true, debug: true }))) .pipe(Optimizejs({ sourceMap: false })) @@ -276,7 +276,7 @@ exports.buildJsbMin = function (sourceFile, outputFile, excludes, callback) { .pipe(Source(outFile)) .pipe(Buffer()) .pipe(FixJavaScriptCore()) - .pipe(Minify(Utils.getUglifyOptions('build', true, false))) + .pipe(Minify(Utils.getUglifyOptions('build', { jsb: true }))) .pipe(Optimizejs({ sourceMap: false })) diff --git a/gulp/tasks/test.js b/gulp/tasks/test.js index 45fee2cae9..760d0a165e 100644 --- a/gulp/tasks/test.js +++ b/gulp/tasks/test.js @@ -63,7 +63,7 @@ exports.build = function (sourceFile, outputFile, sourceFileForExtends, outputFi } // remove `...args` used in CC_JSB - engine = engine.pipe(Minify(Utils.getUglifyOptions('test', false, false))); + engine = engine.pipe(Minify(Utils.getUglifyOptions('test'))); if (sourcemaps) { engine = engine.pipe(Sourcemaps.write('./', { diff --git a/gulp/util/utils.js b/gulp/util/utils.js index 6de32cab5d..62a3803881 100644 --- a/gulp/util/utils.js +++ b/gulp/util/utils.js @@ -1,29 +1,50 @@ const PLATFORM_MACROS = ['CC_EDITOR', 'CC_PREVIEW', 'CC_BUILD', 'CC_TEST']; +const FLAGS = ['jsb', 'wechatgame', 'debug']; // generate macros for uglify's global_defs -// platform: editor | preview | build | test -exports.getMacros = function (platform, isJSB, isDebugBuild) { +// available platforms: 'editor' | 'preview' | 'build' | 'test' +// available keys of flags: 'jsb' | 'wechatgame' | 'debug' +exports.getMacros = function (platform, flags) { + // platform macros var platformMacro = 'CC_' + platform.toUpperCase(); if (PLATFORM_MACROS.indexOf(platformMacro) === -1) { throw new Error('Unknown platform: ' + platform); } var res = {}; - for (var i = 0; i < PLATFORM_MACROS.length; i++) { - var macro = PLATFORM_MACROS[i]; + for (let i = 0; i < PLATFORM_MACROS.length; i++) { + let macro = PLATFORM_MACROS[i]; res[macro] = (macro === platformMacro); } + + // flag macros + if (flags) { + for (let flag in flags) { + if (flags.hasOwnProperty(flag) && flags[flag]) { + if (FLAGS.indexOf(flag) === -1) { + throw new Error('Unknown flag: ' + flag); + } + } + } + } + for (let i = 0; i < FLAGS.length; i++) { + let flag = FLAGS[i]; + let macro = 'CC_' + flag.toUpperCase(); + res[macro] = !!(flags && flags[flag]); + } + + // debug macros res['CC_DEV'] = res['CC_EDITOR'] || res['CC_PREVIEW'] || res['CC_TEST']; - res['CC_DEBUG'] = res['CC_DEV'] || !!isDebugBuild; - res['CC_JSB'] = !!isJSB; + res['CC_DEBUG'] = res['CC_DEBUG'] || res['CC_DEV']; + console.log(res); return res; }; -exports.getUglifyOptions = function (platform, isJSB, isDebugBuild) { - var global_defs = exports.getMacros(platform, isJSB, isDebugBuild); +exports.getUglifyOptions = function (platform, flags) { + var global_defs = exports.getMacros(platform, flags); var releaseMode = !global_defs['CC_DEBUG']; - var optimizeForJSC = releaseMode && isJSB; + var optimizeForJSC = releaseMode && global_defs['CC_JSB']; if (optimizeForJSC) { return { output: { From 2e2fd5919322a54d51779622636d914d150472b5 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 3 Jan 2018 21:49:54 +0800 Subject: [PATCH 113/127] add CC_SUPPORT_JIT macro --- circle.yml | 2 +- cocos2d/core/assets/CCPrefab.js | 2 +- cocos2d/core/component-scheduler.js | 7 +++---- cocos2d/core/node-activator.js | 7 +++---- cocos2d/core/platform/CCClass.js | 12 ++++++------ cocos2d/core/platform/CCObject.js | 2 +- cocos2d/core/platform/CCSys.js | 9 +++------ cocos2d/core/platform/CCView.js | 6 +----- cocos2d/core/platform/_CCClass.js | 2 +- cocos2d/core/platform/attribute.js | 2 +- cocos2d/core/platform/deserialize.js | 4 ++-- cocos2d/core/utils/prefab-helper.js | 2 +- cocos2d/deprecated.js | 2 +- gulp/util/utils.js | 2 +- index.js | 12 +++++++----- jsb/index.js | 9 ++++----- package.json | 2 +- 17 files changed, 38 insertions(+), 46 deletions(-) diff --git a/circle.yml b/circle.yml index 42fe8cbe44..c9d4fd3700 100644 --- a/circle.yml +++ b/circle.yml @@ -1,6 +1,6 @@ machine: node: - version: 5.8.0 + version: 6.12.3 dependencies: pre: diff --git a/cocos2d/core/assets/CCPrefab.js b/cocos2d/core/assets/CCPrefab.js index 201c623bea..131ffc6821 100644 --- a/cocos2d/core/assets/CCPrefab.js +++ b/cocos2d/core/assets/CCPrefab.js @@ -95,7 +95,7 @@ var Prefab = cc.Class({ _instantiate: function () { var node; - if (cc.supportJit) { + if (CC_SUPPORT_JIT) { // instantiate node node = this._doInstantiate(); // initialize node diff --git a/cocos2d/core/component-scheduler.js b/cocos2d/core/component-scheduler.js index 7a02a2b988..b910c23c70 100644 --- a/cocos2d/core/component-scheduler.js +++ b/cocos2d/core/component-scheduler.js @@ -38,15 +38,14 @@ var callUpdateInTryCatch = CC_EDITOR && callerFunctor('update', 'dt'); var callLateUpdateInTryCatch = CC_EDITOR && callerFunctor('lateUpdate', 'dt'); var callOnDisableInTryCatch = CC_EDITOR && callerFunctor('onDisable'); -var supportJit = cc.supportJit; -var callStart = supportJit ? 'c.start();c._objFlags|=' + IsStartCalled : function (c) { +var callStart = CC_SUPPORT_JIT ? 'c.start();c._objFlags|=' + IsStartCalled : function (c) { c.start(); c._objFlags |= IsStartCalled; }; -var callUpdate = supportJit ? 'c.update(dt)' : function (c, dt) { +var callUpdate = CC_SUPPORT_JIT ? 'c.update(dt)' : function (c, dt) { c.update(dt); }; -var callLateUpdate = supportJit ? 'c.lateUpdate(dt)' : function (c, dt) { +var callLateUpdate = CC_SUPPORT_JIT ? 'c.lateUpdate(dt)' : function (c, dt) { c.lateUpdate(dt); }; diff --git a/cocos2d/core/node-activator.js b/cocos2d/core/node-activator.js index 23987801f5..69dab8761c 100644 --- a/cocos2d/core/node-activator.js +++ b/cocos2d/core/node-activator.js @@ -43,12 +43,11 @@ var callResetInTryCatch = CC_EDITOR && callerFunctor('resetInEditor'); var callOnFocusInTryCatch = CC_EDITOR && callerFunctor('onFocusInEditor'); var callOnLostFocusInTryCatch = CC_EDITOR && callerFunctor('onLostFocusInEditor'); -var supportJit = cc.supportJit; -var callPreload = supportJit ? 'c.__preload();' : function (c) { c.__preload(); } -var callOnLoad = supportJit ? ('c.onLoad();c._objFlags|=' + IsOnLoadCalled) : function (c) { +var callPreload = CC_SUPPORT_JIT ? 'c.__preload();' : function (c) { c.__preload(); }; +var callOnLoad = CC_SUPPORT_JIT ? ('c.onLoad();c._objFlags|=' + IsOnLoadCalled) : function (c) { c.onLoad(); c._objFlags |= IsOnLoadCalled; -} +}; // for __preload: use internally, no sort var UnsortedInvoker = cc.Class({ diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 5378010097..c6b8941c26 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -565,7 +565,7 @@ function compileProps (actualClass) { } // Overwite __initProps__ to avoid compile again. - var initProps = cc.supportJit ? getInitPropsJit(attrs, propList) : getInitProps(attrs, propList); + var initProps = CC_SUPPORT_JIT ? getInitPropsJit(attrs, propList) : getInitProps(attrs, propList); actualClass.prototype.__initProps__ = initProps; // call instantiateProps immediately, no need to pass actualClass into it anymore @@ -573,7 +573,7 @@ function compileProps (actualClass) { initProps.call(this); } -var _createCtor = cc.supportJit ? function (ctors, baseClass, className, options) { +var _createCtor = CC_SUPPORT_JIT ? function (ctors, baseClass, className, options) { var superCallBounded = baseClass && boundSuperCalls(baseClass, options, className); var ctorName = CC_DEV ? normalizeClassName_DEV(className) : 'CCClass'; @@ -633,8 +633,8 @@ var _createCtor = cc.supportJit ? function (ctors, baseClass, className, options cs[0].apply(this, arguments); } else { - for (var i = 0; i < ctorLen; i++) { - cs[i].apply(this, arguments);; + for (let i = 0; i < ctorLen; i++) { + cs[i].apply(this, arguments); } } } @@ -647,8 +647,8 @@ var _createCtor = cc.supportJit ? function (ctors, baseClass, className, options cs[0].apply(this, arguments); } else { - for (var i = 0; i < ctorLen; i++) { - cs[i].apply(this, arguments);; + for (let i = 0; i < ctorLen; i++) { + cs[i].apply(this, arguments); } } } diff --git a/cocos2d/core/platform/CCObject.js b/cocos2d/core/platform/CCObject.js index f3e1781f3a..725b21aed4 100644 --- a/cocos2d/core/platform/CCObject.js +++ b/cocos2d/core/platform/CCObject.js @@ -340,7 +340,7 @@ function compileDestruct (obj, ctor) { // compile code var skipId = obj instanceof cc._BaseNode || obj instanceof cc.Component; - if (cc.supportJit) { + if (CC_SUPPORT_JIT) { var func = ''; for (key in propsToReset) { if (skipId && key === '_id') { diff --git a/cocos2d/core/platform/CCSys.js b/cocos2d/core/platform/CCSys.js index eb224a7279..2002811938 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -489,9 +489,6 @@ sys.BROWSER_TYPE_SOUGOU = "sogou"; */ sys.BROWSER_TYPE_UNKNOWN = "unknown"; -function isWeChatGame () { - return window['wx']; -} /** * Is native ? This is set to be true in jsb auto. @@ -503,7 +500,7 @@ sys.isNative = false; * Is web browser ? * @property {Boolean} isBrowser */ -sys.isBrowser = typeof window === 'object' && typeof document === 'object' && !isWeChatGame(); +sys.isBrowser = typeof window === 'object' && typeof document === 'object' && !CC_WECHATGAME; cc.create3DContext = function (canvas, opt_attribs, opt_contextType) { if (opt_contextType) { @@ -539,7 +536,7 @@ if (CC_EDITOR && Editor.isMainProcess) { }; sys.__audioSupport = {}; } -else if (isWeChatGame()) { +else if (CC_WECHATGAME) { var env = wx.getSystemInfoSync(); sys.isMobile = true; sys.platform = sys.WECHAT_GAME; @@ -668,7 +665,7 @@ else { var browserTypes = typeReg1.exec(ua); if(!browserTypes) browserTypes = typeReg2.exec(ua); var browserType = browserTypes ? browserTypes[0].toLowerCase() : sys.BROWSER_TYPE_UNKNOWN; - if (isWeChatGame()) + if (CC_WECHATGAME) browserType = sys.BROWSER_TYPE_WECHAT_GAME; else if (browserType === 'micromessenger') browserType = sys.BROWSER_TYPE_WECHAT; diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index 6206572cc0..db9b408a80 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -24,10 +24,6 @@ THE SOFTWARE. ****************************************************************************/ -function isWeChatGame () { - return window['wx']; -} - var __BrowserGetter = { init: function(){ if (cc.sys.platform !== cc.sys.WECHAT_GAME) { @@ -58,7 +54,7 @@ if (window.navigator.userAgent.indexOf("OS 8_1_") > -1) //this mistake like MIUI if (cc.sys.os === cc.sys.OS_IOS) // All browsers are WebView __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_SAFARI; -if (isWeChatGame()) { +if (CC_WECHATGAME) { __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_WECHAT_GAME; } diff --git a/cocos2d/core/platform/_CCClass.js b/cocos2d/core/platform/_CCClass.js index d66de087d1..713f2a8abe 100644 --- a/cocos2d/core/platform/_CCClass.js +++ b/cocos2d/core/platform/_CCClass.js @@ -69,7 +69,7 @@ Class.extend = function (props) { // The dummy Class constructor var TheClass; - if (cc.supportJit && cc.game && cc.game.config && cc.game.config[cc.game.CONFIG_KEY.exposeClassName]) { + if (CC_SUPPORT_JIT && cc.game && cc.game.config && cc.game.config[cc.game.CONFIG_KEY.exposeClassName]) { var ctor = "return (function " + (props._className || "Class") + "(arg0,arg1,arg2,arg3,arg4) {\n" + "this.__instanceId = cc.ClassManager.getNewInstanceId();\n" + diff --git a/cocos2d/core/platform/attribute.js b/cocos2d/core/platform/attribute.js index da5ef14f0f..eb2583bcb5 100644 --- a/cocos2d/core/platform/attribute.js +++ b/cocos2d/core/platform/attribute.js @@ -30,7 +30,7 @@ const DELIMETER = '$_$'; function createAttrsSingle (owner, ownerCtor, superAttrs) { var AttrsCtor; - if (CC_DEV && cc.supportJit) { + if (CC_DEV && CC_SUPPORT_JIT) { var ctorName = ownerCtor.name; if (owner === ownerCtor) { ctorName += '_ATTRS'; diff --git a/cocos2d/core/platform/deserialize.js b/cocos2d/core/platform/deserialize.js index 0074c1f36a..1fb1b89d04 100644 --- a/cocos2d/core/platform/deserialize.js +++ b/cocos2d/core/platform/deserialize.js @@ -496,7 +496,7 @@ var _Deserializer = (function () { // } // } - var compileObjectType = cc.supportJit ? function (sources, defaultValue, accessorToSet, propNameLiteralToSet, assumeHavePropIfIsValue) { + var compileObjectType = CC_SUPPORT_JIT ? function (sources, defaultValue, accessorToSet, propNameLiteralToSet, assumeHavePropIfIsValue) { if (defaultValue instanceof cc.ValueType) { // fast case if (!assumeHavePropIfIsValue) { @@ -549,7 +549,7 @@ var _Deserializer = (function () { } }; - var compileDeserialize = cc.supportJit ? function (self, klass) { + var compileDeserialize = CC_SUPPORT_JIT ? function (self, klass) { var RAW_TYPE = Attr.DELIMETER + 'rawType'; var EDITOR_ONLY = Attr.DELIMETER + 'editorOnly'; var SERIALIZABLE = Attr.DELIMETER + 'serializable'; diff --git a/cocos2d/core/utils/prefab-helper.js b/cocos2d/core/utils/prefab-helper.js index 9ee8248e5e..5bc63cc13b 100644 --- a/cocos2d/core/utils/prefab-helper.js +++ b/cocos2d/core/utils/prefab-helper.js @@ -81,7 +81,7 @@ module.exports = { // instantiate prefab cc.game._isCloning = true; - if (cc.supportJit) { + if (CC_SUPPORT_JIT) { _prefab.asset._doInstantiate(node); } else { diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js index 0419f0d530..4f479f781c 100644 --- a/cocos2d/deprecated.js +++ b/cocos2d/deprecated.js @@ -227,7 +227,7 @@ if (CC_DEV) { }); function deprecateEnum (obj, oldPath, newPath, hasTypePrefixBefore) { - if (!cc.supportJit) { + if (!CC_SUPPORT_JIT) { return; } hasTypePrefixBefore = hasTypePrefixBefore !== false; diff --git a/gulp/util/utils.js b/gulp/util/utils.js index 62a3803881..136a8025ef 100644 --- a/gulp/util/utils.js +++ b/gulp/util/utils.js @@ -36,7 +36,7 @@ exports.getMacros = function (platform, flags) { // debug macros res['CC_DEV'] = res['CC_EDITOR'] || res['CC_PREVIEW'] || res['CC_TEST']; res['CC_DEBUG'] = res['CC_DEBUG'] || res['CC_DEV']; - console.log(res); + res['CC_SUPPORT_JIT'] = !res['CC_WECHATGAME']; return res; }; diff --git a/index.js b/index.js index eee5acd80b..f4f28be494 100644 --- a/index.js +++ b/index.js @@ -106,6 +106,9 @@ /** * @property {Boolean} CC_TEST - Running in the engine's unit test. */ +/** + * @property {Boolean} CC_WECHATGAME - Running in the Wechat's mini game. + */ // window may be undefined when first load engine from editor var _global = typeof window === 'undefined' ? global : window; @@ -113,12 +116,12 @@ function defineMacro (name, defaultValue) { // if "global_defs" not preprocessed by uglify, just declare them globally, // this may happened in release version's preview page. // (use evaled code to prevent mangle by uglify) - if (typeof _global[name] == 'undefined') { + if (typeof _global[name] === 'undefined') { _global[name] = defaultValue; } } function defined (name) { - return typeof _global[name] == 'object'; + return typeof _global[name] === 'object'; } defineMacro('CC_TEST', defined('tap') || defined('QUnit')); @@ -128,6 +131,8 @@ defineMacro('CC_DEV', true); // (CC_EDITOR && !CC_BUILD) || CC_PREVIEW || CC_ defineMacro('CC_DEBUG', true); // CC_DEV || Debug Build defineMacro('CC_JSB', defined('jsb')); defineMacro('CC_BUILD', false); +defineMacro('CC_WECHATGAME', false); +defineMacro('CC_SUPPORT_JIT', !CC_WECHATGAME); // PREDEFINE @@ -141,9 +146,6 @@ defineMacro('CC_BUILD', false); */ cc = {}; -// check whether support jit -cc.supportJit = !defined('wx') && typeof Function('') === 'function'; - // The namespace for original nodes rendering in scene graph. _ccsg = {}; diff --git a/jsb/index.js b/jsb/index.js index df61f5f14d..14b25f1bc3 100644 --- a/jsb/index.js +++ b/jsb/index.js @@ -25,19 +25,16 @@ 'use strict'; -// check whether support jit -cc.supportJit = typeof Function('') === 'function'; - function defineMacro (name, defaultValue) { // if "global_defs" not preprocessed by uglify, just declare them globally, // this may happened in release version's preview page. // (use evaled code to prevent mangle by uglify) - if (typeof window[name] == 'undefined') { + if (typeof window[name] === 'undefined') { window[name] = defaultValue; } } function defined (name) { - return typeof window[name] == 'object'; + return typeof window[name] === 'object'; } defineMacro('CC_TEST', defined('tap') || defined('QUnit')); @@ -47,6 +44,8 @@ defineMacro('CC_DEV', true); // (CC_EDITOR && !CC_BUILD) || CC_PREVIEW || CC_ defineMacro('CC_DEBUG', true); // CC_DEV || Debug Build defineMacro('CC_JSB', defined('jsb')); defineMacro('CC_BUILD', false); +defineMacro('CC_WECHATGAME', false); +defineMacro('CC_SUPPORT_JIT', !CC_WECHATGAME); if (!cc.ClassManager) { diff --git a/package.json b/package.json index 8f74448c04..1998722077 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,7 @@ "del": "1.2.0", "event-stream": "3.3.2", "fire-fs": "0.2.1", - "gulp": "^3.9.0", + "gulp": "^3.9.1", "gulp-babel": "6.1.2", "gulp-cached": "1.1.0", "gulp-concat": "2.6.0", From 63525c29b46763529fec70a1cf4573e1cacaf5e4 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 4 Jan 2018 10:06:39 +0800 Subject: [PATCH 114/127] fix page hide event on wechat mini game --- cocos2d/core/CCGame.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index 0d03ec477d..ba43a95b09 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -788,6 +788,11 @@ var game = { win.onfocus = function(){ onShow() }; } + if (CC_WECHATGAME) { + wx.onShow = onShow; + wx.onHide = onHidden; + } + if ("onpageshow" in window && "onpagehide" in window) { win.addEventListener("pagehide", onHidden, false); win.addEventListener("pageshow", onShow, false); From fdba2619addd4d5ead45504aa3fc2b2720de1057 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 4 Jan 2018 10:51:27 +0800 Subject: [PATCH 115/127] support build engine with any macro flag --- gulp/tasks/engine.js | 36 ++++++++++++++++++++++++++++-------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/gulp/tasks/engine.js b/gulp/tasks/engine.js index 119d76c085..b7f3a8ca1a 100644 --- a/gulp/tasks/engine.js +++ b/gulp/tasks/engine.js @@ -97,7 +97,12 @@ var jsbSkipModules = [ '../../external/box2d/box2d.js', ]; -exports.buildCocosJs = function (sourceFile, outputFile, excludes, callback) { +exports.buildCocosJs = function (sourceFile, outputFile, excludes, opt_macroFlags, callback) { + if (typeof opt_macroFlags === 'function') { + callback = opt_macroFlags; + opt_macroFlags = null; + } + var outDir = Path.dirname(outputFile); var outFile = Path.basename(outputFile); var bundler = createBundler(sourceFile); @@ -106,7 +111,7 @@ exports.buildCocosJs = function (sourceFile, outputFile, excludes, callback) { bundler.ignore(file); }); - var uglifyOption = Utils.getUglifyOptions('build', { debug: true }); + var uglifyOption = Utils.getUglifyOptions('build', Object.assign({ debug: true }, opt_macroFlags)); bundler = bundler.bundle(); bundler = bundler.pipe(Source(outFile)); @@ -125,7 +130,12 @@ exports.buildCocosJs = function (sourceFile, outputFile, excludes, callback) { return bundler.on('end', callback); }; -exports.buildCocosJsMin = function (sourceFile, outputFile, excludes, callback, createMap) { +exports.buildCocosJsMin = function (sourceFile, outputFile, excludes, opt_macroFlags, callback, createMap) { + if (typeof opt_macroFlags === 'function') { + callback = opt_macroFlags; + opt_macroFlags = null; + } + var outDir = Path.dirname(outputFile); var outFile = Path.basename(outputFile); var bundler = createBundler(sourceFile); @@ -134,7 +144,7 @@ exports.buildCocosJsMin = function (sourceFile, outputFile, excludes, callback, bundler.ignore(file); }); - var uglifyOption = Utils.getUglifyOptions('build'); + var uglifyOption = Utils.getUglifyOptions('build', opt_macroFlags); var Size = null; try { @@ -232,7 +242,12 @@ exports.buildJsbPreview = function (sourceFile, outputFile, excludes, callback) .on('end', callback); }; -exports.buildJsb = function (sourceFile, outputFile, excludes, callback) { +exports.buildJsb = function (sourceFile, outputFile, excludes, opt_macroFlags, callback) { + if (typeof opt_macroFlags === 'function') { + callback = opt_macroFlags; + opt_macroFlags = null; + } + var FixJavaScriptCore = require('../util/fix-jsb-javascriptcore'); var outFile = Path.basename(outputFile); @@ -250,7 +265,7 @@ exports.buildJsb = function (sourceFile, outputFile, excludes, callback) { .pipe(Source(outFile)) .pipe(Buffer()) .pipe(FixJavaScriptCore()) - .pipe(Minify(Utils.getUglifyOptions('build', { jsb: true, debug: true }))) + .pipe(Minify(Utils.getUglifyOptions('build', Object.assign({ jsb: true, debug: true }, opt_macroFlags)))) .pipe(Optimizejs({ sourceMap: false })) @@ -258,7 +273,12 @@ exports.buildJsb = function (sourceFile, outputFile, excludes, callback) { .on('end', callback); }; -exports.buildJsbMin = function (sourceFile, outputFile, excludes, callback) { +exports.buildJsbMin = function (sourceFile, outputFile, excludes, opt_macroFlags, callback) { + if (typeof opt_macroFlags === 'function') { + callback = opt_macroFlags; + opt_macroFlags = null; + } + var FixJavaScriptCore = require('../util/fix-jsb-javascriptcore'); var outFile = Path.basename(outputFile); @@ -276,7 +296,7 @@ exports.buildJsbMin = function (sourceFile, outputFile, excludes, callback) { .pipe(Source(outFile)) .pipe(Buffer()) .pipe(FixJavaScriptCore()) - .pipe(Minify(Utils.getUglifyOptions('build', { jsb: true }))) + .pipe(Minify(Utils.getUglifyOptions('build', Object.assign({ jsb: true }, opt_macroFlags)))) .pipe(Optimizejs({ sourceMap: false })) From 482cb4b18b76efac794c5ebea1b3e993423b779c Mon Sep 17 00:00:00 2001 From: shay_chen <641278529@qq.com> Date: Thu, 4 Jan 2018 15:19:01 +0800 Subject: [PATCH 116/127] Delete unnecessary code --- cocos2d/core/CCNode.js | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 68bd218d11..0db4b6d523 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -1455,10 +1455,7 @@ var Node = cc.Class({ if (!this.active) return; cc.assertID(action, 1618); - - if (!cc.macro.ENABLE_GC_FOR_NATIVE_OBJECTS) { - this._retainAction(action); - } + if (CC_JSB) { this._sgNode._owner = this; } From a39257030e17f4ac7d23ab27e617a8a29110ab45 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Fri, 5 Jan 2018 13:14:20 +0800 Subject: [PATCH 117/127] add Volume and Mute to CCVideoPlayer for fireball/issues/6811 --- cocos2d/core/components/CCVideoPlayer.js | 107 +++++++++++++++----- cocos2d/core/videoplayer/CCSGVideoPlayer.js | 15 ++- 2 files changed, 92 insertions(+), 30 deletions(-) diff --git a/cocos2d/core/components/CCVideoPlayer.js b/cocos2d/core/components/CCVideoPlayer.js index a47007d4b9..1a2629a7f8 100644 --- a/cocos2d/core/components/CCVideoPlayer.js +++ b/cocos2d/core/components/CCVideoPlayer.js @@ -112,7 +112,7 @@ var VideoPlayer = cc.Class({ resourceType: { tooltip: CC_DEV && 'i18n:COMPONENT.videoplayer.resourceType', type: ResourceType, - set: function ( value ) { + set: function (value) { this._resourceType = value; this._updateVideoSource(); }, @@ -130,7 +130,7 @@ var VideoPlayer = cc.Class({ remoteURL: { tooltip: CC_DEV && 'i18n:COMPONENT.videoplayer.url', type: cc.String, - set: function ( url ) { + set: function (url) { this._remoteURL = url; this._updateVideoSource(); }, @@ -153,7 +153,7 @@ var VideoPlayer = cc.Class({ get: function () { return this._clip; }, - set: function ( value ) { + set: function (value) { if (typeof value !== 'string') value = ''; this._clip = value; @@ -170,19 +170,60 @@ var VideoPlayer = cc.Class({ currentTime: { tooltip: CC_DEV && 'i18n:COMPONENT.videoplayer.currentTime', type: cc.Float, - set: function ( time ) { - if(this._sgNode) { + set: function (time) { + if (this._sgNode) { this._sgNode.seekTo(time); } }, get: function () { - if(this._sgNode) { + if (this._sgNode) { return this._sgNode.currentTime(); } return -1; } }, + _volume: 1, + /** + * !#en The volume of the video player. + * !#zh 视频的音量(0.0 ~ 1.0)。 + * @property volume + * @type {Number} + * @default 1 + */ + volume: { + get: function () { + return this._volume; + }, + set: function (value) { + this._volume = value; + if (this.isPlaying() && !this._mute) { + this._syncVolume(); + } + }, + type: cc.Float, + tooltip: CC_DEV && 'i18n:COMPONENT.videoplayer.volume' + }, + + _mute: false, + /** + * !#en Is the video player mute? + * !#zh 是否静音视频。Mute 是设置音量为 0,取消静音是恢复原来的音量。 + * @property mute + * @type {Boolean} + * @default false + */ + mute: { + get: function () { + return this._mute; + }, + set: function (value) { + this._mute = value; + this._syncVolume(); + }, + tooltip: CC_DEV && 'i18n:COMPONENT.videoplayer.mute', + }, + /** * !#en Whether keep the aspect ration of the original video. * !#zh 是否保持视频原来的宽高比 @@ -206,7 +247,7 @@ var VideoPlayer = cc.Class({ tooltip: CC_DEV && 'i18n:COMPONENT.videoplayer.isFullscreen', default: false, type: cc.Boolean, - notify: function() { + notify: function () { this._sgNode.setFullScreenEnabled(this.isFullscreen); } }, @@ -227,16 +268,24 @@ var VideoPlayer = cc.Class({ ResourceType: ResourceType }, - onLoad: function() { - if(CC_JSB) { + onLoad: function () { + if (CC_JSB) { if (cc.sys.os === cc.sys.OS_OSX || cc.sys.os === cc.sys.OS_WINDOWS) { this.enabled = false; } } }, + _syncVolume: function () { + var sgNode = this._sgNode; + if (sgNode) { + var volume = this._mute ? 0 : this._volume; + sgNode.setVolume(volume); + } + }, + _createSgNode: function () { - if(CC_JSB) { + if (CC_JSB) { if (cc.sys.os === cc.sys.OS_OSX || cc.sys.os === cc.sys.OS_WINDOWS) { console.log('VideoPlayer is not supported on Mac and Windows!'); return null; @@ -248,16 +297,20 @@ var VideoPlayer = cc.Class({ _updateVideoSource: function () { var sgNode = this._sgNode; if (this.resourceType === ResourceType.REMOTE) { + if (cc.loader.md5Pipe) { + this.remoteURL = cc.loader.md5Pipe.transformURL(this.remoteURL); + } sgNode.setURL(this.remoteURL); - } else { + } + else { sgNode.setURL(this._clip || ''); } }, _initSgNode: function () { var sgNode = this._sgNode; - if(sgNode) { - if(!CC_JSB) { + if (sgNode) { + if (!CC_JSB) { sgNode.createDomElementIfNeeded(); } this._updateVideoSource(); @@ -295,22 +348,22 @@ var VideoPlayer = cc.Class({ this.node.emit('clicked', this); }, - onPlaying: function(){ + onPlaying: function () { cc.Component.EventHandler.emitEvents(this.videoPlayerEvent, this, EventType.PLAYING); this.node.emit('playing', this); }, - onPasued: function() { + onPasued: function () { cc.Component.EventHandler.emitEvents(this.videoPlayerEvent, this, EventType.PAUSED); this.node.emit('paused', this); }, - onStopped: function() { + onStopped: function () { cc.Component.EventHandler.emitEvents(this.videoPlayerEvent, this, EventType.STOPPED); this.node.emit('stopped', this); }, - onCompleted: function() { + onCompleted: function () { cc.Component.EventHandler.emitEvents(this.videoPlayerEvent, this, EventType.COMPLETED); this.node.emit('completed', this); }, @@ -321,7 +374,8 @@ var VideoPlayer = cc.Class({ * @method play */ play: function () { - if(this._sgNode) { + if (this._sgNode) { + this._syncVolume(); this._sgNode.play(); } }, @@ -331,8 +385,9 @@ var VideoPlayer = cc.Class({ * !#zh 如果一个视频播放被暂停播放了,调用这个接口可以继续播放。 * @method resume */ - resume: function() { + resume: function () { if (this._sgNode) { + this._syncVolume(); this._sgNode.resume(); } }, @@ -343,7 +398,7 @@ var VideoPlayer = cc.Class({ * @method pause */ pause: function () { - if(this._sgNode) { + if (this._sgNode) { this._sgNode.pause(); } }, @@ -353,8 +408,8 @@ var VideoPlayer = cc.Class({ * !#zh 如果一个视频正在播放,调用这个接口可以立马停止播放。 * @method stop */ - stop: function() { - if(this._sgNode) { + stop: function () { + if (this._sgNode) { this._sgNode.stop(); } }, @@ -365,8 +420,8 @@ var VideoPlayer = cc.Class({ * @method getDuration * @returns {Number} */ - getDuration: function() { - if(this._sgNode) { + getDuration: function () { + if (this._sgNode) { return this._sgNode.duration(); } return -1; @@ -378,8 +433,8 @@ var VideoPlayer = cc.Class({ * @method isPlaying * @returns {Boolean} */ - isPlaying: function() { - if(this._sgNode) { + isPlaying: function () { + if (this._sgNode) { return this._sgNode.isPlaying(); } return false; diff --git a/cocos2d/core/videoplayer/CCSGVideoPlayer.js b/cocos2d/core/videoplayer/CCSGVideoPlayer.js index fb59246616..e35d8b97ee 100644 --- a/cocos2d/core/videoplayer/CCSGVideoPlayer.js +++ b/cocos2d/core/videoplayer/CCSGVideoPlayer.js @@ -68,6 +68,10 @@ _ccsg.VideoPlayer = _ccsg.Node.extend(/** @lends _ccsg.VideoPlayer# */{ this._renderCmd.stop(); }, + setVolume: function (volume) { + this._renderCmd.setVolume(volume); + }, + seekTo: function (time) { this._renderCmd.seekTo(time); }, @@ -306,13 +310,9 @@ _ccsg.VideoPlayer.EventType = { }; proto.updateURL = function (path) { - if (cc.loader.md5Pipe) { - path = cc.loader.md5Pipe.transformURL(path); - } var source, video, extname; var node = this._node; - if (this._url === path) { return; } @@ -502,6 +502,13 @@ _ccsg.VideoPlayer.EventType = { } }; + proto.setVolume = function (volume) { + var video = this._video; + if (video) { + video.volume = volume; + } + }; + proto.isPlaying = function () { var video = this._video; if (_ccsg.VideoPlayer._polyfill.autoplayAfterOperation && this._playing) { From 767b3638547e4df5cdb1563dcde1d38d91d67f63 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Mon, 8 Jan 2018 15:46:20 +0800 Subject: [PATCH 118/127] refine videoplayer code --- cocos2d/core/components/CCVideoPlayer.js | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/cocos2d/core/components/CCVideoPlayer.js b/cocos2d/core/components/CCVideoPlayer.js index 1a2629a7f8..12f59d5465 100644 --- a/cocos2d/core/components/CCVideoPlayer.js +++ b/cocos2d/core/components/CCVideoPlayer.js @@ -185,8 +185,8 @@ var VideoPlayer = cc.Class({ _volume: 1, /** - * !#en The volume of the video player. - * !#zh 视频的音量(0.0 ~ 1.0)。 + * !#en The volume of the video. + * !#zh 视频的音量(0.0 ~ 1.0) * @property volume * @type {Number} * @default 1 @@ -201,14 +201,15 @@ var VideoPlayer = cc.Class({ this._syncVolume(); } }, + range: [0, 1], type: cc.Float, tooltip: CC_DEV && 'i18n:COMPONENT.videoplayer.volume' }, _mute: false, /** - * !#en Is the video player mute? - * !#zh 是否静音视频。Mute 是设置音量为 0,取消静音是恢复原来的音量。 + * !#en Mutes the VideoPlayer. Mute sets the volume=0, Un-Mute restore the original volume. + * !#zh 是否静音视频。静音时设置音量为 0,取消静音是恢复原来的音量。 * @property mute * @type {Boolean} * @default false From d05ffd3b53ccea9b360bb465d43a48ea1f523596 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Tue, 9 Jan 2018 09:50:33 +0800 Subject: [PATCH 119/127] fix __ctor__ api for fireball/issues/6806 --- cocos2d/core/platform/CCClass.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 5378010097..1f7d159a96 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -832,7 +832,7 @@ function declareProperties (cls, className, properties, baseClass, mixins, es6) * @param {String} [options.name] - The class name used for serialization. * @param {Function} [options.extends] - The base class. * @param {Function} [options.ctor] - The constructor. - * @param {Function} [options.__ctor__] - The same as ctor, but less encapsulated. + * @param {Function} [options.__ctor__] - The same as ctor, but less encapsulated. * @param {Object} [options.properties] - The property definitions. * @param {Object} [options.statics] - The static members. * @param {Function[]} [options.mixins] From 8362245151f77115b26fa63139aaa14383102201 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Wed, 10 Jan 2018 17:13:28 +0800 Subject: [PATCH 120/127] fix slider bug for fireball/issues/6830 --- cocos2d/core/components/CCSlider.js | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/cocos2d/core/components/CCSlider.js b/cocos2d/core/components/CCSlider.js index 1a4ef837d8..674307b49e 100644 --- a/cocos2d/core/components/CCSlider.js +++ b/cocos2d/core/components/CCSlider.js @@ -59,6 +59,8 @@ var Slider = cc.Class({ }, ctor: function () { + this._offset = cc.p(); + this._touchHandle = false; this._dragging = false; }, @@ -153,13 +155,17 @@ var Slider = cc.Class({ _onHandleDragStart: function (event) { this._dragging = true; + this._touchHandle = true; + this._offset = this.handle.node.convertTouchToNodeSpaceAR(event.touch); event.stopPropagation(); }, _onTouchBegan: function (event) { if (!this.handle) { return; } this._dragging = true; - this._handleSliderLogic(event.touch); + if (!this._touchHandle) { + this._handleSliderLogic(event.touch); + } event.stopPropagation(); }, @@ -171,6 +177,8 @@ var Slider = cc.Class({ _onTouchEnded: function (event) { this._dragging = false; + this._touchHandle = false; + this._offset = cc.p(); event.stopPropagation(); }, @@ -191,16 +199,13 @@ var Slider = cc.Class({ _updateProgress: function (touch) { if (!this.handle) { return; } - var maxRange = null, progress = 0, newPos = this.node.convertTouchToNodeSpaceAR(touch); + var localTouchPos = this.node.convertTouchToNodeSpaceAR(touch); if (this.direction === Direction.Horizontal) { - maxRange = this.node.width / 2 - this.handle.node.width * this.handle.node.anchorX; - progress = cc.clamp01((newPos.x + maxRange) / (maxRange * 2), 0, 1); + this.progress = cc.clamp01(0.5 + (localTouchPos.x - this._offset.x) / this.node.width); } - else if (this.direction === Direction.Vertical) { - maxRange = this.node.height / 2 - this.handle.node.height * this.handle.node.anchorY; - progress = cc.clamp01((newPos.y + maxRange) / (maxRange * 2), 0, 1); + else { + this.progress = cc.clamp01(0.5 + (localTouchPos.y - this._offset.y) / this.node.height); } - this.progress = progress; }, _updateHandlePosition: function () { From 9a092f8882a8d854b229ca0acce2db5a30ab4239 Mon Sep 17 00:00:00 2001 From: knoxHuang <821686174@qq.com> Date: Fri, 12 Jan 2018 16:26:21 +0800 Subject: [PATCH 121/127] add path api and refine code format --- cocos2d/core/utils/CCPath.js | 37 ++++++++++++++++++++++-------------- 1 file changed, 23 insertions(+), 14 deletions(-) diff --git a/cocos2d/core/utils/CCPath.js b/cocos2d/core/utils/CCPath.js index 89888cc9b2..33f313a29c 100644 --- a/cocos2d/core/utils/CCPath.js +++ b/cocos2d/core/utils/CCPath.js @@ -29,12 +29,15 @@ var EXTNAME_RE = /(\.[^\.\/\?\\]*)(\?.*)?$/; var NORMALIZE_RE = /[^\.\/]+\/\.\.\//; /** + * !#en The module provides utilities for working with file and directory paths + * !#zh 用于处理文件与目录的路径的模块 * @class path * @static */ cc.path = /** @lends cc.path# */{ /** - * Join strings to be a path. + * !#en Join strings to be a path. + * !#zh 拼接字符串为 Path * @method join * @example {@link utils/api/engine/docs/cocos2d/core/utils/CCPath/join.js} * @returns {String} @@ -49,7 +52,8 @@ cc.path = /** @lends cc.path# */{ }, /** - * Get the ext name of a path including '.', like '.png'. + * !#en Get the ext name of a path including '.', like '.png'. + * !#zh 返回 Path 的扩展名,包括 '.',例如 '.png'。 * @method extname * @example {@link utils/api/engine/docs/cocos2d/core/utils/CCPath/extname.js} * @param {String} pathStr @@ -61,23 +65,25 @@ cc.path = /** @lends cc.path# */{ }, /** - * Get the main name of a file name + * !#en Get the main name of a file name + * !#zh 获取文件名的主名称 * @method mainFileName * @param {String} fileName * @returns {String} */ - mainFileName: function(fileName){ - if(fileName){ - + mainFileName: function (fileName) { + if (fileName) { + var idx = fileName.lastIndexOf("."); - if(idx !== -1) - return fileName.substring(0,idx); + if (idx !== -1) + return fileName.substring(0, idx); } return fileName; }, /** - * Get the file name of a file path. + * !#en Get the file name of a file path. + * !#zh 获取文件路径的文件名。 * @method basename * @example {@link utils/api/engine/docs/cocos2d/core/utils/CCPath/basename.js} * @param {String} pathStr @@ -97,7 +103,8 @@ cc.path = /** @lends cc.path# */{ }, /** - * Get dirname of a file path. + * !#en Get dirname of a file path. + * !#zh 获取文件路径的目录名。 * @method dirname * @example {@link utils/api/engine/docs/cocos2d/core/utils/CCPath/dirname.js} * @param {String} pathStr @@ -108,7 +115,8 @@ cc.path = /** @lends cc.path# */{ }, /** - * Change extname of a file path. + * !#en Change extname of a file path. + * !#zh 更改文件路径的扩展名。 * @method changeExtname * @example {@link utils/api/engine/docs/cocos2d/core/utils/CCPath/changeExtname.js} * @param {String} pathStr @@ -128,7 +136,8 @@ cc.path = /** @lends cc.path# */{ return pathStr.substring(0, index) + extname + tempStr; }, /** - * Change file name of a file path. + * !#en Change file name of a file path. + * !#zh 更改文件路径的文件名。 * @example {@link utils/api/engine/docs/cocos2d/core/utils/CCPath/changeBasename.js} * @param {String} pathStr * @param {String} basename @@ -149,14 +158,14 @@ cc.path = /** @lends cc.path# */{ return pathStr.substring(0, index) + basename + ext + tempStr; }, //todo make public after verification - _normalize: function(url){ + _normalize: function (url) { var oldUrl = url = String(url); //removing all ../ do { oldUrl = url; url = url.replace(NORMALIZE_RE, ""); - } while(oldUrl.length !== url.length); + } while (oldUrl.length !== url.length); return url; }, From 2d4a67b64a6b35b3155c977b0914bed36dba8003 Mon Sep 17 00:00:00 2001 From: VisualSJ Date: Fri, 12 Jan 2018 17:13:13 +0800 Subject: [PATCH 122/127] Add node locked flag --- cocos2d/core/platform/CCObject.js | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/cocos2d/core/platform/CCObject.js b/cocos2d/core/platform/CCObject.js index 616d07a134..2d923291d6 100644 --- a/cocos2d/core/platform/CCObject.js +++ b/cocos2d/core/platform/CCObject.js @@ -12,6 +12,7 @@ var Dirty = 1 << 5; var DontDestroy = 1 << 6; var Destroying = 1 << 7; var Deactivating = 1 << 8; +var LockedInEditor = 1 << 9; //var HideInGame = 1 << 9; //var HideInEditor = 1 << 10; @@ -109,6 +110,15 @@ JS.value(CCObject, 'Flags', { */ Deactivating, + /** + * !#en The lock node, when the node is locked, cannot be clicked in the scene. + * !#zh 锁定节点,锁定后场景内不能点击 + * + * @property LockedInEditor + * @private + */ + LockedInEditor, + ///** // * !#en // * Hide in game and hierarchy. From 027274708f2f2c2fb383e86560148d80f6ba3561 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 16 Jan 2018 17:28:05 +0800 Subject: [PATCH 123/127] Fix issues caused by merging master --- cocos2d/core/CCDirector.js | 6 +++--- cocos2d/core/CCGame.js | 4 ++-- cocos2d/core/CCNode.js | 17 +++++------------ .../core/load-pipeline/auto-release-utils.js | 4 ++++ cocos2d/core/sprites/CCSpriteFrame.js | 4 ++-- cocos2d/core/textures/CCTexture2D.js | 1 - cocos2d/deprecated.js | 11 ++++++++++- gulp/tasks/engine.js | 6 +----- jsb/jsb-tex-sprite-frame.js | 5 +---- 9 files changed, 28 insertions(+), 30 deletions(-) diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index e4a77e7355..c23a7777ef 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -31,7 +31,7 @@ const ComponentScheduler = require('./component-scheduler'); const NodeActivator = require('./node-activator'); const EventListeners = require('./event/event-listeners'); const renderer = require('./renderer'); -var eventManager = require('./event-manager'); +const eventManager = require('./event-manager'); cc.g_NumberOfDraws = 0; @@ -193,8 +193,8 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ this._nodeActivator = new NodeActivator(); // Event manager - if (cc.eventManager) { - cc.eventManager.setEnabled(true); + if (eventManager) { + eventManager.setEnabled(true); } // Animation manager diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index dcdca97161..ef9c9ea8fa 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -715,8 +715,8 @@ var game = { if (isWeChatGame) { opts['preserveDrawingBuffer'] = true; } - this._renderContext = cc._renderContext = cc.webglContext - = cc.create3DContext(localCanvas, opts); + renderer.init(localCanvas, opts); + this._renderContext = cc._renderContext = renderer.device._gl; } if (!this._renderContext) { cc._renderType = game.RENDER_TYPE_CANVAS; diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 1d9ebbbf71..04513fb11e 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -29,7 +29,7 @@ const mathPools = require('./utils/math-pools'); const renderEngine = require('./renderer/render-engine'); const affineTrans = require('./value-types/CCAffineTransform'); const math = renderEngine.math; -var eventManager = require('./event-manager'); +const eventManager = require('./event-manager'); const Flags = cc.Object.Flags; const Destroying = Flags.Destroying; @@ -44,8 +44,8 @@ const CHILD_REORDER = 'child-reorder'; const ERR_INVALID_NUMBER = CC_EDITOR && 'The %s is invalid'; const ONE_DEGREE = Math.PI / 180; -var Misc = require('./utils/misc'); -var Event = require('./event/event'); +const Misc = require('./utils/misc'); +const Event = require('./event/event'); //var RegisteredInEditor = Flags.RegisteredInEditor; var ActionManagerExist = !!cc.ActionManager; @@ -340,7 +340,7 @@ function _searchMaskInParent (node) { // function updateOrder (node) { // node._parent._delaySort(); - //cc.eventManager._setDirtyForNode(node); + //eventManager._setDirtyForNode(node); // } /** @@ -915,7 +915,7 @@ var Node = cc.Class({ for (; i < len; i++) { sibling = siblings[i]; sibling._updateOrderOfArrival(); - cc.eventManager._setDirtyForNode(sibling); + eventManager._setDirtyForNode(sibling); } parent._delaySort(); }, @@ -943,7 +943,6 @@ var Node = cc.Class({ this._mouseListener.mask = null; this._mouseListener = null; } - cc.eventManager.removeListeners(this); // Recycle math objects mathPools.mat4.put(this._matrix); @@ -1023,12 +1022,6 @@ var Node = cc.Class({ // the same as _onBatchCreated but untouch prefab _onBatchRestored () { - this._updateDummySgNode(); - - if (this._parent) { - this._parent._sgNode.addChild(this._sgNode); - } - if (!this._activeInHierarchy) { // deactivate ActionManager and EventManager by default if (ActionManagerExist) { diff --git a/cocos2d/core/load-pipeline/auto-release-utils.js b/cocos2d/core/load-pipeline/auto-release-utils.js index 0958e1988c..1eceb5e579 100644 --- a/cocos2d/core/load-pipeline/auto-release-utils.js +++ b/cocos2d/core/load-pipeline/auto-release-utils.js @@ -42,6 +42,10 @@ function parseDepends (key, parsed) { } function visitAsset (asset, excludeMap) { + // Skip assets generated programmatically or by user (e.g. label texture) + if (!asset._uuid) { + return; + } var key = cc.loader._getReferenceKey(asset); if ( !excludeMap[key] ) { excludeMap[key] = true; diff --git a/cocos2d/core/sprites/CCSpriteFrame.js b/cocos2d/core/sprites/CCSpriteFrame.js index b8ca1f372b..0e07a3201a 100644 --- a/cocos2d/core/sprites/CCSpriteFrame.js +++ b/cocos2d/core/sprites/CCSpriteFrame.js @@ -173,7 +173,7 @@ var SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ * @returns {boolean} */ textureLoaded: function () { - return this._texture && this._texture.isLoaded(); + return this._texture && this._texture.loaded; }, /** @@ -418,7 +418,7 @@ var SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ */ ensureLoadTexture: function () { if (this._texture) { - if (!this._texture.isLoaded()) { + if (!this._texture.loaded) { // load exists texture this._refreshTexture(this._texture); this._texture.load(); diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 0789b95eaa..050d4d07be 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -651,7 +651,6 @@ var Texture2D = cc.Class({ this._uuid = uuid; var url = this.nativeUrl; this.url = url; - cc.textureCache.cacheImage(url, this); } } } diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js index 1193f2bc2b..99bf2940d5 100644 --- a/cocos2d/deprecated.js +++ b/cocos2d/deprecated.js @@ -8,11 +8,20 @@ if (CC_DEV) { cc.errorID(1404); }); - js.obsolete(cc.textureCache, 'cc.textureCache.textureForKey', 'getTextureForKey'); + js.get(cc, 'textureCache', function () { + cc.errorID(1406, 'cc', 'textureCache'); + }); // Texture js.obsolete(cc.Texture2D.prototype, 'texture.releaseTexture', 'texture.destroy'); + js.get(cc.Texture2D.prototype, 'isLoaded', function () { + cc.errorID(1400, 'texture.isLoaded function', 'texture.loaded property'); + return (function () { + return this.loaded; + }); + }); + js.get(cc.SpriteFrame.prototype, '_textureLoaded', function () { cc.errorID(1400, 'spriteFrame._textureLoaded', 'spriteFrame.textureLoaded()'); return this.textureLoaded(); diff --git a/gulp/tasks/engine.js b/gulp/tasks/engine.js index d041778543..369203e81c 100644 --- a/gulp/tasks/engine.js +++ b/gulp/tasks/engine.js @@ -50,10 +50,6 @@ var jsbSkipModules = [ '../../cocos2d/core/physics/platform/CCPhysicsRayCastCallback.js', '../../cocos2d/core/platform/CCInputManager.js', '../../cocos2d/core/platform/CCVisibleRect.js', - '../../cocos2d/core/camera/CCSGCameraNode.js', - '../../cocos2d/core/videoplayer/CCSGVideoPlayer.js', - '../../cocos2d/core/webview/CCSGWebView.js', - '../../cocos2d/core/editbox/CCSGEditBox.js', '../../cocos2d/core/graphics/helper.js', '../../cocos2d/actions/index.js', '../../cocos2d/audio/CCAudio', @@ -172,7 +168,7 @@ exports.buildPreview = function (sourceFile, outputFile, callback, devMode) { if (!devMode) { bundler = bundler .pipe(Sourcemaps.init({loadMaps: true})) - .pipe(Minify(Utils.getUglifyOptions('preview', false, false))) + .pipe(Utils.uglify('preview')) .pipe(Optimizejs({ sourceMap: false })) diff --git a/jsb/jsb-tex-sprite-frame.js b/jsb/jsb-tex-sprite-frame.js index ac8a867a23..9e5dd332f2 100644 --- a/jsb/jsb-tex-sprite-frame.js +++ b/jsb/jsb-tex-sprite-frame.js @@ -160,9 +160,6 @@ prototype.update = function (options) { this.generateMipmap(); } }; -prototype.isLoaded = function () { - return true; -}; prototype.description = prototype.getDescription; cc.js.get(prototype, 'width', prototype.getPixelsWide); cc.js.get(prototype, 'height', prototype.getPixelsHigh); @@ -223,7 +220,7 @@ prototype.initWithTexture = prototype.setTexture; prototype.ensureLoadTexture = function () { if (this._texture) { - if (!this._texture.isLoaded()) { + if (!this._texture.loaded) { // load exists texture this._refreshTexture(this._texture); this._texture.load(); From 514906576cc406b932d2b8ba867f33b8ee09a12b Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 16 Jan 2018 17:28:15 +0800 Subject: [PATCH 124/127] Fix mask image stencil issue --- cocos2d/core/renderer/assemblers/mask-assembler.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/cocos2d/core/renderer/assemblers/mask-assembler.js b/cocos2d/core/renderer/assemblers/mask-assembler.js index 337749df80..2cbeb2e936 100644 --- a/cocos2d/core/renderer/assemblers/mask-assembler.js +++ b/cocos2d/core/renderer/assemblers/mask-assembler.js @@ -113,7 +113,8 @@ let maskFrontAssembler = js.addon({ // vertex buffer if (mask._type === Mask.Type.IMAGE_STENCIL) { batchData.comp = mask; - spriteAssembler.fillBuffers(batchData, vertexId, vbuf, uintbuf, ibuf); + spriteAssembler.fillVertexBuffer(mask, batchData.byteOffset / 4, vbuf, uintbuf); + spriteAssembler.fillIndexBuffer(mask, batchData.indiceOffset, vertexId, ibuf); } else { // Share node for correct global matrix @@ -155,7 +156,8 @@ let maskEndAssembler = js.addon({ // vertex buffer if (mask._type === Mask.Type.IMAGE_STENCIL) { batchData.comp = mask; - spriteAssembler.fillBuffers(batchData, vertexId, vbuf, uintbuf, ibuf); + spriteAssembler.fillVertexBuffer(mask, batchData.byteOffset / 4, vbuf, uintbuf); + spriteAssembler.fillIndexBuffer(mask, batchData.indiceOffset, vertexId, ibuf); } else { // Share node for correct global matrix From 3aa3d3ebcea11bb40eabb42852e315edb846c6b4 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 16 Jan 2018 17:28:28 +0800 Subject: [PATCH 125/127] Fix ParticleSystem property type issue --- cocos2d/particle/CCParticleSystem.js | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js index 1bb636f37c..4f3575a6ab 100644 --- a/cocos2d/particle/CCParticleSystem.js +++ b/cocos2d/particle/CCParticleSystem.js @@ -603,7 +603,10 @@ var properties = { * @property {ParticleSystem.PositionType} positionType * @default ParticleSystem.PositionType.FREE */ - positionType: PositionType.FREE, + positionType: { + default: PositionType.FREE, + type: PositionType + }, /** * !#en Particles emitter modes. @@ -611,7 +614,10 @@ var properties = { * @property {ParticleSystem.EmitterMode} emitterMode * @default ParticleSystem.EmitterMode.GRAVITY */ - emitterMode: EmitterMode.GRAVITY, + emitterMode: { + default: EmitterMode.GRAVITY, + type: EmitterMode + }, // GRAVITY MODE @@ -791,9 +797,6 @@ var properties = { rotatePerSVar: 0 }; -properties.positionType.type = PositionType; -properties.emitterMode.type = EmitterMode; - /** * Particle System base class.
* Attributes of a Particle System:
From 444360c603feda6adbb3d7a1445835c1e0aad620 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 16 Jan 2018 17:28:52 +0800 Subject: [PATCH 126/127] Fix dragonbones texture asset issue --- extensions/dragonbones/ArmatureDisplay.js | 96 +++++++---------------- extensions/dragonbones/CCFactory.js | 17 +++- extensions/dragonbones/CCSlot.js | 1 + 3 files changed, 44 insertions(+), 70 deletions(-) diff --git a/extensions/dragonbones/ArmatureDisplay.js b/extensions/dragonbones/ArmatureDisplay.js index c6597377a9..8221e72b2e 100644 --- a/extensions/dragonbones/ArmatureDisplay.js +++ b/extensions/dragonbones/ArmatureDisplay.js @@ -76,9 +76,9 @@ let ArmatureDisplay = cc.Class({ }, properties: { - _dragonBonesData: { + _factory: { default: null, - type: dragonBones.DragonBonesData, + type: dragonBones.CCFactory, serializable: false, }, @@ -122,6 +122,7 @@ let ArmatureDisplay = cc.Class({ // parse the atlas asset data this._parseDragonAtlasAsset(); this._buildArmature(); + this._activateMaterial(); }, tooltip: CC_DEV && 'i18n:COMPONENT.dragon_bones.dragon_bones_atlas_asset' }, @@ -284,6 +285,15 @@ let ArmatureDisplay = cc.Class({ ctor () { this._inited = false; + if (CC_JSB) { + // TODO Fix me + // If using the getFactory in JSB. + // There may be throw errors when close the application. + this._factory = new dragonBones.CCFactory(); + } + else { + this._factory = dragonBones.CCFactory.getFactory(); + } }, __preload () { @@ -335,10 +345,12 @@ let ArmatureDisplay = cc.Class({ }, _activateMaterial () { - if (this._material) return; + let texture = this.dragonAtlasAsset.texture; + if (this._material || !texture) + return; - let url = this.dragonAtlasAsset.texture; - let material = renderer.materialUtil.get(url); + let url = texture.url; + let material = renderer.materialUtil.get(texture.url); // Get material if (!material) { @@ -346,17 +358,7 @@ let ArmatureDisplay = cc.Class({ renderer.materialUtil.register(url, material); } - // TODO: old texture in material have been released by loader - let texture = cc.loader.getRes(url, cc.Texture2D); - if (!texture) { - cc.loader.load(url, (err, texture) => { - material.texture = texture ? texture.getImpl() : undefined; - }); - } - else { - material.texture = texture.getImpl(); - } - + material.texture = texture.getImpl(); this._material = material; }, @@ -364,7 +366,7 @@ let ArmatureDisplay = cc.Class({ if (!this.dragonAsset || !this.dragonAtlasAsset || !this.armatureName) return; let factory = dragonBones.CCFactory.getFactory(); - this._armature = factory.buildArmatureDisplay(this.armatureName, this._dragonBonesData.name, this); + this._armature = factory.buildArmatureDisplay(this.armatureName, this.dragonAsset._dragonBonesData.name, this); this._armature.animation.timeScale = this.timeScale; if (this.animationName) { @@ -373,55 +375,14 @@ let ArmatureDisplay = cc.Class({ }, _parseDragonAsset () { - if (!this.dragonAsset) return; - - let factory = dragonBones.CCFactory.getFactory(); - let jsonObj = JSON.parse(this.dragonAsset.dragonBonesJson); - let data = factory.getDragonBonesData(jsonObj.name); - if (data) { - // already added asset - let armature, dragonBonesData; - for (let i = 0, len = jsonObj.armature.length; i < len; i++) { - armature = jsonObj.armature[i]; - if (!data.armatures[armature.name]) { - //add new armature - if (!dragonBonesData) { - dragonBonesData = factory._dataParser.parseDragonBonesData(jsonObj); - } - data.addArmature(dragonBonesData.armatures[armature.name]); - } - } - this._dragonBonesData = data; - return; + if (this.dragonAsset) { + this.dragonAsset.init(this._factory); } - this._dragonBonesData = factory.parseDragonBonesData(jsonObj); }, _parseDragonAtlasAsset () { - if (!this.dragonAtlasAsset) return; - - let factory = dragonBones.CCFactory.getFactory(); - let atlasJsonObj = JSON.parse(this.dragonAtlasAsset.atlasJson); - let atlasName = atlasJsonObj.name; - let existedAtlasData = null; - let atlasDataList = factory.getTextureAtlasData(atlasName); - let texturePath = this.dragonAtlasAsset.texture; - if (atlasDataList && atlasDataList.length > 0) { - for (let idx in atlasDataList) { - let data = atlasDataList[idx]; - if (data && data.texture && data.texture.url === texturePath) { - existedAtlasData = data; - break; - } - } - } - - let texture = cc.loader.getRes(texturePath); - if (existedAtlasData) { - existedAtlasData.texture = texture; - } - else { - factory.parseTextureAtlasData(atlasJsonObj, texture); + if (this.dragonAtlasAsset) { + this.dragonAtlasAsset.init(this._factory); } }, @@ -495,11 +456,8 @@ let ArmatureDisplay = cc.Class({ * @returns {Array} */ getArmatureNames () { - if (this._dragonBonesData) { - return this._dragonBonesData.armatureNames; - } - - return []; + var dragonBonesData = this.dragonAsset && this.dragonAsset._dragonBonesData; + return (dragonBonesData && dragonBonesData.armatureNames) || []; }, /** @@ -513,8 +471,8 @@ let ArmatureDisplay = cc.Class({ */ getAnimationNames (armatureName) { let ret = []; - if (this._dragonBonesData) { - let armatureData = this._dragonBonesData.getArmature(armatureName); + if (this.dragonAsset && this.dragonAsset._dragonBonesData) { + let armatureData = this.dragonAsset._dragonBonesData.getArmature(armatureName); if (armatureData) { for (let animName in armatureData.animations) { if (armatureData.animations.hasOwnProperty(animName)) { diff --git a/extensions/dragonbones/CCFactory.js b/extensions/dragonbones/CCFactory.js index efb35e4dad..26024e3466 100644 --- a/extensions/dragonbones/CCFactory.js +++ b/extensions/dragonbones/CCFactory.js @@ -28,6 +28,16 @@ var CCFactory = dragonBones.CCFactory = cc.Class({ name: 'dragonBones.CCFactory', extends: dragonBones.BaseFactory, + statics: { + _factory: null, + getFactory () { + if (!CCFactory._factory) { + CCFactory._factory = new CCFactory(); + } + return CCFactory._factory; + } + }, + ctor () { this.__instanceId = cc.ClassManager.getNewInstanceId(); this._dragoneBones = new dragonBones.DragonBones(); @@ -48,6 +58,11 @@ var CCFactory = dragonBones.CCFactory = cc.Class({ return armature; }, + parseTextureAtlasData (jsonString, texture) { + var atlasJsonObj = JSON.parse(jsonString); + return this._super(atlasJsonObj, texture); + }, + createArmatureNode (comp, armatureName, node) { node = node || new cc.Node(); let display = node.getComponent(dragonBones.ArmatureDisplay); @@ -147,4 +162,4 @@ var CCFactory = dragonBones.CCFactory = cc.Class({ return slot; } -}); +}); \ No newline at end of file diff --git a/extensions/dragonbones/CCSlot.js b/extensions/dragonbones/CCSlot.js index 111ef420b6..b3c70854d3 100644 --- a/extensions/dragonbones/CCSlot.js +++ b/extensions/dragonbones/CCSlot.js @@ -100,6 +100,7 @@ dragonBones.CCSlot = cc.Class({ }, _updateBlendMode () { + // TODO: new implementation needed return; if (this._renderDisplay instanceof cc.Scale9Sprite) { switch (this._blendMode) { From 4e4df6675e90c38ece0c8fc728a5a7c8dcaaa76e Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 16 Jan 2018 17:29:22 +0800 Subject: [PATCH 127/127] Fix spine texture asset issue --- extensions/spine/Skeleton.js | 89 ++++++++++++++++--------------- extensions/spine/skeleton-data.js | 82 ++++++++++------------------ 2 files changed, 75 insertions(+), 96 deletions(-) diff --git a/extensions/spine/Skeleton.js b/extensions/spine/Skeleton.js index 8e7decf4c9..7c8c897125 100644 --- a/extensions/spine/Skeleton.js +++ b/extensions/spine/Skeleton.js @@ -103,6 +103,7 @@ sp.Skeleton = cc.Class({ if (CC_EDITOR) { this._refreshInspector(); } + this._updateSkeletonData(); }, tooltip: CC_DEV && 'i18n:COMPONENT.skeleton.skeleton_data' }, @@ -383,22 +384,7 @@ sp.Skeleton = cc.Class({ this._refreshInspector(); } - if (this.skeletonData/* && this.atlasFile*/) { - var data = this.skeletonData.getRuntimeData(); - if (data) { - try { - this.setSkeletonData(data); - this.setAnimationStateData(new spine.AnimationStateData(this._skeleton.data)); - if (this.defaultSkin) { - this._skeleton.setSkinByName(this.defaultSkin); - } - } - catch (e) { - cc.warn(e); - } - this.animation = this.defaultAnimation; - } - } + this._updateSkeletonData(); }, onDestroy () { @@ -727,32 +713,6 @@ sp.Skeleton = cc.Class({ } }, - // update animation list for editor - _updateAnimEnum: CC_EDITOR && function () { - var animEnum; - if (this.skeletonData) { - animEnum = this.skeletonData.getAnimsEnum(); - } - // change enum - setEnumAttr(this, '_animationIndex', animEnum || DefaultAnimsEnum); - }, - // update skin list for editor - _updateSkinEnum: CC_EDITOR && function () { - var skinEnum; - if (this.skeletonData) { - skinEnum = this.skeletonData.getSkinsEnum(); - } - // change enum - setEnumAttr(this, '_defaultSkinIndex', skinEnum || DefaultSkinsEnum); - }, - - _ensureListener () { - if (!this._listener) { - this._listener = new TrackEntryListeners(); - this._state.addListener(this._listener); - } - }, - /** * !#en Set the start event listener. * !#zh 用来设置开始播放动画的事件监听。 @@ -900,6 +860,51 @@ sp.Skeleton = cc.Class({ return this._state; }, + // update animation list for editor + _updateAnimEnum: CC_EDITOR && function () { + var animEnum; + if (this.skeletonData) { + animEnum = this.skeletonData.getAnimsEnum(); + } + // change enum + setEnumAttr(this, '_animationIndex', animEnum || DefaultAnimsEnum); + }, + // update skin list for editor + _updateSkinEnum: CC_EDITOR && function () { + var skinEnum; + if (this.skeletonData) { + skinEnum = this.skeletonData.getSkinsEnum(); + } + // change enum + setEnumAttr(this, '_defaultSkinIndex', skinEnum || DefaultSkinsEnum); + }, + + _ensureListener () { + if (!this._listener) { + this._listener = new TrackEntryListeners(); + this._state.addListener(this._listener); + } + }, + + _updateSkeletonData () { + if (this.skeletonData/* && this.atlasFile*/) { + let data = this.skeletonData.getRuntimeData(); + if (data) { + try { + this.setSkeletonData(data); + this.setAnimationStateData(new spine.AnimationStateData(this._skeleton.data)); + if (this.defaultSkin) { + this._skeleton.setSkinByName(this.defaultSkin); + } + } + catch (e) { + cc.warn(e); + } + this.animation = this.defaultAnimation; + } + } + }, + _refreshInspector () { // update inspector this._updateAnimEnum(); diff --git a/extensions/spine/skeleton-data.js b/extensions/spine/skeleton-data.js index fe338c5846..0f57fba24b 100644 --- a/extensions/spine/skeleton-data.js +++ b/extensions/spine/skeleton-data.js @@ -27,48 +27,6 @@ * @module sp */ -// implements a simple texture loader like sp._atlasLoader -var TextureLoader = cc.Class({ - ctor: function () { - // {SkeletonData} - this.asset = arguments[0]; - }, - getTexture: function (line) { - //var name = cc.path.mainFileName(line); - //var textures = this.asset.textures; - //for (var i = 0; i < textures.length; i++) { - // var tex = textures[i]; - // if (tex.name === name) { - // return tex; - // } - //} - var urls = this.asset.textures; - for (var i = 0; i < urls.length; i++) { - var url = urls[i]; - if (url.endsWith(line)) { - var texture = cc.textureUtil.loadImage(url); - var tex = new sp.SkeletonTexture({ width: texture.width, height: texture.height }); - tex.setRealTexture(texture); - return tex; - } - } - return null; - }, - load: function (line) { - var texture = this.getTexture(line); - if (texture) { - return texture; - } - else { - cc.errorID(7506, line); - return null; - } - }, - unload: function (obj) { - //page.rendererObject.release(); - } -}); - /** * !#en The skeleton data of spine. * !#zh Spine 的 骨骼数据。 @@ -117,19 +75,21 @@ var SkeletonData = cc.Class({ } }, - // Fallback to raw asset for JSB ------------------- - atlasUrl: { - default: '', - url: cc.RawAsset - }, - // ------------------------------------------------- - /** * @property {Texture2D[]} textures */ textures: { default: [], - url: [cc.Texture2D] + type: [cc.Texture2D] + }, + + /** + * @property {String[]} textureNames + * @private + */ + textureNames: { + default: [], + type: [cc.String] }, /** @@ -148,7 +108,8 @@ var SkeletonData = cc.Class({ }, statics: { - preventDeferredLoadDependents: true + preventDeferredLoadDependents: true, + preventPreloadNativeObject: true, }, // PUBLIC @@ -192,7 +153,7 @@ var SkeletonData = cc.Class({ return this._skeletonCache; } - if ( !(this.textures && this.textures.length > 0) ) { + if ( !(this.textures && this.textures.length > 0) && this.textureNames && this.textureNames.length > 0 ) { if ( !quiet ) { cc.errorID(7507, this.name); } @@ -252,6 +213,20 @@ var SkeletonData = cc.Class({ // PRIVATE + _getTexture: !CC_JSB && function (line) { + var names = this.textureNames; + for (var i = 0; i < names.length; i++) { + if (names[i] === line) { + var texture = this.textures[i]; + var tex = new sp.SkeletonTexture({ width: texture.width, height: texture.height }); + tex.setRealTexture(texture); + return tex; + } + } + cc.errorID(7506, line); + return null; + }, + /** * @method _getAtlas * @param {boolean} [quiet=false] @@ -270,8 +245,7 @@ var SkeletonData = cc.Class({ return null; } - var loader = new TextureLoader(this); - return this._atlasCache = new sp.spine.TextureAtlas(this.atlasText, loader.load.bind(loader)); + return this._atlasCache = new sp.spine.TextureAtlas(this.atlasText, this._getTexture.bind(this)); } });