Merge pull request #2259 from pandamicro/next

Merge master to next and fix issues
This commit is contained in:
pandamicro
2018-01-16 17:37:44 +08:00
committed by GitHub
146 changed files with 3027 additions and 2001 deletions
+32
View File
@@ -0,0 +1,32 @@
<!--
EN: Here only receive bug report or suggestions for improvement. Feature request please send to the forum: http://discuss.cocos2d-x.org/c/creator
中: 这里只接收 bug 反馈或改进建议。新功能需求请发到论坛:http://forum.cocos.com/c/Creator
-->
### Creator version?(版本号)
### Affected platform?(受影响的平台)
<!-- Mac Editor / Windows Editor / Web / iOS / Android / Simulator ... -->
### How to reproduce?(如何重现)
### JavaScript output or error produced?(报错信息和调用栈)
<!--
EN: The error must be the first error when the problem occurred.
中:这里填写的报错信息必须是出现问题时的第一个报错。
-->
### Demo project?(demo 项目)
<!--
EN: A complete parsable Creator project or resources exhibiting the issue with Creator alone - without third party tools or libraries or server. Ideally the demo should be as small as possible.
It is very likely that issues without a reproducible test case will be closed.
中:用于呈现错误的可理解的 Creator 工程或资源,不依赖第三方工具或插件或者服务端。这个 demo 应该越小越好。
不含可重现范例的 issue 将有可能被关闭。
-->
<!--
### Thanks for the feedback.(感谢反馈)
-->
+6 -3
View File
@@ -3,11 +3,14 @@ Re: cocos-creator/fireball#
Changelog:
*
> Makes sure these boxes are checked before submitting your PR - thank you!
>
<!-- Note: Makes sure these boxes are checked before submitting your PR - thank you!
- [ ] If your pull request has gone "stale", you should **rebase** your work on top of the latest version of the upstream branch.
- [ ] If your commit history is full of small, unimportant commits (such as "fix pep8" or "update tests"), **squash** your commits down to a few, or one, discreet changesets before submitting a pull request.
- To official teams:
- [ ] Check that your javascript is following our [style guide](https://github.com/cocos-creator/fireball/blob/dev/.github/CONTRIBUTING.md) and end files with a newline
- [ ] Document new code with comments in source code based on [API Docs](https://github.com/cocos-creator/fireball#api-docs)
- [ ] Make sure any runtime log information in `cc.log` , `cc.error`, `cc.warn` or `cc.assert` has been moved into `DebugInfos.js` with an ID
- [ ] Make sure any runtime log information in `cc.log` , `cc.error` or `new Error('')` has been moved into `DebugInfos.js` with an ID, and use `cc.logID(id)` or `new Error(cc._getErrorID(id))` instead.
-->
-2
View File
@@ -23,8 +23,6 @@
THE SOFTWARE.
****************************************************************************/
cc._LogInfos = cc._LogInfos || {};
/**
* The current version of Cocos2d being used.<br/>
* Please DO NOT remove this String, it is an important flag for bug tracking.<br/>
+54 -46
View File
@@ -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);
+83 -19
View File
@@ -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;
// }
+1 -1
View File
@@ -1,6 +1,6 @@
machine:
node:
version: 5.8.0
version: 6.12.3
dependencies:
pre:
+2 -2
View File
@@ -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);
+1 -1
View File
@@ -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);
+1 -1
View File
@@ -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;
+6 -6
View File
@@ -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;
+2 -2
View File
@@ -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];
+1 -1
View File
@@ -80,7 +80,7 @@ prototype.play = function () {
this.onResume();
}
else {
this.onError('already-playing');
this.onError(cc._getError(3912));
}
}
else {
+7 -6
View File
@@ -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();
+249 -1
View File
@@ -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();
}
}
}
};
+3 -174
View File
@@ -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();
}
+1 -1
View File
@@ -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"];
+15 -8
View File
@@ -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.<br/>
* It takes into account any possible rotation (device orientation) of the window.<br/>
* 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);
}
},
});
+55 -34
View File
@@ -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 () {
+55 -33
View File
@@ -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);
}
},
+10 -1
View File
@@ -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;
}
},
+70 -60
View File
@@ -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.<br/>
*
* You may want to override:<br/>
* - createNode<br/>
* - getset functions of _nativeAsset<br/>
* - cc.Object._serialize<br/>
* - cc.Object._deserialize<br/>
* !#zh
* 资源基类,该类可以被实例化。<br/>
* Creator 中的资源基类。<br/>
*
* 您可能需要重写:<br/>
* - createNode <br/>
* - _nativeAsset 的 getset 方法<br/>
* - cc.Object._serialize<br/>
* - cc.Object._deserialize<br/>
*
@@ -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
* 使用该资源在场景中创建一个新节点。<br/>
* 如果这类资源没有相应的节点类型,该方法应该是空的。
*
* @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;
+1 -1
View File
@@ -30,7 +30,7 @@
* !#en Class for BitmapFont handling.
* !#zh 位图字体资源类。
* @class BitmapFont
* @extends RawAsset
* @extends Font
*
*/
var BitmapFont = cc.Class({
+2 -4
View File
@@ -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;
+91 -13
View File
@@ -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
* 优化单次创建性能。<br>
* 该选项会跳过针对这个 prefab 的代码生成优化操作。当该 prefab 加载后,一般只会创建一个实例时,请选择此项。
* !#en
* Optimize for single instance creation.<br>
* 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
* 优化多次创建性能。<br>
* 该选项会启用针对这个 prefab 的代码生成优化操作。当该 prefab 加载后,一般会创建多个实例时,请选择此项。如果该 prefab 在场景中的节点启用了自动关联,并且在场景中有多份实例,也建议选择此项。
* !#en
* Optimize for creating instances multiple times.<br>
* 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.
+8 -5
View File
@@ -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;
+1 -1
View File
@@ -27,7 +27,7 @@
* !#en Class for sprite atlas handling.
* !#zh 精灵图集资源类。
* @class SpriteAtlas
* @extends RawAsset
* @extends Asset
*
*/
var SpriteAtlas = cc.Class({
+6 -4
View File
@@ -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;
@@ -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);
+3 -4
View File
@@ -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);
};
+8
View File
@@ -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();
}
},
/**
+5 -7
View File
@@ -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) {
+11 -3
View File
@@ -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);
},
/**
+1 -1
View File
@@ -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;
},
+13 -8
View File
@@ -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 () {
+1 -1
View File
@@ -64,7 +64,7 @@ var Toggle = cc.Class({
toggleGroup: {
default: null,
tooltip: CC_DEV && 'i18n:COMPONENT.toggle.toggleGroup',
type: cc.ToggleGroup
type: require('./CCToggleGroup')
},
/**
+3 -1
View File
@@ -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;
}
});
},
+1
View File
@@ -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'
},
+97 -26
View File
@@ -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;
+1
View File
@@ -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
*/
+17 -9
View File
@@ -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
* <p>
* cc.eventManager is a singleton object which manages event listener subscriptions and event dispatching. <br/>
@@ -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;
+18 -5
View File
@@ -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;
}
+2 -1
View File
@@ -25,4 +25,5 @@
require('./event');
require('./event-listeners');
require('./event-target');
require('./event-target');
require('./system-event');
@@ -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);
}
}
+20 -6
View File
@@ -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;
},
+4 -11
View File
@@ -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);
+1 -1
View File
@@ -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);
@@ -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;
@@ -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);
}
}
+6 -7
View File
@@ -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.
-1
View File
@@ -25,7 +25,6 @@
require('./downloader');
require('./loader');
require('./json-unpacker');
require('./loading-items');
require('./pipeline');
+5 -2
View File
@@ -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;
+44 -28
View File
@@ -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);
}
@@ -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;
@@ -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,
};
+57 -46
View File
@@ -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;
+3 -4
View File
@@ -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({
+1 -1
View File
@@ -213,7 +213,7 @@ var RigidBody = cc.Class({
this._allowSleep = value;
if (this._b2Body) {
this._b2Body.SetAllowSleeping(value);
this._b2Body.SetSleepingAllowed(value);
}
}
},
@@ -6,7 +6,6 @@ var PhysicsDebugDraw = cc.Class({
ctor: function () {
this._drawer = new _ccsg.GraphicsNode();
this._drawer.retain();
},
getDrawer: function () {
+26 -23
View File
@@ -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);
+19 -7
View File
@@ -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) {
* &#64;property(cc.Vec2)
* offsets = [];
*
* &#64;property(cc.Texture2D)
* texture = "";
* &#64;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
* },
* }
* });
+3 -2
View File
@@ -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);
+19 -13
View File
@@ -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;
+3 -4
View File
@@ -1725,10 +1725,9 @@ cc.macro = {
SPRITEBATCHNODE_RENDER_SUBPIXEL: true,
/**
* <p>
* Automatically premultiply alpha for PNG resources
* </p>
* @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,
+16 -5
View File
@@ -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.<br/>
* Actual object destruction will delayed until before rendering.
* <br/>
* 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
* 销毁该对象,并释放所有它对其它对象的引用。<br/>
* 销毁后,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') {
+48 -7
View File
@@ -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;
+8 -6
View File
@@ -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";
}
});
+2 -2
View File
@@ -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));
}
};
+1 -41
View File
@@ -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
};
+146 -239
View File
@@ -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);
}
}
}
};
+5 -6
View File
@@ -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');
}
}
+2 -2
View File
@@ -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);
}
+4 -4
View File
@@ -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;
}
+13 -11
View File
@@ -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
+67 -17
View File
@@ -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;
}
+9 -7
View File
@@ -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;
},
+9 -7
View File
@@ -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;
}
},
@@ -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
+107 -112
View File
@@ -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.<br/>
* #zh 通过 Texture,rect,rotated,offset 和 originalSize 设置 SpriteFrame
* !#en Set SpriteFrame with Texture, rect, rotated, offset and originalSize.<br/>
* !#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;
+100 -6
View File
@@ -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)<br>
* 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)<br/>
* 销毁后,该对象不再可用。您可以在访问对象之前使用 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;
cc.Texture2D = module.exports = Texture2D;
+23 -14
View File
@@ -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;
},
+14 -8
View File
@@ -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;
},
+15 -2
View File
@@ -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 {
@@ -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) {
+4 -5
View File
@@ -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;
+56 -47
View File
@@ -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<list.length; i++){
node = list[i];
if(list[i]._playing){
node.pause();
_ccsg.VideoPlayer.pauseElements.push(node);
for (var element, i = 0; i < list.length; i++) {
element = list[i];
if (element.isPlaying()) {
element.pause();
_ccsg.VideoPlayer.pauseElements.push(element);
}
}
});
cc.game.on(cc.game.EVENT_SHOW, function () {
var list = _ccsg.VideoPlayer.pauseElements;
var node = list.pop();
while(node){
node.play();
node = list.pop();
var element = list.pop();
while (element) {
element.play();
element = list.pop();
}
});
@@ -214,26 +218,26 @@ _ccsg.VideoPlayer.EventType = {
canPlayType: []
};
(function(){
(function () {
/**
* Some old browser only supports Theora encode video
* But native does not support this encode,
* so it is best to provide mp4 and webm or ogv file
*/
var dom = document.createElement("video");
if (sys.browserType !== sys.BROWSER_TYPE_WECHAT_GAME) {
if(dom.canPlayType("video/ogg")){
if (sys.platform !== sys.WECHAT_GAME) {
if (dom.canPlayType("video/ogg")) {
video._polyfill.canPlayType.push(".ogg");
video._polyfill.canPlayType.push(".ogv");
}
if(dom.canPlayType("video/mp4"))
if (dom.canPlayType("video/mp4"))
video._polyfill.canPlayType.push(".mp4");
if(dom.canPlayType("video/webm"))
if (dom.canPlayType("video/webm"))
video._polyfill.canPlayType.push(".webm");
}
})();
if(cc.sys.browserType === cc.sys.BROWSER_TYPE_FIREFOX){
if (cc.sys.browserType === cc.sys.BROWSER_TYPE_FIREFOX) {
video._polyfill.autoplayAfterOperation = true;
}
@@ -288,7 +292,7 @@ _ccsg.VideoPlayer.EventType = {
var container = cc.game.container;
var a = t.a * scaleX, b = t.b, c = t.c, d = t.d * scaleY;
var offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft);
var offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft);
var offsetY = container && container.style.paddingBottom && parseInt(container.style.paddingBottom);
var tx = t.tx * scaleX + offsetX, ty = t.ty * scaleY + offsetY;
@@ -306,20 +310,16 @@ _ccsg.VideoPlayer.EventType = {
};
proto.updateURL = function (path) {
if (cc.loader.md5Pipe) {
path = cc.loader.md5Pipe.transformURL(path);
}
var source, video, extname;
var node = this._node;
if (this._url == path) {
if (this._url === path) {
return;
}
this._url = path;
if(cc.loader.resPath && !/^http/.test(path))
if (cc.loader.resPath && !/^http/.test(path))
path = cc.path.join(cc.loader.resPath, path);
this.removeDom();
@@ -329,8 +329,8 @@ _ccsg.VideoPlayer.EventType = {
video = this._video;
var cb = function(){
if(this._loaded == true)
video.oncanplay = function () {
if (this._loaded)
return;
this._loaded = true;
node.setContentSize(node._contentSize.width, node._contentSize.height);
@@ -339,7 +339,6 @@ _ccsg.VideoPlayer.EventType = {
this.updateVisibility();
this.updateMatrix();
}.bind(this);
video.oncanplay = cb;
//video.controls = "controls";
// if preload set to metadata, the canplay event can't be fired on safari
@@ -354,8 +353,8 @@ _ccsg.VideoPlayer.EventType = {
video.appendChild(source);
extname = cc.path.extname(path);
for(var i=0; i<polyfill.canPlayType.length; i++){
if(extname !== polyfill.canPlayType[i]){
for (var i = 0; i < polyfill.canPlayType.length; i++) {
if (extname !== polyfill.canPlayType[i]) {
source = document.createElement("source");
source.src = path.replace(extname, polyfill.canPlayType[i]);
video.appendChild(source);
@@ -369,16 +368,16 @@ _ccsg.VideoPlayer.EventType = {
video.onloadedmetadata = function () {
node._dispatchEvent(_ccsg.VideoPlayer.EventType.META_LOADED);
};
video.addEventListener("ended", function(){
video.addEventListener("ended", function () {
if (self._video !== video) return;
this._playing = false;
node._dispatchEvent(_ccsg.VideoPlayer.EventType.COMPLETED);
}.bind(this));
video.addEventListener("play", function(){
video.addEventListener("play", function () {
if (self._video !== video) return;
node._dispatchEvent(_ccsg.VideoPlayer.EventType.PLAYING);
});
video.addEventListener("pause", function(){
video.addEventListener("pause", function () {
if (self._ignorePause || self._video !== video) return;
node._dispatchEvent(_ccsg.VideoPlayer.EventType.PAUSED);
});
@@ -393,7 +392,8 @@ _ccsg.VideoPlayer.EventType = {
var video = this._video;
if (node.visible) {
video.style.visibility = 'visible';
} else {
}
else {
video.style.visibility = 'hidden';
video.pause();
this._playing = false;
@@ -415,9 +415,9 @@ _ccsg.VideoPlayer.EventType = {
proto.removeDom = function () {
var video = this._video;
if(video){
if (video) {
var hasChild = Utils.contains(cc.game.container, video);
if(hasChild)
if (hasChild)
cc.game.container.removeChild(video);
}
this._video = null;
@@ -442,13 +442,14 @@ _ccsg.VideoPlayer.EventType = {
return;
}
if(_ccsg.VideoPlayer._polyfill.autoplayAfterOperation){
if (_ccsg.VideoPlayer._polyfill.autoplayAfterOperation) {
var self = this;
setTimeout(function(){
setTimeout(function () {
video.play();
self._playing = true;
}, 20);
}else{
}
else {
video.play();
this._playing = true;
}
@@ -456,7 +457,7 @@ _ccsg.VideoPlayer.EventType = {
proto.pause = function () {
var video = this._video;
if(!this._playing) return;
if (!this._playing) return;
this._playing = false;
if (!video) {
@@ -471,7 +472,7 @@ _ccsg.VideoPlayer.EventType = {
this._ignorePause = true;
video.pause();
var node = this._node;
setTimeout(function(){
setTimeout(function () {
node._dispatchEvent(_ccsg.VideoPlayer.EventType.STOPPED);
this._ignorePause = false;
}.bind(this), 0);
@@ -486,24 +487,32 @@ _ccsg.VideoPlayer.EventType = {
if (this._loaded) {
video.currentTime = sec;
} else {
}
else {
var cb = function () {
video.currentTime = sec;
video.removeEventListener(polyfill.event, cb);
};
video.addEventListener(polyfill.event, cb);
}
if(_ccsg.VideoPlayer._polyfill.autoplayAfterOperation && this.isPlaying()){
setTimeout(function(){
if (_ccsg.VideoPlayer._polyfill.autoplayAfterOperation && this.isPlaying()) {
setTimeout(function () {
video.play();
}, 20);
}
};
proto.setVolume = function (volume) {
var video = this._video;
if (video) {
video.volume = volume;
}
};
proto.isPlaying = function () {
var video = this._video;
if(_ccsg.VideoPlayer._polyfill.autoplayAfterOperation && this._playing){
setTimeout(function(){
if (_ccsg.VideoPlayer._polyfill.autoplayAfterOperation && this._playing) {
setTimeout(function () {
video.play();
}, 20);
}
@@ -513,10 +522,10 @@ _ccsg.VideoPlayer.EventType = {
proto.duration = function () {
var video = this._video;
var duration = -1;
if(!video) return duration;
if (!video) return duration;
duration = video.duration;
if(duration <= 0) {
if (duration <= 0) {
cc.logID(7702);
}
@@ -525,7 +534,7 @@ _ccsg.VideoPlayer.EventType = {
proto.currentTime = function () {
var video = this._video;
if(!video) return -1;
if (!video) return -1;
return video.currentTime;
};
+2 -2
View File
@@ -19,6 +19,7 @@
THE SOFTWARE.
****************************************************************************/
var Utils = require('../platform/utils');
var eventManager = require('../event-manager');
_ccsg.WebView = _ccsg.Node.extend(/** @lends _ccsg.WebView# */{
@@ -275,8 +276,7 @@ _ccsg.WebView.EventType = {
proto.resize = function (view) {
view = view || cc.view;
var node = this._node,
eventManager = cc.eventManager;
var node = this._node;
if (node._parent && node._visible)
this.updateMatrix();
else {
+36 -17
View File
@@ -8,6 +8,25 @@ if (CC_DEV) {
cc.errorID(1404);
});
js.get(cc, 'textureCache', function () {
cc.errorID(1406, 'cc', 'textureCache');
});
// Texture
js.obsolete(cc.Texture2D.prototype, 'texture.releaseTexture', 'texture.destroy');
js.get(cc.Texture2D.prototype, 'isLoaded', function () {
cc.errorID(1400, 'texture.isLoaded function', 'texture.loaded property');
return (function () {
return this.loaded;
});
});
js.get(cc.SpriteFrame.prototype, '_textureLoaded', function () {
cc.errorID(1400, 'spriteFrame._textureLoaded', 'spriteFrame.textureLoaded()');
return this.textureLoaded();
});
// Label
if (cc.Label) {
js.obsolete(cc.Label.prototype, 'cc.Label.file', 'font', true);
@@ -23,7 +42,7 @@ if (CC_DEV) {
* @returns {object}
*/
js.get(cc, "inject", function () {
cc.warnID(1400, 'cc.inject', 'cc.js.mixin');
cc.errorID(1400, 'cc.inject', 'cc.js.mixin');
cc.warnID(1401);
return function (lhs, rhs) {
return js.mixin(rhs, lhs);
@@ -40,7 +59,7 @@ if (CC_DEV) {
* @returns {object}
*/
js.get(cc, "extend", function () {
cc.warnID(1400, 'cc.extend', 'cc.js.mixin');
cc.errorID(1400, 'cc.extend', 'cc.js.mixin');
return js.mixin;
});
@@ -52,12 +71,12 @@ if (CC_DEV) {
* @returns {object}
*/
js.get(cc, "newElement", function () {
cc.warnID(1400, 'cc.newElement', 'document.createElement');
cc.errorID(1400, 'cc.newElement', 'document.createElement');
return document.createElement;
});
js.get(cc, "isFunction", function () {
cc.warnID(1400, 'cc.isFunction', '"typeof obj === \'function\'"');
cc.errorID(1400, 'cc.isFunction', '"typeof obj === \'function\'"');
return function(obj) {
return typeof obj === 'function';
};
@@ -72,7 +91,7 @@ if (CC_DEV) {
* @returns {boolean}
*/
js.get(cc, "isNumber", function () {
cc.warnID(1400, 'cc.isNumber', 'cc.js.isNumber');
cc.errorID(1400, 'cc.isNumber', 'cc.js.isNumber');
return js.isNumber;
});
@@ -85,26 +104,26 @@ if (CC_DEV) {
* @returns {boolean}
*/
js.get(cc, "isString", function () {
cc.warnID(1400, 'cc.isString', 'cc.js.isString');
cc.errorID(1400, 'cc.isString', 'cc.js.isString');
return js.isString;
});
js.get(cc, "isArray", function () {
cc.warnID(1400, 'cc.isArray', 'cc.js.isArray');
cc.errorID(1400, 'cc.isArray', 'cc.js.isArray');
return function(obj) {
return Array.isArray(obj);
};
});
js.get(cc, "isUndefined", function () {
cc.warnID(1400, 'cc.isUndefined', '"typeof obj === \'undefined\'"');
cc.errorID(1400, 'cc.isUndefined', '"typeof obj === \'undefined\'"');
return function(obj) {
return typeof obj === 'undefined';
};
});
js.get(cc, "isObject", function () {
cc.warnID(1400, 'cc.isObject', '"typeof obj === \'object\'"');
cc.errorID(1400, 'cc.isObject', '"typeof obj === \'object\'"');
return function(obj) {
return typeof obj === 'object';
};
@@ -133,7 +152,7 @@ if (CC_DEV) {
* @function
*/
js.get(cc, 'arrayVerifyType', function () {
cc.warnID(1400, 'cc.arrayVerifyType', 'cc.js.array.verifyType');
cc.errorID(1400, 'cc.arrayVerifyType', 'cc.js.array.verifyType');
return cc.js.array.verifyType;
});
@@ -146,7 +165,7 @@ if (CC_DEV) {
* @param {*} delObj remove object
*/
js.get(cc, 'arrayRemoveObject', function () {
cc.warnID(1400, 'cc.arrayRemoveObject', 'cc.js.array.remove');
cc.errorID(1400, 'cc.arrayRemoveObject', 'cc.js.array.remove');
return cc.js.array.remove;
});
@@ -159,7 +178,7 @@ if (CC_DEV) {
* @param {Array} minusArr minus Array
*/
js.get(cc, 'arrayRemoveArray', function () {
cc.warnID(1400, 'cc.arrayRemoveArray', 'cc.js.array.removeArray');
cc.errorID(1400, 'cc.arrayRemoveArray', 'cc.js.array.removeArray');
return cc.js.array.removeArray;
});
@@ -174,7 +193,7 @@ if (CC_DEV) {
* @return {Array}
*/
js.get(cc, 'arrayAppendObjectsToIndex', function() {
cc.warnID(1400, 'cc.arrayAppendObjectsToIndex', 'cc.js.array.appendObjectsAt');
cc.errorID(1400, 'cc.arrayAppendObjectsToIndex', 'cc.js.array.appendObjectsAt');
return cc.js.array.appendObjectsAt;
});
@@ -186,12 +205,12 @@ if (CC_DEV) {
* @return {Array}
*/
js.get(cc, 'copyArray', function() {
cc.warnID(1400, 'cc.copyArray', 'cc.js.array.copy');
cc.errorID(1400, 'cc.copyArray', 'cc.js.array.copy');
return cc.js.array.copy;
});
js.get(cc, 'PI', function () {
cc.warnID(1400, 'cc.PI', 'Math.PI');
cc.errorID(1400, 'cc.PI', 'Math.PI');
return Math.PI;
});
@@ -216,7 +235,7 @@ if (CC_DEV) {
}
function deprecateEnum (obj, oldPath, newPath, hasTypePrefixBefore) {
if (!cc.supportJit) {
if (!CC_SUPPORT_JIT) {
return;
}
hasTypePrefixBefore = hasTypePrefixBefore !== false;
@@ -234,7 +253,7 @@ if (CC_DEV) {
oldPropName = entry;
}
js.get(obj, oldPropName, function (entry) {
cc.warnID(1400, oldPath + delimiter + entry, newPath + '.' + entry);
cc.errorID(1400, oldPath + delimiter + entry, newPath + '.' + entry);
return enumDef[entry];
}.bind(null, entry));
}
+2 -2
View File
@@ -106,7 +106,7 @@ math.glMatrixMode = function (mode) {
cc.current_stack = math.texture_matrix_stack;
break;
default:
throw new Error("Invalid matrix mode specified"); //TODO: Proper error handling
throw new Error(cc._getError(7908)); //TODO: Proper error handling
break;
}
};
@@ -169,7 +169,7 @@ math.glGetMatrix = function (mode, pOut) {
pOut.assignFrom(math.texture_matrix_stack.top);
break;
default:
throw new Error("Invalid matrix mode specified"); //TODO: Proper error handling
throw new Error(cc._getError(7908)); //TODO: Proper error handling
break;
}
};
+1 -1
View File
@@ -153,7 +153,7 @@ proto.multiply = function(quaternion) { //cc.kmQuaternionMultiply
proto.normalize = function(){ //=cc.kmQuaternionNormalize
var length = this.length();
if (Math.abs(length) <= cc.math.EPSILON)
throw new Error("current quaternion is an invalid value");
throw new Error(cc._getError(7909));
this.scale(1.0 / length);
return this;
};
+3 -3
View File
@@ -150,8 +150,8 @@ var MotionStreak = cc.Class({
* motionStreak.texture = newTexture;
*/
_texture: {
default: '',
url: cc.Texture2D
default: null,
type: cc.Texture2D
},
texture: {
get: function () {
@@ -160,7 +160,7 @@ var MotionStreak = cc.Class({
set: function (value) {
this._texture = value;
},
url: cc.Texture2D,
type: cc.Texture2D,
animatable: false,
tooltip: CC_DEV && 'i18n:COMPONENT.motionStreak.texture'
},
+2 -2
View File
@@ -161,7 +161,7 @@ var PNGReader = cc._Class.extend({
}
this.pos += 4;
if (this.pos > this.data.length) {
throw new Error("Incomplete or corrupt PNG file");
throw new Error(cc._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++;
}
+11 -7
View File
@@ -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. <br/>
* Attributes of a Particle System:<br/>
@@ -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;
+11 -11
View File
@@ -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;
}
+5 -5
View File
@@ -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);
},
+9 -17
View File
@@ -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);
},
+63 -96
View File
@@ -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;
}
/**
* <p>cc.TMXMapInfo contains the information about the map like: <br/>
*- Map orientation (hexagonal, isometric or orthogonal)<br/>
@@ -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 <br/>
* 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
+12 -12
View File
@@ -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: {
+7 -3
View File
@@ -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();
-8
View File
@@ -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();
}
}
}
+27 -69
View File
@@ -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)) {

Some files were not shown because too many files have changed in this diff Show More