diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000000..3f467559fa --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,14 @@ +> Makes sure these boxes are checked before submitting your PR - thank you! +> +- [ ] Check that your javascript is following our [style guide](https://github.com/cocos-creator/fireball/blob/dev/.github/CONTRIBUTING.md) and end files with a newline +- [ ] Document new code with comments in source code based on [API Docs](https://github.com/cocos-creator/fireball#api-docs) +- [ ] If your pull request has gone "stale", you should **rebase** your work on top of the latest version of the upstream branch. +- [ ] If your commit history is full of small, unimportant commits (such as "fix pep8" or "update tests"), **squash** your commits down to a few, or one, discreet changesets before submitting a pull request. + +Re: cocos-creator/fireball# + +Changes proposed in this pull request: +- +- + +@cocos-creator/engine-admins \ No newline at end of file diff --git a/CCBoot.js b/CCBoot.js index 2a3b4c4a82..771f82833a 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -192,8 +192,8 @@ cc.formatStr = function(){ }; require('../cocos2d/core/utils'); -require('../cocos2d/core/platform/CCLoader'); require('../cocos2d/core/platform/CCSys'); +require('../cocos2d/core/load-pipeline/CCLoader'); require('../cocos2d/core/CCGame'); @@ -276,7 +276,7 @@ function _load(config) { } else { // Load cocos modules var ccModulesPath = cc.path.join(engineDir, "moduleConfig.json"); - loader.loadJson(ccModulesPath, function (err, modulesJson) { + loader.load(ccModulesPath, function (err, modulesJson) { if (err) throw new Error(err); var modules = config["modules"] || []; var moduleMap = modulesJson["module"]; @@ -287,8 +287,8 @@ function _load(config) { var arr = _getJsListOfModule(moduleMap, modules[i], engineDir); if (arr) jsList = jsList.concat(arr); } - cc.loader.loadJsWithImg(jsList, function (err) { - if (err) throw err; + loader.load(jsList, function (err) { + if (err) throw new Error(JSON.stringify(err)); _afterEngineLoaded(config); }); }); diff --git a/CCDebugger.js b/CCDebugger.js index e59b724c39..a027b183af 100644 --- a/CCDebugger.js +++ b/CCDebugger.js @@ -326,11 +326,13 @@ cc._formatString = function (arg) { return arg; }; +var Enum = require('./cocos2d/core/value-types/CCEnum'); + /** * Enum for debug modes. * @enum DebugMode */ -cc.DebugMode = cc.Enum({ +cc.DebugMode = Enum({ /** * @property {number} NONE - The debug mode none. */ @@ -371,6 +373,9 @@ cc.DebugMode = cc.Enum({ * @param {DebugMode} mode */ cc._initDebugSetting = function (mode) { + // reset + cc.log = cc.warn = cc.error = cc._throw = cc.assert = function () {}; + if(mode === cc.DebugMode.NONE) return; @@ -414,12 +419,15 @@ cc._initDebugSetting = function (mode) { * @param {any} obj - A JavaScript string containing zero or more substitution strings. * @param {any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. */ - if (console.error.bind) { + if (CC_EDITOR) { + cc.error = Editor.error; + } + else if (console.error.bind) { // use bind to avoid pollute call stacks cc.error = console.error.bind(console); } else { - cc.error = function(){ + cc.error = function () { return console.error.apply(console, arguments); }; } @@ -430,7 +438,7 @@ cc._initDebugSetting = function (mode) { throw new Error(msg); } }; - if(mode !== cc.DebugMode.ERROR) + if (mode !== cc.DebugMode.ERROR) { /** * Outputs a warning message to the Cocos Creator Console (editor) or Web Console (runtime). * - In Cocos Creator, warning is yellow. @@ -439,37 +447,45 @@ cc._initDebugSetting = function (mode) { * @param {any} obj - A JavaScript string containing zero or more substitution strings. * @param {any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. */ - if (console.warn.bind) { + if (CC_EDITOR) { + cc.warn = Editor.warn; + } + else if (console.warn.bind) { // use bind to avoid pollute call stacks cc.warn = console.warn.bind(console); } else { - cc.warn = function() { + cc.warn = function () { return console.warn.apply(console, arguments); }; } - if(mode === cc.DebugMode.INFO) { - /** - * Outputs a message to the Cocos Creator Console (editor) or Web Console (runtime). - * @method log - * @param {any} obj - A JavaScript string containing zero or more substitution strings. - * @param {any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. - */ - cc.log = function () { - return console.log.apply(console, arguments); - }; - /** - * Outputs an informational message to the Cocos Creator Console (editor) or Web Console (runtime). - * - In Cocos Creator, info is blue. - * - In Firefox and Chrome, a small "i" icon is displayed next to these items in the Web Console's log. - * @method info - * @param {any} obj - A JavaScript string containing zero or more substitution strings. - * @param {any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. - */ - cc.info = function () { - (console.info || console.log).apply(console, arguments); - }; - } + } + if (CC_EDITOR) { + cc.log = Editor.log; + cc.info = Editor.info; + } + else if (mode === cc.DebugMode.INFO) { + /** + * Outputs a message to the Cocos Creator Console (editor) or Web Console (runtime). + * @method log + * @param {any} obj - A JavaScript string containing zero or more substitution strings. + * @param {any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. + */ + cc.log = function () { + return console.log.apply(console, arguments); + }; + /** + * Outputs an informational message to the Cocos Creator Console (editor) or Web Console (runtime). + * - In Cocos Creator, info is blue. + * - In Firefox and Chrome, a small "i" icon is displayed next to these items in the Web Console's log. + * @method info + * @param {any} obj - A JavaScript string containing zero or more substitution strings. + * @param {any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output. + */ + cc.info = function () { + (console.info || console.log).apply(console, arguments); + }; + } } cc._throw = function (error) { cc.error(error.stack || error); diff --git a/cocos2d/ToMerge/wrappers/progress-timer.js b/cocos2d/ToMerge/wrappers/progress-timer.js deleted file mode 100644 index 328c05c2b2..0000000000 --- a/cocos2d/ToMerge/wrappers/progress-timer.js +++ /dev/null @@ -1,167 +0,0 @@ -var NodeWrapper = require('./node'); - -var ProgressTimerWrapper = cc.Class({ - name: 'cc.ProgressTimerWrapper', - extends: NodeWrapper, - - ctor: function () { - this._midPoint = [0.5, 0.5]; - this._barChangeRate = [1, 1]; - }, - - properties: { - - _type: { - default: cc.ProgressTimer.Type.RADIAL, - type: cc.ProgressTimer.Type - }, - - type: { - get: function () { - return this.targetN.getType(); - }, - set: function (value) { - if (!isNaN(value)) { - this.targetN.setType(value); - } - else { - cc.error('The new type must not be NaN'); - } - }, - type: cc.ProgressTimer.Type - }, - - _percentage: { - default: 50, - }, - - percentage: { - get: function() { - return this.targetN.getPercentage(); - }, - set: function (value) { - if (!isNaN(value)) { - this.targetN.setPercentage(value); - } - else { - cc.error('The new percentage must not be NaN'); - } - }, - }, - - _midPoint: { - default: [] - }, - - midPoint: { - get: function () { - var pt = this.targetN.getMidpoint(); - return new cc.Vec2(pt.x, pt.y); - }, - set: function (value) { - if ( value instanceof cc.Vec2 ) { - this.targetN.setMidpoint(cc.p(value.x, value.y)); - } - else { - cc.error('The new midPoint must be cc.Vec2'); - } - } - }, - - _barChangeRate: { - default: [] - }, - - barChangeRate: { - get: function () { - var pt = this.targetN.getBarChangeRate(); - return new cc.Vec2(pt.x, pt.y); - }, - set: function (value) { - if ( value instanceof cc.Vec2 ) { - this.targetN.setBarChangeRate(cc.p(value.x, value.y)); - } - else { - cc.error('The new barChangeRate must be cc.Vec2'); - } - } - }, - - _reverseDirection : { - default: false, - }, - - reverseDirection: { - get: function () { - return this.targetN.isReverseDirection(); - }, - set: function (value) { - if (typeof value === 'boolean') { - this.targetN.setReverseProgress(value); - } - else { - cc.error('The new reverseDirection must be Boolean'); - } - } - }, - - _texture: { - default: '', - url: cc.Texture2D - }, - - texture: { - get: function () { - var tex = this.targetN.getSprite().texture; - return (tex && tex.url) || ''; - }, - set: function (value) { - this.targetN.getSprite().texture = value; - }, - url: cc.Texture2D - } - }, - - onBeforeSerialize: function () { - NodeWrapper.prototype.onBeforeSerialize.call(this); - this._type = this.type; - this._percentage = this.percentage; - this._midPoint = [this.midPoint.x, this.midPoint.y]; - this._barChangeRate = [this.barChangeRate.x, this.barChangeRate.y]; - this._reverseDirection = this.reverseDirection; - this._texture = this.texture; - }, - - createNode: function (node) { - node = node || new cc.ProgressTimer(new _ccsg.Sprite()); - - var sp = node.getSprite(); - if (this._texture) { - sp.texture = this._texture; - - if (cc.sys.isNative) { - // jsb Texture will not save url, so we save manually. - sp.texture.url = this._texture; - } - } - - node.setType(this._type); - node.setPercentage(this._percentage); - - if (this._midPoint) { - node.setMidpoint(cc.p(this._midPoint[0], this._midPoint[1])); - } - - if (this._barChangeRate) { - node.setBarChangeRate(cc.p(this._barChangeRate[0], this._barChangeRate[1])); - } - - node.setReverseProgress(this._reverseDirection); - - NodeWrapper.prototype.createNode.call(this, node); - - return node; - } -}); - -cc.ProgressTimerWrapper = module.exports = ProgressTimerWrapper; diff --git a/cocos2d/ToMerge/wrappers/tiled-map.js b/cocos2d/ToMerge/wrappers/tiled-map.js index 6a1fcf7d1f..2d17af8e23 100644 --- a/cocos2d/ToMerge/wrappers/tiled-map.js +++ b/cocos2d/ToMerge/wrappers/tiled-map.js @@ -41,7 +41,7 @@ var TiledMapWrapper = cc.Class({ childrenN: { get: function () { var children = this.targetN.children.filter( function (child) { - return !(child instanceof cc.TMXLayer); + return !(child instanceof _ccsg.TMXLayer); }); return children; }, diff --git a/cocos2d/ToMerge/wrappers/ui/text-field.js b/cocos2d/ToMerge/wrappers/ui/text-field.js deleted file mode 100644 index f237873536..0000000000 --- a/cocos2d/ToMerge/wrappers/ui/text-field.js +++ /dev/null @@ -1,214 +0,0 @@ -var Utils = require('../utils'); - -var WidgetWrapper = require('./widget'); - -var TextFieldWrapper = cc.Class({ - name: 'cc.TextFieldWrapper', - extends: WidgetWrapper, - - properties: { - text: { - get: function () { - return this.targetN.string; - }, - set: function (value) { - if (typeof value === 'string') { - this.targetN.string = value; - - this.setDirtyFlag(); - } - else { - cc.error('The new text must be String'); - } - } - }, - - placeHolder: { - get: function () { - return this.targetN.placeHolder; - }, - set: function (value) { - if (typeof value === 'string') { - this.targetN.placeHolder = value; - - this.setDirtyFlag(); - } - else { - cc.error('The new placeHolder must be String'); - } - } - }, - - fontSize: { - get: function () { - return this.targetN.fontSize; - }, - set: function (value) { - if ( !isNaN(value) ) { - this.targetN.fontSize = value; - - this.setDirtyFlag(); - } - else { - cc.error('The new fontSize must not be NaN'); - } - } - }, - - font: { - default: null, - type: cc.TTFFont, - - notify: function () { - if ( !this.targetN ) return; - - var value = this.font; - if (!value || value instanceof cc.TTFFont) { - Utils.setFontToNode(value, this.targetN); - - this.setDirtyFlag(); - } - else { - cc.error('The new font must be cc.TTFFont'); - } - } - }, - - fontFamily: { - get: function () { - return this.targetN.fontName; - }, - set: function (value) { - if (typeof value === 'string') { - this.targetN.fontName = value; - - this.setDirtyFlag(); - } - else { - cc.error('The new fontFamily must be String'); - } - } - }, - - maxLengthEnabled: { - get: function () { - return this.targetN.maxLengthEnabled; - }, - set: function (value) { - if (typeof value === 'boolean') { - this.targetN.maxLengthEnabled = value; - - this.setDirtyFlag(); - } - else { - cc.error('The new maxLengthEnabled must be boolean'); - } - } - }, - - maxLength: { - get: function () { - return this.targetN.maxLength; - }, - set: function (value) { - if (typeof value === 'number') { - this.targetN.maxLength = value; - - this.setDirtyFlag(); - } - else { - cc.error('The new maxLength must be String'); - } - } - }, - - passwordEnabled: { - get: function () { - return this.targetN.passwordEnabled; - }, - set: function (value) { - if (typeof value === 'boolean') { - var targetN = this.targetN; - targetN.passwordEnabled = value; - - this.text = this.text; - } - else { - cc.error('The new passwordEnabled must be boolean'); - } - } - }, - - _text: { - default: '' - }, - - _placeHolder: { - default: 'Input Something' - }, - - _fontSize: { - default: 16 - }, - - _fontFamily: { - default: null - }, - - _maxLengthEnabled: { - default: false - }, - - _maxLength: { - default: 0 - }, - - _passwordEnabled: { - default: false - } - }, - - onSizeChanged: function () { - WidgetWrapper.prototype.onSizeChanged.call(this); - this.setDirtyFlag(); - }, - - setDirtyFlag: function () { - cc.renderer.childrenOrderDirty = true; - }, - - onBeforeSerialize: function () { - WidgetWrapper.prototype.onBeforeSerialize.call(this); - - this._text = this.text; - this._placeHolder = this.placeHolder; - this._fontSize = this.fontSize; - this._fontFamily = this.fontFamily; - this._maxLengthEnabled = this.maxLengthEnabled; - this._passwordEnabled = this.passwordEnabled; - - if (this.maxLengthEnabled) this._maxLength = this.maxLength; - }, - - createNode: function (node) { - node = node || new ccui.TextField(); - node.ignoreContentAdaptWithSize(false); - - WidgetWrapper.prototype.createNode.call(this, node); - - node.passwordEnabled = this._passwordEnabled; - node.string = this._text; - node.placeHolder = this._placeHolder; - node.fontSize = this._fontSize; - node.fontFamily = this._fontFamily; - node.maxLengthEnabled = this._maxLengthEnabled; - - if (this._maxLengthEnabled) node.maxLength = this._maxLength; - - Utils.setFontToNode(this.font, node); - - return node; - } -}); - -cc.TextFieldWrapper = module.exports = TextFieldWrapper; diff --git a/cocos2d/ToMerge/wrappers/utils.js b/cocos2d/ToMerge/wrappers/utils.js index 8854e26ae5..b4246a7dd5 100644 --- a/cocos2d/ToMerge/wrappers/utils.js +++ b/cocos2d/ToMerge/wrappers/utils.js @@ -3,7 +3,7 @@ module.exports = { setFontToNode: function(fontAsset, node) { if (fontAsset) { var config = {type:'font', name: fontAsset.fontFamily, srcs:[fontAsset.url]}; - cc.loader.load(config, function (err, results) { + cc.loader.load(config, function (err, result) { if (err) throw err; node.fontName = config.name; diff --git a/cocos2d/actions/CCAction.js b/cocos2d/actions/CCAction.js index cbdbf98422..f7326163b7 100644 --- a/cocos2d/actions/CCAction.js +++ b/cocos2d/actions/CCAction.js @@ -518,9 +518,6 @@ cc.Follow = cc.Action.extend({ tempPosX = this._halfScreenSize.x - tempPosX; tempPosY = this._halfScreenSize.y - tempPosY; - //TODO Temporary treatment - The dirtyFlag symbol error - this.target._renderCmd._dirtyFlag = 0; - if (this._boundarySet) { // whole map fits inside a single screen, no need to modify the position - unless map boundaries are increased if (this._boundaryFullyCovered) @@ -533,7 +530,7 @@ cc.Follow = cc.Action.extend({ }, isDone:function () { - return ( !this._followedNode.running ); + return ( !this._followedNode.isRunning() ); }, stop:function () { diff --git a/cocos2d/actions/CCActionInstant.js b/cocos2d/actions/CCActionInstant.js index 48fe4485da..d083417421 100644 --- a/cocos2d/actions/CCActionInstant.js +++ b/cocos2d/actions/CCActionInstant.js @@ -251,7 +251,7 @@ cc.FlipX = cc.ActionInstant.extend({ }, update:function (dt) { - this.target.flippedX = this._flippedX; + this.target.scaleX = Math.abs(this.target.scaleX) * (this._flippedX ? 1 : -1); }, reverse:function () { @@ -309,7 +309,7 @@ cc.FlipY = cc.ActionInstant.extend({ }, update:function (dt) { - this.target.flippedY = this._flippedY; + this.target.scaleY = Math.abs(this.target.scaleY) * (this._flippedX ? 1 : -1); }, reverse:function () { diff --git a/cocos2d/actions/CCActionInterval.js b/cocos2d/actions/CCActionInterval.js index 11582362e1..6d47721ef6 100644 --- a/cocos2d/actions/CCActionInterval.js +++ b/cocos2d/actions/CCActionInterval.js @@ -1998,17 +1998,17 @@ cc.Blink = cc.ActionInterval.extend({ if (this.target && !this.isDone()) { var slice = 1.0 / this._times; var m = dt % slice; - this.target.visible = (m > (slice / 2)); + this.target.opacity = (m > (slice / 2)) ? 255 : 0; } }, startWithTarget:function (target) { cc.ActionInterval.prototype.startWithTarget.call(this, target); - this._originalState = target.visible; + this._originalState = target.opacity; }, stop:function () { - this.target.visible = this._originalState; + this.target.opacity = this._originalState; cc.ActionInterval.prototype.stop.call(this); }, @@ -2496,8 +2496,9 @@ cc.reverseTime = function (action) { }; cc.ReverseTime.create = cc.reverseTime; - -/* Animates a sprite given the name of an Animation +/** + * This API is deprecated, will be replaced by new API from {{#crossLink "Animation"}}cc.Animation{{/crossLink}} + * Animates a sprite given the name of an Animation * @class Animate * @extends ActionInterval * @param {SpriteFrameAnimation} animation diff --git a/cocos2d/animation/animation-animator.js b/cocos2d/animation/animation-animator.js index a23a35caa6..75dbb07a28 100644 --- a/cocos2d/animation/animation-animator.js +++ b/cocos2d/animation/animation-animator.js @@ -95,11 +95,9 @@ p.onResume = function () { } }; -if (CC_DEV) { - p.reloadClip = function (state) { - initClipData(this.target, state); - }; -} +p._reloadClip = function (state) { + initClipData(this.target, state); +}; // 这个方法应该是 SampledAnimCurve 才能用 function createBatchedProperty (propPath, firstDotIndex, mainValue, animValue) { diff --git a/cocos2d/animation/animation-clip.js b/cocos2d/animation/animation-clip.js index a900b2e3a0..fb54f0a619 100644 --- a/cocos2d/animation/animation-clip.js +++ b/cocos2d/animation/animation-clip.js @@ -17,6 +17,7 @@ var AnimationClip = cc.Class({ /** * Duration of this animation + * @property duration * @type {Number} */ duration: { @@ -25,6 +26,7 @@ var AnimationClip = cc.Class({ /** * FrameRate of this animation + * @property sample * @type {Number} */ sample: { @@ -33,6 +35,7 @@ var AnimationClip = cc.Class({ /** * Speed of this animation + * @property speed * @type {Number} */ speed: { @@ -41,7 +44,8 @@ var AnimationClip = cc.Class({ /** * WrapMode of this animation - * @type {cc.WrapMode} + * @property wrapMode + * @type {WrapMode} */ wrapMode: { default: cc.WrapMode.Normal diff --git a/cocos2d/animation/animation-curves.js b/cocos2d/animation/animation-curves.js index f5fb912c04..a33a5f86ed 100644 --- a/cocos2d/animation/animation-curves.js +++ b/cocos2d/animation/animation-curves.js @@ -205,6 +205,7 @@ DynamicAnimCurve.Bezier = function (controlPoints) { * 所以 SampledAnimCurve 中查找 frame index 的速度会非常快 * * @class SampledAnimCurve + * @private * @constructor * @extends DynamicAnimCurve */ diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index 0872824337..a9d3489391 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -24,147 +24,44 @@ THE SOFTWARE. ****************************************************************************/ -/** - * Audio support in the browser - * - * MULTI_CHANNEL : Multiple audio while playing - If it doesn't, you can only play background music - * WEB_AUDIO : Support for WebAudio - Support W3C WebAudio standards, all of the audio can be played - * AUTOPLAY : Supports auto-play audio - if Don‘t support it, On a touch detecting background music canvas, and then replay - * REPLAY_AFTER_TOUCH : The first music will fail, must be replay after touchstart - * USE_EMPTIED_EVENT : Whether to use the emptied event to replace load callback - * DELAY_CREATE_CTX : delay created the context object - only webAudio - * NEED_MANUAL_LOOP : WebAudio loop attribute failure, need to manually perform loop - * - * May be modifications for a few browser version - */ -(function(){ - - var DEBUG = false; - - var sys = cc.sys; - var version = sys.browserVersion; - - // check if browser supports Web Audio - // check Web Audio's context - var supportWebAudio = !!(window.AudioContext || window.webkitAudioContext || window.mozAudioContext); - - var supportTable = { - "common" : {MULTI_CHANNEL: true , WEB_AUDIO: supportWebAudio , AUTOPLAY: true } - }; - supportTable[sys.BROWSER_TYPE_IE] = {MULTI_CHANNEL: true , WEB_AUDIO: supportWebAudio , AUTOPLAY: true, USE_EMPTIED_EVENT: true}; - // ANDROID // - supportTable[sys.BROWSER_TYPE_ANDROID] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false}; - supportTable[sys.BROWSER_TYPE_CHROME] = {MULTI_CHANNEL: true , WEB_AUDIO: true , AUTOPLAY: false}; - supportTable[sys.BROWSER_TYPE_FIREFOX] = {MULTI_CHANNEL: true , WEB_AUDIO: true , AUTOPLAY: true , DELAY_CREATE_CTX: true}; - supportTable[sys.BROWSER_TYPE_UC] = {MULTI_CHANNEL: true , WEB_AUDIO: false, AUTOPLAY: false}; - supportTable[sys.BROWSER_TYPE_QQ] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: true }; - supportTable[sys.BROWSER_TYPE_OUPENG] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true }; - supportTable[sys.BROWSER_TYPE_WECHAT] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true }; - supportTable[sys.BROWSER_TYPE_360] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: true }; - supportTable[sys.BROWSER_TYPE_MIUI] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: true }; - supportTable[sys.BROWSER_TYPE_LIEBAO] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true }; - supportTable[sys.BROWSER_TYPE_SOUGOU] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true }; - //"Baidu" browser can automatically play - //But because it may be play failed, so need to replay and auto - supportTable[sys.BROWSER_TYPE_BAIDU] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true }; - supportTable[sys.BROWSER_TYPE_BAIDU_APP]= {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true }; - - // APPLE // - supportTable[sys.BROWSER_TYPE_SAFARI] = {MULTI_CHANNEL: true , WEB_AUDIO: true , AUTOPLAY: false, webAudioCallback: function(realUrl){ - document.createElement("audio").src = realUrl; - }}; - - if(cc.sys.isMobile){ - if(cc.sys.os !== cc.sys.OS_IOS) - window.__audioSupport = supportTable[sys.browserType] || supportTable["common"]; - else - window.__audioSupport = supportTable[sys.BROWSER_TYPE_SAFARI]; - }else{ - switch(sys.browserType){ - case sys.BROWSER_TYPE_IE: - window.__audioSupport = supportTable[sys.BROWSER_TYPE_IE]; - break; - case sys.BROWSER_TYPE_FIREFOX: - window.__audioSupport = supportTable[sys.BROWSER_TYPE_FIREFOX]; - break; - default: - window.__audioSupport = supportTable["common"]; - } - } - - /////////////////////////// - // Browser compatibility// - /////////////////////////// - if(version){ - switch(sys.browserType){ - case sys.BROWSER_TYPE_CHROME: - version = parseInt(version); - if(version < 30){ - window.__audioSupport = {MULTI_CHANNEL: false , WEB_AUDIO: true , AUTOPLAY: false}; - }else if(version === 42){ - window.__audioSupport.NEED_MANUAL_LOOP = true; - } - break; - case sys.BROWSER_TYPE_MIUI: - if(cc.sys.isMobile){ - version = version.match(/\d+/g); - if(version[0] < 2 || (version[0] === 2 && version[1] === 0 && version[2] <= 1)){ - window.__audioSupport.AUTOPLAY = false; - } - } - break; - } - } - - if(DEBUG){ - setTimeout(function(){ - cc.log("browse type: " + sys.browserType); - cc.log("browse version: " + version); - cc.log("MULTI_CHANNEL: " + window.__audioSupport.MULTI_CHANNEL); - cc.log("WEB_AUDIO: " + window.__audioSupport.WEB_AUDIO); - cc.log("AUTOPLAY: " + window.__audioSupport.AUTOPLAY); - }, 0); - } - -})(); +var JS = require('../core/platform/js'); /** * Encapsulate DOM and webAudio */ -cc.Audio = cc._Class.extend({ +cc.Audio = function (context, volume, url) { //TODO Maybe loader shift in will be better - volume: 1, - loop: false, - src: null, - _touch: false, + this.volume = 1; + this.loop = false; + this._touch = false; - _playing: false, - _AUDIO_TYPE: "AUDIO", - _pause: false, + this._playing = false; + this._AUDIO_TYPE = "AUDIO"; + this._pause = false; //Web Audio - _buffer: null, - _currentSource: null, - _startTime: null, - _currentTime: null, - _context: null, - _volume: null, + this._buffer = null; + this._currentSource = null; + this._startTime = null; + this._currentTime = null; + this._context = null; + this._volume = null; - _ignoreEnded: false, - _manualLoop: false, + this._ignoreEnded = false; + this._manualLoop = false; //DOM Audio - _element: null, + this._element = null; - ctor: function(context, volume, url){ - context && (this._context = context); - volume && (this._volume = volume); - if(context && volume){ - this._AUDIO_TYPE = "WEBAUDIO"; - } - this.src = url; - }, + context && (this._context = context); + volume && (this._volume = volume); + if (context && volume) { + this._AUDIO_TYPE = "WEBAUDIO"; + } + this.src = url; +}; +JS.mixin(cc.Audio.prototype, { _setBufferCallback: null, setBuffer: function(buffer){ if(!buffer) return; @@ -440,190 +337,6 @@ cc.Audio = cc._Class.extend({ SWB = polyfill.MULTI_CHANNEL, SWC = polyfill.AUTOPLAY; - var support = []; - - (function(){ - var audio = document.createElement("audio"); - if(audio.canPlayType) { - var ogg = audio.canPlayType('audio/ogg; codecs="vorbis"'); - if (ogg && ogg !== "") support.push(".ogg"); - var mp3 = audio.canPlayType("audio/mpeg"); - if (mp3 && mp3 !== "") support.push(".mp3"); - var wav = audio.canPlayType('audio/wav; codecs="1"'); - if (wav && wav !== "") support.push(".wav"); - var mp4 = audio.canPlayType("audio/mp4"); - if (mp4 && mp4 !== "") support.push(".mp4"); - var m4a = audio.canPlayType("audio/x-m4a"); - if (m4a && m4a !== "") support.push(".m4a"); - } - })(); - try{ - if(SWA){ - var context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); - if(polyfill.DELAY_CREATE_CTX) - setTimeout(function(){ context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); }, 0); - } - }catch(error){ - SWA = false; - cc.log("browser don't support web audio"); - } - - var loader = { - - cache: {}, - - load: function(realUrl, url, res, cb){ - - if(support.length === 0) - return cb("can not support audio!"); - - var i; - - if(cc.loader.audioPath) - realUrl = cc.path.join(cc.loader.audioPath, realUrl); - - var extname = cc.path.extname(realUrl); - - var typeList = [extname]; - for(i=0; i this._maxAudioInstance){ cc.log("Error: %s greater than %d", url, this._maxAudioInstance); }else{ - var audio = loader.cache[url]; + audio = cc.loader.getRes(url); if(!audio){ cc.loader.load(url); - audio = loader.cache[url]; + var item = cc.loader.getItems().map[url]; + audio = item ? item.content : null; + if (!audio) { + return; + } } audio = audio.cloneNode(); audio.setVolume(this._effectVolume); @@ -983,7 +706,6 @@ cc.Audio = cc._Class.extend({ var pool = this._audioPool[url]; if(pool) pool.length = 0; delete this._audioPool[url]; - delete loader.cache[url]; }, /** @@ -1051,4 +773,4 @@ cc.Audio = cc._Class.extend({ }, 150); } -})(window.__audioSupport); +})(cc.sys.__audioSupport); diff --git a/cocos2d/core/CCActionManager.js b/cocos2d/core/CCActionManager.js index 62f1cee527..8a456d84a0 100644 --- a/cocos2d/core/CCActionManager.js +++ b/cocos2d/core/CCActionManager.js @@ -27,6 +27,7 @@ /** * @class HashElement * @extends cc._Class + * @private * @example * var element = new cc.HashElement(); */ @@ -91,8 +92,8 @@ cc.ActionManager = cc._Class.extend(/** @lends cc.ActionManager# */{ * If the target is not present, a new instance of this target will be created either paused or not, and the action will be added to the newly created target. * When the target is paused, the queued actions won't be 'ticked'. * @method addAction - * @param {cc.Action} action - * @param {cc.Node} target + * @param {Action} action + * @param {Node} target * @param {Boolean} paused */ addAction:function (action, target, paused) { @@ -155,7 +156,7 @@ cc.ActionManager = cc._Class.extend(/** @lends cc.ActionManager# */{ }, /** Removes an action given an action reference. * @method removeAction - * @param {cc.Action} action + * @param {Action} action */ removeAction:function (action) { // explicit null handling @@ -205,7 +206,7 @@ cc.ActionManager = cc._Class.extend(/** @lends cc.ActionManager# */{ * @method getActionByTag * @param {Number} tag * @param {object} target - * @return {cc.Action|Null} return the Action with the given tag on success + * @return {Action|Null} return the Action with the given tag on success */ getActionByTag:function (tag, target) { if(tag === cc.ACTION_TAG_INVALID) diff --git a/cocos2d/core/CCDirector.js b/cocos2d/core/CCDirector.js index a651f4b824..53ef5a2a47 100644 --- a/cocos2d/core/CCDirector.js +++ b/cocos2d/core/CCDirector.js @@ -617,43 +617,6 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ } }, - // load raw assets - _loadRawAssets: function (assetObjects, done) { - var urls = assetObjects.map(function (asset) { - return asset.url; - }); - - //var info = 'preload ' + urls; - //console.time(info); - - // currently cocos jsb 3.3 not support preload too much assets - // so we divide assets to 30 a group - var index = 0; - var count = 30; - var total = urls.length; - - function preload () { - if (index + count > total) { - // the last time - count = total - index; - } - - var assets = urls.slice(index, count); - - index += count; - - if (index < total) { - cc.loader.load(assets, preload); - } - else { - //console.timeEnd(info); - done(); - } - } - - preload(); - }, - /** * Loads the scene by its uuid. * @method _loadSceneByUuid @@ -664,7 +627,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ */ _loadSceneByUuid: function (uuid, onLaunched, onUnloaded) { //cc.AssetLibrary.unloadAsset(uuid); // force reload - var handle = cc.AssetLibrary.loadAsset(uuid, function (error, sceneAsset) { + cc.AssetLibrary.loadAsset(uuid, function (error, sceneAsset) { var self = cc.director; var scene; if (error) { @@ -684,10 +647,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ scene = sceneAsset; } if (scene instanceof cc.Scene) { - self._loadRawAssets(handle.assetsNeedPostLoad, - function () { - self.runScene(scene, onUnloaded); - }); + self.runScene(scene, onUnloaded); } else { error = 'The asset ' + uuid + ' is not a scene'; @@ -699,7 +659,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ if (onLaunched) { onLaunched(error, scene); } - }, { recordAssets: true }); + }); }, /** @@ -889,8 +849,10 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ }, /** - * Returns current running Scene. Director can only run one Scene at the time. + * Returns current render Scene, normally you will never need to use this API. + * In most case, you probably want to use `getScene` instead. * @method getRunningScene + * @private * @return {Scene} */ getRunningScene: function () { @@ -898,7 +860,10 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ }, /** - * Returns current running Scene. Director can only run one Scene at the time. + * Returns current logic Scene. + * @example + * // This will help you to get the Canvas node in scene + * cc.director.getScene().getChildByName('Canvas'); * @method getScene * @return {Scene} */ @@ -1101,7 +1066,7 @@ cc.Director.EVENT_BEFORE_SCENE_LAUNCH = "director_before_scene_launch"; /** * @event EVENT_AFTER_SCENE_LAUNCH - * @param {cc.Scene} newScene + * @param {Scene} newScene */ cc.Director.EVENT_AFTER_SCENE_LAUNCH = "director_after_scene_launch"; diff --git a/cocos2d/core/CCDrawingPrimitivesCanvas.js b/cocos2d/core/CCDrawingPrimitivesCanvas.js index 1943681b84..0435ea71c0 100644 --- a/cocos2d/core/CCDrawingPrimitivesCanvas.js +++ b/cocos2d/core/CCDrawingPrimitivesCanvas.js @@ -31,7 +31,7 @@ cc.PI2 = Math.PI * 2; /** * Canvas of DrawingPrimitive implement version use for canvasMode - * @class + * @class DrawingPrimitiveCanvas * @extends cc._Class * @param {CanvasRenderingContext2D} renderContext */ diff --git a/cocos2d/core/CCDrawingPrimitivesWebGL.js b/cocos2d/core/CCDrawingPrimitivesWebGL.js index 660015354e..4c3a75c0ee 100644 --- a/cocos2d/core/CCDrawingPrimitivesWebGL.js +++ b/cocos2d/core/CCDrawingPrimitivesWebGL.js @@ -450,7 +450,7 @@ cc.DrawingPrimitiveWebGL = cc._Class.extend(/** @lends cc.DrawingPrimitiveWebGL# * @param {Number} pointSize */ setPointSize:function (pointSize) { - this._pointSize = pointSize * cc.contentScaleFactor(); + this._pointSize = pointSize; }, /** diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index d2155d5063..d133ad5e43 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -2,7 +2,7 @@ var EventTarget = require('./event/event-target'); /** * An object to boot the game. - * @class game + * @class Game */ var game = /** @lends cc.game# */{ @@ -78,7 +78,31 @@ var game = /** @lends cc.game# */{ canvas: null, /** - * Config of game + * The current game configuration, including: + * 1. debugMode + * "debugMode" possible values : + * 0 - No message will be printed. + * 1 - cc.error, cc.assert, cc.warn, cc.log will print in console. + * 2 - cc.error, cc.assert, cc.warn will print in console. + * 3 - cc.error, cc.assert will print in console. + * 4 - cc.error, cc.assert, cc.warn, cc.log will print on canvas, available only on web. + * 5 - cc.error, cc.assert, cc.warn will print on canvas, available only on web. + * 6 - cc.error, cc.assert will print on canvas, available only on web. + * 2. showFPS + * Left bottom corner fps information will show when "showFPS" equals true, otherwise it will be hide. + * 3. frameRate + * "frameRate" set the wanted frame rate for your game, but the real fps depends on your game implementation and the running environment. + * 4. id + * "gameCanvas" sets the id of your canvas element on the web page, it's useful only on web. + * 5. renderMode + * "renderMode" sets the renderer type, only useful on web : + * 0 - Automatically chosen by engine + * 1 - Forced to use canvas renderer + * 2 - Forced to use WebGL renderer, but this will be ignored on mobile browsers + * 6. scenes + * "scenes" include available scenes in the current bundle. + * + * Please DO NOT modify this object directly, it won't have any effect. * @property config * @type {Object} */ @@ -201,18 +225,17 @@ var game = /** @lends cc.game# */{ this._initRenderer(config[CONFIG_KEY.width], config[CONFIG_KEY.height]); - /** - * @type {cc.EGLView} - * @name cc.view - * @memberof cc - * cc.view is the shared view object. - */ - cc.view = cc.EGLView._getInstance(); - /** * @module cc */ + /** + * cc.view is the shared view object. + * @property view + * @type View + */ + cc.view = cc.EGLView._getInstance(); + /** * @property director * @type Director @@ -223,7 +246,7 @@ var game = /** @lends cc.game# */{ /** * cc.winSize is the alias object for the size of the current game window. * @property winSize - * @type cc.Size + * @type Size */ cc.winSize = cc.director.getWinSize(); @@ -236,9 +259,9 @@ var game = /** @lends cc.game# */{ // Load game scripts var jsList = config[CONFIG_KEY.jsList]; - if (jsList) { - cc.loader.loadJsWithImg(jsList, function (err) { - if (err) throw new Error(err); + if (jsList && jsList.length > 0) { + cc.loader.load(jsList, function (err) { + if (err) throw new Error(JSON.stringify(err)); self._prepared = true; if (cb) cb(); }); @@ -257,7 +280,8 @@ var game = /** @lends cc.game# */{ }, /** - * @class game + * cc.game is the singleton object for game related functions. + * @class Game */ /** @@ -616,4 +640,12 @@ var game = /** @lends cc.game# */{ EventTarget.call(game); cc.js.addon(game, EventTarget.prototype); +/** + * @module cc + */ + +/** + * @property game + * @type Game + */ cc.game = module.exports = game; diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 41c75373e9..d3cddbdce5 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -34,7 +34,7 @@ var DontDestroy = Flags.DontDestroy; /** * The event type supported by Node - * @class Node.EventType + * @enum Node.EventType * @static * @namespace Node */ @@ -43,7 +43,7 @@ var EventType = cc.Enum({ * The event type for touch start event, you can use its value directly: 'touchstart' * @property TOUCH_START * @type {String} - * @readonly + * @static */ TOUCH_START: 'touchstart', /** @@ -51,21 +51,21 @@ var EventType = cc.Enum({ * @property TOUCH_MOVE * @type {String} * @value 1 - * @readonly + * @static */ TOUCH_MOVE: 'touchmove', /** * The event type for touch end event, you can use its value directly: 'touchend' * @property TOUCH_END * @type {String} - * @readonly + * @static */ TOUCH_END: 'touchend', /** * The event type for touch end event, you can use its value directly: 'touchcancel' * @property TOUCH_CANCEL * @type {String} - * @readonly + * @static */ TOUCH_CANCEL: 'touchcancel', @@ -73,42 +73,42 @@ var EventType = cc.Enum({ * The event type for mouse down events, you can use its value directly: 'mousedown' * @property MOUSE_DOWN * @type {String} - * @readonly + * @static */ MOUSE_DOWN: 'mousedown', /** * The event type for mouse move events, you can use its value directly: 'mousemove' * @property MOUSE_MOVE * @type {String} - * @readonly + * @static */ MOUSE_MOVE: 'mousemove', /** * The event type for mouse enter target events, you can use its value directly: 'mouseenter' * @property MOUSE_ENTER * @type {String} - * @readonly + * @static */ MOUSE_ENTER: 'mouseenter', /** * The event type for mouse leave target events, you can use its value directly: 'mouseleave' * @property MOUSE_LEAVE * @type {String} - * @readonly + * @static */ MOUSE_LEAVE: 'mouseleave', /** * The event type for mouse up events, you can use its value directly: 'mouseup' * @property MOUSE_UP * @type {String} - * @readonly + * @static */ MOUSE_UP: 'mouseup', /** * The event type for mouse wheel events, you can use its value directly: 'mousewheel' * @property MOUSE_WHEEL * @type {String} - * @readonly + * @static */ MOUSE_WHEEL: 'mousewheel', }); @@ -128,6 +128,8 @@ var _mouseEvents = [ EventType.MOUSE_WHEEL, ]; +var currentHovered = null; + var _touchStartHandler = function (touch, event) { var pos = touch.getLocation(); var node = this.owner; @@ -179,6 +181,13 @@ var _mouseMoveHandler = function (event) { if (node._hitTest(pos, this)) { event.stopPropagation(); if (!this._previousIn) { + // Fix issue when hover node switched, previous hovered node won't get MOUSE_LEAVE notification + if (currentHovered) { + event.type = EventType.MOUSE_LEAVE; + currentHovered.owner.dispatchEvent(event); + currentHovered._previousIn = false; + } + currentHovered = this; event.type = EventType.MOUSE_ENTER; node.dispatchEvent(event); this._previousIn = true; @@ -190,6 +199,7 @@ var _mouseMoveHandler = function (event) { event.type = EventType.MOUSE_LEAVE; node.dispatchEvent(event); this._previousIn = false; + currentHovered = null; } }; var _mouseUpHandler = function (event) { @@ -233,7 +243,8 @@ var _searchMaskParent = function (node) { /** - * Class of all entities in Fireball scenes. + * Class of all entities in Cocos Creator scenes. + * For events supported by Node, please refer to {{#crossLink "Node.EventType"}}{{/crossLink}} * * @class Node * @extends _BaseNode @@ -551,11 +562,11 @@ var Node = cc.Class({ } } - // check conflict - - if (CC_EDITOR && !_Scene.DetectConflict.beforeAddComponent(this, constructor)) { - return null; - } + //// check conflict + // + //if (CC_EDITOR && !_Scene.DetectConflict.beforeAddComponent(this, constructor)) { + // return null; + //} // @@ -635,8 +646,8 @@ var Node = cc.Class({ /** * @method _getDependComponent - * @param {cc.Component} depended - * @return {cc.Component} + * @param {Component} depended + * @return {Component} * @private */ _getDependComponent: CC_EDITOR && function (depended) { @@ -697,9 +708,11 @@ var Node = cc.Class({ var originCount = this._components.length; for (var c = 0; c < originCount; ++c) { var component = this._components[c]; - if (! (component instanceof cc.Component) && CC_EDITOR) { - cc.error('Sorry, the component of entity "%s" which with an index of %s is corrupted! It has been removed.\nSee DevTools for details.', this.name, c); - console.log('Corrupted component value:', component); + if ( !(component instanceof cc.Component) ) { + if (CC_EDITOR) { + cc.error('Sorry, the component of "%s" which with an index of %s is corrupted! It has been removed.', this.name, c); + console.log('Corrupted component value:', component); + } if (component) { this._removeComponent(component); } @@ -765,17 +778,20 @@ var Node = cc.Class({ if (myPrefabInfo) { if (newPrefabRoot) { // change prefab - Editor.PrefabUtils.linkPrefab(newPrefabRoot._prefab.asset, newPrefabRoot, this); + _Scene.PrefabUtils.linkPrefab(newPrefabRoot._prefab.asset, newPrefabRoot, this); } else if (myPrefabInfo.root !== this) { // detach from prefab - Editor.PrefabUtils.unlinkPrefab(this); + _Scene.PrefabUtils.unlinkPrefab(this); } } else if (newPrefabRoot) { // attach to prefab - Editor.PrefabUtils.linkPrefab(newPrefabRoot._prefab.asset, newPrefabRoot, this); + _Scene.PrefabUtils.linkPrefab(newPrefabRoot._prefab.asset, newPrefabRoot, this); } + + // conflict detection + _Scene.DetectConflict.afterAddChild(this); } }, @@ -812,7 +828,7 @@ var Node = cc.Class({ // update components if also in scene graph for (var c = 0; c < this._components.length; ++c) { var comp = this._components[c]; - if (comp instanceof cc._ComponentInSG && comp.isValid && comp._sgNode) { + if (comp instanceof cc._SGComponent && comp.isValid && comp._sgNode) { comp._sgNode.setColor(this._color); if ( !this._cascadeOpacityEnabled ) { comp._sgNode.setOpacity(this._opacity); @@ -826,7 +842,7 @@ var Node = cc.Class({ var opacity = this._cascadeOpacityEnabled ? 255 : this._opacity; for (var c = 0; c < this._components.length; ++c) { var comp = this._components[c]; - if (comp instanceof cc._ComponentInSG && comp.isValid && comp._sgNode) { + if (comp instanceof cc._SGComponent && comp.isValid && comp._sgNode) { comp._sgNode.setOpacity(opacity); } } @@ -836,9 +852,9 @@ var Node = cc.Class({ // update components if also in scene graph for (var c = 0; c < this._components.length; ++c) { var comp = this._components[c]; - if (comp instanceof cc._ComponentInSG && comp.isValid && comp._sgNode) { + if (comp instanceof cc._SGComponent && comp.isValid && comp._sgNode) { comp._sgNode.setAnchorPoint(this._anchorPoint); - comp._sgNode.ignoreAnchorPointForPosition(this._ignoreAnchorPointForPosition); + comp._sgNode.ignoreAnchorPointForPosition(this.__ignoreAnchor); } } }, @@ -846,7 +862,7 @@ var Node = cc.Class({ _onOpacityModifyRGBChanged: function () { for (var c = 0; c < this._components.length; ++c) { var comp = this._components[c]; - if (comp instanceof cc._ComponentInSG && comp.isValid && comp._sgNode) { + if (comp instanceof cc._SGComponent && comp.isValid && comp._sgNode) { comp._sgNode.setOpacityModifyRGB(this._opacityModifyRGB); } } @@ -966,7 +982,7 @@ var Node = cc.Class({ apy = this._anchorPoint.y, w = this.width, h = this.height; - var rect = cc.rect(-apx * w, -apy * h, w, h); + var rect = cc.rect(0, 0, w, h); var trans = this.getNodeToWorldTransform(); cc._rectApplyAffineTransformIn(rect, trans); var left = point.x - rect.x, @@ -1018,8 +1034,8 @@ var Node = cc.Class({ * The node becomes the action's target. Refer to cc.Action's getTarget() * Calling runAction while the node is not active won't have any effect * @method runAction - * @param {cc.Action} action - * @return {cc.Action} An Action pointer + * @param {Action} action + * @return {Action} An Action pointer */ runAction: function (action) { if (!this.active) @@ -1028,6 +1044,7 @@ var Node = cc.Class({ if (cc.sys.isNative) { this._retainAction(action); + this._sgNode._owner = this; } cc.director.getActionManager().addAction(action, this, false); return action; @@ -1044,7 +1061,7 @@ var Node = cc.Class({ /** * Stops and removes an action from the running action list. * @method stopAction - * @param {cc.Action} action An action object to be removed. + * @param {Action} action An action object to be removed. */ stopAction: function (action) { cc.director.getActionManager().removeAction(action); @@ -1068,7 +1085,7 @@ var Node = cc.Class({ * @method getActionByTag * @see cc.Action#getTag and cc.Action#setTag * @param {Number} tag - * @return {cc.Action} The action object with the given tag. + * @return {Action} The action object with the given tag. */ getActionByTag: function (tag) { if (tag === cc.ACTION_TAG_INVALID) { @@ -1135,45 +1152,66 @@ if (cc.sys.isNative) { /** * @event position-changed - * @param {cc.Event} event - * @param {cc.Vec2} event.detail - old position + * @param {Event} event + * @param {Vec2} event.detail - old position */ /** * @event rotation-changed - * @param {cc.Event} event + * @param {Event} event * @param {Number} event.detail - old rotation x */ /** * @event scale-changed - * @param {cc.Event} event - * @param {cc.Vec2} event.detail - old scale + * @param {Event} event + * @param {Vec2} event.detail - old scale */ /** * @event size-changed - * @param {cc.Event} event - * @param {cc.Size} event.detail - old size + * @param {Event} event + * @param {Size} event.detail - old size */ /** * @event anchor-changed - * @param {cc.Event} event - * @param {cc.Vec2} event.detail - old anchor + * @param {Event} event + * @param {Vec2} event.detail - old anchor */ /** * @event color-changed - * @param {cc.Event} event - * @param {cc.Color} event.detail - old color + * @param {Event} event + * @param {Color} event.detail - old color */ /** * @event opacity-changed - * @param {cc.Event} event + * @param {Event} event * @param {Number} event.detail - old opacity */ +/** + * @event child-added + * @param {Event} event + * @param {Node} event.detail - child + */ +/** + * @event child-removed + * @param {Event} event + * @param {Node} event.detail - child + */ +/** + * @event child-reorder + * @param {Event} event + */ /** * Note: This event is only emitted from the top most node whose active value did changed, * not including its child nodes. * @event active-in-hierarchy-changed - * @param {cc.Event} event + * @param {Event} event */ + +/** + * + * @event touchstart + * + */ + Node.EventType = EventType; cc.Node = module.exports = Node; diff --git a/cocos2d/core/CCScheduler.js b/cocos2d/core/CCScheduler.js index af1dab217f..34a880ec24 100644 --- a/cocos2d/core/CCScheduler.js +++ b/cocos2d/core/CCScheduler.js @@ -39,10 +39,10 @@ cc.PRIORITY_NON_SYSTEM = cc.PRIORITY_SYSTEM + 1; /** * A list double-linked list used for "updates with priority" * @class ListEntry - * @param {cc.ListEntry} prev - * @param {cc.ListEntry} next + * @param {ListEntry} prev + * @param {ListEntry} next * @param {function} callback - * @param {cc._Class} target not retained (retained by hashUpdateEntry) + * @param {Object} target not retained (retained by hashUpdateEntry) * @param {Number} priority * @param {Boolean} paused * @param {Boolean} markedForDeletion selector will no longer be called and entry will be removed at end of the next tick @@ -64,8 +64,8 @@ cc.ListEntry.prototype.trigger = function (dt) { * A update entry list * @class HashUpdateEntry * @param {Array} list Which list does it belong to ? - * @param {cc.ListEntry} entry entry in the list - * @param {cc._Class} target hash key (retained) + * @param {ListEntry} entry entry in the list + * @param {Object} target hash key (retained) * @param {function} callback * @param {Array} hh */ @@ -82,9 +82,9 @@ cc.HashUpdateEntry = function (list, entry, target, callback, hh) { * Hash Element used for "selectors with interval" * @class HashTimerEntry * @param {Array} timers - * @param {cc._Class} target hash key (retained) + * @param {Object} target hash key (retained) * @param {Number} timerIndex - * @param {cc.Timer} currentTimer + * @param {Timer} currentTimer * @param {Boolean} currentTimerSalvaged * @param {Boolean} paused * @param {Array} hh @@ -524,7 +524,7 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{ *

* @method scheduleCallbackForTarget * @deprecated since v3.4 please use .schedule - * @param {_Class} target + * @param {Object} target * @param {function} callback_fn * @param {Number} interval * @param {Number} repeat @@ -541,7 +541,7 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{ * The schedule * @method schedule * @param {Function} callback - * @param {_Class} target + * @param {Object} target * @param {Number} interval * @param {Number} repeat * @param {Number} delay @@ -918,7 +918,7 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{ * If the target is not present, nothing happens. *

* @method pauseTarget - * @param {_Class} target + * @param {Object} target */ pauseTarget:function (target) { @@ -944,7 +944,7 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{ * The 'target' will be unpaused, so all schedule selectors/update will be 'ticked' again.
* If the target is not present, nothing happens. * @method resumeTarget - * @param {_Class} target + * @param {Object} target */ resumeTarget:function (target) { @@ -970,7 +970,7 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{ /** * Returns whether or not the target is paused * @method isTargetPaused - * @param {_Class} target + * @param {Object} target * @return {Boolean} */ isTargetPaused:function (target) { @@ -998,7 +998,7 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{ *

* @method scheduleUpdateForTarget * @deprecated since v3.4 please use .scheduleUpdate - * @param {_Class} target + * @param {Object} target * @param {Number} priority * @param {Boolean} paused * @example {@link utils/api/engine/docs/cocos2d/core/CCScheduler/scheduleUpdateForTarget.js} @@ -1015,7 +1015,7 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{ *

* @method unscheduleCallbackForTarget * @deprecated since v3.4 please use .unschedule - * @param {_Class} target + * @param {Object} target * @param {Function} callback - callback[Function] or key[String] * @example {@link utils/api/engine/docs/cocos2d/core/CCScheduler/unscheduleCallbackForTarget.js} */ @@ -1027,7 +1027,7 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{ /** * Unschedules the update callback function for a given target * @method unscheduleUpdateForTarget - * @param {_Class} target + * @param {Object} target * @deprecated since v3.4 please use .unschedule * @example {@link utils/api/engine/docs/cocos2d/core/CCScheduler/unscheduleUpdateForTarget.js} */ @@ -1040,7 +1040,7 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{ * Unschedules all function callbacks for a given target. This also includes the "update" callback function. * @method unscheduleAllCallbacksForTarget * @deprecated since v3.4 please use .unscheduleAll - * @param {_Class} target + * @param {Object} target */ unscheduleAllCallbacksForTarget: function(target){ //cc.log("unscheduleAllCallbacksForTarget is deprecated. Please use unscheduleAll."); diff --git a/cocos2d/core/assets/CCPrefab.js b/cocos2d/core/assets/CCPrefab.js index 8d0c733e6a..93af2d07f5 100644 --- a/cocos2d/core/assets/CCPrefab.js +++ b/cocos2d/core/assets/CCPrefab.js @@ -33,7 +33,7 @@ var Prefab = cc.Class({ var node = cc.instantiate(this.data); if (CC_DEV) { - Editor.PrefabUtils.linkPrefab(this, node); + _Scene.PrefabUtils.linkPrefab(this, node); } return node; diff --git a/cocos2d/core/assets/CCTiledMapAsset.js b/cocos2d/core/assets/CCTiledMapAsset.js deleted file mode 100644 index 652d139261..0000000000 --- a/cocos2d/core/assets/CCTiledMapAsset.js +++ /dev/null @@ -1,45 +0,0 @@ -/** - * Class for tiled map asset handling. - * @class TiledMapAsset - * @extends RawAsset - * @constructor - */ -var TiledMapAsset = cc.Class({ - name: 'cc.TiledMapAsset', - extends: cc.RawAsset, - - statics: { - createNodeByInfo: function (info, callback) { - if (CC_EDITOR) { - - var Url = require('fire-url'); - - cc.TiledMapWrapper.preloadTmx( info.url , function (err, textures) { - if (err) { - callback(err); - return; - } - - var node; - try { - node = new cc.TMXTiledMap(info.url); - node._file = info.url; - } - catch(e) { - return callback(e); - } - - var wrapper = cc.getWrapper(node); - wrapper.name = Url.basenameNoExt(info.url); - wrapper._textures = textures; - - return callback(null, node); - }.bind(this) ); - - } - } - } -}); - -cc.TiledMapAsset = TiledMapAsset; -module.exports = TiledMapAsset; diff --git a/cocos2d/core/assets/index.js b/cocos2d/core/assets/index.js index eabb918735..7ef40af9a5 100644 --- a/cocos2d/core/assets/index.js +++ b/cocos2d/core/assets/index.js @@ -37,4 +37,3 @@ require('../textures/CCTexture2D'); require('./CCTTFFont'); require('./CCSpriteAnimation'); require('./CCSpriteAtlas'); -require('./CCTiledMapAsset'); diff --git a/cocos2d/core/base-nodes/CCSGNode.js b/cocos2d/core/base-nodes/CCSGNode.js index 0e73d0c6a6..5e8591c386 100644 --- a/cocos2d/core/base-nodes/CCSGNode.js +++ b/cocos2d/core/base-nodes/CCSGNode.js @@ -88,7 +88,7 @@ cc.s_globalOrderOfArrival = 1; * -# The node will be moved according to the camera values (camera)
* -# The grid will render the captured screen

* - * @class + * @class _ccsg.Node * @extends cc._Class * * @property {Number} x - x axis position of node diff --git a/cocos2d/core/components/CCAnimation.js b/cocos2d/core/components/CCAnimation.js index f8edaef626..6510d6508c 100644 --- a/cocos2d/core/components/CCAnimation.js +++ b/cocos2d/core/components/CCAnimation.js @@ -81,6 +81,10 @@ var Animation = cc.Class({ this._defaultClip = value; + if (!value) { + return; + } + var clips = this._clips; for (var i = 0, l = clips.length; i < l; i++) { @@ -302,6 +306,10 @@ var Animation = cc.Class({ state = this._nameToState[name]; } + if (state && !state.curveLoaded) { + this._animator._reloadClip(state); + } + return state || null; }, @@ -415,7 +423,7 @@ var Animation = cc.Class({ state = new cc.AnimationState(clip); if (CC_EDITOR) { - this._animator.reloadClip(state); + this._animator._reloadClip(state); } this._nameToState[state.name] = state; @@ -428,7 +436,7 @@ var Animation = cc.Class({ state = new cc.AnimationState(this._defaultClip); if (CC_EDITOR) { - this._animator.reloadClip(state); + this._animator._reloadClip(state); } this._nameToState[state.name] = state; @@ -468,7 +476,7 @@ var Animation = cc.Class({ } oldState._clip = clip; - this._animator.reloadClip(oldState); + this._animator._reloadClip(oldState); } }); diff --git a/cocos2d/core/components/CCAudioSource.js b/cocos2d/core/components/CCAudioSource.js index 80c88ae3f1..cb69aead65 100644 --- a/cocos2d/core/components/CCAudioSource.js +++ b/cocos2d/core/components/CCAudioSource.js @@ -156,7 +156,7 @@ var AudioSource = cc.Class({ }, set: function (value) { this._loop = value; - if (typeof this.audio === 'object') this.audio.loop = this._loop; + if (this.audio) this.audio.loop = this._loop; }, animatable: false, tooltip: 'i18n.COMPONENT.audio.loop' diff --git a/cocos2d/core/components/CCButton.js b/cocos2d/core/components/CCButton.js index 7e8ffca642..e0e529c71f 100644 --- a/cocos2d/core/components/CCButton.js +++ b/cocos2d/core/components/CCButton.js @@ -290,22 +290,6 @@ var Button = cc.Class({ this.node.on(cc.Node.EventType.MOUSE_LEAVE, this._onMouseMoveOut, this); }, - _handleClickEvent: function () { - var events = this.clickEvents; - for (var i = 0, l = events.length; i < l; i++) { - var event = events[i]; - var target = event.target; - if (!target) continue; - - var comp = target.getComponent(event.component); - if (!comp) continue; - - var handler = comp[event.handler]; - if (!handler) continue; - handler.call(comp) - } - }, - _cancelButtonClick: function(){ this._pressed = false; }, @@ -341,7 +325,7 @@ var Button = cc.Class({ _onTouchEnded: function () { if (this._pressed) { - this._handleClickEvent(); + cc.Component.EventHandler.emitEvents(this.clickEvents); } this._pressed = false; this._updateState(); diff --git a/cocos2d/core/components/CCComponent.js b/cocos2d/core/components/CCComponent.js index a75a449be4..6922f94e4f 100644 --- a/cocos2d/core/components/CCComponent.js +++ b/cocos2d/core/components/CCComponent.js @@ -155,7 +155,7 @@ var _callLateUpdate = CC_EDITOR ? function (event) { // Yes, the id might have a conflict problem once every 365 days // if the game runs at 60 FPS and each frame 4760273 counts of new HashObject's id are requested. var CompId = 0; -var IdPrefix = CC_DEV && ('Comp' + Editor.NonUuidMark); +var IdPrefix = CC_DEV && ('Comp' + Editor.UuidUtils.NonUuidMark); var getNewId = CC_DEV && function () { return IdPrefix + (++CompId); }; @@ -175,8 +175,8 @@ var Component = cc.Class({ extends: cc.Object, ctor: function () { - if (CC_EDITOR) { - Editor._AssetsWatcher.initComponent(this); + if (CC_EDITOR && !CC_TEST && window._Scene) { + _Scene.AssetsWatcher.initComponent(this); } // dont reset _id when destroyed @@ -247,8 +247,8 @@ var Component = cc.Class({ get: function () {}, set: function (value) { if (this.__scriptUuid !== value) { - if (value && Editor.isUuid(value._uuid)) { - var classId = Editor.compressUuid(value._uuid); + if (value && Editor.UuidUtils.isUuid(value._uuid)) { + var classId = Editor.UuidUtils.compressUuid(value._uuid); var NewComp = cc.js._getClassById(classId); if (cc.isChildClassOf(NewComp, cc.Component)) { cc.warn('Sorry, replacing component script is not yet implemented.'); @@ -330,16 +330,6 @@ var Component = cc.Class({ __eventTargets: { default: [], serializable: false - }, - - /** - * Only for editor to calculate bounding box - */ - localSize: { - get: function () { - return cc.size(0, 0); - }, - visible: false } }, @@ -405,7 +395,7 @@ var Component = cc.Class({ */ onLostFocusInEditor: null, - // + // PUBLIC /** * Adds a component class to the entity. You can also add component to entity by passing in the name of the @@ -500,7 +490,44 @@ var Component = cc.Class({ // return Timer.hasTimeoutKey(key); //}, - // OVERRIDES + // VIRTUAL + + /** + * If the component's bounding box is different from the node's, you can implement this method to supply + * a custom axis aligned bounding box (AABB), so the editor's scene view can perform hit test properly. + * + * @method _getLocalBounds + * @param {Rect} out_rect - the Rect to receive the bounding box + */ + _getLocalBounds: null, + + /** + * onRestore is called after the user clicks the Reset item in the Inspector's context menu or performs + * an undo operation on this component. + * + * If the component contains the "internal state", short for "temporary member variables which not included + * in its CCClass properties", then you may need to implement this function. + * + * The editor will call the getset accessors of your component to record/restore the component's state + * for undo/redo operation. However, in extreme cases, it may not works well. Then you should implement + * this function to manually synchronize your component's "internal states" with its public properties. + * Once you implement this function, all the getset accessors of your component will not be called when + * the user performs an undo/redo operation. Which means that only the properties with default value + * will be recorded or restored by editor. + * + * Similarly, the editor may failed to reset your component correctly in extreme cases. Then if you need + * to support the reset menu, you should manually synchronize your component's "internal states" with its + * properties in this function. Once you implement this function, all the getset accessors of your component + * will not be called during reset operation. Which means that only the properties with default value + * will be reset by editor. + * + * This function is only called in editor mode. + * + * @method onRestore + */ + onRestore: null, + + // OVERRIDE destroy: function () { if (CC_EDITOR) { @@ -537,7 +564,9 @@ var Component = cc.Class({ callOnLostFocusInTryCatch(this); } } - Editor._AssetsWatcher.start(this); + if ( !CC_TEST ) { + _Scene.AssetsWatcher.start(this); + } } if (this._enabled) { @@ -577,7 +606,9 @@ var Component = cc.Class({ // onDestroy if (CC_EDITOR) { - Editor._AssetsWatcher.stop(this); + if ( !CC_TEST ) { + _Scene.AssetsWatcher.stop(this); + } if (cc.engine._isPlaying || this.constructor._executeInEditMode) { if (this.onDestroy) { callOnDestroyInTryCatch(this); diff --git a/cocos2d/core/components/CCComponentEventHandler.js b/cocos2d/core/components/CCComponentEventHandler.js index 85113b8b54..0820405bbe 100644 --- a/cocos2d/core/components/CCComponentEventHandler.js +++ b/cocos2d/core/components/CCComponentEventHandler.js @@ -35,5 +35,40 @@ cc.Component.EventHandler = cc.Class({ handler: { default: '', } + }, + + statics: { + /** + * Emit events with params + * @method emitEvents + * @param {Array} events + * @param {*} params + */ + emitEvents: function(events, params) { + for (var i = 0, l = events.length; i < l; i++) { + var event = events[i]; + if (! event instanceof cc.Component.EventHandler) continue; + + event.emit(params); + } + } + }, + + /** + * Emit event with params + * @method emit + * @param {*} params + */ + emit: function(params) { + var target = this.target; + if (!cc.isValid(target)) return; + + var comp = target.getComponent(this.component); + if (!cc.isValid(comp)) return; + + var handler = comp[this.handler]; + if (typeof(handler) !== 'function') return; + + handler.call(comp, params); } }); diff --git a/cocos2d/core/components/CCComponentInSG.js b/cocos2d/core/components/CCComponentInSG.js deleted file mode 100644 index 98516a32b8..0000000000 --- a/cocos2d/core/components/CCComponentInSG.js +++ /dev/null @@ -1,102 +0,0 @@ -var SceneGraphHelper = require('../utils/scene-graph-helper'); - -/** - * Component in scene graph. - * This is the base class for components which will attach a node to the cocos2d scene graph. - * - * You should override: - * - _createSgNode - * - * @class _ComponentInSG - * @extends Component - * @private - */ -var ComponentInSG = cc.Class({ - extends: require('./CCComponent'), - - editor: CC_EDITOR && { - executeInEditMode: true, - disallowMultiple: true - }, - - ctor: function () { - /** - * Reference to the instance of _ccsg.Node - * If it is possible to return null from your overloaded _createSgNode, - * then you should always check for null before using this property. - * - * @property {_ccsg.Node} _sgNode - * @private - */ - this._sgNode = this._createSgNode(); - // retain immediately - // will be released in SceneGraphHelper.removeSgNode - this._sgNode.retain(); - }, - - onLoad: function () { - var sgNode = this._sgNode; - this._initSgNode(); - this._appendSgNode(sgNode); - if ( !this.node._sizeProvider ) { - this.node._sizeProvider = sgNode; - } - }, - onEnable: function () { - if (this._sgNode) { - this._sgNode.visible = true; - } - }, - onDisable: function () { - if (this._sgNode) { - this._sgNode.visible = false; - } - }, - onDestroy: function () { - if ( this.node._sizeProvider === this._sgNode ) { - this.node._sizeProvider = null; - } - this._removeSgNode(); - }, - - /** - * Create and returns your new scene graph node (SGNode) to append to scene graph. - * You should call the setContentSize of the SGNode if its size should be the same with the node's. - * - * @method _createSgNode - * @return {_ccsg.Node} - * @private - */ - _createSgNode: null, - - /** - * @method _initSgNode - * @private - */ - _initSgNode: null, - - _removeSgNode: SceneGraphHelper.removeSgNode, - - _appendSgNode: function (sgNode) { - var node = this.node; - - sgNode.setColor(node._color); - if ( !node._cascadeOpacityEnabled ) { - sgNode.setOpacity(node._opacity); - } - - sgNode.setAnchorPoint(node._anchorPoint); - sgNode.ignoreAnchorPointForPosition(node._ignoreAnchorPointForPosition); - - sgNode.setOpacityModifyRGB(node._opacityModifyRGB); - - // set z order to -1 to make sure component will rendered before all of its entity's children. - - sgNode.setLocalZOrder(-1); - - var sgParent = node._sgNode; - sgParent.addChild(sgNode); - } -}); - -cc._ComponentInSG = module.exports = ComponentInSG; diff --git a/cocos2d/core/components/CCEditBox.js b/cocos2d/core/components/CCEditBox.js index 1e767d310a..55fda2d859 100644 --- a/cocos2d/core/components/CCEditBox.js +++ b/cocos2d/core/components/CCEditBox.js @@ -31,11 +31,11 @@ var InputFlag = _ccsg.EditBox.InputFlag; /** * cc.EditBox is a component for inputing text, you can use it to gather small amounts of text from users. * @class EditBox - * @extends _ComponentInSG + * @extends _RendererUnderSG */ var EditBox = cc.Class({ name: 'cc.EditBox', - extends: cc._ComponentInSG, + extends: cc._RendererUnderSG, editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.ui/EditBox', @@ -44,14 +44,19 @@ var EditBox = cc.Class({ }, properties: { + _useOriginalSize: true, + _string: '', /** * Input string of EditBox. * @property {String} string */ string: { - default: '', - notify: function() { - this._sgNode.string = this.string; + tooltip: 'i18n:COMPONENT.editbox.string', + get: function () { + return this._sgNode.string; + }, + set: function(value) { + this._sgNode.string = this._string = value; } }, @@ -60,13 +65,20 @@ var EditBox = cc.Class({ * @property {cc.SpriteFrame} backGroundImage */ backgroundImage: { + tooltip: 'i18n:COMPONENT.editbox.backgroundImage', default: null, type: cc.SpriteFrame, notify: function() { var sgNode = this._sgNode; var backgroundSprite = sgNode.getBackgroundSprite(); - backgroundSprite.setSpriteFrame(this.backgroundImage); - backgroundSprite.setContentSize(sgNode.getContentSize()); + if(this.backgroundImage) { + var sprite = this._createBackgroundSprite(); + sprite.setSpriteFrame(this.backgroundImage); + sprite.setContentSize(sgNode.getContentSize()); + } + else { + backgroundSprite.removeFromParent(); + } } }, @@ -78,6 +90,8 @@ var EditBox = cc.Class({ */ returnType: { default: KeyboardReturnType.DEFAULT, + tooltip: 'i18n:COMPONENT.editbox.returnType', + displayName: 'KeyboardReturnType', type: KeyboardReturnType, notify: function() { this._sgNode.returnType = this.returnType; @@ -90,13 +104,13 @@ var EditBox = cc.Class({ * @default InputFlag.INITIAL_CAPS_ALL_CHARACTERS */ inputFlag: { + tooltip: 'i18n:COMPONENT.editbox.input_flag', default: InputFlag.INITIAL_CAPS_ALL_CHARACTERS, type: InputFlag, notify: function() { this._sgNode.inputFlag = this.inputFlag; } }, - /** * Set the input mode of the edit box. * If you pass ANY, it will create a multiline EditBox. @@ -104,6 +118,7 @@ var EditBox = cc.Class({ * @default InputMode.ANY */ inputMode: { + tooltip: 'i18n:COMPONENT.editbox.input_mode', default: InputMode.ANY, type: InputMode, notify: function() { @@ -116,17 +131,31 @@ var EditBox = cc.Class({ * @property {Number} fontSize */ fontSize: { + tooltip: 'i18n:COMPONENT.editbox.font_size', default: 20, notify: function() { this._sgNode.fontSize = this.fontSize; } }, + /** + * Change the lineHeight of displayed text. + * @property {Number} lineHeight + */ + lineHeight: { + tooltip: 'i18n:COMPONENT.editbox.line_height', + default: 40, + notify: function() { + this._sgNode.setLineHeight(this.lineHeight); + } + }, + /** * Font color of the input text. * @property {cc.Color} fontColor */ fontColor: { + tooltip: 'i18n:COMPONENT.editbox.font_color', default: cc.Color.WHITE, notify: function() { this._sgNode.fontColor = this.fontColor; @@ -134,35 +163,38 @@ var EditBox = cc.Class({ }, /** - * The display text of placeHolder. - * @property {String} placeHolder + * The display text of placeholder. + * @property {String} placeholder */ - placeHolder: { + placeholder: { + tooltip: 'i18n:COMPONENT.editbox.placeholder', default: 'Enter text here...', notify: function() { - this._sgNode.placeHolder = this.placeHolder; + this._sgNode.placeholder = this.placeholder; } }, /** - * The font size of placeHolder. - * @property {Number} placeHolderFontSize + * The font size of placeholder. + * @property {Number} placeholderFontSize */ - placeHolderFontSize: { + placeholderFontSize: { + tooltip: 'i18n:COMPONENT.editbox.placeholder_font_size', default: 20, notify: function() { - this._sgNode.placeHolderFontSize = this.placeHolderFontSize; + this._sgNode.placeholderFontSize = this.placeholderFontSize; } }, /** - * The font color of placeHolder. - * @property {cc.Color} placeHolderFontColor + * The font color of placeholder. + * @property {cc.Color} placeholderFontColor */ - placeHolderFontColor: { + placeholderFontColor: { + tooltip: 'i18n:COMPONENT.editbox.placeholder_font_color', default: cc.Color.GRAY, notify: function() { - this._sgNode.placeHolderFontColor = this.placeHolderFontColor; + this._sgNode.placeholderFontColor = this.placeholderFontColor; } }, @@ -171,6 +203,7 @@ var EditBox = cc.Class({ * @property {Number} maxLength */ maxLength: { + tooltip: 'i18n:COMPONENT.editbox.max_length', default: 20, notify: function() { this._sgNode.maxLength = this.maxLength; @@ -197,7 +230,7 @@ var EditBox = cc.Class({ /** * The event handler to be called when EditBox edit ends. - * @property {cc.Component.EventHandler} editingDidEnd + * @property {cc.Component.EventHandler} editingDidEnded */ editingDidEnded: { default: [], @@ -213,59 +246,62 @@ var EditBox = cc.Class({ }, _createSgNode: function() { - return new _ccsg.EditBox(cc.size(300, 100)); + return new _ccsg.EditBox(cc.size(160, 40)); + }, + + _createBackgroundSprite: function() { + var sgNode = this._sgNode; + var bgSprite = new cc.Scale9Sprite(this.backgroundImage); + sgNode.initWithSizeAndBackgroundSprite(cc.size(160, 40), bgSprite); + return bgSprite; }, _initSgNode: function() { var sgNode = this._sgNode; - var bgSprite = new cc.Scale9Sprite(this.backgroundImage); - sgNode.initWithSizeAndBackgroundSprite(this.node.getContentSize(), bgSprite); - sgNode.setContentSize(this.node.getContentSize()); + this._createBackgroundSprite(); + sgNode.inputMode = this.inputMode; sgNode.maxLength = this.maxLength; - sgNode.string = this.string; + sgNode.string = this._string; sgNode.fontSize = this.fontSize; sgNode.fontColor = this.fontColor; - sgNode.placeHolder = this.placeHolder; - sgNode.placeHolderFontSize = this.placeHolderFontSize; - sgNode.placeHolderFontColor = this.placeHolderFontColor; + sgNode.placeholder = this.placeholder; + sgNode.placeholderFontSize = this.placeholderFontSize; + sgNode.placeholderFontColor = this.placeholderFontColor; sgNode.inputFlag = this.inputFlag; sgNode.returnType = this.returnType; + sgNode.setLineHeight(this.lineHeight); + + if (!this._useOriginalSize) { + sgNode.setContentSize(this.node.getContentSize()); + } sgNode.setDelegate(this); }, - _handleComponentEvent: function(events, text) { - for (var i = 0, l = events.length; i < l; i++) { - var event = events[i]; - var target = event.target; - if (!cc.isValid(target)) continue; + _resized: function () { + this._useOriginalSize = false; + }, - var comp = target.getComponent(event.component); - if (!cc.isValid(comp)) continue; + onLoad: function () { + this._super(); - var handler = comp[event.handler]; - if (!handler) continue; - handler.call(comp, text); - } + this.node.on('size-changed', this._resized, this); }, editBoxEditingDidBegan: function() { - var events = this.editingDidBegin; - this._handleComponentEvent(events); + cc.Component.EventHandler.emitEvents(this.editingDidBegan); }, editBoxEditingDidEnded: function() { - var events = this.editingDidEnd; - this._handleComponentEvent(events); + cc.Component.EventHandler.emitEvents(this.editingDidEnded); }, editBoxTextChanged: function(editBox, text) { - var events = this.textChanged; - this._handleComponentEvent(events, text); + cc.Component.EventHandler.emitEvents(this.textChanged, text); }, }); diff --git a/cocos2d/core/components/CCLabel.js b/cocos2d/core/components/CCLabel.js index 3e5b012986..974aaedbf3 100644 --- a/cocos2d/core/components/CCLabel.js +++ b/cocos2d/core/components/CCLabel.js @@ -29,11 +29,11 @@ var LabelType = _ccsg.Label.Type; /** * * @class Label - * @extends _ComponentInSG + * @extends _RendererUnderSG */ var Label = cc.Class({ name: 'cc.Label', - extends: cc._ComponentInSG, + extends: cc._RendererUnderSG, editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.renderers/Label' @@ -50,8 +50,10 @@ var Label = cc.Class({ multiline: true, tooltip: 'i18n:COMPONENT.label.string', notify: function () { - this._sgNode.setString(this.string); - this._updateNodeSize(); + if (this._sgNode) { + this._sgNode.setString(this.string); + this._updateNodeSize(); + } } }, @@ -64,7 +66,9 @@ var Label = cc.Class({ type: HorizontalAlign, tooltip: 'i18n:COMPONENT.label.horizontal_align', notify: function () { - this._sgNode.setHorizontalAlign( this.horizontalAlign ); + if (this._sgNode) { + this._sgNode.setHorizontalAlign( this.horizontalAlign ); + } }, animatable: false }, @@ -78,7 +82,9 @@ var Label = cc.Class({ type: VerticalAlign, tooltip: 'i18n:COMPONENT.label.vertical_align', notify: function () { - this._sgNode.setVerticalAlign( this.verticalAlign ); + if (this._sgNode) { + this._sgNode.setVerticalAlign( this.verticalAlign ); + } }, animatable: false }, @@ -90,13 +96,17 @@ var Label = cc.Class({ */ fontSize: { get: function(){ - this._fontSize = this._sgNode.getFontSize(); + if (this._sgNode) { + this._fontSize = this._sgNode.getFontSize(); + } return this._fontSize; }, set: function(value){ this._fontSize = value; - this._sgNode.setFontSize(value); - this._updateNodeSize(); + if (this._sgNode) { + this._sgNode.setFontSize(value); + this._updateNodeSize(); + } }, tooltip: 'i18n:COMPONENT.label.font_size', }, @@ -105,14 +115,18 @@ var Label = cc.Class({ lineHeight: { get: function(){ - this._lineHeight = this._sgNode.getLineHeight(); + if (this._sgNode) { + this._lineHeight = this._sgNode.getLineHeight(); + } return this._lineHeight; }, set: function(value){ this._lineHeight = value; - this._sgNode.setLineHeight(value); - this._updateNodeSize(); + if (this._sgNode) { + this._sgNode.setLineHeight(value); + this._updateNodeSize(); + } }, tooltip: 'i18n:COMPONENT.label.line_height', }, @@ -125,8 +139,10 @@ var Label = cc.Class({ type: Overflow, tooltip: 'i18n:COMPONENT.label.overflow', notify: function () { - this._sgNode.setOverflow(this.overflow); - this._updateNodeSize(); + if (this._sgNode) { + this._sgNode.setOverflow(this.overflow); + this._updateNodeSize(); + } }, animatable: false }, @@ -138,12 +154,16 @@ var Label = cc.Class({ */ enableWrapText: { get: function(){ - this._enableWrapText = this._sgNode.isWrapTextEnabled(); + if (this._sgNode) { + this._enableWrapText = this._sgNode.isWrapTextEnabled(); + } return this._enableWrapText; }, set: function(value){ this._enableWrapText = value; - this._sgNode.enableWrapText(value); + if (this._sgNode) { + this._sgNode.enableWrapText(value); + } }, animatable: false, tooltip: 'i18n:COMPONENT.label.wrap', @@ -151,14 +171,16 @@ var Label = cc.Class({ /** * The font URL of label. - * @property {URL} file + * @property {string} file */ file: { default: "Arial", url: cc.Font, tooltip: 'i18n:COMPONENT.label.file', notify: function () { - this._sgNode.setFontFileOrFamily(this.file); + if (this._sgNode) { + this._sgNode.setFontFileOrFamily(this.file); + } }, animatable: false }, @@ -171,14 +193,18 @@ var Label = cc.Class({ */ useSystemFont: { get: function(){ - this._isSystemFontUsed = this._sgNode.isSystemFontUsed(); + if (this._sgNode) { + this._isSystemFontUsed = this._sgNode.isSystemFontUsed(); + } return this._isSystemFontUsed; }, set: function(value){ this._isSystemFontUsed = value; if (value) { this.file = ""; - this._sgNode.setSystemFontUsed(value); + if (this._sgNode) { + this._sgNode.setSystemFontUsed(value); + } } }, @@ -242,10 +268,12 @@ var Label = cc.Class({ }, _createSgNode: function () { - return new _ccsg.Label(); + return null; }, _initSgNode: function () { + this._sgNode = new _ccsg.Label(this.string, this.file); + this._sgNode.retain(); var sgNode = this._sgNode; // TODO @@ -260,7 +288,9 @@ var Label = cc.Class({ sgNode.setString(this.string); sgNode.setFontFileOrFamily(this.file); if(!this._useOriginalSize){ - sgNode.setContentSize(this.node.getContentSize()); + if(this.overflow !== Overflow.NONE) { + sgNode.setContentSize(this.node.getContentSize()); + } } sgNode.setColor(this.node.color); }, @@ -271,11 +301,14 @@ var Label = cc.Class({ // update node size (this will also invoke the size-changed event) _updateNodeSize: function () { - if (this.overflow === Overflow.NONE) { - this.node.setContentSize(this._sgNode.getContentSize()); - } - if ( !this.node._sizeProvider ) { - this.node._sizeProvider = this._sgNode; + var initialized = this._sgNode && this._sgNode.parent; + if (initialized) { + if (this.overflow === Overflow.NONE) { + this.node.setContentSize(this._sgNode.getContentSize()); + } + if ( !this.node._sizeProvider ) { + this.node._sizeProvider = this._sgNode; + } } } }); diff --git a/cocos2d/core/components/CCLayout.js b/cocos2d/core/components/CCLayout.js index 4adc88c9e7..c0d81b8aa8 100644 --- a/cocos2d/core/components/CCLayout.js +++ b/cocos2d/core/components/CCLayout.js @@ -143,6 +143,12 @@ var Layout = cc.Class({ default: Type.NONE, type: Type, notify: function() { + if (this.layoutType !== Type.NONE && this._resize === ResizeType.CONTAINER && CC_EDITOR && !cc.engine.isPlaying) { + var reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); + if (reLayouted) { + return; + } + } this._doLayoutDirty(); }, animatable: false, @@ -168,8 +174,14 @@ var Layout = cc.Class({ return; } - this._doLayoutDirty(); this._resize = value; + if (this.layoutType !== Type.NONE && value === ResizeType.CONTAINER && CC_EDITOR && !cc.engine.isPlaying) { + var reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); + if (reLayouted) { + return; + } + } + this._doLayoutDirty(); }, animatable: false }, @@ -197,6 +209,12 @@ var Layout = cc.Class({ default: AxisDirection.HORIZONTAL, type: AxisDirection, notify: function() { + if (this._resize === ResizeType.CONTAINER && CC_EDITOR && !cc.engine.isPlaying) { + var reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); + if (reLayouted) { + return; + } + } this._doLayoutDirty(); }, animatable: false @@ -285,6 +303,7 @@ var Layout = cc.Class({ this.node.on('anchor-changed', this._doLayoutDirty, this); this.node.on('child-added', this._childrenAddOrDeleted, this); this.node.on('child-removed', this._childrenAddOrDeleted, this); + this.node.on('child-reorder', this._doLayoutDirty, this); this._updateChildrenEventListener(); }, diff --git a/cocos2d/core/components/CCMask.js b/cocos2d/core/components/CCMask.js index b2415453cb..79e373e50d 100644 --- a/cocos2d/core/components/CCMask.js +++ b/cocos2d/core/components/CCMask.js @@ -23,86 +23,76 @@ ****************************************************************************/ /** - * * @class Mask - * @extends Component + * @extends _RendererInSG */ var Mask = cc.Class({ name: 'cc.Mask', - extends: cc.Component, + extends: cc._RendererInSG, editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.ui/Mask', - executeInEditMode: true }, properties: { - _clippingNode: { - default: null, - serializable: false, - }, _clippingStencil: { default: null, serializable: false, }, }, - onLoad: function () { + _createSgNode: function () { this._clippingStencil = new cc.DrawNode(); - this._clippingNode = new cc.ClippingNode(this._clippingStencil); - if (cc.sys.isNative) { - this._clippingStencil.retain(); - this._clippingNode.retain(); - } + this._clippingStencil.retain(); + return new cc.ClippingNode(this._clippingStencil); }, - onDestroy: function () { - if (cc.sys.isNative) { - this._clippingStencil && this._clippingStencil.release(); - this._clippingNode && this._clippingNode.release(); - } + _initSgNode: function () { + var clippingNode = this._sgNode; + clippingNode.setContentSize(this.node.getContentSize(true)); }, - - _refreshStencil: function () { - var contentSize = this.node._contentSize; - var anchorPoint = this.node._anchorPoint; - var x = contentSize.width * anchorPoint.x; - var y = contentSize.height * anchorPoint.y; - this._clippingStencil.clear(); - var rectangle = [cc.v2(-x, -y), cc.v2(contentSize.width - x, -y), - cc.v2(contentSize.width - x, contentSize.height - y), - cc.v2(-x, contentSize.height - y)]; - this._clippingStencil.drawPoly(rectangle, cc.color(255, 255, 255, 0), 0, cc.color(255, 255, 255, 0)); - }, - + + //onLoad: function () { + // this._super(); + // // ignore node size + // if (this.node._sizeProvider === this._sgNode) { + // this.node._sizeProvider = null; + // } + //}, + onEnable: function () { - var oldNode = this.node._sgNode; this._refreshStencil(); - this.node._replaceSgNode(this._clippingNode); - this.node.on('size-changed', this._onContentSizeChanged, this); - this.node.on('anchor-changed', this._onAnchorChanged, this); + this._super(); + this.node.on('size-changed', this._refreshStencil, this); + this.node.on('anchor-changed', this._refreshStencil, this); }, onDisable: function () { - var oldNode = this.node._sgNode; - var newNode = new _ccsg.Node(); - this.node._replaceSgNode(newNode); - this.node.off('size-changed', this._onContentSizeChanged, this); - this.node.off('anchor-changed', this._onAnchorChanged, this); + this._super(); + this.node.off('size-changed', this._refreshStencil, this); + this.node.off('anchor-changed', this._refreshStencil, this); + }, + + onDestroy: function () { + this._super(); + this._clippingStencil.release(); }, - _onContentSizeChanged: function () { - if (this._clippingStencil) { - this._refreshStencil(); - } - }, - - _onAnchorChanged: function () { - if (this._clippingStencil) { - this._refreshStencil(); - } + _refreshStencil: function () { + var contentSize = this.node.getContentSize(); + var anchorPoint = this.node.getAnchorPoint(); + var width = contentSize.width; + var height = contentSize.height; + var x = - width * anchorPoint.x; + var y = - height * anchorPoint.y; + var rectangle = [ cc.v2(x, y), + cc.v2(x + width, y), + cc.v2(x + width, y + height), + cc.v2(x, y + height) ]; + var color = cc.color(255, 255, 255, 0); + this._clippingStencil.clear(); + this._clippingStencil.drawPoly(rectangle, color, 0, color); } - }); cc.Mask = module.exports = Mask; diff --git a/cocos2d/core/components/CCProgressBar.js b/cocos2d/core/components/CCProgressBar.js index 80fc352c66..f566b95f6f 100644 --- a/cocos2d/core/components/CCProgressBar.js +++ b/cocos2d/core/components/CCProgressBar.js @@ -36,7 +36,11 @@ var Mode = cc.Enum({ /** * @property {Number} VERTICAL */ - VERTICAL: 1 + VERTICAL: 1, + /** + * @property {Number} FILLED + */ + FILLED: 2, }); /** @@ -55,6 +59,7 @@ var ProgressBar = cc.Class({ _initBarSprite: function() { if (this.barSprite) { var entity = this.barSprite.node; + if (!entity) return; var nodeSize = this.node.getContentSize(); var nodeAnchor = this.node.getAnchorPoint(); @@ -65,12 +70,20 @@ var ProgressBar = cc.Class({ this.node.setContentSize(entitySize); } + if (this.barSprite.fillType === cc.Sprite.FillType.RADIAL) { + this.mode = Mode.FILLED; + } + var barSpriteSize = entity.getContentSize(); if (this.mode === Mode.HORIZONTAL) { this.totalLength = barSpriteSize.width; - } else { + } + else if(this.mode === Mode.VERTICAL) { this.totalLength = barSpriteSize.height; } + else { + this.totalLength = this.barSprite.fillRange; + } if(entity.parent === this.node){ var x = - nodeSize.width * nodeAnchor.x; @@ -83,6 +96,9 @@ var ProgressBar = cc.Class({ _updateBarStatus: function() { if (this.barSprite) { var entity = this.barSprite.node; + + if (!entity) return; + var entityAnchorPoint = entity.getAnchorPoint(); var entitySize = entity.getContentSize(); var entityPosition = entity.getPosition(); @@ -110,17 +126,27 @@ var ProgressBar = cc.Class({ finalContentSize = cc.size(entitySize.width, actualLenth); totalWidth = entitySize.width; totalHeight = this.totalLength; + break; + case Mode.FILLED: + if (this.reverse) { + actualLenth = actualLenth * -1; + } + this.barSprite.fillRange = actualLenth; + break; } - var anchorOffsetX = anchorPoint.x - entityAnchorPoint.x; - var anchorOffsetY = anchorPoint.y - entityAnchorPoint.y; + if (this.barSprite.type !== cc.Sprite.Type.FILLED) { - var finalPosition = cc.p(totalWidth * anchorOffsetX, totalHeight * anchorOffsetY); + var anchorOffsetX = anchorPoint.x - entityAnchorPoint.x; + var anchorOffsetY = anchorPoint.y - entityAnchorPoint.y; + var finalPosition = cc.p(totalWidth * anchorOffsetX, totalHeight * anchorOffsetY); - entity.setPosition(cc.pAdd(entityPosition, finalPosition)); + entity.setPosition(cc.pAdd(entityPosition, finalPosition)); + + entity.setAnchorPoint(anchorPoint); + entity.setContentSize(finalContentSize); + } - entity.setAnchorPoint(anchorPoint); - entity.setContentSize(finalContentSize); } }, @@ -151,11 +177,15 @@ var ProgressBar = cc.Class({ notify: function() { if (this.barSprite) { var entity = this.barSprite.node; + if (!entity) return; + var entitySize = entity.getContentSize(); if (this.mode === Mode.HORIZONTAL) { this.totalLength = entitySize.width; } else if (this.mode === Mode.VERTICAL) { this.totalLength = entitySize.height; + } else if (this.mode === Mode.FILLED) { + this.totalLength = this.barSprite.fillRange; } } }, diff --git a/cocos2d/core/components/CCRendererInSG.js b/cocos2d/core/components/CCRendererInSG.js new file mode 100644 index 0000000000..b8e7cde720 --- /dev/null +++ b/cocos2d/core/components/CCRendererInSG.js @@ -0,0 +1,120 @@ +/**************************************************************************** + Copyright (c) 2016 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +/** + * Rendering component in scene graph. + * Maintains a node which will be the scene graph of component's Node. + * + * @class _RendererInSG + * @extends _SGComponent + * @private + */ +var RendererInSG = cc.Class({ + extends: require('./CCSGComponent'), + + ctor: function () { + /** + * The Reference to the instance of _ccsg.Node used when this component enabled + * @property {_ccsg.Node} _sgNode + * @private + */ + this._sgNode = this._createSgNode(); + if (this._sgNode) { + // retain immediately + // will be released in onDestroy + this._sgNode.retain(); + } + else { + cc.error('Not support for asynchronous creating node in SG'); + } + + // The replacement node used when this component disabled + this._plainNode = new _ccsg.Node(); + }, + + onEnable: function () { + this._replaceSgNode(this._sgNode); + this.node._ignoreAnchor = true; + }, + onDisable: function () { + this._replaceSgNode(this._plainNode); + this.node._ignoreAnchor = false; + }, + onDestroy: function () { + this._super(); + + var released = this.node._sgNode; + if (this._sgNode !== released) { + this._sgNode.release(); + } + else { + this._plainNode.release(); + } + }, + + _replaceSgNode: function (sgNode) { + if ( !(sgNode instanceof _ccsg.Node) && CC_EDITOR) { + throw new Error("Invalid sgNode. It must be an instance of _ccsg.Node"); + } + + var node = this.node; + var replaced = node._sgNode; + + if (replaced === sgNode && CC_EDITOR) { + cc.warn('The same sgNode'); + return; + } + + // rebuild scene graph + + // replace children + var children = replaced.getChildren().slice(); + replaced.removeAllChildren(); + if (sgNode.getChildrenCount() > 0) { + if (CC_EDITOR) { + cc.warn('The replacement sgNode should not contain any child.'); + } + sgNode.removeAllChildren(); + } + for (var i = 0, len = children.length; i < len; ++i) { + sgNode.addChild(children[i]); + } + + // replace parent + var parentNode = replaced.getParent(); + parentNode.removeChild(replaced); + parentNode.addChild(sgNode); + sgNode.arrivalOrder = replaced.arrivalOrder; + if (cc.renderer) { + cc.renderer.childrenOrderDirty = parentNode._reorderChildDirty = true; + } + + // apply node's property + + node._sgNode = sgNode; + node._updateSgNode(); + }, +}); + +cc._RendererInSG = module.exports = RendererInSG; diff --git a/cocos2d/core/components/CCRendererUnderSG.js b/cocos2d/core/components/CCRendererUnderSG.js new file mode 100644 index 0000000000..417304a05d --- /dev/null +++ b/cocos2d/core/components/CCRendererUnderSG.js @@ -0,0 +1,96 @@ +/**************************************************************************** + Copyright (c) 2016 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +/** + * The base rendering component which will attach a leaf node to the cocos2d scene graph. + * + * @class _RendererUnderSG + * @extends _SGComponent + * @private + */ +var RendererUnderSG = cc.Class({ + extends: require('./CCSGComponent'), + + ctor: function () { + /** + * Reference to the instance of _ccsg.Node + * If it is possible to return null from your overloaded _createSgNode, + * then you should always check for null before using this property and reimplement onLoad. + * + * @property {_ccsg.Node} _sgNode + * @private + */ + this._sgNode = this._createSgNode(); + if (this._sgNode) { + // retain immediately + // will be released in onDestroy + this._sgNode.retain(); + } + }, + + // You should reimplement this function if your _sgNode maybe null. + onLoad: function () { + this._super(); + this._appendSgNode(this._sgNode); + }, + onEnable: function () { + if (this._sgNode) { + this._sgNode.setVisible(true); + } + }, + onDisable: function () { + if (this._sgNode) { + this._sgNode.setVisible(false); + } + }, + + _appendSgNode: function (sgNode) { + if ( !sgNode ) { + return; + } + + if ( !this.enabled ) { + sgNode.setVisible(false); + } + var node = this.node; + sgNode.setColor(node._color); + if ( !node._cascadeOpacityEnabled ) { + sgNode.setOpacity(node._opacity); + } + + sgNode.setAnchorPoint(node._anchorPoint); + sgNode.ignoreAnchorPointForPosition(node.__ignoreAnchor); + + sgNode.setOpacityModifyRGB(node._opacityModifyRGB); + + // set z order to -1 to make sure component will rendered before all of its entity's children. + + sgNode.setLocalZOrder(-1); + + var sgParent = node._sgNode; + sgParent.addChild(sgNode); + } +}); + +cc._RendererUnderSG = module.exports = RendererUnderSG; diff --git a/cocos2d/core/components/CCSGComponent.js b/cocos2d/core/components/CCSGComponent.js new file mode 100644 index 0000000000..5e7b17333f --- /dev/null +++ b/cocos2d/core/components/CCSGComponent.js @@ -0,0 +1,90 @@ +/**************************************************************************** + Copyright (c) 2016 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +var SceneGraphHelper = require('../utils/scene-graph-helper'); + +/** + * The base class for all rendering component in scene graph. + * + * You should override: + * - _createSgNode + * - _initSgNode + * + * @class _SGComponent + * @extends Component + * @private + */ +var SGComponent = cc.Class({ + extends: require('./CCComponent'), + + editor: CC_EDITOR && { + executeInEditMode: true, + disallowMultiple: true + }, + + properties: { + _sgNode: { + default: null, + serializable: false + } + }, + + onLoad: function () { + this._initSgNode(); + var sgNode = this._sgNode; + if ( !this.node._sizeProvider ) { + this.node._sizeProvider = sgNode; + } + }, + onDestroy: function () { + if ( this.node._sizeProvider === this._sgNode ) { + this.node._sizeProvider = null; + } + this._removeSgNode(); + }, + + /** + * Create and returns your new scene graph node (SGNode) to add to scene graph. + * You should call the setContentSize of the SGNode if its size should be the same with the node's. + * + * @method _createSgNode + * @return {_ccsg.Node} + * @private + */ + _createSgNode: null, + + /** + * @method _initSgNode + * @private + */ + _initSgNode: null, + + /** + * @method _removeSgNode + * @private + */ + _removeSgNode: SceneGraphHelper.removeSgNode, +}); + +cc._SGComponent = module.exports = SGComponent; diff --git a/cocos2d/core/components/CCScrollView.js b/cocos2d/core/components/CCScrollView.js index 1b515e9755..6f79d8b812 100644 --- a/cocos2d/core/components/CCScrollView.js +++ b/cocos2d/core/components/CCScrollView.js @@ -159,8 +159,10 @@ var ScrollView = cc.Class({ type: cc.Scrollbar, tooltip: 'i18n:COMPONENT.scrollview.horizontal_bar', notify: function() { - this.horizontalScrollBar.setTargetScrollView(this); - this._updateScrollBar(0); + if (this.horizontalScrollBar) { + this.horizontalScrollBar.setTargetScrollView(this); + this._updateScrollBar(0); + } }, animatable: false }, @@ -174,8 +176,10 @@ var ScrollView = cc.Class({ type: cc.Scrollbar, tooltip: 'i18n:COMPONENT.scrollview.vertical_bar', notify: function() { - this.verticalScrollBar.setTargetScrollView(this); - this._updateScrollBar(0); + if (this.verticalScrollBar) { + this.verticalScrollBar.setTargetScrollView(this); + this._updateScrollBar(0); + } }, animatable: false } diff --git a/cocos2d/core/components/CCSprite.js b/cocos2d/core/components/CCSprite.js index 967eda9eda..0da310c7bc 100644 --- a/cocos2d/core/components/CCSprite.js +++ b/cocos2d/core/components/CCSprite.js @@ -61,11 +61,11 @@ var SizeMode = cc.Enum({ /** * Renders a sprite in the scene. * @class Sprite - * @extends _ComponentInSG + * @extends _RendererUnderSG */ var Sprite = cc.Class({ name: 'cc.Sprite', - extends: require('./CCComponentInSG'), + extends: require('./CCRendererUnderSG'), editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.renderers/Sprite', @@ -96,7 +96,7 @@ var Sprite = cc.Class({ * @type {SpriteAtlas} */ _atlas: { - default: '', + default: null, type: cc.SpriteAtlas, tooltip: 'i18n:COMPONENT.sprite.atlas', editorOnly: true, @@ -174,7 +174,7 @@ var Sprite = cc.Class({ return this._fillStart; }, set: function(value) { - this._fillStart = value; + this._fillStart = cc.clampf(value, -1, 1); this._sgNode && this._sgNode.setFillStart(value); }, }, @@ -184,7 +184,7 @@ var Sprite = cc.Class({ return this._fillRange; }, set: function(value) { - this._fillRange = value; + this._fillRange = cc.clampf(value, -1, 1); this._sgNode && this._sgNode.setFillRange(value); }, }, @@ -264,20 +264,15 @@ var Sprite = cc.Class({ }, animatable: false, type: SizeMode - }, - /** - * Only for editor to calculate bounding box. - */ - localSize: { - get: function () { - var sgNode = this._sgNode; - return cc.size(sgNode.width, sgNode.height); - }, - visible: false, - override: true } }, + statics: { + FillType: FillType, + Type: SpriteType, + SizeMode: SizeMode, + }, + /** * Sets whether the sprite is visible or not. * @method setVisible @@ -445,6 +440,14 @@ var Sprite = cc.Class({ this.node.on('size-changed', this._resized, this); }, + onEnable: function () { + if (this._sgNode) { + if (this._spriteFrame && this._spriteFrame.textureLoaded()) { + this._sgNode.setVisible(true); + } + } + }, + onDestroy: function () { this._super(); this.node.off('size-changed', this._resized, this); @@ -505,7 +508,7 @@ var Sprite = cc.Class({ sgNode.setSpriteFrame(self._spriteFrame); self._applyCapInset(); self._applySpriteSize(); - if (this.enabledInHierarchy && !sgNode.isVisible()) { + if (self.enabledInHierarchy && !sgNode.isVisible()) { sgNode.setVisible(true); } }, @@ -540,13 +543,8 @@ var Sprite = cc.Class({ _initSgNode: function () { var sgNode = this._sgNode; - - if (!this.enabledInHierarchy) { - sgNode.setVisible(false); - } - + this._validateSizeMode(); - this._applySpriteFrame(null); // should keep the size of the sg node the same as entity, diff --git a/cocos2d/core/components/CCWidget.js b/cocos2d/core/components/CCWidget.js index 9ede45babc..46f0be7773 100644 --- a/cocos2d/core/components/CCWidget.js +++ b/cocos2d/core/components/CCWidget.js @@ -392,6 +392,10 @@ var Widget = cc.Class({ if (this.isStretchWidth) { // become stretch this._originalWidth = this.node.width; + // test check conflict + if (CC_EDITOR && !cc.engine.isPlaying) { + _Scene.DetectConflict.checkConflict_Widget(this); + } } } else { @@ -399,10 +403,14 @@ var Widget = cc.Class({ if (this.isStretchHeight) { // become stretch this._originalHeight = this.node.height; + // test check conflict + if (CC_EDITOR && !cc.engine.isPlaying) { + _Scene.DetectConflict.checkConflict_Widget(this); + } } } - if (CC_EDITOR && !cc.engine._isPlaying) { + if (CC_EDITOR && !cc.engine._isPlaying && this.node._parent) { // adjust the offsets to keep the size and position unchanged after alignment chagned var type; if (flag & TOP) { diff --git a/cocos2d/core/components/index.js b/cocos2d/core/components/index.js index a8634b8cb6..5eb1c7418c 100644 --- a/cocos2d/core/components/index.js +++ b/cocos2d/core/components/index.js @@ -1,6 +1,8 @@ require('./CCComponent'); -require('./CCComponentInSG'); -require('./CCComponentEventHandler') +require('./CCRendererInSG'); +require('./CCRendererUnderSG'); +require('./CCComponentEventHandler'); +require('./missing-script'); module.exports = [ require('./CCSprite'), diff --git a/cocos2d/core/components/missing-script.js b/cocos2d/core/components/missing-script.js new file mode 100644 index 0000000000..24bbabe592 --- /dev/null +++ b/cocos2d/core/components/missing-script.js @@ -0,0 +1,79 @@ +var JS = cc.js; + +/* + * A temp fallback to contain the original component which can not be loaded. + * Actually, this class will be used whenever a class failed to deserialize, + * regardless of whether it is child class of component. + */ +var MissingScript = cc.Class({ + name: 'cc.MissingScript', extends: cc.Component, + properties: { + //_scriptUuid: { + // get: function () { + // var id = this._$erialized.__type__; + // if (Editor.UuidUtils.isUuid(id)) { + // return Editor.UuidUtils.decompressUuid(id); + // } + // return ''; + // }, + // set: function (value) { + // if ( !sandbox.compiled ) { + // cc.error('Scripts not yet compiled, please fix script errors and compile first.'); + // return; + // } + // if (value && Editor.UuidUtils.isUuid(value._uuid)) { + // var classId = Editor.UuidUtils.compressUuid(value); + // if (cc.js._getClassById(classId)) { + // this._$erialized.__type__ = classId; + // Editor.sendToWindows('reload:window-scripts', sandbox.compiled); + // } + // else { + // cc.error('Can not find a component in the script which uuid is "%s".', value); + // } + // } + // else { + // cc.error('invalid script'); + // } + // } + //}, + error: { + default: '', + multiline: true, + readonly: true, + serializable: false, + displayName: '(Error)' + }, + // the serialized data for original script object + _$erialized: { + default: null, + visible: false, + editorOnly: true + } + }, + ctor: CC_EDITOR && function () { + this.error = _Scene.Sandbox.compiled ? + Editor.T('COMPONENT.missing_scirpt.error_compiled') : + Editor.T('COMPONENT.missing_scirpt.error_not_compiled') + }, + statics: { + /* + * @param {string} id + * @return {function} constructor + */ + safeFindClass: function (id) { + var cls = JS._getClassById(id); + if (cls) { + return cls; + } + if (id) { + return MissingScript; + } + return null; + } + }, + onLoad: function () { + cc.warn('The referenced script on "%s" is missing!', this.name); + } +}); + +cc._MissingScript = module.exports = MissingScript; diff --git a/cocos2d/core/editbox/CCSGEditBox.js b/cocos2d/core/editbox/CCSGEditBox.js index 48d79524e9..49074f9b08 100644 --- a/cocos2d/core/editbox/CCSGEditBox.js +++ b/cocos2d/core/editbox/CCSGEditBox.js @@ -26,6 +26,13 @@ THE SOFTWARE. ****************************************************************************/ +var capitalize = function(string) { + return string.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); }); +}; + +function capitalizeFirstLetter(string) { + return string.charAt(0).toUpperCase() + string.slice(1); +} /** * Enum for keyboard return types * @readonly @@ -162,14 +169,14 @@ cc.EditBoxDelegate = cc._Class.extend({ * This method is called when an edit box gains focus after keyboard is shown. * @param {cc.EditBox} sender */ - editBoxEditingDidBegin: function (sender) { + editBoxEditingDidBegan: function (sender) { }, /** * This method is called when an edit box loses focus after keyboard is hidden. * @param {cc.EditBox} sender */ - editBoxEditingDidEnd: function (sender) { + editBoxEditingDidEnded: function (sender) { }, /** @@ -188,6 +195,415 @@ cc.EditBoxDelegate = cc._Class.extend({ } }); +var EditBoxImpl = function(editBox) { + this._domInputSprite = null; + this._spriteDOM = null; + this._edTxt = null; + this._edFontSize = 14; + this._edFontName = 'Arial'; + this._editBox = editBox; + this._textLabel = null; + this._placeholderLabel = null; +}; + +EditBoxImpl.prototype = { + constructor: EditBoxImpl, + + createNativeControl: function(size) { + var tmpDOMSprite = this._domInputSprite = new _ccsg.Sprite(); + tmpDOMSprite.draw = function () {}; //redefine draw function + this._editBox.addChild(tmpDOMSprite); + this._spriteDOM = tmpDOMSprite; + + this._createDomTextArea(); + + cc.DOM.convert(tmpDOMSprite); + + this._addDomInputControl(); + + this._domInputSprite.dom.showTooltipDiv = false; + this._domInputSprite.dom.style.width = (size.width - 6) + 'px'; + this._domInputSprite.dom.style.height = (size.height - 6) + 'px'; + + tmpDOMSprite.canvas.remove(); + + this._domInputSprite.x = 3; + this._domInputSprite.y = 3; + + this._createLabels(); + }, + + _createLabels: function () { + var editBoxSize = this._editBox.getContentSize(); + this._textLabel = new _ccsg.Label(); + this._textLabel.setVisible(false); + this._textLabel.setAnchorPoint(cc.p(0, 1)); + this._editBox.addChild(this._textLabel, 100); + + this._placeholderLabel = new _ccsg.Label(); + this._placeholderLabel.setAnchorPoint(cc.p(0, 1)); + this._placeholderLabel.setColor(cc.Color.GRAY); + this._editBox.addChild(this._placeholderLabel, 100); + + this._updateLabelPosition(editBoxSize); + }, + + _updateLabelPosition: function (editBoxSize) { + var textLabelSize = this._textLabel.getContentSize(); + var placeholderLabelSize = this._placeholderLabel.getContentSize(); + this._placeholderLabel.setLineHeight(editBoxSize.height); + + if (this._editBox._editBoxInputMode === InputMode.ANY){ + this._textLabel.setPosition(cc.p(0, editBoxSize.height)); + this._placeholderLabel.setPosition(cc.p(0, editBoxSize.height)); + this._placeholderLabel.setVerticalAlign(cc.VerticalTextAlignment.TOP); + this._textLabel.setVerticalAlign(cc.VerticalTextAlignment.TOP); + } + else { + this._textLabel.setPosition(cc.p(0, (editBoxSize.height + textLabelSize.height) / 2)); + this._placeholderLabel.setPosition(cc.p(0, (editBoxSize.height + placeholderLabelSize.height) / 2)); + this._placeholderLabel.setVerticalAlign(cc.VerticalTextAlignment.CENTER); + this._textLabel.setVerticalAlign(cc.VerticalTextAlignment.CENTER); + } + + }, + + setLineHeight: function (lineHeight) { + this._textLabel.setLineHeight(lineHeight); + }, + + _hiddenLabels: function () { + this._textLabel.setVisible(false); + this._placeholderLabel.setVisible(false); + }, + + _updateLabelString: function() { + this._textLabel.setVisible(true); + this._textLabel.setString(this._editBox._text); + var inputFlag = this._editBox._editBoxInputFlag; + if (this._edTxt.type === 'password') { + var passwordString = ''; + var len = this._editBox._text.length; + for (var i = 0; i < len; ++i) { + passwordString += '\u25CF'; + } + this._textLabel.setString(passwordString); + } + else if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) { + this._textLabel.setString(this._editBox._text.toUpperCase()); + } + else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) { + this._textLabel.setString(capitalize(this._editBox._text)); + } + else if (inputFlag === InputFlag.INITIAL_CAPS_SENTENCE) { + this._textLabel.setString(capitalizeFirstLetter(this._editBox._text)); + } + }, + + _showLabels: function () { + this._hiddenLabels(); + if (this._edTxt.value === '') { + this._placeholderLabel.setVisible(true); + this._placeholderLabel.setString(this._editBox._placeholderText); + + } + else { + this._updateLabelString(); + } + }, + + registerClickEvent: function() { + var self = this; + var div = self._edTxt.parentNode; + div.style.pointerEvents = 'none'; + div.addEventListener('click', function() { + if (self._edTxt.style.display === 'none') { + self._edTxt.style.display = ''; + self._edTxt.focus(); + self._hiddenLabels(); + } + }); + }, + + show: function() { + var div = this._edTxt.parentNode; + div.style.pointerEvents = ''; + window.setTimeout(function() { + div.click(); + }, 10); + }, + + hidden: function() { + this._edTxt.style.display = 'none'; + var div = this._edTxt.parentNode; + div.style.pointerEvents = 'none'; + this._showLabels(); + }, + + _setFont: function (fontStyle) { + var res = cc.LabelTTF._fontStyleRE.exec(fontStyle); + var textFontName = res[2]; + var textFontSize = parseInt(res[1]); + if (res) { + this.setFont(textFontName, textFontSize); + } + }, + + setFont: function (fontName, fontSize) { + this._edFontName = fontName || this._edFontName; + this._edFontSize = fontSize || this._edFontSize; + this._updateDOMFontStyle(); + }, + + setFontName: function (fontName) { + this._edFontName = fontName || this._edFontName; + this._updateDOMFontStyle(); + }, + + setFontSize: function (fontSize) { + this._edFontSize = fontSize || this._edFontSize; + this._updateDOMFontStyle(); + }, + + setFontColor: function (color) { + if (this._edTxt.value !== this._editBox._placeholderText) { + this._edTxt.style.color = cc.colorToHex(color); + } + this._textLabel.setColor(color); + }, + + setPlaceHolder: function (text) { + this._placeholderLabel.setString(text); + }, + + setMaxLength: function (maxLength) { + this._edTxt.maxLength = maxLength; + }, + + _updateDOMPlaceholderFontStyle: function () { + this._placeholderLabel.setFontFileOrFamily(this._editBox._placeholderFontName); + this._placeholderLabel.setFontSize(this._editBox._placeholderFontSize); + }, + + setPlaceholderFontColor: function (color) { + this._placeholderLabel.setColor(color); + }, + + setInputFlag: function (inputFlag) { + if ((this._edTxt.value !== this._placeholderText) && (inputFlag === InputFlag.PASSWORD)) + this._edTxt.type = 'password'; + else + this._edTxt.type = 'text'; + + this._edTxt.style.textTransform = 'none'; + + if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) { + this._edTxt.style.textTransform = 'uppercase'; + } + else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) { + this._edTxt.style.textTransform = 'capitalize'; + } + this._updateLabelString(); + }, + + setInputMode : function (inputMode) { + if (inputMode === InputMode.ANY) { + this._removeDomInputControl(); + this._createDomTextArea(); + this._addDomInputControl(); + } + else if(this._editBox._editBoxInputMode === InputMode.ANY) { + this._removeDomInputControl(); + this._createDomInput(); + this._addDomInputControl(); + } + }, + + /** + * Set the text entered in the edit box. + * @param {string} text The given text. + */ + setString: function (text) { + if (text !== null) { + this._edTxt.value = text; + + if (text === '') { + this._edTxt.type = 'text'; + this._placeholderLabel.setString(this._editBox._placeholderText); + this._placeholderLabel.setColor(this._editBox._placeholderColor); + this._placeholderLabel.setVisible(true); + this._textLabel.setVisible(false); + } + else { + this._edTxt.style.color = cc.colorToHex(this._editBox._textColor); + this._textLabel.setColor(this._editBox._textColor); + this._placeholderLabel.setVisible(false); + if (this._editBox._editBoxInputFlag === InputFlag.PASSWORD) { + this._edTxt.type = 'password'; + } + else { + this._edTxt.type = 'text'; + } + this._updateLabelString(); + } + } + }, + + _updateDOMFontStyle: function() { + if (this._edTxt.value !== '') { + this._edTxt.style.fontFamily = this._edFontName; + this._edTxt.style.fontSize = this._edFontSize + 'px'; + if (this._editBox._editBoxInputFlag === InputFlag.PASSWORD) + this._edTxt.type = 'password'; + else + this._edTxt.type = 'text'; + } + this._textLabel.setFontSize(this._edFontSize); + this._textLabel.setFontFileOrFamily(this._edFontName); + }, + + + setSize: function(newWidth, newHeight) { + this._spriteDOM.dom.style.width = (newWidth - 6) + 'px'; + this._spriteDOM.dom.style.height = (newHeight - 6) + 'px'; + this._updateLabelPosition(cc.size(newWidth, newHeight)); + }, + + _createDomInput: function () { + var selfPointer = this; + var tmpEdTxt = this._edTxt = document.createElement('input'); + tmpEdTxt.type = 'text'; + tmpEdTxt.style.fontSize = this._edFontSize + 'px'; + tmpEdTxt.style.color = '#000000'; + tmpEdTxt.style.border = 0; + tmpEdTxt.style.background = 'transparent'; + //tmpEdTxt.style.paddingLeft = '2px'; + tmpEdTxt.style.width = '100%'; + tmpEdTxt.style.height = '100%'; + tmpEdTxt.style.active = 0; + tmpEdTxt.style.outline = 'medium'; + tmpEdTxt.style.padding = '0'; + tmpEdTxt.style.textTransform = 'uppercase'; + tmpEdTxt.style.display = 'none'; + var onCanvasClick = function() { tmpEdTxt.blur();}; + + tmpEdTxt.addEventListener('input', function () { + var editBox = selfPointer._editBox; + if (editBox._delegate && editBox._delegate.editBoxTextChanged) + editBox._delegate.editBoxTextChanged(editBox, this.value); + }); + tmpEdTxt.addEventListener('keypress', function (e) { + var editBox = selfPointer._editBox; + + if (e.keyCode === cc.KEY.enter) { + e.stopPropagation(); + e.preventDefault(); + if(this.value === '') { + this.style.fontSize = editBox._placeholderFontSize + 'px'; + this.style.color = cc.colorToHex(editBox._placeholderColor); + } + editBox._text = this.value; + selfPointer.hidden(); + if (editBox._delegate && editBox._delegate.editBoxReturn) + editBox._delegate.editBoxReturn(editBox); + cc._canvas.focus(); + } + }); + tmpEdTxt.addEventListener('focus', function () { + var editBox = selfPointer._editBox; + + this.style.fontSize = selfPointer._edFontSize + 'px'; + this.style.color = cc.colorToHex(editBox._textColor); + if (editBox._editBoxInputFlag === InputFlag.PASSWORD) + selfPointer._edTxt.type = 'password'; + else + selfPointer._edTxt.type = 'text'; + + if (editBox._delegate && editBox._delegate.editBoxEditingDidBegan) + editBox._delegate.editBoxEditingDidBegan(editBox); + cc._canvas.addEventListener('click', onCanvasClick); + }); + tmpEdTxt.addEventListener('blur', function () { + var editBox = selfPointer._editBox; + editBox._text = this.value; + + if (editBox._delegate && editBox._delegate.editBoxEditingDidEnded) + editBox._delegate.editBoxEditingDidEnded(editBox); + cc._canvas.removeEventListener('click', onCanvasClick); + if (this.value === '') { + this.style.fontSize = editBox._placeholderFontSize + 'px'; + this.style.color = cc.colorToHex(editBox._placeholderColor); + } + selfPointer.hidden(); + }); + return tmpEdTxt; + }, + + _createDomTextArea: function () { + var selfPointer = this; + var tmpEdTxt = this._edTxt = document.createElement('textarea'); + tmpEdTxt.type = 'text'; + tmpEdTxt.style.fontSize = this._edFontSize + 'px'; + tmpEdTxt.style.color = '#000000'; + tmpEdTxt.style.border = 0; + tmpEdTxt.style.background = 'transparent'; + //tmpEdTxt.style.paddingLeft = '2px'; + tmpEdTxt.style.width = '100%'; + tmpEdTxt.style.height = '100%'; + tmpEdTxt.style.active = 0; + tmpEdTxt.style.outline = 'medium'; + tmpEdTxt.style.padding = '0'; + tmpEdTxt.style.resize = 'none'; + tmpEdTxt.style.textTransform = 'uppercase'; + tmpEdTxt.style.overflow_y = 'scroll'; + tmpEdTxt.style.display = 'none'; + var onCanvasClick = function() { tmpEdTxt.blur();}; + + tmpEdTxt.addEventListener('input', function () { + var editBox = selfPointer._editBox; + if (editBox._delegate && editBox._delegate.editBoxTextChanged) + editBox._delegate.editBoxTextChanged(editBox, this.value); + }); + + tmpEdTxt.addEventListener('focus', function () { + var editBox = selfPointer._editBox; + + this.style.fontSize = selfPointer._edFontSize + 'px'; + this.style.color = cc.colorToHex(editBox._textColor); + + if (editBox._delegate && editBox._delegate.editBoxEditingDidBegan) + editBox._delegate.editBoxEditingDidBegan(editBox); + + cc._canvas.addEventListener('click', onCanvasClick); + }); + tmpEdTxt.addEventListener('blur', function () { + var editBox = selfPointer._editBox; + editBox._text = this.value; + + if (editBox._delegate && editBox._delegate.editBoxEditingDidEnded) + editBox._delegate.editBoxEditingDidEnded(editBox); + + if (this.value === '') { + this.style.fontSize = editBox._placeholderFontSize + 'px'; + this.style.color = cc.colorToHex(editBox._placeholderColor); + } + + selfPointer.hidden(); + cc._canvas.removeEventListener('click', onCanvasClick); + }); + + return tmpEdTxt; + }, + + _removeDomInputControl: function() { + this._domInputSprite.dom.removeChild(this._edTxt); + }, + + _addDomInputControl: function () { + this._domInputSprite.dom.appendChild(this._edTxt); + }, +}; + /** *

cc.EditBox is a brief Class for edit box.
* You can use this widget to gather small amounts of text from the user.

@@ -213,143 +629,27 @@ cc.EditBoxDelegate = cc._Class.extend({ * */ _ccsg.EditBox = _ccsg.Node.extend({ - _domInputSprite: null, _backgroundSprite: null, - _spriteDOM: null, _delegate: null, _editBoxInputMode: InputMode.ANY, _editBoxInputFlag: InputFlag.SENSITIVE, _keyboardReturnType: KeyboardReturnType.DEFAULT, + _maxLength: 50, + _nativeControl: null, _text: '', - _placeholderText: '', _textColor: null, - _placeholderColor: null, - _maxLength: 50, - _adjustHeight: 18, - - _edTxt: null, - _edFontSize: 14, - _edFontName: 'Arial', + _placeholderText: '', _placeholderFontName: '', _placeholderFontSize: 14, + _placeholderColor: null, + _adjustHeight: 18, _tooltip: false, _className: 'EditBox', - _createDomInput: function () { - var selfPointer = this; - var tmpEdTxt = this._edTxt = document.createElement('input'); - tmpEdTxt.type = 'text'; - tmpEdTxt.style.fontSize = this._edFontSize + 'px'; - tmpEdTxt.style.color = '#000000'; - tmpEdTxt.style.border = 0; - tmpEdTxt.style.background = 'transparent'; - //tmpEdTxt.style.paddingLeft = '2px'; - tmpEdTxt.style.width = '100%'; - tmpEdTxt.style.height = '100%'; - tmpEdTxt.style.active = 0; - tmpEdTxt.style.outline = 'medium'; - tmpEdTxt.style.padding = '0'; - tmpEdTxt.style.textTransform = 'uppercase'; - var onCanvasClick = function() { tmpEdTxt.blur();}; - - // TODO the event listener will be remove when EditBox removes from parent. - tmpEdTxt.addEventListener('input', function () { - if (selfPointer._delegate && selfPointer._delegate.editBoxTextChanged) - selfPointer._delegate.editBoxTextChanged(selfPointer, this.value); - }); - tmpEdTxt.addEventListener('keypress', function (e) { - if (e.keyCode === cc.KEY.enter) { - e.stopPropagation(); - e.preventDefault(); - if (selfPointer._delegate && selfPointer._delegate.editBoxReturn) - selfPointer._delegate.editBoxReturn(selfPointer); - cc._canvas.focus(); - } - }); - tmpEdTxt.addEventListener('focus', function () { - if (this.value === selfPointer._placeholderText) { - this.value = ''; - this.style.fontSize = selfPointer._edFontSize + 'px'; - this.style.color = cc.colorToHex(selfPointer._textColor); - if (selfPointer._editBoxInputFlag === InputFlag.PASSWORD) - selfPointer._edTxt.type = 'password'; - else - selfPointer._edTxt.type = 'text'; - } - if (selfPointer._delegate && selfPointer._delegate.editBoxEditingDidBegin) - selfPointer._delegate.editBoxEditingDidBegin(selfPointer); - cc._canvas.addEventListener('click', onCanvasClick); - }); - tmpEdTxt.addEventListener('blur', function () { - if (this.value === '') { - this.value = selfPointer._placeholderText; - this.style.fontSize = selfPointer._placeholderFontSize + 'px'; - this.style.color = cc.colorToHex(selfPointer._placeholderColor); - selfPointer._edTxt.type = 'text'; - } - if (selfPointer._delegate && selfPointer._delegate.editBoxEditingDidEnd) - selfPointer._delegate.editBoxEditingDidEnd(selfPointer); - cc._canvas.removeEventListener('click', onCanvasClick); - }); - return tmpEdTxt; - }, - - _createDomTextArea: function () { - var selfPointer = this; - var tmpEdTxt = this._edTxt = document.createElement('textarea'); - tmpEdTxt.type = 'text'; - tmpEdTxt.style.fontSize = this._edFontSize + 'px'; - tmpEdTxt.style.color = '#000000'; - tmpEdTxt.style.border = 0; - tmpEdTxt.style.background = 'transparent'; - //tmpEdTxt.style.paddingLeft = '2px'; - tmpEdTxt.style.width = '100%'; - tmpEdTxt.style.height = '100%'; - tmpEdTxt.style.active = 0; - tmpEdTxt.style.outline = 'medium'; - tmpEdTxt.style.padding = '0'; - tmpEdTxt.style.textTransform = 'uppercase'; - var onCanvasClick = function() { tmpEdTxt.blur();}; - - // TODO the event listener will be remove when EditBox removes from parent. - tmpEdTxt.addEventListener('input', function () { - if (selfPointer._delegate && selfPointer._delegate.editBoxTextChanged) - selfPointer._delegate.editBoxTextChanged(selfPointer, this.value); - }); - - tmpEdTxt.addEventListener('focus', function () { - if (this.value === selfPointer._placeholderText) { - this.value = ''; - this.style.fontSize = selfPointer._edFontSize + 'px'; - this.style.color = cc.colorToHex(selfPointer._textColor); - } - if (selfPointer._delegate && selfPointer._delegate.editBoxEditingDidBegin) - selfPointer._delegate.editBoxEditingDidBegin(selfPointer); - cc._canvas.addEventListener('click', onCanvasClick); - }); - tmpEdTxt.addEventListener('blur', function () { - if (this.value === '') { - this.value = selfPointer._placeholderText; - this.style.fontSize = selfPointer._placeholderFontSize + 'px'; - this.style.color = cc.colorToHex(selfPointer._placeholderColor); - } - if (selfPointer._delegate && selfPointer._delegate.editBoxEditingDidEnd) - selfPointer._delegate.editBoxEditingDidEnd(selfPointer); - cc._canvas.removeEventListener('click', onCanvasClick); - }); - return tmpEdTxt; - }, - - _removeDomInputControl: function() { - this._domInputSprite.dom.removeChild(this._edTxt); - }, - - - /** * constructor of cc.EditBox * @param {cc.Size} size @@ -357,10 +657,6 @@ _ccsg.EditBox = _ccsg.Node.extend({ * @param {cc.Scale9Sprite} press9SpriteBg * @param {cc.Scale9Sprite} disabled9SpriteBg */ - _addDomInputControl: function () { - this._domInputSprite.dom.appendChild(this._edTxt); - }, - ctor: function (size, normal9SpriteBg, press9SpriteBg, disabled9SpriteBg) { _ccsg.Node.prototype.ctor.call(this); @@ -368,29 +664,47 @@ _ccsg.EditBox = _ccsg.Node.extend({ this._placeholderColor = cc.Color.GRAY; _ccsg.Node.prototype.setContentSize.call(this, size); - var tmpDOMSprite = this._domInputSprite = new _ccsg.Sprite(); - tmpDOMSprite.draw = function () {}; //redefine draw function - this.addChild(tmpDOMSprite); - this._spriteDOM = tmpDOMSprite; - - this._createDomTextArea(); - - cc.DOM.convert(tmpDOMSprite); - - this._addDomInputControl(); + var editBoxImpl = this._nativeControl = new EditBoxImpl(this); + editBoxImpl.createNativeControl(size); //because cc.DOM.convert will replace editbox's setContentSize method. //here is a hack to provide a better version of setContentSize. this._oldSetContentSize = this.setContentSize; this.setContentSize = this._updateEditBoxSize; - this._domInputSprite.dom.showTooltipDiv = false; - this._domInputSprite.dom.style.width = (size.width - 6) + 'px'; - this._domInputSprite.dom.style.height = (size.height - 6) + 'px'; - - tmpDOMSprite.canvas.remove(); - this.initWithSizeAndBackgroundSprite(size, normal9SpriteBg); + this._registerTouchEvent(); + + this.scheduleOnce(function () { + editBoxImpl.registerClickEvent(); + }, 0.01); + }, + + _registerTouchEvent: function() { + var touchListener = cc.EventListener.create({ + event: cc.EventListener.TOUCH_ONE_BY_ONE, + swallowTouches: true, + onTouchBegan: this._onTouchBegan.bind(this), + onTouchEnded: this._onTouchEnded.bind(this), + }); + cc.eventManager.addListener(touchListener, this); + }, + + _onTouchBegan: function (touch, event) { + var touchPoint = touch.getLocation(); + var bb = cc.rect(0,0, this._contentSize.width, this._contentSize.height); + var hitted = cc.rectContainsPoint(bb, this.convertToNodeSpace(touchPoint)); + if(hitted) { + return true; + } + else { + this._nativeControl.hidden(); + return false; + } + }, + + _onTouchEnded: function (touch, event) { + this._nativeControl.show(); }, _updateBackgroundSpriteSizeAndPosition: function (width, height) { @@ -407,11 +721,11 @@ _ccsg.EditBox = _ccsg.Node.extend({ var newHeight = size.height || height; this._updateBackgroundSpriteSizeAndPosition(newWidth, newHeight); + this._nativeControl.setSize(newWidth, newHeight); + }, - this._spriteDOM.dom.style.width = (newWidth - 6) + 'px'; - this._spriteDOM.dom.style.height = (newHeight - 6) + 'px'; - - this.setFontSize(height * 2 / 3); + setLineHeight: function (lineHeight) { + this._nativeControl.setLineHeight(lineHeight); }, /** @@ -420,18 +734,11 @@ _ccsg.EditBox = _ccsg.Node.extend({ * @param {Number} fontSize The font size. */ setFont: function (fontName, fontSize) { - this._edFontSize = fontSize; - this._edFontName = fontName; - this._setFontToEditBox(); + this._nativeControl.setFont(fontName, fontSize); }, _setFont: function (fontStyle) { - var res = cc.LabelTTF._fontStyleRE.exec(fontStyle); - if (res) { - this._edFontSize = parseInt(res[1]); - this._edFontName = res[2]; - this._setFontToEditBox(); - } + this._nativeControl._setFont(fontStyle); }, getBackgroundSprite: function() { @@ -443,8 +750,7 @@ _ccsg.EditBox = _ccsg.Node.extend({ * @param {String} fontName */ setFontName: function (fontName) { - this._edFontName = fontName; - this._setFontToEditBox(); + this._nativeControl.setFontName(fontName); }, /** @@ -452,19 +758,7 @@ _ccsg.EditBox = _ccsg.Node.extend({ * @param {Number} fontSize */ setFontSize: function (fontSize) { - this._edFontSize = fontSize; - this._setFontToEditBox(); - }, - - _setFontToEditBox: function () { - if (this._edTxt.value !== this._placeholderText) { - this._edTxt.style.fontFamily = this._edFontName; - this._edTxt.style.fontSize = this._edFontSize + 'px'; - if (this._editBoxInputFlag === InputFlag.PASSWORD) - this._edTxt.type = 'password'; - else - this._edTxt.type = 'text'; - } + this._nativeControl.setFontSize(fontSize); }, /** @@ -477,28 +771,12 @@ _ccsg.EditBox = _ccsg.Node.extend({ this.setString(text); }, - /** - * Set the text entered in the edit box. - * @param {string} text The given text. - */ setString: function (text) { - if (text !== null) { - if (text === '') { - this._edTxt.value = this._placeholderText; - this._edTxt.style.color = cc.colorToHex(this._placeholderColor); - this._edTxt.type = 'text'; - } else { - if (text.length >= this._maxLength) { - text = text.slice(0, this._maxLength); - } - this._edTxt.value = text; - this._edTxt.style.color = cc.colorToHex(this._textColor); - if (this._editBoxInputFlag === InputFlag.PASSWORD) - this._edTxt.type = 'password'; - else - this._edTxt.type = 'text'; - } + if (text.length >= this._maxLength) { + text = text.slice(0, this._maxLength); } + this._text = text; + this._nativeControl.setString(text); }, /** @@ -507,9 +785,7 @@ _ccsg.EditBox = _ccsg.Node.extend({ */ setFontColor: function (color) { this._textColor = color; - if (this._edTxt.value !== this._placeholderText) { - this._edTxt.style.color = cc.colorToHex(color); - } + this._nativeControl.setFontColor(color); }, /** @@ -522,7 +798,7 @@ _ccsg.EditBox = _ccsg.Node.extend({ setMaxLength: function (maxLength) { if (!isNaN(maxLength) && maxLength > 0) { this._maxLength = maxLength; - this._edTxt.maxLength = maxLength; + this._nativeControl.setMaxLength(maxLength); } }, @@ -540,13 +816,9 @@ _ccsg.EditBox = _ccsg.Node.extend({ */ setPlaceHolder: function (text) { if (text !== null) { - var oldPlaceholderText = this._placeholderText; + //Note: the following calling order matters + this._nativeControl.setPlaceHolder(text); this._placeholderText = text; - if (this._edTxt.value === oldPlaceholderText) { - this._edTxt.value = text; - this._edTxt.style.color = cc.colorToHex(this._placeholderColor); - this._setPlaceholderFontToEditText(); - } } }, @@ -558,14 +830,15 @@ _ccsg.EditBox = _ccsg.Node.extend({ setPlaceholderFont: function (fontName, fontSize) { this._placeholderFontName = fontName; this._placeholderFontSize = fontSize; - this._setPlaceholderFontToEditText(); + this._nativeControl._updateDOMPlaceholderFontStyle(); }, + _setPlaceholderFont: function (fontStyle) { var res = cc.LabelTTF._fontStyleRE.exec(fontStyle); if (res) { this._placeholderFontName = res[2]; this._placeholderFontSize = parseInt(res[1]); - this._setPlaceholderFontToEditText(); + this._nativeControl._updateDOMPlaceholderFontStyle(); } }, @@ -575,7 +848,7 @@ _ccsg.EditBox = _ccsg.Node.extend({ */ setPlaceholderFontName: function (fontName) { this._placeholderFontName = fontName; - this._setPlaceholderFontToEditText(); + this._nativeControl._updateDOMPlaceholderFontStyle(); }, /** @@ -584,15 +857,7 @@ _ccsg.EditBox = _ccsg.Node.extend({ */ setPlaceholderFontSize: function (fontSize) { this._placeholderFontSize = fontSize; - this._setPlaceholderFontToEditText(); - }, - - _setPlaceholderFontToEditText: function () { - if (this._edTxt.value === this._placeholderText) { - this._edTxt.style.fontFamily = this._placeholderFontName; - this._edTxt.style.fontSize = this._placeholderFontSize + 'px'; - this._edTxt.type = 'text'; - } + this._nativeControl._updateDOMPlaceholderFontStyle(); }, /** @@ -601,9 +866,7 @@ _ccsg.EditBox = _ccsg.Node.extend({ */ setPlaceholderFontColor: function (color) { this._placeholderColor = color; - if (this._edTxt.value === this._placeholderText) { - this._edTxt.style.color = cc.colorToHex(color); - } + this._nativeControl.setPlaceholderFontColor(color); }, /** @@ -613,20 +876,7 @@ _ccsg.EditBox = _ccsg.Node.extend({ */ setInputFlag: function (inputFlag) { this._editBoxInputFlag = inputFlag; - if ((this._edTxt.value !== this._placeholderText) && (inputFlag === InputFlag.PASSWORD)) - this._edTxt.type = 'password'; - else - this._edTxt.type = 'text'; - - if (inputFlag === InputFlag.SENSITIVE || inputFlag === InputFlag.PASSWORD) { - this._edTxt.style.textTransform = 'none'; - } - else if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) { - this._edTxt.style.textTransform = 'uppercase'; - } - else if (inputFlag === InputFlag.INITIAL_CAPS_SENTENCE || inputFlag === InputFlag.INITIAL_CAPS_WORD) { - this._edTxt.style.textTransform = 'capitalize'; - } + this._nativeControl.setInputFlag(inputFlag); }, /** @@ -636,7 +886,7 @@ _ccsg.EditBox = _ccsg.Node.extend({ */ getText: function () { cc.log('Please use the getString'); - return this._edTxt.value; + return this.getString(); }, /** @@ -644,9 +894,7 @@ _ccsg.EditBox = _ccsg.Node.extend({ * @return {string} */ getString: function () { - if(this._edTxt.value === this._placeholderText) - return ''; - return this._edTxt.value; + return this._text; }, /** @@ -655,16 +903,17 @@ _ccsg.EditBox = _ccsg.Node.extend({ * @param {cc.Color | cc.Scale9Sprite} normal9SpriteBg */ initWithSizeAndBackgroundSprite: function (size, normal9SpriteBg) { + if(this._backgroundSprite) { + this._backgroundSprite.removeFromParent(); + } this._backgroundSprite = normal9SpriteBg; - if(this._backgroundSprite) { + if(this._backgroundSprite && !this._backgroundSprite.parent) { this.addChild(this._backgroundSprite); this._updateBackgroundSpriteSizeAndPosition(size.width, size.height); } - this._domInputSprite.x = 3; - this._domInputSprite.y = 3; this.x = 0; this.y = 0; @@ -698,19 +947,11 @@ _ccsg.EditBox = _ccsg.Node.extend({ var oldText = this.getString(); - if (inputMode === InputMode.ANY) { - this._removeDomInputControl(); - this._createDomTextArea(); - this._addDomInputControl(); - } - else if(this._editBoxInputMode === InputMode.ANY) { - this._removeDomInputControl(); - this._createDomInput(); - this._addDomInputControl(); - } + this._nativeControl.setInputMode(inputMode); this.setString(oldText); this._editBoxInputMode = inputMode; + this._nativeControl._updateLabelPosition(this.getContentSize()); }, /** @@ -774,19 +1015,19 @@ _p.maxLength; cc.defineGetterSetter(_p, 'maxLength', _p.getMaxLength, _p.setMaxLength); /** @expose */ _p.placeHolder; -cc.defineGetterSetter(_p, 'placeHolder', _p.getPlaceHolder, _p.setPlaceHolder); +cc.defineGetterSetter(_p, 'placeholder', _p.getPlaceHolder, _p.setPlaceHolder); /** @expose */ _p.placeHolderFont; -cc.defineGetterSetter(_p, 'placeHolderFont', null, _p._setPlaceholderFont); +cc.defineGetterSetter(_p, 'placeholderFont', null, _p._setPlaceholderFont); /** @expose */ _p.placeHolderFontName; -cc.defineGetterSetter(_p, 'placeHolderFontName', null, _p.setPlaceholderFontName); +cc.defineGetterSetter(_p, 'placeholderFontName', null, _p.setPlaceholderFontName); /** @expose */ _p.placeHolderFontSize; -cc.defineGetterSetter(_p, 'placeHolderFontSize', null, _p.setPlaceholderFontSize); +cc.defineGetterSetter(_p, 'placeholderFontSize', null, _p.setPlaceholderFontSize); /** @expose */ _p.placeHolderFontColor; -cc.defineGetterSetter(_p, 'placeHolderFontColor', null, _p.setPlaceholderFontColor); +cc.defineGetterSetter(_p, 'placeholderFontColor', null, _p.setPlaceholderFontColor); /** @expose */ _p.inputFlag; cc.defineGetterSetter(_p, 'inputFlag', null, _p.setInputFlag); diff --git a/cocos2d/core/editbox/CCdomNode.js b/cocos2d/core/editbox/CCdomNode.js index 1880ddb88e..d772073465 100644 --- a/cocos2d/core/editbox/CCdomNode.js +++ b/cocos2d/core/editbox/CCdomNode.js @@ -324,6 +324,7 @@ cc.DOM.methods = /** @lends cc.DOM# */{ * @param {Boolean} x */ setVisible:function (x) { + _ccsg.Node.prototype.setVisible.call(this, x); this._visible = x; this.setNodeDirty(); if (this.dom) @@ -602,7 +603,7 @@ cc.DOM.forSprite = function (x) { cc.DOM.placeHolder = function (x) { //creating a placeholder dom to simulate other ccNode in the hierachy x.dom = cc.$new('div'); - x.placeholder = true; + // x.placeholder = true; x.dom.style.position = 'absolute'; x.dom.style.bottom = 0; //x.dom.style.display='block'; diff --git a/cocos2d/core/event-manager/CCEventListener.js b/cocos2d/core/event-manager/CCEventListener.js index deeb05c800..32297380c9 100644 --- a/cocos2d/core/event-manager/CCEventListener.js +++ b/cocos2d/core/event-manager/CCEventListener.js @@ -141,7 +141,7 @@ cc.EventListener = cc._Class.extend(/** @lends cc.EventListener# */{ /** * Sets scene graph priority for this listener - * @param {_ccsg.Node|cc.Node} node + * @param {_ccsg.Node|Node} node * @private */ _setSceneGraphPriority: function (node) { diff --git a/cocos2d/core/event-manager/CCSystemEvent.js b/cocos2d/core/event-manager/CCSystemEvent.js index 23640f147e..e3b8442a20 100644 --- a/cocos2d/core/event-manager/CCSystemEvent.js +++ b/cocos2d/core/event-manager/CCSystemEvent.js @@ -145,6 +145,15 @@ JS.mixin(EventMouse.prototype, { this._prevY = y; }, + /** + * Returns the previous touch location. + * @method getPreviousLocation + * @return {Vec2} + */ + getPreviousLocation:function () { + return {x: this._prevX, y: this._prevY}; + }, + /** * Returns the delta distance from the previous location to current location. * @method getDelta @@ -305,7 +314,7 @@ EventMouse.BUTTON_8 = 7; * @param {Array} [touchArr=[]] - The array of the touches * @param {Boolean} [bubbles=false] - A boolean indicating whether the event bubbles up through the tree or not */ -EventTouch = function (touchArr, bubbles) { +var EventTouch = function (touchArr, bubbles) { cc.Event.call(this, cc.Event.TOUCH, bubbles); this._eventCode = 0; this._touches = touchArr || []; @@ -338,6 +347,106 @@ JS.mixin(EventTouch.prototype, { _setTouches: function (touches) { this._touches = touches; + }, + + /** + * Sets touch location. + * @method setLocation + * @param {Number} x + * @param {Number} y + */ + setLocation: function (x, y) { + this.touch && this.touch.setTouchInfo(this.touch.getID(), x, y); + }, + + /** + * Returns touch location. + * @method getLocation + * @return {Vec2} location + */ + getLocation: function () { + return this.touch ? this.touch.getLocation() : cc.v2(); + }, + + /** + * Returns the current touch location in screen coordinates. + * @method getLocationInView + * @return {Vec2} + */ + getLocationInView: function() { + return this.touch ? this.touch.getLocationInView() : cc.v2(); + }, + + /** + * Returns the previous touch location. + * @method getPreviousLocation + * @return {Vec2} + */ + getPreviousLocation:function () { + return this.touch ? this.touch.getPreviousLocation() : cc.v2(); + }, + + /** + * Returns the start touch location. + * @method getStartLocation + * @returns {Vec2} + */ + getStartLocation: function() { + return this.touch ? this.touch.getStartLocation() : cc.v2(); + }, + + /** + * Returns the id of cc.Touch. + * @method getID + * @return {Number} + */ + getID:function () { + return this.touch ? this.getID() : null; + }, + + /** + * Returns the delta distance from the previous location to current location. + * @method getDelta + * @return {Vec2} + */ + getDelta: function () { + return this.touch ? this.touch.getDelta() : cc.v2(); + }, + + /** + * Returns the X axis delta distance from the previous location to current location. + * @method getDeltaX + * @return {Number} + */ + getDeltaX: function () { + return this.touch ? this.touch.getDelta().x : 0; + }, + + /** + * Returns the Y axis delta distance from the previous location to current location. + * @method getDeltaY + * @return {Number} + */ + getDeltaY: function () { + return this.touch ? this.touch.getDelta().y : 0; + }, + + /** + * Returns location X axis data. + * @method getLocationX + * @returns {Number} + */ + getLocationX: function () { + return this.touch ? this.touch.getLocationX() : 0; + }, + + /** + * Returns location Y axis data. + * @method getLocationY + * @returns {Number} + */ + getLocationY: function () { + return this.touch ? this.touch.getLocationY() : 0; } }); diff --git a/cocos2d/core/event-manager/CCTouch.js b/cocos2d/core/event-manager/CCTouch.js index c9a7999b96..7a4c0b5716 100644 --- a/cocos2d/core/event-manager/CCTouch.js +++ b/cocos2d/core/event-manager/CCTouch.js @@ -108,7 +108,7 @@ cc.Touch = cc._Class.extend(/** @lends cc.Touch# */{ * @return {Vec2} */ getLocationInView: function() { - return {x: this._point.x, y: this._point.y}; + return {x: this._point.x, y: cc.view._designResolutionSize.height - this._point.y}; }, /** @@ -117,7 +117,7 @@ cc.Touch = cc._Class.extend(/** @lends cc.Touch# */{ * @return {Vec2} */ getPreviousLocationInView: function(){ - return {x: this._prevPoint.x, y: this._prevPoint.y}; + return {x: this._prevPoint.x, y: cc.view._designResolutionSize.height - this._prevPoint.y}; }, /** @@ -126,7 +126,7 @@ cc.Touch = cc._Class.extend(/** @lends cc.Touch# */{ * @return {Vec2} */ getStartLocationInView: function(){ - return {x: this._startPoint.x, y: this._startPoint.y}; + return {x: this._startPoint.x, y: cc.view._designResolutionSize.height - this._startPoint.y}; }, /** @@ -138,17 +138,6 @@ cc.Touch = cc._Class.extend(/** @lends cc.Touch# */{ return this._id; }, - /** - * Returns the id of cc.Touch. - * @method getId - * @return {Number} - * @deprecated since v3.0, please use getID() instead - */ - getId:function () { - cc.log("getId is deprecated. Please use getID instead.") - return this._id; - }, - /** * Sets information to touch. * @method setTouchInfo diff --git a/cocos2d/core/event/event.js b/cocos2d/core/event/event.js index af2e77ccbc..8e1b91218d 100644 --- a/cocos2d/core/event/event.js +++ b/cocos2d/core/event/event.js @@ -46,9 +46,9 @@ cc.Event = function(type, bubbles) { this.type = type; /** - * A reference to the target to which the event was originally dispatched. + * Indicate whether the event bubbles up through the tree or not. * @property bubbles - * @type {Object} + * @type {Boolean} */ this.bubbles = bubbles || false; diff --git a/cocos2d/core/label/CCSGLabel.js b/cocos2d/core/label/CCSGLabel.js index 3d54440457..b72fc7318a 100644 --- a/cocos2d/core/label/CCSGLabel.js +++ b/cocos2d/core/label/CCSGLabel.js @@ -328,7 +328,7 @@ _ccsg.Label = _ccsg.Node.extend({ this._resetBMFont(); //specify font family name directly - if (extName === null) { + if (!extName) { this._fontHandle = fontHandle; this._labelType = _ccsg.Label.Type.SystemFont; this._notifyLabelSkinDirty(); @@ -336,8 +336,6 @@ _ccsg.Label = _ccsg.Node.extend({ this.emit('load'); return; } - //add resource path - fontHandle = cc.path.join(cc.loader.resPath, fontHandle); this._isUseSystemFont = false; if (extName === ".ttf") { @@ -685,8 +683,7 @@ cc.BMFontHelper = { var longestLine = 0; var letterRight = 0; - var contentScaleFactor = cc.contentScaleFactor(); - var lineSpacing = this._lineSpacing * contentScaleFactor; + var lineSpacing = this._lineSpacing; var highestY = 0; var lowestY = 0; var letterDef = null; @@ -728,7 +725,7 @@ cc.BMFontHelper = { continue; } - var letterX = (nextLetterX + letterDef._offsetX * this._bmfontScale) / contentScaleFactor; + var letterX = nextLetterX + letterDef._offsetX * this._bmfontScale; if (this._isWrapText && this._maxLineWidth > 0 @@ -746,7 +743,7 @@ cc.BMFontHelper = { letterPosition.x = letterX; } - letterPosition.y = (nextTokenY - letterDef._offsetY * this._bmfontScale) / contentScaleFactor; + letterPosition.y = nextTokenY - letterDef._offsetY * this._bmfontScale; this._recordLetterInfo(letterPosition, character, letterIndex, lineIndex); if (letterIndex + 1 < this._horizontalKernings.length && letterIndex < textLen - 1) { @@ -788,7 +785,7 @@ cc.BMFontHelper = { this._linesWidth.push(letterRight); this._numberOfLines = lineIndex + 1; - this._textDesiredHeight = (this._numberOfLines * this._lineHeight * this._bmfontScale) / contentScaleFactor; + this._textDesiredHeight = this._numberOfLines * this._lineHeight * this._bmfontScale; if (this._numberOfLines > 1) { this._textDesiredHeight += (this._numberOfLines - 1) * this._lineSpacing; } @@ -1001,7 +998,7 @@ cc.BMFontHelper = { _updateBMFontScale: function() { if (this._labelType === _ccsg.Label.Type.BMFont) { var originalFontSize = this._fontAtlas._fontSize; - this._bmfontScale = this._fontSize * cc.contentScaleFactor() / originalFontSize; + this._bmfontScale = this._fontSize / originalFontSize; } else { this._bmfontScale = 1; } @@ -1047,8 +1044,6 @@ cc.BMFontHelper = { var letterDefinition = new cc.FontLetterDefinition(); var tempRect = locFontDict[fontDef].rect; - cc.rectPointsToPixels(tempRect); - letterDefinition._offsetX = locFontDict[fontDef].xOffset; letterDefinition._offsetY = locFontDict[fontDef].yOffset; @@ -1098,12 +1093,12 @@ cc.BMFontHelper = { this._resetBMFont(); var texture; - cc.loader.load(this._fontHandle, function(err, results) { + cc.loader.load(this._fontHandle, function(err, config) { if (err) { cc.log("_ccsg.Label._initBMFontWithString(): Impossible to create font. Please check file"); } - self._config = results[0]; + self._config = config; self._createFontChars(); texture = cc.textureCache.addImage(self._config.atlasName); var locIsLoaded = texture.isLoaded(); diff --git a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js index cc1c1fadd0..91ec94b505 100644 --- a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js +++ b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js @@ -180,6 +180,12 @@ node._labelSkinDirty = true; }; + proto._syncDisplayColor = function (parentColor) { + _ccsg.Node.RenderCmd.prototype._syncDisplayColor.call(this, parentColor); + var node = this._node; + node._labelSkinDirty = true; + }; + proto._calculateLabelFont = function(canvasSize) { var node = this._node; var paragraphedStrings = node._string.split('\n'); diff --git a/cocos2d/core/label/FNTLoader.js b/cocos2d/core/label/FNTLoader.js deleted file mode 100644 index eb73086bd2..0000000000 --- a/cocos2d/core/label/FNTLoader.js +++ /dev/null @@ -1,103 +0,0 @@ -cc._fntLoader = { - INFO_EXP: /info [^\n]*(\n|$)/gi, - COMMON_EXP: /common [^\n]*(\n|$)/gi, - PAGE_EXP: /page [^\n]*(\n|$)/gi, - CHAR_EXP: /char [^\n]*(\n|$)/gi, - KERNING_EXP: /kerning [^\n]*(\n|$)/gi, - ITEM_EXP: /\w+=[^ \r\n]+/gi, - INT_EXP: /^[\-]?\d+$/, - - _parseStrToObj: function (str) { - var arr = str.match(this.ITEM_EXP); - var obj = {}; - if (arr) { - for (var i = 0, li = arr.length; i < li; i++) { - var tempStr = arr[i]; - var index = tempStr.indexOf("="); - var key = tempStr.substring(0, index); - var value = tempStr.substring(index + 1); - if (value.match(this.INT_EXP)) value = parseInt(value); - else if (value[0] === '"') value = value.substring(1, value.length - 1); - obj[key] = value; - } - } - return obj; - }, - - /** - * Parse Fnt string. - * @param fntStr - * @param url - * @returns {{}} - */ - parseFnt: function (fntStr, url) { - var self = this, fnt = {}; - //padding - var infoObj = self._parseStrToObj(fntStr.match(self.INFO_EXP)[0]); - var paddingArr = infoObj["padding"].split(","); - var padding = { - left: parseInt(paddingArr[0]), - top: parseInt(paddingArr[1]), - right: parseInt(paddingArr[2]), - bottom: parseInt(paddingArr[3]) - }; - - //common - var commonObj = self._parseStrToObj(fntStr.match(self.COMMON_EXP)[0]); - fnt.commonHeight = commonObj["lineHeight"]; - //font size - fnt.fontSize = infoObj["size"]; - if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { - var texSize = cc.configuration.getMaxTextureSize(); - if (commonObj["scaleW"] > texSize.width || commonObj["scaleH"] > texSize.height) - cc.log("cc.LabelBMFont._parseCommonArguments(): page can't be larger than supported"); - } - if (commonObj["pages"] !== 1) cc.log("cc.LabelBMFont._parseCommonArguments(): only supports 1 page"); - - //page - var pageObj = self._parseStrToObj(fntStr.match(self.PAGE_EXP)[0]); - if (pageObj["id"] !== 0) cc.log("cc.LabelBMFont._parseImageFileName() : file could not be found"); - fnt.atlasName = cc.path.changeBasename(url, pageObj["file"]); - - //char - var charLines = fntStr.match(self.CHAR_EXP); - var fontDefDictionary = fnt.fontDefDictionary = {}; - for (var i = 0, li = charLines.length; i < li; i++) { - var charObj = self._parseStrToObj(charLines[i]); - var charId = charObj["id"]; - fontDefDictionary[charId] = { - rect: {x: charObj["x"], y: charObj["y"], width: charObj["width"], height: charObj["height"]}, - xOffset: charObj["xoffset"], - yOffset: charObj["yoffset"], - xAdvance: charObj["xadvance"] - }; - } - - //kerning - var kerningDict = fnt.kerningDict = {}; - var kerningLines = fntStr.match(self.KERNING_EXP); - if (kerningLines) { - for (var i = 0, li = kerningLines.length; i < li; i++) { - var kerningObj = self._parseStrToObj(kerningLines[i]); - kerningDict[(kerningObj["first"] << 16) | (kerningObj["second"] & 0xffff)] = kerningObj["amount"]; - } - } - return fnt; - }, - - /** - * load the fnt - * @param realUrl - * @param url - * @param res - * @param cb - */ - load: function (realUrl, url, res, cb) { - var self = this; - cc.loader.loadTxt(realUrl, function (err, txt) { - if (err) return cb(err); - cb(null, self.parseFnt(txt, url)); - }); - } -}; -cc.loader.register(["fnt"], cc._fntLoader); \ No newline at end of file diff --git a/cocos2d/core/labelttf/CCLabelTTF.js b/cocos2d/core/labelttf/CCLabelTTF.js index c7b406d5f3..28a9759a9e 100644 --- a/cocos2d/core/labelttf/CCLabelTTF.js +++ b/cocos2d/core/labelttf/CCLabelTTF.js @@ -272,7 +272,7 @@ cc.LabelTTF = _ccsg.Sprite.extend(/** @lends cc.LabelTTF# */{ * @return {cc.FontDefinition} */ getTextDefinition: function () { - return this._prepareTextDefinition(false); + return this._prepareTextDefinition(); }, /** @@ -535,18 +535,12 @@ cc.LabelTTF = _ccsg.Sprite.extend(/** @lends cc.LabelTTF# */{ this._renderCmd.setDirtyFlag(flags.colorDirty|flags.opacityDirty|flags.textDirty); }, - _prepareTextDefinition: function (adjustForResolution) { + _prepareTextDefinition: function () { var texDef = new cc.FontDefinition(); - if (adjustForResolution) { - texDef.fontSize = this._fontSize; - texDef.boundingWidth = cc.contentScaleFactor() * this._dimensions.width; - texDef.boundingHeight = cc.contentScaleFactor() * this._dimensions.height; - } else { - texDef.fontSize = this._fontSize; - texDef.boundingWidth = this._dimensions.width; - texDef.boundingHeight = this._dimensions.height; - } + texDef.fontSize = this._fontSize; + texDef.boundingWidth = this._dimensions.width; + texDef.boundingHeight = this._dimensions.height; texDef.fontName = this._fontName; texDef.textAlign = this._hAlignment; @@ -567,8 +561,8 @@ cc.LabelTTF = _ccsg.Sprite.extend(/** @lends cc.LabelTTF# */{ texDef.shadowBlur = this._shadowBlur; texDef.shadowOpacity = this._shadowOpacity; - texDef.shadowOffsetX = (adjustForResolution ? cc.contentScaleFactor() : 1) * this._shadowOffset.x; - texDef.shadowOffsetY = (adjustForResolution ? cc.contentScaleFactor() : 1) * this._shadowOffset.y; + texDef.shadowOffsetX = this._shadowOffset.x; + texDef.shadowOffsetY = this._shadowOffset.y; } else texDef._shadowEnabled = false; @@ -735,8 +729,7 @@ cc.LabelTTF = _ccsg.Sprite.extend(/** @lends cc.LabelTTF# */{ }, setTextureRect: function (rect, rotated, untrimmedSize) { - //set needConvert to false - _ccsg.Sprite.prototype.setTextureRect.call(this, rect, rotated, untrimmedSize, false); + _ccsg.Sprite.prototype.setTextureRect.call(this, rect, rotated, untrimmedSize); }, /** diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js new file mode 100644 index 0000000000..f295c760ee --- /dev/null +++ b/cocos2d/core/load-pipeline/CCLoader.js @@ -0,0 +1,245 @@ +/**************************************************************************** + Copyright (c) 2016 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +var JS = require('../platform/js'); +var Pipeline = require('./pipeline'); +var Downloader = require('./downloader'); +var Loader = require('./loader'); + +var downloader = new Downloader(); +var loader = new Loader(); + +/** + * Loader for resource loading process. It's a singleton object. + * @class loader + * @static + */ +cc.loader = new Pipeline([ + downloader, + loader +]); + + +JS.mixin(cc.loader, { + /** + * The downloader in cc.loader's pipeline, it's by default the first pipe. + * It's used to download files with several handlers: pure text, image, script, audio, font, uuid. + * You can add your own download function with addDownloadHandlers + * @property downloader + * @type {Object} + */ + downloader: downloader, + + /** + * The downloader in cc.loader's pipeline, it's by default the second pipe. + * It's used to parse downloaded content with several handlers: JSON, image, plist, fnt, uuid. + * You can add your own download function with addLoadHandlers + * @property loader + * @type {Object} + */ + loader: loader, + + /** + * Get XMLHttpRequest. + * @returns {XMLHttpRequest} + */ + getXMLHttpRequest: Pipeline.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) { + 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) { + 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(['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|Array} resources - Url list in an array + * @param {[Function]} progressCallback - Callback invoked when progression change + * @param {Function} completeCallback - Callback invoked when all resources loaded + */ + load: function(resources, progressCallback, completeCallback) { + if (completeCallback === undefined) { + completeCallback = progressCallback; + progressCallback = null; + } + + var singleRes = false; + if (!(resources instanceof Array)) { + resources = resources ? [resources] : []; + singleRes = true; + } + // Return directly if no resources + if (resources.length === 0) { + completeCallback && completeCallback.call(this, null, this._items); + } + + // Resolve callback + var error = null; + var checker = {}; + var totalCount = 0; + var completedCount = 0; + var self = this; + + function loadedCheck (item) { + checker[item.src] = item; + if (item.error) { + error = error || []; + error.push(item.src); + } + completedCount++; + + progressCallback && progressCallback.call(self, completedCount, totalCount, item); + + for (var url in checker) { + // Not done yet + if (!checker[url]) { + return; + } + } + // All url completed + if (completeCallback) { + if (singleRes) { + completeCallback.call(self, item.error, item.content); + } + else { + completeCallback.call(self, error, self._items); + } + } + } + + // Add loaded listeners + for (var i = 0; i < resources.length; ++i) { + var url = resources[i].src || resources[i]; + if (typeof url !== 'string') + continue; + var item = this._items.map[url]; + if ( !item || (item && !item.complete) ) { + this._items.add(url, loadedCheck); + checker[url] = null; + totalCount++; + } + else if (item && item.complete) { + checker[url] = item; + totalCount++; + completedCount++; + } + } + + // No new resources, complete directly + if (totalCount === completedCount) { + if (singleRes) { + var src = resources[0].src || resources[0]; + var result = this._items.map[src]; + completeCallback.call(this, result.error, result.content); + } + else { + completeCallback.call(this, null, this._items); + } + } + else { + this.flowIn(resources); + } + }, + + /** + * Get resource data by url. + * + * @method getRes + * @param {String} url + * @returns {*} + */ + getRes: function (url) { + var item = this._items.map[url]; + if (item && item.complete) { + return item.content; + } + else { + return null; + } + }, + + /** + * Release the cache of resource by url. + * + * @method release + * @param {String} url + */ + release: function (url) { + this.removeItem(url); + }, + + /** + * Resource cache of all resources. + * + * @method releaseAll + */ + releaseAll: function () { + this.clear(); + } +}); + +module.exports = cc.loader; \ No newline at end of file diff --git a/cocos2d/core/load-pipeline/audio-downloader.js b/cocos2d/core/load-pipeline/audio-downloader.js new file mode 100644 index 0000000000..4615333be2 --- /dev/null +++ b/cocos2d/core/load-pipeline/audio-downloader.js @@ -0,0 +1,177 @@ +/**************************************************************************** + Copyright (c) 2016 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the 'Software'), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +var Path = require('../utils/CCPath'); +var Sys = require('../platform/CCSys'); +var Pipeline = require('./pipeline'); +require('../../audio/CCAudio'); + +var __audioSupport = Sys.__audioSupport; +var formatSupport = __audioSupport.format; +var context = __audioSupport.context; + +function loadAudioFromExtList (url, typeList, audio, cb){ + if(typeList.length === 0){ + var ERRSTR = 'can not found the resource of audio! Last match url is : '; + ERRSTR += url.replace(/\.(.*)?$/, '('); + formatSupport.forEach(function(ext){ + ERRSTR += ext + '|'; + }); + ERRSTR = ERRSTR.replace(/\|$/, ')'); + return cb({status: 520, errorMessage: ERRSTR}, null); + } + + url = Path.changeExtname(url, typeList.splice(0, 1)); + + if (__audioSupport.WEB_AUDIO) {//Buffer + if (__audioSupport.webAudioCallback) { + __audioSupport.webAudioCallback(url); + } + var request = Pipeline.getXMLHttpRequest(); + request.open('GET', url, true); + request.responseType = 'arraybuffer'; + + request.onload = function () { + context['decodeAudioData'](request.response, function (buffer) { + //success + audio.setBuffer(buffer); + cb(null, audio); + }, function() { + //error + loadAudioFromExtList(url, typeList, audio, cb); + }); + }; + + request.onerror = function () { + cb({status: 520, errorMessage: ERRSTR}, null); + }; + + request.send(); + } else {//DOM + var element = document.createElement('audio'); + var cbCheck = false; + var termination = false; + + var timer = setTimeout(function () { + if (element.readyState === 0) { + emptied(); + } else { + termination = true; + element.pause(); + document.body.removeChild(element); + cb('Audio load timeout : ' + url, audio); + } + }, 8000); + + var success = function () { + if (!cbCheck) { + //element.pause(); + try { + element.currentTime = 0; + element.volume = 1; + } catch (e) {} + document.body.removeChild(element); + audio.setElement(element); + element.removeEventListener('canplaythrough', success, false); + element.removeEventListener('error', failure, false); + element.removeEventListener('emptied', emptied, false); + !termination && cb(null, audio); + cbCheck = true; + clearTimeout(timer); + } + }; + + var failure = function(){ + if (!cbCheck) return; + //element.pause(); + document.body.removeChild(element); + element.removeEventListener('canplaythrough', success, false); + element.removeEventListener('error', failure, false); + element.removeEventListener('emptied', emptied, false); + !termination && loadAudioFromExtList(url, typeList, audio, cb); + cbCheck = true; + clearTimeout(timer); + }; + + var emptied = function(){ + termination = true; + success(); + cb(null, audio); + }; + + element.addEventListener('canplaythrough', success, false); + element.addEventListener('error', failure, false); + if(__audioSupport.USE_EMPTIED_EVENT) + element.addEventListener('emptied', emptied, false); + + element.src = url; + document.body.appendChild(element); + element.volume = 0; + //some browsers cannot pause(qq 6.1) + //element.play(); + } +} + +function downloadAudio (item, callback) { + if (formatSupport.length === 0) { + return callback( new Error('Audio Downloader: audio not supported on this browser!') ); + } + + var url = item.src, + extname = Path.extname(url), + typeList = [extname], + i, audio; + + // Generate all types + for (i = 0; i < formatSupport.length; i++) { + if (extname !== formatSupport[i]) { + typeList.push(formatSupport[i]); + } + } + + if (__audioSupport.WEB_AUDIO) { + try { + var volume = context['createGain'](); + volume['gain'].value = 1; + volume['connect'](context['destination']); + audio = new cc.Audio(context, volume, url); + if (__audioSupport.NEED_MANUAL_LOOP) { + audio._manualLoop = true; + } + } catch(err) { + __audioSupport.WEB_AUDIO = false; + cc.warn('The current browser don\'t support web audio'); + audio = new cc.Audio(null, null, url); + } + } else { + audio = new cc.Audio(null, null, url); + } + + // hack for audio to be found before loaded + item.content = audio; + loadAudioFromExtList(url, typeList, audio, callback); +} + + +module.exports = downloadAudio; \ No newline at end of file diff --git a/cocos2d/core/load-pipeline/binary-downloader.js b/cocos2d/core/load-pipeline/binary-downloader.js new file mode 100644 index 0000000000..d302956c21 --- /dev/null +++ b/cocos2d/core/load-pipeline/binary-downloader.js @@ -0,0 +1,117 @@ +/**************************************************************************** + Copyright (c) 2015-2016 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the 'Software'), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +function _str2Uint8Array (strData) { + if (!strData) + return null; + + var arrData = new Uint8Array(strData.length); + for (var i = 0; i < strData.length; i++) { + arrData[i] = strData.charCodeAt(i) & 0xff; + } + return arrData; +} + +var navigator = window.navigator; + +var _IEFilter = (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)); + +//Compatibility with IE9 +window.Uint8Array = window.Uint8Array || window.Array; + +if (_IEFilter) { + var IEBinaryToArray_ByteStr_Script = + '\r\n' + + //'\r\n'; + + // inject VBScript + //document.write(IEBinaryToArray_ByteStr_Script); + var myVBScript = document.createElement('script'); + myVBScript.type = 'text/vbscript'; + myVBScript.textContent = IEBinaryToArray_ByteStr_Script; + document.body.appendChild(myVBScript); + + // helper to convert from responseBody to a 'responseText' like thing + var _convertResponseBodyToText = function(binary) { + var byteMapping = {}; + for (var i = 0; i < 256; i++) { + for (var j = 0; j < 256; j++) { + byteMapping[ String.fromCharCode(i + j * 256) ] = + String.fromCharCode(i) + String.fromCharCode(j); + } + } + var rawBytes = IEBinaryToArray_ByteStr(binary); + var lastChr = IEBinaryToArray_ByteStr_Last(binary); + return rawBytes.replace(/[\s\S]/g, + function (match) { + return byteMapping[match]; + }) + lastChr; + }; +} + +function downloadBinary (url, callback) { + var self = this; + var xhr = this.getXMLHttpRequest(), + errInfo = 'Load ' + url + ' failed!'; + xhr.open('GET', url, true); + if (_IEFilter) { + // IE-specific logic here + xhr.setRequestHeader('Accept-Charset', 'x-user-defined'); + xhr.onreadystatechange = function () { + if (xhr.readyState === 4 && (xhr.status === 200 || (CC_TEST && xhr.status === 0))) { + var fileContents = _convertResponseBodyToText(xhr['responseBody']); + callback(null, self._str2Uint8Array(fileContents)); + } + else { + callback(errInfo); + } + }; + } else { + if (xhr.overrideMimeType) xhr.overrideMimeType('text\/plain; charset=x-user-defined'); + xhr.onload = function () { + if (xhr.readyState === 4 && (xhr.status === 200 || (CC_TEST && xhr.status === 0))) { + callback(null, self._str2Uint8Array(xhr.responseText)); + } + else { + callback(errInfo); + } + }; + } + xhr.send(null); +}; + +module.exports = downloadBinary; \ No newline at end of file diff --git a/cocos2d/core/load-pipeline/downloader.js b/cocos2d/core/load-pipeline/downloader.js new file mode 100644 index 0000000000..8e6f43a3d3 --- /dev/null +++ b/cocos2d/core/load-pipeline/downloader.js @@ -0,0 +1,403 @@ +/**************************************************************************** + Copyright (c) 2016 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +var JS = require('../platform/js'); +var Path = require('../utils/CCPath'); +var Pipeline = require('./pipeline'); + +var downloadAudio; +if (!CC_EDITOR || !Editor.isCoreLevel) { + downloadAudio = require('./audio-downloader'); +} +else { + downloadAudio = null; +} +// var downloadBinary = require('binary-downloader'); + +var _noCacheRex = /\?/; +function urlAppendTimestamp (url) { + if (cc.game.config['noCache'] && typeof url === 'string') { + if(_noCacheRex.test(url)) + url += '&_t=' + (new Date() - 0); + else + url += '?_t=' + (new Date() - 0); + } + return url; +} + +function downloadScript (item, callback, isAsync) { + var url = item.src, + d = document, + s = document.createElement('script'); + s.async = isAsync; + s.src = urlAppendTimestamp(url); + function loadHandler () { + s.parentNode.removeChild(s); + s.removeEventListener('load', loadHandler, false); + s.removeEventListener('error', errorHandler, false); + callback(null, url); + } + function errorHandler() { + s.parentNode.removeChild(s); + s.removeEventListener('load', loadHandler, false); + s.removeEventListener('error', errorHandler, false); + callback(new Error('Load ' + url + ' failed!'), url); + } + s.addEventListener('load', loadHandler, false); + s.addEventListener('error', errorHandler, false); + d.body.appendChild(s); +} + +function downloadText (item, callback) { + var url = item.src, + xhr = Pipeline.getXMLHttpRequest(), + errInfo = 'Load ' + url + ' failed!', + navigator = window.navigator; + + url = urlAppendTimestamp(url); + + xhr.open('GET', url, true); + if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) { + // IE-specific logic here + xhr.setRequestHeader('Accept-Charset', 'utf-8'); + xhr.onreadystatechange = function () { + if(xhr.readyState === 4) { + if (xhr.status === 200 || xhr.status === 0) { + callback(null, xhr.responseText); + } + else { + callback({status:xhr.status, errorMessage:errInfo}); + } + } + }; + } else { + if (xhr.overrideMimeType) xhr.overrideMimeType('text\/plain; charset=utf-8'); + xhr.onload = function () { + if(xhr.readyState === 4) { + if (xhr.status === 200 || xhr.status === 0) { + callback(null, xhr.responseText); + } + else { + callback({status:xhr.status, errorMessage:errInfo}); + } + } + }; + xhr.onerror = function(){ + callback({status:xhr.status, errorMessage:errInfo}); + }; + } + xhr.send(null); +} + +function downloadTextSync (item) { + var url = item.src; + var xhr = Pipeline.getXMLHttpRequest(); + xhr.open('GET', url, false); + if (/msie/i.test(window.navigator.userAgent) && !/opera/i.test(window.navigator.userAgent)) { + // IE-specific logic here + xhr.setRequestHeader('Accept-Charset', 'utf-8'); + } else { + if (xhr.overrideMimeType) xhr.overrideMimeType('text\/plain; charset=utf-8'); + } + xhr.send(null); + if (xhr.readyState !== 4 || !(xhr.status === 200 || xhr.status === 0)) { + return null; + } + return xhr.responseText; +} + +function downloadImage (item, callback, isCrossOrigin) { + if (isCrossOrigin === undefined) { + isCrossOrigin = true; + } + + var url = urlAppendTimestamp(item.src); + var img = new Image(); + if (isCrossOrigin && window.location.origin !== 'file://') { + img.crossOrigin = 'Anonymous'; + } + + if (img.complete && img.naturalWidth > 0) { + callback(null, img); + } + else { + function loadCallback () { + img.removeEventListener('load', loadCallback); + img.removeEventListener('error', errorCallback); + + if (callback) { + callback(null, img); + } + } + function errorCallback () { + img.removeEventListener('load', loadCallback); + img.removeEventListener('error', errorCallback); + + if (img.crossOrigin && img.crossOrigin.toLowerCase() === 'anonymous') { + downloadImage(url, callback, false); + } + else { + callback('Load image (' + url + ') failed'); + } + } + + img.addEventListener('load', loadCallback); + img.addEventListener('error', errorCallback); + } + img.src = url; +} + +var FONT_TYPE = { + '.eot' : 'embedded-opentype', + '.ttf' : 'truetype', + '.ttc' : 'truetype', + '.woff' : 'woff', + '.svg' : 'svg' +}; +function _loadFont (name, srcs, type){ + var doc = document, + path = cc.path, + fontStyle = document.createElement('style'); + fontStyle.type = 'text/css'; + doc.body.appendChild(fontStyle); + + var fontStr = ''; + if (isNaN(name - 0)) { + fontStr += '@font-face { font-family:' + name + '; src:'; + } + else { + fontStr += '@font-face { font-family:\'' + name + '\'; src:'; + } + if (srcs instanceof Array) { + for (var i = 0, li = srcs.length; i < li; i++) { + var src = srcs[i]; + type = path.extname(src).toLowerCase(); + fontStr += 'url(\'' + srcs[i] + '\') format(\'' + FONT_TYPE[type] + '\')'; + fontStr += (i === li - 1) ? ';' : ','; + } + } else { + type = type.toLowerCase(); + fontStr += 'url(\'' + srcs + '\') format(\'' + FONT_TYPE[type] + '\');'; + } + fontStyle.textContent += fontStr + '}'; + + //
.
+ var preloadDiv = document.createElement('div'); + var _divStyle = preloadDiv.style; + _divStyle.fontFamily = name; + preloadDiv.innerHTML = '.'; + _divStyle.position = 'absolute'; + _divStyle.left = '-100px'; + _divStyle.top = '-100px'; + doc.body.appendChild(preloadDiv); +} +function downloadFont (item, callback) { + var url = item.src, + type = item.type, + name = item.name, + srcs = item.srcs; + if (name && srcs) { + if (srcs.indexOf(url) === -1) { + srcs.push(url); + } + _loadFont(name, srcs); + } else { + type = cc.path.extname(url); + name = cc.path.basename(url, type); + _loadFont(name, url, type); + } + if (document.fonts) { + document.fonts.load('1em ' + name).then(function () { + callback(null, null); + }, function(err){ + callback(err); + }); + } else { + callback(null, null); + } +} + +function downloadUuid (item, callback) { + var uuid = item.src; + var self = this; + cc.AssetLibrary.queryAssetInfo(uuid, function (error, url, isRawAsset) { + if (error) { + callback(error); + } + else { + item.url = url; + item.isRawAsset = isRawAsset; + if (isRawAsset) { + var ext = Path.extname(url).toLowerCase(); + if (!ext) { + callback(new Error('Download Uuid: can not find type of raw asset[' + uuid + ']: ' + url)); + return; + } + ext = ext.substr(1); + // Dispatch to other raw type downloader + var downloadFunc = self.extMap[ext] || self.extMap['default']; + item.type = ext; + downloadFunc({src: url}, callback); + } + else { + self.extMap['json']({src: url}, callback); + } + } + }); +} + + +var defaultMap = { + // JS + 'js' : downloadScript, + + // Images + 'png' : downloadImage, + 'jpg' : downloadImage, + 'bmp' : downloadImage, + 'jpeg' : downloadImage, + 'gif' : downloadImage, + 'ico' : downloadImage, + 'tiff' : downloadImage, + 'webp' : downloadImage, + 'image' : downloadImage, + + // Audio + 'mp3' : downloadAudio, + 'ogg' : downloadAudio, + 'wav' : downloadAudio, + 'mp4' : downloadAudio, + 'm4a' : downloadAudio, + + // Txt + 'txt' : downloadText, + 'xml' : downloadText, + 'vsh' : downloadText, + 'fsh' : downloadText, + 'atlas' : downloadText, + + 'tmx' : downloadText, + 'tsx' : downloadText, + + 'json' : downloadText, + 'ExportJson' : downloadText, + 'plist' : downloadText, + + 'fnt' : downloadText, + + // Font + 'font' : downloadFont, + 'eot' : downloadFont, + 'ttf' : downloadFont, + 'woff' : downloadFont, + 'svg' : downloadFont, + 'ttc' : downloadFont, + + // Deserializer + 'uuid' : downloadUuid, + 'prefab' : downloadUuid, + 'fire' : downloadUuid, + 'scene' : downloadUuid, + + 'default' : downloadText +}; + +var ID = 'Downloader'; + +/** + * The downloader pipe, it can download several types of files: + * 1. Text + * 2. Image + * 3. Script + * 4. Audio + * All unknown type will be downloaded as plain text. + * You can pass custom supported types in the constructor. + * @class Downloader + */ +/** + * Constructor of Downloader, you can pass custom supported types. + * @example + * var downloader = new Downloader({ + * // This will match all url with `.scene` extension or all url with `scene` type + * 'scene' : function (url, callback) {} + * }); + * + * @method Downloader + * @param {Object} extMap Custom supported types with corresponded handler + */ +var Downloader = function (extMap) { + this.id = ID; + this.async = true; + this.pipeline = null; + this.maxConcurrent = 2; + this._curConcurrent = 0; + this._loadQueue = []; + + 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) { + this.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) { + if (cc.sys.isMobile) { + this._curConcurrent++; + } + downloadFunc.call(this, item, function (err, result) { + if (cc.sys.isMobile) { + // 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 { + this._loadQueue.push({ + item: item, + callback: callback + }); + } + } +}); + +Pipeline.Downloader = module.exports = Downloader; \ No newline at end of file diff --git a/cocos2d/core/load-pipeline/index.js b/cocos2d/core/load-pipeline/index.js new file mode 100644 index 0000000000..f7c85d4dc5 --- /dev/null +++ b/cocos2d/core/load-pipeline/index.js @@ -0,0 +1,7 @@ +require('./downloader'); +require('./loader'); + +require('./loading-items'); +require('./pipeline'); + +require('./CCLoader'); diff --git a/cocos2d/core/load-pipeline/loader.js b/cocos2d/core/load-pipeline/loader.js new file mode 100644 index 0000000000..1ddc0e588d --- /dev/null +++ b/cocos2d/core/load-pipeline/loader.js @@ -0,0 +1,245 @@ +/**************************************************************************** + Copyright (c) 2016 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +var JS = require('../platform/js'); +var Pipeline = require('./pipeline'); +var Texture2D = require('../textures/CCTexture2D'); +var loadUuid = require('./uuid-loader'); + +function loadNothing (item, callback) { + callback(null, null); +} + +function loadJSON (item, callback) { + if (typeof item.content !== 'string') { + callback( new Error('JSON Loader: Input item doesn\'t contain string content') ); + } + + try { + var result = JSON.parse(item.content); + callback(null, result); + } + catch (e) { + callback( new Error('JSON Loader: Parse json [' + item.src + '] failed : ' + e) ); + } +} + +function loadImage (item, callback) { + if (!(item.content instanceof Image)) { + callback( new Error('Image Loader: Input item doesn\'t contain Image content') ); + } + var url = item.url || item.src; + var tex = cc.textureCache.getTextureForKey(url) || new Texture2D(); + tex.url = url; + tex.initWithElement(item.content); + tex.handleLoadedTexture(); + cc.textureCache.cacheImage(url, tex); + callback(null, tex); +} + +function loadPlist (item, callback) { + if (typeof item.content !== 'string') { + callback( new Error('Plist Loader: Input item doesn\'t contain string content') ); + } + var result = cc.plistParser.parse(item.content); + if (result) { + callback(null, result); + } + else { + callback( new Error('Plist Loader: Parse [' + item.src + '] failed') ); + } +} + +var fntRE = { + INFO_EXP: /info [^\n]*(\n|$)/gi, + COMMON_EXP: /common [^\n]*(\n|$)/gi, + PAGE_EXP: /page [^\n]*(\n|$)/gi, + CHAR_EXP: /char [^\n]*(\n|$)/gi, + KERNING_EXP: /kerning [^\n]*(\n|$)/gi, + ITEM_EXP: /\w+=[^ \r\n]+/gi, + INT_EXP: /^[\-]?\d+$/, +}; +function _parseFntStrToObj (str) { + var arr = str.match(fntRE.ITEM_EXP); + var obj = {}; + if (arr) { + for (var i = 0, li = arr.length; i < li; i++) { + var tempStr = arr[i]; + var index = tempStr.indexOf('='); + var key = tempStr.substring(0, index); + var value = tempStr.substring(index + 1); + if (value.match(fntRE.INT_EXP)) value = parseInt(value); + else if (value[0] === '"') value = value.substring(1, value.length - 1); + obj[key] = value; + } + } + return obj; +} +function loadFnt (item, callback) { + var fntStr = item.content; + var url = item.src; + + var fnt = {}, i, li; + //padding + var infoObj = _parseFntStrToObj(fntStr.match(fntRE.INFO_EXP)[0]); + var paddingArr = infoObj['padding'].split(','); + var padding = { + left: parseInt(paddingArr[0]), + top: parseInt(paddingArr[1]), + right: parseInt(paddingArr[2]), + bottom: parseInt(paddingArr[3]) + }; + + //common + var commonObj = _parseFntStrToObj(fntStr.match(fntRE.COMMON_EXP)[0]); + fnt.commonHeight = commonObj['lineHeight']; + //font size + fnt.fontSize = infoObj['size']; + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + var texSize = cc.configuration.getMaxTextureSize(); + if (commonObj['scaleW'] > texSize.width || commonObj['scaleH'] > texSize.height) { + cc.log('cc.LabelBMFont._parseCommonArguments(): page can\'t be larger than supported'); + } + } + if (commonObj['pages'] !== 1) { + cc.log('cc.LabelBMFont._parseCommonArguments(): only supports 1 page'); + } + + //page + var pageObj = _parseFntStrToObj(fntStr.match(fntRE.PAGE_EXP)[0]); + if (pageObj['id'] !== 0) { + cc.log('cc.LabelBMFont._parseImageFileName() : file could not be found'); + } + fnt.atlasName = cc.path.changeBasename(url, pageObj['file']); + + //char + var charLines = fntStr.match(fntRE.CHAR_EXP); + var fontDefDictionary = fnt.fontDefDictionary = {}; + for (i = 0, li = charLines.length; i < li; i++) { + var charObj = _parseFntStrToObj(charLines[i]); + var charId = charObj['id']; + fontDefDictionary[charId] = { + rect: {x: charObj['x'], y: charObj['y'], width: charObj['width'], height: charObj['height']}, + xOffset: charObj['xoffset'], + yOffset: charObj['yoffset'], + xAdvance: charObj['xadvance'] + }; + } + + //kerning + var kerningDict = fnt.kerningDict = {}; + var kerningLines = fntStr.match(fntRE.KERNING_EXP); + if (kerningLines) { + for (i = 0, li = kerningLines.length; i < li; i++) { + var kerningObj = _parseFntStrToObj(kerningLines[i]); + kerningDict[(kerningObj['first'] << 16) | (kerningObj['second'] & 0xffff)] = kerningObj['amount']; + } + } + callback(null, fnt); +} + +var defaultMap = { + // Images + 'png' : loadImage, + 'jpg' : loadImage, + 'bmp' : loadImage, + 'jpeg' : loadImage, + 'gif' : loadImage, + 'ico' : loadImage, + 'tiff' : loadImage, + 'webp' : loadImage, + 'image' : loadImage, + + 'json' : loadJSON, + 'ExportJson' : loadJSON, + + 'plist' : loadPlist, + + 'fnt' : loadFnt, + + 'uuid' : loadUuid, + 'prefab' : loadUuid, + 'fire' : loadUuid, + 'scene' : loadUuid, + + 'default' : loadNothing +}; + +var ID = 'Loader'; + +/** + * The loader pipe, it can load several types of files: + * 1. Images + * 2. JSON + * 3. Plist + * 4. Audio + * 5. Font + * 6. Cocos Creator scene + * It will not interfere with items of unknown type. + * You can pass custom supported types in the constructor. + * @class Loader + */ +/** + * Constructor of Loader, you can pass custom supported types. + * @example + * var loader = new Loader({ + * // This will match all url with `.scene` extension or all url with `scene` type + * 'scene' : function (url, callback) {} + * }); + * + * @method Loader + * @param {Object} extMap Custom supported types with corresponded handler + */ +var Loader = function (extMap) { + this.id = ID; + this.async = true; + this.pipeline = null; + + 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); + } + }); + } +}); + +Pipeline.Loader = module.exports = Loader; \ No newline at end of file diff --git a/cocos2d/core/load-pipeline/loading-items.js b/cocos2d/core/load-pipeline/loading-items.js new file mode 100644 index 0000000000..05d619befd --- /dev/null +++ b/cocos2d/core/load-pipeline/loading-items.js @@ -0,0 +1,148 @@ +/**************************************************************************** + Copyright (c) 2016 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +var CallbacksInvoker = require('../platform/callbacks-invoker'); +var JS = require('../platform/js'); + +/** + * LoadingItems is the manager of items in pipeline. + * It hold a map of items, each entry in the map is a url to object key value pair. + * Each item always contains the following property: + * - src: The url + * - type: The type, it's the extension name of the url by default, could be specified manually too + * - error: The error happened in pipeline will be stored in this property + * - content: The content processed by the pipeline, the final result will also be stored in this property + * - complete: The flag indicate whether the item is completed by the pipeline + * - states: An object stores the states of each pipe the item go through, the state can be: Pipeline.ItemState.WORKING | Pipeline.ItemState.ERROR | Pipeline.ItemState.COMPLETE + * + * Item can hold other custom properties + * + * @class LoadingItems + */ +var LoadingItems = function () { + CallbacksInvoker.call(this); + + /** + * The map of all items + * @property map + * @type {Object} + */ + this.map = {}; + + /** + * The map of completed items + * @property completed + * @type {Object} + */ + this.completed = {}; + + /** + * Total count of all items + * @property totalCount + * @type {Number} + */ + this.totalCount = 0; + + /** + * Total count of completed items + * @property completedCount + * @type {Number} + */ + this.completedCount = 0; +}; + +JS.mixin(LoadingItems.prototype, CallbacksInvoker.prototype, { + append: function (items) { + var list = []; + for (var i = 0; i < items.length; ++i) { + var item = items[i]; + var url = item.src; + // No duplicated url + if (!this.map[url]) { + this.map[item.src] = item; + list.push(item); + } + } + this.totalCount += list.length; + return list; + }, + + /** + * Check whether all items are completed + * @return {Boolean} + */ + isCompleted: function () { + return this.completedCount >= this.totalCount; + }, + + /** + * Check whether an item is completed + * @return {Boolean} + */ + isItemCompleted: function (url) { + return !!this.completed[url]; + }, + + /** + * Check whether an item exists + * @return {Boolean} + */ + exists: function (url) { + return !!this.map[url]; + }, + + getContent: function (url) { + var item = this.map[url]; + return item ? item.content : null; + }, + + getError: function (url) { + var item = this.map[url]; + return item ? item.error : null; + }, + + /** + * Remove an item, can only remove completed item, ongoing item can not be removed + * @param {String} url + */ + remove: function (url) { + if (this.completed[url]) { + delete this.completed[url]; + delete this.map[url]; + this.completedCount--; + this.totalCount--; + } + }, + + complete: function (url) { + if (this.map[url] && !this.completed[url]) { + var item = this.map[url]; + item.complete = true; + this.completed[url] = item; + this.completedCount++; + } + } +}); + +module.exports = LoadingItems; \ No newline at end of file diff --git a/cocos2d/core/load-pipeline/pipeline.js b/cocos2d/core/load-pipeline/pipeline.js new file mode 100644 index 0000000000..ac23979c10 --- /dev/null +++ b/cocos2d/core/load-pipeline/pipeline.js @@ -0,0 +1,504 @@ +/**************************************************************************** + Copyright (c) 2016 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +var JS = require('../platform/js'); +var Path = require('../utils/CCPath'); +var LoadingItems = require('./loading-items'); + +var ItemState = { + WORKING: 1, + COMPLETE: 2, + ERROR: 3 +}; + +function asyncFlow (item) { + var pipeId = this.id; + var itemState = item.states[pipeId]; + var next = this.next; + + if (item.error || itemState === ItemState.WORKING || itemState === ItemState.ERROR) { + return; + } + else if (itemState === ItemState.COMPLETE) { + if (next) { + next.async ? asyncFlow.call(next, item) : syncFlow.call(next, item); + } + else { + this.pipeline.flowOut(item); + } + } + else { + item.states[pipeId] = ItemState.WORKING; + var pipe = this; + this.handle(item, function (err, result) { + if (err) { + item.error = err; + item.states[pipeId] = ItemState.ERROR; + pipe.pipeline.flowOut(item); + } + else { + // Result can be null, then it means no result for this pipe + if (result) { + item.content = result; + } + item.states[pipeId] = ItemState.COMPLETE; + if (next) { + next.async ? asyncFlow.call(next, item) : syncFlow.call(next, item); + } + else { + pipe.pipeline.flowOut(item); + } + } + }); + } +} +function syncFlow (item) { + var pipeId = this.id; + var itemState = item.states[pipeId]; + var next = this.next; + + if (item.error || itemState === ItemState.WORKING || itemState === ItemState.ERROR) { + return; + } + else if (itemState === ItemState.COMPLETE) { + if (next) { + next.async ? asyncFlow.call(next, item) : syncFlow.call(next, item); + } + else { + this.pipeline.flowOut(item); + } + } + else { + item.states[pipeId] = ItemState.WORKING; + var result = this.handle(item); + if (result instanceof Error) { + item.error = result; + item.states[pipeId] = ItemState.ERROR; + this.pipeline.flowOut(item); + } + else { + // Result can be null, then it means no result for this pipe + if (result) { + item.content = result; + } + item.states[pipeId] = ItemState.COMPLETE; + if (next) { + next.async ? asyncFlow.call(next, item) : syncFlow.call(next, item); + } + else { + this.pipeline.flowOut(item); + } + } + } +} + +function isUrlValid (url) { + var realUrl = url.src || url; + return (typeof realUrl === 'string'); +} +function createItem (url) { + var result; + if (typeof url === 'object' && url.src) { + if (!url.type) { + url.type = Path.extname(url.src).toLowerCase().substr(1); + } + result = { + error: null, + content: null, + complete: false, + states: {} + }; + JS.mixin(result, url); + } + else if (typeof url === 'string') { + result = { + src: url, + type: Path.extname(url).toLowerCase().substr(1), + error: null, + content: null, + complete: false, + states: {} + }; + } + + if (result.skips) { + for (var i = 0, l = result.skips.length; i < l; i++) { + var skip = result.skips[i]; + result.states[skip] = ItemState.COMPLETE; + } + } + + return result; +} + +function getXMLHttpRequest () { + return window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject('MSXML2.XMLHTTP'); +} + +/** + * A pipeline describes a sequence of manipulations, each manipulation is called a pipe. + * It's designed for loading process, so items should be urls, and the url will be the identity of each item during the process. + * A list of items can flow in the pipeline and it will output the results of all pipes. + * They flow in the pipeline like water in tubes, they go through pipe by pipe separately. + * Finally all items will flow out the pipeline and the process is finished. + * + * @class Pipeline + */ +/** + * Constructor, pass an array of pipes to construct a new Pipeline, the pipes will be chained in the given order. + * A pipe is an object which must contain an `id` in string and a `handle` function, the id must be unique in the pipeline. + * It can also include `async` property to identify whether it's an asynchronous process. + * @example + * var pipeline = new Pipeline([ + * { + * id: 'Downloader', + * handle: function (item, callback) {}, + * async: true + * }, + * {id: 'Parser', handle: function (item) {}, async: false} + * ]); + * + * @method Pipeline + * @param {Array} pipes + */ +var Pipeline = function (pipes) { + this._pipes = pipes; + this._items = new LoadingItems(); + this._errorUrls = []; + this._flowing = false; + + for (var i = 0; i < pipes.length; ++i) { + var pipe = pipes[i]; + // Must have handle and id, handle for flow, id for state flag + if (!pipe.handle || !pipe.id) { + continue; + } + + pipe.pipeline = this; + pipe.next = i < pipes.length - 1 ? pipes[i+1] : null; + } +}; + +Pipeline.ItemState = new cc.Enum(ItemState); +Pipeline.getXMLHttpRequest = getXMLHttpRequest; + +JS.mixin(Pipeline.prototype, { + /** + * 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. + * + * @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; + } + + pipe.pipeline = this; + if (index < this._pipes.length) { + pipe.next = this._pipes[index]; + this._pipes.splice(index, 0, pipe); + } + else { + pipe.next = null; + this._pipes.push(pipe); + } + }, + + /** + * 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. + * + * @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.next = null; + this._pipes.push(pipe); + }, + + /** + * 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 `src` property. + * You can specify its type by `type` property, by default, the type is the extension name in `src`. + * By adding a `skips` property including pipe ids, you can skip these pipe. + * The object can contain any supplementary property as you want. + * @example + * pipeline.flowIn([ + * 'res/Background.png', + * { + * src: 'res/scene.json', + * type: 'scene', + * name: 'scene', + * skips: ['Downloader'] + * } + * ]); + * + * @method flowIn + * @param {Array} urlList + * @return {Array} Items accepted by the pipeline + */ + flowIn: function (urlList) { + var items = [], i, url, item; + for (i = 0; i < urlList.length; ++i) { + url = urlList[i]; + if (isUrlValid(url)) { + item = createItem(url); + items.push(item); + } + else { + throw new Error('Pipeline flowIn: Invalid url: ' + (url.src || url)); + } + } + var acceptedItems = this._items.append(items); + + // Manually complete + if (this._pipes.length === 0 || acceptedItems.length === 0) { + this.complete(); + return acceptedItems; + } + + if (!this._flowing) { + this._flowing = true; + } + // Flow in after appended to loading items + var pipe = this._pipes[0]; + if (pipe) { + for (i = 0; i < acceptedItems.length; i++) { + pipe.async ? asyncFlow.call(pipe, acceptedItems[i]) : syncFlow.call(pipe, acceptedItems[i]); + } + } + return acceptedItems; + }, + + /** + * 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). + * + * @method flowInDeps + * @param {Array} urlList + * @param {Function} callback + * @return {Array} Items accepted by the pipeline + */ + flowInDeps: function (urlList, callback) { + var checker = {}; + var count = 0; + + function loadedCheck (item) { + checker[item.src] = item; + + for (var url in checker) { + // Not done yet + if (!checker[url]) { + return; + } + } + // All url completed + callback && callback.call(this, checker); + } + // Add loaded listeners + for (var i = 0; i < urlList.length; ++i) { + var url = urlList[i].src || urlList[i]; + if (typeof url !== 'string') + continue; + var item = this._items.map[url]; + if ( !item ) { + this._items.add(url, loadedCheck); + checker[url] = null; + count++; + } + else { + checker[url] = item; + } + } + // No new resources, complete directly + if (count === 0) { + callback && callback.call(this, checker); + } + return this.flowIn(urlList); + }, + + complete: function () { + // All completed + if (this._items.isCompleted()) { + this._flowing = false; + if (this.onComplete) { + var error = this._errorUrls.length === 0 ? null : this._errorUrls; + this.onComplete(error, this._items); + this._errorUrls = []; + } + } + }, + + flowOut: function (item) { + var url = item.src; + var items = this._items; + var exists = items.map[url]; + // Not exist or already completed + if (!exists || exists.complete) { + return; + } + + // Register or unregister errors + var errorListId = this._errorUrls.indexOf(url); + if (item.error && errorListId === -1) { + this._errorUrls.push(url); + } + else if (!item.error && errorListId !== -1) { + this._errorUrls.splice(errorListId, 1); + } + + items.complete(item.src); + + this.onProgress && this.onProgress(items.completedCount, items.totalCount, item); + + this.complete(); + + items.invoke(url, item); + }, + + /** + * 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. + * @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; + } + }, + + /** + * Returns whether the pipeline is flowing (contains item) currently. + * @method isFlowing + * @return {Boolean} + */ + isFlowing: function () { + return this._flowing; + }, + + /** + * Returns all items in pipeline. + * @method getItems + * @return {LoadingItems} + */ + getItems: function () { + return this._items; + }, + + /** + * Removes an item in pipeline, no matter it's in progress or completed. + * @method removeItem + * @return {Boolean} succeed or not + */ + removeItem: function (url) { + var item = this._items.map[url]; + if (item) { + if (!item.complete) { + item.error = new Error('Canceled manually'); + this.flowOut(item); + } + this._items.remove(url); + } + else { + return false; + } + }, + + /** + * Clear the current pipeline, this function will clean up the items. + * @method clear + */ + clear: function () { + if (this._flowing) { + var items = this._items.map; + for (var url in items) { + var item = items[url]; + if (!item.complete) { + item.error = new Error('Canceled manually'); + this.flowOut(item); + } + } + } + + this._items = new LoadingItems(); + this._errorUrls = []; + this._flowing = false; + }, + + /** + * This is a callback which will be invoked while an item flow out the pipeline, you should overwrite this function. + * @example + * pipeline.onProgress = function (completedCount, totalCount, item) { + * var progress = (100 * completedCount / totalCount).toFixed(2); + * cc.log(progress + '%'); + * } + * @method onProgress + * @param {Number} completedCount The number of the items that are already completed. + * @param {Number} totalCount The total number of the items. + * @param {Object} item The latest item which flow out the pipeline. + */ + onProgress: function (completedCount, totalCount, item) {}, + + /** + * This is a callback which will be invoked while all items flow out the pipeline, you should overwirte this function. + * @example + * pipeline.onComplete = function (error, items) { + * if (error) + * cc.log('Completed with ' + error.length + ' errors'); + * else + * cc.log('Completed ' + items.totalCount + ' items'); + * } + * @method onComplete + * @param {Array} error All errored urls will be stored in this array, if no error happened, then it will be null + * @param {LoadingItems} items All items. + */ + onComplete: function (error, items) {} +}); + +cc.Pipeline = module.exports = Pipeline; \ No newline at end of file diff --git a/cocos2d/core/load-pipeline/uuid-loader.js b/cocos2d/core/load-pipeline/uuid-loader.js new file mode 100644 index 0000000000..e853108e17 --- /dev/null +++ b/cocos2d/core/load-pipeline/uuid-loader.js @@ -0,0 +1,147 @@ +/**************************************************************************** + Copyright (c) 2016 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +var JS = require('../platform/js'); +require('../platform/deserialize'); + +// temp deserialize info +var _tdInfo = new cc.deserialize.Details(); + +var SCENE_ID = 'cc.Scene'; + +function loadUuid (item, callback) { + var json, + uuid = item.src, + url = item.url; + if (typeof item.content === 'string') { + try { + json = JSON.parse(item.content); + } + catch (e) { + callback( new Error('Uuid Loader: Parse asset [' + item.src + '] failed : ' + e) ); + return; + } + } + else if (typeof item.content === 'object') { + json = item.content; + } + else { + callback( new Error('JSON Loader: Input item doesn\'t contain string content') ); + return; + } + + var isScene = json && ( + (json[0] && json[0].__type__ === SCENE_ID) || + (json[1] && json[1].__type__ === SCENE_ID) + ); + var classFinder = isScene ? cc._MissingScript.safeFindClass : function (id) { + var cls = JS._getClassById(id); + if (cls) { + return cls; + } + cc.warn('Can not get class "%s"', id); + return Object; + }; + + var tdInfo = cc.sys.isNative ? new cc.deserialize.Details() : (item.deserializeInfo || _tdInfo); + + var asset = cc.deserialize(json, tdInfo, { + classFinder: classFinder, + target: item.existingAsset + }); + + var dependsSrcs = JS.array.copy(tdInfo.uuidList); + var ownerList = JS.array.copy(tdInfo.uuidObjList); + var propList = JS.array.copy(tdInfo.uuidPropList); + + var depends = new Array(dependsSrcs.length); + // load depends assets + for (var i = 0; i < dependsSrcs.length; i++) { + var dependSrc = dependsSrcs[i]; + depends[i] = { + src: dependSrc, + type: 'uuid', + uuid: dependSrc + }; + } + // load raw + if (tdInfo.rawProp) { + dependsSrcs.push(url); + ownerList.push(asset); + propList.push(tdInfo.rawProp); + depends.push(url); + } + var pipeline = this.pipeline; + if (depends.length > 0) { + pipeline.flowInDeps(depends, function (items) { + var item; + for (var src in items) { + item = items[src]; + if (item.uuid && item.content) { + item.content._uuid = item.uuid; + } + } + for (var i = 0; i < dependsSrcs.length; i++) { + var dependSrc = dependsSrcs[i]; + var obj = ownerList[i]; + var dependProp = propList[i]; + item = items[dependSrc]; + if (item) { + if (item.complete) { + var value = item.isRawAsset ? (item.url || item.src) : item.content; + obj[dependProp] = value; + } + else { + var loadCallback = function (item) { + var value = item.isRawAsset ? (item.url || item.src) : item.content; + this.obj[this.prop] = value; + }; + var target = { + obj: obj, + prop: dependProp + }; + // Hack to get a better behavior + var list = pipeline.getItems()._callbackTable[dependSrc]; + if (list) { + list.unshift(loadCallback, target); + } + else { + pipeline.getItems().add(dependSrc, loadCallback, target); + } + } + } + } + callback(null, asset); + }); + } + else { + callback(null, asset); + } + asset._uuid = uuid; + + // tdInfo 是用来重用的临时对象,每次使用后都要重设,这样才对 GC 友好。 + tdInfo.reset(); +} + +module.exports = loadUuid; \ No newline at end of file diff --git a/cocos2d/core/platform/CCAssetLibrary.js b/cocos2d/core/platform/CCAssetLibrary.js index d21554528e..3440530703 100644 --- a/cocos2d/core/platform/CCAssetLibrary.js +++ b/cocos2d/core/platform/CCAssetLibrary.js @@ -1,8 +1,6 @@ -var JS = require('./js'); -var Asset = require('../assets/CCAsset'); +var Asset = require('../assets/CCAsset'); var callInNextTick = require('./utils').callInNextTick; -var LoadManager = require('./load-manager'); -var CallbacksInvoker = require('./callbacks-invoker'); +var Loader = require('../load-pipeline/CCLoader'); /** * The asset library which managing loading/unloading assets in project. @@ -17,64 +15,9 @@ var _libraryBase = ''; var _rawAssetsBase = ''; // The base dir for raw assets in runtime var _uuidToRawAssets; -// variables - -// the loading uuid's callbacks -var _uuidToCallbacks = new CallbacksInvoker(); - -// temp deserialize info -var _tdInfo = new cc.deserialize.Details(); - -var _cc_loader_loadJson = cc.loader.loadJson.bind(cc.loader); - -// create a loading context which reserves all relevant parameters -function LoadingHandle (readMainCache, writeMainCache, recordAssets, deserializeInfo) { - //this.readMainCache = readMainCache; - //this.writeMainCache = writeMainCache; - - // FORCE ignore global cache in fireball lite - this.readMainCache = false; - this.writeMainCache = false; - - // 缓存同一个任务中已经加载好的资源 - var needIndieCache = !(this.readMainCache && this.writeMainCache); - this.taskIndieCache = needIndieCache ? {} : null; - - // 保存正在等待依赖项加载完毕的资源,防止循环依赖 - // (其它缓存包含的是已经加载完毕的资源,如果已经缓存会立即结束并回调,而这个缓存存的是还在加载中的资源,不会影响加载也不会触发回调) - this.pendingCache = {}; - - // 需要让场景 preload 的 asset(所有包含 raw file 后缀名的 asset 并且不含 rawType 属性的 asset) - this.assetsNeedPostLoad = recordAssets ? [] : null; - - // 可以提供一个反序列化句柄,用来在执行反序列化任务时,做一些特殊处理 - this.deserializeInfo = deserializeInfo; +function isScene (asset) { + return asset && (asset.constructor === cc.SceneAsset || asset instanceof cc.Scene); } -LoadingHandle.prototype.readCache = function (uuid) { - if (this.readMainCache && this.writeMainCache) { - return AssetLibrary._uuidToAsset[uuid]; - } - else { - if (this.readMainCache) { - // writeMainCache == false - return AssetLibrary._uuidToAsset[uuid] || this.taskIndieCache[uuid]; - } - else { - return this.taskIndieCache[uuid]; - } - } -}; -LoadingHandle.prototype.writeCache = function (uuid, asset, hasRawType) { - if (this.writeMainCache) { - AssetLibrary._uuidToAsset[uuid] = asset; - } - if (this.taskIndieCache) { - this.taskIndieCache[uuid] = asset; - } - if (this.assetsNeedPostLoad && asset._rawFiles && !hasRawType) { - this.assetsNeedPostLoad.push(asset); - } -}; // publics @@ -93,25 +36,27 @@ var AssetLibrary = { * @param {Boolean} options.readMainCache - Default is true. If false, the asset and all its depends assets will reload and create new instances from library. * @param {Boolean} options.writeMainCache - Default is true. If true, the result will cache to AssetLibrary, and MUST be unload by user manually. * @param {Asset} options.existingAsset - load to existing asset, this argument is only available in editor - * @param {Boolean} options.recordAssets - Default is false. If true, tracking statistics associated with the assets which needs to preload(All the assets contains "urls" but dont have "_rawFiles") * @param {deserialize.Details} options.deserializeInfo - specified a DeserializeInfo object if you want, * this parameter is only available in editor. * @private */ loadAsset: function (uuid, callback, options) { - var readMainCache = typeof (options && options.readMainCache) !== 'undefined' ? readMainCache : true; - var writeMainCache = typeof (options && options.writeMainCache) !== 'undefined' ? writeMainCache : true; + // var readMainCache = typeof (options && options.readMainCache) !== 'undefined' ? readMainCache : true; + // var writeMainCache = typeof (options && options.writeMainCache) !== 'undefined' ? writeMainCache : true; - var handle = new LoadingHandle(readMainCache, - writeMainCache, - options && options.recordAssets, - options && options.deserializeInfo); - this._loadAssetByUuid(uuid, callback, handle, options && options.existingAsset); - return handle; + var item = { + src: uuid, + type: 'uuid' + }; + if (options && options.deserializeInfo) { + item.deserializeInfo = options.deserializeInfo; + } + if (options && options.existingAsset) { + item.existingAsset = options.existingAsset; + } + this._loadAssetByUuid(item, callback); }, - _LoadingHandle: LoadingHandle, - getImportedDir: function (uuid) { return _libraryBase + uuid.slice(0, 2)/* + cc.path.sep + uuid*/; }, @@ -120,7 +65,7 @@ var AssetLibrary = { if (CC_EDITOR) { Editor.sendRequestToCore( 'scene:query-asset-info-by-uuid', uuid, function (info) { if (info) { - Editor.onRawAssetUsed(info.url, uuid); + Editor.UuidCache.cache(info.url, uuid); var ctor = Editor.assets[info.type]; if (ctor) { var isRawAsset = !cc.isChildClassOf(ctor, Asset); @@ -176,7 +121,7 @@ var AssetLibrary = { // parse uuid out of url parseUuidInEditor: function (url) { if (CC_EDITOR) { - var uuid = ""; + var uuid = ''; var isImported = url.startsWith(_libraryBase); if (isImported) { var dir = cc.path.dirname(url); @@ -208,264 +153,77 @@ var AssetLibrary = { * 4. 递归加载Asset及其引用到的其它Asset * * @method _loadAssetByUuid - * @param {String} uuid + * @param {Object} item - loading item including uuid, type and extra infos * @param {loadCallback} callback - the callback to receive the asset, can be null - * @param {LoadingHandle} handle - the loading context which reserves all relevant parameters - * @param {Asset} [existingAsset] - load to existing asset, this argument is only available in editor * @private */ - _loadAssetByUuid: function (uuid, callback, handle, existingAsset) { + _loadAssetByUuid: function (item, callback) { + var uuid = item.src; + var thisTick = true; if (typeof uuid !== 'string') { return callInNextTick(callback, new Error('[AssetLibrary] uuid must be string'), null); } - // step 1 - if ( !existingAsset ) { - var asset = handle.readCache(uuid); - if (asset) { - return callInNextTick(callback, null, asset); + + Loader.load(item, function (error, asset) { + if (error || !asset) { + error = new Error('[AssetLibrary] loading JSON or dependencies failed : ' + JSON.stringify(error)); } - } - - // step 2 - // 如果必须重新加载,则不能合并到到 _uuidToCallbacks,否则现有的加载成功后会同时触发回调, - // 导致提前返回的之前的资源。 - var canShareLoadingTask = handle.readMainCache && !existingAsset; - if ( canShareLoadingTask && !_uuidToCallbacks.add(uuid, callback) ) { - // already loading - return; - } - - // 防止循环加载 - var loading = handle.pendingCache[uuid]; - if (loading) { - // already loading - return callInNextTick(callback, null, loading); - } - - //if (CC_EDITOR && !_libraryBase) { - // callInNextTick(callback, new Error('Cannot load ' + uuid + ' in editor because AssetLibrary not yet initialized!'), null); - // return; - //} - function onload (error, json, url) { - function onDeserializedWithDepends (err, asset, hasRawType) { - if (asset) { - asset._uuid = uuid; - handle.writeCache(uuid, asset, hasRawType); - } - if ( canShareLoadingTask ) { - _uuidToCallbacks.invokeAndRemove(uuid, err, asset); - } - else if (callback) { - callback(err, asset); - } - } - if (json) { - AssetLibrary._deserializeWithDepends(json, url, uuid, onDeserializedWithDepends, handle, existingAsset); + if (thisTick) { + callInNextTick(function () { + if (isScene(asset) || CC_EDITOR) { + Loader.removeItem(uuid); + } + callback(error, asset); + }); } else { - onDeserializedWithDepends(error, null); - } - } - - if (CC_EDITOR && !CC_TEST) { - this._queryAssetInfoInEditor(uuid, function (err, url, isRawAsset) { - if (err) { - callback(err); + if (isScene(asset) || CC_EDITOR) { + Loader.removeItem(uuid); } - else { - var shouldLoadByEngine = !isRawAsset; - if (!shouldLoadByEngine) { - return callback(new Error('Should not load raw file in AssetLibrary, uuid: ' + uuid)); - } - LoadManager.loadByLoader(_cc_loader_loadJson, url, function (error, json) { - onload(error, json, url); - }); - } - }); - } - else { - var info = this._getAssetInfoInRuntime(uuid); - if (info.raw) { - return callback(new Error('Should not load raw file in AssetLibrary, uuid: ' + uuid)); + callback(error, asset); } - LoadManager.loadByLoader(_cc_loader_loadJson, info.url, function (error, json) { - onload(error, json, info.url); - }); - } + }); + thisTick = false; }, /** * @method loadJson - * @param {String|Object} json + * @param {String} json * @param {loadCallback} callback - * @param {Boolean} [dontCache=false] - If false, the result will cache to AssetLibrary, and MUST be unload by user manually. - * @param {Boolean} [recordAssets=false] - 是否统计新加载的需要让场景 preload 的 asset(所有包含 raw file 后缀名的 asset 并且不含 rawType 属性的 asset) * @return {LoadingHandle} * @private */ - loadJson: function (json, callback, dontCache, recordAssets) { - var handle = new LoadingHandle(!dontCache, !dontCache, recordAssets); + loadJson: function (json, callback) { + var randomUuid = '' + ((new Date()).getTime() + Math.random()); var thisTick = true; - this._deserializeWithDepends(json, '', '', function (p1, p2) { + var item = { + src: randomUuid, + type: 'uuid', + content: json, + skips: [ Loader.downloader.id ] + }; + Loader.load(item, function (error, asset) { + if (error) { + error = new Error('[AssetLibrary] loading JSON or dependencies failed : ' + JSON.stringify(error)); + } if (thisTick) { - callInNextTick(callback, p1, p2); + callInNextTick(function () { + if (isScene(asset) || CC_EDITOR) { + Loader.removeItem(randomUuid); + } + asset._uuid = ''; + callback(error, asset); + }); } else { - callback(p1, p2); + if (isScene(asset) || CC_EDITOR) { + Loader.removeItem(randomUuid); + } + asset._uuid = ''; + callback(error, asset); } - }, handle); + }); thisTick = false; - return handle; - }, - - _loadDepends: function (asset, _tdInfo, url, handle, callback) { - // load depends - var pendingCount = _tdInfo.uuidList.length; - - // load raw - var rawProp = _tdInfo.rawProp; // _tdInfo不能用在回调里! - if (rawProp) { - // load depends raw objects - var attrs = cc.Class.attr(asset.constructor, _tdInfo.rawProp); - var rawType = attrs.rawType; - ++pendingCount; - LoadManager.load(url, rawType, asset._rawext, function onRawObjLoaded (error, raw) { - if (error) { - cc.error('[AssetLibrary] Failed to load %s of %s. %s', rawType, url, error); - } - asset[rawProp] = raw; - --pendingCount; - if (pendingCount === 0) { - callback(); - callback = null; - } - }); - } - - if (pendingCount === 0) { - if (callback) { - callback(); - } - return; - } - - /* - 如果依赖的所有资源都要重新下载,批量操作时将会导致同时执行多次重复下载。优化方法是增加一全局事件队列, - 队列保存每个任务的注册,启动,结束事件,任务从注册到启动要延迟几帧,每个任务都存有父任务。 - 这样通过队列的事件序列就能做到合并批量任务。 - 如果依赖的资源不重新下载也行,但要判断是否刚好在下载过程中,如果是的话必须等待下载完成才能结束本资源的加载, - 否则外部获取到的依赖资源就会是旧的。 - */ - - // load depends assets - for (var i = 0; i < _tdInfo.uuidList.length; i++) { - var dependsUuid = _tdInfo.uuidList[i]; - (function (dependsUuid, obj, prop) { - AssetLibrary.queryAssetInfo(dependsUuid, function (err, dependsUrl, isRawAsset) { - if (err) { - cc.error('[AssetLibrary] Failed to load "%s", %s', dependsUuid, err); - --pendingCount; - if (callback && pendingCount === 0) { - callback(); - callback = null; - } - - obj[prop] = obj[prop]; // ensures forEach worked - return; - } - else if (isRawAsset) { - cc.loader.load(dependsUrl, function (err, assets) { - if (err) { - cc.error('[AssetLibrary] Failed to load "%s"', dependsUrl); - obj[prop] = ''; - } - else { - obj[prop] = dependsUrl; - } - --pendingCount; - if (callback && pendingCount === 0) { - callback(); - callback = null; - } - }); - return; - } - - var onDependsAssetLoaded = function (error, dependsAsset, hasRawType) { - if (CC_EDITOR && error) { - if (Editor.AssetDB && Editor.AssetDB.isValidUuid(dependsUuid)) { - cc.error('[AssetLibrary] Failed to load "%s", %s', dependsUuid, error); - } - } - //else { - // dependsAsset._uuid = dependsUuid; - //} - // update reference - obj[prop] = dependsAsset; - // - --pendingCount; - if (callback && pendingCount === 0) { - callback(); - callback = null; - } - }; - AssetLibrary._loadAssetByUuid(dependsUuid, onDependsAssetLoaded, handle); - }); - })( dependsUuid, _tdInfo.uuidObjList[i], _tdInfo.uuidPropList[i] ); - } - - // AssetLibrary._loadAssetByUuid 的回调有可能在当帧也可能延后执行,所以这里要判断 callback 来防止多次调用 - if (callback && pendingCount === 0) { - callback(); - callback = null; - } - }, - - /** - * @method _deserializeWithDepends - * @param {String|Object} json - * @param {String} url - * @param {String} uuid - * @param {loadCallback} callback - * @param {Object} handle - the loading context which reserves all relevant parameters - * @param {Asset} [existingAsset] - existing asset to reload - * @private - */ - _deserializeWithDepends: function (json, url, uuid, callback, handle, existingAsset) { - // deserialize asset - //var isScene = typeof Scene !== 'undefined' && json && json[0] && json[0].__type__ === JS._getClassId(Scene); - //var classFinder = isScene ? cc._MissingScript.safeFindClass : function (id) { - var classFinder = function (id) { - var cls = JS._getClassById(id); - if (cls) { - return cls; - } - cc.warn('Can not get class "%s"', id); - return Object; - }; - - var tdInfo = cc.sys.isNative ? new cc.deserialize.Details() : (handle.deserializeInfo || _tdInfo); - - var asset = cc.deserialize(json, tdInfo, { - classFinder: classFinder, - target: existingAsset - }); - - var hasRawType = !!tdInfo.rawProp; - - if (uuid) { - handle.pendingCache[uuid] = asset; - } - - this._loadDepends(asset, tdInfo, url, handle, function () { - if (uuid) { - delete handle.pendingCache[uuid]; - } - callback(null, asset, hasRawType); - }); - - // tdInfo 是用来重用的临时对象,每次使用后都要重设,这样才对 GC 友好。 - tdInfo.reset(); }, /** @@ -524,7 +282,7 @@ var AssetLibrary = { mountPaths = { assets: _rawAssetsBase + 'assets', internal: _rawAssetsBase + 'internal', - } + }; } cc.url._init(mountPaths); } diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js index 59d366fb86..63cac354ae 100644 --- a/cocos2d/core/platform/CCClass.js +++ b/cocos2d/core/platform/CCClass.js @@ -417,7 +417,7 @@ function define (className, baseClasses, mixins, constructor, options) { JS._setClassId(uuid, cls); if (CC_EDITOR) { cc.Component._addMenuItem(cls, 'i18n:MAIN_MENU.component.scripts/' + className, -1); - cls.prototype.__scriptUuid = Editor.decompressUuid(uuid); + cls.prototype.__scriptUuid = Editor.UuidUtils.decompressUuid(uuid); } } frame.beh = cls; @@ -583,35 +583,26 @@ function _boundSuperCall (func, funcName, base) { var superFunc = null; var pd = JS.getPropertyDescriptor(base.prototype, funcName); if (pd) { - if (pd.value) { - if (typeof pd.value === 'function') { - superFunc = pd.value; + superFunc = pd.value; + // ignore pd.get, assume that function defined by getter is just for warnings + if (typeof superFunc === 'function') { + var hasSuperCall = SuperCallReg.test(func); + if (hasSuperCall) { + return function () { + var tmp = this._super; + + // Add a new ._super() method that is the same method but on the super-Class + this._super = superFunc; + + var ret = func.apply(this, arguments); + + // The method only need to be bound temporarily, so we remove it when we're done executing + this._super = tmp; + + return ret; + }; } } - else if (pd.get) { - var got = pd.get(); - if (typeof got === 'function') { - superFunc = got; - } - } - } - if (superFunc) { - var hasSuperCall = SuperCallReg.test(func); - if (hasSuperCall) { - return function () { - var tmp = this._super; - - // Add a new ._super() method that is the same method but on the super-Class - this._super = superFunc; - - var ret = func.apply(this, arguments); - - // The method only need to be bound temporarily, so we remove it when we're done executing - this._super = tmp; - - return ret; - }; - } } return null; } @@ -674,7 +665,6 @@ function declareProperties (cls, className, properties, baseClass, mixins) { * * @method Class * @param {Object} options - * TODO: add properties of options * @return {Function} - the created class * * @example @@ -782,7 +772,13 @@ function CCClass (options) { } var func = options[funcName]; if (typeof func === 'function' || func === null) { - cls.prototype[funcName] = func; + // use defineProperty to redefine some super method defined as getter + Object.defineProperty(cls.prototype, funcName, { + value: func, + enumerable: true, + configurable: true, + writable: true, + }); } else if (CC_DEV) { var correct = TYPO_TO_CORRECT[funcName]; diff --git a/cocos2d/core/platform/CCConfig.js b/cocos2d/core/platform/CCConfig.js index cd2fbf2495..a384437a16 100644 --- a/cocos2d/core/platform/CCConfig.js +++ b/cocos2d/core/platform/CCConfig.js @@ -31,7 +31,13 @@ * @type {String} * @name cc.ENGINE_VERSION */ -window['CocosEngine'] = cc.ENGINE_VERSION = 'Cocos Creator v0.8.0'; +var engineVersion; +if (CC_EDITOR) { + engineVersion = 'Cocos Creator v' + Editor.remote.versions.CocosCreator; +} else { + engineVersion = 'Cocos Creator'; +} +window['CocosEngine'] = cc.ENGINE_VERSION = engineVersion; /** *

diff --git a/cocos2d/core/platform/CCEGLView.js b/cocos2d/core/platform/CCEGLView.js index ec2617ced2..969abf81a4 100644 --- a/cocos2d/core/platform/CCEGLView.js +++ b/cocos2d/core/platform/CCEGLView.js @@ -114,9 +114,9 @@ switch(cc.__BrowserGetter.adaptationType){ * the standard way to use it is by calling:
* - cc.view.methodName();
* - * @class view + * @class View */ -cc.EGLView = cc._Class.extend(/** @lends cc.view# */{ +cc.EGLView = cc._Class.extend({ _delegate: null, // Size of parent node that contains cc.container and cc.game.canvas _frameSize: null, @@ -344,14 +344,6 @@ cc.EGLView = cc._Class.extend(/** @lends cc.view# */{ } }, - // RenderTexture hacker - _setScaleXYForRenderTexture: function () { - //hack for RenderTexture on canvas mode when adapting multiple resolution resources - var scaleFactor = cc.contentScaleFactor(); - this._scaleX = scaleFactor; - this._scaleY = scaleFactor; - }, - // Other helper functions _resetScale: function () { this._scaleX = this._originalScaleX; @@ -887,10 +879,13 @@ cc.EGLView = cc._Class.extend(/** @lends cc.view# */{ selTouch = touches[i]; selPoint = selTouch._point; selPrePoint = selTouch._prevPoint; + selStartPoint = selTouch._startPoint; selTouch._setPoint((selPoint.x - locViewPortRect.x) / locScaleX, (selPoint.y - locViewPortRect.y) / locScaleY); selTouch._setPrevPoint((selPrePoint.x - locViewPortRect.x) / locScaleX, (selPrePoint.y - locViewPortRect.y) / locScaleY); + selStartPoint.x = (selStartPoint.x - locViewPortRect.x) / locScaleX; + selStartPoint.y = (selStartPoint.y - locViewPortRect.y) / locScaleY; } } }); diff --git a/cocos2d/core/platform/CCLoader.js b/cocos2d/core/platform/CCLoader.js deleted file mode 100644 index 7c5819525c..0000000000 --- a/cocos2d/core/platform/CCLoader.js +++ /dev/null @@ -1,595 +0,0 @@ -var _noCacheRex = /\?/; -function urlAppendTimestamp (url) { - if (cc.game.config['noCache'] && typeof url === 'string') { - if(_noCacheRex.test(url)) - url += '&_t=' + (new Date() - 0); - else - url += '?_t=' + (new Date() - 0); - } - return url; -} - -/** - * Loader for resource loading process. It's a singleton object. - * @class loader - * @static - */ -cc.loader = cc.loader || (function () { - var _jsCache = {}, //cache for js - _register = {}, //register of loaders - _langPathCache = {}, //cache for lang path - _aliases = {}, //aliases for res url - _urlRegExp = new RegExp( - "^" + - // protocol identifier - "(?:(?:https?|ftp)://)" + - // user:pass authentication - "(?:\\S+(?::\\S*)?@)?" + - "(?:" + - // IP address dotted notation octets - // excludes loopback network 0.0.0.0 - // excludes reserved space >= 224.0.0.0 - // excludes network & broacast addresses - // (first & last IP address of each class) - "(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" + - "(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" + - "(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" + - "|" + - // host name - "(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" + - // domain name - "(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" + - // TLD identifier - "(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" + - "|" + - "(?:localhost)" + - ")" + - // port number - "(?::\\d{2,5})?" + - // resource path - "(?:/\\S*)?" + - "$", "i" - ); - - return /** @lends cc.loader# */{ - resPath: "",//root path of resource - audioPath: "",//root path of audio - cache: {},//cache for data loaded - - /** - * Get XMLHttpRequest. - * @returns {XMLHttpRequest} - */ - getXMLHttpRequest: function () { - return window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP"); - }, - - //@MODE_BEGIN DEV - - _getArgs4Js: function (args) { - var a0 = args[0], a1 = args[1], a2 = args[2], results = ["", null, null]; - - if (args.length === 1) { - results[1] = a0 instanceof Array ? a0 : [a0]; - } else if (args.length === 2) { - if (typeof a1 === "function") { - results[1] = a0 instanceof Array ? a0 : [a0]; - results[2] = a1; - } else { - results[0] = a0 || ""; - results[1] = a1 instanceof Array ? a1 : [a1]; - } - } else if (args.length === 3) { - results[0] = a0 || ""; - results[1] = a1 instanceof Array ? a1 : [a1]; - results[2] = a2; - } else throw new Error("arguments error to load js!"); - return results; - }, - - /** - * Load js files. - * If the third parameter doesn't exist, then the baseDir turns to be "". - * - * @method loadJs - * @param {String} [baseDir] - The pre path for jsList or the list of js path. - * @param {Array} jsList - List of js path. - * @param {Function} [cb] - Callback function - * @returns {*} - */ - loadJs: function (baseDir, jsList, cb) { - var self = this, - args = self._getArgs4Js(arguments); - - var preDir = args[0], list = args[1], callback = args[2]; - if (navigator.userAgent.indexOf("Trident/5") > -1) { - self._loadJs4Dependency(preDir, list, 0, callback); - } else { - cc.async.map(list, function (item, index, cb1) { - var jsPath = cc.path.join(preDir, item); - if (_jsCache[jsPath]) return cb1(null); - self._createScript(jsPath, false, cb1); - }, callback); - } - }, - /** - * Load js width loading image. - * - * @method loadJsWithImg - * @param {String} [baseDir] - * @param {Array} jsList - * @param {Function} [cb] - */ - loadJsWithImg: function (baseDir, jsList, cb) { - var self = this, jsLoadingImg = self._loadJsImg(), - args = self._getArgs4Js(arguments); - this.loadJs(args[0], args[1], function (err) { - if (err) throw new Error(err); - jsLoadingImg.parentNode.removeChild(jsLoadingImg);//remove loading gif - if (args[2]) args[2](); - }); - }, - _createScript: function (jsPath, isAsync, cb) { - var d = document, self = this, s = document.createElement('script'); - s.async = isAsync; - _jsCache[jsPath] = true; - s.src = urlAppendTimestamp(jsPath); - s.addEventListener('load', function () { - s.parentNode.removeChild(s); - s.removeEventListener('load', arguments.callee, false); - cb(); - }, false); - s.addEventListener('error', function () { - s.parentNode.removeChild(s); - cb("Load " + jsPath + " failed!"); - }, false); - d.body.appendChild(s); - }, - _loadJs4Dependency: function (baseDir, jsList, index, cb) { - if (index >= jsList.length) { - if (cb) cb(); - return; - } - var self = this; - self._createScript(cc.path.join(baseDir, jsList[index]), false, function (err) { - if (err) return cb(err); - self._loadJs4Dependency(baseDir, jsList, index + 1, cb); - }); - }, - _loadJsImg: function () { - var d = document, jsLoadingImg = d.getElementById("cocos2d_loadJsImg"); - if (!jsLoadingImg) { - jsLoadingImg = document.createElement('img'); - - if (cc._loadingImage) - jsLoadingImg.src = cc._loadingImage; - - var canvasNode = d.getElementById(cc.game.config["id"]); - canvasNode.style.backgroundColor = "transparent"; - canvasNode.parentNode.appendChild(jsLoadingImg); - - var canvasStyle = getComputedStyle ? getComputedStyle(canvasNode) : canvasNode.currentStyle; - if (!canvasStyle) - canvasStyle = {width: canvasNode.width, height: canvasNode.height}; - jsLoadingImg.style.left = canvasNode.offsetLeft + (parseFloat(canvasStyle.width) - jsLoadingImg.width) / 2 + "px"; - jsLoadingImg.style.top = canvasNode.offsetTop + (parseFloat(canvasStyle.height) - jsLoadingImg.height) / 2 + "px"; - jsLoadingImg.style.position = "absolute"; - } - return jsLoadingImg; - }, - //@MODE_END DEV - - /** - * Load a single resource as txt. - * - * @method loadTxt - * @param {String} url - * @param {Function} [cb] - arguments are : err, txt - */ - loadTxt: function (url, cb) { - var xhr = this.getXMLHttpRequest(), - errInfo = "load " + url + " failed!"; - - url = urlAppendTimestamp(url); - - xhr.open("GET", url, true); - if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) { - // IE-specific logic here - xhr.setRequestHeader("Accept-Charset", "utf-8"); - xhr.onreadystatechange = function () { - if(xhr.readyState === 4) - (xhr.status === 200 || xhr.status === 0) ? cb(null, xhr.responseText) : cb({status:xhr.status, errorMessage:errInfo}, null); - }; - } else { - if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8"); - xhr.onload = function () { - if(xhr.readyState === 4) { - (xhr.status === 200 || xhr.status === 0) ? cb(null, xhr.responseText) : cb({status:xhr.status, errorMessage:errInfo}, null); - } - }; - xhr.onerror = function(){ - cb({status:xhr.status, errorMessage:errInfo}, null); - }; - } - xhr.send(null); - }, - _loadTxtSync: function (url) { - var xhr = this.getXMLHttpRequest(); - xhr.open("GET", url, false); - if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) { - // IE-specific logic here - xhr.setRequestHeader("Accept-Charset", "utf-8"); - } else { - if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8"); - } - xhr.send(null); - if (!xhr.readyState === 4 || !(xhr.status === 200 || xhr.status === 0)) { - return null; - } - return xhr.responseText; - }, - - loadCsb: function(url, cb){ - var xhr = new XMLHttpRequest(), - errInfo = "load " + url + " failed!"; - - url = urlAppendTimestamp(url); - - xhr.open("GET", url, true); - xhr.responseType = "arraybuffer"; - - xhr.onload = function () { - var arrayBuffer = xhr.response; // Note: not oReq.responseText - if (arrayBuffer) { - window.msg = arrayBuffer; - } - if(xhr.readyState === 4) - xhr.status === 200 ? cb(null, xhr.response) : cb({status:xhr.status, errorMessage:errInfo}, null); - }; - xhr.onerror = function(){ - cb({status:xhr.status, errorMessage:errInfo}, null); - }; - xhr.send(null); - }, - - /** - * Load a single resource as json. - * - * @method loadJson - * @param {String} url - * @param {Function} [cb] - arguments are : err, json - */ - loadJson: function (url, cb) { - this.loadTxt(url, function (err, txt) { - if (err) { - cb(err); - } - else { - try { - var result = JSON.parse(txt); - } - catch (e) { - throw new Error("parse json [" + url + "] failed : " + e); - return; - } - cb(null, result); - } - }); - }, - - _checkIsImageURL: function (url) { - var ext = /(\.png)|(\.jpg)|(\.bmp)|(\.jpeg)|(\.gif)/.exec(url); - return (ext != null); - }, - /** - * Load a single image. - * - * @method loadImg - * @param {String} url - * @param {Object} [option] - * @param {Function} callback - * @returns {Image} - */ - loadImg: function (url, option, callback) { - var opt = { - isCrossOrigin: true - }; - if (callback !== undefined) - opt.isCrossOrigin = option.isCrossOrigin === null ? opt.isCrossOrigin : option.isCrossOrigin; - else if (option !== undefined) - callback = option; - - url = urlAppendTimestamp(url); - var isNew = false; - var img = this.getRes(url); - if (!img) { - img = new Image(); - isNew = true; - if (opt.isCrossOrigin && location.origin !== "file://") - img.crossOrigin = "Anonymous"; - } - - if (!isNew && img.complete && img.naturalWidth > 0) { - callback && callback(null, img); - } - else { - function loadCallback () { - img.removeEventListener('load', loadCallback); - img.removeEventListener('error', errorCallback); - - if (callback) - callback(null, img); - } - - var self = this; - function errorCallback () { - img.removeEventListener('load', loadCallback); - img.removeEventListener('error', errorCallback); - - if (img.crossOrigin && img.crossOrigin.toLowerCase() === "anonymous") { - opt.isCrossOrigin = false; - self.release(url); - cc.loader.loadImg(url, opt, callback); - } - else { - typeof callback === "function" && callback("load image failed"); - } - } - - img.addEventListener("load", loadCallback); - img.addEventListener("error", errorCallback); - } - - if (isNew) { - img.src = url; - } - return img; - }, - - /** - * Iterator function to load res. - * - * @method _loadResIterator - * @param {Object} item - * @param {Number} index - * @param {Function} [cb] - * @returns {*} - * @private - */ - _loadResIterator: function (item, index, cb) { - var self = this, url = null; - var type = item.type; - if (type) { - type = "." + type.toLowerCase(); - url = item.src ? item.src : item.name + type; - } else { - url = item; - type = cc.path.extname(url); - } - - var obj = self.getRes(url); - if (obj) - return cb(null, obj); - var loader = null; - if (type) { - loader = _register[type.toLowerCase()]; - } - if (!loader) { - cc.error("loader for [" + type + "] not exists!"); - return cb(); - } - var realUrl = url; - if (!_urlRegExp.test(url)) - { - var basePath = loader.getBasePath ? loader.getBasePath() : self.resPath; - realUrl = self.getUrl(basePath, url); - } - - loader.load(realUrl, url, item, function (err, data) { - if (err) { - cc.log(err); - self.cache[url] = null; - delete self.cache[url]; - cb({status:520, errorMessage:err}, null); - } else { - self.cache[url] = data; - cb(null, data); - } - }); - }, - - /** - * Get url with basePath. - * - * @method getUrl - * @param {String} basePath - * @param {String} [url] - * @returns {*} - */ - getUrl: function (basePath, url) { - var self = this, path = cc.path; - if (basePath !== undefined && url === undefined) { - url = basePath; - var type = path.extname(url); - type = type ? type.toLowerCase() : ""; - var loader = _register[type]; - if (!loader) - basePath = self.resPath; - else - basePath = loader.getBasePath ? loader.getBasePath() : self.resPath; - } - url = cc.path.join(basePath || "", url); - if (url.match(/[\/(\\\\)]lang[\/(\\\\)]/i)) { - if (_langPathCache[url]) - return _langPathCache[url]; - var extname = path.extname(url) || ""; - url = _langPathCache[url] = url.substring(0, url.length - extname.length) + "_" + cc.sys.language + extname; - } - return url; - }, - - /** - * Load resources then call the callback. - * - * @method load - * @param {String} resources - * @param {Function} [option] - callback or trigger - * @param {Function|Object} [loadCallback] - * @return {AsyncPool} - */ - load: function(resources, option, loadCallback){ - 'use strict'; - - var self = this; - var len = arguments.length; - if(len === 0) - throw new Error("arguments error!"); - - if(len === 3){ - if(typeof option === "function"){ - if(typeof loadCallback === "function") - option = {trigger : option, cb : loadCallback }; - else - option = { cb : option, cbTarget : loadCallback}; - } - }else if(len === 2){ - if(typeof option === "function") - option = {cb : option}; - }else if(len === 1){ - option = {}; - } - - if(!(resources instanceof Array)) - resources = [resources]; - var asyncPool = new cc.AsyncPool( - resources, 0, - function (value, index, AsyncPoolCallback, aPool) { - self._loadResIterator(value, index, function (err, res) { - if (option.trigger) - option.trigger.call(option.triggerTarget, res, aPool.size, aPool.finishedSize); //call trigger - AsyncPoolCallback(err, res); - }); - }, - option.cb, option.cbTarget); - asyncPool.flow(); - return asyncPool; - }, - - _handleAliases: function (fileNames, cb) { - var self = this; - var resList = []; - for (var key in fileNames) { - var value = fileNames[key]; - _aliases[key] = value; - resList.push(value); - } - this.load(resList, cb); - }, - - /** - *

- * Loads alias map from the contents of a filename.
- *
- * @note The plist file name should follow the format below:
- *
- *
- *
- *
- * filenames
- *
- * sounds/click.wav
- * sounds/click.caf
- * sounds/endgame.wav
- * sounds/endgame.caf
- * sounds/gem-0.wav
- * sounds/gem-0.caf
- *

- * metadata
- *
- * version
- * 1
- *

- *

- *

- *

- * - * @method loadAliases - * @param {String} url - The plist file name. - * @param {Function} [callback] - */ - loadAliases: function (url, callback) { - var self = this, dict = self.getRes(url); - if (!dict) { - self.load(url, function (err, results) { - self._handleAliases(results[0]["filenames"], callback); - }); - } else - self._handleAliases(dict["filenames"], callback); - }, - - /** - * Register a resource loader into loader. - * - * @method register - * @param {String} extNames - * @param {Function} loader - */ - register: function (extNames, loader) { - if (!extNames || !loader) return; - var self = this; - if (typeof extNames === "string") - return _register[extNames.trim().toLowerCase()] = loader; - for (var i = 0, li = extNames.length; i < li; i++) { - _register["." + extNames[i].trim().toLowerCase()] = loader; - } - }, - - /** - * Get resource data by url. - * - * @method getRes - * @param {String} url - * @returns {*} - */ - getRes: function (url) { - return this.cache[url] || this.cache[_aliases[url]]; - }, - - /** - * Get aliase by url. - * - * @method getAliase - * @param {String} url - * @returns {*} - */ - getAliase: function (url) { - return _aliases[url]; - }, - - /** - * Release the cache of resource by url. - * - * @method release - * @param {String} url - */ - release: function (url) { - var cache = this.cache; - delete cache[url]; - delete cache[_aliases[url]]; - delete _aliases[url]; - }, - - /** - * Resource cache of all resources. - * - * @method releaseAll - */ - releaseAll: function () { - var locCache = this.cache; - for (var key in locCache) - delete locCache[key]; - for (var key in _aliases) - delete _aliases[key]; - } - }; -})(); \ No newline at end of file diff --git a/cocos2d/core/platform/CCLoaders.js b/cocos2d/core/platform/CCLoaders.js deleted file mode 100644 index 73ed071437..0000000000 --- a/cocos2d/core/platform/CCLoaders.js +++ /dev/null @@ -1,156 +0,0 @@ -/**************************************************************************** - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -cc._txtLoader = { - load : function(realUrl, url, res, cb){ - cc.loader.loadTxt(realUrl, cb); - } -}; -cc.loader.register(["txt", "xml", "vsh", "fsh", "atlas"], cc._txtLoader); - -cc._jsonLoader = { - load : function(realUrl, url, res, cb){ - cc.loader.loadJson(realUrl, cb); - } -}; -cc.loader.register(["json", "ExportJson"], cc._jsonLoader); - -cc._jsLoader = { - load : function(realUrl, url, res, cb){ - cc.loader.loadJs(realUrl, cb); - } -}; -cc.loader.register(["js"], cc._jsLoader); - -cc._imgLoader = { - load : function(realUrl, url, res, cb){ - cc.loader.cache[url] = cc.loader.loadImg(realUrl, function(err, img){ - if(err) - return cb(err); - cc.textureCache.handleLoadedTexture(url); - cb(null, img); - }); - } -}; -cc.loader.register(["png", "jpg", "bmp","jpeg","gif", "ico", "tiff", "webp"], cc._imgLoader); -cc._serverImgLoader = { - load : function(realUrl, url, res, cb){ - cc.loader.cache[url] = cc.loader.loadImg(res.src, function(err, img){ - if(err) - return cb(err); - cc.textureCache.handleLoadedTexture(url); - cb(null, img); - }); - } -}; -cc.loader.register(["serverImg"], cc._serverImgLoader); - -cc._plistLoader = { - load : function(realUrl, url, res, cb){ - cc.loader.loadTxt(realUrl, function(err, txt){ - if(err) - return cb(err); - cb(null, cc.plistParser.parse(txt)); - }); - } -}; -cc.loader.register(["plist"], cc._plistLoader); - -cc._fontLoader = { - TYPE : { - ".eot" : "embedded-opentype", - ".ttf" : "truetype", - ".ttc" : "truetype", - ".woff" : "woff", - ".svg" : "svg" - }, - _loadFont : function(name, srcs, type){ - var doc = document, path = cc.path, TYPE = this.TYPE, fontStyle = document.createElement("style"); - fontStyle.type = "text/css"; - doc.body.appendChild(fontStyle); - - var fontStr = ""; - if(isNaN(name - 0)) - fontStr += "@font-face { font-family:" + name + "; src:"; - else - fontStr += "@font-face { font-family:'" + name + "'; src:"; - if(srcs instanceof Array){ - for(var i = 0, li = srcs.length; i < li; i++){ - var src = srcs[i]; - type = path.extname(src).toLowerCase(); - fontStr += "url('" + srcs[i] + "') format('" + TYPE[type] + "')"; - fontStr += (i === li - 1) ? ";" : ","; - } - }else{ - type = type.toLowerCase(); - fontStr += "url('" + srcs + "') format('" + TYPE[type] + "');"; - } - fontStyle.textContent += fontStr + "}"; - - //
.
- var preloadDiv = document.createElement("div"); - var _divStyle = preloadDiv.style; - _divStyle.fontFamily = name; - preloadDiv.innerHTML = "."; - _divStyle.position = "absolute"; - _divStyle.left = "-100px"; - _divStyle.top = "-100px"; - doc.body.appendChild(preloadDiv); - }, - load : function(realUrl, url, res, cb){ - var self = this; - var type = res.type, name = res.name, srcs = res.srcs; - if(cc.js.isString(res)){ - type = cc.path.extname(res); - name = cc.path.basename(res, type); - self._loadFont(name, res, type); - }else{ - self._loadFont(name, srcs); - } - if(document.fonts){ - document.fonts.load("1em " + name).then(function(){ - cb(null, true); - }, function(err){ - cb(err); - }); - }else{ - cb(null, true); - } - } -}; -cc.loader.register(["font", "eot", "ttf", "woff", "svg", "ttc"], cc._fontLoader); - -cc._binaryLoader = { - load : function(realUrl, url, res, cb){ - cc.loader.loadBinary(realUrl, cb); - } -}; - -cc._csbLoader = { - load: function(realUrl, url, res, cb){ - cc.loader.loadCsb(realUrl, cb); - } -}; -cc.loader.register(["csb"], cc._csbLoader); diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js index c64457e7b7..830039c188 100644 --- a/cocos2d/core/platform/CCMacro.js +++ b/cocos2d/core/platform/CCMacro.js @@ -97,7 +97,7 @@ cc.swap = function (x, y, ref) { * @param {Number} b number B * @param {Number} r ratio between 0 and 1 * @method lerp - * @example {@link utils/api/engine/docs/cocos2d/core/platform/CCMacro/.js} + * @example {@link utils/api/engine/docs/cocos2d/core/platform/CCMacro/lerp.js} */ cc.lerp = function (a, b, r) { return a + (b - a) * r; @@ -234,104 +234,6 @@ cc.incrementGLDraws = function (addNumber) { */ cc.FLT_EPSILON = 0.0000001192092896; -/** - *

- * On Mac it returns 1;
- * On iPhone it returns 2 if RetinaDisplay is On. Otherwise it returns 1 - *

- * @return {Number} - * @method contentScaleFactor - */ -cc.contentScaleFactor = cc.IS_RETINA_DISPLAY_SUPPORTED ? function () { - return cc.director.getContentScaleFactor(); -} : function () { - return 1; -}; - -/** - * Converts a Point in points to pixels - * @param {Vec2} points - * @return {Vec2} - * @method pointPointsToPixels - */ -cc.pointPointsToPixels = function (points) { - var scale = cc.contentScaleFactor(); - return cc.p(points.x * scale, points.y * scale); -}; - -/** - * Converts a Point in pixels to points - * @param {Rect} pixels - * @return {Vec2} - * @method pointPixelsToPoints - */ -cc.pointPixelsToPoints = function (pixels) { - var scale = cc.contentScaleFactor(); - return cc.p(pixels.x / scale, pixels.y / scale); -}; - -cc._pointPixelsToPointsOut = function(pixels, outPoint){ - var scale = cc.contentScaleFactor(); - outPoint.x = pixels.x / scale; - outPoint.y = pixels.y / scale; -}; - -/** - * Converts a Size in points to pixels - * @param {Size} sizeInPoints - * @return {Size} - * @method sizePointsToPixels - */ -cc.sizePointsToPixels = function (sizeInPoints) { - var scale = cc.contentScaleFactor(); - return cc.size(sizeInPoints.width * scale, sizeInPoints.height * scale); -}; - -/** - * Converts a size in pixels to points - * @param {Size} sizeInPixels - * @return {Size} - * @method sizePixelsToPoints - */ -cc.sizePixelsToPoints = function (sizeInPixels) { - var scale = cc.contentScaleFactor(); - return cc.size(sizeInPixels.width / scale, sizeInPixels.height / scale); -}; - -cc._sizePixelsToPointsOut = function (sizeInPixels, outSize) { - var scale = cc.contentScaleFactor(); - outSize.width = sizeInPixels.width / scale; - outSize.height = sizeInPixels.height / scale; -}; - -/** - * Converts a rect in pixels to points - * @param {Rect} pixel - * @return {Rect} - * @method rectPixelsToPoints - */ -cc.rectPixelsToPoints = cc.IS_RETINA_DISPLAY_SUPPORTED ? function (pixel) { - var scale = cc.contentScaleFactor(); - return cc.rect(pixel.x / scale, pixel.y / scale, - pixel.width / scale, pixel.height / scale); -} : function (p) { - return cc.rect(p); -}; - -/** - * Converts a rect in points to pixels - * @param {Rect} point - * @return {Rect} - * @method rectPointsToPixels - */ -cc.rectPointsToPixels = cc.IS_RETINA_DISPLAY_SUPPORTED ? function (point) { - var scale = cc.contentScaleFactor(); - return cc.rect(point.x * scale, point.y * scale, - point.width * scale, point.height * scale); -} : function (p) { - return cc.rect(p); -}; - //some gl constant variable /** * @property {Number} ONE diff --git a/cocos2d/core/platform/CCSys.js b/cocos2d/core/platform/CCSys.js index 3de3f41838..dcb71c10da 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -450,6 +450,7 @@ if (typeof Editor !== 'undefined' && Editor.isCoreLevel) { width: 0, height: 0 }; + sys.__audioSupport = {}; } else { // browser or runtime @@ -581,6 +582,7 @@ else { //Whether or not the Canvas BlendModes are supported. sys._supportCanvasNewBlendModes = (function(){ + var data1, data2; var canvas = _tmpCanvas1; canvas.width = 1; canvas.height = 1; @@ -597,7 +599,27 @@ else { context2.fillRect(0,0,1,1); context.drawImage(canvas2, 0, 0, 1, 1); - return context.getImageData(0,0,1,1).data[0] === 0; + data1 = context.getImageData(0,0,1,1).data[0]; + + canvas = _tmpCanvas1; + canvas.width = 1; + canvas.height = 1; + var context = canvas.getContext('2d'); + context.fillStyle = '#fff'; + context.fillRect(0,0,1,1); + context.globalCompositeOperation = 'destination-atop'; + + canvas2 = _tmpCanvas2; + canvas2.width = 1; + canvas2.height = 1; + var context2 = canvas2.getContext('2d'); + context2.fillStyle = '#000'; + context2.fillRect(0,0,1,1); + context.drawImage(canvas2, 0, 0, 1, 1); + + data2 = context.getImageData(0,0,1,1).data[0]; + + return (data1 === 0) && (data2 === 0); })(); // Adjust mobile css settings @@ -677,6 +699,144 @@ else { delete _tmpCanvas1; delete _tmpCanvas2; + + var __audioSupport; + + /** + * Audio support in the browser + * + * MULTI_CHANNEL : Multiple audio while playing - If it doesn't, you can only play background music + * WEB_AUDIO : Support for WebAudio - Support W3C WebAudio standards, all of the audio can be played + * AUTOPLAY : Supports auto-play audio - if Don‘t support it, On a touch detecting background music canvas, and then replay + * REPLAY_AFTER_TOUCH : The first music will fail, must be replay after touchstart + * USE_EMPTIED_EVENT : Whether to use the emptied event to replace load callback + * DELAY_CREATE_CTX : delay created the context object - only webAudio + * NEED_MANUAL_LOOP : WebAudio loop attribute failure, need to manually perform loop + * + * May be modifications for a few browser version + */ + (function(){ + + var DEBUG = false; + + var version = sys.browserVersion; + + // check if browser supports Web Audio + // check Web Audio's context + var supportWebAudio = !!(window.AudioContext || window.webkitAudioContext || window.mozAudioContext); + + var supportTable = { + 'common' : {MULTI_CHANNEL: true , WEB_AUDIO: supportWebAudio , AUTOPLAY: true } + }; + + supportTable[sys.BROWSER_TYPE_IE] = {MULTI_CHANNEL: true , WEB_AUDIO: supportWebAudio , AUTOPLAY: true, USE_EMPTIED_EVENT: true}; + // ANDROID // + supportTable[sys.BROWSER_TYPE_ANDROID] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false}; + supportTable[sys.BROWSER_TYPE_CHROME] = {MULTI_CHANNEL: true , WEB_AUDIO: true , AUTOPLAY: false}; + supportTable[sys.BROWSER_TYPE_FIREFOX] = {MULTI_CHANNEL: true , WEB_AUDIO: true , AUTOPLAY: true , DELAY_CREATE_CTX: true}; + supportTable[sys.BROWSER_TYPE_UC] = {MULTI_CHANNEL: true , WEB_AUDIO: false, AUTOPLAY: false}; + supportTable[sys.BROWSER_TYPE_QQ] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: true }; + supportTable[sys.BROWSER_TYPE_OUPENG] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true }; + supportTable[sys.BROWSER_TYPE_WECHAT] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true }; + supportTable[sys.BROWSER_TYPE_360] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: true }; + supportTable[sys.BROWSER_TYPE_MIUI] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: true }; + supportTable[sys.BROWSER_TYPE_LIEBAO] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true }; + supportTable[sys.BROWSER_TYPE_SOUGOU] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true }; + //'Baidu' browser can automatically play + //But because it may be play failed, so need to replay and auto + supportTable[sys.BROWSER_TYPE_BAIDU] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true }; + supportTable[sys.BROWSER_TYPE_BAIDU_APP]= {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true }; + + // APPLE // + supportTable[sys.BROWSER_TYPE_SAFARI] = {MULTI_CHANNEL: true , WEB_AUDIO: true , AUTOPLAY: false, webAudioCallback: function(realUrl){ + document.createElement('audio').src = realUrl; + }}; + + if(sys.isMobile){ + if(sys.os !== sys.OS_IOS) + __audioSupport = supportTable[sys.browserType] || supportTable['common']; + else + __audioSupport = supportTable[sys.BROWSER_TYPE_SAFARI]; + }else{ + switch(sys.browserType){ + case sys.BROWSER_TYPE_IE: + __audioSupport = supportTable[sys.BROWSER_TYPE_IE]; + break; + case sys.BROWSER_TYPE_FIREFOX: + __audioSupport = supportTable[sys.BROWSER_TYPE_FIREFOX]; + break; + default: + __audioSupport = supportTable['common']; + } + } + + /////////////////////////// + // Browser compatibility// + /////////////////////////// + if(version){ + switch(sys.browserType){ + case sys.BROWSER_TYPE_CHROME: + version = parseInt(version); + if(version < 30){ + __audioSupport = {MULTI_CHANNEL: false , WEB_AUDIO: true , AUTOPLAY: false}; + }else if(version === 42){ + __audioSupport.NEED_MANUAL_LOOP = true; + } + break; + case sys.BROWSER_TYPE_MIUI: + if(sys.isMobile){ + version = version.match(/\d+/g); + if(version[0] < 2 || (version[0] === 2 && version[1] === 0 && version[2] <= 1)){ + __audioSupport.AUTOPLAY = false; + } + } + break; + } + } + + if(DEBUG){ + setTimeout(function(){ + cc.log('browse type: ' + sys.browserType); + cc.log('browse version: ' + version); + cc.log('MULTI_CHANNEL: ' + __audioSupport.MULTI_CHANNEL); + cc.log('WEB_AUDIO: ' + __audioSupport.WEB_AUDIO); + cc.log('AUTOPLAY: ' + __audioSupport.AUTOPLAY); + }, 0); + } + })(); + + try { + if (__audioSupport.WEB_AUDIO) { + __audioSupport.context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); + if(__audioSupport.DELAY_CREATE_CTX) { + setTimeout(function(){ __audioSupport.context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); }, 0); + } + } + } catch(error) { + __audioSupport.WEB_AUDIO = false; + cc.log("browser don't support web audio"); + } + + var formatSupport = []; + + (function(){ + var audio = document.createElement('audio'); + if(audio.canPlayType) { + var ogg = audio.canPlayType('audio/ogg; codecs="vorbis"'); + if (ogg) formatSupport.push('.ogg'); + var mp3 = audio.canPlayType('audio/mpeg'); + if (mp3) formatSupport.push('.mp3'); + var wav = audio.canPlayType('audio/wav; codecs="1"'); + if (wav) formatSupport.push('.wav'); + var mp4 = audio.canPlayType('audio/mp4'); + if (mp4) formatSupport.push('.mp4'); + var m4a = audio.canPlayType('audio/x-m4a'); + if (m4a) formatSupport.push('.m4a'); + } + })(); + __audioSupport.format = formatSupport; + + sys.__audioSupport = __audioSupport; } /** diff --git a/cocos2d/core/platform/attribute.js b/cocos2d/core/platform/attribute.js index 0a0cbd6983..ec2b81bb08 100644 --- a/cocos2d/core/platform/attribute.js +++ b/cocos2d/core/platform/attribute.js @@ -27,23 +27,23 @@ var JS = require('./js'); var isPlainEmptyObj = require('./utils').isPlainEmptyObj_DEV; -/** - * @class Class - */ +// /** +// * @class Class +// */ -/** - * Tag the class with any meta attributes, then return all current attributes assigned to it. - * This function holds only the attributes, not their implementations. - * - * @method attr - * @param {Function|Object} constructor - the class or instance. If instance, the attribute will be dynamic and only available for the specified instance. - * @param {String} propertyName - the name of property or function, used to retrieve the attributes - * @param {Object} [attributes] - the attribute table to mark, new attributes will merged with existed attributes. Attribute whose key starts with '_' will be ignored. - * @return {Object|Undefined} return all attributes associated with the property. if none undefined will be returned - * @static - * @private - * @example {@link utils/api/engine/docs/cocos2d/core/platform/attribute/attr.js} - */ +// * +// * Tag the class with any meta attributes, then return all current attributes assigned to it. +// * This function holds only the attributes, not their implementations. +// * +// * @method attr +// * @param {Function|Object} constructor - the class or instance. If instance, the attribute will be dynamic and only available for the specified instance. +// * @param {String} propertyName - the name of property or function, used to retrieve the attributes +// * @param {Object} [attributes] - the attribute table to mark, new attributes will merged with existed attributes. Attribute whose key starts with '_' will be ignored. +// * @return {Object|Undefined} return all attributes associated with the property. if none undefined will be returned +// * @static +// * @private +// * @example {@link utils/api/engine/docs/cocos2d/core/platform/attribute/attr.js} + function attr (constructor, propertyName, attributes) { var key = '_attr$' + propertyName; var instance, attrs, name; diff --git a/cocos2d/core/platform/callbacks-invoker.js b/cocos2d/core/platform/callbacks-invoker.js index ae304688cc..263f35d673 100644 --- a/cocos2d/core/platform/callbacks-invoker.js +++ b/cocos2d/core/platform/callbacks-invoker.js @@ -22,13 +22,7 @@ CallbacksHandler.prototype.add = function (key, callback, target) { var list = this._callbackTable[key]; if (typeof list !== 'undefined') { if (typeof callback === 'function') { - if (list !== null) { - list.push(callback); - } - else { - list = [callback]; - this._callbackTable[key] = list; - } + list.push(callback); // Just append the target after callback if (typeof target === 'object') { list.push(target); @@ -38,7 +32,7 @@ CallbacksHandler.prototype.add = function (key, callback, target) { } else { // new key - list = (typeof callback === 'function') ? [callback] : null; + list = (typeof callback === 'function') ? [callback] : []; // Just append the target after callback if (list && typeof target === 'object') { list.push(target); @@ -90,6 +84,11 @@ CallbacksHandler.prototype.has = function (key, callback, target) { * @param {String|Object} key - The event key to be removed or the target to be removed */ CallbacksHandler.prototype.removeAll = function (key) { + // Delay removing + if (this._invoking) { + this._toRemoveAll = key; + return; + } if (typeof key === 'object') { var target = key, list, index, callback; // loop for all event types @@ -120,6 +119,12 @@ CallbacksHandler.prototype.removeAll = function (key) { CallbacksHandler.prototype.remove = function (key, callback, target) { var list = this._callbackTable[key], index, callbackTarget; if (list) { + // Delay removing + if (this._invoking === key) { + this._toRemove.push([callback, target]); + return true; + } + index = list.indexOf(callback); while (index !== -1) { callbackTarget = list[index+1]; @@ -148,6 +153,9 @@ CallbacksHandler.prototype.remove = function (key, callback, target) { */ var CallbacksInvoker = function () { CallbacksHandler.call(this); + this._invoking = null; + this._toRemove = []; + this._toRemoveAll = null; }; JS.extend(CallbacksInvoker, CallbacksHandler); @@ -165,11 +173,12 @@ if (CC_TEST) { * @param {any} [p5] */ CallbacksInvoker.prototype.invoke = function (key, p1, p2, p3, p4, p5) { - var list = this._callbackTable[key]; + this._toRemove.length = 0; + this._invoking = key; + var list = this._callbackTable[key], i; if (list) { var endIndex = list.length - 1; - var lastItem = list[endIndex]; - for (var i = 0; i <= endIndex;) { + for (i = 0; i <= endIndex;) { var callingFunc = list[i]; var target = list[i + 1]; var hasTarget = target && typeof target === 'object'; @@ -183,29 +192,21 @@ CallbacksInvoker.prototype.invoke = function (key, p1, p2, p3, p4, p5) { increment = 1; } - // TODO: check in remove - // check last one to see if any one removed - if (list[endIndex] !== lastItem && i + increment <= endIndex) { // 如果变短 - if (list[endIndex - 1] === lastItem) { - // 只支持删一个 - endIndex -= 1; - } - else if (list[endIndex - 2] === lastItem) { - // 只支持删一个 + target - endIndex -= 2; - } - else { - // 只允许在一个回调里面移除一个回调 - return cc.error('Can remove only a callback at a time.'); - } - if (list[i] !== callingFunc) { // 如果删了前面的回调,索引不加 - continue; - } - } - i += increment; } } + this._invoking = null; + + // Delay removing + for (i = 0; i < this._toRemove.length; ++i) { + var toRemove = this._toRemove[i]; + this.remove(key, toRemove[0], toRemove[1]); + } + this._toRemove.length = 0; + if (this._toRemoveAll) { + this.removeAll(this._toRemoveAll); + this._toRemoveAll = null; + } }; /** diff --git a/cocos2d/core/platform/deserialize.js b/cocos2d/core/platform/deserialize.js index 12c98870fd..31fc98e91e 100644 --- a/cocos2d/core/platform/deserialize.js +++ b/cocos2d/core/platform/deserialize.js @@ -404,9 +404,15 @@ var _Deserializer = (function () { // Type Object (including CCClass) - klass = self._classFinder(serialized.__type__); + var type = serialized.__type__; + klass = self._classFinder(type); if (!klass) { - cc.error('[cc.deserialize] unknown type: ' + serialized.__type__); + if (CC_EDITOR && Editor.UuidUtils.isUuid(type)) { + type = Editor.UuidUtils.decompressUuid(type); + cc.warn('Can not find script "%s"', type); + return null; + } + cc.warn('Can not find class "%s"', type); return null; } diff --git a/cocos2d/core/platform/index.js b/cocos2d/core/platform/index.js index e6fdceef93..d981cc5412 100644 --- a/cocos2d/core/platform/index.js +++ b/cocos2d/core/platform/index.js @@ -34,10 +34,8 @@ require('./instantiate'); require('./prefab-info'); require('./requiring-frame'); require('./CCSys'); -require('./CCLoader'); require('./CCMacro'); if (cc.sys.isBrowser || cc.sys.isNative) { - require('./load-manager'); require('./CCAssetLibrary'); } diff --git a/cocos2d/core/platform/load-manager.js b/cocos2d/core/platform/load-manager.js deleted file mode 100644 index b6099fbe8f..0000000000 --- a/cocos2d/core/platform/load-manager.js +++ /dev/null @@ -1,204 +0,0 @@ -var CallbacksInvoker = require('./callbacks-invoker'); - -function getBuiltinRawTypes () { - return { - image: { - loader: cc.loader.loadImg.bind(cc.loader), - defaultExtname: '.host' - }, - json: { - loader: cc.loader.loadJson.bind(cc.loader), - defaultExtname: '.json' - }, - text: { - loader: cc.loader.loadTxt.bind(cc.loader), - defaultExtname: '.txt' - } - }; -} - -var urlToCallbacks = new CallbacksInvoker(); - - - // list of elements to load, the element type is { - // url: url, - // loader: loader, - // callback: callback, - // } -var loadQueue = []; - -var loadNext = function () { - if (LoadManager._curConcurrent >= LoadManager.maxConcurrent) { - cc.error('too many concurrent requests'); - return; - } - var nextOne = loadQueue.pop(); - if (nextOne) { - doLoad(nextOne.loader, nextOne.url, nextOne.callback); - } -}; - -function doLoad (loader, url, callback) { - LoadManager._curConcurrent += 1; - loader(url, function doLoadCB (error, asset) { - callback(error, asset); - LoadManager._curConcurrent = Math.max(0, LoadManager._curConcurrent - 1); - loadNext(); - }); -} - -/** -* The manager scheduling resources loading -* - It will: -* - select registered loader -* - merge same url request -* - limit the max concurrent request -* - It will NOT: -* - cache what has being loaded -* - load depends of resource -* @class LoadManager -* @static -*/ -var LoadManager = { - - /** - * Max allowed concurrent request count - * @property {Number} maxConcurrent - * @default 2 - */ - maxConcurrent: 2, - - /** - * Current concurrent request count - * @property {Number} _curConcurrent - * @readOnly - */ - _curConcurrent: 0, - - /** - * NOTE: Request the same url with different loader is disallowed - * @method loadByLoader - * @param {Function} loader - * @param {String} url - * @param {Function} callback - * @param {String} callback.param error - null or the error info - * @param {any} callback.param data - the loaded data - * @private - */ - loadByLoader: function (loader, url, callback) { - if (urlToCallbacks.add(url, callback)) { - var callbackBundle = urlToCallbacks.bindKey(url, true); - if (this._curConcurrent < this.maxConcurrent) { - doLoad(loader, url, callbackBundle); - } - else { - loadQueue.push({ - url: url, - loader: loader, - callback: callbackBundle - }); - } - } - }, - - /** - * @method load - * @param {String} url - * @param {String} rawType - * @param {String} [rawExtname] - * @param {Function} callback - * @param {String} callback.param error - null or the error info - * @param {any} callback.param data - the loaded data - * @private - */ - load: function (url, rawType, rawExtname, callback) { - if (typeof rawExtname === 'function') { - callback = rawExtname; - } - var typeInfo = this._rawTypes[rawType]; - if (typeInfo) { - var extname = rawExtname ? ('.' + rawExtname) : typeInfo.defaultExtname; - if (extname) { - var rawUrl = url + extname; - this.loadByLoader(typeInfo.loader, rawUrl, callback); - } - else { - callback(new Error('Undefined extname for the raw ' + rawType + ' file of ' + url), null); - } - } - else { - callback(new Error('Unknown raw type "' + rawType + '" of ' + url), null); - } - }, - - _rawTypes: getBuiltinRawTypes(), - - /** - * @method registerRawTypes - * @param {String} rawType - * @param {Function} loader - * @param {String} defaultExtname - */ - registerRawTypes: function (rawType, loader, defaultExtname) { - if (CC_DEV) { - if (!rawType) { - cc.error('[AssetLibrary.registerRawTypes] rawType must be non-nil'); - return; - } - if (typeof rawType !== 'string') { - cc.error('[AssetLibrary.registerRawTypes] rawType must be string'); - return; - } - if (!loader) { - cc.error('[AssetLibrary.registerRawTypes] loader must be non-nil'); - return; - } - if (typeof loader !== 'function') { - cc.error('[AssetLibrary.registerRawTypes] loader must be function'); - return; - } - } - if (this._rawTypes[rawType]) { - cc.error('rawType "%s" has already defined', rawType); - return; - } - if (defaultExtname && defaultExtname[0] !== '.') { - defaultExtname = '.' + defaultExtname; - } - this._rawTypes[rawType] = { - loader: loader, - defaultExtname: defaultExtname - }; - }, - - reset: function () { - if (CC_EDITOR) { - var audio = this._rawTypes.audio; - this._rawTypes = getBuiltinRawTypes(); - this._rawTypes.audio = audio; - } - }, - - isLoading: function (url, alsoCheckRaw) { - if (CC_EDITOR) { - if (this._curConcurrent === 0) { - return false; - } - if (urlToCallbacks.has(url)) { - return true; - } - if (alsoCheckRaw) { - for (var u in urlToCallbacks._callbackTable) { - if (u.indexOf(url) === 0) { - return true; - } - } - } - return false; - } - } -}; - -// TODO - merge with cc.loader -cc._LoadManager = LoadManager; -module.exports = LoadManager; diff --git a/cocos2d/core/platform/utils.js b/cocos2d/core/platform/utils.js index fb34510757..67130ae479 100644 --- a/cocos2d/core/platform/utils.js +++ b/cocos2d/core/platform/utils.js @@ -77,10 +77,13 @@ if (CC_DEV) { if (CC_TEST) { // editor mocks using in unit tests if (typeof Editor === 'undefined') { - Editor = {}; + Editor = { + UuidUtils: { + NonUuidMark: '.', + uuid: function () { + return '' + ((new Date()).getTime() + Math.random()); + } + } + }; } - Editor.uuid = function () { - return '' + ((new Date()).getTime() + Math.random()); - }; - Editor.NonUuidMark = '.'; } diff --git a/cocos2d/core/scenes/CCLoaderScene.js b/cocos2d/core/scenes/CCLoaderScene.js index 41b205ba27..1d7a02f3de 100644 --- a/cocos2d/core/scenes/CCLoaderScene.js +++ b/cocos2d/core/scenes/CCLoaderScene.js @@ -56,11 +56,12 @@ cc.LoaderScene = _ccsg.Scene.extend({ var fontSize = 24, lblHeight = -logoHeight / 2 + 100; if(cc._loaderImage){ //loading logo - cc.loader.loadImg(cc._loaderImage, {isCrossOrigin : false }, function(err, img){ - logoWidth = img.width; - logoHeight = img.height; - self._initStage(img, cc.visibleRect.center); - }); + var img = new Image(); + img.src = cc._loaderImage; + logoWidth = img.width; + logoHeight = img.height; + self._initStage(img, cc.visibleRect.center); + fontSize = 14; lblHeight = -logoHeight / 2 - 10; } @@ -78,7 +79,6 @@ cc.LoaderScene = _ccsg.Scene.extend({ texture2d.initWithElement(img); texture2d.handleLoadedTexture(); var logo = self._logo = new _ccsg.Sprite(texture2d); - logo.setScale(cc.contentScaleFactor()); logo.x = centerPos.x; logo.y = centerPos.y; self._bgLayer.addChild(logo, 10); @@ -124,13 +124,13 @@ cc.LoaderScene = _ccsg.Scene.extend({ self.unschedule(self._startLoading); var res = self.resources; cc.loader.load(res, - function (result, count, loadedCount) { + function (loadedCount, count) { var percent = (loadedCount / count * 100) | 0; percent = Math.min(percent, 100); self._label.setString("Loading... " + percent + "%"); - }, function () { + }, function (error, items) { if (self.cb) - self.cb.call(self.target); + self.cb.call(self.target, error, items); }); }, diff --git a/cocos2d/core/sprites/CCAnimation.js b/cocos2d/core/sprites/CCAnimation.js index 56925427da..8195b538bc 100644 --- a/cocos2d/core/sprites/CCAnimation.js +++ b/cocos2d/core/sprites/CCAnimation.js @@ -25,15 +25,15 @@ ****************************************************************************/ /** - *

+ * This API is deprecated, will be replaced by new API from {{#crossLink "Animation"}}cc.Animation{{/crossLink}} * cc.AnimationFrame * A frame of the animation. It contains information like: * - sprite frame name * - # of delay units. * - offset - *

- * @class + * @class AnimationFrame * @extends cc._Class + * @deprecated * @param spriteFrame * @param delayUnits * @param userInfo @@ -52,6 +52,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{ /** * Create a new animation frame and copy all contents into it + * @method clone * @returns {AnimationFrame} */ clone: function(){ @@ -62,6 +63,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{ /** * Create a new animation frame and copy all contents into it + * @method copyWithZone * @returns {AnimationFrame} */ copyWithZone:function (pZone) { @@ -70,6 +72,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{ /** * Create a new animation frame and copy all contents into it + * @method copy * @returns {AnimationFrame} */ copy:function (pZone) { @@ -80,6 +83,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{ /** * initializes the animation frame with a spriteframe, number of delay units and a notification user info + * @method initWithSpriteFrame * @param {cc.SpriteFrame} spriteFrame * @param {Number} delayUnits * @param {object} userInfo @@ -94,6 +98,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{ /** * Returns sprite frame to be used + * @method getSpriteFrame * @return {cc.SpriteFrame} */ getSpriteFrame:function () { @@ -102,6 +107,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{ /** * Sets sprite frame to be used + * @method setSpriteFrame * @param {cc.SpriteFrame} spriteFrame */ setSpriteFrame:function (spriteFrame) { @@ -110,6 +116,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{ /** * Returns how many units of time the frame takes getter + * @method getDelayUnits * @return {Number} */ getDelayUnits:function () { @@ -118,6 +125,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{ /** * Sets how many units of time the frame takes setter + * @method setDelayUnits * @param delayUnits */ setDelayUnits:function (delayUnits) { @@ -126,6 +134,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{ /** * Returns the user custom information + * @method getUserInfo * @return {object} */ getUserInfo:function () { @@ -134,6 +143,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{ /** * Sets the user custom information + * @method setUserInfo * @param {object} userInfo */ setUserInfo:function (userInfo) { @@ -143,6 +153,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{ /** * Creates an animation frame. + * @method create * @deprecated since v3.0, please use the new construction instead * @param {cc.SpriteFrame} spriteFrame * @param {Number} delayUnits @@ -154,6 +165,7 @@ cc.AnimationFrame.create = function(spriteFrame,delayUnits,userInfo){ }; /** + * This API is deprecated, will be replaced by new API from {{#crossLink "Animation"}}cc.Animation{{/crossLink}} *

* A cc.SpriteFrameAnimation object is used to perform animations on the _ccsg.Sprite objects.
*
@@ -223,6 +235,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ /** * Returns the array of animation frames + * @method getFrames * @return {Array} */ getFrames:function () { @@ -231,6 +244,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ /** * Sets array of animation frames + * @method setFrames * @param {Array} frames */ setFrames:function (frames) { @@ -239,6 +253,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ /** * Adds a frame to a cc.SpriteFrameAnimation, the frame will be added with one "delay unit". + * @method addSpriteFrame * @param {cc.SpriteFrame} frame */ addSpriteFrame:function (frame) { @@ -252,6 +267,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ /** * Adds a frame with an image filename. Internally it will create a cc.SpriteFrame and it will add it. The frame will be added with one "delay unit". + * @method addSpriteFrameWithFile * @param {String} fileName */ addSpriteFrameWithFile:function (fileName) { @@ -265,6 +281,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ /** * Adds a frame with a texture and a rect. Internally it will create a cc.SpriteFrame and it will add it. The frame will be added with one "delay unit". + * @method addSpriteFrameWithTexture * @param {cc.Texture2D} texture * @param {cc.Rect} rect */ @@ -275,6 +292,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ /** * Initializes a cc.SpriteFrameAnimation with cc.AnimationFrame, do not call this method yourself, please pass parameters to constructor to initialize. + * @method initWithAnimationFrames * @param {Array} arrayOfAnimationFrames * @param {Number} delayPerUnit * @param {Number} [loops=1] @@ -299,6 +317,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ /** * Clone the current animation + * @method clone * @return {cc.SpriteFrameAnimation} */ clone: function(){ @@ -310,6 +329,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ /** * Clone the current animation + * @method copyWithZone * @return {cc.SpriteFrameAnimation} */ copyWithZone:function (pZone) { @@ -328,6 +348,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ /** * Clone the current animation + * @method copy * @param pZone * @returns {cc.SpriteFrameAnimation} */ @@ -337,6 +358,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ /** * Returns how many times the animation is going to loop. 0 means animation is not animated. 1, animation is executed one time, ... + * @method getLoops * @return {Number} */ getLoops:function () { @@ -345,6 +367,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ /** * Sets how many times the animation is going to loop. 0 means animation is not animated. 1, animation is executed one time, ... + * @method setLoops * @param {Number} value */ setLoops:function (value) { @@ -353,6 +376,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ /** * Sets whether or not it shall restore the original frame when the animation finishes + * @method setRestoreOriginalFrame * @param {Boolean} restOrigFrame */ setRestoreOriginalFrame:function (restOrigFrame) { @@ -361,6 +385,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ /** * Returns whether or not it shall restore the original frame when the animation finishes + * @method getRestoreOriginalFrame * @return {Boolean} */ getRestoreOriginalFrame:function () { @@ -369,6 +394,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ /** * Returns duration in seconds of the whole animation. It is the result of totalDelayUnits * delayPerUnit + * @method getDuration * @return {Number} */ getDuration:function () { @@ -377,6 +403,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ /** * Returns delay in seconds of the "delay unit" + * @method getDelayPerUnit * @return {Number} */ getDelayPerUnit:function () { @@ -385,6 +412,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ /** * Sets delay in seconds of the "delay unit" + * @method setDelayPerUnit * @param {Number} delayPerUnit */ setDelayPerUnit:function (delayPerUnit) { @@ -393,6 +421,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ /** * Returns total delay units of the cc.SpriteFrameAnimation. + * @method getTotalDelayUnits * @return {Number} */ getTotalDelayUnits:function () { @@ -401,6 +430,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ /** * Initializes a cc.SpriteFrameAnimation with frames and a delay between frames, do not call this method yourself, please pass parameters to constructor to initialize. + * @method initWithSpriteFrames * @param {Array} frames * @param {Number} delay * @param {Number} [loops=1] @@ -434,7 +464,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ * The retain function can increase a reference count for the native object to avoid it being released,
* you need to manually invoke release function when you think this object is no longer needed, otherwise, there will be memory learks.
* retain and release function call should be paired in developer's game code.

- * @function + * @function retain * @see cc.SpriteFrameAnimation#release */ retain:function () { @@ -449,7 +479,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ * The retain function can increase a reference count for the native object to avoid it being released,
* you need to manually invoke release function when you think this object is no longer needed, otherwise, there will be memory learks.
* retain and release function call should be paired in developer's game code.

- * @function + * @function release * @see cc.SpriteFrameAnimation#retain */ release:function () { @@ -458,6 +488,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({ /** * Creates an animation. + * @method create * @deprecated since v3.0, please use new construction instead * @see cc.SpriteFrameAnimation * @param {Array} frames @@ -471,7 +502,7 @@ cc.SpriteFrameAnimation.create = function (frames, delay, loops) { /** * @deprecated since v3.0, please use new construction instead + * @method createWithAnimationFrames * @see cc.SpriteFrameAnimation - * @type {Function} */ cc.SpriteFrameAnimation.createWithAnimationFrames = cc.SpriteFrameAnimation.create; diff --git a/cocos2d/core/sprites/CCSGSprite.js b/cocos2d/core/sprites/CCSGSprite.js index 8ec4d9aa21..e8d8ead0fd 100644 --- a/cocos2d/core/sprites/CCSGSprite.js +++ b/cocos2d/core/sprites/CCSGSprite.js @@ -758,15 +758,14 @@ _ccsg.Sprite = _ccsg.Node.extend({ * @param {cc.Rect} rect a rect of texture * @param {Boolean} [rotated] Whether or not the texture is rotated * @param {cc.Size} [untrimmedSize] The original pixels size of the texture - * @param {Boolean} [needConvert] contentScaleFactor switch */ - setTextureRect: function (rect, rotated, untrimmedSize, needConvert) { + setTextureRect: function (rect, rotated, untrimmedSize) { var _t = this; _t._rectRotated = rotated || false; _t.setContentSize(untrimmedSize || rect); _t.setVertexRect(rect); - _t._renderCmd._setTextureCoords(rect, needConvert); + _t._renderCmd._setTextureCoords(rect); var relativeOffsetX = _t._unflippedOffsetPositionFromCenter.x, relativeOffsetY = _t._unflippedOffsetPositionFromCenter.y; if (_t._flippedX) @@ -897,10 +896,10 @@ _ccsg.Sprite = _ccsg.Node.extend({ */ getSpriteFrame: function () { return new cc.SpriteFrame(this._texture, - cc.rectPointsToPixels(this._rect), + this._rect, this._rectRotated, - cc.pointPointsToPixels(this._unflippedOffsetPositionFromCenter), - cc.sizePointsToPixels(this._contentSize)); + this._unflippedOffsetPositionFromCenter, + this._contentSize); }, /** diff --git a/cocos2d/core/sprites/CCSGSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSGSpriteCanvasRenderCmd.js index df177ee33a..5e137ed893 100644 --- a/cocos2d/core/sprites/CCSGSpriteCanvasRenderCmd.js +++ b/cocos2d/core/sprites/CCSGSpriteCanvasRenderCmd.js @@ -277,15 +277,12 @@ node.emit("load"); }; - proto._setTextureCoords = function (rect, needConvert) { - if (needConvert === undefined) - needConvert = true; - var locTextureRect = this._textureCoord, - scaleFactor = needConvert ? cc.contentScaleFactor() : 1; - locTextureRect.renderX = locTextureRect.x = 0 | (rect.x * scaleFactor); - locTextureRect.renderY = locTextureRect.y = 0 | (rect.y * scaleFactor); - locTextureRect.width = 0 | (rect.width * scaleFactor); - locTextureRect.height = 0 | (rect.height * scaleFactor); + proto._setTextureCoords = function (rect) { + var locTextureRect = this._textureCoord; + locTextureRect.renderX = locTextureRect.x = 0 | rect.x; + locTextureRect.renderY = locTextureRect.y = 0 | rect.y; + locTextureRect.width = 0 | rect.width; + locTextureRect.height = 0 | rect.height; locTextureRect.validRect = !(locTextureRect.width === 0 || locTextureRect.height === 0 || locTextureRect.x < 0 || locTextureRect.y < 0); }; diff --git a/cocos2d/core/sprites/CCSGSpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCSGSpriteWebGLRenderCmd.js index 05f2331ff6..60ebb6a47f 100644 --- a/cocos2d/core/sprites/CCSGSpriteWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCSGSpriteWebGLRenderCmd.js @@ -143,11 +143,7 @@ node.emit("load"); }; - proto._setTextureCoords = function (rect, needConvert) { - if (needConvert === undefined) - needConvert = true; - if (needConvert) - rect = cc.rectPointsToPixels(rect); + proto._setTextureCoords = function (rect) { var node = this._node; var tex = node._batchNode ? node.textureAtlas.texture : node._texture; diff --git a/cocos2d/core/sprites/CCScale9Sprite.js b/cocos2d/core/sprites/CCScale9Sprite.js index bdc817a57f..8bba89cbe5 100644 --- a/cocos2d/core/sprites/CCScale9Sprite.js +++ b/cocos2d/core/sprites/CCScale9Sprite.js @@ -125,7 +125,7 @@ var simpleQuadGenerator = { var atlasWidth = spriteFrame._texture.getPixelWidth(); var atlasHeight = spriteFrame._texture.getPixelHeight(); - var textureRect = cc.rectPointsToPixels(spriteFrame.getRect()); + var textureRect = spriteFrame.getRect(); //uv computation should take spritesheet into account. var u0, u3; @@ -255,7 +255,7 @@ var scale9QuadGenerator = { bottomHeight = insetBottom; centerHeight = rect.height - topHeight - bottomHeight; - var textureRect = cc.rectPointsToPixels(spriteFrame.getRect()); + var textureRect = spriteFrame.getRect(); //uv computation should take spritesheet into account. var u0, u1, u2, u3; @@ -346,7 +346,7 @@ var tiledQuadGenerator = { var atlasWidth = spriteFrame._texture.getPixelWidth(); var atlasHeight = spriteFrame._texture.getPixelHeight(); - var textureRect = cc.rectPointsToPixels(spriteFrame.getRect()); + var textureRect = spriteFrame.getRect(); //uv computation should take spritesheet into account. var u0, u3; @@ -425,7 +425,7 @@ var fillQuadGeneratorBar = { var progressStart, progressEnd; switch (fillType) { - case cc.Scale9Sprite.FillType.Horizontal: + case cc.Scale9Sprite.FillType.HORIZONTAL: progressStart = vertices[0].x + (vertices[1].x - vertices[0].x) * fillStart; progressEnd = vertices[0].x + (vertices[1].x - vertices[0].x) * fillEnd; @@ -447,7 +447,7 @@ var fillQuadGeneratorBar = { quad._tr.texCoords.u = quadUV[2].u + (quadUV[3].u - quadUV[2].u) * fillEnd; quad._tr.texCoords.v = quadUV[2].v + (quadUV[3].v - quadUV[2].v) * fillEnd; break; - case cc.Scale9Sprite.FillType.Vertical: + case cc.Scale9Sprite.FillType.VERTICAL: progressStart = vertices[0].y + (vertices[1].y - vertices[0].y) * fillStart; progressEnd = vertices[0].y + (vertices[1].y - vertices[0].y) * fillEnd; @@ -494,7 +494,7 @@ var fillQuadGeneratorBar = { var atlasWidth = spriteFrame._texture.getPixelWidth(); var atlasHeight = spriteFrame._texture.getPixelHeight(); - var textureRect = cc.rectPointsToPixels(spriteFrame.getRect()); + var textureRect = spriteFrame.getRect(); //uv computation should take spritesheet into account. var u0, u3; @@ -764,7 +764,7 @@ var fillQuadGeneratorRadial = { var yleft = center.y + tanAngle * (left - center.x); if(yleft > bottom && yleft < top) { intersectPoints[0] = intersectPoints[4]; - intersectPoints[5] = null; + intersectPoints[4] = null; intersectPoints[0].x = left; intersectPoints[0].y = yleft; } @@ -843,7 +843,7 @@ var fillQuadGeneratorRadial = { var atlasWidth = spriteFrame._texture.getPixelWidth(); var atlasHeight = spriteFrame._texture.getPixelHeight(); - var textureRect = cc.rectPointsToPixels(spriteFrame.getRect()); + var textureRect = spriteFrame.getRect(); //uv computation should take spritesheet into account. var u0, u3; @@ -1221,11 +1221,24 @@ cc.Scale9Sprite = _ccsg.Node.extend({ } else if (this._renderingType === cc.Scale9Sprite.RenderingType.TILED) { this._quads = tiledQuadGenerator._rebuildQuads_base(this._spriteFrame, this.getContentSize(), color); } else if (this._renderingType === cc.Scale9Sprite.RenderingType.FILLED) { + var fillstart = this._fillStart; + var fillRange = this._fillRange; + if(fillRange < 0) { + fillstart += fillRange; + fillRange = -fillRange; + } if(this._fillType !== cc.Scale9Sprite.FillType.RADIAL) { - this._quads = fillQuadGeneratorBar._rebuildQuads_base(this._spriteFrame, this.getContentSize(), color, this._fillType, this._fillStart,this._fillRange); + fillRange = fillstart + fillRange; + fillstart = fillstart > 1.0 ? 1.0 : fillstart; + fillstart = fillstart < 0.0 ? 0.0 : fillstart; + + fillRange = fillRange > 1.0 ? 1.0 : fillRange; + fillRange = fillRange < 0.0 ? 0.0 : fillRange; + fillRange = fillRange - fillstart; + this._quads = fillQuadGeneratorBar._rebuildQuads_base(this._spriteFrame, this.getContentSize(), color, this._fillType, fillstart,fillRange); } else { this._isTriangle = true; - var fillResult = fillQuadGeneratorRadial._rebuildQuads_base(this._spriteFrame, this.getContentSize(), color,this._fillCenter,this._fillStart,this._fillRange); + var fillResult = fillQuadGeneratorRadial._rebuildQuads_base(this._spriteFrame, this.getContentSize(), color,this._fillCenter,fillstart,fillRange); this._quads = fillResult.quad; this._rawQuad = fillResult.rawQuad; } @@ -1315,8 +1328,8 @@ cc.Scale9Sprite.RenderingType = cc.Enum({ }); cc.Scale9Sprite.FillType = cc.Enum({ - Horizontal: 0, - Vertical: 1, + HORIZONTAL: 0, + VERTICAL: 1, //todo implement this RADIAL:2, -}); \ No newline at end of file +}); diff --git a/cocos2d/core/sprites/CCSpriteFrame.js b/cocos2d/core/sprites/CCSpriteFrame.js index addb630055..8d5d5e49af 100644 --- a/cocos2d/core/sprites/CCSpriteFrame.js +++ b/cocos2d/core/sprites/CCSpriteFrame.js @@ -90,15 +90,12 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ // the location of the sprite on rendering texture this._rect = null; - this._rectInPixels = null; // for trimming this._offset = null; - this._offsetInPixels = null; // for trimming this._originalSize = null; - this._originalSizeInPixels = null; this._rotated = false; @@ -170,34 +167,6 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ this.once("load", callback, target); }, - /** - * Gets the rect of the frame in the texture. - * @method getRectInPixels - * @return {Rect} - */ - getRectInPixels: function () { - return cc.rect(this._rectInPixels); - }, - - /** - * Sets the rect of the frame in the texture. - * @method setRectInPixels - * @param {Rect} rectInPixels - */ - setRectInPixels: function (rectInPixels) { - if (!this._rectInPixels) { - this._rectInPixels = cc.rect(rectInPixels); - } else { - var rect = this._rectInPixels; - rect.x = rectInPixels.x; - rect.y = rectInPixels.y; - rect.width = rectInPixels.width; - rect.height = rectInPixels.height; - } - - this._rect = cc.rectPixelsToPoints(rectInPixels); - }, - /** * Returns whether the sprite frame is rotated in the texture. * @method isRotated @@ -231,66 +200,7 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ * @param {Rect} rect */ setRect: function (rect) { - if (!this._rect) { - this._rect = cc.rect(rect); - } else { - var locRect = this._rect; - locRect.x = rect.x; - locRect.y = rect.y; - locRect.width = rect.width; - locRect.height = rect.height; - } - this._rectInPixels = cc.rectPointsToPixels(rect); - }, - - /** - * Returns the offset of the sprite frame in the texture in pixel. - * @method getOffsetInPixels - * @return {Vec2} - */ - getOffsetInPixels: function () { - return cc.v2(this._offsetInPixels); - }, - - /** - * Sets the offset of the sprite frame in the texture in pixel. - * @method setOffsetInPixels - * @param {Vec2} offsetInPixels - */ - setOffsetInPixels: function (offsetInPixels) { - if (!this._offsetInPixels) { - this._offsetInPixels = cc.v2(offsetInPixels); - } else { - this._offsetInPixels.x = offsetInPixels.x; - this._offsetInPixels.y = offsetInPixels.y; - } - - this._offset = cc.pointPixelsToPoints(offsetInPixels); - }, - - /** - * Returns the original size of the trimmed image. - * @method getOriginalSizeInPixels - * @return {Size} - */ - getOriginalSizeInPixels: function () { - return cc.size(this._originalSizeInPixels); - }, - - /** - * Sets the original size of the trimmed image. - * @method setOriginalSizeInPixels - * @param {Size} sizeInPixels - */ - setOriginalSizeInPixels: function (sizeInPixels) { - if (!this._originalSizeInPixels) { - this._originalSizeInPixels = cc.size(sizeInPixels); - } else { - this._originalSizeInPixels.width = sizeInPixels.width; - this._originalSizeInPixels.height = sizeInPixels.height; - } - - this._originalSize = cc.sizePixelsToPoints(sizeInPixels); + this._rect = rect; }, /** @@ -314,8 +224,6 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ this._originalSize.width = size.width; this._originalSize.height = size.height; } - - this._originalSizeInPixels = cc.sizePointsToPixels(size); }, /** @@ -388,13 +296,7 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ * @param {Vec2} offsets */ setOffset: function (offsets) { - if (!this._offset) { - this._offset = cc.v2(offsets); - } else { - this._offset.x = offsets.x; - this._offset.y = offsets.y; - } - this._offsetInPixels = cc.pointPointsToPixels(offsets); + this._offset = cc.v2(offsets); }, /** @@ -403,14 +305,14 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ * @return {SpriteFrame} */ clone: function () { - return new cc.SpriteFrame(this._textureFilename, this._rectInPixels, this._rotated, this._offsetInPixels, this._originalSizeInPixels); + return new cc.SpriteFrame(this._texture || this._textureFilename, this._rect, this._rotated, this._offset, this._originalSize); }, /** * Initializes SpriteFrame with Texture, rect, rotated, offset and originalSize in pixels.
* Please pass parameters to the constructor to initialize the sprite, do not call this function yourself. * @method initWithTexture - * @param {String|cc.Texture2D} texture + * @param {String|Texture2D} texture * @param {Rect} rect - if parameters' length equal 2, rect in points, else rect in pixels * @param {Boolean} [rotated=false] * @param {Vec2} [offset=cc.v2(0,0)] @@ -424,21 +326,21 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ setTexture: function (textureOrTextureFile, rect, rotated, offset, originalSize) { if (rect) { - this.setRectInPixels(rect); + this.setRect(rect); } else { - this._rect = this._rectInPixels = null; + this._rect = null; } if (offset) { - this.setOffsetInPixels(offset); + this.setOffset(offset); } else { - this._offset = this._offsetInPixels = null; + this._offset = null; } if (originalSize) { - this.setOriginalSizeInPixels(originalSize); + this.setOriginalSize(originalSize); } else { - this._originalSize = this._originalSizeInPixels = null; + this._originalSize = null; } this._rotated = rotated || false; @@ -463,7 +365,7 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ }, _checkRect: function (texture) { - var rect = this._rectInPixels; + var rect = this._rect; var maxX = rect.x, maxY = rect.y; if (this._rotated) { maxX += rect.height; @@ -494,7 +396,7 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{ uuid = url._uuid; } else { - uuid = Editor.urlToUuid(url); + uuid = Editor.UuidCache.urlToUuid(url); } } var capInsets = undefined; @@ -560,7 +462,7 @@ proto.copyWithZone = proto.clone; /** * Copy the sprite frame * @method copy - * @returns {cc.SpriteFrame} + * @returns {SpriteFrame} */ proto.copy = proto.clone; @@ -571,12 +473,12 @@ proto.copy = proto.clone; *

* since v3.0, please use new constructor {{#crossLink "SpriteFrame/SpriteFrame:method"}}SpriteFrame(){{/crossLink}} instead. * @method create - * @param {String|cc.Texture2D} filename - * @param {cc.Rect} rect if parameters' length equal 2, rect in points, else rect in pixels + * @param {String|Texture2D} filename + * @param {Rect} rect if parameters' length equal 2, rect in points, else rect in pixels * @param {Boolean} rotated - * @param {cc.Vec2} offset - * @param {cc.Size} originalSize - * @return {cc.SpriteFrame} + * @param {Vec2} offset + * @param {Size} originalSize + * @return {SpriteFrame} */ cc.SpriteFrame.create = function (filename, rect, rotated, offset, originalSize) { return new cc.SpriteFrame(filename, rect, rotated, offset, originalSize); diff --git a/cocos2d/core/sprites/CCSpriteFrameCache.js b/cocos2d/core/sprites/CCSpriteFrameCache.js index c1e6249c2e..bbb5ec46a8 100644 --- a/cocos2d/core/sprites/CCSpriteFrameCache.js +++ b/cocos2d/core/sprites/CCSpriteFrameCache.js @@ -185,7 +185,7 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{ var locTexture = spriteFrame.getTexture(); if (locTexture.isLoaded()) { var tempElement = spriteFrame.getTexture().getHtmlElementObj(); - tempElement = _ccsg.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, spriteFrame.getRectInPixels()); + tempElement = _ccsg.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, spriteFrame.getRect()); var tempTexture = new cc.Texture2D(); tempTexture.initWithElement(tempElement); tempTexture.handleLoadedTexture(); diff --git a/cocos2d/core/support/TransformUtils.js b/cocos2d/core/support/TransformUtils.js index aa23c70ed1..b7db840601 100644 --- a/cocos2d/core/support/TransformUtils.js +++ b/cocos2d/core/support/TransformUtils.js @@ -34,7 +34,7 @@ /** * convert an affine transform object to a kmMat4 object * @method CGAffineToGL - * @param {cc.AffineTransform} trans + * @param {AffineTransform} trans * @param {cc.kmMat4} mat */ cc.CGAffineToGL = function (trans, mat) { @@ -56,7 +56,7 @@ cc.CGAffineToGL = function (trans, mat) { * Convert a kmMat4 object to an affine transform object * @method GLToCGAffine * @param {cc.kmMat4} mat - * @param {cc.AffineTransform} trans + * @param {AffineTransform} trans */ cc.GLToCGAffine = function (mat, trans) { trans.a = mat[0]; diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js index 8dbe25b7d7..db6e325ac7 100644 --- a/cocos2d/core/textures/CCTexture2D.js +++ b/cocos2d/core/textures/CCTexture2D.js @@ -194,15 +194,14 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{ * @returns {Size} */ getContentSize: function () { - var locScaleFactor = cc.contentScaleFactor(); - return cc.size(this._contentSize.width / locScaleFactor, this._contentSize.height / locScaleFactor); + return cc.size(this._contentSize.width, this._contentSize.height); }, _getWidth: function () { - return this._contentSize.width / cc.contentScaleFactor(); + return this._contentSize.width; }, _getHeight: function () { - return this._contentSize.height / cc.contentScaleFactor(); + return this._contentSize.height; }, /** @@ -705,22 +704,25 @@ game.once(game.EVENT_RENDERER_INITED, function () { canvas.width = rect.width; canvas.height = 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(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(); @@ -733,53 +735,37 @@ game.once(game.EVENT_RENDERER_INITED, function () { onlyCanvas = true; else canvas = document.createElement("canvas"); - var textureImage = this._htmlElementObj; if(!rect) rect = cc.rect(0, 0, textureImage.width, textureImage.height); - var x, y, w, h; - x = rect.x; y = rect.y; w = rect.width; h = rect.height; - if(!w || !h) - return; - canvas.width = w; - canvas.height = h; - - var context = canvas.getContext("2d"); - var tintedImgCache = cc.textureCache.getTextureColors(this); - context.globalCompositeOperation = 'lighter'; - context.drawImage( - tintedImgCache[3], - x, y, w, h, - 0, 0, w, h - ); - if (r > 0) { - context.globalAlpha = r / 255; + canvas.width = rect.width; + canvas.height = rect.height; + + if(rect.width && rect.height) { + var context = canvas.getContext("2d"); context.drawImage( - tintedImgCache[0], - x, y, w, h, - 0, 0, w, h - ); - } - if (g > 0) { - context.globalAlpha = g / 255; - context.drawImage( - tintedImgCache[1], - x, y, w, h, - 0, 0, w, h - ); - } - if (b > 0) { - context.globalAlpha = b / 255; - context.drawImage( - tintedImgCache[2], - x, y, w, h, - 0, 0, w, h + 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(); diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js index 9a4717d17d..a2b5789c05 100644 --- a/cocos2d/core/textures/CCTextureCache.js +++ b/cocos2d/core/textures/CCTextureCache.js @@ -83,7 +83,7 @@ var textureCache = /** @lends cc.textureCache# */{ * @example {@link utils/api/engine/docs/cocos2d/core/textures/getTextureForKey.js} */ getTextureForKey: function(textureKeyName){ - return this._textures[textureKeyName] || this._textures[cc.loader.getAliase(textureKeyName)]; + return this._textures[textureKeyName]; }, /** @@ -301,7 +301,7 @@ game.once(game.EVENT_RENDERER_INITED, function () { var locTexs = this._textures; //remove judge - var tex = locTexs[url] || locTexs[cc.loader.getAliase(url)]; + var tex = locTexs[url]; if (tex) { if(tex.isLoaded()) { cb && cb.call(target, tex); @@ -318,11 +318,11 @@ game.once(game.EVENT_RENDERER_INITED, function () { tex = locTexs[url] = new Texture2D(); tex.url = url; - cc.loader.loadImg(url, function (err, img) { - if (err) - return cb && cb.call(target, err); + cc.loader.load(url, function (err, texture) { + if (err) { + return cb && cb.call(target, err || new Error('Unknown error')); + } - tex.initWithElement(img); textureCache.handleLoadedTexture(url); cb && cb.call(target, tex); @@ -359,7 +359,7 @@ game.once(game.EVENT_RENDERER_INITED, function () { if (!cc.game._rendererInitialized) { locTexs = this._loadedTexturesBefore; } - var tex = locTexs[url] || locTexs[cc.loader.getAliase(url)]; + var tex = locTexs[url]; if (tex) { if(tex.isLoaded()) { cb && cb.call(target, tex); @@ -376,11 +376,11 @@ game.once(game.EVENT_RENDERER_INITED, function () { tex = locTexs[url] = new Texture2D(); tex.url = url; - cc.loader.loadImg(url, function (err, img) { - if (err) - return cb && cb.call(target, err); + cc.loader.load(url, function (err, texture) { + if (err) { + return cb && cb.call(target, err || new Error('Unknown error')); + } - tex.initWithElement(img); textureCache.handleLoadedTexture(url); cb && cb.call(target, tex); diff --git a/cocos2d/core/utils/BinaryLoader.js b/cocos2d/core/utils/BinaryLoader.js deleted file mode 100644 index 440a94aee0..0000000000 --- a/cocos2d/core/utils/BinaryLoader.js +++ /dev/null @@ -1,159 +0,0 @@ -/**************************************************************************** - Copyright (c) 2008-2010 Ricardo Quesada - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2014 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -require('../platform/CCLoader'); - -/** - * @module cc - * @class loader - */ - -/** - * Load binary data by url. - * @method loadBinary - * @param {String} url - * @param {Function} [cb] - */ - -cc.loader.loadBinary = function (url, cb) { - var self = this; - var xhr = this.getXMLHttpRequest(), - errInfo = "load " + url + " failed!"; - xhr.open("GET", url, true); - if (cc.loader.loadBinary._IEFilter) { - // IE-specific logic here - xhr.setRequestHeader("Accept-Charset", "x-user-defined"); - xhr.onreadystatechange = function () { - if (xhr.readyState === 4 && (xhr.status === 200 || (CC_TEST && xhr.status === 0))) { - var fileContents = cc._convertResponseBodyToText(xhr["responseBody"]); - cb(null, self._str2Uint8Array(fileContents)); - } else cb(errInfo); - }; - } else { - if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=x-user-defined"); - xhr.onload = function () { - xhr.readyState === 4 && (xhr.status === 200 || (CC_TEST && xhr.status === 0)) ? cb(null, self._str2Uint8Array(xhr.responseText)) : cb(errInfo); - }; - } - xhr.send(null); -}; - -cc.loader.loadBinary._IEFilter = (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent) && window.IEBinaryToArray_ByteStr && window.IEBinaryToArray_ByteStr_Last); - -cc.loader._str2Uint8Array = function (strData) { - if (!strData) - return null; - - var arrData = new Uint8Array(strData.length); - for (var i = 0; i < strData.length; i++) { - arrData[i] = strData.charCodeAt(i) & 0xff; - } - return arrData; -}; - -/** - * Load binary data by url synchronously. - * @method loadBinarySync - * @param {String} url - * @return {Uint8Array} - */ -cc.loader.loadBinarySync = function (url) { - var self = this; - var req = this.getXMLHttpRequest(); - var errInfo = "load " + url + " failed!"; - req.open('GET', url, false); - var arrayInfo = null; - if (cc.loader.loadBinary._IEFilter) { - req.setRequestHeader("Accept-Charset", "x-user-defined"); - req.send(null); - if (req.status !== 200) { - cc.log(errInfo); - return null; - } - - var fileContents = cc._convertResponseBodyToText(req["responseBody"]); - if (fileContents) { - arrayInfo = self._str2Uint8Array(fileContents); - } - } else { - if (req.overrideMimeType) - req.overrideMimeType('text\/plain; charset=x-user-defined'); - req.send(null); - if (req.status !== 200) { - cc.log(errInfo); - return null; - } - - arrayInfo = this._str2Uint8Array(req.responseText); - } - return arrayInfo; -}; - -//Compatibility with IE9 -window.Uint8Array = window.Uint8Array || window.Array; - -if (cc.loader.loadBinary._IEFilter) { - var IEBinaryToArray_ByteStr_Script = - "\r\n" + - //"\r\n"; - - // inject VBScript - //document.write(IEBinaryToArray_ByteStr_Script); - var myVBScript = document.createElement('script'); - myVBScript.type = "text/vbscript"; - myVBScript.textContent = IEBinaryToArray_ByteStr_Script; - document.body.appendChild(myVBScript); - - // helper to convert from responseBody to a "responseText" like thing - cc._convertResponseBodyToText = function (binary) { - var byteMapping = {}; - for (var i = 0; i < 256; i++) { - for (var j = 0; j < 256; j++) { - byteMapping[ String.fromCharCode(i + j * 256) ] = - String.fromCharCode(i) + String.fromCharCode(j); - } - } - var rawBytes = IEBinaryToArray_ByteStr(binary); - var lastChr = IEBinaryToArray_ByteStr_Last(binary); - return rawBytes.replace(/[\s\S]/g, - function (match) { - return byteMapping[match]; - }) + lastChr; - }; -} \ No newline at end of file diff --git a/cocos2d/core/utils/CCPath.js b/cocos2d/core/utils/CCPath.js index 0ba32cbfca..df3cb20d6d 100644 --- a/cocos2d/core/utils/CCPath.js +++ b/cocos2d/core/utils/CCPath.js @@ -1,11 +1,13 @@ require('../platform/CCSys'); + +var EXTNAME_RE = /(\.[^\.\/\?\\]*)(\?.*)?$/; +var NORMALIZE_RE = /[^\.\/]+\/\.\.\//; + /** * @class path * @static */ cc.path = /** @lends cc.path# */{ - normalizeRE: /[^\.\/]+\/\.\.\//, - /** * Join strings to be a path. * @method join @@ -22,15 +24,15 @@ cc.path = /** @lends cc.path# */{ }, /** - * Get the ext name of a path. + * Get the ext name of a path including '.', like '.png'. * @method extname * @example {@link utils/api/engine/docs/cocos2d/core/utils/CCPath/extname.js} * @param {String} pathStr * @returns {*} */ extname: function (pathStr) { - var temp = /(\.[^\.\/\?\\]*)(\?.*)?$/.exec(pathStr); - return temp ? temp[1] : null; + var temp = EXTNAME_RE.exec(pathStr); + return temp ? temp[1] : ''; }, /** @@ -128,7 +130,7 @@ cc.path = /** @lends cc.path# */{ //removing all ../ do { oldUrl = url; - url = url.replace(this.normalizeRE, ""); + url = url.replace(NORMALIZE_RE, ""); } while(oldUrl.length !== url.length); return url; }, @@ -159,4 +161,6 @@ cc.path = /** @lends cc.path# */{ } return path; } -}; \ No newline at end of file +}; + +module.exports = cc.path; \ No newline at end of file diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js index 8cf76ec3ef..255a9913c7 100644 --- a/cocos2d/core/utils/base-node.js +++ b/cocos2d/core/utils/base-node.js @@ -48,6 +48,7 @@ var COLOR_CHANGED = 'color-changed'; var OPACITY_CHANGED = 'opacity-changed'; var CHILD_ADDED = 'child-added'; var CHILD_REMOVED = 'child-removed'; +var CHILD_REORDER = 'child-reorder'; var ERR_INVALID_NUMBER = CC_EDITOR && 'The %s is invalid'; @@ -89,7 +90,6 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ _skewY: 0, _localZOrder: 0, _globalZOrder: 0, - _ignoreAnchorPointForPosition: false, _tag: cc.NODE_TAG_INVALID, _opacityModifyRGB: false, @@ -123,6 +123,11 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ if (this._parent === value) { return; } + if (CC_EDITOR && !cc.engine.isPlaying) { + if (_Scene.DetectConflict.beforeAddChild(this)) { + return; + } + } var node = this._sgNode; if (node.parent) { node.parent.removeChild(node, false); @@ -144,12 +149,8 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ return cc.error('Internal error, should not remove unknown node from parent.'); } oldParent._children.splice(removeAt, 1); - oldParent.emit(CHILD_REMOVED, removeAt); + oldParent.emit(CHILD_REMOVED, this); this._onHierarchyChanged(oldParent); - - if (CC_EDITOR) { - _Scene.DetectConflict.afterAddChild(this); - } } } else if (value) { @@ -177,7 +178,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ */ uuid: { get: function () { - return this._id || (this._id = window.Editor ? Editor.uuid() : ''); + return this._id || (this._id = window.Editor ? Editor.UuidUtils.uuid() : ''); } }, @@ -507,16 +508,17 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ /** * Indicate whether ignore the anchor point property for positioning. - * @property ignoreAnchor + * @property _ignoreAnchor * @type {Boolean} + * @private */ - ignoreAnchor: { + _ignoreAnchor: { get: function () { - return this._ignoreAnchorPointForPosition; + return this.__ignoreAnchor; }, set: function (value) { - if (this._ignoreAnchorPointForPosition !== value) { - this._ignoreAnchorPointForPosition = value; + if (this.__ignoreAnchor !== value) { + this.__ignoreAnchor = value; this._sgNode.ignoreAnchor = value; this._onAnchorChanged(); this.emit(ANCHOR_CHANGED, this._anchorPoint); @@ -640,6 +642,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ // _ccsg.Node this._sizeProvider = null; + this.__ignoreAnchor = false; }, _onPreDestroy: function () { @@ -928,7 +931,11 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ * @return {Rect} The calculated bounding box of the node */ getBoundingBox: function () { - var rect = cc.rect(0, 0, this._contentSize.width, this._contentSize.height); + var size = this.getContentSize(); + var rect = cc.rect( - this._anchorPoint.x * size.width, + - this._anchorPoint.y * size.height, + size.width, + size.height ); return cc._rectApplyAffineTransformIn(rect, this.getNodeToParentTransform()); }, @@ -1136,8 +1143,6 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ child.cleanup(); child.parent = null; - cc.js.array.remove(this._children, child); - this.emit(CHILD_REMOVED, child); }, setNodeDirty: function(){ @@ -1161,7 +1166,19 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ * @return {AffineTransform} */ getNodeToWorldTransform: function () { - return this._sgNode.getNodeToWorldTransform(); + var computedSize = this._sgNode.getContentSize(); + var expectedSize = this.getContentSize(); + var mat = this._sgNode.getNodeToWorldTransform(); + var anchorPointIgnored = (computedSize.width === 0 && computedSize.height === 0 && + (expectedSize.width !== 0 || expectedSize.height !== 0)); + if (anchorPointIgnored || this._sgNode.isIgnoreAnchorPointForPosition()) { + // compute anchor, see https://github.com/cocos-creator/engine/pull/391 + var tx = - expectedSize.width * this._anchorPoint.x; + var ty = - expectedSize.height * this._anchorPoint.y; + var offset = cc.affineTransformMake(1, 0, 0, 1, tx, ty); + mat = cc.affineTransformConcatIn(offset, mat); + } + return mat; }, /** @@ -1203,7 +1220,13 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ * @return {Vec2} */ convertToNodeSpaceAR: function (worldPoint) { - return this._sgNode.convertToNodeSpaceAR(worldPoint); + if (this._sgNode.isIgnoreAnchorPointForPosition()) { + // see https://github.com/cocos-creator/engine/pull/391 + return cc.v2(this._sgNode.convertToNodeSpace(worldPoint)); + } + else { + return this._sgNode.convertToNodeSpaceAR(worldPoint); + } }, /** @@ -1214,7 +1237,13 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ * @return {Vec2} */ convertToWorldSpaceAR: function (nodePoint) { - return cc.v2(this._sgNode.convertToWorldSpaceAR(nodePoint)); + if (this._sgNode.isIgnoreAnchorPointForPosition()) { + // see https://github.com/cocos-creator/engine/pull/391 + return cc.v2(this._sgNode.convertToWorldSpace(nodePoint)); + } + else { + return cc.v2(this._sgNode.convertToWorldSpaceAR(nodePoint)); + } }, // _convertToWindowSpace: function (nodePoint) { @@ -1252,12 +1281,42 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ }, /** - * Returns a "world" axis aligned bounding box of the node. + * Returns a "world" axis aligned bounding box of the node.
+ * The bounding box contains self and active children's world bounding box. * @method getBoundingBoxToWorld * @return {Rect} */ getBoundingBoxToWorld: function () { - return this._sgNode.getBoundingBoxToWorld(); + var trans; + if (this.parent) { + trans = this.parent.getNodeToWorldTransform(); + } + return this._getBoundingBoxTo(trans); + }, + + _getBoundingBoxTo: function (parentTransform) { + var size = this.getContentSize(); + var width = size.width; + var height = size.height; + var rect = cc.rect(0, 0, width, height); + + var trans = (parentTransform === undefined) ? this.getNodeToParentTransform() : cc.affineTransformConcat(this.getNodeToParentTransform(), parentTransform); + cc._rectApplyAffineTransformIn(rect, trans); + + //query child's BoundingBox + if (!this._children) + return rect; + + var locChildren = this._children; + for (var i = 0; i < locChildren.length; i++) { + var child = locChildren[i]; + if (child && child.active) { + var childRect = child._getBoundingBoxTo(trans); + if (childRect) + rect = cc.rectUnion(rect, childRect); + } + } + return rect; }, /** @@ -1270,9 +1329,9 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ return this._sgNode.getDisplayedOpacity(); }, - /** + /* * Update displayed opacity - * @method + * @method _updateDisplayedOpacity * @param {Number} parentOpacity */ _updateDisplayedOpacity: function (parentOpacity) { @@ -1360,6 +1419,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ if (cc.renderer) { cc.renderer.childrenOrderDirty = this._parent._sgNode._reorderChildDirty = true; } + this._parent.emit(CHILD_REORDER); } }, @@ -1382,25 +1442,40 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ return false; }, - // The deserializer for sgNode which will be called before components onLoad - _onBatchCreated: function () { + _updateDummySgNode: function () { var sgNode = this._sgNode; - sgNode.setOpacity(this._opacity); - sgNode.setCascadeOpacityEnabled(this._cascadeOpacityEnabled); + + sgNode.setPosition(this._position); sgNode.setRotationX(this._rotationX); sgNode.setRotationY(this._rotationY); sgNode.setScale(this._scaleX, this._scaleY); - sgNode.setPosition(this._position); sgNode.setSkewX(this._skewX); sgNode.setSkewY(this._skewY); + sgNode.ignoreAnchorPointForPosition(this.__ignoreAnchor); + sgNode.setLocalZOrder(this._localZOrder); sgNode.setGlobalZOrder(this._globalZOrder); - sgNode.ignoreAnchorPointForPosition(this._ignoreAnchorPointForPosition); - sgNode.setTag(this._tag); + + sgNode.setOpacity(this._opacity); sgNode.setOpacityModifyRGB(this._opacityModifyRGB); + sgNode.setCascadeOpacityEnabled(this._cascadeOpacityEnabled); + sgNode.setTag(this._tag); + }, + + _updateSgNode: function () { + this._updateDummySgNode(); + var sgNode = this._sgNode; + sgNode.setAnchorPoint(this._anchorPoint); + sgNode.setVisible(this._active); + sgNode.setColor(this._color); + }, + + // The deserializer for sgNode which will be called before components onLoad + _onBatchCreated: function () { + this._updateDummySgNode(); if (this._parent) { - this._parent._sgNode.addChild(sgNode); + this._parent._sgNode.addChild(this._sgNode); } var children = this._children; @@ -1410,56 +1485,6 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ }, _removeSgNode: SceneGraphHelper.removeSgNode, - - _replaceSgNode: function(sgNode) { - if(sgNode instanceof _ccsg.Node) { - var oldSgNode = this._sgNode; - - //apply property - sgNode.setPosition(this._position); - sgNode.setRotationX(this._rotationX); - sgNode.setRotationY(this._rotationY); - sgNode.setScale(this._scaleX, this._scaleY); - sgNode.setSkewX(this._skewX); - sgNode.setSkewY(this._skewY); - - sgNode.setLocalZOrder(this._localZOrder); - sgNode.setGlobalZOrder(this._globalZOrder); - - sgNode.setOpacity(this._opacity); - sgNode.setCascadeOpacityEnabled(this._cascadeOpacityEnabled); - sgNode.ignoreAnchorPointForPosition(this._ignoreAnchorPointForPosition); - sgNode.setTag(this._tag); - sgNode.setColor(this._color); - sgNode.setOpacityModifyRGB(this._opacityModifyRGB); - - //rebuild scenegraph - var children = oldSgNode.getChildren().slice(0); - oldSgNode.removeAllChildren(); - - for(var index = 0; index < children.length; ++index) { - sgNode.addChild(children[index]); - } - - var parentNode = oldSgNode.getParent(); - parentNode.removeChild(oldSgNode); - - // insert node - parentNode.addChild(sgNode); - sgNode.arrivalOrder = oldSgNode.arrivalOrder; - if (cc.renderer) { - cc.renderer.childrenOrderDirty = this._parent._sgNode._reorderChildDirty = true; - } - - this._sgNode = sgNode; - if (cc.sys.isNative) { - oldSgNode.release(); - sgNode.retain(); - } - } else { - throw new Error("Invalid sgNode. It must an instance of _ccsg.Node"); - } - }, }); @@ -1475,7 +1500,6 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ y: ['getPositionY', 'setPositionY'], zIndex: ['getLocalZOrder', 'setLocalZOrder'], //running: ['isRunning'], - ignoreAnchor: ['isIgnoreAnchorPointForPosition', 'ignoreAnchorPointForPosition'], opacityModifyRGB: ['isOpacityModifyRGB'], cascadeOpacity: ['isCascadeOpacityEnabled', 'setCascadeOpacityEnabled'], cascadeColor: ['isCascadeColorEnabled', 'setCascadeColorEnabled'], @@ -1524,13 +1548,13 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ */ /** - *

Sets the x axis position of the node in cocos2d coordinates.

+ *

Returns the x axis position of the node in cocos2d coordinates.

* @method getPositionX * @param {Number} x - The new position in x axis */ /** - *

Returns the x axis position of the node in cocos2d coordinates.

+ *

Sets the x axis position of the node in cocos2d coordinates.

* @method setPositionX * @return {Number} */ diff --git a/cocos2d/core/value-types/CCAffineTransform.js b/cocos2d/core/value-types/CCAffineTransform.js index 69b5ccd404..cd9bf1f429 100644 --- a/cocos2d/core/value-types/CCAffineTransform.js +++ b/cocos2d/core/value-types/CCAffineTransform.js @@ -260,9 +260,9 @@ cc.affineTransformConcat = function (t1, t2) { * The results are reflected in the first matrix.
* t' = t1 * t2 * @method affineTransformConcatIn - * @param {cc.AffineTransform} t1 - The first transform object. - * @param {cc.AffineTransform} t2 - The transform object to concatenate. - * @return {cc.AffineTransform} The result of concatenation. + * @param {AffineTransform} t1 - The first transform object. + * @param {AffineTransform} t2 - The transform object to concatenate. + * @return {AffineTransform} The result of concatenation. */ cc.affineTransformConcatIn = function (t1, t2) { var a = t1.a, b = t1.b, c = t1.c, d = t1.d, tx = t1.tx, ty = t1.ty; diff --git a/cocos2d/core/value-types/CCColor.js b/cocos2d/core/value-types/CCColor.js index 829bb7f130..8b53760e5c 100644 --- a/cocos2d/core/value-types/CCColor.js +++ b/cocos2d/core/value-types/CCColor.js @@ -6,17 +6,17 @@ var Color = (function () { /** * Representation of RGBA colors. * - * Each color component is a floating point value with a range from 0 to 1. + * Each color component is a floating point value with a range from 0 to 255. * * You can also use the convenience method <% crosslink cc.Color cc.Color %> to create a new Color. * * @class Color * @extends ValueType * @constructor - * @param {Number} [r=0] - red component of the color. - * @param {Number} [g=0] - green component of the color. - * @param {Number} [b=0] - blue component of the color. - * @param {Number} [a=255] - alpha component of the color. + * @param {Number} [r=0] - red component of the color, default value is 0. + * @param {Number} [g=0] - green component of the color, defualt value is 0. + * @param {Number} [b=0] - blue component of the color, default value is 0. + * @param {Number} [a=255] - alpha component of the color, default value is 255. */ function Color( r, g, b, a ) { if (typeof r === 'object') { diff --git a/cocos2d/core/value-types/CCVec2.js b/cocos2d/core/value-types/CCVec2.js index c19749576c..03808cd2d5 100644 --- a/cocos2d/core/value-types/CCVec2.js +++ b/cocos2d/core/value-types/CCVec2.js @@ -467,7 +467,7 @@ cc.v2 = function v2 (x, y) { * @method p * @param {Number|Object} [x=0] a Number or a size object * @param {Number} [y=0] - * @return {cc.Vec2} + * @return {Vec2} * @example * var point1 = cc.p(); * var point2 = cc.p(100, 100); @@ -482,8 +482,8 @@ cc.p = cc.v2; /** * Check whether a point's value equals to another * @method pointEqualToPoint - * @param {cc.Vec2} point1 - * @param {cc.Vec2} point2 + * @param {Vec2} point1 + * @param {Vec2} point2 * @return {Boolean} */ cc.pointEqualToPoint = function (point1, point2) { diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js index b2e83104bc..9263a6894f 100644 --- a/cocos2d/deprecated.js +++ b/cocos2d/deprecated.js @@ -133,7 +133,8 @@ if (CC_DEV) { js.obsoletes(cc, 'cc', { 'Point': 'Vec2', 'EScene': 'Scene', - 'ENode': 'Node' + 'ENode': 'Node', + '_ComponentInSG': '_RendererUnderSG' }); /** @@ -203,9 +204,7 @@ if (CC_DEV) { return cc.js.array.copy; }); - - - Object.defineProperty(cc._ComponentInSG.prototype, 'visible', { + Object.defineProperty(cc._SGComponent.prototype, 'visible', { get: function () { cc.warn('The "visible" property of %s is deprecated, use "enabled" instead please.', cc.js.getClassName(this)); return this.enabled; @@ -265,7 +264,7 @@ if (CC_DEV) { function provideClearError (owner, obj) { var className = cc.js.getClassName(owner); - var Info = 'Sorry,' + className + '.%s is removed, please use %s instead.'; + var Info = 'Sorry, ' + className + '.%s is removed, please use %s instead.'; for (var prop in obj) { function define (prop, getset) { function accessor (newProp) { @@ -298,26 +297,6 @@ if (CC_DEV) { } } - function shouldNotUseNodeProp (component) { - var compName = cc.js.getClassName(component); - var Info = 'Sorry, ' + compName + '.%s is removed, please use cc.Node.%s instead.'; - var compProto = component.prototype; - for (var prop in cc.Node.prototype) { - (function (prop) { - if (!(prop in compProto) && prop[0] !== '_') { - js.getset(compProto, prop, - function () { - cc.error(Info, prop, prop); - }, - function () { - cc.error(Info, prop, prop); - } - ); - } - })(prop); - } - } - // cc.Node markAsRemoved(cc.Node, [ @@ -384,7 +363,10 @@ if (CC_DEV) { 'userData', 'userObject', '_cascadeColorEnabled', - 'cascadeColor' + 'cascadeColor', + 'ignoreAnchor', + 'isIgnoreAnchorPointForPosition', + 'ignoreAnchorPointForPosition' ]); provideClearError(cc.Node.prototype, { arrivalOrder: 'getSiblingIndex, setSiblingIndex', @@ -407,8 +389,31 @@ if (CC_DEV) { removeAllComponents: 'removeComponent', getNodeToParentAffineTransform: 'getNodeToParentTransform', }); + + // RENDERERS - // cc.SpriteRenderer + function shouldNotUseNodeProp (component) { + var compProto = component.prototype; + for (var prop in cc.Node.prototype) { + (function (prop) { + if (!(prop in compProto) && prop[0] !== '_') { + Object.defineProperty(compProto, prop, { + get: function () { + var compName = cc.js.getClassName(this); // 允许继承 + var Info = 'Sorry, ' + compName + '.%s is undefined, please use cc.Node.%s instead.'; + cc.error(Info, prop, prop); + }, + enumerable: false, + configurable: true, // 允许继承 + }); + } + })(prop); + } + } + shouldNotUseNodeProp(cc._SGComponent); + + + // cc.Sprite markAsRemoved(cc.Sprite, [ 'textureLoaded', @@ -433,14 +438,12 @@ if (CC_DEV) { createWithSpriteFrame: 'node.addComponent', }); provideClearError(cc.Sprite.prototype, { - ignoreAnchorPointForPosition: 'instance.ignoreAnchor', getPreferredSize: 'node.getContentSize', setPreferredSize: 'node.setContentSize', updateWithSprite: 'spriteFrame', getSpriteFrame: 'spriteFrame', setSpriteFrame: 'spriteFrame', }); - shouldNotUseNodeProp(cc.Sprite); // Particle markAsRemoved(cc.ParticleSystem, [ @@ -490,7 +493,6 @@ if (CC_DEV) { '*etTotalParticles': 'totalParticles', '*etTexture': 'texture', }); - shouldNotUseNodeProp(cc.ParticleSystem); js.obsoletes(cc.ParticleSystem, 'cc.ParticleSystem', { Type: 'PositionType', Mode: 'EmitterMode' @@ -540,4 +542,22 @@ if (CC_DEV) { 'setFlippedY', 'isFlippedY' ]); + + // SPINE + + if (typeof sp !== 'undefined') { + deprecateEnum(sp, 'sp.ANIMATION_EVENT_TYPE', 'sp.AnimationEventType'); + js.obsolete(sp, 'SkeletonAnimation', 'Skeleton'); + provideClearError(sp.Skeleton, { + create: 'node.addComponent', + }); + provideClearError(sp.Skeleton.prototype, { + '*etDebugSlotsEnabled': 'debugSlots', + '*etDebugBonesEnabled': 'debugBones', + 'setDebugSolots': 'debugSlots', + 'setDebugBones': 'debugBones', + '*etTimeScale': 'timeScale', + }); + } } + diff --git a/cocos2d/labels/CCLabelAtlas.js b/cocos2d/labels/CCLabelAtlas.js index 84386be0b3..ee1deea62a 100644 --- a/cocos2d/labels/CCLabelAtlas.js +++ b/cocos2d/labels/CCLabelAtlas.js @@ -124,9 +124,8 @@ cc.LabelAtlas = cc.AtlasNode.extend(/** @lends cc.LabelAtlas# */{ } textureFilename = cc.path.changeBasename(charMapFile, dict["textureFilename"]); - var locScaleFactor = cc.contentScaleFactor(); - width = parseInt(dict["itemWidth"], 10) / locScaleFactor; - height = parseInt(dict["itemHeight"], 10) / locScaleFactor; + width = parseInt(dict["itemWidth"], 10); + height = parseInt(dict["itemHeight"], 10); startChar = String.fromCharCode(parseInt(dict["firstChar"], 10)); } else { textureFilename = charMapFile; diff --git a/cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js b/cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js index 3d3df03694..680108c5ae 100644 --- a/cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js +++ b/cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js @@ -42,7 +42,7 @@ var locString = node._string || ""; var n = locString.length; var texture = this._textureToRender; - var locItemWidth = node._itemWidth , locItemHeight = node._itemHeight; //needn't multiply cc.contentScaleFactor(), because sprite's draw will do this + var locItemWidth = node._itemWidth , locItemHeight = node._itemHeight; for (var i = 0, cr = -1; i < n; i++) { var a = locString.charCodeAt(i) - node._mapStartChar.charCodeAt(0); diff --git a/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js b/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js index 87e9fa79f5..b60438c28e 100644 --- a/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js +++ b/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js @@ -62,12 +62,8 @@ var texture = locTextureAtlas.texture; var textureWide = texture.getPixelWidth(); var textureHigh = texture.getPixelHeight(); - var itemWidthInPixels = node._itemWidth; - var itemHeightInPixels = node._itemHeight; - if (!node._ignoreContentScaleFactor) { - itemWidthInPixels = node._itemWidth * cc.contentScaleFactor(); - itemHeightInPixels = node._itemHeight * cc.contentScaleFactor(); - } + var itemWidth = node._itemWidth; + var itemHeight = node._itemHeight; if (n > locTextureAtlas.getCapacity()) cc.log("cc.LabelAtlas._updateAtlasValues(): Invalid String length"); var quads = locTextureAtlas.quads; @@ -88,15 +84,15 @@ var left, right, top, bottom; if (cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL) { // Issue #938. Don't use texStepX & texStepY - left = (2 * row * itemWidthInPixels + 1) / (2 * textureWide); - right = left + (itemWidthInPixels * 2 - 2) / (2 * textureWide); - top = (2 * col * itemHeightInPixels + 1) / (2 * textureHigh); - bottom = top + (itemHeightInPixels * 2 - 2) / (2 * textureHigh); + left = (2 * row * itemWidth + 1) / (2 * textureWide); + right = left + (itemWidth * 2 - 2) / (2 * textureWide); + top = (2 * col * itemHeight + 1) / (2 * textureHigh); + bottom = top + (itemHeight * 2 - 2) / (2 * textureHigh); } else { - left = row * itemWidthInPixels / textureWide; - right = left + itemWidthInPixels / textureWide; - top = col * itemHeightInPixels / textureHigh; - bottom = top + itemHeightInPixels / textureHigh; + left = row * itemWidth / textureWide; + right = left + itemWidth / textureWide; + top = col * itemHeight / textureHigh; + bottom = top + itemHeight / textureHigh; } var quad = quads[i]; var locQuadTL = quad.tl, locQuadTR = quad.tr, locQuadBL = quad.bl, locQuadBR = quad.br; diff --git a/cocos2d/labels/CCLabelBMFont.js b/cocos2d/labels/CCLabelBMFont.js index d21ec4f8bd..9bf02f5226 100644 --- a/cocos2d/labels/CCLabelBMFont.js +++ b/cocos2d/labels/CCLabelBMFont.js @@ -345,7 +345,6 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ } var rect = cc.rect(fontDef.rect.x, fontDef.rect.y, fontDef.rect.width, fontDef.rect.height); - rect = cc.rectPixelsToPoints(rect); rect.x += self._imageOffset.x; rect.y += self._imageOffset.y; @@ -366,8 +365,8 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ var yOffset = locCfg.commonHeight - fontDef.yOffset; var fontPos = cc.p(nextFontPositionX + fontDef.xOffset + fontDef.rect.width * 0.5 + kerningAmount, - nextFontPositionY + yOffset - rect.height * 0.5 * cc.contentScaleFactor()); - fontChar.setPosition(cc.pointPixelsToPoints(fontPos)); + nextFontPositionY + yOffset - rect.height * 0.5); + fontChar.setPosition(fontPos); // update kerning nextFontPositionX += fontDef.xAdvance + kerningAmount; @@ -384,7 +383,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ else tmpSize.width = longestLine; tmpSize.height = totalHeight; - self.setContentSize(cc.sizePixelsToPoints(tmpSize)); + self.setContentSize(tmpSize); }, /** @@ -867,107 +866,3 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{ cc.LabelBMFont.create = function (str, fntFile, width, alignment, imageOffset) { return new cc.LabelBMFont(str, fntFile, width, alignment, imageOffset); }; - -cc._fntLoader = { - INFO_EXP: /info [^\n]*(\n|$)/gi, - COMMON_EXP: /common [^\n]*(\n|$)/gi, - PAGE_EXP: /page [^\n]*(\n|$)/gi, - CHAR_EXP: /char [^\n]*(\n|$)/gi, - KERNING_EXP: /kerning [^\n]*(\n|$)/gi, - ITEM_EXP: /\w+=[^ \r\n]+/gi, - INT_EXP: /^[\-]?\d+$/, - - _parseStrToObj: function (str) { - var arr = str.match(this.ITEM_EXP); - var obj = {}; - if (arr) { - for (var i = 0, li = arr.length; i < li; i++) { - var tempStr = arr[i]; - var index = tempStr.indexOf("="); - var key = tempStr.substring(0, index); - var value = tempStr.substring(index + 1); - if (value.match(this.INT_EXP)) value = parseInt(value); - else if (value[0] === '"') value = value.substring(1, value.length - 1); - obj[key] = value; - } - } - return obj; - }, - - /** - * Parse Fnt string. - * @param fntStr - * @param url - * @returns {{}} - */ - parseFnt: function (fntStr, url) { - var self = this, fnt = {}; - //padding - var infoObj = self._parseStrToObj(fntStr.match(self.INFO_EXP)[0]); - var paddingArr = infoObj["padding"].split(","); - var padding = { - left: parseInt(paddingArr[0]), - top: parseInt(paddingArr[1]), - right: parseInt(paddingArr[2]), - bottom: parseInt(paddingArr[3]) - }; - - //common - var commonObj = self._parseStrToObj(fntStr.match(self.COMMON_EXP)[0]); - fnt.commonHeight = commonObj["lineHeight"]; - //font size - fnt.fontSize = infoObj["size"]; - if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { - var texSize = cc.configuration.getMaxTextureSize(); - if (commonObj["scaleW"] > texSize.width || commonObj["scaleH"] > texSize.height) - cc.log("cc.LabelBMFont._parseCommonArguments(): page can't be larger than supported"); - } - if (commonObj["pages"] !== 1) cc.log("cc.LabelBMFont._parseCommonArguments(): only supports 1 page"); - - //page - var pageObj = self._parseStrToObj(fntStr.match(self.PAGE_EXP)[0]); - if (pageObj["id"] !== 0) cc.log("cc.LabelBMFont._parseImageFileName() : file could not be found"); - fnt.atlasName = cc.path.changeBasename(url, pageObj["file"]); - - //char - var charLines = fntStr.match(self.CHAR_EXP); - var fontDefDictionary = fnt.fontDefDictionary = {}; - for (var i = 0, li = charLines.length; i < li; i++) { - var charObj = self._parseStrToObj(charLines[i]); - var charId = charObj["id"]; - fontDefDictionary[charId] = { - rect: {x: charObj["x"], y: charObj["y"], width: charObj["width"], height: charObj["height"]}, - xOffset: charObj["xoffset"], - yOffset: charObj["yoffset"], - xAdvance: charObj["xadvance"] - }; - } - - //kerning - var kerningDict = fnt.kerningDict = {}; - var kerningLines = fntStr.match(self.KERNING_EXP); - if (kerningLines) { - for (var i = 0, li = kerningLines.length; i < li; i++) { - var kerningObj = self._parseStrToObj(kerningLines[i]); - kerningDict[(kerningObj["first"] << 16) | (kerningObj["second"] & 0xffff)] = kerningObj["amount"]; - } - } - return fnt; - }, - - /** - * load the fnt - * @param realUrl - * @param url - * @param res - * @param cb - */ - load: function (realUrl, url, res, cb) { - var self = this; - cc.loader.loadTxt(realUrl, function (err, txt) { - if (err) return cb(err); - cb(null, self.parseFnt(txt, url)); - }); - } -}; -cc.loader.register(["fnt"], cc._fntLoader); diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js index 408f808a3a..33900fec74 100644 --- a/cocos2d/particle/CCParticleSystem.js +++ b/cocos2d/particle/CCParticleSystem.js @@ -64,6 +64,10 @@ var PositionType = cc.Enum({ GROUPED: 2 }); +/** + * @class ParticleSystem + */ + var properties = { /** @@ -133,10 +137,10 @@ var properties = { this._file = value; if (value) { this._applyFile(); - cc.engine.repaintInEditMode(); - //if (CC_EDITOR) { - // self.preview = self.preview; - //} + if (CC_EDITOR) { + cc.engine.repaintInEditMode(); + //self.preview = self.preview; + } } else { this.custom = true; @@ -219,9 +223,6 @@ var properties = { } }; -/** - * @class ParticleSystem - */ var CustomProps = (function () { var DefaultValues = { /** @@ -479,48 +480,51 @@ properties.positionType.type = PositionType; properties.emitterMode.type = EmitterMode; /** - *

- * Particle System base class.
- * Attributes of a Particle System:
- * - emmision rate of the particles
- * - Gravity Mode (Mode A):
- * - gravity
- * - direction
- * - speed +- variance
- * - tangential acceleration +- variance
- * - radial acceleration +- variance
- * - Radius Mode (Mode B):
- * - startRadius +- variance
- * - endRadius +- variance
- * - rotate +- variance
- * - Properties common to all modes:
- * - life +- life variance
- * - start spin +- variance
- * - end spin +- variance
- * - start size +- variance
- * - end size +- variance
- * - start color +- variance
- * - end color +- variance
- * - life +- variance
- * - blending function
- * - texture
- *
- * cocos2d also supports particles generated by Particle Designer (http://particledesigner.71squared.com/).
- * 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d,
- * cocos2d uses a another approach, but the results are almost identical.
- * cocos2d supports all the variables used by Particle Designer plus a bit more:
- * - spinning particles (supported when using ParticleSystem)
- * - tangential acceleration (Gravity mode)
- * - radial acceleration (Gravity mode)
- * - radius direction (Radius mode) (Particle Designer supports outwards to inwards direction only)
- * It is possible to customize any of the above mentioned properties in runtime. Example:
- *

+ * Particle System base class.
+ * Attributes of a Particle System:
+ * - emmision rate of the particles
+ * - Gravity Mode (Mode A):
+ * - gravity
+ * - direction
+ * - speed +- variance
+ * - tangential acceleration +- variance
+ * - radial acceleration +- variance
+ * - Radius Mode (Mode B):
+ * - startRadius +- variance
+ * - endRadius +- variance
+ * - rotate +- variance
+ * - Properties common to all modes:
+ * - life +- life variance
+ * - start spin +- variance
+ * - end spin +- variance
+ * - start size +- variance
+ * - end size +- variance
+ * - start color +- variance
+ * - end color +- variance
+ * - life +- variance
+ * - blending function
+ * - texture
+ *
+ * cocos2d also supports particles generated by Particle Designer (http://particledesigner.71squared.com/).
+ * 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d,
+ * cocos2d uses a another approach, but the results are almost identical.
+ * cocos2d supports all the variables used by Particle Designer plus a bit more:
+ * - spinning particles (supported when using ParticleSystem)
+ * - tangential acceleration (Gravity mode)
+ * - radial acceleration (Gravity mode)
+ * - radius direction (Radius mode) (Particle Designer supports outwards to inwards direction only)
+ * It is possible to customize any of the above mentioned properties in runtime. Example:
+ * + * @example + * emitter.radialAccel = 15; + * emitter.startSpin = 0; + * * @class ParticleSystem - * @extends cc._ComponentInSG + * @extends cc._RendererUnderSG */ var ParticleSystem = cc.Class({ name: 'cc.ParticleSystem', - extends: cc._ComponentInSG, + extends: cc._RendererUnderSG, editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.renderers/ParticleSystem', inspector: 'app://editor/page/inspector/particle-system/index.html', @@ -569,6 +573,7 @@ var ParticleSystem = cc.Class({ }, // LIFE-CYCLE METHODS + onLoad: function () { this._super(); // auto play @@ -579,12 +584,7 @@ var ParticleSystem = cc.Class({ this._applyAutoRemove(); } }, - //onEnable: function () { - // this._super(); - //}, - //onDisable: function () { - // this._super(); - //}, + onDestroy: function () { if (this._autoRemoveOnFinish) { this.autoRemoveOnFinish = false; // already removed @@ -723,26 +723,37 @@ var ParticleSystem = cc.Class({ var file = this._file; if (file) { var self = this; - cc.loader.load(file, function (err, results) { - if (err) throw err; + cc.loader.load(file, function (err, content) { + if (err || !content) { + throw err || new Error('Unkown error'); + } sgNode.particleCount = 0; var active = sgNode.isActive(); sgNode.initWithFile(file); + // To avoid it export custom particle data textureImageData too large, + // so use the texutreUuid instead of textureImageData + if (content.textureUuid) { + cc.AssetLibrary.queryAssetInfo(content.textureUuid, function (err, url, raw) { + self.texture = url; + }); + } + + // For custom data export + if (content.emissionRate) { + self.emissionRate = content.emissionRate; + } + // recover sgNode properties + + sgNode.setPosition(0, 0); if (!active) { sgNode.stopSystem(); } - var sourcePos = sgNode.getPosition(); - if (CC_EDITOR && (sourcePos.x !== 0 || sourcePos.y !== 0)) { - cc.log('Discard sourcePosition: %s from "%s", you can set position in the node directly.', sourcePos, cc.path.basename(file)); - } - sgNode.setPosition(0, 0); - if (!CC_EDITOR || cc.engine.isPlaying) { self._applyAutoRemove(); } diff --git a/cocos2d/particle/CCSGParticleSystem.js b/cocos2d/particle/CCSGParticleSystem.js index 7aa02fc39f..b854f8b820 100644 --- a/cocos2d/particle/CCSGParticleSystem.js +++ b/cocos2d/particle/CCSGParticleSystem.js @@ -1953,7 +1953,7 @@ _ccsg.ParticleSystem = _ccsg.Node.extend({ if (!spriteFrame) return; - var locOffset = spriteFrame.getOffsetInPixels(); + var locOffset = spriteFrame.getOffset(); if (locOffset.x !== 0 || locOffset.y !== 0) cc.log("_ccsg.ParticleSystem.setDisplayFrame(): QuadParticle only supports SpriteFrames with no offsets"); diff --git a/cocos2d/particle/CCSGParticleSystemWebGLRenderCmd.js b/cocos2d/particle/CCSGParticleSystemWebGLRenderCmd.js index 9c36609b80..945f4cb6e4 100644 --- a/cocos2d/particle/CCSGParticleSystemWebGLRenderCmd.js +++ b/cocos2d/particle/CCSGParticleSystemWebGLRenderCmd.js @@ -209,13 +209,6 @@ proto.initTexCoordsWithRect = function(pointRect){ var node = this._node; var texture = node.texture; - var scaleFactor = cc.contentScaleFactor(); - // convert to pixels coords - var rect = cc.rect( - pointRect.x * scaleFactor, - pointRect.y * scaleFactor, - pointRect.width * scaleFactor, - pointRect.height * scaleFactor); var wide = pointRect.width; var high = pointRect.height; @@ -227,15 +220,15 @@ var left, bottom, right, top; if (cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL) { - left = (rect.x * 2 + 1) / (wide * 2); - bottom = (rect.y * 2 + 1) / (high * 2); - right = left + (rect.width * 2 - 2) / (wide * 2); - top = bottom + (rect.height * 2 - 2) / (high * 2); + left = (pointRect.x * 2 + 1) / (wide * 2); + bottom = (pointRect.y * 2 + 1) / (high * 2); + right = left + (pointRect.width * 2 - 2) / (wide * 2); + top = bottom + (pointRect.height * 2 - 2) / (high * 2); } else { - left = rect.x / wide; - bottom = rect.y / high; - right = left + rect.width / wide; - top = bottom + rect.height / high; + left = pointRect.x / wide; + bottom = pointRect.y / high; + right = left + pointRect.width / wide; + top = bottom + pointRect.height / high; } // Important. Texture in cocos2d are inverted, so the Y component should be inverted diff --git a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js index 72ebb85b23..5a5f1ca9ea 100644 --- a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js +++ b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js @@ -50,9 +50,9 @@ proto.initWithWidthAndHeight = function(width, height, format, depthStencilFormat){ var node = this._node; - var locCacheCanvas = this._cacheCanvas, locScaleFactor = cc.contentScaleFactor(); - locCacheCanvas.width = 0 | (width * locScaleFactor); - locCacheCanvas.height = 0 | (height * locScaleFactor); + var locCacheCanvas = this._cacheCanvas; + locCacheCanvas.width = 0 | width; + locCacheCanvas.height = 0 | height; var texture = new cc.Texture2D(); texture.initWithElement(locCacheCanvas); @@ -86,8 +86,7 @@ proto.end = function(){ var node = this._node; - var scale = cc.contentScaleFactor(); - cc.renderer._renderingToCacheCanvas(this._cacheContext, node.__instanceId, scale, scale); + cc.renderer._renderingToCacheCanvas(this._cacheContext, node.__instanceId); }; proto.clearRect = function(x, y, width, height){ diff --git a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js index b272a6fdab..e35ce64b97 100644 --- a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js +++ b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js @@ -133,12 +133,12 @@ if(format === cc.Texture2D.PIXEL_FORMAT_A8) cc.log( "cc.RenderTexture._initWithWidthAndHeightForWebGL() : only RGB and RGBA formats are valid for a render texture;"); - var gl = cc._renderContext, locScaleFactor = cc.contentScaleFactor(); + var gl = cc._renderContext; this._fullRect = new cc.Rect(0,0, width, height); this._fullViewport = new cc.Rect(0,0, width, height); - width = 0 | (width * locScaleFactor); - height = 0 | (height * locScaleFactor); + width = 0 | width; + height = 0 | height; this._oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING); @@ -329,11 +329,11 @@ /* var size = director.getWinSizeInPixels(); // restore viewport - gl.viewport(0, 0, size.width * cc.contentScaleFactor(), size.height * cc.contentScaleFactor()); + gl.viewport(0, 0, size.width, size.height); // special viewport for 3d projection + retina display - if (director.getProjection() == cc.Director.PROJECTION_3D && cc.contentScaleFactor() != 1) { - gl.viewport((-size.width / 2), (-size.height / 2), (size.width * cc.contentScaleFactor()), (size.height * cc.contentScaleFactor())); + if (director.getProjection() == cc.Director.PROJECTION_3D) { + gl.viewport((-size.width / 2), (-size.height / 2), size.width, size.height)); } director.setProjection(director.getProjection());*/ diff --git a/cocos2d/tilemap/CCTMXLayer.js b/cocos2d/tilemap/CCSGTMXLayer.js similarity index 90% rename from cocos2d/tilemap/CCTMXLayer.js rename to cocos2d/tilemap/CCSGTMXLayer.js index bb2a3d6309..508797625f 100644 --- a/cocos2d/tilemap/CCTMXLayer.js +++ b/cocos2d/tilemap/CCSGTMXLayer.js @@ -25,7 +25,7 @@ ****************************************************************************/ /** - *

cc.TMXLayer represents the TMX layer.

+ *

_ccsg.TMXLayer represents the TMX layer.

* *

It is a subclass of cc.SpriteBatchNode. By default the tiles are rendered using a cc.TextureAtlas.
* If you modify a tile on runtime, then, that tile will become a _ccsg.Sprite, otherwise no _ccsg.Sprite objects are created.
@@ -55,7 +55,7 @@ * @property {Number} tileWidth - Width of a tile * @property {Number} tileHeight - Height of a tile */ -cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ +_ccsg.TMXLayer = cc.SpriteBatchNode.extend(/** @lends _ccsg.TMXLayer# */{ tiles: null, tileset: null, layerOrientation: null, @@ -81,10 +81,10 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ _className:"TMXLayer", /** - * Creates a cc.TMXLayer with an tile set info, a layer info and a map info
- * Constructor of cc.TMXLayer + * Creates a _ccsg.TMXLayer with an tile set info, a layer info and a map info
+ * Constructor of _ccsg.TMXLayer * @param {cc.TMXTilesetInfo} tilesetInfo - * @param {cc.TMXLayerInfo} layerInfo + * @param {_ccsg.TMXLayerInfo} layerInfo * @param {cc.TMXMapInfo} mapInfo */ ctor:function (tilesetInfo, layerInfo, mapInfo) { @@ -100,9 +100,9 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ _createRenderCmd: function(){ if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new cc.TMXLayer.CanvasRenderCmd(this); + return new _ccsg.TMXLayer.CanvasRenderCmd(this); else - return new cc.TMXLayer.WebGLRenderCmd(this); + return new _ccsg.TMXLayer.WebGLRenderCmd(this); }, /** @@ -250,7 +250,7 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ }, /** - * Initializes a cc.TMXLayer with a tileset info, a layer info and a map info + * Initializes a _ccsg.TMXLayer with a tileset info, a layer info and a map info * @param {cc.TMXTilesetInfo} tilesetInfo * @param {cc.TMXLayerInfo} layerInfo * @param {cc.TMXMapInfo} mapInfo @@ -285,11 +285,11 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ // offset (after layer orientation is set); var offset = this._calculateLayerOffset(layerInfo.offset); - this.setPosition(cc.pointPixelsToPoints(offset)); + this.setPosition(offset); this._atlasIndexArray = []; - this.setContentSize(cc.sizePixelsToPoints(cc.size(this._layerSize.width * this._mapTileSize.width, - this._layerSize.height * this._mapTileSize.height))); + this.setContentSize(cc.size(this._layerSize.width * this._mapTileSize.width, + this._layerSize.height * this._mapTileSize.height)); this._useAutomaticVertexZ = false; this._vertexZvalue = 0; return true; @@ -312,7 +312,7 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ /** *

Returns the tile (_ccsg.Sprite) at a given a tile coordinate.
- * The returned _ccsg.Sprite will be already added to the cc.TMXLayer. Don't add it again.
+ * The returned _ccsg.Sprite will be already added to the _ccsg.TMXLayer. Don't add it again.
* The _ccsg.Sprite can be treated like any other _ccsg.Sprite: rotated, scaled, translated, opacity, color, etc.
* You can remove either by calling:
* - layer.removeChild(sprite, cleanup);
@@ -323,13 +323,13 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ */ getTileAt: function (pos, y) { if(!pos) - throw new Error("cc.TMXLayer.getTileAt(): pos should be non-null"); + throw new Error("_ccsg.TMXLayer.getTileAt(): pos should be non-null"); if(y !== undefined) pos = cc.p(pos, y); if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) - throw new Error("cc.TMXLayer.getTileAt(): invalid position"); + throw new Error("_ccsg.TMXLayer.getTileAt(): invalid position"); if(!this.tiles || !this._atlasIndexArray){ - cc.log("cc.TMXLayer.getTileAt(): TMXLayer: the tiles map has been released"); + cc.log("_ccsg.TMXLayer.getTileAt(): TMXLayer: the tiles map has been released"); return null; } @@ -344,7 +344,6 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ // tile not created yet. create it if (!tile) { var rect = this.tileset.rectForGID(gid); - rect = cc.rectPixelsToPoints(rect); tile = new _ccsg.Sprite(); tile.initWithTexture(this.texture, rect); @@ -371,13 +370,13 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ */ getTileGIDAt:function (pos, y) { if(pos == null) - throw new Error("cc.TMXLayer.getTileGIDAt(): pos should be non-null"); + throw new Error("_ccsg.TMXLayer.getTileGIDAt(): pos should be non-null"); if(y !== undefined) pos = cc.p(pos, y); if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) - throw new Error("cc.TMXLayer.getTileGIDAt(): invalid position"); + throw new Error("_ccsg.TMXLayer.getTileGIDAt(): invalid position"); if(!this.tiles || !this._atlasIndexArray){ - cc.log("cc.TMXLayer.getTileGIDAt(): TMXLayer: the tiles map has been released"); + cc.log("_ccsg.TMXLayer.getTileGIDAt(): TMXLayer: the tiles map has been released"); return null; } @@ -398,13 +397,13 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ */ getTileFlagsAt:function (pos, y) { if(!pos) - throw new Error("cc.TMXLayer.getTileFlagsAt(): pos should be non-null"); + throw new Error("_ccsg.TMXLayer.getTileFlagsAt(): pos should be non-null"); if(y !== undefined) pos = cc.p(pos, y); if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) - throw new Error("cc.TMXLayer.getTileFlagsAt(): invalid position"); + throw new Error("_ccsg.TMXLayer.getTileFlagsAt(): invalid position"); if(!this.tiles || !this._atlasIndexArray){ - cc.log("cc.TMXLayer.getTileFlagsAt(): TMXLayer: the tiles map has been released"); + cc.log("_ccsg.TMXLayer.getTileFlagsAt(): TMXLayer: the tiles map has been released"); return null; } @@ -428,7 +427,7 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ */ setTileGID: function(gid, posOrX, flagsOrY, flags) { if(!posOrX) - throw new Error("cc.TMXLayer.setTileGID(): pos should be non-null"); + throw new Error("_ccsg.TMXLayer.setTileGID(): pos should be non-null"); var pos; if (flags !== undefined) { pos = cc.p(posOrX, flagsOrY); @@ -437,13 +436,13 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ flags = flagsOrY; } if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) - throw new Error("cc.TMXLayer.setTileGID(): invalid position"); + throw new Error("_ccsg.TMXLayer.setTileGID(): invalid position"); if(!this.tiles || !this._atlasIndexArray){ - cc.log("cc.TMXLayer.setTileGID(): TMXLayer: the tiles map has been released"); + cc.log("_ccsg.TMXLayer.setTileGID(): TMXLayer: the tiles map has been released"); return; } if(gid !== 0 && gid < this.tileset.firstGid){ - cc.log( "cc.TMXLayer.setTileGID(): invalid gid:" + gid); + cc.log( "_ccsg.TMXLayer.setTileGID(): invalid gid:" + gid); return; } @@ -464,7 +463,6 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ var sprite = this.getChildByTag(z); if (sprite) { var rect = this.tileset.rectForGID(gid); - rect = cc.rectPixelsToPoints(rect); sprite.setTextureRect(rect, false); if (flags != null) @@ -484,13 +482,13 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ */ removeTileAt:function (pos, y) { if(!pos) - throw new Error("cc.TMXLayer.removeTileAt(): pos should be non-null"); + throw new Error("_ccsg.TMXLayer.removeTileAt(): pos should be non-null"); if(y !== undefined) pos = cc.p(pos, y); if(pos.x >= this._layerSize.width || pos.y >= this._layerSize.height || pos.x < 0 || pos.y < 0) - throw new Error("cc.TMXLayer.removeTileAt(): invalid position"); + throw new Error("_ccsg.TMXLayer.removeTileAt(): invalid position"); if(!this.tiles || !this._atlasIndexArray){ - cc.log("cc.TMXLayer.removeTileAt(): TMXLayer: the tiles map has been released"); + cc.log("_ccsg.TMXLayer.removeTileAt(): TMXLayer: the tiles map has been released"); return; } @@ -552,7 +550,7 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ ret = this._positionForHexAt(pos); break; } - return cc.pointPixelsToPoints(ret); + return ret; }, // XXX: Deprecated. For backward compatibility only // positionAt:getPositionAt, @@ -600,14 +598,14 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ }, /** - * cc.TMXLayer doesn't support adding a _ccsg.Sprite manually. - * @warning addChild(child); is not supported on cc.TMXLayer. Instead of setTileGID. + * _ccsg.TMXLayer doesn't support adding a _ccsg.Sprite manually. + * @warning addChild(child); is not supported on _ccsg.TMXLayer. Instead of setTileGID. * @param {_ccsg.Node} child * @param {number} zOrder * @param {number} tag */ addChild:function (child, zOrder, tag) { - cc.log("addChild: is not supported on cc.TMXLayer. Instead use setTileGID or tileAt."); + cc.log("addChild: is not supported on _ccsg.TMXLayer. Instead use setTileGID or tileAt."); }, /** @@ -621,7 +619,7 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ return; if(this._children.indexOf(sprite) === -1){ - cc.log("cc.TMXLayer.removeChild(): Tile does not belong to TMXLayer"); + cc.log("_ccsg.TMXLayer.removeChild(): Tile does not belong to TMXLayer"); return; } @@ -687,7 +685,6 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ _appendTileForGID:function (gid, pos) { var rect = this.tileset.rectForGID(gid); - rect = cc.rectPixelsToPoints(rect); var z = 0 | (pos.x + pos.y * this._layerSize.width); var tile = this._renderCmd._reusedTileWithRect(rect); @@ -708,7 +705,6 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ _insertTileForGID:function (gid, pos) { var rect = this.tileset.rectForGID(gid); - rect = cc.rectPixelsToPoints(rect); var z = 0 | (pos.x + pos.y * this._layerSize.width); var tile = this._renderCmd._reusedTileWithRect(rect); @@ -866,7 +862,7 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ } } if(!cc.js.isNumber(item)) - cc.log("cc.TMXLayer._atlasIndexForExistantZ(): TMX atlas index not found. Shall not happen"); + cc.log("_ccsg.TMXLayer._atlasIndexForExistantZ(): TMX atlas index not found. Shall not happen"); return i; }, @@ -881,7 +877,7 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{ } }); -var _p = cc.TMXLayer.prototype; +var _p = _ccsg.TMXLayer.prototype; /** @expose */ cc.defineGetterSetter(_p, "texture", _p.getTexture, _p.setTexture); @@ -902,13 +898,13 @@ cc.defineGetterSetter(_p, "tileHeight", _p._getTileHeight, _p._setTileHeight); /** - * Creates a cc.TMXLayer with an tile set info, a layer info and a map info - * @deprecated since v3.0 please use new cc.TMXLayer(tilesetInfo, layerInfo, mapInfo) instead. + * Creates a _ccsg.TMXLayer with an tile set info, a layer info and a map info + * @deprecated since v3.0 please use new _ccsg.TMXLayer(tilesetInfo, layerInfo, mapInfo) instead. * @param {cc.TMXTilesetInfo} tilesetInfo * @param {cc.TMXLayerInfo} layerInfo * @param {cc.TMXMapInfo} mapInfo - * @return {cc.TMXLayer|Null} + * @return {_ccsg.TMXLayer|Null} */ -cc.TMXLayer.create = function (tilesetInfo, layerInfo, mapInfo) { - return new cc.TMXLayer(tilesetInfo, layerInfo, mapInfo); +_ccsg.TMXLayer.create = function (tilesetInfo, layerInfo, mapInfo) { + return new _ccsg.TMXLayer(tilesetInfo, layerInfo, mapInfo); }; diff --git a/cocos2d/tilemap/CCTMXTiledMap.js b/cocos2d/tilemap/CCSGTMXTiledMap.js similarity index 89% rename from cocos2d/tilemap/CCTMXTiledMap.js rename to cocos2d/tilemap/CCSGTMXTiledMap.js index de39af7d61..89126fd712 100644 --- a/cocos2d/tilemap/CCTMXTiledMap.js +++ b/cocos2d/tilemap/CCSGTMXTiledMap.js @@ -76,9 +76,9 @@ cc.TMX_ORIENTATION_ISO = 2; * - It only supports the XML format (the JSON format is not supported)

* *

Technical description:
- * Each layer is created using an cc.TMXLayer (subclass of cc.SpriteBatchNode). If you have 5 layers, then 5 cc.TMXLayer will be created,
+ * Each layer is created using an _ccsg.TMXLayer (subclass of cc.SpriteBatchNode). If you have 5 layers, then 5 _ccsg.TMXLayer will be created,
* unless the layer visibility is off. In that case, the layer won't be created at all.
- * You can obtain the layers (cc.TMXLayer objects) at runtime by:
+ * You can obtain the layers (_ccsg.TMXLayer objects) at runtime by:
* - map.getChildByTag(tag_number); // 0=1st layer, 1=2nd layer, 2=3rd layer, etc...
* - map.getLayer(name_of_the_layer);

* @@ -121,7 +121,7 @@ cc.TMX_ORIENTATION_ISO = 2; * var xmlStr = cc.loader.getRes(filePath); * var tmxTiledMap = new cc.TMXTiledMap(xmlStr, resources); */ -cc.TMXTiledMap = _ccsg.Node.extend(/** @lends cc.TMXTiledMap# */{ +_ccsg.TMXTiledMap = _ccsg.Node.extend(/** @lends cc.TMXTiledMap# */{ properties: null, mapOrientation: null, objectGroups: null, @@ -135,7 +135,7 @@ cc.TMXTiledMap = _ccsg.Node.extend(/** @lends cc.TMXTiledMap# */{ /** * Creates a TMX Tiled Map with a TMX file or content string.
- * Constructor of cc.TMXTiledMap + * Constructor of _ccsg.TMXTiledMap * @param {String} tmxFile tmxFile fileName or content string * @param {String} resourcePath If tmxFile is a file name ,it is not required.If tmxFile is content string ,it is must required. */ @@ -260,17 +260,18 @@ cc.TMXTiledMap = _ccsg.Node.extend(/** @lends cc.TMXTiledMap# */{ }, /** - * Initializes the instance of cc.TMXTiledMap with tmxFile + * Initializes the instance of _ccsg.TMXTiledMap with tmxFile * @param {String} tmxFile * @return {Boolean} Whether the initialization was successful. * @example * //example - * var map = new cc.TMXTiledMap() + * var map = new _ccsg.TMXTiledMap() * map.initWithTMXFile("hello.tmx"); */ initWithTMXFile:function (tmxFile) { - if(!tmxFile || tmxFile.length === 0) - throw new Error("cc.TMXTiledMap.initWithTMXFile(): tmxFile should be non-null or non-empty string."); + if(!tmxFile || tmxFile.length === 0) { + return false; + } this.width = 0; this.height = 0; var mapInfo = new cc.TMXMapInfo(tmxFile); @@ -279,13 +280,13 @@ cc.TMXTiledMap = _ccsg.Node.extend(/** @lends cc.TMXTiledMap# */{ var locTilesets = mapInfo.getTilesets(); if(!locTilesets || locTilesets.length === 0) - cc.log("cc.TMXTiledMap.initWithTMXFile(): Map not found. Please check the filename."); + cc.log("_ccsg.TMXTiledMap.initWithTMXFile(): Map not found. Please check the filename."); this._buildWithMapInfo(mapInfo); return true; }, /** - * Initializes the instance of cc.TMXTiledMap with tmxString + * Initializes the instance of _ccsg.TMXTiledMap with tmxString * @param {String} tmxString * @param {String} resourcePath * @return {Boolean} Whether the initialization was successful. @@ -297,7 +298,7 @@ cc.TMXTiledMap = _ccsg.Node.extend(/** @lends cc.TMXTiledMap# */{ var mapInfo = new cc.TMXMapInfo(tmxString, resourcePath); var locTilesets = mapInfo.getTilesets(); if(!locTilesets || locTilesets.length === 0) - cc.log("cc.TMXTiledMap.initWithXML(): Map not found. Please check the filename."); + cc.log("_ccsg.TMXTiledMap.initWithXML(): Map not found. Please check the filename."); this._buildWithMapInfo(mapInfo); return true; }, @@ -310,6 +311,15 @@ cc.TMXTiledMap = _ccsg.Node.extend(/** @lends cc.TMXTiledMap# */{ this.properties = mapInfo.properties; this._tileProperties = mapInfo.getTileProperties(); + // remove the layers added before + var oldLayers = this.allLayers(); + for (var j = 0, n = oldLayers.length; j < n; j++) { + var layer = oldLayers[j]; + if (layer) { + this.removeChild(layer); + } + } + var idx = 0; var layers = mapInfo.getLayers(); if (layers) { @@ -336,7 +346,7 @@ cc.TMXTiledMap = _ccsg.Node.extend(/** @lends cc.TMXTiledMap# */{ var retArr = [], locChildren = this._children; for(var i = 0, len = locChildren.length;i< len;i++){ var layer = locChildren[i]; - if(layer && layer instanceof cc.TMXLayer) + if(layer && layer instanceof _ccsg.TMXLayer) retArr.push(layer); } return retArr; @@ -345,11 +355,11 @@ cc.TMXTiledMap = _ccsg.Node.extend(/** @lends cc.TMXTiledMap# */{ /** * return the TMXLayer for the specific layer * @param {String} layerName - * @return {cc.TMXLayer} + * @return {_ccsg.TMXLayer} */ getLayer:function (layerName) { if(!layerName || layerName.length === 0) - throw new Error("cc.TMXTiledMap.getLayer(): layerName should be non-null or non-empty string."); + throw new Error("_ccsg.TMXTiledMap.getLayer(): layerName should be non-null or non-empty string."); var locChildren = this._children; for (var i = 0; i < locChildren.length; i++) { var layer = locChildren[i]; @@ -367,7 +377,7 @@ cc.TMXTiledMap = _ccsg.Node.extend(/** @lends cc.TMXTiledMap# */{ */ getObjectGroup:function (groupName) { if(!groupName || groupName.length === 0) - throw new Error("cc.TMXTiledMap.getObjectGroup(): groupName should be non-null or non-empty string."); + throw new Error("_ccsg.TMXTiledMap.getObjectGroup(): groupName should be non-null or non-empty string."); if (this.objectGroups) { for (var i = 0; i < this.objectGroups.length; i++) { var objectGroup = this.objectGroups[i]; @@ -411,7 +421,7 @@ cc.TMXTiledMap = _ccsg.Node.extend(/** @lends cc.TMXTiledMap# */{ _parseLayer:function (layerInfo, mapInfo) { var tileset = this._tilesetForLayer(layerInfo, mapInfo); - var layer = new cc.TMXLayer(tileset, layerInfo, mapInfo); + var layer = new _ccsg.TMXLayer(tileset, layerInfo, mapInfo); // tell the layerinfo to release the ownership of the tiles map. layerInfo.ownTiles = false; layer.setupTiles(); @@ -449,7 +459,7 @@ cc.TMXTiledMap = _ccsg.Node.extend(/** @lends cc.TMXTiledMap# */{ } }); -var _p = cc.TMXTiledMap.prototype; +var _p = _ccsg.TMXTiledMap.prototype; // Extended properties /** @expose */ @@ -468,12 +478,12 @@ cc.defineGetterSetter(_p, "tileHeight", _p._getTileHeight, _p._setTileHeight); /** * Creates a TMX Tiled Map with a TMX file or content string. - * Implementation cc.TMXTiledMap - * @deprecated since v3.0 please use new cc.TMXTiledMap(tmxFile,resourcePath) instead. + * Implementation _ccsg.TMXTiledMap + * @deprecated since v3.0 please use new _ccsg.TMXTiledMap(tmxFile,resourcePath) instead. * @param {String} tmxFile tmxFile fileName or content string * @param {String} resourcePath If tmxFile is a file name ,it is not required.If tmxFile is content string ,it is must required. - * @return {cc.TMXTiledMap|undefined} + * @return {_ccsg.TMXTiledMap|undefined} */ -cc.TMXTiledMap.create = function (tmxFile,resourcePath) { - return new cc.TMXTiledMap(tmxFile,resourcePath); +_ccsg.TMXTiledMap.create = function (tmxFile,resourcePath) { + return new _ccsg.TMXTiledMap(tmxFile,resourcePath); }; diff --git a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js index 6051b50e11..d90a4a767e 100644 --- a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js @@ -23,7 +23,7 @@ ****************************************************************************/ (function(){ - cc.TMXLayer.CanvasRenderCmd = function(renderable){ + _ccsg.TMXLayer.CanvasRenderCmd = function(renderable){ cc.SpriteBatchNode.CanvasRenderCmd.call(this, renderable); this._needDraw = true; this._realWorldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0}; @@ -42,8 +42,8 @@ this._cacheDirty = false; }; - var proto = cc.TMXLayer.CanvasRenderCmd.prototype = Object.create(cc.SpriteBatchNode.CanvasRenderCmd.prototype); - proto.constructor = cc.TMXLayer.CanvasRenderCmd; + var proto = _ccsg.TMXLayer.CanvasRenderCmd.prototype = Object.create(cc.SpriteBatchNode.CanvasRenderCmd.prototype); + proto.constructor = _ccsg.TMXLayer.CanvasRenderCmd; //set the cache dirty flag for canvas proto._setNodeDirtyForCache = function () { @@ -106,14 +106,13 @@ proto._updateCacheContext = function(size, height){ var node = this._node, locContentSize = node._contentSize, - locCanvas = this._cacheCanvas, - scaleFactor = cc.contentScaleFactor(); - locCanvas.width = 0 | (locContentSize.width * 1.5 * scaleFactor); - locCanvas.height = 0 | (locContentSize.height * 1.5 * scaleFactor); + locCanvas = this._cacheCanvas; + locCanvas.width = 0 | (locContentSize.width * 1.5); + locCanvas.height = 0 | (locContentSize.height * 1.5); //todo: need change the wrapper's height if(node.layerOrientation === cc.TMX_ORIENTATION_HEX) - this._cacheContext.setOffset(0, -node._mapTileSize.height * 0.5); //translate for hexagonal + this._cacheContext.setOffset(0, -node._mapTileSize.height * 0.5); //translate for hexagonal else this._cacheContext.setOffset(0, 0); var locTexContentSize = this._cacheTexture._contentSize; diff --git a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js index de0ea7d8ae..a5c262eec4 100644 --- a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js +++ b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js @@ -23,13 +23,13 @@ ****************************************************************************/ (function(){ - cc.TMXLayer.WebGLRenderCmd = function(renderableObject){ + _ccsg.TMXLayer.WebGLRenderCmd = function(renderableObject){ cc.SpriteBatchNode.WebGLRenderCmd.call(this, renderableObject); this._needDraw = true; }; - var proto = cc.TMXLayer.WebGLRenderCmd.prototype = Object.create(cc.SpriteBatchNode.WebGLRenderCmd.prototype); - proto.constructor = cc.TMXLayer.WebGLRenderCmd; + var proto = _ccsg.TMXLayer.WebGLRenderCmd.prototype = Object.create(cc.SpriteBatchNode.WebGLRenderCmd.prototype); + proto.constructor = _ccsg.TMXLayer.WebGLRenderCmd; proto._updateCacheContext = function(){}; diff --git a/cocos2d/tilemap/CCTMXXMLParser.js b/cocos2d/tilemap/CCTMXXMLParser.js index de9a70090b..fe6fa5e288 100644 --- a/cocos2d/tilemap/CCTMXXMLParser.js +++ b/cocos2d/tilemap/CCTMXXMLParser.js @@ -925,9 +925,6 @@ cc.TMXMapInfo.create = function (tmxFile, resourcePath) { }; -cc.loader.register(["tmx", "tsx"], cc._txtLoader); - - /** * @constant * @type Number diff --git a/cocos2d/tilemap/CCTiledLayer.js b/cocos2d/tilemap/CCTiledLayer.js new file mode 100644 index 0000000000..010c59a047 --- /dev/null +++ b/cocos2d/tilemap/CCTiledLayer.js @@ -0,0 +1,374 @@ +/**************************************************************************** + Copyright (c) 2016 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +/** + * Render the TMX layer. + * @class TiledLayer + * @extends _RendererUnderSG + */ +var TiledLayer = cc.Class({ + name: 'cc.TiledLayer', + extends: cc._RendererUnderSG, + + editor: CC_EDITOR, + + properties: {}, + + onLoad: function () { + var sgNode = this._sgNode; + if ( !this.node._sizeProvider ) { + this.node._sizeProvider = sgNode; + } + }, + + _createSgNode: function() { + return null; + }, + + _initSgNode: function() { + + }, + + _replaceSgNode: function(sgNode) { + if (sgNode === this._sgNode) { + return; + } + + // Remove the sgNode before + this._removeSgNode(); + + // retain the new sgNode + if (sgNode && sgNode instanceof _ccsg.TMXLayer) { + this._sgNode = sgNode; + this._sgNode.retain(); + } else { + this._sgNode = null; + } + }, + + /** + * Gets the layer name + * @method getLayerName + * @return {String} + */ + getLayerName: function() { + if (this._sgNode) { + return this._sgNode.getLayerName(); + } + return ''; + }, + + /** + * Set the layer name + * @method SetLayerName + * @param {String} layerName + */ + setLayerName:function (layerName) { + if (this._sgNode) { + this._sgNode.setLayerName(layerName); + } + }, + + /** + * Return the value for the specific property name + * @method getProperty + * @param {String} propertyName + * @return {*} + */ + getProperty:function (propertyName) { + if (this._sgNode) { + return this._sgNode.getProperty(propertyName); + } + + return null; + }, + + /** + * Returns the position in pixels of a given tile coordinate + * @method getPositionAt + * @param {Vec2|Number} pos position or x + * @param {Number} [y] + * @return {Vec2} + */ + getPositionAt:function (pos, y) { + if (this._sgNode) { + return this._sgNode.getPositionAt(pos, y); + } + + return null; + }, + + /** + * Removes a tile at given tile coordinate + * @method removeTileAt + * @param {Vec2|Number} pos position or x + * @param {Number} [y] + */ + removeTileAt:function (pos, y) { + if (this._sgNode) { + this._sgNode.removeTileAt(pos, y); + } + }, + + /** + *

Sets the tile gid (gid = tile global id) at a given tile coordinate.
+ * The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor . Tileset Mgr +1.
+ * If a tile is already placed at that position, then it will be removed.

+ * @method setTileGID + * @param {Number} gid + * @param {Vec2|Number} posOrX position or x + * @param {Number} flagsOrY flags or y + * @param {Number} [flags] + */ + setTileGID: function(gid, posOrX, flagsOrY, flags) { + if (this._sgNode) { + this._sgNode.setTileGID(gid, posOrX, flagsOrY, flags); + } + }, + + /** + * lipped tiles can be changed dynamically + * @method getTileFlagsAt + * @param {Vec2|Number} pos or x + * @param {Number} [y] + * @return {Number} + */ + getTileFlagsAt:function (pos, y) { + if (this._sgNode) { + return this._sgNode.getTileFlagsAt(pos, y); + } + return 0; + }, + + /** + * Returns the tile gid at a given tile coordinate.
+ * if it returns 0, it means that the tile is empty.
+ * This method requires the the tile map has not been previously released (eg. don't call layer.releaseMap())
+ * @method getTileGIDAt + * @param {Vec2|Number} pos or x + * @param {Number} [y] + * @return {Number} + */ + getTileGIDAt:function (pos, y) { + if (this._sgNode) { + return this._sgNode.getTileGIDAt(pos, y); + } + return 0; + }, + + /** + *

Returns the tile (_ccsg.Sprite) at a given a tile coordinate.
+ * The returned _ccsg.Sprite will be already added to the _ccsg.TMXLayer. Don't add it again.
+ * The _ccsg.Sprite can be treated like any other _ccsg.Sprite: rotated, scaled, translated, opacity, color, etc.
+ * You can remove either by calling:
+ * - layer.removeChild(sprite, cleanup);
+ * - or layer.removeTileAt(ccp(x,y));

+ * @method getTileAt + * @param {cc.Vec2|Number} pos or x + * @param {Number} [y] + * @return {_ccsg.Sprite} + */ + getTileAt: function (pos, y) { + if (this._sgNode) { + return this._sgNode.getTileAt(pos, y); + } + return null; + }, + + /** + *

Dealloc the map that contains the tile position from memory.
+ * Unless you want to know at runtime the tiles positions, you can safely call this method.
+ * If you are going to call layer.getTileGIDAt() then, don't release the map

+ * @method releaseMap + */ + releaseMap:function () { + if (this._sgNode) { + this._sgNode.releaseMap(); + } + }, + + /** + * Sets the untransformed size of the _ccsg.TMXLayer. + * @method setContentSize + * @param {cc.Size|Number} size The untransformed size of the _ccsg.TMXLayer or The untransformed size's width of the TMXLayer. + * @param {Number} [height] The untransformed size's height of the _ccsg.TMXLayer. + */ + setContentSize:function (size, height) { + if (this._sgNode) { + this._sgNode.setContentSize(size, height); + } + }, + + /** + * Return texture of cc.SpriteBatchNode + * @method getTexture + * @return {cc.Texture2D} + */ + getTexture: function(){ + if (this._sgNode) { + return this._sgNode.getTexture(); + } + return null; + }, + + /** + * Gets layer size. + * @method getLayerSize + * @return {cc.Size} + */ + getLayerSize:function () { + if (this._sgNode) { + return this._sgNode.getLayerSize(); + } + return cc.size(0, 0); + }, + + /** + * Set layer size + * @method setLayerSize + * @param {cc.Size} layerSize + */ + setLayerSize:function (layerSize) { + if (this._sgNode) { + this._sgNode.setLayerSize(layerSize); + } + }, + + /** + * Size of the map's tile (could be different from the tile's size) + * @method getMapTileSize + * @return {cc.Size} + */ + getMapTileSize:function () { + if (this._sgNode) { + return this._sgNode.getMapTileSize(); + } + return cc.size(0, 0); + }, + + /** + * Set the map tile size. + * @method setMapTileSize + * @param {cc.Size} tileSize + */ + setMapTileSize:function (tileSize) { + if (this._sgNode) { + this._sgNode.setMapTileSize(tileSize); + } + }, + + /** + * Pointer to the map of tiles + * @method getTiles + * @return {Array} + */ + getTiles:function () { + if (this._sgNode) { + return this._sgNode.getTiles(); + } + return null; + }, + + /** + * Pointer to the map of tiles + * @method setTiles + * @param {Array} tiles + */ + setTiles:function (tiles) { + if (this._sgNode) { + this._sgNode.setTiles(tiles); + } + }, + + /** + * Tile set information for the layer + * @method getTileset + * @return {cc.TMXTilesetInfo} + */ + getTileset:function () { + if (this._sgNode) { + return this._sgNode.getTileset(); + } + return null; + }, + + /** + * Tile set information for the layer + * @method setTileset + * @param {cc.TMXTilesetInfo} tileset + */ + setTileset:function (tileset) { + if (this._sgNode) { + this._sgNode.setTileset(tileset); + } + }, + + /** + * Layer orientation, which is the same as the map orientation + * @method getLayerOrientation + * @return {Number} + */ + getLayerOrientation:function () { + if (this._sgNode) { + return this._sgNode.getLayerOrientation(); + } + return 0; + }, + + /** + * Layer orientation, which is the same as the map orientation + * @method setLayerOrientation + * @param {Number} orientation + */ + setLayerOrientation:function (orientation) { + if (this._sgNode) { + this._sgNode.setLayerOrientation(orientation); + } + }, + + /** + * properties from the layer. They can be added using Tiled + * @method getProperties + * @return {Array} + */ + getProperties:function () { + if (this._sgNode) { + return this._sgNode.getProperties(); + } + return null; + }, + + /** + * properties from the layer. They can be added using Tiled + * @method setProperties + * @param {Array} properties + */ + setProperties:function (properties) { + if (this._sgNode) { + this._sgNode.setProperties(properties); + } + }, +}); + +cc.TiledLayer = module.exports = TiledLayer; diff --git a/cocos2d/tilemap/CCTiledMap.js b/cocos2d/tilemap/CCTiledMap.js new file mode 100644 index 0000000000..8189edebbb --- /dev/null +++ b/cocos2d/tilemap/CCTiledMap.js @@ -0,0 +1,541 @@ +/**************************************************************************** + Copyright (c) 2016 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +/** + * Renders a TMX Tile Map in the scene. + * @class TiledMap + * @extends Component + */ +var TiledMap = cc.Class({ + name: 'cc.TiledMap', + extends: require('../core/components/CCComponent'), + + editor: CC_EDITOR && { + menu: 'i18n:MAIN_MENU.component.renderers/TiledMap', + }, + + properties: { + _isLoading: { + default: false, + serializable: false, + }, + + _tiledMap: { + default: null, + serializable: false, + }, + + /** + * The tmx file. + * @property {string} tmxFile + * @default "" + */ + _tmxFile: { + default: '', + url: cc.TiledMapAsset + }, + + tmxFile : { + get: function () { + return this._tmxFile; + }, + set: function (value, force) { + if (this._tmxFile !== value || (CC_EDITOR && force)) { + this._tmxFile = value; + this._applyFile(); + } + }, + url: cc.TiledMapAsset + }, + + /** + * The event handler to be called when the map is loaded. + * @property {cc.Component.EventHandler} mapLoaded + */ + mapLoaded: { + default: [], + type: cc.Component.EventHandler, + } + }, + + ctor: function () { + this._tiledMap = new _ccsg.TMXTiledMap(); + if (cc.sys.isNative) { + this._tiledMap.retain(); + } + }, + + /** + * Gets the map size. + * @method getMapSize + * @return {cc.Size} + */ + getMapSize:function () { + return this._tiledMap.getMapSize(); + }, + + /** + * Set the map size. + * @method setMapSize + * @param {cc.Size} mapSize + */ + setMapSize:function (mapSize) { + this._tiledMap.setMapSize(mapSize); + }, + + /** + * Gets the tile size. + * @method getTileSize + * @return {cc.Size} + */ + getTileSize:function () { + return this._tiledMap.getTileSize(); + }, + + /** + * Set the tile size + * @method setTileSize + * @param {cc.Size} tileSize + */ + setTileSize:function (tileSize) { + this._tiledMap.setTileSize(tileSize); + }, + + /** + * map orientation + * @method getMapOrientation + * @return {Number} + */ + getMapOrientation:function () { + return this._tiledMap.getMapOrientation(); + }, + + /** + * map orientation + * @method setMapOrientation + * @param {Number} orientation + */ + setMapOrientation:function (orientation) { + this._tiledMap.setMapOrientation(orientation); + }, + + /** + * object groups + * @method getObjectGroups + * @return {Array} + */ + getObjectGroups:function () { + return this._tiledMap.getObjectGroups(); + }, + + /** + * object groups + * @method setObjectGroups + * @param {Array} groups + */ + setObjectGroups:function (groups) { + this._tiledMap.setObjectGroups(groups); + }, + + /** + * Gets the map properties + * @method getProperties + * @return {object} + */ + getProperties:function () { + return this._tiledMap.getProperties(); + }, + + /** + * Set the map properties + * @method setProperties + * @param {object} properties + */ + setProperties:function (properties) { + this._tiledMap.setProperties(properties); + }, + + /** + * Initializes the instance of cc.TiledMap with tmxFile. + * The mapLoaded events will be emitted when the map is loaded. + * @method initWithTMXFile + * @param {String} tmxFile + */ + initWithTMXFile:function (tmxFile) { + this._tmxFile = tmxFile; + }, + + /** + * Initializes the instance of cc.TiledMap with tmxString. + * The mapLoaded events will be emitted when the map is loaded. + * @method initWithXML + * @param {String} tmxString + * @param {String} resourcePath + */ + initWithXML:function(tmxString, resourcePath){ + // clear the tmx file + this._tmxFile = null; + + // preload textures & init the _tileMap + var sgNode = this._tiledMap; + var self = this; + var mapInfo = new cc.TMXMapInfo(tmxString, resourcePath); + if (!mapInfo) { + self._onMapLoaded(new Error('Parse map info failed.')); + return; + } + + self._isLoading = true; + this._preloadTextures(mapInfo, function(err, results) { + if (err) { + self._onMapLoaded(err); + } else { + sgNode.initWithXML(tmxString, resourcePath); + self._onMapLoaded(); + } + }); + }, + + /** + * Return All layers array. + * @method allLayers + * @returns {Array} + */ + allLayers: function () { + var logicChildren = this.node.getChildren(); + var ret = []; + for (var i = 0, n = logicChildren.length; i < n; i++) { + var child = logicChildren[i]; + var tmxLayer = child.getComponent('cc.TiledLayer'); + if (tmxLayer) { + ret.push(tmxLayer); + } + } + + return ret; + }, + + /** + * return the cc.TiledLayer for the specific layer + * @method getLayer + * @param {String} layerName + * @return {cc.TiledLayer} + */ + getLayer:function (layerName) { + var logicChildren = this.node.getChildren(); + var ret = null; + for (var i = 0, n = logicChildren.length; i < n; i++) { + var child = logicChildren[i]; + var tmxLayer = child.getComponent('cc.TiledLayer'); + if (tmxLayer && tmxLayer.getLayerName() === layerName) { + ret = tmxLayer; + break; + } + } + + return ret; + }, + + /** + * Return the TMXObjectGroup for the specific group + * @method getObjectGroup + * @param {String} groupName + * @return {cc.TMXObjectGroup} + */ + getObjectGroup:function (groupName) { + return this._tiledMap.getObjectGroup(groupName); + }, + + /** + * Return the value for the specific property name + * @method getProperty + * @param {String} propertyName + * @return {String} + */ + getProperty:function (propertyName) { + return this._tiledMap.getProperty(propertyName); + }, + + /** + * Return properties dictionary for tile GID + * @method getPropertiesForGID + * @param {Number} GID + * @return {object} + */ + getPropertiesForGID: function(GID) { + return this._tiledMap.getPropertiesForGID(GID); + }, + + onEnable: function () { + this.node._replaceSgNode(this._tiledMap); + + if (this._tmxFile && ! this._isLoading) { + // refresh layer entities + this._refreshLayerEntities(); + } + + this.node.on('child-added', this._childAdded, this); + this.node.on('child-reorder', this._reorderChildren, this); + if ( !this.node._sizeProvider ) { + this.node._sizeProvider = this._tiledMap; + } + }, + + onDisable: function () { + // replace a new sgNode + var newNode = new _ccsg.Node(); + this.node._replaceSgNode(newNode); + + // remove the logic children for tmx layers + this._removeLayerEntities(); + + // should move the tmx layers from newNode to _tiledMap + this._moveLayersInSgNode(newNode); + + this.node.off('child-added', this._childAdded, this); + this.node.off('child-reorder', this._reorderChildren, this); + if ( this.node._sizeProvider === this._tiledMap ) { + this.node._sizeProvider = newNode; + } + }, + + onLoad: function () { + this._applyFile(); + }, + + onDestroy: function () { + if (cc.sys.isNative) { + this._tiledMap && this._tiledMap.release(); + } + }, + + _preloadTextures: function(mapInfo, cb) { + var sets = mapInfo.getTilesets(); + if (sets) { + var textures = sets.map(function (set) { + return set.sourceImage; + }); + + cc.loader.load(textures, function (err) { + cb(err, textures); + }); + } + else { + if (cb) cb(); + } + }, + + _preloadTmx: function(file, cb) { + var self = this; + cc.loader.load(file, function (err) { + if (err) { + if (cb) cb(err || new Error('Preload TMX failed: unknown error')); + return; + } + + var mapInfo = new cc.TMXMapInfo(file); + if (!mapInfo) { + cb(new Error('Parse map info failed.')); + return; + } + + self._preloadTextures(mapInfo, cb); + }); + }, + + _onMapLoaded: function(err) { + this._isLoading = false; + if (err) { + cc.Component.EventHandler.emitEvents(this.mapLoaded, err); + } else { + if (this._enabled) { + this._refreshLayerEntities(); + } + cc.Component.EventHandler.emitEvents(this.mapLoaded); + } + }, + + _moveLayersInSgNode: function(sgNode) { + var children = sgNode.getChildren(); + var needRemove = []; + for (var i = 0, n = children.length; i < n; i++) { + var child = children[i]; + if (child instanceof _ccsg.TMXLayer) { + needRemove.push({child: child, zorder: child.getLocalZOrder()}); + } + } + for (i = 0, n = needRemove.length; i < n; i++) { + var info = needRemove[i]; + sgNode.removeChild(info.child); + this._tiledMap.addChild(info.child, info.zorder, info.zorder); + } + }, + + _removeLayerEntities: function() { + var i, n; + var logicChildren = this.node.getChildren(); + var needRemove = []; + for (i = 0, n = logicChildren.length; i < n; i++) { + var child = logicChildren[i]; + var tmxLayer = child.getComponent('cc.TiledLayer'); + if (tmxLayer) { + needRemove.push(child); + } + } + + for (i = 0, n = needRemove.length; i < n; i++) { + this.node.removeChild(needRemove[i]); + } + }, + + _refreshLayerEntities: function() { + // get the layer names in scene graph. + var layerNames = this._tiledMap.allLayers().map(function (layer) { + return layer.getLayerName(); + }); + + var logicChildren = this.node.getChildren(); + var needRemove = []; + var existedLayers = []; + var otherChildrenInfo = []; + var i, n; + + // check the children of this.node + for (i = 0, n = logicChildren.length; i < n; i++) { + var child = logicChildren[i]; + var tmxLayer = child.getComponent('cc.TiledLayer'); + if (tmxLayer) { + var layerName = tmxLayer.getLayerName(); + if (layerNames.indexOf(layerName) < 0) { + // the tmx layer should be removed + needRemove.push(child); + } else { + // the tmx layer should be updated + existedLayers.push(child); + var newSGLayer = this._tiledMap.getLayer(layerName); + tmxLayer._replaceSgNode(newSGLayer); + } + } else { + otherChildrenInfo.push({child: child, index: child.getSiblingIndex()}); + } + } + + // remove the deprecated tmx layers + for (i = 0, n = needRemove.length; i < n; i++) { + this.node.removeChild(needRemove[i]); + } + + // add new tmx layers & update the sibling index with ZOrder + var existedNames = existedLayers.map(function(node) { + var tmxLayer = node.getComponent('cc.TiledLayer'); + return tmxLayer.getLayerName(); + }); + + for (i = 0, n = layerNames.length; i < n; i++) { + var name = layerNames[i]; + var sgLayer = this._tiledMap.getLayer(name); + if (existedNames.indexOf(name) < 0) { + // need add entity for the tmx layer + var node = new cc.Node(name); + var addedLayer = node.addComponent(cc.TiledLayer); + addedLayer._replaceSgNode(sgLayer); + this.node.addChild(node); + node.setSiblingIndex(sgLayer.getLocalZOrder()); + } else { + existedLayers[i].setSiblingIndex(sgLayer.getLocalZOrder()); + } + } + + // update the sibling index of the other children + for (i = 0, n = otherChildrenInfo.length; i < n; i++) { + var info = otherChildrenInfo[i]; + info.child.setSiblingIndex(info.index); + } + + // reorder the children + this._reorderChildren(); + }, + + _childAdded: function(event) { + var node = event.detail; + if (node) { + var tmxLayer = node.getComponent('cc.TiledLayer'); + if (!tmxLayer) { + var childrenCount = this.node.getChildrenCount(); + node.setSiblingIndex(childrenCount); + if (node._sgNode) { + node._sgNode.setLocalZOrder(childrenCount); + } + } + } + }, + + _reorderChildren: function() { + var logicChildren = this.node.getChildren(); + for (var i = 0, n = logicChildren.length; i < n; i++) { + var child = logicChildren[i]; + var tmxLayer = child.getComponent('cc.TiledLayer'); + var zOrderValue = child.getSiblingIndex(); + if (tmxLayer) { + tmxLayer._sgNode.setLocalZOrder(zOrderValue); + } else { + if (child._sgNode) { + child._sgNode.setLocalZOrder(zOrderValue); + } + } + } + }, + + _applyFile: function () { + var sgNode = this._tiledMap; + var file = this._tmxFile; + var self = this; + if (file) { + self._isLoading = true; + this._preloadTmx(file, function (err, results) { + if (err) { + self._onMapLoaded(err); + } else { + sgNode.initWithTMXFile(file); + self._onMapLoaded(); + } + }); + } else { + // tmx file is cleared + // 1. hide the tmx layers in _tiledMap + var layers = self._tiledMap.allLayers(); + for (var i = 0, n = layers.length; i < n; i++) { + self._tiledMap.removeChild(layers); + } + + // 2. if the component is enabled, + // should remove the entities for tmx layers in node + if (self._enabled) { + self._removeLayerEntities(); + } + } + }, +}); + +cc.TiledMap = module.exports = TiledMap; diff --git a/cocos2d/tilemap/CCTiledMapAsset.js b/cocos2d/tilemap/CCTiledMapAsset.js new file mode 100644 index 0000000000..68964946d0 --- /dev/null +++ b/cocos2d/tilemap/CCTiledMapAsset.js @@ -0,0 +1,13 @@ +/** + * Class for tiled map asset handling. + * @class TiledMapAsset + * @extends RawAsset + * @constructor + */ +var TiledMapAsset = cc.Class({ + name: 'cc.TiledMapAsset', + extends: cc.RawAsset, +}); + +cc.TiledMapAsset = TiledMapAsset; +module.exports = TiledMapAsset; diff --git a/cocos2d/tilemap/editor/tiled-map.js b/cocos2d/tilemap/editor/tiled-map.js new file mode 100644 index 0000000000..0b89b88d4f --- /dev/null +++ b/cocos2d/tilemap/editor/tiled-map.js @@ -0,0 +1,13 @@ +'use strict'; + +class TiledMapMeta extends Editor.metas['raw-asset'] { + constructor ( assetdb ) { + super( assetdb ); + } + + static defaultType() { return 'tiled-map'; } +} + +TiledMapMeta.prototype.export = null; + +module.exports = TiledMapMeta; diff --git a/cocos2d/tilemap/editor/tiled-map.png b/cocos2d/tilemap/editor/tiled-map.png new file mode 100644 index 0000000000..27795f4765 Binary files /dev/null and b/cocos2d/tilemap/editor/tiled-map.png differ diff --git a/extends.js b/extends.js index 8c950df659..6f67057a33 100644 --- a/extends.js +++ b/extends.js @@ -30,4 +30,10 @@ if (!(CC_EDITOR && Editor.isCoreLevel)) { require('./cocos2d/particle/CCParticleSystem'); } +require('./cocos2d/tilemap/CCTiledMapAsset'); +if (!(CC_EDITOR && Editor.isCoreLevel)) { + require('./cocos2d/tilemap/CCTiledMap'); + require('./cocos2d/tilemap/CCTiledLayer'); +} + require('./extensions/spine'); diff --git a/extensions/ccpool/CCPool.js b/extensions/ccpool/CCPool.js index 464f3b7543..4941c07a8f 100644 --- a/extensions/ccpool/CCPool.js +++ b/extensions/ccpool/CCPool.js @@ -52,7 +52,7 @@ cc.pool = /** @lends cc.pool# */{ * Put the obj in pool. * @method putInPool * @param {Object} obj - The need put in pool object. - * @example {@link utils/api/cocos/docs/extensions/ccpool/putInPool.js} + * @example {@link utils/api/engine/docs/extensions/ccpool/putInPool.js} */ putInPool: function (obj) { var cid = cc.js._getClassId(obj.constructor); diff --git a/extensions/runtime/CCLoaderLayer.js b/extensions/runtime/CCLoaderLayer.js index 2093e134dd..4fb2ccdafe 100644 --- a/extensions/runtime/CCLoaderLayer.js +++ b/extensions/runtime/CCLoaderLayer.js @@ -214,7 +214,7 @@ cc.LoaderLayer = cc.Layer.extend({ } var self = this; //var progressFunction = self.config.progressCallback ? self.config.progressCallback : null; - cc.loader.load(res, function (result, count, loadedCount) { + cc.loader.load(res, function (loadedCount, count) { var checkGroupName = function (loadedCount) { for (var i = 0; i < groupIndex.length; i++) { if (groupIndex[i] >= loadedCount) { @@ -451,7 +451,7 @@ cc.LoaderLayer.preload = function (groupname, callback, target) { cc.Dialog._finalConfig.cancelBtn.normalRes, cc.Dialog._finalConfig.cancelBtn.pressRes ], - function (result, count, loadedCount) { + function (loadedCount, count, result) { var percent = (loadedCount / count * 100) | 0; percent = Math.min(percent, 100); cc.log("Preloading engine resources... " + percent + "%"); diff --git a/extensions/spine/SGSkeleton.js b/extensions/spine/SGSkeleton.js new file mode 100644 index 0000000000..5d2ca1a7b0 --- /dev/null +++ b/extensions/spine/SGSkeleton.js @@ -0,0 +1,331 @@ +/**************************************************************************** + Copyright (c) 2011-2012 cocos2d-x.org + Copyright (c) 2013-2014 Chukong Technologies Inc. + Copyright (c) 2014 Shengxiang Chen (Nero Chan) + Copyright (c) 2015-2016 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +var spine = sp.spine; + +sp._SGSkeleton = _ccsg.Node.extend({ + _skeleton: null, + _rootBone: null, + _timeScale: 1, + _debugSlots: false, + _debugBones: false, + _premultipliedAlpha: false, + _ownsSkeletonData: null, + _atlas: null, + _blendFunc: null, + + ctor: function(skeletonDataFile, atlasFile, scale) { + _ccsg.Node.prototype.ctor.call(this); + this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST}; + + if(arguments.length === 0) + this.init(); + else + this.initWithArgs(skeletonDataFile, atlasFile, scale); + }, + + _createRenderCmd: function () { + if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) + return new sp._SGSkeleton.CanvasRenderCmd(this); + else + return new sp._SGSkeleton.WebGLRenderCmd(this); + }, + + init: function () { + _ccsg.Node.prototype.init.call(this); + //this.setOpacityModifyRGB(true); + this._blendFunc.src = cc.ONE; + this._blendFunc.dst = cc.ONE_MINUS_SRC_ALPHA; + this.scheduleUpdate(); + }, + + /** + * Sets whether open debug slots. + * @param {boolean} enabled true to open, false to close. + */ + setDebugSlotsEnabled: function(enabled) { + this._debugSlots = enabled; + }, + + /** + * Gets whether open debug slots. + * @returns {boolean} true to open, false to close. + */ + getDebugSlotsEnabled: function() { + return this._debugSlots; + }, + + /** + * Sets whether open debug bones. + * @param {boolean} enabled + */ + setDebugBonesEnabled: function(enabled) { + this._debugBones = enabled; + }, + + /** + * Gets whether open debug bones. + * @returns {boolean} true to open, false to close. + */ + getDebugBonesEnabled: function() { + return this._debugBones; + }, + + /** + * Sets the time scale of sp._SGSkeleton. + * @param {Number} scale + */ + setTimeScale:function(scale){ + this._timeScale = scale; + }, + + getTimeScale: function(){ + return this._timeScale; + }, + + /** + * Initializes sp._SGSkeleton with Data. + * @param {spine.SkeletonData|String} skeletonDataFile + * @param {String|spine.Atlas|spine.SkeletonData} atlasFile atlas filename or atlas data or owns SkeletonData + * @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations. + */ + initWithArgs: function (skeletonDataFile, atlasFile, scale) { + var argSkeletonFile = skeletonDataFile, argAtlasFile = atlasFile, + skeletonData, atlas, ownsSkeletonData; + + if (cc.js.isString(argSkeletonFile)) { + if (cc.js.isString(argAtlasFile)) { + var data = cc.loader.getRes(argAtlasFile); + sp._atlasLoader.setAtlasFile(argAtlasFile); + atlas = new spine.Atlas(data, sp._atlasLoader); + } else { + atlas = atlasFile; + } + scale = scale || 1 / cc.director.getContentScaleFactor(); + + var attachmentLoader = new spine.AtlasAttachmentLoader(atlas); + var skeletonJsonReader = new spine.SkeletonJson(attachmentLoader); + skeletonJsonReader.scale = scale; + + var skeletonJson = cc.loader.getRes(argSkeletonFile); + skeletonData = skeletonJsonReader.readSkeletonData(skeletonJson); + atlas.dispose(skeletonJsonReader); + ownsSkeletonData = true; + } else { + skeletonData = skeletonDataFile; + ownsSkeletonData = atlasFile; + } + this.setSkeletonData(skeletonData, ownsSkeletonData); + this.init(); + }, + + /** + * Returns the bounding box of sp._SGSkeleton. + * @returns {cc.Rect} + */ + getBoundingBox: function () { + var minX = cc.FLT_MAX, minY = cc.FLT_MAX, maxX = cc.FLT_MIN, maxY = cc.FLT_MIN; + var scaleX = this.getScaleX(), scaleY = this.getScaleY(), vertices = [], + slots = this._skeleton.slots, VERTEX = sp.VERTEX_INDEX; + + for (var i = 0, slotCount = slots.length; i < slotCount; ++i) { + var slot = slots[i]; + var attachment = slot.attachment; + if (!attachment || attachment.type != sp.ATTACHMENT_TYPE.REGION) + continue; + this._computeRegionAttachmentWorldVertices(attachment, slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices); + minX = Math.min(minX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); + minY = Math.min(minY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY); + maxX = Math.max(maxX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); + maxY = Math.max(maxY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY); + } + var position = this.getPosition(); + return cc.rect(position.x + minX, position.y + minY, maxX - minX, maxY - minY); + }, + + _computeRegionAttachmentWorldVertices : function(self, x, y, bone, vertices){ + var offset = self.offset, vertexIndex = sp.VERTEX_INDEX; + x += bone.worldX; + y += bone.worldY; + vertices[vertexIndex.X1] = offset[vertexIndex.X1] * bone.m00 + offset[vertexIndex.Y1] * bone.m01 + x; + vertices[vertexIndex.Y1] = offset[vertexIndex.X1] * bone.m10 + offset[vertexIndex.Y1] * bone.m11 + y; + vertices[vertexIndex.X2] = offset[vertexIndex.X2] * bone.m00 + offset[vertexIndex.Y2] * bone.m01 + x; + vertices[vertexIndex.Y2] = offset[vertexIndex.X2] * bone.m10 + offset[vertexIndex.Y2] * bone.m11 + y; + vertices[vertexIndex.X3] = offset[vertexIndex.X3] * bone.m00 + offset[vertexIndex.Y3] * bone.m01 + x; + vertices[vertexIndex.Y3] = offset[vertexIndex.X3] * bone.m10 + offset[vertexIndex.Y3] * bone.m11 + y; + vertices[vertexIndex.X4] = offset[vertexIndex.X4] * bone.m00 + offset[vertexIndex.Y4] * bone.m01 + x; + vertices[vertexIndex.Y4] = offset[vertexIndex.X4] * bone.m10 + offset[vertexIndex.Y4] * bone.m11 + y; + }, + + /** + * Computes the world SRT from the local SRT for each bone. + */ + updateWorldTransform: function () { + this._skeleton.updateWorldTransform(); + }, + + /** + * Sets the bones and slots to the setup pose. + */ + setToSetupPose: function () { + this._skeleton.setToSetupPose(); + }, + + /** + * Sets the bones to the setup pose, using the values from the `BoneData` list in the `SkeletonData`. + */ + setBonesToSetupPose: function () { + this._skeleton.setBonesToSetupPose(); + }, + + /** + * Sets the slots to the setup pose, using the values from the `SlotData` list in the `SkeletonData`. + */ + setSlotsToSetupPose: function () { + this._skeleton.setSlotsToSetupPose(); + }, + + /** + * Finds a bone by name. This does a string comparison for every bone. + * @param {String} boneName + * @returns {spine.Bone} + */ + findBone: function (boneName) { + return this._skeleton.findBone(boneName); + }, + + /** + * Finds a slot by name. This does a string comparison for every slot. + * @param {String} slotName + * @returns {spine.Slot} + */ + findSlot: function (slotName) { + return this._skeleton.findSlot(slotName); + }, + + /** + * Finds a skin by name and makes it the active skin. This does a string comparison for every skin. Note that setting the skin does not change which attachments are visible. + * @param {string} skinName + * @returns {spine.Skin} + */ + setSkin: function (skinName) { + return this._skeleton.setSkinByName(skinName); + }, + + /** + * Returns the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. + * @param {String} slotName + * @param {String} attachmentName + * @returns {spine.RegionAttachment|spine.BoundingBoxAttachment} + */ + getAttachment: function (slotName, attachmentName) { + return this._skeleton.getAttachmentBySlotName(slotName, attachmentName); + }, + + /** + * Sets the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. + * @param {String} slotName + * @param {String} attachmentName + */ + setAttachment: function (slotName, attachmentName) { + this._skeleton.setAttachment(slotName, attachmentName); + }, + + /** + * Sets the premultiplied alpha value to sp._SGSkeleton. + * @param {Number} alpha + */ + setOpacityModifyRGB: function (alpha) { + this._premultipliedAlpha = alpha; + }, + + /** + * Returns whether to enable premultiplied alpha. + * @returns {boolean} + */ + isOpacityModifyRGB: function () { + return this._premultipliedAlpha; + }, + + /** + * Sets skeleton data to sp._SGSkeleton. + * @param {spine.SkeletonData} skeletonData + * @param {spine.SkeletonData} ownsSkeletonData + */ + setSkeletonData: function (skeletonData, ownsSkeletonData) { + if(skeletonData.width != null && skeletonData.height != null) + this.setContentSize(skeletonData.width / cc.director.getContentScaleFactor(), skeletonData.height / cc.director.getContentScaleFactor()); + + this._skeleton = new spine.Skeleton(skeletonData); + this._skeleton.updateWorldTransform(); + this._rootBone = this._skeleton.getRootBone(); + this._ownsSkeletonData = ownsSkeletonData; + + this._renderCmd._createChildFormSkeletonData(); + }, + + /** + * Return the renderer of attachment. + * @param {spine.RegionAttachment|spine.BoundingBoxAttachment} regionAttachment + * @returns {_ccsg.Node} + */ + getTextureAtlas: function (regionAttachment) { + return regionAttachment.rendererObject.page.rendererObject; + }, + + /** + * Returns the blendFunc of sp._SGSkeleton. + * @returns {BlendFunc} + */ + getBlendFunc: function () { + return this._blendFunc; + }, + + /** + * Sets the blendFunc of sp._SGSkeleton. + * @param {BlendFunc|Number} src + * @param {Number} [dst] + */ + setBlendFunc: function (src, dst) { + var locBlendFunc = this._blendFunc; + if (dst === undefined) { + locBlendFunc.src = src.src; + locBlendFunc.dst = src.dst; + } else { + locBlendFunc.src = src; + locBlendFunc.dst = dst; + } + }, + + /** + * Update will be called automatically every frame if "scheduleUpdate" is called when the node is "live". + * @param {Number} dt Delta time since last update + */ + update: function (dt) { + this._skeleton.update(dt); + } +}); diff --git a/extensions/spine/SkeletonAnimation.js b/extensions/spine/SGSkeletonAnimation.js similarity index 80% rename from extensions/spine/SkeletonAnimation.js rename to extensions/spine/SGSkeletonAnimation.js index edfc167f02..05c9388e32 100644 --- a/extensions/spine/SkeletonAnimation.js +++ b/extensions/spine/SGSkeletonAnimation.js @@ -25,11 +25,8 @@ THE SOFTWARE. ****************************************************************************/ -var spine = require('./spine-exported'); - -/** - * @module sp - */ +var spine = sp.spine; +var animEventType = sp.AnimationEventType; sp._atlasPage_createTexture_webGL = function (self, path) { var texture = cc.textureCache.addImage(path); @@ -62,17 +59,6 @@ sp._atlasLoader = { } }; -/** - * The event type of spine skeleton animation. It contains event types: START(0), END(1), COMPLETE(2), EVENT(3). - * @constant - * @type {{START: number, END: number, COMPLETE: number, EVENT: number}} - */ -sp.ANIMATION_EVENT_TYPE = { - START: 0, - END: 1, - COMPLETE: 2, - EVENT: 3 -}; sp.TrackEntryListeners = function(startListener, endListener, completeListener, eventListener){ this.startListener = startListener || null; @@ -93,15 +79,8 @@ sp.trackEntryCallback = function(state, trackIndex, type, event, loopCount) { state.rendererObject.onTrackEntryEvent(trackIndex, type, event, loopCount); }; -/** - * The skeleton animation of spine. It updates animation's state and skeleton's world transform. - * @class - * @extends sp.Skeleton - * @example - * var spineBoy = new sp.SkeletonAnimation('res/skeletons/spineboy.json', 'res/skeletons/spineboy.atlas'); - * this.addChild(spineBoy, 4); - */ -sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ + +sp._SGSkeletonAnimation = sp._SGSkeleton.extend({ _state: null, _target: null, _callback: null, @@ -113,17 +92,17 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ _eventListener: null, /** - * Initializes a sp.SkeletonAnimation. please do not call this function by yourself, you should pass the parameters to constructor to initialize it. + * Initializes a sp._SGSkeletonAnimation. please do not call this function by yourself, you should pass the parameters to constructor to initialize it. * @override */ init: function () { - sp.Skeleton.prototype.init.call(this); + sp._SGSkeleton.prototype.init.call(this); this._ownsAnimationStateData = true; this.setAnimationStateData(new spine.AnimationStateData(this._skeleton.data)); }, /** - * Sets animation state data to sp.SkeletonAnimation. + * Sets animation state data to sp._SGSkeletonAnimation. * @param {spine.AnimationStateData} stateData */ setAnimationStateData: function (stateData) { @@ -147,7 +126,7 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ }, /** - * Sets event listener of sp.SkeletonAnimation. + * Sets event listener of sp._SGSkeletonAnimation. * @param {Object} target * @param {Function} callback */ @@ -275,19 +254,19 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ return; var listeners = entry.rendererObject; switch (type){ - case sp.ANIMATION_EVENT_TYPE.START: + case animEventType.START: if(listeners.startListener) listeners.startListener(traceIndex); break; - case sp.ANIMATION_EVENT_TYPE.END: + case animEventType.END: if(listeners.endListener) listeners.endListener(traceIndex); break; - case sp.ANIMATION_EVENT_TYPE.COMPLETE: + case animEventType.COMPLETE: if(listeners.completeListener) listeners.completeListener(traceIndex, loopCount); break; - case sp.ANIMATION_EVENT_TYPE.EVENT: + case animEventType.EVENT: if(listeners.eventListener) listeners.eventListener(traceIndex, event); break; @@ -296,19 +275,19 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ onAnimationStateEvent: function(trackIndex, type, event, loopCount) { switch(type){ - case sp.ANIMATION_EVENT_TYPE.START: + case animEventType.START: if(this._startListener) this._startListener(trackIndex); break; - case sp.ANIMATION_EVENT_TYPE.END: + case animEventType.END: if(this._endListener) this._endListener(trackIndex); break; - case sp.ANIMATION_EVENT_TYPE.COMPLETE: + case animEventType.COMPLETE: if(this._completeListener) this._completeListener(trackIndex, loopCount); break; - case sp.ANIMATION_EVENT_TYPE.EVENT: + case animEventType.EVENT: if(this._eventListener) this._eventListener(trackIndex, event); break; @@ -320,16 +299,16 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ }, _onAnimationStateStart: function (trackIndex) { - this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.START, null, 0); + this._animationStateCallback(trackIndex, animEventType.START, null, 0); }, _onAnimationStateEnd: function (trackIndex) { - this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.END, null, 0); + this._animationStateCallback(trackIndex, animEventType.END, null, 0); }, _onAnimationStateComplete: function (trackIndex, count) { - this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.COMPLETE, null, count); + this._animationStateCallback(trackIndex, animEventType.COMPLETE, null, count); }, _onAnimationStateEvent: function (trackIndex, event) { - this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.EVENT, event, 0); + this._animationStateCallback(trackIndex, animEventType.EVENT, event, 0); }, _animationStateCallback: function (trackIndex, type, event, loopCount) { this.onAnimationStateEvent(trackIndex, type, event, loopCount); @@ -338,15 +317,3 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{ } } }); - -/** - * Creates a skeleton animation object. - * @deprecated since v3.0, please use new sp.SkeletonAnimation(skeletonDataFile, atlasFile, scale) instead. - * @param {spine.SkeletonData|String} skeletonDataFile - * @param {String|spine.Atlas|spine.SkeletonData} atlasFile atlas filename or atlas data or owns SkeletonData - * @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations. - * @returns {sp.Skeleton} - */ -sp.SkeletonAnimation.create = function (skeletonDataFile, atlasFile/* or atlas*/, scale) { - return new sp.SkeletonAnimation(skeletonDataFile, atlasFile, scale); -}; diff --git a/extensions/spine/SkeletonCanvasRenderCmd.js b/extensions/spine/SGSkeletonCanvasRenderCmd.js similarity index 96% rename from extensions/spine/SkeletonCanvasRenderCmd.js rename to extensions/spine/SGSkeletonCanvasRenderCmd.js index 5f33707590..c0914c65fa 100644 --- a/extensions/spine/SkeletonCanvasRenderCmd.js +++ b/extensions/spine/SGSkeletonCanvasRenderCmd.js @@ -22,19 +22,15 @@ THE SOFTWARE. ****************************************************************************/ -var spine = require('./spine-exported'); +var spine = sp.spine; -/** - * @module sp - */ - -sp.Skeleton.CanvasRenderCmd = function(renderableObject){ +sp._SGSkeleton.CanvasRenderCmd = function(renderableObject){ _ccsg.Node.CanvasRenderCmd.call(this, renderableObject); this._needDraw = true; }; -var proto = sp.Skeleton.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); -proto.constructor = sp.Skeleton.CanvasRenderCmd; +var proto = sp._SGSkeleton.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype); +proto.constructor = sp._SGSkeleton.CanvasRenderCmd; proto.rendering = function (wrapper, scaleX, scaleY) { var node = this._node, i, n, slot, slotNode; diff --git a/extensions/spine/SkeletonWebGLRenderCmd.js b/extensions/spine/SGSkeletonWebGLRenderCmd.js similarity index 97% rename from extensions/spine/SkeletonWebGLRenderCmd.js rename to extensions/spine/SGSkeletonWebGLRenderCmd.js index 78a9363775..11355a9b92 100644 --- a/extensions/spine/SkeletonWebGLRenderCmd.js +++ b/extensions/spine/SGSkeletonWebGLRenderCmd.js @@ -22,21 +22,18 @@ THE SOFTWARE. ****************************************************************************/ -var spine = require('./spine-exported'); +var spine = sp.spine; -/** - * @module sp - */ -sp.Skeleton.WebGLRenderCmd = function (renderableObject) { +sp._SGSkeleton.WebGLRenderCmd = function (renderableObject) { _ccsg.Node.WebGLRenderCmd.call(this, renderableObject); this._needDraw = true; this.setShaderProgram(cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR)); this._tmpQuad = new cc.V3F_C4B_T2F_Quad(); }; -var proto = sp.Skeleton.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); -proto.constructor = sp.Skeleton.WebGLRenderCmd; +var proto = sp._SGSkeleton.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype); +proto.constructor = sp._SGSkeleton.WebGLRenderCmd; proto.rendering = function (ctx) { var node = this._node, tmpQuad = this._tmpQuad; diff --git a/extensions/spine/Skeleton.js b/extensions/spine/Skeleton.js index 8cadc1f618..911b109b38 100644 --- a/extensions/spine/Skeleton.js +++ b/extensions/spine/Skeleton.js @@ -1,8 +1,5 @@ /**************************************************************************** - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2014 Chukong Technologies Inc. - Copyright (c) 2014 Shengxiang Chen (Nero Chan) - Copyright (c) 2015-2016 Chukong Technologies Inc. + Copyright (c) 2016 Chukong Technologies Inc. http://www.cocos2d-x.org @@ -25,383 +22,708 @@ THE SOFTWARE. ****************************************************************************/ -var spine = require('./spine-exported'); - /** * @module sp */ -/** - * The vertex index of spine. - * @constant - * @type {{X1: number, Y1: number, X2: number, Y2: number, X3: number, Y3: number, X4: number, Y4: number}} - */ -sp.VERTEX_INDEX = { - X1: 0, - Y1: 1, - X2: 2, - Y2: 3, - X3: 4, - Y3: 5, - X4: 6, - Y4: 7 -}; +var DefaultSkinsEnum = cc.Enum({ 'default': -1 }); +var DefaultAnimsEnum = cc.Enum({ '': 0 }); + +function setEnumAttr (obj, propName, enumDef) { + cc.Class.attr(obj, propName, { + type: 'Enum', + enumList: cc.Enum.getList(enumDef) + }); +} /** - * The attachment type of spine. It contains three type: REGION(0), BOUNDING_BOX(1), MESH(2) and SKINNED_MESH. - * @constant - * @type {{REGION: number, BOUNDING_BOX: number, REGION_SEQUENCE: number, MESH: number}} + * The skeleton of Spine
+ *
+ * (Skeleton has a reference to a SkeletonData and stores the state for skeleton instance, + * which consists of the current pose's bone SRT, slot colors, and which slot attachments are visible.
+ * Multiple skeletons can use the same SkeletonData which includes all animations, skins, and attachments.)
+ * + * @class Skeleton + * @extends cc._RendererUnderSG + * @constructor */ -sp.ATTACHMENT_TYPE = { - REGION: 0, - BOUNDING_BOX: 1, - MESH: 2, - SKINNED_MESH:3 -}; -/** - *

- * The skeleton of Spine.
- * Skeleton has a reference to a SkeletonData and stores the state for skeleton instance, - * which consists of the current pose's bone SRT, slot colors, and which slot attachments are visible.
- * Multiple skeletons can use the same SkeletonData (which includes all animations, skins, and attachments).
- *

- * @class - * @extends _ccsg.Node - */ -sp.Skeleton = _ccsg.Node.extend(/** @lends sp.Skeleton# */{ - _skeleton: null, - _rootBone: null, - _timeScale: 1, - _debugSlots: false, - _debugBones: false, - _premultipliedAlpha: false, - _ownsSkeletonData: null, - _atlas: null, - _blendFunc: null, +// 由于 Spine 的 _sgNode 需要参数才能初始化, 所以这里的 _sgNode 不在构造函数中赋值, 每次访问前都要先判断一次是否初始化了 - /** - * The constructor of sp.Skeleton. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. - */ - ctor:function(skeletonDataFile, atlasFile, scale){ - _ccsg.Node.prototype.ctor.call(this); - this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST}; - - if(arguments.length === 0) - this.init(); - else - this.initWithArgs(skeletonDataFile, atlasFile, scale); +sp.Skeleton = cc.Class({ + name: 'sp.Skeleton', + extends: cc._RendererUnderSG, + editor: CC_EDITOR && { + menu: 'i18n:MAIN_MENU.component.others/Spine Skeleton', + //playOnFocus: true }, - _createRenderCmd:function () { - if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) - return new sp.Skeleton.CanvasRenderCmd(this); - else - return new sp.Skeleton.WebGLRenderCmd(this); - }, + properties: { - /** - * Initializes a sp.Skeleton. please do not call this function by yourself, you should pass the parameters to constructor to initialize it. - */ - init: function () { - _ccsg.Node.prototype.init.call(this); - //this.setOpacityModifyRGB(true); - this._blendFunc.src = cc.ONE; - this._blendFunc.dst = cc.ONE_MINUS_SRC_ALPHA; - this.scheduleUpdate(); - }, + /** + * The skeleton data contains the skeleton information (bind pose bones, slots, draw order, + * attachments, skins, etc) and animations but does not hold any state. + * Multiple skeletons can share the same skeleton data. + * @property {SkeletonData} skeletonData + */ + skeletonData: { + default: null, + type: sp.SkeletonData, + notify: function () { + this.defaultSkin = ''; + this.defaultAnimation = ''; + this._refresh(); + }, + }, - /** - * Sets whether open debug slots. - * @param {boolean} enable true to open, false to close. - */ - setDebugSolots:function(enable){ - this._debugSlots = enable; - }, + ///** + // * The url of atlas file. + // * @property {string} file + // */ + //atlasFile: { + // default: '', + // url: cc.TextAsset, + // notify: function () { + // this.defaultSkin = ''; + // this.defaultAnimation = ''; + // this._applyAsset(); + // }, + //}, - /** - * Sets whether open debug bones. - * @param {boolean} enable - */ - setDebugBones:function(enable){ - this._debugBones = enable; - }, + // 由于 spine 的 skin 是无法二次替换的,所以只能设置默认的 skin + /** + * The name of default skin. + * @property {string} defaultSkin + */ + defaultSkin: { + default: '', + visible: false + }, - /** - * Sets whether open debug slots. - * @param {boolean} enabled true to open, false to close. - */ - setDebugSlotsEnabled: function(enabled) { - this._debugSlots = enabled; - }, + /** + * The name of default animation. + * @property {string} defaultAnimation + */ + defaultAnimation: { + default: '', + visible: false + }, - /** - * Gets whether open debug slots. - * @returns {boolean} true to open, false to close. - */ - getDebugSlotsEnabled: function() { - return this._debugSlots; - }, + /** + * The name of current playing animation. + * @property {string} animation + */ + animation: { + get: function () { + var entry = this.getCurrent(0); + return (entry && entry.animation.name) || ""; + }, + set: function (value) { + this.defaultAnimation = value; + if (value) { + this.setAnimation(0, value, this.loop); + } + else { + this.clearTrack(0); + this.setToSetupPose(); + } + }, + visible: false + }, - /** - * Sets whether open debug bones. - * @param {boolean} enabled - */ - setDebugBonesEnabled: function(enabled) { - this._debugBones = enabled; - }, + /** + * @property {number} _defaultSkinIndex + */ + _defaultSkinIndex: { + get: function () { + if (this.skeletonData && this.defaultSkin) { + var skinsEnum = this.skeletonData.getSkinsEnum(); + if (skinsEnum) { + var skinIndex = skinsEnum[this.defaultSkin]; + if (skinIndex !== undefined) { + return skinIndex; + } + } + } + return 0; + }, + set: function (value) { + var skinsEnum; + if (this.skeletonData) { + skinsEnum = this.skeletonData.getSkinsEnum(); + } + if ( !skinsEnum ) { + return cc.error('Failed to set _defaultSkinIndex for "%s" because its skeletonData is invalid.', + this.name); + } + var skinName = skinsEnum[value]; + if (skinName !== undefined) { + this.defaultSkin = skinName; + if (CC_EDITOR && !cc.engine.isPlaying) { + this._refresh(); + } + } + else { + cc.error('Failed to set _defaultSkinIndex for "%s" because the index is out of range.', this.name); + } + }, + type: DefaultSkinsEnum, + visible: true, + displayName: "Default Skin" + }, - /** - * Gets whether open debug bones. - * @returns {boolean} true to open, false to close. - */ - getDebugBonesEnabled: function() { - return this._debugBones; - }, + // value of 0 represents no animation + _animationIndex: { + get: function () { + var animationName = (!CC_EDITOR || cc.engine.isPlaying) ? this.animation : this.defaultAnimation; + if (this.skeletonData && animationName) { + var animsEnum = this.skeletonData.getAnimsEnum(); + if (animsEnum) { + var animIndex = animsEnum[animationName]; + if (animIndex !== undefined) { + return animIndex; + } + } + } + return 0; + }, + set: function (value) { + if (value === 0) { + this.animation = ''; + return; + } + var animsEnum; + if (this.skeletonData) { + animsEnum = this.skeletonData.getAnimsEnum(); + } + if ( !animsEnum ) { + return cc.error('Failed to set _animationIndex for "%s" because its skeletonData is invalid.', this.name); + } + var animName = animsEnum[value]; + if (animName !== undefined) { + this.animation = animName; + } + else { + cc.error('Failed to set _animationIndex for "%s" because the index is out of range.', this.name); + } - /** - * Sets the time scale of sp.Skeleton. - * @param {Number} scale - */ - setTimeScale:function(scale){ - this._timeScale = scale; - }, + }, + type: DefaultAnimsEnum, + visible: true, + displayName: 'Animation' + }, - getTimeScale: function(){ - return this._timeScale; - }, + //// for inspector + //_animationList: { + // default: [], + // type: cc.String, + // serializable: false + //}, + // + //// for inspector + //_skinList: { + // default: [], + // type: cc.String, + // serializable: false + //}, - /** - * Initializes sp.Skeleton with Data. - * @param {spine.SkeletonData|String} skeletonDataFile - * @param {String|spine.Atlas|spine.SkeletonData} atlasFile atlas filename or atlas data or owns SkeletonData - * @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations. - */ - initWithArgs: function (skeletonDataFile, atlasFile, scale) { - var argSkeletonFile = skeletonDataFile, argAtlasFile = atlasFile, - skeletonData, atlas, ownsSkeletonData; + /** + * @property {boolean} loop + * @default true + */ + loop: true, - if (cc.js.isString(argSkeletonFile)) { - if (cc.js.isString(argAtlasFile)) { - var data = cc.loader.getRes(argAtlasFile); - sp._atlasLoader.setAtlasFile(argAtlasFile); - atlas = new spine.Atlas(data, sp._atlasLoader); - } else { - atlas = atlasFile; + /** + * The time scale of this skeleton. + * @property {number} timeScale + * @default 1 + */ + timeScale: { + default: 1, + notify: function () { + if (this._sgNode) { + this._sgNode.setTimeScale(this.timeScale); + } } - scale = scale || 1 / cc.director.getContentScaleFactor(); + }, - var attachmentLoader = new spine.AtlasAttachmentLoader(atlas); - var skeletonJsonReader = new spine.SkeletonJson(attachmentLoader); - skeletonJsonReader.scale = scale; + /** + * Indicates whether open debug slots. + * @property {boolean} debugSlots + * @default false + */ + debugSlots: { + default: false, + notify: function () { + if (this._sgNode) { + this._sgNode.setDebugSlotsEnabled(this.debugSlots); + } + }, + editorOnly: true, + }, - var skeletonJson = cc.loader.getRes(argSkeletonFile); - skeletonData = skeletonJsonReader.readSkeletonData(skeletonJson); - atlas.dispose(skeletonJsonReader); - ownsSkeletonData = true; - } else { - skeletonData = skeletonDataFile; - ownsSkeletonData = atlasFile; + /** + * Indicates whether open debug bones. + * @property {boolean} debugBones + * @default false + */ + debugBones: { + default: false, + notify: function () { + if (this._sgNode) { + this._sgNode.setDebugBonesEnabled(this.debugBones); + } + }, + editorOnly: true, } - this.setSkeletonData(skeletonData, ownsSkeletonData); - this.init(); }, - /** - * Returns the bounding box of sp.Skeleton. - * @returns {cc.Rect} - */ - getBoundingBox: function () { - var minX = cc.FLT_MAX, minY = cc.FLT_MAX, maxX = cc.FLT_MIN, maxY = cc.FLT_MIN; - var scaleX = this.getScaleX(), scaleY = this.getScaleY(), vertices = [], - slots = this._skeleton.slots, VERTEX = sp.VERTEX_INDEX; + // IMPLEMENT - for (var i = 0, slotCount = slots.length; i < slotCount; ++i) { - var slot = slots[i]; - if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION) - continue; - var attachment = slot.attachment; - this._computeRegionAttachmentWorldVertices(attachment, slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices); - minX = Math.min(minX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); - minY = Math.min(minY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY); - maxX = Math.max(maxX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX); - maxY = Math.max(maxY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY); + onLoad: function () { + var Flags = cc.Object.Flags; + this._objFlags |= (Flags.IsAnchorLocked | Flags.IsSizeLocked); + this._refresh(); + }, + + //onEnable: function () { + // this._super(); + //}, + + _createSgNode: function () { + if (this.skeletonData/* && self.atlasFile*/) { + var data = this.skeletonData.getRuntimeData(); + if (data) { + return new sp._SGSkeletonAnimation(data, null, this.skeletonData.scale); + } } - var position = this.getPosition(); - return cc.rect(position.x + minX, position.y + minY, maxX - minX, maxY - minY); + return null; }, - _computeRegionAttachmentWorldVertices : function(self, x, y, bone, vertices){ - var offset = self.offset, vertexIndex = sp.VERTEX_INDEX; - x += bone.worldX; - y += bone.worldY; - vertices[vertexIndex.X1] = offset[vertexIndex.X1] * bone.m00 + offset[vertexIndex.Y1] * bone.m01 + x; - vertices[vertexIndex.Y1] = offset[vertexIndex.X1] * bone.m10 + offset[vertexIndex.Y1] * bone.m11 + y; - vertices[vertexIndex.X2] = offset[vertexIndex.X2] * bone.m00 + offset[vertexIndex.Y2] * bone.m01 + x; - vertices[vertexIndex.Y2] = offset[vertexIndex.X2] * bone.m10 + offset[vertexIndex.Y2] * bone.m11 + y; - vertices[vertexIndex.X3] = offset[vertexIndex.X3] * bone.m00 + offset[vertexIndex.Y3] * bone.m01 + x; - vertices[vertexIndex.Y3] = offset[vertexIndex.X3] * bone.m10 + offset[vertexIndex.Y3] * bone.m11 + y; - vertices[vertexIndex.X4] = offset[vertexIndex.X4] * bone.m00 + offset[vertexIndex.Y4] * bone.m01 + x; - vertices[vertexIndex.Y4] = offset[vertexIndex.X4] * bone.m10 + offset[vertexIndex.Y4] * bone.m11 + y; + _initSgNode: function () { + var sgNode = this._sgNode; + sgNode.setTimeScale(this.timeScale); + //if (!CC_EDITOR) { + // function animationCallback (ccObj, trackIndex, type, event, loopCount) { + // var eventType = AnimEvents[type];3 + // var detail = { + // trackIndex: trackIndex + // }; + // if (type === sp.ANIMATION_EVENT_TYPE.COMPLETE) { + // detail.loopCount = loopCount; + // } + // else if (type === sp.ANIMATION_EVENT_TYPE.EVENT) { + // detail.event = event; + // } + // //Fire.log("[animationCallback] eventType: %s, time: '%s'", eventType, Fire.Time.time); + // self.entity.emit(eventType, detail); + // } + // sgNode.setAnimationListener(target, animationCallback); + //} + if (this.defaultSkin) { + try { + sgNode.setSkin(this.defaultSkin); + } + catch (e) { + cc._throw(e); + } + } + this.animation = this.defaultAnimation; + if (CC_EDITOR) { + sgNode.setDebugSlotsEnabled(this.debugSlots); + sgNode.setDebugBonesEnabled(this.debugBones); + } }, - /** - * Computes the world SRT from the local SRT for each bone. - */ - updateWorldTransform: function () { - this._skeleton.updateWorldTransform(); + _getLocalBounds: CC_EDITOR && function (out_rect) { + if (this._sgNode) { + var rect = this._sgNode.getBoundingBox(); + out_rect.x = rect.x; + out_rect.y = rect.y; + out_rect.width = rect.width; + out_rect.height = rect.height; + } + else { + out_rect.x = 0; + out_rect.y = 0; + out_rect.width = 0; + out_rect.height = 0; + } }, + // RENDERER + /** * Sets the bones and slots to the setup pose. + * @method setToSetupPose */ setToSetupPose: function () { - this._skeleton.setToSetupPose(); + if (this._sgNode) { + this._sgNode.setToSetupPose(); + } }, /** * Sets the bones to the setup pose, using the values from the `BoneData` list in the `SkeletonData`. + * @method setBonesToSetupPose */ setBonesToSetupPose: function () { - this._skeleton.setBonesToSetupPose(); - }, - - /** - * Sets the slots to the setup pose, using the values from the `SlotData` list in the `SkeletonData`. - */ - setSlotsToSetupPose: function () { - this._skeleton.setSlotsToSetupPose(); - }, - - /** - * Finds a bone by name. This does a string comparison for every bone. - * @param {String} boneName - * @returns {spine.Bone} - */ - findBone: function (boneName) { - return this._skeleton.findBone(boneName); - }, - - /** - * Finds a slot by name. This does a string comparison for every slot. - * @param {String} slotName - * @returns {spine.Slot} - */ - findSlot: function (slotName) { - return this._skeleton.findSlot(slotName); - }, - - /** - * Finds a skin by name and makes it the active skin. This does a string comparison for every skin. Note that setting the skin does not change which attachments are visible. - * @param {string} skinName - * @returns {spine.Skin} - */ - setSkin: function (skinName) { - return this._skeleton.setSkinByName(skinName); - }, - - /** - * Returns the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. - * @param {String} slotName - * @param {String} attachmentName - * @returns {spine.RegionAttachment|spine.BoundingBoxAttachment} - */ - getAttachment: function (slotName, attachmentName) { - return this._skeleton.getAttachmentBySlotName(slotName, attachmentName); - }, - - /** - * Sets the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. - * @param {String} slotName - * @param {String} attachmentName - */ - setAttachment: function (slotName, attachmentName) { - this._skeleton.setAttachment(slotName, attachmentName); - }, - - /** - * Sets the premultiplied alpha value to sp.Skeleton. - * @param {Number} alpha - */ - setOpacityModifyRGB: function (alpha) { - this._premultipliedAlpha = alpha; - }, - - /** - * Returns whether to enable premultiplied alpha. - * @returns {boolean} - */ - isOpacityModifyRGB: function () { - return this._premultipliedAlpha; - }, - - /** - * Sets skeleton data to sp.Skeleton. - * @param {spine.SkeletonData} skeletonData - * @param {spine.SkeletonData} ownsSkeletonData - */ - setSkeletonData: function (skeletonData, ownsSkeletonData) { - if(skeletonData.width != null && skeletonData.height != null) - this.setContentSize(skeletonData.width / cc.director.getContentScaleFactor(), skeletonData.height / cc.director.getContentScaleFactor()); - - this._skeleton = new spine.Skeleton(skeletonData); - this._skeleton.updateWorldTransform(); - this._rootBone = this._skeleton.getRootBone(); - this._ownsSkeletonData = ownsSkeletonData; - - this._renderCmd._createChildFormSkeletonData(); - }, - - /** - * Return the renderer of attachment. - * @param {spine.RegionAttachment|spine.BoundingBoxAttachment} regionAttachment - * @returns {_ccsg.Node} - */ - getTextureAtlas: function (regionAttachment) { - return regionAttachment.rendererObject.page.rendererObject; - }, - - /** - * Returns the blendFunc of sp.Skeleton. - * @returns {cc.BlendFunc} - */ - getBlendFunc: function () { - return this._blendFunc; - }, - - /** - * Sets the blendFunc of sp.Skeleton. - * @param {cc.BlendFunc|Number} src - * @param {Number} [dst] - */ - setBlendFunc: function (src, dst) { - var locBlendFunc = this._blendFunc; - if (dst === undefined) { - locBlendFunc.src = src.src; - locBlendFunc.dst = src.dst; - } else { - locBlendFunc.src = src; - locBlendFunc.dst = dst; + if (this._sgNode) { + this._sgNode.setBonesToSetupPose(); } }, /** - * Update will be called automatically every frame if "scheduleUpdate" is called when the node is "live". - * @param {Number} dt Delta time since last update + * Sets the slots to the setup pose, using the values from the `SlotData` list in the `SkeletonData`. + * @method setSlotsToSetupPose */ - update: function (dt) { - this._skeleton.update(dt); + setSlotsToSetupPose: function () { + if (this._sgNode) { + this._sgNode.setSlotsToSetupPose(); + } + }, + + /** + * Finds a bone by name. This does a string comparison for every bone. + * @method findBone + * @param {string} boneName + * @return {spine.Bone} + */ + findBone: function (boneName) { + if (this._sgNode) { + return this._sgNode.findBone(boneName); + } + return null; + }, + + /** + * Finds a slot by name. This does a string comparison for every slot. + * @method findSlot + * @param {string} slotName + * @return {spine.Slot} + */ + findSlot: function (slotName) { + if (this._sgNode) { + return this._sgNode.findSlot(slotName); + } + return null; + }, + + /** + * Finds a skin by name and makes it the active skin. This does a string comparison for every skin. Note that setting the skin does not change which attachments are visible. + * @method setSkin + * @param {string} skinName + * @return {spine.Skin} + */ + setSkin: function (skinName) { + if (this._sgNode) { + return this._sgNode.setSkin(skinName); + } + return null; + }, + + /** + * Returns the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. + * @method getAttachment + * @param {string} slotName + * @param {string} attachmentName + * @return {spine.RegionAttachment|sp.spine.BoundingBoxAttachment} + */ + getAttachment: function (slotName, attachmentName) { + if (this._sgNode) { + return this._sgNode.getAttachment(slotName, attachmentName); + } + return null; + }, + + /** + * Sets the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin. + * @method setAttachment + * @param {string} slotName + * @param {string} attachmentName + */ + setAttachment: function (slotName, attachmentName) { + if (this._sgNode) { + this._sgNode.setAttachment(slotName, attachmentName); + } + }, + + /** + * Sets skeleton data to sp.Skeleton. + * @method setSkeletonData + * @param {spine.SkeletonData} skeletonData + * @param {spine.SkeletonData} ownsSkeletonData + */ + setSkeletonData: function (skeletonData, ownsSkeletonData) { + if (this._sgNode) { + this._sgNode.setSkeletonData(skeletonData, ownsSkeletonData); + } + }, + + ///** + // * Return the renderer of attachment. + // * @method getTextureAtlas + // * @param {spine.RegionAttachment|sp.spine.BoundingBoxAttachment} regionAttachment + // * @return {_ccsg.Node} + // */ + //getTextureAtlas: function (regionAttachment) { + // if (this._sgNode) { + // this._sgNode.getTextureAtlas(regionAttachment); + // } + //}, + + // ANIMATION + + /** + * Sets animation state data. + * @method setAnimationStateData + * @param {spine.AnimationStateData} stateData + */ + setAnimationStateData: function (stateData) { + if (this._sgNode) { + return this._sgNode.setAnimationStateData(stateData); + } + }, + + /** + * Mix applies all keyframe values, interpolated for the specified time and mixed with the current values. + * @method setMix + * @param {string} fromAnimation + * @param {string} toAnimation + * @param {number} duration + */ + setMix: function (fromAnimation, toAnimation, duration) { + if (this._sgNode) { + this._sgNode.setMix(fromAnimation, toAnimation, duration); + } + }, + + /** + * Sets event listener. + * @method setAnimationListener + * @param {object} target + * @param {function} callback + */ + setAnimationListener: function (target, callback) { + if (this._sgNode) { + this._sgNode.setAnimationListener(target, callback); + } + }, + + /** + * Set the current animation. Any queued animations are cleared. + * @method setAnimation + * @param {number} trackIndex + * @param {string} name + * @param {boolean} loop + * @return {spine.TrackEntry} + */ + setAnimation: function (trackIndex, name, loop) { + if (this._sgNode) { + var res = this._sgNode.setAnimation(trackIndex, name, loop); + if (CC_EDITOR && !cc.engine.isPlaying) { + this._sample(); + this.clearTrack(trackIndex); + } + return res; + } + return null; + }, + + _sample: function () { + if (this._sgNode) { + this._sgNode.update(0); + } + }, + + /** + * Adds an animation to be played delay seconds after the current or last queued animation. + * @method addAnimation + * @param {number} trackIndex + * @param {string} name + * @param {boolean} loop + * @param {number} [delay=0] + * @return {spine.TrackEntry} + */ + addAnimation: function (trackIndex, name, loop, delay) { + if (this._sgNode) { + return this._sgNode.addAnimation(trackIndex, name, loop, delay); + } + return null; + }, + + /** + * Returns track entry by trackIndex. + * @method getCurrent + * @param trackIndex + * @return {spine.TrackEntry} + */ + getCurrent: function (trackIndex) { + if (this._sgNode) { + return this._sgNode.getCurrent(trackIndex); + } + return null; + }, + + /** + * Clears all tracks of animation state. + * @method clearTracks + */ + clearTracks: function () { + if (this._sgNode) { + this._sgNode.clearTracks(); + } + }, + + /** + * Clears track of animation state by trackIndex. + * @method clearTrack + * @param {number} trackIndex + */ + clearTrack: function (trackIndex) { + if (this._sgNode) { + this._sgNode.clearTrack(trackIndex); + if (CC_EDITOR && !cc.engine.isPlaying) { + this._sample(); + } + } + }, + + // update animation list for editor + _updateAnimEnum: CC_EDITOR && function () { + var animEnum; + if (this.skeletonData) { + animEnum = this.skeletonData.getAnimsEnum(); + } + // change enum + setEnumAttr(this, '_animationIndex', animEnum || DefaultAnimsEnum); + }, + // update skin list for editor + _updateSkinEnum: CC_EDITOR && function () { + var skinEnum; + if (this.skeletonData) { + skinEnum = this.skeletonData.getSkinsEnum(); + } + // change enum + setEnumAttr(this, '_defaultSkinIndex', skinEnum || DefaultSkinsEnum); + }, + // force refresh inspector + _refreshInspector: CC_EDITOR && function () { + var ga = Editor.Selection.curGlobalActivate(); + var inspecting = (ga && ga.id === this.node.uuid && ga.type === 'node'); + if (inspecting) { + Editor.Selection.unselect('node', this.node.uuid); + ga = Editor.Selection.curGlobalActivate(); + var id = this.node.uuid; + var inspectOther = (ga && ga.type === 'node' && ga.id); + if (inspectOther) { + setTimeout(function () { + Editor.Selection.select('node', id, false); + }, 200); + } + else { + Editor.Selection.select('node', id, false); + } + } + }, + + /** + * Set the start event listener. + * @method setStartListener + * @param {function} listener + */ + setStartListener: function (listener) { + if (this._sgNode) { + this._sgNode.setStartListener(listener); + } + }, + + /** + * Set the end event listener. + * @method setEndListener + * @param {function} listener + */ + setEndListener: function (listener) { + if (this._sgNode) { + this._sgNode.setEndListener(listener); + } + }, + + setCompleteListener: function (listener) { + if (this._sgNode) { + this._sgNode.setCompleteListener(listener); + } + }, + + setEventListener: function (listener) { + if (this._sgNode) { + this._sgNode.setEventListener(listener); + } + }, + + setTrackStartListener: function (entry, listener) { + if (this._sgNode) { + this._sgNode.setTrackStartListener(entry, listener); + } + }, + + setTrackEndListener: function (entry, listener) { + if (this._sgNode) { + this._sgNode.setTrackEndListener(entry, listener); + } + }, + + setTrackCompleteListener: function (entry, listener) { + if (this._sgNode) { + this._sgNode.setTrackCompleteListener(entry, listener); + } + }, + + setTrackEventListener: function (entry, listener) { + if (this._sgNode) { + this._sgNode.setTrackEventListener(entry, listener); + } + }, + + // + + getState: function () { + if (this._sgNode) { + return this._sgNode.getState(); + } + }, + + _refresh: function () { + var self = this; + + // discard exists sgNode + if (self._sgNode) { + if ( self.node._sizeProvider === self._sgNode ) { + self.node._sizeProvider = null; + } + self._removeSgNode(); + self._sgNode = null; + } + + // recreate sgNode... + var sgNode = self._sgNode = self._createSgNode(); + if (sgNode) { + sgNode.retain(); + self._initSgNode(); + self._appendSgNode(sgNode); + if ( !self.node._sizeProvider ) { + self.node._sizeProvider = sgNode; + } + } + + // sgNode 的尺寸不是很可靠 同时 Node 的框框也没办法和渲染匹配 只好先强制尺寸为零 + self.node.setContentSize(0, 0); + + if (CC_EDITOR) { + // update inspector + self._updateAnimEnum(); + self._updateSkinEnum(); + self._refreshInspector(); + } } }); - -/** - * Creates a skeleton object. - * @deprecated since v3.0, please use new sp.Skeleton(skeletonDataFile, atlasFile, scale) instead. - * @param {spine.SkeletonData|String} skeletonDataFile - * @param {String|spine.Atlas|spine.SkeletonData} atlasFile atlas filename or atlas data or owns SkeletonData - * @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations. - * @returns {sp.Skeleton} - */ -sp.Skeleton.create = function (skeletonDataFile, atlasFile/* or atlas*/, scale) { - return new sp.Skeleton(skeletonDataFile, atlasFile, scale); -}; diff --git a/extensions/spine/SkeletonData.js b/extensions/spine/SkeletonData.js new file mode 100644 index 0000000000..d84ed51bc0 --- /dev/null +++ b/extensions/spine/SkeletonData.js @@ -0,0 +1,269 @@ +/**************************************************************************** + Copyright (c) 2016 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +/** + * @module sp + */ + +// implements a simple texture loader like sp._atlasLoader +var TextureLoader = cc.Class({ + ctor: function () { + // {SkeletonData} + this.asset = arguments[0]; + }, + getTexture: function (line) { + //var name = cc.path.mainFileName(line); + //var textures = this.asset.textures; + //for (var i = 0; i < textures.length; i++) { + // var tex = textures[i]; + // if (tex.name === name) { + // return tex; + // } + //} + var urls = this.asset.textures; + for (var i = 0; i < urls.length; i++) { + var url = urls[i]; + if (url.endsWith(line)) { + return cc.textureCache.addImage(url); + } + } + return null; + }, + load: function (page, line, spAtlas) { + var texture = this.getTexture(line); + if (texture) { + if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) { + page.rendererObject = new cc.TextureAtlas(texture, 128); + page.width = texture.getPixelWidth(); + page.height = texture.getPixelHeight(); + } + else { + page._texture = texture; + } + } + else { + cc.error('Failed to load spine atlas "$s"', line); + } + }, + unload: function (obj) { + //page.rendererObject.release(); + } +}); + +/** + * The skeleton data of spine. + * + * @class SkeletonData + * @extends cc.Asset + */ +var SkeletonData = cc.Class({ + name: 'sp.SkeletonData', + extends: cc.Asset, + + ctor: function () { + this.reset(); + }, + + properties: { + + _skeletonJson: null, + + /** + * See http://en.esotericsoftware.com/spine-json-format + * @property {object} skeletonJson + */ + skeletonJson: { + get: function () { + return this._skeletonJson; + }, + set: function (value) { + this._skeletonJson = value; + this.reset(); + } + }, + + _atlasText: "", + + /** + * @property {string} atlasText + */ + atlasText: { + get: function () { + return this._atlasText; + }, + set: function (value) { + this._atlasText = value; + this.reset(); + } + }, + + /** + * @property {cc.Texture2D} textures + */ + textures: { + default: [], + url: [cc.Texture2D] + }, + + /** + * A scale can be specified on the JSON or binary loader which will scale the bone positions, + * image sizes, and animation translations. + * This can be useful when using different sized images than were used when designing the skeleton + * in Spine. For example, if using images that are half the size than were used in Spine, + * a scale of 0.5 can be used. This is commonly used for games that can run with either low or high + * resolution texture atlases. + * + * @see http://en.esotericsoftware.com/spine-using-runtimes#Scaling + * @property {number} scale + */ + scale: 1 + }, + + // PUBLIC + + createNode: function (callback) { + //var Url = require('fire-url'); + //var node = new cc.Node(Url.basenameNoExt(info.url)); + //var skeleton = node.addComponent(sp.Skeleton); + //skeleton.skeletonFile = info.url; + + var node = new cc.Node(this.name); + var skeleton = node.addComponent(sp.Skeleton); + skeleton.skeletonData = this; + + return callback(null, node); + }, + + reset: function () { + /** + * @property {spine.SkeletonData} _skeletonData + * @private + */ + this._skeletonCache = null; + /** + * @property {spine.Atlas} _atlasCache + * @private + */ + this._atlasCache = null; + if (CC_EDITOR) { + this._skinsEnum = null; + this._animsEnum = null; + } + }, + + /** + * Get the included SkeletonData used in spine runtime. + * @method getRuntimeData + * @param {boolean} [quiet=false] + * @return {spine.SkeletonData} + */ + getRuntimeData: function (quiet) { + if (this._skeletonCache) { + return this._skeletonCache; + } + + + if ( !(this.textures && this.textures.length > 0) ) { + if ( !quiet ) { + cc.error('Please re-import "%s" because its textures is not initialized! (This workflow will be improved in the future.)', this.name); + } + return null; + } + + var atlas = this._getAtlas(quiet); + if (! atlas) { + return null; + } + var attachmentLoader = new sp.spine.AtlasAttachmentLoader(atlas); + var jsonReader = new sp.spine.SkeletonJson(attachmentLoader); + jsonReader.scale = this.scale; + + var json = this.skeletonJson; + this._skeletonCache = jsonReader.readSkeletonData(json); + atlas.dispose(jsonReader); + + return this._skeletonCache; + }, + + // EDITOR + + getSkinsEnum: CC_EDITOR && function () { + if (this._skinsEnum) { + return this._skinsEnum; + } + var sd = this.getRuntimeData(true); + if (sd) { + var skins = sd.skins; + var enumDef = {}; + for (var i = 0; i < skins.length; i++) { + var name = skins[i].name; + enumDef[name] = i; + } + return this._skinsEnum = cc.Enum(enumDef); + } + return null; + }, + + getAnimsEnum: CC_EDITOR && function () { + if (this._animsEnum) { + return this._animsEnum; + } + var sd = this.getRuntimeData(true); + if (sd) { + var enumDef = { '': 0 }; + var anims = sd.animations; + for (var i = 0; i < anims.length; i++) { + var name = anims[i].name; + enumDef[name] = i + 1; + } + return this._animsEnum = cc.Enum(enumDef); + } + return null; + }, + + // PRIVATE + + /** + * @method _getAtlas + * @param {boolean} [quiet=false] + * @return {spine.Atlas} + * @private + */ + _getAtlas: function (quiet) { + if (this._atlasCache) { + return this._atlasCache; + } + + if ( !this.atlasText ) { + if ( !quiet ) { + cc.error('The atlas asset of "%s" is not exists!', this.name); + } + return null; + } + + return this._atlasCache = new sp.spine.Atlas(this.atlasText, new TextureLoader(this)); + } +}); + +sp.SkeletonData = module.exports = SkeletonData; diff --git a/extensions/spine/SpineAsset.js b/extensions/spine/SpineAsset.js deleted file mode 100644 index 9bb126170e..0000000000 --- a/extensions/spine/SpineAsset.js +++ /dev/null @@ -1,40 +0,0 @@ -/**************************************************************************** - Copyright (c) 2016 Chukong Technologies Inc. - - http://www.cocos2d-x.org - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -/** - * @module sp - */ - -/** - * The skeleton data of spine. - * @class SpineAsset - * @extends RawAsset - * @constructor - */ -var SpineAsset = cc.Class({ - name: 'sp.SpineAsset', - extends: cc.RawAsset, -}); - -sp.SpineAsset = module.exports = SpineAsset; diff --git a/extensions/spine/editor/spine-asset.html b/extensions/spine/editor/spine-asset.html new file mode 100644 index 0000000000..81cf2b6d84 --- /dev/null +++ b/extensions/spine/editor/spine-asset.html @@ -0,0 +1,44 @@ + + + + + + + + + diff --git a/extensions/spine/editor/spine-asset.png b/extensions/spine/editor/spine-asset.png new file mode 100644 index 0000000000..5ac8644d95 Binary files /dev/null and b/extensions/spine/editor/spine-asset.png differ diff --git a/extensions/spine/editor/spine-meta.js b/extensions/spine/editor/spine-meta.js new file mode 100644 index 0000000000..5478f38c6d --- /dev/null +++ b/extensions/spine/editor/spine-meta.js @@ -0,0 +1,182 @@ +'use strict'; + +/* + * Reference: + * http://en.esotericsoftware.com/spine-json-format + */ + +const Fs = require('fire-fs'); +const Path = require('fire-path'); +const Spine = require('../lib/spine'); + +const ATLAS_EXTS = ['.atlas', '.txt', '']; +const SPINE_ENCODING = { encoding: 'utf-8' }; + +const CustomAssetMeta = Editor.metas['custom-asset']; + +function searchAtlas (skeletonPath, callback) { + skeletonPath = Path.stripExt(skeletonPath); + + function next (index) { + var suffix = ATLAS_EXTS[index]; + var path = skeletonPath + suffix; + Fs.exists(path, exists => { + if (exists) { + return callback(null, path); + } + else if (index + 1 < ATLAS_EXTS.length) { + next(index + 1); + } + else { + callback(new Error(`Can not find ${skeletonPath + ATLAS_EXTS[0]}`)); + } + }); + } + + next(0); +} + +function loadAtlasText (skeletonPath, callback) { + searchAtlas(skeletonPath, (err, path) => { + if (err) { + return callback(err); + } + Fs.readFile(path, SPINE_ENCODING, (err, data) => { + callback(err, { + data: data, + atlasPath: path + }); + }); + }); +} + +// A dummy texture loader to record all textures in atlas +class TextureParser { + constructor (atlasPath) { + this.atlasPath = atlasPath; + // the loaded texture array + this.textures = []; + } + load (page, line) { + var name = Path.basename(line); + var base = Path.dirname(this.atlasPath); + var path = Path.resolve(base, name); + var uuid = Editor.assetdb.fspathToUuid(path); + if (!uuid) { + return; + } + //if (!uuid) { + // cc.error('Can not find texture "%s" for atlas "%s"', line, this.atlasPath); + // return; + //} + //var texture = Editor.serialize.asAsset(uuid); + var url = Editor.assetdb.uuidToUrl(uuid); + this.textures.push(url); + } + unload () {} +} + +class SpineMeta extends CustomAssetMeta { + constructor (assetdb) { + super(assetdb); + this.textures = []; + this.scale = 1; + } + + // HACK - for inspector + get texture () { + //return this.textures[0]; + return Editor.assetdb.uuidToUrl(this.textures[0]); + } + set texture (value) { + this.textures[0] = Editor.assetdb.urlToUuid(value); + //this.textures[0] = value; + } + + static version () { return '1.0.0'; } + static defaultType () { + return 'spine'; + } + + static validate (assetpath) { + // TODO - import as a folder named '***.spine' + var json; + var text = Fs.readFileSync(assetpath, 'utf8'); + var fastTest = text.slice(0, 30); + var maybe = ( fastTest.indexOf('slots') > 0 || + fastTest.indexOf('skins') > 0 || + fastTest.indexOf('events') > 0 || + fastTest.indexOf('animations') > 0 || + fastTest.indexOf('bones') > 0 || + fastTest.indexOf('skeleton') > 0 || + fastTest.indexOf('\"ik\"') > 0 + ); + if (maybe) { + try { + json = JSON.parse(text); + } + catch (e) { + return false; + } + return Array.isArray(json.bones); + } + return false; + } + + import (fspath, cb) { + var self = this; + + Fs.readFile(fspath, SPINE_ENCODING, (err, data) => { + if (err) { + return cb(err); + } + + var json; + try { + json = JSON.parse(data); + } + catch (e) { + return cb(e); + } + + var asset = new sp.SkeletonData(); + asset.name = Path.basenameNoExt(fspath); + asset.skeletonJson = json; + asset.scale = this.scale; + + loadAtlasText(fspath, (err, res) => { + if (err) { + return cb(err); + } + + // parse atlas textures + var textureParser = new TextureParser(res.atlasPath); + try { + new Spine.Atlas(res.data, textureParser); + } + catch (err) { + return cb(new Error(`Failed to load atlas file: "${res.atlasPath}". ${err.stack || err}`)); + } + if (textureParser.textures.length > 0) { + asset.textures = textureParser.textures; + this.textures = textureParser.textures.map(url => Editor.assetdb.urlToUuid(url)); + } + else { + asset.textures = this.textures.map(uuid => Editor.assetdb.uuidToUrl(uuid)); + } + + // + asset.atlasText = res.data; + + // + self._assetdb.saveAssetToLibrary(self.uuid, asset); + + cb(); + }); + }); + } +} + +SpineMeta.prototype.export = null; + +module.exports = SpineMeta; diff --git a/extensions/spine/index.js b/extensions/spine/index.js index 454cf2e0e6..a84678dc64 100644 --- a/extensions/spine/index.js +++ b/extensions/spine/index.js @@ -28,13 +28,79 @@ * @main sp */ +/* + * Reference: + * http://esotericsoftware.com/spine-runtime-terminology + * http://esotericsoftware.com/files/runtime-diagram.png + * http://en.esotericsoftware.com/spine-using-runtimes + */ + sp = {}; -if (!CC_JSB && (!CC_EDITOR || !Editor.isCoreLevel)) { - require('./Skeleton'); - require('./SkeletonCanvasRenderCmd'); - require('./SkeletonWebGLRenderCmd'); - require('./SkeletonAnimation'); -} +// The vertex index of spine. +sp.VERTEX_INDEX = { + X1: 0, + Y1: 1, + X2: 2, + Y2: 3, + X3: 4, + Y3: 5, + X4: 6, + Y4: 7 +}; -require('./SpineAsset'); +// The attachment type of spine. It contains three type: REGION(0), BOUNDING_BOX(1), MESH(2) and SKINNED_MESH. +sp.ATTACHMENT_TYPE = { + REGION: 0, + BOUNDING_BOX: 1, + MESH: 2, + SKINNED_MESH:3 +}; + +/** + * The event type of spine skeleton animation. + * @enum AnimationEventType + */ +sp.AnimationEventType = cc.Enum({ + /** + * @property {Number} START + */ + START: 0, + /** + * @property {Number} END + */ + END: 1, + /** + * @property {Number} COMPLETE + */ + COMPLETE: 2, + /** + * @property {Number} EVENT + */ + EVENT: 3 +}); + +/** + * @module sp + */ + +if (!CC_JSB && (!CC_EDITOR || !Editor.isCoreLevel)) { + + /** + * The official spine runtime. + * See http://en.esotericsoftware.com/spine-using-runtimes + * @property {object} spine + */ + sp.spine = require('./lib/spine'); + + require('./SGSkeleton'); + require('./SGSkeletonCanvasRenderCmd'); + require('./SGSkeletonWebGLRenderCmd'); + require('./SGSkeletonAnimation'); + + require('./SkeletonData'); + require('./Skeleton'); +} +else { + require('./SkeletonData'); +} diff --git a/extensions/spine/spine-exported.js b/extensions/spine/lib/spine.js similarity index 96% rename from extensions/spine/spine-exported.js rename to extensions/spine/lib/spine.js index 55ca291338..f4e875cf1c 100644 --- a/extensions/spine/spine-exported.js +++ b/extensions/spine/lib/spine.js @@ -1,10 +1,10 @@ /****************************************************************************** * Spine Runtimes Software License * Version 2.3 - * + * * Copyright (c) 2013-2015, Esoteric Software * All rights reserved. - * + * * You are granted a perpetual, non-exclusive, non-sublicensable and * non-transferable license to use, install, execute and perform the Spine * Runtimes Software (the "Software") and derivative works solely for personal @@ -16,7 +16,7 @@ * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. - * + * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO @@ -178,6 +178,7 @@ spine.Slot.prototype = { attachment: null, attachmentVertices: [], setAttachment: function (attachment) { + if (this.attachment == attachment) return; this.attachment = attachment; this._attachmentTime = this.bone.skeleton.time; this.attachmentVertices.length = 0; @@ -195,11 +196,16 @@ spine.Slot.prototype = { this.b = data.b; this.a = data.a; - var slotDatas = this.bone.skeleton.data.slots; - for (var i = 0, n = slotDatas.length; i < n; i++) { - if (slotDatas[i] == data) { - this.setAttachment(!data.attachmentName ? null : this.bone.skeleton.getAttachmentBySlotIndex(i, data.attachmentName)); - break; + if (!data.attachmentName) + this.setAttachment(null); + else { + var slotDatas = this.bone.skeleton.data.slots; + for (var i = 0, n = slotDatas.length; i < n; i++) { + if (slotDatas[i] == data) { + this.attachment = null; + this.setAttachment(this.bone.skeleton.getAttachmentBySlotIndex(i, data.attachmentName)); + break; + } } } } @@ -220,12 +226,12 @@ spine.IkConstraint.prototype = { var target = this.target; var bones = this.bones; switch (bones.length) { - case 1: - spine.IkConstraint.apply1(bones[0], target.worldX, target.worldY, this.mix); - break; - case 2: - spine.IkConstraint.apply2(bones[0], bones[1], target.worldX, target.worldY, this.bendDirection, this.mix); - break; + case 1: + spine.IkConstraint.apply1(bones[0], target.worldX, target.worldY, this.mix); + break; + case 2: + spine.IkConstraint.apply2(bones[0], bones[1], target.worldX, target.worldY, this.bendDirection, this.mix); + break; } } }; @@ -412,7 +418,7 @@ spine.Curves.prototype = { var i = frameIndex * 19/*BEZIER_SIZE*/; var curves = this.curves; curves[i++] = 2/*BEZIER*/; - + var x = dfx, y = dfy; for (var n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) { curves[i] = x; @@ -1018,7 +1024,7 @@ spine.Skeleton = function (skeletonData) { this.slots.push(slot); this.drawOrder.push(slot); } - + this.ikConstraints = []; for (var i = 0, n = skeletonData.ikConstraints.length; i < n; i++) this.ikConstraints.push(new spine.IkConstraint(skeletonData.ikConstraints[i], this)); @@ -1049,28 +1055,28 @@ spine.Skeleton.prototype = { var bones = this.bones; outer: - for (var i = 0, n = bones.length; i < n; i++) { - var bone = bones[i]; - var current = bone; - do { - for (var ii = 0; ii < ikConstraintsCount; ii++) { - var ikConstraint = ikConstraints[ii]; - var parent = ikConstraint.bones[0]; - var child= ikConstraint.bones[ikConstraint.bones.length - 1]; - while (true) { - if (current == child) { - boneCache[ii].push(bone); - boneCache[ii + 1].push(bone); - continue outer; + for (var i = 0, n = bones.length; i < n; i++) { + var bone = bones[i]; + var current = bone; + do { + for (var ii = 0; ii < ikConstraintsCount; ii++) { + var ikConstraint = ikConstraints[ii]; + var parent = ikConstraint.bones[0]; + var child= ikConstraint.bones[ikConstraint.bones.length - 1]; + while (true) { + if (current == child) { + boneCache[ii].push(bone); + boneCache[ii + 1].push(bone); + continue outer; + } + if (child == parent) break; + child = child.parent; } - if (child == parent) break; - child = child.parent; } - } - current = current.parent; - } while (current); - nonIkBones[nonIkBones.length] = bone; - } + current = current.parent; + } while (current); + nonIkBones[nonIkBones.length] = bone; + } }, /** Updates the world transform for each bone. */ updateWorldTransform: function () { @@ -1148,11 +1154,11 @@ spine.Skeleton.prototype = { }, setSkinByName: function (skinName) { var skin = this.data.findSkin(skinName); - if (!skin) throw new Error("Skin not found: " + skinName); + if (!skin) throw "Skin not found: " + skinName; this.setSkin(skin); }, - /** Sets the skin used to look up attachments before looking in the {@link SkeletonData#getDefaultSkin() default skin}. - * Attachments from the new skin are attached if the corresponding attachment from the old skin was attached. If there was + /** Sets the skin used to look up attachments before looking in the {@link SkeletonData#getDefaultSkin() default skin}. + * Attachments from the new skin are attached if the corresponding attachment from the old skin was attached. If there was * no old skin, each slot's setup mode attachment is attached from the new skin. * @param newSkin May be null. */ setSkin: function (newSkin) { @@ -1195,13 +1201,13 @@ spine.Skeleton.prototype = { var attachment = null; if (attachmentName) { attachment = this.getAttachmentBySlotIndex(i, attachmentName); - if (!attachment) throw new Error("Attachment not found: " + attachmentName + ", for slot: " + slotName); + if (!attachment) throw "Attachment not found: " + attachmentName + ", for slot: " + slotName; } slot.setAttachment(attachment); return; } } - throw new Error("Slot not found: " + slotName); + throw "Slot not found: " + slotName; }, /** @return May be null. */ findIkConstraint: function (ikConstraintName) { @@ -1489,9 +1495,9 @@ spine.AnimationStateData.prototype = { defaultMix: 0, setMixByName: function (fromName, toName, duration) { var from = this.skeletonData.findAnimation(fromName); - if (!from) throw new Error("Animation not found: " + fromName); + if (!from) throw "Animation not found: " + fromName; var to = this.skeletonData.findAnimation(toName); - if (!to) throw new Error("Animation not found: " + toName); + if (!to) throw "Animation not found: " + toName; this.setMix(from, to, duration); }, setMix: function (from, to, duration) { @@ -1599,7 +1605,7 @@ spine.AnimationState.prototype = { clearTracks: function () { for (var i = 0, n = this.tracks.length; i < n; i++) this.clearTrack(i); - this.tracks.length = 0; + this.tracks.length = 0; }, clearTrack: function (trackIndex) { if (trackIndex >= this.tracks.length) return; @@ -1644,7 +1650,7 @@ spine.AnimationState.prototype = { }, setAnimationByName: function (trackIndex, animationName, loop) { var animation = this.data.skeletonData.findAnimation(animationName); - if (!animation) throw new Error("Animation not found: " + animationName); + if (!animation) throw "Animation not found: " + animationName; return this.setAnimation(trackIndex, animation, loop); }, /** Set the current animation. Any queued animations are cleared. */ @@ -1658,7 +1664,7 @@ spine.AnimationState.prototype = { }, addAnimationByName: function (trackIndex, animationName, loop, delay) { var animation = this.data.skeletonData.findAnimation(animationName); - if (!animation) throw new Error("Animation not found: " + animationName); + if (!animation) throw "Animation not found: " + animationName; return this.addAnimation(trackIndex, animation, loop, delay); }, /** Adds an animation to be played delay seconds after the current or last queued animation. @@ -1719,7 +1725,7 @@ spine.SkeletonJson.prototype = { var parent = null; if (boneMap["parent"]) { parent = skeletonData.findBone(boneMap["parent"]); - if (!parent) throw new Error("Parent bone not found: " + boneMap["parent"]); + if (!parent) throw "Parent bone not found: " + boneMap["parent"]; } var boneData = new spine.BoneData(boneMap["name"], parent); boneData.length = (boneMap["length"] || 0) * this.scale; @@ -1743,12 +1749,12 @@ spine.SkeletonJson.prototype = { var bones = ikMap["bones"]; for (var ii = 0, nn = bones.length; ii < nn; ii++) { var bone = skeletonData.findBone(bones[ii]); - if (!bone) throw new Error("IK bone not found: " + bones[ii]); + if (!bone) throw "IK bone not found: " + bones[ii]; ikConstraintData.bones.push(bone); } ikConstraintData.target = skeletonData.findBone(ikMap["target"]); - if (!ikConstraintData.target) throw new Error("Target bone not found: " + ikMap["target"]); + if (!ikConstraintData.target) throw "Target bone not found: " + ikMap["target"]; ikConstraintData.bendDirection = (!ikMap.hasOwnProperty("bendPositive") || ikMap["bendPositive"]) ? 1 : -1; ikConstraintData.mix = ikMap.hasOwnProperty("mix") ? ikMap["mix"] : 1; @@ -1762,7 +1768,7 @@ spine.SkeletonJson.prototype = { for (var i = 0, n = slots.length; i < n; i++) { var slotMap = slots[i]; var boneData = skeletonData.findBone(slotMap["bone"]); - if (!boneData) throw new Error("Slot bone not found: " + slotMap["bone"]); + if (!boneData) throw "Slot bone not found: " + slotMap["bone"]; var slotData = new spine.SlotData(slotMap["name"], boneData); var color = slotMap["color"]; @@ -1774,7 +1780,7 @@ spine.SkeletonJson.prototype = { } slotData.attachmentName = slotMap["attachment"]; - slotData.blendMode = spine.AttachmentType[slotMap["blend"] || "normal"]; + slotData.blendMode = spine.BlendMode[slotMap["blend"] || "normal"]; skeletonData.slots.push(slotData); } @@ -1825,7 +1831,7 @@ spine.SkeletonJson.prototype = { var type = spine.AttachmentType[map["type"] || "region"]; var path = map["path"] || name; - + var scale = this.scale; if (type == spine.AttachmentType.region) { var region = this.attachmentLoader.newRegionAttachment(skin, name, path); @@ -1852,7 +1858,7 @@ spine.SkeletonJson.prototype = { } else if (type == spine.AttachmentType.mesh) { var mesh = this.attachmentLoader.newMeshAttachment(skin, name, path); if (!mesh) return null; - mesh.path = path; + mesh.path = path; mesh.vertices = this.getFloatArray(map, "vertices", scale); mesh.triangles = this.getIntArray(map, "triangles"); mesh.regionUVs = this.getFloatArray(map, "uvs", 1); @@ -1896,7 +1902,7 @@ spine.SkeletonJson.prototype = { mesh.triangles = this.getIntArray(map, "triangles"); mesh.regionUVs = uvs; mesh.updateUVs(); - + color = map["color"]; if (color) { mesh.r = this.toColor(color, 0); @@ -1904,7 +1910,7 @@ spine.SkeletonJson.prototype = { mesh.b = this.toColor(color, 2); mesh.a = this.toColor(color, 3); } - + mesh.hullLength = (map["hull"] || 0) * 2; if (map["edges"]) mesh.edges = this.getIntArray(map, "edges"); mesh.width = (map["width"] || 0) * scale; @@ -1917,7 +1923,7 @@ spine.SkeletonJson.prototype = { attachment.vertices.push(vertices[i] * scale); return attachment; } - throw new Error("Unknown attachment type: " + type); + throw "Unknown attachment type: " + type; }, readAnimation: function (name, map, skeletonData) { var timelines = []; @@ -1964,7 +1970,7 @@ spine.SkeletonJson.prototype = { duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]); } else - throw new Error("Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")"); + throw "Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")"; } } @@ -1972,7 +1978,7 @@ spine.SkeletonJson.prototype = { for (var boneName in bones) { if (!bones.hasOwnProperty(boneName)) continue; var boneIndex = skeletonData.findBoneIndex(boneName); - if (boneIndex == -1) throw new Error("Bone not found: " + boneName); + if (boneIndex == -1) throw "Bone not found: " + boneName; var boneMap = bones[boneName]; for (var timelineName in boneMap) { @@ -2030,7 +2036,7 @@ spine.SkeletonJson.prototype = { timelines.push(timeline); duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 2 - 2]); } else - throw new Error("Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")"); + throw "Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")"; } } @@ -2065,10 +2071,10 @@ spine.SkeletonJson.prototype = { var values = meshMap[meshName]; var timeline = new spine.FfdTimeline(values.length); var attachment = skin.getAttachment(slotIndex, meshName); - if (!attachment) throw new Error("FFD attachment not found: " + meshName); + if (!attachment) throw "FFD attachment not found: " + meshName; timeline.slotIndex = slotIndex; timeline.attachment = attachment; - + var isMesh = attachment.type == spine.AttachmentType.mesh; var vertexCount; if (isMesh) @@ -2106,7 +2112,7 @@ spine.SkeletonJson.prototype = { vertices[ii] += meshVertices[ii]; } } - + timeline.setFrame(frameIndex, valueMap["time"], vertices); this.readCurve(timeline, frameIndex, valueMap); frameIndex++; @@ -2138,7 +2144,7 @@ spine.SkeletonJson.prototype = { for (var ii = 0, nn = offsets.length; ii < nn; ii++) { var offsetMap = offsets[ii]; var slotIndex = skeletonData.findSlotIndex(offsetMap["slot"]); - if (slotIndex == -1) throw new Error("Slot not found: " + offsetMap["slot"]); + if (slotIndex == -1) throw "Slot not found: " + offsetMap["slot"]; // Collect unchanged items. while (originalIndex != slotIndex) unchanged[unchangedIndex++] = originalIndex++; @@ -2165,7 +2171,7 @@ spine.SkeletonJson.prototype = { for (var i = 0, n = events.length; i < n; i++) { var eventMap = events[i]; var eventData = skeletonData.findEvent(eventMap["name"]); - if (!eventData) throw new Error("Event not found: " + eventMap["name"]); + if (!eventData) throw "Event not found: " + eventMap["name"]; var event = new spine.Event(eventData); event.intValue = eventMap.hasOwnProperty("int") ? eventMap["int"] : eventData.intValue; event.floatValue = eventMap.hasOwnProperty("float") ? eventMap["float"] : eventData.floatValue; @@ -2180,7 +2186,7 @@ spine.SkeletonJson.prototype = { }, readCurve: function (timeline, frameIndex, valueMap) { var curve = valueMap["curve"]; - if (!curve) + if (!curve) timeline.curves.setLinear(frameIndex); else if (curve == "stepped") timeline.curves.setStepped(frameIndex); @@ -2188,7 +2194,7 @@ spine.SkeletonJson.prototype = { timeline.curves.setCurve(frameIndex, curve[0], curve[1], curve[2], curve[3]); }, toColor: function (hexString, colorIndex) { - if (hexString.length != 8) throw new Error("Color hexidecimal length must be 8, recieved: " + hexString); + if (hexString.length != 8) throw "Color hexidecimal length must be 8, recieved: " + hexString; return parseInt(hexString.substring(colorIndex * 2, (colorIndex * 2) + 2), 16) / 255; }, getFloatArray: function (map, name, scale) { @@ -2408,14 +2414,14 @@ spine.AtlasReader.prototype = { readValue: function () { var line = this.readLine(); var colon = line.indexOf(":"); - if (colon == -1) throw new Error("Invalid line: " + line); + if (colon == -1) throw "Invalid line: " + line; return this.trim(line.substring(colon + 1)); }, /** Returns the number of tuple values read (1, 2 or 4). */ readTuple: function (tuple) { var line = this.readLine(); var colon = line.indexOf(":"); - if (colon == -1) throw new Error("Invalid line: " + line); + if (colon == -1) throw "Invalid line: " + line; var i = 0, lastMatch = colon + 1; for (; i < 3; i++) { var comma = line.indexOf(",", lastMatch); @@ -2434,7 +2440,7 @@ spine.AtlasAttachmentLoader = function (atlas) { spine.AtlasAttachmentLoader.prototype = { newRegionAttachment: function (skin, name, path) { var region = this.atlas.findRegion(path); - if (!region) throw new Error("Region not found in atlas: " + path + " (region attachment: " + name + ")"); + if (!region) throw "Region not found in atlas: " + path + " (region attachment: " + name + ")"; var attachment = new spine.RegionAttachment(name); attachment.rendererObject = region; attachment.setUVs(region.u, region.v, region.u2, region.v2, region.rotate); @@ -2448,7 +2454,7 @@ spine.AtlasAttachmentLoader.prototype = { }, newMeshAttachment: function (skin, name, path) { var region = this.atlas.findRegion(path); - if (!region) throw new Error("Region not found in atlas: " + path + " (mesh attachment: " + name + ")"); + if (!region) throw "Region not found in atlas: " + path + " (mesh attachment: " + name + ")"; var attachment = new spine.MeshAttachment(name); attachment.rendererObject = region; attachment.regionU = region.u; @@ -2466,7 +2472,7 @@ spine.AtlasAttachmentLoader.prototype = { }, newSkinnedMeshAttachment: function (skin, name, path) { var region = this.atlas.findRegion(path); - if (!region) throw new Error("Region not found in atlas: " + path + " (skinned mesh attachment: " + name + ")"); + if (!region) throw "Region not found in atlas: " + path + " (skinned mesh attachment: " + name + ")"; var attachment = new spine.SkinnedMeshAttachment(name); attachment.rendererObject = region; attachment.regionU = region.u; @@ -2635,4 +2641,5 @@ spine.SkeletonBounds.prototype = { } }; +// TODO - delete me module.exports = spine; diff --git a/gulp/tasks/build-cocos2d.js b/gulp/tasks/build-cocos2d.js index c3e8fa477a..cfc958f156 100644 --- a/gulp/tasks/build-cocos2d.js +++ b/gulp/tasks/build-cocos2d.js @@ -12,7 +12,6 @@ var srcs = [ './cocos2d/core/platform/CCCommon.js', './cocos2d/core/platform/CCSAXParser.js', - './cocos2d/core/platform/CCLoaders.js', './cocos2d/core/platform/CCConfig.js', './cocos2d/core/platform/miniFramework.js', './cocos2d/core/platform/CCEGLView.js', @@ -65,7 +64,6 @@ var srcs = [ './cocos2d/core/CCDrawingPrimitivesCanvas.js', './cocos2d/core/CCDrawingPrimitivesWebGL.js', - './cocos2d/core/label/FNTLoader.js', './cocos2d/core/label/CCSGLabel.js', './cocos2d/core/label/CCSGLabelCanvasRenderCmd.js', './cocos2d/core/label/CCSGLabelWebGLRenderCmd.js', @@ -134,18 +132,16 @@ var srcs = [ './cocos2d/menus/CCMenu.js', './cocos2d/tilemap/CCTGAlib.js', - './cocos2d/tilemap/CCTMXTiledMap.js', + './cocos2d/tilemap/CCSGTMXTiledMap.js', './cocos2d/tilemap/CCTMXXMLParser.js', './cocos2d/tilemap/CCTMXObjectGroup.js', - './cocos2d/tilemap/CCTMXLayer.js', + './cocos2d/tilemap/CCSGTMXLayer.js', './cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js', './cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js', './cocos2d/parallax/CCParallaxNode.js', './cocos2d/parallax/CCParallaxNodeRenderCmd.js', - './cocos2d/audio/CCAudio.js', - './extensions/ccpool/CCPool.js', './cocos2d/physics/CCPhysicsDebugNode.js', diff --git a/gulpfile.js b/gulpfile.js index 4a862aaf3b..4ed81e9c5e 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -20,20 +20,20 @@ paths = { '../../cocos2d/core/CCGame', '../../cocos2d/core/textures/CCTexture2D', '../../cocos2d/core/sprites/CCSpriteFrame', - '../../cocos2d/core/platform/CCLoader', - '../../cocos2d/core/platform/CCLoaders', '../../cocos2d/core/event/event', - '../../extensions/spine/Skeleton', - '../../extensions/spine/SkeletonAnimation', - '../../extensions/spine/SkeletonCanvasRenderCmd', - '../../extensions/spine/SkeletonWebGLRenderCmd', - '../../extensions/spine/spine-exported', + '../../cocos2d/core/load-pipeline/audio-downloader', + '../../cocos2d/audio/CCAudio', + '../../extensions/spine/SGSkeleton', + '../../extensions/spine/SGSkeletonAnimation', + '../../extensions/spine/SGSkeletonCanvasRenderCmd', + '../../extensions/spine/SGSkeletonWebGLRenderCmd', + '../../extensions/spine/lib/spine', ], test: { src: 'test/qunit/unit/**/*.js', runner: 'test/qunit/lib/qunit-runner.html', - jsEntryEditorExtends: '../editor/share/engine-extends/index.js', // only available in editor + jsEntryEditorExtends: '../editor/test-utils/engine-extends-entry.js', // only available in editor dest: 'bin/cocos2d-js-for-test.js', destEditorExtends: 'bin/cocos2d-js-extends-for-test.js' }, diff --git a/jsb/index.js b/jsb/index.js index 5be79c7cbb..1ebf0d3b25 100644 --- a/jsb/index.js +++ b/jsb/index.js @@ -11,14 +11,17 @@ cc.initEngine = function (config, cb) { }; require('./jsb-predefine'); +require('./jsb-loader'); require('./jsb-game'); require('./jsb-director'); require('./jsb-tex-sprite-frame'); require('./jsb-scale9sprite'); require('./jsb-label'); +require('./jsb-editbox'); require('./jsb-particle'); require('./jsb-enums'); require('./jsb-event'); +require('./jsb-action'); require('./jsb-etc'); // Check version diff --git a/jsb/jsb-action.js b/jsb/jsb-action.js new file mode 100644 index 0000000000..9f69bf348b --- /dev/null +++ b/jsb/jsb-action.js @@ -0,0 +1,262 @@ +// Independent Action from retain/release +var actionArr = [ + 'ActionEase', + 'EaseExponentialIn', + 'EaseExponentialOut', + 'EaseExponentialInOut', + 'EaseSineIn', + 'EaseSineOut', + 'EaseSineInOut', + 'EaseBounce', + 'EaseBounceIn', + 'EaseBounceOut', + 'EaseBounceInOut', + 'EaseBackIn', + 'EaseBackOut', + 'EaseBackInOut', + 'EaseRateAction', + 'EaseIn', + 'EaseElastic', + 'EaseElasticIn', + 'EaseElasticOut', + 'EaseElasticInOut', + 'RemoveSelf', + 'FlipX', + 'FlipY', + 'Place', + 'CallFunc', + 'DelayTime', + 'Sequence', + 'Spawn', + 'Speed', + 'Repeat', + 'RepeatForever', + 'Follow', + 'TargetedAction', + 'Animate', + 'OrbitCamera', + 'GridAction', + 'ProgressTo', + 'ProgressFromTo', + 'ActionInterval', + 'RotateTo', + 'RotateBy', + 'MoveBy', + 'MoveTo', + 'SkewTo', + 'SkewBy', + 'JumpTo', + 'JumpBy', + 'ScaleTo', + 'ScaleBy', + 'Blink', + 'FadeTo', + 'FadeIn', + 'FadeOut', + 'TintTo', + 'TintBy', +]; + +function setCtorReplacer (proto) { + var ctor = proto._ctor; + proto._ctor = function () { + ctor.apply(this, arguments); + this.retain(); + this._retained = true; + }; +} +function setAliasReplacer (name, type) { + var aliasName = name[0].toLowerCase() + name.substr(1); + cc[aliasName] = function () { + var action = type.create.apply(this, arguments); + action.retain(); + action._retained = true; + return action; + }; +} + +for (var i = 0; i < actionArr.length; ++i) { + var name = actionArr[i]; + var type = cc[name]; + if (!type) + continue; + var proto = type.prototype; + setCtorReplacer(proto); + setAliasReplacer(name, type); +} + +function setChainFuncReplacer (proto, name) { + var oldFunc = proto[name]; + proto[name] = function () { + if (this._retained) { + this.release(); + this._retained = false; + } + var newAction = oldFunc.apply(this, arguments); + newAction.retain(); + newAction._retained = true; + return newAction; + }; +} + +setChainFuncReplacer(cc.ActionInterval.prototype, 'repeat'); +setChainFuncReplacer(cc.ActionInterval.prototype, 'repeatForever'); +setChainFuncReplacer(cc.ActionInterval.prototype, 'easing'); + +var jsbRunAction = cc.Node.prototype.runAction; +cc.Node.prototype.runAction = function (action) { + jsbRunAction.call(this, action); + if (action._retained) { + action.release(); + action._retained = false; + } +}; + +function getSGTarget (target) { + if (target instanceof cc.Component) { + target = target.node._sgNode; + } + if (target instanceof cc.Node) { + target = target._sgNode; + } + return target; +} +var jsbAddAction = cc.ActionManager.prototype.addAction; +cc.ActionManager.prototype.addAction = function (action, target, paused) { + target = getSGTarget(target); + jsbAddAction.call(this, action, target, paused); + if (action._retained) { + action.release(); + action._retained = false; + } +}; + +function actionMgrFuncReplacer (funcName, targetPos) { + var proto = cc.ActionManager.prototype; + var oldFunc = proto[funcName]; + proto[funcName] = function () { + arguments[targetPos] = getSGTarget(arguments[targetPos]); + return oldFunc.apply(this, arguments); + }; +} + +var targetRelatedFuncs = [ + ['removeAllActionsFromTarget', 0], + ['removeActionByTag', 1], + ['getActionByTag', 1], + ['numberOfRunningActionsInTarget', 0], + ['pauseTarget', 0], + ['resumeTarget', 0] +]; + +for (var i = 0; i < targetRelatedFuncs.length; ++i) { + actionMgrFuncReplacer.apply(null, targetRelatedFuncs[i]); +} + +cc.ActionManager.prototype.resumeTargets = function (targetsToResume) { + if (!targetsToResume) + return; + + for (var i = 0; i< targetsToResume.length; i++) { + if (targetsToResume[i]) + this.resumeTarget(targetsToResume[i]); + } +}; + +cc.ActionManager.prototype.pauseTargets = function (targetsToPause) { + if (!targetsToPause) + return; + + for (var i = 0; i< targetsToPause.length; i++) { + if (targetsToPause[i]) + this.pauseTarget(targetsToPause[i]); + } +}; + + + +function syncPositionUpdate (dt) { + this._jsbUpdate(dt); + var target = this.getTarget(); + if (target._owner) { + target._owner.x = target.getPositionX(); + target._owner.y = target.getPositionY(); + } +} + +function syncRotationUpdate (dt) { + this._jsbUpdate(dt); + var target = this.getTarget(); + if (target._owner) { + target._owner.rotation = target.getRotation(); + } +} + +function syncScaleUpdate (dt) { + this._jsbUpdate(dt); + var target = this.getTarget(); + if (target._owner) { + target._owner.scaleX = target.getScaleX(); + target._owner.scaleY = target.getScaleY(); + } +} + +function syncRemoveSelfUpdate (dt) { + this._jsbUpdate(dt); + var target = this.getTarget(); + if (target._owner) { + target._owner.removeFromParent(); + } +} + +function syncSkewUpdate (dt) { + this._jsbUpdate(dt); + var target = this.getTarget(); + if (target._owner) { + target._owner.skewX = target.getSkewX(); + target._owner.skewY = target.getSkewY(); + } +} + +// function syncOpacityUpdate (dt) { +// this._jsbUpdate(dt); +// var target = this.getTarget(); +// if (target._owner) { +// target._owner.opacity = target.getOpacity(); +// } +// } + +function syncColorUpdate (dt) { + this._jsbUpdate(dt); + var target = this.getTarget(); + if (target._owner) { + target._owner.color = target.getColor(); + } +} + +var actionUpdate = { + 'MoveTo' : syncPositionUpdate, + 'MoveBy' : syncPositionUpdate, + 'JumpTo' : syncPositionUpdate, + 'JumpBy' : syncPositionUpdate, + 'Place' : syncPositionUpdate, + 'RotateTo' : syncRotationUpdate, + 'RotateBy' : syncRotationUpdate, + 'ScaleTo' : syncScaleUpdate, + 'ScaleBy' : syncScaleUpdate, + 'RemoveSelf' : syncRemoveSelfUpdate, + 'SkewTo' : syncSkewUpdate, + 'SkewBy' : syncSkewUpdate, + // 'Blink' : syncOpacityUpdate, + // 'FadeTo' : syncOpacityUpdate, + // 'FadeIn' : syncOpacityUpdate, + // 'FadeOut' : syncOpacityUpdate, + 'TintTo' : syncColorUpdate, + 'TintBy' : syncColorUpdate +}; + +for (var key in actionUpdate) { + var action = cc[key]; + action.prototype._jsbUpdate = action.prototype.update; + action.prototype.update = actionUpdate[key]; +} \ No newline at end of file diff --git a/jsb/jsb-editbox.js b/jsb/jsb-editbox.js new file mode 100644 index 0000000000..0145ce7ee0 --- /dev/null +++ b/jsb/jsb-editbox.js @@ -0,0 +1,54 @@ +/**************************************************************************** + Copyright (c) 2015 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +'use strict'; + +var _p = cc.EditBox.prototype; +cc.defineGetterSetter(_p, 'font', null, _p.setFont); +cc.defineGetterSetter(_p, 'fontName', null, _p.setFontName); +cc.defineGetterSetter(_p, 'fontSize', null, _p.setFontSize); +cc.defineGetterSetter(_p, 'fontColor', null, _p.setFontColor); +cc.defineGetterSetter(_p, 'string', _p.getString, _p.setString); +cc.defineGetterSetter(_p, 'maxLength', _p.getMaxLength, _p.setMaxLength); +cc.defineGetterSetter(_p, 'placeholder', _p.getPlaceHolder, _p.setPlaceHolder); +cc.defineGetterSetter(_p, 'placeholderFont', null, _p.setPlaceholderFont); +cc.defineGetterSetter(_p, 'placeholderFontName', null, _p.setPlaceholderFontName); +cc.defineGetterSetter(_p, 'placeholderFontSize', null, _p.setPlaceholderFontSize); +cc.defineGetterSetter(_p, 'placeholderFontColor', null, _p.setPlaceholderFontColor); +cc.defineGetterSetter(_p, 'inputFlag', null, _p.setInputFlag); +cc.defineGetterSetter(_p, 'delegate', null, _p.setDelegate); +cc.defineGetterSetter(_p, 'inputMode', null, _p.setInputMode); +cc.defineGetterSetter(_p, 'returnType', null, _p.setReturnType); + + +_p.editBoxEditingDidBegin = function (sender) { + this.editBoxEditingDidBegan(sender); +} +_p.editBoxEditingDidEnd = function (sender) { + this.editBoxEditingDidEnded(sender); +} + +_p.setLineHeight = function () {} + +_p = null; diff --git a/jsb/jsb-etc.js b/jsb/jsb-etc.js index b7bc76e563..a7d89ea353 100644 --- a/jsb/jsb-etc.js +++ b/jsb/jsb-etc.js @@ -24,6 +24,8 @@ 'use strict'; +var NORMALIZE_RE = /[^\.\/]+\/\.\.\//; + // cc.path cc.js.mixin(cc.path, { //todo make public after verification @@ -33,7 +35,7 @@ cc.js.mixin(cc.path, { //removing all ../ do { oldUrl = url; - url = url.replace(this.normalizeRE, ''); + url = url.replace(NORMALIZE_RE, ''); } while (oldUrl.length !== url.length); return url; }, @@ -78,180 +80,6 @@ cc.Scheduler.prototype.unschedule = function (callback, target) { this._unschedule(target, callback); }; -// Independent Action from retain/release -var actionArr = [ - 'ActionEase', - 'EaseExponentialIn', - 'EaseExponentialOut', - 'EaseExponentialInOut', - 'EaseSineIn', - 'EaseSineOut', - 'EaseSineInOut', - 'EaseBounce', - 'EaseBounceIn', - 'EaseBounceOut', - 'EaseBounceInOut', - 'EaseBackIn', - 'EaseBackOut', - 'EaseBackInOut', - 'EaseRateAction', - 'EaseIn', - 'EaseElastic', - 'EaseElasticIn', - 'EaseElasticOut', - 'EaseElasticInOut', - 'RemoveSelf', - 'FlipX', - 'FlipY', - 'Place', - 'CallFunc', - 'DelayTime', - 'Sequence', - 'Spawn', - 'Speed', - 'Repeat', - 'RepeatForever', - 'Follow', - 'TargetedAction', - 'Animate', - 'OrbitCamera', - 'GridAction', - 'ProgressTo', - 'ProgressFromTo', - 'ActionInterval', - 'RotateTo', - 'RotateBy', - 'MoveBy', - 'MoveTo', - 'SkewTo', - 'SkewBy', - 'JumpTo', - 'JumpBy', - 'ScaleTo', - 'ScaleBy', - 'Blink', - 'FadeTo', - 'FadeIn', - 'FadeOut', - 'TintTo', - 'TintBy', -]; - -function setCtorReplacer (proto) { - var ctor = proto._ctor; - proto._ctor = function () { - ctor.apply(this, arguments); - this.retain(); - this._retained = true; - }; -} -function setAliasReplacer (name, type) { - var aliasName = name[0].toLowerCase() + name.substr(1); - cc[aliasName] = function () { - var action = type.create.apply(this, arguments); - action.retain(); - action._retained = true; - return action; - }; -} - -for (var i = 0; i < actionArr.length; ++i) { - var name = actionArr[i]; - var type = cc[name]; - if (!type) - continue; - var proto = type.prototype; - setCtorReplacer(proto); - setAliasReplacer(name, type); -} - -function setChainFuncReplacer (proto, name) { - var oldFunc = proto[name]; - proto[name] = function () { - if (this._retained) { - this.release(); - this._retained = false; - } - var newAction = oldFunc.apply(this, arguments); - newAction.retain(); - newAction._retained = true; - return newAction; - }; -} - -setChainFuncReplacer(cc.ActionInterval.prototype, 'repeat'); -setChainFuncReplacer(cc.ActionInterval.prototype, 'repeatForever'); -setChainFuncReplacer(cc.ActionInterval.prototype, 'easing'); - -var jsbRunAction = cc.Node.prototype.runAction; -cc.Node.prototype.runAction = function (action) { - jsbRunAction.call(this, action); - if (action._retained) { - action.release(); - action._retained = false; - } -}; - -function getSGTarget (target) { - if (target instanceof cc.Component) { - target = target.node._sgNode; - } - if (target instanceof cc.Node) { - target = target._sgNode; - } - return target; -} -var jsbAddAction = cc.ActionManager.prototype.addAction; -cc.ActionManager.prototype.addAction = function (action, target, paused) { - target = getSGTarget(target); - jsbAddAction.call(this, action, target, paused); - if (action._retained) { - action.release(); - action._retained = false; - } -}; - -function actionMgrFuncReplacer (funcName, targetPos) { - var proto = cc.ActionManager.prototype; - var oldFunc = proto[funcName]; - proto[funcName] = function () { - arguments[targetPos] = getSGTarget(arguments[targetPos]); - return oldFunc.apply(this, arguments); - }; -} - -var targetRelatedFuncs = [ - ['removeAllActionsFromTarget', 0], - ['removeActionByTag', 1], - ['getActionByTag', 1], - ['numberOfRunningActionsInTarget', 0], - ['pauseTarget', 0], - ['resumeTarget', 0] -]; - -for (var i = 0; i < targetRelatedFuncs.length; ++i) { - actionMgrFuncReplacer.apply(null, targetRelatedFuncs[i]); -} - -cc.ActionManager.prototype.resumeTargets = function (targetsToResume) { - if (!targetsToResume) - return; - - for (var i = 0; i< targetsToResume.length; i++) { - if (targetsToResume[i]) - this.resumeTarget(targetsToResume[i]); - } -}; - -cc.ActionManager.prototype.pauseTargets = function (targetsToPause) { - if (!targetsToPause) - return; - - for (var i = 0; i< targetsToPause.length; i++) { - if (targetsToPause[i]) - this.pauseTarget(targetsToPause[i]); - } -}; // ccsg window._ccsg = { @@ -260,7 +88,9 @@ window._ccsg = { Sprite: cc.Sprite, ParticleSystem: cc.ParticleSystem, Label: cc.Label, - EditBox: cc.EditBox + EditBox: cc.EditBox, + TMXTiledMap: cc.TMXTiledMap, + TMXLayer: cc.TMXLayer }; // rename cc.Class to cc._Class diff --git a/jsb/jsb-event.js b/jsb/jsb-event.js index 8fd9800e43..82e42bf785 100644 --- a/jsb/jsb-event.js +++ b/jsb/jsb-event.js @@ -77,7 +77,13 @@ cc.js.mixin(cc.Event.prototype, { // cc.Event.EventCustom cc.Event.EventCustom = function (type, bubbles) { - cc.Event.call(this, cc.Event.CUSTOM); + this.target = null; + this.currentTarget = null; + this.eventPhase = 0; + this._defaultPrevented = false; + this._propagationStopped = false; + this._propagationImmediateStopped = false; + this.type = type; this.bubbles = bubbles || false; this.detail = null; @@ -177,4 +183,50 @@ cc.eventManager.resumeTarget = function (target, recursive) { target = target._sgNode; } this._resumeTarget(target, recursive || false); -}; \ No newline at end of file +}; + +cc.js.mixin(cc.EventTouch.prototype, { + setLocation: function (x, y) { + this.touch && this.touch.setTouchInfo(this.touch.getID(), x, y); + }, + + getLocation: function () { + return this.touch ? this.touch.getLocation() : cc.v2(); + }, + + getLocationInView: function() { + return this.touch ? this.touch.getLocationInView() : cc.v2(); + }, + + getPreviousLocation:function () { + return this.touch ? this.touch.getPreviousLocation() : cc.v2(); + }, + + getStartLocation: function() { + return this.touch ? this.touch.getStartLocation() : cc.v2(); + }, + + getID:function () { + return this.touch ? this.getID() : null; + }, + + getDelta: function () { + return this.touch ? this.touch.getDelta() : cc.v2(); + }, + + getDeltaX: function () { + return this.touch ? this.touch.getDelta().x : 0; + }, + + getDeltaY: function () { + return this.touch ? this.touch.getDelta().y : 0; + }, + + getLocationX: function () { + return this.touch ? this.touch.getLocationX() : 0; + }, + + getLocationY: function () { + return this.touch ? this.touch.getLocationY() : 0; + } +}); \ No newline at end of file diff --git a/jsb/jsb-game.js b/jsb/jsb-game.js index 628ecf2933..93d9b2a5ac 100644 --- a/jsb/jsb-game.js +++ b/jsb/jsb-game.js @@ -97,8 +97,8 @@ cc.js.mixin(cc.game, { // Load game scripts var jsList = config[CONFIG_KEY.jsList]; if (jsList) { - cc.loader.loadJs(jsList, function (err) { - if (err) throw new Error(err); + cc.loader.load(jsList, function (err) { + if (err) throw new Error(JSON.stringify(err)); self._prepared = true; if (cb) cb(); }); @@ -133,7 +133,7 @@ cc.js.mixin(cc.game, { cc.game.onStart = onStart; } } - + cc.director.startAnimation(); this.prepare(cc.game.onStart && cc.game.onStart.bind(cc.game)); }, diff --git a/jsb/jsb-label.js b/jsb/jsb-label.js index 37e8b9a994..ead0be392e 100644 --- a/jsb/jsb-label.js +++ b/jsb/jsb-label.js @@ -46,7 +46,20 @@ if (!jsbLabel.prototype.getOverflow) { jsbLabel.prototype.getOverflow = function(){}; } +if (!jsbLabel.prototype.isSystemFontUsed) { + jsbLabel.prototype.isSystemFontUsed = function() { + return this._isSystemFontUsed; + } + + jsbLabel.prototype.setSystemFontUsed = function(value) { + this._isSystemFontUsed = value; + this.setSystemFontName("Arial"); + this.setSystemFontSize(this.getFontSize()); + } +} + jsbLabel.prototype.setFontSize = function (size) { + this._fontSize = size; if (this._labelType === _ccsg.Label.Type.SystemFont) { this.setSystemFontSize(size); } @@ -60,6 +73,10 @@ jsbLabel.prototype.setFontSize = function (size) { } }; +jsbLabel.prototype.getFontSize = function () { + return this._fontSize; +} + jsbLabel.prototype.enableWrapText = jsbLabel.prototype.enableWrap || function(){}; jsbLabel.prototype.isWrapTextEnabled = jsbLabel.prototype.isWrapEnabled || function(){}; @@ -93,20 +110,17 @@ jsbLabel.prototype.setFontFileOrFamily = function (fontHandle) { var extName = cc.path.extname(fontHandle); //specify font family name directly - if (extName === null) { + if (!extName) { this._labelType = _ccsg.Label.Type.SystemFont; this.setSystemFontName(fontHandle); + this._isSystemFontUsed = true; } else { - //add resource path - fontHandle = cc.path.join(cc.loader.resPath, fontHandle); - if (extName === '.ttf') { this._labelType = _ccsg.Label.Type.TTF; this._ttfConfig.fontFilePath = fontHandle; this.setTTFConfig(this._ttfConfig); } else if (extName === '.fnt') { - //todo add bmfont here this._labelType = _ccsg.Label.Type.BMFont; this.setBMFontFilePath(fontHandle, cc.v2(0, 0), this.getBMFontSize()); } @@ -139,6 +153,7 @@ cc.Label = function (string, fontHandle) { else { label = jsbLabel.createWithSystemFont(string || '', fontHandle, 40); type = _ccsg.Label.Type.SystemFont; + label._isSystemFontUsed = true; } label._labelType = type; return label; @@ -148,9 +163,8 @@ cc.Label.Type = cc.Enum({ BMFont: 1 }); cc.Label.Overflow = cc.Enum({ - //TODO: uncomment if normal is supported in web - // NONE: 0, + NONE: 0, CLAMP: 1, SHRINK: 2, RESIZE_HEIGHT: 3 -}); \ No newline at end of file +}); diff --git a/jsb/jsb-loader.js b/jsb/jsb-loader.js new file mode 100644 index 0000000000..ce7ae82e48 --- /dev/null +++ b/jsb/jsb-loader.js @@ -0,0 +1,142 @@ +/**************************************************************************** + Copyright (c) 2016 Chukong Technologies Inc. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + ****************************************************************************/ + +'use strict'; + +require('../cocos2d/core/load-pipeline'); + +function empty (item, callback) { + callback(null, null); +} + +function downloadScript (item, callback) { + var url = item.src; + require(url); + callback(null, url); +} + +function downloadText (item, callback) { + var url = item.src; + var result = jsb.fileUtils.getStringFromFile(url); + if (typeof result === 'string') { + callback(null, result); + } + else { + callback(new Error('Download text failed: ' + url)); + } +} + +cc.loader.addDownloadHandlers({ + // JS + 'js' : downloadScript, + + // Images + 'png' : empty, + 'jpg' : empty, + 'bmp' : empty, + 'jpeg' : empty, + 'gif' : empty, + 'ico' : empty, + 'tiff' : empty, + 'webp' : empty, + 'image' : empty, + + // Audio + 'mp3' : empty, + 'ogg' : empty, + 'wav' : empty, + 'mp4' : empty, + 'm4a' : empty, + + // Txt + 'txt' : downloadText, + 'xml' : downloadText, + 'vsh' : downloadText, + 'fsh' : downloadText, + 'atlas' : downloadText, + + 'tmx' : downloadText, + 'tsx' : downloadText, + + 'json' : downloadText, + 'ExportJson' : downloadText, + 'plist' : downloadText, + + 'fnt' : downloadText, + + // Font + 'font' : empty, + 'eot' : empty, + 'ttf' : empty, + 'woff' : empty, + 'svg' : empty, + 'ttc' : empty, + + 'default' : downloadText +}); + + +function loadImage (item, callback) { + var url = item.src; + + var cachedTex = cc.textureCache.getTextureForKey(url); + if (cachedTex) { + callback && callback(null, cachedTex); + } + else if (url.match(jsb.urlRegExp)) { + jsb.loadRemoteImg(url, function(succeed, tex) { + if (succeed) { + callback && callback(null, tex); + } + else { + callback && callback(new Error('Load image failed: ' + url)); + } + }); + } + else { + cc.textureCache._addImageAsync(url, function (tex){ + if (tex instanceof cc.Texture2D) { + callback && callback(null, tex); + } + else { + callback && callback(new Error('Load image failed: ' + url)); + } + }); + } +} + +cc.loader.addLoadHandlers({ + // Images + 'png' : loadImage, + 'jpg' : loadImage, + 'bmp' : loadImage, + 'jpeg' : loadImage, + 'gif' : loadImage, + 'ico' : loadImage, + 'tiff' : loadImage, + 'webp' : loadImage, + 'image' : loadImage, + + 'default' : empty +}); \ No newline at end of file diff --git a/jsb/jsb-tex-sprite-frame.js b/jsb/jsb-tex-sprite-frame.js index 184db33703..79a3952a3f 100644 --- a/jsb/jsb-tex-sprite-frame.js +++ b/jsb/jsb-tex-sprite-frame.js @@ -76,9 +76,6 @@ cc.SpriteFrame.prototype.initWithTexture = function (texture, rect, rotated, off } } - if(arguments.length === 2) - rect = cc.rectPointsToPixels(rect); - offset = offset || cc.p(0, 0); originalSize = originalSize || rect; rotated = rotated || false; @@ -142,7 +139,7 @@ cc.SpriteFrame.prototype._deserialize = function (data, handle) { this.initWithTexture(null, rect, rotated, offset, size, textureUuid); }; cc.SpriteFrame.prototype._checkRect = function (texture) { - var rect = this.getRectInPixels(); + var rect = this.getRect(); var maxX = rect.x, maxY = rect.y; if (this._rotated) { maxX += rect.height; diff --git a/jsb/versions/jsb-polyfill-v3.5.js b/jsb/versions/jsb-polyfill-v3.5.js index 4a1e9d0476..79f02d2b36 100644 --- a/jsb/versions/jsb-polyfill-v3.5.js +++ b/jsb/versions/jsb-polyfill-v3.5.js @@ -55,9 +55,6 @@ cc.SpriteFrame.prototype.initWithTexture = function (texture, rect, rotated, off } } - if(arguments.length === 2) - rect = cc.rectPointsToPixels(rect); - offset = cc.p(0, 0); originalSize = originalSize || rect; rotated = rotated || false; diff --git a/moduleConfig.json b/moduleConfig.json index 58a975f07e..212d1378e2 100644 --- a/moduleConfig.json +++ b/moduleConfig.json @@ -45,7 +45,6 @@ "cocos2d/core/platform/CCClass.js", "cocos2d/core/platform/CCCommon.js", "cocos2d/core/platform/CCSAXParser.js", - "cocos2d/core/platform/CCLoaders.js", "cocos2d/core/platform/CCConfig.js", "cocos2d/core/platform/miniFramework.js", "cocos2d/core/platform/CCMacro.js", diff --git a/predefine.js b/predefine.js index 6fee5427e2..c7580fe65b 100644 --- a/predefine.js +++ b/predefine.js @@ -32,9 +32,6 @@ cc = {}; // The namespace for original nodes rendering in scene graph. _ccsg = {}; -//to make sure the cc.log, cc.warn, cc.error, cc._throw and cc.assert would not throw error before init by debugger mode. -cc.log = cc.warn = cc.error = cc._throw = cc.assert = function () {}; - if (CC_DEV) { /** * contains internal apis for unit tests @@ -43,6 +40,10 @@ if (CC_DEV) { cc._Test = {}; } +// output all info before initialized +require('./CCDebugger'); +cc._initDebugSetting(cc.DebugMode.INFO); + // polyfills /* require('./polyfill/bind'); */ require('./polyfill/string'); @@ -55,12 +56,7 @@ require('./cocos2d/core/platform/CCInputManager'); require('./cocos2d/core/platform/CCInputExtension'); require('./cocos2d/core/event'); require('./cocos2d/core/platform/CCSys'); -require('./cocos2d/core/platform/CCLoader'); -require('./CCDebugger'); -if (CC_DEV) { - // output all errors before initialized - cc._initDebugSetting(1); // DEBUG_MODE_INFO -} +require('./cocos2d/core/load-pipeline'); require('./cocos2d/core/CCDirector'); require('./cocos2d/core/CCDirectorWebGL'); require('./cocos2d/core/CCDirectorCanvas'); diff --git a/test/qunit/assets/Thonburi.eot b/test/qunit/assets/Thonburi.eot new file mode 100644 index 0000000000..3661613d78 Binary files /dev/null and b/test/qunit/assets/Thonburi.eot differ diff --git a/test/qunit/assets/Thonburi.ttf b/test/qunit/assets/Thonburi.ttf new file mode 100755 index 0000000000..ab579da818 Binary files /dev/null and b/test/qunit/assets/Thonburi.ttf differ diff --git a/test/qunit/lib/polyfill-for-phantom.js b/test/qunit/lib/polyfill-for-phantom.js index 2612406315..9b0c82ac9c 100644 --- a/test/qunit/lib/polyfill-for-phantom.js +++ b/test/qunit/lib/polyfill-for-phantom.js @@ -61,4 +61,40 @@ if (isPhantomJS) { // polyfill var video = document.createElement("video"); video.constructor.prototype.canPlayType = function () { return ''; }; + + (function () { + var log = console.log; + console.log = function () { + var str = arguments[0]; + str = '' + str; + if (str && str.length > 110) { + log.call(console, "(Can not output this too long log)"); + } + else { + log.apply(console, arguments); + } + } + var warn = console.warn; + console.warn = function () { + var str = arguments[0]; + str = '' + str; + if (str && str.length > 110) { + warn.call(console, "(Can not output this too long warn)"); + } + else { + warn.apply(console, arguments); + } + } + var error = console.error; + console.error = function () { + var str = arguments[0]; + str = '' + str; + if (str && str.length > 110) { + error.call(console, "(Can not output this too long error)"); + } + else { + error.apply(console, arguments); + } + } + })(); } diff --git a/test/qunit/unit/_init.js b/test/qunit/unit/_init.js index 1c627e5738..8ef440b5ca 100644 --- a/test/qunit/unit/_init.js +++ b/test/qunit/unit/_init.js @@ -107,7 +107,7 @@ var TestScript = cc.Class({ } }); -// polyfills to test engine extends +// mocks to test engine extends cc.engine = new (cc.Class({ extends: cc.EventTarget, @@ -121,10 +121,25 @@ cc.engine = new (cc.Class({ } }))(); +(function () { + function beFalse () { + return false; + } + + window._Scene = window._Scene || {}; + _Scene.DetectConflict = { + beforeAddChild: beFalse, + afterAddChild: beFalse, + checkConflict_Layout: beFalse, + checkConflict_Widget: beFalse, + }; +})(); + Editor.log = cc.log; Editor.warn = cc.warn; Editor.error = cc.error; Editor.info = cc.info; +Editor.UuidCache = {}; var assetDir = '../test/qunit/assets'; diff --git a/test/qunit/unit/test-animation.js b/test/qunit/unit/test-animation.js index 7c5c6bb636..6eade7658c 100644 --- a/test/qunit/unit/test-animation.js +++ b/test/qunit/unit/test-animation.js @@ -483,6 +483,8 @@ test('Animation Component', function () { var state = animation.getAnimationState('test'); strictEqual(state.clip, clip, 'should create state with clip'); + strictEqual(state.duration, 10, 'should get state duration'); + animation.play('test'); animation.sample(); strictEqual(entity.x, 0, 'target property should equals value in frame 0s'); diff --git a/test/qunit/unit/test-callbacks-invoker.js b/test/qunit/unit/test-callbacks-invoker.js index 727ae748bb..9eb52a0bde 100644 --- a/test/qunit/unit/test-callbacks-invoker.js +++ b/test/qunit/unit/test-callbacks-invoker.js @@ -1,4 +1,4 @@ -module('CallbacksInvoker'); +largeModule('CallbacksInvoker'); test('test', function () { var ci = new cc._Test.CallbacksInvoker(); @@ -137,6 +137,58 @@ test('remove last with target during invoking', function () { strictEqual(ci.has('eve', cb2, target), false, 'self callback should be removed'); }); +test('remove multiple callbacks during invoking', function () { + var ci = new cc._Test.CallbacksInvoker(); + var cb1 = new Callback().enable(); + var cb2 = new Callback(function () { + ci.remove('eve', cb1); + ci.remove('eve', cb3); + ci.remove('eve', cb3, target); + }).enable(); + var cb3 = new Callback(function () { + ci.remove('eve', cb2, target); + }).enable(); + var target = {}; + ci.add('eve', cb1); + ci.add('eve', cb1, target); + ci.add('eve', cb2, target); + ci.add('eve', cb3); + ci.add('eve', cb3, target); + ci.invoke('eve'); + + cb1.expect(2, 'first callback should be invoked twice'); + cb2.expect(1, 'second callback should be invoked once'); + cb3.expect(2, 'third callback should be invoked twice'); + strictEqual(ci.has('eve', cb1, target), true, 'first callback with target should not be removed'); + strictEqual(ci.has('eve', cb1), false, 'first callback should be removed'); + strictEqual(ci.has('eve', cb2, target), false, 'second callback with target should be removed'); + strictEqual(ci.has('eve', cb3), false, 'third callback should be removed'); + strictEqual(ci.has('eve', cb3, target), false, 'third callback with target should be removed'); +}); + +test('remove all callbacks during invoking', function () { + var ci = new cc._Test.CallbacksInvoker(); + var cb1 = new Callback().enable(); + var cb2 = new Callback(function () { + ci.removeAll('eve'); + }).enable(); + var cb3 = new Callback(function () { + ci.remove('eve', cb2, target); + }).enable(); + var target = {}; + ci.add('eve', cb1); + ci.add('eve', cb1, target); + ci.add('eve', cb2, target); + ci.add('eve', cb3); + ci.add('eve', cb3, target); + ci.invoke('eve'); + + cb1.expect(2, 'first callback should be invoked twice'); + cb2.expect(1, 'second callback should be invoked once'); + cb3.expect(2, 'third callback should be invoked twice'); + strictEqual(ci.has('eve'), false, 'All callbacks should be removed'); +}); + test('CallbacksInvoker support target', function () { var ci = new cc._Test.CallbacksInvoker(); var cb1 = function () { diff --git a/test/qunit/unit/test-load-manager.js b/test/qunit/unit/test-load-manager.js deleted file mode 100644 index f7b7e66398..0000000000 --- a/test/qunit/unit/test-load-manager.js +++ /dev/null @@ -1,68 +0,0 @@ - -module('LoadManager', { - setup: function () { - } -}); - -asyncTest('base', function () { - var dummyAsset = {}; - - var myLoader = function (url, callback, onProgress) { - setTimeout(function () { - cb.enable(); - callback(null, dummyAsset); - }, 1); - }; - - var cb = new Callback(function (err, asset) { - strictEqual(asset, dummyAsset, 'should return the right asset'); - clearTimeout(timerId); - start(); - }); - - LoadManager.loadByLoader(myLoader, '', cb); - - var timerId = setTimeout(function () { - ok(false, 'time out!'); - start(); - }, 100); -}); - -asyncTest('Concurrent', function () { - strictEqual(LoadManager._curConcurrent, 0, 'should finish all tasks'); - LoadManager.maxConcurrent = 1; - - var cb = new Callback().enable(); - var immediateLoader = function (url, callback, onProgress) { - callback(); - }; - - LoadManager.loadByLoader(immediateLoader, '', cb); - cb.once('should load immediate if concurrent < max'); - LoadManager.loadByLoader(immediateLoader, '', cb); - cb.once('should load immediate again'); - - - var asyncLoader = function (url, callback, onProgress) { - setTimeout(function () { - callback(); - }, 1); - }; - - cb.disable('should wait for first loaded'); - // load first - LoadManager.loadByLoader(asyncLoader, '', function () { - cb.enable(); - }); - cb.callbackFunction(function () { - clearTimeout(timerId); - start(); - }); - // deferred load second - LoadManager.loadByLoader(asyncLoader, '', cb); - - var timerId = setTimeout(function () { - ok(false, 'time out!'); - start(); - }, 100); -}); diff --git a/test/qunit/unit/test-loader.js b/test/qunit/unit/test-loader.js new file mode 100644 index 0000000000..d9df38448f --- /dev/null +++ b/test/qunit/unit/test-loader.js @@ -0,0 +1,191 @@ +largeModule('Loader'); + +var loader = cc.loader; + +asyncTest('Load', function () { + var image1 = assetDir + '/button.png'; + var json1 = assetDir + '/library/12/123200.json'; + var json2 = assetDir + '/library/deferred-loading/74/748321.json'; + var resources = [ + image1, + json1, + json2, + ]; + + loader.load(resources, function (completedCount, totalCount, item) { + if (item.src === image1) { + ok(item.content instanceof cc.Texture2D, 'image url\'s result should be Texture2D'); + } + else if (item.src === json1) { + strictEqual(item.content.width, 89, 'should give correct js object as result of JSON'); + } + else if (item.src === json2) { + strictEqual(item.content._rawFiles[0], 'YouKnowEverything', 'should give correct js object as result of JSON'); + } + else { + ok(false, 'should not load an unknown url'); + } + }, function (error, items) { + ok(items.isCompleted(), 'be able to load all resources'); + + loader.releaseAll(); + strictEqual(Object.keys(this.getItems().map).length, 0, 'should clear loading items after releaseAll called'); + + clearTimeout(timeoutId); + start(); + }); + + var timeoutId = setTimeout(function () { + ok(false, 'time out!'); + start(); + }, 5000); +}); + +asyncTest('Load single file', function () { + var image1 = assetDir + '/button.png'; + + loader.load(image1, function (completedCount, totalCount, item) { + if (item.src === image1) { + ok(item.content instanceof cc.Texture2D, 'image url\'s result should be Texture2D'); + } + else { + ok(false, 'should not load an unknown url'); + } + }, function (error, texture) { + ok(!error, 'should not return error'); + ok(texture instanceof cc.Texture2D, 'the single result should be Texture2D'); + + loader.releaseAll(); + clearTimeout(timeoutId); + start(); + }); + + var timeoutId = setTimeout(function () { + ok(false, 'time out!'); + start(); + }, 5000); +}); + +asyncTest('Load with dependencies', function () { + var dep1 = assetDir + '/button.png'; + var dep2 = assetDir + '/library/12/123200.json'; + var dep3 = assetDir + '/library/65/6545543.png'; + + function loadWithDeps (item, callback) { + try { + var result = JSON.parse(item.content); + } + catch (e) { + callback( new Error('JSON Loader: Parse json [' + item.src + '] failed : ' + e) ); + } + var resources = [ + dep1, + dep2, + dep3 + ]; + this.pipeline.flowInDeps(resources, function (deps) { + callback(null, result); + }); + } + + loader.addLoadHandlers({ + 'deps': loadWithDeps + }); + + var json1 = { + src: assetDir + '/library/65/6545543', + type: 'deps' + }; + var json2 = assetDir + '/library/deferred-loading/74/748321.json'; + var audio = assetDir + '/background.mp3'; + var resources = [ + json1, + json2, + audio + ]; + + var total = resources.length; + + var items = loader.getItems(); + + var progressCallback = new Callback(function (completedCount, totalCount, item) { + if (item.src === json1.src) { + var depsLoaded = items.isItemCompleted(dep1) && + items.isItemCompleted(dep2) && + items.isItemCompleted(dep3); + ok(depsLoaded, 'should load all dependencies before complete parent resources'); + var dep = this.getRes(dep1); + ok(dep instanceof cc.Texture2D, 'should correctly load dependent image1'); + dep = this.getRes(dep2); + strictEqual(dep.width, 89, 'should correctly load dependent JSON'); + dep = this.getRes(dep3); + ok(dep instanceof cc.Texture2D, 'should correctly load dependent image2'); + + strictEqual(item.content.__type__, 'TestTexture', 'should give correct js object as result of deps type'); + } + else if (item.src === json2) { + strictEqual(item.content._rawFiles[0], 'YouKnowEverything', 'should give correct js object as result of JSON'); + } + else if (item.src === audio) { + // Test environment doesn't support audio + ok((item.content instanceof cc.Audio) || true, 'audio url\'s result should be Audio'); + } + else { + ok(false, 'should not load an unknown url: ' + item.src); + } + }).enable(); + + loader.load(resources, progressCallback, function (error, items) { + ok(items.isCompleted(), 'be able to load all resources'); + progressCallback.expect(total, 'should call ' + total + ' times progress callback for ' + total + ' resources'); + loader.releaseAll(); + + clearTimeout(timeoutId); + start(); + }); + + var timeoutId = setTimeout(function () { + ok(false, 'time out!'); + start(); + }, 5000); +}); + +asyncTest('Loading font', function () { + var image = assetDir + '/button.png'; + var font = { + src: assetDir + '/Thonburi.ttf', + type: 'font', + name: 'Thonburi', + srcs: [assetDir + '/Thonburi.eot'] + }; + var resources = [ + image, + font + ]; + var total = resources.length; + + var progressCallback = new Callback(function (completedCount, totalCount, item) { + if (item.src === image) { + ok(item.content instanceof cc.Texture2D, 'image url\'s result should be Texture2D'); + } + else if (item.src === font.src) { + strictEqual(item.content, null, 'should set null as content for Font type'); + } + else { + ok(false, 'should not load an unknown url'); + } + }).enable(); + + loader.load(resources, progressCallback, function (error, items) { + ok(items.isCompleted(), 'be able to load all resources'); + progressCallback.expect(total, 'should call ' + total + ' times progress callback for ' + total + ' resources'); + + clearTimeout(timeoutId); + start(); + }); + + var timeoutId = setTimeout(function () { + ok(false, 'time out!'); + start(); + }, 5000); +}); \ No newline at end of file diff --git a/test/qunit/unit/test-node-serialization.js b/test/qunit/unit/test-node-serialization.js index a97fc79fe1..332f26f644 100644 --- a/test/qunit/unit/test-node-serialization.js +++ b/test/qunit/unit/test-node-serialization.js @@ -31,7 +31,6 @@ if (TestEditorExtends) { '_skewY', '_anchorPoint', '_contentSize', - '_ignoreAnchorPointForPosition', 'tag', '_name', '_opacity', @@ -55,7 +54,6 @@ if (TestEditorExtends) { '_active' : getRandomBool(), '_anchorPoint' : cc.p(getRandomDouble(), getRandomDouble()), '_contentSize' : cc.size(getRandomDouble(), getRandomDouble()), - '_ignoreAnchorPointForPosition' : getRandomBool(), 'tag' : getRandomInt(), '_name' : nodeName, '_opacity' : getSpecRandomInt(0, 256), @@ -80,7 +78,6 @@ if (TestEditorExtends) { ret._active = getRandomBool(); ret._anchorPoint = cc.p(getRandomDouble(), getRandomDouble()); ret._contentSize = cc.size(getRandomDouble(), getRandomDouble()); - ret._ignoreAnchorPointForPosition = getRandomBool(); ret.tag = getRandomInt(); ret._name = nodeName; ret._opacity = getSpecRandomInt(0, 256); diff --git a/test/qunit/unit/test-node.js b/test/qunit/unit/test-node.js index 2a6068aa82..d6fa271bd6 100644 --- a/test/qunit/unit/test-node.js +++ b/test/qunit/unit/test-node.js @@ -414,3 +414,13 @@ test('release sg node', function () { strictEqual(parentReleased, true, 'should release parent sg node'); strictEqual(childReleased, true, 'should release child sg node'); }); + +test('getBoundingBox', function () { + var node = new cc.Node(); + node.anchorX = 0.5; + node.anchorY = 0.5; + node.width = 10; + node.height = 20; + + deepEqual(node.getBoundingBox(), cc.rect(-5, -10, 10, 20), 'should compute anchor'); +}); diff --git a/test/qunit/unit/test-pipeline.js b/test/qunit/unit/test-pipeline.js new file mode 100644 index 0000000000..57ea7fa4aa --- /dev/null +++ b/test/qunit/unit/test-pipeline.js @@ -0,0 +1,239 @@ +largeModule('Pipeline'); + +var download = function (item, callback) { + callback(null, null); +}; + +var load = function () {}; + +var pipeline = new cc.Pipeline([ + { + id: 'Downloader', + handle: download, + async: true + }, + { + id: 'Loader', + handle: load, + async: false + } +]); + +test('construction', function () { + var pipes = pipeline._pipes; + + strictEqual(pipes[0].id, 'Downloader', 'should have first pipe id equal to Downloader'); + strictEqual(pipes[1].id, 'Loader', 'should have second pipe id equal to Loader'); + strictEqual(pipes[0].handle, download, 'should have first pipe use download function as handle'); + strictEqual(pipes[1].handle, load, 'should have second pipe use load function as handle'); + strictEqual(pipes[0].async, true, 'should set first pipe asynchronous'); + strictEqual(pipes[1].async, false, 'should set second pipe synchronous'); + strictEqual(pipes[0].pipeline, pipeline, 'should set first pipe\'s pipeline property'); + strictEqual(pipes[1].pipeline, pipeline, 'should set second pipe\'s pipeline property'); + strictEqual(pipes[0].next, pipes[1], 'should set first pipe\'s next as second pipe'); + strictEqual(pipes[1].next, null, 'should set last pipe\' next as null'); +}); + +test('items', function () { + pipeline.flowIn([ + 'res/Background.png', + { + src: 'res/scene.json', + type: 'scene', + name: 'scene' + } + ]); + + var items = pipeline._items.map; + var background = items['res/Background.png']; + var scene = items['res/scene.json']; + + ok(background, 'should have background image'); + ok(scene, 'should have scene'); + strictEqual(background.type, 'png', 'should extract extension as type'); + strictEqual(scene.type, 'scene', 'should use custom type if specified'); + + pipeline.flowIn([ + 'res/scene.json', + 'res/role.plist', + 'res/role.png' + ]); + + var scene2 = items['res/scene.json']; + var role = items['res/role.plist']; + + ok(role, 'can append items'); + strictEqual(scene2, scene, 'shouldn\'t add new item for existing url'); + strictEqual(scene2.name, 'scene', 'should be able to set custom property of item'); + strictEqual(pipeline._items.totalCount, 4, 'should now hold 4 items in total'); + + pipeline.clear(); + strictEqual(pipeline._items.totalCount, 0, 'should hold 0 item after clear'); +}); + +test('pipeline flow', function () { + var download = new Callback(function (item, callback) { + if (!item.type) { + callback('Error'); + } + else { + callback(null, null); + } + }); + var load = new Callback(function () { + return null; + }); + var pipeline = new cc.Pipeline([ + { + id: 'Downloader', + handle: download, + async: true + }, + { + id: 'Loader', + handle: load, + async: false + } + ]); + + var onComplete = new Callback(function (error, items) { + ok(error instanceof Array, 'should return error array in onComplete when error happened'); + strictEqual(error[0], 'res/role', 'should contains correct errored url in error array'); + ok(items.getError('res/role') !== null, 'should set error property in errored item.'); + }).enable(); + var onProgress = new Callback().enable(); + pipeline.onComplete = onComplete; + pipeline.onProgress = onProgress; + + download.enable(); + load.enable(); + + pipeline.flowIn([ + 'res/Background.png', + { + src: 'res/scene.json', + type: 'scene', + name: 'scene' + }, + 'res/role.plist', + 'res/role' + ]); + + strictEqual(pipeline._items.totalCount, 4, 'should now hold 4 items in total'); + strictEqual(pipeline._items.completedCount, 4, 'should complete all 4 items'); + strictEqual(pipeline._items.isCompleted(), true, 'should be completed'); + strictEqual(pipeline.isFlowing(), false, 'should not be flowing now'); + download.expect(4, 'should call download for each item'); + load.expect(3, 'should call load for each item successfully passed from download'); + onComplete.expect(1, 'should call onComplete callback'); + onProgress.expect(4, 'should call onProgress callback 4 times'); +}); + +test('flow empty array', function () { + var onComplete = new Callback(function (error, items) { + strictEqual(error, null, 'shouldn\'t return error after flowIn empty array'); + strictEqual(items.totalCount, 0, 'should contains zero item in items'); + strictEqual(items.completedCount, 0, 'should contains zero completed item'); + }).enable(); + var onProgress = new Callback().enable(); + pipeline.onComplete = onComplete; + pipeline.onProgress = onProgress; + + pipeline.flowIn([]); + + onComplete.expect(1, 'should call onComplete after flowIn empty array'); + onProgress.expect(0, 'shouldn\'t call onProgress after flowIn empty array'); +}); + +asyncTest('content manipulation', function () { + var init = function (item) { + if (!item.type) { + return new Error('No type found'); + } + else { + return item.src; + } + }; + var download = function (item, callback) { + setTimeout(function () { + callback(null, item.content + '_Downloaded'); + }, 1); + }; + var load = function (item) { + return item.content + '_Loaded'; + }; + var pipeline = new cc.Pipeline([ + { + id: 'DataIniter', + handle: init, + async: false + }, + { + id: 'Downloader', + handle: download, + async: true + }, + { + id: 'Loader', + handle: load, + async: false + } + ]); + + pipeline.onComplete = function (error, items) { + ok(true, 'should call onComplete at the end'); + strictEqual(items.completedCount, 4, 'should complete all 4 items'); + strictEqual(items.isCompleted(), true, 'should be completed'); + strictEqual(pipeline.isFlowing(), false, 'should not be flowing now'); + + for (var url in items.map) { + var item = items.map[url]; + if (url === 'res/role') { + strictEqual(item.content, null, 'should have no content in failed item'); + } + else { + strictEqual(item.content, url + '_Downloaded' + '_Loaded', 'should have correct result after pipeline process'); + } + } + clearTimeout(timeoutId); + start(); + }; + var urls = { + 'res/Background.png': 0, + 'res/scene.json': 0, + 'res/role.plist': 0, + 'res/role': 0 + }; + var count = 0; + pipeline.onProgress = function (completed, total, item) { + var url = item.src; + urls[url]++; + if (url === 'res/role') { + ok(item.error instanceof Error, 'should fail on item without type'); + strictEqual(item.states['DataIniter'], cc.Pipeline.ItemState.ERROR, 'should set DataIniter state to ERROR while failed'); + } + else { + strictEqual(item.states['DataIniter'], cc.Pipeline.ItemState.COMPLETE, 'should set DataIniter state to COMPLETE while completed'); + strictEqual(item.states['Downloader'], cc.Pipeline.ItemState.COMPLETE, 'should set Downloader state to COMPLETE while completed'); + strictEqual(item.states['Loader'], cc.Pipeline.ItemState.COMPLETE, 'should set Loader state to COMPLETE while completed'); + } + strictEqual(urls[url], 1, 'should only complete once for each item'); + count++; + strictEqual(completed, count, 'should increase completed count by one'); + }; + + pipeline.flowIn([ + 'res/Background.png', + { + src: 'res/scene.json', + type: 'scene' + }, + 'res/role.plist', + 'res/role' + ]); + + var timeoutId = setTimeout(function () { + ok(false, 'time out!'); + start(); + }, 2); +}); \ No newline at end of file diff --git a/test/qunit/unit/test-prefab.js b/test/qunit/unit/test-prefab.js index 64c1ef5ae5..07b04f84a9 100644 --- a/test/qunit/unit/test-prefab.js +++ b/test/qunit/unit/test-prefab.js @@ -59,8 +59,8 @@ var prefabJson; (function savePrefab () { - prefab = Editor.PrefabUtils.createPrefabFrom(parent); - Editor.PrefabUtils.savePrefabUuid(parent, UUID); + prefab = _Scene.PrefabUtils.createPrefabFrom(parent); + _Scene.PrefabUtils.savePrefabUuid(parent, UUID); // 已经加载好的 prefab,去除类型,去除 runtime node prefabJson = Editor.serialize(prefab); @@ -139,15 +139,20 @@ asyncTest('revert prefab', function () { // stub - var restore = cc.loader.loadTxt; - cc.loader.loadTxt = function (url, callback) { - if (url.endsWith(UUID + '.json')) { - callback(null, JSON.stringify(prefabJson)); + cc.loader.insertPipe({ + id : 'Prefab_Provider', + async : false, + handle : function (item) { + var url = item.src; + if (url === UUID) { + item.states['Downloader'] = cc.Pipeline.ItemState.COMPLETE; + return JSON.stringify(prefabJson); + } + else { + return; + } } - else { - restore(url, callback); - } - }; + }, 0); var testNode = cc.instantiate(prefab); var testChild = testNode.children[0]; @@ -165,8 +170,7 @@ newNode2.parent = testNode; newNode2.setSiblingIndex(0); - Editor.PrefabUtils.revertPrefab(testNode, function () { - cc.loader.loadTxt = restore; + _Scene.PrefabUtils.revertPrefab(testNode, function () { ok(testNode.getScaleX() === 123 && testNode.getScaleY() === 432, 'Revert property of the parent node'); ok(testNode.getComponent(TestScript).constructor === TestScript, 'Restore removed component'); var c = testNode.children[0]; diff --git a/test/qunit/unit/test-record-object.js b/test/qunit/unit/test-record-object.js index 755407bd36..30e5c8e47b 100644 --- a/test/qunit/unit/test-record-object.js +++ b/test/qunit/unit/test-record-object.js @@ -5,15 +5,15 @@ if (TestEditorExtends) { extends: cc.Object }); var obj1 = new Type(); - var record = Editor._recordObject(obj1); + var record = _Scene._UndoImpl.recordObject(obj1); obj1.destroy(); - Editor._restoreObject(obj1, record); + _Scene._UndoImpl.restoreObject(obj1, record); cc.Object._deferredDestroy(); ok(obj1.isValid, 'it should be valid if restored before _deferredDestroy'); obj1.destroy(); cc.Object._deferredDestroy(); - Editor._restoreObject(obj1, record); + _Scene._UndoImpl.restoreObject(obj1, record); ok(obj1.isValid, 'it should be valid if restored after _deferredDestroy'); }); diff --git a/test/qunit/unit/test-serialize-missing-script.js b/test/qunit/unit/test-serialize-missing-script.js index 004b0a39eb..ddd6e847c0 100644 --- a/test/qunit/unit/test-serialize-missing-script.js +++ b/test/qunit/unit/test-serialize-missing-script.js @@ -1,51 +1,56 @@ -//module('Serialize'); -// -//test('deserialize missing script', function() { -// -// var MissingScript = cc.Class({ -// name: 'MissingScript', -// properties: { -// _$erialized: null -// } -// }); -// MissingScript.safeFindClass = function (id) { -// return cc.js._getClassById(id) || MissingScript; -// }; -// -// var ToMiss = cc.Class({ -// name: 'ToMiss', -// properties: { -// ref: null -// } -// }); -// -// var obj = new ToMiss(); -// obj.ref = new cc.Object(); -// -// var lastData = Editor.serialize(obj); -// delete obj.__id__; -// delete obj.ref.__id__; -// cc.js.unregisterClass(ToMiss); -// -// // deserialize -// -// var missed = cc.deserialize(lastData, null, {classFinder: MissingScript.safeFindClass}); -// -// var expectBackup = { -// "__type__": "ToMiss", -// "ref": obj.ref, -// }; -// deepEqual(missed._$erialized, expectBackup, 'can deserialize missing script'); -// -// // serialize -// -// reSerialized = Editor.serialize(missed, {stringify: false}); -// delete obj.ref.__id__; -// deepEqual(reSerialized, JSON.parse(lastData), 'can serialize missing script as its original data'); -// -// //// re deserialize after fixed, no need to test ;) -// //cc.setClassName('ToMiss', ToMiss); -// //var recovered = cc.deserialize(reSerialized); -// //deepEqual(recovered, obj, 'can deserialize correctly after script fixed'); -// //cc.unregisterClass(ToMiss); -//}); +if (TestEditorExtends) { + + largeModule('Serialize'); + + test('deserialize missing script', function () { + + var MissingScript = cc.Class({ + name: 'MissingScript', + properties: { + _$erialized: null + }, + statics: { + safeFindClass: function (id) { + return cc.js._getClassById(id) || MissingScript; + } + } + }); + + var ToMiss = cc.Class({ + name: 'ToMiss', + properties: { + ref: null + } + }); + + var obj = new ToMiss(); + obj.ref = new cc.Object(); + + var lastData = Editor.serialize(obj); + delete obj.__id__; + delete obj.ref.__id__; + cc.js.unregisterClass(ToMiss); + + // deserialize + + var missed = cc.deserialize(lastData, null, {classFinder: MissingScript.safeFindClass}); + + var expectBackup = { + "__type__": "ToMiss", + "ref": obj.ref, + }; + deepEqual(missed._$erialized, expectBackup, 'can deserialize missing script'); + + // serialize + + reSerialized = Editor.serialize(missed, {stringify: false}); + delete obj.ref.__id__; + deepEqual(reSerialized, JSON.parse(lastData), 'can serialize missing script as its original data'); + + //// re deserialize after fixed, no need to test ;) + //cc.setClassName('ToMiss', ToMiss); + //var recovered = cc.deserialize(reSerialized); + //deepEqual(recovered, obj, 'can deserialize correctly after script fixed'); + //cc.unregisterClass(ToMiss); + }); +} \ No newline at end of file diff --git a/test/qunit/unit/test-serialize.js b/test/qunit/unit/test-serialize.js index d39db6e6b0..4694d19200 100644 --- a/test/qunit/unit/test-serialize.js +++ b/test/qunit/unit/test-serialize.js @@ -385,8 +385,8 @@ } } }); - var restore = Editor.urlToUuid; - Editor.urlToUuid = function (url) { + var restore = Editor.UuidCache.urlToUuid; + Editor.UuidCache.urlToUuid = function (url) { return { foo: '01', bar: '02' @@ -412,7 +412,7 @@ }; deepEqual(actual, expected, 'could be serialized'); - Editor.urlToUuid = restore; + Editor.UuidCache.urlToUuid = restore; cc.js.unregisterClass(Data); }); diff --git a/test/qunit/unit/test-spriteRenderer.js b/test/qunit/unit/test-spriteRenderer.js index d5c6108ba1..6e5c743108 100644 --- a/test/qunit/unit/test-spriteRenderer.js +++ b/test/qunit/unit/test-spriteRenderer.js @@ -18,3 +18,325 @@ test('basic test', function () { ok(true); }); + +var generateSpriteFrame = function () { + var url = assetDir + '/button.png'; + var texture = cc.textureCache.addImage(url); + var spriteFrame = new cc.SpriteFrame(); + var rect = cc.rect(10, 10, 40, 60); + var offset = cc.v2(-20, 10); + var originalSize = cc.size(100, 100); + spriteFrame.initWithTexture(texture, rect, false, offset, originalSize); + + return spriteFrame; +}; + +var spriteFrame = generateSpriteFrame(); + +test('simple spriteQuad trimmed', function () { + var testCallBack = function () { + var contentSize = cc.size(100, 100); + var color = cc.color(255, 128, 0, 255); + var isTrimmed = true; + var s9Sprite = new cc.Scale9Sprite(spriteFrame); + s9Sprite.setContentSize(contentSize); + s9Sprite.setColor(color); + s9Sprite.enableTrimmedContentSize(isTrimmed); + s9Sprite.setRenderingType(cc.Scale9Sprite.RenderingType.SIMPLE); + s9Sprite._rebuildQuads(); + var quads = s9Sprite._quads; + strictEqual(quads.length, 1, 'quads number[1] success'); + strictEqual(quads[0]._bl.vertices.x, 0, 'vertex-bl-x test success'); + strictEqual(quads[0]._bl.vertices.y, 0, 'vertex-bl-y test success'); + + strictEqual(quads[0]._tr.vertices.x, contentSize.width, 'vertex-tr-x test success'); + strictEqual(quads[0]._tr.vertices.y, contentSize.height, 'vertex-tr-y test success'); + + deepClose(quads[0]._bl.texCoords.u, 10 / 100, 0.0001, 'texCoords-bl-x test success'); + deepClose(quads[0]._bl.texCoords.v, 70 / 100, 0.0001, 'texCoords-bl-y test success'); + + deepClose(quads[0]._tr.texCoords.u, 50 / 100, 0.0001, 'texCoords-tr-x test success'); + deepClose(quads[0]._tr.texCoords.v, 10 / 100, 0.0001, 'texCoords-tr-y test success'); + }; + if (spriteFrame.textureLoaded()) { + testCallBack(); + } else { + spriteFrame.once('load', testCallBack); + } +}); + +test('simple spriteQuad no trimmed', function () { + var testCallBack = function () { + var contentSize = cc.size(100, 100); + var color = cc.color(255, 128, 0, 255); + var isTrimmed = false; + var s9Sprite = new cc.Scale9Sprite(spriteFrame); + s9Sprite.setContentSize(contentSize); + s9Sprite.setColor(color); + s9Sprite.enableTrimmedContentSize(isTrimmed); + s9Sprite.setRenderingType(cc.Scale9Sprite.RenderingType.SIMPLE); + s9Sprite._rebuildQuads(); + var quads = s9Sprite._quads; + strictEqual(quads.length, 1, 'quads number[1] success'); + strictEqual(quads[0]._bl.vertices.x, 10, 'vertex-bl-x test success'); + strictEqual(quads[0]._bl.vertices.y, 30, 'vertex-bl-y test success'); + + strictEqual(quads[0]._tr.vertices.x, 50, 'vertex-tr-x test success'); + strictEqual(quads[0]._tr.vertices.y, 90, 'vertex-tr-y test success'); + + deepClose(quads[0]._bl.texCoords.u, 10 / 100, 0.0001, 'texCoords-bl-x test success'); + deepClose(quads[0]._bl.texCoords.v, 70 / 100, 0.0001, 'texCoords-bl-y test success'); + + deepClose(quads[0]._tr.texCoords.u, 50 / 100, 0.0001, 'texCoords-tr-x test success'); + deepClose(quads[0]._tr.texCoords.v, 10 / 100, 0.0001, 'texCoords-tr-y test success'); + }; + if (spriteFrame.textureLoaded()) { + testCallBack(); + } else { + spriteFrame.once('load', testCallBack); + } +}); + +test('scale9 spriteQuad trimmed', function () { + var testCallBack = function () { + var contentSize = cc.size(100, 100); + var color = cc.color(255, 128, 0, 255); + var isTrimmed = false; + var s9Sprite = new cc.Scale9Sprite(spriteFrame); + //set border + s9Sprite.setInsetLeft(5); + s9Sprite.setInsetRight(6); + s9Sprite.setInsetBottom(7); + s9Sprite.setInsetTop(8); + + s9Sprite.setContentSize(contentSize); + s9Sprite.setColor(color); + s9Sprite.enableTrimmedContentSize(isTrimmed); + s9Sprite.setRenderingType(cc.Scale9Sprite.RenderingType.SLICED); + s9Sprite._rebuildQuads(); + var quads = s9Sprite._quads; + strictEqual(quads.length, 9, 'quads number[9] success'); + strictEqual(quads[0]._bl.vertices.x, 0, 'x0 test success'); + strictEqual(quads[0]._bl.vertices.y, 0, 'y0 test success'); + + strictEqual(quads[4]._bl.vertices.x, 5, 'x1 test success'); + strictEqual(quads[4]._bl.vertices.y, 7, 'y1 test success'); + + strictEqual(quads[8]._bl.vertices.x, 94, 'x2 test success'); + strictEqual(quads[8]._bl.vertices.y, 92, 'y2 test success'); + + strictEqual(quads[8]._tr.vertices.x, 100, 'x3 test success'); + strictEqual(quads[8]._tr.vertices.y, 100, 'y3 test success'); + + deepClose(quads[0]._bl.texCoords.u, 10 / 100, 0.0001, 'u0 test success'); + deepClose(quads[0]._bl.texCoords.v, 70 / 100, 0.0001, 'v0 test success'); + + deepClose(quads[4]._bl.texCoords.u, 15 / 100, 0.0001, 'u1 test success'); + deepClose(quads[4]._bl.texCoords.v, 63 / 100, 0.0001, 'v1 test success'); + + deepClose(quads[8]._bl.texCoords.u, 44 / 100, 0.0001, 'u2 test success'); + deepClose(quads[8]._bl.texCoords.v, 18 / 100, 0.0001, 'v2 test success'); + + deepClose(quads[8]._tr.texCoords.u, 50 / 100, 0.0001, 'u3 test success'); + deepClose(quads[8]._tr.texCoords.v, 10 / 100, 0.0001, 'v3 test success'); + }; + if (spriteFrame.textureLoaded()) { + testCallBack(); + } else { + spriteFrame.once('load', testCallBack); + } +}); + +test('tiled spriteQuad trimmed', function () { + var testCallBack = function () { + var contentSize = cc.size(100, 100); + var color = cc.color(255, 128, 0, 255); + var isTrimmed = true; + var s9Sprite = new cc.Scale9Sprite(spriteFrame); + s9Sprite.setContentSize(contentSize); + s9Sprite.setColor(color); + s9Sprite.enableTrimmedContentSize(isTrimmed); + s9Sprite.setRenderingType(cc.Scale9Sprite.RenderingType.TILED); + s9Sprite._rebuildQuads(); + var quads = s9Sprite._quads; + strictEqual(quads.length, 6, 'quads number[6] success'); + strictEqual(quads[0]._bl.vertices.x, 0, 'x0 test success'); + strictEqual(quads[2]._bl.vertices.x, 40, 'x1 test success'); + strictEqual(quads[4]._bl.vertices.x, 80, 'x2 test success'); + strictEqual(quads[4]._tr.vertices.x, 100, 'x3 test success'); + + strictEqual(quads[0]._bl.vertices.y, 0, 'y0 test success'); + strictEqual(quads[5]._bl.vertices.y, 60, 'y1 test success'); + strictEqual(quads[5]._tr.vertices.y, 100, 'y2 test success'); + + strictEqual(quads[2]._bl.vertices.x, 40, 'x1 test success'); + strictEqual(quads[2]._bl.vertices.x, 40, 'x1 test success'); + strictEqual(quads[2]._bl.vertices.x, 40, 'x1 test success'); + strictEqual(quads[2]._bl.vertices.x, 40, 'x1 test success'); + // + deepClose(quads[2]._bl.texCoords.u, 10 / 100, 0.0001, 'full quad u0 test success'); + deepClose(quads[2]._bl.texCoords.v, 70 / 100, 0.0001, 'full quad v0 test success'); + + deepClose(quads[2]._tr.texCoords.u, 50 / 100, 0.0001, 'full quad u1 test success'); + deepClose(quads[2]._tr.texCoords.v, 10 / 100, 0.0001, 'full quad v1 test success'); + + deepClose(quads[5]._bl.texCoords.u, 10 / 100, 0.0001, 'part quad u0 test success'); + deepClose(quads[5]._bl.texCoords.v, 70 / 100, 0.0001, 'part quad v0 test success'); + + deepClose(quads[5]._tr.texCoords.u, 30 / 100, 0.0001, 'part quad u1 test success'); + deepClose(quads[5]._tr.texCoords.v, 30 / 100, 0.0001, 'part quad v1 test success'); + }; + if (spriteFrame.textureLoaded()) { + testCallBack(); + } else { + spriteFrame.once('load', testCallBack); + } + +}); + +test('filled-bar-horizontal spriteQuad trimmed', function () { + var testCallBack = function () { + var contentSize = cc.size(100, 100); + var color = cc.color(255, 128, 0, 255); + var isTrimmed = true; + var s9Sprite = new cc.Scale9Sprite(spriteFrame); + s9Sprite.setContentSize(contentSize); + s9Sprite.setColor(color); + s9Sprite.enableTrimmedContentSize(isTrimmed); + s9Sprite.setRenderingType(cc.Scale9Sprite.RenderingType.FILLED); + s9Sprite.setFillType(cc.Scale9Sprite.FillType.HORIZONTAL); + s9Sprite.setFillStart(0.1); + s9Sprite.setFillRange(0.3); + s9Sprite._rebuildQuads(); + var quads = s9Sprite._quads; + strictEqual(quads.length, 1, 'quads number[1] success'); + strictEqual(quads[0]._bl.vertices.x, 10, 'vertex-bl-x test success'); + strictEqual(quads[0]._bl.vertices.y, 0, 'vertex-bl-y test success'); + + strictEqual(quads[0]._tr.vertices.x, 40, 'vertex-tr-x test success'); + strictEqual(quads[0]._tr.vertices.y, 100, 'vertex-tr-y test success'); + + deepClose(quads[0]._bl.texCoords.u, 14 / 100, 0.0001, 'texCoords-bl-x test success'); + deepClose(quads[0]._bl.texCoords.v, 70 / 100, 0.0001, 'texCoords-bl-y test success'); + + deepClose(quads[0]._tr.texCoords.u, 26 / 100, 0.0001, 'texCoords-tr-x test success'); + deepClose(quads[0]._tr.texCoords.v, 10 / 100, 0.0001, 'texCoords-tr-y test success'); + + s9Sprite.setFillStart(0.3); + s9Sprite.setFillRange(-0.4); + s9Sprite._rebuildQuads(); + quads = s9Sprite._quads; + strictEqual(quads.length, 1, 'quads number[1] success'); + strictEqual(quads[0]._bl.vertices.x, 0, 'vertex-bl-x test success'); + strictEqual(quads[0]._bl.vertices.y, 0, 'vertex-bl-y test success'); + + strictEqual(quads[0]._tr.vertices.x, 30, 'vertex-tr-x test success'); + strictEqual(quads[0]._tr.vertices.y, 100, 'vertex-tr-y test success'); + + deepClose(quads[0]._bl.texCoords.u, 10 / 100, 0.0001, 'texCoords-bl-x test success'); + deepClose(quads[0]._bl.texCoords.v, 70 / 100, 0.0001, 'texCoords-bl-y test success'); + + deepClose(quads[0]._tr.texCoords.u, 22 / 100, 0.0001, 'texCoords-tr-x test success'); + deepClose(quads[0]._tr.texCoords.v, 10 / 100, 0.0001, 'texCoords-tr-y test success'); + }; + if (spriteFrame.textureLoaded()) { + testCallBack(); + } else { + spriteFrame.once('load', testCallBack); + } +}); + +test('filled-bar-vertical spriteQuad trimmed', function () { + var testCallBack = function () { + var contentSize = cc.size(100, 100); + var color = cc.color(255, 128, 0, 255); + var isTrimmed = true; + var s9Sprite = new cc.Scale9Sprite(spriteFrame); + s9Sprite.setContentSize(contentSize); + s9Sprite.setColor(color); + s9Sprite.enableTrimmedContentSize(isTrimmed); + s9Sprite.setRenderingType(cc.Scale9Sprite.RenderingType.FILLED); + s9Sprite.setFillType(cc.Scale9Sprite.FillType.VERTICAL); + s9Sprite.setFillStart(0.1); + s9Sprite.setFillRange(0.3); + s9Sprite._rebuildQuads(); + var quads = s9Sprite._quads; + strictEqual(quads.length, 1, 'quads number[1] success'); + strictEqual(quads[0]._bl.vertices.x, 0, 'vertex-bl-x test success'); + strictEqual(quads[0]._bl.vertices.y, 10, 'vertex-bl-y test success'); + + strictEqual(quads[0]._tr.vertices.x, 100, 'vertex-tr-x test success'); + strictEqual(quads[0]._tr.vertices.y, 40, 'vertex-tr-y test success'); + + deepClose(quads[0]._bl.texCoords.u, 10 / 100, 0.0001, 'texCoords-bl-x test success'); + deepClose(quads[0]._bl.texCoords.v, 64 / 100, 0.0001, 'texCoords-bl-y test success'); + + deepClose(quads[0]._tr.texCoords.u, 50 / 100, 0.0001, 'texCoords-tr-x test success'); + deepClose(quads[0]._tr.texCoords.v, 46 / 100, 0.0001, 'texCoords-tr-y test success'); + + s9Sprite.setFillStart(0.3); + s9Sprite.setFillRange(-0.4); + s9Sprite._rebuildQuads(); + quads = s9Sprite._quads; + strictEqual(quads.length, 1, 'quads number[1] success'); + strictEqual(quads[0]._bl.vertices.x, 0, 'vertex-bl-x test success'); + strictEqual(quads[0]._bl.vertices.y, 0, 'vertex-bl-y test success'); + + strictEqual(quads[0]._tr.vertices.x, 100, 'vertex-tr-x test success'); + strictEqual(quads[0]._tr.vertices.y, 30, 'vertex-tr-y test success'); + + deepClose(quads[0]._bl.texCoords.u, 10 / 100, 0.0001, 'texCoords-bl-x test success'); + deepClose(quads[0]._bl.texCoords.v, 70 / 100, 0.0001, 'texCoords-bl-y test success'); + + deepClose(quads[0]._tr.texCoords.u, 50 / 100, 0.0001, 'texCoords-tr-x test success'); + deepClose(quads[0]._tr.texCoords.v, 52 / 100, 0.0001, 'texCoords-tr-y test success'); + }; + if (spriteFrame.textureLoaded()) { + testCallBack(); + } else { + spriteFrame.once('load', testCallBack); + } +}); + +test('filled-bar-radial spriteQuad trimmed', function () { + var testCallBack = function () { + var contentSize = cc.size(100, 100); + var color = cc.color(255, 128, 0, 255); + var isTrimmed = true; + var s9Sprite = new cc.Scale9Sprite(spriteFrame); + s9Sprite.setContentSize(contentSize); + s9Sprite.setColor(color); + s9Sprite.enableTrimmedContentSize(isTrimmed); + s9Sprite.setRenderingType(cc.Scale9Sprite.RenderingType.FILLED); + s9Sprite.setFillType(cc.Scale9Sprite.FillType.RADIAL); + s9Sprite.setFillCenter(0.5, 0.5); + s9Sprite.setFillStart(0.0); + s9Sprite.setFillRange(1 / 4); + s9Sprite._rebuildQuads(); + var quads = s9Sprite._quads; + strictEqual(s9Sprite._isTriangle, true, "Triangles used"); + strictEqual(quads.length, 2, 'triangles number[2] success'); + + var center = cc.v2(50, 50); + var p0 = cc.v2(100, 50); + var p1 = cc.v2(100, 100); + var p2 = cc.v2(50, 100); + + deepClose(quads[1]._tl.vertices.x, center.x, 0.0001, 'center test success'); + deepClose(quads[1]._tl.vertices.y, center.y, 0.0001, 'center test success'); + + deepClose(quads[0]._bl.vertices.x, p0.x, 0.0001, 'p0 test success'); + deepClose(quads[0]._bl.vertices.y, p0.y, 0.0001, 'p0 test success'); + + deepClose(quads[1]._bl.vertices.x, p1.x, 0.0001, 'p1 test success'); + deepClose(quads[1]._bl.vertices.y, p1.y, 0.0001, 'p1 test success'); + + deepClose(quads[1]._tr.vertices.x, p2.x, 0.0001, 'p2 test success'); + deepClose(quads[1]._tr.vertices.y, p2.y, 0.0001, 'p2 test success'); + }; + if (spriteFrame.textureLoaded()) { + testCallBack(); + } else { + spriteFrame.once('load', testCallBack); + } +}); diff --git a/test/visual-tests/main.js b/test/visual-tests/main.js index 789dc19e82..ffb7e4f6ff 100644 --- a/test/visual-tests/main.js +++ b/test/visual-tests/main.js @@ -116,7 +116,6 @@ cc.game.run({ "src/tests-main.js", "src/PathTest/PathTest.js", - "src/LoaderTest/LoaderTest.js", "src/BakeLayerTest/BakeLayerTest.js", @@ -189,10 +188,6 @@ cc.game.run({ } jsb.fileUtils.setSearchPaths(searchPaths); } - else - { - cc.loader.resPath = 'res'; - } cc.LoaderScene.preload(g_resources, function () { if(window.sideIndexBar && typeof sideIndexBar.start === 'function'){ diff --git a/test/visual-tests/src/ActionsTest/ActionsTest.js b/test/visual-tests/src/ActionsTest/ActionsTest.js index 5bcab05269..a10a409ede 100644 --- a/test/visual-tests/src/ActionsTest/ActionsTest.js +++ b/test/visual-tests/src/ActionsTest/ActionsTest.js @@ -73,20 +73,20 @@ var ActionsDemo = BaseTestLayer.extend({ this._tamara.visible = false; this._kathia.visible = false; this._grossini.visible = false; - } else if (numberOfSprites == 1) { + } else if (numberOfSprites === 1) { this._tamara.visible = false; this._kathia.visible = false; this._grossini.x = winSize.width / 2; this._grossini.y = winSize.height / 2; } - else if (numberOfSprites == 2) { + else if (numberOfSprites === 2) { this._kathia.x = winSize.width / 3; this._kathia.y = winSize.height / 2; this._tamara.x = 2 * winSize.width / 3; this._tamara.y = winSize.height / 2; this._grossini.visible = false; } - else if (numberOfSprites == 3) { + else if (numberOfSprites === 3) { this._grossini.x = winSize.width / 2; this._grossini.y = winSize.height / 2; this._tamara.x = winSize.width / 4; @@ -974,7 +974,7 @@ var ActionAnimate = ActionsDemo.extend({ // var animation = new cc.SpriteFrameAnimation(); for (var i = 1; i < 15; i++) { - var frameName = "Images/grossini_dance_" + ((i < 10) ? ("0" + i) : i) + ".png"; + var frameName = "res/Images/grossini_dance_" + ((i < 10) ? ("0" + i) : i) + ".png"; animation.addSpriteFrameWithFile(frameName); } animation.setDelayPerUnit(2.8 / 14); @@ -1668,7 +1668,7 @@ var ActionFollow = ActionsDemo.extend({ this._grossini.runAction(rep); - this.runAction(cc.follow(this._grossini, cc.rect(0, 0, s.width * 2 - 100, s.height))); + this.runAction(cc.follow(this._grossini)); //----end30---- }, subtitle:function () { @@ -2515,7 +2515,7 @@ var Issue1438 = ActionsDemo.extend({ // Add 60 frames for (var j = 0; j < 4; j++) { for (var i = 1; i < 15; i++) { - var frameName = "Images/grossini_dance_" + ((i < 10) ? ("0" + i) : i) + ".png"; + var frameName = "res/Images/grossini_dance_" + ((i < 10) ? ("0" + i) : i) + ".png"; animation.addSpriteFrameWithFile(frameName); } } @@ -2837,7 +2837,7 @@ var ActionCustomTest = ActionsDemo.extend({ spriteTemp = this.addandCreateSpriteTemp("cc.Animate"); var animation = new cc.SpriteFrameAnimation(); for (var i = 1; i < 15; i++) { - var frameName = "Images/grossini_dance_" + ((i < 10) ? ("0" + i) : i) + ".png"; + var frameName = "res/Images/grossini_dance_" + ((i < 10) ? ("0" + i) : i) + ".png"; animation.addSpriteFrameWithFile(frameName); } animation.setDelayPerUnit(5 / 14); diff --git a/test/visual-tests/src/CocosDenshionTest/CocosDenshionTest.js b/test/visual-tests/src/CocosDenshionTest/CocosDenshionTest.js index 1a2373ac1c..dbd45cec78 100644 --- a/test/visual-tests/src/CocosDenshionTest/CocosDenshionTest.js +++ b/test/visual-tests/src/CocosDenshionTest/CocosDenshionTest.js @@ -26,8 +26,8 @@ var audioEngine = cc.audioEngine; -var MUSIC_FILE = cc.sys.os == cc.sys.OS_WINRT ? "background.wav" : "background.mp3"; -var EFFECT_FILE = cc.sys.os == cc.sys.OS_WINRT ? "effect1.wav" : "effect2.mp3"; +var MUSIC_FILE = "res/background.mp3"; +var EFFECT_FILE = "res/effect2.mp3"; var _DenshionTests = [ 'Music Test' diff --git a/test/visual-tests/src/EaseActionsTest/EaseActionsTest.js b/test/visual-tests/src/EaseActionsTest/EaseActionsTest.js index 78f70d93a4..ddf6000972 100644 --- a/test/visual-tests/src/EaseActionsTest/EaseActionsTest.js +++ b/test/visual-tests/src/EaseActionsTest/EaseActionsTest.js @@ -738,7 +738,7 @@ var SchedulerTest = EaseSpriteDemo.extend({ var emitter = new cc.ParticleFireworks(); emitter.setTotalParticles(250); - emitter.texture = cc.textureCache.addImage("Images/fire.png"); + emitter.texture = cc.textureCache.addImage("res/Images/fire.png"); this.addChild(emitter); //----end13---- }, diff --git a/test/visual-tests/src/ExtensionsTest/AssetsManagerTest/AssetsManagerTest.js b/test/visual-tests/src/ExtensionsTest/AssetsManagerTest/AssetsManagerTest.js index 707303441d..0bb3ce32db 100644 --- a/test/visual-tests/src/ExtensionsTest/AssetsManagerTest/AssetsManagerTest.js +++ b/test/visual-tests/src/ExtensionsTest/AssetsManagerTest/AssetsManagerTest.js @@ -39,7 +39,6 @@ var AssetsManagerTestLayer = BaseTestLayer.extend({ ctor : function (spritePath) { this._super(); this._spritePath = spritePath; - cc.loader.resPath = "../cpp-tests/Resources/"; }, getTitle : function() { diff --git a/test/visual-tests/src/ExtensionsTest/S9SpriteTest/S9SpriteTest.js b/test/visual-tests/src/ExtensionsTest/S9SpriteTest/S9SpriteTest.js index d6f267b308..29b589c714 100644 --- a/test/visual-tests/src/ExtensionsTest/S9SpriteTest/S9SpriteTest.js +++ b/test/visual-tests/src/ExtensionsTest/S9SpriteTest/S9SpriteTest.js @@ -111,7 +111,7 @@ var S9CreationTest = S9SpriteTestDemo.extend({ var x = winSize.width; var y = 0 + (winSize.height/2); - var s9sprite1 = new cc.Scale9Sprite("Images/blocks.png"); + var s9sprite1 = new cc.Scale9Sprite("res/Images/blocks.png"); var s9sprite2 = new cc.Scale9Sprite("blocks9.png"); diff --git a/test/visual-tests/src/LabelTest/LabelTest.js b/test/visual-tests/src/LabelTest/LabelTest.js index 66dff62e48..02fb0fe84f 100644 --- a/test/visual-tests/src/LabelTest/LabelTest.js +++ b/test/visual-tests/src/LabelTest/LabelTest.js @@ -98,13 +98,13 @@ var LabelAtlasOpacityTest = AtlasDemo.extend({ this._super(); this.time = 0; - var label1 = new cc.LabelAtlas("123 Test", s_resprefix + "fonts/tuffy_bold_italic-charmap.plist"); + var label1 = new cc.LabelAtlas("123 Test", "res/fonts/tuffy_bold_italic-charmap.plist"); this.addChild(label1, 0, TAG_LABEL_SPRITE1); label1.x = 10; label1.y = 100; label1.opacity = 200; - var label2 = new cc.LabelAtlas("0123456789", s_resprefix + "fonts/tuffy_bold_italic-charmap.plist"); + var label2 = new cc.LabelAtlas("0123456789", "res/fonts/tuffy_bold_italic-charmap.plist"); this.addChild(label2, 0, TAG_LABEL_SPRITE12); label2.x = 10; label2.y = 200; @@ -164,13 +164,13 @@ var LabelAtlasOpacityColorTest = AtlasDemo.extend({ ctor:function () { //----start1----ctor this._super(); - var label1 = new cc.LabelAtlas("123 Test", s_resprefix + "fonts/tuffy_bold_italic-charmap.png", 48, 64, ' '); + var label1 = new cc.LabelAtlas("123 Test", "res/fonts/tuffy_bold_italic-charmap.png", 48, 64, ' '); this.addChild(label1, 0, TAG_LABEL_SPRITE1); label1.x = 10; label1.y = 100; label1.opacity = 200; - var label2 = new cc.LabelAtlas("0123456789", s_resprefix + "fonts/tuffy_bold_italic-charmap.png", 48, 64, ' '); + var label2 = new cc.LabelAtlas("0123456789", "res/fonts/tuffy_bold_italic-charmap.png", 48, 64, ' '); this.addChild(label2, 0, TAG_LABEL_SPRITE12); label2.x = 10; label2.y = 200; @@ -242,7 +242,7 @@ var LabelAtlasHD = AtlasDemo.extend({ var s = director.getWinSize(); // cc.LabelBMFont - var label1 = new cc.LabelAtlas("TESTING RETINA DISPLAY", s_resprefix + "fonts/larabie-16.plist"); + var label1 = new cc.LabelAtlas("TESTING RETINA DISPLAY", "res/fonts/larabie-16.plist"); label1.anchorX = 0.5; label1.anchorY = 0.5; @@ -298,7 +298,7 @@ var BMFontOpacityColorAlignmentTest = AtlasDemo.extend({ var col = new cc.LayerColor(cc.color(128, 128, 128, 255)); this.addChild(col, -10); - var label1 = new cc.LabelBMFont("Test", s_resprefix + "fonts/bitmapFontTest2.fnt"); + var label1 = new cc.LabelBMFont("Test", "res/fonts/bitmapFontTest2.fnt"); // testing anchors label1.anchorX = 0; @@ -314,7 +314,7 @@ var BMFontOpacityColorAlignmentTest = AtlasDemo.extend({ // color and opacity work OK because bitmapFontAltas2 loads a BMP image (not a PNG image) // If you want to use both opacity and color, it is recommended to use NON premultiplied images like BMP images // Of course, you can also tell XCode not to compress PNG images, but I think it doesn't work as expected - var label2 = new cc.LabelBMFont("Test", s_resprefix + "fonts/bitmapFontTest2.fnt"); + var label2 = new cc.LabelBMFont("Test", "res/fonts/bitmapFontTest2.fnt"); // testing anchors label2.anchorX = 0.5; label2.anchorY = 0.5; @@ -322,7 +322,7 @@ var BMFontOpacityColorAlignmentTest = AtlasDemo.extend({ this.addChild(label2, 0, TAG_BITMAP_ATLAS2); label2.runAction(repeat.clone()); - var label3 = new cc.LabelBMFont("Test", s_resprefix + "fonts/bitmapFontTest2.fnt"); + var label3 = new cc.LabelBMFont("Test", "res/fonts/bitmapFontTest2.fnt"); // testing anchors label3.anchorX = 1; label3.anchorY = 1; @@ -408,7 +408,7 @@ var BMFontSubSpriteTest = AtlasDemo.extend({ drawNode.drawSegment(cc.p(s.width / 2, 0), cc.p(s.width / 2, s.height), 2); // Upper Label - var label = new cc.LabelBMFont("Bitmap Font Atlas", s_resprefix + "fonts/bitmapFontTest.fnt"); + var label = new cc.LabelBMFont("Bitmap Font Atlas", "res/fonts/bitmapFontTest.fnt"); this.labelObj = label; this.addChild(label); @@ -453,7 +453,7 @@ var BMFontSubSpriteTest = AtlasDemo.extend({ AChar.runAction(fade_4ever); // Bottom Label - var label2 = new cc.LabelBMFont("00.0", s_resprefix + "fonts/bitmapFontTest.fnt"); + var label2 = new cc.LabelBMFont("00.0", "res/fonts/bitmapFontTest.fnt"); this.addChild(label2, 0, TAG_BITMAP_ATLAS2); label2.x = s.width / 2.0; label2.y = 80; @@ -510,7 +510,7 @@ var BMFontPaddingTest = AtlasDemo.extend({ ctor:function () { //----start5---- this._super(); - var label = new cc.LabelBMFont("abcdefg", s_resprefix + "fonts/bitmapFontTest4.fnt"); + var label = new cc.LabelBMFont("abcdefg", "res/fonts/bitmapFontTest4.fnt"); this.addChild(label); var s = director.getWinSize(); @@ -563,21 +563,21 @@ var BMFontOffsetTest = AtlasDemo.extend({ var s = director.getWinSize(); var label = null; - label = new cc.LabelBMFont("FaFeFiFoFu", s_resprefix + "fonts/bitmapFontTest5.fnt"); + label = new cc.LabelBMFont("FaFeFiFoFu", "res/fonts/bitmapFontTest5.fnt"); this.addChild(label); label.x = s.width / 2; label.y = s.height / 2 + 50; label.anchorX = 0.5; label.anchorY = 0.5; - label = new cc.LabelBMFont("fafefifofu", s_resprefix + "fonts/bitmapFontTest5.fnt"); + label = new cc.LabelBMFont("fafefifofu", "res/fonts/bitmapFontTest5.fnt"); this.addChild(label); label.x = s.width / 2; label.y = s.height / 2; label.anchorX = 0.5; label.anchorY = 0.5; - label = new cc.LabelBMFont("aeiou", s_resprefix + "fonts/bitmapFontTest5.fnt"); + label = new cc.LabelBMFont("aeiou", "res/fonts/bitmapFontTest5.fnt"); this.addChild(label); label.x = s.width / 2; label.y = s.height / 2 - 50; @@ -628,7 +628,7 @@ var BMFontTintTest = AtlasDemo.extend({ var s = director.getWinSize(); var label = null; - label = new cc.LabelBMFont("Blue", s_resprefix + "fonts/bitmapFontTest5.fnt"); + label = new cc.LabelBMFont("Blue", "res/fonts/bitmapFontTest5.fnt"); label.color = cc.color(0, 0, 255); this.addChild(label); label.x = s.width / 2; @@ -636,7 +636,7 @@ var BMFontTintTest = AtlasDemo.extend({ label.anchorX = 0.5; label.anchorY = 0.5; - label = new cc.LabelBMFont("Red", s_resprefix + "fonts/bitmapFontTest5.fnt"); + label = new cc.LabelBMFont("Red", "res/fonts/bitmapFontTest5.fnt"); this.addChild(label); label.x = s.width / 2; label.y = 2 * s.height / 4; @@ -644,7 +644,7 @@ var BMFontTintTest = AtlasDemo.extend({ label.anchorY = 0.5; label.color = cc.color(255, 0, 0); - label = new cc.LabelBMFont("G", s_resprefix + "fonts/bitmapFontTest5.fnt"); + label = new cc.LabelBMFont("G", "res/fonts/bitmapFontTest5.fnt"); this.addChild(label); label.x = s.width / 2; label.y = 3 * s.height / 4; @@ -698,7 +698,7 @@ var BMFontSpeedTest = AtlasDemo.extend({ // Upper Label for (var i = 0; i < 100; i++) { var str = "-" + i + "-"; - var label = new cc.LabelBMFont(str, s_resprefix + "fonts/bitmapFontTest.fnt"); + var label = new cc.LabelBMFont(str, "res/fonts/bitmapFontTest.fnt"); this.addChild(label); var s = director.getWinSize(); @@ -729,7 +729,7 @@ var BMFontMultiLineTest = AtlasDemo.extend({ this._super(); // Left - var label1 = new cc.LabelBMFont("Multi line\nLeft", s_resprefix + "fonts/bitmapFontTest3.fnt"); + var label1 = new cc.LabelBMFont("Multi line\nLeft", "res/fonts/bitmapFontTest3.fnt"); label1.anchorX = 0; label1.anchorY = 0; this.addChild(label1, 0, TAG_BITMAP_ATLAS1); @@ -737,14 +737,14 @@ var BMFontMultiLineTest = AtlasDemo.extend({ // Center - var label2 = new cc.LabelBMFont("Multi line\nCenter", s_resprefix + "fonts/bitmapFontTest3.fnt"); + var label2 = new cc.LabelBMFont("Multi line\nCenter", "res/fonts/bitmapFontTest3.fnt"); label2.anchorX = 0.5; label2.anchorY = 0.5; this.addChild(label2, 0, TAG_BITMAP_ATLAS2); cc.log("content size:" + label2.width + "," + label2.height); // right - var label3 = new cc.LabelBMFont("Multi line\nRight\nThree lines Three", s_resprefix + "fonts/bitmapFontTest3.fnt"); + var label3 = new cc.LabelBMFont("Multi line\nRight\nThree lines Three", "res/fonts/bitmapFontTest3.fnt"); label3.anchorX = 1; label3.anchorY = 1; this.addChild(label3, 0, TAG_BITMAP_ATLAS3); @@ -804,7 +804,7 @@ var BMFontMultiLine2Test = AtlasDemo.extend({ this._super(); // Left - var label1 = new cc.LabelBMFont("Multi line\n\nAligned to the left", s_resprefix + "fonts/bitmapFontTest3.fnt"); + var label1 = new cc.LabelBMFont("Multi line\n\nAligned to the left", "res/fonts/bitmapFontTest3.fnt"); label1.anchorX = 0; label1.anchorY = 0; label1.textAlign = cc.TextAlignment.LEFT; @@ -814,7 +814,7 @@ var BMFontMultiLine2Test = AtlasDemo.extend({ // Center - var label2 = new cc.LabelBMFont("Error\n\nSome error message", s_resprefix + "fonts/bitmapFontTest3.fnt"); + var label2 = new cc.LabelBMFont("Error\n\nSome error message", "res/fonts/bitmapFontTest3.fnt"); label2.anchorX = 0.5; label2.anchorY = 0.5; label2.textAlign = cc.TextAlignment.CENTER; @@ -823,7 +823,7 @@ var BMFontMultiLine2Test = AtlasDemo.extend({ cc.log("content size:" + label2.width + "," + label2.height); // right - var label3 = new cc.LabelBMFont("Multi line\n\nAligned to the right", s_resprefix + "fonts/bitmapFontTest3.fnt"); + var label3 = new cc.LabelBMFont("Multi line\n\nAligned to the right", "res/fonts/bitmapFontTest3.fnt"); label3.anchorX = 1; label3.anchorY = 1; label3.textAlign = cc.TextAlignment.RIGHT; @@ -884,7 +884,7 @@ var LabelsEmpty = AtlasDemo.extend({ // cc.LabelBMFont - var label1 = new cc.LabelBMFont("", s_resprefix + "fonts/bitmapFontTest3.fnt"); + var label1 = new cc.LabelBMFont("", "res/fonts/bitmapFontTest3.fnt"); this.addChild(label1, 0, TAG_BITMAP_ATLAS1); label1.x = winSize.width / 2; label1.y = winSize.height - 100; @@ -896,7 +896,7 @@ var LabelsEmpty = AtlasDemo.extend({ label2.y = winSize.height / 2; // cc.LabelAtlas - var label3 = new cc.LabelAtlas("", s_resprefix + "fonts/tuffy_bold_italic-charmap.png", 48, 64, ' '); + var label3 = new cc.LabelAtlas("", "res/fonts/tuffy_bold_italic-charmap.png", 48, 64, ' '); this.addChild(label3, 0, TAG_BITMAP_ATLAS3); label3.x = winSize.width / 2; label3.y = 0 + 100; @@ -948,7 +948,7 @@ var BMFontHDTest = AtlasDemo.extend({ var s = director.getWinSize(); // cc.LabelBMFont - var label1 = new cc.LabelBMFont("TESTING RETINA DISPLAY", s_resprefix + "fonts/konqa32.fnt"); + var label1 = new cc.LabelBMFont("TESTING RETINA DISPLAY", "res/fonts/konqa32.fnt"); this.addChild(label1); label1.x = s.width / 2; label1.y = s.height / 2; @@ -1001,7 +1001,7 @@ var BMFontGlyphDesignerTest = AtlasDemo.extend({ this.addChild(layer, -10); // cc.LabelBMFont - var label1 = new cc.LabelBMFont("Testing Glyph Designer", s_resprefix + "fonts/futura-48.fnt"); + var label1 = new cc.LabelBMFont("Testing Glyph Designer", "res/fonts/futura-48.fnt"); this.addChild(label1); label1.x = s.width / 2; label1.y = s.height / 2; @@ -1354,7 +1354,7 @@ var BMFontChineseTest = AtlasDemo.extend({ //----start18----ctor this._super(); var size = director.getWinSize(); - var label = new cc.LabelBMFont("中国", s_resprefix + "fonts/bitmapFontChinese.fnt"); + var label = new cc.LabelBMFont("中国", "res/fonts/bitmapFontChinese.fnt"); label.x = size.width / 2; label.y = size.height / 2; this.addChild(label); @@ -1449,9 +1449,9 @@ var BMFontMultiLineAlignmentTest = AtlasDemo.extend({ var size = director.getWinSize(); // create and initialize a Label - this.labelShouldRetain = new cc.LabelBMFont(LongSentencesExample, s_resprefix + "fonts/markerFelt.fnt", size.width / 2, cc.TextAlignment.CENTER, cc.p(0, 0)); - this.arrowsBarShouldRetain = new _ccsg.Sprite(s_resprefix + "Images/arrowsBar.png"); - this.arrowsShouldRetain = new _ccsg.Sprite(s_resprefix + "Images/arrows.png"); + this.labelShouldRetain = new cc.LabelBMFont(LongSentencesExample, "res/fonts/markerFelt.fnt", size.width / 2, cc.TextAlignment.CENTER, cc.p(0, 0)); + this.arrowsBarShouldRetain = new _ccsg.Sprite("res/Images/arrowsBar.png"); + this.arrowsShouldRetain = new _ccsg.Sprite("res/Images/arrows.png"); cc.MenuItemFont.setFontSize(20); var longSentences = new cc.MenuItemFont("Long Flowing Sentences", this.onStringChanged, this); @@ -1558,26 +1558,26 @@ var BMFontMultiLineAlignmentTest = AtlasDemo.extend({ switch (sender.tag) { case LongSentences: this.labelShouldRetain.setString(LongSentencesExample); - this.labelShouldRetain.setFntFile(s_resprefix + "fonts/markerFelt.fnt"); + this.labelShouldRetain.setFntFile("res/fonts/markerFelt.fnt"); break; case LineBreaks: this.labelShouldRetain.setString(LineBreaksExample); - this.labelShouldRetain.setFntFile(s_resprefix + "fonts/markerFelt.fnt"); + this.labelShouldRetain.setFntFile("res/fonts/markerFelt.fnt"); break; case Mixed: this.labelShouldRetain.setString(MixedExample); - this.labelShouldRetain.setFntFile(s_resprefix + "fonts/markerFelt.fnt"); + this.labelShouldRetain.setFntFile("res/fonts/markerFelt.fnt"); break; case chineseText: - this.labelShouldRetain.setFntFile(s_resprefix + "fonts/arial-unicode-26.fnt"); + this.labelShouldRetain.setFntFile("res/fonts/arial-unicode-26.fnt"); this.labelShouldRetain.setString(chineseExampleText); break; case chineseMixEnglish: - this.labelShouldRetain.setFntFile(s_resprefix + "fonts/arial-unicode-26.fnt"); + this.labelShouldRetain.setFntFile("res/fonts/arial-unicode-26.fnt"); this.labelShouldRetain.setString(chineseMixEnglishText); break; case mixAllLanguage: - this.labelShouldRetain.setFntFile(s_resprefix + "fonts/arial-unicode-26.fnt"); + this.labelShouldRetain.setFntFile("res/fonts/arial-unicode-26.fnt"); this.labelShouldRetain.setString(mixAllLanguageText); break; default: @@ -1698,12 +1698,12 @@ var BMFontOneAtlas = AtlasDemo.extend({ this._super(); var s = director.getWinSize(); - var label1 = new cc.LabelBMFont("This is Helvetica", s_resprefix + "fonts/helvetica-32.fnt", cc.LabelAutomaticWidth, cc.TextAlignment.LEFT, cc.p(0, 0)); + var label1 = new cc.LabelBMFont("This is Helvetica", "res/fonts/helvetica-32.fnt", cc.LabelAutomaticWidth, cc.TextAlignment.LEFT, cc.p(0, 0)); this.addChild(label1); label1.x = s.width / 2; label1.y = s.height * 2 / 3; - var label2 = new cc.LabelBMFont("And this is Geneva", s_resprefix + "fonts/geneva-32.fnt", cc.LabelAutomaticWidth, cc.TextAlignment.LEFT, cc.p(0, 128)); + var label2 = new cc.LabelBMFont("And this is Geneva", "res/fonts/geneva-32.fnt", cc.LabelAutomaticWidth, cc.TextAlignment.LEFT, cc.p(0, 128)); this.addChild(label2); label2.x = s.width / 2; label2.y = s.height / 3; @@ -1728,17 +1728,17 @@ var BMFontUnicode = AtlasDemo.extend({ var japanese = "良い一日を"; var spanish = "Buen día"; - var label1 = new cc.LabelBMFont(spanish, s_resprefix + "fonts/arial-unicode-26.fnt", 200, cc.TextAlignment.LEFT); + var label1 = new cc.LabelBMFont(spanish, "res/fonts/arial-unicode-26.fnt", 200, cc.TextAlignment.LEFT); this.addChild(label1); label1.x = winSize.width / 2; label1.y = winSize.height / 4; - var label2 = new cc.LabelBMFont(chinese, s_resprefix + "fonts/arial-unicode-26.fnt"); + var label2 = new cc.LabelBMFont(chinese, "res/fonts/arial-unicode-26.fnt"); this.addChild(label2); label2.x = winSize.width / 2; label2.y = winSize.height / 2.2; - var label3 = new cc.LabelBMFont(japanese, s_resprefix + "fonts/arial-unicode-26.fnt"); + var label3 = new cc.LabelBMFont(japanese, "res/fonts/arial-unicode-26.fnt"); this.addChild(label3); label3.x = winSize.width / 2; label3.y = winSize.height / 1.5; @@ -1759,7 +1759,7 @@ var BMFontInit = AtlasDemo.extend({ this._super(); var bmFont = new cc.LabelBMFont(); - bmFont.setFntFile(s_resprefix + "fonts/helvetica-32.fnt"); + bmFont.setFntFile("res/fonts/helvetica-32.fnt"); bmFont.setString("It is working!"); this.addChild(bmFont); bmFont.x = winSize.width / 2; @@ -1857,7 +1857,7 @@ var BMFontColorParentChild = AtlasDemo.extend({ //----start15----ctor this._super(); - this.label = new cc.LabelBMFont("YRGB", s_resprefix + "fonts/konqa32.fnt"); + this.label = new cc.LabelBMFont("YRGB", "res/fonts/konqa32.fnt"); this.addChild(this.label); this.label.x = winSize.width / 2; this.label.y = winSize.height / 2; @@ -2324,7 +2324,7 @@ var LabelLayoutBaseTest = AtlasDemo.extend({ _initTestLabel: function(winSize){ var center = cc.visibleRect.center; - this._label = new _ccsg.Label("Hello World. This is a very long sentence Hehe.", s_resprefix + "fonts/bitmapFontTest2.fnt", _ccsg.Label.Type.BMFont); + this._label = new _ccsg.Label("Hello World. This is a very long sentence Hehe.", "res/fonts/bitmapFontTest2.fnt", _ccsg.Label.Type.BMFont); this._label.setDimensions(winSize.width/2, winSize.height/2); this._label.setLineBreakWithoutSpace(true); this._label.setPosition(center); diff --git a/test/visual-tests/src/LoaderTest/LoaderTest.js b/test/visual-tests/src/LoaderTest/LoaderTest.js deleted file mode 100644 index 517a298fb7..0000000000 --- a/test/visual-tests/src/LoaderTest/LoaderTest.js +++ /dev/null @@ -1,221 +0,0 @@ -/**************************************************************************** - Copyright (c) 2008-2010 Ricardo Quesada - Copyright (c) 2011-2012 cocos2d-x.org - Copyright (c) 2013-2014 Chukong Technologies Inc. - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - ****************************************************************************/ - -//------------------------------------------------------------------ -// -// LoaderTestLayer -// -//------------------------------------------------------------------ -var LoaderTestLayer = BaseTestLayer.extend({ - _title:"Loader Test", - _subtitle:"", - - ctor:function() { - var self = this; - self._super(cc.color(0,0,0,255), cc.color(98,99,117,255)); - - var winSize = cc.winSize; - cc.loader.load(s_helloWorld, function(err, results){ - if(err){ - cc.log("Failed to load %s.", s_helloWorld); - return; - } - cc.log(s_helloWorld + "--->"); - cc.log(results[0]); - var bg = new _ccsg.Sprite(s_helloWorld); - self.addChild(bg); - bg.x = winSize.width/2; - bg.y = winSize.height/2; - }); - - // cc.loader.load([s_Cowboy_plist, s_Cowboy_png], function(err, results){ - // if(err){ - // cc.log("Failed to load %s, %s .", s_Cowboy_plist, s_Cowboy_png); - // return; - // } - - // cc.log(s_Cowboy_plist + "--->"); - // cc.log(results[0]); - // cc.log(s_Cowboy_png + "--->"); - // cc.log(results[1]); - // cc.spriteFrameCache.addSpriteFrames(s_Cowboy_plist); - // var frame = new _ccsg.Sprite("#testAnimationResource/1.png"); - // self.addChild(frame); - // frame.x = winSize.width/4; - // frame.y = winSize.height/4; - // }); - - var str; - if(cc.sys.isNative) { - str = s_lookup_desktop_plist; - } else if(cc.sys.isMobile) { - str = s_lookup_mobile_plist; - } else { - str = s_lookup_html5_plist; - } - - cc.loader.loadAliases(str, function(){ - var sprite = new _ccsg.Sprite("grossini.bmp"); - self.addChild( sprite ); - sprite.x = winSize.width/2; - sprite.y = winSize.height/2; - }); - - }, - - onNextCallback: function(){ - var parent = this.getParent(); - parent.removeChild(this); - parent.addChild(new LoaderCycleLayer()); - } -}); - -var LoaderCycleLayer = BaseTestLayer.extend({ - _title:"Failed to load Test", - _subtitle:"", - - ctor: function(){ - BaseTestLayer.prototype.ctor.call(this); - var index = 0; - - var winSize = cc.director.getWinSize(); - var t = this, - cb = function(num){ - var labelTTF = new cc.LabelTTF(num + " file failed"); - labelTTF.x = index++*100 + winSize.width - 150; - labelTTF.y = winSize.height / 2 - 20; - if(num === 1) - labelTTF.setColor(cc.Color.GREEN); - else - labelTTF.setColor(cc.Color.RED); - t.addChild(labelTTF); - if(index < 4) - t.test(cb); - }; - this.createInfo(); - this.regLoad(); - this.test(cb); - }, - - regLoad: function(){ - cc.loader.register(["_test1"], { - load: function(realUrl, url, res, cb){ - cc.loader.cache[url] = {}; - setTimeout(function(){ - cb && cb(null, cc.loader.cache[url]); - return cc.loader.cache[url]; - }, Math.random()*1000); - - } - }); - cc.loader.register(["_test2"], { - load: function(realUrl, url, res, cb){ - cb && cb({}); - return null; - } - }); - }, - - list: [ - "1._test2", - "1._test1", - "2._test1", - "3._test1", - "4._test1" - ], - - createInfo: function(){ - var winSize = cc.director.getWinSize(); - var info1 = new cc.LabelTTF("Load 5 files"); - info1.x = winSize.width / 2; - info1.y = winSize.height / 2 + 80; - var info2 = new cc.LabelTTF("1 file does not exist"); - info2.x = winSize.width / 2; - info2.y = winSize.height / 2 + 60; - var info3 = new cc.LabelTTF("The other 4 files should be loaded."); - info3.x = winSize.width / 2; - info3.y = winSize.height / 2 + 40; - - this.addChild(info1); - this.addChild(info2); - this.addChild(info3); - - var info4 = new cc.LabelTTF("test 1"); - info4.x = winSize.width / 2 - 50; - info4.y = winSize.height / 2; - var info5 = new cc.LabelTTF("test 2"); - info5.x = winSize.width / 2 - 150; - info5.y = winSize.height / 2; - var info6 = new cc.LabelTTF("test 3"); - info6.x = winSize.width / 2 + 50; - info6.y = winSize.height / 2; - var info7 = new cc.LabelTTF("test 4"); - info7.x = winSize.width / 2 + 150; - info7.y = winSize.height / 2; - - this.addChild(info4); - this.addChild(info5); - this.addChild(info6); - this.addChild(info7); - }, - - test: function(cb){ - this.clearRes(); - var layer = this; - cc.loader.load(layer.list, function(){ - var num = 0; - layer.list.forEach(function(item){ - if(!cc.loader.getRes(item)){ - num++; - } - }); - cb(num); - }); - }, - - clearRes: function(){ - this.list.forEach(function(item){ - cc.loader.release(item); - }); - }, - - onRestartCallback: function(){ - var parent = this._parent; - parent.removeChild(this); - parent.addChild(new LoaderCycleLayer()); - }, - - onBackCallback: function(){ - var parent = this._parent; - parent.removeChild(this); - parent.addChild(new LoaderTestLayer()); - } -}); - -var LoaderTestScene = TestScene.extend({ - runThisTest:function () { - this.addChild(new LoaderTestLayer()); - director.runScene(this); - } -}); \ No newline at end of file diff --git a/test/visual-tests/src/NewEventManagerTest/NewEventManagerTest.js b/test/visual-tests/src/NewEventManagerTest/NewEventManagerTest.js index d9b532bd76..8edf31fcfb 100644 --- a/test/visual-tests/src/NewEventManagerTest/NewEventManagerTest.js +++ b/test/visual-tests/src/NewEventManagerTest/NewEventManagerTest.js @@ -75,16 +75,16 @@ var TouchableSpriteTest = EventDispatcherTestDemo.extend({ var size = director.getVisibleSize(); var containerForSprite1 = new _ccsg.Node(); - var sprite1 = new _ccsg.Sprite("Images/CyanSquare.png"); + var sprite1 = new _ccsg.Sprite("res/Images/CyanSquare.png"); sprite1.setPosition(origin.x + size.width/2 - 80, origin.y + size.height/2 + 80); containerForSprite1.addChild(sprite1); this.addChild(containerForSprite1, 10); - var sprite2 = new _ccsg.Sprite("Images/MagentaSquare.png"); + var sprite2 = new _ccsg.Sprite("res/Images/MagentaSquare.png"); sprite2.setPosition(origin.x + size.width/2, origin.y + size.height/2); this.addChild(sprite2, 20); - var sprite3 = new _ccsg.Sprite("Images/YellowSquare.png"); + var sprite3 = new _ccsg.Sprite("res/Images/YellowSquare.png"); sprite3.setPosition(0,0); sprite2.addChild(sprite3, 1); @@ -254,19 +254,19 @@ var FixedPriorityTest = EventDispatcherTestDemo.extend({ var size = director.getVisibleSize(); var sprite1 = TouchableSprite.create(30); - sprite1.setTexture("Images/CyanSquare.png"); + sprite1.setTexture("res/Images/CyanSquare.png"); sprite1.x = origin.x + size.width / 2 - 80; sprite1.y = origin.y + size.height / 2 + 40; this.addChild(sprite1, 10); var sprite2 = TouchableSprite.create(20); - sprite2.setTexture("Images/MagentaSquare.png"); + sprite2.setTexture("res/Images/MagentaSquare.png"); sprite2.x = origin.x + size.width / 2; sprite2.y = origin.y + size.height / 2; this.addChild(sprite2, 20); var sprite3 = TouchableSprite.create(10); - sprite3.setTexture("Images/YellowSquare.png"); + sprite3.setTexture("res/Images/YellowSquare.png"); sprite3.x = 0; sprite3.y = 0; sprite2.addChild(sprite3, 1); @@ -296,7 +296,7 @@ var RemoveListenerWhenDispatching = EventDispatcherTestDemo.extend({ var origin = director.getVisibleOrigin(); var size = director.getVisibleSize(); - var sprite1 = new _ccsg.Sprite("Images/CyanSquare.png"); + var sprite1 = new _ccsg.Sprite("res/Images/CyanSquare.png"); sprite1.setPosition(origin.x + size.width/2, origin.y + size.height/2); this.addChild(sprite1, 10); @@ -516,7 +516,7 @@ var SpriteAccelerationEventTest = EventDispatcherTestDemo.extend({ cc.inputManager.setAccelerometerEnabled(true); - var sprite = new _ccsg.Sprite("Images/ball.png"); + var sprite = new _ccsg.Sprite("res/Images/ball.png"); sprite.setPosition(origin.x + size.width/2, origin.y + size.height/2); this.addChild(sprite); @@ -580,7 +580,7 @@ var RemoveAndRetainNodeTest = EventDispatcherTestDemo.extend({ var origin = director.getVisibleOrigin(); var size = director.getVisibleSize(); - this._sprite = new _ccsg.Sprite("Images/CyanSquare.png"); + this._sprite = new _ccsg.Sprite("res/Images/CyanSquare.png"); this._sprite.setPosition(origin.x + size.width/2, origin.y + size.height/2); this.addChild(this._sprite, 10); @@ -878,11 +878,11 @@ var GlobalZTouchTest = EventDispatcherTestDemo.extend({ var SPRITE_COUNT = 8, sprite; for (var i = 0; i < SPRITE_COUNT; i++) { if(i==4) { - sprite = new _ccsg.Sprite("Images/CyanSquare.png"); + sprite = new _ccsg.Sprite("res/Images/CyanSquare.png"); this._sprite = sprite; this._sprite.setGlobalZOrder(-1); } else - sprite = new _ccsg.Sprite("Images/YellowSquare.png"); + sprite = new _ccsg.Sprite("res/Images/YellowSquare.png"); cc.eventManager.addListener(listener.clone(), sprite); this.addChild(sprite); @@ -998,17 +998,17 @@ var StopPropagationTest = EventDispatcherTestDemo.extend({ for (var i = 0; i < SPRITE_COUNT; i++) { if(i==4) { - sprite1 = new _ccsg.Sprite("Images/CyanSquare.png"); + sprite1 = new _ccsg.Sprite("res/Images/CyanSquare.png"); sprite1.setTag(StopPropagationTest._TAG_BLUE_SPRITE); this.addChild(sprite1, 100); - sprite2 = new _ccsg.Sprite("Images/CyanSquare.png"); + sprite2 = new _ccsg.Sprite("res/Images/CyanSquare.png"); sprite2.setTag(StopPropagationTest._TAG_BLUE_SPRITE2); this.addChild(sprite2, 100); } else { - sprite1 = new _ccsg.Sprite("Images/YellowSquare.png"); + sprite1 = new _ccsg.Sprite("res/Images/YellowSquare.png"); this.addChild(sprite1, 0); - sprite2 = new _ccsg.Sprite("Images/YellowSquare.png"); + sprite2 = new _ccsg.Sprite("res/Images/YellowSquare.png"); this.addChild(sprite2, 0); } @@ -1068,20 +1068,20 @@ var Issue4160 = EventDispatcherTestDemo.extend({ var size = cc.director.getVisibleSize(); var sprite1 = TouchableSprite.create(-30); - sprite1.setTexture("Images/CyanSquare.png"); + sprite1.setTexture("res/Images/CyanSquare.png"); sprite1.x = origin.x + (size.width/2) - 80; sprite1.y = origin.y + (size.height/2) + 40; this.addChild(sprite1, 5); var sprite2 = TouchableSprite.create(-20); - sprite2.setTexture("Images/MagentaSquare.png"); + sprite2.setTexture("res/Images/MagentaSquare.png"); sprite2.removeListenerOnTouchEnded(true); sprite2.x = origin.x + (size.width/2); sprite2.y = origin.y + (size.height/2); this.addChild(sprite2, 10); var sprite3 = TouchableSprite.create(-10); - sprite3.setTexture("Images/YellowSquare.png"); + sprite3.setTexture("res/Images/YellowSquare.png"); sprite3.x = 0; sprite3.y = 0; sprite2.addChild(sprite3, 21); @@ -1112,19 +1112,19 @@ var PauseResumeTargetTest = EventDispatcherTestDemo.extend({ var size = cc.director.getVisibleSize(); var sprite1 = TouchableSprite.create(); - sprite1.setTexture("Images/CyanSquare.png"); + sprite1.setTexture("res/Images/CyanSquare.png"); sprite1.x = origin.x + size.width / 2 - 180; sprite1.y = origin.y + size.height / 2 + 40; this.addChild(sprite1, 10); var sprite2 = TouchableSprite.create(); - sprite2.setTexture("Images/MagentaSquare.png"); + sprite2.setTexture("res/Images/MagentaSquare.png"); sprite2.x = origin.x + size.width / 2 - 100; sprite2.y = origin.y + size.height / 2; this.addChild(sprite2, 1); var sprite3 = TouchableSprite.create(100); // Sprite3 uses fixed priority listener - sprite3.setTexture("Images/YellowSquare.png"); + sprite3.setTexture("res/Images/YellowSquare.png"); sprite3.x = 0; sprite3.y = 0; sprite2.addChild(sprite3, -1); diff --git a/test/visual-tests/src/OpenGLTest/OpenGLTest.js b/test/visual-tests/src/OpenGLTest/OpenGLTest.js index 1531266cf4..a942e8813a 100644 --- a/test/visual-tests/src/OpenGLTest/OpenGLTest.js +++ b/test/visual-tests/src/OpenGLTest/OpenGLTest.js @@ -644,7 +644,7 @@ var ShaderHeartTest = OpenGLTestLayer.extend({ this._super(); if( 'opengl' in cc.sys.capabilities ) { - var shaderNode = new ShaderNode(ccbjs + "Shaders/example_Heart.vsh", ccbjs + "Shaders/example_Heart.fsh"); + var shaderNode = new ShaderNode("res/Shaders/example_Heart.vsh", "res/Shaders/example_Heart.fsh"); this.addChild(shaderNode,10); shaderNode.x = winSize.width/2; shaderNode.y = winSize.height/2; @@ -684,7 +684,7 @@ var ShaderMandelbrotTest = OpenGLTestLayer.extend({ this._super(); if( 'opengl' in cc.sys.capabilities ) { - var shaderNode = new ShaderNode(ccbjs + "Shaders/example_Mandelbrot.vsh", ccbjs + "Shaders/example_Mandelbrot.fsh"); + var shaderNode = new ShaderNode("res/Shaders/example_Mandelbrot.vsh", "res/Shaders/example_Mandelbrot.fsh"); this.addChild(shaderNode,10); shaderNode.x = winSize.width/2; shaderNode.y = winSize.height/2; @@ -719,7 +719,7 @@ var ShaderMonjoriTest = OpenGLTestLayer.extend({ this._super(); if( 'opengl' in cc.sys.capabilities ) { - var shaderNode = new ShaderNode(ccbjs + "Shaders/example_Monjori.vsh", ccbjs + "Shaders/example_Monjori.fsh"); + var shaderNode = new ShaderNode("res/Shaders/example_Monjori.vsh", "res/Shaders/example_Monjori.fsh"); this.addChild(shaderNode,10); shaderNode.x = winSize.width/2; shaderNode.y = winSize.height/2; @@ -754,7 +754,7 @@ var ShaderPlasmaTest = OpenGLTestLayer.extend({ this._super(); if( 'opengl' in cc.sys.capabilities ) { - var shaderNode = new ShaderNode(ccbjs + "Shaders/example_Plasma.vsh", ccbjs + "Shaders/example_Plasma.fsh"); + var shaderNode = new ShaderNode("res/Shaders/example_Plasma.vsh", "res/Shaders/example_Plasma.fsh"); this.addChild(shaderNode,10); shaderNode.x = winSize.width/2; shaderNode.y = winSize.height/2; @@ -793,7 +793,7 @@ var ShaderFlowerTest = OpenGLTestLayer.extend({ if( 'opengl' in cc.sys.capabilities ) { - var shaderNode = new ShaderNode(ccbjs + "Shaders/example_Flower.vsh", ccbjs + "Shaders/example_Flower.fsh"); + var shaderNode = new ShaderNode("res/Shaders/example_Flower.vsh", "res/Shaders/example_Flower.fsh"); this.addChild(shaderNode,10); shaderNode.x = winSize.width/2; shaderNode.y = winSize.height/2; @@ -832,7 +832,7 @@ var ShaderJuliaTest = OpenGLTestLayer.extend({ if( 'opengl' in cc.sys.capabilities ) { - var shaderNode = new ShaderNode(ccbjs + "Shaders/example_Julia.vsh", ccbjs + "Shaders/example_Julia.fsh"); + var shaderNode = new ShaderNode("res/Shaders/example_Julia.vsh", "res/Shaders/example_Julia.fsh"); this.addChild(shaderNode,10); shaderNode.x = winSize.width/2; shaderNode.y = winSize.height/2; @@ -873,12 +873,12 @@ var ShaderOutlineEffect = OpenGLTestLayer.extend({ if( 'opengl' in cc.sys.capabilities ) { if(cc.sys.isNative){ - this.shader = new cc.GLProgram(ccbjs + "Shaders/example_Outline_noMVP.vsh", ccbjs + "Shaders/example_Outline.fsh"); + this.shader = new cc.GLProgram("res/Shaders/example_Outline_noMVP.vsh", "res/Shaders/example_Outline.fsh"); this.shader.link(); this.shader.updateUniforms(); } else{ - this.shader = new cc.GLProgram(ccbjs + "Shaders/example_Outline.vsh", ccbjs + "Shaders/example_Outline.fsh"); + this.shader = new cc.GLProgram("res/Shaders/example_Outline.vsh", "res/Shaders/example_Outline.fsh"); this.shader.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); this.shader.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); this.shader.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR); @@ -890,7 +890,7 @@ var ShaderOutlineEffect = OpenGLTestLayer.extend({ this.shader.setUniformLocationWith3f(this.shader.getUniformLocationForName('u_outlineColor'), 0 / 255, 255 / 255, 0 / 255); } - this.sprite = new _ccsg.Sprite('Images/grossini.png'); + this.sprite = new _ccsg.Sprite('res/Images/grossini.png'); this.sprite.attr({ x: winSize.width / 2, y: winSize.height / 2 @@ -949,13 +949,13 @@ var ShaderRetroEffect = OpenGLTestLayer.extend({ this._super(); if( 'opengl' in cc.sys.capabilities ) { - var program = new cc.GLProgram(ccbjs + "Shaders/example_ColorBars.vsh", ccbjs + "Shaders/example_ColorBars.fsh"); + var program = new cc.GLProgram("res/Shaders/example_ColorBars.vsh", "res/Shaders/example_ColorBars.fsh"); program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS); program.link(); program.updateUniforms(); - var label = new cc.LabelBMFont("RETRO EFFECT","fonts/west_england-64.fnt"); + var label = new cc.LabelBMFont("RETRO EFFECT", "res/fonts/west_england-64.fnt"); if(cc.sys.isNative) label.children[0].shaderProgram = program; @@ -1019,7 +1019,7 @@ var GLGetActiveTest = OpenGLTestLayer.extend({ this._super(); if( 'opengl' in cc.sys.capabilities ) { - var sprite = this.sprite = new _ccsg.Sprite("Images/grossini.png"); + var sprite = this.sprite = new _ccsg.Sprite("res/Images/grossini.png"); sprite.x = winSize.width/2; sprite.y = winSize.height/2; this.addChild( sprite ); diff --git a/test/visual-tests/src/ParallaxTest/ParallaxTest.js b/test/visual-tests/src/ParallaxTest/ParallaxTest.js index 82dcbd7729..c9ac3661f5 100644 --- a/test/visual-tests/src/ParallaxTest/ParallaxTest.js +++ b/test/visual-tests/src/ParallaxTest/ParallaxTest.js @@ -84,7 +84,7 @@ var Parallax1 = ParallaxDemo.extend({ // Middle layer: a Tile map atlas //var tilemap = cc.TileMapAtlas.create(s_tilesPng, s_levelMapTga, 16, 16); - this._tilemap = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test2.tmx"); + this._tilemap = new cc.TMXTiledMap("res/TileMaps/orthogonal-test2.tmx"); // change the transform anchor to 0,0 (optional) this._tilemap.anchorX = 0; @@ -197,7 +197,7 @@ var Parallax2 = ParallaxDemo.extend({ // Middle layer: a Tile map atlas //var tilemap = cc.TileMapAtlas.create(s_tilesPng, s_levelMapTga, 16, 16); - var tilemap = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test2.tmx"); + var tilemap = new cc.TMXTiledMap("res/TileMaps/orthogonal-test2.tmx"); // change the transform anchor to 0,0 (optional) tilemap.anchorX = 0; diff --git a/test/visual-tests/src/ParticleTest/ParticleTest.js b/test/visual-tests/src/ParticleTest/ParticleTest.js index c3a1b1688a..9ba39a17e4 100644 --- a/test/visual-tests/src/ParticleTest/ParticleTest.js +++ b/test/visual-tests/src/ParticleTest/ParticleTest.js @@ -879,9 +879,9 @@ var DemoParticleFromFile = ParticleDemo.extend({ this.removeChild(this._background, true); this._background = null; - this._emitter = new _ccsg.ParticleSystem(s_resprefix + "Particles/" + this._title + ".plist"); + this._emitter = new _ccsg.ParticleSystem("res/Particles/" + this._title + ".plist"); // test create from a object - // var plistData = jsb.fileUtils.getValueMapFromFile(s_resprefix + "Particles/" + this._title + ".plist"); + // var plistData = jsb.fileUtils.getValueMapFromFile("res/Particles/" + this._title + ".plist"); // this._emitter = new _ccsg.ParticleSystem(plistData); this.addChild(this._emitter, 10); @@ -1134,7 +1134,7 @@ var Issue870 = ParticleDemo.extend({ this.removeChild(this._background, true); this._background = null; - var system = new _ccsg.ParticleSystem(s_resprefix + "Particles/SpinningPeas.plist"); + var system = new _ccsg.ParticleSystem("res/Particles/SpinningPeas.plist"); system.setTextureWithRect(cc.textureCache.addImage(s_particles), cc.rect(0, 0, 32, 32)); this.addChild(system, 10); this._emitter = system; @@ -1162,11 +1162,11 @@ var ParticleBatchTest = ParticleDemo.extend({ onEnter:function () { this._super(); - var emitter1 = new _ccsg.ParticleSystem(s_resprefix + 'Particles/LavaFlow.plist'); + var emitter1 = new _ccsg.ParticleSystem('res/Particles/LavaFlow.plist'); emitter1.startColor = cc.color(255, 0, 0, 255); - var emitter2 = new _ccsg.ParticleSystem(s_resprefix + 'Particles/LavaFlow.plist'); + var emitter2 = new _ccsg.ParticleSystem('res/Particles/LavaFlow.plist'); emitter2.startColor = cc.color(0, 255, 0, 255); - var emitter3 = new _ccsg.ParticleSystem(s_resprefix + 'Particles/LavaFlow.plist'); + var emitter3 = new _ccsg.ParticleSystem('res/Particles/LavaFlow.plist'); emitter3.startColor = cc.color(0, 0, 255, 255); emitter1.x = winSize.width / 1.25; @@ -1203,7 +1203,7 @@ var ParticleResizeTest = ParticleDemo.extend({ onEnter:function () { this._super(); - var emitter1 = new _ccsg.ParticleSystem( s_resprefix + 'Particles/LavaFlow.plist'); + var emitter1 = new _ccsg.ParticleSystem( 'res/Particles/LavaFlow.plist'); emitter1.x = winSize.width/2; emitter1.y = winSize.height/2; this.addChild(emitter1); diff --git a/test/visual-tests/src/SpineTest/SpineTest.js b/test/visual-tests/src/SpineTest/SpineTest.js index c8a6353de2..791ee7836e 100644 --- a/test/visual-tests/src/SpineTest/SpineTest.js +++ b/test/visual-tests/src/SpineTest/SpineTest.js @@ -74,7 +74,7 @@ var SpineTestLayer = BaseTestLayer.extend({ } }); -var customSkeletonAnimation = sp.SkeletonAnimation.extend({ +var customSkeletonAnimation = sp._SGSkeletonAnimation.extend({ ctor:function () { this._super.apply(this, arguments); } @@ -97,10 +97,10 @@ var SpineTestLayerNormal = SpineTestLayer.extend({ // No JS binding for spine-c in this version. So, only file loading is supported. var spineBoy; if (idx % 2 == 0) { - spineBoy = new customSkeletonAnimation('spine/spineboy.json', 'spine/spineboy.atlas'); + spineBoy = new customSkeletonAnimation('res/spine/spineboy.json', 'res/spine/spineboy.atlas'); } else { - spineBoy = new sp.SkeletonAnimation('spine/spineboy.json', 'spine/spineboy.atlas'); + spineBoy = new sp._SGSkeletonAnimation('res/spine/spineboy.json', 'res/spine/spineboy.atlas'); } spineBoy.setPosition(cc.p(size.width / 2, size.height / 2 - 150)); spineBoy.setMix('walk', 'jump', 0.2); @@ -186,16 +186,16 @@ var SpineTestLayerNormal = SpineTestLayer.extend({ var entry = this._spineboy.getCurrent(); var animationName = (entry && entry.animation) ? entry.animation.name : 0; switch(type) { - case sp.ANIMATION_EVENT_TYPE.START: + case sp.AnimationEventType.START: cc.log(trackIndex + " start: " + animationName); break; - case sp.ANIMATION_EVENT_TYPE.END: + case sp.AnimationEventType.END: cc.log(trackIndex + " end:" + animationName); break; - case sp.ANIMATION_EVENT_TYPE.EVENT: + case sp.AnimationEventType.EVENT: cc.log(trackIndex + " event: " + animationName); break; - case sp.ANIMATION_EVENT_TYPE.COMPLETE: + case sp.AnimationEventType.COMPLETE: cc.log(trackIndex + " complete: " + animationName + "," + loopCount); if(this._flipped){ this._flipped = false; @@ -223,7 +223,7 @@ var SpineTestLayerFFD = SpineTestLayer.extend({ ctor: function(){ this._super(cc.color(0,0,0,255), cc.color(98,99,117,255)); - var skeletonNode = new sp.SkeletonAnimation("spine/goblins-ffd.json", "spine/goblins-ffd.atlas", 1.5); + var skeletonNode = new sp._SGSkeletonAnimation("res/spine/goblins-ffd.json", "res/spine/goblins-ffd.atlas", 1.5); skeletonNode.setAnimation(0, "walk", true); skeletonNode.setSkin("goblin"); @@ -267,7 +267,7 @@ var SpineTestPerformanceLayer = SpineTestLayer.extend({ event: cc.EventListener.TOUCH_ONE_BY_ONE, onTouchBegan: function(touch, event){ var pos = self.convertToNodeSpace(touch.getLocation()); - var skeletonNode = new sp.SkeletonAnimation("spine/goblins-ffd.json", "spine/goblins-ffd.atlas", 1.5); + var skeletonNode = new sp._SGSkeletonAnimation("res/spine/goblins-ffd.json", "res/spine/goblins-ffd.atlas", 1.5); skeletonNode.setAnimation(0, "walk", true); skeletonNode.setSkin("goblin"); diff --git a/test/visual-tests/src/SpriteTest/SpriteTest.js b/test/visual-tests/src/SpriteTest/SpriteTest.js index cd8ffb0215..d5d765b266 100644 --- a/test/visual-tests/src/SpriteTest/SpriteTest.js +++ b/test/visual-tests/src/SpriteTest/SpriteTest.js @@ -4914,113 +4914,6 @@ var SpriteSkewNegativeScaleChildren = SpriteTestDemo.extend({ } }); -var DoubleSprite = _ccsg.Sprite.extend({ - HD:false, - - ctor:function (fileName) { - this._super(fileName); - //var resolutionType = texture.getResolutionType(); - //this.HD = ( resolutionType == cc.kCCResolutioniPhoneRetinaDisplay || resolutionType == kCCResolutioniPadRetinaDisplay ); - }, - - setContentSize:function (size) { - var newSize = cc.size(size.width, size.height); - // If Retina Display and Texture is in HD then scale the vertex rect - if (cc.contentScaleFactor() == 2 && !this.HD) { - newSize.width *= 2; - newSize.height *= 2; - } - this._super(newSize); - }, - _setWidth:function (value) { - // If Retina Display and Texture is in HD then scale the vertex rect - if (cc.contentScaleFactor() == 2 && !this.HD) { - value *= 2; - } - this._super(value); - }, - _setHeight:function (value) { - // If Retina Display and Texture is in HD then scale the vertex rect - if (cc.contentScaleFactor() == 2 && !this.HD) { - value *= 2; - } - this._super(value); - }, - - setVertexRect:function (rect) { - // If Retina Display and Texture is in HD then scale the vertex rect - if (cc.contentScaleFactor() == 2 && !this.HD) { - rect.width *= 2; - rect.height *= 2; - } - this._super(rect); - } -}); - -cc.defineGetterSetter(DoubleSprite.prototype, "width", DoubleSprite.prototype._getWidth, DoubleSprite.prototype._setWidth); -cc.defineGetterSetter(DoubleSprite.prototype, "height", DoubleSprite.prototype._getHeight, DoubleSprite.prototype._setHeight); - -var SpriteDoubleResolution = SpriteTestDemo.extend({ - - _title:"Sprite Double resolution", - _subtitle:"Retina Display. SD (left) should be equal to HD (right)", - - ctor:function () { - //----start52----ctor - this._super(); - - // - // LEFT: SD sprite - // - // there is no HD resolution file of grossini_dance_08. - var spriteSD = new DoubleSprite(s_grossiniDance08); - this.addChild(spriteSD); - spriteSD.x = winSize.width / 4; - spriteSD.y = winSize.height / 2; - - var child1_left = new DoubleSprite(s_grossiniDance08); - spriteSD.addChild(child1_left); - child1_left.x = -30; - child1_left.y = 0; - - var child1_right = new _ccsg.Sprite(s_pathGrossini); - spriteSD.addChild(child1_right); - child1_left.x = spriteSD.height; - child1_left.y = 0; - - // - // RIGHT: HD sprite - // - // there is an HD version of grossini.png - var spriteHD = new _ccsg.Sprite(s_pathGrossini); - this.addChild(spriteHD); - spriteHD.x = winSize.width / 4 * 3; - spriteHD.y = winSize.height / 2; - - var child2_left = new DoubleSprite(s_grossiniDance08); - spriteHD.addChild(child2_left); - child2_left.x = -30; - child2_left.y = 0; - - var child2_right = new _ccsg.Sprite(s_pathGrossini); - spriteHD.addChild(child2_right); - child2_left.x = spriteHD.height; - child2_left.y = 0; - - - // Actions - var scale = cc.scaleBy(2, 0.5); - var scale_back = scale.reverse(); - var seq = cc.sequence(scale, scale_back); - - var seq_copy = seq.clone(); - - spriteSD.runAction(seq); - spriteHD.runAction(seq_copy); - //----end52---- - } -}); - var SpriteFrameAnimationCacheFile = SpriteTestDemo.extend({ _title:"SpriteFrameAnimationCache - Load file", @@ -5339,7 +5232,7 @@ var SpriteBlendFuncTest = SpriteTestDemo.extend({ var destTitles = ["ZERO", "ONE", "DST_COLOR", "ONE_MINUS_DST_COLOR", "DST_ALPHA", "ONE_MINUS_DST_ALPHA"], srcTitles = ["ZERO", "ONE", "SRC_COLOR", "ONE_MINUS_SRC_COLOR", "SRC_ALPHA", "ONE_MINUS_SRC_ALPHA"]; - var sourceImg = "Images/dot.png", destImg = "Images/wood.jpg"; + var sourceImg = "res/Images/dot.png", destImg = "res/Images/wood.jpg"; var sourceTexture = cc.textureCache.addImage(sourceImg); sourceTexture.handleLoadedTexture(true); var sourceSprite = new _ccsg.Sprite(sourceImg); diff --git a/test/visual-tests/src/TextureCacheTest/TextureCacheTest.js b/test/visual-tests/src/TextureCacheTest/TextureCacheTest.js index e650912944..ee36b40363 100644 --- a/test/visual-tests/src/TextureCacheTest/TextureCacheTest.js +++ b/test/visual-tests/src/TextureCacheTest/TextureCacheTest.js @@ -147,57 +147,57 @@ var TextureCacheTest = TextureCacheTestBase.extend({ var texCache = cc.textureCache; // load textrues - texCache.addImageAsync("Images/HelloWorld.png", this.loadingCallBack, this); - texCache.addImageAsync("Images/grossini.png", this.loadingCallBack, this); - texCache.addImageAsync("Images/grossini_dance_01.png", this.loadingCallBack, this); - texCache.addImageAsync("Images/grossini_dance_02.png", this.loadingCallBack, this); - texCache.addImageAsync("Images/grossini_dance_03.png", this.loadingCallBack, this); - texCache.addImageAsync("Images/grossini_dance_04.png", this.loadingCallBack, this); - texCache.addImageAsync("Images/grossini_dance_05.png", this.loadingCallBack, this); - texCache.addImageAsync("Images/grossini_dance_06.png", this.loadingCallBack, this); - texCache.addImageAsync("Images/grossini_dance_07.png", this.loadingCallBack, this); - texCache.addImageAsync("Images/grossini_dance_08.png", this.loadingCallBack, this); - texCache.addImageAsync("Images/grossini_dance_09.png", this.loadingCallBack, this); - texCache.addImageAsync("Images/grossini_dance_10.png", this.loadingCallBack, this); - texCache.addImageAsync("Images/grossini_dance_11.png", this.loadingCallBack, this); - texCache.addImageAsync("Images/grossini_dance_12.png", this.loadingCallBack, this); - texCache.addImageAsync("Images/grossini_dance_13.png", this.loadingCallBack, this); - texCache.addImageAsync("Images/grossini_dance_14.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/HelloWorld.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_01.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_02.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_03.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_04.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_05.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_06.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_07.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_08.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_09.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_10.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_11.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_12.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_13.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/grossini_dance_14.png", this.loadingCallBack, this); texCache.addImageAsync("res/Images/background1.png", this.loadingCallBack, this); texCache.addImageAsync("res/Images/background2.png", this.loadingCallBack, this); - texCache.addImageAsync("Images/background3.png", this.loadingCallBack, this); - texCache.addImageAsync("Images/blocks.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/background3.png", this.loadingCallBack, this); + texCache.addImageAsync("res/Images/blocks.png", this.loadingCallBack, this); }, addSprite:function () { var size = cc.director.getWinSize(); // create sprites - var bg = new _ccsg.Sprite("Images/HelloWorld.png"); + var bg = new _ccsg.Sprite("res/Images/HelloWorld.png"); bg.x = size.width / 2; bg.y = size.height / 2; //bg.scale = 1.7; - var s1 = new _ccsg.Sprite("Images/grossini.png"); - var s2 = new _ccsg.Sprite("Images/grossini_dance_01.png"); - var s3 = new _ccsg.Sprite("Images/grossini_dance_02.png"); - var s4 = new _ccsg.Sprite("Images/grossini_dance_03.png"); - var s5 = new _ccsg.Sprite("Images/grossini_dance_04.png"); - var s6 = new _ccsg.Sprite("Images/grossini_dance_05.png"); - var s7 = new _ccsg.Sprite("Images/grossini_dance_06.png"); - var s8 = new _ccsg.Sprite("Images/grossini_dance_07.png"); - var s9 = new _ccsg.Sprite("Images/grossini_dance_08.png"); - var s10 = new _ccsg.Sprite("Images/grossini_dance_09.png"); - var s11 = new _ccsg.Sprite("Images/grossini_dance_10.png"); - var s12 = new _ccsg.Sprite("Images/grossini_dance_11.png"); - var s13 = new _ccsg.Sprite("Images/grossini_dance_12.png"); - var s14 = new _ccsg.Sprite("Images/grossini_dance_13.png"); - var s15 = new _ccsg.Sprite("Images/grossini_dance_14.png"); + var s1 = new _ccsg.Sprite("res/Images/grossini.png"); + var s2 = new _ccsg.Sprite("res/Images/grossini_dance_01.png"); + var s3 = new _ccsg.Sprite("res/Images/grossini_dance_02.png"); + var s4 = new _ccsg.Sprite("res/Images/grossini_dance_03.png"); + var s5 = new _ccsg.Sprite("res/Images/grossini_dance_04.png"); + var s6 = new _ccsg.Sprite("res/Images/grossini_dance_05.png"); + var s7 = new _ccsg.Sprite("res/Images/grossini_dance_06.png"); + var s8 = new _ccsg.Sprite("res/Images/grossini_dance_07.png"); + var s9 = new _ccsg.Sprite("res/Images/grossini_dance_08.png"); + var s10 = new _ccsg.Sprite("res/Images/grossini_dance_09.png"); + var s11 = new _ccsg.Sprite("res/Images/grossini_dance_10.png"); + var s12 = new _ccsg.Sprite("res/Images/grossini_dance_11.png"); + var s13 = new _ccsg.Sprite("res/Images/grossini_dance_12.png"); + var s14 = new _ccsg.Sprite("res/Images/grossini_dance_13.png"); + var s15 = new _ccsg.Sprite("res/Images/grossini_dance_14.png"); // just loading textures to slow down var s16 = new _ccsg.Sprite("res/Images/background1.png"); var s17 = new _ccsg.Sprite("res/Images/background2.png"); - var s18 = new _ccsg.Sprite("Images/background3.png"); - var s19 = new _ccsg.Sprite("Images/blocks.png"); + var s18 = new _ccsg.Sprite("res/Images/background3.png"); + var s19 = new _ccsg.Sprite("res/Images/blocks.png"); s1.x = 50; s1.y = 50; diff --git a/test/visual-tests/src/TileMapTest/TileMapTest.js b/test/visual-tests/src/TileMapTest/TileMapTest.js index 274a68837d..11e4e48b71 100644 --- a/test/visual-tests/src/TileMapTest/TileMapTest.js +++ b/test/visual-tests/src/TileMapTest/TileMapTest.js @@ -175,7 +175,7 @@ var TileMapEditTest = TileDemo.extend({ var TMXOrthoTest = TileDemo.extend({ ctor:function () { this._super(); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test1.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test1.tmx"); this.addChild(map, 0, TAG_TILE_MAP); map.runAction(new cc.ScaleBy(2, 0.5)); @@ -217,7 +217,7 @@ var TMXOrthoTest2 = TileDemo.extend({ // // it should not flicker. No artifacts should appear // - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test2.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test2.tmx"); this.addChild(map, 0, TAG_TILE_MAP); }, title:function () { @@ -260,7 +260,7 @@ var TMXOrthoTest2 = TileDemo.extend({ var TMXOrthoTest3 = TileDemo.extend({ ctor:function () { this._super(); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test3.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test3.tmx"); this.addChild(map, 0, TAG_TILE_MAP); map.scale = 0.2; @@ -298,7 +298,7 @@ var TMXOrthoTest3 = TileDemo.extend({ var TMXOrthoTest4 = TileDemo.extend({ ctor:function () { this._super(); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test4.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test4.tmx"); this.addChild(map, 0, TAG_TILE_MAP); map.anchorX = 0; @@ -368,7 +368,7 @@ var TMXReadWriteTest = TileDemo.extend({ ctor:function () { this._super(); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test2.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test2.tmx"); this.addChild(map, 0, TAG_TILE_MAP); var layer = map.getLayer("Layer 0"); @@ -490,7 +490,7 @@ var TMXHexTest = TileDemo.extend({ var color = new cc.LayerColor(cc.color(64, 64, 64, 255)); this.addChild(color, -1); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/hexa-test.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/hexa-test.tmx"); this.addChild(map, 0, TAG_TILE_MAP); }, title:function () { @@ -526,7 +526,7 @@ var TMXIsoTest = TileDemo.extend({ var color = new cc.LayerColor(cc.color(64, 64, 64, 255)); this.addChild(color, -1); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/iso-test.tmx"); this.addChild(map, 0, TAG_TILE_MAP); // move map to the center of the screen @@ -570,7 +570,7 @@ var TMXIsoTest1 = TileDemo.extend({ var color = new cc.LayerColor(cc.color(64, 64, 64, 255)); this.addChild(color, -1); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test1.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/iso-test1.tmx"); this.addChild(map, 0, TAG_TILE_MAP); map.anchorX = 0.5; @@ -612,7 +612,7 @@ var TMXIsoTest2 = TileDemo.extend({ var color = new cc.LayerColor(cc.color(64, 64, 64, 255)); this.addChild(color, -1); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test2.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/iso-test2.tmx"); this.addChild(map, 0, TAG_TILE_MAP); // move map to the center of the screen @@ -657,7 +657,7 @@ var TMXUncompressedTest = TileDemo.extend({ var color = new cc.LayerColor(cc.color(64, 64, 64, 255)); this.addChild(color, -1); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test2-uncompressed.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/iso-test2-uncompressed.tmx"); this.addChild(map, 0, TAG_TILE_MAP); // move map to the center of the screen @@ -710,7 +710,7 @@ var TMXUncompressedTest = TileDemo.extend({ var TMXTilesetTest = TileDemo.extend({ ctor:function () { this._super(); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test5.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test5.tmx"); this.addChild(map, 0, TAG_TILE_MAP); if ("opengl" in cc.sys.capabilities) { @@ -760,7 +760,7 @@ var TMXOrthoObjectsTest = TileDemo.extend({ drawNode.setLineWidth(3); drawNode.setDrawColor(cc.color(255,255,255,255)); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/ortho-objects.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/ortho-objects.tmx"); this.addChild(map, 0, TAG_TILE_MAP); var group = map.getObjectGroup("Object Group 1"); @@ -835,7 +835,7 @@ var TMXIsoObjectsTest = TileDemo.extend({ drawNode.setDrawColor(cc.color(255,255,255,255)); this.addChild(drawNode); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test-objectgroup.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/iso-test-objectgroup.tmx"); this.addChild(map, 0, TAG_TILE_MAP); var group = map.getObjectGroup("Object Group 1"); @@ -906,7 +906,7 @@ var TMXIsoObjectsTest = TileDemo.extend({ var TMXResizeTest = TileDemo.extend({ ctor:function () { this._super(); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test5.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test5.tmx"); this.addChild(map, 0, TAG_TILE_MAP); var layer; @@ -950,7 +950,7 @@ var TMXIsoZorder = TileDemo.extend({ tamara:null, ctor:function () { this._super(); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test-zorder.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/iso-test-zorder.tmx"); this.addChild(map, 0, TAG_TILE_MAP); map.x = -map.width / 2; @@ -1019,7 +1019,7 @@ var TMXOrthoZorder = TileDemo.extend({ tamara:null, ctor:function () { this._super(); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test-zorder.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test-zorder.tmx"); this.addChild(map, 0, TAG_TILE_MAP); this.tamara = new _ccsg.Sprite(s_pathSister1); @@ -1082,7 +1082,7 @@ var TMXIsoVertexZ = TMXFixBugLayer.extend({ tamara:null, ctor:function () { this._super(); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test-vertexz.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/iso-test-vertexz.tmx"); this.addChild(map, 0, TAG_TILE_MAP); map.x = -map.width / 2; @@ -1157,7 +1157,7 @@ var TMXOrthoVertexZ = TMXFixBugLayer.extend({ tamara:null, ctor:function () { this._super(); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test-vertexz.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test-vertexz.tmx"); this.addChild(map, 0, TAG_TILE_MAP); // because I'm lazy, I'm reusing a tile as an sprite, but since this method uses vertexZ, you @@ -1231,7 +1231,7 @@ var TMXOrthoVertexZ = TMXFixBugLayer.extend({ var TMXIsoMoveLayer = TileDemo.extend({ ctor:function () { this._super(); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test-movelayer.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/iso-test-movelayer.tmx"); this.addChild(map, 0, TAG_TILE_MAP); map.x = -700; map.y = -50; @@ -1252,7 +1252,7 @@ var TMXIsoMoveLayer = TileDemo.extend({ var TMXOrthoMoveLayer = TileDemo.extend({ ctor:function () { this._super(); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test-movelayer.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test-movelayer.tmx"); this.addChild(map, 0, TAG_TILE_MAP); }, title:function () { @@ -1271,7 +1271,7 @@ var TMXOrthoMoveLayer = TileDemo.extend({ var TMXTilePropertyTest = TileDemo.extend({ ctor:function () { this._super(); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/ortho-tile-property.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/ortho-tile-property.tmx"); this.addChild(map, 0, TAG_TILE_MAP); for (var i = 1; i <= 6; i++) { @@ -1314,7 +1314,7 @@ var TMXTilePropertyTest = TileDemo.extend({ var TMXOrthoFlipTest = TileDemo.extend({ ctor:function () { this._super(); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/ortho-rotation-test.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/ortho-rotation-test.tmx"); this.addChild(map, 0, TAG_TILE_MAP); this.log("ContentSize:" + map.width + "," + map.height); @@ -1350,7 +1350,7 @@ var TMXOrthoFlipTest = TileDemo.extend({ var TMXOrthoFlipRunTimeTest = TileDemo.extend({ ctor:function () { this._super(); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/ortho-rotation-test.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/ortho-rotation-test.tmx"); this.addChild(map, 0, TAG_TILE_MAP); this.log("ContentSize:" + map.width + "," + map.height); @@ -1435,8 +1435,8 @@ var TMXOrthoFromXMLTest = TileDemo.extend({ ctor:function () { this._super(); - var resources = s_resprefix + "TileMaps"; - var filePath = s_resprefix + "TileMaps/orthogonal-test1.tmx"; + var resources = "res/TileMaps"; + var filePath = "res/TileMaps/orthogonal-test1.tmx"; var xmlStr = cc.loader.getRes(filePath); var map = new cc.TMXTiledMap(xmlStr, resources); this.addChild(map, 0, TAG_TILE_MAP); @@ -1485,7 +1485,7 @@ var TMXOrthoFromXMLTest = TileDemo.extend({ var TMXBug987 = TileDemo.extend({ ctor:function () { this._super(); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/orthogonal-test6.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/orthogonal-test6.tmx"); this.addChild(map, 0, TAG_TILE_MAP); this.log("ContentSize:" + map.width + "," + map.height); @@ -1540,7 +1540,7 @@ var TMXBug987 = TileDemo.extend({ var TMXBug787 = TileDemo.extend({ ctor:function () { this._super(); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/iso-test-bug787.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/iso-test-bug787.tmx"); this.addChild(map, 0, TAG_TILE_MAP); map.scale = 0.25; @@ -1576,7 +1576,7 @@ var TMXGIDObjectsTest = TileDemo.extend({ drawNode.setDrawColor(cc.color(255,255,255,255)); this.addChild(drawNode); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/test-object-layer.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/test-object-layer.tmx"); this.addChild(map, 0, TAG_TILE_MAP); this.log("ContentSize:" + map.width + "," + map.height); @@ -1639,7 +1639,7 @@ var TMXGIDObjectsTest = TileDemo.extend({ var TMXIsoOffsetTest = TileDemo.extend({ ctor:function () { this._super(); - var map = new cc.TMXTiledMap(s_resprefix + "TileMaps/tile_iso_offset.tmx"); + var map = new cc.TMXTiledMap("res/TileMaps/tile_iso_offset.tmx"); this.addChild(map, 0, TAG_TILE_MAP); }, diff --git a/test/visual-tests/src/tests-main.js b/test/visual-tests/src/tests-main.js index da5026e1ca..8de946bcb1 100644 --- a/test/visual-tests/src/tests-main.js +++ b/test/visual-tests/src/tests-main.js @@ -333,14 +333,6 @@ var testNames = [ return new LayerTestScene(); } }, - { - title:"Loader Test", - platforms: PLATFORM_ALL, - linksrc:"src/LoaderTest/LoaderTest.js", - testScene:function () { - return new LoaderTestScene(); - } - }, { title:"Node Test", platforms: PLATFORM_ALL, diff --git a/test/visual-tests/src/tests_resources.js b/test/visual-tests/src/tests_resources.js index 43adc2a1c1..3999ef644e 100644 --- a/test/visual-tests/src/tests_resources.js +++ b/test/visual-tests/src/tests_resources.js @@ -1,225 +1,209 @@ -// Resources prefix -var s_resprefix = ""; -var ccbjs = ""; -// js-test use cpptest resource in debug mode , and in the release mode, console will copy the resource into the res dir -// so the respath will modify to res, -if (!cc.sys.isNative) -{ - cc.game._loadConfig(); - if (cc.game.config[cc.game.CONFIG_KEY.engineDir] !== "frameworks/cocos2d-html5") { - ccbjs = "../../js-tests/resjs/"; - } - else - { - ccbjs = ""; - } +var res = "res/"; -} - -var s_pathGrossini = "Images/grossini.png"; -var s_pathSister1 = "Images/grossinis_sister1.png"; -var s_pathSister2 = "Images/grossinis_sister2.png"; -var s_pathB1 = "Images/b1.png"; -var s_pathB2 = "Images/b2.png"; -var s_pathR1 = "Images/r1.png"; -var s_pathR2 = "Images/r2.png"; -var s_pathF1 = "Images/f1.png"; -var s_pathF2 = "Images/f2.png"; -var s_pathBlock = "Images/blocks.png"; -var s_back = "Images/background.png"; +var s_pathGrossini = "res/Images/grossini.png"; +var s_pathSister1 = "res/Images/grossinis_sister1.png"; +var s_pathSister2 = "res/Images/grossinis_sister2.png"; +var s_pathB1 = "res/Images/b1.png"; +var s_pathB2 = "res/Images/b2.png"; +var s_pathR1 = "res/Images/r1.png"; +var s_pathR2 = "res/Images/r2.png"; +var s_pathF1 = "res/Images/f1.png"; +var s_pathF2 = "res/Images/f2.png"; +var s_pathBlock = "res/Images/blocks.png"; +var s_back = "res/Images/background.png"; var s_back1 = "res/Images/background1.png"; var s_back2 = "res/Images/background2.png"; -var s_back3 = "Images/background3.png"; -var s_stars1 = "Images/stars.png"; -var s_stars2 = "Images/stars2.png"; -var s_fire = "Images/fire.png"; -var s_snow = "Images/snow.png"; -var s_streak = "Images/streak.png"; -var s_playNormal = "Images/btn-play-normal.png"; -var s_playSelect = "Images/btn-play-selected.png"; -var s_aboutNormal = "Images/btn-about-normal.png"; -var s_aboutSelect = "Images/btn-about-selected.png"; -var s_highNormal = "Images/btn-highscores-normal.png"; -var s_highSelect = "Images/btn-highscores-selected.png"; -var s_ball = "Images/ball.png"; -var s_paddle = "Images/paddle.png"; -var s_pathClose = "Images/close.png"; -var s_menuItem = "Images/menuitemsprite.png"; -var s_shapeModeMenuItem = "Images/shapemode.png"; -var s_textureModeMenuItem = "Images/texturemode.png"; -var s_MovementMenuItem = "Images/movement.png"; -var s_sendScore = "Images/SendScoreButton.png"; -var s_pressSendScore = "Images/SendScoreButtonPressed.png"; -var s_power = "Images/powered.png"; -var s_atlasTest = "Images/atlastest.png"; -var s_stars2Grayscale = "Images/stars2-grayscale.png"; -var s_starsGrayscale = "Images/stars-grayscale.png"; -var s_grossini_dance_atlas = "Images/grossini_dance_atlas.png"; -var s_piece = "Images/piece.png"; -var s_grossini_dance_atlas_mono = "Images/grossini_dance_atlas-mono.png"; -var s_lookup_desktop_plist = "Images/lookup-desktop.plist"; -var s_lookup_mobile_plist = "Images/lookup-mobile.plist"; -var s_lookup_html5_plist = "Images/lookup-html5.plist"; +var s_back3 = "res/Images/background3.png"; +var s_stars1 = "res/Images/stars.png"; +var s_stars2 = "res/Images/stars2.png"; +var s_fire = "res/Images/fire.png"; +var s_snow = "res/Images/snow.png"; +var s_streak = "res/Images/streak.png"; +var s_playNormal = "res/Images/btn-play-normal.png"; +var s_playSelect = "res/Images/btn-play-selected.png"; +var s_aboutNormal = "res/Images/btn-about-normal.png"; +var s_aboutSelect = "res/Images/btn-about-selected.png"; +var s_highNormal = "res/Images/btn-highscores-normal.png"; +var s_highSelect = "res/Images/btn-highscores-selected.png"; +var s_ball = "res/Images/ball.png"; +var s_paddle = "res/Images/paddle.png"; +var s_pathClose = "res/Images/close.png"; +var s_menuItem = "res/Images/menuitemsprite.png"; +var s_shapeModeMenuItem = "res/Images/shapemode.png"; +var s_textureModeMenuItem = "res/Images/texturemode.png"; +var s_MovementMenuItem = "res/Images/movement.png"; +var s_sendScore = "res/Images/SendScoreButton.png"; +var s_pressSendScore = "res/Images/SendScoreButtonPressed.png"; +var s_power = "res/Images/powered.png"; +var s_atlasTest = "res/Images/atlastest.png"; +var s_stars2Grayscale = "res/Images/stars2-grayscale.png"; +var s_starsGrayscale = "res/Images/stars-grayscale.png"; +var s_grossini_dance_atlas = "res/Images/grossini_dance_atlas.png"; +var s_piece = "res/Images/piece.png"; +var s_grossini_dance_atlas_mono = "res/Images/grossini_dance_atlas-mono.png"; +var s_lookup_desktop_plist = "res/Images/lookup-desktop.plist"; +var s_lookup_mobile_plist = "res/Images/lookup-mobile.plist"; +var s_lookup_html5_plist = "res/Images/lookup-html5.plist"; -var s_grossini = "animations/grossini.png"; -var s_grossini_gray = "animations/grossini_gray.png"; -var s_grossini_blue = "animations/grossini_blue.png"; -var s_grossini_aliases = "animations/grossini-aliases.png"; -var s_dragon_animation = "animations/dragon_animation.png"; -var s_ghosts = "animations/ghosts.png"; -var s_grossini_family = "animations/grossini_family.png"; +var s_grossini = "res/animations/grossini.png"; +var s_grossini_gray = "res/animations/grossini_gray.png"; +var s_grossini_blue = "res/animations/grossini_blue.png"; +var s_grossini_aliases = "res/animations/grossini-aliases.png"; +var s_dragon_animation = "res/animations/dragon_animation.png"; +var s_ghosts = "res/animations/ghosts.png"; +var s_grossini_family = "res/animations/grossini_family.png"; -var s_tcc_issue_1 = "animations/tcc_issue_1.png"; -var s_tcc_issue_2 = "animations/tcc_issue_2.png"; -var s_tcc_issue_1_plist = "animations/tcc_issue_1.plist"; -var s_tcc_issue_2_plist = "animations/tcc_issue_2.plist"; +var s_tcc_issue_1 = "res/animations/tcc_issue_1.png"; +var s_tcc_issue_2 = "res/animations/tcc_issue_2.png"; +var s_tcc_issue_1_plist = "res/animations/tcc_issue_1.plist"; +var s_tcc_issue_2_plist = "res/animations/tcc_issue_2.plist"; -var s_Cowboy_json = "ccs-res/armature/Cowboy.ExportJson"; -var s_Cowboy_plist = "ccs-res/armature/Cowboy0.plist"; -var s_Cowboy_png = "ccs-res/armature/Cowboy0.png"; -var s_hero_json = "ccs-res/armature/hero.ExportJson"; -var s_hero0_plist = "ccs-res/armature/hero0.plist"; -var s_hero0_png = "ccs-res/armature/hero0.png"; -var s_horse_json = "ccs-res/armature/horse.ExportJson"; -var s_horse0_plist = "ccs-res/armature/horse0.plist"; -var s_horse0_png = "ccs-res/armature/horse0.png"; -var s_bear_json = "ccs-res/armature/bear.ExportJson"; -var s_bear0_plist = "ccs-res/armature/bear0.plist"; -var s_bear0_png = "ccs-res/armature/bear0.png"; -var s_blood_plist = "ccs-res/armature/blood.plist"; -var s_HeroAnimation_json = "ccs-res/armature/HeroAnimation.ExportJson"; -var s_HeroAnimation0_plist = "ccs-res/armature/HeroAnimation0.plist"; -var s_HeroAnimation0_png = "ccs-res/armature/HeroAnimation0.png"; -var s_cyborg_plist = "ccs-res/armature/cyborg.plist"; -var s_cyborg_png = "ccs-res/armature/cyborg.png"; -var s_cyborg_xml = "ccs-res/armature/cyborg.xml"; -var s_Dragon_plist = "ccs-res/armature/Dragon.plist"; -var s_Dragon_png = "ccs-res/armature/Dragon.png"; -var s_Dragon_xml = "ccs-res/armature/Dragon.xml"; -var s_knight_plist = "ccs-res/armature/knight.plist"; -var s_knight_png = "ccs-res/armature/knight.png"; -var s_knight_xml = "ccs-res/armature/knight.xml"; -var s_robot_plist = "ccs-res/armature/robot.plist"; -var s_robot_png = "ccs-res/armature/robot.png"; -var s_robot_xml = "ccs-res/armature/robot.xml"; -var s_weapon_plist = "ccs-res/armature/weapon.plist"; -var s_weapon_png = "ccs-res/armature/weapon.png"; -var s_weapon_xml = "ccs-res/armature/weapon.xml"; -var s_testEasing_json = "ccs-res/armature/testEasing.ExportJson"; -var s_testEasing0_plist = "ccs-res/armature/testEasing0.plist"; -var s_testEasing0_png = "ccs-res/armature/testEasing0.png"; +var s_Cowboy_json = "res/ccs-res/armature/Cowboy.ExportJson"; +var s_Cowboy_plist = "res/ccs-res/armature/Cowboy0.plist"; +var s_Cowboy_png = "res/ccs-res/armature/Cowboy0.png"; +var s_hero_json = "res/ccs-res/armature/hero.ExportJson"; +var s_hero0_plist = "res/ccs-res/armature/hero0.plist"; +var s_hero0_png = "res/ccs-res/armature/hero0.png"; +var s_horse_json = "res/ccs-res/armature/horse.ExportJson"; +var s_horse0_plist = "res/ccs-res/armature/horse0.plist"; +var s_horse0_png = "res/ccs-res/armature/horse0.png"; +var s_bear_json = "res/ccs-res/armature/bear.ExportJson"; +var s_bear0_plist = "res/ccs-res/armature/bear0.plist"; +var s_bear0_png = "res/ccs-res/armature/bear0.png"; +var s_blood_plist = "res/ccs-res/armature/blood.plist"; +var s_HeroAnimation_json = "res/ccs-res/armature/HeroAnimation.ExportJson"; +var s_HeroAnimation0_plist = "res/ccs-res/armature/HeroAnimation0.plist"; +var s_HeroAnimation0_png = "res/ccs-res/armature/HeroAnimation0.png"; +var s_cyborg_plist = "res/ccs-res/armature/cyborg.plist"; +var s_cyborg_png = "res/ccs-res/armature/cyborg.png"; +var s_cyborg_xml = "res/ccs-res/armature/cyborg.xml"; +var s_Dragon_plist = "res/ccs-res/armature/Dragon.plist"; +var s_Dragon_png = "res/ccs-res/armature/Dragon.png"; +var s_Dragon_xml = "res/ccs-res/armature/Dragon.xml"; +var s_knight_plist = "res/ccs-res/armature/knight.plist"; +var s_knight_png = "res/ccs-res/armature/knight.png"; +var s_knight_xml = "res/ccs-res/armature/knight.xml"; +var s_robot_plist = "res/ccs-res/armature/robot.plist"; +var s_robot_png = "res/ccs-res/armature/robot.png"; +var s_robot_xml = "res/ccs-res/armature/robot.xml"; +var s_weapon_plist = "res/ccs-res/armature/weapon.plist"; +var s_weapon_png = "res/ccs-res/armature/weapon.png"; +var s_weapon_xml = "res/ccs-res/armature/weapon.xml"; +var s_testEasing_json = "res/ccs-res/armature/testEasing.ExportJson"; +var s_testEasing0_plist = "res/ccs-res/armature/testEasing0.plist"; +var s_testEasing0_png = "res/ccs-res/armature/testEasing0.png"; -var s_s9s_blocks9 = "Images/blocks9ss.png"; -var s_s9s_blocks9_plist = "Images/blocks9ss.plist"; +var s_s9s_blocks9 = "res/Images/blocks9ss.png"; +var s_s9s_blocks9_plist = "res/Images/blocks9ss.plist"; var s_blocks9 = "res/Images/blocks9.png"; -var s_s9s_ui = "Images/ui.png"; -var s_s9s_ui_plist = "Images/ui.plist"; +var s_s9s_ui = "res/Images/ui.png"; +var s_s9s_ui_plist = "res/Images/ui.plist"; -var s_boilingFoamPlist = "Images/BoilingFoam.plist"; -var s_grossiniPlist = "animations/grossini.plist"; -var s_grossini_grayPlist = "animations/grossini_gray.plist"; -var s_grossini_bluePlist = "animations/grossini_blue.plist"; -var s_grossini_aliasesPlist = "animations/grossini-aliases.plist"; -var s_ghostsPlist = "animations/ghosts.plist"; -var s_grossini_familyPlist = "animations/grossini_family.plist"; -var s_animations2Plist = "animations/animations-2.plist"; -var s_animationsPlist = "animations/animations.plist"; +var s_boilingFoamPlist = "res/Images/BoilingFoam.plist"; +var s_grossiniPlist = "res/animations/grossini.plist"; +var s_grossini_grayPlist = "res/animations/grossini_gray.plist"; +var s_grossini_bluePlist = "res/animations/grossini_blue.plist"; +var s_grossini_aliasesPlist = "res/animations/grossini-aliases.plist"; +var s_ghostsPlist = "res/animations/ghosts.plist"; +var s_grossini_familyPlist = "res/animations/grossini_family.plist"; +var s_animations2Plist = "res/animations/animations-2.plist"; +var s_animationsPlist = "res/animations/animations.plist"; -var s_helloWorld = "Images/HelloWorld.png"; -var s_grossiniDance01 = "Images/grossini_dance_01.png"; -var s_grossiniDance02 = "Images/grossini_dance_02.png"; -var s_grossiniDance03 = "Images/grossini_dance_03.png"; -var s_grossiniDance04 = "Images/grossini_dance_04.png"; -var s_grossiniDance05 = "Images/grossini_dance_05.png"; -var s_grossiniDance06 = "Images/grossini_dance_06.png"; -var s_grossiniDance07 = "Images/grossini_dance_07.png"; -var s_grossiniDance08 = "Images/grossini_dance_08.png"; -var s_grossiniDance09 = "Images/grossini_dance_09.png"; -var s_grossiniDance10 = "Images/grossini_dance_10.png"; -var s_grossiniDance11 = "Images/grossini_dance_11.png"; -var s_grossiniDance12 = "Images/grossini_dance_12.png"; -var s_grossiniDance13 = "Images/grossini_dance_13.png"; -var s_grossiniDance14 = "Images/grossini_dance_14.png"; +var s_helloWorld = "res/Images/HelloWorld.png"; +var s_grossiniDance01 = "res/Images/grossini_dance_01.png"; +var s_grossiniDance02 = "res/Images/grossini_dance_02.png"; +var s_grossiniDance03 = "res/Images/grossini_dance_03.png"; +var s_grossiniDance04 = "res/Images/grossini_dance_04.png"; +var s_grossiniDance05 = "res/Images/grossini_dance_05.png"; +var s_grossiniDance06 = "res/Images/grossini_dance_06.png"; +var s_grossiniDance07 = "res/Images/grossini_dance_07.png"; +var s_grossiniDance08 = "res/Images/grossini_dance_08.png"; +var s_grossiniDance09 = "res/Images/grossini_dance_09.png"; +var s_grossiniDance10 = "res/Images/grossini_dance_10.png"; +var s_grossiniDance11 = "res/Images/grossini_dance_11.png"; +var s_grossiniDance12 = "res/Images/grossini_dance_12.png"; +var s_grossiniDance13 = "res/Images/grossini_dance_13.png"; +var s_grossiniDance14 = "res/Images/grossini_dance_14.png"; -var s_arrows = "Images/arrows.png"; -var s_arrowsBar = "Images/arrowsBar.png"; -var s_arrows_hd = "Images/arrows-hd.png"; -var s_arrowsBar_hd = "Images/arrowsBar-hd.png"; +var s_arrows = "res/Images/arrows.png"; +var s_arrowsBar = "res/Images/arrowsBar.png"; +var s_arrows_hd = "res/Images/arrows-hd.png"; +var s_arrowsBar_hd = "res/Images/arrowsBar-hd.png"; // tilemaps resource -var s_tilesPng = "TileMaps/tiles.png"; -var s_levelMapTga = "TileMaps/levelmap.tga"; -var s_fixedOrthoTest2Png = "TileMaps/fixed-ortho-test2.png"; -var s_hexaTilesPng = "TileMaps/hexa-tiles.png"; -var s_isoTestPng = "TileMaps/iso-test.png"; -var s_isoTest2Png = "TileMaps/iso-test2.png"; -var s_isoPng = "TileMaps/iso.png"; -var s_orthoTest1BwPng = "TileMaps/ortho-test1_bw.png"; -var s_orthoTest1Png = "TileMaps/ortho-test1.png"; -var s_tilesHdPng = "TileMaps/tiles-hd.png"; -var s_tmwDesertSpacingHdPng = "TileMaps/tmw_desert_spacing-hd.png"; -var s_tmwDesertSpacingPng = "TileMaps/tmw_desert_spacing.png"; -var s_tileISOOffsetPng = "TileMaps/tile_iso_offset.png"; -var s_tileISOOffsetTmx = "TileMaps/tile_iso_offset.tmx"; +var s_tilesPng = "res/TileMaps/tiles.png"; +var s_levelMapTga = "res/TileMaps/levelmap.tga"; +var s_fixedOrthoTest2Png = "res/TileMaps/fixed-ortho-test2.png"; +var s_hexaTilesPng = "res/TileMaps/hexa-tiles.png"; +var s_isoTestPng = "res/TileMaps/iso-test.png"; +var s_isoTest2Png = "res/TileMaps/iso-test2.png"; +var s_isoPng = "res/TileMaps/iso.png"; +var s_orthoTest1BwPng = "res/TileMaps/ortho-test1_bw.png"; +var s_orthoTest1Png = "res/TileMaps/ortho-test1.png"; +var s_tilesHdPng = "res/TileMaps/tiles-hd.png"; +var s_tmwDesertSpacingHdPng = "res/TileMaps/tmw_desert_spacing-hd.png"; +var s_tmwDesertSpacingPng = "res/TileMaps/tmw_desert_spacing.png"; +var s_tileISOOffsetPng = "res/TileMaps/tile_iso_offset.png"; +var s_tileISOOffsetTmx = "res/TileMaps/tile_iso_offset.tmx"; -var s_fnTuffyBoldItalicCharmapPng = "fonts/tuffy_bold_italic-charmap.png"; -var s_fpsImages = "fps_images.png"; -var s_bitmapFontTest = "fonts/bitmapFontTest.png"; -var s_bitmapFontTest2 = "fonts/bitmapFontTest2.png"; -var s_bitmapFontTest3 = "fonts/bitmapFontTest3.png"; -var s_bitmapFontTest4 = "fonts/bitmapFontTest4.png"; -var s_bitmapFontTest5 = "fonts/bitmapFontTest5.png"; -var s_konqa32 = "fonts/konqa32.png"; -var s_konqa32_hd = "fonts/konqa32-hd.png"; -var s_bitmapFontChinese = "fonts/bitmapFontChinese.png"; -var s_arial16 = "fonts/arial16.png"; -var s_larabie_16 = "fonts/larabie-16.png"; -var s_larabie_16_hd = "fonts/larabie-16-hd.png"; -var s_futura48 = "fonts/futura-48.png"; -var s_arial_unicode_26 = "fonts/arial-unicode-26.png"; +var s_fnTuffyBoldItalicCharmapPng = "res/fonts/tuffy_bold_italic-charmap.png"; +var s_fpsImages = "res/fps_images.png"; +var s_bitmapFontTest = "res/fonts/bitmapFontTest.png"; +var s_bitmapFontTest2 = "res/fonts/bitmapFontTest2.png"; +var s_bitmapFontTest3 = "res/fonts/bitmapFontTest3.png"; +var s_bitmapFontTest4 = "res/fonts/bitmapFontTest4.png"; +var s_bitmapFontTest5 = "res/fonts/bitmapFontTest5.png"; +var s_konqa32 = "res/fonts/konqa32.png"; +var s_konqa32_hd = "res/fonts/konqa32-hd.png"; +var s_bitmapFontChinese = "res/fonts/bitmapFontChinese.png"; +var s_arial16 = "res/fonts/arial16.png"; +var s_larabie_16 = "res/fonts/larabie-16.png"; +var s_larabie_16_hd = "res/fonts/larabie-16-hd.png"; +var s_futura48 = "res/fonts/futura-48.png"; +var s_arial_unicode_26 = "res/fonts/arial-unicode-26.png"; -var s_bitmapFontTest_fnt = "fonts/bitmapFontTest.fnt"; -var s_bitmapFontTest2_fnt = "fonts/bitmapFontTest2.fnt"; -var s_bitmapFontTest3_fnt = "fonts/bitmapFontTest3.fnt"; -var s_bitmapFontTest4_fnt = "fonts/bitmapFontTest4.fnt"; -var s_bitmapFontTest5_fnt = "fonts/bitmapFontTest5.fnt"; -var s_konqa32_fnt = "fonts/konqa32.fnt"; -var s_konqa32_hd_fnt = "fonts/konqa32-hd.fnt"; -var s_bitmapFontChinese_fnt = "fonts/bitmapFontChinese.fnt"; -var s_arial16_fnt = "fonts/arial16.fnt"; -var s_futura48_fnt = "fonts/futura-48.fnt"; -var s_helvetica32_fnt = "fonts/helvetica-32.fnt"; -var s_geneva32_fnt = "fonts/geneva-32.fnt"; -var s_helvetica_helvetica_32_png = "fonts/helvetica-geneva-32.png"; -var s_arial_unicode_26_fnt = "fonts/arial-unicode-26.fnt"; -var s_markerFelt_fnt = "fonts/markerFelt.fnt"; -var s_markerFelt_png = "fonts/markerFelt.png"; -var s_markerFelt_hd_fnt = "fonts/markerFelt-hd.fnt"; -var s_markerFelt_hd_png = "fonts/markerFelt-hd.png"; +var s_bitmapFontTest_fnt = "res/fonts/bitmapFontTest.fnt"; +var s_bitmapFontTest2_fnt = "res/fonts/bitmapFontTest2.fnt"; +var s_bitmapFontTest3_fnt = "res/fonts/bitmapFontTest3.fnt"; +var s_bitmapFontTest4_fnt = "res/fonts/bitmapFontTest4.fnt"; +var s_bitmapFontTest5_fnt = "res/fonts/bitmapFontTest5.fnt"; +var s_konqa32_fnt = "res/fonts/konqa32.fnt"; +var s_konqa32_hd_fnt = "res/fonts/konqa32-hd.fnt"; +var s_bitmapFontChinese_fnt = "res/fonts/bitmapFontChinese.fnt"; +var s_arial16_fnt = "res/fonts/arial16.fnt"; +var s_futura48_fnt = "res/fonts/futura-48.fnt"; +var s_helvetica32_fnt = "res/fonts/helvetica-32.fnt"; +var s_geneva32_fnt = "res/fonts/geneva-32.fnt"; +var s_helvetica_helvetica_32_png = "res/fonts/helvetica-geneva-32.png"; +var s_arial_unicode_26_fnt = "res/fonts/arial-unicode-26.fnt"; +var s_markerFelt_fnt = "res/fonts/markerFelt.fnt"; +var s_markerFelt_png = "res/fonts/markerFelt.png"; +var s_markerFelt_hd_fnt = "res/fonts/markerFelt-hd.fnt"; +var s_markerFelt_hd_png = "res/fonts/markerFelt-hd.png"; -var s_larabie_16_plist = "fonts/larabie-16.plist"; -var s_larabie_16_hd_plist = "fonts/larabie-16-hd.plist"; -var s_tuffy_bold_italic_charmap = "fonts/tuffy_bold_italic-charmap.plist"; -var s_tuffy_bold_italic_charmap_hd = "fonts/tuffy_bold_italic-charmap-hd.plist"; +var s_larabie_16_plist = "res/fonts/larabie-16.plist"; +var s_larabie_16_hd_plist = "res/fonts/larabie-16-hd.plist"; +var s_tuffy_bold_italic_charmap = "res/fonts/tuffy_bold_italic-charmap.plist"; +var s_tuffy_bold_italic_charmap_hd = "res/fonts/tuffy_bold_italic-charmap-hd.plist"; -var s_particles = "Images/particles.png"; -var s_particles_hd = "Images/particles-hd.png"; -var s_texture512 = "Images/texture512x512.png"; -var s_hole_effect_png = "Images/hole_effect.png"; -var s_hole_stencil_png = "Images/hole_stencil.png"; -var s_pathFog = "Images/Fog.png"; -var s_circle_plist = "Images/bugs/circle.plist"; -var s_circle_png = "Images/bugs/circle.png"; +var s_particles = "res/Images/particles.png"; +var s_particles_hd = "res/Images/particles-hd.png"; +var s_texture512 = "res/Images/texture512x512.png"; +var s_hole_effect_png = "res/Images/hole_effect.png"; +var s_hole_stencil_png = "res/Images/hole_stencil.png"; +var s_pathFog = "res/Images/Fog.png"; +var s_circle_plist = "res/Images/bugs/circle.plist"; +var s_circle_png = "res/Images/bugs/circle.png"; -var s_extensions_background = "extensions/background.png"; -var s_extensions_buttonBackground = "extensions/buttonBackground.png"; -var s_extensions_button = "extensions/button.png"; -var s_extensions_buttonHighlighted = "extensions/buttonHighlighted.png"; -var s_extensions_ribbon = "extensions/ribbon.png"; -var s_image_icon = "Images/Icon.png"; -var s_html5_logo = "Images/cocos-html5.png"; +var s_extensions_background = "res/extensions/background.png"; +var s_extensions_buttonBackground = "res/extensions/buttonBackground.png"; +var s_extensions_button = "res/extensions/button.png"; +var s_extensions_buttonHighlighted = "res/extensions/buttonHighlighted.png"; +var s_extensions_ribbon = "res/extensions/ribbon.png"; +var s_image_icon = "res/Images/Icon.png"; +var s_html5_logo = "res/Images/cocos-html5.png"; var g_resources = [ //global @@ -272,7 +256,9 @@ var g_resources = [ s_playSelect, s_bitmapFontTest5_fnt, s_extensions_background, - s_extensions_ribbon + s_extensions_ribbon, + // s_back1, + // s_back2 ]; var g_sprites = [ @@ -299,8 +285,8 @@ var g_sprites = [ s_s9s_blocks9_plist, s_s9s_blocks9, - "Images/dot.png", - "Images/wood.jpg" + "res/Images/dot.png", + "res/Images/wood.jpg" ]; var g_menu = [ @@ -330,28 +316,28 @@ var g_s9s_blocks = [ var g_opengl_resources = [ //preload shader source - ccbjs + "Shaders/example_Outline.fsh", - ccbjs + "Shaders/example_Outline.vsh", - ccbjs + "Shaders/example_Blur.fsh", - ccbjs + "Shaders/example_ColorBars.fsh", - ccbjs + "Shaders/example_ColorBars.vsh", - ccbjs + "Shaders/example_Flower.fsh", - ccbjs + "Shaders/example_Flower.vsh", - ccbjs + "Shaders/example_Heart.fsh", - ccbjs + "Shaders/example_Heart.vsh", - ccbjs + "Shaders/example_Julia.fsh", - ccbjs + "Shaders/example_Julia.vsh", - ccbjs + "Shaders/example_Mandelbrot.fsh", - ccbjs + "Shaders/example_Mandelbrot.vsh", - ccbjs + "Shaders/example_Monjori.fsh", - ccbjs + "Shaders/example_Monjori.vsh", - ccbjs + "Shaders/example_Plasma.fsh", - ccbjs + "Shaders/example_Plasma.vsh", - ccbjs + "Shaders/example_Twist.fsh", - ccbjs + "Shaders/example_Twist.vsh", + res + "Shaders/example_Outline.fsh", + res + "Shaders/example_Outline.vsh", + res + "Shaders/example_Blur.fsh", + res + "Shaders/example_ColorBars.fsh", + res + "Shaders/example_ColorBars.vsh", + res + "Shaders/example_Flower.fsh", + res + "Shaders/example_Flower.vsh", + res + "Shaders/example_Heart.fsh", + res + "Shaders/example_Heart.vsh", + res + "Shaders/example_Julia.fsh", + res + "Shaders/example_Julia.vsh", + res + "Shaders/example_Mandelbrot.fsh", + res + "Shaders/example_Mandelbrot.vsh", + res + "Shaders/example_Monjori.fsh", + res + "Shaders/example_Monjori.vsh", + res + "Shaders/example_Plasma.fsh", + res + "Shaders/example_Plasma.vsh", + res + "Shaders/example_Twist.fsh", + res + "Shaders/example_Twist.vsh", - "fonts/west_england-64.fnt", - "fonts/west_england-64.png" + "res/fonts/west_england-64.fnt", + "res/fonts/west_england-64.png" ]; var g_label = [ @@ -395,7 +381,7 @@ var g_label = [ s_markerFelt_png, s_markerFelt_hd_fnt, s_markerFelt_hd_png, - "fonts/strings.xml" + "res/fonts/strings.xml" ]; var g_transitions = [ @@ -408,24 +394,24 @@ var g_box2d = [ ]; var g_cocosdeshion = [ - "background.mp3", - "effect2.mp3" + "res/background.mp3", + "res/effect2.mp3" //"background.ogg", //one sound only, cc.audio can auto select other format to load if the sound format isn't supported on some browser. //"effect2.ogg" ]; var g_parallax = [ - "TileMaps/orthogonal-test2.tmx", + "res/TileMaps/orthogonal-test2.tmx", s_fixedOrthoTest2Png, s_power, s_back ]; var g_eventDispatcher = [ - "Images/CyanSquare.png", - "Images/MagentaSquare.png", - "Images/YellowSquare.png", - "Images/ball.png", + "res/Images/CyanSquare.png", + "res/Images/MagentaSquare.png", + "res/Images/YellowSquare.png", + "res/Images/ball.png", s_extensions_button, s_extensions_buttonHighlighted, s_extensions_buttonBackground @@ -443,21 +429,21 @@ var g_particle = [ s_snow, s_particles, s_particles_hd, - "Particles/BoilingFoam.plist", - "Particles/BurstPipe.plist", - "Particles/Comet.plist", - "Particles/debian.plist", - "Particles/ExplodingRing.plist", - "Particles/Flower.plist", - "Particles/Galaxy.plist", - "Particles/LavaFlow.plist", - "Particles/Phoenix.plist", - "Particles/SmallSun.plist", - "Particles/SpinningPeas.plist", - "Particles/Spiral.plist", - "Particles/SpookyPeas.plist", - "Particles/TestPremultipliedAlpha.plist", - "Particles/Upsidedown.plist" + "res/Particles/BoilingFoam.plist", + "res/Particles/BurstPipe.plist", + "res/Particles/Comet.plist", + "res/Particles/debian.plist", + "res/Particles/ExplodingRing.plist", + "res/Particles/Flower.plist", + "res/Particles/Galaxy.plist", + "res/Particles/LavaFlow.plist", + "res/Particles/Phoenix.plist", + "res/Particles/SmallSun.plist", + "res/Particles/SpinningPeas.plist", + "res/Particles/Spiral.plist", + "res/Particles/SpookyPeas.plist", + "res/Particles/TestPremultipliedAlpha.plist", + "res/Particles/Upsidedown.plist" ]; var g_fonts = [ @@ -465,22 +451,22 @@ var g_fonts = [ { type:"font", name:"Thonburi", - srcs:["../cpp-tests/Resources/fonts/Thonburi.eot", "../cpp-tests/Resources/fonts/Thonburi.ttf"] + srcs:["res/fonts/Thonburi.eot", "res/fonts/Thonburi.ttf"] }, { type:"font", name:"Schwarzwald Regular", - srcs:["../cpp-tests/Resources/fonts/Schwarzwald_Regular.eot", "../cpp-tests/Resources/fonts/Schwarzwald Regular.ttf"] + srcs:["res/fonts/Schwarzwald_Regular.eot", "res/fonts/Schwarzwald Regular.ttf"] }, { type:"font", name:"ThonburiBold", - srcs:["../cpp-tests/Resources/fonts/ThonburiBold.eot", "../cpp-tests/Resources/fonts/ThonburiBold.ttf"] + srcs:["res/fonts/ThonburiBold.eot", "res/fonts/ThonburiBold.ttf"] }, { type:"font", name:"Courier New", - srcs:["../cpp-tests/Resources/fonts/Courier New.eot", "../cpp-tests/Resources/fonts/Courier New.ttf"] + srcs:["res/fonts/Courier New.eot", "res/fonts/Courier New.ttf"] } ]; @@ -488,490 +474,75 @@ var g_extensions = [ s_image_icon, ]; -var g_cocoStudio = [ - //Armature - s_Cowboy_json , - s_Cowboy_plist, - s_Cowboy_png, - s_hero_json, - s_hero0_plist, - s_hero0_png, - s_horse_json, - s_horse0_plist, - s_horse0_png, - s_bear_json, - s_bear0_plist, - s_bear0_png, - s_blood_plist, - s_HeroAnimation_json, - s_HeroAnimation0_plist, - s_HeroAnimation0_png, - s_cyborg_plist , - s_cyborg_png , - s_cyborg_xml , - s_Dragon_plist , - s_Dragon_png , - s_Dragon_xml , - s_knight_plist , - s_knight_png , - s_knight_xml , - s_robot_plist , - s_robot_png , - s_robot_xml , - s_weapon_plist , - s_weapon_png , - s_weapon_xml , - s_testEasing_json , - s_testEasing0_plist , - s_testEasing0_png , - -//GUI - "Particles/SmallSun.plist", - "Images/b1.png", - "Images/b2.png", - "Images/f1.png", - "Images/f2.png", - "ccs-res/cocosui/UIEditorTest/UIButton/background.png", - "ccs-res/cocosui/UIEditorTest/UIButton/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UIButton/buttonHighlighted.png", - "ccs-res/cocosui/UIEditorTest/UIButton/button_n.png", - "ccs-res/cocosui/UIEditorTest/UIButton/button_p.png", - "ccs-res/cocosui/UIEditorTest/UIButton/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UIButton/Button_1.json", - "ccs-res/cocosui/UIEditorTest/UICheckBox/background.png", - "ccs-res/cocosui/UIEditorTest/UICheckBox/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UICheckBox/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UICheckBox/selected01.png", - "ccs-res/cocosui/UIEditorTest/UICheckBox/selected02.png", - "ccs-res/cocosui/UIEditorTest/UICheckBox/checkbox_1.json", - "ccs-res/cocosui/UIEditorTest/UICheckBox/MainScene.json", - "ccs-res/cocosui/UIEditorTest/UICheckBox/Default/CheckBox_Disable.png", - "ccs-res/cocosui/UIEditorTest/UICheckBox/img/btn_music.png", - "ccs-res/cocosui/UIEditorTest/UICheckBox/img/btn_sound_off.png", - "ccs-res/cocosui/UIEditorTest/UIImageView/background.png", - "ccs-res/cocosui/UIEditorTest/UIImageView/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UIImageView/buttonHighlighted.png", - "ccs-res/cocosui/UIEditorTest/UIImageView/GUI/image.png", - "ccs-res/cocosui/UIEditorTest/UIImageView/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UIImageView/ImageView_1.json", - "ccs-res/cocosui/UIEditorTest/UILabelAtlas/background.png", - "ccs-res/cocosui/UIEditorTest/UILabelAtlas/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UILabelAtlas/GUI/labelatlasimg.png", - "ccs-res/cocosui/UIEditorTest/UILabelAtlas/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UILabelAtlas/labelatlas_1.json", - "ccs-res/cocosui/UIEditorTest/UILabelBMFont/background.png", - "ccs-res/cocosui/UIEditorTest/UILabelBMFont/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UILabelBMFont/GUI/missing-font.fnt", - "ccs-res/cocosui/UIEditorTest/UILabelBMFont/GUI/missing-font.png", - "ccs-res/cocosui/UIEditorTest/UILabelBMFont/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UILabelBMFont/labelbmfont_1.json", - "ccs-res/cocosui/UIEditorTest/UILabel/background.png", - "ccs-res/cocosui/UIEditorTest/UILabel/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UILabel/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UILabel/label_1.json", - "ccs-res/cocosui/UIEditorTest/UILayout/BackgroundImage/background.png", - "ccs-res/cocosui/UIEditorTest/UILayout/BackgroundImage/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UILayout/BackgroundImage/button_n.png", - "ccs-res/cocosui/UIEditorTest/UILayout/BackgroundImage/button_p.png", - "ccs-res/cocosui/UIEditorTest/UILayout/BackgroundImage/GUI/image.png", - "ccs-res/cocosui/UIEditorTest/UILayout/BackgroundImage/Hello.png", - "ccs-res/cocosui/UIEditorTest/UILayout/BackgroundImage/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UILayout/BackgroundImage/selected01.png", - "ccs-res/cocosui/UIEditorTest/UILayout/BackgroundImage/selected02.png", - "ccs-res/cocosui/UIEditorTest/UILayout/BackgroundImage/backgroundimage_1.json", - "ccs-res/cocosui/UIEditorTest/UILayout/Color/background.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Color/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Color/button_n.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Color/button_p.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Color/GUI/image.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Color/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Color/selected01.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Color/selected02.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Color/color_1.json", - "ccs-res/cocosui/UIEditorTest/UILayout/Layout/background.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Layout/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Layout/button_n.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Layout/button_p.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Layout/GUI/image.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Layout/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Layout/selected01.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Layout/selected02.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Layout/layout_1.json", - "ccs-res/cocosui/UIEditorTest/UILayout/Gradient_Color/background.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Gradient_Color/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Gradient_Color/button_n.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Gradient_Color/button_p.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Gradient_Color/GUI/image.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Gradient_Color/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Gradient_Color/selected01.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Gradient_Color/selected02.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Gradient_Color/gradient_color_1.json", - "ccs-res/cocosui/UIEditorTest/UILayout/Linear_Horizontal_Layout/background.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Linear_Horizontal_Layout/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Linear_Horizontal_Layout/button_n.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Linear_Horizontal_Layout/button_p.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Linear_Horizontal_Layout/GUI/image.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Linear_Horizontal_Layout/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Linear_Horizontal_Layout/selected01.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Linear_Horizontal_Layout/selected02.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Linear_Horizontal_Layout/linear_horizontal.json", - "ccs-res/cocosui/UIEditorTest/UILayout/Linear_Vertical_Layout/background.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Linear_Vertical_Layout/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Linear_Vertical_Layout/button_n.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Linear_Vertical_Layout/button_p.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Linear_Vertical_Layout/GUI/image.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Linear_Vertical_Layout/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Linear_Vertical_Layout/selected01.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Linear_Vertical_Layout/selected02.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Linear_Vertical_Layout/linear_vertical.json", - "ccs-res/cocosui/UIEditorTest/UILayout/Relative_Align_Location/background.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Relative_Align_Location/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Relative_Align_Location/button_n.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Relative_Align_Location/button_p.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Relative_Align_Location/GUI/image.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Relative_Align_Location/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Relative_Align_Location/selected01.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Relative_Align_Location/selected02.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Relative_Align_Location/relative_align_location.json", - "ccs-res/cocosui/UIEditorTest/UILayout/Relative_Align_Parent/background.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Relative_Align_Parent/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Relative_Align_Parent/button_n.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Relative_Align_Parent/button_p.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Relative_Align_Parent/GUI/image.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Relative_Align_Parent/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Relative_Align_Parent/selected01.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Relative_Align_Parent/selected02.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Relative_Align_Parent/relative_align_parent.json", - "ccs-res/cocosui/UIEditorTest/UILayout/Scale9_BackgroundImage/background.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Scale9_BackgroundImage/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Scale9_BackgroundImage/button_n.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Scale9_BackgroundImage/button_p.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Scale9_BackgroundImage/GUI/image.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Scale9_BackgroundImage/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Scale9_BackgroundImage/selected01.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Scale9_BackgroundImage/selected02.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Scale9_BackgroundImage/slider_bar.png", - "ccs-res/cocosui/UIEditorTest/UILayout/Scale9_BackgroundImage/scale9.json", - "ccs-res/cocosui/UIEditorTest/UIListView/Horizontal/background.png", - "ccs-res/cocosui/UIEditorTest/UIListView/Horizontal/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UIListView/Horizontal/button_p.png", - "ccs-res/cocosui/UIEditorTest/UIListView/Horizontal/GUI/button.png", - "ccs-res/cocosui/UIEditorTest/UIListView/Horizontal/GUI/image.png", - "ccs-res/cocosui/UIEditorTest/UIListView/Horizontal/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UIListView/Horizontal/horizontal_1.json", - "ccs-res/cocosui/UIEditorTest/UIListView/Vertical/background.png", - "ccs-res/cocosui/UIEditorTest/UIListView/Vertical/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UIListView/Vertical/button_p.png", - "ccs-res/cocosui/UIEditorTest/UIListView/Vertical/GUI/button.png", - "ccs-res/cocosui/UIEditorTest/UIListView/Vertical/GUI/image.png", - "ccs-res/cocosui/UIEditorTest/UIListView/Vertical/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UIListView/Vertical/vertical_1.json", - "ccs-res/cocosui/UIEditorTest/UILoadingBar/background.png", - "ccs-res/cocosui/UIEditorTest/UILoadingBar/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UILoadingBar/GUI/loadingbar.png", - "ccs-res/cocosui/UIEditorTest/UILoadingBar/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UILoadingBar/loadingbar_1.json", - "ccs-res/cocosui/UIEditorTest/UIPageView/background.png", - "ccs-res/cocosui/UIEditorTest/UIPageView/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UIPageView/button_n.png", - "ccs-res/cocosui/UIEditorTest/UIPageView/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UIPageView/pageview_1.json", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Both/background.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Both/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Both/button_n.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Both/button_p.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Both/GUI/image.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Both/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Both/selected01.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Both/selected02.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Both/both_1.json", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Horizontal/background.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Horizontal/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Horizontal/button_n.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Horizontal/button_p.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Horizontal/GUI/image.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Horizontal/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Horizontal/selected01.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Horizontal/selected02.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Horizontal/horizontal_1.json", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Vertical/background.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Vertical/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Vertical/button_n.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Vertical/button_p.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Vertical/GUI/image.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Vertical/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Vertical/selected01.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Vertical/selected02.png", - "ccs-res/cocosui/UIEditorTest/UIScrollView/Vertical/vertical_1.json", - "ccs-res/cocosui/UIEditorTest/UISlider/2014-1-26 11-42-09.png", - "ccs-res/cocosui/UIEditorTest/UISlider/2014-1-26 11-43-52.png", - "ccs-res/cocosui/UIEditorTest/UISlider/background.png", - "ccs-res/cocosui/UIEditorTest/UISlider/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UISlider/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UISlider/silder_progressBar.png", - "ccs-res/cocosui/UIEditorTest/UISlider/slider_bar.png", - "ccs-res/cocosui/UIEditorTest/UISlider/slider_bar_button.png", - "ccs-res/cocosui/UIEditorTest/UISlider/slider_1.json", - "ccs-res/cocosui/UIEditorTest/UITextField/background.png", - "ccs-res/cocosui/UIEditorTest/UITextField/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UITextField/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UITextField/textfield_1.json", - "ccs-res/cocosui/UIEditorTest/UIWidgetAddNode/background.png", - "ccs-res/cocosui/UIEditorTest/UIWidgetAddNode/buttonBackground.png", - "ccs-res/cocosui/UIEditorTest/UIWidgetAddNode/ribbon.png", - "ccs-res/cocosui/UIEditorTest/UIWidgetAddNode/widget_add_node.json", - "background-music-aac.wav", - "pew-pew-lei.wav", - //Components - "components/Player.png", - "components/Projectile.png", - "components/Target.png", - //Scene - "ccs-res/scenetest/ArmatureComponentTest/ArmatureComponentTest.json", - "ccs-res/scenetest/ArmatureComponentTest/fishes/blowFish/Blowfish.ExportJson", - "ccs-res/scenetest/ArmatureComponentTest/fishes/blowFish/Blowfish0.plist", - "ccs-res/scenetest/ArmatureComponentTest/fishes/blowFish/Blowfish0.png", - "ccs-res/scenetest/ArmatureComponentTest/fishes/Butterflyfish/Butterflyfish.ExportJson", - "ccs-res/scenetest/ArmatureComponentTest/fishes/Butterflyfish/Butterflyfish0.plist", - "ccs-res/scenetest/ArmatureComponentTest/fishes/Butterflyfish/Butterflyfish0.png", - "ccs-res/scenetest/ArmatureComponentTest/Images/startMenuBG.png", - "ccs-res/scenetest/AttributeComponentTest/AttributeComponentTest.json", - "ccs-res/scenetest/AttributeComponentTest/grossinis_sister1.png", - "ccs-res/scenetest/AttributeComponentTest/grossinis_sister2.png", - "ccs-res/scenetest/AttributeComponentTest/PlayerAttribute.json", - "ccs-res/scenetest/BackgroundComponentTest/BackgroundComponentTest.json", - "ccs-res/scenetest/BackgroundComponentTest/Images/startMenuBG.png", - "ccs-res/scenetest/BackgroundComponentTest/Misc/music_logo.mp3", - "ccs-res/scenetest/BackgroundComponentTest/Misc/music_logo.wav", - "ccs-res/scenetest/BackgroundComponentTest/Particles/qipao01.plist", - "ccs-res/scenetest/BackgroundComponentTest/Particles/qipao01.png", - "ccs-res/scenetest/BackgroundComponentTest/startMenu/Fish_UI/starMenuButton01.png", - "ccs-res/scenetest/BackgroundComponentTest/startMenu/Fish_UI/starMenuButton02.png", - "ccs-res/scenetest/BackgroundComponentTest/startMenu/Fish_UI/ui_logo_001-hd.png", - "ccs-res/scenetest/BackgroundComponentTest/startMenu/startMenu_1.json", - "ccs-res/scenetest/EffectComponentTest/CowBoy/Cowboy.ExportJson", - "ccs-res/scenetest/EffectComponentTest/CowBoy/Cowboy0.plist", - "ccs-res/scenetest/EffectComponentTest/CowBoy/Cowboy0.png", - "ccs-res/scenetest/EffectComponentTest/EffectComponentTest.json", - "ccs-res/scenetest/EffectComponentTest/pew-pew-lei.wav", - "ccs-res/scenetest/LoadSceneEdtiorFileTest/fishes/blowFish/Blowfish.ExportJson", - "ccs-res/scenetest/LoadSceneEdtiorFileTest/fishes/blowFish/Blowfish0.plist", - "ccs-res/scenetest/LoadSceneEdtiorFileTest/fishes/blowFish/Blowfish0.png", - "ccs-res/scenetest/LoadSceneEdtiorFileTest/fishes/Butterflyfish/Butterflyfish.ExportJson", - "ccs-res/scenetest/LoadSceneEdtiorFileTest/fishes/Butterflyfish/Butterflyfish0.plist", - "ccs-res/scenetest/LoadSceneEdtiorFileTest/fishes/Butterflyfish/Butterflyfish0.png", - "ccs-res/scenetest/LoadSceneEdtiorFileTest/FishJoy2.json", - "ccs-res/scenetest/LoadSceneEdtiorFileTest/Images/startMenuBG.png", - "ccs-res/scenetest/LoadSceneEdtiorFileTest/Misc/music_logo.mp3", - "ccs-res/scenetest/LoadSceneEdtiorFileTest/Misc/music_logo.wav", - "ccs-res/scenetest/LoadSceneEdtiorFileTest/Particles/qipao01.plist", - "ccs-res/scenetest/LoadSceneEdtiorFileTest/Particles/qipao01.png", - "ccs-res/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/starMenuButton01.png", - "ccs-res/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/starMenuButton02.png", - "ccs-res/scenetest/LoadSceneEdtiorFileTest/startMenu/Fish_UI/ui_logo_001-hd.png", - "ccs-res/scenetest/LoadSceneEdtiorFileTest/startMenu/startMenu_1.json", - "ccs-res/scenetest/ParticleComponentTest/ParticleComponentTest.json", - "ccs-res/scenetest/ParticleComponentTest/SmallSun.plist", - "ccs-res/scenetest/ParticleComponentTest/Upsidedown.plist", - "ccs-res/scenetest/SpriteComponentTest/grossinis_sister1.png", - "ccs-res/scenetest/SpriteComponentTest/grossinis_sister2.png", - "ccs-res/scenetest/SpriteComponentTest/SpriteComponentTest.json", - "ccs-res/scenetest/TmxMapComponentTest/iso-test.png", - "ccs-res/scenetest/TmxMapComponentTest/iso-test.tmx", - "ccs-res/scenetest/TmxMapComponentTest/TmxMapComponentTest.json", - "ccs-res/scenetest/TriggerTest/fishes/blowFish/Blowfish.ExportJson", - "ccs-res/scenetest/TriggerTest/fishes/blowFish/Blowfish0.plist", - "ccs-res/scenetest/TriggerTest/fishes/blowFish/Blowfish0.png", - "ccs-res/scenetest/TriggerTest/fishes/Butterflyfish/Butterflyfish.ExportJson", - "ccs-res/scenetest/TriggerTest/fishes/Butterflyfish/Butterflyfish0.plist", - "ccs-res/scenetest/TriggerTest/fishes/Butterflyfish/Butterflyfish0.png", - "ccs-res/scenetest/TriggerTest/Images/startMenuBG.png", - "ccs-res/scenetest/TriggerTest/TriggerTest.json", - "ccs-res/scenetest/UIComponentTest/fishes/blowFish/Blowfish.ExportJson", - "ccs-res/scenetest/UIComponentTest/fishes/blowFish/Blowfish0.plist", - "ccs-res/scenetest/UIComponentTest/fishes/blowFish/Blowfish0.png", - "ccs-res/scenetest/UIComponentTest/fishes/Butterflyfish/Butterflyfish.ExportJson", - "ccs-res/scenetest/UIComponentTest/fishes/Butterflyfish/Butterflyfish0.plist", - "ccs-res/scenetest/UIComponentTest/fishes/Butterflyfish/Butterflyfish0.png", - "ccs-res/scenetest/UIComponentTest/Images/startMenuBG.png", - "ccs-res/scenetest/UIComponentTest/starMenuButton/starMenuButton.ExportJson", - "ccs-res/scenetest/UIComponentTest/starMenuButton/starMenuButton0.plist", - "ccs-res/scenetest/UIComponentTest/starMenuButton/starMenuButton0.png", - "ccs-res/scenetest/UIComponentTest/UIComponentTest.json", - - //parser - "ccs-res/cocosui/UIEditorTest/cocostudio1_3/CocostudioV1_3_1.ExportJson", - "ccs-res/cocosui/UIEditorTest/cocostudio1_3/CocostudioV1_30.plist", - "ccs-res/cocosui/UIEditorTest/cocostudio1_3/CocostudioV1_30.png", - "ccs-res/cocosui/UIEditorTest/cocostudio1_3/SmallSun.plist", - "ccs-res/cocosui/UIEditorTest/cocostudio1_3/GUI/labelatlasimg.png", - "ccs-res/cocosui/UIEditorTest/cocostudio1_3/GUI/missing-font.fnt", - "ccs-res/cocosui/UIEditorTest/cocostudio1_3/GUI/missing-font.png", - "ccs-res/cocosui/UIEditorTest/cocostudio1_4/Cocostudio1_4_1.ExportJson", - "ccs-res/cocosui/UIEditorTest/cocostudio1_4/Cocostudio1_40.plist", - "ccs-res/cocosui/UIEditorTest/cocostudio1_4/Cocostudio1_40.png", - "ccs-res/cocosui/UIEditorTest/cocostudio1_4/SmallSun.plist", - "ccs-res/cocosui/UIEditorTest/cocostudio1_4/GUI/labelatlasimg.png", - "ccs-res/cocosui/UIEditorTest/cocostudio1_4/GUI/missing-font.fnt", - "ccs-res/cocosui/UIEditorTest/cocostudio1_4/GUI/missing-font.png", - "ccs-res/cocosui/UIEditorTest/cocostudio1_5/Cocostudio1_5_1.ExportJson", - "ccs-res/cocosui/UIEditorTest/cocostudio1_5/Cocostudio1_50.plist", - "ccs-res/cocosui/UIEditorTest/cocostudio1_5/Cocostudio1_50.png", - "ccs-res/cocosui/UIEditorTest/cocostudio1_5/SmallSun.plist", - "ccs-res/cocosui/UIEditorTest/cocostudio1_5/GUI/labelatlasimg.png", - "ccs-res/cocosui/UIEditorTest/cocostudio1_5/GUI/missing-font.fnt", - "ccs-res/cocosui/UIEditorTest/cocostudio1_5/GUI/missing-font.png", - - "ccs-res/cocosui/UIEditorTest/2.1/MainScene.json", - "ccs-res/cocosui/UIEditorTest/2.1/plist1/Plist.plist", - "ccs-res/cocosui/UIEditorTest/2.1/Plist/ui.plist", - "ccs-res/cocosui/UIEditorTest/2.1/LoadingBar/pipe2.png", - "ccs-res/cocosui/UIEditorTest/2.1/Slider/2013-8-13 15-44-11.png", - "ccs-res/cocosui/UIEditorTest/2.1/Slider/teehanlax - iOS 6 - iPhone_slider01.png", - "ccs-res/cocosui/UIEditorTest/2.1/particle/blue.plist", - "ccs-res/cocosui/UIEditorTest/2.1/Default/Slider_Back.png", - "ccs-res/cocosui/UIEditorTest/2.1/Default/SliderNode_Normal.png", - "ccs-res/cocosui/UIEditorTest/2.1/Default/SliderNode_Press.png", - "ccs-res/cocosui/UIEditorTest/2.1/Default/SliderNode_Disable.png", - "ccs-res/cocosui/UIEditorTest/2.1/Default/Slider_PressBar.png", - "ccs-res/cocosui/UIEditorTest/2.1/Default/defaultParticle.plist", - "ccs-res/cocosui/UIEditorTest/2.1/Default/TextAtlas.png", - "ccs-res/cocosui/UIEditorTest/2.1/fonts_weapon_001-hd.png", - "ccs-res/cocosui/UIEditorTest/2.1/FNT/futura.fnt", - "ccs-res/cocosui/UIEditorTest/2.1/Default/defaultBMFont.fnt", - "ccs-res/cocosui/UIEditorTest/2.1/FNT/Heiti18.fnt", - - "Particles/BoilingFoam.plist", - "ccs-res/cocosui/CustomImageViewTest/NewProject_2_1.ExportJson", - "ccs-res/cocosui/CustomImageViewTest/NewProject_20.plist", - "ccs-res/cocosui/CustomImageViewTest/NewProject_20.png", - - "ActionTimeline/DemoPlayer_skeleton.json" -]; - -var g_ui = [ - "ccs-res/cocosui/switch-mask.png", - "ccs-res/cocosui/animationbuttonnormal.png", - "ccs-res/cocosui/animationbuttonpressed.png", - "ccs-res/cocosui/arrow.png", - "ccs-res/cocosui/b11.png", - "ccs-res/cocosui/backtotopnormal.png", - "ccs-res/cocosui/backtotoppressed.png", - "ccs-res/cocosui/bitmapFontTest2.fnt", - "ccs-res/cocosui/bitmapFontTest2.png", - "ccs-res/cocosui/button.png", - "ccs-res/cocosui/buttonHighlighted.png", - "ccs-res/cocosui/ccicon.png", - "ccs-res/cocosui/check_box_active.png", - "ccs-res/cocosui/check_box_active_disable.png", - "ccs-res/cocosui/check_box_active_press.png", - "ccs-res/cocosui/check_box_normal.png", - "ccs-res/cocosui/check_box_normal_disable.png", - "ccs-res/cocosui/check_box_normal_press.png", - "ccs-res/cocosui/CloseNormal.png", - "ccs-res/cocosui/CloseSelected.png", - "ccs-res/cocosui/green_edit.png", - "ccs-res/cocosui/grossini-aliases.png", - "ccs-res/cocosui/Hello.png", - "ccs-res/cocosui/labelatlas.png", - "ccs-res/cocosui/loadingbar.png", - {type:"font", name:"Marker Felt", srcs:["../cpp-tests/Resources/fonts/Marker Felt.ttf"]}, - "ccs-res/cocosui/scrollviewbg.png", - "ccs-res/cocosui/slidbar.png", - "ccs-res/cocosui/sliderballnormal.png", - "ccs-res/cocosui/sliderballpressed.png", - "ccs-res/cocosui/sliderProgress.png", - "ccs-res/cocosui/sliderProgress2.png", - "ccs-res/cocosui/sliderThumb.png", - "ccs-res/cocosui/sliderTrack.png", - "ccs-res/cocosui/sliderTrack2.png", - "ccs-res/cocosui/slider_bar_active_9patch.png", - "ccs-res/cocosui/UITest/b1.png", - "ccs-res/cocosui/UITest/b2.png", - "ccs-res/cocosui/UITest/background.png", - "ccs-res/cocosui/UITest/buttonBackground.png", - "ccs-res/cocosui/UITest/f1.png", - "ccs-res/cocosui/UITest/f2.png", - "ccs-res/cocosui/UITest/r1.png", - "ccs-res/cocosui/UITest/r2.png", - "ccs-res/cocosui/UITest/ribbon.png", - "ccs-res/cocosui/UITest/UITest.json", - "ccs-res/cocosui/100/100.ExportJson", - "ccs-res/cocosui/100/1000.plist", - "ccs-res/cocosui/100/1000.png", - s_s9s_blocks9_plist, - "ccs-res/cocosui/CloseSelected.png" -]; - var g_performace = [ - "animations/crystals.plist", - "animations/crystals.png", - "fps_images.png", - "Images/spritesheet1.png", - "Images/sprites_test/sprite-0-0.png", - "Images/sprites_test/sprite-0-1.png", - "Images/sprites_test/sprite-0-2.png", - "Images/sprites_test/sprite-0-3.png", - "Images/sprites_test/sprite-0-4.png", - "Images/sprites_test/sprite-0-5.png", - "Images/sprites_test/sprite-0-6.png", - "Images/sprites_test/sprite-0-7.png", - "Images/sprites_test/sprite-1-0.png", - "Images/sprites_test/sprite-1-1.png", - "Images/sprites_test/sprite-1-2.png", - "Images/sprites_test/sprite-1-3.png", - "Images/sprites_test/sprite-1-4.png", - "Images/sprites_test/sprite-1-5.png", - "Images/sprites_test/sprite-1-6.png", - "Images/sprites_test/sprite-1-7.png", - "Images/sprites_test/sprite-2-0.png", - "Images/sprites_test/sprite-2-1.png", - "Images/sprites_test/sprite-2-2.png", - "Images/sprites_test/sprite-2-3.png", - "Images/sprites_test/sprite-2-4.png", - "Images/sprites_test/sprite-2-5.png", - "Images/sprites_test/sprite-2-6.png", - "Images/sprites_test/sprite-2-7.png", - "Images/sprites_test/sprite-3-0.png", - "Images/sprites_test/sprite-3-1.png", - "Images/sprites_test/sprite-3-2.png", - "Images/sprites_test/sprite-3-3.png", - "Images/sprites_test/sprite-3-4.png", - "Images/sprites_test/sprite-3-5.png", - "Images/sprites_test/sprite-3-6.png", - "Images/sprites_test/sprite-3-7.png", - "Images/sprites_test/sprite-4-0.png", - "Images/sprites_test/sprite-4-1.png", - "Images/sprites_test/sprite-4-2.png", - "Images/sprites_test/sprite-4-3.png", - "Images/sprites_test/sprite-4-4.png", - "Images/sprites_test/sprite-4-5.png", - "Images/sprites_test/sprite-4-6.png", - "Images/sprites_test/sprite-4-7.png", - "Images/sprites_test/sprite-5-0.png", - "Images/sprites_test/sprite-5-1.png", - "Images/sprites_test/sprite-5-2.png", - "Images/sprites_test/sprite-5-3.png", - "Images/sprites_test/sprite-5-4.png", - "Images/sprites_test/sprite-5-5.png", - "Images/sprites_test/sprite-5-6.png", - "Images/sprites_test/sprite-5-7.png", - "Images/sprites_test/sprite-6-0.png", - "Images/sprites_test/sprite-6-1.png", - "Images/sprites_test/sprite-6-2.png", - "Images/sprites_test/sprite-6-3.png", - "Images/sprites_test/sprite-6-4.png", - "Images/sprites_test/sprite-6-5.png", - "Images/sprites_test/sprite-6-6.png", - "Images/sprites_test/sprite-6-7.png", - "Images/sprites_test/sprite-7-0.png", - "Images/sprites_test/sprite-7-1.png", - "Images/sprites_test/sprite-7-2.png", - "Images/sprites_test/sprite-7-3.png", - "Images/sprites_test/sprite-7-4.png", - "Images/sprites_test/sprite-7-5.png", - "Images/sprites_test/sprite-7-6.png", - "Images/sprites_test/sprite-7-7.png" + "res/animations/crystals.plist", + "res/animations/crystals.png", + "res/fps_images.png", + "res/Images/spritesheet1.png", + "res/Images/sprites_test/sprite-0-0.png", + "res/Images/sprites_test/sprite-0-1.png", + "res/Images/sprites_test/sprite-0-2.png", + "res/Images/sprites_test/sprite-0-3.png", + "res/Images/sprites_test/sprite-0-4.png", + "res/Images/sprites_test/sprite-0-5.png", + "res/Images/sprites_test/sprite-0-6.png", + "res/Images/sprites_test/sprite-0-7.png", + "res/Images/sprites_test/sprite-1-0.png", + "res/Images/sprites_test/sprite-1-1.png", + "res/Images/sprites_test/sprite-1-2.png", + "res/Images/sprites_test/sprite-1-3.png", + "res/Images/sprites_test/sprite-1-4.png", + "res/Images/sprites_test/sprite-1-5.png", + "res/Images/sprites_test/sprite-1-6.png", + "res/Images/sprites_test/sprite-1-7.png", + "res/Images/sprites_test/sprite-2-0.png", + "res/Images/sprites_test/sprite-2-1.png", + "res/Images/sprites_test/sprite-2-2.png", + "res/Images/sprites_test/sprite-2-3.png", + "res/Images/sprites_test/sprite-2-4.png", + "res/Images/sprites_test/sprite-2-5.png", + "res/Images/sprites_test/sprite-2-6.png", + "res/Images/sprites_test/sprite-2-7.png", + "res/Images/sprites_test/sprite-3-0.png", + "res/Images/sprites_test/sprite-3-1.png", + "res/Images/sprites_test/sprite-3-2.png", + "res/Images/sprites_test/sprite-3-3.png", + "res/Images/sprites_test/sprite-3-4.png", + "res/Images/sprites_test/sprite-3-5.png", + "res/Images/sprites_test/sprite-3-6.png", + "res/Images/sprites_test/sprite-3-7.png", + "res/Images/sprites_test/sprite-4-0.png", + "res/Images/sprites_test/sprite-4-1.png", + "res/Images/sprites_test/sprite-4-2.png", + "res/Images/sprites_test/sprite-4-3.png", + "res/Images/sprites_test/sprite-4-4.png", + "res/Images/sprites_test/sprite-4-5.png", + "res/Images/sprites_test/sprite-4-6.png", + "res/Images/sprites_test/sprite-4-7.png", + "res/Images/sprites_test/sprite-5-0.png", + "res/Images/sprites_test/sprite-5-1.png", + "res/Images/sprites_test/sprite-5-2.png", + "res/Images/sprites_test/sprite-5-3.png", + "res/Images/sprites_test/sprite-5-4.png", + "res/Images/sprites_test/sprite-5-5.png", + "res/Images/sprites_test/sprite-5-6.png", + "res/Images/sprites_test/sprite-5-7.png", + "res/Images/sprites_test/sprite-6-0.png", + "res/Images/sprites_test/sprite-6-1.png", + "res/Images/sprites_test/sprite-6-2.png", + "res/Images/sprites_test/sprite-6-3.png", + "res/Images/sprites_test/sprite-6-4.png", + "res/Images/sprites_test/sprite-6-5.png", + "res/Images/sprites_test/sprite-6-6.png", + "res/Images/sprites_test/sprite-6-7.png", + "res/Images/sprites_test/sprite-7-0.png", + "res/Images/sprites_test/sprite-7-1.png", + "res/Images/sprites_test/sprite-7-2.png", + "res/Images/sprites_test/sprite-7-3.png", + "res/Images/sprites_test/sprite-7-4.png", + "res/Images/sprites_test/sprite-7-5.png", + "res/Images/sprites_test/sprite-7-6.png", + "res/Images/sprites_test/sprite-7-7.png" ]; var g_tilemaps = [ @@ -989,56 +560,56 @@ var g_tilemaps = [ s_tilesPng, s_tileISOOffsetPng, s_tileISOOffsetTmx, - "TileMaps/ortho-test2.png", + "res/TileMaps/ortho-test2.png", //tmx - "TileMaps/orthogonal-test1.tmx", - "TileMaps/orthogonal-test1.tsx", - "TileMaps/orthogonal-test2.tmx", - "TileMaps/orthogonal-test3.tmx", - "TileMaps/orthogonal-test4.tmx", - "TileMaps/orthogonal-test4-hd.tmx", - "TileMaps/orthogonal-test5.tmx", - "TileMaps/orthogonal-test6.tmx", - "TileMaps/orthogonal-test6-hd.tmx", - "TileMaps/hexa-test.tmx", - "TileMaps/iso-test.tmx", - "TileMaps/iso-test1.tmx", - "TileMaps/iso-test2.tmx", - "TileMaps/iso-test2-uncompressed.tmx", - "TileMaps/ortho-objects.tmx", - "TileMaps/iso-test-objectgroup.tmx", - "TileMaps/iso-test-zorder.tmx", - "TileMaps/orthogonal-test-zorder.tmx", - "TileMaps/iso-test-vertexz.tmx", - "TileMaps/orthogonal-test-vertexz.tmx", - "TileMaps/iso-test-movelayer.tmx", - "TileMaps/orthogonal-test-movelayer.tmx", - "TileMaps/iso-test-bug787.tmx", - "TileMaps/test-object-layer.tmx", - "TileMaps/ortho-tile-property.tmx", - "TileMaps/ortho-rotation-test.tmx" + "res/TileMaps/orthogonal-test1.tmx", + "res/TileMaps/orthogonal-test1.tsx", + "res/TileMaps/orthogonal-test2.tmx", + "res/TileMaps/orthogonal-test3.tmx", + "res/TileMaps/orthogonal-test4.tmx", + "res/TileMaps/orthogonal-test4-hd.tmx", + "res/TileMaps/orthogonal-test5.tmx", + "res/TileMaps/orthogonal-test6.tmx", + "res/TileMaps/orthogonal-test6-hd.tmx", + "res/TileMaps/hexa-test.tmx", + "res/TileMaps/iso-test.tmx", + "res/TileMaps/iso-test1.tmx", + "res/TileMaps/iso-test2.tmx", + "res/TileMaps/iso-test2-uncompressed.tmx", + "res/TileMaps/ortho-objects.tmx", + "res/TileMaps/iso-test-objectgroup.tmx", + "res/TileMaps/iso-test-zorder.tmx", + "res/TileMaps/orthogonal-test-zorder.tmx", + "res/TileMaps/iso-test-vertexz.tmx", + "res/TileMaps/orthogonal-test-vertexz.tmx", + "res/TileMaps/iso-test-movelayer.tmx", + "res/TileMaps/orthogonal-test-movelayer.tmx", + "res/TileMaps/iso-test-bug787.tmx", + "res/TileMaps/test-object-layer.tmx", + "res/TileMaps/ortho-tile-property.tmx", + "res/TileMaps/ortho-rotation-test.tmx" ]; var g_spine = [ - "spine/spineboy.atlas", - "spine/spineboy.json", - "spine/spineboy.png", - "spine/sprite.png", - "spine/goblins-ffd.png", - "spine/goblins-ffd.atlas", - "spine/goblins-ffd.json" + "res/spine/spineboy.atlas", + "res/spine/spineboy.json", + "res/spine/spineboy.png", + "res/spine/sprite.png", + "res/spine/goblins-ffd.png", + "res/spine/goblins-ffd.atlas", + "res/spine/goblins-ffd.json" ]; var g_ccs2 = [ - "ActionTimeline/boy_1.csb", - "ActionTimeline/armature/Cowboy0.plist", - "ccs-res/cocosui/UIEditorTest/UILabelBMFont_Editor/GUI/missing-font.fnt", - "ccs-res/cocosui/UIEditorTest/UILabelBMFont_Editor/GUI/missing-font.png" + "res/ActionTimeline/boy_1.csb", + "res/ActionTimeline/armature/Cowboy0.plist", + "res/ccs-res/cocosui/UIEditorTest/UILabelBMFont_Editor/GUI/missing-font.fnt", + "res/ccs-res/cocosui/UIEditorTest/UILabelBMFont_Editor/GUI/missing-font.png" ]; if (!cc.sys.isNative) { var res = res || {}; - res.CCControlColourPickerSpriteSheet_plist = "extensions/CCControlColourPickerSpriteSheet.plist"; - res.CCControlColourPickerSpriteSheet_png = "extensions/CCControlColourPickerSpriteSheet.png"; + res.CCControlColourPickerSpriteSheet_plist = "res/extensions/CCControlColourPickerSpriteSheet.plist"; + res.CCControlColourPickerSpriteSheet_png = "res/extensions/CCControlColourPickerSpriteSheet.png"; } \ No newline at end of file