From 65a3f04796cb11fa749813fde801485c5bbb3a61 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 3 May 2017 14:11:29 +0800 Subject: [PATCH 1/5] optimizing startup time --- DebugInfos.js | 3 +- cocos2d/core/platform/CCClass.js | 131 ++++++++++++++++------------- cocos2d/core/platform/CCSys.js | 108 +++++++++++------------- cocos2d/core/platform/_CCClass.js | 8 +- cocos2d/core/platform/attribute.js | 101 +++++++++++----------- 5 files changed, 176 insertions(+), 175 deletions(-) diff --git a/DebugInfos.js b/DebugInfos.js index 707ae71505..c448fc0c7f 100644 --- a/DebugInfos.js +++ b/DebugInfos.js @@ -266,7 +266,7 @@ if (CC_DEV) { "3610": "The type of %s must be cc.Float or cc.Integer, not Number.", //getTypeChecker_7 "3611": "Can not indicate the '%s' attribute for %s, which its default value is type of %s.", //getTypeChecker_8 "3612": "%s Just set the default value to 'new %s()' and it will be handled properly.", //getTypeChecker_9 - "3613": "'No need to use 'serializable: false' or 'editorOnly: true' for the getter of '%s.%s', every getter is actually non-serialized.", //defineGetSet + "3613": "'No need to specify the '%s' attribute for the getter of '%s.%s', every getter is actually non-serialized.", //defineGetSet "3615": "Each script can have at most one Component.", //define_2 "3616": "Should not specify class name %s for Component which defines in project.", //define_3 "3617": "ctor of CCClass '%s' should not accept any arguments.", //_createCtor @@ -291,7 +291,6 @@ if (CC_DEV) { "3636": "Do not set default value to non-empty object, unless the object defines its own 'clone' function. Set default value of %s.%s to null or {}, and initialize in 'onLoad' or 'ctor' please. (just like 'this.%s = {foo: bar};')", //defineProp_2 "3637": "Can not declare %s.%s, it is already defined in the prototype of %s", //defineProp_3 "3638": "'%s': the getter of '%s' is already defined!", //defineGetSet_2 - "3639": "Can not apply the specified attribute to the getter of '%s.%s', attribute index: %s", //defineGetSet_3 "3640": "'%s': the setter of '%s' is already defined!", //defineGetSet_4 "3641": "Can not construct %s because it contains object property.", //getNewValueTypeCode "3642": "Cannot define %s.%s because static member name can not be '%s'.", //CCClass_4 diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 82dd794810..3cd4666d5a 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -29,6 +29,7 @@ var Utils = require('./utils'); var _isPlainEmptyObj_DEV = Utils.isPlainEmptyObj_DEV; var _cloneable_DEV = Utils.cloneable_DEV; var Attr = require('./attribute'); +var DELIMETER = Attr.DELIMETER; var getTypeChecker = Attr.getTypeChecker; var preprocess = require('./preprocess-class'); var Misc = require('../utils/misc'); @@ -104,7 +105,10 @@ function appendProp (cls, name) { pushUnique(cls.__props__, name); } -function defineProp (cls, className, propName, defaultValue, attrs, es6) { +var tmpArray = []; +function defineProp (cls, className, propName, val, es6) { + var defaultValue = val.default; + if (CC_DEV) { if (!es6) { // check default object value @@ -141,27 +145,27 @@ function defineProp (cls, className, propName, defaultValue, attrs, es6) { appendProp(cls, propName); // apply attributes + var attrs = parseAttributes(cls, val, className, propName, false); if (attrs) { - var onAfterProp = null; + var onAfterProp = tmpArray; for (var i = 0; i < attrs.length; i++) { var attr = attrs[i]; Attr.attr(cls, propName, attr); // register callback if (attr._onAfterProp) { - onAfterProp = onAfterProp || []; onAfterProp.push(attr._onAfterProp); } } // call callback - if (onAfterProp) { - for (var c = 0; c < onAfterProp.length; c++) { - onAfterProp[c](cls, propName); - } + for (var c = 0; c < onAfterProp.length; c++) { + onAfterProp[c](cls, propName); } + tmpArray.length = 0; + attrs.length = 0; } } -function defineGetSet (cls, name, propName, val, attrs, es6) { +function defineGetSet (cls, name, propName, val, es6) { var getter = val.get; var setter = val.set; var proto = cls.prototype; @@ -173,26 +177,12 @@ function defineGetSet (cls, name, propName, val, attrs, es6) { return; } - if (attrs) { - for (var i = 0; i < attrs.length; ++i) { - var attr = attrs[i]; - if (CC_DEV && attr._canUsedInGetter === false) { - cc.errorID(3639, name, propName, i); - continue; - } + var attrs = parseAttributes(cls, val, name, propName, true); + attrs.length = 0; - Attr.attr(cls, propName, attr); - - // check attributes - if (CC_DEV && (attr.serializable === false || attr.editorOnly === true)) { - cc.warnID(3613, name, propName); - } - } - } - - var ForceSerializable = false; + const ForceSerializable = false; if (!ForceSerializable) { - Attr.attr(cls, propName, Attr.NonSerialized); + Attr.setClassAttr(cls, propName, 'serializable', false); } if (ForceSerializable || CC_DEV) { // 不论是否 visible 都要添加到 props,否则 asset watcher 不能正常工作 @@ -505,7 +495,7 @@ function compileProps (actualClass) { for (var i = 0; i < propList.length; i++) { var prop = propList[i]; - var attrKey = prop + Attr.DELIMETER + 'default'; + var attrKey = prop + DELIMETER + 'default'; if (attrKey in attrs) { // getter does not have default var statement; if (IDENTIFIER_RE.test(prop)) { @@ -774,12 +764,11 @@ function declareProperties (cls, className, properties, baseClass, mixins, es6) for (var propName in properties) { var val = properties[propName]; - var attrs = parseAttributes(val, className, propName); if ('default' in val) { - defineProp(cls, className, propName, val.default, attrs, es6); + defineProp(cls, className, propName, val, es6); } else { - defineGetSet(cls, className, propName, val, attrs, es6); + defineGetSet(cls, className, propName, val, es6); } } } @@ -985,11 +974,11 @@ CCClass._fastDefine = function (className, constructor, serializableFields) { JS.setClassName(className, constructor); //constructor.__ctors__ = constructor.__ctors__ || null; var props = constructor.__props__ = Object.keys(serializableFields); + var attrProtos = Attr.getClassAttrsProto(constructor); for (var i = 0; i < props.length; i++) { var key = props[i]; - var val = serializableFields[key]; - Attr.setClassAttr(constructor, key, 'visible', false); - Attr.setClassAttr(constructor, key, 'default', val); + attrProtos[key + DELIMETER + 'visible'] = false; + attrProtos[key + DELIMETER + 'default'] = serializableFields[key]; } }; @@ -1061,9 +1050,16 @@ var PrimitiveTypes = { String: 'String', }; var tmpAttrs = []; -function parseAttributes (attrs, className, propName) { +function parseAttributes (cls, attrs, className, propName, usedInGetter) { var ERR_Type = CC_DEV ? 'The %s of %s must be type %s' : ''; + var attrsProto = null; + var attrsProtoKey = ''; + function getAttrsProto () { + attrsProtoKey = propName + DELIMETER; + return attrsProto = Attr.getClassAttrsProto(cls); + } + tmpAttrs.length = 0; var result = tmpAttrs; @@ -1121,18 +1117,11 @@ function parseAttributes (attrs, className, propName) { } } - function parseSimpleAttr (attrName, expectType, attrCreater) { + function parseSimpleAttr (attrName, expectType) { if (attrName in attrs) { var val = attrs[attrName]; if (typeof val === expectType) { - if ( !attrCreater ) { - var attr = {}; - attr[attrName] = val; - result.push(attr); - } - else { - result.push(typeof attrCreater === 'function' ? attrCreater(val) : attrCreater); - } + (attrsProto || getAttrsProto())[attrsProtoKey + attrName] = val; } else if (CC_DEV) { cc.error(ERR_Type, attrName, className, propName, expectType); @@ -1140,26 +1129,54 @@ function parseAttributes (attrs, className, propName) { } } - parseSimpleAttr('rawType', 'string', Attr.RawType); - parseSimpleAttr('editorOnly', 'boolean', Attr.EditorOnly); + // 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); + } + else { + (attrsProto || getAttrsProto())[attrsProtoKey + 'editorOnly'] = true; + } + } //parseSimpleAttr('preventDeferredLoad', 'boolean'); if (CC_DEV) { parseSimpleAttr('displayName', 'string'); - parseSimpleAttr('multiline', 'boolean', {multiline: true}); - parseSimpleAttr('readonly', 'boolean', {readonly: true}); + parseSimpleAttr('multiline', 'boolean'); + if (attrs.readonly) { + (attrsProto || getAttrsProto())[attrsProtoKey + 'readonly'] = true; + } parseSimpleAttr('tooltip', 'string'); parseSimpleAttr('slide', 'boolean'); } if (attrs.url) { - result.push({ saveUrlAsAsset: true }); + (attrsProto || getAttrsProto())[attrsProtoKey + 'saveUrlAsAsset'] = true; } if (attrs.serializable === false) { - result.push(Attr.NonSerialized); + if (CC_DEV && usedInGetter) { + cc.errorID(3613, "serializable", name, propName); + } + else { + (attrsProto || getAttrsProto())[attrsProtoKey + 'serializable'] = false; + } } if (CC_EDITOR) { if ('animatable' in attrs && !attrs.animatable) { - result.push({ animatable: false }); + (attrsProto || getAttrsProto())[attrsProtoKey + 'animatable'] = false; } } @@ -1167,29 +1184,27 @@ function parseAttributes (attrs, className, propName) { var visible = attrs.visible; if (typeof visible !== 'undefined') { if (!visible) { - result.push({visible: false}); + (attrsProto || getAttrsProto())[attrsProtoKey + 'visible'] = false; } else if (typeof visible === 'function') { - result.push({visible: visible}); + (attrsProto || getAttrsProto())[attrsProtoKey + 'visible'] = visible; } } else { var startsWithUS = (propName.charCodeAt(0) === 95); if (startsWithUS) { - result.push({visible: false}); + (attrsProto || getAttrsProto())[attrsProtoKey + 'visible'] = false; } } } - //if (attrs.custom) { - // result.push( { custom: attrs.custom }); - //} - var range = attrs.range; if (range) { if (Array.isArray(range)) { if (range.length >= 2) { - result.push({ min: range[0], max: range[1], step: range[2] }); + (attrsProto || getAttrsProto())[attrsProtoKey + 'min'] = range[0]; + attrsProto[attrsProtoKey + 'max'] = range[1]; + attrsProto[attrsProtoKey + 'step'] = range[2]; } else if (CC_DEV) { cc.errorID(3647); diff --git a/cocos2d/core/platform/CCSys.js b/cocos2d/core/platform/CCSys.js index 1ccc2671e9..910800f8ca 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -646,19 +646,21 @@ else { var _tmpCanvas1 = document.createElement("canvas"), _tmpCanvas2 = document.createElement("canvas"); - cc.create3DContext = function (canvas, opt_attribs) { - var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"]; - var context = null; - for (var ii = 0; ii < names.length; ++ii) { + cc.create3DContext = function (canvas, opt_attribs, opt_contextType) { + if (opt_contextType) { try { - context = canvas.getContext(names[ii], opt_attribs); + return canvas.getContext(opt_contextType, opt_attribs); } catch (e) { - } - if (context) { - break; + return null; } } - return context; + else { + return cc.create3DContext(canvas, opt_attribs, "webgl") || + cc.create3DContext(canvas, opt_attribs, "experimental-webgl") || + cc.create3DContext(canvas, opt_attribs, "webkit-3d") || + cc.create3DContext(canvas, opt_attribs, "moz-webgl") || + null; + } }; //Whether or not the Canvas BlendModes are supported. @@ -717,56 +719,48 @@ else { var _supportCanvas = !!_tmpCanvas1.getContext("2d"); var _supportWebGL = false; if (win.WebGLRenderingContext) { - var tmpCanvas = document.createElement("CANVAS"); - try{ - var context = cc.create3DContext(tmpCanvas); - if (context) { - _supportWebGL = true; - } - - if (_supportWebGL && sys.os === sys.OS_IOS && sys.osMainVersion === 9) { - // Not activating WebGL in iOS 9 UIWebView because it may crash when entering background - if (!window.indexedDB) { - _supportWebGL = false; - } - } - - if (_supportWebGL && sys.os === sys.OS_ANDROID) { - var browserVer = parseFloat(sys.browserVersion); - switch (sys.browserType) { - case sys.BROWSER_TYPE_MOBILE_QQ: - case sys.BROWSER_TYPE_BAIDU: - case sys.BROWSER_TYPE_BAIDU_APP: - // QQ & Baidu Brwoser 6.2+ (using blink kernel) - if (browserVer >= 6.2) { - _supportWebGL = true; - } - else { - _supportWebGL = false; - } - break; - case sys.BROWSER_TYPE_ANDROID: - // Android 5+ default browser - if (sys.osMainVersion && sys.osMainVersion >= 5) { - _supportWebGL = true; - } - break; - case sys.BROWSER_TYPE_CHROME: - // Chrome on android supports WebGL from v. 30 - if(browserVer >= 30.0) { - _supportWebGL = true; - } else { - _supportWebGL = false; - } - break; - case sys.BROWSER_TYPE_360: - case sys.BROWSER_TYPE_UC: - _supportWebGL = false; - } + if (cc.create3DContext(document.createElement("CANVAS"))) { + _supportWebGL = true; + } + if (_supportWebGL && sys.os === sys.OS_IOS && sys.osMainVersion === 9) { + // Not activating WebGL in iOS 9 UIWebView because it may crash when entering background + if (!win.indexedDB) { + _supportWebGL = false; + } + } + if (_supportWebGL && sys.os === sys.OS_ANDROID) { + var browserVer = parseFloat(sys.browserVersion); + switch (sys.browserType) { + case sys.BROWSER_TYPE_MOBILE_QQ: + case sys.BROWSER_TYPE_BAIDU: + case sys.BROWSER_TYPE_BAIDU_APP: + // QQ & Baidu Brwoser 6.2+ (using blink kernel) + if (browserVer >= 6.2) { + _supportWebGL = true; + } + else { + _supportWebGL = false; + } + break; + case sys.BROWSER_TYPE_ANDROID: + // Android 5+ default browser + if (sys.osMainVersion && sys.osMainVersion >= 5) { + _supportWebGL = true; + } + break; + case sys.BROWSER_TYPE_CHROME: + // Chrome on android supports WebGL from v. 30 + if(browserVer >= 30.0) { + _supportWebGL = true; + } else { + _supportWebGL = false; + } + break; + case sys.BROWSER_TYPE_360: + case sys.BROWSER_TYPE_UC: + _supportWebGL = false; } } - catch (e) {} - tmpCanvas = null; } /** diff --git a/cocos2d/core/platform/_CCClass.js b/cocos2d/core/platform/_CCClass.js index 8c7944075c..51085ab602 100644 --- a/cocos2d/core/platform/_CCClass.js +++ b/cocos2d/core/platform/_CCClass.js @@ -136,10 +136,10 @@ Class.extend = function (props) { for (var name in props) { var isFunc = (typeof props[name] === "function"); - var override = (typeof _super[name] === "function"); - var hasSuperCall = fnTest.test(props[name]); - - if (isFunc && override && hasSuperCall) { + var override = isFunc && (typeof _super[name] === "function"); + var hasSuperCall = override && fnTest.test(props[name]); + + if (hasSuperCall) { desc.value = (function (name, fn) { return CC_JSB ? function (...args) { var tmp = this._super; diff --git a/cocos2d/core/platform/attribute.js b/cocos2d/core/platform/attribute.js index ecf1471fda..ac6102e375 100644 --- a/cocos2d/core/platform/attribute.js +++ b/cocos2d/core/platform/attribute.js @@ -126,13 +126,19 @@ function attr (ctor, propName, newAttrs) { } } +// returns a readonly meta object function getClassAttrs (ctor) { return (ctor.hasOwnProperty('__attrs__') && ctor.__attrs__) || createAttrs(ctor); } +// returns a writable meta object, used to set multi attributes +function getClassAttrsProto (ctor) { + return getClassAttrs(ctor).constructor.prototype; +} + function setClassAttr (ctor, propName, key, value) { - var attrs = getClassAttrs(ctor); - attrs.constructor.prototype[propName + DELIMETER + key] = value; + var proto = getClassAttrsProto(ctor); + proto[propName + DELIMETER + key] = value; } /** @@ -222,7 +228,6 @@ cc.String = 'String'; /* BuiltinAttributes: { default: defaultValue, - _canUsedInGetter: true, (default true) _canUsedInSetter: false, (default false) (NYI) } Getter or Setter: { @@ -236,16 +241,6 @@ Callbacks: { } */ -var NonSerialized = { - serializable: false, - _canUsedInGetter: false -}; - -var EditorOnly = { - editorOnly: true, - _canUsedInGetter: false -}; - function getTypeChecker (type, attrName) { if (CC_DEV) { return function (constructor, mainPropName) { @@ -343,55 +338,53 @@ 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, - _canUsedInGetter: false, +// 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); - } - }; -} +// _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, + getClassAttrsProto: getClassAttrsProto, setClassAttr: setClassAttr, DELIMETER: DELIMETER, getTypeChecker: getTypeChecker, - NonSerialized: NonSerialized, - EditorOnly: EditorOnly, ObjectType: ObjectType, - RawType: RawType, + // RawType: RawType, ScriptUuid: {}, // the value will be represented as a uuid string }; From 633e976f699a6cf4abd6ec10d6f233752bc6a820 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Wed, 3 May 2017 17:21:13 +0800 Subject: [PATCH 2/5] optimizing startup time by reusing property descripter --- cocos2d/core/components/CCComponent.js | 107 ++++++++-------- cocos2d/core/platform/CCClass.js | 58 ++------- cocos2d/core/platform/CCObject.js | 20 +-- cocos2d/core/platform/attribute.js | 13 +- cocos2d/core/platform/deserialize.js | 2 +- cocos2d/core/platform/js.js | 167 ++++++++++++++++--------- cocos2d/core/value-types/CCColor.js | 7 +- cocos2d/core/value-types/CCRect.js | 56 ++++----- 8 files changed, 218 insertions(+), 212 deletions(-) diff --git a/cocos2d/core/components/CCComponent.js b/cocos2d/core/components/CCComponent.js index 42c63bed84..a871271a34 100644 --- a/cocos2d/core/components/CCComponent.js +++ b/cocos2d/core/components/CCComponent.js @@ -24,6 +24,7 @@ ****************************************************************************/ var CCObject = require('../platform/CCObject'); +var JS = require('../platform/js'); var idGenerater = new (require('../platform/id-generater'))('Comp'); var IsOnEnableCalled = CCObject.Flags.IsOnEnableCalled; @@ -624,8 +625,8 @@ if (CC_EDITOR || CC_TEST) { // NON-INHERITED STATIC MEMBERS - Object.defineProperty(Component, '_inspector', { value: '', writable: true }); - Object.defineProperty(Component, '_icon', { value: '', writable: true }); + JS.value(Component, '_inspector', '', true); + JS.value(Component, '_icon', '', true); // COMPONENT HELPERS @@ -640,67 +641,65 @@ if (CC_EDITOR || CC_TEST) { }; } -// use defineProperty to prevent inherited by sub classes -Object.defineProperty(Component, '_registerEditorProps', { - value (cls, props) { - var reqComp = props.requireComponent; - if (reqComp) { - cls._requireComponent = reqComp; - } - var order = props.executionOrder; - if (order && typeof order === 'number') { - cls._executionOrder = order; - } - if (CC_EDITOR || CC_TEST) { - var name = cc.js.getClassName(cls); - for (var key in props) { - var val = props[key]; - switch (key) { - case 'executeInEditMode': - cls._executeInEditMode = !!val; - break; +// we make this non-enumerable, to prevent inherited by sub classes. +JS.value(Component, '_registerEditorProps', function (cls, props) { + var reqComp = props.requireComponent; + if (reqComp) { + cls._requireComponent = reqComp; + } + var order = props.executionOrder; + if (order && typeof order === 'number') { + cls._executionOrder = order; + } + if (CC_EDITOR || CC_TEST) { + var name = cc.js.getClassName(cls); + for (var key in props) { + var val = props[key]; + switch (key) { + case 'executeInEditMode': + cls._executeInEditMode = !!val; + break; - case 'playOnFocus': - if (val) { - var willExecuteInEditMode = ('executeInEditMode' in props) ? props.executeInEditMode : cls._executeInEditMode; - if (willExecuteInEditMode) { - cls._playOnFocus = true; - } - else { - cc.warnID(3601, name); - } + case 'playOnFocus': + if (val) { + var willExecuteInEditMode = ('executeInEditMode' in props) ? props.executeInEditMode : cls._executeInEditMode; + if (willExecuteInEditMode) { + cls._playOnFocus = true; } - break; + else { + cc.warnID(3601, name); + } + } + break; - case 'inspector': - Object.defineProperty(cls, '_inspector', { value: val, writable: true }); - break; + case 'inspector': + JS.value(cls, '_inspector', val, true); + break; - case 'icon': - Object.defineProperty(cls, '_icon', { value: val, writable: true }); - break; + case 'icon': + JS.value(cls, '_icon', val, true); + break; - case 'menu': - Component._addMenuItem(cls, val, props.menuPriority); - break; + case 'menu': + Component._addMenuItem(cls, val, props.menuPriority); + break; - case 'disallowMultiple': - cls._disallowMultiple = cls; - break; + case 'disallowMultiple': + cls._disallowMultiple = cls; + break; - case 'requireComponent': - case 'executionOrder': - // skip here - break; + case 'requireComponent': + case 'executionOrder': + // skip here + break; - case 'help': - cls._help = val; - break; + case 'help': + cls._help = val; + break; - default: - cc.warnID(3602, key, name); - break; - } + default: + cc.warnID(3602, key, name); + break; } } } diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 3cd4666d5a..d80af6074d 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -190,18 +190,8 @@ function defineGetSet (cls, name, propName, val, es6) { } if (!es6) { - if (d) { - Object.defineProperty(proto, propName, { - get: getter - }); - } - else { - Object.defineProperty(proto, propName, { - get: getter, - configurable: true, - enumerable: true - }); - } + var setterUndefined = !d; + JS.get(proto, propName, getter, setterUndefined, setterUndefined); } if (CC_DEV) { @@ -215,26 +205,16 @@ function defineGetSet (cls, name, propName, val, es6) { if (d && d.set) { return cc.errorID(3640, name, propName); } - Object.defineProperty(proto, propName, { - set: setter, - configurable: true, - enumerable: true - }); + JS.set(proto, propName, setter, true, true); } Attr.setClassAttr(cls, propName, 'hasSetter', true); // 方便 editor 做判断 } else if (!es6) { if (d) { - Object.defineProperty(proto, propName, { - set: setter - }); + JS.set(proto, propName, setter); } else { - Object.defineProperty(proto, propName, { - set: setter, - configurable: true, - enumerable: true - }); + JS.set(proto, propName, setter, true, true); } } } @@ -315,22 +295,13 @@ function doDefine (className, baseClass, mixins, options) { fireClass = _createCtor(ctors, baseClass, className, options); // extend - Create a new Class that inherits from this Class - Object.defineProperty(fireClass, 'extend', { - value: function (options) { - options.extends = this; - return CCClass(options); - }, - writable: true, - configurable: true - // enumerable should be false - }); + JS.value(fireClass, 'extend', function (options) { + options.extends = this; + return CCClass(options); + }, true); } - Object.defineProperty(fireClass, '__ctors__', { - value: ctors.length > 0 ? ctors : null, - writable: true, - // enumerable should be false - }); + JS.value(fireClass, '__ctors__', ctors.length > 0 ? ctors : null, true); var prototype = fireClass.prototype; @@ -925,13 +896,8 @@ function CCClass (options) { if (!preprocess.validateMethod(func, funcName, name, cls, base)) { continue; } - // use defineProperty to redefine some super method defined as getter - Object.defineProperty(cls.prototype, funcName, { - value: func, - enumerable: true, - configurable: true, - writable: true, - }); + // use value to redefine some super method defined as getter + JS.value(cls.prototype, funcName, func, true, true); } diff --git a/cocos2d/core/platform/CCObject.js b/cocos2d/core/platform/CCObject.js index 553d90180e..7b76db2fc9 100644 --- a/cocos2d/core/platform/CCObject.js +++ b/cocos2d/core/platform/CCObject.js @@ -59,21 +59,13 @@ function CCObject () { } CCClass.fastDefine('cc.Object', CCObject, { _name: '', _objFlags: 0 }); -function defineNotInheritable (obj, prop, value, writable) { - Object.defineProperty(obj, prop, { - value: value, - writable: !!writable - // enumerable is false by default - }); -} - /** * Bit mask that controls object states. * @enum Flags * @static * @private */ -defineNotInheritable(CCObject, 'Flags', { +JS.value(CCObject, 'Flags', { Destroyed: Destroyed, //ToDestroy: ToDestroy, @@ -189,10 +181,10 @@ function deferredDestroy () { } } -defineNotInheritable(CCObject, '_deferredDestroy', deferredDestroy); +JS.value(CCObject, '_deferredDestroy', deferredDestroy); if (CC_EDITOR) { - defineNotInheritable(CCObject, '_clearDeferredDestroyTimer', function () { + JS.value(CCObject, '_clearDeferredDestroyTimer', function () { if (deferredDestroyTimer !== null) { clearImmediate(deferredDestroyTimer); deferredDestroyTimer = null; @@ -394,7 +386,7 @@ prototype._destruct = function () { var destruct = ctor.__destruct__; if (!destruct) { destruct = compileDestruct(this, ctor); - defineNotInheritable(ctor, '__destruct__', destruct, true); + JS.value(ctor, '__destruct__', destruct, true); } destruct(this); }; @@ -466,10 +458,10 @@ cc.isValid = function (value) { }; if (CC_EDITOR || CC_TEST) { - defineNotInheritable(CCObject, '_willDestroy', function (obj) { + JS.value(CCObject, '_willDestroy', function (obj) { return !(obj._objFlags & Destroyed) && (obj._objFlags & ToDestroy) > 0; }); - defineNotInheritable(CCObject, '_cancelDestroy', function (obj) { + JS.value(CCObject, '_cancelDestroy', function (obj) { obj._objFlags &= ~ToDestroy; JS.array.fastRemove(objectsToDestroy, obj); }); diff --git a/cocos2d/core/platform/attribute.js b/cocos2d/core/platform/attribute.js index ac6102e375..222dafe267 100644 --- a/cocos2d/core/platform/attribute.js +++ b/cocos2d/core/platform/attribute.js @@ -29,9 +29,12 @@ var isPlainEmptyObj = require('./utils').isPlainEmptyObj_DEV; function createAttrsSingle (owner, ownerCtor, superAttrs) { var AttrsCtor; if (CC_DEV) { - var ctorName = ownerCtor.name + '_ATTRS'; - if (owner !== ownerCtor) { - ctorName += '_INSTANCE'; + var ctorName = ownerCtor.name; + if (owner === ownerCtor) { + ctorName += '_ATTRS'; + } + else { + ctorName += '_ATTRS_INSTANCE'; } AttrsCtor = Function('return (function ' + ctorName + '(){});')(); } @@ -42,9 +45,7 @@ function createAttrsSingle (owner, ownerCtor, superAttrs) { JS.extend(AttrsCtor, superAttrs.constructor); } var attrs = new AttrsCtor(); - Object.defineProperty(owner, '__attrs__', { - value: attrs, - }); + JS.value(owner, '__attrs__', attrs); return attrs; } diff --git a/cocos2d/core/platform/deserialize.js b/cocos2d/core/platform/deserialize.js index 2d9459c6e0..841504e425 100644 --- a/cocos2d/core/platform/deserialize.js +++ b/cocos2d/core/platform/deserialize.js @@ -453,7 +453,7 @@ var _Deserializer = (function () { // if (CC_TEST && !isPhantomJS) { // cc.log(deserialize); // } - Object.defineProperty(klass, '__deserialize__', { value: deserialize, writable: true }); + JS.value(klass, '__deserialize__', deserialize, true); } deserialize(self, obj, serialized, klass, target); // if preview or build diff --git a/cocos2d/core/platform/js.js b/cocos2d/core/platform/js.js index b6bf842303..c8e6c9ae21 100644 --- a/cocos2d/core/platform/js.js +++ b/cocos2d/core/platform/js.js @@ -234,6 +234,106 @@ var js = { getPropertyDescriptor: _getPropertyDescriptor }; + +var tmpValueDesc = { + value: undefined, + enumerable: false, + writable: false, + configurable: true +}; + +/** + * Define value, just help to call Object.defineProperty.
+ * The configurable will be true. + * @method value + * @param {Object} obj + * @param {String} prop + * @param {any} value + * @param {Boolean} [writable=false] + * @param {Boolean} [enumerable=false] + */ +js.value = function (obj, prop, value, writable, enumerable) { + tmpValueDesc.value = value; + tmpValueDesc.writable = writable; + tmpValueDesc.enumerable = enumerable; + Object.defineProperty(obj, prop, tmpValueDesc); + tmpValueDesc.value = undefined; +}; + +var tmpGetSetDesc = { + get: null, + set: null, + enumerable: false, +}; + +/** + * Define get set accessor, just help to call Object.defineProperty(...) + * @method getset + * @param {Object} obj + * @param {String} prop + * @param {Function} getter + * @param {Function} setter + * @param {Boolean} [enumerable=false] + */ +js.getset = function (obj, prop, getter, setter, enumerable) { + if (typeof setter !== 'function') { + enumerable = setter; + setter = undefined; + } + tmpGetSetDesc.get = getter; + tmpGetSetDesc.set = setter; + tmpGetSetDesc.enumerable = enumerable; + Object.defineProperty(obj, prop, tmpGetSetDesc); + tmpGetSetDesc.get = null; + tmpGetSetDesc.set = null; +}; + +var tmpGetDesc = { + get: null, + enumerable: false, + configurable: false +}; + +/** + * Define get accessor, just help to call Object.defineProperty(...) + * @method get + * @param {Object} obj + * @param {String} prop + * @param {Function} getter + * @param {Boolean} [enumerable=false] + * @param {Boolean} [configurable=false] + */ +js.get = function (obj, prop, getter, enumerable, configurable) { + tmpGetDesc.get = getter; + tmpGetDesc.enumerable = enumerable; + tmpGetDesc.configurable = configurable; + Object.defineProperty(obj, prop, tmpGetDesc); + tmpGetDesc.get = null; +}; + +var tmpSetDesc = { + set: null, + enumerable: false, + configurable: false +}; + +/** + * Define set accessor, just help to call Object.defineProperty(...) + * @method set + * @param {Object} obj + * @param {String} prop + * @param {Function} setter + * @param {Boolean} [enumerable=false] + * @param {Boolean} [configurable=false] + */ +js.set = function (obj, prop, setter, enumerable, configurable) { + tmpSetDesc.set = setter; + tmpSetDesc.enumerable = enumerable; + tmpSetDesc.configurable = configurable; + Object.defineProperty(obj, prop, tmpSetDesc); + tmpSetDesc.set = null; +}; + /** * Get class name of the object, if object is just a {} (and which class named 'Object'), it will return "". * (modified from the code from this stackoverflow post) @@ -429,91 +529,40 @@ cc.js.unregisterClass to remove the id of unused class'; }; if (CC_DEV) { - Object.defineProperty(js, '_registeredClassIds', { - get: function () { + js.getset(js, '_registeredClassIds', + function () { var dump = {}; for (var id in _idToClass) { dump[id] = _idToClass[id]; } return dump; }, - set: function (value) { + function (value) { js.clear(_idToClass); for (var id in value) { _idToClass[id] = value[id]; } } - }); - Object.defineProperty(js, '_registeredClassNames', { - get: function () { + ); + js.getset(js, '_registeredClassNames', + function () { var dump = {}; for (var id in _nameToClass) { dump[id] = _nameToClass[id]; } return dump; }, - set: function (value) { + function (value) { js.clear(_nameToClass); for (var id in value) { _nameToClass[id] = value[id]; } } - }); + ); } })(); -/** - * Define get set accessor, just help to call Object.defineProperty(...) - * @method getset - * @param {any} obj - * @param {String} prop - * @param {Function} getter - * @param {Function} setter - * @param {Boolean} [enumerable=false] - */ -js.getset = function (obj, prop, getter, setter, enumerable) { - if (typeof setter !== 'function') { - enumerable = setter; - setter = undefined; - } - Object.defineProperty(obj, prop, { - get: getter, - set: setter, - enumerable: !!enumerable - }); -}; - -/** - * Define get accessor, just help to call Object.defineProperty(...) - * @method get - * @param {any} obj - * @param {String} prop - * @param {Function} getter - * @param {Boolean} [enumerable=false] - */ -js.get = function (obj, prop, getter, enumerable) { - Object.defineProperty(obj, prop, { - get: getter, - enumerable: !!enumerable - }); -}; - -/** - * Define set accessor, just help to call Object.defineProperty(...) - * @method set - * @param {any} obj - * @param {String} prop - * @param {Function} setter - * @param {Boolean} [enumerable=false] - */ -js.set = function (obj, prop, setter, enumerable) { - Object.defineProperty(obj, prop, { - set: setter, - enumerable: !!enumerable - }); -}; - /** * Defines a polyfill field for obsoleted codes. * @method obsolete diff --git a/cocos2d/core/value-types/CCColor.js b/cocos2d/core/value-types/CCColor.js index 64488980c3..61d924f17a 100644 --- a/cocos2d/core/value-types/CCColor.js +++ b/cocos2d/core/value-types/CCColor.js @@ -161,12 +161,11 @@ var Color = (function () { MAGENTA: [255, 0, 255] }; for (var colorName in DefaultColors) { - var colorGetter = (function (r, g, b, a) { + JS.get(Color, colorName, (function (rgba) { return function () { - return new Color(r, g, b, a); + return new Color(rgba[0], rgba[1], rgba[2], rgba[3]); }; - }).apply(null, DefaultColors[colorName]); - Object.defineProperty(Color, colorName, { get: colorGetter }); + })(DefaultColors[colorName])); } var proto = Color.prototype; diff --git a/cocos2d/core/value-types/CCRect.js b/cocos2d/core/value-types/CCRect.js index 62cb68802c..6af6f2d363 100644 --- a/cocos2d/core/value-types/CCRect.js +++ b/cocos2d/core/value-types/CCRect.js @@ -215,13 +215,13 @@ proto.toString = function () { * @property xMin * @type {Number} */ -Object.defineProperty(proto, 'xMin', { - get: function () { return this.x; }, - set: function (value) { +JS.getset(proto, 'xMin', + function () { return this.x; }, + function (value) { this.width += this.x - value; this.x = value; } -}); +); /** * !#en TODO @@ -229,13 +229,13 @@ Object.defineProperty(proto, 'xMin', { * @property yMin * @type {Number} */ -Object.defineProperty(proto, 'yMin', { - get: function () { return this.y; }, - set: function (value) { +JS.getset(proto, 'yMin', + function () { return this.y; }, + function (value) { this.height += this.y - value; this.y = value; } -}); +); /** * !#en TODO @@ -243,10 +243,10 @@ Object.defineProperty(proto, 'yMin', { * @property xMax * @type {Number} */ -Object.defineProperty(proto, 'xMax', { - get: function () { return this.x + this.width; }, - set: function (value) { this.width = value - this.x; } -}); +JS.getset(proto, 'xMax', + function () { return this.x + this.width; }, + function (value) { this.width = value - this.x; } +); /** * !#en TODO @@ -254,56 +254,56 @@ Object.defineProperty(proto, 'xMax', { * @property yMax * @type {Number} */ -Object.defineProperty(proto, 'yMax', { - get: function () { return this.y + this.height; }, - set: function (value) { this.height = value - this.y; } -}); +JS.getset(proto, 'yMax', + function () { return this.y + this.height; }, + function (value) { this.height = value - this.y; } +); /** * !#en The position of the center of the rectangle. * !#zh 矩形的中心点。 * @property {Vec2} center */ -Object.defineProperty(proto, 'center', { - get: function () { +JS.getset(proto, 'center', + function () { return new cc.Vec2(this.x + this.width * 0.5, this.y + this.height * 0.5); }, - set: function (value) { + function (value) { this.x = value.x - this.width * 0.5; this.y = value.y - this.height * 0.5; } -}); +); /** * !#en The X and Y position of the rectangle. * !#zh 矩形的 x 和 y 坐标。 * @property {Vec2} origin */ -Object.defineProperty(proto, 'origin', { - get () { +JS.getset(proto, 'origin', + function () { return new cc.Vec2(this.x, this.y); }, - set (value) { + function (value) { this.x = value.x; this.y = value.y; } -}); +); /** * !#en Width and height of the rectangle. * !#zh 矩形的大小。 * @property {Size} size */ -Object.defineProperty(proto, 'size', { - get: function () { +JS.getset(proto, 'size', + function () { return new cc.Size(this.width, this.height); }, - set: function (value) { + function (value) { this.width = value.width; this.height = value.height; } -}); +); /** * !#en TODO From 6c75eb09cb62cf1fac82ca1fbea011064d7fa169 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 4 May 2017 15:47:14 +0800 Subject: [PATCH 3/5] optimize browserify startup time --- gulp/browserify_prelude.js | 48 ++++++++++++++++++++++++++++++++++++++ gulp/tasks/utils.js | 8 +++++++ 2 files changed, 56 insertions(+) create mode 100644 gulp/browserify_prelude.js diff --git a/gulp/browserify_prelude.js b/gulp/browserify_prelude.js new file mode 100644 index 0000000000..ae38433678 --- /dev/null +++ b/gulp/browserify_prelude.js @@ -0,0 +1,48 @@ + +// Based on https://github.com/substack/browser-pack/blob/master/prelude.js + +// modules are defined as an array +// [ module function, map of requireuires ] +// +// map of requireuires is short require name -> numeric require +// +// anything defined in a previous bundle is accessed via the +// orig method which is the requireuire for previous bundles + +(function outer (modules, cache, entry) { + // Save the require from previous bundle to this closure if any + var previousRequire = typeof require == "function" && require; + + function newRequire(name, jumped){ + var module = cache[name]; + if(!module) { + var moduleData = modules[name]; + if(!moduleData) { + // if we cannot find the module within our internal map or + // cache jump to the current global require ie. the last bundle + // that was added to the page. + var currentRequire = typeof require == "function" && require; + if (!jumped && currentRequire) return currentRequire(name, true); + + // If there are other bundles on this page the require from the + // previous one is saved to 'previousRequire'. Repeat this as + // many times as there are bundles until the module is found or + // we exhaust the require chain. + if (previousRequire) return previousRequire(name, true); + var err = new Error('Cannot find module \'' + name + '\''); + err.code = 'MODULE_NOT_FOUND'; + throw err; + } + var exports = {}; + module = cache[name] = {exports}; + moduleData[0](function(x){ + return newRequire(moduleData[1][x] || x); + },module,exports); + } + return module.exports; + } + for(var i=0;i Date: Thu, 4 May 2017 15:54:48 +0800 Subject: [PATCH 4/5] optimize engine startup time by removing some js.mixin --- cocos2d/animation/types.js | 305 ++- cocos2d/core/CCScheduler.js | 139 +- cocos2d/core/event-manager/CCEvent.js | 524 +++--- cocos2d/core/event/event-target.js | 506 ++--- cocos2d/core/event/event.js | 56 +- cocos2d/core/graphics/graphics-canvas-cmd.js | 235 ++- cocos2d/core/graphics/graphics-node.js | 191 +- cocos2d/core/graphics/graphics-webgl-cmd.js | 1640 ++++++++--------- cocos2d/core/load-pipeline/CCLoader.js | 1539 ++++++++-------- cocos2d/core/load-pipeline/asset-table.js | 200 +- cocos2d/core/load-pipeline/downloader.js | 75 +- cocos2d/core/load-pipeline/loader.js | 41 +- cocos2d/core/load-pipeline/loading-items.js | 603 +++--- cocos2d/core/load-pipeline/pipeline.js | 460 ++--- cocos2d/core/platform/instantiate-jit.js | 419 +++-- cocos2d/core/platform/utils.js | 38 +- cocos2d/core/textures/CCTexture2D.js | 823 ++++----- cocos2d/core/textures/CCTextureAtlas.js | 124 +- cocos2d/core/utils/misc.js | 2 +- cocos2d/core/value-types/CCValueType.js | 38 +- cocos2d/core/value-types/CCVec2.js | 924 +++++----- cocos2d/shape-nodes/CCDrawNode.js | 1353 +++++++------- .../shape-nodes/CCDrawNodeCanvasRenderCmd.js | 181 +- gulp/browserify_prelude.js | 2 +- 24 files changed, 5198 insertions(+), 5220 deletions(-) diff --git a/cocos2d/animation/types.js b/cocos2d/animation/types.js index 78a92f682a..203d23d387 100644 --- a/cocos2d/animation/types.js +++ b/cocos2d/animation/types.js @@ -73,7 +73,7 @@ var WrapMode = cc.Enum({ cc.WrapMode = WrapMode; // For internal -var WrappedInfo = function (info) { +function WrappedInfo (info) { if (info) { this.set(info); return; @@ -84,7 +84,7 @@ var WrappedInfo = function (info) { this.direction = 1; this.stopped = true; this.iterations = 0; -}; +} WrappedInfo.prototype.set = function (info) { for (var k in info) { @@ -99,9 +99,9 @@ WrappedInfo.prototype.set = function (info) { * * @extends Playable */ -var AnimationNodeBase = function () { +function AnimationNodeBase () { Playable.call(this); -}; +} JS.extend(AnimationNodeBase, Playable); /** @@ -257,167 +257,166 @@ function AnimationNode (animator, curves, timingInput) { } JS.extend(AnimationNode, AnimationNodeBase); -JS.mixin(AnimationNode.prototype, { +var proto = AnimationNode.prototype; - update: function (delta) { +proto.update = function (delta) { - // calculate delay time + // calculate delay time - if (this._duringDelay) { - this._timeNoScale += delta; - if (this._timeNoScale < this.delay) { - // still waiting - return; - } - else { - this._duringDelay = false; - } - //// start play - // delta -= (this._timeNoScale - this.delay); - } - - // make first frame perfect - - //var playPerfectFirstFrame = (this.time === 0); - if (this._firstFramePlayed) { - this.time += (delta * this.speed); + if (this._duringDelay) { + this._timeNoScale += delta; + if (this._timeNoScale < this.delay) { + // still waiting + return; } else { - this._firstFramePlayed = true; + this._duringDelay = false; } + //// start play + // delta -= (this._timeNoScale - this.delay); + } - // sample - var info = this.sample(); + // make first frame perfect - if (!this._lastWrappedInfo) { - this._lastWrappedInfo = new WrappedInfo(info); - } + //var playPerfectFirstFrame = (this.time === 0); + if (this._firstFramePlayed) { + this.time += (delta * this.speed); + } + else { + this._firstFramePlayed = true; + } - var anotherIteration = (info.iterations | 0) > (this._lastWrappedInfo.iterations | 0); - if (this.repeatCount > 1 && anotherIteration) { - if ((this.wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse) { - if (this._lastWrappedInfo.direction < 0) { - this.emit('lastframe', this); - } - } - else { - if (this._lastWrappedInfo.direction > 0) { - this.emit('lastframe', this); - } + // sample + var info = this.sample(); + + if (!this._lastWrappedInfo) { + this._lastWrappedInfo = new WrappedInfo(info); + } + + var anotherIteration = (info.iterations | 0) > (this._lastWrappedInfo.iterations | 0); + if (this.repeatCount > 1 && anotherIteration) { + if ((this.wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse) { + if (this._lastWrappedInfo.direction < 0) { + this.emit('lastframe', this); } } - - if (info.stopped) { - this.stop(); - this.emit('finished', this); - } - - this._lastWrappedInfo.set(info); - }, - - _needRevers: function (currentIterations) { - var wrapMode = this.wrapMode; - var needRevers = false; - - if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) { - var isEnd = currentIterations - (currentIterations | 0) === 0; - if (isEnd && (currentIterations > 0)) { - currentIterations -= 1; - } - - var isOddIteration = currentIterations & 1; - if (isOddIteration) { - needRevers = !needRevers; + else { + if (this._lastWrappedInfo.direction > 0) { + this.emit('lastframe', this); } } - if ((wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse) { + } + + if (info.stopped) { + this.stop(); + this.emit('finished', this); + } + + this._lastWrappedInfo.set(info); +}; + +proto._needRevers = function (currentIterations) { + var wrapMode = this.wrapMode; + var needRevers = false; + + if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) { + var isEnd = currentIterations - (currentIterations | 0) === 0; + if (isEnd && (currentIterations > 0)) { + currentIterations -= 1; + } + + var isOddIteration = currentIterations & 1; + if (isOddIteration) { needRevers = !needRevers; } - return needRevers; - }, - - getWrappedInfo: function (time, info) { - info = info || new WrappedInfo(); - - var stopped = false; - var duration = this.duration; - var ratio = 0; - var wrapMode = this.wrapMode; - - var currentIterations = Math.abs(time / duration); - if (currentIterations > this.repeatCount) currentIterations = this.repeatCount; - - var needRevers = false; - if (wrapMode & WrapModeMask.ShouldWrap) { - needRevers = this._needRevers(currentIterations); - } - - var direction = needRevers ? -1 : 1; - if (this.speed < 0) direction *= -1; - - if (currentIterations >= this.repeatCount) { - stopped = true; - var tempRatio = this.repeatCount - (this.repeatCount | 0); - if (tempRatio === 0) { - tempRatio = 1; // 如果播放过,动画不复位 - } - time = tempRatio * duration * (time > 0 ? 1 : -1); - } - - if (time > duration) { - var tempTime = time % duration; - time = tempTime === 0 ? duration : tempTime; - } - else if (time < 0) { - time = time % duration; - if (time !== 0 ) time += duration; - } - - // calculate wrapped time - if (wrapMode & WrapModeMask.ShouldWrap) { - if (needRevers) time = duration - time; - } - - ratio = time / duration; - - info.ratio = ratio; - info.time = time; - info.direction = direction; - info.stopped = stopped; - info.iterations = currentIterations; - - return info; - }, - - sample: function () { - var info = this.getWrappedInfo(this.time, this._wrappedInfo); - var curves = this.curves; - for (var i = 0, len = curves.length; i < len; i++) { - var curve = curves[i]; - curve.sample(info.time, info.ratio, this); - } - - return info; - }, - - onStop: function () { - this.emit('stop', this); - }, - - onPlay: function () { - this.emit('play', this); - }, - - onPause: function () { - this.emit('pause', this); - }, - - onResume: function () { - this.emit('resume', this); } -}); + if ((wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse) { + needRevers = !needRevers; + } + return needRevers; +}; -cc.defineGetterSetter(AnimationNode.prototype, 'wrapMode', +proto.getWrappedInfo = function (time, info) { + info = info || new WrappedInfo(); + + var stopped = false; + var duration = this.duration; + var ratio = 0; + var wrapMode = this.wrapMode; + + var currentIterations = Math.abs(time / duration); + if (currentIterations > this.repeatCount) currentIterations = this.repeatCount; + + var needRevers = false; + if (wrapMode & WrapModeMask.ShouldWrap) { + needRevers = this._needRevers(currentIterations); + } + + var direction = needRevers ? -1 : 1; + if (this.speed < 0) direction *= -1; + + if (currentIterations >= this.repeatCount) { + stopped = true; + var tempRatio = this.repeatCount - (this.repeatCount | 0); + if (tempRatio === 0) { + tempRatio = 1; // 如果播放过,动画不复位 + } + time = tempRatio * duration * (time > 0 ? 1 : -1); + } + + if (time > duration) { + var tempTime = time % duration; + time = tempTime === 0 ? duration : tempTime; + } + else if (time < 0) { + time = time % duration; + if (time !== 0 ) time += duration; + } + + // calculate wrapped time + if (wrapMode & WrapModeMask.ShouldWrap) { + if (needRevers) time = duration - time; + } + + ratio = time / duration; + + info.ratio = ratio; + info.time = time; + info.direction = direction; + info.stopped = stopped; + info.iterations = currentIterations; + + return info; +}; + +proto.sample = function () { + var info = this.getWrappedInfo(this.time, this._wrappedInfo); + var curves = this.curves; + for (var i = 0, len = curves.length; i < len; i++) { + var curve = curves[i]; + curve.sample(info.time, info.ratio, this); + } + + return info; +}; + +proto.onStop = function () { + this.emit('stop', this); +}; + +proto.onPlay = function () { + this.emit('play', this); +}; + +proto.onPause = function () { + this.emit('pause', this); +}; + +proto.onResume = function () { + this.emit('resume', this); +}; + +JS.getset(proto, 'wrapMode', function () { return this._wrapMode; }, @@ -438,13 +437,13 @@ cc.defineGetterSetter(AnimationNode.prototype, 'wrapMode', } ); -cc.js.mixin(AnimationNode.prototype, cc.EventTarget.prototype); +cc.js.mixin(proto, cc.EventTarget.prototype); cc.AnimationNode = AnimationNode; module.exports = { - WrapModeMask: WrapModeMask, - WrapMode: WrapMode, - AnimationNode: AnimationNode, - WrappedInfo: WrappedInfo + WrapModeMask, + WrapMode, + AnimationNode, + WrappedInfo }; diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index 5b1a4d83f1..8efda2ccaa 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -159,7 +159,7 @@ HashTimerEntry.put = function (entry) { * Light weight timer * @extends cc.Class */ -var CallbackTimer = function () { +function CallbackTimer () { this._scheduler = null; this._elapsed = -1; this._runForever = false; @@ -171,84 +171,85 @@ var CallbackTimer = function () { this._target = null; this._callback = null; +} + +var proto = CallbackTimer.prototype; + +proto.initWithCallback = function (scheduler, callback, target, seconds, repeat, delay) { + this._scheduler = scheduler; + this._target = target; + this._callback = callback; + + this._elapsed = -1; + this._interval = seconds; + this._delay = delay; + this._useDelay = (this._delay > 0); + this._repeat = repeat; + this._runForever = (this._repeat === cc.macro.REPEAT_FOREVER); + return true; }; -cc.js.mixin(CallbackTimer.prototype, { - initWithCallback: function (scheduler, callback, target, seconds, repeat, delay) { - this._scheduler = scheduler; - this._target = target; - this._callback = callback; +/** + * @return {Number} returns interval of timer + */ +proto.getInterval = function(){return this._interval;}; +/** + * @param {Number} interval set interval in seconds + */ +proto.setInterval = function(interval){this._interval = interval;}; - this._elapsed = -1; - this._interval = seconds; - this._delay = delay; - this._useDelay = (this._delay > 0); - this._repeat = repeat; - this._runForever = (this._repeat === cc.macro.REPEAT_FOREVER); - return true; - }, - /** - * @return {Number} returns interval of timer - */ - getInterval : function(){return this._interval;}, - /** - * @param {Number} interval set interval in seconds - */ - setInterval : function(interval){this._interval = interval;}, +/** + * triggers the timer + * @param {Number} dt delta time + */ +proto.update = function (dt) { + if (this._elapsed === -1) { + this._elapsed = 0; + this._timesExecuted = 0; + } else { + this._elapsed += dt; + if (this._runForever && !this._useDelay) {//standard timer usage + if (this._elapsed >= this._interval) { + this.trigger(); + this._elapsed = 0; + } + } else {//advanced usage + if (this._useDelay) { + if (this._elapsed >= this._delay) { + this.trigger(); - /** - * triggers the timer - * @param {Number} dt delta time - */ - update: function (dt) { - if (this._elapsed === -1) { - this._elapsed = 0; - this._timesExecuted = 0; - } else { - this._elapsed += dt; - if (this._runForever && !this._useDelay) {//standard timer usage + this._elapsed -= this._delay; + this._timesExecuted += 1; + this._useDelay = false; + } + } else { if (this._elapsed >= this._interval) { this.trigger(); + this._elapsed = 0; + this._timesExecuted += 1; } - } else {//advanced usage - if (this._useDelay) { - if (this._elapsed >= this._delay) { - this.trigger(); - - this._elapsed -= this._delay; - this._timesExecuted += 1; - this._useDelay = false; - } - } else { - if (this._elapsed >= this._interval) { - this.trigger(); - - this._elapsed = 0; - this._timesExecuted += 1; - } - } - - if (this._callback && !this._runForever && this._timesExecuted > this._repeat) - this.cancel(); } + + if (this._callback && !this._runForever && this._timesExecuted > this._repeat) + this.cancel(); } - }, - - getCallback: function(){ - return this._callback; - }, - - trigger: function () { - if (this._target && this._callback){ - this._callback.call(this._target, this._elapsed); - } - }, - - cancel: function () { - //override - this._scheduler.unschedule(this._callback, this._target); } -}); +}; + +proto.getCallback = function(){ + return this._callback; +}; + +proto.trigger = function () { + if (this._target && this._callback){ + this._callback.call(this._target, this._elapsed); + } +}; + +proto.cancel = function () { + //override + this._scheduler.unschedule(this._callback, this._target); +}; var _timers = []; CallbackTimer.get = function () { diff --git a/cocos2d/core/event-manager/CCEvent.js b/cocos2d/core/event-manager/CCEvent.js index 9c05eafef6..25b978d6a1 100644 --- a/cocos2d/core/event-manager/CCEvent.js +++ b/cocos2d/core/event-manager/CCEvent.js @@ -49,156 +49,156 @@ var EventMouse = function (eventType, bubbles) { }; JS.extend(EventMouse, cc.Event); -JS.mixin(EventMouse.prototype, { - /** - * !#en Sets scroll data. - * !#zh 设置鼠标的滚动数据。 - * @method setScrollData - * @param {Number} scrollX - * @param {Number} scrollY - */ - setScrollData: function (scrollX, scrollY) { - this._scrollX = scrollX; - this._scrollY = scrollY; - }, +var proto = EventMouse.prototype; - /** - * !#en Returns the x axis scroll value. - * !#zh 获取鼠标滚动的X轴距离,只有滚动时才有效。 - * @method getScrollX - * @returns {Number} - */ - getScrollX: function () { - return this._scrollX; - }, +/** + * !#en Sets scroll data. + * !#zh 设置鼠标的滚动数据。 + * @method setScrollData + * @param {Number} scrollX + * @param {Number} scrollY + */ +proto.setScrollData = function (scrollX, scrollY) { + this._scrollX = scrollX; + this._scrollY = scrollY; +}; - /** - * !#en Returns the y axis scroll value. - * !#zh 获取滚轮滚动的 Y 轴距离,只有滚动时才有效。 - * @method getScrollY - * @returns {Number} - */ - getScrollY: function () { - return this._scrollY; - }, +/** + * !#en Returns the x axis scroll value. + * !#zh 获取鼠标滚动的X轴距离,只有滚动时才有效。 + * @method getScrollX + * @returns {Number} + */ +proto.getScrollX = function () { + return this._scrollX; +}; - /** - * !#en Sets cursor location. - * !#zh 设置当前鼠标位置。 - * @method setLocation - * @param {Number} x - * @param {Number} y - */ - setLocation: function (x, y) { - this._x = x; - this._y = y; - }, +/** + * !#en Returns the y axis scroll value. + * !#zh 获取滚轮滚动的 Y 轴距离,只有滚动时才有效。 + * @method getScrollY + * @returns {Number} + */ +proto.getScrollY = function () { + return this._scrollY; +}; - /** - * !#en Returns cursor location. - * !#zh 获取鼠标位置对象,对象包含 x 和 y 属性。 - * @method getLocation - * @return {Vec2} location - */ - getLocation: function () { - return {x: this._x, y: this._y}; - }, +/** + * !#en Sets cursor location. + * !#zh 设置当前鼠标位置。 + * @method setLocation + * @param {Number} x + * @param {Number} y + */ +proto.setLocation = function (x, y) { + this._x = x; + this._y = y; +}; - /** - * !#en Returns the current cursor location in screen coordinates. - * !#zh 获取当前事件在游戏窗口内的坐标位置对象,对象包含 x 和 y 属性。 - * @method getLocationInView - * @return {Vec2} - */ - getLocationInView: function() { - return {x: this._x, y: cc.view._designResolutionSize.height - this._y}; - }, +/** + * !#en Returns cursor location. + * !#zh 获取鼠标位置对象,对象包含 x 和 y 属性。 + * @method getLocation + * @return {Vec2} location + */ +proto.getLocation = function () { + return {x: this._x, y: this._y}; +}; - _setPrevCursor: function (x, y) { - this._prevX = x; - this._prevY = y; - }, +/** + * !#en Returns the current cursor location in screen coordinates. + * !#zh 获取当前事件在游戏窗口内的坐标位置对象,对象包含 x 和 y 属性。 + * @method getLocationInView + * @return {Vec2} + */ +proto.getLocationInView = function() { + return {x: this._x, y: cc.view._designResolutionSize.height - this._y}; +}; - /** - * !#en Returns the previous touch location. - * !#zh 获取鼠标点击在上一次事件时的位置对象,对象包含 x 和 y 属性。 - * @method getPreviousLocation - * @return {Vec2} - */ - getPreviousLocation:function () { - return {x: this._prevX, y: this._prevY}; - }, +proto._setPrevCursor = function (x, y) { + this._prevX = x; + this._prevY = y; +}; - /** - * !#en Returns the delta distance from the previous location to current location. - * !#zh 获取鼠标距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 - * @method getDelta - * @return {Vec2} - */ - getDelta: function () { - return {x: this._x - this._prevX, y: this._y - this._prevY}; - }, +/** + * !#en Returns the previous touch location. + * !#zh 获取鼠标点击在上一次事件时的位置对象,对象包含 x 和 y 属性。 + * @method getPreviousLocation + * @return {Vec2} + */ +proto.getPreviousLocation = function () { + return {x: this._prevX, y: this._prevY}; +}; - /** - * !#en Returns the X axis delta distance from the previous location to current location. - * !#zh 获取鼠标距离上一次事件移动的 X 轴距离。 - * @method getDeltaX - * @return {Number} - */ - getDeltaX: function () { - return this._x - this._prevX; - }, +/** + * !#en Returns the delta distance from the previous location to current location. + * !#zh 获取鼠标距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 + * @method getDelta + * @return {Vec2} + */ +proto.getDelta = function () { + return {x: this._x - this._prevX, y: this._y - this._prevY}; +}; - /** - * !#en Returns the Y axis delta distance from the previous location to current location. - * !#zh 获取鼠标距离上一次事件移动的 Y 轴距离。 - * @method getDeltaY - * @return {Number} - */ - getDeltaY: function () { - return this._y - this._prevY; - }, +/** + * !#en Returns the X axis delta distance from the previous location to current location. + * !#zh 获取鼠标距离上一次事件移动的 X 轴距离。 + * @method getDeltaX + * @return {Number} + */ +proto.getDeltaX = function () { + return this._x - this._prevX; +}; - /** - * !#en Sets mouse button. - * !#zh 设置鼠标按键。 - * @method setButton - * @param {Number} button - */ - setButton: function (button) { - this._button = button; - }, +/** + * !#en Returns the Y axis delta distance from the previous location to current location. + * !#zh 获取鼠标距离上一次事件移动的 Y 轴距离。 + * @method getDeltaY + * @return {Number} + */ +proto.getDeltaY = function () { + return this._y - this._prevY; +}; - /** - * !#en Returns mouse button. - * !#zh 获取鼠标按键。 - * @method getButton - * @returns {Number} - */ - getButton: function () { - return this._button; - }, +/** + * !#en Sets mouse button. + * !#zh 设置鼠标按键。 + * @method setButton + * @param {Number} button + */ +proto.setButton = function (button) { + this._button = button; +}; - /** - * !#en Returns location X axis data. - * !#zh 获取鼠标当前位置 X 轴。 - * @method getLocationX - * @returns {Number} - */ - getLocationX: function () { - return this._x; - }, +/** + * !#en Returns mouse button. + * !#zh 获取鼠标按键。 + * @method getButton + * @returns {Number} + */ +proto.getButton = function () { + return this._button; +}; - /** - * !#en Returns location Y axis data. - * !#zh 获取鼠标当前位置 Y 轴。 - * @method getLocationY - * @returns {Number} - */ - getLocationY: function () { - return this._y; - } -}); +/** + * !#en Returns location X axis data. + * !#zh 获取鼠标当前位置 X 轴。 + * @method getLocationX + * @returns {Number} + */ +proto.getLocationX = function () { + return this._x; +}; + +/** + * !#en Returns location Y axis data. + * !#zh 获取鼠标当前位置 Y 轴。 + * @method getLocationY + * @returns {Number} + */ +proto.getLocationY = function () { + return this._y; +}; //Inner event types of MouseEvent /** @@ -334,146 +334,146 @@ var EventTouch = function (touchArr, bubbles) { }; JS.extend(EventTouch, cc.Event); -JS.mixin(EventTouch.prototype, { - /** - * !#en Returns event code. - * !#zh 获取事件类型。 - * @method getEventCode - * @returns {Number} - */ - getEventCode: function () { - return this._eventCode; - }, +proto = EventTouch.prototype; - /** - * !#en Returns touches of event. - * !#zh 获取触摸点的列表。 - * @method getTouches - * @returns {Array} - */ - getTouches: function () { - return this._touches; - }, +/** + * !#en Returns event code. + * !#zh 获取事件类型。 + * @method getEventCode + * @returns {Number} + */ +proto.getEventCode = function () { + return this._eventCode; +}; - _setEventCode: function (eventCode) { - this._eventCode = eventCode; - }, +/** + * !#en Returns touches of event. + * !#zh 获取触摸点的列表。 + * @method getTouches + * @returns {Array} + */ +proto.getTouches = function () { + return this._touches; +}; - _setTouches: function (touches) { - this._touches = touches; - }, +proto._setEventCode = function (eventCode) { + this._eventCode = eventCode; +}; - /** - * !#en Sets touch location. - * !#zh 设置当前触点位置 - * @method setLocation - * @param {Number} x - * @param {Number} y - */ - setLocation: function (x, y) { - this.touch && this.touch.setTouchInfo(this.touch.getID(), x, y); - }, +proto._setTouches = function (touches) { + this._touches = touches; +}; - /** - * !#en Returns touch location. - * !#zh 获取触点位置。 - * @method getLocation - * @return {Vec2} location - */ - getLocation: function () { - return this.touch ? this.touch.getLocation() : cc.v2(); - }, +/** + * !#en Sets touch location. + * !#zh 设置当前触点位置 + * @method setLocation + * @param {Number} x + * @param {Number} y + */ +proto.setLocation = function (x, y) { + this.touch && this.touch.setTouchInfo(this.touch.getID(), x, y); +}; - /** - * !#en Returns the current touch location in screen coordinates. - * !#zh 获取当前触点在游戏窗口中的位置。 - * @method getLocationInView - * @return {Vec2} - */ - getLocationInView: function() { - return this.touch ? this.touch.getLocationInView() : cc.v2(); - }, +/** + * !#en Returns touch location. + * !#zh 获取触点位置。 + * @method getLocation + * @return {Vec2} location + */ +proto.getLocation = function () { + return this.touch ? this.touch.getLocation() : cc.v2(); +}; - /** - * !#en Returns the previous touch location. - * !#zh 获取触点在上一次事件时的位置对象,对象包含 x 和 y 属性。 - * @method getPreviousLocation - * @return {Vec2} - */ - getPreviousLocation:function () { - return this.touch ? this.touch.getPreviousLocation() : cc.v2(); - }, +/** + * !#en Returns the current touch location in screen coordinates. + * !#zh 获取当前触点在游戏窗口中的位置。 + * @method getLocationInView + * @return {Vec2} + */ +proto.getLocationInView = function() { + return this.touch ? this.touch.getLocationInView() : cc.v2(); +}; - /** - * !#en Returns the start touch location. - * !#zh 获获取触点落下时的位置对象,对象包含 x 和 y 属性。 - * @method getStartLocation - * @returns {Vec2} - */ - getStartLocation: function() { - return this.touch ? this.touch.getStartLocation() : cc.v2(); - }, +/** + * !#en Returns the previous touch location. + * !#zh 获取触点在上一次事件时的位置对象,对象包含 x 和 y 属性。 + * @method getPreviousLocation + * @return {Vec2} + */ +proto.getPreviousLocation = function () { + return this.touch ? this.touch.getPreviousLocation() : cc.v2(); +}; - /** - * !#en Returns the id of cc.Touch. - * !#zh 触点的标识 ID,可以用来在多点触摸中跟踪触点。 - * @method getID - * @return {Number} - */ - getID:function () { - return this.touch ? this.touch.getID() : null; - }, +/** + * !#en Returns the start touch location. + * !#zh 获获取触点落下时的位置对象,对象包含 x 和 y 属性。 + * @method getStartLocation + * @returns {Vec2} + */ +proto.getStartLocation = function() { + return this.touch ? this.touch.getStartLocation() : cc.v2(); +}; - /** - * !#en Returns the delta distance from the previous location to current location. - * !#zh 获取触点距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 - * @method getDelta - * @return {Vec2} - */ - getDelta: function () { - return this.touch ? this.touch.getDelta() : cc.v2(); - }, +/** + * !#en Returns the id of cc.Touch. + * !#zh 触点的标识 ID,可以用来在多点触摸中跟踪触点。 + * @method getID + * @return {Number} + */ +proto.getID = function () { + return this.touch ? this.touch.getID() : null; +}; - /** - * !#en Returns the X axis delta distance from the previous location to current location. - * !#zh 获取触点距离上一次事件移动的 x 轴距离。 - * @method getDeltaX - * @return {Number} - */ - getDeltaX: function () { - return this.touch ? this.touch.getDelta().x : 0; - }, +/** + * !#en Returns the delta distance from the previous location to current location. + * !#zh 获取触点距离上一次事件移动的距离对象,对象包含 x 和 y 属性。 + * @method getDelta + * @return {Vec2} + */ +proto.getDelta = function () { + return this.touch ? this.touch.getDelta() : cc.v2(); +}; - /** - * !#en Returns the Y axis delta distance from the previous location to current location. - * !#zh 获取触点距离上一次事件移动的 y 轴距离。 - * @method getDeltaY - * @return {Number} - */ - getDeltaY: function () { - return this.touch ? this.touch.getDelta().y : 0; - }, +/** + * !#en Returns the X axis delta distance from the previous location to current location. + * !#zh 获取触点距离上一次事件移动的 x 轴距离。 + * @method getDeltaX + * @return {Number} + */ +proto.getDeltaX = function () { + return this.touch ? this.touch.getDelta().x : 0; +}, - /** - * !#en Returns location X axis data. - * !#zh 获取当前触点 X 轴位置。 - * @method getLocationX - * @returns {Number} - */ - getLocationX: function () { - return this.touch ? this.touch.getLocationX() : 0; - }, +/** + * !#en Returns the Y axis delta distance from the previous location to current location. + * !#zh 获取触点距离上一次事件移动的 y 轴距离。 + * @method getDeltaY + * @return {Number} + */ +proto.getDeltaY = function () { + return this.touch ? this.touch.getDelta().y : 0; +}; - /** - * !#en Returns location Y axis data. - * !#zh 获取当前触点 Y 轴位置。 - * @method getLocationY - * @returns {Number} - */ - getLocationY: function () { - return this.touch ? this.touch.getLocationY() : 0; - } -}); +/** + * !#en Returns location X axis data. + * !#zh 获取当前触点 X 轴位置。 + * @method getLocationX + * @returns {Number} + */ +proto.getLocationX = function () { + return this.touch ? this.touch.getLocationX() : 0; +}; + +/** + * !#en Returns location Y axis data. + * !#zh 获取当前触点 Y 轴位置。 + * @method getLocationY + * @returns {Number} + */ +proto.getLocationY = function () { + return this.touch ? this.touch.getLocationY() : 0; +}; /** * !#en The maximum touch numbers diff --git a/cocos2d/core/event/event-target.js b/cocos2d/core/event/event-target.js index 936a8efde1..085b44a069 100644 --- a/cocos2d/core/event/event-target.js +++ b/cocos2d/core/event/event-target.js @@ -116,7 +116,7 @@ var _doDispatchEvent = function (owner, event) { * * @class EventTarget */ -var EventTarget = function () { +function EventTarget () { /* * @property _capturingListeners * @type {EventListeners} @@ -132,261 +132,261 @@ var EventTarget = function () { * @private */ this._bubblingListeners = null; +} + +var proto = EventTarget.prototype; + +/** + * !#en Checks whether the EventTarget object has any callback registered for a specific type of event. + * !#zh 检查事件目标对象是否有为特定类型的事件注册的回调。 + * @param {String} type - The type of event. + * @param {Boolean} checkCapture - Check for capturing or bubbling phase, check bubbling phase by default. + * @return {Boolean} True if a callback of the specified type is registered in specified phase; false otherwise. + */ +proto.hasEventListener = function (type, checkCapture) { + if (checkCapture && this._capturingListeners && this._capturingListeners.has(type)) + return true; + if (!checkCapture && this._bubblingListeners && this._bubblingListeners.has(type)) + return true; + return false; }; -JS.mixin(EventTarget.prototype, { - - /** - * !#en Checks whether the EventTarget object has any callback registered for a specific type of event. - * !#zh 检查事件目标对象是否有为特定类型的事件注册的回调。 - * @param {String} type - The type of event. - * @param {Boolean} checkCapture - Check for capturing or bubbling phase, check bubbling phase by default. - * @return {Boolean} True if a callback of the specified type is registered in specified phase; false otherwise. - */ - hasEventListener: function (type, checkCapture) { - if (checkCapture && this._capturingListeners && this._capturingListeners.has(type)) - return true; - if (!checkCapture && this._bubblingListeners && this._bubblingListeners.has(type)) - return true; - return false; - }, - - /** - * !#en - * Register an callback of a specific event type on the EventTarget. - * !#zh - * 注册事件目标的特定事件类型回调。 - * - * @method on - * @param {String} type - A string representing the event type to listen for. - * @param {Function} callback - The callback that will be invoked when the event is dispatched. - * The callback is ignored if it is a duplicate (the callbacks are unique). - * @param {Event} callback.param event - * @param {Object} [target] - The target to invoke the callback, can be null - * @param {Boolean} [useCapture=false] - When set to true, the capture argument prevents callback - * from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. - * When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE. - * Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET. - * @return {Function} - Just returns the incoming callback so you can save the anonymous function easier. - * @example - * node.on(cc.Node.EventType.TOUCH_END, function (event) { - * cc.log("this is callback"); - * }, node); - */ - on: function (type, callback, target, useCapture) { - // Accept also patameters like: (type, callback, useCapture) - if (typeof target === 'boolean') { - useCapture = target; - target = undefined; - } - else useCapture = !!useCapture; - if (!callback) { - cc.errorID(6800); - return; - } - var listeners = null; - if (useCapture) { - listeners = this._capturingListeners = this._capturingListeners || new EventListeners(); - } - else { - listeners = this._bubblingListeners = this._bubblingListeners || new EventListeners(); - } - if ( ! listeners.has(type, callback, target) ) { - listeners.add(type, callback, target); - - if (target && target.__eventTargets) - target.__eventTargets.push(this); - } - return callback; - }, - - /** - * !#en - * Removes the callback previously registered with the same type, callback, target and or useCapture. - * !#zh - * 删除之前与同类型,回调,目标或 useCapture 注册的回调。 - * - * @method off - * @param {String} type - A string representing the event type being removed. - * @param {Function} callback - The callback to remove. - * @param {Object} [target] - The target to invoke the callback, if it's not given, only callback without target will be removed - * @param {Boolean} [useCapture=false] - Specifies whether the callback being removed was registered as a capturing callback or not. - * If not specified, useCapture defaults to false. If a callback was registered twice, - * one with capture and one without, each must be removed separately. Removal of a capturing callback - * does not affect a non-capturing version of the same listener, and vice versa. - * @example - * // register touchEnd eventListener - * var touchEnd = node.on(cc.Node.EventType.TOUCH_END, function (event) { - * cc.log("this is callback"); - * }, node); - * // remove touchEnd eventListener - * node.off(cc.Node.EventType.TOUCH_END, touchEnd, node); - */ - off: function (type, callback, target, useCapture) { - // Accept also patameters like: (type, callback, useCapture) - if (typeof target === 'boolean') { - useCapture = target; - target = undefined; - } - else useCapture = !!useCapture; - if (!callback) { - return; - } - var listeners = useCapture ? this._capturingListeners : this._bubblingListeners; - if (listeners) { - listeners.remove(type, callback, target); - - if (target && target.__eventTargets) { - fastRemove(target.__eventTargets, this); - } - } - }, - - /** - * !#en Removes all callbacks previously registered with the same target (passed as parameter). - * This is not for removing all listeners in the current event target, - * and this is not for removing all listeners the target parameter have registered. - * It's only for removing all listeners (callback and target couple) registered on the current event target by the target parameter. - * !#zh 在当前 EventTarget 上删除指定目标(target 参数)注册的所有事件监听器。 - * 这个函数无法删除当前 EventTarget 的所有事件监听器,也无法删除 target 参数所注册的所有事件监听器。 - * 这个函数只能删除 target 参数在当前 EventTarget 上注册的所有事件监听器。 - * @method targetOff - * @param {Object} target - The target to be searched for all related listeners - */ - targetOff: function (target) { - if (this._capturingListeners) { - this._capturingListeners.removeAll(target); - } - if (this._bubblingListeners) { - this._bubblingListeners.removeAll(target); - } - }, - - /** - * !#en - * Register an callback of a specific event type on the EventTarget, - * the callback will remove itself after the first time it is triggered. - * !#zh - * 注册事件目标的特定事件类型回调,回调会在第一时间被触发后删除自身。 - * - * @method once - * @param {String} type - A string representing the event type to listen for. - * @param {Function} callback - The callback that will be invoked when the event is dispatched. - * The callback is ignored if it is a duplicate (the callbacks are unique). - * @param {Event} callback.param event - * @param {Object} [target] - The target to invoke the callback, can be null - * @param {Boolean} [useCapture=false] - When set to true, the capture argument prevents callback - * from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. - * When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE. - * Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET. - * @example - * node.once(cc.Node.EventType.TOUCH_END, function (event) { - * cc.log("this is callback"); - * }, node); - */ - once: function (type, callback, target, useCapture) { - var self = this; - var cb = function (event) { - self.off(type, cb, target, useCapture); - callback.call(this, event); - }; - this.on(type, cb, target, useCapture); - }, - - /** - * !#en - * Dispatches an event into the event flow. - * The event target is the EventTarget object upon which the dispatchEvent() method is called. - * !#zh 分发事件到事件流中。 - * - * @method dispatchEvent - * @param {Event} event - The Event object that is dispatched into the event flow - */ - dispatchEvent: function (event) { - _doDispatchEvent(this, event); - cachedArray.length = 0; - }, - - /** - * !#en - * Send an event to this object directly, this method will not propagate the event to any other objects. - * The event will be created from the supplied message, you can get the "detail" argument from event.detail. - * !#zh - * 该对象直接发送事件, 这种方法不会对事件传播到任何其他对象。 - * - * @method emit - * @param {String} message - the message to send - * @param {*} [detail] - whatever argument the message needs - */ - emit: function (message, detail) { - if (CC_DEV && typeof message !== 'string') { - cc.errorID(6801); - return; - } - //don't emit event when listeners are not exists. - var caplisteners = this._capturingListeners && this._capturingListeners._callbackTable[message]; - var bublisteners = this._bubblingListeners && this._bubblingListeners._callbackTable[message]; - if ((!caplisteners || caplisteners.length === 0) && (!bublisteners || bublisteners.length === 0)) { - return; - } - - var event = cc.Event.EventCustom.get(message); - event.detail = detail; - - // Event.AT_TARGET - event.eventPhase = 2; - event.target = event.currentTarget = this; - if (caplisteners) { - this._capturingListeners.invoke(event); - } - if (bublisteners && !event._propagationImmediateStopped) { - this._bubblingListeners.invoke(event); - } - cc.Event.EventCustom.put(event); - }, - - /* - * Get whether the target is active for events. - * The name is for avoiding conflict with user defined functions. - * - * Subclasses can override this method to make event target active or inactive. - * @method _isTargetActive - * @param {String} type - the event type - * @return {Boolean} - A boolean value indicates the event target is active or not - */ - _isTargetActive: function (type) { - return true; - }, - - /* - * Get all the targets listening to the supplied type of event in the target's capturing phase. - * The capturing phase comprises the journey from the root to the last node BEFORE the event target's node. - * The result should save in the array parameter, and MUST SORT from child nodes to parent nodes. - * - * Subclasses can override this method to make event propagable. - * @method _getCapturingTargets - * @param {String} type - the event type - * @param {Array} array - the array to receive targets - * @example {@link utils/api/engine/docs/cocos2d/core/event/_getCapturingTargets.js} - */ - _getCapturingTargets: function (type, array) { - - }, - - /* - * Get all the targets listening to the supplied type of event in the target's bubbling phase. - * The bubbling phase comprises any SUBSEQUENT nodes encountered on the return trip to the root of the tree. - * The result should save in the array parameter, and MUST SORT from child nodes to parent nodes. - * - * Subclasses can override this method to make event propagable. - * @method _getBubblingTargets - * @param {String} type - the event type - * @param {Array} array - the array to receive targets - */ - _getBubblingTargets: function (type, array) { - // Object can override this method to make event propagable. +/** + * !#en + * Register an callback of a specific event type on the EventTarget. + * !#zh + * 注册事件目标的特定事件类型回调。 + * + * @method on + * @param {String} type - A string representing the event type to listen for. + * @param {Function} callback - The callback that will be invoked when the event is dispatched. + * The callback is ignored if it is a duplicate (the callbacks are unique). + * @param {Event} callback.param event + * @param {Object} [target] - The target to invoke the callback, can be null + * @param {Boolean} [useCapture=false] - When set to true, the capture argument prevents callback + * from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. + * When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE. + * Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET. + * @return {Function} - Just returns the incoming callback so you can save the anonymous function easier. + * @example + * node.on(cc.Node.EventType.TOUCH_END, function (event) { + * cc.log("this is callback"); + * }, node); + */ +proto.on = function (type, callback, target, useCapture) { + // Accept also patameters like: (type, callback, useCapture) + if (typeof target === 'boolean') { + useCapture = target; + target = undefined; } -}); + else useCapture = !!useCapture; + if (!callback) { + cc.errorID(6800); + return; + } + var listeners = null; + if (useCapture) { + listeners = this._capturingListeners = this._capturingListeners || new EventListeners(); + } + else { + listeners = this._bubblingListeners = this._bubblingListeners || new EventListeners(); + } + if ( ! listeners.has(type, callback, target) ) { + listeners.add(type, callback, target); + + if (target && target.__eventTargets) + target.__eventTargets.push(this); + } + return callback; +}; + +/** + * !#en + * Removes the callback previously registered with the same type, callback, target and or useCapture. + * !#zh + * 删除之前与同类型,回调,目标或 useCapture 注册的回调。 + * + * @method off + * @param {String} type - A string representing the event type being removed. + * @param {Function} callback - The callback to remove. + * @param {Object} [target] - The target to invoke the callback, if it's not given, only callback without target will be removed + * @param {Boolean} [useCapture=false] - Specifies whether the callback being removed was registered as a capturing callback or not. + * If not specified, useCapture defaults to false. If a callback was registered twice, + * one with capture and one without, each must be removed separately. Removal of a capturing callback + * does not affect a non-capturing version of the same listener, and vice versa. + * @example + * // register touchEnd eventListener + * var touchEnd = node.on(cc.Node.EventType.TOUCH_END, function (event) { + * cc.log("this is callback"); + * }, node); + * // remove touchEnd eventListener + * node.off(cc.Node.EventType.TOUCH_END, touchEnd, node); + */ +proto.off = function (type, callback, target, useCapture) { + // Accept also patameters like: (type, callback, useCapture) + if (typeof target === 'boolean') { + useCapture = target; + target = undefined; + } + else useCapture = !!useCapture; + if (!callback) { + return; + } + var listeners = useCapture ? this._capturingListeners : this._bubblingListeners; + if (listeners) { + listeners.remove(type, callback, target); + + if (target && target.__eventTargets) { + fastRemove(target.__eventTargets, this); + } + } +}; + +/** + * !#en Removes all callbacks previously registered with the same target (passed as parameter). + * This is not for removing all listeners in the current event target, + * and this is not for removing all listeners the target parameter have registered. + * It's only for removing all listeners (callback and target couple) registered on the current event target by the target parameter. + * !#zh 在当前 EventTarget 上删除指定目标(target 参数)注册的所有事件监听器。 + * 这个函数无法删除当前 EventTarget 的所有事件监听器,也无法删除 target 参数所注册的所有事件监听器。 + * 这个函数只能删除 target 参数在当前 EventTarget 上注册的所有事件监听器。 + * @method targetOff + * @param {Object} target - The target to be searched for all related listeners + */ +proto.targetOff = function (target) { + if (this._capturingListeners) { + this._capturingListeners.removeAll(target); + } + if (this._bubblingListeners) { + this._bubblingListeners.removeAll(target); + } +}; + +/** + * !#en + * Register an callback of a specific event type on the EventTarget, + * the callback will remove itself after the first time it is triggered. + * !#zh + * 注册事件目标的特定事件类型回调,回调会在第一时间被触发后删除自身。 + * + * @method once + * @param {String} type - A string representing the event type to listen for. + * @param {Function} callback - The callback that will be invoked when the event is dispatched. + * The callback is ignored if it is a duplicate (the callbacks are unique). + * @param {Event} callback.param event + * @param {Object} [target] - The target to invoke the callback, can be null + * @param {Boolean} [useCapture=false] - When set to true, the capture argument prevents callback + * from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE. + * When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE. + * Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET. + * @example + * node.once(cc.Node.EventType.TOUCH_END, function (event) { + * cc.log("this is callback"); + * }, node); + */ +proto.once = function (type, callback, target, useCapture) { + var self = this; + var cb = function (event) { + self.off(type, cb, target, useCapture); + callback.call(this, event); + }; + this.on(type, cb, target, useCapture); +}; + +/** + * !#en + * Dispatches an event into the event flow. + * The event target is the EventTarget object upon which the dispatchEvent() method is called. + * !#zh 分发事件到事件流中。 + * + * @method dispatchEvent + * @param {Event} event - The Event object that is dispatched into the event flow + */ +proto.dispatchEvent = function (event) { + _doDispatchEvent(this, event); + cachedArray.length = 0; +}; + +/** + * !#en + * Send an event to this object directly, this method will not propagate the event to any other objects. + * The event will be created from the supplied message, you can get the "detail" argument from event.detail. + * !#zh + * 该对象直接发送事件, 这种方法不会对事件传播到任何其他对象。 + * + * @method emit + * @param {String} message - the message to send + * @param {*} [detail] - whatever argument the message needs + */ +proto.emit = function (message, detail) { + if (CC_DEV && typeof message !== 'string') { + cc.errorID(6801); + return; + } + //don't emit event when listeners are not exists. + var caplisteners = this._capturingListeners && this._capturingListeners._callbackTable[message]; + var bublisteners = this._bubblingListeners && this._bubblingListeners._callbackTable[message]; + if ((!caplisteners || caplisteners.length === 0) && (!bublisteners || bublisteners.length === 0)) { + return; + } + + var event = cc.Event.EventCustom.get(message); + event.detail = detail; + + // Event.AT_TARGET + event.eventPhase = 2; + event.target = event.currentTarget = this; + if (caplisteners) { + this._capturingListeners.invoke(event); + } + if (bublisteners && !event._propagationImmediateStopped) { + this._bubblingListeners.invoke(event); + } + cc.Event.EventCustom.put(event); +}; + +/* + * Get whether the target is active for events. + * The name is for avoiding conflict with user defined functions. + * + * Subclasses can override this method to make event target active or inactive. + * @method _isTargetActive + * @param {String} type - the event type + * @return {Boolean} - A boolean value indicates the event target is active or not + */ +proto._isTargetActive = function (type) { + return true; +}; + +/* + * Get all the targets listening to the supplied type of event in the target's capturing phase. + * The capturing phase comprises the journey from the root to the last node BEFORE the event target's node. + * The result should save in the array parameter, and MUST SORT from child nodes to parent nodes. + * + * Subclasses can override this method to make event propagable. + * @method _getCapturingTargets + * @param {String} type - the event type + * @param {Array} array - the array to receive targets + * @example {@link utils/api/engine/docs/cocos2d/core/event/_getCapturingTargets.js} + */ +proto._getCapturingTargets = function (type, array) { + +}; + +/* + * Get all the targets listening to the supplied type of event in the target's bubbling phase. + * The bubbling phase comprises any SUBSEQUENT nodes encountered on the return trip to the root of the tree. + * The result should save in the array parameter, and MUST SORT from child nodes to parent nodes. + * + * Subclasses can override this method to make event propagable. + * @method _getBubblingTargets + * @param {String} type - the event type + * @param {Array} array - the array to receive targets + */ +proto._getBubblingTargets = function (type, array) { + // Object can override this method to make event propagable. +}; + // Improve performance of function call (avoid using EventTarget.prototype.on.call) EventTarget.prototype._EventTargetOn = EventTarget.prototype.on; EventTarget.prototype._EventTargetOnce = EventTarget.prototype.once; diff --git a/cocos2d/core/event/event.js b/cocos2d/core/event/event.js index 59e30e91e1..5e74fd2ca0 100644 --- a/cocos2d/core/event/event.js +++ b/cocos2d/core/event/event.js @@ -294,37 +294,37 @@ var EventCustom = function (type, bubbles) { }; JS.extend(EventCustom, cc.Event); -JS.mixin(EventCustom.prototype, { - reset: EventCustom, - /** - * !#en Sets user data - * !#zh 设置用户数据 - * @method setUserData - * @param {*} data - */ - setUserData: function (data) { - this.detail = data; - }, +EventCustom.prototype.reset = EventCustom; - /** - * !#en Gets user data - * !#zh 获取用户数据 - * @method getUserData - * @returns {*} - */ - getUserData: function () { - return this.detail; - }, +/** + * !#en Sets user data + * !#zh 设置用户数据 + * @method setUserData + * @param {*} data + */ +EventCustom.prototype.setUserData = function (data) { + this.detail = data; +}; + +/** + * !#en Gets user data + * !#zh 获取用户数据 + * @method getUserData + * @returns {*} + */ +EventCustom.prototype.getUserData = function () { + return this.detail; +}; + +/** + * !#en Gets event name + * !#zh 获取事件名称 + * @method getEventName + * @returns {String} + */ +EventCustom.prototype.getEventName = cc.Event.prototype.getType; - /** - * !#en Gets event name - * !#zh 获取事件名称 - * @method getEventName - * @returns {String} - */ - getEventName: cc.Event.prototype.getType -}); var _eventPool = []; var MAX_POOL_SIZE = 10; diff --git a/cocos2d/core/graphics/graphics-canvas-cmd.js b/cocos2d/core/graphics/graphics-canvas-cmd.js index 2bfaf7681d..ad06547ad2 100644 --- a/cocos2d/core/graphics/graphics-canvas-cmd.js +++ b/cocos2d/core/graphics/graphics-canvas-cmd.js @@ -93,128 +93,127 @@ _p.rendering = function (ctx, scaleX, scaleY) { }; // draw api -Js.mixin(_p, { - setStrokeColor: function (v) { - var strokeStyle = 'rgba(' + (0 | v.r) + ',' + (0 | v.g) + ',' + (0 | v.b) + ',' + v.a / 255 + ')'; - this.cmds.push(['strokeStyle', strokeStyle]); - this.style.strokeStyle = strokeStyle; - }, - setFillColor: function (v) { - var fillStyle = 'rgba(' + (0 | v.r) + ',' + (0 | v.g) + ',' + (0 | v.b) + ',' + v.a / 255 + ')'; - this.cmds.push(['fillStyle', fillStyle]); - this.style.fillStyle = fillStyle; - }, +_p.setStrokeColor = function (v) { + var strokeStyle = 'rgba(' + (0 | v.r) + ',' + (0 | v.g) + ',' + (0 | v.b) + ',' + v.a / 255 + ')'; + this.cmds.push(['strokeStyle', strokeStyle]); + this.style.strokeStyle = strokeStyle; +}; - setLineWidth: function (v) { - this.cmds.push(['lineWidth', v]); - this.style.lineWidth = v; - }, +_p.setFillColor = function (v) { + var fillStyle = 'rgba(' + (0 | v.r) + ',' + (0 | v.g) + ',' + (0 | v.b) + ',' + v.a / 255 + ')'; + this.cmds.push(['fillStyle', fillStyle]); + this.style.fillStyle = fillStyle; +}; - setLineCap: function (v) { - var lineCap = 'butt'; - if (v === LineCap.BUTT) { - lineCap = 'butt'; - } - else if (v === LineCap.ROUND) { - lineCap = 'round'; - } - else if (v === LineCap.SQUARE) { - lineCap = 'square'; - } - this.cmds.push(['lineCap', lineCap]); - this.style.lineCap = lineCap; - }, +_p.setLineWidth = function (v) { + this.cmds.push(['lineWidth', v]); + this.style.lineWidth = v; +}; - setLineJoin: function (v) { - var lineJoin = 'bevel'; - if (v === LineJoin.BEVEL) { - lineJoin = 'bevel'; - } - else if (v === LineJoin.ROUND) { - lineJoin = 'round'; - } - else if (v === LineJoin.MITER) { - lineJoin = 'miter'; - } - - this.cmds.push(['lineJoin', lineJoin]); - this.style.lineJoin = lineJoin; - }, - - setMiterLimit: function (v) { - this.cmds.push(['miterLimit', v]); - this.style.miterLimit = v; - }, - - // draw functions - - beginPath: function () { - }, - - moveTo: function (x, y) { - this.cmds.push(['moveTo', [x, y]]); - }, - - lineTo: function (x, y) { - this.cmds.push(['lineTo', [x, y]]); - }, - - bezierCurveTo: function (c1x, c1y, c2x, c2y, x, y) { - this.cmds.push(['bezierCurveTo', [c1x, c1y, c2x, c2y, x, y]]); - }, - - quadraticCurveTo: function (cx, cy, x, y) { - this.cmds.push(['quadraticCurveTo', [cx, cy, x, y]]); - }, - - arc: function (cx, cy, r, startAngle, endAngle, counterclockwise) { - Helper.arc(this, cx, cy, r, startAngle, endAngle, counterclockwise); - }, - - ellipse: function (cx, cy, rx, ry) { - Helper.ellipse(this, cx, cy, rx, ry); - }, - - circle: function (cx, cy, r) { - Helper.ellipse(this, cx, cy, r, r); - }, - - rect: function (x, y, w, h) { - this.moveTo(x, y); - this.lineTo(x+w, y); - this.lineTo(x+w, y+h); - this.lineTo(x, y+h); - this.close(); - }, - - roundRect: function (x, y, w, h, r) { - Helper.roundRect(this, x, y, w, h, r); - }, - - fillRect: function (x, y, w, h) { - this.cmds.push(['fillRect', [x, y, w, h]]); - this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); - }, - - close: function () { - this.cmds.push(['closePath', []]); - }, - - stroke: function () { - this.cmds.push(['stroke', []]); - this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); - }, - - fill: function () { - this.cmds.push(['fill', []]); - this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); - }, - - clear: function () { - this.cmds.length = 0; - this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); +_p.setLineCap = function (v) { + var lineCap = 'butt'; + if (v === LineCap.BUTT) { + lineCap = 'butt'; } -}); + else if (v === LineCap.ROUND) { + lineCap = 'round'; + } + else if (v === LineCap.SQUARE) { + lineCap = 'square'; + } + this.cmds.push(['lineCap', lineCap]); + this.style.lineCap = lineCap; +}; + +_p.setLineJoin = function (v) { + var lineJoin = 'bevel'; + if (v === LineJoin.BEVEL) { + lineJoin = 'bevel'; + } + else if (v === LineJoin.ROUND) { + lineJoin = 'round'; + } + else if (v === LineJoin.MITER) { + lineJoin = 'miter'; + } + + this.cmds.push(['lineJoin', lineJoin]); + this.style.lineJoin = lineJoin; +}; + +_p.setMiterLimit = function (v) { + this.cmds.push(['miterLimit', v]); + this.style.miterLimit = v; +}; + +// draw functions + +_p.beginPath = function () { +}; + +_p.moveTo = function (x, y) { + this.cmds.push(['moveTo', [x, y]]); +}; + +_p.lineTo = function (x, y) { + this.cmds.push(['lineTo', [x, y]]); +}; + +_p.bezierCurveTo = function (c1x, c1y, c2x, c2y, x, y) { + this.cmds.push(['bezierCurveTo', [c1x, c1y, c2x, c2y, x, y]]); +}; + +_p.quadraticCurveTo = function (cx, cy, x, y) { + this.cmds.push(['quadraticCurveTo', [cx, cy, x, y]]); +}; + +_p.arc = function (cx, cy, r, startAngle, endAngle, counterclockwise) { + Helper.arc(this, cx, cy, r, startAngle, endAngle, counterclockwise); +}; + +_p.ellipse = function (cx, cy, rx, ry) { + Helper.ellipse(this, cx, cy, rx, ry); +}; + +_p.circle = function (cx, cy, r) { + Helper.ellipse(this, cx, cy, r, r); +}; + +_p.rect = function (x, y, w, h) { + this.moveTo(x, y); + this.lineTo(x+w, y); + this.lineTo(x+w, y+h); + this.lineTo(x, y+h); + this.close(); +}; + +_p.roundRect = function (x, y, w, h, r) { + Helper.roundRect(this, x, y, w, h, r); +}; + +_p.fillRect = function (x, y, w, h) { + this.cmds.push(['fillRect', [x, y, w, h]]); + this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); +}; + +_p.close = function () { + this.cmds.push(['closePath', []]); +}; + +_p.stroke = function () { + this.cmds.push(['stroke', []]); + this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); +}; + +_p.fill = function () { + this.cmds.push(['fill', []]); + this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); +}; + +_p.clear = function () { + this.cmds.length = 0; + this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty); +}; module.exports = CanvasRenderCmd; diff --git a/cocos2d/core/graphics/graphics-node.js b/cocos2d/core/graphics/graphics-node.js index 0451ca7199..85a543f956 100644 --- a/cocos2d/core/graphics/graphics-node.js +++ b/cocos2d/core/graphics/graphics-node.js @@ -58,124 +58,123 @@ var GraphicsNode = _ccsg.Node.extend({ var _p = GraphicsNode.prototype; // draw api -Js.mixin(_p, { - // properties - _strokeColor: null, - _fillColor: null, - _lineWidth: 1, +// properties +_p._strokeColor = null; +_p._fillColor = null; - _lineCap: LineCap.BUTT, - _lineJoin: LineJoin.MITER, +_p._lineWidth = 1; - _miterLimit: 10, +_p._lineCap = LineCap.BUTT; +_p._lineJoin = LineJoin.MITER; - setStrokeColor: function (v) { - this._strokeColor = v; - this._renderCmd.setStrokeColor(v); - }, - getStrokeColor: function () { - return this._strokeColor; - }, +_p._miterLimit = 10; - setFillColor: function (v) { - this._fillColor = v; - this._renderCmd.setFillColor(v); - }, - getFillColor: function () { - return this._fillColor; - }, +_p.setStrokeColor = function (v) { + this._strokeColor = v; + this._renderCmd.setStrokeColor(v); +}; +_p.getStrokeColor = function () { + return this._strokeColor; +}; - setLineWidth: function (v) { - this._lineWidth = v; - this._renderCmd.setLineWidth(v); - }, - getLineWidth: function () { - return this._lineWidth; - }, +_p.setFillColor = function (v) { + this._fillColor = v; + this._renderCmd.setFillColor(v); +}; +_p.getFillColor = function () { + return this._fillColor; +}; - setLineCap: function (v) { - this._lineCap = v; - this._renderCmd.setLineCap(v); - }, - getLineCap: function () { - return this._lineCap; - }, +_p.setLineWidth = function (v) { + this._lineWidth = v; + this._renderCmd.setLineWidth(v); +}; +_p.getLineWidth = function () { + return this._lineWidth; +}; - setLineJoin: function (v) { - this._lineJoin = v; - this._renderCmd.setLineJoin(v); - }, - getLineJoin: function () { - return this._lineJoin; - }, +_p.setLineCap = function (v) { + this._lineCap = v; + this._renderCmd.setLineCap(v); +}; +_p.getLineCap = function () { + return this._lineCap; +}; - setMiterLimit: function (v) { - this._miterLimit = v; - this._renderCmd.setMiterLimit(v); - }, - getMiterLimit: function () { - return this._miterLimit; - }, +_p.setLineJoin = function (v) { + this._lineJoin = v; + this._renderCmd.setLineJoin(v); +}; +_p.getLineJoin = function () { + return this._lineJoin; +}; - // draw functions - - beginPath: function () { - this._renderCmd.beginPath(); - }, +_p.setMiterLimit = function (v) { + this._miterLimit = v; + this._renderCmd.setMiterLimit(v); +}; +_p.getMiterLimit = function () { + return this._miterLimit; +}; - moveTo: function (x, y) { - this._renderCmd.moveTo(x, y); - }, +// draw functions - lineTo: function (x, y) { - this._renderCmd.lineTo(x, y); - }, +_p.beginPath = function () { + this._renderCmd.beginPath(); +}; - bezierCurveTo: function (c1x, c1y, c2x, c2y, x, y) { - this._renderCmd.bezierCurveTo(c1x, c1y, c2x, c2y, x, y); - }, +_p.moveTo = function (x, y) { + this._renderCmd.moveTo(x, y); +}; - quadraticCurveTo: function (cx, cy, x, y) { - this._renderCmd.quadraticCurveTo(cx, cy, x, y); - }, +_p.lineTo = function (x, y) { + this._renderCmd.lineTo(x, y); +}; - // - arc: function (cx, cy, r, a0, a1, counterclockwise) { - this._renderCmd.arc(cx, cy, r, a0, a1, counterclockwise); - }, +_p.bezierCurveTo = function (c1x, c1y, c2x, c2y, x, y) { + this._renderCmd.bezierCurveTo(c1x, c1y, c2x, c2y, x, y); +}; - ellipse: function (cx, cy, rx, ry) { - this._renderCmd.ellipse(cx, cy, rx, ry); - }, +_p.quadraticCurveTo = function (cx, cy, x, y) { + this._renderCmd.quadraticCurveTo(cx, cy, x, y); +}; - circle: function (cx, cy, r) { - this._renderCmd.circle(cx, cy, r); - }, +// +_p.arc = function (cx, cy, r, a0, a1, counterclockwise) { + this._renderCmd.arc(cx, cy, r, a0, a1, counterclockwise); +}; - rect: function (x, y, w, h) { - this._renderCmd.rect(x, y, w, h); - }, +_p.ellipse = function (cx, cy, rx, ry) { + this._renderCmd.ellipse(cx, cy, rx, ry); +}; - roundRect: function (x, y, w, h, r) { - this._renderCmd.roundRect(x, y, w, h, r); - }, +_p.circle = function (cx, cy, r) { + this._renderCmd.circle(cx, cy, r); +}; - fillRect: function (x, y, w, h) { - this._renderCmd.fillRect(x, y, w, h); - }, +_p.rect = function (x, y, w, h) { + this._renderCmd.rect(x, y, w, h); +}; - close: function () { - this._renderCmd.close(); - }, +_p.roundRect = function (x, y, w, h, r) { + this._renderCmd.roundRect(x, y, w, h, r); +}; - stroke: function () { - this._renderCmd.stroke(); - }, +_p.fillRect = function (x, y, w, h) { + this._renderCmd.fillRect(x, y, w, h); +}; - fill: function () { - this._renderCmd.fill(); - } -}); +_p.close = function () { + this._renderCmd.close(); +}; + +_p.stroke = function () { + this._renderCmd.stroke(); +}; + +_p.fill = function () { + this._renderCmd.fill(); +}; module.exports = GraphicsNode; diff --git a/cocos2d/core/graphics/graphics-webgl-cmd.js b/cocos2d/core/graphics/graphics-webgl-cmd.js index 2ad45befb2..ebe873c325 100644 --- a/cocos2d/core/graphics/graphics-webgl-cmd.js +++ b/cocos2d/core/graphics/graphics-webgl-cmd.js @@ -76,16 +76,14 @@ function Point (x, y) { } Js.extend(Point, Vec2); -Js.mixin(Point.prototype, { - reset: function () { - this.dx = 0; - this.dy = 0; - this.dmx = 0; - this.dmy = 0; - this.flags = 0; - this.len = 0; - } -}); +Point.prototype.reset = function () { + this.dx = 0; + this.dy = 0; + this.dmx = 0; + this.dmy = 0; + this.flags = 0; + this.len = 0; +}; // Path function Path () { @@ -148,915 +146,911 @@ WebGLRenderCmd.prototype.constructor = WebGLRenderCmd; var _p = WebGLRenderCmd.prototype; // draw api -Js.mixin(_p, { - _tessTol: 0.25, // Tessellation Tolerance - _distTol: 0.01, - lineWidth: 1, +_p._tessTol = 0.25; // Tessellation Tolerance +_p._distTol = 0.01; - lineCap: LineCap.BUTT, - lineJoin: LineJoin.MITER, +_p.lineWidth = 1; - miterLimit: 10, +_p.lineCap = LineCap.BUTT; +_p.lineJoin = LineJoin.MITER; - beginPath: function () { +_p.miterLimit = 10; + +_p.beginPath = function () { + this._pathOffset = this._pathLength; +}; + +_p.moveTo = function (x, y) { + if (this._updatePathOffset) { this._pathOffset = this._pathLength; - }, - - moveTo: function (x, y) { - if (this._updatePathOffset) { - this._pathOffset = this._pathLength; - this._updatePathOffset = false; - } - - this._addPath(); - this._addPoint(x, y, PointFlags.PT_CORNER); - - this._commandx = x; - this._commandy = y; - }, - - lineTo: function (x, y) { - this._addPoint(x, y, PointFlags.PT_CORNER); - - this._commandx = x; - this._commandy = y; - }, - - bezierCurveTo: function (c1x, c1y, c2x, c2y, x, y) { - var path = this._curPath; - var last = path.points[path.points.length - 1]; - - if (last.x === c1x && last.y === c1y && c2x === x && c2y === y) { - this.lineTo(x, y); - return; - } - - this._tesselateBezier(last.x, last.y, c1x, c1y, c2x, c2y, x, y, 0, PointFlags.PT_CORNER); - - this._commandx = x; - this._commandy = y; - }, - - quadraticCurveTo: function (cx, cy, x, y) { - var x0 = this._commandx; - var y0 = this._commandy; - this.bezierCurveTo(x0 + 2.0 / 3.0 * (cx - x0), y0 + 2.0 / 3.0 * (cy - y0), x + 2.0 / 3.0 * (cx - x), y + 2.0 / 3.0 * (cy - y), x, y); - }, - - // - arc: function (cx, cy, r, startAngle, endAngle, counterclockwise) { - Helper.arc(this, cx, cy, r, startAngle, endAngle, counterclockwise); - }, - - ellipse: function (cx, cy, rx, ry) { - Helper.ellipse(this, cx, cy, rx, ry); - this._curPath.complex = false; - }, - - circle: function (cx, cy, r) { - Helper.ellipse(this, cx, cy, r, r); - this._curPath.complex = false; - }, - - rect: function (x, y, w, h) { - this.moveTo(x, y); - this.lineTo(x, y + h); - this.lineTo(x + w, y + h); - this.lineTo(x + w, y); - this.close(); - this._curPath.complex = false; - }, - - roundRect: function (x, y, w, h, r) { - Helper.roundRect(this, x, y, w, h, r); - this._curPath.complex = false; - }, - - fillRect: function (x, y, w, h) { - this.rect(x, y, w, h); - - this.fill(); - }, - - close: function () { - this._curPath.closed = true; - }, - - stroke: function () { - this._flattenPaths(); - - this._expandStroke(); - - this._vertsDirty = true; - this._updatePathOffset = true; - }, - - fill: function () { - // this._flattenPaths(); - - this._expandFill(); - - this._vertsDirty = true; - this._updatePathOffset = true; - this._filling = false; + this._updatePathOffset = false; } -}); + + this._addPath(); + this._addPoint(x, y, PointFlags.PT_CORNER); + + this._commandx = x; + this._commandy = y; +}; + +_p.lineTo = function (x, y) { + this._addPoint(x, y, PointFlags.PT_CORNER); + + this._commandx = x; + this._commandy = y; +}; + +_p.bezierCurveTo = function (c1x, c1y, c2x, c2y, x, y) { + var path = this._curPath; + var last = path.points[path.points.length - 1]; + + if (last.x === c1x && last.y === c1y && c2x === x && c2y === y) { + this.lineTo(x, y); + return; + } + + this._tesselateBezier(last.x, last.y, c1x, c1y, c2x, c2y, x, y, 0, PointFlags.PT_CORNER); + + this._commandx = x; + this._commandy = y; +}; + +_p.quadraticCurveTo = function (cx, cy, x, y) { + var x0 = this._commandx; + var y0 = this._commandy; + this.bezierCurveTo(x0 + 2.0 / 3.0 * (cx - x0), y0 + 2.0 / 3.0 * (cy - y0), x + 2.0 / 3.0 * (cx - x), y + 2.0 / 3.0 * (cy - y), x, y); +}; + +// +_p.arc = function (cx, cy, r, startAngle, endAngle, counterclockwise) { + Helper.arc(this, cx, cy, r, startAngle, endAngle, counterclockwise); +}; + +_p.ellipse = function (cx, cy, rx, ry) { + Helper.ellipse(this, cx, cy, rx, ry); + this._curPath.complex = false; +}; + +_p.circle = function (cx, cy, r) { + Helper.ellipse(this, cx, cy, r, r); + this._curPath.complex = false; +}; + +_p.rect = function (x, y, w, h) { + this.moveTo(x, y); + this.lineTo(x, y + h); + this.lineTo(x + w, y + h); + this.lineTo(x + w, y); + this.close(); + this._curPath.complex = false; +}; + +_p.roundRect = function (x, y, w, h, r) { + Helper.roundRect(this, x, y, w, h, r); + this._curPath.complex = false; +}; + +_p.fillRect = function (x, y, w, h) { + this.rect(x, y, w, h); + + this.fill(); +}; + +_p.close = function () { + this._curPath.closed = true; +}; + +_p.stroke = function () { + this._flattenPaths(); + + this._expandStroke(); + + this._vertsDirty = true; + this._updatePathOffset = true; +}; + +_p.fill = function () { + // this._flattenPaths(); + + this._expandFill(); + + this._vertsDirty = true; + this._updatePathOffset = true; + this._filling = false; +}; // inner properties -Js.mixin(_p, { - _strokeColor: null, - _fillColor: null, - setStrokeColor: function (c) { - this._strokeColor = c; - }, +_p._strokeColor = null; +_p._fillColor = null; - getStrokeColor: function () { - return this._strokeColor; - }, +_p.setStrokeColor = function (c) { + this._strokeColor = c; +}; - setFillColor: function (c) { - this._fillColor = c; - }, +_p.getStrokeColor = function () { + return this._strokeColor; +}; - getFillColor: function () { - return this._fillColor; - }, +_p.setFillColor = function (c) { + this._fillColor = c; +}; - setLineWidth: function (v) { - this.lineWidth = v; - }, +_p.getFillColor = function () { + return this._fillColor; +}; - setLineJoin: function (v) { - this.lineJoin = v; - }, +_p.setLineWidth = function (v) { + this.lineWidth = v; +}; - setLineCap: function (v) { - this.lineCap = v; - }, +_p.setLineJoin = function (v) { + this.lineJoin = v; +}; - setMiterLimit: function (v) { - this.miterLimit = v; +_p.setLineCap = function (v) { + this.lineCap = v; +}; + +_p.setMiterLimit = function (v) { + this.miterLimit = v; +}; + + +Js.getset(_p, 'strokeColor', _p.getStrokeColor, _p.setStrokeColor); +Js.getset(_p, 'fillColor', _p.getFillColor, _p.setFillColor); + +_p._render = function () { + var vertsBuffer = this._vertsBuffer; + if (!vertsBuffer || vertsBuffer.length === 0 || this._cmds.length === 0) return; + + var gl = cc._renderContext; + + gl.bindBuffer(gl.ARRAY_BUFFER, this._vertsVBO); + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesVBO); + + if (this._vertsDirty) { + gl.bufferData(gl.ARRAY_BUFFER, vertsBuffer, gl.STREAM_DRAW); + this._vertsDirty = false; } -}); -cc.defineGetterSetter(_p, 'strokeColor', _p.getStrokeColor, _p.setStrokeColor); -cc.defineGetterSetter(_p, 'fillColor', _p.getFillColor, _p.setFillColor); + if (this._indicesDirty && this._indicesBuffer) { + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer, gl.STREAM_DRAW); + this._indicesDirty = false; + } -Js.mixin(_p, { - _render: function () { - var vertsBuffer = this._vertsBuffer; - if (!vertsBuffer || vertsBuffer.length === 0 || this._cmds.length === 0) return; + if (this._vertsOffset > 65536) { + cc.warnID(2401); + } - var gl = cc._renderContext; + gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION); + gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, VERTS_BYTE_LENGTH, 0); - gl.bindBuffer(gl.ARRAY_BUFFER, this._vertsVBO); - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, this._indicesVBO); + var shader = this._shader; + var colorLocation = shader.getUniformLocationForName('color'); - if (this._vertsDirty) { - gl.bufferData(gl.ARRAY_BUFFER, vertsBuffer, gl.STREAM_DRAW); - this._vertsDirty = false; + // draw paths + var cmds = this._cmds; + for (var i = 0, l = cmds.length; i < l; i++) { + var cmd = cmds[i]; + + if (cmd.nIndices) { + var color = cmd.color; + gl.uniform4f(colorLocation, color.r / 255, color.g / 255, color.b / 255, color.a / 255); + gl.drawElements(gl.TRIANGLES, cmd.nIndices, gl.UNSIGNED_SHORT, cmd.indicesOffset * 2); + + cc.incrementGLDraws(cmd.nverts); } + } - if (this._indicesDirty && this._indicesBuffer) { - gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, this._indicesBuffer, gl.STREAM_DRAW); - this._indicesDirty = false; - } + cc.checkGLErrorDebug(); +}; - if (this._vertsOffset > 65536) { - cc.warnID(2401); - } +_p.rendering = function () { + cc.gl.blendFunc(this._blendFunc.src, this._blendFunc.dst); - gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION); - gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, VERTS_BYTE_LENGTH, 0); + var wt = this._worldTransform, mat = this._matrix.mat; + mat[0] = wt.a; + mat[4] = wt.c; + mat[12] = wt.tx; + mat[1] = wt.b; + mat[5] = wt.d; + mat[13] = wt.ty; - var shader = this._shader; - var colorLocation = shader.getUniformLocationForName('color'); + var shader = this._shader; + shader.use(); + shader._setUniformForMVPMatrixWithMat4(this._matrix); - // draw paths - var cmds = this._cmds; - for (var i = 0, l = cmds.length; i < l; i++) { - var cmd = cmds[i]; + this._render(); +}; - if (cmd.nIndices) { - var color = cmd.color; - gl.uniform4f(colorLocation, color.r / 255, color.g / 255, color.b / 255, color.a / 255); - gl.drawElements(gl.TRIANGLES, cmd.nIndices, gl.UNSIGNED_SHORT, cmd.indicesOffset * 2); +// clear +_p.clear = function (clean) { + this._vertsOffset = 0; + this._indicesOffset = 0; - cc.incrementGLDraws(cmd.nverts); - } - } + this._pathLength = 0; + this._pathOffset = 0; + this._pointsOffset = 0; - cc.checkGLErrorDebug(); - }, + this._curPath = null; - rendering: function () { - cc.gl.blendFunc(this._blendFunc.src, this._blendFunc.dst); + this._cmds.length = 0; - var wt = this._worldTransform, mat = this._matrix.mat; - mat[0] = wt.a; - mat[4] = wt.c; - mat[12] = wt.tx; - mat[1] = wt.b; - mat[5] = wt.d; - mat[13] = wt.ty; + if (clean) { + this._paths.length = 0; + this._points.length = 0; - var shader = this._shader; - shader.use(); - shader._setUniformForMVPMatrixWithMat4(this._matrix); - - this._render(); - }, - - // clear - clear: function (clean) { - this._vertsOffset = 0; - this._indicesOffset = 0; - - this._pathLength = 0; - this._pathOffset = 0; - this._pointsOffset = 0; - - this._curPath = null; - - this._cmds.length = 0; - - if (clean) { - this._paths.length = 0; - this._points.length = 0; - - this._vertsBuffer = null; - this._indicesBuffer = null; - } - }, -}); + this._vertsBuffer = null; + this._indicesBuffer = null; + } +}; // inner function -Js.mixin(_p, { - _updatePathOffset: false, - _paths: null, - _pathLength: 0, - _pathOffset: 0, +_p._updatePathOffset = false; - _points: null, - _pointsOffset: 0, +_p._paths = null; +_p._pathLength = 0; +_p._pathOffset = 0; - _commandx: 0, - _commandy: 0, +_p._points = null; +_p._pointsOffset = 0; - _addPath: function () { - var offset = this._pathLength; - var path = this._paths[offset]; +_p._commandx = 0; +_p._commandy = 0; - if (!path) { - path = new Path(); +_p._addPath = function () { + var offset = this._pathLength; + var path = this._paths[offset]; - this._paths.push(path); - } else { - path.reset(); + if (!path) { + path = new Path(); + + this._paths.push(path); + } else { + path.reset(); + } + + this._pathLength++; + this._curPath = path; + + return path; +}; + +_p._addPoint = function (x, y, flags) { + var path = this._curPath; + if (!path) return; + + var pt; + var points = this._points; + var pathPoints = path.points; + + var offset = this._pointsOffset++; + pt = points[offset]; + + if (!pt) { + pt = new Point(x, y); + points.push(pt); + } else { + pt.x = x; + pt.y = y; + } + + pt.flags = flags; + pathPoints.push(pt); +}; + +_p._flattenPaths = function () { + var paths = this._paths; + for (var i = this._pathOffset, l = this._pathLength; i < l; i++) { + var path = paths[i]; + var pts = path.points; + + var p0 = pts[pts.length - 1]; + var p1 = pts[0]; + + if (p0.equals(p1)) { + path.closed = true; + pts.pop(); + p0 = pts[pts.length - 1]; } - this._pathLength++; - this._curPath = path; + for (var j = 0, size = pts.length; j < size; j++) { + // Calculate segment direction and length + var dPos = p1.sub(p0); + p0.len = dPos.mag(); + if (dPos.x || dPos.y) + dPos.normalizeSelf(); + p0.dx = dPos.x; + p0.dy = dPos.y; + // Advance + p0 = p1; + p1 = pts[j + 1]; + } + } +}; - return path; - }, +_p._allocVerts = function (cverts) { + var dnverts = this._vertsOffset + cverts; + var buffer = this._vertsBuffer; + var nverts = buffer ? buffer.length / VERTS_FLOAT_LENGTH : 0; - _addPoint: function (x, y, flags) { - var path = this._curPath; - if (!path) return; - - var pt; - var points = this._points; - var pathPoints = path.points; - - var offset = this._pointsOffset++; - pt = points[offset]; - - if (!pt) { - pt = new Point(x, y); - points.push(pt); - } else { - pt.x = x; - pt.y = y; + if (dnverts > nverts) { + if (nverts === 0) { + nverts = INIT_VERTS_SIZE; } - pt.flags = flags; - pathPoints.push(pt); - }, + while (dnverts > nverts) { + nverts *= 2; + } - _flattenPaths: function () { - var paths = this._paths; - for (var i = this._pathOffset, l = this._pathLength; i < l; i++) { - var path = paths[i]; - var pts = path.points; + var newBuffer = new Float32Array(nverts * VERTS_FLOAT_LENGTH); - var p0 = pts[pts.length - 1]; - var p1 = pts[0]; - - if (p0.equals(p1)) { - path.closed = true; - pts.pop(); - p0 = pts[pts.length - 1]; - } - - for (var j = 0, size = pts.length; j < size; j++) { - // Calculate segment direction and length - var dPos = p1.sub(p0); - p0.len = dPos.mag(); - if (dPos.x || dPos.y) - dPos.normalizeSelf(); - p0.dx = dPos.x; - p0.dy = dPos.y; - // Advance - p0 = p1; - p1 = pts[j + 1]; + if (buffer) { + for (var i = 0, l = buffer.length; i < l; i++) { + newBuffer[i] = buffer[i]; } } - }, - _allocVerts: function (cverts) { - var dnverts = this._vertsOffset + cverts; - var buffer = this._vertsBuffer; - var nverts = buffer ? buffer.length / VERTS_FLOAT_LENGTH : 0; + this._vertsBuffer = newBuffer; + } +}; - if (dnverts > nverts) { - if (nverts === 0) { - nverts = INIT_VERTS_SIZE; - } +_p._allocIndices = function (cindices) { + var indices = this._indicesBuffer; + var dnindices = this._indicesOffset + cindices; + var nindices = indices ? indices.length : 0; - while (dnverts > nverts) { - nverts *= 2; - } - - var newBuffer = new Float32Array(nverts * VERTS_FLOAT_LENGTH); - - if (buffer) { - for (var i = 0, l = buffer.length; i < l; i++) { - newBuffer[i] = buffer[i]; - } - } - - this._vertsBuffer = newBuffer; + if (dnindices > nindices) { + if (nindices === 0) { + nindices = INIT_VERTS_SIZE * 3; } - }, - _allocIndices: function (cindices) { - var indices = this._indicesBuffer; - var dnindices = this._indicesOffset + cindices; - var nindices = indices ? indices.length : 0; - - if (dnindices > nindices) { - if (nindices === 0) { - nindices = INIT_VERTS_SIZE * 3; - } - - while (dnindices > nindices) { - nindices *= 2; - } - - var newIndices = new Uint16Array(nindices); - - if (indices) { - for (var i = 0, l = indices.length; i < l; i++) { - newIndices[i] = indices[i]; - } - } - this._indicesBuffer = newIndices; + while (dnindices > nindices) { + nindices *= 2; } - }, - _pushCmd: function (cmd) { - var cmds = this._cmds; - var lastCmd = cmds[cmds.length - 1]; + var newIndices = new Uint16Array(nindices); - if (lastCmd) { - var lastColor = lastCmd.color; - var color = cmd.color; - - if (lastColor.r === color.r && - lastColor.g === color.g && - lastColor.b === color.b && - lastColor.a === color.a && - (lastCmd.indicesOffset + lastCmd.nIndices === cmd.indicesOffset)) { - lastCmd.nIndices += cmd.nIndices; - lastCmd.nverts += cmd.nverts; - } - else { - cmds.push(cmd); + if (indices) { + for (var i = 0, l = indices.length; i < l; i++) { + newIndices[i] = indices[i]; } } + this._indicesBuffer = newIndices; + } +}; + +_p._pushCmd = function (cmd) { + var cmds = this._cmds; + var lastCmd = cmds[cmds.length - 1]; + + if (lastCmd) { + var lastColor = lastCmd.color; + var color = cmd.color; + + if (lastColor.r === color.r && + lastColor.g === color.g && + lastColor.b === color.b && + lastColor.a === color.a && + (lastCmd.indicesOffset + lastCmd.nIndices === cmd.indicesOffset)) { + lastCmd.nIndices += cmd.nIndices; + lastCmd.nverts += cmd.nverts; + } else { cmds.push(cmd); } - }, + } + else { + cmds.push(cmd); + } +}; - _expandStroke: function () { - var w = this.lineWidth * 0.5, - lineCap = this.lineCap, - lineJoin = this.lineJoin, - miterLimit = this.miterLimit; +_p._expandStroke = function () { + var w = this.lineWidth * 0.5, + lineCap = this.lineCap, + lineJoin = this.lineJoin, + miterLimit = this.miterLimit; - var ncap = this._curveDivs(w, PI, this._tessTol); - var paths = this._paths; + var ncap = this._curveDivs(w, PI, this._tessTol); + var paths = this._paths; - this._calculateJoins(w, lineJoin, miterLimit); + this._calculateJoins(w, lineJoin, miterLimit); - // Calculate max vertex usage. - var cverts = 0; - for (var i = this._pathOffset, l = this._pathLength; i < l; i++) { - var path = paths[i]; - var pointsLength = path.points.length; + // Calculate max vertex usage. + var cverts = 0; + for (var i = this._pathOffset, l = this._pathLength; i < l; i++) { + var path = paths[i]; + var pointsLength = path.points.length; - if (lineJoin === LineJoin.ROUND) cverts += (pointsLength + path.nbevel * (ncap + 2) + 1) * 2; // plus one for loop - else cverts += (pointsLength + path.nbevel * 5 + 1) * 2; // plus one for loop + if (lineJoin === LineJoin.ROUND) cverts += (pointsLength + path.nbevel * (ncap + 2) + 1) * 2; // plus one for loop + else cverts += (pointsLength + path.nbevel * 5 + 1) * 2; // plus one for loop - if (!path.closed) { - // space for caps - if (lineCap === LineCap.ROUND) { - cverts += (ncap * 2 + 2) * 2; - } else { - cverts += (3 + 3) * 2; - } + if (!path.closed) { + // space for caps + if (lineCap === LineCap.ROUND) { + cverts += (ncap * 2 + 2) * 2; + } else { + cverts += (3 + 3) * 2; } } + } - this._allocVerts(cverts); - this._allocIndices((cverts - 2*(this._pathLength-this._pathOffset)) * 3); + this._allocVerts(cverts); + this._allocIndices((cverts - 2*(this._pathLength-this._pathOffset)) * 3); - for (var i = this._pathOffset, l = this._pathLength; i < l; i++) { - var path = paths[i]; - var pts = path.points; - var pointsLength = path.points.length; + for (var i = this._pathOffset, l = this._pathLength; i < l; i++) { + var path = paths[i]; + var pts = path.points; + var pointsLength = path.points.length; - var p0, p1; - var s, e, loop; + var p0, p1; + var s, e, loop; - loop = path.closed; - var offset = this._vertsOffset; + loop = path.closed; + var offset = this._vertsOffset; - if (loop) { - // Looping - p0 = pts[pointsLength - 1]; - p1 = pts[0]; - s = 0; - e = pointsLength; - } else { - // Add cap - p0 = pts[0]; - p1 = pts[1]; - s = 1; - e = pointsLength - 1; + if (loop) { + // Looping + p0 = pts[pointsLength - 1]; + p1 = pts[0]; + s = 0; + e = pointsLength; + } else { + // Add cap + p0 = pts[0]; + p1 = pts[1]; + s = 1; + e = pointsLength - 1; + } + + if (!loop) { + // Add cap + var dPos = p1.sub(p0); + dPos.normalizeSelf(); + + var dx = dPos.x; + var dy = dPos.y; + + if (lineCap === LineCap.BUTT) + this._buttCap(p0, dx, dy, w, 0); + else if (lineCap === LineCap.SQUARE) + this._buttCap(p0, dx, dy, w, w); + else if (lineCap === LineCap.ROUND) + this._roundCapStart(p0, dx, dy, w, ncap); + } + + for (var j = s; j < e; ++j) { + if (lineJoin === LineJoin.ROUND) { + this._roundJoin(p0, p1, w, w, ncap); + } + else if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) { + this._bevelJoin(p0, p1, w, w); + } + else { + this._vset(p1.x + p1.dmx * w, p1.y + p1.dmy * w); + this._vset(p1.x - p1.dmx * w, p1.y - p1.dmy * w); } - if (!loop) { - // Add cap - var dPos = p1.sub(p0); - dPos.normalizeSelf(); + p0 = p1; + p1 = pts[j + 1]; + } - var dx = dPos.x; - var dy = dPos.y; + if (loop) { + var v0 = this._vget(offset); + var v1 = this._vget(offset + 1); + // Loop it + this._vset(v0.x, v0.y); + this._vset(v1.x, v1.y); + } else { + // Add cap + var dPos = p1.sub(p0); + dPos.normalizeSelf(); - if (lineCap === LineCap.BUTT) - this._buttCap(p0, dx, dy, w, 0); - else if (lineCap === LineCap.SQUARE) - this._buttCap(p0, dx, dy, w, w); - else if (lineCap === LineCap.ROUND) - this._roundCapStart(p0, dx, dy, w, ncap); + var dx = dPos.x; + var dy = dPos.y; + + if (lineCap === LineCap.BUTT) + this._buttCap(p1, dx, dy, w, 0); + else if (lineCap === LineCap.BUTT || lineCap === LineCap.SQUARE) + this._buttCap(p1, dx, dy, w, w); + else if (lineCap === LineCap.ROUND) + this._roundCapEnd(p1, dx, dy, w, ncap); + } + + // stroke indices + var indicesOffset = this._indicesOffset; + var indicesBuffer = this._indicesBuffer; + + for (var start = offset+2, end = this._vertsOffset; start < end; start++) { + indicesBuffer[indicesOffset++] = start - 2; + indicesBuffer[indicesOffset++] = start - 1; + indicesBuffer[indicesOffset++] = start; + } + + this._pushCmd({ + color: this._strokeColor, + indicesOffset: this._indicesOffset, + nIndices: indicesOffset - this._indicesOffset, + vertsOffset: offset, + nverts: this._vertsOffset - offset + }); + + this._indicesOffset = indicesOffset; + this._indicesDirty = true; + } +}; + +_p._expandFill = function () { + // this._calculateJoins(0, LineJoin.MITER, 2.4); + + var paths = this._paths; + + // Calculate max vertex usage. + var cverts = 0; + for (var i = this._pathOffset, l = this._pathLength; i < l; i++) { + var path = paths[i]; + var pointsLength = path.points.length; + + cverts += pointsLength; + } + + this._allocVerts(cverts); + this._allocIndices((cverts - 2*(this._pathLength-this._pathOffset)) * 3); + + for (var i = this._pathOffset, l = this._pathLength; i < l; i++) { + var path = paths[i]; + var pts = path.points; + var pointsLength = pts.length; + + if (pointsLength === 0) { + continue; + } + + // Calculate shape vertices. + var offset = this._vertsOffset; + + for (var j = 0; j < pointsLength; ++j) { + this._vset(pts[j].x, pts[j].y, 0.5, 1); + } + + var indicesOffset = path.indicesOffset = this._indicesOffset; + var indicesBuffer = this._indicesBuffer; + var nIndices = 0; + + if (path.complex) { + var data = new Float32Array(this._vertsBuffer.buffer, offset * 8, (this._vertsOffset - offset) * 2); + var newIndices = Earcut(data, null, 2); + + if (!newIndices || newIndices.length === 0) { + continue; } - for (var j = s; j < e; ++j) { - if (lineJoin === LineJoin.ROUND) { - this._roundJoin(p0, p1, w, w, ncap); - } - else if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) { - this._bevelJoin(p0, p1, w, w); - } - else { - this._vset(p1.x + p1.dmx * w, p1.y + p1.dmy * w); - this._vset(p1.x - p1.dmx * w, p1.y - p1.dmy * w); - } + nIndices = newIndices.length; - p0 = p1; - p1 = pts[j + 1]; + for (var j = 0, l3 = nIndices; j < l3; j++) { + indicesBuffer[indicesOffset + j] = newIndices[j] + offset; } - - if (loop) { - var v0 = this._vget(offset); - var v1 = this._vget(offset + 1); - // Loop it - this._vset(v0.x, v0.y); - this._vset(v1.x, v1.y); - } else { - // Add cap - var dPos = p1.sub(p0); - dPos.normalizeSelf(); - - var dx = dPos.x; - var dy = dPos.y; - - if (lineCap === LineCap.BUTT) - this._buttCap(p1, dx, dy, w, 0); - else if (lineCap === LineCap.BUTT || lineCap === LineCap.SQUARE) - this._buttCap(p1, dx, dy, w, w); - else if (lineCap === LineCap.ROUND) - this._roundCapEnd(p1, dx, dy, w, ncap); - } - - // stroke indices - var indicesOffset = this._indicesOffset; - var indicesBuffer = this._indicesBuffer; - + } + else { + var first = offset; for (var start = offset+2, end = this._vertsOffset; start < end; start++) { - indicesBuffer[indicesOffset++] = start - 2; + indicesBuffer[indicesOffset++] = first; indicesBuffer[indicesOffset++] = start - 1; indicesBuffer[indicesOffset++] = start; } - this._pushCmd({ - color: this._strokeColor, - indicesOffset: this._indicesOffset, - nIndices: indicesOffset - this._indicesOffset, - vertsOffset: offset, - nverts: this._vertsOffset - offset - }); - - this._indicesOffset = indicesOffset; - this._indicesDirty = true; - } - }, - - _expandFill: function () { - // this._calculateJoins(0, LineJoin.MITER, 2.4); - - var paths = this._paths; - - // Calculate max vertex usage. - var cverts = 0; - for (var i = this._pathOffset, l = this._pathLength; i < l; i++) { - var path = paths[i]; - var pointsLength = path.points.length; - - cverts += pointsLength; + nIndices = indicesOffset - this._indicesOffset; } - this._allocVerts(cverts); - this._allocIndices((cverts - 2*(this._pathLength-this._pathOffset)) * 3); + this._pushCmd({ + color: this._fillColor, + indicesOffset: this._indicesOffset, + nIndices: nIndices, + vertsOffset: offset, + nverts: this._vertsOffset - offset + }); - for (var i = this._pathOffset, l = this._pathLength; i < l; i++) { - var path = paths[i]; - var pts = path.points; - var pointsLength = pts.length; - - if (pointsLength === 0) { - continue; - } - - // Calculate shape vertices. - var offset = this._vertsOffset; - - for (var j = 0; j < pointsLength; ++j) { - this._vset(pts[j].x, pts[j].y, 0.5, 1); - } - - var indicesOffset = path.indicesOffset = this._indicesOffset; - var indicesBuffer = this._indicesBuffer; - var nIndices = 0; - - if (path.complex) { - var data = new Float32Array(this._vertsBuffer.buffer, offset * 8, (this._vertsOffset - offset) * 2); - var newIndices = Earcut(data, null, 2); - - if (!newIndices || newIndices.length === 0) { - continue; - } - - nIndices = newIndices.length; - - for (var j = 0, l3 = nIndices; j < l3; j++) { - indicesBuffer[indicesOffset + j] = newIndices[j] + offset; - } - } - else { - var first = offset; - for (var start = offset+2, end = this._vertsOffset; start < end; start++) { - indicesBuffer[indicesOffset++] = first; - indicesBuffer[indicesOffset++] = start - 1; - indicesBuffer[indicesOffset++] = start; - } - - nIndices = indicesOffset - this._indicesOffset; - } - - this._pushCmd({ - color: this._fillColor, - indicesOffset: this._indicesOffset, - nIndices: nIndices, - vertsOffset: offset, - nverts: this._vertsOffset - offset - }); - - this._indicesOffset += nIndices; - this._indicesDirty = true; - } - }, - - _curveDivs: function (r, arc, tol) { - var da = acos(r / (r + tol)) * 2.0; - return max(2, ceil(arc / da)); - }, - - _calculateJoins: function (w, lineJoin, miterLimit) { - var iw = 0.0; - - if (w > 0.0) { - iw = 1 / w; - } - - // Calculate which joins needs extra vertices to append, and gather vertex count. - var paths = this._paths; - - for (var i = this._pathOffset, l = this._pathLength; i < l; i++) { - var path = paths[i]; - - var pts = path.points; - var ptsLength = pts.length; - var p0 = pts[ptsLength - 1]; - var p1 = pts[0]; - var nleft = 0; - - path.nbevel = 0; - - for (var j = 0; j < ptsLength; j++) { - var dmr2, cross, limit; - - // perp normals - var dlx0 = p0.dy; - var dly0 = -p0.dx; - var dlx1 = p1.dy; - var dly1 = -p1.dx; - - // Calculate extrusions - p1.dmx = (dlx0 + dlx1) * 0.5; - p1.dmy = (dly0 + dly1) * 0.5; - dmr2 = p1.dmx * p1.dmx + p1.dmy * p1.dmy; - if (dmr2 > 0.000001) { - var scale = 1 / dmr2; - if (scale > 600) { - scale = 600; - } - p1.dmx *= scale; - p1.dmy *= scale; - } - - // Keep track of left turns. - cross = p1.dx * p0.dy - p0.dx * p1.dy; - if (cross > 0) { - nleft++; - p1.flags |= PointFlags.PT_LEFT; - } - - // Calculate if we should use bevel or miter for inner join. - limit = max(11, min(p0.len, p1.len) * iw); - if (dmr2 * limit * limit < 1) { - p1.flags |= PointFlags.PT_INNERBEVEL; - } - - // Check to see if the corner needs to be beveled. - if (p1.flags & PointFlags.PT_CORNER) { - if (dmr2 * miterLimit * miterLimit < 1 || lineJoin === LineJoin.BEVEL || lineJoin === LineJoin.ROUND) { - p1.flags |= PointFlags.PT_BEVEL; - } - } - - if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) { - path.nbevel++; - } - - p0 = p1; - p1 = pts[j + 1]; - } - } - }, - - _vset: function (x, y) { - var offset = this._vertsOffset * VERTS_FLOAT_LENGTH; - var buffer = this._vertsBuffer; - - buffer[offset] = x; - buffer[offset + 1] = y; - - this._vertsOffset++; - }, - - _vget: function (index) { - var buffer = this._vertsBuffer; - var offset = index * VERTS_FLOAT_LENGTH; - return { - x: buffer[offset], - y: buffer[offset + 1] - }; - }, - - // - _chooseBevel: function (bevel, p0, p1, w) { - var x = p1.x; - var y = p1.y; - var x0, y0, x1, y1; - - if (bevel !== 0) { - x0 = x + p0.dy * w; - y0 = y - p0.dx * w; - x1 = x + p1.dy * w; - y1 = y - p1.dx * w; - } else { - x0 = x1 = x + p1.dmx * w; - y0 = y1 = y + p1.dmy * w; - } - - return [x0, y0, x1, y1]; - }, - - _buttCap: function (p, dx, dy, w, d) { - var px = p.x - dx * d; - var py = p.y - dy * d; - var dlx = dy; - var dly = -dx; - - this._vset(px + dlx * w, py + dly * w); - this._vset(px - dlx * w, py - dly * w); - }, - - _roundCapStart: function (p, dx, dy, w, ncap) { - var px = p.x; - var py = p.y; - var dlx = dy; - var dly = -dx; - - for (var i = 0; i < ncap; i++) { - var a = i / (ncap - 1) * PI; - var ax = cos(a) * w, - ay = sin(a) * w; - this._vset(px - dlx * ax - dx * ay, py - dly * ax - dy * ay); - this._vset(px, py); - } - this._vset(px + dlx * w, py + dly * w); - this._vset(px - dlx * w, py - dly * w); - }, - - _roundCapEnd: function (p, dx, dy, w, ncap) { - var px = p.x; - var py = p.y; - var dlx = dy; - var dly = -dx; - - this._vset(px + dlx * w, py + dly * w); - this._vset(px - dlx * w, py - dly * w); - for (var i = 0; i < ncap; i++) { - var a = i / (ncap - 1) * PI; - var ax = cos(a) * w, - ay = sin(a) * w; - this._vset(px, py); - this._vset(px - dlx * ax + dx * ay, py - dly * ax + dy * ay); - } - }, - - _roundJoin: function (p0, p1, lw, rw, ncap) { - var dlx0 = p0.dy; - var dly0 = -p0.dx; - var dlx1 = p1.dy; - var dly1 = -p1.dx; - - var p1x = p1.x; - var p1y = p1.y; - - if ((p1.flags & PointFlags.PT_LEFT) !== 0) { - var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, lw); - var lx0 = out[0]; - var ly0 = out[1]; - var lx1 = out[2]; - var ly1 = out[3]; - - var a0 = atan2(-dly0, -dlx0); - var a1 = atan2(-dly1, -dlx1); - if (a1 > a0) a1 -= PI * 2; - - this._vset(lx0, ly0); - this._vset(p1x - dlx0 * rw, p1.y - dly0 * rw); - - var n = clamp(ceil((a0 - a1) / PI) * ncap, 2, ncap); - for (var i = 0; i < n; i++) { - var u = i / (n - 1); - var a = a0 + u * (a1 - a0); - var rx = p1x + cos(a) * rw; - var ry = p1y + sin(a) * rw; - this._vset(p1x, p1y); - this._vset(rx, ry); - } - - this._vset(lx1, ly1); - this._vset(p1x - dlx1 * rw, p1y - dly1 * rw); - } else { - var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw); - var rx0 = out[0]; - var ry0 = out[1]; - var rx1 = out[2]; - var ry1 = out[3]; - - var a0 = atan2(dly0, dlx0); - var a1 = atan2(dly1, dlx1); - if (a1 < a0) a1 += PI * 2; - - this._vset(p1x + dlx0 * rw, p1y + dly0 * rw); - this._vset(rx0, ry0); - - var n = clamp(ceil((a1 - a0) / PI) * ncap, 2, ncap); - for (var i = 0; i < n; i++) { - var u = i / (n - 1); - var a = a0 + u * (a1 - a0); - var lx = p1x + cos(a) * lw; - var ly = p1y + sin(a) * lw; - this._vset(lx, ly); - this._vset(p1x, p1y); - } - - this._vset(p1x + dlx1 * rw, p1y + dly1 * rw); - this._vset(rx1, ry1); - } - }, - - _bevelJoin: function (p0, p1, lw, rw) { - var rx0, ry0, rx1, ry1; - var lx0, ly0, lx1, ly1; - var dlx0 = p0.dy; - var dly0 = -p0.dx; - var dlx1 = p1.dy; - var dly1 = -p1.dx; - - if (p1.flags & PointFlags.PT_LEFT) { - var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, lw); - lx0 = out[0]; - ly0 = out[1]; - lx1 = out[2]; - ly1 = out[3]; - - this._vset(lx0, ly0); - this._vset(p1.x - dlx0 * rw, p1.y - dly0 * rw); - - this._vset(lx1, ly1); - this._vset(p1.x - dlx1 * rw, p1.y - dly1 * rw); - } else { - var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw); - rx0 = out[0]; - ry0 = out[1]; - rx1 = out[2]; - ry1 = out[3]; - - this._vset(p1.x + dlx0 * lw, p1.y + dly0 * lw); - this._vset(rx0, ry0); - - this._vset(p1.x + dlx1 * lw, p1.y + dly1 * lw); - this._vset(rx1, ry1); - } - }, - - _tesselateBezier: function (x1, y1, x2, y2, x3, y3, x4, y4, level, type) { - var x12, y12, x23, y23, x34, y34, x123, y123, x234, y234, x1234, y1234; - var dx, dy, d2, d3; - - if (level > 10) return; - - x12 = (x1 + x2) * 0.5; - y12 = (y1 + y2) * 0.5; - x23 = (x2 + x3) * 0.5; - y23 = (y2 + y3) * 0.5; - x34 = (x3 + x4) * 0.5; - y34 = (y3 + y4) * 0.5; - x123 = (x12 + x23) * 0.5; - y123 = (y12 + y23) * 0.5; - - dx = x4 - x1; - dy = y4 - y1; - d2 = abs((x2 - x4) * dy - (y2 - y4) * dx); - d3 = abs((x3 - x4) * dy - (y3 - y4) * dx); - - if ((d2 + d3) * (d2 + d3) < this._tessTol * (dx * dx + dy * dy)) { - this._addPoint(x4, y4, type === 0 ? type | PointFlags.PT_BEVEL : type); - return; - } - - x234 = (x23 + x34) * 0.5; - y234 = (y23 + y34) * 0.5; - x1234 = (x123 + x234) * 0.5; - y1234 = (y123 + y234) * 0.5; - - this._tesselateBezier(x1, y1, x12, y12, x123, y123, x1234, y1234, level + 1, 0); - this._tesselateBezier(x1234, y1234, x234, y234, x34, y34, x4, y4, level + 1, type); + this._indicesOffset += nIndices; + this._indicesDirty = true; } -}); +}; + +_p._curveDivs = function (r, arc, tol) { + var da = acos(r / (r + tol)) * 2.0; + return max(2, ceil(arc / da)); +}; + +_p._calculateJoins = function (w, lineJoin, miterLimit) { + var iw = 0.0; + + if (w > 0.0) { + iw = 1 / w; + } + + // Calculate which joins needs extra vertices to append, and gather vertex count. + var paths = this._paths; + + for (var i = this._pathOffset, l = this._pathLength; i < l; i++) { + var path = paths[i]; + + var pts = path.points; + var ptsLength = pts.length; + var p0 = pts[ptsLength - 1]; + var p1 = pts[0]; + var nleft = 0; + + path.nbevel = 0; + + for (var j = 0; j < ptsLength; j++) { + var dmr2, cross, limit; + + // perp normals + var dlx0 = p0.dy; + var dly0 = -p0.dx; + var dlx1 = p1.dy; + var dly1 = -p1.dx; + + // Calculate extrusions + p1.dmx = (dlx0 + dlx1) * 0.5; + p1.dmy = (dly0 + dly1) * 0.5; + dmr2 = p1.dmx * p1.dmx + p1.dmy * p1.dmy; + if (dmr2 > 0.000001) { + var scale = 1 / dmr2; + if (scale > 600) { + scale = 600; + } + p1.dmx *= scale; + p1.dmy *= scale; + } + + // Keep track of left turns. + cross = p1.dx * p0.dy - p0.dx * p1.dy; + if (cross > 0) { + nleft++; + p1.flags |= PointFlags.PT_LEFT; + } + + // Calculate if we should use bevel or miter for inner join. + limit = max(11, min(p0.len, p1.len) * iw); + if (dmr2 * limit * limit < 1) { + p1.flags |= PointFlags.PT_INNERBEVEL; + } + + // Check to see if the corner needs to be beveled. + if (p1.flags & PointFlags.PT_CORNER) { + if (dmr2 * miterLimit * miterLimit < 1 || lineJoin === LineJoin.BEVEL || lineJoin === LineJoin.ROUND) { + p1.flags |= PointFlags.PT_BEVEL; + } + } + + if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) { + path.nbevel++; + } + + p0 = p1; + p1 = pts[j + 1]; + } + } +}; + +_p._vset = function (x, y) { + var offset = this._vertsOffset * VERTS_FLOAT_LENGTH; + var buffer = this._vertsBuffer; + + buffer[offset] = x; + buffer[offset + 1] = y; + + this._vertsOffset++; +}; + +_p._vget = function (index) { + var buffer = this._vertsBuffer; + var offset = index * VERTS_FLOAT_LENGTH; + return { + x: buffer[offset], + y: buffer[offset + 1] + }; + }; + +// +_p._chooseBevel = function (bevel, p0, p1, w) { + var x = p1.x; + var y = p1.y; + var x0, y0, x1, y1; + + if (bevel !== 0) { + x0 = x + p0.dy * w; + y0 = y - p0.dx * w; + x1 = x + p1.dy * w; + y1 = y - p1.dx * w; + } else { + x0 = x1 = x + p1.dmx * w; + y0 = y1 = y + p1.dmy * w; + } + + return [x0, y0, x1, y1]; +}; + +_p._buttCap = function (p, dx, dy, w, d) { + var px = p.x - dx * d; + var py = p.y - dy * d; + var dlx = dy; + var dly = -dx; + + this._vset(px + dlx * w, py + dly * w); + this._vset(px - dlx * w, py - dly * w); +}; + +_p._roundCapStart = function (p, dx, dy, w, ncap) { + var px = p.x; + var py = p.y; + var dlx = dy; + var dly = -dx; + + for (var i = 0; i < ncap; i++) { + var a = i / (ncap - 1) * PI; + var ax = cos(a) * w, + ay = sin(a) * w; + this._vset(px - dlx * ax - dx * ay, py - dly * ax - dy * ay); + this._vset(px, py); + } + this._vset(px + dlx * w, py + dly * w); + this._vset(px - dlx * w, py - dly * w); +}; + +_p._roundCapEnd = function (p, dx, dy, w, ncap) { + var px = p.x; + var py = p.y; + var dlx = dy; + var dly = -dx; + + this._vset(px + dlx * w, py + dly * w); + this._vset(px - dlx * w, py - dly * w); + for (var i = 0; i < ncap; i++) { + var a = i / (ncap - 1) * PI; + var ax = cos(a) * w, + ay = sin(a) * w; + this._vset(px, py); + this._vset(px - dlx * ax + dx * ay, py - dly * ax + dy * ay); + } +}; + +_p._roundJoin = function (p0, p1, lw, rw, ncap) { + var dlx0 = p0.dy; + var dly0 = -p0.dx; + var dlx1 = p1.dy; + var dly1 = -p1.dx; + + var p1x = p1.x; + var p1y = p1.y; + + if ((p1.flags & PointFlags.PT_LEFT) !== 0) { + var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, lw); + var lx0 = out[0]; + var ly0 = out[1]; + var lx1 = out[2]; + var ly1 = out[3]; + + var a0 = atan2(-dly0, -dlx0); + var a1 = atan2(-dly1, -dlx1); + if (a1 > a0) a1 -= PI * 2; + + this._vset(lx0, ly0); + this._vset(p1x - dlx0 * rw, p1.y - dly0 * rw); + + var n = clamp(ceil((a0 - a1) / PI) * ncap, 2, ncap); + for (var i = 0; i < n; i++) { + var u = i / (n - 1); + var a = a0 + u * (a1 - a0); + var rx = p1x + cos(a) * rw; + var ry = p1y + sin(a) * rw; + this._vset(p1x, p1y); + this._vset(rx, ry); + } + + this._vset(lx1, ly1); + this._vset(p1x - dlx1 * rw, p1y - dly1 * rw); + } else { + var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw); + var rx0 = out[0]; + var ry0 = out[1]; + var rx1 = out[2]; + var ry1 = out[3]; + + var a0 = atan2(dly0, dlx0); + var a1 = atan2(dly1, dlx1); + if (a1 < a0) a1 += PI * 2; + + this._vset(p1x + dlx0 * rw, p1y + dly0 * rw); + this._vset(rx0, ry0); + + var n = clamp(ceil((a1 - a0) / PI) * ncap, 2, ncap); + for (var i = 0; i < n; i++) { + var u = i / (n - 1); + var a = a0 + u * (a1 - a0); + var lx = p1x + cos(a) * lw; + var ly = p1y + sin(a) * lw; + this._vset(lx, ly); + this._vset(p1x, p1y); + } + + this._vset(p1x + dlx1 * rw, p1y + dly1 * rw); + this._vset(rx1, ry1); + } +}; + +_p._bevelJoin = function (p0, p1, lw, rw) { + var rx0, ry0, rx1, ry1; + var lx0, ly0, lx1, ly1; + var dlx0 = p0.dy; + var dly0 = -p0.dx; + var dlx1 = p1.dy; + var dly1 = -p1.dx; + + if (p1.flags & PointFlags.PT_LEFT) { + var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, lw); + lx0 = out[0]; + ly0 = out[1]; + lx1 = out[2]; + ly1 = out[3]; + + this._vset(lx0, ly0); + this._vset(p1.x - dlx0 * rw, p1.y - dly0 * rw); + + this._vset(lx1, ly1); + this._vset(p1.x - dlx1 * rw, p1.y - dly1 * rw); + } else { + var out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw); + rx0 = out[0]; + ry0 = out[1]; + rx1 = out[2]; + ry1 = out[3]; + + this._vset(p1.x + dlx0 * lw, p1.y + dly0 * lw); + this._vset(rx0, ry0); + + this._vset(p1.x + dlx1 * lw, p1.y + dly1 * lw); + this._vset(rx1, ry1); + } +}; + +_p._tesselateBezier = function (x1, y1, x2, y2, x3, y3, x4, y4, level, type) { + var x12, y12, x23, y23, x34, y34, x123, y123, x234, y234, x1234, y1234; + var dx, dy, d2, d3; + + if (level > 10) return; + + x12 = (x1 + x2) * 0.5; + y12 = (y1 + y2) * 0.5; + x23 = (x2 + x3) * 0.5; + y23 = (y2 + y3) * 0.5; + x34 = (x3 + x4) * 0.5; + y34 = (y3 + y4) * 0.5; + x123 = (x12 + x23) * 0.5; + y123 = (y12 + y23) * 0.5; + + dx = x4 - x1; + dy = y4 - y1; + d2 = abs((x2 - x4) * dy - (y2 - y4) * dx); + d3 = abs((x3 - x4) * dy - (y3 - y4) * dx); + + if ((d2 + d3) * (d2 + d3) < this._tessTol * (dx * dx + dy * dy)) { + this._addPoint(x4, y4, type === 0 ? type | PointFlags.PT_BEVEL : type); + return; + } + + x234 = (x23 + x34) * 0.5; + y234 = (y23 + y34) * 0.5; + x1234 = (x123 + x234) * 0.5; + y1234 = (y123 + y234) * 0.5; + + this._tesselateBezier(x1, y1, x12, y12, x123, y123, x1234, y1234, level + 1, 0); + this._tesselateBezier(x1234, y1234, x234, y234, x34, y34, x4, y4, level + 1, type); +}; module.exports = WebGLRenderCmd; diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js index f42c4e8fcd..4f4a07770c 100644 --- a/cocos2d/core/load-pipeline/CCLoader.js +++ b/cocos2d/core/load-pipeline/CCLoader.js @@ -114,825 +114,824 @@ function CCLoader () { this._autoReleaseSetting = {}; } JS.extend(CCLoader, Pipeline); -JS.mixin(CCLoader.prototype, { +var proto = CCLoader.prototype; - /** - * Get XMLHttpRequest. - * @returns {XMLHttpRequest} - */ - getXMLHttpRequest: getXMLHttpRequest, +/** + * Get XMLHttpRequest. + * @returns {XMLHttpRequest} + */ +proto.getXMLHttpRequest = getXMLHttpRequest; - /** - * Add custom supported types handler or modify existing type handler for download process. - * @example - * cc.loader.addDownloadHandlers({ - * // This will match all url with `.scene` extension or all url with `scene` type - * 'scene' : function (url, callback) {} - * }); - * @method addDownloadHandlers - * @param {Object} extMap Custom supported types with corresponded handler - */ - addDownloadHandlers: function (extMap) { - this.downloader.addHandlers(extMap); - }, +/** + * Add custom supported types handler or modify existing type handler for download process. + * @example + * cc.loader.addDownloadHandlers({ + * // This will match all url with `.scene` extension or all url with `scene` type + * 'scene' : function (url, callback) {} + * }); + * @method addDownloadHandlers + * @param {Object} extMap Custom supported types with corresponded handler + */ +proto.addDownloadHandlers = function (extMap) { + this.downloader.addHandlers(extMap); +}; - /** - * Add custom supported types handler or modify existing type handler for load process. - * @example - * cc.loader.addLoadHandlers({ - * // This will match all url with `.scene` extension or all url with `scene` type - * 'scene' : function (url, callback) {} - * }); - * @method addLoadHandlers - * @param {Object} extMap Custom supported types with corresponded handler - */ - addLoadHandlers: function (extMap) { - this.loader.addHandlers(extMap); - }, +/** + * Add custom supported types handler or modify existing type handler for load process. + * @example + * cc.loader.addLoadHandlers({ + * // This will match all url with `.scene` extension or all url with `scene` type + * 'scene' : function (url, callback) {} + * }); + * @method addLoadHandlers + * @param {Object} extMap Custom supported types with corresponded handler + */ +proto.addLoadHandlers = function (extMap) { + this.loader.addHandlers(extMap); +}; - /** - * Load resources with a progression callback and a complete callback. - * The progression callback is the same as Pipeline's {{#crossLink "Pipeline/onProgress:method"}}onProgress{{/crossLink}} - * The complete callback is almost the same as Pipeline's {{#crossLink "Pipeline/onComplete:method"}}onComplete{{/crossLink}} - * The only difference is when user pass a single url as resources, the complete callback will set its result directly as the second parameter. - * - * @example - * cc.loader.load('a.png', function (err, tex) { - * cc.log('Result should be a texture: ' + (tex instanceof cc.Texture2D)); - * }); - * - * cc.loader.load('http://example.com/a.png', function (err, tex) { - * cc.log('Should load a texture from external url: ' + (tex instanceof cc.Texture2D)); - * }); - * - * cc.loader.load({url: 'http://example.com/getImageREST?file=a.png', type: 'png'}, function (err, tex) { - * cc.log('Should load a texture from RESTful API by specify the type: ' + (tex instanceof cc.Texture2D)); - * }); - * - * cc.loader.load(['a.png', 'b.json'], function (errors, results) { - * if (errors) { - * for (var i = 0; i < errors.length; i++) { - * cc.log('Error url [' + errors[i] + ']: ' + results.getError(errors[i])); - * } - * } - * var aTex = results.getContent('a.png'); - * var bJsonObj = results.getContent('b.json'); - * }); - * - * @method load - * @param {String|String[]|Object} resources - Url list in an array - * @param {Function} [progressCallback] - Callback invoked when progression change - * @param {Function} [completeCallback] - Callback invoked when all resources loaded - * @typescript - * load(resources: string|string[]|{uuid?: string, url?: string, type?: string}, completeCallback?: Function): void - * load(resources: string|string[]|{uuid?: string, url?: string, type?: string}, progressCallback: Function, completeCallback: Function|null): void - */ - load: function(resources, progressCallback, completeCallback) { - if (completeCallback === undefined) { - completeCallback = progressCallback; - progressCallback = this.onProgress || null; - } +/** + * Load resources with a progression callback and a complete callback. + * The progression callback is the same as Pipeline's {{#crossLink "Pipeline/onProgress:method"}}onProgress{{/crossLink}} + * The complete callback is almost the same as Pipeline's {{#crossLink "Pipeline/onComplete:method"}}onComplete{{/crossLink}} + * The only difference is when user pass a single url as resources, the complete callback will set its result directly as the second parameter. + * + * @example + * cc.loader.load('a.png', function (err, tex) { + * cc.log('Result should be a texture: ' + (tex instanceof cc.Texture2D)); + * }); + * + * cc.loader.load('http://example.com/a.png', function (err, tex) { + * cc.log('Should load a texture from external url: ' + (tex instanceof cc.Texture2D)); + * }); + * + * cc.loader.load({url: 'http://example.com/getImageREST?file=a.png', type: 'png'}, function (err, tex) { + * cc.log('Should load a texture from RESTful API by specify the type: ' + (tex instanceof cc.Texture2D)); + * }); + * + * cc.loader.load(['a.png', 'b.json'], function (errors, results) { + * if (errors) { + * for (var i = 0; i < errors.length; i++) { + * cc.log('Error url [' + errors[i] + ']: ' + results.getError(errors[i])); + * } + * } + * var aTex = results.getContent('a.png'); + * var bJsonObj = results.getContent('b.json'); + * }); + * + * @method load + * @param {String|String[]|Object} resources - Url list in an array + * @param {Function} [progressCallback] - Callback invoked when progression change + * @param {Function} [completeCallback] - Callback invoked when all resources loaded + * @typescript + * load(resources: string|string[]|{uuid?: string, url?: string, type?: string}, completeCallback?: Function): void + * load(resources: string|string[]|{uuid?: string, url?: string, type?: string}, progressCallback: Function, completeCallback: Function|null): void + */ +proto.load = function(resources, progressCallback, completeCallback) { + if (completeCallback === undefined) { + completeCallback = progressCallback; + progressCallback = this.onProgress || null; + } - var self = this; - var singleRes = false; - if (!(resources instanceof Array)) { - singleRes = true; - resources = resources ? [resources] : []; - } + var self = this; + var singleRes = false; + if (!(resources instanceof Array)) { + singleRes = true; + resources = resources ? [resources] : []; + } - _sharedResources.length = 0; - for (var i = 0; i < resources.length; ++i) { - var resource = resources[i]; - // Backward compatibility - if (resource && resource.id) { - cc.warnID(4920, resource.id); - if (!resource.uuid && !resource.url) { - resource.url = resource.id; - } + _sharedResources.length = 0; + for (var i = 0; i < resources.length; ++i) { + var resource = resources[i]; + // Backward compatibility + if (resource && resource.id) { + cc.warnID(4920, resource.id); + if (!resource.uuid && !resource.url) { + resource.url = resource.id; } - var res = getResWithUrl(resource); - if (!res.url && !res.uuid) - continue; - var item = this.getItem(res.url); - _sharedResources.push(item || res); } + var res = getResWithUrl(resource); + if (!res.url && !res.uuid) + continue; + var item = this.getItem(res.url); + _sharedResources.push(item || res); + } - var queue = LoadingItems.create(this, progressCallback, function (errors, items) { - callInNextTick(function () { - if (!completeCallback) - return; + var queue = LoadingItems.create(this, progressCallback, function (errors, items) { + callInNextTick(function () { + if (!completeCallback) + return; - if (singleRes) { - var id = res.url; - completeCallback.call(self, items.getError(id), items.getContent(id)); - } - else { - completeCallback.call(self, errors, items); - } - completeCallback = null; - - if (CC_EDITOR) { - for (var id in self._cache) { - if (self._cache[id].complete) { - self.removeItem(id); - } - } - } - items.destroy(); - }); - }); - LoadingItems.initQueueDeps(queue); - queue.append(_sharedResources); - _sharedResources.length = 0; - }, - - flowInDeps: function (owner, urlList, callback) { - if (owner && !owner.deps) { - owner.deps = []; - } - - _sharedList.length = 0; - for (var i = 0; i < urlList.length; ++i) { - var res = getResWithUrl(urlList[i]); - if (!res.url && ! res.uuid) - continue; - var item = this.getItem(res.url); - if (item) { - _sharedList.push(item); - // Collect deps to avoid circle reference - owner && owner.deps.push(item); + if (singleRes) { + var id = res.url; + completeCallback.call(self, items.getError(id), items.getContent(id)); } else { - _sharedList.push(res); + completeCallback.call(self, errors, items); } - } + completeCallback = null; - var queue = LoadingItems.create(this, owner ? function (completedCount, totalCount, item) { - if (this._ownerQueue && this._ownerQueue.onProgress) { - this._ownerQueue._childOnProgress(item); + if (CC_EDITOR) { + for (var id in self._cache) { + if (self._cache[id].complete) { + self.removeItem(id); + } + } } - } : null, function (errors, items) { - callback(errors, items); - // Clear deps because it's already done - // Each item will only flowInDeps once, so it's still safe here - owner && (owner.deps.length = 0); items.destroy(); }); - if (owner) { - var ownerQueue = LoadingItems.getQueue(owner); - // Set the root ownerQueue, if no ownerQueue defined in ownerQueue, it's the root - queue._ownerQueue = ownerQueue._ownerQueue || ownerQueue; - } - var accepted = queue.append(_sharedList, owner); - _sharedList.length = 0; - return accepted; - }, + }); + LoadingItems.initQueueDeps(queue); + queue.append(_sharedResources); + _sharedResources.length = 0; +}; - _resources: resources, - _getResUuid: function (url, type, quiet) { - if (!url) { - return null; +proto.flowInDeps = function (owner, urlList, callback) { + if (owner && !owner.deps) { + owner.deps = []; + } + + _sharedList.length = 0; + for (var i = 0; i < urlList.length; ++i) { + var res = getResWithUrl(urlList[i]); + if (!res.url && ! res.uuid) + continue; + var item = this.getItem(res.url); + if (item) { + _sharedList.push(item); + // Collect deps to avoid circle reference + owner && owner.deps.push(item); } - // Ignore parameter - var index = url.indexOf('?'); - if (index !== -1) - url = url.substr(0, index); - var uuid = resources.getUuid(url, type); - if ( !uuid ) { - var extname = cc.path.extname(url); - if (extname) { - // strip extname - url = url.slice(0, - extname.length); - uuid = resources.getUuid(url, type); - if (uuid && !quiet) { - cc.warnID(4901, url, extname); - } + else { + _sharedList.push(res); + } + } + + var queue = LoadingItems.create(this, owner ? function (completedCount, totalCount, item) { + if (this._ownerQueue && this._ownerQueue.onProgress) { + this._ownerQueue._childOnProgress(item); + } + } : null, function (errors, items) { + callback(errors, items); + // Clear deps because it's already done + // Each item will only flowInDeps once, so it's still safe here + owner && (owner.deps.length = 0); + items.destroy(); + }); + if (owner) { + var ownerQueue = LoadingItems.getQueue(owner); + // Set the root ownerQueue, if no ownerQueue defined in ownerQueue, it's the root + queue._ownerQueue = ownerQueue._ownerQueue || ownerQueue; + } + var accepted = queue.append(_sharedList, owner); + _sharedList.length = 0; + return accepted; +}; + +proto._resources = resources; +proto._getResUuid = function (url, type, quiet) { + if (!url) { + return null; + } + // Ignore parameter + var index = url.indexOf('?'); + if (index !== -1) + url = url.substr(0, index); + var uuid = resources.getUuid(url, type); + if ( !uuid ) { + var extname = cc.path.extname(url); + if (extname) { + // strip extname + url = url.slice(0, - extname.length); + uuid = resources.getUuid(url, type); + if (uuid && !quiet) { + cc.warnID(4901, url, extname); } } - return uuid; - }, - // Find the asset's reference id in loader, asset could be asset object, asset uuid or asset url - _getReferenceKey: function (assetOrUrlOrUuid) { - var key; - if (typeof assetOrUrlOrUuid === 'object') { - key = assetOrUrlOrUuid._uuid || null; - } - else if (typeof assetOrUrlOrUuid === 'string') { - key = this._getResUuid(assetOrUrlOrUuid, null, true) || assetOrUrlOrUuid; - } - if (!key) { - cc.warnID(4800, assetOrUrlOrUuid); - return key; - } - _info.url = null; - _info.raw = false; - cc.AssetLibrary._getAssetInfoInRuntime(key, _info); - return this._cache[_info.url] ? _info.url : key; - }, + } + return uuid; +}; +// Find the asset's reference id in loader, asset could be asset object, asset uuid or asset url +proto._getReferenceKey = function (assetOrUrlOrUuid) { + var key; + if (typeof assetOrUrlOrUuid === 'object') { + key = assetOrUrlOrUuid._uuid || null; + } + else if (typeof assetOrUrlOrUuid === 'string') { + key = this._getResUuid(assetOrUrlOrUuid, null, true) || assetOrUrlOrUuid; + } + if (!key) { + cc.warnID(4800, assetOrUrlOrUuid); + return key; + } + _info.url = null; + _info.raw = false; + cc.AssetLibrary._getAssetInfoInRuntime(key, _info); + return this._cache[_info.url] ? _info.url : key; +}; - _urlNotFound: function (url, type, completeCallback) { - callInNextTick(function () { - url = cc.url.normalize(url); - var info = `${type ? JS.getClassName(type) : 'Asset'} in "resources/${url}" does not exist.`; - if (completeCallback) { - completeCallback(new Error(info), []); +proto._urlNotFound = function (url, type, completeCallback) { + callInNextTick(function () { + url = cc.url.normalize(url); + var info = `${type ? JS.getClassName(type) : 'Asset'} in "resources/${url}" does not exist.`; + if (completeCallback) { + completeCallback(new Error(info), []); + } + }); +}; + +/** + * @param {Function} [type] + * @param {Function} [onProgress] + * @param {Function} onComplete + * @returns {Object} arguments + * @returns {Function} arguments.type + * @returns {Function} arguments.onProgress + * @returns {Function} arguments.onComplete + */ +proto._parseLoadResArgs = function (type, onProgress, onComplete) { + if (onComplete === undefined) { + var isValidType = cc.isChildClassOf(type, cc.RawAsset); + if (onProgress) { + onComplete = onProgress; + if (isValidType) { + onProgress = this.onProgress || null; + } + } + else if (onProgress === undefined && !isValidType) { + onComplete = type; + onProgress = this.onProgress || null; + type = null; + } + if (onProgress !== undefined && !isValidType) { + onProgress = type; + type = null; + } + } + return { + type: type, + onProgress: onProgress, + onComplete: onComplete, + }; +}; + +/** + * Load resources from the "resources" folder inside the "assets" folder of your project.
+ *
+ * Note: All asset URLs in Creator use forward slashes, URLs using backslashes will not work. + * + * @method loadRes + * @param {String} url - Url of the target resource. + * The url is relative to the "resources" folder, extensions must be omitted. + * @param {Function} [type] - Only asset of type will be loaded if this argument is supplied. + * @param {Function} [progressCallback] - Callback invoked when progression change. + * @param {Function} [completeCallback] - Callback invoked when the resource loaded. + * @param {Error} completeCallback.error - The error info or null if loaded successfully. + * @param {Object} completeCallback.resource - The loaded resource if it can be found otherwise returns null. + * + * @example + * + * // load the prefab (project/assets/resources/misc/character/cocos) from resources folder + * cc.loader.loadRes('misc/character/cocos', function (err, prefab) { + * if (err) { + * cc.error(err.message || err); + * return; + * } + * cc.log('Result should be a prefab: ' + (prefab instanceof cc.Prefab)); + * }); + * + * // load the sprite frame of (project/assets/resources/imgs/cocos.png) from resources folder + * cc.loader.loadRes('imgs/cocos', cc.SpriteFrame, function (err, spriteFrame) { + * if (err) { + * cc.error(err.message || err); + * return; + * } + * cc.log('Result should be a sprite frame: ' + (spriteFrame instanceof cc.SpriteFrame)); + * }); + * @typescript + * loadRes(url: string, type: {new (): cc.Asset}, progressCallback: Function, completeCallback: ((error: Error, resource: any) => void)|null): void + * loadRes(url: string, type: {new (): cc.Asset}, completeCallback: (error: Error, resource: any) => void): void + * loadRes(url: string, type: {new (): cc.Asset}): void + * loadRes(url: string, progressCallback: Function, completeCallback: ((error: Error, resource: any) => void)|null): void + * loadRes(url: string, completeCallback: (error: Error, resource: any) => void): void + * loadRes(url: string): void + */ +proto.loadRes = function (url, type, progressCallback, completeCallback) { + var args = this._parseLoadResArgs(type, progressCallback, completeCallback); + type = args.type; + progressCallback = args.onProgress; + completeCallback = args.onComplete; + var self = this; + var uuid = self._getResUuid(url, type); + if (uuid) { + this.load( + { + type: 'uuid', + uuid: uuid + }, + progressCallback, + function (err, asset) { + if (asset) { + // should not release these assets, even if they are static referenced in the scene. + self.setAutoReleaseRecursively(uuid, false); + } + if (completeCallback) { + completeCallback(err, asset); + } + } + ); + } + else { + self._urlNotFound(url, type, completeCallback); + } +}; + +proto._loadResUuids = function (uuids, progressCallback, completeCallback, urls) { + if (uuids.length > 0) { + var self = this; + var res = uuids.map(function (uuid) { + return { + type: 'uuid', + uuid: uuid } }); - }, - - /** - * @param {Function} [type] - * @param {Function} [onProgress] - * @param {Function} onComplete - * @returns {Object} arguments - * @returns {Function} arguments.type - * @returns {Function} arguments.onProgress - * @returns {Function} arguments.onComplete - */ - _parseLoadResArgs: function (type, onProgress, onComplete) { - if (onComplete === undefined) { - var isValidType = cc.isChildClassOf(type, cc.RawAsset); - if (onProgress) { - onComplete = onProgress; - if (isValidType) { - onProgress = this.onProgress || null; - } - } - else if (onProgress === undefined && !isValidType) { - onComplete = type; - onProgress = this.onProgress || null; - type = null; - } - if (onProgress !== undefined && !isValidType) { - onProgress = type; - type = null; - } - } - return { - type: type, - onProgress: onProgress, - onComplete: onComplete, - }; - }, - - /** - * Load resources from the "resources" folder inside the "assets" folder of your project.
- *
- * Note: All asset URLs in Creator use forward slashes, URLs using backslashes will not work. - * - * @method loadRes - * @param {String} url - Url of the target resource. - * The url is relative to the "resources" folder, extensions must be omitted. - * @param {Function} [type] - Only asset of type will be loaded if this argument is supplied. - * @param {Function} [progressCallback] - Callback invoked when progression change. - * @param {Function} [completeCallback] - Callback invoked when the resource loaded. - * @param {Error} completeCallback.error - The error info or null if loaded successfully. - * @param {Object} completeCallback.resource - The loaded resource if it can be found otherwise returns null. - * - * @example - * - * // load the prefab (project/assets/resources/misc/character/cocos) from resources folder - * cc.loader.loadRes('misc/character/cocos', function (err, prefab) { - * if (err) { - * cc.error(err.message || err); - * return; - * } - * cc.log('Result should be a prefab: ' + (prefab instanceof cc.Prefab)); - * }); - * - * // load the sprite frame of (project/assets/resources/imgs/cocos.png) from resources folder - * cc.loader.loadRes('imgs/cocos', cc.SpriteFrame, function (err, spriteFrame) { - * if (err) { - * cc.error(err.message || err); - * return; - * } - * cc.log('Result should be a sprite frame: ' + (spriteFrame instanceof cc.SpriteFrame)); - * }); - * @typescript - * loadRes(url: string, type: {new (): cc.Asset}, progressCallback: Function, completeCallback: ((error: Error, resource: any) => void)|null): void - * loadRes(url: string, type: {new (): cc.Asset}, completeCallback: (error: Error, resource: any) => void): void - * loadRes(url: string, type: {new (): cc.Asset}): void - * loadRes(url: string, progressCallback: Function, completeCallback: ((error: Error, resource: any) => void)|null): void - * loadRes(url: string, completeCallback: (error: Error, resource: any) => void): void - * loadRes(url: string): void - */ - loadRes: function (url, type, progressCallback, completeCallback) { - var args = this._parseLoadResArgs(type, progressCallback, completeCallback); - type = args.type; - progressCallback = args.onProgress; - completeCallback = args.onComplete; - var self = this; - var uuid = self._getResUuid(url, type); - if (uuid) { - this.load( - { - type: 'uuid', - uuid: uuid - }, - progressCallback, - function (err, asset) { - if (asset) { + this.load(res, progressCallback, function (errors, items) { + if (completeCallback) { + var assetRes = []; + var urlRes = urls && []; + for (var i = 0; i < res.length; ++i) { + var uuid = res[i].uuid; + var id = this._getReferenceKey(uuid); + var item = items.getContent(id); + if (item) { // should not release these assets, even if they are static referenced in the scene. self.setAutoReleaseRecursively(uuid, false); - } - if (completeCallback) { - completeCallback(err, asset); - } - } - ); - } - else { - self._urlNotFound(url, type, completeCallback); - } - }, - - _loadResUuids: function (uuids, progressCallback, completeCallback, urls) { - if (uuids.length > 0) { - var self = this; - var res = uuids.map(function (uuid) { - return { - type: 'uuid', - uuid: uuid - } - }); - this.load(res, progressCallback, function (errors, items) { - if (completeCallback) { - var assetRes = []; - var urlRes = urls && []; - for (var i = 0; i < res.length; ++i) { - var uuid = res[i].uuid; - var id = this._getReferenceKey(uuid); - var item = items.getContent(id); - if (item) { - // should not release these assets, even if they are static referenced in the scene. - self.setAutoReleaseRecursively(uuid, false); - assetRes.push(item); - if (urlRes) { - urlRes.push(urls[i]); - } + assetRes.push(item); + if (urlRes) { + urlRes.push(urls[i]); } } - if (urls) { - completeCallback(errors, assetRes, urlRes); - } - else { - completeCallback(errors, assetRes); - } + } + if (urls) { + completeCallback(errors, assetRes, urlRes); + } + else { + completeCallback(errors, assetRes); + } + } + }); + } + else { + if (completeCallback) { + callInNextTick(function () { + if (urls) { + completeCallback(null, [], []); + } + else { + completeCallback(null, []); } }); } - else { - if (completeCallback) { - callInNextTick(function () { - if (urls) { - completeCallback(null, [], []); - } - else { - completeCallback(null, []); - } - }); - } - } - }, + } +}; - /** - * This method is like {{#crossLink "loader/loadRes:method"}}{{/crossLink}} except that it accepts array of url. - * - * @method loadResArray - * @param {String[]} urls - Array of URLs of the target resource. - * The url is relative to the "resources" folder, extensions must be omitted. - * @param {Function} [type] - Only asset of type will be loaded if this argument is supplied. - * @param {Function} [progressCallback] - Callback invoked when progression change. - * @param {Function} [completeCallback] - A callback which is called when all assets have been loaded, or an error occurs. - * @param {Error} completeCallback.error - If one of the asset failed, the complete callback is immediately called - * with the error. If all assets are loaded successfully, error will be null. - * @param {Asset[]|Array} completeCallback.assets - An array of all loaded assets. - * If nothing to load, assets will be an empty array. - * @example - * - * // load the SpriteFrames from resources folder - * var spriteFrames; - * var urls = ['misc/characters/character_01', 'misc/weapons/weapons_01']; - * cc.loader.loadResArray(urls, cc.SpriteFrame, function (err, assets) { - * if (err) { - * cc.error(err); - * return; - * } - * spriteFrames = assets; - * // ... - * }); - * @typescript - * loadResArray(url: string[], type: {new (): cc.Asset}, progressCallback: Function, completeCallback: ((error: Error, resource: any[]) => void)|null): void - * loadResArray(url: string[], type: {new (): cc.Asset}, completeCallback: (error: Error, resource: any[]) => void): void - * loadResArray(url: string[], type: {new (): cc.Asset}): void - * loadResArray(url: string[], progressCallback: Function, completeCallback: ((error: Error, resource: any[]) => void)|null): void - * loadResArray(url: string[], completeCallback: (error: Error, resource: any[]) => void): void - * loadResArray(url: string[]): void - */ - loadResArray: function (urls, type, progressCallback, completeCallback) { - var args = this._parseLoadResArgs(type, progressCallback, completeCallback); - type = args.type; - progressCallback = args.onProgress; - completeCallback = args.onComplete; +/** + * This method is like {{#crossLink "loader/loadRes:method"}}{{/crossLink}} except that it accepts array of url. + * + * @method loadResArray + * @param {String[]} urls - Array of URLs of the target resource. + * The url is relative to the "resources" folder, extensions must be omitted. + * @param {Function} [type] - Only asset of type will be loaded if this argument is supplied. + * @param {Function} [progressCallback] - Callback invoked when progression change. + * @param {Function} [completeCallback] - A callback which is called when all assets have been loaded, or an error occurs. + * @param {Error} completeCallback.error - If one of the asset failed, the complete callback is immediately called + * with the error. If all assets are loaded successfully, error will be null. + * @param {Asset[]|Array} completeCallback.assets - An array of all loaded assets. + * If nothing to load, assets will be an empty array. + * @example + * + * // load the SpriteFrames from resources folder + * var spriteFrames; + * var urls = ['misc/characters/character_01', 'misc/weapons/weapons_01']; + * cc.loader.loadResArray(urls, cc.SpriteFrame, function (err, assets) { + * if (err) { + * cc.error(err); + * return; + * } + * spriteFrames = assets; + * // ... + * }); + * @typescript + * loadResArray(url: string[], type: {new (): cc.Asset}, progressCallback: Function, completeCallback: ((error: Error, resource: any[]) => void)|null): void + * loadResArray(url: string[], type: {new (): cc.Asset}, completeCallback: (error: Error, resource: any[]) => void): void + * loadResArray(url: string[], type: {new (): cc.Asset}): void + * loadResArray(url: string[], progressCallback: Function, completeCallback: ((error: Error, resource: any[]) => void)|null): void + * loadResArray(url: string[], completeCallback: (error: Error, resource: any[]) => void): void + * loadResArray(url: string[]): void + */ +proto.loadResArray = function (urls, type, progressCallback, completeCallback) { + var args = this._parseLoadResArgs(type, progressCallback, completeCallback); + type = args.type; + progressCallback = args.onProgress; + completeCallback = args.onComplete; - var uuids = []; - for (var i = 0; i < urls.length; i++) { - var url = urls[i]; - var uuid = this._getResUuid(url, type); - if (uuid) { - uuids.push(uuid); - } - else { - this._urlNotFound(url, type, completeCallback); - return; - } - } - this._loadResUuids(uuids, progressCallback, completeCallback); - }, - - /** - * Load all assets in a folder inside the "assets/resources" folder of your project.
- *
- * Note: All asset URLs in Creator use forward slashes, URLs using backslashes will not work. - * - * @method loadResDir - * @param {String} url - Url of the target folder. - * The url is relative to the "resources" folder, extensions must be omitted. - * @param {Function} [type] - Only asset of type will be loaded if this argument is supplied. - * @param {Function} [progressCallback] - Callback invoked when progression change. - * @param {Function} [completeCallback] - A callback which is called when all assets have been loaded, or an error occurs. - * @param {Error} completeCallback.error - If one of the asset failed, the complete callback is immediately called - * with the error. If all assets are loaded successfully, error will be null. - * @param {Asset[]|Array} completeCallback.assets - An array of all loaded assets. - * If nothing to load, assets will be an empty array. - * @param {String[]} completeCallback.urls - An array that lists all the URLs of loaded assets. - * - * @example - * - * // load the texture (resources/imgs/cocos.png) and the corresponding sprite frame - * cc.loader.loadResDir('imgs/cocos', function (err, assets) { - * if (err) { - * cc.error(err); - * return; - * } - * var texture = assets[0]; - * var spriteFrame = assets[1]; - * }); - * - * // load all textures in "resources/imgs/" - * cc.loader.loadResDir('imgs', cc.Texture2D, function (err, textures) { - * var texture1 = textures[0]; - * var texture2 = textures[1]; - * }); - * - * // load all JSONs in "resources/data/" - * cc.loader.loadResDir('data', function (err, objects, urls) { - * var data = objects[0]; - * var url = urls[0]; - * }); - * @typescript - * loadResDir(url: string, type: {new (): cc.Asset}, progressCallback: Function, completeCallback: ((error: Error, resource: any[], urls: string[]) => void)|null): void - * loadResDir(url: string, type: {new (): cc.Asset}, completeCallback: (error: Error, resource: any[], urls: string[]) => void): void - * loadResDir(url: string, type: {new (): cc.Asset}): void - * loadResDir(url: string, progressCallback: Function, completeCallback: ((error: Error, resource: any[], urls: string[]) => void)|null): void - * loadResDir(url: string, completeCallback: (error: Error, resource: any[], urls: string[]) => void): void - * loadResDir(url: string): void - */ - loadResDir: function (url, type, progressCallback, completeCallback) { - var args = this._parseLoadResArgs(type, progressCallback, completeCallback); - type = args.type; - progressCallback = args.onProgress; - completeCallback = args.onComplete; - - var urls = []; - var uuids = resources.getUuidArray(url, type, urls); - this._loadResUuids(uuids, progressCallback, completeCallback, urls); - }, - - /** - * Get resource data by id.
- * When you load resources with {{#crossLink "loader/load:method"}}{{/crossLink}} or {{#crossLink "loader/loadRes:method"}}{{/crossLink}}, - * the url will be the unique identity of the resource. - * After loaded, you can acquire them by passing the url to this API. - * - * @method getRes - * @param {String} url - * @param {Function} [type] - Only asset of type will be returned if this argument is supplied. - * @returns {*} - */ - getRes: function (url, type) { - var item = this._cache[url]; - if (!item) { - var uuid = this._getResUuid(url, type, true); - if (uuid) { - var ref = this._getReferenceKey(uuid); - item = this._cache[ref]; - } - else { - return null; - } - } - if (item && item.alias) { - item = this._cache[item.alias]; - } - return (item && item.complete) ? item.content : null; - }, - - /** - * Get total resources count in loader. - * @returns {Number} - */ - getResCount: function () { - return Object.keys(this._cache).length; - }, - - /** - * !#en Get all resource dependencies of the requested asset in an array, including itself. - * The owner parameter accept the following types: 1. The asset itself; 2. The resource url; 3. The asset's uuid. - * The returned array stores the dependencies with their uuids, after retrieve dependencies, - * you can release them, access dependent assets by passing the uuid to {{#crossLink "loader/getRes:method"}}{{/crossLink}}, or other stuffs you want. - * For release all dependencies of an asset, please refer to {{#crossLink "loader/release:method"}}{{/crossLink}} - * Here is some examples: - * !#zh 获取一个指定资源的所有依赖资源,包含它自身,并保存在数组中返回。owner 参数接收以下几种类型: - * 1. 资源 asset 对象;2. 资源目录下的 url;3. 资源的 uuid - * 返回的数组将仅保存依赖资源的 uuid,获取这些 uuid 后,你可以从 loader 释放这些资源;通过 {{#crossLink "loader/getRes:method"}}{{/crossLink}} 获取某个资源或者其他你需要的处理。 - * 想要释放一个资源及其依赖资源,可以参考 {{#crossLink "loader/release:method"}}{{/crossLink}}。 - * 下面是一些示例代码: - * - * @example - * // Release all dependencies of a loaded prefab - * var deps = cc.loader.getDependsRecursively(prefab); - * cc.loader.release(deps); - * // Retrieve all dependent textures - * var deps = cc.loader.getDependsRecursively('prefabs/sample'); - * var textures = []; - * for (var i = 0; i < deps.length; ++i) { - * var item = cc.loader.getRes(deps[i]); - * if (item instanceof cc.Texture2D) { - * textures.push(item); - * } - * } - * - * @param {Asset|RawAsset|String} owner The owner asset or the resource url or the asset's uuid - * @returns {Array} - */ - getDependsRecursively: function (owner) { - if (owner) { - var key = this._getReferenceKey(owner); - var assets = AutoReleaseUtils.getDependsRecursively(key); - assets.push(key); - return assets; - } - else { - return []; - } - }, - - /** - * !#en - * Release the content of an asset or an array of assets by uuid. - * Start from v1.3, this method will not only remove the cache of the asset in loader, but also clean up its content. - * For example, if you release a texture, the texture asset and its gl texture data will be freed up. - * In complexe project, you can use this function with {{#crossLink "loader/getDependsRecursively:method"}}{{/crossLink}} to free up memory in critical circumstances. - * Notice, this method may cause the texture to be unusable, if there are still other nodes use the same texture, they may turn to black and report gl errors. - * If you only want to remove the cache of an asset, please use {{#crossLink "pipeline/removeItem:method"}}{{/crossLink}} - * !#zh - * 通过 id(通常是资源 url)来释放一个资源或者一个资源数组。 - * 从 v1.3 开始,这个方法不仅会从 loader 中删除资源的缓存引用,还会清理它的资源内容。 - * 比如说,当你释放一个 texture 资源,这个 texture 和它的 gl 贴图数据都会被释放。 - * 在复杂项目中,我们建议你结合 {{#crossLink "loader/getDependsRecursively:method"}}{{/crossLink}} 来使用,便于在设备内存告急的情况下更快地释放不再需要的资源的内存。 - * 注意,这个函数可能会导致资源贴图或资源所依赖的贴图不可用,如果场景中存在节点仍然依赖同样的贴图,它们可能会变黑并报 GL 错误。 - * 如果你只想删除一个资源的缓存引用,请使用 {{#crossLink "pipeline/removeItem:method"}}{{/crossLink}} - * - * @example - * // Release a texture which is no longer need - * cc.loader.release(texture); - * // Release all dependencies of a loaded prefab - * var deps = cc.loader.getDependsRecursively('prefabs/sample'); - * cc.loader.release(deps); - * // If there is no instance of this prefab in the scene, the prefab and its dependencies like textures, sprite frames, etc, will be freed up. - * // If you have some other nodes share a texture in this prefab, you can skip it in two ways: - * // 1. Forbid auto release a texture before release - * cc.loader.setAutoRelease(texture2d, false); - * // 2. Remove it from the dependencies array - * var deps = cc.loader.getDependsRecursively('prefabs/sample'); - * var index = deps.indexOf(texture2d._uuid); - * if (index !== -1) - * deps.splice(index, 1); - * cc.loader.release(deps); - * - * @method release - * @param {Asset|RawAsset|String|Array} asset - */ - release: function (asset) { - if (Array.isArray(asset)) { - for (let i = 0; i < asset.length; i++) { - var key = asset[i]; - this.release(key); - } - } - else if (asset) { - var id = this._getReferenceKey(asset); - var item = this.getItem(id); - if (item) { - var removed = this.removeItem(id); - asset = item.content; - // TODO: AUDIO - if (asset instanceof cc.Asset) { - if (CC_JSB && asset instanceof cc.SpriteFrame && removed) { - // for the "Temporary solution" in deserialize.js - asset.release(); - } - var urls = asset.rawUrls; - for (let i = 0; i < urls.length; i++) { - this.release(urls[i]); - } - } - else if (asset instanceof cc.Texture2D) { - cc.textureCache.removeTextureForKey(item.url); - } - } - } - }, - - /** - * !#en Release the asset by its object. Refer to {{#crossLink "loader/release:method"}}{{/crossLink}} for detailed informations. - * !#zh 通过资源对象自身来释放资源。详细信息请参考 {{#crossLink "loader/release:method"}}{{/crossLink}} - * - * @method releaseAsset - * @param {Asset} asset - */ - releaseAsset: function (asset) { - var uuid = asset._uuid; - if (uuid) { - this.release(uuid); - } - }, - - /** - * !#en Release the asset loaded by {{#crossLink "loader/loadRes:method"}}{{/crossLink}}. Refer to {{#crossLink "loader/release:method"}}{{/crossLink}} for detailed informations. - * !#zh 释放通过 {{#crossLink "loader/loadRes:method"}}{{/crossLink}} 加载的资源。详细信息请参考 {{#crossLink "loader/release:method"}}{{/crossLink}} - * - * @method releaseRes - * @param {String} url - * @param {Function} [type] - Only asset of type will be released if this argument is supplied. - */ - releaseRes: function (url, type) { + var uuids = []; + for (var i = 0; i < urls.length; i++) { + var url = urls[i]; var uuid = this._getResUuid(url, type); if (uuid) { - this.release(uuid); + uuids.push(uuid); } else { - cc.errorID(4914, url); + this._urlNotFound(url, type, completeCallback); + return; } - }, + } + this._loadResUuids(uuids, progressCallback, completeCallback); +}; - /** - * !#en Release the all assets loaded by {{#crossLink "loader/loadResDir:method"}}{{/crossLink}}. Refer to {{#crossLink "loader/release:method"}}{{/crossLink}} for detailed informations. - * !#zh 释放通过 {{#crossLink "loader/loadResDir:method"}}{{/crossLink}} 加载的资源。详细信息请参考 {{#crossLink "loader/release:method"}}{{/crossLink}} - * - * @method releaseResDir - * @param {String} url - * @param {Function} [type] - Only asset of type will be released if this argument is supplied. - */ - releaseResDir: function (url, type) { - var uuids = resources.getUuidArray(url, type); - for (var i = 0; i < uuids.length; i++) { - var uuid = uuids[i]; - this.release(uuid); +/** + * Load all assets in a folder inside the "assets/resources" folder of your project.
+ *
+ * Note: All asset URLs in Creator use forward slashes, URLs using backslashes will not work. + * + * @method loadResDir + * @param {String} url - Url of the target folder. + * The url is relative to the "resources" folder, extensions must be omitted. + * @param {Function} [type] - Only asset of type will be loaded if this argument is supplied. + * @param {Function} [progressCallback] - Callback invoked when progression change. + * @param {Function} [completeCallback] - A callback which is called when all assets have been loaded, or an error occurs. + * @param {Error} completeCallback.error - If one of the asset failed, the complete callback is immediately called + * with the error. If all assets are loaded successfully, error will be null. + * @param {Asset[]|Array} completeCallback.assets - An array of all loaded assets. + * If nothing to load, assets will be an empty array. + * @param {String[]} completeCallback.urls - An array that lists all the URLs of loaded assets. + * + * @example + * + * // load the texture (resources/imgs/cocos.png) and the corresponding sprite frame + * cc.loader.loadResDir('imgs/cocos', function (err, assets) { + * if (err) { + * cc.error(err); + * return; + * } + * var texture = assets[0]; + * var spriteFrame = assets[1]; + * }); + * + * // load all textures in "resources/imgs/" + * cc.loader.loadResDir('imgs', cc.Texture2D, function (err, textures) { + * var texture1 = textures[0]; + * var texture2 = textures[1]; + * }); + * + * // load all JSONs in "resources/data/" + * cc.loader.loadResDir('data', function (err, objects, urls) { + * var data = objects[0]; + * var url = urls[0]; + * }); + * @typescript + * loadResDir(url: string, type: {new (): cc.Asset}, progressCallback: Function, completeCallback: ((error: Error, resource: any[], urls: string[]) => void)|null): void + * loadResDir(url: string, type: {new (): cc.Asset}, completeCallback: (error: Error, resource: any[], urls: string[]) => void): void + * loadResDir(url: string, type: {new (): cc.Asset}): void + * loadResDir(url: string, progressCallback: Function, completeCallback: ((error: Error, resource: any[], urls: string[]) => void)|null): void + * loadResDir(url: string, completeCallback: (error: Error, resource: any[], urls: string[]) => void): void + * loadResDir(url: string): void + */ +proto.loadResDir = function (url, type, progressCallback, completeCallback) { + var args = this._parseLoadResArgs(type, progressCallback, completeCallback); + type = args.type; + progressCallback = args.onProgress; + completeCallback = args.onComplete; + + var urls = []; + var uuids = resources.getUuidArray(url, type, urls); + this._loadResUuids(uuids, progressCallback, completeCallback, urls); +}; + +/** + * Get resource data by id.
+ * When you load resources with {{#crossLink "loader/load:method"}}{{/crossLink}} or {{#crossLink "loader/loadRes:method"}}{{/crossLink}}, + * the url will be the unique identity of the resource. + * After loaded, you can acquire them by passing the url to this API. + * + * @method getRes + * @param {String} url + * @param {Function} [type] - Only asset of type will be returned if this argument is supplied. + * @returns {*} + */ +proto.getRes = function (url, type) { + var item = this._cache[url]; + if (!item) { + var uuid = this._getResUuid(url, type, true); + if (uuid) { + var ref = this._getReferenceKey(uuid); + item = this._cache[ref]; } - }, - - /** - * !#en Resource all assets. Refer to {{#crossLink "loader/release:method"}}{{/crossLink}} for detailed informations. - * !#zh 释放所有资源。详细信息请参考 {{#crossLink "loader/release:method"}}{{/crossLink}} - * - * @method releaseAll - */ - releaseAll: function () { - for (var id in this._cache) { - this.release(id); + else { + return null; } - }, + } + if (item && item.alias) { + item = this._cache[item.alias]; + } + return (item && item.complete) ? item.content : null; +}; - // AUTO RELEASE +/** + * Get total resources count in loader. + * @returns {Number} + */ +proto.getResCount = function () { + return Object.keys(this._cache).length; +}; - // override - removeItem: function (key) { - var removed = Pipeline.prototype.removeItem.call(this, key); - delete this._autoReleaseSetting[key]; - return removed; - }, +/** + * !#en Get all resource dependencies of the requested asset in an array, including itself. + * The owner parameter accept the following types: 1. The asset itself; 2. The resource url; 3. The asset's uuid. + * The returned array stores the dependencies with their uuids, after retrieve dependencies, + * you can release them, access dependent assets by passing the uuid to {{#crossLink "loader/getRes:method"}}{{/crossLink}}, or other stuffs you want. + * For release all dependencies of an asset, please refer to {{#crossLink "loader/release:method"}}{{/crossLink}} + * Here is some examples: + * !#zh 获取一个指定资源的所有依赖资源,包含它自身,并保存在数组中返回。owner 参数接收以下几种类型: + * 1. 资源 asset 对象;2. 资源目录下的 url;3. 资源的 uuid + * 返回的数组将仅保存依赖资源的 uuid,获取这些 uuid 后,你可以从 loader 释放这些资源;通过 {{#crossLink "loader/getRes:method"}}{{/crossLink}} 获取某个资源或者其他你需要的处理。 + * 想要释放一个资源及其依赖资源,可以参考 {{#crossLink "loader/release:method"}}{{/crossLink}}。 + * 下面是一些示例代码: + * + * @example + * // Release all dependencies of a loaded prefab + * var deps = cc.loader.getDependsRecursively(prefab); + * cc.loader.release(deps); + * // Retrieve all dependent textures + * var deps = cc.loader.getDependsRecursively('prefabs/sample'); + * var textures = []; + * for (var i = 0; i < deps.length; ++i) { + * var item = cc.loader.getRes(deps[i]); + * if (item instanceof cc.Texture2D) { + * textures.push(item); + * } + * } + * + * @param {Asset|RawAsset|String} owner The owner asset or the resource url or the asset's uuid + * @returns {Array} + */ +proto.getDependsRecursively = function (owner) { + if (owner) { + var key = this._getReferenceKey(owner); + var assets = AutoReleaseUtils.getDependsRecursively(key); + assets.push(key); + return assets; + } + else { + return []; + } +}; - /** - * !#en - * Indicates whether to release the asset when loading a new scene.
- * By default, when loading a new scene, all assets in the previous scene will be released or preserved - * according to whether the previous scene checked the "Auto Release Assets" option. - * On the other hand, assets dynamically loaded by using `cc.loader.loadRes` or `cc.loader.loadResDir` - * will not be affected by that option, remain not released by default.
- * Use this API to change the default behavior on a single asset, to force preserve or release specified asset when scene switching.
- *
- * See: {{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}}, {{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}} - * !#zh - * 设置当场景切换时是否自动释放资源。
- * 默认情况下,当加载新场景时,旧场景的资源根据旧场景是否勾选“Auto Release Assets”,将会被释放或者保留。 - * 而使用 `cc.loader.loadRes` 或 `cc.loader.loadResDir` 动态加载的资源,则不受场景设置的影响,默认不自动释放。
- * 使用这个 API 可以在单个资源上改变这个默认行为,强制在切换场景时保留或者释放指定资源。
- *
- * 参考:{{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}},{{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}} - * - * @example - * // auto release the texture event if "Auto Release Assets" disabled in current scene - * cc.loader.setAutoRelease(texture2d, true); - * // don't release the texture even if "Auto Release Assets" enabled in current scene - * cc.loader.setAutoRelease(texture2d, false); - * // first parameter can be url - * cc.loader.setAutoRelease(audioUrl, false); - * - * @method setAutoRelease - * @param {Asset|String} assetOrUrlOrUuid - asset object or the raw asset's url or uuid - * @param {Boolean} autoRelease - indicates whether should release automatically - */ - setAutoRelease: function (assetOrUrlOrUuid, autoRelease) { - var key = this._getReferenceKey(assetOrUrlOrUuid); - if (key) { - this._autoReleaseSetting[key] = !!autoRelease; +/** + * !#en + * Release the content of an asset or an array of assets by uuid. + * Start from v1.3, this method will not only remove the cache of the asset in loader, but also clean up its content. + * For example, if you release a texture, the texture asset and its gl texture data will be freed up. + * In complexe project, you can use this function with {{#crossLink "loader/getDependsRecursively:method"}}{{/crossLink}} to free up memory in critical circumstances. + * Notice, this method may cause the texture to be unusable, if there are still other nodes use the same texture, they may turn to black and report gl errors. + * If you only want to remove the cache of an asset, please use {{#crossLink "pipeline/removeItem:method"}}{{/crossLink}} + * !#zh + * 通过 id(通常是资源 url)来释放一个资源或者一个资源数组。 + * 从 v1.3 开始,这个方法不仅会从 loader 中删除资源的缓存引用,还会清理它的资源内容。 + * 比如说,当你释放一个 texture 资源,这个 texture 和它的 gl 贴图数据都会被释放。 + * 在复杂项目中,我们建议你结合 {{#crossLink "loader/getDependsRecursively:method"}}{{/crossLink}} 来使用,便于在设备内存告急的情况下更快地释放不再需要的资源的内存。 + * 注意,这个函数可能会导致资源贴图或资源所依赖的贴图不可用,如果场景中存在节点仍然依赖同样的贴图,它们可能会变黑并报 GL 错误。 + * 如果你只想删除一个资源的缓存引用,请使用 {{#crossLink "pipeline/removeItem:method"}}{{/crossLink}} + * + * @example + * // Release a texture which is no longer need + * cc.loader.release(texture); + * // Release all dependencies of a loaded prefab + * var deps = cc.loader.getDependsRecursively('prefabs/sample'); + * cc.loader.release(deps); + * // If there is no instance of this prefab in the scene, the prefab and its dependencies like textures, sprite frames, etc, will be freed up. + * // If you have some other nodes share a texture in this prefab, you can skip it in two ways: + * // 1. Forbid auto release a texture before release + * cc.loader.setAutoRelease(texture2d, false); + * // 2. Remove it from the dependencies array + * var deps = cc.loader.getDependsRecursively('prefabs/sample'); + * var index = deps.indexOf(texture2d._uuid); + * if (index !== -1) + * deps.splice(index, 1); + * cc.loader.release(deps); + * + * @method release + * @param {Asset|RawAsset|String|Array} asset + */ +proto.release = function (asset) { + if (Array.isArray(asset)) { + for (let i = 0; i < asset.length; i++) { + var key = asset[i]; + this.release(key); } - else if (CC_DEV) { - cc.warnID(4902); - } - }, - - /** - * !#en - * Indicates whether to release the asset and its referenced other assets when loading a new scene.
- * By default, when loading a new scene, all assets in the previous scene will be released or preserved - * according to whether the previous scene checked the "Auto Release Assets" option. - * On the other hand, assets dynamically loaded by using `cc.loader.loadRes` or `cc.loader.loadResDir` - * will not be affected by that option, remain not released by default.
- * Use this API to change the default behavior on the specified asset and its recursively referenced assets, to force preserve or release specified asset when scene switching.
- *
- * See: {{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}}, {{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}} - * !#zh - * 设置当场景切换时是否自动释放资源及资源引用的其它资源。
- * 默认情况下,当加载新场景时,旧场景的资源根据旧场景是否勾选“Auto Release Assets”,将会被释放或者保留。 - * 而使用 `cc.loader.loadRes` 或 `cc.loader.loadResDir` 动态加载的资源,则不受场景设置的影响,默认不自动释放。
- * 使用这个 API 可以在指定资源及资源递归引用到的所有资源上改变这个默认行为,强制在切换场景时保留或者释放指定资源。
- *
- * 参考:{{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}},{{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}} - * - * @example - * // auto release the SpriteFrame and its Texture event if "Auto Release Assets" disabled in current scene - * cc.loader.setAutoReleaseRecursively(spriteFrame, true); - * // don't release the SpriteFrame and its Texture even if "Auto Release Assets" enabled in current scene - * cc.loader.setAutoReleaseRecursively(spriteFrame, false); - * // don't release the Prefab and all the referenced assets - * cc.loader.setAutoReleaseRecursively(prefab, false); - * - * @method setAutoReleaseRecursively - * @param {Asset|String} assetOrUrlOrUuid - asset object or the raw asset's url or uuid - * @param {Boolean} autoRelease - indicates whether should release automatically - */ - setAutoReleaseRecursively: function (assetOrUrlOrUuid, autoRelease) { - autoRelease = !!autoRelease; - var key = this._getReferenceKey(assetOrUrlOrUuid); - if (key) { - this._autoReleaseSetting[key] = autoRelease; - - var depends = AutoReleaseUtils.getDependsRecursively(key); - for (var i = 0; i < depends.length; i++) { - var depend = depends[i]; - this._autoReleaseSetting[depend] = autoRelease; + } + else if (asset) { + var id = this._getReferenceKey(asset); + var item = this.getItem(id); + if (item) { + var removed = this.removeItem(id); + asset = item.content; + // TODO: AUDIO + if (asset instanceof cc.Asset) { + if (CC_JSB && asset instanceof cc.SpriteFrame && removed) { + // for the "Temporary solution" in deserialize.js + asset.release(); + } + var urls = asset.rawUrls; + for (let i = 0; i < urls.length; i++) { + this.release(urls[i]); + } + } + else if (asset instanceof cc.Texture2D) { + cc.textureCache.removeTextureForKey(item.url); } } - else if (CC_DEV) { - cc.warnID(4902); - } - }, + } +}; - /** - * !#en - * Returns whether the asset is configured as auto released, despite how "Auto Release Assets" property is set on scene asset.
- *
- * See: {{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}}, {{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}} - * - * !#zh - * 返回指定的资源是否有被设置为自动释放,不论场景的“Auto Release Assets”如何设置。
- *
- * 参考:{{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}},{{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}} - * @method isAutoRelease - * @param {Asset|String} assetOrUrl - asset object or the raw asset's url - * @returns {Boolean} - */ - isAutoRelease: function (assetOrUrl) { - var key = this._getReferenceKey(assetOrUrl); - if (key) { - return !!this._autoReleaseSetting[key]; +/** + * !#en Release the asset by its object. Refer to {{#crossLink "loader/release:method"}}{{/crossLink}} for detailed informations. + * !#zh 通过资源对象自身来释放资源。详细信息请参考 {{#crossLink "loader/release:method"}}{{/crossLink}} + * + * @method releaseAsset + * @param {Asset} asset + */ +proto.releaseAsset = function (asset) { + var uuid = asset._uuid; + if (uuid) { + this.release(uuid); + } +}; + +/** + * !#en Release the asset loaded by {{#crossLink "loader/loadRes:method"}}{{/crossLink}}. Refer to {{#crossLink "loader/release:method"}}{{/crossLink}} for detailed informations. + * !#zh 释放通过 {{#crossLink "loader/loadRes:method"}}{{/crossLink}} 加载的资源。详细信息请参考 {{#crossLink "loader/release:method"}}{{/crossLink}} + * + * @method releaseRes + * @param {String} url + * @param {Function} [type] - Only asset of type will be released if this argument is supplied. + */ +proto.releaseRes = function (url, type) { + var uuid = this._getResUuid(url, type); + if (uuid) { + this.release(uuid); + } + else { + cc.errorID(4914, url); + } +}; + +/** + * !#en Release the all assets loaded by {{#crossLink "loader/loadResDir:method"}}{{/crossLink}}. Refer to {{#crossLink "loader/release:method"}}{{/crossLink}} for detailed informations. + * !#zh 释放通过 {{#crossLink "loader/loadResDir:method"}}{{/crossLink}} 加载的资源。详细信息请参考 {{#crossLink "loader/release:method"}}{{/crossLink}} + * + * @method releaseResDir + * @param {String} url + * @param {Function} [type] - Only asset of type will be released if this argument is supplied. + */ +proto.releaseResDir = function (url, type) { + var uuids = resources.getUuidArray(url, type); + for (var i = 0; i < uuids.length; i++) { + var uuid = uuids[i]; + this.release(uuid); + } +}; + +/** + * !#en Resource all assets. Refer to {{#crossLink "loader/release:method"}}{{/crossLink}} for detailed informations. + * !#zh 释放所有资源。详细信息请参考 {{#crossLink "loader/release:method"}}{{/crossLink}} + * + * @method releaseAll + */ +proto.releaseAll = function () { + for (var id in this._cache) { + this.release(id); + } +}; + +// AUTO RELEASE + +// override +proto.removeItem = function (key) { + var removed = Pipeline.prototype.removeItem.call(this, key); + delete this._autoReleaseSetting[key]; + return removed; +}; + +/** + * !#en + * Indicates whether to release the asset when loading a new scene.
+ * By default, when loading a new scene, all assets in the previous scene will be released or preserved + * according to whether the previous scene checked the "Auto Release Assets" option. + * On the other hand, assets dynamically loaded by using `cc.loader.loadRes` or `cc.loader.loadResDir` + * will not be affected by that option, remain not released by default.
+ * Use this API to change the default behavior on a single asset, to force preserve or release specified asset when scene switching.
+ *
+ * See: {{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}}, {{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}} + * !#zh + * 设置当场景切换时是否自动释放资源。
+ * 默认情况下,当加载新场景时,旧场景的资源根据旧场景是否勾选“Auto Release Assets”,将会被释放或者保留。 + * 而使用 `cc.loader.loadRes` 或 `cc.loader.loadResDir` 动态加载的资源,则不受场景设置的影响,默认不自动释放。
+ * 使用这个 API 可以在单个资源上改变这个默认行为,强制在切换场景时保留或者释放指定资源。
+ *
+ * 参考:{{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}},{{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}} + * + * @example + * // auto release the texture event if "Auto Release Assets" disabled in current scene + * cc.loader.setAutoRelease(texture2d, true); + * // don't release the texture even if "Auto Release Assets" enabled in current scene + * cc.loader.setAutoRelease(texture2d, false); + * // first parameter can be url + * cc.loader.setAutoRelease(audioUrl, false); + * + * @method setAutoRelease + * @param {Asset|String} assetOrUrlOrUuid - asset object or the raw asset's url or uuid + * @param {Boolean} autoRelease - indicates whether should release automatically + */ +proto.setAutoRelease = function (assetOrUrlOrUuid, autoRelease) { + var key = this._getReferenceKey(assetOrUrlOrUuid); + if (key) { + this._autoReleaseSetting[key] = !!autoRelease; + } + else if (CC_DEV) { + cc.warnID(4902); + } +}; + +/** + * !#en + * Indicates whether to release the asset and its referenced other assets when loading a new scene.
+ * By default, when loading a new scene, all assets in the previous scene will be released or preserved + * according to whether the previous scene checked the "Auto Release Assets" option. + * On the other hand, assets dynamically loaded by using `cc.loader.loadRes` or `cc.loader.loadResDir` + * will not be affected by that option, remain not released by default.
+ * Use this API to change the default behavior on the specified asset and its recursively referenced assets, to force preserve or release specified asset when scene switching.
+ *
+ * See: {{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}}, {{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}} + * !#zh + * 设置当场景切换时是否自动释放资源及资源引用的其它资源。
+ * 默认情况下,当加载新场景时,旧场景的资源根据旧场景是否勾选“Auto Release Assets”,将会被释放或者保留。 + * 而使用 `cc.loader.loadRes` 或 `cc.loader.loadResDir` 动态加载的资源,则不受场景设置的影响,默认不自动释放。
+ * 使用这个 API 可以在指定资源及资源递归引用到的所有资源上改变这个默认行为,强制在切换场景时保留或者释放指定资源。
+ *
+ * 参考:{{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}},{{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}} + * + * @example + * // auto release the SpriteFrame and its Texture event if "Auto Release Assets" disabled in current scene + * cc.loader.setAutoReleaseRecursively(spriteFrame, true); + * // don't release the SpriteFrame and its Texture even if "Auto Release Assets" enabled in current scene + * cc.loader.setAutoReleaseRecursively(spriteFrame, false); + * // don't release the Prefab and all the referenced assets + * cc.loader.setAutoReleaseRecursively(prefab, false); + * + * @method setAutoReleaseRecursively + * @param {Asset|String} assetOrUrlOrUuid - asset object or the raw asset's url or uuid + * @param {Boolean} autoRelease - indicates whether should release automatically + */ +proto.setAutoReleaseRecursively = function (assetOrUrlOrUuid, autoRelease) { + autoRelease = !!autoRelease; + var key = this._getReferenceKey(assetOrUrlOrUuid); + if (key) { + this._autoReleaseSetting[key] = autoRelease; + + var depends = AutoReleaseUtils.getDependsRecursively(key); + for (var i = 0; i < depends.length; i++) { + var depend = depends[i]; + this._autoReleaseSetting[depend] = autoRelease; } - return false; - }, -}); + } + else if (CC_DEV) { + cc.warnID(4902); + } +}; + +/** + * !#en + * Returns whether the asset is configured as auto released, despite how "Auto Release Assets" property is set on scene asset.
+ *
+ * See: {{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}}, {{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}} + * + * !#zh + * 返回指定的资源是否有被设置为自动释放,不论场景的“Auto Release Assets”如何设置。
+ *
+ * 参考:{{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}},{{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}} + * @method isAutoRelease + * @param {Asset|String} assetOrUrl - asset object or the raw asset's url + * @returns {Boolean} + */ +proto.isAutoRelease = function (assetOrUrl) { + var key = this._getReferenceKey(assetOrUrl); + if (key) { + return !!this._autoReleaseSetting[key]; + } + return false; +}; cc.loader = new CCLoader(); diff --git a/cocos2d/core/load-pipeline/asset-table.js b/cocos2d/core/load-pipeline/asset-table.js index 527ee31bdd..95b2ff2a67 100644 --- a/cocos2d/core/load-pipeline/asset-table.js +++ b/cocos2d/core/load-pipeline/asset-table.js @@ -47,121 +47,121 @@ function isMatchByWord (path, test) { return true; } -cc.js.mixin(AssetTable.prototype, { +var proto = AssetTable.prototype; - getUuid: function (path, type) { - path = cc.url.normalize(path); - var item = this._pathToUuid[path]; - if (item) { +proto.getUuid = function (path, type) { + path = cc.url.normalize(path); + var item = this._pathToUuid[path]; + if (item) { + if (Array.isArray(item)) { + if (type) { + for (var i = 0; i < item.length; i++) { + var entry = item[i]; + if (cc.isChildClassOf(entry.type, type)) { + return entry.uuid; + } + } + } + else { + return item[0].uuid; + } + } + else if (!type || cc.isChildClassOf(item.type, type)) { + return item.uuid; + } + } + return ''; +}; + +proto.getUuidArray = function (path, type, out_urls) { + path = cc.url.normalize(path); + if (path[path.length - 1] === '/') { + path = path.slice(0, -1); + } + var path2uuid = this._pathToUuid; + var uuids = []; + var isChildClassOf = cc.isChildClassOf; + for (var p in path2uuid) { + if ((p.startsWith(path) && isMatchByWord(p, path)) || !path) { + var item = path2uuid[p]; if (Array.isArray(item)) { - if (type) { - for (var i = 0; i < item.length; i++) { - var entry = item[i]; - if (cc.isChildClassOf(entry.type, type)) { - return entry.uuid; - } - } - } - else { - return item[0].uuid; - } - } - else if (!type || cc.isChildClassOf(item.type, type)) { - return item.uuid; - } - } - return ''; - }, - - getUuidArray: function (path, type, out_urls) { - path = cc.url.normalize(path); - if (path[path.length - 1] === '/') { - path = path.slice(0, -1); - } - var path2uuid = this._pathToUuid; - var uuids = []; - var isChildClassOf = cc.isChildClassOf; - for (var p in path2uuid) { - if ((p.startsWith(path) && isMatchByWord(p, path)) || !path) { - var item = path2uuid[p]; - if (Array.isArray(item)) { - for (var i = 0; i < item.length; i++) { - var entry = item[i]; - if (!type || isChildClassOf(entry.type, type)) { - uuids.push(entry.uuid); - if (out_urls) { - out_urls.push(p); - } - } - } - } - else { - if (!type || isChildClassOf(item.type, type)) { - uuids.push(item.uuid); + for (var i = 0; i < item.length; i++) { + var entry = item[i]; + if (!type || isChildClassOf(entry.type, type)) { + uuids.push(entry.uuid); if (out_urls) { out_urls.push(p); } } } } - } - return uuids; - }, - - /** - * !#en Returns all asset paths in the table. - * !#zh 返回表中的所有资源路径。 - * @method getAllPaths - * @return {string[]} - */ - getAllPaths: function () { - return Object.keys(this._pathToUuid); - }, - - /** - * !#en TODO - * !#zh 以路径为 key,uuid 为值添加到表中。 - * @method add - * @param {String} path - the path to load, should NOT include filename extensions. - * @param {String} uuid - * @param {Function} type - * @param {Boolean} isMainAsset - * @private - */ - add: function (path, uuid, type, isMainAsset) { - // remove extname - // (can not use path.slice because length of extname maybe 0) - path = path.substring(0, path.length - cc.path.extname(path).length); - var newEntry = new Entry(uuid, type); - var pathToUuid = this._pathToUuid; - var exists = pathToUuid[path]; - if (exists) { - if (Array.isArray(exists)) { - if (isMainAsset) { - // load main asset first - exists.unshift(newEntry); - } - else { - exists.push(newEntry); + else { + if (!type || isChildClassOf(item.type, type)) { + uuids.push(item.uuid); + if (out_urls) { + out_urls.push(p); + } } } + } + } + return uuids; +}; + +/** + * !#en Returns all asset paths in the table. + * !#zh 返回表中的所有资源路径。 + * @method getAllPaths + * @return {string[]} + */ +proto.getAllPaths = function () { + return Object.keys(this._pathToUuid); +}; + +/** + * !#en TODO + * !#zh 以路径为 key,uuid 为值添加到表中。 + * @method add + * @param {String} path - the path to load, should NOT include filename extensions. + * @param {String} uuid + * @param {Function} type + * @param {Boolean} isMainAsset + * @private + */ +proto.add = function (path, uuid, type, isMainAsset) { + // remove extname + // (can not use path.slice because length of extname maybe 0) + path = path.substring(0, path.length - cc.path.extname(path).length); + var newEntry = new Entry(uuid, type); + var pathToUuid = this._pathToUuid; + var exists = pathToUuid[path]; + if (exists) { + if (Array.isArray(exists)) { + if (isMainAsset) { + // load main asset first + exists.unshift(newEntry); + } else { - if (isMainAsset) { - pathToUuid[path] = [newEntry, exists]; - } - else { - pathToUuid[path] = [exists, newEntry]; - } + exists.push(newEntry); } } else { - pathToUuid[path] = newEntry; + if (isMainAsset) { + pathToUuid[path] = [newEntry, exists]; + } + else { + pathToUuid[path] = [exists, newEntry]; + } } - }, - - reset: function () { - this._pathToUuid = {}; } -}); + else { + pathToUuid[path] = newEntry; + } +}; + +proto.reset = function () { + this._pathToUuid = {}; +}; + module.exports = AssetTable; diff --git a/cocos2d/core/load-pipeline/downloader.js b/cocos2d/core/load-pipeline/downloader.js index 1e47dfc7c6..0a4124cee9 100644 --- a/cocos2d/core/load-pipeline/downloader.js +++ b/cocos2d/core/load-pipeline/downloader.js @@ -319,47 +319,46 @@ var Downloader = function (extMap) { this.extMap = JS.mixin(extMap, defaultMap); }; Downloader.ID = ID; -JS.mixin(Downloader.prototype, { - /** - * Add custom supported types handler or modify existing type handler. - * @method addHandlers - * @param {Object} extMap Custom supported types with corresponded handler - */ - addHandlers: function (extMap) { - JS.mixin(this.extMap, extMap); - }, - handle: function (item, callback) { - var self = this; - var downloadFunc = this.extMap[item.type] || this.extMap['default']; - if (this._curConcurrent < this.maxConcurrent) { - this._curConcurrent++; - downloadFunc.call(this, item, function (err, result) { - // Concurrent logic - self._curConcurrent = Math.max(0, self._curConcurrent - 1); - while (self._curConcurrent < self.maxConcurrent) { - var nextOne = self._loadQueue.shift(); - if (!nextOne) { - break; - } - self.handle(nextOne.item, nextOne.callback); +/** + * Add custom supported types handler or modify existing type handler. + * @method addHandlers + * @param {Object} extMap Custom supported types with corresponded handler + */ +Downloader.prototype.addHandlers = function (extMap) { + JS.mixin(this.extMap, extMap); +}; + +Downloader.prototype.handle = function (item, callback) { + var self = this; + var downloadFunc = this.extMap[item.type] || this.extMap['default']; + if (this._curConcurrent < this.maxConcurrent) { + this._curConcurrent++; + downloadFunc.call(this, item, function (err, result) { + // Concurrent logic + self._curConcurrent = Math.max(0, self._curConcurrent - 1); + while (self._curConcurrent < self.maxConcurrent) { + var nextOne = self._loadQueue.shift(); + if (!nextOne) { + break; } + self.handle(nextOne.item, nextOne.callback); + } - callback && callback(err, result); - }); - } - else if (item.ignoreMaxConcurrency) { - downloadFunc.call(this, item, function (err, result) { - callback && callback(err, result); - }); - } - else { - this._loadQueue.push({ - item: item, - callback: callback - }); - } + callback && callback(err, result); + }); } -}); + else if (item.ignoreMaxConcurrency) { + downloadFunc.call(this, item, function (err, result) { + callback && callback(err, result); + }); + } + else { + this._loadQueue.push({ + item: item, + callback: callback + }); + } +}; Pipeline.Downloader = module.exports = Downloader; diff --git a/cocos2d/core/load-pipeline/loader.js b/cocos2d/core/load-pipeline/loader.js index 2c416bf770..44af879cb4 100644 --- a/cocos2d/core/load-pipeline/loader.js +++ b/cocos2d/core/load-pipeline/loader.js @@ -137,27 +137,26 @@ var Loader = function (extMap) { this.extMap = JS.mixin(extMap, defaultMap); }; Loader.ID = ID; -JS.mixin(Loader.prototype, { - /** - * Add custom supported types handler or modify existing type handler. - * @method addHandlers - * @param {Object} extMap Custom supported types with corresponded handler - */ - addHandlers: function (extMap) { - this.extMap = JS.mixin(this.extMap, extMap); - }, - handle: function (item, callback) { - var loadFunc = this.extMap[item.type] || this.extMap['default']; - loadFunc.call(this, item, function (err, result) { - if (err) { - callback && callback(err); - } - else { - callback && callback(null, result); - } - }); - } -}); +/** + * Add custom supported types handler or modify existing type handler. + * @method addHandlers + * @param {Object} extMap Custom supported types with corresponded handler + */ +Loader.prototype.addHandlers = function (extMap) { + this.extMap = JS.mixin(this.extMap, extMap); +}; + +Loader.prototype.handle = function (item, callback) { + var loadFunc = this.extMap[item.type] || this.extMap['default']; + loadFunc.call(this, item, function (err, result) { + if (err) { + callback && callback(err); + } + else { + callback && callback(null, result); + } + }); +}; Pipeline.Loader = module.exports = Loader; diff --git a/cocos2d/core/load-pipeline/loading-items.js b/cocos2d/core/load-pipeline/loading-items.js index 8c643db7d2..b0977ba5d8 100644 --- a/cocos2d/core/load-pipeline/loading-items.js +++ b/cocos2d/core/load-pipeline/loading-items.js @@ -449,315 +449,316 @@ LoadingItems.finishDep = function (depId) { } }; -JS.mixin(LoadingItems.prototype, CallbacksInvoker.prototype, { - /** - * !#en Add urls to the LoadingItems queue. - * !#zh 向一个 LoadingItems 队列添加加载项。 - * @method append - * @param {Array} urlList The url list to be appended, the url can be object or string - * @return {Array} The accepted url list, some invalid items could be refused. - */ - append: function (urlList, owner) { - if (!this.active) { - return []; - } +var proto = LoadingItems.prototype; +JS.mixin(proto, CallbacksInvoker.prototype); - this._appending = true; - var accepted = [], i, url, item; - for (i = 0; i < urlList.length; ++i) { - url = urlList[i]; +/** + * !#en Add urls to the LoadingItems queue. + * !#zh 向一个 LoadingItems 队列添加加载项。 + * @method append + * @param {Array} urlList The url list to be appended, the url can be object or string + * @return {Array} The accepted url list, some invalid items could be refused. + */ +proto.append = function (urlList, owner) { + if (!this.active) { + return []; + } - // Already queued in another items queue, url is actually the item - if (url.queueId && !this.map[url.id]) { - this.map[url.id] = url; - // Queued and completed or Owner circle referenced by dependency - if (url.complete || checkCircleReference(owner, url)) { + this._appending = true; + var accepted = [], i, url, item; + for (i = 0; i < urlList.length; ++i) { + url = urlList[i]; + + // Already queued in another items queue, url is actually the item + if (url.queueId && !this.map[url.id]) { + this.map[url.id] = url; + // Queued and completed or Owner circle referenced by dependency + if (url.complete || checkCircleReference(owner, url)) { + this.totalCount++; + // console.log('----- Completed already or circle referenced ' + url.id + ', rest: ' + (this.totalCount - this.completedCount-1)); + this.itemComplete(url.id); + continue; + } + // Not completed yet, should wait it + else { + var self = this; + var queue = _queues[url.queueId]; + if (queue) { this.totalCount++; - // console.log('----- Completed already or circle referenced ' + url.id + ', rest: ' + (this.totalCount - this.completedCount-1)); - this.itemComplete(url.id); - continue; - } - // Not completed yet, should wait it - else { - var self = this; - var queue = _queues[url.queueId]; - if (queue) { - this.totalCount++; - LoadingItems.registerDep(owner || this._id, url.id); - // console.log('+++++ Waited ' + url.id); - queue.addListener(url.id, function (item) { - // console.log('----- Completed by waiting ' + item.id + ', rest: ' + (self.totalCount - self.completedCount-1)); - self.itemComplete(item.id); - }); - } - continue; - } - } - // Queue new items - if (isIdValid(url)) { - item = createItem(url, this._id); - var key = item.id; - // No duplicated url - if (!this.map[key]) { - this.map[key] = item; - this.totalCount++; - LoadingItems.registerDep(owner || this._id, key); - accepted.push(item); - // console.log('+++++ Appended ' + item.id); + LoadingItems.registerDep(owner || this._id, url.id); + // console.log('+++++ Waited ' + url.id); + queue.addListener(url.id, function (item) { + // console.log('----- Completed by waiting ' + item.id + ', rest: ' + (self.totalCount - self.completedCount-1)); + self.itemComplete(item.id); + }); } + continue; } } - this._appending = false; - - // Manually complete - if (this.completedCount === this.totalCount) { - // console.log('===== All Completed '); - this.allComplete(); - } - else { - this._pipeline.flowIn(accepted); - } - return accepted; - }, - - _childOnProgress: function (item) { - if (this.onProgress) { - var dep = _queueDeps[this._id]; - this.onProgress(dep ? dep.completed.length : this.completedCount, dep ? dep.deps.length : this.totalCount, item); - } - }, - - /** - * !#en Complete a LoadingItems queue, please do not call this method unless you know what's happening. - * !#zh 完成一个 LoadingItems 队列,请不要调用这个函数,除非你知道自己在做什么。 - * @method allComplete - */ - allComplete: function () { - var errors = this._errorUrls.length === 0 ? null : this._errorUrls; - if (this.onComplete) { - this.onComplete(errors, this); - } - }, - - /** - * !#en Check whether all items are completed. - * !#zh 检查是否所有加载项都已经完成。 - * @method isCompleted - * @return {Boolean} - */ - isCompleted: function () { - return this.completedCount >= this.totalCount; - }, - - /** - * !#en Check whether an item is completed. - * !#zh 通过 id 检查指定加载项是否已经加载完成。 - * @method isItemCompleted - * @param {String} id The item's id. - * @return {Boolean} - */ - isItemCompleted: function (id) { - return !!this.completed[id]; - }, - - /** - * !#en Check whether an item exists. - * !#zh 通过 id 检查加载项是否存在。 - * @method exists - * @param {String} id The item's id. - * @return {Boolean} - */ - exists: function (id) { - return !!this.map[id]; - }, - - /** - * !#en Returns the content of an internal item. - * !#zh 通过 id 获取指定对象的内容。 - * @method getContent - * @param {String} id The item's id. - * @return {Object} - */ - getContent: function (id) { - var item = this.map[id]; - var ret = null; - if (item) { - if (item.content) { - ret = item.content; + // Queue new items + if (isIdValid(url)) { + item = createItem(url, this._id); + var key = item.id; + // No duplicated url + if (!this.map[key]) { + this.map[key] = item; + this.totalCount++; + LoadingItems.registerDep(owner || this._id, key); + accepted.push(item); + // console.log('+++++ Appended ' + item.id); } - else if (item.alias) { - ret = this.getContent(item.alias); - } - } - - return ret; - }, - - /** - * !#en Returns the error of an internal item. - * !#zh 通过 id 获取指定对象的错误信息。 - * @method getError - * @param {String} id The item's id. - * @return {Object} - */ - getError: function (id) { - var item = this.map[id]; - var ret = null; - if (item) { - if (item.error) { - ret = item.error; - } else if (item.alias) { - ret = this.getError(item.alias); - } - } - - return ret; - }, - - /** - * !#en Add a listener for an item, the callback will be invoked when the item is completed. - * !#zh 监听加载项(通过 key 指定)的完成事件。 - * @method addListener - * @param {String} key - * @param {Function} callback - can be null - * @param {Object} target - can be null - * @return {Boolean} whether the key is new - */ - addListener: CallbacksInvoker.prototype.add, - - /** - * !#en - * Check if the specified key has any registered callback.
- * If a callback is also specified, it will only return true if the callback is registered. - * !#zh - * 检查指定的加载项是否有完成事件监听器。
- * 如果同时还指定了一个回调方法,并且回调有注册,它只会返回 true。 - * @method hasListener - * @param {String} key - * @param {Function} [callback] - * @param {Object} [target] - * @return {Boolean} - */ - hasListener: CallbacksInvoker.prototype.has, - - /** - * !#en - * Removes a listener.
- * It will only remove when key, callback, target all match correctly. - * !#zh - * 移除指定加载项已经注册的完成事件监听器。
- * 只会删除 key, callback, target 均匹配的监听器。 - * @method remove - * @param {String} key - * @param {Function} callback - * @param {Object} target - * @return {Boolean} removed - */ - removeListener: CallbacksInvoker.prototype.remove, - - /** - * !#en - * Removes all callbacks registered in a certain event - * type or all callbacks registered with a certain target. - * !#zh 删除指定目标的所有完成事件监听器。 - * @method removeAllListeners - * @param {String|Object} key - The event key to be removed or the target to be removed - */ - removeAllListeners: CallbacksInvoker.prototype.removeAll, - - /** - * !#en Remove an item, can only remove completed item, ongoing item can not be removed. - * !#zh 移除加载项,这里只会移除已经完成的加载项,正在进行的加载项将不能被删除。 - * @param {String} url - */ - removeItem: function (url) { - var item = this.map[url]; - if (!item) return; - - if (!this.completed[item.alias || url]) return; - - delete this.completed[url]; - delete this.map[url]; - if (item.alias) { - delete this.completed[item.alias]; - delete this.map[item.alias]; - } - - this.completedCount--; - this.totalCount--; - }, - - /** - * !#en Complete an item in the LoadingItems queue, please do not call this method unless you know what's happening. - * !#zh 通知 LoadingItems 队列一个 item 对象已完成,请不要调用这个函数,除非你知道自己在做什么。 - * @method itemComplete - * @param {String} id The item url - */ - itemComplete: function (id) { - var item = this.map[id]; - if (!item) { - return; - } - - // Register or unregister errors - var errorListId = this._errorUrls.indexOf(id); - if (item.error && errorListId === -1) { - this._errorUrls.push(id); - } - else if (!item.error && errorListId !== -1) { - this._errorUrls.splice(errorListId, 1); - } - - this.completed[id] = item; - this.completedCount++; - - LoadingItems.finishDep(item.id); - if (this.onProgress) { - var dep = _queueDeps[this._id]; - this.onProgress(dep ? dep.completed.length : this.completedCount, dep ? dep.deps.length : this.totalCount, item); - } - - this.invokeAndRemove(id, item); - - // All completed - if (!this._appending && this.completedCount >= this.totalCount) { - // console.log('===== All Completed '); - this.allComplete(); - } - }, - - /** - * !#en Destroy the LoadingItems queue, the queue object won't be garbage collected, it will be recycled, so every after destroy is not reliable. - * !#zh 销毁一个 LoadingItems 队列,这个队列对象会被内部缓冲池回收,所以销毁后的所有内部信息都是不可依赖的。 - * @method destroy - */ - destroy: function () { - this.active = false; - this._appending = false; - this._pipeline = null; - this._ownerQueue = null; - this._errorUrls.length = 0; - this.onProgress = null; - this.onComplete = null; - - this.map = {}; - this.completed = {}; - - this.totalCount = 0; - this.completedCount = 0; - - // Reinitialize CallbacksInvoker, generate three new objects, could be improved - CallbacksInvoker.call(this); - - _queues[this._id] = null; - if (_queueDeps[this._id]) { - _queueDeps[this._id].completed.length = 0; - _queueDeps[this._id].deps.length = 0; - } - if (_pool.indexOf(this) === -1 && _pool.length < _POOL_MAX_LENGTH) { - _pool.push(this); } } -}); + this._appending = false; + + // Manually complete + if (this.completedCount === this.totalCount) { + // console.log('===== All Completed '); + this.allComplete(); + } + else { + this._pipeline.flowIn(accepted); + } + return accepted; +}; + +proto._childOnProgress = function (item) { + if (this.onProgress) { + var dep = _queueDeps[this._id]; + this.onProgress(dep ? dep.completed.length : this.completedCount, dep ? dep.deps.length : this.totalCount, item); + } +}; + +/** + * !#en Complete a LoadingItems queue, please do not call this method unless you know what's happening. + * !#zh 完成一个 LoadingItems 队列,请不要调用这个函数,除非你知道自己在做什么。 + * @method allComplete + */ +proto.allComplete = function () { + var errors = this._errorUrls.length === 0 ? null : this._errorUrls; + if (this.onComplete) { + this.onComplete(errors, this); + } +}; + +/** + * !#en Check whether all items are completed. + * !#zh 检查是否所有加载项都已经完成。 + * @method isCompleted + * @return {Boolean} + */ +proto.isCompleted = function () { + return this.completedCount >= this.totalCount; +}; + +/** + * !#en Check whether an item is completed. + * !#zh 通过 id 检查指定加载项是否已经加载完成。 + * @method isItemCompleted + * @param {String} id The item's id. + * @return {Boolean} + */ +proto.isItemCompleted = function (id) { + return !!this.completed[id]; +}; + +/** + * !#en Check whether an item exists. + * !#zh 通过 id 检查加载项是否存在。 + * @method exists + * @param {String} id The item's id. + * @return {Boolean} + */ +proto.exists = function (id) { + return !!this.map[id]; +}; + +/** + * !#en Returns the content of an internal item. + * !#zh 通过 id 获取指定对象的内容。 + * @method getContent + * @param {String} id The item's id. + * @return {Object} + */ +proto.getContent = function (id) { + var item = this.map[id]; + var ret = null; + if (item) { + if (item.content) { + ret = item.content; + } + else if (item.alias) { + ret = this.getContent(item.alias); + } + } + + return ret; +}; + +/** + * !#en Returns the error of an internal item. + * !#zh 通过 id 获取指定对象的错误信息。 + * @method getError + * @param {String} id The item's id. + * @return {Object} + */ +proto.getError = function (id) { + var item = this.map[id]; + var ret = null; + if (item) { + if (item.error) { + ret = item.error; + } else if (item.alias) { + ret = this.getError(item.alias); + } + } + + return ret; +}; + +/** + * !#en Add a listener for an item, the callback will be invoked when the item is completed. + * !#zh 监听加载项(通过 key 指定)的完成事件。 + * @method addListener + * @param {String} key + * @param {Function} callback - can be null + * @param {Object} target - can be null + * @return {Boolean} whether the key is new + */ +proto.addListener = CallbacksInvoker.prototype.add; + +/** + * !#en + * Check if the specified key has any registered callback.
+ * If a callback is also specified, it will only return true if the callback is registered. + * !#zh + * 检查指定的加载项是否有完成事件监听器。
+ * 如果同时还指定了一个回调方法,并且回调有注册,它只会返回 true。 + * @method hasListener + * @param {String} key + * @param {Function} [callback] + * @param {Object} [target] + * @return {Boolean} + */ +proto.hasListener = CallbacksInvoker.prototype.has; + +/** + * !#en + * Removes a listener.
+ * It will only remove when key, callback, target all match correctly. + * !#zh + * 移除指定加载项已经注册的完成事件监听器。
+ * 只会删除 key, callback, target 均匹配的监听器。 + * @method remove + * @param {String} key + * @param {Function} callback + * @param {Object} target + * @return {Boolean} removed + */ +proto.removeListener = CallbacksInvoker.prototype.remove; + +/** + * !#en + * Removes all callbacks registered in a certain event + * type or all callbacks registered with a certain target. + * !#zh 删除指定目标的所有完成事件监听器。 + * @method removeAllListeners + * @param {String|Object} key - The event key to be removed or the target to be removed + */ +proto.removeAllListeners = CallbacksInvoker.prototype.removeAll; + +/** + * !#en Remove an item, can only remove completed item, ongoing item can not be removed. + * !#zh 移除加载项,这里只会移除已经完成的加载项,正在进行的加载项将不能被删除。 + * @param {String} url + */ +proto.removeItem = function (url) { + var item = this.map[url]; + if (!item) return; + + if (!this.completed[item.alias || url]) return; + + delete this.completed[url]; + delete this.map[url]; + if (item.alias) { + delete this.completed[item.alias]; + delete this.map[item.alias]; + } + + this.completedCount--; + this.totalCount--; +}; + +/** + * !#en Complete an item in the LoadingItems queue, please do not call this method unless you know what's happening. + * !#zh 通知 LoadingItems 队列一个 item 对象已完成,请不要调用这个函数,除非你知道自己在做什么。 + * @method itemComplete + * @param {String} id The item url + */ +proto.itemComplete = function (id) { + var item = this.map[id]; + if (!item) { + return; + } + + // Register or unregister errors + var errorListId = this._errorUrls.indexOf(id); + if (item.error && errorListId === -1) { + this._errorUrls.push(id); + } + else if (!item.error && errorListId !== -1) { + this._errorUrls.splice(errorListId, 1); + } + + this.completed[id] = item; + this.completedCount++; + + LoadingItems.finishDep(item.id); + if (this.onProgress) { + var dep = _queueDeps[this._id]; + this.onProgress(dep ? dep.completed.length : this.completedCount, dep ? dep.deps.length : this.totalCount, item); + } + + this.invokeAndRemove(id, item); + + // All completed + if (!this._appending && this.completedCount >= this.totalCount) { + // console.log('===== All Completed '); + this.allComplete(); + } +}; + +/** + * !#en Destroy the LoadingItems queue, the queue object won't be garbage collected, it will be recycled, so every after destroy is not reliable. + * !#zh 销毁一个 LoadingItems 队列,这个队列对象会被内部缓冲池回收,所以销毁后的所有内部信息都是不可依赖的。 + * @method destroy + */ +proto.destroy = function () { + this.active = false; + this._appending = false; + this._pipeline = null; + this._ownerQueue = null; + this._errorUrls.length = 0; + this.onProgress = null; + this.onComplete = null; + + this.map = {}; + this.completed = {}; + + this.totalCount = 0; + this.completedCount = 0; + + // Reinitialize CallbacksInvoker, generate three new objects, could be improved + CallbacksInvoker.call(this); + + _queues[this._id] = null; + if (_queueDeps[this._id]) { + _queueDeps[this._id].completed.length = 0; + _queueDeps[this._id].deps.length = 0; + } + if (_pool.indexOf(this) === -1 && _pool.length < _POOL_MAX_LENGTH) { + _pool.push(this); + } +}; cc.LoadingItems = module.exports = LoadingItems; diff --git a/cocos2d/core/load-pipeline/pipeline.js b/cocos2d/core/load-pipeline/pipeline.js index 85b352d01b..6b8dfcc974 100644 --- a/cocos2d/core/load-pipeline/pipeline.js +++ b/cocos2d/core/load-pipeline/pipeline.js @@ -167,245 +167,245 @@ var Pipeline = function (pipes) { Pipeline.ItemState = ItemState; -JS.mixin(Pipeline.prototype, { - /** - * !#en - * Insert a new pipe at the given index of the pipeline.
- * A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline. - * !#zh - * 在给定的索引位置插入一个新的 pipe。
- * 一个 pipe 必须包含一个字符串类型的 ‘id’ 和 ‘handle’ 函数,该 id 在 pipeline 必须是唯一标识。 - * @method insertPipe - * @param {Object} pipe The pipe to be inserted - * @param {Number} index The index to insert - */ - insertPipe: function (pipe, index) { - // Must have handle and id, handle for flow, id for state flag - if (!pipe.handle || !pipe.id) { - return; - } +var proto = Pipeline.prototype; - pipe.pipeline = this; - pipe.flowIn = pipe.async ? asyncFlow : syncFlow; - if (index < this._pipes.length) { - pipe.next = this._pipes[index]; - this._pipes.splice(index, 0, pipe); - } - else { - pipe.next = null; - this._pipes.push(pipe); - } - }, +/** + * !#en + * Insert a new pipe at the given index of the pipeline.
+ * A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline. + * !#zh + * 在给定的索引位置插入一个新的 pipe。
+ * 一个 pipe 必须包含一个字符串类型的 ‘id’ 和 ‘handle’ 函数,该 id 在 pipeline 必须是唯一标识。 + * @method insertPipe + * @param {Object} pipe The pipe to be inserted + * @param {Number} index The index to insert + */ +proto.insertPipe = function (pipe, index) { + // Must have handle and id, handle for flow, id for state flag + if (!pipe.handle || !pipe.id) { + return; + } - /** - * !#en - * Add a new pipe at the end of the pipeline.
- * A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline. - * !#zh - * 添加一个新的 pipe 到 pipeline 尾部。
- * 该 pipe 必须包含一个字符串类型 ‘id’ 和 ‘handle’ 函数,该 id 在 pipeline 必须是唯一标识。 - * @method appendPipe - * @param {Object} pipe The pipe to be appended - */ - appendPipe: function (pipe) { - // Must have handle and id, handle for flow, id for state flag - if (!pipe.handle || !pipe.id) { - return; - } - - pipe.pipeline = this; + pipe.pipeline = this; + pipe.flowIn = pipe.async ? asyncFlow : syncFlow; + if (index < this._pipes.length) { + pipe.next = this._pipes[index]; + this._pipes.splice(index, 0, pipe); + } + else { pipe.next = null; - pipe.flowIn = pipe.async ? asyncFlow : syncFlow; this._pipes.push(pipe); - }, + } +}; - /** - * !#en - * Let new items flow into the pipeline.
- * Each item can be a simple url string or an object, - * if it's an object, it must contain `id` property.
- * You can specify its type by `type` property, by default, the type is the extension name in url.
- * By adding a `skips` property including pipe ids, you can skip these pipe.
- * The object can contain any supplementary property as you want.
- * !#zh - * 让新的 item 流入 pipeline 中。
- * 这里的每个 item 可以是一个简单字符串类型的 url 或者是一个对象, - * 如果它是一个对象的话,他必须要包含 ‘id’ 属性。
- * 你也可以指定它的 ‘type’ 属性类型,默认情况下,该类型是 ‘url’ 的后缀名。
- * 也通过添加一个 包含 ‘skips’ 属性的 item 对象,你就可以跳过 skips 中包含的 pipe。
- * 该对象可以包含任何附加属性。 - * @method flowIn - * @param {Array} items - * @example - * pipeline.flowIn([ - * 'res/Background.png', - * { - * id: 'res/scene.json', - * type: 'scene', - * name: 'scene', - * skips: ['Downloader'] - * } - * ]); - */ - flowIn: function (items) { - var i, pipe = this._pipes[0], item; - if (pipe) { - for (i = 0; i < items.length; i++) { - item = items[i]; - this._cache[item.id] = item; - pipe.flowIn(item); - } - } - else { - for (i = 0; i < items.length; i++) { - this.flowOut(items[i]); - } - } - }, +/** + * !#en + * Add a new pipe at the end of the pipeline.
+ * A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline. + * !#zh + * 添加一个新的 pipe 到 pipeline 尾部。
+ * 该 pipe 必须包含一个字符串类型 ‘id’ 和 ‘handle’ 函数,该 id 在 pipeline 必须是唯一标识。 + * @method appendPipe + * @param {Object} pipe The pipe to be appended + */ +proto.appendPipe = function (pipe) { + // Must have handle and id, handle for flow, id for state flag + if (!pipe.handle || !pipe.id) { + return; + } - /** - * !#en - * Let new items flow into the pipeline and give a callback when the list of items are all completed.
- * This is for loading dependencies for an existing item in flow, usually used in a pipe logic.
- * For example, we have a loader for scene configuration file in JSON, the scene will only be fully loaded
- * after all its dependencies are loaded, then you will need to use function to flow in all dependencies
- * found in the configuration file, and finish the loader pipe only after all dependencies are loaded (in the callback). - * !#zh - * 让新 items 流入 pipeline 并且当 item 列表完成时进行回调函数。
- * 这个 API 的使用通常是为了加载依赖项。
- * 例如:
- * 我们需要加载一个场景配置的 JSON 文件,该场景会将所有的依赖项全部都加载完毕以后,进行回调表示加载完毕。 - * @method flowInDeps - * @deprecated since v1.3 - * @param {Array} urlList - * @param {Function} callback - * @return {Array} Items accepted by the pipeline - */ - flowInDeps: function (owner, urlList, callback) { - var deps = LoadingItems.create(this, function (errors, items) { - callback(errors, items); - items.destroy(); - }); - return deps.append(urlList, owner); - }, + pipe.pipeline = this; + pipe.next = null; + pipe.flowIn = pipe.async ? asyncFlow : syncFlow; + this._pipes.push(pipe); +}; - flowOut: function (item) { - if (item.error) { - delete this._cache[item.id]; - } - else if (!this._cache[item.id]) { +/** + * !#en + * Let new items flow into the pipeline.
+ * Each item can be a simple url string or an object, + * if it's an object, it must contain `id` property.
+ * You can specify its type by `type` property, by default, the type is the extension name in url.
+ * By adding a `skips` property including pipe ids, you can skip these pipe.
+ * The object can contain any supplementary property as you want.
+ * !#zh + * 让新的 item 流入 pipeline 中。
+ * 这里的每个 item 可以是一个简单字符串类型的 url 或者是一个对象, + * 如果它是一个对象的话,他必须要包含 ‘id’ 属性。
+ * 你也可以指定它的 ‘type’ 属性类型,默认情况下,该类型是 ‘url’ 的后缀名。
+ * 也通过添加一个 包含 ‘skips’ 属性的 item 对象,你就可以跳过 skips 中包含的 pipe。
+ * 该对象可以包含任何附加属性。 + * @method flowIn + * @param {Array} items + * @example + * pipeline.flowIn([ + * 'res/Background.png', + * { + * id: 'res/scene.json', + * type: 'scene', + * name: 'scene', + * skips: ['Downloader'] + * } + * ]); + */ +proto.flowIn = function (items) { + var i, pipe = this._pipes[0], item; + if (pipe) { + for (i = 0; i < items.length; i++) { + item = items[i]; this._cache[item.id] = item; - } - item.complete = true; - LoadingItems.itemComplete(item); - }, - - /** - * !#en - * Copy the item states from one source item to all destination items.
- * It's quite useful when a pipe generate new items from one source item,
- * then you should flowIn these generated items into pipeline,
- * but you probably want them to skip all pipes the source item already go through,
- * you can achieve it with this API.
- *
- * For example, an unzip pipe will generate more items, but you won't want them to pass unzip or download pipe again. - * !#zh - * 从一个源 item 向所有目标 item 复制它的 pipe 状态,用于避免重复通过部分 pipe。
- * 当一个源 item 生成了一系列新的 items 时很有用,
- * 你希望让这些新的依赖项进入 pipeline,但是又不希望它们通过源 item 已经经过的 pipe,
- * 但是你可能希望他们源 item 已经通过并跳过所有 pipes,
- * 这个时候就可以使用这个 API。 - * @method copyItemStates - * @param {Object} srcItem The source item - * @param {Array|Object} dstItems A single destination item or an array of destination items - */ - copyItemStates: function (srcItem, dstItems) { - if (!(dstItems instanceof Array)) { - dstItems.states = srcItem.states; - return; - } - for (var i = 0; i < dstItems.length; ++i) { - dstItems[i].states = srcItem.states; - } - }, - - /** - * !#en Returns whether the pipeline is flowing (contains item) currently. - * !#zh 获取 pipeline 当前是否正在处理中。 - * @method isFlowing - * @return {Boolean} - * @deprecated since v1.3 - */ - isFlowing: function () { - return true; - }, - - /** - * !#en Returns all items in pipeline. - * !#zh 获取 pipeline 中的所有 items。 - * @method getItems - * @return {LoadingItems} - * @deprecated since v1.3 - */ - getItems: function () { - return null; - }, - - /** - * !#en Returns an item in pipeline. - * !#zh 根据 id 获取一个 item - * @method getItem - * @param {Object} id The id of the item - * @return {Object} - */ - getItem: function (id) { - var item = this._cache[id]; - - if (!item) - return item; - - // downloader.js downloadUuid - if (item.alias) - item = this._cache[item.alias]; - - return item; - }, - - /** - * !#en Removes an completed item in pipeline. - * It will only remove the cache in the pipeline or loader, its dependencies won't be released. - * cc.loader provided another method to completely cleanup the resource and its dependencies, - * please refer to {{#crossLink "loader/release:method"}}cc.loader.release{{/crossLink}} - * !#zh 移除指定的已完成 item。 - * 这将仅仅从 pipeline 或者 loader 中删除其缓存,并不会释放它所依赖的资源。 - * cc.loader 中提供了另一种删除资源及其依赖的清理方法,请参考 {{#crossLink "loader/release:method"}}cc.loader.release{{/crossLink}} - * @method removeItem - * @param {Object} id The id of the item - * @return {Boolean} succeed or not - */ - removeItem: function (id) { - var removed = this._cache[id]; - if (removed && removed.complete) { - delete this._cache[id]; - } - return removed; - }, - - /** - * !#en Clear the current pipeline, this function will clean up the items. - * !#zh 清空当前 pipeline,该函数将清理 items。 - * @method clear - */ - clear: function () { - for (var id in this._cache) { - var item = this._cache[id]; - delete this._cache[id]; - if (!item.complete) { - item.error = new Error('Canceled manually'); - this.flowOut(item); - } + pipe.flowIn(item); } } -}); + else { + for (i = 0; i < items.length; i++) { + this.flowOut(items[i]); + } + } +}; + +/** + * !#en + * Let new items flow into the pipeline and give a callback when the list of items are all completed.
+ * This is for loading dependencies for an existing item in flow, usually used in a pipe logic.
+ * For example, we have a loader for scene configuration file in JSON, the scene will only be fully loaded
+ * after all its dependencies are loaded, then you will need to use function to flow in all dependencies
+ * found in the configuration file, and finish the loader pipe only after all dependencies are loaded (in the callback). + * !#zh + * 让新 items 流入 pipeline 并且当 item 列表完成时进行回调函数。
+ * 这个 API 的使用通常是为了加载依赖项。
+ * 例如:
+ * 我们需要加载一个场景配置的 JSON 文件,该场景会将所有的依赖项全部都加载完毕以后,进行回调表示加载完毕。 + * @method flowInDeps + * @deprecated since v1.3 + * @param {Array} urlList + * @param {Function} callback + * @return {Array} Items accepted by the pipeline + */ +proto.flowInDeps = function (owner, urlList, callback) { + var deps = LoadingItems.create(this, function (errors, items) { + callback(errors, items); + items.destroy(); + }); + return deps.append(urlList, owner); +}; + +proto.flowOut = function (item) { + if (item.error) { + delete this._cache[item.id]; + } + else if (!this._cache[item.id]) { + this._cache[item.id] = item; + } + item.complete = true; + LoadingItems.itemComplete(item); +}; + +/** + * !#en + * Copy the item states from one source item to all destination items.
+ * It's quite useful when a pipe generate new items from one source item,
+ * then you should flowIn these generated items into pipeline,
+ * but you probably want them to skip all pipes the source item already go through,
+ * you can achieve it with this API.
+ *
+ * For example, an unzip pipe will generate more items, but you won't want them to pass unzip or download pipe again. + * !#zh + * 从一个源 item 向所有目标 item 复制它的 pipe 状态,用于避免重复通过部分 pipe。
+ * 当一个源 item 生成了一系列新的 items 时很有用,
+ * 你希望让这些新的依赖项进入 pipeline,但是又不希望它们通过源 item 已经经过的 pipe,
+ * 但是你可能希望他们源 item 已经通过并跳过所有 pipes,
+ * 这个时候就可以使用这个 API。 + * @method copyItemStates + * @param {Object} srcItem The source item + * @param {Array|Object} dstItems A single destination item or an array of destination items + */ +proto.copyItemStates = function (srcItem, dstItems) { + if (!(dstItems instanceof Array)) { + dstItems.states = srcItem.states; + return; + } + for (var i = 0; i < dstItems.length; ++i) { + dstItems[i].states = srcItem.states; + } +}; + +/** + * !#en Returns whether the pipeline is flowing (contains item) currently. + * !#zh 获取 pipeline 当前是否正在处理中。 + * @method isFlowing + * @return {Boolean} + * @deprecated since v1.3 + */ +proto.isFlowing = function () { + return true; +}; + +/** + * !#en Returns all items in pipeline. + * !#zh 获取 pipeline 中的所有 items。 + * @method getItems + * @return {LoadingItems} + * @deprecated since v1.3 + */ +proto.getItems = function () { + return null; +}; + +/** + * !#en Returns an item in pipeline. + * !#zh 根据 id 获取一个 item + * @method getItem + * @param {Object} id The id of the item + * @return {Object} + */ +proto.getItem = function (id) { + var item = this._cache[id]; + + if (!item) + return item; + + // downloader.js downloadUuid + if (item.alias) + item = this._cache[item.alias]; + + return item; +}; + +/** + * !#en Removes an completed item in pipeline. + * It will only remove the cache in the pipeline or loader, its dependencies won't be released. + * cc.loader provided another method to completely cleanup the resource and its dependencies, + * please refer to {{#crossLink "loader/release:method"}}cc.loader.release{{/crossLink}} + * !#zh 移除指定的已完成 item。 + * 这将仅仅从 pipeline 或者 loader 中删除其缓存,并不会释放它所依赖的资源。 + * cc.loader 中提供了另一种删除资源及其依赖的清理方法,请参考 {{#crossLink "loader/release:method"}}cc.loader.release{{/crossLink}} + * @method removeItem + * @param {Object} id The id of the item + * @return {Boolean} succeed or not + */ +proto.removeItem = function (id) { + var removed = this._cache[id]; + if (removed && removed.complete) { + delete this._cache[id]; + } + return removed; +}; + +/** + * !#en Clear the current pipeline, this function will clean up the items. + * !#zh 清空当前 pipeline,该函数将清理 items。 + * @method clear + */ +proto.clear = function () { + for (var id in this._cache) { + var item = this._cache[id]; + delete this._cache[id]; + if (!item.complete) { + item.error = new Error('Canceled manually'); + this.flowOut(item); + } + } +}; cc.Pipeline = module.exports = Pipeline; diff --git a/cocos2d/core/platform/instantiate-jit.js b/cocos2d/core/platform/instantiate-jit.js index 47b78d44ea..340b24c18d 100644 --- a/cocos2d/core/platform/instantiate-jit.js +++ b/cocos2d/core/platform/instantiate-jit.js @@ -176,234 +176,233 @@ function Parser (obj, parent) { this.objsToClear_iN$t.length = 0; } -JS.mixin(Parser.prototype, { +var proto = Parser.prototype; - getFuncModule: function (func, usedInNew) { - var clsName = JS.getClassName(func); - var clsNameIsModule = clsName.indexOf('.') !== -1; - if (clsNameIsModule) { - try { - // ensure is module - clsNameIsModule = (func === Function('return ' + clsName)()); - if (clsNameIsModule) { - return clsName; - } +proto.getFuncModule = function (func, usedInNew) { + var clsName = JS.getClassName(func); + var clsNameIsModule = clsName.indexOf('.') !== -1; + if (clsNameIsModule) { + try { + // ensure is module + clsNameIsModule = (func === Function('return ' + clsName)()); + if (clsNameIsModule) { + return clsName; } - catch (e) {} } - var index = this.funcs.indexOf(func); - if (index < 0) { - index = this.funcs.length; - this.funcs.push(func); - } - var res = 'F[' + index + ']'; - return usedInNew ? '(' + res + ')' : res; - }, + catch (e) {} + } + var index = this.funcs.indexOf(func); + if (index < 0) { + index = this.funcs.length; + this.funcs.push(func); + } + var res = 'F[' + index + ']'; + return usedInNew ? '(' + res + ')' : res; +}; - getObjRef: function (obj) { - var index = this.objs.indexOf(obj); - if (index < 0) { - index = this.objs.length; - this.objs.push(obj); - } - return 'O[' + index + ']'; - }, +proto.getObjRef = function (obj) { + var index = this.objs.indexOf(obj); + if (index < 0) { + index = this.objs.length; + this.objs.push(obj); + } + return 'O[' + index + ']'; +}; - enumerateCCClass: function (codeArray, obj, klass) { - var props = klass.__props__; - var attrs = Attr.getClassAttrs(klass); - for (var p = 0; p < props.length; p++) { - var key = props[p]; - if (CC_EDITOR && key === '_id') { +proto.enumerateCCClass = function (codeArray, obj, klass) { + var props = klass.__props__; + var attrs = Attr.getClassAttrs(klass); + for (var p = 0; p < props.length; p++) { + var key = props[p]; + if (CC_EDITOR && key === '_id') { + if (obj instanceof cc._BaseNode || obj instanceof cc.Component) { + continue; + } + } + if (attrs[key + SERIALIZABLE] !== false) { + var val = obj[key]; + if (equalsToDefault(attrs[key + DEFAULT], val)) { + continue; + } + this.writeObjectField(codeArray, obj, key, val); + } + } +}; + +proto.instantiateArray = function (value) { + if (value.length === 0) { + return '[]'; + } + + var arrayVar = 't' + (++this.localVariableId); + var declaration = new Declaration(arrayVar, 'new Array(' + value.length + ')'); + var codeArray = [declaration]; + + // assign a _iN$t flag to indicate that this object has been parsed. + value._iN$t = { + globalVar: '', // the name of declared global variable used to access this object + source: codeArray, // the source code array for this object + }; + this.objsToClear_iN$t.push(value); + + for (var i = 0; i < value.length; ++i) { + var statement = arrayVar + '[' + i + ']='; + this.writeFiled(codeArray, statement, value, i, value[i]); + } + return codeArray; +}; + +proto.enumerateField = function (obj, key, value) { + if (typeof value === 'object' && value) { + var _iN$t = value._iN$t; + if (_iN$t) { + // parsed + var globalVar = _iN$t.globalVar; + if (!globalVar) { + // declare a global var + globalVar = _iN$t.globalVar = 'v' + (++this.globalVariableId); + this.globalVariables.push(globalVar); + // insert assignment statement to assign to global var + var line = _iN$t.source[LINE_INDEX_OF_NEW_OBJ]; + _iN$t.source[LINE_INDEX_OF_NEW_OBJ] = mergeDeclaration(globalVar + '=', line); + // if (typeof line ==='string' && line.startsWith(VAR)) { + // // var o=xxx -> var o=global=xxx + // var LEN_OF_VAR_O = 5; + // _iN$t.source[LINE_INDEX_OF_NEW_OBJ] = line.slice(0, LEN_OF_VAR_O) + '=' + globalVar + line.slice(LEN_OF_VAR_O); + // } + } + return globalVar; + } + else if (Array.isArray(value)) { + return this.instantiateArray(value); + } + else { + return this.instantiateObj(value); + } + } + else if (typeof value === 'function') { + return this.getFuncModule(value); + } + else if (typeof value === 'string') { + return escapeForJS(value); + } + else { + if (key === '_objFlags' && obj instanceof CCObject) { + value &= PersistentMask; + } + return value; + } +}; + +proto.writeObjectField = function (codeArray, obj, key, value) { + var statement; + if (IDENTIFIER_RE.test(key)) { + statement = LOCAL_OBJ + '.' + key + '='; + } + else { + statement = LOCAL_OBJ + '[' + escapeForJS(key) + ']='; + } + this.writeFiled(codeArray, statement, obj, key, value); +}; + +proto.writeFiled = function (codeArray, statement, obj, key, value) { + var expression = this.enumerateField(obj, key, value); + if (Array.isArray(expression)) { + expression[0] = mergeDeclaration(statement, expression[0]); + codeArray.push(expression); + } + else { + codeArray.push(mergeDeclaration(statement, expression) + ';'); + } +}; + +// codeArray - the source code array for this object +proto.enumerateObject = function (codeArray, obj) { + var klass = obj.constructor; + if (cc.Class._isCCClass(klass)) { + this.enumerateCCClass(codeArray, obj, klass); + } + else { + // primitive javascript object + for (var key in obj) { + if (!obj.hasOwnProperty(key) || + (key.charCodeAt(0) === 95 && key.charCodeAt(1) === 95 && // starts with "__" + key !== '__type__') + ) { + continue; + } + var value = obj[key]; + if (typeof value === 'object' && value && value === obj._iN$t) { + continue; + } + this.writeObjectField(codeArray, obj, key, value); + } + } +}; + +proto.instantiateObj = function (obj) { + if (obj instanceof cc.ValueType) { + return CCClass.getNewValueTypeCode(obj); + } + if (obj instanceof cc.Asset) { + // register to asset list and just return the reference. + return this.getObjRef(obj); + } + if (obj._objFlags & Destroyed) { + // the same as cc.isValid(obj) + return null; + } + + var createCode; + var ctor = obj.constructor; + if (cc.Class._isCCClass(ctor)) { + if (this.parent) { + if (this.parent instanceof cc.Component) { if (obj instanceof cc._BaseNode || obj instanceof cc.Component) { - continue; + return this.getObjRef(obj); } } - if (attrs[key + SERIALIZABLE] !== false) { - var val = obj[key]; - if (equalsToDefault(attrs[key + DEFAULT], val)) { - continue; - } - this.writeObjectField(codeArray, obj, key, val); - } - } - }, - - instantiateArray: function (value) { - if (value.length === 0) { - return '[]'; - } - - var arrayVar = 't' + (++this.localVariableId); - var declaration = new Declaration(arrayVar, 'new Array(' + value.length + ')'); - var codeArray = [declaration]; - - // assign a _iN$t flag to indicate that this object has been parsed. - value._iN$t = { - globalVar: '', // the name of declared global variable used to access this object - source: codeArray, // the source code array for this object - }; - this.objsToClear_iN$t.push(value); - - for (var i = 0; i < value.length; ++i) { - var statement = arrayVar + '[' + i + ']='; - this.writeFiled(codeArray, statement, value, i, value[i]); - } - return codeArray; - }, - - enumerateField: function (obj, key, value) { - if (typeof value === 'object' && value) { - var _iN$t = value._iN$t; - if (_iN$t) { - // parsed - var globalVar = _iN$t.globalVar; - if (!globalVar) { - // declare a global var - globalVar = _iN$t.globalVar = 'v' + (++this.globalVariableId); - this.globalVariables.push(globalVar); - // insert assignment statement to assign to global var - var line = _iN$t.source[LINE_INDEX_OF_NEW_OBJ]; - _iN$t.source[LINE_INDEX_OF_NEW_OBJ] = mergeDeclaration(globalVar + '=', line); - // if (typeof line ==='string' && line.startsWith(VAR)) { - // // var o=xxx -> var o=global=xxx - // var LEN_OF_VAR_O = 5; - // _iN$t.source[LINE_INDEX_OF_NEW_OBJ] = line.slice(0, LEN_OF_VAR_O) + '=' + globalVar + line.slice(LEN_OF_VAR_O); - // } - } - return globalVar; - } - else if (Array.isArray(value)) { - return this.instantiateArray(value); - } - else { - return this.instantiateObj(value); - } - } - else if (typeof value === 'function') { - return this.getFuncModule(value); - } - else if (typeof value === 'string') { - return escapeForJS(value); - } - else { - if (key === '_objFlags' && obj instanceof CCObject) { - value &= PersistentMask; - } - return value; - } - }, - - writeObjectField: function (codeArray, obj, key, value) { - var statement; - if (IDENTIFIER_RE.test(key)) { - statement = LOCAL_OBJ + '.' + key + '='; - } - else { - statement = LOCAL_OBJ + '[' + escapeForJS(key) + ']='; - } - this.writeFiled(codeArray, statement, obj, key, value); - }, - - writeFiled: function (codeArray, statement, obj, key, value) { - var expression = this.enumerateField(obj, key, value); - if (Array.isArray(expression)) { - expression[0] = mergeDeclaration(statement, expression[0]); - codeArray.push(expression); - } - else { - codeArray.push(mergeDeclaration(statement, expression) + ';'); - } - }, - - // codeArray - the source code array for this object - enumerateObject: function (codeArray, obj) { - var klass = obj.constructor; - if (cc.Class._isCCClass(klass)) { - this.enumerateCCClass(codeArray, obj, klass); - } - else { - // primitive javascript object - for (var key in obj) { - if (!obj.hasOwnProperty(key) || - (key.charCodeAt(0) === 95 && key.charCodeAt(1) === 95 && // starts with "__" - key !== '__type__') - ) { - continue; - } - var value = obj[key]; - if (typeof value === 'object' && value && value === obj._iN$t) { - continue; - } - this.writeObjectField(codeArray, obj, key, value); - } - } - }, - - instantiateObj: function (obj) { - if (obj instanceof cc.ValueType) { - return CCClass.getNewValueTypeCode(obj); - } - if (obj instanceof cc.Asset) { - // register to asset list and just return the reference. - return this.getObjRef(obj); - } - if (obj._objFlags & Destroyed) { - // the same as cc.isValid(obj) - return null; - } - - var createCode; - var ctor = obj.constructor; - if (cc.Class._isCCClass(ctor)) { - if (this.parent) { - if (this.parent instanceof cc.Component) { - if (obj instanceof cc._BaseNode || obj instanceof cc.Component) { + else if (this.parent instanceof cc._BaseNode) { + if (obj instanceof cc._BaseNode) { + if (!obj.isChildOf(this.parent)) { + // should not clone other nodes if not descendant return this.getObjRef(obj); } } - else if (this.parent instanceof cc._BaseNode) { - if (obj instanceof cc._BaseNode) { - if (!obj.isChildOf(this.parent)) { - // should not clone other nodes if not descendant - return this.getObjRef(obj); - } - } - else if (obj instanceof cc.Component) { - if (!obj.node.isChildOf(this.parent)) { - // should not clone other component if not descendant - return this.getObjRef(obj); - } + else if (obj instanceof cc.Component) { + if (!obj.node.isChildOf(this.parent)) { + // should not clone other component if not descendant + return this.getObjRef(obj); } } } - createCode = new Declaration(LOCAL_OBJ, 'new ' + this.getFuncModule(ctor, true) + '()'); - } - else if (ctor === Object) { - createCode = new Declaration(LOCAL_OBJ, '{}'); - } - else { - // do not clone unknown type - return this.getObjRef(obj); } + createCode = new Declaration(LOCAL_OBJ, 'new ' + this.getFuncModule(ctor, true) + '()'); + } + else if (ctor === Object) { + createCode = new Declaration(LOCAL_OBJ, '{}'); + } + else { + // do not clone unknown type + return this.getObjRef(obj); + } - var codeArray = [createCode]; + var codeArray = [createCode]; - // assign a _iN$t flag to indicate that this object has been parsed. - obj._iN$t = { - globalVar: '', // the name of declared global variable used to access this object - source: codeArray, // the source code array for this object - //propName: '', // the propName this object defined in its source code, - // // if defined, use LOCAL_OBJ.propName to access the obj, else just use o - }; - this.objsToClear_iN$t.push(obj); + // assign a _iN$t flag to indicate that this object has been parsed. + obj._iN$t = { + globalVar: '', // the name of declared global variable used to access this object + source: codeArray, // the source code array for this object + //propName: '', // the propName this object defined in its source code, + // // if defined, use LOCAL_OBJ.propName to access the obj, else just use o + }; + this.objsToClear_iN$t.push(obj); - this.enumerateObject(codeArray, obj); - return ['(function(){', - codeArray, - 'return o;})();']; - }, -}); + this.enumerateObject(codeArray, obj); + return ['(function(){', + codeArray, + 'return o;})();']; +}; function compile (node) { diff --git a/cocos2d/core/platform/utils.js b/cocos2d/core/platform/utils.js index dbb90f3b1e..21d427e29e 100644 --- a/cocos2d/core/platform/utils.js +++ b/cocos2d/core/platform/utils.js @@ -88,27 +88,25 @@ module.exports = { }; if (CC_DEV) { - cc.js.mixin(module.exports, { - ///** - // * @param {Object} obj - // * @return {Boolean} is {} ? - // */ - isPlainEmptyObj_DEV: function (obj) { - if (!obj || obj.constructor !== Object) { - return false; - } - // jshint ignore: start - for (var k in obj) { - return false; - } - // jshint ignore: end - return true; - }, - cloneable_DEV: function (obj) { - return obj && typeof obj.clone === 'function' && - (obj.constructor.prototype.hasOwnProperty('clone') || obj.hasOwnProperty('clone')); + ///** + // * @param {Object} obj + // * @return {Boolean} is {} ? + // */ + module.exports.isPlainEmptyObj_DEV = function (obj) { + if (!obj || obj.constructor !== Object) { + return false; } - }); + // jshint ignore: start + for (var k in obj) { + return false; + } + // jshint ignore: end + return true; + }; + module.exports.cloneable_DEV = function (obj) { + return obj && typeof obj.clone === 'function' && + (obj.constructor.prototype.hasOwnProperty('clone') || obj.hasOwnProperty('clone')); + }; } if (CC_TEST) { diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 395c16a08e..c913304afb 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -604,455 +604,450 @@ game.once(game.EVENT_RENDERER_INITED, function () { return renderCanvas; }; - JS.mixin(Texture2D.prototype, { - _generateTextureCacheForColor: function(){ - if (this.channelCache) - return this.channelCache; + _p._generateTextureCacheForColor = function(){ + if (this.channelCache) + return this.channelCache; - var textureCache = [ - document.createElement("canvas"), - document.createElement("canvas"), - document.createElement("canvas"), - document.createElement("canvas") - ]; - //todo texture onload - renderToCache(this._htmlElementObj, textureCache); - return this.channelCache = textureCache; - }, + var textureCache = [ + document.createElement("canvas"), + document.createElement("canvas"), + document.createElement("canvas"), + document.createElement("canvas") + ]; + //todo texture onload + renderToCache(this._htmlElementObj, textureCache); + return this.channelCache = textureCache; + }; - _switchToGray: function(toGray){ - if(!this._textureLoaded || this._isGray === toGray) - return; - this._isGray = toGray; - if(this._isGray){ - this._backupElement = this._htmlElementObj; - if(!this._grayElementObj) - this._grayElementObj = generateGrayTexture(this._htmlElementObj); - this._htmlElementObj = this._grayElementObj; - } else { - if(this._backupElement !== null) - this._htmlElementObj = this._backupElement; - } - }, - - _generateGrayTexture: function() { - if(!this._textureLoaded) - return null; - var grayElement = generateGrayTexture(this._htmlElementObj);; - var newTexture = new Texture2D(); - newTexture.initWithElement(grayElement); - newTexture.handleLoadedTexture(); - return newTexture; - }, - - //change color function - _generateColorTexture: sys._supportCanvasNewBlendModes ? function(r, g, b, rect, canvas) { - var onlyCanvas = false; - if(canvas) - onlyCanvas = true; - else - canvas = document.createElement("canvas"); - var textureImage = this._htmlElementObj; - if(!rect) - rect = cc.rect(0, 0, textureImage.width, textureImage.height); - - canvas.width = rect.width; - canvas.height = rect.height; - - if(rect.width && rect.height) { - var context = canvas.getContext("2d"); - context.globalCompositeOperation = "source-over"; - context.fillStyle = "rgb(" + (r|0) + "," + (g|0) + "," + (b|0) + ")"; - context.fillRect(0, 0, rect.width, rect.height); - context.globalCompositeOperation = "multiply"; - context.drawImage( - textureImage, - rect.x, rect.y, rect.width, rect.height, - 0, 0, rect.width, rect.height - ); - context.globalCompositeOperation = "destination-atop"; - context.drawImage( - textureImage, - rect.x, rect.y, rect.width, rect.height, - 0, 0, rect.width, rect.height - ); - } - - if(onlyCanvas) - return canvas; - var newTexture = new Texture2D(); - newTexture.initWithElement(canvas); - newTexture.handleLoadedTexture(); - return newTexture; - } : function(r, g, b, rect, canvas){ - var onlyCanvas = false; - if(canvas) - onlyCanvas = true; - else - canvas = document.createElement("canvas"); - var textureImage = this._htmlElementObj; - if(!rect) - rect = cc.rect(0, 0, textureImage.width, textureImage.height); - - canvas.width = rect.width; - canvas.height = rect.height; - - if(rect.width && rect.height) { - var context = canvas.getContext("2d"); - context.drawImage( - textureImage, - rect.x, rect.y, rect.width, rect.height, - 0, 0, rect.width, rect.height - ); - - var imageData = context.getImageData(0,0,canvas.width, canvas.height); - var data = imageData.data; - r = r/255; - g = g/255; - b = b/255; - for (var i = 0; i < data.length; i += 4) { - data[i] = data[i] * r; - data[i + 1] = data[i+1] * g; - data[i + 2] = data[i+2] * b; - } - - context.putImageData(imageData, 0, 0); - } - - if(onlyCanvas) - return canvas; - var newTexture = new Texture2D(); - newTexture.initWithElement(canvas); - newTexture.handleLoadedTexture(); - return newTexture; + _p._switchToGray = function(toGray){ + if(!this._textureLoaded || this._isGray === toGray) + return; + this._isGray = toGray; + if(this._isGray){ + this._backupElement = this._htmlElementObj; + if(!this._grayElementObj) + this._grayElementObj = generateGrayTexture(this._htmlElementObj); + this._htmlElementObj = this._grayElementObj; + } else { + if(this._backupElement !== null) + this._htmlElementObj = this._backupElement; } - }); + }; + + _p._generateGrayTexture = function() { + if(!this._textureLoaded) + return null; + var grayElement = generateGrayTexture(this._htmlElementObj);; + var newTexture = new Texture2D(); + newTexture.initWithElement(grayElement); + newTexture.handleLoadedTexture(); + return newTexture; + }; + + //change color function + _p._generateColorTexture = sys._supportCanvasNewBlendModes ? function(r, g, b, rect, canvas) { + var onlyCanvas = false; + if(canvas) + onlyCanvas = true; + else + canvas = document.createElement("canvas"); + var textureImage = this._htmlElementObj; + if(!rect) + rect = cc.rect(0, 0, textureImage.width, textureImage.height); + + canvas.width = rect.width; + canvas.height = rect.height; + + if(rect.width && rect.height) { + var context = canvas.getContext("2d"); + context.globalCompositeOperation = "source-over"; + context.fillStyle = "rgb(" + (r|0) + "," + (g|0) + "," + (b|0) + ")"; + context.fillRect(0, 0, rect.width, rect.height); + context.globalCompositeOperation = "multiply"; + context.drawImage( + textureImage, + rect.x, rect.y, rect.width, rect.height, + 0, 0, rect.width, rect.height + ); + context.globalCompositeOperation = "destination-atop"; + context.drawImage( + textureImage, + rect.x, rect.y, rect.width, rect.height, + 0, 0, rect.width, rect.height + ); + } + + if(onlyCanvas) + return canvas; + var newTexture = new Texture2D(); + newTexture.initWithElement(canvas); + newTexture.handleLoadedTexture(); + return newTexture; + } : function(r, g, b, rect, canvas){ + var onlyCanvas = false; + if(canvas) + onlyCanvas = true; + else + canvas = document.createElement("canvas"); + var textureImage = this._htmlElementObj; + if(!rect) + rect = cc.rect(0, 0, textureImage.width, textureImage.height); + + canvas.width = rect.width; + canvas.height = rect.height; + + if(rect.width && rect.height) { + var context = canvas.getContext("2d"); + context.drawImage( + textureImage, + rect.x, rect.y, rect.width, rect.height, + 0, 0, rect.width, rect.height + ); + + var imageData = context.getImageData(0,0,canvas.width, canvas.height); + var data = imageData.data; + r = r/255; + g = g/255; + b = b/255; + for (var i = 0; i < data.length; i += 4) { + data[i] = data[i] * r; + data[i + 1] = data[i+1] * g; + data[i + 2] = data[i+2] * b; + } + + context.putImageData(imageData, 0, 0); + } + + if(onlyCanvas) + return canvas; + var newTexture = new Texture2D(); + newTexture.initWithElement(canvas); + newTexture.handleLoadedTexture(); + return newTexture; + }; } else if (cc._renderType === game.RENDER_TYPE_WEBGL) { - JS.mixin(Texture2D.prototype, { + _p.initWithData = function (data, pixelFormat, pixelsWide, pixelsHigh, contentSize) { + var self = this, tex2d = Texture2D; + var gl = cc._renderContext; + var format = gl.RGBA, type = gl.UNSIGNED_BYTE; - initWithData: function (data, pixelFormat, pixelsWide, pixelsHigh, contentSize) { - var self = this, tex2d = Texture2D; - var gl = cc._renderContext; - var format = gl.RGBA, type = gl.UNSIGNED_BYTE; - - var bitsPerPixel = Texture2D._B[pixelFormat]; - - var bytesPerRow = pixelsWide * bitsPerPixel / 8; - if (bytesPerRow % 8 === 0) { - gl.pixelStorei(gl.UNPACK_ALIGNMENT, 8); - } else if (bytesPerRow % 4 === 0) { - gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4); - } else if (bytesPerRow % 2 === 0) { - gl.pixelStorei(gl.UNPACK_ALIGNMENT, 2); - } else { - gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); - } - - self._webTextureObj = gl.createTexture(); - cc.gl.bindTexture2D(self); - - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); - - // Specify OpenGL texture image - switch (pixelFormat) { - case tex2d.PIXEL_FORMAT_RGBA8888: - format = gl.RGBA; - break; - case tex2d.PIXEL_FORMAT_RGB888: - format = gl.RGB; - break; - case tex2d.PIXEL_FORMAT_RGBA4444: - type = gl.UNSIGNED_SHORT_4_4_4_4; - break; - case tex2d.PIXEL_FORMAT_RGB5A1: - type = gl.UNSIGNED_SHORT_5_5_5_1; - break; - case tex2d.PIXEL_FORMAT_RGB565: - type = gl.UNSIGNED_SHORT_5_6_5; - break; - case tex2d.PIXEL_FORMAT_AI88: - format = gl.LUMINANCE_ALPHA; - break; - case tex2d.PIXEL_FORMAT_A8: - format = gl.ALPHA; - break; - case tex2d.PIXEL_FORMAT_I8: - format = gl.LUMINANCE; - break; - default: - cc.assertID(0, 3113); - } - gl.texImage2D(gl.TEXTURE_2D, 0, format, pixelsWide, pixelsHigh, 0, format, type, data); - - - self._contentSize.width = contentSize.width; - self._contentSize.height = contentSize.height; - self._pixelWidth = pixelsWide; - self._pixelHeight = pixelsHigh; - self._pixelFormat = pixelFormat; - - self._hasPremultipliedAlpha = false; - self._hasMipmaps = false; - - self._textureLoaded = true; - - return true; - }, - - initWithImage: function (uiImage) { - if (uiImage == null) { - cc.logID(3104); - return false; - } - - var imageWidth = uiImage.getWidth(); - var imageHeight = uiImage.getHeight(); - - var maxTextureSize = cc.configuration.getMaxTextureSize(); - if (imageWidth > maxTextureSize || imageHeight > maxTextureSize) { - cc.logID(3105, imageWidth, imageHeight, maxTextureSize, maxTextureSize); - return false; - } - this._textureLoaded = true; - - // always load premultiplied images - return this._initPremultipliedATextureWithImage(uiImage, imageWidth, imageHeight); - }, - - initWithElement: function (element) { - if (!element) - return; - this._webTextureObj = cc._renderContext.createTexture(); - this._htmlElementObj = element; - this._textureLoaded = true; - }, - - // [premultiplied=false] - handleLoadedTexture: function (premultiplied) { - premultiplied = !!premultiplied; - var self = this; - // Not sure about this ! Some texture need to be updated even after loaded - if (!game._rendererInitialized) { - return; - } - if (!self._htmlElementObj || !self._htmlElementObj.width || !self._htmlElementObj.height) { - return; - } - - //upload image to buffer - var gl = cc._renderContext; - - cc.gl.bindTexture2D(self); + var bitsPerPixel = Texture2D._B[pixelFormat]; + var bytesPerRow = pixelsWide * bitsPerPixel / 8; + if (bytesPerRow % 8 === 0) { + gl.pixelStorei(gl.UNPACK_ALIGNMENT, 8); + } else if (bytesPerRow % 4 === 0) { gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4); - if(premultiplied) - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1); + } else if (bytesPerRow % 2 === 0) { + gl.pixelStorei(gl.UNPACK_ALIGNMENT, 2); + } else { + gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1); + } - // Specify OpenGL texture image - gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, self._htmlElementObj); + self._webTextureObj = gl.createTexture(); + cc.gl.bindTexture2D(self); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + + // Specify OpenGL texture image + switch (pixelFormat) { + case tex2d.PIXEL_FORMAT_RGBA8888: + format = gl.RGBA; + break; + case tex2d.PIXEL_FORMAT_RGB888: + format = gl.RGB; + break; + case tex2d.PIXEL_FORMAT_RGBA4444: + type = gl.UNSIGNED_SHORT_4_4_4_4; + break; + case tex2d.PIXEL_FORMAT_RGB5A1: + type = gl.UNSIGNED_SHORT_5_5_5_1; + break; + case tex2d.PIXEL_FORMAT_RGB565: + type = gl.UNSIGNED_SHORT_5_6_5; + break; + case tex2d.PIXEL_FORMAT_AI88: + format = gl.LUMINANCE_ALPHA; + break; + case tex2d.PIXEL_FORMAT_A8: + format = gl.ALPHA; + break; + case tex2d.PIXEL_FORMAT_I8: + format = gl.LUMINANCE; + break; + default: + cc.assertID(0, 3113); + } + gl.texImage2D(gl.TEXTURE_2D, 0, format, pixelsWide, pixelsHigh, 0, format, type, data); + + + self._contentSize.width = contentSize.width; + self._contentSize.height = contentSize.height; + self._pixelWidth = pixelsWide; + self._pixelHeight = pixelsHigh; + self._pixelFormat = pixelFormat; + + self._hasPremultipliedAlpha = false; + self._hasMipmaps = false; + + self._textureLoaded = true; + + return true; + }; + + _p.initWithImage = function (uiImage) { + if (uiImage == null) { + cc.logID(3104); + return false; + } + + var imageWidth = uiImage.getWidth(); + var imageHeight = uiImage.getHeight(); + + var maxTextureSize = cc.configuration.getMaxTextureSize(); + if (imageWidth > maxTextureSize || imageHeight > maxTextureSize) { + cc.logID(3105, imageWidth, imageHeight, maxTextureSize, maxTextureSize); + return false; + } + this._textureLoaded = true; + + // always load premultiplied images + return this._initPremultipliedATextureWithImage(uiImage, imageWidth, imageHeight); + }; + + _p.initWithElement = function (element) { + if (!element) + return; + this._webTextureObj = cc._renderContext.createTexture(); + this._htmlElementObj = element; + this._textureLoaded = true; + }; + + // [premultiplied=false] + _p.handleLoadedTexture = function (premultiplied) { + premultiplied = !!premultiplied; + var self = this; + // Not sure about this ! Some texture need to be updated even after loaded + if (!game._rendererInitialized) { + return; + } + if (!self._htmlElementObj || !self._htmlElementObj.width || !self._htmlElementObj.height) { + return; + } + + //upload image to buffer + var gl = cc._renderContext; + + cc.gl.bindTexture2D(self); + + gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4); + if(premultiplied) + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1); + + // Specify OpenGL texture image + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, self._htmlElementObj); + + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + + cc.gl.bindTexture2D(null); + if(premultiplied) + gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0); + + var pixelsWide = self._htmlElementObj.width; + var pixelsHigh = self._htmlElementObj.height; + + self._pixelWidth = self._contentSize.width = pixelsWide; + self._pixelHeight = self._contentSize.height = pixelsHigh; + self._pixelFormat = Texture2D.PIXEL_FORMAT_RGBA8888; + + self._hasPremultipliedAlpha = premultiplied; + self._hasMipmaps = false; + self._textureLoaded = true; + + if (cc.view._antiAliasEnabled) { + self.setAntiAliasTexParameters(); + } + else { + self.setAliasTexParameters(); + } + + self._htmlElementObj = null; + + //dispatch load event to listener. + self.emit("load"); + }; + + _p.setTexParameters = function (texParams, magFilter, wrapS, wrapT) { + var _t = this; + var gl = cc._renderContext; + + if(magFilter !== undefined) + texParams = {minFilter: texParams, magFilter: magFilter, wrapS: wrapS, wrapT: wrapT}; + + cc.assertID((_t._pixelWidth === misc.NextPOT(_t._pixelWidth) && _t._pixelHeight === misc.NextPOT(_t._pixelHeight)) || + (texParams.wrapS === gl.CLAMP_TO_EDGE && texParams.wrapT === gl.CLAMP_TO_EDGE), + 3116); + + cc.gl.bindTexture2D(_t); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texParams.minFilter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texParams.magFilter); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, texParams.wrapS); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, texParams.wrapT); + }; + + _p.setAntiAliasTexParameters = function () { + var gl = cc._renderContext; + + cc.gl.bindTexture2D(this); + if (!this._hasMipmaps) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + else + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + }; - cc.gl.bindTexture2D(null); - if(premultiplied) - gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0); + _p.setAliasTexParameters = function () { + var gl = cc._renderContext; - var pixelsWide = self._htmlElementObj.width; - var pixelsHigh = self._htmlElementObj.height; + cc.gl.bindTexture2D(this); + if (!this._hasMipmaps) + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); + else + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_NEAREST); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); + }; - self._pixelWidth = self._contentSize.width = pixelsWide; - self._pixelHeight = self._contentSize.height = pixelsHigh; - self._pixelFormat = Texture2D.PIXEL_FORMAT_RGBA8888; + _p.generateMipmap = function () { + var _t = this; + cc.assertID(_t._pixelWidth === misc.NextPOT(_t._pixelWidth) && _t._pixelHeight === misc.NextPOT(_t._pixelHeight), 3117); - self._hasPremultipliedAlpha = premultiplied; - self._hasMipmaps = false; - self._textureLoaded = true; + cc.gl.bindTexture2D(_t); + cc._renderContext.generateMipmap(cc._renderContext.TEXTURE_2D); + _t._hasMipmaps = true; + }; - if (cc.view._antiAliasEnabled) { - self.setAntiAliasTexParameters(); - } - else { - self.setAliasTexParameters(); + _p.stringForFormat = function () { + return Texture2D._M[this._pixelFormat]; + }; + + _p.bitsPerPixelForFormat = function (format) {//TODO I want to delete the format argument, use this._pixelFormat + format = format || this._pixelFormat; + var value = Texture2D._B[format]; + if (value != null) return value; + cc.logID(3110, format); + return -1; + }; + + _p._initPremultipliedATextureWithImage = function (uiImage, width, height) { + var tex2d = Texture2D; + var tempData = uiImage.getData(); + var inPixel32 = null; + var inPixel8 = null; + var outPixel16 = null; + var hasAlpha = uiImage.hasAlpha(); + var imageSize = cc.size(uiImage.getWidth(), uiImage.getHeight()); + var pixelFormat = tex2d.defaultPixelFormat; + var bpp = uiImage.getBitsPerComponent(); + var i; + + // compute pixel format + if (!hasAlpha) { + if (bpp >= 8) { + pixelFormat = tex2d.PIXEL_FORMAT_RGB888; + } else { + cc.logID(3111); + pixelFormat = tex2d.PIXEL_FORMAT_RGB565; } + } - self._htmlElementObj = null; + // Repack the pixel data into the right format + var length = width * height; - //dispatch load event to listener. - self.emit("load"); - }, - - setTexParameters: function (texParams, magFilter, wrapS, wrapT) { - var _t = this; - var gl = cc._renderContext; - - if(magFilter !== undefined) - texParams = {minFilter: texParams, magFilter: magFilter, wrapS: wrapS, wrapT: wrapT}; - - cc.assertID((_t._pixelWidth === misc.NextPOT(_t._pixelWidth) && _t._pixelHeight === misc.NextPOT(_t._pixelHeight)) || - (texParams.wrapS === gl.CLAMP_TO_EDGE && texParams.wrapT === gl.CLAMP_TO_EDGE), - 3116); - - cc.gl.bindTexture2D(_t); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texParams.minFilter); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texParams.magFilter); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, texParams.wrapS); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, texParams.wrapT); - }, - - setAntiAliasTexParameters: function () { - var gl = cc._renderContext; - - cc.gl.bindTexture2D(this); - if (!this._hasMipmaps) - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); - else - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); - }, - - setAliasTexParameters: function () { - var gl = cc._renderContext; - - cc.gl.bindTexture2D(this); - if (!this._hasMipmaps) - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); - else - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_NEAREST); - gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); - }, - - generateMipmap: function () { - var _t = this; - cc.assertID(_t._pixelWidth === misc.NextPOT(_t._pixelWidth) && _t._pixelHeight === misc.NextPOT(_t._pixelHeight), 3117); - - cc.gl.bindTexture2D(_t); - cc._renderContext.generateMipmap(cc._renderContext.TEXTURE_2D); - _t._hasMipmaps = true; - }, - - stringForFormat: function () { - return Texture2D._M[this._pixelFormat]; - }, - - bitsPerPixelForFormat: function (format) {//TODO I want to delete the format argument, use this._pixelFormat - format = format || this._pixelFormat; - var value = Texture2D._B[format]; - if (value != null) return value; - cc.logID(3110, format); - return -1; - }, - - _initPremultipliedATextureWithImage: function (uiImage, width, height) { - var tex2d = Texture2D; - var tempData = uiImage.getData(); - var inPixel32 = null; - var inPixel8 = null; - var outPixel16 = null; - var hasAlpha = uiImage.hasAlpha(); - var imageSize = cc.size(uiImage.getWidth(), uiImage.getHeight()); - var pixelFormat = tex2d.defaultPixelFormat; - var bpp = uiImage.getBitsPerComponent(); - var i; - - // compute pixel format - if (!hasAlpha) { - if (bpp >= 8) { - pixelFormat = tex2d.PIXEL_FORMAT_RGB888; - } else { - cc.logID(3111); - pixelFormat = tex2d.PIXEL_FORMAT_RGB565; - } - } - - // Repack the pixel data into the right format - var length = width * height; - - if (pixelFormat === tex2d.PIXEL_FORMAT_RGB565) { - if (hasAlpha) { - // Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGGBBBBB" - tempData = new Uint16Array(width * height); - inPixel32 = uiImage.getData(); - - for (i = 0; i < length; ++i) { - tempData[i] = - ((((inPixel32[i] >> 0) & 0xFF) >> 3) << 11) | // R - ((((inPixel32[i] >> 8) & 0xFF) >> 2) << 5) | // G - ((((inPixel32[i] >> 16) & 0xFF) >> 3) << 0); // B - } - } else { - // Convert "RRRRRRRRRGGGGGGGGBBBBBBBB" to "RRRRRGGGGGGBBBBB" - tempData = new Uint16Array(width * height); - inPixel8 = uiImage.getData(); - - for (i = 0; i < length; ++i) { - tempData[i] = - (((inPixel8[i] & 0xFF) >> 3) << 11) | // R - (((inPixel8[i] & 0xFF) >> 2) << 5) | // G - (((inPixel8[i] & 0xFF) >> 3) << 0); // B - } - } - } else if (pixelFormat === tex2d.PIXEL_FORMAT_RGBA4444) { - // Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRGGGGBBBBAAAA" - tempData = new Uint16Array(width * height); - inPixel32 = uiImage.getData(); - - for (i = 0; i < length; ++i) { - tempData[i] = - ((((inPixel32[i] >> 0) & 0xFF) >> 4) << 12) | // R - ((((inPixel32[i] >> 8) & 0xFF) >> 4) << 8) | // G - ((((inPixel32[i] >> 16) & 0xFF) >> 4) << 4) | // B - ((((inPixel32[i] >> 24) & 0xFF) >> 4) << 0); // A - } - } else if (pixelFormat === tex2d.PIXEL_FORMAT_RGB5A1) { - // Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGBBBBBA" + if (pixelFormat === tex2d.PIXEL_FORMAT_RGB565) { + if (hasAlpha) { + // Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGGBBBBB" tempData = new Uint16Array(width * height); inPixel32 = uiImage.getData(); for (i = 0; i < length; ++i) { tempData[i] = ((((inPixel32[i] >> 0) & 0xFF) >> 3) << 11) | // R - ((((inPixel32[i] >> 8) & 0xFF) >> 3) << 6) | // G - ((((inPixel32[i] >> 16) & 0xFF) >> 3) << 1) | // B - ((((inPixel32[i] >> 24) & 0xFF) >> 7) << 0); // A + ((((inPixel32[i] >> 8) & 0xFF) >> 2) << 5) | // G + ((((inPixel32[i] >> 16) & 0xFF) >> 3) << 0); // B } - } else if (pixelFormat === tex2d.PIXEL_FORMAT_A8) { - // Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "AAAAAAAA" - tempData = new Uint8Array(width * height); - inPixel32 = uiImage.getData(); + } else { + // Convert "RRRRRRRRRGGGGGGGGBBBBBBBB" to "RRRRRGGGGGGBBBBB" + tempData = new Uint16Array(width * height); + inPixel8 = uiImage.getData(); for (i = 0; i < length; ++i) { - tempData[i] = (inPixel32 >> 24) & 0xFF; // A + tempData[i] = + (((inPixel8[i] & 0xFF) >> 3) << 11) | // R + (((inPixel8[i] & 0xFF) >> 2) << 5) | // G + (((inPixel8[i] & 0xFF) >> 3) << 0); // B } } + } else if (pixelFormat === tex2d.PIXEL_FORMAT_RGBA4444) { + // Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRGGGGBBBBAAAA" + tempData = new Uint16Array(width * height); + inPixel32 = uiImage.getData(); - if (hasAlpha && pixelFormat === tex2d.PIXEL_FORMAT_RGB888) { - // Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRRRRGGGGGGGGBBBBBBBB" - inPixel32 = uiImage.getData(); - tempData = new Uint8Array(width * height * 3); - - for (i = 0; i < length; ++i) { - tempData[i * 3] = (inPixel32 >> 0) & 0xFF; // R - tempData[i * 3 + 1] = (inPixel32 >> 8) & 0xFF; // G - tempData[i * 3 + 2] = (inPixel32 >> 16) & 0xFF; // B - } + for (i = 0; i < length; ++i) { + tempData[i] = + ((((inPixel32[i] >> 0) & 0xFF) >> 4) << 12) | // R + ((((inPixel32[i] >> 8) & 0xFF) >> 4) << 8) | // G + ((((inPixel32[i] >> 16) & 0xFF) >> 4) << 4) | // B + ((((inPixel32[i] >> 24) & 0xFF) >> 4) << 0); // A } + } else if (pixelFormat === tex2d.PIXEL_FORMAT_RGB5A1) { + // Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGBBBBBA" + tempData = new Uint16Array(width * height); + inPixel32 = uiImage.getData(); - this.initWithData(tempData, pixelFormat, width, height, imageSize); + for (i = 0; i < length; ++i) { + tempData[i] = + ((((inPixel32[i] >> 0) & 0xFF) >> 3) << 11) | // R + ((((inPixel32[i] >> 8) & 0xFF) >> 3) << 6) | // G + ((((inPixel32[i] >> 16) & 0xFF) >> 3) << 1) | // B + ((((inPixel32[i] >> 24) & 0xFF) >> 7) << 0); // A + } + } else if (pixelFormat === tex2d.PIXEL_FORMAT_A8) { + // Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "AAAAAAAA" + tempData = new Uint8Array(width * height); + inPixel32 = uiImage.getData(); - if (tempData != uiImage.getData()) - tempData = null; - - this._hasPremultipliedAlpha = uiImage.isPremultipliedAlpha(); - return true; + for (i = 0; i < length; ++i) { + tempData[i] = (inPixel32 >> 24) & 0xFF; // A + } } - }); + + if (hasAlpha && pixelFormat === tex2d.PIXEL_FORMAT_RGB888) { + // Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRRRRGGGGGGGGBBBBBBBB" + inPixel32 = uiImage.getData(); + tempData = new Uint8Array(width * height * 3); + + for (i = 0; i < length; ++i) { + tempData[i * 3] = (inPixel32 >> 0) & 0xFF; // R + tempData[i * 3 + 1] = (inPixel32 >> 8) & 0xFF; // G + tempData[i * 3 + 2] = (inPixel32 >> 16) & 0xFF; // B + } + } + + this.initWithData(tempData, pixelFormat, width, height, imageSize); + + if (tempData != uiImage.getData()) + tempData = null; + + this._hasPremultipliedAlpha = uiImage.isPremultipliedAlpha(); + return true; + }; } }); diff --git a/cocos2d/core/textures/CCTextureAtlas.js b/cocos2d/core/textures/CCTextureAtlas.js index fe464cadba..a78d28d508 100644 --- a/cocos2d/core/textures/CCTextureAtlas.js +++ b/cocos2d/core/textures/CCTextureAtlas.js @@ -623,74 +623,72 @@ cc.defineGetterSetter(_p, "quads", _p.getQuads, _p.setQuads); game.once(game.EVENT_RENDERER_INITED, function () { if (cc._renderType === game.RENDER_TYPE_WEBGL) { - JS.mixin(TextureAtlas.prototype, { - _setupVBO: function () { - var _t = this; - var gl = cc._renderContext; - //create WebGLBuffer - _t._buffersVBO[0] = gl.createBuffer(); - _t._buffersVBO[1] = gl.createBuffer(); + TextureAtlas.prototype._setupVBO = function () { + var _t = this; + var gl = cc._renderContext; + //create WebGLBuffer + _t._buffersVBO[0] = gl.createBuffer(); + _t._buffersVBO[1] = gl.createBuffer(); - _t._quadsWebBuffer = gl.createBuffer(); - _t._mapBuffers(); - }, + _t._quadsWebBuffer = gl.createBuffer(); + _t._mapBuffers(); + }; - _mapBuffers: function () { - var _t = this; - var gl = cc._renderContext; + TextureAtlas.prototype._mapBuffers = function () { + var _t = this; + var gl = cc._renderContext; - gl.bindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer); + gl.bindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer); + gl.bufferData(gl.ARRAY_BUFFER, _t._quadsArrayBuffer, gl.DYNAMIC_DRAW); + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _t._buffersVBO[1]); + gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, _t._indices, gl.STATIC_DRAW); + + //cc.checkGLErrorDebug(); + }; + + TextureAtlas.prototype.drawQuads = function () { + this.drawNumberOfQuads(this._totalQuads, 0); + }; + + TextureAtlas.prototype.drawNumberOfQuads = function (n, start) { + var _t = this; + start = start || 0; + if (0 === n || !_t.texture || !_t.texture.isLoaded()) + return; + + var gl = cc._renderContext; + cc.gl.bindTexture2D(_t.texture); + + // + // Using VBO without VAO + // + //vertices + //gl.bindBuffer(gl.ARRAY_BUFFER, _t._buffersVBO[0]); + // XXX: update is done in draw... perhaps it should be done in a timer + gl.bindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer); + gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION); + gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_COLOR); + gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_TEX_COORDS); + if (_t.dirty){ gl.bufferData(gl.ARRAY_BUFFER, _t._quadsArrayBuffer, gl.DYNAMIC_DRAW); - - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _t._buffersVBO[1]); - gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, _t._indices, gl.STATIC_DRAW); - - //cc.checkGLErrorDebug(); - }, - - drawQuads: function () { - this.drawNumberOfQuads(this._totalQuads, 0); - }, - - drawNumberOfQuads: function (n, start) { - var _t = this; - start = start || 0; - if (0 === n || !_t.texture || !_t.texture.isLoaded()) - return; - - var gl = cc._renderContext; - cc.gl.bindTexture2D(_t.texture); - - // - // Using VBO without VAO - // - //vertices - //gl.bindBuffer(gl.ARRAY_BUFFER, _t._buffersVBO[0]); - // XXX: update is done in draw... perhaps it should be done in a timer - gl.bindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer); - gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION); - gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_COLOR); - gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_TEX_COORDS); - if (_t.dirty){ - gl.bufferData(gl.ARRAY_BUFFER, _t._quadsArrayBuffer, gl.DYNAMIC_DRAW); - _t.dirty = false; - } - - gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0); // vertices - gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12); // colors - gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16); // tex coords - - gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _t._buffersVBO[1]); - - if (cc.macro.TEXTURE_ATLAS_USE_TRIANGLE_STRIP) - gl.drawElements(gl.TRIANGLE_STRIP, n * 6, gl.UNSIGNED_SHORT, start * 6 * _t._indices.BYTES_PER_ELEMENT); - else - gl.drawElements(gl.TRIANGLES, n * 6, gl.UNSIGNED_SHORT, start * 6 * _t._indices.BYTES_PER_ELEMENT); - - cc.g_NumberOfDraws++; - //cc.checkGLErrorDebug(); + _t.dirty = false; } - }); + + gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0); // vertices + gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12); // colors + gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16); // tex coords + + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _t._buffersVBO[1]); + + if (cc.macro.TEXTURE_ATLAS_USE_TRIANGLE_STRIP) + gl.drawElements(gl.TRIANGLE_STRIP, n * 6, gl.UNSIGNED_SHORT, start * 6 * _t._indices.BYTES_PER_ELEMENT); + else + gl.drawElements(gl.TRIANGLES, n * 6, gl.UNSIGNED_SHORT, start * 6 * _t._indices.BYTES_PER_ELEMENT); + + cc.g_NumberOfDraws++; + //cc.checkGLErrorDebug(); + }; } }); diff --git a/cocos2d/core/utils/misc.js b/cocos2d/core/utils/misc.js index 5857308478..60f3ed9d9a 100644 --- a/cocos2d/core/utils/misc.js +++ b/cocos2d/core/utils/misc.js @@ -149,7 +149,7 @@ m.imagePool = { this.count++; } } -} +}; module.exports = m; diff --git a/cocos2d/core/value-types/CCValueType.js b/cocos2d/core/value-types/CCValueType.js index f3a4925f89..7d9c1e445e 100644 --- a/cocos2d/core/value-types/CCValueType.js +++ b/cocos2d/core/value-types/CCValueType.js @@ -34,17 +34,19 @@ var JS = require('../platform/js'); function ValueType () {} JS.setClassName('cc.ValueType', ValueType); -JS.mixin(ValueType.prototype, { +var proto = ValueType.prototype; + +if (CC_EDITOR) { /** * !#en This method returns an exact copy of current value. * !#zh 克隆当前值,该方法返回一个新对象,新对象的值和原对象相等。 * @method clone * @return {ValueType} */ - clone: CC_EDITOR && function () { + proto.clone = function () { cc.errorID(5801, JS.getClassName(this)); return null; - }, + }; /** * !#en Compares this object with the other one. @@ -53,20 +55,10 @@ JS.mixin(ValueType.prototype, { * @param {ValueType} other * @return {Boolean} */ - equals: CC_EDITOR && function (other) { + proto.equals = function (other) { cc.errorID(5802, JS.getClassName(this)); return false; - }, - - /** - * !#en TODO - * !#zh 转换为方便阅读的字符串。 - * @method toString - * @return {string} - */ - toString: function () { - return '' + {}; - }, + }; /** * !#en @@ -80,11 +72,21 @@ JS.mixin(ValueType.prototype, { * @param {number} ratio - the interpolation coefficient * @return {ValueType} */ - lerp: CC_EDITOR && function (to, ratio) { + proto.lerp = function (to, ratio) { cc.warnID(5800, JS.getClassName(this)); return this.clone(); - } -}); + }; +} + +/** + * !#en TODO + * !#zh 转换为方便阅读的字符串。 + * @method toString + * @return {string} + */ +proto.toString = function () { + return '' + {}; +}; cc.ValueType = ValueType; module.exports = ValueType; diff --git a/cocos2d/core/value-types/CCVec2.js b/cocos2d/core/value-types/CCVec2.js index 05a784126d..02aadcc517 100644 --- a/cocos2d/core/value-types/CCVec2.js +++ b/cocos2d/core/value-types/CCVec2.js @@ -63,475 +63,475 @@ CCClass.fastDefine('cc.Vec2', Vec2, { x: 0, y: 0 }); * @property {Number} y */ -JS.mixin(Vec2.prototype, { +var proto = Vec2.prototype; - /** - * !#en clone a Vec2 value - * !#zh 克隆一个 Vec2 值 - * @method clone - * @return {Vec2} - */ - clone: function () { - return new Vec2(this.x, this.y); - }, - /** - * !#en TODO - * !#zh 设置向量值。 - * @method set - * @param {Vec2} newValue - !#en new value to set. !#zh 要设置的新值 - * @return {Vec2} returns this - * @chainable - */ - set: function (newValue) { - this.x = newValue.x; - this.y = newValue.y; +/** + * !#en clone a Vec2 value + * !#zh 克隆一个 Vec2 值 + * @method clone + * @return {Vec2} + */ +proto.clone = function () { + return new Vec2(this.x, this.y); +}; + +/** + * !#en TODO + * !#zh 设置向量值。 + * @method set + * @param {Vec2} newValue - !#en new value to set. !#zh 要设置的新值 + * @return {Vec2} returns this + * @chainable + */ +proto.set = function (newValue) { + this.x = newValue.x; + this.y = newValue.y; + return this; +}; + +/** + * !#en TODO + * !#zh 当前的向量是否与指定的向量相等。 + * @method equals + * @param {Vec2} other + * @return {Boolean} + */ +proto.equals = function (other) { + return other && this.x === other.x && this.y === other.y; +}; + +/** + * !#en TODO + * !#zh 转换为方便阅读的字符串。 + * @method toString + * @return {string} + */ +proto.toString = function () { + return "(" + + this.x.toFixed(2) + ", " + + this.y.toFixed(2) + ")" + ; +}; + +/** + * !#en TODO + * !#zh 线性插值。 + * @method lerp + * @param {Vec2} to + * @param {number} ratio - the interpolation coefficient + * @param {Vec2} [out] - optional, the receiving vector + * @return {Vec2} + */ +proto.lerp = function (to, ratio, out) { + out = out || new Vec2(); + var x = this.x; + var y = this.y; + out.x = x + (to.x - x) * ratio; + out.y = y + (to.y - y) * ratio; + return out; +}; + +/** + * !#en Adds this vector. If you want to save result to another vector, use add() instead. + * !#zh 向量加法。如果你想保存结果到另一个向量,使用 add() 代替。 + * @method addSelf + * @param {Vec2} vector + * @return {Vec2} returns this + * @chainable + * @example + * var v = cc.v2(10, 10); + * v.addSelf(cc.v2(5, 5));// return Vec2 {x: 15, y: 15}; + */ +proto.addSelf = function (vector) { + this.x += vector.x; + this.y += vector.y; + return this; +}; + +/** + * !#en Adds two vectors, and returns the new result. + * !#zh 向量加法,并返回新结果。 + * @method add + * @param {Vec2} vector + * @param {Vec2} [out] - optional, the receiving vector + * @return {Vec2} the result + * @example + * var v = cc.v2(10, 10); + * v.add(cc.v2(5, 5)); // return Vec2 {x: 15, y: 15}; + * var v1; + * v.add(cc.v2(5, 5), v1); // return Vec2 {x: 15, y: 15}; + */ +proto.add = function (vector, out) { + out = out || new Vec2(); + out.x = this.x + vector.x; + out.y = this.y + vector.y; + return out; +}; + +/** + * !#en Subtracts one vector from this. If you want to save result to another vector, use sub() instead. + * !#zh 向量减法。如果你想保存结果到另一个向量,可使用 sub() 代替。 + * @method subSelf + * @param {Vec2} vector + * @return {Vec2} returns this + * @chainable + * @example + * var v = cc.v2(10, 10); + * v.subSelf(cc.v2(5, 5));// return Vec2 {x: 5, y: 5}; + */ +proto.subSelf = function (vector) { + this.x -= vector.x; + this.y -= vector.y; + return this; +}; + +/** + * !#en Subtracts one vector from this, and returns the new result. + * !#zh 向量减法,并返回新结果。 + * @method sub + * @param {Vec2} vector + * @param {Vec2} [out] - optional, the receiving vector + * @return {Vec2} the result + * @example + * var v = cc.v2(10, 10); + * v.sub(cc.v2(5, 5)); // return Vec2 {x: 5, y: 5}; + * var v1; + * v.sub(cc.v2(5, 5), v1); // return Vec2 {x: 5, y: 5}; + */ +proto.sub = function (vector, out) { + out = out || new Vec2(); + out.x = this.x - vector.x; + out.y = this.y - vector.y; + return out; +}; + +/** + * !#en Multiplies this by a number. If you want to save result to another vector, use mul() instead. + * !#zh 缩放当前向量。如果你想结果保存到另一个向量,可使用 mul() 代替。 + * @method mulSelf + * @param {number} num + * @return {Vec2} returns this + * @chainable + * @example + * var v = cc.v2(10, 10); + * v.mulSelf(5);// return Vec2 {x: 50, y: 50}; + */ +proto.mulSelf = function (num) { + this.x *= num; + this.y *= num; + return this; +}; + +/** + * !#en Multiplies by a number, and returns the new result. + * !#zh 缩放当前向量,并返回新结果。 + * @method mul + * @param {number} num + * @param {Vec2} [out] - optional, the receiving vector + * @return {Vec2} the result + * @example + * var v = cc.v2(10, 10); + * v.mul(5); // return Vec2 {x: 50, y: 50}; + * var v1; + * v.mul(5, v1); // return Vec2 {x: 50, y: 50}; + */ +proto.mul = function (num, out) { + out = out || new Vec2(); + out.x = this.x * num; + out.y = this.y * num; + return out; +}; + +/** + * !#en Multiplies two vectors. + * !#zh 分量相乘。 + * @method scaleSelf + * @param {Vec2} vector + * @return {Vec2} returns this + * @chainable + * @example + * var v = cc.v2(10, 10); + * v.scaleSelf(cc.v2(5, 5));// return Vec2 {x: 50, y: 50}; + */ +proto.scaleSelf = function (vector) { + this.x *= vector.x; + this.y *= vector.y; + return this; +}; + +/** + * !#en Multiplies two vectors, and returns the new result. + * !#zh 分量相乘,并返回新的结果。 + * @method scale + * @param {Vec2} vector + * @param {Vec2} [out] - optional, the receiving vector + * @return {Vec2} the result + * @example + * var v = cc.v2(10, 10); + * v.scale(cc.v2(5, 5)); // return Vec2 {x: 50, y: 50}; + * var v1; + * v.scale(cc.v2(5, 5), v1); // return Vec2 {x: 50, y: 50}; + */ +proto.scale = function (vector, out) { + out = out || new Vec2(); + out.x = this.x * vector.x; + out.y = this.y * vector.y; + return out; +}; + +/** + * !#en Divides by a number. If you want to save result to another vector, use div() instead. + * !#zh 向量除法。如果你想结果保存到另一个向量,可使用 div() 代替。 + * @method divSelf + * @param {Vec2} vector + * @return {Vec2} returns this + * @chainable + * @example + * var v = cc.v2(10, 10); + * v.divSelf(5); // return Vec2 {x: 2, y: 2}; + */ +proto.divSelf = function (num) { + this.x /= num; + this.y /= num; + return this; +}; + +/** + * !#en Divides by a number, and returns the new result. + * !#zh 向量除法,并返回新的结果。 + * @method div + * @param {Vec2} vector + * @param {Vec2} [out] - optional, the receiving vector + * @return {Vec2} the result + * @example + * var v = cc.v2(10, 10); + * v.div(5); // return Vec2 {x: 2, y: 2}; + * var v1; + * v.div(5, v1); // return Vec2 {x: 2, y: 2}; + */ +proto.div = function (num, out) { + out = out || new Vec2(); + out.x = this.x / num; + out.y = this.y / num; + return out; +}; + +/** + * !#en Negates the components. If you want to save result to another vector, use neg() instead. + * !#zh 向量取反。如果你想结果保存到另一个向量,可使用 neg() 代替。 + * @method negSelf + * @return {Vec2} returns this + * @chainable + * @example + * var v = cc.v2(10, 10); + * v.negSelf(); // return Vec2 {x: -10, y: -10}; + */ +proto.negSelf = function () { + this.x = -this.x; + this.y = -this.y; + return this; +}; + +/** + * !#en Negates the components, and returns the new result. + * !#zh 返回取反后的新向量。 + * @method neg + * @param {Vec2} [out] - optional, the receiving vector + * @return {Vec2} the result + * @example + * var v = cc.v2(10, 10); + * var v1; + * v.neg(v1); // return Vec2 {x: -10, y: -10}; + */ +proto.neg = function (out) { + out = out || new Vec2(); + out.x = -this.x; + out.y = -this.y; + return out; +}; + +/** + * !#en Dot product + * !#zh 当前向量与指定向量进行点乘。 + * @method dot + * @param {Vec2} [vector] + * @return {number} the result + * @example + * var v = cc.v2(10, 10); + * v.dot(cc.v2(5, 5)); // return 100; + */ +proto.dot = function (vector) { + return this.x * vector.x + this.y * vector.y; +}; + +/** + * !#en Cross product + * !#zh 当前向量与指定向量进行叉乘。 + * @method cross + * @param {Vec2} [vector] + * @return {number} the result + * @example + * var v = cc.v2(10, 10); + * v.cross(cc.v2(5, 5)); // return 0; + */ +proto.cross = function (vector) { + return this.y * vector.x - this.x * vector.y; +}; + +/** + * !#en Returns the length of this vector. + * !#zh 返回该向量的长度。 + * @method mag + * @return {number} the result + * @example + * var v = cc.v2(10, 10); + * v.mag(); // return 14.142135623730951; + */ +proto.mag = function () { + return Math.sqrt(this.x * this.x + this.y * this.y); +}; + +/** + * !#en Returns the squared length of this vector. + * !#zh 返回该向量的长度平方。 + * @method magSqr + * @return {number} the result + * @example + * var v = cc.v2(10, 10); + * v.magSqr(); // return 200; + */ +proto.magSqr = function () { + return this.x * this.x + this.y * this.y; +}; + +/** + * !#en Make the length of this vector to 1. + * !#zh 向量归一化,让这个向量的长度为 1。 + * @method normalizeSelf + * @return {Vec2} returns this + * @chainable + * @example + * var v = cc.v2(10, 10); + * v.normalizeSelf(); // return Vec2 {x: 0.7071067811865475, y: 0.7071067811865475}; + */ +proto.normalizeSelf = function () { + var magSqr = this.x * this.x + this.y * this.y; + if (magSqr === 1.0) return this; - }, - /** - * !#en TODO - * !#zh 当前的向量是否与指定的向量相等。 - * @method equals - * @param {Vec2} other - * @return {Boolean} - */ - equals: function (other) { - return other && this.x === other.x && this.y === other.y; - }, - - /** - * !#en TODO - * !#zh 转换为方便阅读的字符串。 - * @method toString - * @return {string} - */ - toString: function () { - return "(" + - this.x.toFixed(2) + ", " + - this.y.toFixed(2) + ")" - ; - }, - - /** - * !#en TODO - * !#zh 线性插值。 - * @method lerp - * @param {Vec2} to - * @param {number} ratio - the interpolation coefficient - * @param {Vec2} [out] - optional, the receiving vector - * @return {Vec2} - */ - lerp: function (to, ratio, out) { - out = out || new Vec2(); - var x = this.x; - var y = this.y; - out.x = x + (to.x - x) * ratio; - out.y = y + (to.y - y) * ratio; - return out; - }, - - /** - * !#en Adds this vector. If you want to save result to another vector, use add() instead. - * !#zh 向量加法。如果你想保存结果到另一个向量,使用 add() 代替。 - * @method addSelf - * @param {Vec2} vector - * @return {Vec2} returns this - * @chainable - * @example - * var v = cc.v2(10, 10); - * v.addSelf(cc.v2(5, 5));// return Vec2 {x: 15, y: 15}; - */ - addSelf: function (vector) { - this.x += vector.x; - this.y += vector.y; - return this; - }, - - /** - * !#en Adds two vectors, and returns the new result. - * !#zh 向量加法,并返回新结果。 - * @method add - * @param {Vec2} vector - * @param {Vec2} [out] - optional, the receiving vector - * @return {Vec2} the result - * @example - * var v = cc.v2(10, 10); - * v.add(cc.v2(5, 5)); // return Vec2 {x: 15, y: 15}; - * var v1; - * v.add(cc.v2(5, 5), v1); // return Vec2 {x: 15, y: 15}; - */ - add: function (vector, out) { - out = out || new Vec2(); - out.x = this.x + vector.x; - out.y = this.y + vector.y; - return out; - }, - - /** - * !#en Subtracts one vector from this. If you want to save result to another vector, use sub() instead. - * !#zh 向量减法。如果你想保存结果到另一个向量,可使用 sub() 代替。 - * @method subSelf - * @param {Vec2} vector - * @return {Vec2} returns this - * @chainable - * @example - * var v = cc.v2(10, 10); - * v.subSelf(cc.v2(5, 5));// return Vec2 {x: 5, y: 5}; - */ - subSelf: function (vector) { - this.x -= vector.x; - this.y -= vector.y; - return this; - }, - - /** - * !#en Subtracts one vector from this, and returns the new result. - * !#zh 向量减法,并返回新结果。 - * @method sub - * @param {Vec2} vector - * @param {Vec2} [out] - optional, the receiving vector - * @return {Vec2} the result - * @example - * var v = cc.v2(10, 10); - * v.sub(cc.v2(5, 5)); // return Vec2 {x: 5, y: 5}; - * var v1; - * v.sub(cc.v2(5, 5), v1); // return Vec2 {x: 5, y: 5}; - */ - sub: function (vector, out) { - out = out || new Vec2(); - out.x = this.x - vector.x; - out.y = this.y - vector.y; - return out; - }, - - /** - * !#en Multiplies this by a number. If you want to save result to another vector, use mul() instead. - * !#zh 缩放当前向量。如果你想结果保存到另一个向量,可使用 mul() 代替。 - * @method mulSelf - * @param {number} num - * @return {Vec2} returns this - * @chainable - * @example - * var v = cc.v2(10, 10); - * v.mulSelf(5);// return Vec2 {x: 50, y: 50}; - */ - mulSelf: function (num) { - this.x *= num; - this.y *= num; - return this; - }, - - /** - * !#en Multiplies by a number, and returns the new result. - * !#zh 缩放当前向量,并返回新结果。 - * @method mul - * @param {number} num - * @param {Vec2} [out] - optional, the receiving vector - * @return {Vec2} the result - * @example - * var v = cc.v2(10, 10); - * v.mul(5); // return Vec2 {x: 50, y: 50}; - * var v1; - * v.mul(5, v1); // return Vec2 {x: 50, y: 50}; - */ - mul: function (num, out) { - out = out || new Vec2(); - out.x = this.x * num; - out.y = this.y * num; - return out; - }, - - /** - * !#en Multiplies two vectors. - * !#zh 分量相乘。 - * @method scaleSelf - * @param {Vec2} vector - * @return {Vec2} returns this - * @chainable - * @example - * var v = cc.v2(10, 10); - * v.scaleSelf(cc.v2(5, 5));// return Vec2 {x: 50, y: 50}; - */ - scaleSelf: function (vector) { - this.x *= vector.x; - this.y *= vector.y; - return this; - }, - - /** - * !#en Multiplies two vectors, and returns the new result. - * !#zh 分量相乘,并返回新的结果。 - * @method scale - * @param {Vec2} vector - * @param {Vec2} [out] - optional, the receiving vector - * @return {Vec2} the result - * @example - * var v = cc.v2(10, 10); - * v.scale(cc.v2(5, 5)); // return Vec2 {x: 50, y: 50}; - * var v1; - * v.scale(cc.v2(5, 5), v1); // return Vec2 {x: 50, y: 50}; - */ - scale: function (vector, out) { - out = out || new Vec2(); - out.x = this.x * vector.x; - out.y = this.y * vector.y; - return out; - }, - - /** - * !#en Divides by a number. If you want to save result to another vector, use div() instead. - * !#zh 向量除法。如果你想结果保存到另一个向量,可使用 div() 代替。 - * @method divSelf - * @param {Vec2} vector - * @return {Vec2} returns this - * @chainable - * @example - * var v = cc.v2(10, 10); - * v.divSelf(5); // return Vec2 {x: 2, y: 2}; - */ - divSelf: function (num) { - this.x /= num; - this.y /= num; - return this; - }, - - /** - * !#en Divides by a number, and returns the new result. - * !#zh 向量除法,并返回新的结果。 - * @method div - * @param {Vec2} vector - * @param {Vec2} [out] - optional, the receiving vector - * @return {Vec2} the result - * @example - * var v = cc.v2(10, 10); - * v.div(5); // return Vec2 {x: 2, y: 2}; - * var v1; - * v.div(5, v1); // return Vec2 {x: 2, y: 2}; - */ - div: function (num, out) { - out = out || new Vec2(); - out.x = this.x / num; - out.y = this.y / num; - return out; - }, - - /** - * !#en Negates the components. If you want to save result to another vector, use neg() instead. - * !#zh 向量取反。如果你想结果保存到另一个向量,可使用 neg() 代替。 - * @method negSelf - * @return {Vec2} returns this - * @chainable - * @example - * var v = cc.v2(10, 10); - * v.negSelf(); // return Vec2 {x: -10, y: -10}; - */ - negSelf: function () { - this.x = -this.x; - this.y = -this.y; - return this; - }, - - /** - * !#en Negates the components, and returns the new result. - * !#zh 返回取反后的新向量。 - * @method neg - * @param {Vec2} [out] - optional, the receiving vector - * @return {Vec2} the result - * @example - * var v = cc.v2(10, 10); - * var v1; - * v.neg(v1); // return Vec2 {x: -10, y: -10}; - */ - neg: function (out) { - out = out || new Vec2(); - out.x = -this.x; - out.y = -this.y; - return out; - }, - - /** - * !#en Dot product - * !#zh 当前向量与指定向量进行点乘。 - * @method dot - * @param {Vec2} [vector] - * @return {number} the result - * @example - * var v = cc.v2(10, 10); - * v.dot(cc.v2(5, 5)); // return 100; - */ - dot: function (vector) { - return this.x * vector.x + this.y * vector.y; - }, - - /** - * !#en Cross product - * !#zh 当前向量与指定向量进行叉乘。 - * @method cross - * @param {Vec2} [vector] - * @return {number} the result - * @example - * var v = cc.v2(10, 10); - * v.cross(cc.v2(5, 5)); // return 0; - */ - cross: function (vector) { - return this.y * vector.x - this.x * vector.y; - }, - - /** - * !#en Returns the length of this vector. - * !#zh 返回该向量的长度。 - * @method mag - * @return {number} the result - * @example - * var v = cc.v2(10, 10); - * v.mag(); // return 14.142135623730951; - */ - mag: function () { - return Math.sqrt(this.x * this.x + this.y * this.y); - }, - - /** - * !#en Returns the squared length of this vector. - * !#zh 返回该向量的长度平方。 - * @method magSqr - * @return {number} the result - * @example - * var v = cc.v2(10, 10); - * v.magSqr(); // return 200; - */ - magSqr: function () { - return this.x * this.x + this.y * this.y; - }, - - /** - * !#en Make the length of this vector to 1. - * !#zh 向量归一化,让这个向量的长度为 1。 - * @method normalizeSelf - * @return {Vec2} returns this - * @chainable - * @example - * var v = cc.v2(10, 10); - * v.normalizeSelf(); // return Vec2 {x: 0.7071067811865475, y: 0.7071067811865475}; - */ - normalizeSelf: function () { - var magSqr = this.x * this.x + this.y * this.y; - if (magSqr === 1.0) - return this; - - if (magSqr === 0.0) { - console.warn("Can't normalize zero vector"); - return this; - } - - var invsqrt = 1.0 / Math.sqrt(magSqr); - this.x *= invsqrt; - this.y *= invsqrt; - - return this; - }, - - /** - * !#en - * Returns this vector with a magnitude of 1.
- *
- * Note that the current vector is unchanged and a new normalized vector is returned. If you want to normalize the current vector, use normalizeSelf function. - * !#zh - * 返回归一化后的向量。
- *
- * 注意,当前向量不变,并返回一个新的归一化向量。如果你想来归一化当前向量,可使用 normalizeSelf 函数。 - * @method normalize - * @param {Vec2} [out] - optional, the receiving vector - * @return {Vec2} result - * var v = cc.v2(10, 10); - * v.normalize(); // return Vec2 {x: 0.7071067811865475, y: 0.7071067811865475}; - */ - normalize: function (out) { - out = out || new Vec2(); - out.x = this.x; - out.y = this.y; - out.normalizeSelf(); - return out; - }, - - /** - * !#en Get angle in radian between this and vector. - * !#zh 夹角的弧度。 - * @method angle - * @param {Vec2} vector - * @return {number} from 0 to Math.PI - */ - angle: function (vector) { - var magSqr1 = this.magSqr(); - var magSqr2 = vector.magSqr(); - - if (magSqr1 === 0 || magSqr2 === 0) { - console.warn("Can't get angle between zero vector"); - return 0.0; - } - - var dot = this.dot(vector); - var theta = dot / (Math.sqrt(magSqr1 * magSqr2)); - theta = cc.clampf(theta, -1.0, 1.0); - return Math.acos(theta); - }, - - /** - * !#en Get angle in radian between this and vector with direction. - * !#zh 带方向的夹角的弧度。 - * @method signAngle - * @param {Vec2} vector - * @return {number} from -MathPI to Math.PI - */ - signAngle: function (vector) { - // NOTE: this algorithm will return 0.0 without signed if vectors are parallex - // var angle = this.angle(vector); - // var cross = this.cross(vector); - // return Math.sign(cross) * angle; - - return Math.atan2(this.y, this.x) - Math.atan2(vector.y, vector.x); - }, - - /** - * !#en rotate - * !#zh 返回旋转给定弧度后的新向量。 - * @method rotate - * @param {number} radians - * @param {Vec2} [out] - optional, the receiving vector - * @return {Vec2} the result - */ - rotate: function (radians, out) { - out = out || new Vec2(); - out.x = this.x; - out.y = this.y; - return out.rotateSelf(radians); - }, - - /** - * !#en rotate self - * !#zh 按指定弧度旋转向量。 - * @method rotateSelf - * @param {number} radians - * @return {Vec2} returns this - * @chainable - */ - rotateSelf: function (radians) { - var sin = Math.sin(radians); - var cos = Math.cos(radians); - var x = this.x; - this.x = cos * x - sin * this.y; - this.y = sin * x + cos * this.y; + if (magSqr === 0.0) { + console.warn("Can't normalize zero vector"); return this; } - //_serialize: function () { - // return [this.x, this.y]; - //}, - //_deserialize: function (data) { - // this.x = data[0]; - // this.y = data[1]; - //} -}); + var invsqrt = 1.0 / Math.sqrt(magSqr); + this.x *= invsqrt; + this.y *= invsqrt; + + return this; +}; + +/** + * !#en + * Returns this vector with a magnitude of 1.
+ *
+ * Note that the current vector is unchanged and a new normalized vector is returned. If you want to normalize the current vector, use normalizeSelf function. + * !#zh + * 返回归一化后的向量。
+ *
+ * 注意,当前向量不变,并返回一个新的归一化向量。如果你想来归一化当前向量,可使用 normalizeSelf 函数。 + * @method normalize + * @param {Vec2} [out] - optional, the receiving vector + * @return {Vec2} result + * var v = cc.v2(10, 10); + * v.normalize(); // return Vec2 {x: 0.7071067811865475, y: 0.7071067811865475}; + */ +proto.normalize = function (out) { + out = out || new Vec2(); + out.x = this.x; + out.y = this.y; + out.normalizeSelf(); + return out; +}; + +/** + * !#en Get angle in radian between this and vector. + * !#zh 夹角的弧度。 + * @method angle + * @param {Vec2} vector + * @return {number} from 0 to Math.PI + */ +proto.angle = function (vector) { + var magSqr1 = this.magSqr(); + var magSqr2 = vector.magSqr(); + + if (magSqr1 === 0 || magSqr2 === 0) { + console.warn("Can't get angle between zero vector"); + return 0.0; + } + + var dot = this.dot(vector); + var theta = dot / (Math.sqrt(magSqr1 * magSqr2)); + theta = cc.clampf(theta, -1.0, 1.0); + return Math.acos(theta); +}; + +/** + * !#en Get angle in radian between this and vector with direction. + * !#zh 带方向的夹角的弧度。 + * @method signAngle + * @param {Vec2} vector + * @return {number} from -MathPI to Math.PI + */ +proto.signAngle = function (vector) { + // NOTE: this algorithm will return 0.0 without signed if vectors are parallex + // var angle = this.angle(vector); + // var cross = this.cross(vector); + // return Math.sign(cross) * angle; + + return Math.atan2(this.y, this.x) - Math.atan2(vector.y, vector.x); +}; + +/** + * !#en rotate + * !#zh 返回旋转给定弧度后的新向量。 + * @method rotate + * @param {number} radians + * @param {Vec2} [out] - optional, the receiving vector + * @return {Vec2} the result + */ +proto.rotate = function (radians, out) { + out = out || new Vec2(); + out.x = this.x; + out.y = this.y; + return out.rotateSelf(radians); +}; + +/** + * !#en rotate self + * !#zh 按指定弧度旋转向量。 + * @method rotateSelf + * @param {number} radians + * @return {Vec2} returns this + * @chainable + */ +proto.rotateSelf = function (radians) { + var sin = Math.sin(radians); + var cos = Math.cos(radians); + var x = this.x; + this.x = cos * x - sin * this.y; + this.y = sin * x + cos * this.y; + return this; +}; + +//_serialize: function () { +// return [this.x, this.y]; +//}, +//_deserialize: function (data) { +// this.x = data[0]; +// this.y = data[1]; +//} // static diff --git a/cocos2d/shape-nodes/CCDrawNode.js b/cocos2d/shape-nodes/CCDrawNode.js index 8db1994c04..e19b55a924 100644 --- a/cocos2d/shape-nodes/CCDrawNode.js +++ b/cocos2d/shape-nodes/CCDrawNode.js @@ -110,6 +110,7 @@ cc.DrawNode.TYPE_SEGMENT = 1; cc.DrawNode.TYPE_POLY = 2; cc.game.once(cc.game.EVENT_RENDERER_INITED, function () { + var proto = cc.DrawNode.prototype; if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) { cc._DrawNodeElement = function (type, verts, fillColor, lineWidth, lineColor, lineCap, isClosePolygon, isFill, isStroke) { @@ -125,725 +126,721 @@ cc.game.once(cc.game.EVENT_RENDERER_INITED, function () { _t.isStroke = isStroke || false; }; - cc.js.mixin(cc.DrawNode.prototype, /** @lends cc.DrawNode# */{ - _className: "DrawNodeCanvas", + proto._className = "DrawNodeCanvas"; - /** - *

The cc.DrawNodeCanvas's constructor.
- * This function will automatically be invoked when you create a node using new construction: "var node = new cc.DrawNodeCanvas()".
- * Override it to extend its behavior, remember to call "this._super()" in the extended "ctor" function.

- */ - ctor: function () { - _ccsg.Node.prototype.ctor.call(this); - var locCmd = this._renderCmd; - locCmd._buffer = this._buffer = []; - locCmd._drawColor = this._drawColor = cc.color(255, 255, 255, 255); - locCmd._blendFunc = this._blendFunc = new cc.BlendFunc(cc.macro.SRC_ALPHA, cc.macro.ONE_MINUS_SRC_ALPHA); + /** + *

The cc.DrawNodeCanvas's constructor.
+ * This function will automatically be invoked when you create a node using new construction: "var node = new cc.DrawNodeCanvas()".
+ * Override it to extend its behavior, remember to call "this._super()" in the extended "ctor" function.

+ */ + proto.ctor = function () { + _ccsg.Node.prototype.ctor.call(this); + var locCmd = this._renderCmd; + locCmd._buffer = this._buffer = []; + locCmd._drawColor = this._drawColor = cc.color(255, 255, 255, 255); + locCmd._blendFunc = this._blendFunc = new cc.BlendFunc(cc.macro.SRC_ALPHA, cc.macro.ONE_MINUS_SRC_ALPHA); - this.init(); - }, + this.init(); + }; - /** - * draws a rectangle given the origin and destination point measured in points. - * @param {cc.Vec2} origin - * @param {cc.Vec2} destination - * @param {cc.Color} fillColor - * @param {Number} lineWidth - * @param {cc.Color} lineColor - */ - drawRect: function (origin, destination, fillColor, lineWidth, lineColor) { - lineWidth = (lineWidth == null) ? this._lineWidth : lineWidth; - lineColor = lineColor || this.getDrawColor(); - if(lineColor.a == null) - lineColor.a = 255; + /** + * draws a rectangle given the origin and destination point measured in points. + * @param {cc.Vec2} origin + * @param {cc.Vec2} destination + * @param {cc.Color} fillColor + * @param {Number} lineWidth + * @param {cc.Color} lineColor + */ + proto.drawRect = function (origin, destination, fillColor, lineWidth, lineColor) { + lineWidth = (lineWidth == null) ? this._lineWidth : lineWidth; + lineColor = lineColor || this.getDrawColor(); + if(lineColor.a == null) + lineColor.a = 255; - var vertices = [ - origin, - cc.p(destination.x, origin.y), - destination, - cc.p(origin.x, destination.y) - ]; - var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); - element.verts = vertices; - element.lineWidth = lineWidth; - element.lineColor = lineColor; - element.isClosePolygon = true; - element.isStroke = true; - element.lineCap = "butt"; - element.fillColor = fillColor; - if (fillColor) { - if(fillColor.a == null) - fillColor.a = 255; - element.isFill = true; - } - this._buffer.push(element); - }, - - /** - * draws a circle given the center, radius and number of segments. - * @override - * @param {cc.Vec2} center center of circle - * @param {Number} radius - * @param {Number} angle angle in radians - * @param {Number} segments - * @param {Boolean} drawLineToCenter - * @param {Number} lineWidth - * @param {cc.Color} color - */ - drawCircle: function (center, radius, angle, segments, drawLineToCenter, lineWidth, color) { - lineWidth = lineWidth || this._lineWidth; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - - var coef = 2.0 * Math.PI / segments; - var vertices = []; - for (var i = 0; i <= segments; i++) { - var rads = i * coef; - var j = radius * Math.cos(rads + angle) + center.x; - var k = radius * Math.sin(rads + angle) + center.y; - vertices.push(cc.p(j, k)); - } - if (drawLineToCenter) { - vertices.push(cc.p(center.x, center.y)); - } - - var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); - element.verts = vertices; - element.lineWidth = lineWidth; - element.lineColor = color; - element.isClosePolygon = true; - element.isStroke = true; - this._buffer.push(element); - }, - - /** - * draws a quad bezier path - * @override - * @param {cc.Vec2} origin - * @param {cc.Vec2} control - * @param {cc.Vec2} destination - * @param {Number} segments - * @param {Number} lineWidth - * @param {cc.Color} color - */ - drawQuadBezier: function (origin, control, destination, segments, lineWidth, color) { - lineWidth = lineWidth || this._lineWidth; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - - var vertices = [], t = 0.0; - for (var i = 0; i < segments; i++) { - var x = Math.pow(1 - t, 2) * origin.x + 2.0 * (1 - t) * t * control.x + t * t * destination.x; - var y = Math.pow(1 - t, 2) * origin.y + 2.0 * (1 - t) * t * control.y + t * t * destination.y; - vertices.push(cc.p(x, y)); - t += 1.0 / segments; - } - vertices.push(cc.p(destination.x, destination.y)); - - var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); - element.verts = vertices; - element.lineWidth = lineWidth; - element.lineColor = color; - element.isStroke = true; - element.lineCap = "round"; - this._buffer.push(element); - }, - - /** - * draws a cubic bezier path - * @override - * @param {cc.Vec2} origin - * @param {cc.Vec2} control1 - * @param {cc.Vec2} control2 - * @param {cc.Vec2} destination - * @param {Number} segments - * @param {Number} lineWidth - * @param {cc.Color} color - */ - drawCubicBezier: function (origin, control1, control2, destination, segments, lineWidth, color) { - lineWidth = lineWidth || this._lineWidth; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - - var vertices = [], t = 0; - for (var i = 0; i < segments; i++) { - var x = Math.pow(1 - t, 3) * origin.x + 3.0 * Math.pow(1 - t, 2) * t * control1.x + 3.0 * (1 - t) * t * t * control2.x + t * t * t * destination.x; - var y = Math.pow(1 - t, 3) * origin.y + 3.0 * Math.pow(1 - t, 2) * t * control1.y + 3.0 * (1 - t) * t * t * control2.y + t * t * t * destination.y; - vertices.push(cc.p(x, y)); - t += 1.0 / segments; - } - vertices.push(cc.p(destination.x, destination.y)); - - var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); - element.verts = vertices; - element.lineWidth = lineWidth; - element.lineColor = color; - element.isStroke = true; - element.lineCap = "round"; - this._buffer.push(element); - }, - - /** - * draw a CatmullRom curve - * @override - * @param {Array} points - * @param {Number} segments - * @param {Number} lineWidth - * @param {cc.Color} color - */ - drawCatmullRom: function (points, segments, lineWidth, color) { - this.drawCardinalSpline(points, 0.5, segments, lineWidth, color); - }, - - /** - * draw a cardinal spline path - * @override - * @param {Array} config - * @param {Number} tension - * @param {Number} segments - * @param {Number} lineWidth - * @param {cc.Color} color - */ - drawCardinalSpline: function (config, tension, segments, lineWidth, color) { - lineWidth = lineWidth || this._lineWidth; - color = color || this.getDrawColor(); - if(color.a == null) - color.a = 255; - - var vertices = [], p, lt, deltaT = 1.0 / config.length; - for (var i = 0; i < segments + 1; i++) { - var dt = i / segments; - // border - if (dt === 1) { - p = config.length - 1; - lt = 1; - } else { - p = 0 | (dt / deltaT); - lt = (dt - deltaT * p) / deltaT; - } - - // Interpolate - var newPos = cc.cardinalSplineAt( - cc.getControlPointAt(config, p - 1), - cc.getControlPointAt(config, p - 0), - cc.getControlPointAt(config, p + 1), - cc.getControlPointAt(config, p + 2), - tension, lt); - vertices.push(newPos); - } - - var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); - element.verts = vertices; - element.lineWidth = lineWidth; - element.lineColor = color; - element.isStroke = true; - element.lineCap = "round"; - this._buffer.push(element); - }, - - /** - * draw a dot at a position, with a given radius and color - * @param {cc.Vec2} pos - * @param {Number} radius - * @param {cc.Color} color - */ - drawDot: function (pos, radius, color) { - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_DOT); - element.verts = [pos]; - element.lineWidth = radius; - element.fillColor = color; - this._buffer.push(element); - }, - - /** - * draws an array of points. - * @override - * @param {Array} points point of array - * @param {Number} radius - * @param {cc.Color} color - */ - drawDots: function(points, radius, color){ - if(!points || points.length == 0) - return; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - for(var i = 0, len = points.length; i < len; i++) - this.drawDot(points[i], radius, color); - }, - - /** - * draw a segment with a radius and color - * @param {cc.Vec2} from - * @param {cc.Vec2} to - * @param {Number} lineWidth - * @param {cc.Color} color - */ - drawSegment: function (from, to, lineWidth, color) { - lineWidth = lineWidth || this._lineWidth; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); - element.verts = [from, to]; - element.lineWidth = lineWidth * 2; - element.lineColor = color; - element.isStroke = true; - element.lineCap = "round"; - this._buffer.push(element); - }, - - /** - * draw a polygon with a fill color and line color without copying the vertex list - * @param {Array} verts - * @param {cc.Color} fillColor - * @param {Number} lineWidth - * @param {cc.Color} color - */ - drawPoly_: function (verts, fillColor, lineWidth, color, notClosePoly) { - lineWidth = (lineWidth == null ) ? this._lineWidth : lineWidth; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); - - element.verts = verts; - element.fillColor = fillColor; - element.lineWidth = lineWidth; - element.lineColor = color; - element.isClosePolygon = !notClosePoly; - element.isStroke = true; - element.lineCap = "round"; - if (fillColor) - element.isFill = true; - this._buffer.push(element); - }, - - /** - * draw a polygon with a fill color and line color, copying the vertex list - * @param {Array} verts - * @param {cc.Color} fillColor - * @param {Number} lineWidth - * @param {cc.Color} color - * @param {Boolean} notClosePoly - */ - drawPoly: function (verts, fillColor, lineWidth, color, notClosePoly) { - var vertsCopy = []; - for (var i=0; i < verts.length; i++) { - vertsCopy.push(cc.p(verts[i].x, verts[i].y)); - } - return this.drawPoly_(vertsCopy, fillColor, lineWidth, color, notClosePoly); - }, - - /** - * Clear the geometry in the node's buffer. - */ - clear: function () { - this._buffer.length = 0; - }, - - _createRenderCmd: function(){ - return new cc.DrawNode.CanvasRenderCmd(this); + var vertices = [ + origin, + cc.p(destination.x, origin.y), + destination, + cc.p(origin.x, destination.y) + ]; + var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); + element.verts = vertices; + element.lineWidth = lineWidth; + element.lineColor = lineColor; + element.isClosePolygon = true; + element.isStroke = true; + element.lineCap = "butt"; + element.fillColor = fillColor; + if (fillColor) { + if(fillColor.a == null) + fillColor.a = 255; + element.isFill = true; } - }); + this._buffer.push(element); + }; + + /** + * draws a circle given the center, radius and number of segments. + * @override + * @param {cc.Vec2} center center of circle + * @param {Number} radius + * @param {Number} angle angle in radians + * @param {Number} segments + * @param {Boolean} drawLineToCenter + * @param {Number} lineWidth + * @param {cc.Color} color + */ + proto.drawCircle = function (center, radius, angle, segments, drawLineToCenter, lineWidth, color) { + lineWidth = lineWidth || this._lineWidth; + color = color || this.getDrawColor(); + if (color.a == null) + color.a = 255; + + var coef = 2.0 * Math.PI / segments; + var vertices = []; + for (var i = 0; i <= segments; i++) { + var rads = i * coef; + var j = radius * Math.cos(rads + angle) + center.x; + var k = radius * Math.sin(rads + angle) + center.y; + vertices.push(cc.p(j, k)); + } + if (drawLineToCenter) { + vertices.push(cc.p(center.x, center.y)); + } + + var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); + element.verts = vertices; + element.lineWidth = lineWidth; + element.lineColor = color; + element.isClosePolygon = true; + element.isStroke = true; + this._buffer.push(element); + }; + + /** + * draws a quad bezier path + * @override + * @param {cc.Vec2} origin + * @param {cc.Vec2} control + * @param {cc.Vec2} destination + * @param {Number} segments + * @param {Number} lineWidth + * @param {cc.Color} color + */ + proto.drawQuadBezier = function (origin, control, destination, segments, lineWidth, color) { + lineWidth = lineWidth || this._lineWidth; + color = color || this.getDrawColor(); + if (color.a == null) + color.a = 255; + + var vertices = [], t = 0.0; + for (var i = 0; i < segments; i++) { + var x = Math.pow(1 - t, 2) * origin.x + 2.0 * (1 - t) * t * control.x + t * t * destination.x; + var y = Math.pow(1 - t, 2) * origin.y + 2.0 * (1 - t) * t * control.y + t * t * destination.y; + vertices.push(cc.p(x, y)); + t += 1.0 / segments; + } + vertices.push(cc.p(destination.x, destination.y)); + + var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); + element.verts = vertices; + element.lineWidth = lineWidth; + element.lineColor = color; + element.isStroke = true; + element.lineCap = "round"; + this._buffer.push(element); + }; + + /** + * draws a cubic bezier path + * @override + * @param {cc.Vec2} origin + * @param {cc.Vec2} control1 + * @param {cc.Vec2} control2 + * @param {cc.Vec2} destination + * @param {Number} segments + * @param {Number} lineWidth + * @param {cc.Color} color + */ + proto.drawCubicBezier = function (origin, control1, control2, destination, segments, lineWidth, color) { + lineWidth = lineWidth || this._lineWidth; + color = color || this.getDrawColor(); + if (color.a == null) + color.a = 255; + + var vertices = [], t = 0; + for (var i = 0; i < segments; i++) { + var x = Math.pow(1 - t, 3) * origin.x + 3.0 * Math.pow(1 - t, 2) * t * control1.x + 3.0 * (1 - t) * t * t * control2.x + t * t * t * destination.x; + var y = Math.pow(1 - t, 3) * origin.y + 3.0 * Math.pow(1 - t, 2) * t * control1.y + 3.0 * (1 - t) * t * t * control2.y + t * t * t * destination.y; + vertices.push(cc.p(x, y)); + t += 1.0 / segments; + } + vertices.push(cc.p(destination.x, destination.y)); + + var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); + element.verts = vertices; + element.lineWidth = lineWidth; + element.lineColor = color; + element.isStroke = true; + element.lineCap = "round"; + this._buffer.push(element); + }; + + /** + * draw a CatmullRom curve + * @override + * @param {Array} points + * @param {Number} segments + * @param {Number} lineWidth + * @param {cc.Color} color + */ + proto.drawCatmullRom = function (points, segments, lineWidth, color) { + this.drawCardinalSpline(points, 0.5, segments, lineWidth, color); + }; + + /** + * draw a cardinal spline path + * @override + * @param {Array} config + * @param {Number} tension + * @param {Number} segments + * @param {Number} lineWidth + * @param {cc.Color} color + */ + proto.drawCardinalSpline = function (config, tension, segments, lineWidth, color) { + lineWidth = lineWidth || this._lineWidth; + color = color || this.getDrawColor(); + if(color.a == null) + color.a = 255; + + var vertices = [], p, lt, deltaT = 1.0 / config.length; + for (var i = 0; i < segments + 1; i++) { + var dt = i / segments; + // border + if (dt === 1) { + p = config.length - 1; + lt = 1; + } else { + p = 0 | (dt / deltaT); + lt = (dt - deltaT * p) / deltaT; + } + + // Interpolate + var newPos = cc.cardinalSplineAt( + cc.getControlPointAt(config, p - 1), + cc.getControlPointAt(config, p - 0), + cc.getControlPointAt(config, p + 1), + cc.getControlPointAt(config, p + 2), + tension, lt); + vertices.push(newPos); + } + + var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); + element.verts = vertices; + element.lineWidth = lineWidth; + element.lineColor = color; + element.isStroke = true; + element.lineCap = "round"; + this._buffer.push(element); + }; + + /** + * draw a dot at a position, with a given radius and color + * @param {cc.Vec2} pos + * @param {Number} radius + * @param {cc.Color} color + */ + proto.drawDot = function (pos, radius, color) { + color = color || this.getDrawColor(); + if (color.a == null) + color.a = 255; + var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_DOT); + element.verts = [pos]; + element.lineWidth = radius; + element.fillColor = color; + this._buffer.push(element); + }; + + /** + * draws an array of points. + * @override + * @param {Array} points point of array + * @param {Number} radius + * @param {cc.Color} color + */ + proto.drawDots = function(points, radius, color){ + if(!points || points.length == 0) + return; + color = color || this.getDrawColor(); + if (color.a == null) + color.a = 255; + for(var i = 0, len = points.length; i < len; i++) + this.drawDot(points[i], radius, color); + }; + + /** + * draw a segment with a radius and color + * @param {cc.Vec2} from + * @param {cc.Vec2} to + * @param {Number} lineWidth + * @param {cc.Color} color + */ + proto.drawSegment = function (from, to, lineWidth, color) { + lineWidth = lineWidth || this._lineWidth; + color = color || this.getDrawColor(); + if (color.a == null) + color.a = 255; + var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); + element.verts = [from, to]; + element.lineWidth = lineWidth * 2; + element.lineColor = color; + element.isStroke = true; + element.lineCap = "round"; + this._buffer.push(element); + }; + + /** + * draw a polygon with a fill color and line color without copying the vertex list + * @param {Array} verts + * @param {cc.Color} fillColor + * @param {Number} lineWidth + * @param {cc.Color} color + */ + proto.drawPoly_ = function (verts, fillColor, lineWidth, color, notClosePoly) { + lineWidth = (lineWidth == null ) ? this._lineWidth : lineWidth; + color = color || this.getDrawColor(); + if (color.a == null) + color.a = 255; + var element = new cc._DrawNodeElement(cc.DrawNode.TYPE_POLY); + + element.verts = verts; + element.fillColor = fillColor; + element.lineWidth = lineWidth; + element.lineColor = color; + element.isClosePolygon = !notClosePoly; + element.isStroke = true; + element.lineCap = "round"; + if (fillColor) + element.isFill = true; + this._buffer.push(element); + }; + + /** + * draw a polygon with a fill color and line color, copying the vertex list + * @param {Array} verts + * @param {cc.Color} fillColor + * @param {Number} lineWidth + * @param {cc.Color} color + * @param {Boolean} notClosePoly + */ + proto.drawPoly = function (verts, fillColor, lineWidth, color, notClosePoly) { + var vertsCopy = []; + for (var i=0; i < verts.length; i++) { + vertsCopy.push(cc.p(verts[i].x, verts[i].y)); + } + return this.drawPoly_(vertsCopy, fillColor, lineWidth, color, notClosePoly); + }; + + /** + * Clear the geometry in the node's buffer. + */ + proto.clear = function () { + this._buffer.length = 0; + }; + + proto._createRenderCmd = function(){ + return new cc.DrawNode.CanvasRenderCmd(this); + }; } else if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { - - cc.js.mixin(cc.DrawNode.prototype, { - _bufferCapacity:0, - _trianglesArrayBuffer:null, - _trianglesWebBuffer:null, - _trianglesReader:null, + proto._bufferCapacity = 0; - _dirty:false, - _className:"DrawNodeWebGL", + proto._trianglesArrayBuffer = null; + proto._trianglesWebBuffer = null; + proto._trianglesReader = null; - ctor:function () { - _ccsg.Node.prototype.ctor.call(this); - this._buffer = []; - this._blendFunc = new cc.BlendFunc(cc.macro.SRC_ALPHA, cc.macro.ONE_MINUS_SRC_ALPHA); - this._drawColor = cc.color(255,255,255,255); + proto._dirty = false; + proto._className = "DrawNodeWebGL"; - this.init(); - }, + proto.ctor = function () { + _ccsg.Node.prototype.ctor.call(this); + this._buffer = []; + this._blendFunc = new cc.BlendFunc(cc.macro.SRC_ALPHA, cc.macro.ONE_MINUS_SRC_ALPHA); + this._drawColor = cc.color(255,255,255,255); - init:function () { - if (_ccsg.Node.prototype.init.call(this)) { - this.shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_POSITION_LENGTHTEXTURECOLOR); - this._ensureCapacity(64); - this._trianglesWebBuffer = cc._renderContext.createBuffer(); - this._dirty = true; - return true; - } - return false; - }, + this.init(); + }; - drawRect: function (origin, destination, fillColor, lineWidth, lineColor) { - lineWidth = (lineWidth == null) ? this._lineWidth : lineWidth; - lineColor = lineColor || this.getDrawColor(); - if (lineColor.a == null) - lineColor.a = 255; - var vertices = [origin, cc.p(destination.x, origin.y), destination, cc.p(origin.x, destination.y)]; - if(fillColor == null) - this._drawSegments(vertices, lineWidth, lineColor, true); - else - this.drawPoly(vertices, fillColor, lineWidth, lineColor); - }, - - drawCircle: function (center, radius, angle, segments, drawLineToCenter, lineWidth, color) { - lineWidth = lineWidth || this._lineWidth; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - var coef = 2.0 * Math.PI / segments, vertices = [], i, len; - for (i = 0; i <= segments; i++) { - var rads = i * coef; - var j = radius * Math.cos(rads + angle) + center.x; - var k = radius * Math.sin(rads + angle) + center.y; - vertices.push(cc.p(j, k)); - } - if (drawLineToCenter) - vertices.push(cc.p(center.x, center.y)); - - lineWidth *= 0.5; - for (i = 0, len = vertices.length; i < len - 1; i++) - this.drawSegment(vertices[i], vertices[i + 1], lineWidth, color); - }, - - drawQuadBezier: function (origin, control, destination, segments, lineWidth, color) { - lineWidth = lineWidth || this._lineWidth; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - var vertices = [], t = 0.0; - for (var i = 0; i < segments; i++) { - var x = Math.pow(1 - t, 2) * origin.x + 2.0 * (1 - t) * t * control.x + t * t * destination.x; - var y = Math.pow(1 - t, 2) * origin.y + 2.0 * (1 - t) * t * control.y + t * t * destination.y; - vertices.push(cc.p(x, y)); - t += 1.0 / segments; - } - vertices.push(cc.p(destination.x, destination.y)); - this._drawSegments(vertices, lineWidth, color, false); - }, - - drawCubicBezier: function (origin, control1, control2, destination, segments, lineWidth, color) { - lineWidth = lineWidth || this._lineWidth; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - var vertices = [], t = 0; - for (var i = 0; i < segments; i++) { - var x = Math.pow(1 - t, 3) * origin.x + 3.0 * Math.pow(1 - t, 2) * t * control1.x + 3.0 * (1 - t) * t * t * control2.x + t * t * t * destination.x; - var y = Math.pow(1 - t, 3) * origin.y + 3.0 * Math.pow(1 - t, 2) * t * control1.y + 3.0 * (1 - t) * t * t * control2.y + t * t * t * destination.y; - vertices.push(cc.p(x, y)); - t += 1.0 / segments; - } - vertices.push(cc.p(destination.x, destination.y)); - this._drawSegments(vertices, lineWidth, color, false); - }, - - drawCatmullRom: function (points, segments, lineWidth, color) { - this.drawCardinalSpline(points, 0.5, segments, lineWidth, color); - }, - - drawCardinalSpline: function (config, tension, segments, lineWidth, color) { - lineWidth = lineWidth || this._lineWidth; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - var vertices = [], p, lt, deltaT = 1.0 / config.length; - - for (var i = 0; i < segments + 1; i++) { - var dt = i / segments; - - // border - if (dt === 1) { - p = config.length - 1; - lt = 1; - } else { - p = 0 | (dt / deltaT); - lt = (dt - deltaT * p) / deltaT; - } - - // Interpolate - var newPos = cc.cardinalSplineAt( - cc.getControlPointAt(config, p - 1), - cc.getControlPointAt(config, p - 0), - cc.getControlPointAt(config, p + 1), - cc.getControlPointAt(config, p + 2), - tension, lt); - vertices.push(newPos); - } - - lineWidth *= 0.5; - for (var j = 0, len = vertices.length; j < len - 1; j++) - this.drawSegment(vertices[j], vertices[j + 1], lineWidth, color); - }, - - _render:function () { - var gl = cc._renderContext; - - gl.bindBuffer(gl.ARRAY_BUFFER, this._trianglesWebBuffer); - if (this._dirty) { - gl.bufferData(gl.ARRAY_BUFFER, this._trianglesArrayBuffer, gl.STREAM_DRAW); - this._dirty = false; - } - var triangleSize = cc.V2F_C4B_T2F.BYTES_PER_ELEMENT; - - gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION); - gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_COLOR); - gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_TEX_COORDS); - - // vertex - gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, triangleSize, 0); - // color - gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, triangleSize, 8); - // texcood - gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, triangleSize, 12); - - gl.drawArrays(gl.TRIANGLES, 0, this._buffer.length * 3); - cc.incrementGLDraws(1); - //cc.checkGLErrorDebug(); - }, - - _ensureCapacity:function(count){ - var _t = this; - var locBuffer = _t._buffer; - if(locBuffer.length + count > _t._bufferCapacity){ - var TriangleLength = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT; - _t._bufferCapacity += Math.max(_t._bufferCapacity, count); - //re alloc - if((locBuffer == null) || (locBuffer.length === 0)){ - //init - _t._buffer = []; - _t._trianglesArrayBuffer = new ArrayBuffer(TriangleLength * _t._bufferCapacity); - _t._trianglesReader = new Uint8Array(_t._trianglesArrayBuffer); - } else { - var newTriangles = []; - var newArrayBuffer = new ArrayBuffer(TriangleLength * _t._bufferCapacity); - for(var i = 0; i < locBuffer.length;i++){ - newTriangles[i] = new cc.V2F_C4B_T2F_Triangle(locBuffer[i].a,locBuffer[i].b,locBuffer[i].c, - newArrayBuffer, i * TriangleLength); - } - _t._trianglesReader = new Uint8Array(newArrayBuffer); - _t._trianglesArrayBuffer = newArrayBuffer; - _t._buffer = newTriangles; - } - } - }, - - drawDot:function (pos, radius, color) { - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - var c4bColor = {r: 0 | color.r, g: 0 | color.g, b: 0 | color.b, a: 0 | color.a}; - var a = {vertices: {x: pos.x - radius, y: pos.y - radius}, colors: c4bColor, texCoords: {u: -1.0, v: -1.0}}; - var b = {vertices: {x: pos.x - radius, y: pos.y + radius}, colors: c4bColor, texCoords: {u: -1.0, v: 1.0}}; - var c = {vertices: {x: pos.x + radius, y: pos.y + radius}, colors: c4bColor, texCoords: {u: 1.0, v: 1.0}}; - var d = {vertices: {x: pos.x + radius, y: pos.y - radius}, colors: c4bColor, texCoords: {u: 1.0, v: -1.0}}; - - this._ensureCapacity(2*3); - - this._buffer.push(new cc.V2F_C4B_T2F_Triangle(a, b, c, this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT)); - this._buffer.push(new cc.V2F_C4B_T2F_Triangle(a, c, d, this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT)); + proto.init = function () { + if (_ccsg.Node.prototype.init.call(this)) { + this.shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_POSITION_LENGTHTEXTURECOLOR); + this._ensureCapacity(64); + this._trianglesWebBuffer = cc._renderContext.createBuffer(); this._dirty = true; - }, + return true; + } + return false; + }; - drawDots: function(points, radius,color) { - if(!points || points.length === 0) - return; - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - for(var i = 0, len = points.length; i < len; i++) - this.drawDot(points[i], radius, color); - }, + proto.drawRect = function (origin, destination, fillColor, lineWidth, lineColor) { + lineWidth = (lineWidth == null) ? this._lineWidth : lineWidth; + lineColor = lineColor || this.getDrawColor(); + if (lineColor.a == null) + lineColor.a = 255; + var vertices = [origin, cc.p(destination.x, origin.y), destination, cc.p(origin.x, destination.y)]; + if(fillColor == null) + this._drawSegments(vertices, lineWidth, lineColor, true); + else + this.drawPoly(vertices, fillColor, lineWidth, lineColor); + }; - drawSegment:function (from, to, radius, color) { - color = color || this.getDrawColor(); - if (color.a == null) - color.a = 255; - radius = radius || (this._lineWidth * 0.5); - var vertexCount = 6*3; - this._ensureCapacity(vertexCount); + proto.drawCircle = function (center, radius, angle, segments, drawLineToCenter, lineWidth, color) { + lineWidth = lineWidth || this._lineWidth; + color = color || this.getDrawColor(); + if (color.a == null) + color.a = 255; + var coef = 2.0 * Math.PI / segments, vertices = [], i, len; + for (i = 0; i <= segments; i++) { + var rads = i * coef; + var j = radius * Math.cos(rads + angle) + center.x; + var k = radius * Math.sin(rads + angle) + center.y; + vertices.push(cc.p(j, k)); + } + if (drawLineToCenter) + vertices.push(cc.p(center.x, center.y)); - var c4bColor = {r: 0 | color.r, g: 0 | color.g, b: 0 | color.b, a: 0 | color.a}; - var a = cc.v2(from), b = cc.v2(to); - var n = cc.pNormalize(cc.pPerp(cc.pSub(b, a))), t = cc.pPerp(n); - var nw = cc.pMult(n, radius), tw = cc.pMult(t, radius); + lineWidth *= 0.5; + for (i = 0, len = vertices.length; i < len - 1; i++) + this.drawSegment(vertices[i], vertices[i + 1], lineWidth, color); + }; - var v0 = cc.pSub(b, cc.pAdd(nw, tw)); - var v1 = cc.pAdd(b, cc.pSub(nw, tw)); - var v2 = cc.pSub(b, nw); - var v3 = cc.pAdd(b, nw); - var v4 = cc.pSub(a, nw); - var v5 = cc.pAdd(a, nw); - var v6 = cc.pSub(a, cc.pSub(nw, tw)); - var v7 = cc.pAdd(a, cc.pAdd(nw, tw)); + proto.drawQuadBezier = function (origin, control, destination, segments, lineWidth, color) { + lineWidth = lineWidth || this._lineWidth; + color = color || this.getDrawColor(); + if (color.a == null) + color.a = 255; + var vertices = [], t = 0.0; + for (var i = 0; i < segments; i++) { + var x = Math.pow(1 - t, 2) * origin.x + 2.0 * (1 - t) * t * control.x + t * t * destination.x; + var y = Math.pow(1 - t, 2) * origin.y + 2.0 * (1 - t) * t * control.y + t * t * destination.y; + vertices.push(cc.p(x, y)); + t += 1.0 / segments; + } + vertices.push(cc.p(destination.x, destination.y)); + this._drawSegments(vertices, lineWidth, color, false); + }; - var TriangleLength = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, triangleBuffer = this._trianglesArrayBuffer, locBuffer = this._buffer; - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v0, colors: c4bColor, texCoords: __t(cc.pNeg(cc.pAdd(n, t)))}, - {vertices: v1, colors: c4bColor, texCoords: __t(cc.pSub(n, t))}, {vertices: v2, colors: c4bColor, texCoords: __t(cc.pNeg(n))}, - triangleBuffer, locBuffer.length * TriangleLength)); + proto.drawCubicBezier = function (origin, control1, control2, destination, segments, lineWidth, color) { + lineWidth = lineWidth || this._lineWidth; + color = color || this.getDrawColor(); + if (color.a == null) + color.a = 255; + var vertices = [], t = 0; + for (var i = 0; i < segments; i++) { + var x = Math.pow(1 - t, 3) * origin.x + 3.0 * Math.pow(1 - t, 2) * t * control1.x + 3.0 * (1 - t) * t * t * control2.x + t * t * t * destination.x; + var y = Math.pow(1 - t, 3) * origin.y + 3.0 * Math.pow(1 - t, 2) * t * control1.y + 3.0 * (1 - t) * t * t * control2.y + t * t * t * destination.y; + vertices.push(cc.p(x, y)); + t += 1.0 / segments; + } + vertices.push(cc.p(destination.x, destination.y)); + this._drawSegments(vertices, lineWidth, color, false); + }; - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v3, colors: c4bColor, texCoords: __t(n)}, - {vertices: v1, colors: c4bColor, texCoords: __t(cc.pSub(n, t))}, {vertices: v2, colors: c4bColor, texCoords: __t(cc.pNeg(n))}, - triangleBuffer, locBuffer.length * TriangleLength)); + proto.drawCatmullRom = function (points, segments, lineWidth, color) { + this.drawCardinalSpline(points, 0.5, segments, lineWidth, color); + }; - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v3, colors: c4bColor, texCoords: __t(n)}, - {vertices: v4, colors: c4bColor, texCoords: __t(cc.pNeg(n))}, {vertices: v2, colors: c4bColor, texCoords: __t(cc.pNeg(n))}, - triangleBuffer, locBuffer.length * TriangleLength)); + proto.drawCardinalSpline = function (config, tension, segments, lineWidth, color) { + lineWidth = lineWidth || this._lineWidth; + color = color || this.getDrawColor(); + if (color.a == null) + color.a = 255; + var vertices = [], p, lt, deltaT = 1.0 / config.length; - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v3, colors: c4bColor, texCoords: __t(n)}, - {vertices: v4, colors: c4bColor, texCoords: __t(cc.pNeg(n))}, {vertices: v5, colors: c4bColor, texCoords: __t(n)}, - triangleBuffer, locBuffer.length * TriangleLength)); + for (var i = 0; i < segments + 1; i++) { + var dt = i / segments; - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v6, colors: c4bColor, texCoords: __t(cc.pSub(t, n))}, - {vertices: v4, colors: c4bColor, texCoords: __t(cc.pNeg(n))}, {vertices: v5, colors: c4bColor, texCoords: __t(n)}, - triangleBuffer, locBuffer.length * TriangleLength)); - - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v6, colors: c4bColor, texCoords: __t(cc.pSub(t, n))}, - {vertices: v7, colors: c4bColor, texCoords: __t(cc.pAdd(n, t))}, {vertices: v5, colors: c4bColor, texCoords: __t(n)}, - triangleBuffer, locBuffer.length * TriangleLength)); - this._dirty = true; - }, - - drawPoly:function (verts, fillColor, borderWidth, borderColor, notClosePoly) { - if(fillColor == null){ - this._drawSegments(verts, borderWidth, borderColor, !notClosePoly); - return; - } - if (fillColor.a == null) - fillColor.a = 255; - if (borderColor.a == null) - borderColor.a = 255; - borderWidth = (borderWidth == null)? this._lineWidth : borderWidth; - borderWidth *= 0.5; - var c4bFillColor = {r: 0 | fillColor.r, g: 0 | fillColor.g, b: 0 | fillColor.b, a: 0 | fillColor.a}; - var c4bBorderColor = {r: 0 | borderColor.r, g: 0 | borderColor.g, b: 0 | borderColor.b, a: 0 | borderColor.a}; - var extrude = [], i, v0, v1, v2, count = verts.length; - for (i = 0; i < count; i++) { - v0 = cc.v2(verts[(i - 1 + count) % count]); - v1 = cc.v2(verts[i]); - v2 = cc.v2(verts[(i + 1) % count]); - var n1 = cc.pNormalize(cc.pPerp(cc.pSub(v1, v0))); - var n2 = cc.pNormalize(cc.pPerp(cc.pSub(v2, v1))); - var offset = cc.pMult(cc.pAdd(n1, n2), 1.0 / (cc.pDot(n1, n2) + 1.0)); - extrude[i] = {offset: offset, n: n2}; - } - var outline = (borderWidth > 0.0), triangleCount = 3 * count - 2, vertexCount = 3 * triangleCount; - this._ensureCapacity(vertexCount); - - var triangleBytesLen = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, trianglesBuffer = this._trianglesArrayBuffer; - var locBuffer = this._buffer; - var inset = (outline == false ? 0.5 : 0.0); - for (i = 0; i < count - 2; i++) { - v0 = cc.pSub(cc.v2(verts[0]), cc.pMult(extrude[0].offset, inset)); - v1 = cc.pSub(cc.v2(verts[i + 1]), cc.pMult(extrude[i + 1].offset, inset)); - v2 = cc.pSub(cc.v2(verts[i + 2]), cc.pMult(extrude[i + 2].offset, inset)); - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v0, colors: c4bFillColor, texCoords: __t(cc.v2())}, - {vertices: v1, colors: c4bFillColor, texCoords: __t(cc.v2())}, {vertices: v2, colors: c4bFillColor, texCoords: __t(cc.v2())}, - trianglesBuffer, locBuffer.length * triangleBytesLen)); + // border + if (dt === 1) { + p = config.length - 1; + lt = 1; + } else { + p = 0 | (dt / deltaT); + lt = (dt - deltaT * p) / deltaT; } - for (i = 0; i < count; i++) { - var j = (i + 1) % count; - v0 = cc.v2(verts[i]); - v1 = cc.v2(verts[j]); + // Interpolate + var newPos = cc.cardinalSplineAt( + cc.getControlPointAt(config, p - 1), + cc.getControlPointAt(config, p - 0), + cc.getControlPointAt(config, p + 1), + cc.getControlPointAt(config, p + 2), + tension, lt); + vertices.push(newPos); + } - var n0 = extrude[i].n; - var offset0 = extrude[i].offset; - var offset1 = extrude[j].offset; - var inner0 = outline ? cc.pSub(v0, cc.pMult(offset0, borderWidth)) : cc.pSub(v0, cc.pMult(offset0, 0.5)); - var inner1 = outline ? cc.pSub(v1, cc.pMult(offset1, borderWidth)) : cc.pSub(v1, cc.pMult(offset1, 0.5)); - var outer0 = outline ? cc.pAdd(v0, cc.pMult(offset0, borderWidth)) : cc.pAdd(v0, cc.pMult(offset0, 0.5)); - var outer1 = outline ? cc.pAdd(v1, cc.pMult(offset1, borderWidth)) : cc.pAdd(v1, cc.pMult(offset1, 0.5)); + lineWidth *= 0.5; + for (var j = 0, len = vertices.length; j < len - 1; j++) + this.drawSegment(vertices[j], vertices[j + 1], lineWidth, color); + }; - if (outline) { - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: __t(cc.pNeg(n0))}, - {vertices: inner1, colors: c4bBorderColor, texCoords: __t(cc.pNeg(n0))}, {vertices: outer1, colors: c4bBorderColor, texCoords: __t(n0)}, - trianglesBuffer, locBuffer.length * triangleBytesLen)); - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: __t(cc.pNeg(n0))}, - {vertices: outer0, colors: c4bBorderColor, texCoords: __t(n0)}, {vertices: outer1, colors: c4bBorderColor, texCoords: __t(n0)}, - trianglesBuffer, locBuffer.length * triangleBytesLen)); - } else { - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bFillColor, texCoords: __t(cc.v2())}, - {vertices: inner1, colors: c4bFillColor, texCoords: __t(cc.v2())}, {vertices: outer1, colors: c4bFillColor, texCoords: __t(n0)}, - trianglesBuffer, locBuffer.length * triangleBytesLen)); - locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bFillColor, texCoords: __t(cc.v2())}, - {vertices: outer0, colors: c4bFillColor, texCoords: __t(n0)}, {vertices: outer1, colors: c4bFillColor, texCoords: __t(n0)}, - trianglesBuffer, locBuffer.length * triangleBytesLen)); + proto._render = function () { + var gl = cc._renderContext; + + gl.bindBuffer(gl.ARRAY_BUFFER, this._trianglesWebBuffer); + if (this._dirty) { + gl.bufferData(gl.ARRAY_BUFFER, this._trianglesArrayBuffer, gl.STREAM_DRAW); + this._dirty = false; + } + var triangleSize = cc.V2F_C4B_T2F.BYTES_PER_ELEMENT; + + gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION); + gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_COLOR); + gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_TEX_COORDS); + + // vertex + gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, triangleSize, 0); + // color + gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, triangleSize, 8); + // texcood + gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, triangleSize, 12); + + gl.drawArrays(gl.TRIANGLES, 0, this._buffer.length * 3); + cc.incrementGLDraws(1); + //cc.checkGLErrorDebug(); + }; + + proto._ensureCapacity = function(count){ + var _t = this; + var locBuffer = _t._buffer; + if(locBuffer.length + count > _t._bufferCapacity){ + var TriangleLength = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT; + _t._bufferCapacity += Math.max(_t._bufferCapacity, count); + //re alloc + if((locBuffer == null) || (locBuffer.length === 0)){ + //init + _t._buffer = []; + _t._trianglesArrayBuffer = new ArrayBuffer(TriangleLength * _t._bufferCapacity); + _t._trianglesReader = new Uint8Array(_t._trianglesArrayBuffer); + } else { + var newTriangles = []; + var newArrayBuffer = new ArrayBuffer(TriangleLength * _t._bufferCapacity); + for(var i = 0; i < locBuffer.length;i++){ + newTriangles[i] = new cc.V2F_C4B_T2F_Triangle(locBuffer[i].a,locBuffer[i].b,locBuffer[i].c, + newArrayBuffer, i * TriangleLength); } + _t._trianglesReader = new Uint8Array(newArrayBuffer); + _t._trianglesArrayBuffer = newArrayBuffer; + _t._buffer = newTriangles; } - extrude = null; - this._dirty = true; - }, + } + }; - _drawSegments: function(verts, borderWidth, borderColor, closePoly){ - borderWidth = (borderWidth == null) ? this._lineWidth : borderWidth; - borderColor = borderColor || this._drawColor; - if(borderColor.a == null) - borderColor.a = 255; - borderWidth *= 0.5; - if (borderWidth <= 0) - return; + proto.drawDot = function (pos, radius, color) { + color = color || this.getDrawColor(); + if (color.a == null) + color.a = 255; + var c4bColor = {r: 0 | color.r, g: 0 | color.g, b: 0 | color.b, a: 0 | color.a}; + var a = {vertices: {x: pos.x - radius, y: pos.y - radius}, colors: c4bColor, texCoords: {u: -1.0, v: -1.0}}; + var b = {vertices: {x: pos.x - radius, y: pos.y + radius}, colors: c4bColor, texCoords: {u: -1.0, v: 1.0}}; + var c = {vertices: {x: pos.x + radius, y: pos.y + radius}, colors: c4bColor, texCoords: {u: 1.0, v: 1.0}}; + var d = {vertices: {x: pos.x + radius, y: pos.y - radius}, colors: c4bColor, texCoords: {u: 1.0, v: -1.0}}; - var c4bBorderColor = {r: 0 | borderColor.r, g: 0 | borderColor.g, b: 0 | borderColor.b, a: 0 | borderColor.a }; - var extrude = [], i, v0, v1, v2, count = verts.length; - for (i = 0; i < count; i++) { - v0 = cc.v2(verts[(i - 1 + count) % count]); - v1 = cc.v2(verts[i]); - v2 = cc.v2(verts[(i + 1) % count]); - var n1 = cc.pNormalize(cc.pPerp(cc.pSub(v1, v0))); - var n2 = cc.pNormalize(cc.pPerp(cc.pSub(v2, v1))); - var offset = cc.pMult(cc.pAdd(n1, n2), 1.0 / (cc.pDot(n1, n2) + 1.0)); - extrude[i] = {offset: offset, n: n2}; - } + this._ensureCapacity(2*3); - var triangleCount = 3 * count - 2, vertexCount = 3 * triangleCount; - this._ensureCapacity(vertexCount); + this._buffer.push(new cc.V2F_C4B_T2F_Triangle(a, b, c, this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT)); + this._buffer.push(new cc.V2F_C4B_T2F_Triangle(a, c, d, this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT)); + this._dirty = true; + }; - var triangleBytesLen = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, trianglesBuffer = this._trianglesArrayBuffer; - var locBuffer = this._buffer; - var len = closePoly ? count : count - 1; - for (i = 0; i < len; i++) { - var j = (i + 1) % count; - v0 = cc.v2(verts[i]); - v1 = cc.v2(verts[j]); + proto.drawDots = function(points, radius,color) { + if(!points || points.length === 0) + return; + color = color || this.getDrawColor(); + if (color.a == null) + color.a = 255; + for(var i = 0, len = points.length; i < len; i++) + this.drawDot(points[i], radius, color); + }; - var n0 = extrude[i].n; - var offset0 = extrude[i].offset; - var offset1 = extrude[j].offset; - var inner0 = cc.pSub(v0, cc.pMult(offset0, borderWidth)); - var inner1 = cc.pSub(v1, cc.pMult(offset1, borderWidth)); - var outer0 = cc.pAdd(v0, cc.pMult(offset0, borderWidth)); - var outer1 = cc.pAdd(v1, cc.pMult(offset1, borderWidth)); + proto.drawSegment = function (from, to, radius, color) { + color = color || this.getDrawColor(); + if (color.a == null) + color.a = 255; + radius = radius || (this._lineWidth * 0.5); + var vertexCount = 6*3; + this._ensureCapacity(vertexCount); + + var c4bColor = {r: 0 | color.r, g: 0 | color.g, b: 0 | color.b, a: 0 | color.a}; + var a = cc.v2(from), b = cc.v2(to); + var n = cc.pNormalize(cc.pPerp(cc.pSub(b, a))), t = cc.pPerp(n); + var nw = cc.pMult(n, radius), tw = cc.pMult(t, radius); + + var v0 = cc.pSub(b, cc.pAdd(nw, tw)); + var v1 = cc.pAdd(b, cc.pSub(nw, tw)); + var v2 = cc.pSub(b, nw); + var v3 = cc.pAdd(b, nw); + var v4 = cc.pSub(a, nw); + var v5 = cc.pAdd(a, nw); + var v6 = cc.pSub(a, cc.pSub(nw, tw)); + var v7 = cc.pAdd(a, cc.pAdd(nw, tw)); + + var TriangleLength = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, triangleBuffer = this._trianglesArrayBuffer, locBuffer = this._buffer; + locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v0, colors: c4bColor, texCoords: __t(cc.pNeg(cc.pAdd(n, t)))}, + {vertices: v1, colors: c4bColor, texCoords: __t(cc.pSub(n, t))}, {vertices: v2, colors: c4bColor, texCoords: __t(cc.pNeg(n))}, + triangleBuffer, locBuffer.length * TriangleLength)); + + locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v3, colors: c4bColor, texCoords: __t(n)}, + {vertices: v1, colors: c4bColor, texCoords: __t(cc.pSub(n, t))}, {vertices: v2, colors: c4bColor, texCoords: __t(cc.pNeg(n))}, + triangleBuffer, locBuffer.length * TriangleLength)); + + locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v3, colors: c4bColor, texCoords: __t(n)}, + {vertices: v4, colors: c4bColor, texCoords: __t(cc.pNeg(n))}, {vertices: v2, colors: c4bColor, texCoords: __t(cc.pNeg(n))}, + triangleBuffer, locBuffer.length * TriangleLength)); + + locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v3, colors: c4bColor, texCoords: __t(n)}, + {vertices: v4, colors: c4bColor, texCoords: __t(cc.pNeg(n))}, {vertices: v5, colors: c4bColor, texCoords: __t(n)}, + triangleBuffer, locBuffer.length * TriangleLength)); + + locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v6, colors: c4bColor, texCoords: __t(cc.pSub(t, n))}, + {vertices: v4, colors: c4bColor, texCoords: __t(cc.pNeg(n))}, {vertices: v5, colors: c4bColor, texCoords: __t(n)}, + triangleBuffer, locBuffer.length * TriangleLength)); + + locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v6, colors: c4bColor, texCoords: __t(cc.pSub(t, n))}, + {vertices: v7, colors: c4bColor, texCoords: __t(cc.pAdd(n, t))}, {vertices: v5, colors: c4bColor, texCoords: __t(n)}, + triangleBuffer, locBuffer.length * TriangleLength)); + this._dirty = true; + }; + + proto.drawPoly = function (verts, fillColor, borderWidth, borderColor, notClosePoly) { + if(fillColor == null){ + this._drawSegments(verts, borderWidth, borderColor, !notClosePoly); + return; + } + if (fillColor.a == null) + fillColor.a = 255; + if (borderColor.a == null) + borderColor.a = 255; + borderWidth = (borderWidth == null)? this._lineWidth : borderWidth; + borderWidth *= 0.5; + var c4bFillColor = {r: 0 | fillColor.r, g: 0 | fillColor.g, b: 0 | fillColor.b, a: 0 | fillColor.a}; + var c4bBorderColor = {r: 0 | borderColor.r, g: 0 | borderColor.g, b: 0 | borderColor.b, a: 0 | borderColor.a}; + var extrude = [], i, v0, v1, v2, count = verts.length; + for (i = 0; i < count; i++) { + v0 = cc.v2(verts[(i - 1 + count) % count]); + v1 = cc.v2(verts[i]); + v2 = cc.v2(verts[(i + 1) % count]); + var n1 = cc.pNormalize(cc.pPerp(cc.pSub(v1, v0))); + var n2 = cc.pNormalize(cc.pPerp(cc.pSub(v2, v1))); + var offset = cc.pMult(cc.pAdd(n1, n2), 1.0 / (cc.pDot(n1, n2) + 1.0)); + extrude[i] = {offset: offset, n: n2}; + } + var outline = (borderWidth > 0.0), triangleCount = 3 * count - 2, vertexCount = 3 * triangleCount; + this._ensureCapacity(vertexCount); + + var triangleBytesLen = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, trianglesBuffer = this._trianglesArrayBuffer; + var locBuffer = this._buffer; + var inset = (outline == false ? 0.5 : 0.0); + for (i = 0; i < count - 2; i++) { + v0 = cc.pSub(cc.v2(verts[0]), cc.pMult(extrude[0].offset, inset)); + v1 = cc.pSub(cc.v2(verts[i + 1]), cc.pMult(extrude[i + 1].offset, inset)); + v2 = cc.pSub(cc.v2(verts[i + 2]), cc.pMult(extrude[i + 2].offset, inset)); + locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v0, colors: c4bFillColor, texCoords: __t(cc.v2())}, + {vertices: v1, colors: c4bFillColor, texCoords: __t(cc.v2())}, {vertices: v2, colors: c4bFillColor, texCoords: __t(cc.v2())}, + trianglesBuffer, locBuffer.length * triangleBytesLen)); + } + + for (i = 0; i < count; i++) { + var j = (i + 1) % count; + v0 = cc.v2(verts[i]); + v1 = cc.v2(verts[j]); + + var n0 = extrude[i].n; + var offset0 = extrude[i].offset; + var offset1 = extrude[j].offset; + var inner0 = outline ? cc.pSub(v0, cc.pMult(offset0, borderWidth)) : cc.pSub(v0, cc.pMult(offset0, 0.5)); + var inner1 = outline ? cc.pSub(v1, cc.pMult(offset1, borderWidth)) : cc.pSub(v1, cc.pMult(offset1, 0.5)); + var outer0 = outline ? cc.pAdd(v0, cc.pMult(offset0, borderWidth)) : cc.pAdd(v0, cc.pMult(offset0, 0.5)); + var outer1 = outline ? cc.pAdd(v1, cc.pMult(offset1, borderWidth)) : cc.pAdd(v1, cc.pMult(offset1, 0.5)); + + if (outline) { locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: __t(cc.pNeg(n0))}, {vertices: inner1, colors: c4bBorderColor, texCoords: __t(cc.pNeg(n0))}, {vertices: outer1, colors: c4bBorderColor, texCoords: __t(n0)}, trianglesBuffer, locBuffer.length * triangleBytesLen)); locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: __t(cc.pNeg(n0))}, {vertices: outer0, colors: c4bBorderColor, texCoords: __t(n0)}, {vertices: outer1, colors: c4bBorderColor, texCoords: __t(n0)}, trianglesBuffer, locBuffer.length * triangleBytesLen)); + } else { + locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bFillColor, texCoords: __t(cc.v2())}, + {vertices: inner1, colors: c4bFillColor, texCoords: __t(cc.v2())}, {vertices: outer1, colors: c4bFillColor, texCoords: __t(n0)}, + trianglesBuffer, locBuffer.length * triangleBytesLen)); + locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bFillColor, texCoords: __t(cc.v2())}, + {vertices: outer0, colors: c4bFillColor, texCoords: __t(n0)}, {vertices: outer1, colors: c4bFillColor, texCoords: __t(n0)}, + trianglesBuffer, locBuffer.length * triangleBytesLen)); } - extrude = null; - this._dirty = true; - }, - - clear:function () { - this._buffer.length = 0; - this._dirty = true; - }, - - _createRenderCmd: function () { - return new cc.DrawNode.WebGLRenderCmd(this); } - }); + extrude = null; + this._dirty = true; + }; + + proto._drawSegments = function(verts, borderWidth, borderColor, closePoly){ + borderWidth = (borderWidth == null) ? this._lineWidth : borderWidth; + borderColor = borderColor || this._drawColor; + if(borderColor.a == null) + borderColor.a = 255; + borderWidth *= 0.5; + if (borderWidth <= 0) + return; + + var c4bBorderColor = {r: 0 | borderColor.r, g: 0 | borderColor.g, b: 0 | borderColor.b, a: 0 | borderColor.a }; + var extrude = [], i, v0, v1, v2, count = verts.length; + for (i = 0; i < count; i++) { + v0 = cc.v2(verts[(i - 1 + count) % count]); + v1 = cc.v2(verts[i]); + v2 = cc.v2(verts[(i + 1) % count]); + var n1 = cc.pNormalize(cc.pPerp(cc.pSub(v1, v0))); + var n2 = cc.pNormalize(cc.pPerp(cc.pSub(v2, v1))); + var offset = cc.pMult(cc.pAdd(n1, n2), 1.0 / (cc.pDot(n1, n2) + 1.0)); + extrude[i] = {offset: offset, n: n2}; + } + + var triangleCount = 3 * count - 2, vertexCount = 3 * triangleCount; + this._ensureCapacity(vertexCount); + + var triangleBytesLen = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, trianglesBuffer = this._trianglesArrayBuffer; + var locBuffer = this._buffer; + var len = closePoly ? count : count - 1; + for (i = 0; i < len; i++) { + var j = (i + 1) % count; + v0 = cc.v2(verts[i]); + v1 = cc.v2(verts[j]); + + var n0 = extrude[i].n; + var offset0 = extrude[i].offset; + var offset1 = extrude[j].offset; + var inner0 = cc.pSub(v0, cc.pMult(offset0, borderWidth)); + var inner1 = cc.pSub(v1, cc.pMult(offset1, borderWidth)); + var outer0 = cc.pAdd(v0, cc.pMult(offset0, borderWidth)); + var outer1 = cc.pAdd(v1, cc.pMult(offset1, borderWidth)); + locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: __t(cc.pNeg(n0))}, + {vertices: inner1, colors: c4bBorderColor, texCoords: __t(cc.pNeg(n0))}, {vertices: outer1, colors: c4bBorderColor, texCoords: __t(n0)}, + trianglesBuffer, locBuffer.length * triangleBytesLen)); + locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: __t(cc.pNeg(n0))}, + {vertices: outer0, colors: c4bBorderColor, texCoords: __t(n0)}, {vertices: outer1, colors: c4bBorderColor, texCoords: __t(n0)}, + trianglesBuffer, locBuffer.length * triangleBytesLen)); + } + extrude = null; + this._dirty = true; + }; + + proto.clear = function () { + this._buffer.length = 0; + this._dirty = true; + }; + + proto._createRenderCmd = function () { + return new cc.DrawNode.WebGLRenderCmd(this); + }; } }); diff --git a/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js b/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js index d472121583..716c7996a3 100644 --- a/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js +++ b/cocos2d/shape-nodes/CCDrawNodeCanvasRenderCmd.js @@ -30,98 +30,97 @@ cc.DrawNode.CanvasRenderCmd = function(renderableObject){ this._blendFunc = null; }; -cc.DrawNode.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); -cc.DrawNode.CanvasRenderCmd.prototype.constructor = cc.DrawNode.CanvasRenderCmd; -cc.js.mixin( cc.DrawNode.CanvasRenderCmd.prototype, { - rendering: function (ctx, scaleX, scaleY) { - var wrapper = ctx || cc._renderContext, context = wrapper.getContext(), node = this._node; - var alpha = node._displayedOpacity / 255; - if (alpha === 0) - return; +var proto = cc.DrawNode.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); +proto.constructor = cc.DrawNode.CanvasRenderCmd; - wrapper.setTransform(this._worldTransform, scaleX, scaleY); +proto.rendering = function (ctx, scaleX, scaleY) { + var wrapper = ctx || cc._renderContext, context = wrapper.getContext(), node = this._node; + var alpha = node._displayedOpacity / 255; + if (alpha === 0) + return; - //context.save(); - wrapper.setGlobalAlpha(alpha); - if ((this._blendFunc && (this._blendFunc.src === cc.macro.SRC_ALPHA) && (this._blendFunc.dst === cc.macro.ONE))) - wrapper.setCompositeOperation('lighter'); //todo: need refactor - var locBuffer = this._buffer; - for (var i = 0, len = locBuffer.length; i < len; i++) { - var element = locBuffer[i]; - switch (element.type) { - case cc.DrawNode.TYPE_DOT: - this._drawDot(wrapper, element, scaleX, scaleY); - break; - case cc.DrawNode.TYPE_SEGMENT: - this._drawSegment(wrapper, element, scaleX, scaleY); - break; - case cc.DrawNode.TYPE_POLY: - this._drawPoly(wrapper, element, scaleX, scaleY); - break; - } + wrapper.setTransform(this._worldTransform, scaleX, scaleY); + + //context.save(); + wrapper.setGlobalAlpha(alpha); + if ((this._blendFunc && (this._blendFunc.src === cc.macro.SRC_ALPHA) && (this._blendFunc.dst === cc.macro.ONE))) + wrapper.setCompositeOperation('lighter'); //todo: need refactor + var locBuffer = this._buffer; + for (var i = 0, len = locBuffer.length; i < len; i++) { + var element = locBuffer[i]; + switch (element.type) { + case cc.DrawNode.TYPE_DOT: + this._drawDot(wrapper, element, scaleX, scaleY); + break; + case cc.DrawNode.TYPE_SEGMENT: + this._drawSegment(wrapper, element, scaleX, scaleY); + break; + case cc.DrawNode.TYPE_POLY: + this._drawPoly(wrapper, element, scaleX, scaleY); + break; } - //context.restore(); //todo It can be reserve - }, - - _drawDot: function (wrapper, element, scaleX, scaleY) { - var locColor = element.fillColor, locPos = element.verts[0], locRadius = element.lineWidth; - - var ctx = wrapper.getContext(); - wrapper.setFillStyle("rgba(" + (0 | locColor.r) + "," + (0 | locColor.g) + "," + (0 | locColor.b) + "," + locColor.a / 255 + ")"); - - ctx.beginPath(); - ctx.arc(locPos.x, -locPos.y, locRadius, 0, Math.PI * 2, false); - ctx.closePath(); - ctx.fill(); - }, - - _drawSegment: function (wrapper, element, scaleX, scaleY) { - var locColor = element.lineColor; - var locFrom = element.verts[0], locTo = element.verts[1]; - var locLineWidth = element.lineWidth, locLineCap = element.lineCap; - - var ctx = wrapper.getContext(); - wrapper.setStrokeStyle("rgba(" + (0 | locColor.r) + "," + (0 | locColor.g) + "," + (0 | locColor.b) + "," + locColor.a / 255 + ")"); - - ctx.lineWidth = locLineWidth * scaleX; - ctx.beginPath(); - ctx.lineCap = locLineCap; - ctx.moveTo(locFrom.x, -locFrom.y); - ctx.lineTo(locTo.x, -locTo.y); - ctx.stroke(); - }, - - _drawPoly: function (wrapper, element, scaleX, scaleY) { - var locVertices = element.verts, locLineCap = element.lineCap; - if (locVertices == null) - return; - - var locFillColor = element.fillColor, locLineWidth = element.lineWidth; - var locLineColor = element.lineColor, locIsClosePolygon = element.isClosePolygon; - var locIsFill = element.isFill, locIsStroke = element.isStroke; - - var ctx = wrapper.getContext(); - var firstPoint = locVertices[0]; - ctx.lineCap = locLineCap; - if (locFillColor) - wrapper.setFillStyle("rgba(" + (0 | locFillColor.r) + "," + (0 | locFillColor.g) + "," - + (0 | locFillColor.b) + "," + locFillColor.a / 255 + ")"); - if (locLineWidth) - ctx.lineWidth = locLineWidth * scaleX; - if (locLineColor) - wrapper.setStrokeStyle("rgba(" + (0 | locLineColor.r) + "," + (0 | locLineColor.g) + "," - + (0 | locLineColor.b) + "," + locLineColor.a / 255 + ")"); - - ctx.beginPath(); - ctx.moveTo(firstPoint.x, -firstPoint.y); - for (var i = 1, len = locVertices.length; i < len; i++) - ctx.lineTo(locVertices[i].x, -locVertices[i].y); - - if (locIsClosePolygon) - ctx.closePath(); - if (locIsFill) - ctx.fill(); - if (locIsStroke) - ctx.stroke(); } -}); \ No newline at end of file + //context.restore(); //todo It can be reserve +}; + +proto._drawDot = function (wrapper, element, scaleX, scaleY) { + var locColor = element.fillColor, locPos = element.verts[0], locRadius = element.lineWidth; + + var ctx = wrapper.getContext(); + wrapper.setFillStyle("rgba(" + (0 | locColor.r) + "," + (0 | locColor.g) + "," + (0 | locColor.b) + "," + locColor.a / 255 + ")"); + + ctx.beginPath(); + ctx.arc(locPos.x, -locPos.y, locRadius, 0, Math.PI * 2, false); + ctx.closePath(); + ctx.fill(); +}; + +proto._drawSegment = function (wrapper, element, scaleX, scaleY) { + var locColor = element.lineColor; + var locFrom = element.verts[0], locTo = element.verts[1]; + var locLineWidth = element.lineWidth, locLineCap = element.lineCap; + + var ctx = wrapper.getContext(); + wrapper.setStrokeStyle("rgba(" + (0 | locColor.r) + "," + (0 | locColor.g) + "," + (0 | locColor.b) + "," + locColor.a / 255 + ")"); + + ctx.lineWidth = locLineWidth * scaleX; + ctx.beginPath(); + ctx.lineCap = locLineCap; + ctx.moveTo(locFrom.x, -locFrom.y); + ctx.lineTo(locTo.x, -locTo.y); + ctx.stroke(); +}; + +proto._drawPoly = function (wrapper, element, scaleX, scaleY) { + var locVertices = element.verts, locLineCap = element.lineCap; + if (locVertices == null) + return; + + var locFillColor = element.fillColor, locLineWidth = element.lineWidth; + var locLineColor = element.lineColor, locIsClosePolygon = element.isClosePolygon; + var locIsFill = element.isFill, locIsStroke = element.isStroke; + + var ctx = wrapper.getContext(); + var firstPoint = locVertices[0]; + ctx.lineCap = locLineCap; + if (locFillColor) + wrapper.setFillStyle("rgba(" + (0 | locFillColor.r) + "," + (0 | locFillColor.g) + "," + + (0 | locFillColor.b) + "," + locFillColor.a / 255 + ")"); + if (locLineWidth) + ctx.lineWidth = locLineWidth * scaleX; + if (locLineColor) + wrapper.setStrokeStyle("rgba(" + (0 | locLineColor.r) + "," + (0 | locLineColor.g) + "," + + (0 | locLineColor.b) + "," + locLineColor.a / 255 + ")"); + + ctx.beginPath(); + ctx.moveTo(firstPoint.x, -firstPoint.y); + for (var i = 1, len = locVertices.length; i < len; i++) + ctx.lineTo(locVertices[i].x, -locVertices[i].y); + + if (locIsClosePolygon) + ctx.closePath(); + if (locIsFill) + ctx.fill(); + if (locIsStroke) + ctx.stroke(); +}; \ No newline at end of file diff --git a/gulp/browserify_prelude.js b/gulp/browserify_prelude.js index ae38433678..67266611b7 100644 --- a/gulp/browserify_prelude.js +++ b/gulp/browserify_prelude.js @@ -34,7 +34,7 @@ throw err; } var exports = {}; - module = cache[name] = {exports}; + module = cache[name] = {exports: exports}; moduleData[0](function(x){ return newRequire(moduleData[1][x] || x); },module,exports); From 96de0a1dd985425c8c0bacf4f30e1e76acc8bae3 Mon Sep 17 00:00:00 2001 From: Jare Guo Date: Thu, 4 May 2017 20:27:16 +0800 Subject: [PATCH 5/5] optimize engine startup time by wrapping IIFE --- gulp/tasks/engine.js | 24 ++++++++++++++++++++++-- gulp/tasks/utils.js | 9 ++++++++- package.json | 7 ++++--- 3 files changed, 34 insertions(+), 6 deletions(-) diff --git a/gulp/tasks/engine.js b/gulp/tasks/engine.js index 862b0bced3..cc9faf5abf 100644 --- a/gulp/tasks/engine.js +++ b/gulp/tasks/engine.js @@ -37,6 +37,7 @@ const Sourcemaps = require('gulp-sourcemaps'); const EventStream = require('event-stream'); const Chalk = require('chalk'); const HandleErrors = require('../util/handleErrors'); +const Optimizejs = require('gulp-optimize-js'); exports.buildCocosJs = function (sourceFile, outputFile, excludes, callback) { var outDir = Path.dirname(outputFile); @@ -59,6 +60,9 @@ exports.buildCocosJs = function (sourceFile, outputFile, excludes, callback) { bundler = bundler.pipe(Buffer()); bundler = bundler.pipe(Sourcemaps.init({loadMaps: true})); bundler = bundler.pipe(Minifier(uglifyOption, UglifyHarmony)); + bundler = bundler.pipe(Optimizejs({ + sourceMap: false + })); bundler = bundler.pipe(Sourcemaps.write('./', { sourceRoot: './', includeContent: true, @@ -99,9 +103,15 @@ exports.buildCocosJsMin = function (sourceFile, outputFile, excludes, callback, bundler = bundler.bundle(); bundler = bundler.pipe(Source(outFile)); bundler = bundler.pipe(Buffer()); - if (createMap !== false) + if (createMap) { + console.error('Can not use sourcemap with optimize-js'); bundler = bundler.pipe(Sourcemaps.init({loadMaps: true})); + } bundler = bundler.pipe(Minifier(uglifyOption, UglifyHarmony)); + bundler = bundler.pipe(Optimizejs({ + sourceMap: false + })); + if (Size) { bundler = bundler.pipe(rawSize); bundler = bundler.pipe(zippedSize); @@ -113,12 +123,13 @@ exports.buildCocosJsMin = function (sourceFile, outputFile, excludes, callback, this.emit('end'); })); } - if (createMap !== false) + if (createMap) { bundler = bundler.pipe(Sourcemaps.write('./', { sourceRoot: './', includeContent: true, addComment: true })); + } bundler = bundler.pipe(Gulp.dest(outDir)); return bundler.on('end', callback); }; @@ -140,6 +151,9 @@ exports.buildPreview = function (sourceFile, outputFile, callback) { CC_TEST: false, CC_JSB: false }), UglifyHarmony)) + .pipe(Optimizejs({ + sourceMap: false + })) .pipe(Sourcemaps.write('./', { sourceRoot: '../', includeContent: false, @@ -168,6 +182,9 @@ exports.buildJsb = function (sourceFile, outputFile, jsbSkipModules, callback) { CC_TEST: false, CC_JSB: true }), UglifyHarmony)) + .pipe(Optimizejs({ + sourceMap: false + })) .pipe(Gulp.dest(outDir)) .on('end', callback); }; @@ -191,6 +208,9 @@ exports.buildJsbMin = function (sourceFile, outputFile, jsbSkipModules, callback CC_TEST: false, CC_JSB: true }), UglifyHarmony)) + .pipe(Optimizejs({ + sourceMap: false + })) .pipe(Gulp.dest(outDir)) .on('end', callback); }; diff --git a/gulp/tasks/utils.js b/gulp/tasks/utils.js index ba7779a58c..a174778208 100644 --- a/gulp/tasks/utils.js +++ b/gulp/tasks/utils.js @@ -70,7 +70,14 @@ function allowReturnOutsideFunctionInBrowserifyTransform () { if (typeof parse === 'function') { if (acorn.parse.name !== 'monkeyPatchedParse') { acorn.parse = function monkeyPatchedParse(input, options) { - options.allowReturnOutsideFunction = true; + if (options) { + options.allowReturnOutsideFunction = true; + } + else { + options = { + allowReturnOutsideFunction: true + }; + } return parse(input, options); }; } diff --git a/package.json b/package.json index 3cbfec0a53..7a2409026a 100644 --- a/package.json +++ b/package.json @@ -26,27 +26,28 @@ "event-stream": "3.3.2", "fire-fs": "0.2.1", "gulp": "^3.9.0", + "gulp-babel": "6.1.2", "gulp-cached": "1.1.0", "gulp-concat": "2.6.0", - "gulp-babel": "6.1.2", "gulp-fb": "0.5.1", "gulp-header": "1.2.2", "gulp-jshint": "1.11.2", "gulp-mirror": "0.4.0", + "gulp-optimize-js": "^1.1.0", "gulp-plumber": "0.6.6", "gulp-rename": "1.2.2", "gulp-shell": "0.4.1", "gulp-size": "2.1.0", "gulp-sourcemaps": "1.5.2", "gulp-uglify": "1.5.3", - "uglify-js-harmony": "2.7.5", "gulp-util": "3.0.6", "jshint-stylish": "2.1.0", "multipipe": "0.3.0", "require-dir": "0.3.0", + "uglify-js-harmony": "2.7.5", "vinyl": "1.1.0", "vinyl-buffer": "1.0.0", "vinyl-source-stream": "1.0.0", "watchify": "^3.7.0" } -} \ No newline at end of file +}