diff --git a/CCBoot.js b/CCBoot.js index 87e0549293..81ba94d079 100644 --- a/CCBoot.js +++ b/CCBoot.js @@ -58,7 +58,7 @@ _p = null; * @name cc.ENGINE_VERSION */ var engineVersion; -engineVersion = '1.0.1'; +engineVersion = '1.1.0-beta.3'; window['CocosEngine'] = cc.ENGINE_VERSION = engineVersion; /** diff --git a/CCDebugger.js b/CCDebugger.js index c78aef1f52..8b825c87c7 100644 --- a/CCDebugger.js +++ b/CCDebugger.js @@ -313,7 +313,7 @@ cc._logToWebPage = function (msg) { //to make sure the cc.log, cc.warn, cc.error and cc.assert would not throw error before init by debugger mode. function _formatString (arg) { - if (cc.js.isObject(arg)) { + if (typeof arg === 'object') { try { return JSON.stringify(arg); } catch (err) { @@ -321,7 +321,7 @@ function _formatString (arg) { } } else return arg; -}; +} var Enum = require('./cocos2d/core/value-types/CCEnum'); diff --git a/cocos2d/animation/easing.js b/cocos2d/animation/easing.js index af51505fa4..5bd051dc68 100644 --- a/cocos2d/animation/easing.js +++ b/cocos2d/animation/easing.js @@ -1,4 +1,5 @@ var Easing = { + constant: function () { return 0; }, linear: function (k) { return k; }, // quad diff --git a/cocos2d/animation/motion-path-helper.js b/cocos2d/animation/motion-path-helper.js index f78535e1a6..8b43ab7cbd 100644 --- a/cocos2d/animation/motion-path-helper.js +++ b/cocos2d/animation/motion-path-helper.js @@ -246,6 +246,7 @@ function sampleMotionPaths (motionPaths, data, duration, fps) { var startRatioOffset = 0; var EPSILON = 1e-6; + var newType = DynamicAnimCurve.Linear; // do not need to compute last path for (var i = 0, l = motionPaths.length; i < l-1; i++) { @@ -329,9 +330,11 @@ function sampleMotionPaths (motionPaths, data, duration, fps) { } } + newType = type === 'constant' ? type : DynamicAnimCurve.Linear; + for (var j = 0, l2 = results.length; j < l2; j++) { var newRatio = ratio + startRatioOffset + speed * j * betweenRatio; - addNewDatas(results[j], DynamicAnimCurve.Linear, newRatio); + addNewDatas(results[j], newType, newRatio); } if (Math.abs(progress - 1) > EPSILON) // progress > 1 @@ -341,7 +344,7 @@ function sampleMotionPaths (motionPaths, data, duration, fps) { } if (ratios[ratios.length - 1] !== newRatios[newRatios.length -1]) { - addNewDatas(values[values.length - 1], DynamicAnimCurve.Linear, ratios[ratios.length - 1]); + addNewDatas(values[values.length - 1], newType, ratios[ratios.length - 1]); } } diff --git a/cocos2d/audio/CCAudio.js b/cocos2d/audio/CCAudio.js index bedf3cd8ca..9d7f8c2658 100644 --- a/cocos2d/audio/CCAudio.js +++ b/cocos2d/audio/CCAudio.js @@ -29,314 +29,223 @@ var JS = require('../core/platform/js'); /** * Encapsulate DOM and webAudio */ -cc.Audio = function (context, volume, url) { - //TODO Maybe loader shift in will be better - this.volume = 1; - this.loop = false; - this._touch = false; - - this._playing = false; - this._AUDIO_TYPE = "AUDIO"; - this._pause = false; - - //Web Audio - this._buffer = null; - this._currentSource = null; - this._startTime = null; - this._currentTime = null; - this._context = null; - this._volume = null; - - this._ignoreEnded = false; - this._manualLoop = false; - - //DOM Audio - this._element = null; - - context && (this._context = context); - volume && (this._volume = volume); - if (context && volume) { - this._AUDIO_TYPE = "WEBAUDIO"; - } +cc.Audio = function (url) { this.src = url; + this._element = null; + this._AUDIO_TYPE = 'AUDIO'; }; -cc.Audio.useWebAudio = false; +cc.Audio.touchPlayList = [ + //{ offset: 0, audio: audio } +]; + +cc.Audio.bindTouch = false; +cc.Audio.touchStart = function () { + var list = cc.Audio.touchPlayList; + var item = null; + while (item = list.pop()) { + item.audio.loop = !!item.loop; + item.audio.play(item.offset); + } +}; + +cc.Audio.WebAudio = function (buffer) { + this.buffer = buffer; + this.context = cc.sys.__audioSupport.context; + + var volume = this.context['createGain'](); + volume['gain'].value = 1; + volume['connect'](this.context['destination']); + this._volume = volume; + + this._loop = false; + + // The time stamp on the audio time axis when the recording begins to play. + this._startTime = -1; + // Record the currently playing 'Source' + this._currentSource = null; + // Record the time has been played + this.playedLength = 0; + + this._currextTimer = null; +}; + +cc.Audio.WebAudio.prototype = { + constructor: cc.Audio.WebAudio, + + get paused () { + // If the current audio is a loop, paused is false + if (this._currentSource && this._currentSource.loop) + return false; + + // startTime default is -1 + if (this._startTime === -1) + return true; + + // Current time - Start playing time > Audio duration + return this.context.currentTime - this._startTime > this.buffer.duration; + }, + + get loop () { return this._loop; }, + set loop (bool) { return this._loop = bool; }, + + get volume () { return this._volume['gain'].value; }, + set volume (num) { return this._volume['gain'].value = num; }, + + get currentTime () { return this.playedLength; }, + set currentTime (num) { return this.playedLength = num; }, + + play: function (offset) { + + // If repeat play, you need to stop before an audio + if (this._currentSource && !this.paused) { + this._currentSource.stop(0); + this.playedLength = 0; + } + + var audio = this.context["createBufferSource"](); + audio.buffer = this.buffer; + audio["connect"](this._volume); + audio.loop = this._loop; + + this._startTime = this.context.currentTime; + offset = offset || this.playedLength; + + var duration = this.buffer.duration; + if (!this._loop) { + if (audio.start) + audio.start(0, offset, duration - offset); + else if (audio["notoGrainOn"]) + audio["noteGrainOn"](0, offset, duration - offset); + else + audio["noteOn"](0, offset, duration - offset); + } else { + if (audio.start) + audio.start(0); + else if (audio["notoGrainOn"]) + audio["noteGrainOn"](0); + else + audio["noteOn"](0); + } + + this._currentSource = audio; + + // If the current audio context time stamp is 0 + // There may be a need to touch events before you can actually start playing audio + if (this.context.currentTime === 0) { + var self = this; + clearTimeout(this._currextTimer); + this._currextTimer = setTimeout(function () { + if (self.context.currentTime === 0) { + cc.Audio.touchPlayList.push({ + offset: offset, + audio: self + }); + } + }, 10); + } + }, + pause: function () { + // Record the time the current has been played + this.playedLength = this.context.currentTime - this._startTime; + // If more than the duration of the audio, Need to take the remainder + this.playedLength %= this.buffer.duration; + var audio = this._currentSource; + this._currentSource = null; + this._startTime = -1; + if (audio) + audio.stop(0); + } +}; JS.mixin(cc.Audio.prototype, { - _setBufferCallback: null, - setBuffer: function(buffer){ - if(!buffer) return; - var playing = this._playing; + setBuffer: function (buffer) { this._AUDIO_TYPE = "WEBAUDIO"; - - if(this._buffer && this._buffer !== buffer && this.getPlaying()) - this.stop(); - - this._buffer = buffer; - if(playing) - this.play(); - - this._volume["gain"].value = this.volume; - this._setBufferCallback && this._setBufferCallback(buffer); + this._element = new cc.Audio.WebAudio(buffer); }, - _setElementCallback: null, - setElement: function(element){ - if(!element) return; - var playing = this._playing; + setElement: function (element) { this._AUDIO_TYPE = "AUDIO"; - - if(this._element && this._element !== element && this.getPlaying()) - this.stop(); - this._element = element; - if(playing) - this.play(); - element.volume = this.volume; - element.loop = this.loop; - this._setElementCallback && this._setElementCallback(element); - }, - - play: function(offset, loop){ - this._playing = true; - this.loop = loop === undefined ? this.loop : loop; - if(this._AUDIO_TYPE === "AUDIO"){ - this._playOfAudio(offset); - }else{ - this._playOfWebAudio(offset); - } - }, - - getPlaying: function(){ - // if(!this._playing){ - // return false; - // } - if(this._AUDIO_TYPE === "AUDIO"){ - var audio = this._element; - if(!audio || this._pause || audio.ended){ - return this._playing = false; + // Prevent partial browser from playing after the end does not reset the paused tag + element.addEventListener('ended', function () { + if (!element.loop) { + element.paused = true; } - return true; - } - var sourceNode = this._currentSource; - if(!sourceNode || !sourceNode["playbackState"]) - return true; - return this._currentTime + this._context.currentTime - this._startTime < sourceNode.buffer.duration; + }); }, - _playOfWebAudio: function(offset){ - var cs = this._currentSource; - if(!this._buffer){ - return; - } - if(!this._pause && cs){ - if(this._context.currentTime === 0 || this._currentTime + this._context.currentTime - this._startTime > cs.buffer.duration) - this._stopOfWebAudio(); - else - return; - } - var audio = this._context["createBufferSource"](); - audio.buffer = this._buffer; - audio["connect"](this._volume); - if(this._manualLoop) - audio.loop = false; - else - audio.loop = this.loop; - this._startTime = this._context.currentTime; - this._currentTime = offset || 0; - this._ignoreEnded = false; + play: function (offset, loop) { + if (!this._element) return; + this._element.loop = loop; + this._element.play(); - /* - * Safari on iOS 6 only supports noteOn(), noteGrainOn(), and noteOff() now.(iOS 6.1.3) - * The latest version of chrome has supported start() and stop() - * start() & stop() are specified in the latest specification (written on 04/26/2013) - * Reference: https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html - * noteOn(), noteGrainOn(), and noteOff() are specified in Draft 13 version (03/13/2012) - * Reference: http://www.w3.org/2011/audio/drafts/2WD/Overview.html - */ - if(audio.start){ - audio.start(0, offset || 0); - }else if(audio["noteGrainOn"]){ - var duration = audio.buffer.duration; - if (this.loop) { - /* - * On Safari on iOS 6, if loop == true, the passed in @param duration will be the duration from now on. - * In other words, the sound will keep playing the rest of the music all the time. - * On latest chrome desktop version, the passed in duration will only be the duration in this cycle. - * Now that latest chrome would have start() method, it is prepared for iOS here. - */ - audio["noteGrainOn"](0, offset, duration); - } else { - audio["noteGrainOn"](0, offset, duration - offset); - } - }else { - // if only noteOn() is supported, resuming sound will NOT work - audio["noteOn"](0); + if (this._AUDIO_TYPE === 'AUDIO' && this._element.paused) { + this.stop(); + cc.Audio.touchPlayList.push({ loop: loop, offset: offset, audio: this._element }); } - this._currentSource = audio; - var self = this; - audio["onended"] = function(){ - if(self._manualLoop && self._playing && self.loop){ - self.stop(); - self.play(); - return; - } - if(self._ignoreEnded){ - self._ignoreEnded = false; - }else{ - if(!self._pause) - self.stop(); - else - self._playing = false; - } - }; - }, - _playOfAudio: function(){ - var audio = this._element; - if(audio){ - audio.loop = this.loop; - audio.play(); + if (cc.Audio.bindTouch === false) { + cc.Audio.bindTouch = true; + // Listen to the touchstart body event and play the audio when necessary. + cc.game.canvas.addEventListener('touchstart', cc.Audio.touchStart); } }, - stop: function(){ - this._playing = false; - if(this._AUDIO_TYPE === "AUDIO"){ - this._stopOfAudio(); - }else{ - this._stopOfWebAudio(); - } + getPlaying: function () { + if (!this._element) return true; + return !this._element.paused; }, - _stopOfWebAudio: function(){ - var audio = this._currentSource; - this._ignoreEnded = true; - if(audio){ - audio.stop(0); - this._currentSource = null; - } + stop: function () { + if (!this._element) return; + this._element.pause(); + try{ + this._element.currentTime = 0; + } catch (err) {} }, - _stopOfAudio: function(){ - var audio = this._element; - if(audio){ - audio.pause(); - if (audio.duration) - audio.currentTime = 0; - } + pause: function () { + if (!this._element) return; + this._element.pause(); }, - pause: function(){ - if(this.getPlaying() === false) - return; - this._playing = false; - this._pause = true; - if(this._AUDIO_TYPE === "AUDIO"){ - this._pauseOfAudio(); - }else{ - this._pauseOfWebAudio(); - } + resume: function () { + if (!this._element) return; + this._element.play(); }, - _pauseOfWebAudio: function(){ - this._currentTime += this._context.currentTime - this._startTime; - var audio = this._currentSource; - if(audio){ - audio.stop(0); - } + setVolume: function (volume) { + if (!this._element) return; + this._element.volume = volume; }, - _pauseOfAudio: function(){ - var audio = this._element; - if(audio){ - audio.pause(); - } + getVolume: function () { + if (!this._element) return; + return this._element.volume; }, - resume: function(){ - if(this._pause){ - if(this._AUDIO_TYPE === "AUDIO"){ - this._resumeOfAudio(); - }else{ - this._resumeOfWebAudio(); - } - this._pause = false; - this._playing = true; - } - }, - - _resumeOfWebAudio: function(){ - var audio = this._currentSource; - if(audio){ - this._startTime = this._context.currentTime; - var offset = this._currentTime % audio.buffer.duration; - this._playOfWebAudio(offset); - } - }, - - _resumeOfAudio: function(){ - var audio = this._element; - if(audio){ - audio.play(); - } - }, - - setVolume: function(volume){ - if(volume > 1) volume = 1; - if(volume < 0) volume = 0; - this.volume = volume; - if(this._AUDIO_TYPE === "AUDIO"){ - if(this._element){ - this._element.volume = volume; - } - }else{ - if(this._volume){ - this._volume["gain"].value = volume; - } - } - }, - - getVolume: function(){ - return this.volume; - }, - - cloneNode: function(){ - var audio, self; - if(this._AUDIO_TYPE === "AUDIO"){ - audio = new cc.Audio(); - + cloneNode: function () { + var audio = new cc.Audio(this.src); + if (this._AUDIO_TYPE === "AUDIO") { var elem = document.createElement("audio"); + var sources = elem.getElementsByTagName('source'); + for (var i=0; i * cc.director 也同步定时器与显示器的刷新速率。 *
- * 特点和局限性:
+ * 特点和局限性:
* - 将计时器 & 渲染与显示器的刷新频率同步。
- * - 只支持动画的间隔 1/60 1/30 & 1/15
+ * - 只支持动画的间隔 1/60 1/30 & 1/15。
*

* * @class Director @@ -199,6 +199,15 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ this._animationManager = null; } + // collision manager + if (cc.CollisionManager) { + this._collisionManager = new cc.CollisionManager(); + this._scheduler.scheduleUpdate(this._collisionManager, cc.Scheduler.PRIORITY_SYSTEM, false); + } + else { + this._collisionManager = null; + } + // WidgetManager cc._widgetManager.init(this); }, @@ -223,7 +232,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ this._lastUpdate = now; }, - /** + /* * !#en * Converts a view coordinate to an WebGL coordinate
* Useful to convert (multi) touches coordinates to the current layout (portrait or landscape)
@@ -257,7 +266,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ var renderer = cc.renderer; if (renderer.childrenOrderDirty) { renderer.clearRenderCommands(); - this._runningScene._renderCmd._curLevel = 0; //level start from 0; + this._runningScene._renderCmd._curLevel = 0; //level start from 0; this._runningScene.visit(); renderer.resetFlag(); } @@ -409,7 +418,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ this._paused = true; }, - /** + /* * Pops out a scene from the queue.
* This scene will replace the running one.
* The running scene will be deleted. If there are no more scenes in the stack the execution is terminated.
@@ -495,6 +504,11 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ this._scheduler.scheduleUpdate(this._animationManager, cc.Scheduler.PRIORITY_SYSTEM, false); } + // Collider manager + if (this._collisionManager) { + this._scheduler.scheduleUpdate(this._collisionManager, cc.Scheduler.PRIORITY_SYSTEM, false); + } + this.startAnimation(); }, @@ -727,6 +741,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ //cc.AssetLibrary.unloadAsset(uuid); // force reload cc.AssetLibrary.loadAsset(uuid, function (error, sceneAsset) { var self = cc.director; + self._loadingScene = ''; var scene; if (error) { error = 'Failed to load scene: ' + error; @@ -753,7 +768,6 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ scene = null; } } - self._loadingScene = ''; if (error && onLaunched) { onLaunched(error); } @@ -955,13 +969,13 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ /** * !#en - * Returns whether or not the replaced scene will receive the cleanup message.
+ * Returns whether or not the replaced scene will receive the cleanup message.
* If the new scene is pushed, then the old scene won't receive the "cleanup" message.
* If the new scene replaces the old one, the it will receive the "cleanup" message. * !#zh * 更换场景时是否接收清理消息。
- * 如果新场景是采用 push 方式进入的,那么旧的场景将不会接收到 “cleanup” 消息。
- * 如果新场景取代旧的场景,它将会接收到 “cleanup” 消息。
+ * 如果新场景是采用 push 方式进入的,那么旧的场景将不会接收到 “cleanup” 消息。
+ * 如果新场景取代旧的场景,它将会接收到 “cleanup” 消息。
* @method isSendCleanupToScene * @return {Boolean} */ @@ -1135,7 +1149,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ /** * !#en Returns the cc.ActionManager associated with this director. - * !#zh 获取和 director 相关联的 cc.ActionManager(动作管理器). + * !#zh 获取和 director 相关联的 cc.ActionManager(动作管理器)。 * @method getActionManager * @return {ActionManager} */ @@ -1144,7 +1158,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ }, /** * !#en Sets the cc.ActionManager associated with this director. - * !#zh 设置和 director 相关联的 cc.ActionManager(动作管理器). + * !#zh 设置和 director 相关联的 cc.ActionManager(动作管理器)。 * @method setActionManager * @param {ActionManager} actionManager */ @@ -1156,7 +1170,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ /* * !#en Returns the cc.AnimationManager associated with this director. - * !#zh 获取和 director 相关联的 cc.AnimationManager(动画管理器). + * !#zh 获取和 director 相关联的 cc.AnimationManager(动画管理器)。 * @method getAnimationManager * @return {AnimationManager} */ @@ -1164,6 +1178,15 @@ cc.Director = Class.extend(/** @lends cc.Director# */{ return this._animationManager; }, + /** + * Returns the cc.CollisionManager associated with this director. + * @method getCollisionManager + * @return {CollisionManager} + */ + getCollisionManager: function () { + return this._collisionManager; + }, + /** * !#en Returns the delta time since last frame. * !#zh 获取上一帧的 “delta time”。 diff --git a/cocos2d/core/CCGame.js b/cocos2d/core/CCGame.js index 110fceb87e..55a3af979f 100644 --- a/cocos2d/core/CCGame.js +++ b/cocos2d/core/CCGame.js @@ -39,6 +39,7 @@ var game = /** @lends cc.game# */{ EVENT_HIDE: "game_on_hide", EVENT_SHOW: "game_on_show", EVENT_RESIZE: "game_on_resize", + EVENT_GAME_INITED: "game_inited", EVENT_RENDERER_INITED: "renderer_inited", RENDER_TYPE_CANVAS: 0, @@ -336,10 +337,12 @@ var game = /** @lends cc.game# */{ cc.loader.load(jsList, function (err) { if (err) throw new Error(JSON.stringify(err)); self._prepared = true; + self.emit(self.EVENT_GAME_INITED); if (cb) cb(); }); } else { + self.emit(self.EVENT_GAME_INITED); if (cb) cb(); } @@ -578,6 +581,10 @@ var game = /** @lends cc.game# */{ // Scene parser this._sceneInfos = this._sceneInfos.concat(config[CONFIG_KEY.scenes]); + // Collide Map and Group List + this.collideMap = config.collideMap; + this.groupList = config.groupList; + this.config = config; }, @@ -676,16 +683,16 @@ var game = /** @lends cc.game# */{ if (this.config[this.CONFIG_KEY.registerSystemEvent]) cc.inputManager.registerSystemEvent(this.canvas); - if (!cc.js.isUndefined(document.hidden)) { + if (typeof document.hidden !== 'undefined') { hidden = "hidden"; visibilityChange = "visibilitychange"; - } else if (!cc.js.isUndefined(document.mozHidden)) { + } else if (typeof document.mozHidden !== 'undefined') { hidden = "mozHidden"; visibilityChange = "mozvisibilitychange"; - } else if (!cc.js.isUndefined(document.msHidden)) { + } else if (typeof document.msHidden !== 'undefined') { hidden = "msHidden"; visibilityChange = "msvisibilitychange"; - } else if (!cc.js.isUndefined(document.webkitHidden)) { + } else if (typeof document.webkitHidden !== 'undefined') { hidden = "webkitHidden"; visibilityChange = "webkitvisibilitychange"; } diff --git a/cocos2d/core/CCNode.js b/cocos2d/core/CCNode.js index 5a35660e2e..ece1d4a470 100644 --- a/cocos2d/core/CCNode.js +++ b/cocos2d/core/CCNode.js @@ -647,7 +647,7 @@ var Node = cc.Class({ */ addComponent: function (typeOrClassName) { - if ((this._objFlags & Destroying) && CC_EDITOR) { + if (CC_EDITOR && (this._objFlags & Destroying)) { cc.error('isDestroying'); return null; } @@ -684,7 +684,7 @@ var Node = cc.Class({ return null; } - if (constructor._disallowMultiple && CC_EDITOR) { + if (CC_EDITOR && constructor._disallowMultiple) { if (!this._checkMultipleComp(constructor)) { return null; } @@ -1006,50 +1006,6 @@ var Node = cc.Class({ return clone; }, - _onColorChanged: function () { - // 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._SGComponent && comp.isValid && comp._sgNode) { - comp._sgNode.setColor(this._color); - if ( !this._cascadeOpacityEnabled ) { - comp._sgNode.setOpacity(this._opacity); - } - } - } - }, - - _onCascadeChanged: function () { - // update components which also in scene graph - 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._SGComponent && comp.isValid && comp._sgNode) { - comp._sgNode.setOpacity(opacity); - } - } - }, - - _onAnchorChanged: function () { - // 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._SGComponent && comp.isValid && comp._sgNode) { - comp._sgNode.setAnchorPoint(this._anchorPoint); - comp._sgNode.ignoreAnchorPointForPosition(this.__ignoreAnchor); - } - } - }, - - _onOpacityModifyRGBChanged: function () { - for (var c = 0; c < this._components.length; ++c) { - var comp = this._components[c]; - if (comp instanceof cc._SGComponent && comp.isValid && comp._sgNode) { - comp._sgNode.setOpacityModifyRGB(this._opacityModifyRGB); - } - } - }, - // EVENTS /** * !#en @@ -1404,16 +1360,6 @@ if (cc.sys.isNative) { * @param {Event} event * @param {Vec2} event.detail - old anchor */ -/** - * @event color-changed - * @param {Event} event - * @param {Color} event.detail - old color - */ -/** - * @event opacity-changed - * @param {Event} event - * @param {Number} event.detail - old opacity - */ /** * @event child-added * @param {Event} event diff --git a/cocos2d/core/CCScene.js b/cocos2d/core/CCScene.js index d33ae4c464..bf206ae372 100644 --- a/cocos2d/core/CCScene.js +++ b/cocos2d/core/CCScene.js @@ -67,10 +67,6 @@ cc.Scene = cc.Class({ }, _onHierarchyChanged: NIL, - _onColorChanged: NIL, - _onAnchorChanged: NIL, - _onOpacityModifyRGBChanged: NIL, - _onCascadeChanged: NIL, _load: function () { if ( ! this._inited) { diff --git a/cocos2d/core/base-nodes/CCSGNode.js b/cocos2d/core/base-nodes/CCSGNode.js index 806e43dad9..176236110a 100644 --- a/cocos2d/core/base-nodes/CCSGNode.js +++ b/cocos2d/core/base-nodes/CCSGNode.js @@ -1125,7 +1125,7 @@ _ccsg.Node = cc.Class({ addChild: function (child, localZOrder, tag) { localZOrder = localZOrder === undefined ? child._localZOrder : localZOrder; var name, setTag = false; - if(cc.js.isUndefined(tag)){ + if(typeof tag === 'undefined'){ tag = undefined; name = child._name; } else if(cc.js.isString(tag)){ @@ -2239,6 +2239,6 @@ _ccsg.Node.prototype.ctor = _ccsg.Node; _ccsg.Node._stateCallbackType = {onEnter: 1, onExit: 2, cleanup: 3, onEnterTransitionDidFinish: 4, updateTransform: 5, onExitTransitionDidStart: 6, sortAllChildren: 7}; -cc.assert(cc.js.isFunction(cc._tmp.PrototypeCCNode), cc._LogInfos.MissingFile, "BaseNodesPropertyDefine.js"); +cc.assert(typeof cc._tmp.PrototypeCCNode === 'function', cc._LogInfos.MissingFile, "BaseNodesPropertyDefine.js"); cc._tmp.PrototypeCCNode(); delete cc._tmp.PrototypeCCNode; diff --git a/cocos2d/core/collider/CCBoxCollider.js b/cocos2d/core/collider/CCBoxCollider.js new file mode 100644 index 0000000000..e3722f1f62 --- /dev/null +++ b/cocos2d/core/collider/CCBoxCollider.js @@ -0,0 +1,79 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + 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. + ****************************************************************************/ + +/** + * !#en Box Collider. + * !#zh 包围盒碰撞组件 + * @class BoxCollider + * @extends Component + */ +var BoxCollider = cc.Class({ + name: 'cc.BoxCollider', + extends: cc.Collider, + + editor: CC_EDITOR && { + menu: 'i18n:MAIN_MENU.component.collider/Box Collider', + }, + + properties: { + _offset: cc.v2(0, 0), + _size: cc.size(100, 100), + + /** + * !#en Position offset + * !#zh 位置偏移量 + * @property offset + * @type {Vec2} + */ + offset: { + get: function () { + return this._offset; + }, + set: function (value) { + this._offset = value; + }, + type: cc.Vec2 + }, + + /** + * !#en Box size + * !#zh 包围盒大小 + * @property size + * @type {Size} + */ + size: { + get: function () { + return this._size; + }, + set: function (value) { + this._size.width = value.width < 0 ? 0 : value.width; + this._size.height = value.height < 0 ? 0 : value.height; + }, + type: cc.Size + } + } +}); + +cc.BoxCollider = module.exports = BoxCollider; diff --git a/cocos2d/core/collider/CCCircleCollider.js b/cocos2d/core/collider/CCCircleCollider.js new file mode 100644 index 0000000000..2f65ff1f1a --- /dev/null +++ b/cocos2d/core/collider/CCCircleCollider.js @@ -0,0 +1,77 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + 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. + ****************************************************************************/ + +/** + * !#en Circle Collider. + * !#zh 圆形碰撞组件 + * @class CircleCollider + * @extends Component + */ +var CircleCollider = cc.Class({ + name: 'cc.CircleCollider', + extends: require('./CCCollider'), + + editor: CC_EDITOR && { + menu: 'i18n:MAIN_MENU.component.collider/Circle Collider', + }, + + properties: { + _offset: cc.v2(0, 0), + _radius: 50, + + /** + * !#en Position offset + * !#zh 位置偏移量 + * @property offset + * @type {Vec2} + */ + offset: { + get: function () { + return this._offset; + }, + set: function (value) { + this._offset = value; + }, + type: cc.Vec2 + }, + + /** + * !#en Circle radius + * !#zh 圆形半径 + * @property radius + * @type {Number} + */ + radius: { + get: function () { + return this._radius; + }, + set: function (value) { + this._radius = value < 0 ? 0 : value; + } + } + } +}); + +cc.CircleCollider = module.exports = CircleCollider; diff --git a/cocos2d/core/collider/CCCollider.js b/cocos2d/core/collider/CCCollider.js new file mode 100644 index 0000000000..3e6d52c7b8 --- /dev/null +++ b/cocos2d/core/collider/CCCollider.js @@ -0,0 +1,121 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + 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. + ****************************************************************************/ + +/** + * !#en Collider component base class. + * !#zh 碰撞组件基类 + * @class Collider + * @extends Component + */ +var Collider = cc.Class({ + name: 'cc.Collider', + extends: cc.Component, + + editor: CC_EDITOR && { + executeInEditMode: true + }, + + properties: { + _category: { + default: 1, + type: cc.Integer + }, + + _mask: { + default: 65535, + type: cc.Integer + }, + + editing: { + default: false, + serializable: false, + tooltip: 'i18n:COMPONENT.collider.editing' + }, + + /** + * !#en Collider component category. + * !#zh 碰撞组件所属类别 + * @property category + * @type {Integer} + * @default 1 + */ + category: { + get: function () { + return this._category; + }, + set: function (value) { + if (!CC_EDITOR) { + cc.director.getCollisionManager().removeCollider(this); + } + + this._category = value; + + if (!CC_EDITOR) { + cc.director.getCollisionManager().addCollider(this); + } + }, + range: [0, 65535], + type: cc.Integer, + tooltip: 'i18n:COMPONENT.collider.category' + }, + + /** + * !#en The collider mask can collide with this collider. + * !#zh 可以与碰撞组件相碰撞的组件掩码 + * @property mask + * @type {Integer} + * @default 65535 + */ + mask: { + get: function () { + return this._mask; + }, + set: function (value) { + if (!CC_EDITOR) { + cc.director.getCollisionManager().removeCollider(this); + } + + this._mask = value; + + if (!CC_EDITOR) { + cc.director.getCollisionManager().addCollider(this); + } + }, + range: [0, 65535], + type: cc.Integer, + tooltip: 'i18n:COMPONENT.collider.mask' + } + }, + + onDisable: function () { + cc.director.getCollisionManager().removeCollider(this); + }, + + onEnable: function () { + cc.director.getCollisionManager().addCollider(this); + } +}); + +cc.Collider = module.exports = Collider; diff --git a/cocos2d/core/collider/CCCollisionManager.js b/cocos2d/core/collider/CCCollisionManager.js new file mode 100644 index 0000000000..8f1afbab3d --- /dev/null +++ b/cocos2d/core/collider/CCCollisionManager.js @@ -0,0 +1,395 @@ +var Contact = require('./CCContact'); +var CollisionType = Contact.CollisionType; + +/** + * !#en + * A simple collision manager class. + * It will calculate whether the collider collides other colliders, if collides then call the callbacks. + * !#zh + * 一个简单的碰撞组件管理类,用于处理节点之间的碰撞组件是否产生了碰撞,并调用相应回调函数。 + * + * @class ColliderManager + * @example + * + * // Get the collider manager. + * var manager = cc.director.getCollisionManager(); + * + * // Enabled the colider manager. + * manager.enabled = true; + * + * // Enabled draw collider + * manager.enabledDebugDraw = true; + * + * // Enabled draw collider bounding box + * manager.enabledDrawBoundingBox = true; + * + * + * // Collider callback + * onCollisionEnter: function (other, self) { + * this.node.color = cc.Color.RED; + * this.touchingNumber ++; + * + * // var world = self.world; + * // var aabb = world.aabb; + * // var preAabb = world.preAabb; + * // var t = world.transform; + * + * // for circle collider + * // var r = world.radius; + * // var p = world.position; + * + * // for box collider and polygon collider + * // var ps = world.points; + * }, + * + * onCollisionStay: function (other, self) { + * console.log('on collision stay'); + * }, + * + * onCollisionExit: function (other, self) { + * this.touchingNumber --; + * if (this.touchingNumber === 0) { + * this.node.color = cc.Color.WHITE; + * } + * } +}); + + * + */ +var CollisionManager = cc.Class({ + mixins: [cc.EventTarget], + + properties: { + /** + * !#en + * !#zh + * 是否开启碰撞管理,默认为不开启 + * @property {Boolean} enabled + * @default false + */ + enabled: false, + /** + * !#en + * !#zh + * 是否绘制碰撞组件的包围盒,默认为不绘制 + * @property {Boolean} enabledDrawBoundingBox + * @default false + */ + enabledDrawBoundingBox: false + }, + + ctor: function () { + this.__instanceId = cc.ClassManager.getNewInstanceId(); + + this._contacts = []; + this._colliders = []; + + this._updating = false; + this._removeList = []; + + this._debugDrawer = null; + this._enabledDebugDraw = false; + }, + + update: function (dt) { + if (!this.enabled) { + return; + } + + this._updating = true; + + var i, l; + + // update collider + var colliders = this._colliders; + for (i = 0, l = colliders.length; i < l; i++) { + this.updateCollider(colliders[i]); + } + + // do collide + var contacts = this._contacts; + + for (i = 0, l = contacts.length; i < l; i++) { + this.collide(contacts[i]); + } + + // do remove collider + var removeList = this._removeList; + for (i = 0, l = removeList.length; i < l; i++) { + this.removeCollider( removeList[i] ); + } + removeList.length = 0; + + // draw colliders + this.drawColliders(); + + this._updating = false; + }, + + collide: function (contact) { + var collisionType = contact.updateState(); + if (collisionType === CollisionType.None) { + return; + } + + this._doCollide(collisionType, contact); + }, + + _doCollide: function (collisionType, contact) { + var contactFunc; + switch (collisionType) { + case CollisionType.CollisionEnter: + contactFunc = 'onCollisionEnter'; + break; + case CollisionType.CollisionStay: + contactFunc = 'onCollisionStay'; + break; + case CollisionType.CollisionExit: + contactFunc = 'onCollisionExit'; + break; + } + + var collider1 = contact.collider1; + var collider2 = contact.collider2; + + var comps1 = collider1.node._components; + var comps2 = collider2.node._components; + + var i, l, comp; + for (i = 0, l = comps1.length; i < l; i++) { + comp = comps1[i]; + if (comp[contactFunc]) { + comp[contactFunc](collider2, collider1); + } + } + + for (i = 0, l = comps2.length; i < l; i++) { + comp = comps2[i]; + if (comp[contactFunc]) { + comp[contactFunc](collider1, collider2); + } + } + }, + + shouldCollide: function (c1, c2) { + return c1.node !== c2.node && (c1.mask & c2.category) && (c1.category & c2.mask); + }, + + initCollider: function (collider) { + if (!collider.world) { + var world = collider.world = {}; + world.aabb = cc.rect(); + world.preAabb = cc.rect(); + + world.radius = 0; + + if (collider instanceof cc.BoxCollider) { + world.position = null; + world.points = [cc.v2(), cc.v2(), cc.v2(), cc.v2()]; + } + else if (collider instanceof cc.PolygonCollider) { + world.position = null; + world.points = collider.points.slice(0, collider.points.length); + } + else if (collider instanceof cc.CircleCollider) { + world.position = cc.v2(); + world.points = null; + } + } + }, + + updateCollider: function (collider) { + var offset = collider.offset; + var world = collider.world; + var aabb = world.aabb; + var t = world.transform = collider.node.getNodeToWorldTransformAR(); + + var preAabb = world.preAabb; + preAabb.x = aabb.x; + preAabb.y = aabb.y; + preAabb.width = aabb.width; + preAabb.height = aabb.height; + + if (collider instanceof cc.BoxCollider) { + var size = collider.size; + var rect = cc.rect(offset.x - size.width/2, offset.y - size.height/2, size.width, size.height); + var wps = world.points; + var wp0 = wps[0]; + var wp1 = wps[1]; + var wp2 = wps[2]; + var wp3 = wps[3]; + cc.obbApplyAffineTransform(rect, t, wp0, wp1, wp2, wp3); + + var minx = Math.min(wp0.x, wp1.x, wp2.x, wp3.x); + var miny = Math.min(wp0.y, wp1.y, wp2.y, wp3.y); + var maxx = Math.max(wp0.x, wp1.x, wp2.x, wp3.x); + var maxy = Math.max(wp0.y, wp1.y, wp2.y, wp3.y); + + aabb.x = minx; + aabb.y = miny; + aabb.width = maxx - minx; + aabb.height = maxy - miny; + } + else if (collider instanceof cc.CircleCollider) { + var p = cc.pointApplyAffineTransform(collider.offset, t); + + var tmpX = t.tx, tmpY = t.ty; + t.tx = t.ty = 0; + + var tempP = cc.pointApplyAffineTransform(cc.v2(collider.radius, 0), t); + var d = cc.v2(tempP).mag(); + + world.radius = d; + world.position = cc.v2(p); + + t.tx = tmpX; + t.ty = tmpY; + + aabb.x = tmpX - d; + aabb.y = tmpY - d; + aabb.width = d * 2; + aabb.height = d * 2; + } + else if (collider instanceof cc.PolygonCollider) { + var points = collider.points; + var worldPoints = world.points; + + var minx = 1e6, miny = 1e6, maxx = -1e6, maxy = -1e6; + for (var i = 0, l = points.length; i < l; i++) { + var p = points[i].add(offset); + p = cc.pointApplyAffineTransform(p, t); + worldPoints[i] = p; + + if (p.x > maxx) maxx = p.x; + if (p.x < minx) minx = p.x; + if (p.y > maxy) maxy = p.y; + if (p.y < miny) miny = p.y; + } + + aabb.x = minx; + aabb.y = miny; + aabb.width = maxx - minx; + aabb.height = maxy - miny; + } + }, + + addCollider: function (collider) { + var colliders = this._colliders; + var index = colliders.indexOf(collider); + if (index === -1) { + for (var i = 0, l = colliders.length; i < l; i++) { + var other = colliders[i]; + if (this.shouldCollide(collider, other)) { + var contact = new Contact(collider, other); + this._contacts.push(contact); + } + } + + colliders.push(collider); + this.initCollider(collider); + } + + index = this._removeList.indexOf(collider); + if (index !== -1) { + this._removeList.splice(index, 1); + } + }, + + removeCollider: function (collider) { + var colliders = this._colliders; + var index = colliders.indexOf(collider); + if (index >= 0) { + if (this._updating) { + var removeList = this._removeList; + if (removeList.indexOf(collider) === -1) { + removeList.push(collider); + } + } + else { + colliders.splice(index, 1); + + var contacts = this._contacts; + for (var i = contacts.length - 1; i >= 0; i--) { + var contact = contacts[i]; + if (contact.collider1 === collider || contact.collider2 === collider) { + if (contact.touching) { + this._doCollide(CollisionType.CollisionExit, contact); + } + + contacts.splice(i, 1); + } + } + } + } + else { + cc.error('collider not added or already removed'); + } + }, + + drawColliders: function () { + if (!this._enabledDebugDraw || !this._debugDrawer) { + return; + } + + this._debugDrawer.clear(); + + var colliders = this._colliders; + + for (var i = 0, l = colliders.length; i < l; i++) { + var collider = colliders[i]; + + if (collider instanceof cc.BoxCollider || collider instanceof cc.PolygonCollider) { + this._debugDrawer.drawPoly(collider.world.points); + } + else if (collider instanceof cc.CircleCollider) { + this._debugDrawer.drawCircle(collider.world.position, collider.world.radius, 0, 30); + } + + if (this.enabledDrawBoundingBox) { + var aabb = collider.world.aabb; + var points = [cc.v2(aabb.xMin, aabb.yMin), cc.v2(aabb.xMin, aabb.yMax), cc.v2(aabb.xMax, aabb.yMax), cc.v2(aabb.xMax, aabb.yMin)]; + this._debugDrawer.drawPoly(points, null, 1, cc.Color.BLUE); + } + } + }, + + onSceneLaunched: function () { + if (this._enabledDebugDraw && this._debugDrawer) { + this._debugDrawer.removeFromParent(); + cc.director.getScene()._sgNode.addChild(this._debugDrawer); + } + } +}); + +/** + * !#en + * !#zh + * 是否绘制碰撞组件的形状,默认为不绘制 + * @property {Boolean} enabledDebugDraw + * @default false + */ +cc.js.getset(CollisionManager.prototype, 'enabledDebugDraw', + function () { + return this._enabledDebugDraw; + }, + function (value) { + if (value && !this._enabledDebugDraw) { + if (!this._debugDrawer) { + this._debugDrawer = new cc.DrawNode(); + this._debugDrawer.retain(); + } + + cc.director.getScene()._sgNode.addChild(this._debugDrawer); + cc.director.on(cc.Director.EVENT_AFTER_SCENE_LAUNCH, this.onSceneLaunched, this); + } + else if (!value && this._enabledDebugDraw) { + cc.director.getScene()._sgNode.removeChild(this._debugDrawer); + cc.director.off(cc.Director.EVENT_AFTER_SCENE_LAUNCH, this.onSceneLaunched, this); + } + + this._enabledDebugDraw = value; + } +); + + +cc.CollisionManager = module.exports = CollisionManager; diff --git a/cocos2d/core/collider/CCContact.js b/cocos2d/core/collider/CCContact.js new file mode 100644 index 0000000000..1cfa2cc281 --- /dev/null +++ b/cocos2d/core/collider/CCContact.js @@ -0,0 +1,84 @@ + +var Intersection = require('./CCIntersection'); + +var CollisionType = cc.Enum({ + None: 0, + CollisionEnter: 1, + CollisionStay: 2, + CollisionExit: 3 +}); + +function Contact (collider1, collider2) { + this.collider1 = collider1; + this.collider2 = collider2; + + this.touching = false; + + var isCollider1Polygon = (collider1 instanceof cc.BoxCollider) || (collider1 instanceof cc.PolygonCollider); + var isCollider2Polygon = (collider2 instanceof cc.BoxCollider) || (collider2 instanceof cc.PolygonCollider); + var isCollider1Circle = collider1 instanceof cc.CircleCollider; + var isCollider2Circle = collider2 instanceof cc.CircleCollider; + + if (isCollider1Polygon && isCollider2Polygon) { + this.testFunc = Intersection.polygonPolygon; + } + else if (isCollider1Circle && isCollider2Circle) { + this.testFunc = Intersection.circleCircle; + } + else if (isCollider1Polygon && isCollider2Circle) { + this.testFunc = Intersection.polygonCircle; + } + else if (isCollider1Circle && isCollider2Polygon) { + this.testFunc = Intersection.polygonCircle; + this.collider1 = collider2; + this.collider2 = collider1; + } + else { + cc.error('Can\'t find testFunc for (%s, $s).', cc.js.getClassName(collider1), cc.js.getClassName(collider2)); + } +} + +Contact.prototype.test = function () { + var world1 = this.collider1.world; + var world2 = this.collider2.world; + + if (!world1.aabb.intersects(world2.aabb)) { + return false; + } + + if (this.testFunc === Intersection.polygonPolygon) { + return this.testFunc(world1.points, world2.points); + } + else if (this.testFunc === Intersection.circleCircle) { + return this.testFunc(world1, world2); + } + else if (this.testFunc === Intersection.polygonCircle) { + return this.testFunc(world1.points, world2); + } + + return false; +}; + +Contact.prototype.updateState = function () { + var result = this.test(); + + var type = CollisionType.None; + if (result && !this.touching) { + this.touching = true; + type = CollisionType.CollisionEnter; + } + else if (result && this.touching) { + type = CollisionType.CollisionStay; + } + else if (!result && this.touching) { + this.touching = false; + type = CollisionType.CollisionExit; + } + + return type; +}; + + +Contact.CollisionType = CollisionType; + +module.exports = Contact; diff --git a/cocos2d/core/collider/CCIntersection.js b/cocos2d/core/collider/CCIntersection.js new file mode 100644 index 0000000000..59f33f4da6 --- /dev/null +++ b/cocos2d/core/collider/CCIntersection.js @@ -0,0 +1,313 @@ +/** + * !#en Intersection helper class + * !#zh 辅助类,用于测试形状与形状是否相交 + * @class Intersection + * @static + */ +var Intersection = {}; + +/** + * @method lineLine + * @param {Vec2} a1 + * @param {Vec2} a2 + * @param {Vec2} b1 + * @param {Vec2} b2 + * @return {boolean} + */ +function lineLine ( a1, a2, b1, b2 ) { + // jshint camelcase:false + + var ua_t = (b2.x - b1.x) * (a1.y - b1.y) - (b2.y - b1.y) * (a1.x - b1.x); + var ub_t = (a2.x - a1.x) * (a1.y - b1.y) - (a2.y - a1.y) * (a1.x - b1.x); + var u_b = (b2.y - b1.y) * (a2.x - a1.x) - (b2.x - b1.x) * (a2.y - a1.y); + + if ( u_b !== 0 ) { + var ua = ua_t / u_b; + var ub = ub_t / u_b; + + if ( 0 <= ua && ua <= 1 && 0 <= ub && ub <= 1 ) { + return true; + } + } + + return false; +} + +Intersection.lineLine = lineLine; + +/** + * @method lineRect + * @param {Vec2} a1 + * @param {Vec2} a2 + * @param {Vec2} b + * @return {boolean} + */ +function lineRect ( a1, a2, b ) { + var r0 = new cc.Vec2( b.x, b.y ); + var r1 = new cc.Vec2( b.x, b.yMax ); + var r2 = new cc.Vec2( b.xMax, b.yMax ); + var r3 = new cc.Vec2( b.xMax, b.y ); + + if ( lineLine( a1, a2, r0, r1 ) ) + return true; + + if ( lineLine( a1, a2, r1, r2 ) ) + return true; + + if ( lineLine( a1, a2, r2, r3 ) ) + return true; + + if ( lineLine( a1, a2, r3, r0 ) ) + return true; + + return false; +} + +Intersection.lineRect = lineRect; + +/** + * @method linePolygon + * @param {Vec2} a1 + * @param {Vec2} a2 + * @param {[Vec2]} b + * @return {boolean} + */ +function linePolygon ( a1, a2, b ) { + var length = b.length; + + for ( var i = 0; i < length; ++i ) { + var b1 = b[i]; + var b2 = b[(i+1)%length]; + + if ( lineLine( a1, a2, b1, b2 ) ) + return true; + } + + return false; +} + +Intersection.linePolygon = linePolygon; + +/** + * @method rectRect + * @param {Rect} a + * @param {Rect} b + * @return {boolean} + */ +function rectRect ( a, b ) { + // jshint camelcase:false + + var a_min_x = a.x; + var a_min_y = a.y; + var a_max_x = a.x + a.width; + var a_max_y = a.y + a.height; + + var b_min_x = b.x; + var b_min_y = b.y; + var b_max_x = b.x + b.width; + var b_max_y = b.y + b.height; + + return a_min_x <= b_max_x && + a_max_x >= b_min_x && + a_min_y <= b_max_y && + a_max_y >= b_min_y + ; +} + +Intersection.rectRect = rectRect; + +/** + * @method rectPolygon + * @param {Rect} a + * @param {[Vec2]} b + * @return {boolean} + */ +function rectPolygon ( a, b ) { + var i, l; + var r0 = new cc.Vec2( a.x, a.y ); + var r1 = new cc.Vec2( a.x, a.yMax ); + var r2 = new cc.Vec2( a.xMax, a.yMax ); + var r3 = new cc.Vec2( a.xMax, a.y ); + + // intersection check + if ( linePolygon( r0, r1, b ) ) + return true; + + if ( linePolygon( r1, r2, b ) ) + return true; + + if ( linePolygon( r2, r3, b ) ) + return true; + + if ( linePolygon( r3, r0, b ) ) + return true; + + // check if a contains b + for ( i = 0, l = b.length; i < l; ++i ) { + if ( pointInPolygon(b[i], a) ) + return true; + } + + // check if b contains a + if ( pointInPolygon(r0, b) ) + return true; + + if ( pointInPolygon(r1, b) ) + return true; + + if ( pointInPolygon(r2, b) ) + return true; + + if ( pointInPolygon(r3, b) ) + return true; + + return false; +} + +Intersection.rectPolygon = rectPolygon; + +/** + * @method polygonPolygon + * @param {[Vec2]} a + * @param {[Vec2]} b + * @return {boolean} + */ +function polygonPolygon ( a, b ) { + var i, l; + + // check if a intersects b + for ( i = 0, l = a.length; i < l; ++i ) { + var a1 = a[i]; + var a2 = a[(i+1)%l]; + + if ( linePolygon( a1, a2, b ) ) + return true; + } + + // check if a contains b + for ( i = 0, l = b.length; i < l; ++i ) { + if ( pointInPolygon(b[i], a) ) + return true; + } + + // check if b contains a + for ( i = 0, l = a.length; i < l; ++i ) { + if ( pointInPolygon( a[i], b ) ) + return true; + } + + return false; +} + +Intersection.polygonPolygon = polygonPolygon; + + +/** + * @method pointInPolygon + * @param {Vec2} point + * @param {[Vec2]} polygon + * @return {boolean} + */ +function pointInPolygon (point, polygon) { + var inside = false; + var x = point.x; + var y = point.y; + + // use some raycasting to test hits + // https://github.com/substack/point-in-polygon/blob/master/index.js + var length = polygon.length; + + for ( var i = 0, j = length-1; i < length; j = i++ ) { + var xi = polygon[i].x, yi = polygon[i].y, + xj = polygon[j].x, yj = polygon[j].y, + intersect = ((yi > y) !== (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi); + + if ( intersect ) inside = !inside; + } + + return inside; +} + +Intersection.pointInPolygon = pointInPolygon; + + +/** + * @method circleCircle + * @param {Object} a - Object contains position and radius + * @param {Object} b - Object contains position and radius + * @return {boolean} + */ +function circleCircle (a, b) { + var distance = a.position.sub(b.position).mag(); + return distance < (a.radius + b.radius); +} + +Intersection.circleCircle = circleCircle; + + +/** + * @method polygonCircle + * @param {[Vec2]} polygon + * @param {Object} circle - Object contains position and radius + * @return {boolean} + */ +function polygonCircle (polygon, circle) { + var position = circle.position; + if (pointInPolygon(position, polygon)) { + return true; + } + + for (var i = 0, l = polygon.length; i < l; i++) { + var start = i === 0 ? polygon[polygon.length - 1] : polygon[i- 1]; + var end = polygon[i]; + + if (pointLineDistance(position, start, end, true) < circle.radius) { + return true; + } + } + + return false; +} + +Intersection.polygonCircle = polygonCircle; + +/** + * !#en Calculate the distance of point to line. + * !#zh 计算点到直线的距离。如果这是一条线段并且垂足不在线段内,则会计算点到线段端点的距离。 + * @method pointLineDistance + * @param {Vec2} point + * @param {Vec2} start - start point of line + * @param {Vec2} end - end point of line + * @param {boolean} isSegment - whether this line is a segment + * @return {boolean} + */ +function pointLineDistance(point, start, end, isSegment) { + var dx = end.x - start.x; + var dy = end.y - start.y; + var d = dx*dx + dy*dy; + var t = ((point.x - start.x) * dx + (point.y - start.y) * dy) / d; + var p; + + if (!isSegment) { + p = cc.v2(start.x + t * dx, start.y + t * dy); + } + else { + if (d) { + if (t < 0) p = start; + else if (t > 1) p = end; + else p = cc.v2(start.x + t * dx, start.y + t * dy); + } + else { + p = start; + } + } + + dx = point.x - p.x; + dy = point.y - p.y; + return Math.sqrt(dx*dx + dy*dy); +} + +Intersection.pointLineDistance = pointLineDistance; + + +cc.Intersection = module.exports = Intersection; diff --git a/cocos2d/core/collider/CCPolygonCollider.js b/cocos2d/core/collider/CCPolygonCollider.js new file mode 100644 index 0000000000..7e4d0616bf --- /dev/null +++ b/cocos2d/core/collider/CCPolygonCollider.js @@ -0,0 +1,74 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + 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. + ****************************************************************************/ + +/** + * !#en Polygon Collider. + * !#zh 多边形碰撞组件 + * @class PolygonCollider + * @extends Component + */ +var PolygonCollider = cc.Class({ + name: 'cc.PolygonCollider', + extends: require('./CCCollider'), + + editor: CC_EDITOR && { + menu: 'i18n:MAIN_MENU.component.collider/Polygon Collider', + }, + + properties: { + _offset: cc.v2(0, 0), + + /** + * !#en Position offset + * !#zh 位置偏移量 + * @property offset + * @type {Vec2} + */ + offset: { + get: function () { + return this._offset; + }, + set: function (value) { + this._offset = value; + }, + type: cc.Vec2 + }, + + /** + * !#en Polygon points + * !#zh 多边形顶点数组 + * @property points + * @type {[Vec2]} + */ + points: { + default: function () { + return [cc.v2(-50, -50), cc.v2(-50, 50), cc.v2(50, 50), cc.v2(50, -50)]; + }, + type: [cc.Vec2] + } + } +}); + +cc.PolygonCollider = module.exports = PolygonCollider; diff --git a/cocos2d/core/collider/index.js b/cocos2d/core/collider/index.js new file mode 100644 index 0000000000..e772ebee6c --- /dev/null +++ b/cocos2d/core/collider/index.js @@ -0,0 +1,6 @@ + +require('./CCCollisionManager'); +require('./CCCollider'); +require('./CCBoxCollider'); +require('./CCCircleCollider'); +require('./CCPolygonCollider'); diff --git a/cocos2d/core/components/CCAnimation.js b/cocos2d/core/components/CCAnimation.js index 419c84c6d4..c707ab6985 100644 --- a/cocos2d/core/components/CCAnimation.js +++ b/cocos2d/core/components/CCAnimation.js @@ -79,8 +79,7 @@ var Animation = cc.Class({ return this._defaultClip; }, set: function (value) { - var engine = cc.engine; - if (!CC_EDITOR || (engine && engine.isPlaying)) { + if (!CC_EDITOR || (cc.engine && cc.engine.isPlaying)) { return; } @@ -113,12 +112,8 @@ var Animation = cc.Class({ get: function () { return this._currentClip; }, - set: function (value, force) { + set: function (value) { this._currentClip = value; - - if (CC_EDITOR && force && value) { - this._updateClip(value); - } }, type: AnimationClip, visible: false @@ -504,7 +499,7 @@ var Animation = cc.Class({ } }, - _updateClip: (CC_TEST || CC_EDITOR) && function (clip, clipName) { + _updateClip: (CC_TEST || CC_EDITOR) && function (clip, clipName, notReload) { this._init(); clipName = clipName || clip.name; @@ -536,8 +531,10 @@ var Animation = cc.Class({ oldState._name = clipName; } - oldState._clip = clip; - this._animator._reloadClip(oldState); + if (!notReload) { + oldState._clip = clip; + this._animator._reloadClip(oldState); + } } }); diff --git a/cocos2d/core/components/CCComponent.js b/cocos2d/core/components/CCComponent.js index ef882bf680..34d90ea09b 100644 --- a/cocos2d/core/components/CCComponent.js +++ b/cocos2d/core/components/CCComponent.js @@ -29,6 +29,7 @@ var IdGenerater = require('../platform/id-generater'); var Flags = cc.Object.Flags; var IsOnEnableCalled = Flags.IsOnEnableCalled; +var IsEditorOnEnableCalled = Flags.IsEditorOnEnableCalled; var IsOnLoadStarted = Flags.IsOnLoadStarted; var IsOnLoadCalled = Flags.IsOnLoadCalled; var IsOnStartCalled = Flags.IsOnStartCalled; @@ -47,18 +48,18 @@ var callOnLostFocusInTryCatch = CC_EDITOR && eval(ExecInTryCatchTmpl.replace(/_F function callOnEnable (self, enable) { if (CC_EDITOR) { - //if (enable ) { - // if ( !(self._objFlags & IsEditorOnEnabledCalled) ) { - // editorCallback.onComponentEnabled(self); - // self._objFlags |= IsEditorOnEnabledCalled; - // } - //} - //else { - // if (self._objFlags & IsEditorOnEnabledCalled) { - // editorCallback.onComponentDisabled(self); - // self._objFlags &= ~IsEditorOnEnabledCalled; - // } - //} + if (enable) { + if ( !(self._objFlags & IsEditorOnEnableCalled) ) { + cc.engine.emit('component-enabled', self.uuid); + self._objFlags |= IsEditorOnEnableCalled; + } + } + else { + if (self._objFlags & IsEditorOnEnableCalled) { + cc.engine.emit('component-disabled', self.uuid); + self._objFlags &= ~IsEditorOnEnableCalled; + } + } if ( !(cc.engine.isPlaying || self.constructor._executeInEditMode) ) { return; } @@ -81,29 +82,25 @@ function callOnEnable (self, enable) { } cc.director.getScheduler().resumeTarget(self); - _registerEvent(self, true); self._objFlags |= IsOnEnableCalled; } } - else { - if (enableCalled) { - if (self.onDisable) { - if (CC_EDITOR) { - callOnDisableInTryCatch(self); - } - else { - self.onDisable(); - } + else if (enableCalled) { + if (self.onDisable) { + if (CC_EDITOR) { + callOnDisableInTryCatch(self); + } + else { + self.onDisable(); } - - cc.director.getScheduler().pauseTarget(self); - - _registerEvent(self, false); - - self._objFlags &= ~IsOnEnableCalled; } + + cc.director.getScheduler().pauseTarget(self); + _registerEvent(self, false); + + self._objFlags &= ~IsOnEnableCalled; } } diff --git a/cocos2d/core/components/CCComponentEventHandler.js b/cocos2d/core/components/CCComponentEventHandler.js index 74ed52d673..e1eb563194 100644 --- a/cocos2d/core/components/CCComponentEventHandler.js +++ b/cocos2d/core/components/CCComponentEventHandler.js @@ -80,15 +80,15 @@ cc.Component.EventHandler = cc.Class({ /** * @method emitEvents * @param {Component.EventHandler[]} events - * @param {*} params * @statics */ - emitEvents: function(events, params) { + emitEvents: function(events) { + 'use strict'; for (var i = 0, l = events.length; i < l; i++) { var event = events[i]; if (! event instanceof cc.Component.EventHandler) continue; - event.emit(params); + event.emit(Array.prototype.slice.call(arguments,1)); } } }, @@ -113,6 +113,6 @@ cc.Component.EventHandler = cc.Class({ var handler = comp[this.handler]; if (typeof(handler) !== 'function') return; - handler.call(comp, params); + handler.apply(comp, params); } }); diff --git a/cocos2d/core/components/CCEditBox.js b/cocos2d/core/components/CCEditBox.js index 2196c9a484..7f627df86c 100644 --- a/cocos2d/core/components/CCEditBox.js +++ b/cocos2d/core/components/CCEditBox.js @@ -420,7 +420,7 @@ var EditBox = cc.Class({ this._createBackgroundSprite(); - if(this._useOriginalSize && CC_EDITOR){ + if (CC_EDITOR && this._useOriginalSize) { this.node.setContentSize(sgNode.getContentSize()); this._useOriginalSize = false; } else { @@ -445,15 +445,15 @@ var EditBox = cc.Class({ }, editBoxEditingDidBegan: function() { - cc.Component.EventHandler.emitEvents(this.editingDidBegan); + cc.Component.EventHandler.emitEvents(this.editingDidBegan, this); }, editBoxEditingDidEnded: function() { - cc.Component.EventHandler.emitEvents(this.editingDidEnded); + cc.Component.EventHandler.emitEvents(this.editingDidEnded, this); }, editBoxTextChanged: function(editBox, text) { - cc.Component.EventHandler.emitEvents(this.textChanged, text); + cc.Component.EventHandler.emitEvents(this.textChanged, text, this); }, onLoad: function() { @@ -465,8 +465,10 @@ var EditBox = cc.Class({ }, _registerEvent: function () { - this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); - this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); + if(!CC_JSB) { + this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this); + this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this); + } }, _onTouchBegan: function(event) { @@ -485,4 +487,14 @@ var EditBox = cc.Class({ }); +if(CC_JSB) { + EditBox.prototype.editBoxEditingDidBegin = function (sender) { + this.editBoxEditingDidBegan(sender); + } + + EditBox.prototype.editBoxEditingDidEnd = function (sender) { + this.editBoxEditingDidEnded(sender); + } +} + cc.EditBox = module.exports = EditBox; diff --git a/cocos2d/core/components/CCLabel.js b/cocos2d/core/components/CCLabel.js index 5cd7abac48..da7759d614 100644 --- a/cocos2d/core/components/CCLabel.js +++ b/cocos2d/core/components/CCLabel.js @@ -87,6 +87,7 @@ var Label = cc.Class({ editor: CC_EDITOR && { menu: 'i18n:MAIN_MENU.component.renderers/Label', help: 'i18n:COMPONENT.help_url.label', + inspector: 'app://editor/page/inspector/label.html', }, properties: { @@ -191,7 +192,7 @@ var Label = cc.Class({ /** * !#en Overflow of label. * !#zh 文字显示超出范围时的处理方式。 - * @property {Label.Overflow} overFlow + * @property {Label.Overflow} overflow */ overflow: { default: Overflow.NONE, @@ -364,7 +365,7 @@ var Label = cc.Class({ sgNode.setLineHeight(this._lineHeight); sgNode.setString(this.string); sgNode.setFontFileOrFamily(fntRawUrl, textureUrl); - if(this._useOriginalSize && CC_EDITOR){ + if (CC_EDITOR && this._useOriginalSize) { this.node.setContentSize(sgNode.getContentSize()); this._useOriginalSize = false; } else { diff --git a/cocos2d/core/components/CCLayout.js b/cocos2d/core/components/CCLayout.js index 65e400e6d5..9efecac732 100644 --- a/cocos2d/core/components/CCLayout.js +++ b/cocos2d/core/components/CCLayout.js @@ -185,7 +185,7 @@ var Layout = cc.Class({ set: function(value) { this._N$layoutType = value; - if (this.type !== Type.NONE && this._resize === ResizeMode.CONTAINER && CC_EDITOR && !cc.engine.isPlaying) { + if (CC_EDITOR && this.type !== Type.NONE && this._resize === ResizeMode.CONTAINER && !cc.engine.isPlaying) { var reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); if (reLayouted) { return; @@ -218,7 +218,7 @@ var Layout = cc.Class({ } this._resize = value; - if (this.type !== Type.NONE && value === ResizeMode.CONTAINER && CC_EDITOR && !cc.engine.isPlaying) { + if (CC_EDITOR && this.type !== Type.NONE && value === ResizeMode.CONTAINER && !cc.engine.isPlaying) { var reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); if (reLayouted) { return; @@ -257,7 +257,7 @@ var Layout = cc.Class({ tooltip: 'i18n:COMPONENT.layout.start_axis', type: AxisDirection, notify: function() { - if (this._resize === ResizeMode.CONTAINER && CC_EDITOR && !cc.engine.isPlaying) { + if (CC_EDITOR && this._resize === ResizeMode.CONTAINER && !cc.engine.isPlaying) { var reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); if (reLayouted) { return; diff --git a/cocos2d/core/components/CCMask.js b/cocos2d/core/components/CCMask.js index 3e8acbeab8..8957573d8d 100644 --- a/cocos2d/core/components/CCMask.js +++ b/cocos2d/core/components/CCMask.js @@ -116,19 +116,8 @@ var Mask = cc.Class({ return new cc.ClippingNode(this._clippingStencil); }, - _initSgNode: function () { - var clippingNode = this._sgNode; - clippingNode.setContentSize(this.node.getContentSize(true)); - }, - - //onLoad: function () { - // this._super(); - // // ignore node size - // if (this.node._sizeProvider === this._sgNode) { - // this.node._sizeProvider = null; - // } - //}, - + _initSgNode: function () {}, + onEnable: function () { this._refreshStencil(); this._super(); @@ -177,7 +166,7 @@ var Mask = cc.Class({ var center = cc.v2(x + width /2, y+height/2); var radius = {x: width/2, y: height/2}; var segements = this._segements; - this._clippingStencil.drawPoly(this._calculateCircle(center,radius, segements), color, 0, color); + this._clippingStencil.drawPoly(this._calculateCircle(center, radius, segements), color, 0, color); } } }); diff --git a/cocos2d/core/components/CCRendererInSG.js b/cocos2d/core/components/CCRendererInSG.js index 9e37e363c4..ad55092bbb 100644 --- a/cocos2d/core/components/CCRendererInSG.js +++ b/cocos2d/core/components/CCRendererInSG.js @@ -40,32 +40,44 @@ var RendererInSG = cc.Class({ * @property {_ccsg.Node} _sgNode * @private */ - this._sgNode = this._createSgNode(); - if (this._sgNode) { - // retain immediately - // will be released in onDestroy - this._sgNode.retain(); - } - else { + var sgNode = this._sgNode = this._createSgNode(); + if (CC_EDITOR && !sgNode) { cc.error('Not support for asynchronous creating node in SG'); } - + if (CC_JSB) { + // retain immediately + // will be released in onDestroy + sgNode.retain(); + } + // The replacement node used when this component disabled this._plainNode = new _ccsg.Node(); - this._plainNode.retain(); + if (CC_JSB) { + this._plainNode.retain(); + } + }, + + onLoad: function () { + this._initSgNode(); + if (CC_EDITOR) { + var sgSize = this._sgNode.getContentSize(); + // sgSize is not a Vec2 in JSB + if (sgSize.width !== 0 || sgSize.height !== 0) { + cc.error('Renderer error: Size of the cc._RendererInSG._sgNode must be zero'); + } + } }, onEnable: function () { this._replaceSgNode(this._sgNode); - this.node._ignoreAnchor = true; }, + onDisable: function () { this._replaceSgNode(this._plainNode); - this.node._ignoreAnchor = false; }, + onDestroy: function () { - this._super(); - + this._removeSgNode(); var releasedByNode = this.node._sgNode; if (this._plainNode !== releasedByNode) { this._plainNode.release(); @@ -73,14 +85,14 @@ var RendererInSG = cc.Class({ }, _replaceSgNode: function (sgNode) { - if ( !(sgNode instanceof _ccsg.Node) && CC_EDITOR) { + if (CC_EDITOR && !(sgNode instanceof _ccsg.Node)) { 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) { + if (CC_EDITOR && replaced === sgNode) { cc.warn('The same sgNode'); return; } diff --git a/cocos2d/core/components/CCRendererUnderSG.js b/cocos2d/core/components/CCRendererUnderSG.js index f28388d633..b7bed2a7c6 100644 --- a/cocos2d/core/components/CCRendererUnderSG.js +++ b/cocos2d/core/components/CCRendererUnderSG.js @@ -52,20 +52,33 @@ var RendererUnderSG = cc.Class({ // You should reimplement this function if your _sgNode maybe null. onLoad: function () { - this._super(); + this._initSgNode(); + var sgNode = this._sgNode; + if ( !this.node._sizeProvider ) { + this.node._sizeProvider = sgNode; + } this._appendSgNode(this._sgNode); }, + onEnable: function () { if (this._sgNode) { this._sgNode.setVisible(true); } }, + onDisable: function () { if (this._sgNode) { this._sgNode.setVisible(false); } }, + onDestroy: function () { + if ( this.node._sizeProvider === this._sgNode ) { + this.node._sizeProvider = null; + } + this._removeSgNode(); + }, + _appendSgNode: function (sgNode) { if ( !sgNode ) { return; diff --git a/cocos2d/core/components/CCSGComponent.js b/cocos2d/core/components/CCSGComponent.js index 594f23503b..986ab36173 100644 --- a/cocos2d/core/components/CCSGComponent.js +++ b/cocos2d/core/components/CCSGComponent.js @@ -51,19 +51,12 @@ var SGComponent = cc.Class({ } }, - 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(); - }, + //onLoad: function () { + // this._initSgNode(); + //}, + //onDestroy: function () { + // this._removeSgNode(); + //}, /** * Create and returns your new scene graph node (SGNode) to add to scene graph. diff --git a/cocos2d/core/components/CCSpriteDistortion.js b/cocos2d/core/components/CCSpriteDistortion.js new file mode 100644 index 0000000000..d12a370de2 --- /dev/null +++ b/cocos2d/core/components/CCSpriteDistortion.js @@ -0,0 +1,111 @@ +/**************************************************************************** + Copyright (c) 2013-2016 Chukong Technologies Inc. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Chukong Aipu reserves all rights not expressly granted to you. + + 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. + ****************************************************************************/ + +/** + * !#en A distortion used to change the rendering of simple sprite.If will take effect after sprite component is added. + * !#zh 扭曲效果组件,用于改变SIMPLE类型sprite的渲染,只有当sprite组件已经添加后,才能起作用. + * @class SpriteDistortion + * @extends Component + * @example + * // Create a new node and add sprite components. + * var node = new cc.Node("New Sprite"); + * var sprite = node.addComponent(cc.Sprite); + * var spriteDistortion = node.addComponent(cc.SpriteDistortion); + * node.parent = this.node; + */ + +var SpriteDistortion = cc.Class({ + name: 'cc.SpriteDistortion', extends: require('./CCComponent'), + editor: CC_EDITOR && { + menu: 'i18n:MAIN_MENU.component.renderers/SpriteDistortion', + executeInEditMode: true, + requireComponent: cc.Sprite, + }, + + ctor: function() { + this._spriteSGNode = null; + }, + + properties: { + /** + * !#en Change the UV offset for distortion rendering. + * !#zh 在渲染时改变UV的整体偏移. + * @property offset + * @type {Vec2} + * @example + * distortion.offset = new cc.Vec2(0.5, 0.3);; + */ + _distortionOffset: cc.v2(0.0,0.0), + offset: { + get: function() { + return this._distortionOffset; + }, + set:function(value) { + this._distortionOffset.x = value.x; + this._distortionOffset.y = value.y; + } + }, + + /** + * !#en Change the UV scale for distortion rendering. + * !#zh 在渲染时改变UV的寻址系数 + * @property tiling + * @type {Vec2} + * @example + * distortion.tiling = new cc.Vec2(0.5, 0.3);; + */ + _distortionTiling: cc.v2(1.0,1.0), + tiling: { + get: function() { + return this._distortionTiling; + }, + set:function(value) { + this._distortionTiling.x = value.x; + this._distortionTiling.y = value.y; + } + }, + }, + + onEnable: function () { + var sprite = this.node.getComponent('cc.Sprite'); + var sgNode = this._spriteSGNode = sprite && sprite._sgNode; + if(this._spriteSGNode) { + sgNode.setState(cc.Scale9Sprite.state.DISTORTION); + sgNode._distortionOffset = this._distortionOffset; + sgNode._distortionTiling = this._distortionTiling; + } + }, + + onDisable: function () { + if(this._spriteSGNode) { + this._spriteSGNode.setState(cc.Scale9Sprite.state.NORMAL); + } + + this._spriteSGNode = null; + }, + +}); + +cc.SpriteDistortion = module.exports = SpriteDistortion; diff --git a/cocos2d/core/components/index.js b/cocos2d/core/components/index.js index 027a97c615..e246995f45 100644 --- a/cocos2d/core/components/index.js +++ b/cocos2d/core/components/index.js @@ -43,4 +43,5 @@ module.exports = [ require('./CCScrollView'), require('./CCLayout'), require('./CCEditBox'), + require('./CCSpriteDistortion'), ]; diff --git a/cocos2d/core/event/event-listeners.js b/cocos2d/core/event/event-listeners.js index 51991d9ee6..885cf6823e 100644 --- a/cocos2d/core/event/event-listeners.js +++ b/cocos2d/core/event/event-listeners.js @@ -49,25 +49,33 @@ EventListeners.prototype.invoke = function (event) { } else { endIndex = list.length - 1; - for (i = 0; i <= endIndex;) { - callingFunc = list[i]; - target = list[i+1]; - hasTarget = target && typeof target === 'object'; - var increment; - if (hasTarget) { - callingFunc.call(target, event); - increment = 2; - } - else { - callingFunc.call(event.currentTarget, event); - increment = 1; + if (key === cc.Director.EVENT_COMPONENT_UPDATE) { + for (i = 1; i <= endIndex; i += 2) { + target = list[i]; + target.update(event.detail); } + } + else { + for (i = 0; i <= endIndex;) { + callingFunc = list[i]; + target = list[i+1]; + hasTarget = target && typeof target === 'object'; + var increment; + if (hasTarget) { + callingFunc.call(target, event); + increment = 2; + } + else { + callingFunc.call(event.currentTarget, event); + increment = 1; + } - if (event._propagationImmediateStopped || i + increment > endIndex) { - break; - } + if (event._propagationImmediateStopped || i + increment > endIndex) { + break; + } - i += increment; + i += increment; + } } } } diff --git a/cocos2d/core/index.js b/cocos2d/core/index.js index b6817dcfb7..2d947a6604 100644 --- a/cocos2d/core/index.js +++ b/cocos2d/core/index.js @@ -35,6 +35,7 @@ if (!CC_EDITOR || !Editor.isMainProcess) { require('./CCScene'); require('./components'); + require('./collider'); } require('./base-ui/CCWidgetManager'); diff --git a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js index 489527321a..fb00c7749d 100644 --- a/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js +++ b/cocos2d/core/label/CCSGLabelCanvasRenderCmd.js @@ -52,6 +52,7 @@ } }; + proto._syncStatus = function (parentCmd) { var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag; var parentNode = parentCmd ? parentCmd._node : null; diff --git a/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js b/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js index bf33adf4b9..2ec5be05b8 100644 --- a/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js +++ b/cocos2d/core/label/CCSGLabelWebGLRenderCmd.js @@ -58,6 +58,11 @@ cc.js.mixin(proto, _ccsg.Label.TTFLabelBaker.prototype); proto.constructor = _ccsg.Label.WebGLRenderCmd; +proto._updateDisplayOpacity = function (parentOpacity) { + _ccsg.Node.WebGLRenderCmd.prototype._updateDisplayOpacity.call(this, parentOpacity); + this._rebuildLabelSkin(); +}; + proto.rendering = function (ctx) { var node = this._node; diff --git a/cocos2d/core/labelttf/CCLabelTTF.js b/cocos2d/core/labelttf/CCLabelTTF.js index ad4084b35c..57eb2208a4 100644 --- a/cocos2d/core/labelttf/CCLabelTTF.js +++ b/cocos2d/core/labelttf/CCLabelTTF.js @@ -775,7 +775,7 @@ cc.LabelTTF = _ccsg.Sprite.extend(/** @lends cc.LabelTTF# */{ } }); -cc.assert(cc.js.isFunction(cc._tmp.PrototypeLabelTTF), cc._LogInfos.MissingFile, "LabelTTFPropertyDefine.js"); +cc.assert(typeof cc._tmp.PrototypeLabelTTF === 'function', cc._LogInfos.MissingFile, "LabelTTFPropertyDefine.js"); cc._tmp.PrototypeLabelTTF(); delete cc._tmp.PrototypeLabelTTF; diff --git a/cocos2d/core/load-pipeline/CCLoader.js b/cocos2d/core/load-pipeline/CCLoader.js index 419f7e7109..e94ad28612 100644 --- a/cocos2d/core/load-pipeline/CCLoader.js +++ b/cocos2d/core/load-pipeline/CCLoader.js @@ -203,7 +203,7 @@ JS.mixin(cc.loader, { var url = resources[i].id || resources[i]; if (typeof url !== 'string') continue; - var item = this._items.map[url]; + var item = this.getItem(url); if ( !item || (item && !item.complete) ) { this._items.addListener(url, loadedCheck); checker[url] = null; @@ -219,11 +219,12 @@ JS.mixin(cc.loader, { // No new resources, complete directly if (totalCount === completedCount) { var id = resources[0].id || resources[0]; - var result = this._items.map[id]; + var content = this._items.getContent(id); + var error = this._items.getError(id); if (completeCallback) { callInNextTick(function () { if (singleRes) { - completeCallback.call(self, result.error, result.content); + completeCallback.call(self, error, content); } else { completeCallback.call(self, null, self._items); @@ -239,7 +240,6 @@ JS.mixin(cc.loader, { _resources: resources, _getResUuid: function (url) { - url = cc.url.normalize(url); var uuid = resources.getUuid(url); if ( !uuid ) { var extname = cc.path.extname(url); @@ -260,15 +260,15 @@ JS.mixin(cc.loader, { * * @method loadRes * @param {String} url - Url of the target resource. - * The url is relative to the "resources" folder, extensions must be omitted. + * The url is relative to the "resources" folder, extensions must be omitted. * @param {Function} completeCallback - Callback invoked when the resource loaded. * @param {Error} completeCallback.error - The error info or null if loaded successfully. * @param {Object} completeCallback.resource - The loaded resource if it can be found otherwise returns null. * * @example * - * // load the sprite frame (project/assets/resources/imgs/cocos.png/cocos) from resources folder with no extension - * cc.loader.loadRes('imgs/cocos/cocos', function (err, spriteFrame) { + * // load the sprite frame (project/assets/resources/imgs/cocos.png/cocos) from resources folder + * cc.loader.loadRes('imgs/cocos.png/cocos', function (err, spriteFrame) { * if (err) { * cc.error(err.message || err); * return; @@ -295,6 +295,70 @@ JS.mixin(cc.loader, { } }, + /** + * Load all assets in a folder inside the "assets/resources" folder of your project.
+ *
+ * Note: All asset urls in Creator use forward slashes, urls using backslashes will not work. + * + * @method loadResAll + * @param {String} url - Url of the target folder. + * The url is relative to the "resources" folder. + * @param {Function} completeCallback - A callback which is called when all assets have been loaded, or an error occurs. + * @param {Error} completeCallback.error - If one of the asset failed, the complete callback is immediately called with the error. If all assets are loaded successfully, error will be null. + * @param {Object[]} completeCallback.assets - An array of all loaded assets. If nothing to load, assets will be an empty array. If error occurs, assets will be null. + * + * @example + * + * // load the sprite frame (project/assets/resources/imgs/cocos.png/cocos) from resources folder + * cc.loader.loadResAll('imgs/cocos.png', function (err, assets) { + * if (err) { + * cc.error(err); + * return; + * } + * var texture = assets[0]; + * var spriteFrame = assets[1]; + * }); + */ + loadResAll: function (url, completeCallback) { + var uuids = resources.getUuidArray(url); + var remain = uuids.length; + if (remain > 0) { + var results = []; + var aborted = false; + function loaded (err, res) { + if (aborted) { + return; + } + if (err) { + aborted = true; + completeCallback(err, null); + return; + } + results.push(res); + --remain; + if (remain === 0) { + completeCallback(null, results); + } + } + for (var i = 0, len = remain; i < len; ++i) { + var uuid = uuids[i]; + this.load( + { + id: uuid, + type: 'uuid', + uuid: uuid + }, + loaded + ); + } + } + else { + callInNextTick(function () { + completeCallback.call(null, null, []); + }); + } + }, + /** * Get resource data by id.
* When you load resources with {{#crossLink "loader/load:method"}}{{/crossLink}} or {{#crossLink "loader/loadRes:method"}}{{/crossLink}}, @@ -317,6 +381,23 @@ JS.mixin(cc.loader, { return this._items.totalCount; }, + /** + * Returns an item in pipeline. + * @method getItem + * @return {LoadingItem} + */ + getItem: function (url) { + var item = this._items.map[url]; + + if (!item) + return item; + + if (item.alias) + item = this._items.map[item.alias]; + + return item; + }, + /** * Release the cache of resource by url. * diff --git a/cocos2d/core/load-pipeline/asset-table.js b/cocos2d/core/load-pipeline/asset-table.js index 1c91c901c4..dae417acef 100644 --- a/cocos2d/core/load-pipeline/asset-table.js +++ b/cocos2d/core/load-pipeline/asset-table.js @@ -23,22 +23,6 @@ THE SOFTWARE. ****************************************************************************/ -var callInNextTick = require('./../platform/utils').callInNextTick; - -function normalizePath (path) { - if (path.charCodeAt(0) === 46 && path.charCodeAt(1) === 47) { - // strip './' - path = path.slice(2); - } - else if (path.charCodeAt(0) === 47) { - // strip '/' - path = path.slice(1); - } - return path; -} - -var GLOB = '**/*'; - /* * !#en AssetTable is used to find asset's uuid by url. * !#zh AssetTable 用于查找资源的 uuid 和 url。 @@ -48,9 +32,7 @@ var GLOB = '**/*'; function AssetTable () { this._pathToUuid = {}; } -AssetTable._hasWildcard = function (path) { - return path.endsWith(GLOB); -}; + cc.js.mixin(AssetTable.prototype, { ///** @@ -67,7 +49,7 @@ cc.js.mixin(AssetTable.prototype, { //}, getUuid: function (path) { - path = normalizePath(path); + path = cc.url.normalize(path); if ( !path ) { return ''; } @@ -75,22 +57,26 @@ cc.js.mixin(AssetTable.prototype, { if (uuid) { return uuid; } - else if (AssetTable._hasWildcard(path)) { - var uuids = []; - var pathNoWildcard = path.slice(0, - GLOB.length); - for (var p in this._pathToUuid) { - if (p.startsWith(pathNoWildcard)) { - var uuid = this._pathToUuid[p]; - uuids.push(uuid); - } - } - return uuids; - } else { return ''; } }, + getUuidArray: function (path) { + path = cc.url.normalize(path); + if ( !path ) { + return []; + } + var uuids = []; + var p2u = this._pathToUuid; + for (var p in p2u) { + if (p.startsWith(path)) { + uuids.push(p2u[p]); + } + } + return uuids; + }, + /** * !#en Returns all asset paths in the table. * !#zh 返回表中的所有资源路径。 @@ -100,81 +86,6 @@ cc.js.mixin(AssetTable.prototype, { getAllPaths: function () { return Object.keys(this._pathToUuid); }, - - //_loadByWildcard: function (path, callback) { - // var results = []; - // var remain = 0; - // var aborted = false; - // function onLoad (err, asset) { - // if (aborted) { - // return; - // } - // if (asset) { - // results.push(asset); - // if (--remain <= 0) { - // callback(null, results); - // } - // } - // else { - // aborted = true; - // callback(err, results); - // callback = null; - // } - // } - // - // var pathNoWildcard = path.slice(0, - GLOB.length); - // for (var p in this._pathToUuid) { - // if (p.startsWith(pathNoWildcard)) { - // ++remain; - // var uuid = this._pathToUuid[p]; - // cc.AssetLibrary.loadAsset(uuid, onLoad); - // } - // } - // return remain > 0; - //}, - - ///** - // * Loads asset with path from the table asynchronously.
- // *
- // * wildcard:
- // * 如果路径以 **/* 作为结尾,则该路径下的所有资源都会被加载,含子文件夹。 - // * 此时 callback 的第二参数将返回数组,如果文件夹下没有资源,数组长度将会是 0。如果加载出错,数组内的元素将不全。 - // * - // * Note: All asset paths in Creator use forward slashes, paths using backslashes will not work. - // * - // * @method load - // * @param {string} path - // * @param {function} [callback] - // * @param {string} callback.param error - null or the error info - // * @param {object} callback.param data - the loaded object or null - // * @param {boolean} [quiet=false] - If true, the callback will not invoked even if asset is not found. - // * @return {boolean} start loading - // */ - //load: function (path, callback, quiet) { - // if ( !path ) { - // if ( !quiet ) { - // callInNextTick(callback, 'Argument must be non-nil', null); - // } - // return false; - // } - // path = normalizePath(path); - // var uuid = this._pathToUuid[path]; - // if (uuid) { - // AssetLibrary.loadAsset(uuid, callback); - // return true; - // } - // else if (AssetTable._hasWildcard(path)) { - // var loading = this._loadByWildcard(path, callback); - // if ( !loading && !quiet ) { - // callInNextTick(callback, null, []); - // } - // return loading; - // } - // else if (! quiet) { - // callInNextTick(callback, 'Path not exists', null); - // return false; - // } - //}, /** * !#en TODO diff --git a/cocos2d/core/load-pipeline/audio-downloader.js b/cocos2d/core/load-pipeline/audio-downloader.js index 9098f1222a..2022be6aed 100644 --- a/cocos2d/core/load-pipeline/audio-downloader.js +++ b/cocos2d/core/load-pipeline/audio-downloader.js @@ -43,92 +43,80 @@ function loadAudioFromExtList (url, typeList, audio, cb){ return cb({status: 520, errorMessage: ERRSTR}, null); } - url = Path.changeExtname(url, typeList.splice(0, 1)); - - if (__audioSupport.WEB_AUDIO && cc.Audio.useWebAudio) {//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.src); - }, function() { - //error - loadAudioFromExtList(url, typeList, audio, cb); - }); - }; - - request.onerror = function () { - cb({status: 520, errorMessage: ERRSTR}, null); - }; - - request.send(); - } else {//DOM - var element = new Audio(); - audio.setElement(element); - 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, null); - } - }, 8000); - - var success = function () { - if (!cbCheck) { - //element.pause(); - try { - element.currentTime = 0; - element.volume = 1; - } catch (e) {} - audio.setElement(element); - element.removeEventListener('canplaythrough', success, false); - element.removeEventListener('error', failure, false); - element.removeEventListener('emptied', emptied, false); - !termination && cb(null, url); - cbCheck = true; - clearTimeout(timer); - } - }; - - var failure = function(){ - if (!cbCheck) return; - 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, url); - }; - - element.addEventListener('canplaythrough', success, false); - element.addEventListener('error', failure, false); - if(__audioSupport.USE_EMPTIED_EVENT) - element.addEventListener('emptied', emptied, false); - - document.body.appendChild(element); - element.src = url; + if (__audioSupport.WEB_AUDIO && cc.Audio.useWebAudio) { + loadWebAudio(url, typeList, audio, cb); + } else { + loadDomAudio(url, typeList, audio, cb); } } +function loadDomAudio (url, typeList, audio, cb) { + + var num = __audioSupport.ONE_SOURCE ? 1 : typeList.length; + + // 加载统一使用dom + var dom = document.createElement('audio'); + for (var i=0; i= 0) { continue; } - if (funcName === 'constructor' && CC_EDITOR) { + if (CC_EDITOR && funcName === 'constructor') { cc.error('Can not define a member called "constructor" in the class "%s", please use "ctor" instead.', name); continue; } diff --git a/cocos2d/core/platform/CCInputManager.js b/cocos2d/core/platform/CCInputManager.js index fec46c8c5c..b8499550e2 100644 --- a/cocos2d/core/platform/CCInputManager.js +++ b/cocos2d/core/platform/CCInputManager.js @@ -203,7 +203,7 @@ var inputManager = /** @lends cc.inputManager# */{ var docElem = document.documentElement; var win = window; var box = null; - if (cc.js.isFunction(element.getBoundingClientRect)) { + if (typeof element.getBoundingClientRect === 'function') { box = element.getBoundingClientRect(); } else { if (element instanceof HTMLCanvasElement) { diff --git a/cocos2d/core/platform/CCObject.js b/cocos2d/core/platform/CCObject.js index 4d8918ad1f..4c55d293a4 100644 --- a/cocos2d/core/platform/CCObject.js +++ b/cocos2d/core/platform/CCObject.js @@ -15,20 +15,21 @@ var HideInGame = 1 << 9; var HideInEditor = 1 << 10; var IsOnEnableCalled = 1 << 12; -var IsOnLoadCalled = 1 << 13; -var IsOnLoadStarted = 1 << 14; -var IsOnStartCalled = 1 << 15; +var IsEditorOnEnableCalled = 1 << 13; +var IsOnLoadCalled = 1 << 14; +var IsOnLoadStarted = 1 << 15; +var IsOnStartCalled = 1 << 16; -var IsRotationLocked = 1 << 16; -var IsScaleLocked = 1 << 17; -var IsAnchorLocked = 1 << 18; -var IsSizeLocked = 1 << 19; -var IsPositionLocked = 1 << 20; +var IsRotationLocked = 1 << 17; +var IsScaleLocked = 1 << 18; +var IsAnchorLocked = 1 << 19; +var IsSizeLocked = 1 << 20; +var IsPositionLocked = 1 << 21; var Hide = HideInGame | HideInEditor; // should not clone or serialize these flags var PersistentMask = ~(ToDestroy | Dirty | Destroying | DontDestroy | Activating | - IsOnEnableCalled | IsOnLoadStarted | IsOnLoadCalled | IsOnStartCalled + IsOnEnableCalled | IsEditorOnEnableCalled | IsOnLoadStarted | IsOnLoadCalled | IsOnStartCalled /*RegisteredInEditor*/); /** @@ -136,6 +137,7 @@ CCObject.Flags = { IsOnLoadStarted: IsOnLoadStarted, IsOnEnableCalled: IsOnEnableCalled, IsOnStartCalled: IsOnStartCalled, + IsEditorOnEnableCalled: IsEditorOnEnableCalled, IsPositionLocked: IsPositionLocked, IsRotationLocked: IsRotationLocked, @@ -262,7 +264,7 @@ prototype.destroy = function () { this._objFlags |= ToDestroy; objectsToDestroy.push(this); - if (deferredDestroyTimer === null && cc.engine && ! cc.engine._isUpdating && CC_EDITOR) { + if (CC_EDITOR && deferredDestroyTimer === null && cc.engine && ! cc.engine._isUpdating) { // auto destroy immediate in edit mode deferredDestroyTimer = setImmediate(deferredDestroy); } diff --git a/cocos2d/core/platform/CCSys.js b/cocos2d/core/platform/CCSys.js index 863ad3926f..7298730bf8 100644 --- a/cocos2d/core/platform/CCSys.js +++ b/cocos2d/core/platform/CCSys.js @@ -747,72 +747,16 @@ else { // check Web Audio's context var supportWebAudio = !!(window.AudioContext || window.webkitAudioContext || window.mozAudioContext); - var supportTable = { - "common" : {MULTI_CHANNEL: true, WEB_AUDIO: supportWebAudio, AUTOPLAY: true } - }; + __audioSupport = { ONLY_ONE: true, WEB_AUDIO: supportWebAudio, DELAY_CREATE_CTX: false }; - 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: true , WEB_AUDIO: true , 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: true , WEB_AUDIO: true , 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: true , WEB_AUDIO: true , 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']; - } + if (sys.browserType === sys.BROWSER_TYPE_FIREFOX) { + __audioSupport.DELAY_CREATE_CTX = true; + __audioSupport.USE_LOADER_EVENT = 'canplay'; } - /////////////////////////// - // 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 (sys.os === sys.OS_ANDROID) { + if (sys.browserType === sys.BROWSER_TYPE_UC) { + __audioSupport.ONE_SOURCE = true; } } diff --git a/cocos2d/core/platform/CCView.js b/cocos2d/core/platform/CCView.js index 007fbc84dd..01c07919e9 100644 --- a/cocos2d/core/platform/CCView.js +++ b/cocos2d/core/platform/CCView.js @@ -273,7 +273,7 @@ var View = cc._Class.extend({ * @param {Function|Null} callback - The callback function */ setResizeCallback: function (callback) { - if (cc.js.isFunction(callback) || callback == null) { + if (typeof callback === 'function' || callback == null) { this._resizeCallback = callback; } }, diff --git a/cocos2d/core/platform/instantiate.js b/cocos2d/core/platform/instantiate.js index 350721bd55..8a42d4c68e 100644 --- a/cocos2d/core/platform/instantiate.js +++ b/cocos2d/core/platform/instantiate.js @@ -143,7 +143,7 @@ var enumerateObject = function (obj, parent) { } } } - if ((clone instanceof cc._BaseNode || clone instanceof cc.Component) && CC_EDITOR) { + if (CC_EDITOR && (clone instanceof cc._BaseNode || clone instanceof cc.Component)) { clone._id = ''; } } diff --git a/cocos2d/core/platform/js.js b/cocos2d/core/platform/js.js index c8148ad220..2154a91944 100644 --- a/cocos2d/core/platform/js.js +++ b/cocos2d/core/platform/js.js @@ -51,65 +51,28 @@ function _copyprop(name, source, target) { */ var js = { - /** - * Check the obj whether is function or not - * @method isFunction - * @param {*} obj - * @returns {Boolean} - */ - isFunction: function(obj) { - return typeof obj === 'function'; - }, - /** * Check the obj whether is number or not + * If a number is created by using 'new Number(10086)', the typeof it will be "object"... + * Then you can use this function if you care about this case. * @method isNumber * @param {*} obj * @returns {Boolean} */ isNumber: function(obj) { - return typeof obj === 'number' || Object.prototype.toString.call(obj) === '[object Number]'; + return typeof obj === 'number' || obj instanceof Number; }, /** - * Check the obj whether is string or not + * Check the obj whether is string or not. + * If a string is created by using 'new String("blabla")', the typeof it will be "object"... + * Then you can use this function if you care about this case. * @method isString * @param {*} obj * @returns {Boolean} */ isString: function(obj) { - return typeof obj === 'string' || Object.prototype.toString.call(obj) === '[object String]'; - }, - - /** - * Check the obj whether is array or not - * @method isArray - * @param {*} obj - * @returns {Boolean} - */ - isArray: function(obj) { - return Array.isArray(obj) || - (typeof obj === 'object' && Object.prototype.toString.call(obj) === '[object Array]'); - }, - - /** - * Check the obj whether is undefined or not - * @method isUndefined - * @param {*} obj - * @returns {Boolean} - */ - isUndefined: function(obj) { - return typeof obj === 'undefined'; - }, - - /** - * Check the obj whether is object or not - * @method isObject - * @param {*} obj - * @returns {Boolean} - */ - isObject: function(obj) { - return typeof obj === "object" && Object.prototype.toString.call(obj) === '[object Object]'; + return typeof obj === 'string' || obj instanceof String; }, /** diff --git a/cocos2d/core/platform/preprocess-attrs.js b/cocos2d/core/platform/preprocess-attrs.js index 36c6cdc1e7..83e5b04dec 100644 --- a/cocos2d/core/platform/preprocess-attrs.js +++ b/cocos2d/core/platform/preprocess-attrs.js @@ -135,7 +135,7 @@ function parseType (val, type, className, propName) { } function postCheckType (val, type, className, propName) { - if (typeof type === 'function' && CC_EDITOR) { + if (CC_EDITOR && typeof type === 'function') { if (cc.Class._isCCClass(type) && val.serializable !== false && !cc.js._getClassId(type, false)) { cc.warn('Can not serialize "%s.%s" because the specified type is anonymous, please provide a class name or set the "serializable" attribute of "%s.%s" to "false".', className, propName, className, propName); } @@ -206,7 +206,7 @@ module.exports = function (properties, className, cls) { className, propName); } } - if (!val.override && cls.__props__.indexOf(propName) !== -1 && CC_DEV) { + if (CC_DEV && !val.override && cls.__props__.indexOf(propName) !== -1) { // check override var baseClass = cc.js.getClassName(getBaseClassWherePropertyDefined(propName, cls)); cc.warn('"%s.%s" hides inherited property "%s.%s". To make the current property override that implementation, add the `override: true` attribute please.', className, propName, baseClass, propName); diff --git a/cocos2d/core/platform/url.js b/cocos2d/core/platform/url.js index b23432da8f..794a23d945 100644 --- a/cocos2d/core/platform/url.js +++ b/cocos2d/core/platform/url.js @@ -49,10 +49,12 @@ cc.url = { _builtinRawAssets: '', normalize: function (url) { - if (url[0] === '.' && url[1] === '/') { + if (url.charCodeAt(0) === 46 && url.charCodeAt(1) === 47) { + // strip './' url = url.slice(2); } - else if (url[0] === '/') { + else if (url.charCodeAt(0) === 47) { + // strip '/' url = url.slice(1); } return url; @@ -67,7 +69,7 @@ cc.url = { * @example {@link utils/api/engine/docs/cocos2d/core/platform/url/raw.js} */ raw: function (url) { - if (!this._rawAssets && CC_EDITOR) { + if (CC_EDITOR && !this._rawAssets) { cc.error('Failed to init asset\'s raw path.'); return ''; } diff --git a/cocos2d/core/renderer/RendererCanvas.js b/cocos2d/core/renderer/RendererCanvas.js index d2ab35faf8..55d2b2af56 100644 --- a/cocos2d/core/renderer/RendererCanvas.js +++ b/cocos2d/core/renderer/RendererCanvas.js @@ -65,8 +65,8 @@ cc.rendererCanvas = { _renderingToCacheCanvas: function (ctx, instanceID, scaleX, scaleY) { if (!ctx) cc.log("The context of RenderTexture is invalid."); - scaleX = cc.js.isUndefined(scaleX) ? 1 : scaleX; - scaleY = cc.js.isUndefined(scaleY) ? 1 : scaleY; + scaleX = (typeof scaleX === 'undefined') ? 1 : scaleX; + scaleY = (typeof scaleY === 'undefined') ? 1 : scaleY; instanceID = instanceID || this._currentID; var locCmds = this._cacheToCanvasCmds[instanceID], i, len; ctx.computeRealOffsetY(); diff --git a/cocos2d/core/sprites/CCSGSprite.js b/cocos2d/core/sprites/CCSGSprite.js index 02db734c08..979acba6e6 100644 --- a/cocos2d/core/sprites/CCSGSprite.js +++ b/cocos2d/core/sprites/CCSGSprite.js @@ -996,6 +996,6 @@ _ccsg.Sprite.INDEX_NOT_INITIALIZED = -1; cc.js.addon(_ccsg.Sprite.prototype, EventTarget.prototype); -cc.assert(cc.js.isFunction(cc._tmp.PrototypeSprite), cc._LogInfos.MissingFile, "SpritesPropertyDefine.js"); +cc.assert(typeof cc._tmp.PrototypeSprite === 'function', cc._LogInfos.MissingFile, "SpritesPropertyDefine.js"); cc._tmp.PrototypeSprite(); delete cc._tmp.PrototypeSprite; \ No newline at end of file diff --git a/cocos2d/core/sprites/CCScale9Sprite.js b/cocos2d/core/sprites/CCScale9Sprite.js index 1fd624cb4f..255ccaa790 100644 --- a/cocos2d/core/sprites/CCScale9Sprite.js +++ b/cocos2d/core/sprites/CCScale9Sprite.js @@ -874,6 +874,8 @@ cc.Scale9Sprite = _ccsg.Node.extend({ //normalized filled start and range _fillStart: 0, _fillRange: Math.PI * 2, + _distortionOffset: null, + _distortionTiling: null, ctor: function (textureOrSpriteFrame) { _ccsg.Node.prototype.ctor.call(this); @@ -1249,7 +1251,7 @@ cc.defineGetterSetter(_p, "insetBottom", _p.getInsetBottom, _p.setInsetBottom); _p = null; -cc.Scale9Sprite.state = {NORMAL: 0, GRAY: 1}; +cc.Scale9Sprite.state = {NORMAL: 0, GRAY: 1, DISTORTION: 2}; /** * Enum for sprite type diff --git a/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js index d68f6417cc..dea7127439 100644 --- a/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js +++ b/cocos2d/core/sprites/CCScale9SpriteWebGLRenderCmd.js @@ -64,7 +64,16 @@ if (_ccsg.Node.WebGLRenderCmd) { { this._shaderProgram.use(); this._shaderProgram._setUniformForMVPMatrixWithMat4(this._stackMatrix); - + if(this._shaderProgram === cc.Scale9Sprite.WebGLRenderCmd._distortionProgram && this._node._distortionOffset) { + this._shaderProgram.setUniformLocationWith2f( + cc.Scale9Sprite.WebGLRenderCmd._distortionOffset, + this._node._distortionOffset.x, this._node._distortionOffset.y + ); + this._shaderProgram.setUniformLocationWith2f( + cc.Scale9Sprite.WebGLRenderCmd._distortionTiling, + this._node._distortionTiling.x, this._node._distortionTiling.y + ); + } ccgl.blendFunc(node._blendFunc.src, node._blendFunc.dst); //optimize performance for javascript ccgl.bindTexture2DN(0, locTexture); // = cc.gl.bindTexture2D(locTexture); @@ -147,6 +156,8 @@ if (_ccsg.Node.WebGLRenderCmd) { node.setShaderProgram(cc.shaderCache.programForKey(cc.macro.SHADER_POSITION_TEXTURECOLOR)); } else if (state === cc.Scale9Sprite.state.GRAY) { node.setShaderProgram(cc.Scale9Sprite.WebGLRenderCmd._getGrayShaderProgram()); + } else if (state === cc.Scale9Sprite.state.DISTORTION) { + node.setShaderProgram(cc.Scale9Sprite.WebGLRenderCmd._getDistortionProgram()); } }; @@ -178,4 +189,55 @@ if (_ccsg.Node.WebGLRenderCmd) { + " gl_FragColor.xyz = vec3(0.2126*c.r + 0.7152*c.g + 0.0722*c.b); \n" +" gl_FragColor.w = c.w ; \n" + "}"; + + cc.Scale9Sprite.WebGLRenderCmd._distortionProgram = null; + cc.Scale9Sprite.WebGLRenderCmd._getDistortionProgram = function(){ + var shader = cc.Scale9Sprite.WebGLRenderCmd._distortionProgram; + if(shader) + return shader; + + shader = new cc.GLProgram(); + shader.initWithVertexShaderByteArray(cc.PresetShaders.POSITION_TEXTURE_COLOR_VERT, distortionSpriteShader.fShader); + shader.addAttribute(cc.macro.ATTRIBUTE_NAME_POSITION, cc.macro.VERTEX_ATTRIB_POSITION); + shader.addAttribute(cc.macro.ATTRIBUTE_NAME_COLOR, cc.macro.VERTEX_ATTRIB_COLOR); + shader.addAttribute(cc.macro.ATTRIBUTE_NAME_TEX_COORD, cc.macro.VERTEX_ATTRIB_TEX_COORDS); + shader.link(); + shader.updateUniforms(); + + cc.Scale9Sprite.WebGLRenderCmd._distortionProgram = shader; + cc.Scale9Sprite.WebGLRenderCmd._distortionOffset = shader.getUniformLocationForName('u_offset'); + cc.Scale9Sprite.WebGLRenderCmd._distortionTiling = shader.getUniformLocationForName('u_offset_tiling'); + return shader; + }; + + var distortionSpriteShader = { + }; + distortionSpriteShader.shaderKey = 'cc.Sprite.Shader.Distortion'; + distortionSpriteShader.fShader = "precision lowp float;\n" + + "varying vec4 v_fragmentColor; \n" + + "varying vec2 v_texCoord; \n" + + "uniform vec2 u_offset; \n" + + "uniform vec2 u_offset_tiling; \n" + + "const float PI = 3.14159265359;\n" + + "void main() \n" + + "{ \n" + + "float halfPI = 0.5 * PI;\n" + + "float maxFactor = sin(halfPI);\n" + + "vec2 uv = v_texCoord;\n" + + "vec2 xy = 2.0 * uv.xy - 1.0;\n" + + "float d = length(xy);\n" + + "if (d < (2.0-maxFactor)) {\n" + + "d = length(xy * maxFactor);\n" + + "float z = sqrt(1.0 - d * d);\n" + + " float r = atan(d, z) / PI;\n" + + "float phi = atan(xy.y, xy.x);\n" + + "uv.x = r * cos(phi) + 0.5;\n" + + "uv.y = r * sin(phi) + 0.5;\n" + + "} else {\n" + + "discard;\n" + + "}\n" + + "uv = uv * u_offset_tiling + u_offset;\n" + + "uv = fract(uv); \n" + + "gl_FragColor = v_fragmentColor * texture2D(CC_Texture0, uv);\n" + + "}"; } diff --git a/cocos2d/core/utils/base-node.js b/cocos2d/core/utils/base-node.js index 65ac17d650..6202c953b9 100644 --- a/cocos2d/core/utils/base-node.js +++ b/cocos2d/core/utils/base-node.js @@ -45,8 +45,6 @@ var ROTATION_CHANGED = 'rotation-changed'; var SCALE_CHANGED = 'scale-changed'; var SIZE_CHANGED = 'size-changed'; var ANCHOR_CHANGED = 'anchor-changed'; -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'; @@ -392,7 +390,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ set: function (value) { var localPosition = this._position; if (value !== localPosition.x) { - if (isFinite(value) || !CC_EDITOR) { + if (!CC_EDITOR || isFinite(value)) { var oldValue = localPosition.x; localPosition.x = value; @@ -425,7 +423,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ set: function (value) { var localPosition = this._position; if (value !== localPosition.y) { - if (isFinite(value) || !CC_EDITOR) { + if (!CC_EDITOR || isFinite(value)) { var oldValue = localPosition.y; localPosition.y = value; @@ -489,10 +487,14 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ return this._anchorPoint.x; }, set: function (value) { - if (this._anchorPoint.x !== value) { - var old = cc.v2(this._anchorPoint); - this._anchorPoint.x = value; - this._onAnchorChanged(); + var anchorPoint = this._anchorPoint; + if (anchorPoint.x !== value) { + var old = new cc.Vec2(anchorPoint); + anchorPoint.x = value; + var sizeProvider = this._sizeProvider; + if (sizeProvider instanceof _ccsg.Node) { + sizeProvider.setAnchorPoint(anchorPoint); + } this.emit(ANCHOR_CHANGED, old); } }, @@ -511,10 +513,14 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ return this._anchorPoint.y; }, set: function (value) { - if (this._anchorPoint.y !== value) { - var old = cc.v2(this._anchorPoint); - this._anchorPoint.y = value; - this._onAnchorChanged(); + var anchorPoint = this._anchorPoint; + if (anchorPoint.y !== value) { + var old = new cc.Vec2(anchorPoint); + anchorPoint.y = value; + var sizeProvider = this._sizeProvider; + if (sizeProvider instanceof _ccsg.Node) { + sizeProvider.setAnchorPoint(anchorPoint); + } this.emit(ANCHOR_CHANGED, old); } }, @@ -541,8 +547,9 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ }, set: function (value) { if (value !== this._contentSize.width) { - if (this._sizeProvider) { - this._sizeProvider.setContentSize(value, this._sizeProvider._getHeight()); + var sizeProvider = this._sizeProvider; + if (sizeProvider) { + sizeProvider.setContentSize(value, sizeProvider._getHeight()); } var clone = cc.size(this._contentSize); this._contentSize.width = value; @@ -572,8 +579,9 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ }, set: function (value) { if (value !== this._contentSize.height) { - if (this._sizeProvider) { - this._sizeProvider.setContentSize(this._sizeProvider._getWidth(), value); + var sizeProvider = this._sizeProvider; + if (sizeProvider) { + sizeProvider.setContentSize(sizeProvider._getWidth(), value); } var clone = cc.size(this._contentSize); this._contentSize.height = value; @@ -600,7 +608,10 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ if (this.__ignoreAnchor !== value) { this.__ignoreAnchor = value; this._sgNode.ignoreAnchor = value; - this._onAnchorChanged(); + var sizeProvider = this._sizeProvider; + if (sizeProvider instanceof _ccsg.Node && sizeProvider !== this._sgNode) { + sizeProvider.ignoreAnchor = value; + } this.emit(ANCHOR_CHANGED, this._anchorPoint); } }, @@ -638,11 +649,15 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ }, set: function (value) { if (this._opacity !== value) { - var old = this._opacity; this._opacity = value; - this._sgNode.opacity = value; - this._onColorChanged(); - this.emit(OPACITY_CHANGED, old); + this._sgNode.setOpacity(value); + var sizeProvider = this._sizeProvider; + if ( !this._cascadeOpacityEnabled && + sizeProvider instanceof _ccsg.Node && + this._sgNode !== sizeProvider + ) { + sizeProvider.setOpacity(value); + } } }, range: [0, 255] @@ -664,7 +679,12 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ if (this._cascadeOpacityEnabled !== value) { this._cascadeOpacityEnabled = value; this._sgNode.cascadeOpacity = value; - this._onCascadeChanged(); + + var opacity = value ? 255 : this._opacity; + var sizeProvider = this._sizeProvider; + if (sizeProvider instanceof _ccsg.Node) { + sizeProvider.setOpacity(opacity); + } } }, }, @@ -690,10 +710,11 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ color.g = value.g; color.b = value.b; if (CC_DEV && value.a !== 255) { - cc.warn('Should not set alpha via "color", use "opacity" please.'); + cc.warn('Should not set alpha via "color", set "opacity" please.'); + } + if (this._sizeProvider instanceof _ccsg.Node) { + this._sizeProvider.setColor(value); } - this._onColorChanged(); - this.emit(COLOR_CHANGED, old); } }, }, @@ -706,6 +727,13 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ enumerable: false }); + /** + * Current scene graph node for this node. + * + * @property _sgNode + * @type {_ccsg.Node} + * @private + */ var sgNode = this._sgNode = new _ccsg.Node(); if (cc.sys.isNative) { sgNode.retain(); @@ -725,13 +753,13 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ this._dirtyFlags = DirtyFlags.ALL; /** - * Current active scene graph node which provides content size. + * Current active size provider for this node. + * Size provider can equals to this._sgNode. * * @property _sizeProvider - * @type {Object} + * @type {_ccsg.Node} * @private */ - // _ccsg.Node this._sizeProvider = null; this.__ignoreAnchor = false; @@ -745,15 +773,6 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ // called when the node's parent changed _onHierarchyChanged: null, - // called when the node's color or opacity changed - _onColorChanged: null, - // called when the node's anchor changed - _onAnchorChanged: null, - // called when the node's cascadeOpacity or cascadeColor changed - _onCascadeChanged: null, - // called when the node's isOpacityModifyRGB changed - _onOpacityModifyRGBChanged: null, - /* * Initializes the instance of cc.Node @@ -907,7 +926,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ */ setPosition: function (newPosOrxValue, yValue) { var xValue; - if (yValue === undefined) { + if (typeof yValue === 'undefined') { xValue = newPosOrxValue.x; yValue = newPosOrxValue.y; } @@ -923,20 +942,20 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ var oldPosition = new cc.Vec2(locPosition); - if (isFinite(xValue) || !CC_EDITOR) { + if (!CC_EDITOR || isFinite(xValue)) { locPosition.x = xValue; } else { return cc.error(ERR_INVALID_NUMBER, 'x of new position'); } - if (isFinite(yValue) || !CC_EDITOR) { + if (!CC_EDITOR || isFinite(yValue)) { locPosition.y = yValue; } else { return cc.error(ERR_INVALID_NUMBER, 'y of new position'); } - this._sgNode.setPosition(locPosition); + this._sgNode.setPosition(xValue, yValue); if (this.emit) { this.emit(POSITION_CHANGED, oldPosition); @@ -1005,7 +1024,10 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ locAnchorPoint.x = point; locAnchorPoint.y = y; } - this._onAnchorChanged(); + var sizeProvider = this._sizeProvider; + if (sizeProvider instanceof _ccsg.Node) { + sizeProvider.setAnchorPoint(locAnchorPoint); + } this.emit(ANCHOR_CHANGED, old); }, @@ -1208,7 +1230,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ addChild: function (child, localZOrder, tag) { localZOrder = localZOrder === undefined ? child._localZOrder : localZOrder; var name, setTag = false; - if(cc.js.isUndefined(tag)){ + if(typeof tag === 'undefined'){ tag = undefined; name = child._name; } else if(cc.js.isString(tag)){ @@ -1729,7 +1751,10 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ if (this._opacityModifyRGB !== opacityValue) { this._opacityModifyRGB = opacityValue; this._sgNode.setOpacityModifyRGB(opacityValue); - this._onOpacityModifyRGBChanged(); + var sizeProvider = this._sizeProvider; + if (sizeProvider instanceof _ccsg.Node && sizeProvider !== this._sgNode) { + sizeProvider.setOpacityModifyRGB(opacityValue); + } } }, @@ -2094,32 +2119,6 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{ * node.setLocalZOrder(1); */ -/* - * !#en - * Returns whether the anchor point will be ignored when you position this node.
- * When anchor point ignored, position will be calculated based on the origin point (0, 0) in parent's coordinates. - * !#zh - * 返回这个节点位置时,是否会忽略这个锚点。
- * 当锚点被忽略时,在父坐标系中的原点(0,0)计算位置。 - * @method isIgnoreAnchorPointForPosition - * @return {Boolean} true if the anchor point will be ignored when you position this node. - */ - -/* - * !#en - * Sets whether the anchor point will be ignored when you position this node.
- * When anchor point ignored, position will be calculated based on the origin point (0, 0) in parent's coordinates.
- * This is an internal method, only used by CCLayer and CCScene. Don't call it outside framework.
- * The default value is false, while in CCLayer and CCScene are true - * !#zh - * 设置抹点为(0,0)当你摆放这个节点的时候。 - * 这是一个内部方法,仅仅被 Layer 和 Scene 使用。不要在框架外调用。默认值是 false,但是在 Layer 和 Scene 中是 true. - * @method ignoreAnchorPointForPosition - * @param {Boolean} newValue - true if anchor point will be ignored when you position this node - * @example - * node.ignoreAnchorPointForPosition(true); - */ - /** * !#en Returns whether node's opacity value affect its child nodes. * !#zh 返回节点的不透明度值是否影响其子节点。 diff --git a/cocos2d/core/value-types/CCAffineTransform.js b/cocos2d/core/value-types/CCAffineTransform.js index 7ba42d4677..0dcd42023b 100644 --- a/cocos2d/core/value-types/CCAffineTransform.js +++ b/cocos2d/core/value-types/CCAffineTransform.js @@ -196,6 +196,40 @@ cc._rectApplyAffineTransformIn = function(rect, anAffineTransform){ return rect; }; +/** + * !#en Apply the affine transformation on a rect, and truns to an Oriented Bounding Box. + * !#zh 应用 Rect 到仿射变换矩阵上, 并转换为有向包围盒 + * @method obbApplyAffineTransform + * @param {Rect} rect + * @param {AffineTransform} anAffineTransform + * @param {Vec2} out_bl + * @param {Vec2} out_tl + * @param {Vec2} out_tr + * @param {Vec2} out_br + */ +cc.obbApplyAffineTransform = function (rect, anAffineTransform, out_bl, out_tl, out_tr, out_br) { + var x = rect.x; + var y = rect.y; + var width = rect.width; + var height = rect.height; + + var tx = anAffineTransform.a * x + anAffineTransform.c * y + anAffineTransform.tx; + var ty = anAffineTransform.b * x + anAffineTransform.d * y + anAffineTransform.ty; + var xa = anAffineTransform.a * width; + var xb = anAffineTransform.b * width; + var yc = anAffineTransform.c * height; + var yd = anAffineTransform.d * height; + + out_tl.x = tx; + out_tl.y = ty; + out_tr.x = xa + tx; + out_tr.y = xb + ty; + out_bl.x = yc + tx; + out_bl.y = yd + ty; + out_br.x = xa + yc + tx; + out_br.y = xb + yd + ty; +}; + /** * !#en Create a new affine transformation with a base transformation matrix and a translation based on it. * !#zh 基于一个基础矩阵加上一个平移操作来创建一个新的矩阵。 diff --git a/cocos2d/core/value-types/CCColor.js b/cocos2d/core/value-types/CCColor.js index 3bbdda10f0..a691195f6b 100644 --- a/cocos2d/core/value-types/CCColor.js +++ b/cocos2d/core/value-types/CCColor.js @@ -586,11 +586,11 @@ cc.Color = Color; * @example {@link utils/api/engine/docs/cocos2d/core/value-types/CCColor/color.js} */ cc.color = function color (r, g, b, a) { - if (JS.isString(r)) { + if (typeof r === 'string') { var result = new cc.Color(); return result.fromHEX(r); } - if (cc.js.isObject(r)) { + if (typeof r === 'object') { return new cc.Color(r.r, r.g, r.b, r.a); } return new cc.Color(r, g, b, a); diff --git a/cocos2d/deprecated.js b/cocos2d/deprecated.js index 114d9788a8..bb2ad1d89b 100644 --- a/cocos2d/deprecated.js +++ b/cocos2d/deprecated.js @@ -47,17 +47,17 @@ if (CC_DEV) { return document.createElement; }); - /** - * Check the obj whether is function or not - * @name cc.isFunction - * @memberof cc - * @deprecated - * @param {*} obj - * @returns {boolean} - */ js.get(cc, "isFunction", function () { - cc.warn(INFO, 'cc.isFunction', 'cc.js.isFunction'); - return js.isFunction; + cc.warn(INFO, 'cc.isFunction', '"typeof obj === \'function\'"'); + return function(obj) { + return typeof obj === 'function'; + }; + }); + js.get(cc.js, "isFunction", function () { + cc.warn(INFO, 'cc.js.isFunction', '"typeof obj === \'function\'"'); + return function(obj) { + return typeof obj === 'function'; + }; }); /** @@ -86,43 +86,44 @@ if (CC_DEV) { return js.isString; }); - /** - * Check the obj whether is array or not - * @name cc.isArray - * @memberof cc - * @deprecated - * @param {*} obj - * @returns {boolean} - */ js.get(cc, "isArray", function () { cc.warn(INFO, 'cc.isArray', 'cc.js.isArray'); - return js.isArray; + return function(obj) { + return Array.isArray(obj); + }; + }); + js.get(cc.js, "isArray", function () { + cc.warn(INFO, 'cc.js.isArray', '"Array.isArray(obj)"'); + return function(obj) { + return Array.isArray(obj); + }; }); - /** - * Check the obj whether is undefined or not - * @name cc.isUndefined - * @memberof cc - * @deprecated - * @param {*} obj - * @returns {boolean} - */ js.get(cc, "isUndefined", function () { - cc.warn(INFO, 'cc.isUndefined', 'cc.js.isUndefined'); - return js.isUndefined; + cc.warn(INFO, 'cc.isUndefined', '"typeof obj === \'undefined\'"'); + return function(obj) { + return typeof obj === 'undefined'; + }; + }); + js.get(cc.js, "isUndefined", function () { + cc.warn(INFO, 'cc.js.isUndefined', '"typeof obj === \'undefined\'"'); + return function(obj) { + return typeof obj === 'undefined'; + }; }); - /** - * Check the obj whether is object or not - * @name cc.isObject - * @memberof cc - * @deprecated - * @param {*} obj - * @returns {boolean} - */ js.get(cc, "isObject", function () { - cc.warn(INFO, 'cc.isObject', 'cc.js.isObject'); - return js.isObject; + cc.warn(INFO, 'cc.isObject', '"typeof obj === \'object\'"'); + return function(obj) { + return typeof obj === 'object'; + }; + }); + + js.get(cc.js, "isObject", function () { + cc.warn(INFO, 'cc.js.isObject', '"typeof obj === \'object\'"'); + return function(obj) { + return typeof obj === "object"; + }; }); /** diff --git a/cocos2d/menus/CCMenuItem.js b/cocos2d/menus/CCMenuItem.js index ebbee30753..c6a3d204cf 100644 --- a/cocos2d/menus/CCMenuItem.js +++ b/cocos2d/menus/CCMenuItem.js @@ -172,7 +172,7 @@ cc.MenuItem = _ccsg.Node.extend(/** @lends cc.MenuItem# */{ return; if (locTarget && cc.js.isString(locCallback)) { locTarget[locCallback](this); - } else if (locTarget && cc.js.isFunction(locCallback)) { + } else if (locTarget && typeof locCallback === 'function') { locCallback.call(locTarget, this); } else locCallback(this); @@ -701,10 +701,10 @@ cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{ disabledImage = three; callback = four; target = five; - } else if (four !== undefined && cc.js.isFunction(four)) { + } else if (four !== undefined && typeof four === 'function') { disabledImage = three; callback = four; - } else if (four !== undefined && cc.js.isFunction(three)) { + } else if (four !== undefined && typeof three === 'function') { target = four; callback = three; disabledImage = null; @@ -1219,10 +1219,10 @@ cc.MenuItemToggle = cc.MenuItem.extend(/** @lends cc.MenuItemToggle# */{ initWithItems: function (args) { var l = args.length; // passing callback. - if (cc.js.isFunction(args[args.length - 2])) { + if (typeof args[args.length - 2] === 'function') { this.initWithCallback(args[args.length - 2], args[args.length - 1]); l = l - 2; - } else if (cc.js.isFunction(args[args.length - 1])) { + } else if (typeof args[args.length - 1] === 'function') { this.initWithCallback(args[args.length - 1], null); l = l - 1; } else { diff --git a/cocos2d/particle/CCSGParticleSystem.js b/cocos2d/particle/CCSGParticleSystem.js index e7a401dda7..e9e33eb332 100644 --- a/cocos2d/particle/CCSGParticleSystem.js +++ b/cocos2d/particle/CCSGParticleSystem.js @@ -346,7 +346,7 @@ _ccsg.ParticleSystem = _ccsg.Node.extend({ this.initWithTotalParticles(ton); } else if (cc.js.isString(plistFile)) { this.initWithFile(plistFile); - } else if (cc.js.isObject(plistFile)) { + } else if (typeof plistFile === 'object') { this.initWithDictionary(plistFile, ""); } }, diff --git a/cocos2d/physics/CCPhysicsSprite.js b/cocos2d/physics/CCPhysicsSprite.js index bef8ef35ab..8b2d7c9ca1 100644 --- a/cocos2d/physics/CCPhysicsSprite.js +++ b/cocos2d/physics/CCPhysicsSprite.js @@ -81,7 +81,7 @@ //init with filename and rect this.init(fileName, rect); } - }else if (cc.js.isObject(fileName)) { + }else if (typeof fileName === 'object') { if (fileName instanceof cc.Texture2D) { //init with texture and rect this.initWithTexture(fileName, rect); @@ -252,7 +252,7 @@ //init with filename and rect this.init(fileName, rect); } - }else if (cc.js.isObject(fileName)) { + }else if (typeof fileName === 'object') { if (fileName instanceof cc.Texture2D) { //init with texture and rect this.initWithTexture(fileName, rect); diff --git a/cocos2d/text-input/CCTextFieldTTF.js b/cocos2d/text-input/CCTextFieldTTF.js index 9a157e6de9..2f3cefe958 100644 --- a/cocos2d/text-input/CCTextFieldTTF.js +++ b/cocos2d/text-input/CCTextFieldTTF.js @@ -189,7 +189,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ this.colorSpaceHolder.r = value.r; this.colorSpaceHolder.g = value.g; this.colorSpaceHolder.b = value.b; - this.colorSpaceHolder.a = cc.js.isUndefined(value.a) ? 255 : value.a; + this.colorSpaceHolder.a = (typeof value.a === 'undefined') ? 255 : value.a; if(!this._inputText.length) this.setColor(this.colorSpaceHolder); }, @@ -202,7 +202,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{ this._colorText.r = textColor.r; this._colorText.g = textColor.g; this._colorText.b = textColor.b; - this._colorText.a = cc.js.isUndefined(textColor.a) ? 255 : textColor.a; + this._colorText.a = (typeof textColor.a === 'undefined') ? 255 : textColor.a; if(this._inputText.length) this.setColor(this._colorText); }, diff --git a/cocos2d/tilemap/CCTiledMap.js b/cocos2d/tilemap/CCTiledMap.js index f9c7610fec..2d054546a6 100644 --- a/cocos2d/tilemap/CCTiledMap.js +++ b/cocos2d/tilemap/CCTiledMap.js @@ -170,29 +170,23 @@ var TiledMap = cc.Class({ }, properties: { - _isLoading: { - default: false, - serializable: false, - }, - // the detached array of TiledLayer _detachedLayers: { default: [], serializable: false, }, + _tmxFile: { + default: null, + type: cc.TiledMapAsset + }, /** - * !#en The tmx file. - * !#zh tmx 文件。 - * @property {String} tmxFile + * !#en The TiledMap Asset. + * !#zh TiledMap 资源。 + * @property {cc.TiledMapAsset} tmxAsset * @default "" */ - _tmxFile: { - default: '', - url: cc.TiledMapAsset - }, - - tmxFile : { + tmxAsset : { get: function () { return this._tmxFile; }, @@ -202,17 +196,7 @@ var TiledMap = cc.Class({ this._applyFile(); } }, - url: cc.TiledMapAsset - }, - - /** - * !#en The event handler to be called when the map is loaded. - * !#zh 在加载在地图时要调用的事件处理程序。 - * @property {Component.EventHandler} mapLoaded - */ - mapLoaded: { - default: [], - type: cc.Component.EventHandler, + type: cc.TiledMapAsset } }, @@ -345,54 +329,12 @@ var TiledMap = cc.Class({ this._sgNode.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; + cc.error('Method "initWithTMXFile" is no effect now, please set property "tmxAsset" instead.'); }, - /* - * 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 self = this; - var sgNode = self._sgNode; - var mapInfo = new cc.TMXMapInfo(tmxString, resourcePath); - if (!mapInfo) { - self._onMapLoaded(new Error('Parse map info failed.')); - return; - } - - self._isLoading = true; - if (cc.sys.isNative) { - // TODO Consider to remove the setTimeout - // In native environment, the reason of using setTimeout: - // If not use setTimeout, the _sgNode of cc.TiledLayer - // will be removed from the scene graph. - setTimeout(function() { - sgNode.initWithXML(tmxString, resourcePath); - self._onMapLoaded(); - }, 0); - } else { - this._preloadTextures(mapInfo, function (err, results) { - if (!err) { - sgNode.initWithXML(tmxString, resourcePath); - } - self._onMapLoaded(err); - }); - } + cc.error('Method "initWithXML" is no effect now, please set property "tmxAsset" instead.'); }, /** @@ -486,9 +428,15 @@ var TiledMap = cc.Class({ }, onEnable: function () { + if (this._detachedLayers.length === 0) { + // When the TiledMap loaded first time, the detachedLayers is empty. + // Should move the layers in sgNode to detachedLayers. + this._moveLayersInSgNode(this._sgNode); + } + this._super(); - if (this._tmxFile && ! this._isLoading) { + if (this._tmxFile) { // refresh layer entities this._refreshLayerEntities(); } @@ -502,14 +450,7 @@ var TiledMap = cc.Class({ this._super(); // disable the TiledLayer component in logic children - var logicChildren = this.node.getChildren(); - for (var i = logicChildren.length - 1; i >= 0; i--) { - var child = logicChildren[i]; - var tmxLayer = child.getComponent(cc.TiledLayer); - if (tmxLayer) { - tmxLayer.enabled = false; - } - } + this._setLayersEnabled(false); // remove the sg children for tmx layers (which not maintained by TiledLayer) var restoredSgNode = this._plainNode; @@ -535,54 +476,33 @@ var TiledMap = cc.Class({ this._applyFile(); }, - _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(); - } + _resetSgSize: function () { + this.node.setContentSize(this._sgNode.getContentSize()); + this._sgNode.setContentSize(0, 0); }, - _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 ) { - if (this._enabled) { - this._refreshLayerEntities(); - this._anchorChanged(); - } else { - this._moveLayersInSgNode(this._sgNode); - } + _onMapLoaded: function() { + this._refreshLayerEntities(); + if (this._enabled) { + this._anchorChanged(); + } else { + this._moveLayersInSgNode(this._sgNode); } - if (!CC_EDITOR) { - // if it's not in Editor, emit mapLoaded events. - cc.Component.EventHandler.emitEvents(this.mapLoaded, err); + // enable / disable the TiledLayer component + this._setLayersEnabled(this._enabled); + + this._resetSgSize(); + }, + + _setLayersEnabled: function(enabled) { + var logicChildren = this.node.getChildren(); + for (var i = logicChildren.length - 1; i >= 0; i--) { + var child = logicChildren[i]; + var tmxLayer = child.getComponent(cc.TiledLayer); + if (tmxLayer) { + tmxLayer.enabled = enabled; + } } }, @@ -758,6 +678,7 @@ var TiledMap = cc.Class({ var child = logicChildren[i]; var tmxLayer = child.getComponent(cc.TiledLayer); var zOrderValue = child.getSiblingIndex(); + child.setLocalZOrder(zOrderValue); if (tmxLayer) { if (tmxLayer._sgNode) { tmxLayer._sgNode.setLocalZOrder(zOrderValue); @@ -775,26 +696,11 @@ var TiledMap = cc.Class({ var file = this._tmxFile; var self = this; if (file) { - self._isLoading = true; - if (cc.sys.isNative) { - // TODO Consider to remove the setTimeout - // In native environment, the reason of using setTimeout: - // If not use setTimeout, the _sgNode of cc.TiledLayer - // will be removed from the scene graph. - setTimeout(function() { - if (sgNode.initWithTMXFile(file)) { - self._onMapLoaded(); - } else { - self._onMapLoaded(new Error('Parse map info failed.')); - } - }, 0); - } else { - this._preloadTmx(file, function (err, results) { - if (!err) { - sgNode.initWithTMXFile(file); - } - self._onMapLoaded(err); - }); + var resPath = cc.url._rawAssets + file.tmxFolderPath; + resPath = cc.path._setEndWithSep(resPath, false); + var ret = sgNode.initWithXML(file.tmxXmlStr, resPath); + if (ret) { + self._onMapLoaded(); } } else { // tmx file is cleared @@ -804,13 +710,18 @@ var TiledMap = cc.Class({ sgNode.removeChild(layers[i]); } - // 2. if the component is enabled, - // should remove the entities for tmx layers in node - if (self._enabled) { - self._removeLayerEntities(); - } + // 2. clean the detached layers + this._detachedLayers.length = 0; + + // 3. remove the logic nodes of TiledLayer + self._removeLayerEntities(); } }, }); cc.TiledMap = module.exports = TiledMap; +cc.js.obsolete(cc.TiledMap.prototype, 'cc.TiledMap.tmxFile', 'tmxAsset', true); +cc.js.get(cc.TiledMap.prototype, 'mapLoaded', function () { + cc.error('Property "mapLoaded" is unused now. Please write the logic to the callback "start".'); + return []; +}, false); \ No newline at end of file diff --git a/cocos2d/tilemap/CCTiledMapAsset.js b/cocos2d/tilemap/CCTiledMapAsset.js index 466fed7cdc..c8d956950c 100644 --- a/cocos2d/tilemap/CCTiledMapAsset.js +++ b/cocos2d/tilemap/CCTiledMapAsset.js @@ -26,12 +26,40 @@ /** * Class for tiled map asset handling. * @class TiledMapAsset - * @extends RawAsset + * @extends Asset * @constructor */ var TiledMapAsset = cc.Class({ name: 'cc.TiledMapAsset', - extends: cc.RawAsset, + extends: cc.Asset, + + properties: { + tmxXmlStr: { + default: '' + }, + + tmxFolderPath : { + default: '' + }, + + textures: { + default: [], + url: [cc.Texture2D] + }, + + tsxFiles: { + default: [], + url: [cc.RawAsset] + } + }, + + createNode: CC_EDITOR && function (callback) { + var node = new cc.Node(this.name); + var tiledMap = node.addComponent(cc.TiledMap); + tiledMap.tmxAsset = this; + + return callback(null, node); + } }); cc.TiledMapAsset = TiledMapAsset; diff --git a/cocos2d/tilemap/editor/tiled-map.html b/cocos2d/tilemap/editor/tiled-map.html new file mode 100644 index 0000000000..212eafb723 --- /dev/null +++ b/cocos2d/tilemap/editor/tiled-map.html @@ -0,0 +1,19 @@ + + + + + + + + + diff --git a/cocos2d/tilemap/editor/tiled-map.js b/cocos2d/tilemap/editor/tiled-map.js index 0b89b88d4f..3812892618 100644 --- a/cocos2d/tilemap/editor/tiled-map.js +++ b/cocos2d/tilemap/editor/tiled-map.js @@ -1,11 +1,105 @@ 'use strict'; -class TiledMapMeta extends Editor.metas['raw-asset'] { - constructor ( assetdb ) { - super( assetdb ); +const CustomAssetMeta = Editor.metas['custom-asset']; + +const Fs = require('fire-fs'); +const Path = require('fire-path'); +const Url = require('fire-url'); + +const DOMParser = require('xmldom').DOMParser; +const TMX_ENCODING = { encoding: 'utf-8' }; + +function searchDependFiles(tmxFile, cb) { + if (!Fs.existsSync(tmxFile)) { + return cb(new Error(`${tmxFile} is not found!`)); } + var fileContent = Fs.readFileSync(tmxFile, 'utf-8'); + var doc = new DOMParser().parseFromString(fileContent); + if (!doc) { + return cb(new Error(`Parse ${tmxFile} failed.`)); + } + + var textures = []; + var tsxFiles = []; + function parseTilesetImages(tilesetNode, sourcePath) { + var images = tilesetNode.getElementsByTagName('image'); + for (var i = 0, n = images.length; i < n ; i++) { + var imageCfg = images[i].getAttribute('source'); + if (imageCfg) { + var imgPath = cc.path.changeBasename(sourcePath, imageCfg); + textures.push(imgPath); + } + } + } + + var rootElement = doc.documentElement; + var tilesetElements = rootElement.getElementsByTagName('tileset'); + for (var i = 0, n = tilesetElements.length; i < n; i++) { + var tileset = tilesetElements[i]; + var sourceTSX = tileset.getAttribute('source'); + if (sourceTSX) { + var tsxPath = cc.path.changeBasename(tmxFile, sourceTSX); + + if (Fs.existsSync(tsxPath)) { + tsxFiles.push(tsxPath); + var tsxContent = Fs.readFileSync(tsxPath, 'utf-8'); + var tsxDoc = new DOMParser().parseFromString(tsxContent); + if (tsxDoc) { + parseTilesetImages(tsxDoc, tsxPath); + } else { + Editor.warn('Parse %s failed.', tsxPath); + } + } + } + + // import images + parseTilesetImages(tileset, tmxFile); + } + + cb(null, { textures: textures, tsxFiles: tsxFiles }); +} + +const AssetRootUrl = 'db://assets/'; + +class TiledMapMeta extends CustomAssetMeta { + constructor (assetdb) { + super(assetdb); + this.textures = []; + this.tsxFiles = []; + } + + static version () { return '1.0.1'; } static defaultType() { return 'tiled-map'; } + + import (fspath, cb) { + Fs.readFile(fspath, TMX_ENCODING, (err, data) => { + if (err) { + return cb(err); + } + + var db = this._assetdb; + var asset = new cc.TiledMapAsset(); + asset.name = Path.basenameNoExt(fspath); + asset.tmxXmlStr = data; + asset.tmxFolderPath = Path.relative(AssetRootUrl, Url.dirname(db.fspathToUrl(fspath))); + + searchDependFiles(fspath, (err, info) => { + if (err) { + return cb(err); + } + + this.textures = info.textures.map(p => db.fspathToUrl(p)); + this.tsxFiles = info.tsxFiles.map(p => db.fspathToUrl(p)); + + asset.textures = this.textures; + asset.tsxFiles = this.tsxFiles; + + db.saveAssetToLibrary(this.uuid, asset); + cb(); + }); + }); + } } TiledMapMeta.prototype.export = null; diff --git a/extensions/ccb-reader/CCBReader.js b/extensions/ccb-reader/CCBReader.js index 577a1e0ccc..296e2c5bd2 100644 --- a/extensions/ccb-reader/CCBReader.js +++ b/extensions/ccb-reader/CCBReader.js @@ -1059,7 +1059,7 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) { controller[outletName] = outletNode; } - if (controller.onDidLoadFromCCB && cc.js.isFunction(controller.onDidLoadFromCCB)) + if (controller.onDidLoadFromCCB && typeof controller.onDidLoadFromCCB === 'function') controller.onDidLoadFromCCB(); // Setup timeline callbacks diff --git a/extensions/ccui/layouts/UILayoutParameter.js b/extensions/ccui/layouts/UILayoutParameter.js index e66580f958..a172a28feb 100644 --- a/extensions/ccui/layouts/UILayoutParameter.js +++ b/extensions/ccui/layouts/UILayoutParameter.js @@ -114,7 +114,7 @@ ccui.LayoutParameter = ccui.Class.extend(/** @lends ccui.LayoutParameter# */{ * @param {ccui.Margin} margin */ setMargin: function (margin) { - if(cc.js.isObject(margin)){ + if(typeof margin === 'object'){ this._margin.left = margin.left; this._margin.top = margin.top; this._margin.right = margin.right; diff --git a/extensions/cocostudio/armature/utils/CCDataReaderHelper.js b/extensions/cocostudio/armature/utils/CCDataReaderHelper.js index 329382ae6f..b6b881c654 100644 --- a/extensions/cocostudio/armature/utils/CCDataReaderHelper.js +++ b/extensions/cocostudio/armature/utils/CCDataReaderHelper.js @@ -1173,7 +1173,7 @@ ccs.dataReaderHelper = /** @lends ccs.dataReaderHelper# */{ }, _asyncCallBack: function (selector, target, percent) { - if(selector && cc.js.isFunction(selector)) + if(selector && typeof selector === 'function') selector.call(target, percent); if(target && selector && typeof selector === 'string') target[selector](percent); diff --git a/extensions/cocostudio/loader/parsers/scene-1.x.js b/extensions/cocostudio/loader/parsers/scene-1.x.js index 94051c199a..f5fd5d8328 100644 --- a/extensions/cocostudio/loader/parsers/scene-1.x.js +++ b/extensions/cocostudio/loader/parsers/scene-1.x.js @@ -48,25 +48,25 @@ }, setPropertyFromJsonDict: function(node, json){ - var x = (cc.js.isUndefined(json["x"]))?0:json["x"]; - var y = (cc.js.isUndefined(json["y"]))?0:json["y"]; + var x = (typeof json["x"] === 'undefined')?0:json["x"]; + var y = (typeof json["y"] === 'undefined')?0:json["y"]; node.setPosition(x, y); - var bVisible = Boolean((cc.js.isUndefined(json["visible"]))?1:json["visible"]); + var bVisible = Boolean((typeof json["visible"] === 'undefined')?1:json["visible"]); node.setVisible(bVisible); - var nTag = (cc.js.isUndefined(json["objecttag"]))?-1:json["objecttag"]; + var nTag = (typeof json["objecttag"] === 'undefined')?-1:json["objecttag"]; node.setTag(nTag); - var nZorder = (cc.js.isUndefined(json["zorder"]))?0:json["zorder"]; + var nZorder = (typeof json["zorder"] === 'undefined')?0:json["zorder"]; node.setLocalZOrder(nZorder); - var fScaleX = (cc.js.isUndefined(json["scalex"]))?1:json["scalex"]; - var fScaleY = (cc.js.isUndefined(json["scaley"]))?1:json["scaley"]; + var fScaleX = (typeof json["scalex"] === 'undefined')?1:json["scalex"]; + var fScaleY = (typeof json["scaley"] === 'undefined')?1:json["scaley"]; node.setScaleX(fScaleX); node.setScaleY(fScaleY); - var fRotationZ = (cc.js.isUndefined(json["rotation"]))?0:json["rotation"]; + var fRotationZ = (typeof json["rotation"] === 'undefined')?0:json["rotation"]; node.setRotation(fRotationZ); var sName = json["name"] || ""; diff --git a/extensions/cocostudio/trigger/ObjectFactory.js b/extensions/cocostudio/trigger/ObjectFactory.js index 29c21c8c8d..fe60e0220f 100644 --- a/extensions/cocostudio/trigger/ObjectFactory.js +++ b/extensions/cocostudio/trigger/ObjectFactory.js @@ -40,7 +40,7 @@ ccs.objectFactory = /** @lends ccs.objectFactory# */{ var o = null; var t = this._typeMap[className]; if (t) { - if(cc.js.isFunction(t._fun)) + if(typeof t._fun === 'function') o = new t._fun(); else o = t._fun; diff --git a/gulp/tasks/build.js b/gulp/tasks/build.js index eeb1ace057..4265e4144f 100644 --- a/gulp/tasks/build.js +++ b/gulp/tasks/build.js @@ -47,7 +47,6 @@ function getUglifyOptions (minify, global_defs) { return { compress: { global_defs: global_defs, - conditionals: false, // 如果为 true, 会把 if 压缩成 bool 表达式, 但 sourcemap 的行号就会乱掉 } }; } diff --git a/jsb/jsb-director.js b/jsb/jsb-director.js index 7ea41db90b..0b285ef9cd 100644 --- a/jsb/jsb-director.js +++ b/jsb/jsb-director.js @@ -41,6 +41,15 @@ cc.js.mixin(cc.director, { this._animationManager = null; } + // collider manager + if (cc.CollisionManager) { + this._collisionManager = new cc.CollisionManager(); + this.getScheduler().scheduleUpdate(this._collisionManager, cc.Scheduler.PRIORITY_SYSTEM, false); + } + else { + this._collisionManager = null; + } + // WidgetManager cc._widgetManager.init(this); }, @@ -65,6 +74,11 @@ cc.js.mixin(cc.director, { this.getScheduler().scheduleUpdate(this._animationManager, cc.Scheduler.PRIORITY_SYSTEM, false); } + // Collision manager + if (this._collisionManager) { + this.getScheduler().scheduleUpdate(this._collisionManager, cc.Scheduler.PRIORITY_SYSTEM, false); + } + this.startAnimation(); }, @@ -77,6 +91,15 @@ cc.js.mixin(cc.director, { return this._animationManager; }, + /** + * Returns the cc.CollisionManager associated with this director. + * @method getCollisionManager + * @return {CollisionManager} + */ + getCollisionManager: function () { + return this._collisionManager; + }, + /** * Returns current running Scene. Director can only run one Scene at the time. * @method getScene @@ -252,6 +275,7 @@ cc.js.mixin(cc.director, { //cc.AssetLibrary.unloadAsset(uuid); // force reload cc.AssetLibrary.loadAsset(uuid, function (error, sceneAsset) { var self = cc.director; + self._loadingScene = ''; var scene; if (error) { error = 'Failed to load scene: ' + error; @@ -272,7 +296,6 @@ cc.js.mixin(cc.director, { scene = null; } } - self._loadingScene = ''; if (error && onLaunched) { onLaunched(error); } diff --git a/jsb/jsb-editbox.js b/jsb/jsb-editbox.js index fbf76d738f..553d06ceca 100644 --- a/jsb/jsb-editbox.js +++ b/jsb/jsb-editbox.js @@ -48,18 +48,6 @@ _p.setMaxLength = function(maxLength) { maxLength = Number.MAX_VALUE; } this._setMaxLength(maxLength); -} +}; -_p.editBoxEditingDidBegin = function (sender) { - this.editBoxEditingDidBegan(sender); -} -_p.editBoxEditingDidEnd = function (sender) { - this.editBoxEditingDidEnded(sender); -} - -_p._onTouchBegan = function() {} -_p._onTouchEnded = function() {} - -_p.setLineHeight = function () {} - -_p = null; +_p.setLineHeight = function () {}; diff --git a/jsb/jsb-etc.js b/jsb/jsb-etc.js index b8fb830233..b5ce394506 100644 --- a/jsb/jsb-etc.js +++ b/jsb/jsb-etc.js @@ -119,28 +119,6 @@ cc.TextureCache.prototype.addImage = function(url, cb, target) { } }; -// cc.SpriteFrame -cc.SpriteFrame.prototype._ctor = function (filename, rect, rotated, offset, originalSize) { - if (originalSize !== undefined) { - if(filename instanceof cc.Texture2D) { - this.initWithTexture(filename, rect, rotated, offset, originalSize); - } - else { - this.initWithTexture(filename, rect, rotated, offset, originalSize); - } - } else if (rect !== undefined) { - if(filename instanceof cc.Texture2D) { - this.initWithTexture(filename, rect); - } - else { - this.initWithTextureFilename(filename, rect); - } - } else if (filename instanceof cc.Texture2D) { - rect = cc.rect(0, 0, filename.getPixelWidth(), filename.getPixelHeight()); - this.initWithTexture(filename, rect); - } -}; - // setTimeout, setInterval, clearTimeout, clearInteval var _windowTimeIntervalId = 0; var _windowTimeFunHash = {}; diff --git a/jsb/jsb-game.js b/jsb/jsb-game.js index b9469c2b3d..caaf37b3d5 100644 --- a/jsb/jsb-game.js +++ b/jsb/jsb-game.js @@ -40,6 +40,8 @@ cc.js.mixin(cc.game, { RENDER_TYPE_CANVAS: 0, RENDER_TYPE_WEBGL: 1, RENDER_TYPE_OPENGL: 2, + + EVENT_GAME_INITED: "game_inited", CONFIG_KEY: { width: 'width', @@ -105,10 +107,12 @@ cc.js.mixin(cc.game, { cc.loader.load(jsList, function (err) { if (err) throw new Error(JSON.stringify(err)); self._prepared = true; + self.emit(self.EVENT_GAME_INITED); if (cb) cb(); }); } else { + self.emit(self.EVENT_GAME_INITED); if (cb) cb(); } @@ -236,6 +240,10 @@ cc.js.mixin(cc.game, { config[CONFIG_KEY.showFPS] = (CONFIG_KEY.showFPS in config) ? (!!config[CONFIG_KEY.showFPS]) : true; config[CONFIG_KEY.engineDir] = config[CONFIG_KEY.engineDir] || 'frameworks/cocos2d-html5'; + // Group List and Collide Map + this.groupList = config.groupList; + this.collideMap = config.collideMap; + // Scene parser this._sceneInfos = this._sceneInfos.concat(config[CONFIG_KEY.scenes]); diff --git a/jsb/jsb-label.js b/jsb/jsb-label.js index 9f0fc4ec26..c1e79ce072 100644 --- a/jsb/jsb-label.js +++ b/jsb/jsb-label.js @@ -61,7 +61,7 @@ jsbLabel.prototype.getOverflow = function() { if (!jsbLabel.prototype.isSystemFontUsed) { jsbLabel.prototype.isSystemFontUsed = function() { return this._isSystemFontUsed; - } + }; jsbLabel.prototype.setSystemFontUsed = function(value) { this._isSystemFontUsed = value; @@ -87,7 +87,7 @@ 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(){}; diff --git a/jsb/jsb-tex-sprite-frame.js b/jsb/jsb-tex-sprite-frame.js index df25442a13..643283f552 100644 --- a/jsb/jsb-tex-sprite-frame.js +++ b/jsb/jsb-tex-sprite-frame.js @@ -55,73 +55,103 @@ cc.js.mixin(cc.SpriteFrame.prototype, cc.EventTarget.prototype); cc.SpriteFrame.prototype.textureLoaded = function () { return this.getTexture() !== null; }; + +// cc.SpriteFrame +cc.SpriteFrame.prototype._ctor = function (filename, rect, rotated, offset, originalSize) { + if (filename !== undefined) { + this.initWithTexture(filename, rect, rotated, offset, originalSize); + } else { + //todo log Error + } +}; + cc.SpriteFrame.prototype._initWithTexture = cc.SpriteFrame.prototype.initWithTexture; -cc.SpriteFrame.prototype.initWithTexture = function (texture, rect, rotated, offset, originalSize, _uuid) { - function check(texture) { - if (texture && texture.isLoaded()) { - var _x, _y; - if (rotated) { - _x = rect.x + rect.height; - _y = rect.y + rect.width; - } - else { - _x = rect.x + rect.width; - _y = rect.y + rect.height; - } - if (_x > texture.getPixelWidth()) { - cc.error(cc._LogInfos.RectWidth, _uuid); - } - if (_y > texture.getPixelHeight()) { - cc.error(cc._LogInfos.RectHeight, _uuid); - } - } +cc.SpriteFrame.prototype.initWithTexture = function (texture, rect, rotated, offset, originalSize) { + this.setTexture(texture, rect, rotated, offset, originalSize); +}; + +cc.SpriteFrame.prototype.setTexture = function (textureOrTextureFile, rect, rotated, offset, originalSize) { + + if (rect) { + this.setRect(rect); } - offset = offset || cc.p(0, 0); - originalSize = originalSize || rect; - rotated = rotated || false; - - if (this.insetTop === undefined) { - this.insetTop = 0; - this.insetBottom = 0; - this.insetLeft = 0; - this.insetRight = 0; + if (offset) { + this.setOffset(offset); } - var locTexture; - if (!texture && _uuid) { - // deserialize texture from uuid - var info = cc.AssetLibrary._getAssetInfoInRuntime(_uuid); - if (!info) { - cc.error('SpriteFrame: Failed to load sprite texture "%s"', _uuid); - return; - } + if (originalSize) { + this.setOriginalSize(originalSize); + } - this._textureFilename = info.url; + this.setRotated(rotated || false); - locTexture = cc.textureCache.addImage(info.url); - this._initWithTexture(locTexture, rect, rotated, offset, originalSize); + var texture = textureOrTextureFile; + if (cc.js.isString(textureOrTextureFile)) { + this._textureFilename = textureOrTextureFile; + texture = cc.textureCache.addImage(textureOrTextureFile); + } + + if (texture instanceof cc.Texture2D) { + this._refreshTexture(texture); } else { - if (cc.js.isString(texture)){ - this._textureFilename = texture; - locTexture = cc.textureCache.addImage(this._textureFilename); - this._initWithTexture(locTexture, rect, rotated, offset, originalSize); - } else if (texture instanceof cc.Texture2D) { - this._textureFilename = ''; - this._initWithTexture(texture, rect, rotated, offset, originalSize); - } + //todo log error } - this.emit('load'); - check(this.getTexture()); + return true; }; + +cc.SpriteFrame.prototype._refreshTexture = function (texture) { + + if (this.getTexture() !== texture) { + + var w = texture.width, h = texture.height; + + var rect = this.getRect(); + if (rect.width === 0 || rect.height === 0) { + rect = cc.rect(0, 0, w, h); + } + else { + this._checkRect(texture); + } + + var originalSize = this.getOriginalSize(); + if (originalSize.width === 0 || originalSize.height === 0) { + originalSize = cc.size(w, h); + } + + var offset = this.getOffset(); + var rotated = this.isRotated(); + + if (this.insetTop === undefined) { + this.insetTop = 0; + this.insetBottom = 0; + this.insetLeft = 0; + this.insetRight = 0; + } + + this._initWithTexture(texture, rect, rotated, offset, originalSize); + + //dispatch 'load' event of cc.SpriteFrame + this.emit("load"); + } +}; + cc.SpriteFrame.prototype._deserialize = function (data, handle) { - var rect = data.rect ? new cc.Rect(data.rect[0], data.rect[1], data.rect[2], data.rect[3]) : undefined; - var offset = data.offset ? new cc.Vec2(data.offset[0], data.offset[1]) : undefined; - var size = data.originalSize ? new cc.Size(data.originalSize[0], data.originalSize[1]) : undefined; - var rotated = data.rotated === 1; - // init properties not included in this._initWithTexture() + var rect = data.rect; + if (rect) { + this.setRect(new cc.Rect(rect[0], rect[1], rect[2], rect[3])); + } + if (data.offset) { + this.setOffset(new cc.Vec2(data.offset[0], data.offset[1])); + } + if (data.originalSize) { + this.setOriginalSize(new cc.Size(data.originalSize[0], data.originalSize[1])); + } + + this.setRotated(data.rotated === 1); + this._name = data.name; var capInsets = data.capInsets; if (capInsets) { @@ -136,8 +166,6 @@ cc.SpriteFrame.prototype._deserialize = function (data, handle) { if (textureUuid) { handle.result.push(this, '_textureFilenameSetter', textureUuid); } - - this.initWithTexture(null, rect, rotated, offset, size, textureUuid); }; cc.SpriteFrame.prototype._checkRect = function (texture) { var rect = this.getRect(); @@ -157,34 +185,17 @@ cc.SpriteFrame.prototype._checkRect = function (texture) { cc.error(cc._LogInfos.RectHeight, texture.url); } }; -var getTextureJSB = cc.SpriteFrame.prototype.getTexture; +cc.SpriteFrame.prototype._getTexture = cc.SpriteFrame.prototype.getTexture; cc.SpriteFrame.prototype.getTexture = function () { - var tex = getTextureJSB.call(this); + var tex = this._getTexture(); this._texture = tex; return tex; }; cc.js.set(cc.SpriteFrame.prototype, '_textureFilenameSetter', function (url) { this._textureFilename = url; if (url) { - cc.textureCache.addImage(url, function (texture) { - if (this.getTexture() !== texture) { - this.setTexture(texture); - var w = texture.getPixelWidth(), h = texture.getPixelHeight(); - if (this.getRect().width === 0) { - this.setRect(cc.rect(0, 0, w, h)); - } - if (this.getOriginalSize().width === 0) { - this.setOriginalSize(cc.size(w, h)); - } - if (this.getOffset().width === 0) { - this.setOffset(cc.v2(0, 0)); - } - - this._texture = texture; - } - this._checkRect(texture); - this.emit('load'); - }, this); + var texture = cc.textureCache.addImage(url); + this._refreshTexture(texture); } }); diff --git a/package.json b/package.json index e41dac77fb..36143ed68e 100644 --- a/package.json +++ b/package.json @@ -27,7 +27,7 @@ "gulp-rename": "1.2.2", "gulp-shell": "0.4.1", "gulp-sourcemaps": "1.5.2", - "gulp-uglify": "1.5.1", + "gulp-uglify": "1.5.3", "gulp-util": "3.0.6", "jshint-stylish": "2.1.0", "require-dir": "0.3.0", diff --git a/test/qunit/assets/library/65/65341123490 b/test/qunit/assets/library/65/65341123490 deleted file mode 100644 index bd1d617d68..0000000000 --- a/test/qunit/assets/library/65/65341123490 +++ /dev/null @@ -1,16 +0,0 @@ -{ - "__type__": "TestSprite", - "rawTexture": null, - "texture": { - "__uuid__": "6545543" - }, - "rotated": false, - "trim": false, - "trimThreshold": 1, - "trimLeft": 10, - "trimTop": 20, - "width": 89, - "height": 44, - "x": 0, - "y": 49 -} \ No newline at end of file diff --git a/test/qunit/unit/test-collider.js b/test/qunit/unit/test-collider.js new file mode 100644 index 0000000000..a405459ef9 --- /dev/null +++ b/test/qunit/unit/test-collider.js @@ -0,0 +1,117 @@ +largeModule('collider'); + +test('collision manager', function() { + var manager = cc.director.getCollisionManager(); + ok(manager); + + manager.enabled = true; + + var node1 = new cc.Node(); + cc.director.getScene().addChild(node1); + + var box1 = node1.addComponent(cc.BoxCollider); + strictEqual( manager._colliders.length, 1, 'collision manager should add 1 collider'); + + var box2 = node1.addComponent(cc.BoxCollider); + strictEqual( manager._colliders.length, 2, 'collision manager should add 2 colliders'); + + var node2 = new cc.Node(); + cc.director.getScene().addChild(node2); + + var box3 = node2.addComponent(cc.BoxCollider); + strictEqual( manager._colliders.length, 3, 'collision manager should add 3 colliders'); + strictEqual( manager._contacts.length, 2, 'collision manager should add 2 contacts'); + + var box4 = node2.addComponent(cc.BoxCollider); + + strictEqual( manager._colliders.length, 4, 'collision manager should add 4 colliders'); + strictEqual( manager._contacts.length, 4, 'collision manager should add 4 contacts'); + + box4.mask = 0; + + strictEqual( manager._colliders.length, 4, 'collision manager should add 4 colliders'); + strictEqual( manager._contacts.length, 2, 'collision manager should add 2 contacts'); + + box4.enabled = false; + strictEqual( manager._colliders.length, 3, 'collision manager should add 3 colliders'); + + node1.parent = null; + node2.parent = null; + + strictEqual( manager._colliders.length, 0, 'collision manager should add 0 colliders'); + strictEqual( manager._contacts.length, 0, 'collision manager should add 0 contacts'); + + manager.enabled = false; +}); + +test('collider callback', function () { + var manager = cc.director.getCollisionManager(); + manager.enabled = true; + + var callbacks = []; + + // my component + var MyComponent = cc.Class({ + name: 'MyComponent', + extends: cc.Component, + + onCollisionEnter: function () { + callbacks.push('enter'); + }, + + onCollisionExit: function () { + callbacks.push('exit'); + }, + + onCollisionStay: function () { + callbacks.push('stay'); + } + }); + + var node1 = new cc.Node(); + cc.director.getScene().addChild(node1); + + var box1 = node1.addComponent(cc.BoxCollider); + node1.addComponent(MyComponent); + + var node2 = new cc.Node(); + cc.director.getScene().addChild(node2); + + var box2 = node2.addComponent(cc.BoxCollider); + + deepEqual(callbacks, [], 'should hove no callbacks'); + + manager.update(); + + deepEqual(callbacks, ['enter'], 'should call enter'); + + callbacks = []; + manager.update(); + deepEqual(callbacks, ['stay'], 'should call stay'); + + callbacks = []; + manager.update(); + deepEqual(callbacks, ['stay'], 'should call stay again'); + + node2.x = 1000; + + callbacks = []; + manager.update(); + deepEqual(callbacks, ['exit'], 'should call exit'); + + node2.x = 0; + + callbacks = []; + manager.update(); + deepEqual(callbacks, ['enter'], 'should call enter'); + + callbacks = []; + + node1.parent = null; + node2.parent = null; + + deepEqual(callbacks, ['exit'], 'should call exit'); + + cc.js.unregisterClass(MyComponent); + manager.enabled = false; +}); diff --git a/test/qunit/unit/test-deserialize.js b/test/qunit/unit/test-deserialize.js index d7d8fe1b3d..4b8877dd63 100644 --- a/test/qunit/unit/test-deserialize.js +++ b/test/qunit/unit/test-deserialize.js @@ -83,7 +83,7 @@ if (TestEditorExtends) { var obj = { 'null': null, }; - var str = '{ "null": null }' + var str = '{ "null": null }'; deepEqual(cc.deserialize(str), obj, 'can deserialize null'); var MyAsset = cc.Class({ @@ -96,11 +96,11 @@ if (TestEditorExtends) { } }); - str = '{ "__type__": "MyAsset" }' + str = '{ "__type__": "MyAsset" }'; obj = new MyAsset(); deepEqual(cc.deserialize(str), obj, 'use default value'); - str = '{ "__type__": "MyAsset", "nil": null }' + str = '{ "__type__": "MyAsset", "nil": null }'; obj = new MyAsset(); obj.nil = null; deepEqual(cc.deserialize(str), obj, 'can override as null'); @@ -112,7 +112,7 @@ if (TestEditorExtends) { var obj = { 'null': null, }; - var str = '{ "null": null }' + var str = '{ "null": null }'; deepEqual(cc.deserialize(str, null, {target: null}), obj, 'can deserialize null'); }); diff --git a/test/qunit/unit/test-resources-loader.js b/test/qunit/unit/test-resources-loader.js index 93e4aa0547..d9b92c73c6 100644 --- a/test/qunit/unit/test-resources-loader.js +++ b/test/qunit/unit/test-resources-loader.js @@ -8,7 +8,8 @@ rawAssetsBase: cc.path.dirname(cc.path._setEndWithSep(assetDir, false) + '.dummyExtForDirname') + '/', rawAssets: { assets: { - '748321': { url: 'resources/grossini.png', raw: true } + '748321': { url: 'resources/grossini.png', raw: true }, + '1232218': { url: 'resources/grossini.png/grossini', raw: false } } } }); @@ -18,7 +19,26 @@ asyncTest('load single', function () { cc.loader.releaseAll(); cc.loader.loadRes('grossini.png', function (err, texture) { - ok(texture instanceof cc.Texture2D, 'should be able to load texture without file extname'); + ok(texture instanceof cc.Texture2D, 'should be able to load texture with file extname'); + clearTimeout(timeoutId); + start(); + }); + + var timeoutId = setTimeout(function () { + ok(false, 'time out!'); + start(); + }, 5000); + }); + + asyncTest('load main asset and sub asset by loadAll', function () { + cc.loader.releaseAll(); + cc.loader.loadResAll('grossini.png', function (err, results) { + ok(Array.isArray(results), 'result should be an array'); + var texture = results[0] instanceof cc.Texture2D ? results[0] : results[1]; + var sprite = results[0] instanceof TestSprite ? results[0] : results[1]; + ok(texture instanceof cc.Texture2D, 'should be able to load texture'); + ok(sprite instanceof TestSprite, 'should be able to load test sprite'); + clearTimeout(timeoutId); start(); });