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 项目) + + + 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/CCBoot.js b/CCBoot.js index dcf9bc2d51..0aacc357c3 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 b7e4ef1a0e..e538769256 100644 --- a/CCDebugger.js +++ b/CCDebugger.js @@ -23,11 +23,11 @@ THE SOFTWARE. ****************************************************************************/ -// for cc.DebugMode.INFO_FOR_WEB_PAGE -var logList; - var Enum = require('./cocos2d/core/platform/CCEnum'); +// the html element displays log in web page (cc.DebugMode.INFO_FOR_WEB_PAGE) +var logList; + /** * !#en Enum for debug modes. * !#zh 调试模式 @@ -92,10 +92,6 @@ cc.DebugMode = Enum({ ERROR_FOR_WEB_PAGE: 6 }); -/** - * @module cc - */ - /** * !#en Init Debug setting. * !#zh 设置调试模式。 @@ -104,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; @@ -292,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) { @@ -329,26 +307,56 @@ cc._throw = CC_EDITOR ? Editor.error : function (error) { } }; -var errorMapUrl = 'https://github.com/cocos-creator/engine/blob/master/EngineErrorMap.md'; +// define log methods to lookup message ID -function genLogFunc(func, type) { - return function (id) { - 'use strict'; +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 () { + 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) { - CC_DEBUG ? func(cc._LogInfos[id]) : func(type + ' ' + id + ', please go to ' + errorMapUrl + '#' + id + ' to see details.'); - return; + return 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) { + 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 6aac1fca69..ef1a1b1009 100644 --- a/DebugInfos.js +++ b/DebugInfos.js @@ -1,5 +1,7 @@ if (CC_DEBUG) { - var logs = { + module.exports = { + // 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 @@ -22,6 +24,16 @@ 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 @@ -242,9 +254,9 @@ if (CC_DEBUG) { "3117": "Mimpap texture only works in POT textures", //generateMipmap "3118": "Lazy init texture with image element failed due to image loading failure: %s", //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 @@ -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 @@ -322,7 +335,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" + @@ -339,6 +352,14 @@ if (CC_DEBUG) { " set %s (value) {\n" + " ...\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" + + "}", + "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 @@ -363,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 @@ -376,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 @@ -430,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 @@ -438,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 @@ -501,8 +534,20 @@ if (CC_DEBUG) { "6013": "Particle system: not enough memory", //initWithTotalParticles "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. + "6016": "_ccsg.ParticleSystem._allocMemory(): Memory should not be allocated when not using batchNode", //WebGLRenderCmd._allocMemory "6017": "Please use spriteFrame property to set new texture, texture property is readonly from v1.9", + "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 @@ -512,8 +557,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 @@ -524,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 @@ -563,6 +611,22 @@ 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": "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 //Wrapper: 7300 "7300": "The new selected must be number", //CheckBox.selected "7301": "The new bake must be boolean", //layer @@ -584,6 +648,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 @@ -604,6 +674,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 @@ -616,6 +688,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 @@ -628,16 +704,4 @@ if (CC_DEBUG) { "9000": "Stencil manager does not support level bigger than %d in this device.", "9001": "Stencil manager is already empty, cannot pop any mask", }; - cc._LogInfos = logs; } - -// 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; -// } 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/actions/CCAction.js b/cocos2d/actions/CCAction.js index 5e362ef7fd..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.Speed.initWithAction(): action must be non nil"); + 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.Follow.initWithAction(): followedNode must be non nil"); + 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 20e2d2a2b4..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("Invalid configuration. It must at least have one control point"); + 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 e33b3f6251..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.ActionEase.initWithAction(): action must be non nil"); + 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 f293913dfa..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.Sequence.initWithTwoActions(): arguments must all be non nil"); + 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.RepeatForever.initWithAction(): action must be non null"); + 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.Spawn.initWithTwoActions(): arguments must all be non null"); + 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.ReverseTime.initWithAction(): action must be non null"); + throw new Error(cc._getError(1028)); if(action === this._other) - throw new Error("cc.ReverseTime.initWithAction(): the action was already passed in."); + 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.Animate.initWithAnimation(): animation must be non-NULL"); + 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 55185d3fa3..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.ActionManager.addAction(): action must be non-null"); + throw new Error(cc._getError(1000)); if(!target) - throw new Error("cc.ActionManager.addAction(): action must be non-null"); + 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 648e8680a3..b0bf1bf459 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._getError(3912)); } } else { 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/audio/CCAudioEngine.js b/cocos2d/audio/CCAudioEngine.js index 3dd6f0c986..5bf879d392 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) { @@ -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..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 () { @@ -42,185 +41,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.warnID(1400, '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.warnID(1400, 'audioEngine.unloadEffect', 'audioEngine.stop'); return function (id) { return audioEngine.stop(id); } @@ -228,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 e87b9acdfb..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("Please load the resource first : " + url); + if(!dict) throw new Error(cc._getError(1102, url)); cc.assertID(dict, 1101, url); var getDatas = dict["data"]; diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index 3fb0bf99aa..c23a7777ef 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -31,6 +31,7 @@ const ComponentScheduler = require('./component-scheduler'); const NodeActivator = require('./node-activator'); const EventListeners = require('./event/event-listeners'); const renderer = require('./renderer'); +const eventManager = require('./event-manager'); cc.g_NumberOfDraws = 0; @@ -192,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 @@ -352,9 +353,13 @@ 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} + * @deprecated */ getWinSizeInPixels: function () { return cc.size(this._winSizeInPoints.width * this._contentScaleFactor, this._winSizeInPoints.height * this._contentScaleFactor); @@ -446,8 +451,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 @@ -482,8 +487,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){ @@ -1505,7 +1510,7 @@ cc.DisplayLinkDirector = cc.Director.extend(/** @lends cc.Director# */{ this._totalFrames++; this.emit(cc.Director.EVENT_AFTER_DRAW); - cc.eventManager.frameUpdateListeners(); + eventManager.frameUpdateListeners(); } }, @@ -1535,12 +1540,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); } }, }); diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index d5f76a37c8..ef9c9ea8fa 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -651,14 +651,14 @@ 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._getError(3820, this.config[this.CONFIG_KEY.renderMode])); } 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"); this.frame = localContainer.parentNode === document.body ? document.documentElement : localContainer.parentNode; @@ -708,11 +708,14 @@ var game = { // WebGL context created successfully if (cc._renderType === game.RENDER_TYPE_WEBGL) { - win.gl = this._renderContext; // global variable declared in CCMacro.js - renderer.init(localCanvas, { + var opts = { 'stencil': true, 'alpha': cc.macro.ENABLE_TRANSPARENT_CANVAS - }); + }; + if (isWeChatGame) { + opts['preserveDrawingBuffer'] = true; + } + renderer.init(localCanvas, opts); this._renderContext = cc._renderContext = renderer.device._gl; } if (!this._renderContext) { @@ -732,58 +735,76 @@ 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 (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); + win.addEventListener("pagehide", onHidden); + win.addEventListener("pageshow", onShown); + // Taobao UIWebKit + document.addEventListener("pagehide", onHidden); + document.addEventListener("pageshow", onShown); } this.on(game.EVENT_HIDE, function () { diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index c34c014c07..04513fb11e 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -29,6 +29,7 @@ const mathPools = require('./utils/math-pools'); const renderEngine = require('./renderer/render-engine'); const affineTrans = require('./value-types/CCAffineTransform'); const math = renderEngine.math; +const eventManager = require('./event-manager'); const Flags = cc.Object.Flags; const Destroying = Flags.Destroying; @@ -43,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; @@ -164,6 +165,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; @@ -180,6 +183,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); } }; @@ -200,6 +205,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); } }; @@ -218,7 +225,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(); @@ -230,6 +237,7 @@ var _mouseMoveHandler = function (event) { var node = this.owner; 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); } @@ -283,7 +291,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(); @@ -305,7 +313,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(); @@ -332,7 +340,7 @@ function _searchMaskInParent (node) { // function updateOrder (node) { // node._parent._delaySort(); - //cc.eventManager._setDirtyForNode(node); + //eventManager._setDirtyForNode(node); // } /** @@ -907,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(); }, @@ -935,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); @@ -945,6 +952,8 @@ var Node = cc.Class({ cc.director.__fastOff(cc.Director.EVENT_AFTER_UPDATE, this.sortAllChildren, this); } + eventManager.removeListeners(this); + if (!destroyByParent) { // simulate some destruct logic to make undo system work correctly if (CC_EDITOR) { @@ -959,7 +968,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) { @@ -973,7 +982,7 @@ var Node = cc.Class({ else { // deactivate actionManager && actionManager.pauseTarget(this); - cc.eventManager.pauseTarget(this); + eventManager.pauseTarget(this); } }, @@ -989,11 +998,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); } if (!this._activeInHierarchy) { @@ -1001,7 +1011,7 @@ var Node = cc.Class({ if (ActionManagerExist) { cc.director.getActionManager().pauseTarget(this); } - cc.eventManager.pauseTarget(this); + eventManager.pauseTarget(this); } var children = this._children; @@ -1010,6 +1020,22 @@ var Node = cc.Class({ } }, + // the same as _onBatchCreated but untouch prefab + _onBatchRestored () { + if (!this._activeInHierarchy) { + // deactivate ActionManager and EventManager by default + if (ActionManagerExist) { + cc.director.getActionManager().pauseTarget(this); + } + eventManager.pauseTarget(this); + } + + var children = this._children; + for (var i = 0, len = children.length; i < len; i++) { + children[i]._onBatchRestored(); + } + }, + // EVENTS /** @@ -1059,10 +1085,7 @@ var Node = cc.Class({ onTouchMoved: _touchMoveHandler, onTouchEnded: _touchEndHandler }); - if (CC_JSB) { - this._touchListener.retain(); - } - cc.eventManager.addListener(this._touchListener, this); + eventManager.addListener(this._touchListener, this); newAdded = true; } } @@ -1078,17 +1101,14 @@ var Node = cc.Class({ onMouseUp: _mouseUpHandler, onMouseScroll: _mouseWheelHandler, }); - 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); } @@ -1153,7 +1173,7 @@ var Node = cc.Class({ * node.pauseSystemEvents(true); */ pauseSystemEvents (recursive) { - cc.eventManager.pauseTarget(this, recursive); + eventManager.pauseTarget(this, recursive); }, /** @@ -1169,7 +1189,7 @@ var Node = cc.Class({ * node.resumeSystemEvents(true); */ resumeSystemEvents (recursive) { - cc.eventManager.resumeTarget(this, recursive); + eventManager.resumeTarget(this, recursive); }, _checkTouchListeners () { @@ -1190,7 +1210,7 @@ var Node = cc.Class({ } } - cc.eventManager.removeListener(this._touchListener); + eventManager.removeListener(this._touchListener); this._touchListener = null; } }, @@ -1216,7 +1236,7 @@ var Node = cc.Class({ _currentHovered = null; } - cc.eventManager.removeListener(this._mouseListener); + eventManager.removeListener(this._mouseListener); this._mouseListener = null; } }, @@ -1765,8 +1785,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 @@ -2259,7 +2281,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; @@ -2321,11 +2343,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); } }, diff --git a/cocos2d/core/CCScene.js b/cocos2d/core/CCScene.js index 268315fb6d..83b778ca6e 100644 --- a/cocos2d/core/CCScene.js +++ b/cocos2d/core/CCScene.js @@ -57,6 +57,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; }, @@ -74,7 +78,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/assets/CCAsset.js b/cocos2d/core/assets/CCAsset.js index 269c4c659c..96655a46ee 100644 --- a/cocos2d/core/assets/CCAsset.js +++ b/cocos2d/core/assets/CCAsset.js @@ -24,19 +24,22 @@ ****************************************************************************/ var RawAsset = require('./CCRawAsset'); + /** * !#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
+ * - getset functions of _nativeAsset
* - cc.Object._serialize
* - cc.Object._deserialize
* !#zh - * 资源基类,该类可以被实例化。
+ * Creator 中的资源基类。
* * 您可能需要重写:
* - createNode
+ * - _nativeAsset 的 getset 方法
* - cc.Object._serialize
* - cc.Object._deserialize
* @@ -49,18 +52,27 @@ 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 文件,它将返回一个空字符串。 - * @property rawUrl + * Returns the url of this asset's native object, if none it will returns an empty string. + * !#zh + * 返回该资源对应的目标平台资源的 URL,如果没有将返回一个空字符串。 + * @property nativeUrl * @type {String} * @readOnly */ - rawUrl: { + nativeUrl: { get: function () { - if (this._rawFiles) { + if (this._native) { if (cc.AssetLibrary) { - return cc.AssetLibrary.getLibUrlNoExt(this._uuid) + '/' + this._rawFiles[0]; + var base = cc.AssetLibrary.getLibUrlNoExt(this._uuid); + 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); @@ -72,44 +84,40 @@ cc.Asset = cc.Class({ }, /** - * !#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 + * Serializable url for native asset. + * @property {String} _native + * @default undefined + * @private */ - rawUrls: { - get: function () { - if (this._rawFiles) { - if (cc.AssetLibrary) { - var dir = cc.AssetLibrary.getLibUrlNoExt(this._uuid) + '/'; - return this._rawFiles.map(function (filename) { - return dir + filename; - }); - } - else { - cc.errorID(6401); - } - } - return []; - }, - visible: false - }, + _native: "", + + // __nativeAsset: { + // default: null, + // serializable: 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[]} + * 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 */ - _rawFiles: null + _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; + } + }, }, statics: { @@ -122,7 +130,7 @@ cc.Asset = cc.Class({ * @static * @private */ - deserialize: function (data) { + deserialize: CC_EDITOR && function (data) { return cc.deserialize(data); }, @@ -134,7 +142,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 }, /** @@ -144,7 +162,7 @@ cc.Asset = cc.Class({ * @return {String} * @private */ - serialize: function () { + serialize: CC_EDITOR && function () { return Editor.serialize(this); }, @@ -155,6 +173,7 @@ cc.Asset = cc.Class({ * !#zh * 使用该资源在场景中创建一个新节点。
* 如果这类资源没有相应的节点类型,该方法应该是空的。 + * * @method createNode * @param {Function} callback * @param {String} callback.error - null or the error info @@ -163,25 +182,16 @@ cc.Asset = cc.Class({ createNode: null, /** - * Set raw file names for this asset. + * Set native file name for this asset. + * @seealso nativeUrl * - * @method _setRawFiles - * @param {String[]} rawFiles + * @method _setRawAsset + * @param {String} filename * @private */ - _setRawFiles: 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: function (filename) { + this._native = filename || undefined; + } }); module.exports = cc.Asset; 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..b8c0d747ed 100644 --- a/cocos2d/core/assets/CCFont.js +++ b/cocos2d/core/assets/CCFont.js @@ -30,13 +30,11 @@ * !#en Class for Font handling. * !#zh 字体资源类。 * @class Font - * @extends RawAsset - * + * @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/CCPrefab.js b/cocos2d/core/assets/CCPrefab.js index 201c623bea..30c2a897a4 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; - if (cc.supportJit) { + var node, useJit = false; + if (CC_SUPPORT_JIT) { + 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/assets/CCRawAsset.js b/cocos2d/core/assets/CCRawAsset.js index b078669ae7..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,11 +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 +JS.value(cc.RawAsset, 'wasRawAssetType', function (ctor) { + return ctor === cc.Texture2D; }); module.exports = cc.RawAsset; 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/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/collider/CCCollisionManager.js b/cocos2d/core/collider/CCCollisionManager.js index e032b86005..626f4f1086 100644 --- a/cocos2d/core/collider/CCCollisionManager.js +++ b/cocos2d/core/collider/CCCollisionManager.js @@ -419,7 +419,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/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/components/CCButton.js b/cocos2d/core/components/CCButton.js index ca0a2a058a..6f903f8106 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/components/CCCanvas.js b/cocos2d/core/components/CCCanvas.js index 4df4a5d67f..f0de3a7db9 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 () { @@ -143,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); @@ -173,11 +172,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(); @@ -199,12 +198,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); - this._thisOnResized.release(); + eventManager.removeListener(this._thisOnResized); } if (Canvas.instance === this) { diff --git a/cocos2d/core/components/CCComponent.js b/cocos2d/core/components/CCComponent.js index 5a982739b9..eca392761a 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(this); + + scheduler.schedule(callback, this, interval, repeat, delay, paused); }, /** diff --git a/cocos2d/core/components/CCRichText.js b/cocos2d/core/components/CCRichText.js index 371deb4ebc..9025edfc1b 100644 --- a/cocos2d/core/components/CCRichText.js +++ b/cocos2d/core/components/CCRichText.js @@ -278,7 +278,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/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 () { 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') }, /** 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; + } }); }, 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' }, diff --git a/cocos2d/core/components/CCVideoPlayer.js b/cocos2d/core/components/CCVideoPlayer.js index 115f3805ec..7de0281084 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; @@ -97,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(); }, @@ -115,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(); }, @@ -138,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; @@ -155,19 +170,61 @@ 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. + * !#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(); + } + }, + range: [0, 1], + type: cc.Float, + tooltip: CC_DEV && 'i18n:COMPONENT.videoplayer.volume' + }, + + _mute: false, + /** + * !#en Mutes the VideoPlayer. Mute sets the volume=0, Un-Mute restore the original volume. + * !#zh 是否静音视频。静音时设置音量为 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 是否保持视频原来的宽高比 @@ -191,7 +248,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); } }, @@ -212,16 +269,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; @@ -233,16 +298,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(); @@ -280,22 +349,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); }, @@ -306,7 +375,8 @@ var VideoPlayer = cc.Class({ * @method play */ play: function () { - if(this._sgNode) { + if (this._sgNode) { + this._syncVolume(); this._sgNode.play(); } }, @@ -316,8 +386,9 @@ var VideoPlayer = cc.Class({ * !#zh 如果一个视频播放被暂停播放了,调用这个接口可以继续播放。 * @method resume */ - resume: function() { + resume: function () { if (this._sgNode) { + this._syncVolume(); this._sgNode.resume(); } }, @@ -328,7 +399,7 @@ var VideoPlayer = cc.Class({ * @method pause */ pause: function () { - if(this._sgNode) { + if (this._sgNode) { this._sgNode.pause(); } }, @@ -338,8 +409,8 @@ var VideoPlayer = cc.Class({ * !#zh 如果一个视频正在播放,调用这个接口可以立马停止播放。 * @method stop */ - stop: function() { - if(this._sgNode) { + stop: function () { + if (this._sgNode) { this._sgNode.stop(); } }, @@ -350,8 +421,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; @@ -363,8 +434,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/components/CCWebView.js b/cocos2d/core/components/CCWebView.js index 6dc34c3329..3dcbf13d0e 100644 --- a/cocos2d/core/components/CCWebView.js +++ b/cocos2d/core/components/CCWebView.js @@ -271,4 +271,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 */ diff --git a/cocos2d/core/event-manager/CCEventManager.js b/cocos2d/core/event-manager/CCEventManager.js index 135addb9e6..e920dadc08 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; } @@ -546,9 +547,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; } } @@ -581,7 +581,7 @@ cc.eventManager = { // If the event was stopped, return directly. if (event.isStopped()) { - cc.eventManager._updateTouchListeners(event); + eventManager._updateTouchListeners(event); return true; } return false; @@ -809,7 +809,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) @@ -1044,7 +1044,7 @@ cc.eventManager = { this._updateDirtyFlagForSceneGraph(); this._inDispatch++; if(!event || !event.getType) - throw new Error("event is undefined"); + throw new Error(cc._getError(3511)); if (event.getType().startsWith(cc.Event.TOUCH)) { this._dispatchTouchEvent(event); this._inDispatch--; @@ -1081,3 +1081,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/index.js b/cocos2d/core/event-manager/index.js index 1777126e01..a90e2c50b5 100644 --- a/cocos2d/core/event-manager/index.js +++ b/cocos2d/core/event-manager/index.js @@ -22,9 +22,22 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ - -require('./CCTouch'); -require('./CCEventListener'); -require('./CCEventManager'); + require('./CCEvent'); -require('./CCSystemEvent'); + +var eventManager; +if (CC_JSB) { + eventManager = cc.eventManager; +} +else { + require('./CCTouch'); + require('./CCEventListener'); + eventManager = require('./CCEventManager'); +} + +module.exports = eventManager; + +if (CC_TEST) { + cc._Test.eventManager = eventManager; +} + 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 82% rename from cocos2d/core/event-manager/CCSystemEvent.js rename to cocos2d/core/event/system-event.js index 4f00ba1218..e2301fae37 100644 --- a/cocos2d/core/event-manager/CCSystemEvent.js +++ b/cocos2d/core/event/system-event.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/label/CCTextUtils.js b/cocos2d/core/label/CCTextUtils.js index 24b6e48341..02b2bfe9e2 100644 --- a/cocos2d/core/label/CCTextUtils.js +++ b/cocos2d/core/label/CCTextUtils.js @@ -205,10 +205,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) { @@ -289,7 +289,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; @@ -297,16 +297,30 @@ var TextUtils = { sText = text.substr(0, fuzzyLen); } } - if (sText.trim().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); } - if (text.length > 0) { + + if (wrappedWords.length === 0) { wrappedWords.push(text); } - + else { + text = text.trim(); + if (text.length > 0) { + wrappedWords.push(text); + } + } return wrappedWords; }, diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js index c400ae1069..841eac5b94 100644 --- a/cocos2d/core/load-pipeline/CCLoader.js +++ b/cocos2d/core/load-pipeline/CCLoader.js @@ -765,18 +765,11 @@ 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(); + if (cc.Class.isInstanceOf(asset, cc.Asset)) { + if (asset.nativeUrl) { + this.release(asset.nativeUrl); } - var urls = asset.rawUrls; - for (let i = 0; i < urls.length; i++) { - this.release(urls[i]); - } - } - else if (asset instanceof cc.Texture2D) { - asset.releaseTexture(); + asset.destroy(); } if (CC_DEBUG && removed) { this._releasedAssetChecker_DEBUG.setReleased(item, id); diff --git a/cocos2d/core/load-pipeline/asset-loader.js b/cocos2d/core/load-pipeline/asset-loader.js index 266ec35d1b..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('Download Uuid: can not find type of raw asset[' + 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 9cee1057bd..b6d536433f 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; @@ -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._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('Audio Downloader: audio not supported on this browser!'); + return new Error(cc._getError(4927)); } item.content = item.url; diff --git a/cocos2d/core/load-pipeline/auto-release-utils.js b/cocos2d/core/load-pipeline/auto-release-utils.js index 3f2feecca3..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; @@ -57,7 +61,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 +70,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 && value._uuid) { + else if (cc.Class.isInstanceOf(value, cc.RawAsset)) { visitAsset(value, excludeMap); } } diff --git a/cocos2d/core/load-pipeline/downloader.js b/cocos2d/core/load-pipeline/downloader.js index 1576a0e59b..9df905138d 100644 --- a/cocos2d/core/load-pipeline/downloader.js +++ b/cocos2d/core/load-pipeline/downloader.js @@ -41,7 +41,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; @@ -62,7 +62,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._getError(4928, url))); } s.addEventListener('load', loadHandler, false); s.addEventListener('error', errorHandler, false); @@ -71,7 +71,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._getError(4929, item.url)); } return downloadImage(item, callback, isCrossOrigin, img); } @@ -110,7 +110,7 @@ function downloadImage (item, callback, isCrossOrigin, img) { downloadImage(item, callback, false, img); } else { - callback(new Error('Load image (' + url + ') failed')); + callback(new Error(cc._getError(4930, url))); } } @@ -194,9 +194,7 @@ function downloadUuid (item, callback) { if (result === undefined) { return this.extMap['json'](item, callback); } - else if (!!result) { - return result; - } + return result || undefined; } @@ -285,6 +283,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. 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/loader.js b/cocos2d/core/load-pipeline/loader.js index 3093eb01d5..b25c7a623a 100644 --- a/cocos2d/core/load-pipeline/loader.js +++ b/cocos2d/core/load-pipeline/loader.js @@ -28,7 +28,6 @@ var sys = require('../platform/CCSys'); 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; @@ -49,13 +48,17 @@ function loadJSON (item, callback) { } function loadImage (item, callback) { - if (sys.browserType !== sys.BROWSER_TYPE_WECHAT_GAME && !(item.content instanceof Image)) { + var image = item.content; + if (sys.platform !== sys.WECHAT_GAME && !(image instanceof Image)) { return new Error('Image Loader: Input item doesn\'t contain Image content'); } + + // load cc.Texture2D var rawUrl = item.rawUrl; var tex = item.texture || new Texture2D(); tex._uuid = item.uuid; tex.url = rawUrl; + tex._nativeAsset = image; tex.initWithElement(item.content); tex.handleLoadedTexture(); return tex; diff --git a/cocos2d/core/load-pipeline/pack-downloader.js b/cocos2d/core/load-pipeline/pack-downloader.js index 4fd1c52b8a..0dbd87ff13 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 === Unpackers.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/text-downloader.js b/cocos2d/core/load-pipeline/text-downloader.js index d4c6689784..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.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; 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/load-pipeline/uuid-loader.js b/cocos2d/core/load-pipeline/uuid-loader.js index 8eab54ba15..c08d595f09 100644 --- a/cocos2d/core/load-pipeline/uuid-loader.js +++ b/cocos2d/core/load-pipeline/uuid-loader.js @@ -37,77 +37,78 @@ 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); - } - // preload raw files - if (asset._preloadRawFiles) { - var finalCallback = callback; - callback = function () { - asset._preloadRawFiles(function (err) { - finalCallback(err || null, asset); + + // 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', }); - }; - } - // fast path - if (depends.length === 0) { - cc.deserialize.Details.pool.put(tdInfo); - return callback(null, asset); + } } + 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) { @@ -117,19 +118,23 @@ 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; + 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); } @@ -168,7 +173,6 @@ function loadDepends (pipeline, item, asset, tdInfo, deferredLoadRawAssetsInRunt if (CC_EDITOR && missingAssetReporter) { missingAssetReporter.reportByOwner(); } - cc.deserialize.Details.pool.put(tdInfo); callback(null, asset); }); } @@ -181,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; } } @@ -209,14 +213,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._getError(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._getError(4924)); } var classFinder; @@ -261,7 +265,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._getError(4925, item.id, err)); } asset._uuid = item.uuid; @@ -271,7 +275,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/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/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); } } }, 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/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 1f7d159a96..f52f520e20 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 () {}; } @@ -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); } } } @@ -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; @@ -1058,7 +1060,7 @@ cc.isChildClassOf = function (subclass, superclass) { return false; }; -/** +/* * Return all super classes * @method getInheritanceChain * @param {Function} constructor @@ -1078,6 +1080,22 @@ 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} + */ +// 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) { + 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. @@ -1167,21 +1185,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/CCClassDecorator.js b/cocos2d/core/platform/CCClassDecorator.js index c307c610a9..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 || {}); @@ -214,9 +219,16 @@ 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; } + if (cc.RawAsset.wasRawAssetType(prop.url) && + prop._short && + isDefaultValueSpecified && + defaultValue == null + ) { + cc.warnID(3656, JS.getClassName(ctor), propName); + } } prop.default = defaultValue; } @@ -356,8 +368,8 @@ var ccclass = checkCtorArgument(function (ctor, name) { * @property(cc.Vec2) * offsets = []; * - * @property(cc.Texture2D) - * texture = ""; + * @property(cc.SpriteFrame) + * frame = null; * } * * // above is equivalent to (上面的代码相当于): @@ -397,9 +409,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/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 170306ea2f..084645df21 100644 --- a/cocos2d/core/platform/CCInputManager.js +++ b/cocos2d/core/platform/CCInputManager.js @@ -23,8 +23,10 @@ THE SOFTWARE. ****************************************************************************/ +var js = require('../platform/js'); var macro = require('./CCMacro'); var sys = require('./CCSys'); +var eventManager = require('../event-manager'); var TOUCH_TIMEOUT = macro.TOUCH_TIMEOUT; @@ -121,7 +123,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); } }, @@ -133,7 +135,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]; @@ -153,7 +155,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); } }, @@ -167,7 +169,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); } }, @@ -181,7 +183,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); } }, @@ -217,7 +219,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 +350,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 +413,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; @@ -443,7 +445,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); } @@ -488,7 +490,7 @@ var inputManager = { handler(event, mouseEvent, location, pos); - cc.eventManager.dispatchEvent(mouseEvent); + eventManager.dispatchEvent(mouseEvent); event.stopPropagation(); event.preventDefault(); }, false); @@ -521,7 +523,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(); } }, @@ -574,11 +576,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/CCMacro.js b/cocos2d/core/platform/CCMacro.js index c2c5d00545..4366cc964b 100644 --- a/cocos2d/core/platform/CCMacro.js +++ b/cocos2d/core/platform/CCMacro.js @@ -1725,10 +1725,9 @@ cc.macro = { SPRITEBATCHNODE_RENDER_SUBPIXEL: true, /** - *

- * 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: false, diff --git a/cocos2d/core/platform/CCObject.js b/cocos2d/core/platform/CCObject.js index f3e1781f3a..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. @@ -216,7 +226,8 @@ JS.getset(prototype, 'name', }, function (value) { this._name = value; - } + }, + true ); /** @@ -230,7 +241,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 () { @@ -245,11 +256,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 @@ -340,7 +351,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 20311f0afe..2ce35db886 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -23,7 +23,6 @@ THE SOFTWARE. ****************************************************************************/ - function initSys () { /** * System variables @@ -334,6 +333,12 @@ function initSys () { * @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 @@ -482,10 +487,6 @@ function initSys () { */ sys.BROWSER_TYPE_UNKNOWN = "unknown"; - function isWeChatGame () { - return window['wx']; - } - /** * Is native ? This is set to be true in jsb auto. * @property {Boolean} isNative @@ -496,7 +497,7 @@ function initSys () { * Is web browser ? * @property {Boolean} isBrowser */ - sys.isBrowser = typeof window === 'object' && typeof document === 'object'; + sys.isBrowser = typeof window === 'object' && typeof document === 'object' && !CC_WECHATGAME; if (CC_EDITOR && Editor.isMainProcess) { sys.isMobile = false; @@ -515,6 +516,46 @@ function initSys () { }; sys.__audioSupport = {}; } + else if (CC_WECHATGAME) { + 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 = window.localStorage; + + sys.capabilities = { + "canvas": true, + "opengl": true, + "webp": false + }; + sys.__audioSupport = { + ONLY_ONE: false, + WEB_AUDIO: false, + DELAY_CREATE_CTX: false, + format: ['.mp3'] + }; + } else { // browser or runtime var win = window, nav = win.navigator, doc = document, docEle = doc.documentElement; @@ -604,7 +645,7 @@ function initSys () { 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 42124781c9..b8f6dd2909 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'); const renderer = require('../renderer'); @@ -32,7 +33,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]; } }, @@ -60,7 +61,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; } @@ -226,7 +227,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(); } @@ -397,7 +398,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; } @@ -817,7 +818,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); @@ -1053,7 +1054,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'; @@ -1170,6 +1171,7 @@ cc.ContentStrategy = cc._Class.extend(/** @lends cc.ContentStrategy# */{ else { containerStyle.margin = '0px'; } + containerStyle.padding = "0px"; } }); diff --git a/cocos2d/core/platform/_CCClass.js b/cocos2d/core/platform/_CCClass.js index d66de087d1..644320e987 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" + @@ -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._getError(3658)); } }; diff --git a/cocos2d/core/platform/attribute.js b/cocos2d/core/platform/attribute.js index da5ef14f0f..e3542aa139 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'; @@ -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 0074c1f36a..653b2c079d 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 @@ -60,11 +54,8 @@ var Details = function () { */ this.uuidPropList = []; - /** - * the corresponding field name which referenced to the raw object - * @property {String} rawProp - */ - this.rawProp = ''; + // TODO - DELME since 2.0 + this._stillUseUrl = JS.createMap(true); }; /** * @method reset @@ -73,12 +64,11 @@ 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; + JS.clear(this._stillUseUrl); }; -if (CC_EDITOR) { +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]; @@ -87,27 +77,30 @@ if (CC_EDITOR) { } }; } -/** - * @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); @@ -176,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); } } } @@ -195,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; @@ -216,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; @@ -284,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 { @@ -299,7 +293,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__; @@ -313,16 +307,14 @@ 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) { - 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); } } } @@ -439,64 +431,7 @@ 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) { + var compileObjectType = CC_SUPPORT_JIT ? function (sources, defaultValue, accessorToSet, propNameLiteralToSet, assumeHavePropIfIsValue, stillUseUrl) { if (defaultValue instanceof cc.ValueType) { // fast case if (!assumeHavePropIfIsValue) { @@ -511,17 +446,17 @@ 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;'); } - } : function (s, o, t, prop, defaultValue, propName, assumeHavePropIfIsValue) { + } : function (s, o, t, prop, defaultValue, propName, assumeHavePropIfIsValue, stillUseUrl) { if (defaultValue instanceof cc.ValueType) { var ctor = defaultValue.constructor; - + if (assumeHavePropIfIsValue) { s._deserializeTypedObject(o[propName], prop, ctor); } @@ -537,10 +472,10 @@ var _Deserializer = (function () { else { if (prop) { if (CC_EDITOR || CC_TEST) { - s._deserializeObjField(o, prop, propName, t&&o); + s._deserializeObjField(o, prop, propName, t&&o, stillUseUrl); } else { - s._deserializeObjField(o, prop, propName); + s._deserializeObjField(o, prop, propName, null, stillUseUrl); } } else { @@ -549,8 +484,7 @@ var _Deserializer = (function () { } }; - var compileDeserialize = cc.supportJit ? function (self, klass) { - var RAW_TYPE = Attr.DELIMETER + 'rawType'; + var compileDeserialize = CC_SUPPORT_JIT ? function (self, klass) { var EDITOR_ONLY = Attr.DELIMETER + 'editorOnly'; var SERIALIZABLE = Attr.DELIMETER + 'serializable'; var DEFAULT = Attr.DELIMETER + 'default'; @@ -567,9 +501,86 @@ 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 + } + + var accessorToSet, propNameLiteralToSet; + if (CCClass.IDENTIFIER_RE.test(propName)) { + propNameLiteralToSet = '"' + propName + '"'; + accessorToSet = '.' + propName; + } + else { + propNameLiteralToSet = CCClass.escapeForJS(propName); + accessorToSet = '[' + propNameLiteralToSet + ']'; + } + + var accessorToGet = accessorToSet; + if (attrs[propName + FORMERLY_SERIALIZED_AS]) { + var propNameToRead = attrs[propName + FORMERLY_SERIALIZED_AS]; + if (CCClass.IDENTIFIER_RE.test(propNameToRead)) { + accessorToGet = '.' + propNameToRead; + } + else { + accessorToGet = '[' + CCClass.escapeForJS(propNameToRead) + ']'; + } + } + + sources.push('prop=d' + accessorToGet + ';'); + sources.push(`if(typeof ${CC_JSB ? '(prop)' : 'prop'}!=="undefined"){`); + + var stillUseUrl = attrs[propName + SAVE_URL_AS_ASSET]; + // function undefined object(null) string boolean number + var defaultValue = CCClass.getDefault(attrs[propName + DEFAULT]); + if (fastMode) { + var defaultType = typeof defaultValue; + var isPrimitiveType = (defaultType === 'string' && !stillUseUrl) || + defaultType === 'number' || + defaultType === 'boolean'; + if (isPrimitiveType) { + sources.push(`o${accessorToSet}=prop;`); + } + else { + 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, stillUseUrl); + sources.push('}'); + } + sources.push('}'); + } + if (props[props.length - 1] === '_$erialized') { + // deep copy original serialized data + sources.push('o._$erialized=JSON.parse(JSON.stringify(d));'); + // parse the serialized data as primitive javascript object, so its __id__ will be dereferenced + sources.push('s._deserializePrimitiveObject(o._$erialized,d);'); + } + return Function('s', 'o', 'd', 'k', 't', sources.join('')); + } : function (self, klass) { + var EDITOR_ONLY = Attr.DELIMETER + 'editorOnly'; + var SERIALIZABLE = Attr.DELIMETER + 'serializable'; + var DEFAULT = Attr.DELIMETER + 'default'; + var SAVE_URL_AS_ASSET = Attr.DELIMETER + 'saveUrlAsAsset'; + var FORMERLY_SERIALIZED_AS = Attr.DELIMETER + 'formerlySerializedAs'; + var attrs = Attr.getClassAttrs(klass); + + var props = klass.__props__; + var fastMode = Misc.BUILTIN_CLASSID_RE.test(JS._getClassId(klass)); + + return function (s, o, d, k, t) { + var prop; + for (var p = 0; p < props.length; p++) { + var propName = props[p]; if ((CC_PREVIEW || (CC_EDITOR && self._ignoreEditorOnly)) && attrs[propName + EDITOR_ONLY]) { var mayUsedInPersistRoot = (propName === '_id' && cc.isChildClassOf(klass, cc.Node)); if (!mayUsedInPersistRoot) { @@ -580,141 +591,37 @@ var _Deserializer = (function () { 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; + var propNameToRead = propName; 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) + ']'; - } + propNameToRead = attrs[propName + FORMERLY_SERIALIZED_AS]; } - sources.push('prop=d' + accessorToGet + ';'); - sources.push(`if(typeof ${CC_JSB ? '(prop)' : 'prop'}!=="undefined"){`); + prop = d[propNameToRead]; - // 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('}'); - } - else { - if (CCClass.IDENTIFIER_RE.test(propName)) { - propNameLiteralToSet = '"' + propName + '"'; - } - else { - propNameLiteralToSet = CCClass.escapeForJS(propName); - } - // 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 + ';'); - } - } - if (props[props.length - 1] === '_$erialized') { - // deep copy original serialized data - sources.push('o._$erialized=JSON.parse(JSON.stringify(d));'); - // parse the serialized data as primitive javascript object, so its __id__ will be dereferenced - sources.push('s._deserializePrimitiveObject(o._$erialized,d);'); - } - return Function('s', 'o', 'd', 'k', 't', sources.join('')); - } : function (self, klass) { - var RAW_TYPE = Attr.DELIMETER + 'rawType'; - var EDITOR_ONLY = Attr.DELIMETER + 'editorOnly'; - var SERIALIZABLE = Attr.DELIMETER + 'serializable'; - var DEFAULT = Attr.DELIMETER + 'default'; - var SAVE_URL_AS_ASSET = Attr.DELIMETER + 'saveUrlAsAsset'; - var FORMERLY_SERIALIZED_AS = Attr.DELIMETER + 'formerlySerializedAs'; - var attrs = Attr.getClassAttrs(klass); - - var props = klass.__props__; - var fastMode = Misc.BUILTIN_CLASSID_RE.test(JS._getClassId(klass)); - - return function (s, o, d, k, t) { - var prop; - for (var p = 0; p < props.length; p++) { - var propName = props[p]; - 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 - } - - var propNameToRead = propName; - if (attrs[propName + FORMERLY_SERIALIZED_AS]) { - propNameToRead = attrs[propName + FORMERLY_SERIALIZED_AS]; - } - - prop = d[propNameToRead]; - - if (typeof 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) { - o[propName] = prop; - } - else { - compileObjectType(s, o, t, prop, defaultValue, propName, true); - } + if (typeof 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' && !stillUseUrl) || + defaultType === 'number' || + defaultType === 'boolean'; + if (isPrimitiveType) { + o[propName] = prop; } else { - if (typeof prop !== 'object') { - o[propName] = prop; - } - else { - compileObjectType(s, o, t, prop, defaultValue, propName, false); - } + compileObjectType(s, o, t, prop, defaultValue, propName, true, stillUseUrl); } } - } - else { - // always load raw objects even if property not serialized - // 这里假定每个asset都有uuid,每个json只能包含一个asset,只能包含一个rawProp - if (s.result.rawProp) { - cc.error("not support multi raw object in a file"); + else { + if (typeof prop !== 'object') { + o[propName] = prop; + } + else { + compileObjectType(s, o, t, prop, defaultValue, propName, false, stillUseUrl); + } } - s.result.rawProp = propName; } } if (props[props.length - 1] === '_$erialized') { @@ -722,7 +629,7 @@ var _Deserializer = (function () { o._$erialized=JSON.parse(JSON.stringify(d)); // parse the serialized data as primitive javascript object, so its __id__ will be dereferenced s._deserializePrimitiveObject(o._$erialized,d); - } + } } }; 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/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/cocos2d/core/platform/js.js b/cocos2d/core/platform/js.js index cb668a46f3..458a2215a3 100644 --- a/cocos2d/core/platform/js.js +++ b/cocos2d/core/platform/js.js @@ -524,30 +524,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); } }; @@ -619,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/platform/preprocess-class.js b/cocos2d/core/platform/preprocess-class.js index b30ad221fe..95226385e8 100644 --- a/cocos2d/core/platform/preprocess-class.js +++ b/cocos2d/core/platform/preprocess-class.js @@ -32,7 +32,7 @@ var SerializableAttrs = { default: {}, serializable: {}, editorOnly: {}, - rawType: {}, + formerlySerializedAs: {} }; var TYPO_TO_CORRECT_DEV = CC_DEV && { @@ -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) { @@ -167,10 +167,37 @@ function getBaseClassWherePropertyDefined_DEV (propName, cls) { } } -exports.getFullFormOfProperty = function (options) { +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, @@ -179,20 +206,43 @@ exports.getFullFormOfProperty = function (options) { } else if (typeof options === 'function') { var type = options; - if (cc.RawAsset.isRawAssetType(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 { @@ -207,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/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/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; } }, 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 diff --git a/cocos2d/core/sprites/CCSpriteFrame.js b/cocos2d/core/sprites/CCSpriteFrame.js index 1438f13463..0e07a3201a 100644 --- a/cocos2d/core/sprites/CCSpriteFrame.js +++ b/cocos2d/core/sprites/CCSpriteFrame.js @@ -51,30 +51,38 @@ 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], 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(); + if (this._texture !== texture) { + 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 +153,6 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ this._texture = null; this._textureFilename = ''; - this._textureLoaded = false; if (CC_EDITOR) { // Atlas asset uuid @@ -166,7 +173,7 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ * @returns {boolean} */ textureLoaded: function () { - return this._textureLoaded; + return this._texture && this._texture.loaded; }, /** @@ -255,73 +262,56 @@ cc.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, 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._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) { - 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._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 (locLoaded) { - textureLoadedCallback(); - } - else { - texture.once("load", textureLoadedCallback); - } + this._texture = texture; + if (texture.loaded) { + this._textureLoadedCallback(); + } + else { + texture.once('load', this._textureLoadedCallback, this); } - //if (texture && texture.url && texture.isLoaded()) { - // if (self._rect) { - // self._checkRect(texture); - // } - // else { - // self.setRect(cc.rect(0, 0, texture.width, texture.height)); - // } - //} }, /** @@ -351,12 +341,12 @@ 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); }, /** - * #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] @@ -391,16 +381,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._texture !== texture) { this._refreshTexture(texture); } - else { - // todo log error - } return true; }, @@ -431,8 +417,17 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ * } */ ensureLoadTexture: function () { - if (!this._texture) { - this._loadTexture(); + if (this._texture) { + if (!this._texture.loaded) { + // 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); } }, @@ -450,8 +445,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) { @@ -466,17 +460,13 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ maxY += rect.height; } if (maxX > texture.width) { - cc.errorID(3300, texture.url + '/' + this.name); + cc.errorID(3300, texture.url + '/' + this.name, maxX, texture.width); } if (maxY > texture.height) { - cc.errorID(3400, texture.url + '/' + this.name); + cc.errorID(3400, texture.url + '/' + this.name, maxY, texture.height); } }, - // _instantiate () { - // var clone = new cc.SpriteFrame(); - // }, - // SERIALIZATION _serialize: CC_EDITOR && function (exporting) { @@ -484,17 +474,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,18 +530,22 @@ 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); } } }); -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 a439759e9f..050d4d07be 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -30,7 +30,6 @@ const misc = require('../utils/misc'); const game = require('../CCGame'); const renderEngine = require('../renderer/render-engine'); const renderer = require('../renderer'); -require('../platform/_CCClass'); require('../platform/CCClass'); const gfx = renderEngine.gfx; @@ -231,9 +230,16 @@ function _getSharedOptions () { return _sharedOpts; } +/** + * This class allows to easily create OpenGL or Canvas 2D textures from images or raw data. + * + * @class Texture2D + * @uses EventTarget + * @extends Asset + */ var Texture2D = cc.Class({ name: 'cc.Texture2D', - extends: require('../assets/CCRawAsset'), + extends: require('../assets/CCAsset'), mixins: [EventTarget], properties: { @@ -255,13 +261,15 @@ var Texture2D = cc.Class({ ctor () { /** * !#en - * The url of the texture, this coule be empty if the texture wasn't created via a file. + * The url of the texture, this could be empty if the texture wasn't created via a file. * !#zh * 贴图文件的 url,当贴图不是由文件创建时值可能为空 * @property url * @type {String} + * @readonly */ - this.url = null; + this.url = ""; + /** * !#en * Whether the texture is loaded or not @@ -297,8 +305,38 @@ var Texture2D = cc.Class({ return this._texture; }, + properties: { + _nativeAsset: { + get () { + // maybe returned to pool in webgl + return this._image; + }, + set (image) { + this.initWithElement(image); + this.handleLoadedTexture(); + }, + override: true + }, + _hasMipmap: false, + _format: PixelFormat.RGBA8888, + _compressed: false, + _premultiplyAlpha: false, + _minFilter: Filter.LINEAR, + _magFilter: Filter.LINEAR, + _wrapS: WrapMode.CLAMP_TO_EDGE, + _wrapT: WrapMode.CLAMP_TO_EDGE + }, + + statics: { + WrapMode: WrapMode, + PixelFormat: PixelFormat, + Filter: Filter, + // predefined most common extnames + extnames: ['.png', '.jpg', '.jpeg', '.bmp', '.webp'] + }, + /** - * Update texture options, not available in Canvas render mode. + * Update texture options, not available in Canvas render mode. * image, format, premultiplyAlpha can not be updated in native. * @method update * @param {Object} options @@ -414,6 +452,24 @@ var Texture2D = cc.Class({ return this._image; }, + /** + * !#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._image = null; + this._texture.destroy(); + // TODO cc.textureUtil ? + // cc.textureCache.removeTextureForKey(this.url); // item.rawUrl || item.url + this._super(); + }, + /** * Pixel format of the texture. * @method getPixelFormat @@ -559,7 +615,45 @@ var Texture2D = cc.Class({ opts.hasMipmap = mipmap; this.update(opts); } + }, + + // SERIALIZATION + + _serialize: (CC_EDITOR || CC_TEST) && function () { + var extId = ""; + if (this._native) { + // encode extname + var ext = cc.path.extname(this._native); + 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._setRawAsset(ext || extIdStr); + + // preset uuid to get correct nativeUrl + var loadingItem = handle.customEnv; + var uuid = loadingItem && loadingItem.uuid; + if (uuid) { + this._uuid = uuid; + var url = this.nativeUrl; + this.url = url; + } + } } }); -cc.Texture2D = module.exports = Texture2D; \ No newline at end of file +cc.Texture2D = module.exports = Texture2D; 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; }, diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js index bcf2094241..986286b1a1 100644 --- a/cocos2d/core/utils/base-node.js +++ b/cocos2d/core/utils/base-node.js @@ -23,9 +23,11 @@ THE SOFTWARE. ****************************************************************************/ +var PrefabHelper = require('./prefab-helper'); 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 +367,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); @@ -1165,6 +1167,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; @@ -1217,11 +1225,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; @@ -1243,8 +1251,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; //} @@ -1255,7 +1261,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..e676304786 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 @@ -81,7 +94,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/core/value-types/CCAffineTransform.js b/cocos2d/core/value-types/CCAffineTransform.js index 4e05259b9f..9c6b26a54a 100644 --- a/cocos2d/core/value-types/CCAffineTransform.js +++ b/cocos2d/core/value-types/CCAffineTransform.js @@ -324,14 +324,14 @@ 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); }; function affineTransformFromMatrixOut (mat, out) { 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/core/videoplayer/CCSGVideoPlayer.js b/cocos2d/core/videoplayer/CCSGVideoPlayer.js index 783d385437..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); }, @@ -172,23 +176,23 @@ _ccsg.VideoPlayer.elements = []; // video 在 game_hide 事件中被自动暂停的队列,用于回复的时候重新开始播放 _ccsg.VideoPlayer.pauseElements = []; -cc.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 this.data.length) { - throw new Error("Incomplete or corrupt PNG file"); + throw new Error(cc._getError(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._getError(6018, data[pos - 1])); } row++; } diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js index 8e036b3c0c..4f3575a6ab 100644 --- a/cocos2d/particle/CCParticleSystem.js +++ b/cocos2d/particle/CCParticleSystem.js @@ -232,7 +232,8 @@ var properties = { set: function (value) { cc.warnID(6017); }, - url: cc.Texture2D, + type: cc.Texture2D, + tooltip: CC_DEV && 'i18n:COMPONENT.particle_system.texture', readonly: true, visible: false, animatable: false @@ -602,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. @@ -610,7 +614,10 @@ var properties = { * @property {ParticleSystem.EmitterMode} emitterMode * @default ParticleSystem.EmitterMode.GRAVITY */ - emitterMode: EmitterMode.GRAVITY, + emitterMode: { + default: EmitterMode.GRAVITY, + type: EmitterMode + }, // GRAVITY MODE @@ -790,9 +797,6 @@ var properties = { rotatePerSVar: 0 }; -properties.positionType.type = PositionType; -properties.emitterMode.type = EmitterMode; - /** * Particle System base class.
* Attributes of a Particle System:
@@ -1060,7 +1064,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._getError(6029)); } if (!self.isValid) { return; diff --git a/cocos2d/particle/CCTIFFReader.js b/cocos2d/particle/CCTIFFReader.js index 54c16f9420..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("Invalid byte order value."); + 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("You forgot your towel!"); + throw RangeError(cc._getError(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._getError(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._getError(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._getError(6026)); } break; @@ -412,7 +412,7 @@ var tiffReader = /** @lends tiffReader# */{ sample++; } } else { - throw RangeError("Cannot handle sub-byte bits per sample"); + 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("Palette image missing color map"); + throw Error(cc._getError(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._getError(6028, photometricInterpretation)); break; } diff --git a/cocos2d/shaders/CCGLProgram.js b/cocos2d/shaders/CCGLProgram.js index 004b1f23d7..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("Please load the resource firset : " + vShaderFilename); + if (!vertexSource) throw new Error(cc._getError(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._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.GLProgram.getUniformLocationForName(): uniform name should be non-null"); + throw new Error(cc._getError(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._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("modelView matrix is undefined."); + 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/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/cocos2d/tilemap/CCTMXXMLParser.js b/cocos2d/tilemap/CCTMXXMLParser.js index a89bb992f7..f685295ba1 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); @@ -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)
@@ -210,7 +222,6 @@ cc.TMXTilesetInfo = cc._Class.extend(/** @lends cc.TMXTilesetInfo# */{ * @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 @@ -237,7 +248,6 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ parentGID:null, layerAttrs:0, storingCharacters:false, - tmxFileName:null, currentString:null, _objectGroups:null, @@ -248,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, @@ -258,10 +271,11 @@ 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 + * @param {Object} textures */ - ctor (tmxFile, resourcePath) { + ctor (tmxFile, resourcePath, textures) { cc.SAXParser.prototype.ctor.apply(this); this._mapSize = cc.size(0, 0); this._tileSize = cc.size(0, 0); @@ -272,11 +286,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, textures); }, /** * Gets Map orientation. @@ -536,24 +546,32 @@ 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 (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 * @param {String} resourcePath + * @param {Object} textures * @return {Boolean} */ - initWithXML (tmxString, resourcePath) { - this._internalInit(null, resourcePath); + initWithXML (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); }, @@ -565,8 +583,10 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ */ parseXMLFile (tmxFile, isXmlString, tilesetFirstGid) { isXmlString = isXmlString || false; - let xmlStr = isXmlString ? tmxFile : cc.loader.getRes(tmxFile); - if(!xmlStr) throw new Error("Please load the resource first : " + tmxFile); + var xmlStr = isXmlString ? tmxFile : cc.loader.getRes(tmxFile); + if (!xmlStr) { + cc.errorID(7220, tmxFile); + } let mapXML = this._parseXML(xmlStr); let i, j; @@ -622,7 +642,7 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ this.setTileSize(mapSize); // The parent element is the map - let propertyArr = map.querySelectorAll("map > properties > property"); + var propertyArr = getPropertyList(map); if (propertyArr) { let aPropertyDict = {}; for (i = 0; i < propertyArr.length; i++) { @@ -664,16 +684,11 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ tilesetSize.height = parseFloat(selTileset.getAttribute('tileheight')); tileset._tileSize = tilesetSize; - let image = selTileset.getElementsByTagName('image')[0]; - let imagename = image.getAttribute('source'); - let num = -1; - if(this.tmxFileName) - num = this.tmxFileName.lastIndexOf("/"); - if (num !== -1) { - let dir = this.tmxFileName.substr(0, num + 1); - tileset.sourceImage = dir + imagename; - } else { - tileset.sourceImage = this._resources + (this._resources ? "/" : "") + imagename; + var image = selTileset.getElementsByTagName('image')[0]; + var imagename = image.getAttribute('source'); + tileset.sourceImage = this._textures[imagename]; + if (!tileset.sourceImage) { + cc.errorID(7221, imagename); } this.setTilesets(tileset); @@ -692,7 +707,7 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ for (let tIdx = 0; tIdx < tiles.length; tIdx++) { let t = tiles[tIdx]; this.parentGID = parseInt(tileset.firstGid) + parseInt(t.getAttribute('id') || 0); - let tp = t.querySelectorAll("properties > property"); + var tp = getPropertyList(t); if (tp) { let dict = {}; for (j = 0; j < tp.length; j++) { @@ -805,7 +820,7 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ } // The parent element is the last layer - let layerProps = selLayer.querySelectorAll("properties > property"); + var layerProps = getPropertyList(selLayer); if (layerProps) { let layerProp = {}; for (let j = 0; j < layerProps.length; j++) { @@ -839,7 +854,7 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ if (draworder) objectGroup._draworder = draworder; - let groupProps = selGroup.querySelectorAll("objectgroup > properties > property"); + var groupProps = getPropertyList(selGroup); if (groupProps) { let parsedProps = {}; for (let j = 0; j < groupProps.length; j++) { @@ -849,8 +864,8 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ objectGroup.setProperties(parsedProps); } - let objects = selGroup.querySelectorAll('object'); - let getContentScaleFactor = cc.director.getContentScaleFactor(); + var objects = selGroup.getElementsByTagName('object'); + var getContentScaleFactor = cc.director.getContentScaleFactor(); if (objects) { for (let j = 0; j < objects.length; j++) { let selObj = objects[j]; @@ -873,7 +888,7 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ objectProp["rotation"] = parseFloat(selObj.getAttribute('rotation')) || 0; - let docObjProps = selObj.querySelectorAll("properties > property"); + var docObjProps = getPropertyList(selObj); if (docObjProps) { for (let k = 0; k < docObjProps.length; k++) objectProp[docObjProps[k].getAttribute('name')] = docObjProps[k].getAttribute('value'); @@ -891,13 +906,13 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ } // ellipse - let ellipse = selObj.querySelectorAll('ellipse'); + var ellipse = selObj.getElementsByTagName('ellipse'); if (ellipse && ellipse.length > 0) { objectProp['type'] = cc.TiledMap.TMXObjectType.ELLIPSE; } //polygon - let polygonProps = selObj.querySelectorAll("polygon"); + var polygonProps = selObj.getElementsByTagName("polygon"); if(polygonProps && polygonProps.length > 0) { objectProp['type'] = cc.TiledMap.TMXObjectType.POLYGON; let selPgPointStr = polygonProps[0].getAttribute('points'); @@ -906,7 +921,7 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ } //polyline - let polylineProps = selObj.querySelectorAll("polyline"); + var polylineProps = selObj.getElementsByTagName("polyline"); if(polylineProps && polylineProps.length > 0) { objectProp['type'] = cc.TiledMap.TMXObjectType.POLYLINE; let selPlPointStr = polylineProps[0].getAttribute('points'); @@ -977,42 +992,6 @@ cc.TMXMapInfo = cc.SAXParser.extend(/** @lends cc.TMXMapInfo# */{ */ setCurrentString (currentString) { this.currentString = currentString; - }, - - /** - * Gets the tmxFileName - * @return {String} - */ - getTMXFileName () { - return this.tmxFileName; - }, - - /** - * Set the tmxFileName - * @param {String} fileName - */ - setTMXFileName (fileName) { - this.tmxFileName = fileName; - }, - - _internalInit (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; } }); @@ -1033,18 +1012,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 diff --git a/cocos2d/tilemap/CCTiledMapAsset.js b/cocos2d/tilemap/CCTiledMapAsset.js index ee6aa75c4d..7a8beb35a4 100644 --- a/cocos2d/tilemap/CCTiledMapAsset.js +++ b/cocos2d/tilemap/CCTiledMapAsset.js @@ -34,23 +34,23 @@ let TiledMapAsset = cc.Class({ extends: cc.Asset, properties: { - tmxXmlStr: { - default: '' - }, - - tmxFolderPath : { - default: '' - }, + tmxXmlStr: '', + tmxFolderPath: '', + /** + * @property {Texture2D[]} textures + */ textures: { default: [], - url: [cc.Texture2D] + type: [cc.Texture2D] }, - tsxFiles: { - default: [], - url: [cc.RawAsset] - } + /** + * @property {String[]} textureNames + */ + textureNames: [cc.String], + + tsxFiles: [cc.RawAsset] }, statics: { diff --git a/cocos2d/tilemap/editor/tiled-map.js b/cocos2d/tilemap/editor/tiled-map.js index df5a70d4f8..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(`Parse ${tmxFile} failed.`)); + return cb(new Error(cc._getError(7222, tmxFile))); } var textures = []; @@ -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) { @@ -95,7 +95,11 @@ 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.textureNames = this._textures.map(p => Path.basename(p)); asset.tsxFiles = this._tsxFiles.map(p => db.fspathToUrl(p)); db.saveAssetToLibrary(this.uuid, asset); cb(); 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 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 5e92fbba06..26024e3466 100644 --- a/extensions/dragonbones/CCFactory.js +++ b/extensions/dragonbones/CCFactory.js @@ -24,10 +24,20 @@ let 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; + } + }, + ctor () { this.__instanceId = cc.ClassManager.getNewInstanceId(); this._dragoneBones = new dragonBones.DragonBones(); @@ -48,6 +58,11 @@ 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,12 +162,4 @@ dragonBones.CCFactory = cc.Class({ return slot; } -}); - -dragonBones.CCFactory._factory = null; -dragonBones.CCFactory.getFactory = function() { - if (!dragonBones.CCFactory._factory) { - dragonBones.CCFactory._factory = new dragonBones.CCFactory(); - } - return dragonBones.CCFactory._factory; -}; +}); \ 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) { diff --git a/extensions/dragonbones/CCTextureData.js b/extensions/dragonbones/CCTextureData.js index 3c0bb09aa2..f361e207e5 100644 --- a/extensions/dragonbones/CCTextureData.js +++ b/extensions/dragonbones/CCTextureData.js @@ -23,17 +23,22 @@ ****************************************************************************/ 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; }, @@ -44,21 +49,24 @@ dragonBones.CCTextureAtlasData = cc.Class({ }); dragonBones.CCTextureData = cc.Class({ - name: 'dragonBones.CCTextureData', extends: dragonBones.TextureData, - texture: null, - statics : { - toString : function() { + properties: { + // SpriteFrame + 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(); - 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 4e5a186cbf..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: '', - url: 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; 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/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/editor/spine-meta.js b/extensions/spine/editor/spine-meta.js index b70f7a260b..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); @@ -64,8 +66,8 @@ 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); + this.textureNames.push(line); var tex = new Spine.Texture({}); tex.setFilters = function() {}; tex.setWraps = function() {}; @@ -81,7 +83,6 @@ class TextureParser { return null; } - unload () {} } const RAW_SKELETON_FILE = 'raw-skeleton.json'; @@ -104,7 +105,7 @@ class SpineMeta extends CustomAssetMeta { //this.textures[0] = value; } - static version () { return '1.0.2'; } + static version () { return '1.2.0'; } static defaultType () { return 'spine'; } @@ -172,33 +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) { - 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 = 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._setRawFiles([RAW_SKELETON_FILE]); - + asset._setRawAsset(RAW_SKELETON_FILE); + + var atlasUuid = db.fspathToUuid(res.atlasPath); this.atlas = atlasUuid; // save for dest() // 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)); } }); diff --git a/gulp/tasks/engine.js b/gulp/tasks/engine.js index 25aa393364..369203e81c 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'); @@ -43,26 +40,31 @@ const Optimizejs = require('gulp-optimize-js'); var jsbSkipModules = [ '../../cocos2d/core/CCGame', - '../../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', + '../../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/camera/CCSGCameraNode.js', - '../../cocos2d/core/videoplayer/CCSGVideoPlayer.js', - '../../cocos2d/core/webview/CCSGWebView.js', - '../../cocos2d/core/editbox/CCSGEditBox.js', + '../../cocos2d/core/platform/CCInputManager.js', + '../../cocos2d/core/platform/CCVisibleRect.js', '../../cocos2d/core/graphics/helper.js', + '../../cocos2d/actions/index.js', '../../cocos2d/audio/CCAudio', '../../extensions/spine/lib/spine', '../../extensions/dragonbones/lib/dragonBones', '../../external/box2d/box2d.js', + '../../external/chipmunk/chipmunk.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); @@ -71,13 +73,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', Object.assign({ debug: true }, opt_macroFlags))); bundler = bundler.pipe(Optimizejs({ sourceMap: false })); @@ -90,7 +90,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); @@ -99,8 +104,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'); @@ -120,7 +123,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', opt_macroFlags)); bundler = bundler.pipe(Optimizejs({ sourceMap: false })); @@ -165,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 })) @@ -182,6 +185,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); @@ -192,13 +196,14 @@ 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)) .pipe(Buffer()) .pipe(FixJavaScriptCore()) - .pipe(Minify(Utils.getUglifyOptions('preview', true, false))) + .pipe(Utils.uglify('preview', { jsb: true })) .pipe(Optimizejs({ sourceMap: false })) @@ -206,7 +211,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); @@ -224,7 +234,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', Object.assign({ jsb: true, debug: true }, opt_macroFlags))) .pipe(Optimizejs({ sourceMap: false })) @@ -232,7 +242,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); @@ -250,7 +265,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', Object.assign({ jsb: true }, opt_macroFlags))) .pipe(Optimizejs({ sourceMap: false })) diff --git a/gulp/tasks/test.js b/gulp/tasks/test.js index 45fee2cae9..29de7715c3 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')); if (sourcemaps) { engine = engine.pipe(Sourcemaps.write('./', { 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 +}; diff --git a/gulp/util/utils.js b/gulp/util/utils.js index a41839f33d..2fd8ac09f1 100644 --- a/gulp/util/utils.js +++ b/gulp/util/utils.js @@ -1,29 +1,51 @@ 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']; + res['CC_SUPPORT_JIT'] = !res['CC_WECHATGAME']; return res; }; -exports.getUglifyOptions = function (platform, isJSB, isDebugBuild) { - var global_defs = exports.getMacros(platform, isJSB, isDebugBuild); +// see https://github.com/mishoo/UglifyJS2/tree/harmony#compress-options +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: { @@ -43,6 +65,9 @@ exports.getUglifyOptions = function (platform, isJSB, isDebugBuild) { return { compress: { global_defs: global_defs, + }, + output: { + ascii_only: true, } }; } @@ -54,29 +79,32 @@ 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 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 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_funcs: false, reduce_vars: false, // Improve optimization on variables assigned with and used as constant values. //warnings: true, negate_iife: false, @@ -87,8 +115,15 @@ 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 } }; } }; + +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)); +}; diff --git a/index.js b/index.js index 3e08bad500..19c859e023 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 = typeof Function('') === 'function'; - // The namespace for original nodes rendering in scene graph. _ccsg = {}; @@ -155,12 +157,7 @@ if (CC_DEV) { cc._Test = {}; } -// output all info before initialized require('./CCDebugger'); -cc._initDebugSetting(cc.DebugMode.INFO); -if (CC_DEBUG) { - require('./DebugInfos'); -} // polyfills /* require('./polyfill/bind'); */ @@ -179,10 +176,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 df61f5f14d..93fb4d1a44 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) { @@ -76,14 +75,8 @@ 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) { - //Debug Info ID map - require('../DebugInfos'); -} - // Mark memory model var macro = require('../cocos2d/core/platform/CCMacro'); 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 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); } }, }); 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; 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 diff --git a/jsb/jsb-label.js b/jsb/jsb-label.js index 65d219183e..50bb531805 100644 --- a/jsb/jsb-label.js +++ b/jsb/jsb-label.js @@ -160,7 +160,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') { @@ -303,6 +303,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/jsb/jsb-loader.js b/jsb/jsb-loader.js index ad576b35ea..70228ddc23 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,16 +74,14 @@ 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) { + var isRemote = jsb.urlRegExp.test(url); + var loadByDeserializedTexture = item._owner instanceof cc.Texture2D; + if (loadByDeserializedTexture) { + // load Image + var loader = isRemote ? jsb.initRemoteImg : jsb.initTextureAsync; + loader(item._owner, url, function(succeed) { if (succeed) { - tex.url = url; - callback && callback(null, tex); + callback && callback(null); } else { callback && callback(new Error('Load image failed: ' + url)); @@ -91,30 +89,46 @@ function loadImage (item, callback) { }); } else { - var addImageCallback = function (tex) { - if (tex instanceof cc.Texture2D) { - tex.url = url; - callback && callback(null, tex); - } - else { - callback && callback(new Error('Load image failed: ' + url)); - } - }; - cc.textureCache._addImageAsync(url, addImageCallback); + var cachedTex = cc.textureCache.getTextureForKey(url); + if (cachedTex) { + return cachedTex; + } + else if (isRemote) { + jsb.loadRemoteImg(url, function(succeed, tex) { + if (succeed) { + tex.url = url; + 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) { + tex.url = url; + 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-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 c133866aa2..9e5dd332f2 100644 --- a/jsb/jsb-tex-sprite-frame.js +++ b/jsb/jsb-tex-sprite-frame.js @@ -27,16 +27,19 @@ 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 +// 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; @@ -47,10 +50,21 @@ 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) { + // 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; + } + + var md5Pipe = cc.loader.md5Pipe; + if (md5Pipe) { + url = md5Pipe.transformURL(url); + } + if (typeof cb === "function") { return this.addImageAsync(url, cb, target); } @@ -64,7 +78,7 @@ cc.TextureCache.prototype.addImage = function (url, cb, target) { } }; -// cc.textureCache.cacheImage +// cc.textureCache cc.textureCache._textures = {}; cc.textureCache.cacheImage = function (key, texture) { @@ -74,52 +88,45 @@ 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) { - if (this._textures[key]) - delete this._textures[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; + } + + delete this._textures[key]; this._removeTextureForKey(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.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 +[ + 'WrapMode', + 'PixelFormat', + 'Filter', + 'extnames', + 'preventDeferredLoadDependents', + 'preventPreloadNativeObject', +].forEach(function (key) { + cc.Texture2D[key] = WebTexture[key]; }); -cc.Texture2D.WrapMode = cc.Enum({ - REPEAT: GL_REPEAT, - CLAMP_TO_EDGE: GL_CLAMP_TO_EDGE, - MIRRORED_REPEAT: GL_MIRRORED_REPEAT -}); +prototype = cc.Texture2D.prototype; +prototype._releaseTexture = prototype.releaseTexture; -cc.Texture2D.Filter = cc.Enum({ - LINEAR: GL_LINEAR, - NEAREST: GL_NEAREST -}); +cc.js.addon(prototype, WebTexture.prototype); -var prototype = cc.Texture2D.prototype; +prototype._ctor = function () { + cc.Asset.call(this); + this.url = ""; +}; prototype.loaded = true; prototype.update = function (options) { @@ -153,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); @@ -164,24 +168,22 @@ cc.js.get(prototype, '_glID', prototype.getName); // 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; -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 } }; @@ -202,66 +204,59 @@ 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.getTexture() !== texture) { this._refreshTexture(texture); } - else { - //todo log error - } return true; }; prototype.initWithTexture = prototype.setTexture; -prototype._loadTexture = function () { - if (this._textureFilename) { +prototype.ensureLoadTexture = function () { + if (this._texture) { + if (!this._texture.loaded) { + // 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(); - } -}; - 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) { @@ -287,12 +282,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) { @@ -332,18 +325,5 @@ prototype.clone = function () { return cloned; }; -cc.js.set(prototype, '_textureFilenameSetter', function (url) { - this._textureFilename = url; - if (url) { - this._loadTexture(); - } -}); - -cc.js.getset(prototype, 'name', - function () { - return this._name; - }, - function (value) { - this._name = value; - } -); +cc.js.getset(prototype, 'texture', prototype.getTexture, prototype.setTexture); +cc.js.addon(prototype, WebSpriteFrame.prototype); 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" ] }, { diff --git a/package.json b/package.json index 7b9ece30df..92d1416749 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": [ @@ -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", @@ -44,8 +44,7 @@ "jshint-stylish": "2.1.0", "multipipe": "0.3.0", "persistify": "^1.1.1", - "require-dir": "0.3.0", - "uglify-es": "^3.0.26", + "uglify-es": "~3.3.3", "vinyl": "1.1.0", "vinyl-buffer": "1.0.0", "vinyl-source-stream": "1.0.0", 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/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 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/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/_init.js b/test/qunit/unit-es5/_init.js index 5f44d25661..d385629c0d 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, @@ -169,6 +169,7 @@ function _resetGame (w, h) { id: 'test-canvas', debugMode: cc.DebugMode.INFO }); + cc.director.setDisplayStats(false); } else { var view = cc.view; @@ -200,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(); 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-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-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-migrating-raw-asset.js b/test/qunit/unit-es5/test-migrating-raw-asset.js new file mode 100644 index 0000000000..382f53651f --- /dev/null +++ b/test/qunit/unit-es5/test-migrating-raw-asset.js @@ -0,0 +1,111 @@ +if (TestEditorExtends) { + (function () { + + module('Migrating Raw Assets'); + + 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: { + ref_full: { + 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 sysUrlToUuid = Editor.Utils.UuidCache.urlToUuid; + Editor.Utils.UuidCache.urlToUuid = function (url) { + return { + foo: '01', + }[url]; + }; + var serializedAsset = Editor.serialize(asset); + Editor.Utils.UuidCache.urlToUuid = sysUrlToUuid; + + // deserialize + 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_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); + }); + + test('serialization if declared in the NEW way', function () { + // setup + var MyAsset = cc.Class({ + name: 'MyAsset', + properties: { + ref_full: { + 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; + 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_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-es5/test-pack-unpack.js b/test/qunit/unit-es5/test-pack-unpack.js new file mode 100644 index 0000000000..712e0f15f1 --- /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._setRawAsset('.png'); + var tex1Json = Editor.serialize(tex1, { stringify: false }); + + var tex2 = new cc.Texture2D(); + tex2._uuid = '08T18'; + tex2._setRawAsset('.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-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 () { 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(); }); }); diff --git a/test/qunit/unit-es5/test-serialize.js b/test/qunit/unit-es5/test-serialize.js index 1c418ff9bd..de860260bc 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'); @@ -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 new file mode 100644 index 0000000000..689d6a0fea --- /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('nativeUrl', function () { + var tex = new cc.Texture2D(); + tex._uuid = '555AC'; + tex._setRawAsset('.png'); + ok(tex.nativeUrl.endsWith('.png'), 'nativeUrl 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.nativeUrl, '', 'nativeUrl 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._setRawAsset('.png'); + tex.url = tex.nativeUrl; + 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.nativeUrl, tex.nativeUrl, 'nativeUrl should be deserialized'); + strictEqual(deserialized.url, tex.url, 'url should be deserialized'); + }); + } + testSerializationOfUrl('.png'); + testSerializationOfUrl('.jareguo'); + } + +})(); \ No newline at end of file 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');