* @param {String} densityDPI
*/
- setTargetDensityDPI: function(densityDPI){
+ setTargetDensityDPI: function (densityDPI) {
this._targetDensityDPI = densityDPI;
this._adjustViewportMeta();
},
@@ -253,7 +253,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{
* Returns the current target-densitydpi value of cc.view.
* @returns {String}
*/
- getTargetDensityDPI: function(){
+ getTargetDensityDPI: function () {
return this._targetDensityDPI;
},
@@ -295,9 +295,9 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{
/**
* Sets the orientation of the game, it can be landscape, portrait or auto.
- * When set it to landscape or portrait, and screen w/h ratio doesn't fit,
+ * When set it to landscape or portrait, and screen w/h ratio doesn't fit,
* cc.view will automatically rotate the game canvas using CSS.
- * Note that this function doesn't have any effect in native,
+ * Note that this function doesn't have any effect in native,
* in native, you need to set the application orientation in native project settings
* @param {Number} orientation - Possible values: cc.ORIENTATION_LANDSCAPE | cc.ORIENTATION_PORTRAIT | cc.ORIENTATION_AUTO
*/
@@ -311,6 +311,18 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{
}
},
+ setDocumentPixelWidth: function (width) {
+ // Set viewport's width
+ this._setViewportMeta({"width": width}, true);
+
+ // Set body width to the exact pixel resolution
+ document.documentElement.style.width = width + 'px';
+ document.body.style.width = "100%";
+
+ // Reset the resolution size and policy
+ this.setDesignResolutionSize(this._designResolutionSize.width, this._designResolutionSize.height, this._resolutionPolicy);
+ },
+
_initFrameSize: function () {
var locFrameSize = this._frameSize;
var w = __BrowserGetter.availWidth(this._frame);
@@ -318,7 +330,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{
var isLandscape = w >= h;
if (!this._orientationChanging || !cc.sys.isMobile ||
- (isLandscape && this._orientation & cc.ORIENTATION_LANDSCAPE) ||
+ (isLandscape && this._orientation & cc.ORIENTATION_LANDSCAPE) ||
(!isLandscape && this._orientation & cc.ORIENTATION_PORTRAIT)) {
locFrameSize.width = w;
locFrameSize.height = h;
@@ -350,7 +362,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{
_setViewportMeta: function (metas, overwrite) {
var vp = document.getElementById("cocosMetaElement");
- if(vp && overwrite){
+ if (vp && overwrite) {
document.head.removeChild(vp);
}
@@ -369,11 +381,11 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{
content += "," + key + "=" + metas[key];
}
else if (overwrite) {
- pattern = new RegExp(key+"\s*=\s*[^,]+");
+ pattern = new RegExp(key + "\s*=\s*[^,]+");
content.replace(pattern, key + "=" + metas[key]);
}
}
- if(/^,/.test(content))
+ if (/^,/.test(content))
content = content.substr(1);
vp.content = content;
@@ -431,7 +443,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{
* Only useful on web
* @param {Boolean} enabled Enable or disable retina display
*/
- enableRetina: function(enabled) {
+ enableRetina: function (enabled) {
this._retinaEnabled = !!enabled;
},
@@ -440,7 +452,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{
* Only useful on web
* @return {Boolean}
*/
- isRetinaEnabled: function() {
+ isRetinaEnabled: function () {
return this._retinaEnabled;
},
@@ -450,7 +462,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{
* Only useful on web
* @param {Boolean} enabled Enable or disable auto full screen on mobile devices
*/
- enableAutoFullScreen: function(enabled) {
+ enableAutoFullScreen: function (enabled) {
if (enabled && enabled !== this._autoFullScreen && cc.sys.isMobile && this._frame === document.documentElement) {
// Automatically full screen when user touches on mobile version
this._autoFullScreen = true;
@@ -466,7 +478,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{
* Only useful on web
* @return {Boolean} Auto full screen enabled or not
*/
- isAutoFullScreenEnabled: function() {
+ isAutoFullScreenEnabled: function () {
return this._autoFullScreen;
},
@@ -572,7 +584,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{
* @return {cc.Size}
*/
getVisibleSize: function () {
- return cc.size(this._visibleRect.width,this._visibleRect.height);
+ return cc.size(this._visibleRect.width, this._visibleRect.height);
},
/**
@@ -589,7 +601,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{
* @return {cc.Point}
*/
getVisibleOrigin: function () {
- return cc.p(this._visibleRect.x,this._visibleRect.y);
+ return cc.p(this._visibleRect.x, this._visibleRect.y);
},
/**
@@ -631,15 +643,15 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{
// Ensure compatibility with JSB
else {
var _locPolicy = cc.ResolutionPolicy;
- if(resolutionPolicy === _locPolicy.EXACT_FIT)
+ if (resolutionPolicy === _locPolicy.EXACT_FIT)
_t._resolutionPolicy = _t._rpExactFit;
- if(resolutionPolicy === _locPolicy.SHOW_ALL)
+ if (resolutionPolicy === _locPolicy.SHOW_ALL)
_t._resolutionPolicy = _t._rpShowAll;
- if(resolutionPolicy === _locPolicy.NO_BORDER)
+ if (resolutionPolicy === _locPolicy.NO_BORDER)
_t._resolutionPolicy = _t._rpNoBorder;
- if(resolutionPolicy === _locPolicy.FIXED_HEIGHT)
+ if (resolutionPolicy === _locPolicy.FIXED_HEIGHT)
_t._resolutionPolicy = _t._rpFixedHeight;
- if(resolutionPolicy === _locPolicy.FIXED_WIDTH)
+ if (resolutionPolicy === _locPolicy.FIXED_WIDTH)
_t._resolutionPolicy = _t._rpFixedWidth;
}
},
@@ -659,38 +671,41 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{
*/
setDesignResolutionSize: function (width, height, resolutionPolicy) {
// Defensive code
- if( !(width > 0 || height > 0) ){
+ if (!(width > 0 || height > 0)) {
cc.log(cc._LogInfos.EGLView_setDesignResolutionSize);
return;
}
this.setResolutionPolicy(resolutionPolicy);
var policy = this._resolutionPolicy;
- if (!policy){
- cc.log(cc._LogInfos.EGLView_setDesignResolutionSize_2);
- return;
+ if (policy) {
+ policy.preApply(this);
}
- policy.preApply(this);
// Reinit frame size
- if(cc.sys.isMobile)
+ if (cc.sys.isMobile)
this._adjustViewportMeta();
// Permit to re-detect the orientation of device.
this._orientationChanging = true;
this._initFrameSize();
+ if (!policy) {
+ cc.log(cc._LogInfos.EGLView_setDesignResolutionSize_2);
+ return;
+ }
+
this._originalDesignResolutionSize.width = this._designResolutionSize.width = width;
this._originalDesignResolutionSize.height = this._designResolutionSize.height = height;
var result = policy.apply(this, this._designResolutionSize);
- if(result.scale && result.scale.length === 2){
+ if (result.scale && result.scale.length === 2) {
this._scaleX = result.scale[0];
this._scaleY = result.scale[1];
}
- if(result.viewport){
+ if (result.viewport) {
var vp = this._viewPortRect,
vb = this._visibleRect,
rv = result.viewport;
@@ -756,9 +771,8 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{
this._setViewportMeta({"width": width}, true);
// Set body width to the exact pixel resolution
- document.body.style.width = width + "px";
- document.body.style.left = "0px";
- document.body.style.top = "0px";
+ document.documentElement.style.width = width + 'px';
+ document.body.style.width = "100%";
// Reset the resolution size and policy
this.setDesignResolutionSize(width, height, resolutionPolicy);
@@ -787,15 +801,24 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{
* @param {Number} h
*/
setScissorInPoints: function (x, y, w, h) {
- var zoomFactor = this._frameZoomFactor, scaleX = this._scaleX, scaleY = this._scaleY;
- _scissorRect.x = x;
- _scissorRect.y = y;
- _scissorRect.width = w;
- _scissorRect.height = h;
- cc._renderContext.scissor(x * scaleX * zoomFactor + this._viewPortRect.x * zoomFactor,
- y * scaleY * zoomFactor + this._viewPortRect.y * zoomFactor,
- w * scaleX * zoomFactor,
- h * scaleY * zoomFactor);
+ var locFrameZoomFactor = this._frameZoomFactor, locScaleX = this._scaleX, locScaleY = this._scaleY;
+ var sx = Math.ceil(x * locScaleX * locFrameZoomFactor + this._viewPortRect.x * locFrameZoomFactor);
+ var sy = Math.ceil(y * locScaleY * locFrameZoomFactor + this._viewPortRect.y * locFrameZoomFactor);
+ var sw = Math.ceil(w * locScaleX * locFrameZoomFactor);
+ var sh = Math.ceil(h * locScaleY * locFrameZoomFactor);
+
+ if (!_scissorRect) {
+ var boxArr = gl.getParameter(gl.SCISSOR_BOX);
+ _scissorRect = cc.rect(boxArr[0], boxArr[1], boxArr[2], boxArr[3]);
+ }
+
+ if (_scissorRect.x != sx || _scissorRect.y != sy || _scissorRect.width != sw || _scissorRect.height != sh) {
+ _scissorRect.x = sx;
+ _scissorRect.y = sy;
+ _scissorRect.width = sw;
+ _scissorRect.height = sh;
+ cc._renderContext.scissor(sx, sy, sw, sh);
+ }
},
/**
@@ -811,7 +834,18 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{
* @return {cc.Rect}
*/
getScissorRect: function () {
- return cc.rect(_scissorRect);
+ if (!_scissorRect) {
+ var boxArr = gl.getParameter(gl.SCISSOR_BOX);
+ _scissorRect = cc.rect(boxArr[0], boxArr[1], boxArr[2], boxArr[3]);
+ }
+ var scaleX = this._scaleX;
+ var scaleY = this._scaleY;
+ return cc.rect(
+ (_scissorRect.x - this._viewPortRect.x) / scaleX,
+ (_scissorRect.y - this._viewPortRect.y) / scaleY,
+ _scissorRect.width / scaleX,
+ _scissorRect.height / scaleY
+ );
},
/**
@@ -860,7 +894,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{
* Returns device pixel ratio for retina display.
* @return {Number}
*/
- getDevicePixelRatio: function() {
+ getDevicePixelRatio: function () {
return this._devicePixelRatio;
},
@@ -892,7 +926,7 @@ cc.EGLView = cc.Class.extend(/** @lends cc.view# */{
_convertTouchesWithScale: function (touches) {
var viewport = this._viewPortRect, scaleX = this._scaleX, scaleY = this._scaleY,
selTouch, selPoint, selPrePoint;
- for( var i = 0; i < touches.length; i++){
+ for (var i = 0; i < touches.length; i++) {
selTouch = touches[i];
selPoint = selTouch._point;
selPrePoint = selTouch._prevPoint;
@@ -1010,7 +1044,7 @@ cc.ContentStrategy = cc.Class.extend(/** @lends cc.ContentStrategy# */{
contentW, contentH);
// Translate the content
- if (cc._renderType === cc.game.RENDER_TYPE_CANVAS){
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
//TODO: modify something for setTransform
//cc._renderContext.translate(viewport.x, viewport.y + contentH);
}
diff --git a/cocos2d/core/platform/CCInputManager.js b/cocos2d/core/platform/CCInputManager.js
index 11230c464a..382b1f86ed 100644
--- a/cocos2d/core/platform/CCInputManager.js
+++ b/cocos2d/core/platform/CCInputManager.js
@@ -62,20 +62,20 @@ cc.inputManager = /** @lends cc.inputManager# */{
_isRegisterEvent: false,
- _preTouchPoint: cc.p(0,0),
- _prevMousePoint: cc.p(0,0),
+ _preTouchPoint: cc.p(0, 0),
+ _prevMousePoint: cc.p(0, 0),
_preTouchPool: [],
_preTouchPoolPointer: 0,
_touches: [],
- _touchesIntegerDict:{},
+ _touchesIntegerDict: {},
_indexBitsUsed: 0,
_maxTouches: 5,
_accelEnabled: false,
- _accelInterval: 1/30,
+ _accelInterval: 1 / 30,
_accelMinus: 1,
_accelCurTime: 0,
_acceleration: null,
@@ -121,15 +121,15 @@ cc.inputManager = /** @lends cc.inputManager# */{
* @param {Array} touches
*/
handleTouchesBegin: function (touches) {
- var selTouch, index, curTouch, touchID,
+ var selTouch, index, curTouch, touchID,
handleTouches = [], locTouchIntDict = this._touchesIntegerDict,
now = cc.sys.now();
- for(var i = 0, len = touches.length; i< len; i ++){
+ for (var i = 0, len = touches.length; i < len; i++) {
selTouch = touches[i];
touchID = selTouch.getID();
index = locTouchIntDict[touchID];
- if(index == null){
+ if (index == null) {
var unusedIndex = this._getUnUsedIndex();
if (unusedIndex === -1) {
cc.log(cc._LogInfos.inputManager_handleTouchesBegin, unusedIndex);
@@ -143,7 +143,7 @@ cc.inputManager = /** @lends cc.inputManager# */{
handleTouches.push(curTouch);
}
}
- if(handleTouches.length > 0){
+ if (handleTouches.length > 0) {
this._glView._convertTouchesWithScale(handleTouches);
var touchEvent = new cc.EventTouch(handleTouches);
touchEvent._eventCode = cc.EventTouch.EventCode.BEGAN;
@@ -155,27 +155,27 @@ cc.inputManager = /** @lends cc.inputManager# */{
* @function
* @param {Array} touches
*/
- handleTouchesMove: function(touches){
- var selTouch, index, touchID,
+ handleTouchesMove: function (touches) {
+ var selTouch, index, touchID,
handleTouches = [], locTouches = this._touches,
now = cc.sys.now();
- for(var i = 0, len = touches.length; i< len; i ++){
+ for (var i = 0, len = touches.length; i < len; i++) {
selTouch = touches[i];
touchID = selTouch.getID();
index = this._touchesIntegerDict[touchID];
- if(index == null){
+ if (index == null) {
//cc.log("if the index doesn't exist, it is an error");
continue;
}
- if(locTouches[index]){
+ if (locTouches[index]) {
locTouches[index]._setPoint(selTouch._point);
locTouches[index]._setPrevPoint(selTouch._prevPoint);
locTouches[index]._lastModified = now;
handleTouches.push(locTouches[index]);
}
}
- if(handleTouches.length > 0){
+ if (handleTouches.length > 0) {
this._glView._convertTouchesWithScale(handleTouches);
var touchEvent = new cc.EventTouch(handleTouches);
touchEvent._eventCode = cc.EventTouch.EventCode.MOVED;
@@ -187,9 +187,9 @@ cc.inputManager = /** @lends cc.inputManager# */{
* @function
* @param {Array} touches
*/
- handleTouchesEnd: function(touches){
+ handleTouchesEnd: function (touches) {
var handleTouches = this.getSetOfTouchesEndOrCancel(touches);
- if(handleTouches.length > 0) {
+ if (handleTouches.length > 0) {
this._glView._convertTouchesWithScale(handleTouches);
var touchEvent = new cc.EventTouch(handleTouches);
touchEvent._eventCode = cc.EventTouch.EventCode.ENDED;
@@ -201,9 +201,9 @@ cc.inputManager = /** @lends cc.inputManager# */{
* @function
* @param {Array} touches
*/
- handleTouchesCancel: function(touches){
+ handleTouchesCancel: function (touches) {
var handleTouches = this.getSetOfTouchesEndOrCancel(touches);
- if(handleTouches.length > 0) {
+ if (handleTouches.length > 0) {
this._glView._convertTouchesWithScale(handleTouches);
var touchEvent = new cc.EventTouch(handleTouches);
touchEvent._eventCode = cc.EventTouch.EventCode.CANCELLED;
@@ -216,17 +216,17 @@ cc.inputManager = /** @lends cc.inputManager# */{
* @param {Array} touches
* @returns {Array}
*/
- getSetOfTouchesEndOrCancel: function(touches) {
+ getSetOfTouchesEndOrCancel: function (touches) {
var selTouch, index, touchID, handleTouches = [], locTouches = this._touches, locTouchesIntDict = this._touchesIntegerDict;
- for(var i = 0, len = touches.length; i< len; i ++){
+ for (var i = 0, len = touches.length; i < len; i++) {
selTouch = touches[i];
touchID = selTouch.getID();
index = locTouchesIntDict[touchID];
- if(index == null){
+ if (index == null) {
continue; //cc.log("if the index doesn't exist, it is an error");
}
- if(locTouches[index]){
+ if (locTouches[index]) {
locTouches[index]._setPoint(selTouch._point);
locTouches[index]._setPrevPoint(selTouch._prevPoint);
handleTouches.push(locTouches[index]);
@@ -269,7 +269,7 @@ cc.inputManager = /** @lends cc.inputManager# */{
* @param {cc.Touch} touch
* @return {cc.Touch}
*/
- getPreTouch: function(touch){
+ getPreTouch: function (touch) {
var preTouch = null;
var locPreTouchPool = this._preTouchPool;
var id = touch.getID();
@@ -288,7 +288,7 @@ cc.inputManager = /** @lends cc.inputManager# */{
* @function
* @param {cc.Touch} touch
*/
- setPreTouch: function(touch){
+ setPreTouch: function (touch) {
var find = false;
var locPreTouchPool = this._preTouchPool;
var id = touch.getID();
@@ -316,10 +316,10 @@ cc.inputManager = /** @lends cc.inputManager# */{
* @param {cc.Point} pos
* @return {cc.Touch}
*/
- getTouchByXY: function(tx, ty, pos){
+ getTouchByXY: function (tx, ty, pos) {
var locPreTouch = this._preTouchPoint;
var location = this._glView.convertToLocationInView(tx, ty, pos);
- var touch = new cc.Touch(location.x, location.y);
+ var touch = new cc.Touch(location.x, location.y);
touch._setPrevPoint(locPreTouch.x, locPreTouch.y);
locPreTouch.x = location.x;
locPreTouch.y = location.y;
@@ -333,7 +333,7 @@ cc.inputManager = /** @lends cc.inputManager# */{
* @param {Number} eventType
* @returns {cc.EventMouse}
*/
- getMouseEvent: function(location, pos, eventType){
+ getMouseEvent: function (location, pos, eventType) {
var locPreMouse = this._prevMousePoint;
this._glView._convertMouseToLocationInView(location, pos);
var mouseEvent = new cc.EventMouse(eventType);
@@ -350,7 +350,7 @@ cc.inputManager = /** @lends cc.inputManager# */{
* @param {cc.Point} pos
* @return {cc.Point}
*/
- getPointByEvent: function(event, pos){
+ getPointByEvent: function (event, pos) {
if (event.pageX != null) //not available in <= IE8
return {x: event.pageX, y: event.pageY};
@@ -365,7 +365,7 @@ cc.inputManager = /** @lends cc.inputManager# */{
* @param {cc.Point} pos
* @returns {Array}
*/
- getTouchesByEvent: function(event, pos){
+ getTouchesByEvent: function (event, pos) {
var touchArr = [], locView = this._glView;
var touch_event, touch, preLocation;
var locPreTouch = this._preTouchPoint;
@@ -401,8 +401,8 @@ cc.inputManager = /** @lends cc.inputManager# */{
* @function
* @param {HTMLElement} element
*/
- registerSystemEvent: function(element){
- if(this._isRegisterEvent) return;
+ registerSystemEvent: function (element) {
+ if (this._isRegisterEvent) return;
var locView = this._glView = cc.view;
var selfPointer = this;
@@ -416,7 +416,7 @@ cc.inputManager = /** @lends cc.inputManager# */{
// miui
// WECHAT
var prohibition = false;
- if( cc.sys.isMobile)
+ if (cc.sys.isMobile)
prohibition = true;
//register touch event
@@ -426,19 +426,19 @@ cc.inputManager = /** @lends cc.inputManager# */{
}, false);
window.addEventListener('mouseup', function (event) {
- if(prohibition) return;
+ if (prohibition) return;
var savePressed = selfPointer._mousePressed;
selfPointer._mousePressed = false;
- if(!savePressed)
+ if (!savePressed)
return;
var pos = selfPointer.getHTMLElementPosition(element);
var location = selfPointer.getPointByEvent(event, pos);
- if (!cc.rectContainsPoint(new cc.Rect(pos.left, pos.top, pos.width, pos.height), location)){
+ if (!cc.rectContainsPoint(new cc.Rect(pos.left, pos.top, pos.width, pos.height), location)) {
selfPointer.handleTouchesEnd([selfPointer.getTouchByXY(location.x, location.y, pos)]);
- var mouseEvent = selfPointer.getMouseEvent(location,pos,cc.EventMouse.UP);
+ var mouseEvent = selfPointer.getMouseEvent(location, pos, cc.EventMouse.UP);
mouseEvent.setButton(event.button);
cc.eventManager.dispatchEvent(mouseEvent);
}
@@ -446,7 +446,7 @@ cc.inputManager = /** @lends cc.inputManager# */{
//register canvas mouse event
element.addEventListener("mousedown", function (event) {
- if(prohibition) return;
+ if (prohibition) return;
selfPointer._mousePressed = true;
var pos = selfPointer.getHTMLElementPosition(element);
@@ -454,7 +454,7 @@ cc.inputManager = /** @lends cc.inputManager# */{
selfPointer.handleTouchesBegin([selfPointer.getTouchByXY(location.x, location.y, pos)]);
- var mouseEvent = selfPointer.getMouseEvent(location,pos,cc.EventMouse.DOWN);
+ var mouseEvent = selfPointer.getMouseEvent(location, pos, cc.EventMouse.DOWN);
mouseEvent.setButton(event.button);
cc.eventManager.dispatchEvent(mouseEvent);
@@ -464,7 +464,7 @@ cc.inputManager = /** @lends cc.inputManager# */{
}, false);
element.addEventListener("mouseup", function (event) {
- if(prohibition) return;
+ if (prohibition) return;
selfPointer._mousePressed = false;
var pos = selfPointer.getHTMLElementPosition(element);
@@ -472,7 +472,7 @@ cc.inputManager = /** @lends cc.inputManager# */{
selfPointer.handleTouchesEnd([selfPointer.getTouchByXY(location.x, location.y, pos)]);
- var mouseEvent = selfPointer.getMouseEvent(location,pos,cc.EventMouse.UP);
+ var mouseEvent = selfPointer.getMouseEvent(location, pos, cc.EventMouse.UP);
mouseEvent.setButton(event.button);
cc.eventManager.dispatchEvent(mouseEvent);
@@ -481,15 +481,15 @@ cc.inputManager = /** @lends cc.inputManager# */{
}, false);
element.addEventListener("mousemove", function (event) {
- if(prohibition) return;
+ if (prohibition) return;
var pos = selfPointer.getHTMLElementPosition(element);
var location = selfPointer.getPointByEvent(event, pos);
selfPointer.handleTouchesMove([selfPointer.getTouchByXY(location.x, location.y, pos)]);
- var mouseEvent = selfPointer.getMouseEvent(location,pos,cc.EventMouse.MOVE);
- if(selfPointer._mousePressed)
+ var mouseEvent = selfPointer.getMouseEvent(location, pos, cc.EventMouse.MOVE);
+ if (selfPointer._mousePressed)
mouseEvent.setButton(event.button);
else
mouseEvent.setButton(null);
@@ -503,7 +503,7 @@ cc.inputManager = /** @lends cc.inputManager# */{
var pos = selfPointer.getHTMLElementPosition(element);
var location = selfPointer.getPointByEvent(event, pos);
- var mouseEvent = selfPointer.getMouseEvent(location,pos,cc.EventMouse.SCROLL);
+ var mouseEvent = selfPointer.getMouseEvent(location, pos, cc.EventMouse.SCROLL);
mouseEvent.setButton(event.button);
mouseEvent.setScrollData(0, event.wheelDelta);
cc.eventManager.dispatchEvent(mouseEvent);
@@ -513,11 +513,11 @@ cc.inputManager = /** @lends cc.inputManager# */{
}, false);
/* firefox fix */
- element.addEventListener("DOMMouseScroll", function(event) {
+ element.addEventListener("DOMMouseScroll", function (event) {
var pos = selfPointer.getHTMLElementPosition(element);
var location = selfPointer.getPointByEvent(event, pos);
- var mouseEvent = selfPointer.getMouseEvent(location,pos,cc.EventMouse.SCROLL);
+ var mouseEvent = selfPointer.getMouseEvent(location, pos, cc.EventMouse.SCROLL);
mouseEvent.setButton(event.button);
mouseEvent.setScrollData(0, event.detail * -120);
cc.eventManager.dispatchEvent(mouseEvent);
@@ -527,17 +527,17 @@ cc.inputManager = /** @lends cc.inputManager# */{
}, false);
}
- if(window.navigator.msPointerEnabled){
+ if (window.navigator.msPointerEnabled) {
var _pointerEventsMap = {
- "MSPointerDown" : selfPointer.handleTouchesBegin,
- "MSPointerMove" : selfPointer.handleTouchesMove,
- "MSPointerUp" : selfPointer.handleTouchesEnd,
- "MSPointerCancel" : selfPointer.handleTouchesCancel
+ "MSPointerDown": selfPointer.handleTouchesBegin,
+ "MSPointerMove": selfPointer.handleTouchesMove,
+ "MSPointerUp": selfPointer.handleTouchesEnd,
+ "MSPointerCancel": selfPointer.handleTouchesCancel
};
- for(var eventName in _pointerEventsMap){
- (function(_pointerEvent, _touchEvent){
- element.addEventListener(_pointerEvent, function (event){
+ for (var eventName in _pointerEventsMap) {
+ (function (_pointerEvent, _touchEvent) {
+ element.addEventListener(_pointerEvent, function (event) {
var pos = selfPointer.getHTMLElementPosition(element);
pos.left -= document.documentElement.scrollLeft;
pos.top -= document.documentElement.scrollTop;
@@ -549,7 +549,7 @@ cc.inputManager = /** @lends cc.inputManager# */{
}
}
- if(supportTouches) {
+ if (supportTouches) {
//register canvas touch event
element.addEventListener("touchstart", function (event) {
if (!event.changedTouches) return;
@@ -606,16 +606,18 @@ cc.inputManager = /** @lends cc.inputManager# */{
this._isRegisterEvent = true;
},
- _registerKeyboardEvent: function(){},
+ _registerKeyboardEvent: function () {
+ },
- _registerAccelerometerEvent: function(){},
+ _registerAccelerometerEvent: function () {
+ },
/**
* @function
* @param {Number} dt
*/
- update:function(dt){
- if(this._accelCurTime > this._accelInterval){
+ update: function (dt) {
+ if (this._accelCurTime > this._accelInterval) {
this._accelCurTime -= this._accelInterval;
cc.eventManager.dispatchEvent(new cc.EventAcceleration(this._acceleration));
}
diff --git a/cocos2d/core/platform/CCLoaders.js b/cocos2d/core/platform/CCLoaders.js
index 9d1f44041d..69c8e9430f 100644
--- a/cocos2d/core/platform/CCLoaders.js
+++ b/cocos2d/core/platform/CCLoaders.js
@@ -24,35 +24,35 @@
****************************************************************************/
cc._txtLoader = {
- load : function(realUrl, url, res, cb){
+ load: function (realUrl, url, res, cb) {
cc.loader.loadTxt(realUrl, cb);
}
};
cc.loader.register(["txt", "xml", "vsh", "fsh", "atlas"], cc._txtLoader);
cc._jsonLoader = {
- load : function(realUrl, url, res, cb){
+ load: function (realUrl, url, res, cb) {
cc.loader.loadJson(realUrl, cb);
}
};
cc.loader.register(["json", "ExportJson"], cc._jsonLoader);
cc._jsLoader = {
- load : function(realUrl, url, res, cb){
+ load: function (realUrl, url, res, cb) {
cc.loader.loadJs(realUrl, cb);
}
};
cc.loader.register(["js"], cc._jsLoader);
cc._imgLoader = {
- load : function(realUrl, url, res, cb){
+ load: function (realUrl, url, res, cb) {
var callback;
if (cc.loader.isLoading(realUrl)) {
callback = cb;
}
else {
- callback = function(err, img){
- if(err)
+ callback = function (err, img) {
+ if (err)
return cb(err);
cc.loader.cache[url] = img;
cc.textureCache.handleLoadedTexture(url);
@@ -62,18 +62,18 @@ cc._imgLoader = {
cc.loader.loadImg(realUrl, callback);
}
};
-cc.loader.register(["png", "jpg", "bmp","jpeg","gif", "ico", "tiff", "webp"], cc._imgLoader);
+cc.loader.register(["png", "jpg", "bmp", "jpeg", "gif", "ico", "tiff", "webp"], cc._imgLoader);
cc._serverImgLoader = {
- load : function(realUrl, url, res, cb){
+ load: function (realUrl, url, res, cb) {
cc._imgLoader.load(res.src, url, res, cb);
}
};
cc.loader.register(["serverImg"], cc._serverImgLoader);
cc._plistLoader = {
- load : function(realUrl, url, res, cb){
- cc.loader.loadTxt(realUrl, function(err, txt){
- if(err)
+ load: function (realUrl, url, res, cb) {
+ cc.loader.loadTxt(realUrl, function (err, txt) {
+ if (err)
return cb(err);
cb(null, cc.plistParser.parse(txt));
});
@@ -82,31 +82,31 @@ cc._plistLoader = {
cc.loader.register(["plist"], cc._plistLoader);
cc._fontLoader = {
- TYPE : {
- ".eot" : "embedded-opentype",
- ".ttf" : "truetype",
- ".ttc" : "truetype",
- ".woff" : "woff",
- ".svg" : "svg"
+ TYPE: {
+ ".eot": "embedded-opentype",
+ ".ttf": "truetype",
+ ".ttc": "truetype",
+ ".woff": "woff",
+ ".svg": "svg"
},
- _loadFont : function(name, srcs, type){
+ _loadFont: function (name, srcs, type) {
var doc = document, path = cc.path, TYPE = this.TYPE, fontStyle = document.createElement("style");
fontStyle.type = "text/css";
doc.body.appendChild(fontStyle);
var fontStr = "";
- if(isNaN(name - 0))
+ if (isNaN(name - 0))
fontStr += "@font-face { font-family:" + name + "; src:";
else
fontStr += "@font-face { font-family:'" + name + "'; src:";
- if(srcs instanceof Array){
- for(var i = 0, li = srcs.length; i < li; i++){
+ if (srcs instanceof Array) {
+ for (var i = 0, li = srcs.length; i < li; i++) {
var src = srcs[i];
type = path.extname(src).toLowerCase();
fontStr += "url('" + srcs[i] + "') format('" + TYPE[type] + "')";
fontStr += (i === li - 1) ? ";" : ",";
}
- }else{
+ } else {
type = type.toLowerCase();
fontStr += "url('" + srcs + "') format('" + TYPE[type] + "');";
}
@@ -114,7 +114,7 @@ cc._fontLoader = {
//
.
var preloadDiv = document.createElement("div");
- var _divStyle = preloadDiv.style;
+ var _divStyle = preloadDiv.style;
_divStyle.fontFamily = name;
preloadDiv.innerHTML = ".";
_divStyle.position = "absolute";
@@ -122,23 +122,23 @@ cc._fontLoader = {
_divStyle.top = "-100px";
doc.body.appendChild(preloadDiv);
},
- load : function(realUrl, url, res, cb){
+ load: function (realUrl, url, res, cb) {
var self = this;
var type = res.type, name = res.name, srcs = res.srcs;
- if(cc.isString(res)){
+ if (cc.isString(res)) {
type = cc.path.extname(res);
name = cc.path.basename(res, type);
self._loadFont(name, res, type);
- }else{
+ } else {
self._loadFont(name, srcs);
}
- if(document.fonts){
- document.fonts.load("1em " + name).then(function(){
+ if (document.fonts) {
+ document.fonts.load("1em " + name).then(function () {
cb(null, true);
- }, function(err){
+ }, function (err) {
cb(err);
});
- }else{
+ } else {
cb(null, true);
}
}
@@ -146,7 +146,7 @@ cc._fontLoader = {
cc.loader.register(["font", "eot", "ttf", "woff", "svg", "ttc"], cc._fontLoader);
cc._binaryLoader = {
- load : function(realUrl, url, res, cb){
+ load: function (realUrl, url, res, cb) {
cc.loader.loadBinary(realUrl, cb);
}
};
diff --git a/cocos2d/core/platform/CCMacro.js b/cocos2d/core/platform/CCMacro.js
index a9dce0d6ed..e5e4e3c609 100644
--- a/cocos2d/core/platform/CCMacro.js
+++ b/cocos2d/core/platform/CCMacro.js
@@ -245,7 +245,7 @@ cc.FLT_EPSILON = 0.0000001192092896;
* @function
*/
cc.contentScaleFactor = cc.IS_RETINA_DISPLAY_SUPPORTED ? function () {
- return cc.director.getContentScaleFactor();
+ return cc.director._contentScaleFactor;
} : function () {
return 1;
};
@@ -497,6 +497,13 @@ cc.ORIENTATION_LANDSCAPE = 2;
*/
cc.ORIENTATION_AUTO = 3;
+/**
+ * The limit count for concurrency http request, useful in some mobile browsers
+ * @constant
+ * @type Number
+ */
+cc.CONCURRENCY_HTTP_REQUEST_COUNT = cc.sys.isMobile ? 9 : 0;
+
// ------------------- vertex attrib flags -----------------------------
/**
@@ -641,7 +648,7 @@ cc.SHADER_POSITION_TEXTURE = "ShaderPositionTexture";
* @constant
* @type {String}
*/
-cc.SHADER_POSITION_TEXTURE_UCOLOR = "ShaderPositionTexture_uColor";
+cc.SHADER_POSITION_TEXTURE_UCOLOR = "ShaderPositionTextureUColor";
/**
* @constant
* @type {String}
@@ -651,7 +658,7 @@ cc.SHADER_POSITION_TEXTUREA8COLOR = "ShaderPositionTextureA8Color";
* @constant
* @type {String}
*/
-cc.SHADER_POSITION_UCOLOR = "ShaderPosition_uColor";
+cc.SHADER_POSITION_UCOLOR = "ShaderPositionUColor";
/**
* @constant
* @type {String}
diff --git a/cocos2d/core/platform/CCTypes.js b/cocos2d/core/platform/CCTypes.js
index d819a242b9..84bc1ab3fb 100644
--- a/cocos2d/core/platform/CCTypes.js
+++ b/cocos2d/core/platform/CCTypes.js
@@ -34,12 +34,55 @@
* @see cc.color
*/
cc.Color = function (r, g, b, a) {
- this.r = r || 0;
- this.g = g || 0;
- this.b = b || 0;
- this.a = (a == null) ? 255 : a;
+ r = r || 0;
+ g = g || 0;
+ b = b || 0;
+ a = a || 0;
+ this._val = ((r << 24) >>> 0) + (g << 16) + (b << 8) + a;
};
+var _p = cc.Color.prototype;
+_p._getR = function () {
+ return (this._val & 0xff000000) >>> 24;
+};
+_p._setR = function (value) {
+ this._val = (this._val & 0x00ffffff) | ((value << 24) >>> 0);
+};
+_p._getG = function () {
+ return (this._val & 0x00ff0000) >> 16;
+};
+_p._setG = function (value) {
+ this._val = (this._val & 0xff00ffff) | (value << 16);
+};
+_p._getB = function () {
+ return (this._val & 0x0000ff00) >> 8;
+};
+_p._setB = function (value) {
+ this._val = (this._val & 0xffff00ff) | (value << 8);
+};
+
+_p._getA = function () {
+ return this._val & 0x000000ff;
+};
+
+_p.setA = function (value) {
+ this._val = (this._val & 0xffffff00) | value;
+};
+
+
+/** @expose */
+_p.r;
+cc.defineGetterSetter(_p, "r", _p._getR, _p._setR);
+/** @expose */
+_p.g;
+cc.defineGetterSetter(_p, "g", _p._getG, _p._setG);
+/** @expose */
+_p.b;
+cc.defineGetterSetter(_p, "b", _p._getB, _p._setB);
+/** @expose */
+_p.a;
+cc.defineGetterSetter(_p, "a", _p._getA, _p._setA);
+
/**
* Generate a color object based on multiple forms of parameters
* @example
@@ -63,12 +106,12 @@ cc.Color = function (r, g, b, a) {
*/
cc.color = function (r, g, b, a) {
if (r === undefined)
- return {r: 0, g: 0, b: 0, a: 255};
- if (cc.isString(r))
+ return new cc.Color(0, 0, 0, 255);
+ if (typeof r === 'object')
+ return new cc.Color(r.r, r.g, r.b, (r.a == null) ? 255 : r.a);
+ if (typeof r === 'string')
return cc.hexToColor(r);
- if (cc.isObject(r))
- return {r: r.r, g: r.g, b: r.b, a: (r.a == null) ? 255 : r.a};
- return {r: r, g: g, b: b, a: (a == null ? 255 : a)};
+ return new cc.Color(r, g, b, (a == null ? 255 : a));
};
/**
@@ -280,7 +323,7 @@ _p._setTR = function (trValue) {
this._tr._view[0] = trValue.x;
this._tr._view[1] = trValue.y;
};
-_p._getBL = function() {
+_p._getBL = function () {
return this._bl;
};
_p._setBL = function (blValue) {
@@ -354,10 +397,10 @@ cc.V3F_C4B_T2F = function (vertices, colors, texCoords, arrayBuffer, offset) {
new cc.Vertex3F(0, 0, 0, locArrayBuffer, locOffset);
locOffset += cc.Vertex3F.BYTES_PER_ELEMENT;
- this._colors = colors ? new cc.Color(colors.r, colors.g, colors.b, colors.a, locArrayBuffer, locOffset) :
- new cc.Color(0, 0, 0, 0, locArrayBuffer, locOffset);
+ this._colors = colors ? new cc._WebGLColor(colors.r, colors.g, colors.b, colors.a, locArrayBuffer, locOffset) :
+ new cc._WebGLColor(0, 0, 0, 0, locArrayBuffer, locOffset);
- locOffset += cc.Color.BYTES_PER_ELEMENT;
+ locOffset += cc._WebGLColor.BYTES_PER_ELEMENT;
this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, locArrayBuffer, locOffset) :
new cc.Tex2F(0, 0, locArrayBuffer, locOffset);
};
@@ -508,23 +551,31 @@ cc.V3F_C4B_T2F_QuadZero = function () {
*/
cc.V3F_C4B_T2F_QuadCopy = function (sourceQuad) {
if (!sourceQuad)
- return cc.V3F_C4B_T2F_QuadZero();
+ return cc.V3F_C4B_T2F_QuadZero();
//return new cc.V3F_C4B_T2F_Quad(sourceQuad,tl,sourceQuad,bl,sourceQuad.tr,sourceQuad.br,null,0);
var srcTL = sourceQuad.tl, srcBL = sourceQuad.bl, srcTR = sourceQuad.tr, srcBR = sourceQuad.br;
return {
- tl: {vertices: {x: srcTL.vertices.x, y: srcTL.vertices.y, z: srcTL.vertices.z},
+ tl: {
+ vertices: {x: srcTL.vertices.x, y: srcTL.vertices.y, z: srcTL.vertices.z},
colors: {r: srcTL.colors.r, g: srcTL.colors.g, b: srcTL.colors.b, a: srcTL.colors.a},
- texCoords: {u: srcTL.texCoords.u, v: srcTL.texCoords.v}},
- bl: {vertices: {x: srcBL.vertices.x, y: srcBL.vertices.y, z: srcBL.vertices.z},
+ texCoords: {u: srcTL.texCoords.u, v: srcTL.texCoords.v}
+ },
+ bl: {
+ vertices: {x: srcBL.vertices.x, y: srcBL.vertices.y, z: srcBL.vertices.z},
colors: {r: srcBL.colors.r, g: srcBL.colors.g, b: srcBL.colors.b, a: srcBL.colors.a},
- texCoords: {u: srcBL.texCoords.u, v: srcBL.texCoords.v}},
- tr: {vertices: {x: srcTR.vertices.x, y: srcTR.vertices.y, z: srcTR.vertices.z},
+ texCoords: {u: srcBL.texCoords.u, v: srcBL.texCoords.v}
+ },
+ tr: {
+ vertices: {x: srcTR.vertices.x, y: srcTR.vertices.y, z: srcTR.vertices.z},
colors: {r: srcTR.colors.r, g: srcTR.colors.g, b: srcTR.colors.b, a: srcTR.colors.a},
- texCoords: {u: srcTR.texCoords.u, v: srcTR.texCoords.v}},
- br: {vertices: {x: srcBR.vertices.x, y: srcBR.vertices.y, z: srcBR.vertices.z},
+ texCoords: {u: srcTR.texCoords.u, v: srcTR.texCoords.v}
+ },
+ br: {
+ vertices: {x: srcBR.vertices.x, y: srcBR.vertices.y, z: srcBR.vertices.z},
colors: {r: srcBR.colors.r, g: srcBR.colors.g, b: srcBR.colors.b, a: srcBR.colors.a},
- texCoords: {u: srcBR.texCoords.u, v: srcBR.texCoords.v}}
+ texCoords: {u: srcBR.texCoords.u, v: srcBR.texCoords.v}
+ }
};
};
@@ -562,9 +613,9 @@ cc.V2F_C4B_T2F = function (vertices, colors, texCoords, arrayBuffer, offset) {
this._vertices = vertices ? new cc.Vertex2F(vertices.x, vertices.y, locArrayBuffer, locOffset) :
new cc.Vertex2F(0, 0, locArrayBuffer, locOffset);
locOffset += cc.Vertex2F.BYTES_PER_ELEMENT;
- this._colors = colors ? cc.color(colors.r, colors.g, colors.b, colors.a, locArrayBuffer, locOffset) :
- cc.color(0, 0, 0, 0, locArrayBuffer, locOffset);
- locOffset += cc.Color.BYTES_PER_ELEMENT;
+ this._colors = colors ? new cc._WebGLColor(colors.r, colors.g, colors.b, colors.a, locArrayBuffer, locOffset) :
+ new cc._WebGLColor(0, 0, 0, 0, locArrayBuffer, locOffset);
+ locOffset += cc._WebGLColor.BYTES_PER_ELEMENT;
this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, locArrayBuffer, locOffset) :
new cc.Tex2F(0, 0, locArrayBuffer, locOffset);
};
@@ -745,7 +796,7 @@ cc.hexToColor = function (hex) {
var r = c >> 16;
var g = (c >> 8) % 256;
var b = c % 256;
- return cc.color(r, g, b);
+ return new cc.Color(r, g, b);
};
/**
@@ -927,24 +978,203 @@ cc.FontDefinition = function (properties) {
_t.shadowOpacity = 1.0;
//properties mapping:
- if(properties && properties instanceof Object){
- for(var key in properties){
- _t[key] = properties[key];
- }
+ if (properties && properties instanceof Object) {
+ for (var key in properties) {
+ _t[key] = properties[key];
+ }
}
};
/**
* Web ONLY
* */
-cc.FontDefinition.prototype._getCanvasFontStr = function(){
- var lineHeight = !this.lineHeight.charAt ? this.lineHeight+"px" : this.lineHeight;
- return this.fontStyle + " " + this.fontWeight + " " + this.fontSize + "px/"+lineHeight+" '" + this.fontName + "'";
+cc.FontDefinition.prototype._getCanvasFontStr = function () {
+ var lineHeight = !this.lineHeight.charAt ? this.lineHeight + "px" : this.lineHeight;
+ return this.fontStyle + " " + this.fontWeight + " " + this.fontSize + "px/" + lineHeight + " '" + this.fontName + "'";
};
cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
- if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
- cc.assert(cc.isFunction(cc._tmp.PrototypeColor), cc._LogInfos.MissingFile, "CCTypesPropertyDefine.js");
- cc._tmp.PrototypeColor();
- delete cc._tmp.PrototypeColor;
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
+ //redefine Color
+ cc._WebGLColor = function (r, g, b, a, arrayBuffer, offset) {
+ this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc._WebGLColor.BYTES_PER_ELEMENT);
+ this._offset = offset || 0;
+
+ var locArrayBuffer = this._arrayBuffer, locOffset = this._offset;
+ this._view = new Uint8Array(locArrayBuffer, locOffset, 4);
+
+ this._view[0] = r || 0;
+ this._view[1] = g || 0;
+ this._view[2] = b || 0;
+ this._view[3] = (a == null) ? 255 : a;
+
+ if (a === undefined)
+ this.a_undefined = true;
+ };
+ cc._WebGLColor.BYTES_PER_ELEMENT = 4;
+ _p = cc._WebGLColor.prototype;
+ _p._getR = function () {
+ return this._view[0];
+ };
+ _p._setR = function (value) {
+ this._view[0] = value < 0 ? 0 : value;
+ };
+ _p._getG = function () {
+ return this._view[1];
+ };
+ _p._setG = function (value) {
+ this._view[1] = value < 0 ? 0 : value;
+ };
+ _p._getB = function () {
+ return this._view[2];
+ };
+ _p._setB = function (value) {
+ this._view[2] = value < 0 ? 0 : value;
+ };
+ _p._getA = function () {
+ return this._view[3];
+ };
+ _p._setA = function (value) {
+ this._view[3] = value < 0 ? 0 : value;
+ };
+ cc.defineGetterSetter(_p, "r", _p._getR, _p._setR);
+ cc.defineGetterSetter(_p, "g", _p._getG, _p._setG);
+ cc.defineGetterSetter(_p, "b", _p._getB, _p._setB);
+ cc.defineGetterSetter(_p, "a", _p._getA, _p._setA);
}
});
+
+_p = cc.color;
+/**
+ * White color (255, 255, 255, 255)
+ * @returns {cc.Color}
+ * @private
+ */
+_p._getWhite = function () {
+ return cc.color(255, 255, 255);
+};
+
+/**
+ * Yellow color (255, 255, 0, 255)
+ * @returns {cc.Color}
+ * @private
+ */
+_p._getYellow = function () {
+ return cc.color(255, 255, 0);
+};
+
+/**
+ * Blue color (0, 0, 255, 255)
+ * @type {cc.Color}
+ * @private
+ */
+_p._getBlue = function () {
+ return cc.color(0, 0, 255);
+};
+
+/**
+ * Green Color (0, 255, 0, 255)
+ * @type {cc.Color}
+ * @private
+ */
+_p._getGreen = function () {
+ return cc.color(0, 255, 0);
+};
+
+/**
+ * Red Color (255, 0, 0, 255)
+ * @type {cc.Color}
+ * @private
+ */
+_p._getRed = function () {
+ return cc.color(255, 0, 0);
+};
+
+/**
+ * Magenta Color (255, 0, 255, 255)
+ * @type {cc.Color}
+ * @private
+ */
+_p._getMagenta = function () {
+ return cc.color(255, 0, 255);
+};
+
+/**
+ * Black Color (0, 0, 0, 255)
+ * @type {cc.Color}
+ * @private
+ */
+_p._getBlack = function () {
+ return cc.color(0, 0, 0);
+};
+
+/**
+ * Orange Color (255, 127, 0, 255)
+ * @type {_p}
+ * @private
+ */
+_p._getOrange = function () {
+ return cc.color(255, 127, 0);
+};
+
+/**
+ * Gray Color (166, 166, 166, 255)
+ * @type {_p}
+ * @private
+ */
+_p._getGray = function () {
+ return cc.color(166, 166, 166);
+};
+
+/** @expose */
+_p.WHITE;
+cc.defineGetterSetter(_p, "WHITE", _p._getWhite);
+/** @expose */
+_p.YELLOW;
+cc.defineGetterSetter(_p, "YELLOW", _p._getYellow);
+/** @expose */
+_p.BLUE;
+cc.defineGetterSetter(_p, "BLUE", _p._getBlue);
+/** @expose */
+_p.GREEN;
+cc.defineGetterSetter(_p, "GREEN", _p._getGreen);
+/** @expose */
+_p.RED;
+cc.defineGetterSetter(_p, "RED", _p._getRed);
+/** @expose */
+_p.MAGENTA;
+cc.defineGetterSetter(_p, "MAGENTA", _p._getMagenta);
+/** @expose */
+_p.BLACK;
+cc.defineGetterSetter(_p, "BLACK", _p._getBlack);
+/** @expose */
+_p.ORANGE;
+cc.defineGetterSetter(_p, "ORANGE", _p._getOrange);
+/** @expose */
+_p.GRAY;
+cc.defineGetterSetter(_p, "GRAY", _p._getGray);
+
+cc.BlendFunc._disable = function(){
+ return new cc.BlendFunc(cc.ONE, cc.ZERO);
+};
+cc.BlendFunc._alphaPremultiplied = function(){
+ return new cc.BlendFunc(cc.ONE, cc.ONE_MINUS_SRC_ALPHA);
+};
+cc.BlendFunc._alphaNonPremultiplied = function(){
+ return new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA);
+};
+cc.BlendFunc._additive = function(){
+ return new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE);
+};
+
+/** @expose */
+cc.BlendFunc.DISABLE;
+cc.defineGetterSetter(cc.BlendFunc, "DISABLE", cc.BlendFunc._disable);
+/** @expose */
+cc.BlendFunc.ALPHA_PREMULTIPLIED;
+cc.defineGetterSetter(cc.BlendFunc, "ALPHA_PREMULTIPLIED", cc.BlendFunc._alphaPremultiplied);
+/** @expose */
+cc.BlendFunc.ALPHA_NON_PREMULTIPLIED;
+cc.defineGetterSetter(cc.BlendFunc, "ALPHA_NON_PREMULTIPLIED", cc.BlendFunc._alphaNonPremultiplied);
+/** @expose */
+cc.BlendFunc.ADDITIVE;
+cc.defineGetterSetter(cc.BlendFunc, "ADDITIVE", cc.BlendFunc._additive);
diff --git a/cocos2d/core/platform/CCTypesPropertyDefine.js b/cocos2d/core/platform/CCTypesPropertyDefine.js
deleted file mode 100644
index f0be5ac1de..0000000000
--- a/cocos2d/core/platform/CCTypesPropertyDefine.js
+++ /dev/null
@@ -1,165 +0,0 @@
-/****************************************************************************
- Copyright (c) 2008-2010 Ricardo Quesada
- Copyright (c) 2011-2012 cocos2d-x.org
- Copyright (c) 2013-2014 Chukong Technologies Inc.
-
- http://www.cocos2d-x.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-
-cc._tmp.PrototypeColor = function () {
- var _p = cc.color;
- /**
- * White color (255, 255, 255, 255)
- * @returns {cc.Color}
- * @private
- */
- _p._getWhite = function () {
- return _p(255, 255, 255);
- };
-
- /**
- * Yellow color (255, 255, 0, 255)
- * @returns {cc.Color}
- * @private
- */
- _p._getYellow = function () {
- return _p(255, 255, 0);
- };
-
- /**
- * Blue color (0, 0, 255, 255)
- * @type {cc.Color}
- * @private
- */
- _p._getBlue = function () {
- return _p(0, 0, 255);
- };
-
- /**
- * Green Color (0, 255, 0, 255)
- * @type {cc.Color}
- * @private
- */
- _p._getGreen = function () {
- return _p(0, 255, 0);
- };
-
- /**
- * Red Color (255, 0, 0, 255)
- * @type {cc.Color}
- * @private
- */
- _p._getRed = function () {
- return _p(255, 0, 0);
- };
-
- /**
- * Magenta Color (255, 0, 255, 255)
- * @type {cc.Color}
- * @private
- */
- _p._getMagenta = function () {
- return _p(255, 0, 255);
- };
-
- /**
- * Black Color (0, 0, 0, 255)
- * @type {cc.Color}
- * @private
- */
- _p._getBlack = function () {
- return _p(0, 0, 0);
- };
-
- /**
- * Orange Color (255, 127, 0, 255)
- * @type {_p}
- * @private
- */
- _p._getOrange = function () {
- return _p(255, 127, 0);
- };
-
- /**
- * Gray Color (166, 166, 166, 255)
- * @type {_p}
- * @private
- */
- _p._getGray = function () {
- return _p(166, 166, 166);
- };
-
- /** @expose */
- _p.WHITE;
- cc.defineGetterSetter(_p, "WHITE", _p._getWhite);
- /** @expose */
- _p.YELLOW;
- cc.defineGetterSetter(_p, "YELLOW", _p._getYellow);
- /** @expose */
- _p.BLUE;
- cc.defineGetterSetter(_p, "BLUE", _p._getBlue);
- /** @expose */
- _p.GREEN;
- cc.defineGetterSetter(_p, "GREEN", _p._getGreen);
- /** @expose */
- _p.RED;
- cc.defineGetterSetter(_p, "RED", _p._getRed);
- /** @expose */
- _p.MAGENTA;
- cc.defineGetterSetter(_p, "MAGENTA", _p._getMagenta);
- /** @expose */
- _p.BLACK;
- cc.defineGetterSetter(_p, "BLACK", _p._getBlack);
- /** @expose */
- _p.ORANGE;
- cc.defineGetterSetter(_p, "ORANGE", _p._getOrange);
- /** @expose */
- _p.GRAY;
- cc.defineGetterSetter(_p, "GRAY", _p._getGray);
-
- cc.BlendFunc._disable = function(){
- return new cc.BlendFunc(cc.ONE, cc.ZERO);
- };
- cc.BlendFunc._alphaPremultiplied = function(){
- return new cc.BlendFunc(cc.ONE, cc.ONE_MINUS_SRC_ALPHA);
- };
- cc.BlendFunc._alphaNonPremultiplied = function(){
- return new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE_MINUS_SRC_ALPHA);
- };
- cc.BlendFunc._additive = function(){
- return new cc.BlendFunc(cc.SRC_ALPHA, cc.ONE);
- };
-
- /** @expose */
- cc.BlendFunc.DISABLE;
- cc.defineGetterSetter(cc.BlendFunc, "DISABLE", cc.BlendFunc._disable);
- /** @expose */
- cc.BlendFunc.ALPHA_PREMULTIPLIED;
- cc.defineGetterSetter(cc.BlendFunc, "ALPHA_PREMULTIPLIED", cc.BlendFunc._alphaPremultiplied);
- /** @expose */
- cc.BlendFunc.ALPHA_NON_PREMULTIPLIED;
- cc.defineGetterSetter(cc.BlendFunc, "ALPHA_NON_PREMULTIPLIED", cc.BlendFunc._alphaNonPremultiplied);
- /** @expose */
- cc.BlendFunc.ADDITIVE;
- cc.defineGetterSetter(cc.BlendFunc, "ADDITIVE", cc.BlendFunc._additive);
-};
-
-
diff --git a/cocos2d/core/platform/CCTypesWebGL.js b/cocos2d/core/platform/CCTypesWebGL.js
deleted file mode 100644
index bbee8dd1ff..0000000000
--- a/cocos2d/core/platform/CCTypesWebGL.js
+++ /dev/null
@@ -1,130 +0,0 @@
-/****************************************************************************
- Copyright (c) 2008-2010 Ricardo Quesada
- Copyright (c) 2011-2012 cocos2d-x.org
- Copyright (c) 2013-2014 Chukong Technologies Inc.
-
- http://www.cocos2d-x.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-
-var cc = cc || {};
-cc._tmp = cc._tmp || {};
-
-cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
- if (cc._renderType !== cc.game.RENDER_TYPE_WEBGL) {
- return;
- }
-
- //redefine some types with ArrayBuffer for WebGL
- /**
- * @class cc.Color
- * @param {Number} r
- * @param {Number}g
- * @param {Number} b
- * @param {Number} a
- * @param {Array} arrayBuffer
- * @param {Number} offset
- * @returns {cc.Color}
- */
- cc.color = function (r, g, b, a, arrayBuffer, offset) {
- if (r === undefined)
- return new cc.Color(0, 0, 0, 255, arrayBuffer, offset);
- if (cc.isString(r)) {
- var color = cc.hexToColor(r);
- return new cc.Color(color.r, color.g, color.b, color.a);
- }
- if (cc.isObject(r))
- return new cc.Color(r.r, r.g, r.b, r.a, r.arrayBuffer, r.offset);
- return new cc.Color(r, g, b, a, arrayBuffer, offset);
- };
- //redefine cc.Color
- /**
- * @class cc.Color
- * @param {Number} r
- * @param {Number}g
- * @param {Number} b
- * @param {Number} a
- * @param {Array} arrayBuffer
- * @param {Number} offset
- * @constructor
- */
- cc.Color = function (r, g, b, a, arrayBuffer, offset) {
- this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Color.BYTES_PER_ELEMENT);
- this._offset = offset || 0;
-
- var locArrayBuffer = this._arrayBuffer, locOffset = this._offset;
- this._view = new Uint8Array(locArrayBuffer, locOffset, 4);
-
- this._view[0] = r || 0;
- this._view[1] = g || 0;
- this._view[2] = b || 0;
- this._view[3] = (a == null) ? 255 : a;
-
- if (a === undefined)
- this.a_undefined = true;
- };
- /**
- * @constant
- * @type {number}
- */
- cc.Color.BYTES_PER_ELEMENT = 4;
- var _p = cc.Color.prototype;
- _p._getR = function () {
- return this._view[0];
- };
- _p._setR = function (value) {
- this._view[0] = value < 0 ? 0 : value;
- };
- _p._getG = function () {
- return this._view[1];
- };
- _p._setG = function (value) {
- this._view[1] = value < 0 ? 0 : value;
- };
- _p._getB = function () {
- return this._view[2];
- };
- _p._setB = function (value) {
- this._view[2] = value < 0 ? 0 : value;
- };
- _p._getA = function () {
- return this._view[3];
- };
- _p._setA = function (value) {
- this._view[3] = value < 0 ? 0 : value;
- };
- /** @expose */
- _p.r;
- cc.defineGetterSetter(_p, "r", _p._getR, _p._setR);
- /** @expose */
- _p.g;
- cc.defineGetterSetter(_p, "g", _p._getG, _p._setG);
- /** @expose */
- _p.b;
- cc.defineGetterSetter(_p, "b", _p._getB, _p._setB);
- /** @expose */
- _p.a;
- cc.defineGetterSetter(_p, "a", _p._getA, _p._setA);
-
- cc.assert(cc.isFunction(cc._tmp.PrototypeColor), cc._LogInfos.MissingFile, "CCTypesPropertyDefine.js");
- cc._tmp.PrototypeColor();
- delete cc._tmp.PrototypeColor;
-
-});
diff --git a/cocos2d/core/renderer/GlobalVertexBuffer.js b/cocos2d/core/renderer/GlobalVertexBuffer.js
index 4bb7029805..e81c95a133 100644
--- a/cocos2d/core/renderer/GlobalVertexBuffer.js
+++ b/cocos2d/core/renderer/GlobalVertexBuffer.js
@@ -26,13 +26,13 @@ var GlobalVertexBuffer = (function () {
var VERTICES_SIZE = 888;
-var GlobalVertexBuffer = function (gl) {
+var GlobalVertexBuffer = function (gl, byteLength) {
// WebGL buffer
this.gl = gl;
this.vertexBuffer = gl.createBuffer();
this.size = VERTICES_SIZE;
- this.byteLength = VERTICES_SIZE * 4 * cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT;
+ this.byteLength = byteLength || VERTICES_SIZE * 4 * cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT;
// buffer data and views
this.data = new ArrayBuffer(this.byteLength);
@@ -72,14 +72,10 @@ GlobalVertexBuffer.prototype = {
offset = parseInt(key);
available = this._spaces[key];
if (available >= size && this.allocBuffer(offset, size)) {
- return {
- buffer: this,
- offset: offset,
- size: size
- };
+ return offset;
}
}
- return null;
+ return -1;
},
freeBuffer: function (offset, size) {
@@ -121,6 +117,11 @@ GlobalVertexBuffer.prototype = {
}
},
+ updateSubData: function (offset, dataArray) {
+ this.gl.bindBuffer(gl.ARRAY_BUFFER, this.vertexBuffer);
+ this.gl.bufferSubData(gl.ARRAY_BUFFER, offset, dataArray);
+ },
+
destroy: function () {
this.gl.deleteBuffer(this.vertexBuffer);
diff --git a/cocos2d/core/renderer/RendererCanvas.js b/cocos2d/core/renderer/RendererCanvas.js
index 1fb7c09f6f..65d2a8835c 100644
--- a/cocos2d/core/renderer/RendererCanvas.js
+++ b/cocos2d/core/renderer/RendererCanvas.js
@@ -213,7 +213,7 @@ cc.rendererCanvas = {
scaleX = cc.isUndefined(scaleX) ? 1 : scaleX;
scaleY = cc.isUndefined(scaleY) ? 1 : scaleY;
instanceID = instanceID || this._currentID;
- var locCmds = this._cacheToCanvasCmds[instanceID], i, len;
+ var i, locCmds = this._cacheToCanvasCmds[instanceID], len;
ctx.computeRealOffsetY();
for (i = 0, len = locCmds.length; i < len; i++) {
locCmds[i].rendering(ctx, scaleX, scaleY);
diff --git a/cocos2d/core/renderer/RendererWebGL.js b/cocos2d/core/renderer/RendererWebGL.js
index 918c175b71..593a4434ef 100644
--- a/cocos2d/core/renderer/RendererWebGL.js
+++ b/cocos2d/core/renderer/RendererWebGL.js
@@ -108,7 +108,7 @@ return {
childrenOrderDirty: true,
assignedZ: 0,
- assignedZStep: 1/100,
+ assignedZStep: 1 / 100,
_transformNodePool: [], //save nodes transform dirty
_renderCmds: [], //save renderer commands
@@ -126,7 +126,7 @@ return {
this.mat4Identity = new cc.math.Matrix4();
this.mat4Identity.identity();
- initQuadBuffer(2000);
+ initQuadBuffer(500);
if (cc.sys.os === cc.sys.OS_IOS) {
_IS_IOS = true;
}
@@ -236,20 +236,20 @@ return {
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
},
- setDepthTest: function (enable){
+ setDepthTest: function (enable) {
var gl = cc._renderContext;
- if(enable){
+ if (enable) {
gl.clearDepth(1.0);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
}
- else{
+ else {
gl.disable(gl.DEPTH_TEST);
}
},
pushRenderCommand: function (cmd) {
- if(!cmd.needDraw())
+ if (!cmd.needDraw())
return;
if (this._isCacheToBufferOn) {
var currentId = this._currentID, locCmdBuffer = this._cacheToBufferCmds;
@@ -273,9 +273,13 @@ return {
}
// Check batching
- var texture = cmd._node._texture;
- var blendSrc = cmd._node._blendFunc.src;
- var blendDst = cmd._node._blendFunc.dst;
+ var node = cmd._node;
+ var texture = node._texture || (node._spriteFrame ? node._spriteFrame._texture : null);
+ if (!texture) {
+ return;
+ }
+ var blendSrc = node._blendFunc.src;
+ var blendDst = node._blendFunc.dst;
var shader = cmd._shaderProgram;
if (_batchedInfo.texture !== texture ||
_batchedInfo.blendSrc !== blendSrc ||
@@ -369,4 +373,4 @@ return {
_batchedInfo.texture = null;
}
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/core/sprites/CCSprite.js b/cocos2d/core/sprites/CCSprite.js
index 5457a24714..9314462c67 100644
--- a/cocos2d/core/sprites/CCSprite.js
+++ b/cocos2d/core/sprites/CCSprite.js
@@ -84,41 +84,41 @@
* @property {cc.V3F_C4B_T2F_Quad} quad - <@readonly> The quad (tex coords, vertex coords and color) information.
*/
cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
- dirty:false,
- atlasIndex:0,
- textureAtlas:null,
+ dirty: false,
+ atlasIndex: 0,
+ textureAtlas: null,
- _batchNode:null,
- _recursiveDirty:null, //Whether all of the sprite's children needs to be updated
- _hasChildren:null, //Whether the sprite contains children
- _shouldBeHidden:false, //should not be drawn because one of the ancestors is not visible
- _transformToBatch:null,
+ _batchNode: null,
+ _recursiveDirty: null, //Whether all of the sprite's children needs to be updated
+ _hasChildren: null, //Whether the sprite contains children
+ _shouldBeHidden: false, //should not be drawn because one of the ancestors is not visible
+ _transformToBatch: null,
//
// Data used when the sprite is self-rendered
//
- _blendFunc:null, //It's required for CCTextureProtocol inheritance
- _texture:null, //cc.Texture2D object that is used to render the sprite
+ _blendFunc: null, //It's required for CCTextureProtocol inheritance
+ _texture: null, //cc.Texture2D object that is used to render the sprite
//
// Shared data
//
// texture
- _rect:null, //Rectangle of cc.Texture2D
- _rectRotated:false, //Whether the texture is rotated
+ _rect: null, //Rectangle of cc.Texture2D
+ _rectRotated: false, //Whether the texture is rotated
// Offset Position (used by Zwoptex)
- _offsetPosition:null, // absolute
- _unflippedOffsetPositionFromCenter:null,
+ _offsetPosition: null, // absolute
+ _unflippedOffsetPositionFromCenter: null,
- _opacityModifyRGB:false,
+ _opacityModifyRGB: false,
// image is flipped
- _flippedX:false, //Whether the sprite is flipped horizontally or not.
- _flippedY:false, //Whether the sprite is flipped vertically or not.
+ _flippedX: false, //Whether the sprite is flipped horizontally or not.
+ _flippedY: false, //Whether the sprite is flipped vertically or not.
- _textureLoaded:false,
- _className:"Sprite",
+ _textureLoaded: false,
+ _className: "Sprite",
ctor: function (fileName, rect, rotated) {
var self = this;
@@ -140,7 +140,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Returns whether the texture have been loaded
* @returns {boolean}
*/
- textureLoaded:function(){
+ textureLoaded: function () {
return this._textureLoaded;
},
@@ -150,7 +150,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* @param {Object} target
* @deprecated since 3.1, please use addEventListener instead
*/
- addLoadedEventListener:function(callback, target){
+ addLoadedEventListener: function (callback, target) {
this.addEventListener("load", callback, target);
},
@@ -158,7 +158,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Returns whether or not the Sprite needs to be updated in the Atlas
* @return {Boolean} True if the sprite needs to be updated in the Atlas, false otherwise.
*/
- isDirty:function () {
+ isDirty: function () {
return this.dirty;
},
@@ -166,7 +166,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Makes the sprite to be updated in the Atlas.
* @param {Boolean} bDirty
*/
- setDirty:function (bDirty) {
+ setDirty: function (bDirty) {
this.dirty = bDirty;
},
@@ -174,7 +174,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Returns whether or not the texture rectangle is rotated.
* @return {Boolean}
*/
- isTextureRectRotated:function () {
+ isTextureRectRotated: function () {
return this._rectRotated;
},
@@ -182,7 +182,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Returns the index used on the TextureAtlas.
* @return {Number}
*/
- getAtlasIndex:function () {
+ getAtlasIndex: function () {
return this.atlasIndex;
},
@@ -191,7 +191,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* @warning Don't modify this value unless you know what you are doing
* @param {Number} atlasIndex
*/
- setAtlasIndex:function (atlasIndex) {
+ setAtlasIndex: function (atlasIndex) {
this.atlasIndex = atlasIndex;
},
@@ -199,7 +199,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Returns the rect of the cc.Sprite in points
* @return {cc.Rect}
*/
- getTextureRect:function () {
+ getTextureRect: function () {
return cc.rect(this._rect);
},
@@ -207,7 +207,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Returns the weak reference of the cc.TextureAtlas when the sprite is rendered using via cc.SpriteBatchNode
* @return {cc.TextureAtlas}
*/
- getTextureAtlas:function () {
+ getTextureAtlas: function () {
return this.textureAtlas;
},
@@ -215,7 +215,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Sets the weak reference of the cc.TextureAtlas when the sprite is rendered using via cc.SpriteBatchNode
* @param {cc.TextureAtlas} textureAtlas
*/
- setTextureAtlas:function (textureAtlas) {
+ setTextureAtlas: function (textureAtlas) {
this.textureAtlas = textureAtlas;
},
@@ -223,7 +223,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Returns the offset position of the sprite. Calculated automatically by editors like Zwoptex.
* @return {cc.Point}
*/
- getOffsetPosition:function () {
+ getOffsetPosition: function () {
return cc.p(this._offsetPosition);
},
@@ -238,7 +238,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Returns the blend function
* @return {cc.BlendFunc}
*/
- getBlendFunc:function () {
+ getBlendFunc: function () {
return this._blendFunc;
},
@@ -248,7 +248,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* @param {cc.SpriteFrame} spriteFrame A CCSpriteFrame object. It should includes a valid texture and a rect
* @return {Boolean} true if the sprite is initialized properly, false otherwise.
*/
- initWithSpriteFrame:function (spriteFrame) {
+ initWithSpriteFrame: function (spriteFrame) {
cc.assert(spriteFrame, cc._LogInfos.Sprite_initWithSpriteFrame);
return this.setSpriteFrame(spriteFrame);
},
@@ -264,7 +264,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* var sprite = new cc.Sprite();
* sprite.initWithSpriteFrameName("grossini_dance_01.png");
*/
- initWithSpriteFrameName:function (spriteFrameName) {
+ initWithSpriteFrameName: function (spriteFrameName) {
cc.assert(spriteFrameName, cc._LogInfos.Sprite_initWithSpriteFrameName);
var frame = cc.spriteFrameCache.getSpriteFrame(spriteFrameName);
cc.assert(frame, spriteFrameName + cc._LogInfos.Sprite_initWithSpriteFrameName1);
@@ -275,7 +275,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Tell the sprite to use batch node render.
* @param {cc.SpriteBatchNode} batchNode
*/
- useBatchNode:function (batchNode) {
+ useBatchNode: function (batchNode) {
this.textureAtlas = batchNode.getTextureAtlas(); // weak ref
this._batchNode = batchNode;
},
@@ -290,7 +290,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
*
* @param {cc.Rect} rect
*/
- setVertexRect:function (rect) {
+ setVertexRect: function (rect) {
var locRect = this._rect;
locRect.x = rect.x;
locRect.y = rect.y;
@@ -303,7 +303,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Sort all children of this sprite node.
* @override
*/
- sortAllChildren:function () {
+ sortAllChildren: function () {
if (this._reorderChildDirty) {
var _children = this._children;
@@ -325,9 +325,9 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* @param {Number} zOrder
* @override
*/
- reorderChild:function (child, zOrder) {
+ reorderChild: function (child, zOrder) {
cc.assert(child, cc._LogInfos.Sprite_reorderChild_2);
- if(this._children.indexOf(child) === -1){
+ if (this._children.indexOf(child) === -1) {
cc.log(cc._LogInfos.Sprite_reorderChild);
return;
}
@@ -348,28 +348,18 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* @param cleanup whether or not cleanup all running actions
* @override
*/
- removeChild:function (child, cleanup) {
+ removeChild: function (child, cleanup) {
if (this._batchNode)
this._batchNode.removeSpriteFromAtlas(child);
cc.Node.prototype.removeChild.call(this, child, cleanup);
},
- /**
- * Sets whether the sprite is visible or not.
- * @param {Boolean} visible
- * @override
- */
- setVisible:function (visible) {
- cc.Node.prototype.setVisible.call(this, visible);
- this._renderCmd.setDirtyRecursively(true);
- },
-
/**
* Removes all children from the container.
* @param cleanup whether or not cleanup all running actions
* @override
*/
- removeAllChildren:function (cleanup) {
+ removeAllChildren: function (cleanup) {
var locChildren = this._children, locBatchNode = this._batchNode;
if (locBatchNode && locChildren != null) {
for (var i = 0, len = locChildren.length; i < len; i++)
@@ -389,8 +379,8 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* @param {Boolean} relative
* @override
*/
- ignoreAnchorPointForPosition:function (relative) {
- if(this._batchNode){
+ ignoreAnchorPointForPosition: function (relative) {
+ if (this._batchNode) {
cc.log(cc._LogInfos.Sprite_ignoreAnchorPointForPosition);
return;
}
@@ -401,7 +391,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Sets whether the sprite should be flipped horizontally or not.
* @param {Boolean} flippedX true if the sprite should be flipped horizontally, false otherwise.
*/
- setFlippedX:function (flippedX) {
+ setFlippedX: function (flippedX) {
if (this._flippedX !== flippedX) {
this._flippedX = flippedX;
this.setTextureRect(this._rect, this._rectRotated, this._contentSize);
@@ -413,7 +403,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Sets whether the sprite should be flipped vertically or not.
* @param {Boolean} flippedY true if the sprite should be flipped vertically, false otherwise.
*/
- setFlippedY:function (flippedY) {
+ setFlippedY: function (flippedY) {
if (this._flippedY !== flippedY) {
this._flippedY = flippedY;
this.setTextureRect(this._rect, this._rectRotated, this._contentSize);
@@ -431,7 +421,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* sprite.setScaleX(sprite.getScaleX() * -1);
* @return {Boolean} true if the sprite is flipped horizontally, false otherwise.
*/
- isFlippedX:function () {
+ isFlippedX: function () {
return this._flippedX;
},
@@ -445,7 +435,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* sprite.setScaleY(sprite.getScaleY() * -1);
* @return {Boolean} true if the sprite is flipped vertically, false otherwise.
*/
- isFlippedY:function () {
+ isFlippedY: function () {
return this._flippedY;
},
@@ -468,7 +458,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Returns whether opacity modify color or not.
* @return {Boolean}
*/
- isOpacityModifyRGB:function () {
+ isOpacityModifyRGB: function () {
return this._opacityModifyRGB;
},
@@ -480,16 +470,16 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* @param {String} animationName
* @param {Number} frameIndex
*/
- setDisplayFrameWithAnimationName:function (animationName, frameIndex) {
+ setDisplayFrameWithAnimationName: function (animationName, frameIndex) {
cc.assert(animationName, cc._LogInfos.Sprite_setDisplayFrameWithAnimationName_3);
var cache = cc.animationCache.getAnimation(animationName);
- if(!cache){
+ if (!cache) {
cc.log(cc._LogInfos.Sprite_setDisplayFrameWithAnimationName);
return;
}
var animFrame = cache.getFrames()[frameIndex];
- if(!animFrame){
+ if (!animFrame) {
cc.log(cc._LogInfos.Sprite_setDisplayFrameWithAnimationName_2);
return;
}
@@ -500,11 +490,11 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Returns the batch node object if this sprite is rendered by cc.SpriteBatchNode
* @returns {cc.SpriteBatchNode|null} The cc.SpriteBatchNode object if this sprite is rendered by cc.SpriteBatchNode, null if the sprite isn't used batch node.
*/
- getBatchNode:function () {
+ getBatchNode: function () {
return this._batchNode;
},
- _setReorderChildDirtyRecursively:function () {
+ _setReorderChildDirtyRecursively: function () {
//only set parents flag the first time
if (!this._reorderChildDirty) {
this._reorderChildDirty = true;
@@ -521,14 +511,14 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Returns the texture of the sprite node
* @returns {cc.Texture2D}
*/
- getTexture:function () {
+ getTexture: function () {
return this._texture;
},
_softInit: function (fileName, rect, rotated) {
if (fileName === undefined)
cc.Sprite.prototype.init.call(this);
- else if (cc.isString(fileName)) {
+ else if (typeof fileName === 'string') {
if (fileName[0] === "#") {
// Init with a sprite frame name
var frameName = fileName.substr(1, fileName.length - 1);
@@ -562,7 +552,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Returns the quad (tex coords, vertex coords and color) information.
* @return {cc.V3F_C4B_T2F_Quad|null} Returns a cc.V3F_C4B_T2F_Quad object when render mode is WebGL, returns null when render mode is Canvas.
*/
- getQuad:function () {
+ getQuad: function () {
return null;
},
@@ -632,7 +622,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* @param {cc.Rect} rect The rectangle assigned the content area from texture.
* @return {Boolean} true if the sprite is initialized properly, false otherwise.
*/
- initWithFile:function (filename, rect) {
+ initWithFile: function (filename, rect) {
cc.assert(filename, cc._LogInfos.Sprite_initWithFile);
var tex = cc.textureCache.getTextureForKey(filename);
@@ -768,7 +758,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
if (tag == null)
tag = child.tag;
- if(this._renderCmd._setBatchNodeForAddChild(child)){
+ if (this._renderCmd._setBatchNodeForAddChild(child)) {
//cc.Node already sets isReorderChildDirty_ so this needs to be after batchNode check
cc.Node.prototype.addChild.call(this, child, localZOrder, tag);
this._hasChildren = true;
@@ -783,7 +773,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
*/
setSpriteFrame: function (newFrame) {
var _t = this;
- if(cc.isString(newFrame)){
+ if (typeof newFrame === 'string') {
newFrame = cc.spriteFrameCache.getSpriteFrame(newFrame);
cc.assert(newFrame, cc._LogInfos.Sprite_setSpriteFrame)
}
@@ -819,7 +809,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* @param {cc.SpriteFrame|String} newFrame
* @deprecated
*/
- setDisplayFrame: function(newFrame){
+ setDisplayFrame: function (newFrame) {
cc.log(cc._LogInfos.Sprite_setDisplayFrame);
this.setSpriteFrame(newFrame);
},
@@ -830,7 +820,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* @param {cc.SpriteFrame} frame
* @return {Boolean}
*/
- isFrameDisplayed: function(frame){
+ isFrameDisplayed: function (frame) {
return this._renderCmd.isFrameDisplayed(frame);
},
@@ -865,7 +855,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* batch.addChild(sprite);
* layer.addChild(batch);
*/
- setBatchNode:function (spriteBatchNode) {
+ setBatchNode: function (spriteBatchNode) {
var _t = this;
_t._batchNode = spriteBatchNode; // weak reference
@@ -889,13 +879,13 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* @param {cc.Texture2D|String} texture
*/
setTexture: function (texture) {
- if(!texture)
+ if (!texture)
return this._renderCmd._setTexture(null);
//CCSprite.cpp 327 and 338
- var isFileName = cc.isString(texture);
+ var isFileName = (typeof texture === 'string');
- if(isFileName)
+ if (isFileName)
texture = cc.textureCache.addImage(texture);
this._loader.clear();
@@ -915,7 +905,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
this._textureLoaded = true;
},
- _changeRectWithTexture: function(texture){
+ _changeRectWithTexture: function (texture) {
var contentSize = texture._contentSize;
var rect = cc.rect(
0, 0,
@@ -924,8 +914,8 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
this.setTextureRect(rect);
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return new cc.Sprite.CanvasRenderCmd(this);
else
return new cc.Sprite.WebGLRenderCmd(this);
@@ -1011,4 +1001,4 @@ delete cc._tmp.PrototypeSprite;
item.source.removeEventListener('load', item.listener, item.target);
}
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/core/sprites/CCSpriteBatchNode.js b/cocos2d/core/sprites/CCSpriteBatchNode.js
index d8044af074..3abd61fb4c 100644
--- a/cocos2d/core/sprites/CCSpriteBatchNode.js
+++ b/cocos2d/core/sprites/CCSpriteBatchNode.js
@@ -69,7 +69,7 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{
texture2D = cc.textureCache.getTextureForKey(fileImage);
if (!texture2D)
texture2D = cc.textureCache.addImage(fileImage);
- }else if (fileImage instanceof cc.Texture2D)
+ } else if (fileImage instanceof cc.Texture2D)
texture2D = fileImage;
texture2D && this.initWithTexture(texture2D);
@@ -105,7 +105,8 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{
* @param {cc.TextureAtlas} textureAtlas
* @deprecated since v3.12
*/
- setTextureAtlas: function (textureAtlas) {},
+ setTextureAtlas: function (textureAtlas) {
+ },
/**
* Return Descendants of cc.SpriteBatchNode
@@ -156,7 +157,8 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{
* Do nothing
* @deprecated since v3.12
*/
- increaseAtlasCapacity: function () {},
+ increaseAtlasCapacity: function () {
+ },
/**
* Removes a child given a certain index. It will also cleanup the running actions depending on the cleanup parameter.
@@ -243,7 +245,7 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{
* @return {cc.BlendFunc}
*/
getBlendFunc: function () {
- return new cc.BlendFunc(this._blendFunc.src,this._blendFunc.dst);
+ return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst);
},
/**
@@ -301,8 +303,8 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{
*/
appendChild: function (sprite) {
this.sortAllChildren();
- var lastLocalZOrder = this._children[this._children.length-1]._localZOrder;
- this.addChild(sprite. lastLocalZOrder + 1);
+ var lastLocalZOrder = this._children[this._children.length - 1]._localZOrder;
+ this.addChild(sprite.lastLocalZOrder + 1);
},
/**
@@ -342,18 +344,18 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{
* @function
* @param {cc.Texture2D} texture
*/
- setTexture: function(texture){
+ setTexture: function (texture) {
this._texture = texture;
if (texture._textureLoaded) {
- var children = this._children, i, len = children.length;
+ var i, children = this._children, len = children.length;
for (i = 0; i < len; ++i) {
children[i].setTexture(texture);
}
}
else {
- texture.addEventListener("load", function(){
- var children = this._children, i, len = children.length;
+ texture.addEventListener("load", function () {
+ var i, children = this._children, len = children.length;
for (i = 0; i < len; ++i) {
children[i].setTexture(texture);
}
@@ -363,7 +365,7 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{
setShaderProgram: function (newShaderProgram) {
this._renderCmd.setShaderProgram(newShaderProgram);
- var children = this._children, i, len = children.length;
+ var i, children = this._children, len = children.length;
for (i = 0; i < len; ++i) {
children[i].setShaderProgram(newShaderProgram);
}
@@ -380,7 +382,7 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{
addChild: function (child, zOrder, tag) {
cc.assert(child !== undefined, cc._LogInfos.CCSpriteBatchNode_addChild_3);
- if(!this._isValidChild(child))
+ if (!this._isValidChild(child))
return;
zOrder = (zOrder === undefined) ? child.zIndex : zOrder;
diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js
index ba289bfcf1..eaa8bbfecb 100644
--- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js
+++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js
@@ -22,9 +22,9 @@
THE SOFTWARE.
****************************************************************************/
-(function() {
+(function () {
cc.Sprite.CanvasRenderCmd = function (renderable) {
- cc.Node.CanvasRenderCmd.call(this, renderable);
+ this._rootCtor(renderable);
this._needDraw = true;
this._textureCoord = {
renderX: 0, //the x of texture coordinate for render, when texture tinted, its value doesn't equal x.
@@ -43,15 +43,17 @@
var proto = cc.Sprite.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
proto.constructor = cc.Sprite.CanvasRenderCmd;
+ proto._spriteCmdCtor = cc.Sprite.CanvasRenderCmd;
- proto.setDirtyRecursively = function (value) {};
+ proto.setDirtyRecursively = function (value) {
+ };
proto._setTexture = function (texture) {
var node = this._node;
if (node._texture !== texture) {
if (texture) {
node._textureLoaded = texture._textureLoaded;
- }else{
+ } else {
node._textureLoaded = false;
}
node._texture = texture;
@@ -107,7 +109,7 @@
var locTextureCoord = this._textureCoord, alpha = (this._displayedOpacity / 255);
var texture = this._textureToRender || node._texture;
- if ((texture && (locTextureCoord.width === 0 || locTextureCoord.height === 0|| !texture._textureLoaded)) || alpha === 0)
+ if ((texture && (locTextureCoord.width === 0 || locTextureCoord.height === 0 || !texture._textureLoaded)) || alpha === 0)
return;
var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
@@ -118,7 +120,7 @@
wrapper.setCompositeOperation(this._blendFuncStr);
wrapper.setGlobalAlpha(alpha);
- if(node._flippedX || node._flippedY)
+ if (node._flippedX || node._flippedY)
wrapper.save();
if (node._flippedX) {
locX = -locX - locWidth;
@@ -133,7 +135,7 @@
if (this._colorized) {
sx = 0;
sy = 0;
- }else{
+ } else {
sx = locTextureCoord.renderX;
sy = locTextureCoord.renderY;
}
@@ -163,22 +165,22 @@
context.fillRect(x, y, contentSize.width * scaleX, contentSize.height * scaleY);
}
}
- if(node._flippedX || node._flippedY)
+ if (node._flippedX || node._flippedY)
wrapper.restore();
cc.g_NumberOfDraws++;
};
- proto._updateColor = function(){
+ proto._updateColor = function () {
var node = this._node;
var texture = node._texture, rect = this._textureCoord;
var dColor = this._displayedColor;
- if(texture){
- if(dColor.r !== 255 || dColor.g !== 255 || dColor.b !== 255){
+ if (texture) {
+ if (dColor.r !== 255 || dColor.g !== 255 || dColor.b !== 255) {
this._textureToRender = texture._generateColorTexture(dColor.r, dColor.g, dColor.b, rect);
this._colorized = true;
- }else if(texture){
+ } else if (texture) {
this._textureToRender = texture;
this._colorized = false;
}
@@ -232,14 +234,14 @@
if (!rect)
return texture;
- counterclockwise = counterclockwise == null? true: counterclockwise; // texture package is counterclockwise, spine is clockwise
+ counterclockwise = counterclockwise == null ? true : counterclockwise; // texture package is counterclockwise, spine is clockwise
var nCanvas = document.createElement("canvas");
nCanvas.width = rect.width;
nCanvas.height = rect.height;
var ctx = nCanvas.getContext("2d");
ctx.translate(nCanvas.width / 2, nCanvas.height / 2);
- if(counterclockwise)
+ if (counterclockwise)
ctx.rotate(-1.5707963267948966);
else
ctx.rotate(1.5707963267948966);
diff --git a/cocos2d/core/sprites/CCSpriteFrame.js b/cocos2d/core/sprites/CCSpriteFrame.js
index ccb7f9a86e..4879225a53 100644
--- a/cocos2d/core/sprites/CCSpriteFrame.js
+++ b/cocos2d/core/sprites/CCSpriteFrame.js
@@ -52,18 +52,18 @@
* var frame2 = new cc.SpriteFrame(texture, cc.rect(0,0,90,128),false,0,cc.size(90,128));
*/
cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
- _offset:null,
- _originalSize:null,
- _rectInPixels:null,
- _rotated:false,
- _rect:null,
- _offsetInPixels:null,
- _originalSizeInPixels:null,
- _texture:null,
- _textureFilename:"",
- _textureLoaded:false,
-
- ctor:function (filename, rect, rotated, offset, originalSize) {
+ _offset: null,
+ _originalSize: null,
+ _rectInPixels: null,
+ _rotated: false,
+ _rect: null,
+ _offsetInPixels: null,
+ _originalSizeInPixels: null,
+ _texture: null,
+ _textureFilename: "",
+ _textureLoaded: false,
+
+ ctor: function (filename, rect, rotated, offset, originalSize) {
this._offset = cc.p(0, 0);
this._offsetInPixels = cc.p(0, 0);
this._originalSize = cc.size(0, 0);
@@ -73,11 +73,11 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
this._texture = null;
this._textureLoaded = false;
- if(filename !== undefined && rect !== undefined ){
- if(rotated === undefined || offset === undefined || originalSize === undefined)
+ if (filename !== undefined && rect !== undefined) {
+ if (rotated === undefined || offset === undefined || originalSize === undefined)
this.initWithTexture(filename, rect);
else
- this.initWithTexture(filename, rect, rotated, offset, originalSize)
+ this.initWithTexture(filename, rect, rotated, offset, originalSize);
}
},
@@ -85,7 +85,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Returns whether the texture have been loaded
* @returns {boolean}
*/
- textureLoaded:function(){
+ textureLoaded: function () {
return this._textureLoaded;
},
@@ -95,7 +95,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* @param {Object} target
* @deprecated since 3.1, please use addEventListener instead
*/
- addLoadedEventListener:function(callback, target){
+ addLoadedEventListener: function (callback, target) {
this.addEventListener("load", callback, target);
},
@@ -103,7 +103,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Gets the rect of the frame in the texture
* @return {cc.Rect}
*/
- getRectInPixels:function () {
+ getRectInPixels: function () {
var locRectInPixels = this._rectInPixels;
return cc.rect(locRectInPixels.x, locRectInPixels.y, locRectInPixels.width, locRectInPixels.height);
},
@@ -112,9 +112,9 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Sets the rect of the frame in the texture
* @param {cc.Rect} rectInPixels
*/
- setRectInPixels:function (rectInPixels) {
- if (!this._rectInPixels){
- this._rectInPixels = cc.rect(0,0,0,0);
+ setRectInPixels: function (rectInPixels) {
+ if (!this._rectInPixels) {
+ this._rectInPixels = cc.rect(0, 0, 0, 0);
}
this._rectInPixels.x = rectInPixels.x;
this._rectInPixels.y = rectInPixels.y;
@@ -127,7 +127,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Returns whether the sprite frame is rotated in the texture.
* @return {Boolean}
*/
- isRotated:function () {
+ isRotated: function () {
return this._rotated;
},
@@ -135,7 +135,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Set whether the sprite frame is rotated in the texture.
* @param {Boolean} bRotated
*/
- setRotated:function (bRotated) {
+ setRotated: function (bRotated) {
this._rotated = bRotated;
},
@@ -143,7 +143,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Returns the rect of the sprite frame in the texture
* @return {cc.Rect}
*/
- getRect:function () {
+ getRect: function () {
var locRect = this._rect;
return cc.rect(locRect.x, locRect.y, locRect.width, locRect.height);
},
@@ -152,9 +152,9 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Sets the rect of the sprite frame in the texture
* @param {cc.Rect} rect
*/
- setRect:function (rect) {
- if (!this._rect){
- this._rect = cc.rect(0,0,0,0);
+ setRect: function (rect) {
+ if (!this._rect) {
+ this._rect = cc.rect(0, 0, 0, 0);
}
this._rect.x = rect.x;
this._rect.y = rect.y;
@@ -167,7 +167,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Returns the offset of the sprite frame in the texture in pixel
* @return {cc.Point}
*/
- getOffsetInPixels:function () {
+ getOffsetInPixels: function () {
return cc.p(this._offsetInPixels);
},
@@ -175,7 +175,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Sets the offset of the sprite frame in the texture in pixel
* @param {cc.Point} offsetInPixels
*/
- setOffsetInPixels:function (offsetInPixels) {
+ setOffsetInPixels: function (offsetInPixels) {
this._offsetInPixels.x = offsetInPixels.x;
this._offsetInPixels.y = offsetInPixels.y;
cc._pointPixelsToPointsOut(this._offsetInPixels, this._offset);
@@ -185,7 +185,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Returns the original size of the trimmed image
* @return {cc.Size}
*/
- getOriginalSizeInPixels:function () {
+ getOriginalSizeInPixels: function () {
return cc.size(this._originalSizeInPixels);
},
@@ -193,7 +193,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Sets the original size of the trimmed image
* @param {cc.Size} sizeInPixels
*/
- setOriginalSizeInPixels:function (sizeInPixels) {
+ setOriginalSizeInPixels: function (sizeInPixels) {
this._originalSizeInPixels.width = sizeInPixels.width;
this._originalSizeInPixels.height = sizeInPixels.height;
},
@@ -202,7 +202,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Returns the original size of the trimmed image
* @return {cc.Size}
*/
- getOriginalSize:function () {
+ getOriginalSize: function () {
return cc.size(this._originalSize);
},
@@ -210,7 +210,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Sets the original size of the trimmed image
* @param {cc.Size} sizeInPixels
*/
- setOriginalSize:function (sizeInPixels) {
+ setOriginalSize: function (sizeInPixels) {
this._originalSize.width = sizeInPixels.width;
this._originalSize.height = sizeInPixels.height;
},
@@ -219,7 +219,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Returns the texture of the frame
* @return {cc.Texture2D}
*/
- getTexture:function () {
+ getTexture: function () {
if (this._texture)
return this._texture;
if (this._textureFilename !== "") {
@@ -235,15 +235,15 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Sets the texture of the frame, the texture is retained automatically
* @param {cc.Texture2D} texture
*/
- setTexture:function (texture) {
+ setTexture: function (texture) {
if (this._texture !== texture) {
var locLoaded = texture.isLoaded();
this._textureLoaded = locLoaded;
this._texture = texture;
- if(!locLoaded){
- texture.addEventListener("load", function(sender){
+ if (!locLoaded) {
+ texture.addEventListener("load", function (sender) {
this._textureLoaded = true;
- if(this._rotated && cc._renderType === cc.game.RENDER_TYPE_CANVAS){
+ if (this._rotated && cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
var tempElement = sender.getHtmlElementObj();
tempElement = cc.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, this.getRect());
var tempTexture = new cc.Texture2D();
@@ -255,15 +255,15 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
this.setRect(cc.rect(0, 0, rect.width, rect.height));
}
var locRect = this._rect;
- if(locRect.width === 0 && locRect.height === 0){
+ if (locRect.width === 0 && locRect.height === 0) {
var w = sender.width, h = sender.height;
this._rect.width = w;
this._rect.height = h;
this._rectInPixels = cc.rectPointsToPixels(this._rect);
this._originalSizeInPixels.width = this._rectInPixels.width;
this._originalSizeInPixels.height = this._rectInPixels.height;
- this._originalSize.width = w;
- this._originalSize.height = h;
+ this._originalSize.width = w;
+ this._originalSize.height = h;
}
//dispatch 'load' event of cc.SpriteFrame
this.dispatchEvent("load");
@@ -276,7 +276,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Returns the offset of the frame in the texture
* @return {cc.Point}
*/
- getOffset:function () {
+ getOffset: function () {
return cc.p(this._offset);
},
@@ -284,7 +284,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Sets the offset of the frame in the texture
* @param {cc.Point} offsets
*/
- setOffset:function (offsets) {
+ setOffset: function (offsets) {
this._offset.x = offsets.x;
this._offset.y = offsets.y;
},
@@ -293,7 +293,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Clone the sprite frame
* @returns {SpriteFrame}
*/
- clone: function(){
+ clone: function () {
var frame = new cc.SpriteFrame();
frame.initWithTexture(this._textureFilename, this._rectInPixels, this._rotated, this._offsetInPixels, this._originalSizeInPixels);
frame.setTexture(this._texture);
@@ -304,7 +304,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Copy the sprite frame
* @return {cc.SpriteFrame}
*/
- copyWithZone:function () {
+ copyWithZone: function () {
var copy = new cc.SpriteFrame();
copy.initWithTexture(this._textureFilename, this._rectInPixels, this._rotated, this._offsetInPixels, this._originalSizeInPixels);
copy.setTexture(this._texture);
@@ -315,7 +315,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Copy the sprite frame
* @returns {cc.SpriteFrame}
*/
- copy:function () {
+ copy: function () {
return this.copyWithZone();
},
@@ -329,18 +329,18 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* @param {cc.Size} [originalSize=rect.size]
* @return {Boolean}
*/
- initWithTexture:function (texture, rect, rotated, offset, originalSize) {
- if(arguments.length === 2)
+ initWithTexture: function (texture, rect, rotated, offset, originalSize) {
+ if (arguments.length === 2)
rect = cc.rectPointsToPixels(rect);
offset = offset || cc.p(0, 0);
originalSize = originalSize || rect;
rotated = rotated || false;
- if (cc.isString(texture)){
+ if (typeof texture === 'string') {
this._texture = null;
this._textureFilename = texture;
- } else if (texture instanceof cc.Texture2D){
+ } else if (texture instanceof cc.Texture2D) {
this.setTexture(texture);
}
@@ -349,19 +349,19 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
this._rectInPixels = rect;
this._rect = cc.rectPixelsToPoints(rect);
- if(texture && texture.url && texture.isLoaded()) {
+ if (texture && texture.url && texture.isLoaded()) {
var _x, _y;
- if(rotated){
+ if (rotated) {
_x = rect.x + rect.height;
_y = rect.y + rect.width;
- }else{
+ } else {
_x = rect.x + rect.width;
_y = rect.y + rect.height;
}
- if(_x > texture.getPixelsWide()){
+ if (_x > texture.getPixelsWide()) {
cc.error(cc._LogInfos.RectWidth, texture.url);
}
- if(_y > texture.getPixelsHigh()){
+ if (_y > texture.getPixelsHigh()) {
cc.error(cc._LogInfos.RectHeight, texture.url);
}
}
@@ -394,7 +394,7 @@ cc.EventHelper.prototype.apply(cc.SpriteFrame.prototype);
* @return {cc.SpriteFrame}
*/
cc.SpriteFrame.create = function (filename, rect, rotated, offset, originalSize) {
- return new cc.SpriteFrame(filename,rect,rotated,offset,originalSize);
+ return new cc.SpriteFrame(filename, rect, rotated, offset, originalSize);
};
/**
diff --git a/cocos2d/core/sprites/CCSpriteFrameCache.js b/cocos2d/core/sprites/CCSpriteFrameCache.js
index d6955477c1..d8df34823b 100644
--- a/cocos2d/core/sprites/CCSpriteFrameCache.js
+++ b/cocos2d/core/sprites/CCSpriteFrameCache.js
@@ -36,38 +36,38 @@
* @name cc.spriteFrameCache
*/
cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
- _CCNS_REG1 : /^\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*$/,
- _CCNS_REG2 : /^\s*\{\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*,\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*\}\s*$/,
+ _CCNS_REG1: /^\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*$/,
+ _CCNS_REG2: /^\s*\{\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*,\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*\}\s*$/,
_spriteFrames: {},
_spriteFramesAliases: {},
- _frameConfigCache : {},
+ _frameConfigCache: {},
- _rectFromString : function (content) {
+ _rectFromString: function (content) {
var result = this._CCNS_REG2.exec(content);
- if(!result) return cc.rect(0, 0, 0, 0);
+ if (!result) return cc.rect(0, 0, 0, 0);
return cc.rect(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]), parseFloat(result[4]));
},
- _pointFromString : function (content) {
+ _pointFromString: function (content) {
var result = this._CCNS_REG1.exec(content);
- if(!result) return cc.p(0,0);
+ if (!result) return cc.p(0, 0);
return cc.p(parseFloat(result[1]), parseFloat(result[2]));
},
- _sizeFromString : function (content) {
+ _sizeFromString: function (content) {
var result = this._CCNS_REG1.exec(content);
- if(!result) return cc.size(0, 0);
+ if (!result) return cc.size(0, 0);
return cc.size(parseFloat(result[1]), parseFloat(result[2]));
},
- _getFrameConfig : function(url){
+ _getFrameConfig: function (url) {
var dict = cc.loader.getRes(url);
cc.assert(dict, cc._LogInfos.spriteFrameCache__getFrameConfig_2, url);
cc.loader.release(url);//release it in loader
- if(dict._inited){
+ if (dict._inited) {
this._frameConfigCache[url] = dict;
return dict;
}
@@ -75,24 +75,24 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
return this._frameConfigCache[url];
},
- _getFrameConfigByJsonObject: function(url, jsonObject) {
+ _getFrameConfigByJsonObject: function (url, jsonObject) {
cc.assert(jsonObject, cc._LogInfos.spriteFrameCache__getFrameConfig_2, url);
this._frameConfigCache[url] = this._parseFrameConfig(jsonObject);
return this._frameConfigCache[url];
},
- _parseFrameConfig: function(dict) {
+ _parseFrameConfig: function (dict) {
var tempFrames = dict["frames"], tempMeta = dict["metadata"] || dict["meta"];
var frames = {}, meta = {};
var format = 0;
- if(tempMeta){//init meta
+ if (tempMeta) {//init meta
var tmpFormat = tempMeta["format"];
format = (tmpFormat.length <= 1) ? parseInt(tmpFormat) : tmpFormat;
meta.image = tempMeta["textureFileName"] || tempMeta["textureFileName"] || tempMeta["image"];
}
for (var key in tempFrames) {
var frameDict = tempFrames[key];
- if(!frameDict) continue;
+ if (!frameDict) continue;
var tempFrame = {};
if (format == 0) {
@@ -140,9 +140,9 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
},
// Adds multiple Sprite Frames from a json object. it uses for local web view app.
- _addSpriteFramesByObject: function(url, jsonObject, texture) {
+ _addSpriteFramesByObject: function (url, jsonObject, texture) {
cc.assert(url, cc._LogInfos.spriteFrameCache_addSpriteFrames_2);
- if(!jsonObject || !jsonObject["frames"])
+ if (!jsonObject || !jsonObject["frames"])
return;
var frameConfig = this._frameConfigCache[url] || this._getFrameConfigByJsonObject(url, jsonObject);
@@ -150,16 +150,16 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
this._createSpriteFrames(url, frameConfig, texture);
},
- _createSpriteFrames: function(url, frameConfig, texture) {
+ _createSpriteFrames: function (url, frameConfig, texture) {
var frames = frameConfig.frames, meta = frameConfig.meta;
- if(!texture){
+ if (!texture) {
var texturePath = cc.path.changeBasename(url, meta.image || ".png");
texture = cc.textureCache.addImage(texturePath);
- }else if(texture instanceof cc.Texture2D){
+ } else if (texture instanceof cc.Texture2D) {
//do nothing
- }else if(cc.isString(texture)){//string
+ } else if (cc.isString(texture)) {//string
texture = cc.textureCache.addImage(texture);
- }else{
+ } else {
cc.assert(0, cc._LogInfos.spriteFrameCache_addSpriteFrames_3);
}
@@ -171,8 +171,8 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
if (!spriteFrame) {
spriteFrame = new cc.SpriteFrame(texture, frame.rect, frame.rotated, frame.offset, frame.size);
var aliases = frame.aliases;
- if(aliases){//set aliases
- for(var i = 0, li = aliases.length; i < li; i++){
+ if (aliases) {//set aliases
+ for (var i = 0, li = aliases.length; i < li; i++) {
var alias = aliases[i];
if (spAliases[alias])
cc.log(cc._LogInfos.spriteFrameCache_addSpriteFrames, alias);
@@ -190,6 +190,7 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
tempTexture.initWithElement(tempElement);
tempTexture.handleLoadedTexture();
spriteFrame.setTexture(tempTexture);
+ spriteFrame.setRotated(false);
var rect = spriteFrame._rect;
spriteFrame.setRect(cc.rect(0, 0, rect.width, rect.height));
@@ -218,7 +219,7 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
//Is it a SpriteFrame plist?
var dict = this._frameConfigCache[url] || cc.loader.getRes(url);
- if(!dict || !dict["frames"])
+ if (!dict || !dict["frames"])
return;
var frameConfig = this._frameConfigCache[url] || this._getFrameConfig(url);
@@ -294,13 +295,13 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
removeSpriteFramesFromFile: function (url) {
var self = this, spriteFrames = self._spriteFrames,
aliases = self._spriteFramesAliases, cfg = self._frameConfigCache[url];
- if(!cfg) return;
+ if (!cfg) return;
var frames = cfg.frames;
for (var key in frames) {
if (spriteFrames[key]) {
delete(spriteFrames[key]);
for (var alias in aliases) {//remove alias
- if(aliases[alias] === key) delete aliases[alias];
+ if (aliases[alias] === key) delete aliases[alias];
}
}
}
@@ -320,7 +321,7 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
if (frame && (frame.getTexture() === texture)) {
delete(spriteFrames[key]);
for (var alias in aliases) {//remove alias
- if(aliases[alias] === key) delete aliases[alias];
+ if (aliases[alias] === key) delete aliases[alias];
}
}
}
@@ -345,15 +346,15 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
var key = self._spriteFramesAliases[name];
if (key) {
frame = self._spriteFrames[key.toString()];
- if(!frame) delete self._spriteFramesAliases[name];
+ if (!frame) delete self._spriteFramesAliases[name];
}
}
return frame;
},
- _clear: function () {
- this._spriteFrames = {};
- this._spriteFramesAliases = {};
- this._frameConfigCache = {};
- }
+ _clear: function () {
+ this._spriteFrames = {};
+ this._spriteFramesAliases = {};
+ this._frameConfigCache = {};
+ }
};
diff --git a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js
index 3d02a422ce..f10773b1d7 100644
--- a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js
+++ b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js
@@ -23,10 +23,10 @@
****************************************************************************/
//Sprite's WebGL render command
-(function() {
+(function () {
cc.Sprite.WebGLRenderCmd = function (renderable) {
- cc.Node.WebGLRenderCmd.call(this, renderable);
+ this._rootCtor(renderable);
this._needDraw = true;
this._vertices = [
@@ -44,10 +44,12 @@
var proto = cc.Sprite.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
proto.constructor = cc.Sprite.WebGLRenderCmd;
+ proto._spriteCmdCtor = cc.Sprite.WebGLRenderCmd;
- proto.updateBlendFunc = function (blendFunc) {};
+ proto.updateBlendFunc = function (blendFunc) {
+ };
- proto.setDirtyFlag = function(dirtyFlag){
+ proto.setDirtyFlag = function (dirtyFlag) {
cc.Node.WebGLRenderCmd.prototype.setDirtyFlag.call(this, dirtyFlag);
this._dirty = true;
};
@@ -201,7 +203,8 @@
}
};
- proto._setColorDirty = function () {};
+ proto._setColorDirty = function () {
+ };
proto._updateBlendFunc = function () {
if (this._batchNode) {
@@ -229,12 +232,12 @@
var node = this._node;
// If batchnode, then texture id should be the same
if (node._batchNode) {
- if(node._batchNode.texture !== texture){
+ if (node._batchNode.texture !== texture) {
cc.log(cc._LogInfos.Sprite_setTexture);
return;
}
} else {
- if(node._texture !== texture){
+ if (node._texture !== texture) {
node._textureLoaded = texture ? texture._textureLoaded : false;
node._texture = texture;
this._updateBlendFunc();
@@ -272,17 +275,20 @@
var node = this._node,
lx = node._offsetPosition.x, rx = lx + node._rect.width,
by = node._offsetPosition.y, ty = by + node._rect.height,
- wt = this._worldTransform;
+ wt = this._worldTransform,
+ wtx = wt.tx, wty = wt.ty,
+ lxa = lx * wt.a, lxb = lx * wt.b, rxa = rx * wt.a, rxb = rx * wt.b,
+ tyc = ty * wt.c, tyd = ty * wt.d, byc = by * wt.c, byd = by * wt.d;
var vertices = this._vertices;
- vertices[0].x = lx * wt.a + ty * wt.c + wt.tx; // tl
- vertices[0].y = lx * wt.b + ty * wt.d + wt.ty;
- vertices[1].x = lx * wt.a + by * wt.c + wt.tx; // bl
- vertices[1].y = lx * wt.b + by * wt.d + wt.ty;
- vertices[2].x = rx * wt.a + ty * wt.c + wt.tx; // tr
- vertices[2].y = rx * wt.b + ty * wt.d + wt.ty;
- vertices[3].x = rx * wt.a + by * wt.c + wt.tx; // br
- vertices[3].y = rx * wt.b + by * wt.d + wt.ty;
+ vertices[0].x = lxa + tyc + wtx; // tl
+ vertices[0].y = lxb + tyd + wty;
+ vertices[1].x = lxa + byc + wtx; // bl
+ vertices[1].y = lxb + byd + wty;
+ vertices[2].x = rxa + tyc + wtx; // tr
+ vertices[2].y = rxb + tyd + wty;
+ vertices[3].x = rxa + byc + wtx; // br
+ vertices[3].y = rxb + byd + wty;
};
proto.needDraw = function () {
@@ -306,7 +312,7 @@
g *= a;
b *= a;
}
- this._color[0] = ((opacity<<24) | (b<<16) | (g<<8) | r);
+ this._color[0] = ((opacity << 24) | (b << 16) | (g << 8) | r);
var z = node._vertexZ;
var vertices = this._vertices;
@@ -324,4 +330,4 @@
return len;
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js
index b772532ae1..41b1726168 100644
--- a/cocos2d/core/textures/CCTexture2D.js
+++ b/cocos2d/core/textures/CCTexture2D.js
@@ -98,7 +98,7 @@ cc.PVRHaveAlphaPremultiplied_ = false;
cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
- if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
var proto = {
_contentSize: null,
@@ -112,6 +112,8 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
this._textureLoaded = false;
this._htmlElementObj = null;
this._pattern = "";
+ this._pixelsWide = 0;
+ this._pixelsHigh = 0;
},
/**
@@ -119,7 +121,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
* @return {Number}
*/
getPixelsWide: function () {
- return this._contentSize.width;
+ return this._pixelsWide;
},
/**
@@ -127,7 +129,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
* @return {Number}
*/
getPixelsHigh: function () {
- return this._contentSize.height;
+ return this._pixelsHigh;
},
/**
@@ -162,8 +164,8 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
if (!element)
return;
this._htmlElementObj = element;
- this._contentSize.width = element.width;
- this._contentSize.height = element.height;
+ this._pixelsWide = this._contentSize.width = element.width;
+ this._pixelsHigh = this._contentSize.height = element.height;
this._textureLoaded = true;
},
@@ -196,8 +198,8 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
}
var locElement = self._htmlElementObj;
- self._contentSize.width = locElement.width;
- self._contentSize.height = locElement.height;
+ self._pixelsWide = self._contentSize.width = locElement.width;
+ self._pixelsHigh = self._contentSize.height = locElement.height;
//dispatch load event to listener.
self.dispatchEvent("load");
@@ -322,20 +324,20 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
},
setTexParameters: function (texParams, magFilter, wrapS, wrapT) {
- if(magFilter !== undefined)
+ if (magFilter !== undefined)
texParams = {minFilter: texParams, magFilter: magFilter, wrapS: wrapS, wrapT: wrapT};
- if(texParams.wrapS === cc.REPEAT && texParams.wrapT === cc.REPEAT){
+ if (texParams.wrapS === cc.REPEAT && texParams.wrapT === cc.REPEAT) {
this._pattern = "repeat";
return;
}
- if(texParams.wrapS === cc.REPEAT ){
+ if (texParams.wrapS === cc.REPEAT) {
this._pattern = "repeat-x";
return;
}
- if(texParams.wrapT === cc.REPEAT){
+ if (texParams.wrapT === cc.REPEAT) {
this._pattern = "repeat-y";
return;
}
@@ -383,8 +385,9 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
this.removeEventTarget("load", target);
},
- _generateColorTexture: function(){/*overide*/},
- _generateTextureCacheForColor: function(){
+ _generateColorTexture: function () {/*overide*/
+ },
+ _generateTextureCacheForColor: function () {
if (this.channelCache)
return this.channelCache;
@@ -403,23 +406,23 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
_grayElementObj: null,
_backupElement: null,
_isGray: false,
- _switchToGray: function(toGray){
- if(!this._textureLoaded || this._isGray === toGray)
+ _switchToGray: function (toGray) {
+ if (!this._textureLoaded || this._isGray === toGray)
return;
this._isGray = toGray;
- if(this._isGray){
+ if (this._isGray) {
this._backupElement = this._htmlElementObj;
- if(!this._grayElementObj)
+ if (!this._grayElementObj)
this._grayElementObj = cc.Texture2D._generateGrayTexture(this._htmlElementObj);
this._htmlElementObj = this._grayElementObj;
} else {
- if(this._backupElement !== null)
+ if (this._backupElement !== null)
this._htmlElementObj = this._backupElement;
}
}
};
- var renderToCache = function(image, cache){
+ var renderToCache = function (image, cache) {
var w = image.width;
var h = image.height;
@@ -443,7 +446,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
var to = ctx.getImageData(0, 0, w, h);
var data = to.data;
for (var i = 0; i < pixels.length; i += 4) {
- data[i ] = (rgbI === 0) ? pixels[i ] : 0;
+ data[i] = (rgbI === 0) ? pixels[i] : 0;
data[i + 1] = (rgbI === 1) ? pixels[i + 1] : 0;
data[i + 2] = (rgbI === 2) ? pixels[i + 2] : 0;
data[i + 3] = pixels[i + 3];
@@ -454,17 +457,17 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
};
//change color function
- if(cc.sys._supportCanvasNewBlendModes){
+ if (cc.sys._supportCanvasNewBlendModes) {
//multiply mode
//Primary afferent, Draw a new texture based on rect
- proto._generateColorTexture = function(r, g, b, rect, canvas){
+ proto._generateColorTexture = function (r, g, b, rect, canvas) {
var onlyCanvas = false;
- if(canvas)
+ if (canvas)
onlyCanvas = true;
else
canvas = document.createElement("canvas");
var textureImage = this._htmlElementObj;
- if(!rect)
+ if (!rect)
rect = cc.rect(0, 0, textureImage.width, textureImage.height);
canvas.width = rect.width;
@@ -472,7 +475,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
var context = canvas.getContext("2d");
context.globalCompositeOperation = "source-over";
- context.fillStyle = "rgb(" + (r|0) + "," + (g|0) + "," + (b|0) + ")";
+ context.fillStyle = "rgb(" + (r | 0) + "," + (g | 0) + "," + (b | 0) + ")";
context.fillRect(0, 0, rect.width, rect.height);
context.globalCompositeOperation = "multiply";
context.drawImage(
@@ -486,28 +489,28 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
rect.x, rect.y, rect.width, rect.height,
0, 0, rect.width, rect.height
);
- if(onlyCanvas)
+ if (onlyCanvas)
return canvas;
var newTexture = new cc.Texture2D();
newTexture.initWithElement(canvas);
newTexture.handleLoadedTexture();
return newTexture;
};
- }else{
+ } else {
//Four color map overlay
- proto._generateColorTexture = function(r, g, b, rect, canvas){
+ proto._generateColorTexture = function (r, g, b, rect, canvas) {
var onlyCanvas = false;
- if(canvas)
+ if (canvas)
onlyCanvas = true;
else
canvas = document.createElement("canvas");
var textureImage = this._htmlElementObj;
- if(!rect)
+ if (!rect)
rect = cc.rect(0, 0, textureImage.width, textureImage.height);
var x, y, w, h;
x = rect.x; y = rect.y; w = rect.width; h = rect.height;
- if(!w || !h)
+ if (!w || !h)
return;
canvas.width = w;
@@ -545,7 +548,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
0, 0, w, h
);
}
- if(onlyCanvas)
+ if (onlyCanvas)
return canvas;
var newTexture = new cc.Texture2D();
@@ -578,7 +581,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
*/
cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */proto);
- cc.Texture2D._generateGrayTexture = function(texture, rect, renderCanvas){
+ cc.Texture2D._generateGrayTexture = function (texture, rect, renderCanvas) {
if (texture === null)
return null;
renderCanvas = renderCanvas || document.createElement("canvas");
diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js
index dcef25dc39..19cac4b9fa 100644
--- a/cocos2d/core/textures/CCTextureCache.js
+++ b/cocos2d/core/textures/CCTextureCache.js
@@ -108,7 +108,7 @@ cc.textureCache = /** @lends cc.textureCache# */{
* //example
* var key = cc.textureCache.getTextureForKey("hello.png");
*/
- getTextureForKey: function(textureKeyName){
+ getTextureForKey: function (textureKeyName) {
return this._textures[textureKeyName] || this._textures[cc.loader._getAliase(textureKeyName)];
},
@@ -343,13 +343,12 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
//remove judge
var tex = locTexs[url] || locTexs[cc.loader._getAliase(url)];
if (tex) {
- if(tex.isLoaded()) {
+ if (tex.isLoaded()) {
cb && cb.call(target, tex);
return tex;
}
- else
- {
- tex.addEventListener("load", function(){
+ else {
+ tex.addEventListener("load", function () {
cb && cb.call(target, tex);
}, target);
return tex;
diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js
index cf6a2555de..bcec5bfb53 100644
--- a/cocos2d/core/textures/TexturesWebGL.js
+++ b/cocos2d/core/textures/TexturesWebGL.js
@@ -324,10 +324,10 @@ cc._tmp.WebGLTexture2D = function () {
drawAtPoint: function (point) {
var self = this;
var coordinates = [
- 0.0, self.maxT,
- self.maxS, self.maxT,
- 0.0, 0.0,
- self.maxS, 0.0 ],
+ 0.0, self.maxT,
+ self.maxS, self.maxT,
+ 0.0, 0.0,
+ self.maxS, 0.0],
gl = cc._renderContext;
var width = self._pixelsWide * self.maxS,
@@ -337,7 +337,7 @@ cc._tmp.WebGLTexture2D = function () {
point.x, point.y, 0.0,
width + point.x, point.y, 0.0,
point.x, height + point.y, 0.0,
- width + point.x, height + point.y, 0.0 ];
+ width + point.x, height + point.y, 0.0];
self._shaderProgram.use();
self._shaderProgram.setUniformsForBuiltins();
@@ -364,10 +364,10 @@ cc._tmp.WebGLTexture2D = function () {
0.0, 0.0,
self.maxS, 0.0];
- var vertices = [ rect.x, rect.y, /*0.0,*/
+ var vertices = [rect.x, rect.y, /*0.0,*/
rect.x + rect.width, rect.y, /*0.0,*/
rect.x, rect.y + rect.height, /*0.0,*/
- rect.x + rect.width, rect.y + rect.height /*0.0*/ ];
+ rect.x + rect.width, rect.y + rect.height /*0.0*/];
self._shaderProgram.use();
self._shaderProgram.setUniformsForBuiltins();
@@ -451,9 +451,9 @@ cc._tmp.WebGLTexture2D = function () {
handleLoadedTexture: function (premultiplied) {
var self = this;
premultiplied =
- (premultiplied !== undefined)
- ? premultiplied
- : self._hasPremultipliedAlpha;
+ (premultiplied !== undefined)
+ ? premultiplied
+ : self._hasPremultipliedAlpha;
// Not sure about this ! Some texture need to be updated even after loaded
if (!cc.game._rendererInitialized)
return;
@@ -471,7 +471,7 @@ cc._tmp.WebGLTexture2D = function () {
cc.glBindTexture2D(self);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
- if(premultiplied)
+ if (premultiplied)
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
// Specify OpenGL texture image
@@ -484,7 +484,7 @@ cc._tmp.WebGLTexture2D = function () {
self.shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE);
cc.glBindTexture2D(null);
- if(premultiplied)
+ if (premultiplied)
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
var pixelsWide = self._htmlElementObj.width;
@@ -575,7 +575,7 @@ cc._tmp.WebGLTexture2D = function () {
var _t = this;
var gl = cc._renderContext;
- if(magFilter !== undefined)
+ if (magFilter !== undefined)
texParams = {minFilter: texParams, magFilter: magFilter, wrapS: wrapS, wrapT: wrapT};
cc.assert((_t._pixelsWide === cc.NextPOT(_t._pixelsWide) && _t._pixelsHigh === cc.NextPOT(_t._pixelsHigh)) ||
@@ -664,7 +664,6 @@ cc._tmp.WebGLTexture2D = function () {
var imageSize = cc.size(uiImage.getWidth(), uiImage.getHeight());
var pixelFormat = tex2d.defaultPixelFormat;
var bpp = uiImage.getBitsPerComponent();
- var i;
// compute pixel format
if (!hasAlpha) {
@@ -677,7 +676,7 @@ cc._tmp.WebGLTexture2D = function () {
}
// Repack the pixel data into the right format
- var length = width * height;
+ var i, length = width * height;
if (pixelFormat === tex2d.PIXEL_FORMAT_RGB565) {
if (hasAlpha) {
@@ -688,8 +687,8 @@ cc._tmp.WebGLTexture2D = function () {
for (i = 0; i < length; ++i) {
tempData[i] =
((((inPixel32[i] >> 0) & 0xFF) >> 3) << 11) | // R
- ((((inPixel32[i] >> 8) & 0xFF) >> 2) << 5) | // G
- ((((inPixel32[i] >> 16) & 0xFF) >> 3) << 0); // B
+ ((((inPixel32[i] >> 8) & 0xFF) >> 2) << 5) | // G
+ ((((inPixel32[i] >> 16) & 0xFF) >> 3) << 0); // B
}
} else {
// Convert "RRRRRRRRRGGGGGGGGBBBBBBBB" to "RRRRRGGGGGGBBBBB"
@@ -699,8 +698,8 @@ cc._tmp.WebGLTexture2D = function () {
for (i = 0; i < length; ++i) {
tempData[i] =
(((inPixel8[i] & 0xFF) >> 3) << 11) | // R
- (((inPixel8[i] & 0xFF) >> 2) << 5) | // G
- (((inPixel8[i] & 0xFF) >> 3) << 0); // B
+ (((inPixel8[i] & 0xFF) >> 2) << 5) | // G
+ (((inPixel8[i] & 0xFF) >> 3) << 0); // B
}
}
} else if (pixelFormat === tex2d.PIXEL_FORMAT_RGBA4444) {
@@ -711,9 +710,9 @@ cc._tmp.WebGLTexture2D = function () {
for (i = 0; i < length; ++i) {
tempData[i] =
((((inPixel32[i] >> 0) & 0xFF) >> 4) << 12) | // R
- ((((inPixel32[i] >> 8) & 0xFF) >> 4) << 8) | // G
- ((((inPixel32[i] >> 16) & 0xFF) >> 4) << 4) | // B
- ((((inPixel32[i] >> 24) & 0xFF) >> 4) << 0); // A
+ ((((inPixel32[i] >> 8) & 0xFF) >> 4) << 8) | // G
+ ((((inPixel32[i] >> 16) & 0xFF) >> 4) << 4) | // B
+ ((((inPixel32[i] >> 24) & 0xFF) >> 4) << 0); // A
}
} else if (pixelFormat === tex2d.PIXEL_FORMAT_RGB5A1) {
// Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGBBBBBA"
@@ -723,9 +722,9 @@ cc._tmp.WebGLTexture2D = function () {
for (i = 0; i < length; ++i) {
tempData[i] =
((((inPixel32[i] >> 0) & 0xFF) >> 3) << 11) | // R
- ((((inPixel32[i] >> 8) & 0xFF) >> 3) << 6) | // G
- ((((inPixel32[i] >> 16) & 0xFF) >> 3) << 1) | // B
- ((((inPixel32[i] >> 24) & 0xFF) >> 7) << 0); // A
+ ((((inPixel32[i] >> 8) & 0xFF) >> 3) << 6) | // G
+ ((((inPixel32[i] >> 16) & 0xFF) >> 3) << 1) | // B
+ ((((inPixel32[i] >> 24) & 0xFF) >> 7) << 0); // A
}
} else if (pixelFormat === tex2d.PIXEL_FORMAT_A8) {
// Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "AAAAAAAA"
@@ -827,7 +826,7 @@ cc._tmp.WebGLTextureAtlas = function () {
// XXX: update is done in draw... perhaps it should be done in a timer
gl.bindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer);
- if (_t.dirty){
+ if (_t.dirty) {
gl.bufferData(gl.ARRAY_BUFFER, _t._quadsArrayBuffer, gl.DYNAMIC_DRAW);
_t.dirty = false;
}
@@ -899,14 +898,13 @@ cc._tmp.WebGLTextureCache = function () {
}
var tex = locTexs[url] || locTexs[cc.loader._getAliase(url)];
if (tex) {
- if(tex.isLoaded()) {
+ if (tex.isLoaded()) {
cb && cb.call(target, tex);
return tex;
}
- else
- {
- tex.addEventListener("load", function(){
- cb && cb.call(target, tex);
+ else {
+ tex.addEventListener("load", function () {
+ cb && cb.call(target, tex);
}, target);
return tex;
}
diff --git a/cocos2d/core/utils/BinaryLoader.js b/cocos2d/core/utils/BinaryLoader.js
index b95b93e799..7127b1279c 100644
--- a/cocos2d/core/utils/BinaryLoader.js
+++ b/cocos2d/core/utils/BinaryLoader.js
@@ -77,6 +77,7 @@ cc.loader._str2Uint8Array = function (strData) {
cc.loader.loadBinarySync = function (url) {
var self = this;
var req = this.getXMLHttpRequest();
+ req.timeout = 0;
var errInfo = "load " + url + " failed!";
req.open('GET', url, false);
var arrayInfo = null;
diff --git a/cocos2d/core/utils/CCProfiler.js b/cocos2d/core/utils/CCProfiler.js
index 704f8697eb..5d314f629d 100644
--- a/cocos2d/core/utils/CCProfiler.js
+++ b/cocos2d/core/utils/CCProfiler.js
@@ -2,9 +2,9 @@ cc.profiler = (function () {
var _showFPS = false;
var _inited = false;
var _frames = 0, _frameRate = 0, _lastSPF = 0, _accumDt = 0;
- var _afterVisitListener = null,
- _FPSLabel = document.createElement('div'),
- _SPFLabel = document.createElement('div'),
+ var _afterVisitListener = null,
+ _FPSLabel = document.createElement('div'),
+ _SPFLabel = document.createElement('div'),
_drawsLabel = document.createElement('div'),
_fps = document.createElement('div');
@@ -21,7 +21,7 @@ cc.profiler = (function () {
_fps.style.bottom = cc.DIRECTOR_STATS_POSITION.y + '0px';
_fps.style.left = cc.DIRECTOR_STATS_POSITION.x + 'px';
_fps.style.width = '45px';
- _fps.style.height = '60px';
+ _fps.style.height = '80px';
var labels = [_drawsLabel, _SPFLabel, _FPSLabel];
for (var i = 0; i < 3; ++i) {
@@ -47,7 +47,7 @@ cc.profiler = (function () {
if (_analyseCount >= _levelDetCycle) {
average = _totalFPS / _levelDetCycle;
- for (i = lastId; i >0; i--) {
+ for (i = lastId; i > 0; i--) {
ratio = _fpsCount[i] / _levelDetCycle;
// Determined level
if (ratio >= LEVEL_DET_FACTOR && average >= LEVELS[i]) {
@@ -85,8 +85,9 @@ cc.profiler = (function () {
}
if (_showFPS) {
+ var mode = cc._renderType === cc.game.RENDER_TYPE_CANVAS ? "\n canvas" : "\n webgl";
_SPFLabel.innerText = _lastSPF.toFixed(3);
- _FPSLabel.innerText = _frameRate.toFixed(1);
+ _FPSLabel.innerText = _frameRate.toFixed(1).toString() + mode;
_drawsLabel.innerText = (0 | cc.g_NumberOfDraws).toString();
}
}
@@ -147,4 +148,4 @@ cc.profiler = (function () {
};
return profiler;
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/effects/CCGrid.js b/cocos2d/effects/CCGrid.js
index 8c5cd08a22..f6459a2269 100644
--- a/cocos2d/effects/CCGrid.js
+++ b/cocos2d/effects/CCGrid.js
@@ -31,18 +31,18 @@
* @extends cc.Class
*/
cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
- _active:false,
- _reuseGrid:0,
- _gridSize:null,
- _gridRect:null,
- _texture:null,
- _step:null,
- _grabber:null,
- _isTextureFlipped:false,
- _shaderProgram:null,
- _directorProjection:0,
-
- _dirty:false,
+ _active: false,
+ _reuseGrid: 0,
+ _gridSize: null,
+ _gridRect: null,
+ _texture: null,
+ _step: null,
+ _grabber: null,
+ _isTextureFlipped: false,
+ _shaderProgram: null,
+ _directorProjection: 0,
+
+ _dirty: false,
/**
* create one cc.GridBase Object
@@ -52,21 +52,21 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* @param {Boolean} [flipped=]
* @param {cc.Rect} rect
*/
- ctor:function (gridSize, texture, flipped, rect) {
+ ctor: function (gridSize, texture, flipped, rect) {
cc.sys._checkWebGLRenderMode();
- this._active=false;
- this._reuseGrid=0;
- this._gridSize=null;
- this._gridRect=new cc.rect();
- this._texture=null;
+ this._active = false;
+ this._reuseGrid = 0;
+ this._gridSize = null;
+ this._gridRect = new cc.rect();
+ this._texture = null;
this._step = cc.p(0, 0);
- this._grabber=null;
- this._isTextureFlipped=false;
- this._shaderProgram=null;
- this._directorProjection=0;
- this._dirty=false;
+ this._grabber = null;
+ this._isTextureFlipped = false;
+ this._shaderProgram = null;
+ this._directorProjection = 0;
+ this._dirty = false;
- if(gridSize !== undefined)
+ if (gridSize !== undefined)
this.initWithSize(gridSize, texture, flipped, rect);
},
@@ -74,7 +74,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* whether or not the grid is active
* @return {Boolean}
*/
- isActive:function () {
+ isActive: function () {
return this._active;
},
@@ -82,7 +82,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* whether or not the grid is active
* @param {Number} active
*/
- setActive:function (active) {
+ setActive: function (active) {
this._active = active;
if (!active) {
var director = cc.director;
@@ -95,14 +95,14 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* get number of times that the grid will be reused
* @return {Number}
*/
- getReuseGrid:function () {
+ getReuseGrid: function () {
return this._reuseGrid;
},
/**
* set number of times that the grid will be reused
* @param reuseGrid
*/
- setReuseGrid:function (reuseGrid) {
+ setReuseGrid: function (reuseGrid) {
this._reuseGrid = reuseGrid;
},
@@ -110,7 +110,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* get size of the grid
* @return {cc.Size}
*/
- getGridSize:function () {
+ getGridSize: function () {
return cc.size(this._gridSize.width, this._gridSize.height);
},
@@ -118,7 +118,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* set size of the grid
* @param {cc.Size} gridSize
*/
- setGridSize:function (gridSize) {
+ setGridSize: function (gridSize) {
this._gridSize.width = parseInt(gridSize.width);
this._gridSize.height = parseInt(gridSize.height);
},
@@ -127,7 +127,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* set rect of the grid
* @param {cc.Rect} rect
*/
- setGridRect:function (rect) {
+ setGridRect: function (rect) {
this._gridRect = rect;
},
@@ -135,7 +135,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* get rect of the grid
* @return {cc.Rect} rect
*/
- getGridRect:function () {
+ getGridRect: function () {
return this._gridRect;
},
@@ -143,7 +143,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* get pixels between the grids
* @return {cc.Point}
*/
- getStep:function () {
+ getStep: function () {
return cc.p(this._step.x, this._step.y);
},
@@ -151,7 +151,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* set pixels between the grids
* @param {cc.Point} step
*/
- setStep:function (step) {
+ setStep: function (step) {
this._step.x = step.x;
this._step.y = step.y;
},
@@ -160,7 +160,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* get whether or not the texture is flipped
* @return {Boolean}
*/
- isTextureFlipped:function () {
+ isTextureFlipped: function () {
return this._isTextureFlipped;
},
@@ -168,7 +168,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* set whether or not the texture is flipped
* @param {Boolean} flipped
*/
- setTextureFlipped:function (flipped) {
+ setTextureFlipped: function (flipped) {
if (this._isTextureFlipped !== flipped) {
this._isTextureFlipped = flipped;
this.calculateVertexPoints();
@@ -183,7 +183,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* @param {cc.Rect} [rect=]
* @returns {boolean}
*/
- initWithSize:function (gridSize, texture, flipped, rect) {
+ initWithSize: function (gridSize, texture, flipped, rect) {
if (!texture) {
var director = cc.director;
var winSize = director.getWinSizeInPixels();
@@ -213,10 +213,9 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
this._gridSize = gridSize;
this._texture = texture;
this._isTextureFlipped = flipped;
- if(rect === undefined || cc._rectEqualToZero(rect))
- {
+ if (rect === undefined || cc._rectEqualToZero(rect)) {
var size = this._texture.getContentSize();
- rect = new cc.rect(0,0,size.width,size.height);
+ rect = new cc.rect(0, 0, size.width, size.height);
}
this._gridRect = rect;
@@ -233,17 +232,17 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
return true;
},
- beforeDraw:function () {
+ beforeDraw: function () {
// save projection
this._directorProjection = cc.director.getProjection();
//this.set2DProjection(); //TODO why?
var size = cc.director.getWinSizeInPixels();
- gl.viewport(0, 0, size.width , size.height);
+ gl.viewport(0, 0, size.width, size.height);
this._grabber.beforeRender(this._texture);
},
- afterDraw:function (target) {
+ afterDraw: function (target) {
this._grabber.afterRender(this._texture);
// restore projection
@@ -262,23 +261,23 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
afterBlit: function () {
},
- blit:function () {
+ blit: function () {
cc.log("cc.GridBase.blit(): Shall be overridden in subclass.");
},
- reuse:function () {
+ reuse: function () {
cc.log("cc.GridBase.reuse(): Shall be overridden in subclass.");
},
- calculateVertexPoints:function () {
+ calculateVertexPoints: function () {
cc.log("cc.GridBase.calculateVertexPoints(): Shall be overridden in subclass.");
},
- set2DProjection:function () {
+ set2DProjection: function () {
var winSize = cc.director.getWinSizeInPixels();
var gl = cc._renderContext;
- gl.viewport(0, 0, winSize.width , winSize.height);
+ gl.viewport(0, 0, winSize.width, winSize.height);
cc.kmGLMatrixMode(cc.KM_GL_PROJECTION);
cc.kmGLLoadIdentity();
@@ -310,14 +309,14 @@ cc.GridBase.create = function (gridSize, texture, flipped, rect) {
* @extends cc.GridBase
*/
cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
- _texCoordinates:null,
- _vertices:null,
- _originalVertices:null,
- _indices:null,
+ _texCoordinates: null,
+ _vertices: null,
+ _originalVertices: null,
+ _indices: null,
- _texCoordinateBuffer:null,
- _verticesBuffer:null,
- _indicesBuffer:null,
+ _texCoordinateBuffer: null,
+ _verticesBuffer: null,
+ _indicesBuffer: null,
_needDepthTestForBlit: false,
_oldDepthTestValue: false,
@@ -331,21 +330,21 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
* @param {Boolean} [flipped=]
* @param {cc.Rect} [rect=]
*/
- ctor:function (gridSize, texture, flipped, rect) {
+ ctor: function (gridSize, texture, flipped, rect) {
cc.GridBase.prototype.ctor.call(this);
- this._texCoordinates=null;
- this._vertices=null;
- this._originalVertices=null;
- this._indices=null;
+ this._texCoordinates = null;
+ this._vertices = null;
+ this._originalVertices = null;
+ this._indices = null;
- this._texCoordinateBuffer=null;
- this._verticesBuffer=null;
- this._indicesBuffer=null;
+ this._texCoordinateBuffer = null;
+ this._verticesBuffer = null;
+ this._indicesBuffer = null;
this._matrix = new cc.math.Matrix4();
this._matrix.identity();
- if(gridSize !== undefined)
+ if (gridSize !== undefined)
this.initWithSize(gridSize, texture, flipped, rect);
},
@@ -355,8 +354,8 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
* @param {cc.Point} pos
* @return {cc.Vertex3F}
*/
- vertex:function (pos) {
- return this.getVertex(pos);
+ vertex: function (pos) {
+ return this.getVertex(pos);
},
/**
@@ -364,8 +363,8 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
* @param {cc.Point} pos
* @return {cc.Vertex3F}
*/
- getVertex: function(pos){
- if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y))
+ getVertex: function (pos) {
+ if (pos.x !== (0 | pos.x) || pos.y !== (0 | pos.y))
cc.log("cc.Grid3D.vertex() : Numbers must be integers");
var index = 0 | ((pos.x * (this._gridSize.height + 1) + pos.y) * 3);
var locVertices = this._vertices;
@@ -378,7 +377,7 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
* @param {cc.Point} pos
* @return {cc.Vertex3F}
*/
- originalVertex:function (pos) {
+ originalVertex: function (pos) {
return this.getOriginalVertex(pos);
},
@@ -387,8 +386,8 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
* @param {cc.Point} pos
* @return {cc.Vertex3F}
*/
- getOriginalVertex: function(pos) {
- if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y))
+ getOriginalVertex: function (pos) {
+ if (pos.x !== (0 | pos.x) || pos.y !== (0 | pos.y))
cc.log("cc.Grid3D.originalVertex() : Numbers must be integers");
var index = 0 | ((pos.x * (this._gridSize.height + 1) + pos.y) * 3);
var locOriginalVertices = this._originalVertices;
@@ -400,8 +399,8 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
* @param {cc.Point} pos
* @param {cc.Vertex3F} vertex
*/
- setVertex:function (pos, vertex) {
- if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y))
+ setVertex: function (pos, vertex) {
+ if (pos.x !== (0 | pos.x) || pos.y !== (0 | pos.y))
cc.log("cc.Grid3D.setVertex() : Numbers must be integers");
var index = 0 | ((pos.x * (this._gridSize.height + 1) + pos.y) * 3);
var vertArray = this._vertices;
@@ -433,7 +432,7 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
}
},
- blit:function (target) {
+ blit: function (target) {
var n = this._gridSize.width * this._gridSize.height;
var wt = target._renderCmd._worldTransform;
@@ -476,16 +475,16 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
cc.incrementGLDraws(1);
},
- reuse:function () {
+ reuse: function () {
if (this._reuseGrid > 0) {
var locOriginalVertices = this._originalVertices, locVertices = this._vertices;
- for (var i = 0, len = this._vertices.length; i < len; i++)
+ for (var i = 0, len = this._vertices.length; i < len; i++)
locOriginalVertices[i] = locVertices[i];
--this._reuseGrid;
}
},
- calculateVertexPoints:function () {
+ calculateVertexPoints: function () {
var gl = cc._renderContext;
var width = this._texture.pixelsWidth;
@@ -498,13 +497,13 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
this._texCoordinates = new Float32Array(numOfPoints * 2);
this._indices = new Uint16Array(locGridSize.width * locGridSize.height * 6);
- if(this._verticesBuffer)
+ if (this._verticesBuffer)
gl.deleteBuffer(this._verticesBuffer);
this._verticesBuffer = gl.createBuffer();
- if(this._texCoordinateBuffer)
+ if (this._texCoordinateBuffer)
gl.deleteBuffer(this._texCoordinateBuffer);
this._texCoordinateBuffer = gl.createBuffer();
- if(this._indicesBuffer)
+ if (this._indicesBuffer)
gl.deleteBuffer(this._indicesBuffer);
this._indicesBuffer = gl.createBuffer();
@@ -531,10 +530,10 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
locIndices[idx * 6 + 5] = d;
var l1 = [a * 3, b * 3, c * 3, d * 3];
- var e = {x:x1, y:y1, z:0}; //new cc.Vertex3F(x1, y1, 0);
- var f = {x:x2, y:y1, z:0}; //new cc.Vertex3F(x2, y1, 0);
- var g = {x:x2, y:y2, z:0}; // new cc.Vertex3F(x2, y2, 0);
- var h = {x:x1, y:y2, z:0}; //new cc.Vertex3F(x1, y2, 0);
+ var e = {x: x1, y: y1, z: 0}; //new cc.Vertex3F(x1, y1, 0);
+ var f = {x: x2, y: y1, z: 0}; //new cc.Vertex3F(x2, y1, 0);
+ var g = {x: x2, y: y2, z: 0}; // new cc.Vertex3F(x2, y2, 0);
+ var h = {x: x1, y: y2, z: 0}; //new cc.Vertex3F(x1, y2, 0);
var l2 = [e, f, g, h];
var tex1 = [a * 2, b * 2, c * 2, d * 2];
@@ -562,11 +561,11 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
this._dirty = true;
},
- setNeedDepthTestForBlit: function(needDepthTest){
+ setNeedDepthTestForBlit: function (needDepthTest) {
this._needDepthTestForBlit = needDepthTest;
},
- getNeedDepthTestForBlit: function(){
+ getNeedDepthTestForBlit: function () {
return this._needDepthTestForBlit;
}
});
@@ -590,14 +589,14 @@ cc.Grid3D.create = function (gridSize, texture, flipped) {
* @extends cc.GridBase
*/
cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
- _texCoordinates:null,
- _vertices:null,
- _originalVertices:null,
- _indices:null,
+ _texCoordinates: null,
+ _vertices: null,
+ _originalVertices: null,
+ _indices: null,
- _texCoordinateBuffer:null,
- _verticesBuffer:null,
- _indicesBuffer:null,
+ _texCoordinateBuffer: null,
+ _verticesBuffer: null,
+ _indicesBuffer: null,
/**
* create one TiledGrid3D object
@@ -606,21 +605,21 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
* @param {cc.Texture2D} [texture=]
* @param {Boolean} [flipped=]
*/
- ctor:function (gridSize, texture, flipped, rect) {
+ ctor: function (gridSize, texture, flipped, rect) {
cc.GridBase.prototype.ctor.call(this);
- this._texCoordinates=null;
- this._vertices=null;
- this._originalVertices=null;
- this._indices=null;
+ this._texCoordinates = null;
+ this._vertices = null;
+ this._originalVertices = null;
+ this._indices = null;
- this._texCoordinateBuffer=null;
- this._verticesBuffer=null;
- this._indicesBuffer=null;
+ this._texCoordinateBuffer = null;
+ this._verticesBuffer = null;
+ this._indicesBuffer = null;
this._matrix = new cc.math.Matrix4();
this._matrix.identity();
- if(gridSize !== undefined)
+ if (gridSize !== undefined)
this.initWithSize(gridSize, texture, flipped, rect);
},
@@ -630,7 +629,7 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
* @param {cc.Point} pos
* @return {cc.Quad3}
*/
- tile:function (pos) {
+ tile: function (pos) {
return this.getTile(pos);
},
@@ -639,15 +638,15 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
* @param {cc.Point} pos
* @return {cc.Quad3}
*/
- getTile: function(pos){
- if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y))
+ getTile: function (pos) {
+ if (pos.x !== (0 | pos.x) || pos.y !== (0 | pos.y))
cc.log("cc.TiledGrid3D.tile() : Numbers must be integers");
var idx = (this._gridSize.height * pos.x + pos.y) * 4 * 3;
var locVertices = this._vertices;
return new cc.Quad3(new cc.Vertex3F(locVertices[idx], locVertices[idx + 1], locVertices[idx + 2]),
new cc.Vertex3F(locVertices[idx + 3], locVertices[idx + 4], locVertices[idx + 5]),
- new cc.Vertex3F(locVertices[idx + 6 ], locVertices[idx + 7], locVertices[idx + 8]),
+ new cc.Vertex3F(locVertices[idx + 6], locVertices[idx + 7], locVertices[idx + 8]),
new cc.Vertex3F(locVertices[idx + 9], locVertices[idx + 10], locVertices[idx + 11]));
},
@@ -656,15 +655,15 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
* @param {cc.Point} pos
* @return {cc.Quad3}
*/
- getOriginalTile:function (pos) {
- if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y))
+ getOriginalTile: function (pos) {
+ if (pos.x !== (0 | pos.x) || pos.y !== (0 | pos.y))
cc.log("cc.TiledGrid3D.originalTile() : Numbers must be integers");
var idx = (this._gridSize.height * pos.x + pos.y) * 4 * 3;
var locOriginalVertices = this._originalVertices;
return new cc.Quad3(new cc.Vertex3F(locOriginalVertices[idx], locOriginalVertices[idx + 1], locOriginalVertices[idx + 2]),
new cc.Vertex3F(locOriginalVertices[idx + 3], locOriginalVertices[idx + 4], locOriginalVertices[idx + 5]),
- new cc.Vertex3F(locOriginalVertices[idx + 6 ], locOriginalVertices[idx + 7], locOriginalVertices[idx + 8]),
+ new cc.Vertex3F(locOriginalVertices[idx + 6], locOriginalVertices[idx + 7], locOriginalVertices[idx + 8]),
new cc.Vertex3F(locOriginalVertices[idx + 9], locOriginalVertices[idx + 10], locOriginalVertices[idx + 11]));
},
@@ -674,7 +673,7 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
* @param {cc.Point} pos
* @return {cc.Quad3}
*/
- originalTile: function(pos) {
+ originalTile: function (pos) {
return this.getOriginalTile(pos);
},
@@ -683,8 +682,8 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
* @param {cc.Point} pos
* @param {cc.Quad3} coords
*/
- setTile:function (pos, coords) {
- if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y))
+ setTile: function (pos, coords) {
+ if (pos.x !== (0 | pos.x) || pos.y !== (0 | pos.y))
cc.log("cc.TiledGrid3D.setTile() : Numbers must be integers");
var idx = (this._gridSize.height * pos.x + pos.y) * 12;
@@ -747,7 +746,7 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
cc.incrementGLDraws(1);
},
- reuse:function () {
+ reuse: function () {
if (this._reuseGrid > 0) {
var locVertices = this._vertices, locOriginalVertices = this._originalVertices;
for (var i = 0; i < locVertices.length; i++)
@@ -756,7 +755,7 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
}
},
- calculateVertexPoints:function () {
+ calculateVertexPoints: function () {
var width = this._texture.pixelsWidth;
var height = this._texture.pixelsHeight;
var imageH = this._texture.getContentSizeInPixels().height;
@@ -768,13 +767,13 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
this._indices = new Uint16Array(numQuads * 6);
var gl = cc._renderContext;
- if(this._verticesBuffer)
+ if (this._verticesBuffer)
gl.deleteBuffer(this._verticesBuffer);
this._verticesBuffer = gl.createBuffer();
- if(this._texCoordinateBuffer)
+ if (this._texCoordinateBuffer)
gl.deleteBuffer(this._texCoordinateBuffer);
this._texCoordinateBuffer = gl.createBuffer();
- if(this._indicesBuffer)
+ if (this._indicesBuffer)
gl.deleteBuffer(this._indicesBuffer);
this._indicesBuffer = gl.createBuffer();
diff --git a/cocos2d/kazmath/gl/mat4stack.js b/cocos2d/kazmath/gl/mat4stack.js
index ecd3aceba3..cd339423e2 100644
--- a/cocos2d/kazmath/gl/mat4stack.js
+++ b/cocos2d/kazmath/gl/mat4stack.js
@@ -26,54 +26,55 @@
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-(function(cc){
+(function (cc) {
/**
* The stack of cc.math.Matrix4
* @param {cc.math.Matrix4} [top]
* @param {Array} [stack]
* @constructor
*/
- cc.math.Matrix4Stack = function(top, stack) {
+ cc.math.Matrix4Stack = function (top, stack) {
this.top = top;
this.stack = stack || [];
+ this.lastUpdated = 0;
//this._matrixPool = []; // use pool in next version
};
cc.km_mat4_stack = cc.math.Matrix4Stack;
var proto = cc.math.Matrix4Stack.prototype;
- proto.initialize = function() { //cc.km_mat4_stack_initialize
+ proto.initialize = function () { //cc.km_mat4_stack_initialize
this.stack.length = 0;
this.top = null;
};
//for compatibility
- cc.km_mat4_stack_push = function(stack, item){
+ cc.km_mat4_stack_push = function (stack, item) {
stack.stack.push(stack.top);
stack.top = new cc.math.Matrix4(item);
};
- cc.km_mat4_stack_pop = function(stack, pOut){
+ cc.km_mat4_stack_pop = function (stack, pOut) {
stack.top = stack.stack.pop();
};
- cc.km_mat4_stack_release = function(stack){
+ cc.km_mat4_stack_release = function (stack) {
stack.stack = null;
stack.top = null;
};
- proto.push = function(item) {
+ proto.push = function (item) {
item = item || this.top;
this.stack.push(this.top);
this.top = new cc.math.Matrix4(item);
//this.top = this._getFromPool(item);
};
- proto.pop = function() {
+ proto.pop = function () {
//this._putInPool(this.top);
this.top = this.stack.pop();
};
- proto.release = function(){
+ proto.release = function () {
this.stack = null;
this.top = null;
this._matrixPool = null;
@@ -88,7 +89,7 @@
return ret;
};
- proto._putInPool = function(matrix){
+ proto._putInPool = function (matrix) {
this._matrixPool.push(matrix);
};
})(cc);
diff --git a/cocos2d/kazmath/gl/matrix.js b/cocos2d/kazmath/gl/matrix.js
index ae2605db06..13c9798125 100644
--- a/cocos2d/kazmath/gl/matrix.js
+++ b/cocos2d/kazmath/gl/matrix.js
@@ -26,7 +26,7 @@
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-(function(cc) {
+(function (cc) {
cc.KM_GL_MODELVIEW = 0x1700;
cc.KM_GL_PROJECTION = 0x1701;
cc.KM_GL_TEXTURE = 0x1702;
@@ -106,6 +106,7 @@
throw new Error("Invalid matrix mode specified"); //TODO: Proper error handling
break;
}
+ cc.current_stack.lastUpdated = cc.director.getTotalFrames();
};
cc.kmGLLoadIdentity = function () {
diff --git a/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js b/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js
index 9a7484d1ba..5edf6c501b 100644
--- a/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js
+++ b/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js
@@ -22,8 +22,8 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- cc.LabelAtlas.WebGLRenderCmd = function(renderable){
+(function () {
+ cc.LabelAtlas.WebGLRenderCmd = function (renderable) {
cc.AtlasNode.WebGLRenderCmd.call(this, renderable);
this._needDraw = true;
};
@@ -50,13 +50,13 @@
}
};
- proto.setCascade = function(){
+ proto.setCascade = function () {
var node = this._node;
node._cascadeOpacityEnabled = true;
node._cascadeColorEnabled = true;
};
- proto.rendering = function(ctx){
+ proto.rendering = function (ctx) {
cc.AtlasNode.WebGLRenderCmd.prototype.rendering.call(this, ctx);
if (cc.LABELATLAS_DEBUG_DRAW) {
var node = this._node;
@@ -64,15 +64,15 @@
var locRect = node.getBoundingBoxToWorld();
var posX = locRect.x,
posY = locRect.y;
- s.width = locRect.width;
- s.height = locRect.height;
- var vertices = [cc.p(posX, posY), cc.p(posX+ s.width, posY),
- cc.p(s.width+posX, s.height+posY), cc.p(posX, posY+s.height)];
+ s.width = locRect.width;
+ s.height = locRect.height;
+ var vertices = [cc.p(posX, posY), cc.p(posX + s.width, posY),
+ cc.p(s.width + posX, s.height + posY), cc.p(posX, posY + s.height)];
cc._drawingUtil.drawPoly(vertices, 4, true);
}
};
- proto.updateAtlasValues = function(){
+ proto.updateAtlasValues = function () {
var node = this._node;
var locString = node._string;
var n = locString.length;
@@ -96,9 +96,9 @@
var a = locString.charCodeAt(i) - node._mapStartChar.charCodeAt(0);
var row = a % node._itemsPerRow;
var col = 0 | (a / node._itemsPerRow);
- if(row < 0 || col < 0)
+ if (row < 0 || col < 0)
continue;
- if(row*locItemWidth + locItemWidth > textureWide || col*locItemHeight + locItemHeight > textureHigh)
+ if (row * locItemWidth + locItemWidth > textureWide || col * locItemHeight + locItemHeight > textureHigh)
continue;
cr++;
@@ -142,7 +142,7 @@
this._updateColor();
- this.updateContentSize(i, cr+1);
+ this.updateContentSize(i, cr + 1);
if (n > 0) {
locTextureAtlas.dirty = true;
var totalQuads = locTextureAtlas.totalQuads;
@@ -151,19 +151,20 @@
}
};
- proto.updateContentSize = function(i, cr){
+ proto.updateContentSize = function (i, cr) {
var node = this._node,
contentSize = node._contentSize;
- if(i !== cr && i*node._itemWidth === contentSize.width && node._itemHeight === contentSize.height){
+ if (i !== cr && i * node._itemWidth === contentSize.width && node._itemHeight === contentSize.height) {
node.setContentSize(cr * node._itemWidth, node._itemHeight);
}
};
- proto.setString = function(label){
+ proto.setString = function (label) {
var len = label.length;
if (len > this._textureAtlas.totalQuads)
this._textureAtlas.resizeCapacity(len);
};
- proto._addChild = function(){};
-})();
\ No newline at end of file
+ proto._addChild = function () {
+ };
+})();
diff --git a/cocos2d/labels/CCLabelBMFont.js b/cocos2d/labels/CCLabelBMFont.js
index 0dd628e128..7c261a14b7 100644
--- a/cocos2d/labels/CCLabelBMFont.js
+++ b/cocos2d/labels/CCLabelBMFont.js
@@ -106,8 +106,8 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
_textureLoaded: false,
_className: "LabelBMFont",
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
return new cc.LabelBMFont.WebGLRenderCmd(this);
else
return new cc.LabelBMFont.CanvasRenderCmd(this);
@@ -128,7 +128,9 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
}
}
if (this._textureLoaded) {
- this.createFontChars();
+ if(this._string && this._string.length > 0) {
+ this.createFontChars();
+ }
if (needUpdateLabel)
this.updateLabel();
}
@@ -273,6 +275,9 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
* updates the font chars based on the string to render
*/
createFontChars: function () {
+ var locStr = this._string;
+ var stringLen = locStr ? locStr.length : 0;
+
var self = this;
var cmd = this._renderCmd;
var locTexture = cmd._texture || this._texture;
@@ -285,11 +290,6 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
var quantityOfLines = 1;
- var locStr = self._string;
- var stringLen = locStr ? locStr.length : 0;
-
- if (stringLen === 0)
- return;
var i, locCfg = self._config, locKerningDict = locCfg.kerningDict,
locCommonH = locCfg.commonHeight, locFontDict = locCfg.fontDefDictionary;
@@ -366,7 +366,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
//If the last character processed has an xAdvance which is less that the width of the characters image, then we need
// to adjust the width of the string to take this into account, or the character will overlap the end of the bounding box
- if(fontDef && fontDef.xAdvance < fontDef.rect.width)
+ if (fontDef && fontDef.xAdvance < fontDef.rect.width)
tmpSize.width = longestLine - fontDef.xAdvance + fontDef.rect.width;
else
tmpSize.width = longestLine;
@@ -383,13 +383,17 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
var self = this;
var locChildren = self._children;
if (locChildren) {
- for (var i = 0, li = locChildren.length; i < li; i++) {
+ var length = locChildren.length;
+ for (var i = 0, li = length; i < li; i++) {
var node = locChildren[i];
if (node) node.visible = false;
}
}
- if (self._config)
- self.createFontChars();
+ if (self._config) {
+ if(self._string && self._string.length > 0) {
+ self.createFontChars();
+ }
+ }
if (!fromUpdate)
self.updateLabel();
@@ -410,9 +414,9 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
*/
setString: function (newString, needUpdateLabel) {
newString = String(newString);
- if (needUpdateLabel == null)
+ if (needUpdateLabel === undefined)
needUpdateLabel = true;
- if (newString == null || !cc.isString(newString))
+ if (newString === undefined || typeof newString !== 'string')
newString = newString + "";
this._initialString = newString;
@@ -434,9 +438,8 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
},
// calc the text all with in a line
- _getCharsWidth:function (startIndex, endIndex) {
- if (endIndex <= 0)
- {
+ _getCharsWidth: function (startIndex, endIndex) {
+ if (endIndex <= 0) {
return 0;
}
var curTextFirstSprite = this.getChildByTag(startIndex);
@@ -444,12 +447,11 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
return this._getLetterPosXLeft(curTextLastSprite) - this._getLetterPosXLeft(curTextFirstSprite);
},
- _checkWarp:function (strArr, i, maxWidth, initStringWrapNum) {
+ _checkWarp: function (strArr, i, maxWidth, initStringWrapNum) {
var self = this;
var text = strArr[i];
var curLength = 0;
- for (var strArrIndex = 0; strArrIndex < i; strArrIndex++)
- {
+ for (var strArrIndex = 0; strArrIndex < i; strArrIndex++) {
curLength += strArr[strArrIndex].length;
}
@@ -554,8 +556,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
if (oldArrLength < stringArr.length) {
newWrapNum++;
}
- if (i > 0)
- {
+ if (i > 0) {
wrapString += "\n";
}
wrapString += stringArr[i];
@@ -718,7 +719,10 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
var self1 = this;
self1._textureLoaded = true;
self1.setTexture(sender);
- self1.createFontChars();
+ if(self1._string && self1._string.length > 0) {
+ self1.createFontChars();
+ }
+
self1._changeTextureColor();
self1.updateLabel();
@@ -726,7 +730,9 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
}, self);
} else {
self.setTexture(texture);
- self.createFontChars();
+ if(self._string && self._string.length > 0) {
+ self.createFontChars();
+ }
}
}
},
@@ -739,7 +745,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
return this._fntFile;
},
- setTexture: function(texture){
+ setTexture: function (texture) {
this._texture = texture;
this._renderCmd.setTexture(texture);
},
@@ -766,7 +772,8 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
this.updateLabel();
},
- _atlasNameFromFntFile: function (fntFile) {},
+ _atlasNameFromFntFile: function (fntFile) {
+ },
_kerningAmountForFirst: function (first, second) {
var ret = 0;
@@ -788,14 +795,14 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
},
//Checking whether the character is a whitespace
- _isspace_unicode: function(ch){
+ _isspace_unicode: function (ch) {
ch = ch.charCodeAt(0);
return ((ch >= 9 && ch <= 13) || ch === 32 || ch === 133 || ch === 160 || ch === 5760
|| (ch >= 8192 && ch <= 8202) || ch === 8232 || ch === 8233 || ch === 8239
|| ch === 8287 || ch === 12288)
},
- _utf8_trim_ws: function(str){
+ _utf8_trim_ws: function (str) {
var len = str.length;
if (len <= 0)
@@ -819,7 +826,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
//Trims str st str=[0, index) after the operation.
//Return value: the trimmed string.
- _utf8_trim_from: function(str, index){
+ _utf8_trim_from: function (str, index) {
var len = str.length;
if (index >= len || index < 0)
return;
@@ -827,7 +834,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
}
});
-(function(){
+(function () {
var p = cc.LabelBMFont.prototype;
cc.EventHelper.prototype.apply(p);
diff --git a/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js b/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js
index 1f34cd6cb4..5861daa30a 100644
--- a/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js
+++ b/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js
@@ -30,15 +30,15 @@
http://www.angelcode.com/products/bmfont/ (Free, Windows only)
****************************************************************************/
-(function(){
- cc.LabelBMFont.CanvasRenderCmd = function(renderableObject){
- cc.Node.CanvasRenderCmd.call(this, renderableObject);
+(function () {
+ cc.LabelBMFont.CanvasRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
};
var proto = cc.LabelBMFont.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
proto.constructor = cc.LabelBMFont.CanvasRenderCmd;
- proto._updateCharTexture = function(fontChar, rect, key){
+ proto._updateCharTexture = function (fontChar, rect, key) {
if (key === 32) {
fontChar.setTextureRect(rect, false, cc.size(0, 0));
} else {
@@ -49,7 +49,7 @@
}
};
- proto._updateCharColorAndOpacity = function(fontChar){
+ proto._updateCharColorAndOpacity = function (fontChar) {
// Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on
fontChar._displayedColor = this._displayedColor;
fontChar._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty);
@@ -73,7 +73,7 @@
node._texture = texture;
};
- proto._changeTextureColor = function(){
+ proto._changeTextureColor = function () {
var node = this._node;
var texture = node._texture,
contentSize = texture.getContentSize();
@@ -83,19 +83,19 @@
var disColor = this._displayedColor;
var textureRect = cc.rect(0, 0, oElement.width, oElement.height);
if (texture && contentSize.width > 0) {
- if(!oElement)
+ if (!oElement)
return;
var textureToRender = oTexture._generateColorTexture(disColor.r, disColor.g, disColor.b, textureRect);
node.setTexture(textureToRender);
}
};
- proto._updateChildrenDisplayedOpacity = function(locChild){
+ proto._updateChildrenDisplayedOpacity = function (locChild) {
cc.Node.prototype.updateDisplayedOpacity.call(locChild, this._displayedOpacity);
};
- proto._updateChildrenDisplayedColor = function(locChild){
+ proto._updateChildrenDisplayedColor = function (locChild) {
cc.Node.prototype.updateDisplayedColor.call(locChild, this._displayedColor);
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js b/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js
index 68d5c374a7..7e468e37d7 100644
--- a/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js
+++ b/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js
@@ -30,9 +30,9 @@
http://www.angelcode.com/products/bmfont/ (Free, Windows only)
****************************************************************************/
-(function(){
- cc.LabelBMFont.WebGLRenderCmd = function(renderableObject){
- cc.Node.WebGLRenderCmd.call(this, renderableObject);
+(function () {
+ cc.LabelBMFont.WebGLRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
};
var proto = cc.LabelBMFont.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
@@ -42,14 +42,16 @@
this._node.setOpacityModifyRGB(this._node._texture.hasPremultipliedAlpha());
};
- proto._updateCharTexture = function(fontChar, rect, key){
+ proto._updateCharTexture = function (fontChar, rect, key) {
// updating previous sprite
fontChar.setTextureRect(rect, false);
// restore to default in case they were modified
fontChar.visible = true;
};
- proto._changeTextureColor = function(){};
+ proto._changeTextureColor = function () {
+ };
- proto._updateCharColorAndOpacity = function(){};
-})();
\ No newline at end of file
+ proto._updateCharColorAndOpacity = function () {
+ };
+})();
diff --git a/cocos2d/menus/CCMenu.js b/cocos2d/menus/CCMenu.js
index 6cf5703760..e3edd737ee 100644
--- a/cocos2d/menus/CCMenu.js
+++ b/cocos2d/menus/CCMenu.js
@@ -84,19 +84,14 @@ cc.Menu = cc.Layer.extend(/** @lends cc.Menu# */{
onTouchCancelled: this._onTouchCancelled
});
- if ((arguments.length > 0) && (arguments[arguments.length - 1] == null))
- cc.log("parameters should not be ending with null in Javascript");
-
var argc = arguments.length, items;
- if (argc === 0) {
+ if (menuItems instanceof Array) {
+ items = menuItems;
+ }
+ else if (argc === 0) {
items = [];
- } else if (argc === 1) {
- if (menuItems instanceof Array) {
- items = menuItems;
- }
- else items = [menuItems];
}
- else if (argc > 1) {
+ else if (argc > 0) {
items = [];
for (var i = 0; i < argc; i++) {
if (arguments[i])
@@ -281,8 +276,8 @@ cc.Menu = cc.Layer.extend(/** @lends cc.Menu# */{
if ((arguments.length > 0) && (arguments[arguments.length - 1] == null))
cc.log("parameters should not be ending with null in Javascript");
- var rows = [];
- for (var i = 0; i < arguments.length; i++) {
+ var i, rows = [];
+ for (i = 0; i < arguments.length; i++) {
rows.push(arguments[i]);
}
var height = -5;
@@ -363,7 +358,7 @@ cc.Menu = cc.Layer.extend(/** @lends cc.Menu# */{
alignItemsInRows: function (/*Multiple arguments*/) {
if ((arguments.length > 0) && (arguments[arguments.length - 1] == null))
cc.log("parameters should not be ending with null in Javascript");
- var columns = [], i;
+ var i, columns = [];
for (i = 0; i < arguments.length; i++) {
columns.push(arguments[i]);
}
@@ -558,7 +553,7 @@ cc.Menu = cc.Layer.extend(/** @lends cc.Menu# */{
},
/**
* only use for jsbinding
- * @returns {boolean}
+ * @returns {boolean}
*/
isOpacityModifyRGB: function () {
return false;
diff --git a/cocos2d/motion-streak/CCMotionStreak.js b/cocos2d/motion-streak/CCMotionStreak.js
index 1553aa4c2a..158393454a 100644
--- a/cocos2d/motion-streak/CCMotionStreak.js
+++ b/cocos2d/motion-streak/CCMotionStreak.js
@@ -44,33 +44,33 @@
* new cc.MotionStreak(2, 3, 32, cc.color.GREEN, s_streak);
*/
cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
- texture:null,
- fastMode:false,
- startingPositionInitialized:false,
+ texture: null,
+ fastMode: false,
+ startingPositionInitialized: false,
- _blendFunc:null,
+ _blendFunc: null,
- _stroke:0,
- _fadeDelta:0,
- _minSeg:0,
+ _stroke: 0,
+ _fadeDelta: 0,
+ _minSeg: 0,
- _maxPoints:0,
- _nuPoints:0,
- _previousNuPoints:0,
+ _maxPoints: 0,
+ _nuPoints: 0,
+ _previousNuPoints: 0,
/* Pointers */
- _pointVertexes:null,
- _pointState:null,
+ _pointVertexes: null,
+ _pointState: null,
// webgl
- _vertices:null,
- _colorPointer:null,
- _texCoords:null,
+ _vertices: null,
+ _colorPointer: null,
+ _texCoords: null,
- _verticesBuffer:null,
- _colorPointerBuffer:null,
- _texCoordsBuffer:null,
- _className:"MotionStreak",
+ _verticesBuffer: null,
+ _colorPointerBuffer: null,
+ _texCoordsBuffer: null,
+ _className: "MotionStreak",
/**
* creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture filename or texture
@@ -112,7 +112,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
this._colorPointerBuffer = null;
this._texCoordsBuffer = null;
- if(texture !== undefined)
+ if (texture !== undefined)
this.initWithFade(fade, minSeg, stroke, color, texture);
},
@@ -120,7 +120,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Gets the texture.
* @return {cc.Texture2D}
*/
- getTexture:function () {
+ getTexture: function () {
return this.texture;
},
@@ -128,7 +128,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Set the texture.
* @param {cc.Texture2D} texture
*/
- setTexture:function (texture) {
+ setTexture: function (texture) {
if (this.texture !== texture)
this.texture = texture;
},
@@ -137,7 +137,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Gets the blend func.
* @return {cc.BlendFunc}
*/
- getBlendFunc:function () {
+ getBlendFunc: function () {
return this._blendFunc;
},
@@ -146,7 +146,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* @param {Number} src
* @param {Number} dst
*/
- setBlendFunc:function (src, dst) {
+ setBlendFunc: function (src, dst) {
if (dst === undefined) {
this._blendFunc = src;
} else {
@@ -160,7 +160,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* @warning cc.MotionStreak.getOpacity has not been supported.
* @returns {number}
*/
- getOpacity:function () {
+ getOpacity: function () {
cc.log("cc.MotionStreak.getOpacity has not been supported.");
return 0;
},
@@ -170,7 +170,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* @warning cc.MotionStreak.setOpacity has not been supported.
* @param opacity
*/
- setOpacity:function (opacity) {
+ setOpacity: function (opacity) {
cc.log("cc.MotionStreak.setOpacity has not been supported.");
},
@@ -179,14 +179,14 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* @warning cc.MotionStreak.setOpacityModifyRGB has not been supported.
* @param value
*/
- setOpacityModifyRGB:function (value) {
+ setOpacityModifyRGB: function (value) {
},
/**
* Checking OpacityModifyRGB.
* @returns {boolean}
*/
- isOpacityModifyRGB:function () {
+ isOpacityModifyRGB: function () {
return false;
},
@@ -194,7 +194,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Checking fast mode.
* @returns {boolean}
*/
- isFastMode:function () {
+ isFastMode: function () {
return this.fastMode;
},
@@ -202,7 +202,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* set fast mode
* @param {Boolean} fastMode
*/
- setFastMode:function (fastMode) {
+ setFastMode: function (fastMode) {
this.fastMode = fastMode;
},
@@ -210,7 +210,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Checking starting position initialized.
* @returns {boolean}
*/
- isStartingPositionInitialized:function () {
+ isStartingPositionInitialized: function () {
return this.startingPositionInitialized;
},
@@ -218,7 +218,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Set Starting Position Initialized.
* @param {Boolean} startingPositionInitialized
*/
- setStartingPositionInitialized:function (startingPositionInitialized) {
+ setStartingPositionInitialized: function (startingPositionInitialized) {
this.startingPositionInitialized = startingPositionInitialized;
},
@@ -226,7 +226,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Get stroke.
* @returns {Number} stroke
*/
- getStroke:function () {
+ getStroke: function () {
return this._stroke;
},
@@ -234,7 +234,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Set stroke.
* @param {Number} stroke
*/
- setStroke:function (stroke) {
+ setStroke: function (stroke) {
this._stroke = stroke;
},
@@ -247,14 +247,14 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* @param {string|cc.Texture2D} texture texture filename or texture
* @return {Boolean}
*/
- initWithFade:function (fade, minSeg, stroke, color, texture) {
- if(!texture)
+ initWithFade: function (fade, minSeg, stroke, color, texture) {
+ if (!texture)
throw new Error("cc.MotionStreak.initWithFade(): Invalid filename or texture");
if (cc.isString(texture))
texture = cc.textureCache.addImage(texture);
- cc.Node.prototype.setPosition.call(this, cc.p(0,0));
+ cc.Node.prototype.setPosition.call(this, cc.p(0, 0));
this.anchorX = 0;
this.anchorY = 0;
this.ignoreAnchor = true;
@@ -304,7 +304,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* color used for the tint
* @param {cc.Color} color
*/
- tintWithColor:function (color) {
+ tintWithColor: function (color) {
this.color = color;
// Fast assignation
@@ -319,7 +319,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
/**
* Remove all living segments of the ribbon
*/
- reset:function () {
+ reset: function () {
this._nuPoints = 0;
},
@@ -329,9 +329,9 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* @param {cc.Point|Number} position
* @param {Number} [yValue=undefined] If not exists, the first parameter must be cc.Point.
*/
- setPosition:function (position, yValue) {
+ setPosition: function (position, yValue) {
this.startingPositionInitialized = true;
- if(yValue === undefined){
+ if (yValue === undefined) {
this._positionR.x = position.x;
this._positionR.y = position.y;
} else {
@@ -344,7 +344,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Gets the position.x
* @return {Number}
*/
- getPositionX:function () {
+ getPositionX: function () {
return this._positionR.x;
},
@@ -352,9 +352,9 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Set the position.x
* @param {Number} x
*/
- setPositionX:function (x) {
+ setPositionX: function (x) {
this._positionR.x = x;
- if(!this.startingPositionInitialized)
+ if (!this.startingPositionInitialized)
this.startingPositionInitialized = true;
},
@@ -362,17 +362,17 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Gets the position.y
* @return {Number}
*/
- getPositionY:function () {
- return this._positionR.y;
+ getPositionY: function () {
+ return this._positionR.y;
},
/**
* Set the position.y
* @param {Number} y
*/
- setPositionY:function (y) {
+ setPositionY: function (y) {
this._positionR.y = y;
- if(!this.startingPositionInitialized)
+ if (!this.startingPositionInitialized)
this.startingPositionInitialized = true;
},
@@ -383,7 +383,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Only one "update" method could be scheduled per node.
* @param {Number} delta
*/
- update:function (delta) {
+ update: function (delta) {
if (!this.startingPositionInitialized)
return;
@@ -392,7 +392,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
delta *= this._fadeDelta;
- var newIdx, newIdx2, i, i2;
+ var i, newIdx, newIdx2, i2;
var mov = 0;
// Update current points
@@ -447,7 +447,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
appendNewPoint = false;
else if (locNuPoints > 0) {
var a1 = cc.pDistanceSQ(cc.p(locPointVertexes[(locNuPoints - 1) * 2], locPointVertexes[(locNuPoints - 1) * 2 + 1]),
- this._positionR) < this._minSeg;
+ this._positionR) < this._minSeg;
var a2 = (locNuPoints === 1) ? false : (cc.pDistanceSQ(
cc.p(locPointVertexes[(locNuPoints - 2) * 2], locPointVertexes[(locNuPoints - 2) * 2 + 1]), this._positionR) < (this._minSeg * 2.0));
if (a1 || a2)
@@ -506,8 +506,8 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
this._nuPoints = locNuPoints;
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
return new cc.MotionStreak.WebGLRenderCmd(this);
else
return null; //MotionStreak doesn't support Canvas mode
diff --git a/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js b/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js
index 69f4f12f5f..e2d74f574a 100644
--- a/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js
+++ b/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js
@@ -22,8 +22,8 @@
THE SOFTWARE.
****************************************************************************/
-cc.MotionStreak.WebGLRenderCmd = function(renderableObject){
- cc.Node.WebGLRenderCmd.call(this, renderableObject);
+cc.MotionStreak.WebGLRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
this._needDraw = true;
this._matrix = new cc.math.Matrix4();
this._matrix.identity();
@@ -33,7 +33,7 @@ cc.MotionStreak.WebGLRenderCmd = function(renderableObject){
cc.MotionStreak.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
cc.MotionStreak.WebGLRenderCmd.prototype.constructor = cc.Sprite.WebGLRenderCmd;
-cc.MotionStreak.WebGLRenderCmd.prototype.rendering = function(ctx){
+cc.MotionStreak.WebGLRenderCmd.prototype.rendering = function (ctx) {
var node = this._node;
if (node._nuPoints <= 1)
return;
@@ -77,4 +77,4 @@ cc.MotionStreak.WebGLRenderCmd.prototype.rendering = function(ctx){
ctx.drawArrays(ctx.TRIANGLE_STRIP, 0, node._nuPoints * 2);
cc.g_NumberOfDraws++;
}
-};
\ No newline at end of file
+};
diff --git a/cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js b/cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js
index 8c45377dfe..9288a0fd69 100644
--- a/cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js
+++ b/cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js
@@ -22,9 +22,9 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- cc.NodeGrid.WebGLRenderCmd = function(renderable){
- cc.Node.WebGLRenderCmd.call(this, renderable);
+(function () {
+ cc.NodeGrid.WebGLRenderCmd = function (renderable) {
+ this._rootCtor(renderable);
this._needDraw = false;
this._gridBeginCommand = new cc.CustomRenderCmd(this, this.onGridBeginDraw);
this._gridEndCommand = new cc.CustomRenderCmd(this, this.onGridEndDraw);
@@ -33,15 +33,15 @@
var proto = cc.NodeGrid.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
proto.constructor = cc.NodeGrid.WebGLRenderCmd;
- proto.visit = function(parentCmd) {
+ proto.visit = function (parentCmd) {
var node = this._node;
// quick return if not visible
if (!node._visible)
return;
parentCmd = parentCmd || this.getParentRenderCmd();
- if (node._parent && node._parent._renderCmd)
- this._curLevel = node._parent._renderCmd._curLevel + 1;
+ if (parentCmd)
+ this._curLevel = parentCmd._curLevel + 1;
var currentStack = cc.current_stack;
currentStack.stack.push(currentStack.top);
@@ -49,16 +49,16 @@
currentStack.top = this._stackMatrix;
/*var beforeProjectionType = cc.director.PROJECTION_DEFAULT;
- if (locGrid && locGrid._active) {
- //var backMatrix = new cc.kmMat4();
- //cc.kmMat4Assign(backMatrix, this._stackMatrix);
+ if (locGrid && locGrid._active) {
+ //var backMatrix = new cc.kmMat4();
+ //cc.kmMat4Assign(backMatrix, this._stackMatrix);
- beforeProjectionType = cc.director.getProjection();
- //locGrid.set2DProjection();
+ beforeProjectionType = cc.director.getProjection();
+ //locGrid.set2DProjection();
- //reset this._stackMatrix to current_stack.top
- //cc.kmMat4Assign(currentStack.top, backMatrix);
- }*/
+ //reset this._stackMatrix to current_stack.top
+ //cc.kmMat4Assign(currentStack.top, backMatrix);
+ }*/
cc.renderer.pushRenderCommand(this._gridBeginCommand);
if (node._target)
@@ -76,7 +76,7 @@
}
//if (locGrid && locGrid._active) {
- //cc.director.setProjection(beforeProjectionType);
+ //cc.director.setProjection(beforeProjectionType);
//}
cc.renderer.pushRenderCommand(this._gridEndCommand);
@@ -84,13 +84,13 @@
currentStack.top = currentStack.stack.pop();
};
- proto.onGridBeginDraw = function(){
+ proto.onGridBeginDraw = function () {
var locGrid = this._node.grid;
if (locGrid && locGrid._active)
locGrid.beforeDraw();
};
- proto.onGridEndDraw = function(){
+ proto.onGridEndDraw = function () {
var locGrid = this._node.grid;
if (locGrid && locGrid._active)
locGrid.afterDraw(this._node);
diff --git a/cocos2d/parallax/CCParallaxNodeRenderCmd.js b/cocos2d/parallax/CCParallaxNodeRenderCmd.js
index 572c10e3e1..2f5031c844 100644
--- a/cocos2d/parallax/CCParallaxNodeRenderCmd.js
+++ b/cocos2d/parallax/CCParallaxNodeRenderCmd.js
@@ -24,46 +24,46 @@
//TODO find a way to simple these code.
-(function(){
- cc.ParallaxNode.CanvasRenderCmd = function(renderable){
- cc.Node.CanvasRenderCmd.call(this, renderable);
+(function () {
+ cc.ParallaxNode.CanvasRenderCmd = function (renderable) {
+ this._rootCtor(renderable);
this._needDraw = false;
};
var proto = cc.ParallaxNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
proto.constructor = cc.ParallaxNode.CanvasRenderCmd;
- proto.updateStatus = function(){
+ proto.updateStatus = function () {
this._node._updateParallaxPosition();
- cc.Node.CanvasRenderCmd.prototype.updateStatus.call(this);
+ this.originUpdateStatus();
};
- proto._syncStatus = function(parentCmd){
+ proto._syncStatus = function (parentCmd) {
this._node._updateParallaxPosition();
- cc.Node.CanvasRenderCmd.prototype._syncStatus.call(this, parentCmd);
+ this._originSyncStatus(parentCmd);
};
})();
cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
- if(cc._renderType !== cc.game.RENDER_TYPE_WEBGL)
+ if (cc._renderType !== cc.game.RENDER_TYPE_WEBGL)
return;
- cc.ParallaxNode.WebGLRenderCmd = function(renderable){
- cc.Node.WebGLRenderCmd.call(this, renderable);
+ cc.ParallaxNode.WebGLRenderCmd = function (renderable) {
+ this._rootCtor(renderable);
this._needDraw = false;
};
var proto = cc.ParallaxNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
proto.constructor = cc.ParallaxNode.WebGLRenderCmd;
- proto.updateStatus = function(){
+ proto.updateStatus = function () {
this._node._updateParallaxPosition();
- cc.Node.WebGLRenderCmd.prototype.updateStatus.call(this);
+ this.originUpdateStatus();
};
- proto._syncStatus = function(parentCmd){
+ proto._syncStatus = function (parentCmd) {
this._node._updateParallaxPosition();
- cc.Node.WebGLRenderCmd.prototype._syncStatus.call(this, parentCmd);
+ this._originSyncStatus(parentCmd);
};
});
diff --git a/cocos2d/particle/CCParticleBatchNode.js b/cocos2d/particle/CCParticleBatchNode.js
index 1a2200f93e..3db6117391 100644
--- a/cocos2d/particle/CCParticleBatchNode.js
+++ b/cocos2d/particle/CCParticleBatchNode.js
@@ -71,10 +71,10 @@ cc.PARTICLE_DEFAULT_CAPACITY = 500;
* var particleBatchNode = new cc.ParticleBatchNode(texture, 30);
*/
cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
- textureAtlas:null,
+ textureAtlas: null,
//the blend function used for drawing the quads
- _blendFunc:null,
- _className:"ParticleBatchNode",
+ _blendFunc: null,
+ _className: "ParticleBatchNode",
/**
* initializes the particle system with the name of a file on disk (for a list of supported formats look at the cc.Texture2D class), a capacity of particles
@@ -91,9 +91,9 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* var texture = cc.TextureCache.getInstance().addImage("res/grossini_dance.png");
* var particleBatchNode = new cc.ParticleBatchNode(texture, 30);
*/
- ctor:function (fileImage, capacity) {
+ ctor: function (fileImage, capacity) {
cc.Node.prototype.ctor.call(this);
- this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST};
+ this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST};
if (cc.isString(fileImage)) {
this.init(fileImage, capacity);
} else if (fileImage instanceof cc.Texture2D) {
@@ -101,8 +101,8 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
}
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return new cc.ParticleBatchNode.CanvasRenderCmd(this);
else
return new cc.ParticleBatchNode.WebGLRenderCmd(this);
@@ -114,7 +114,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* @param {Number} capacity
* @return {Boolean}
*/
- initWithTexture:function (texture, capacity) {
+ initWithTexture: function (texture, capacity) {
this.textureAtlas = new cc.TextureAtlas();
this.textureAtlas.initWithTexture(texture, capacity);
@@ -131,7 +131,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* @param {Number} capacity
* @return {Boolean}
*/
- initWithFile:function (fileImage, capacity) {
+ initWithFile: function (fileImage, capacity) {
var tex = cc.textureCache.addImage(fileImage);
return this.initWithTexture(tex, capacity);
},
@@ -142,34 +142,45 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* @param {Number} capacity
* @return {Boolean}
*/
- init:function (fileImage, capacity) {
+ init: function (fileImage, capacity) {
var tex = cc.textureCache.addImage(fileImage);
return this.initWithTexture(tex, capacity);
},
+ visit: function (parent) {
+ // quick return if not visible
+ if (!this._visible)
+ return;
+
+ var cmd = this._renderCmd;
+ cmd.visit(parent && parent._renderCmd);
+ renderer.pushRenderCommand(cmd);
+ cmd._dirtyFlag = 0;
+ },
+
/**
* Add a child into the cc.ParticleBatchNode
* @param {cc.ParticleSystem} child
* @param {Number} zOrder
* @param {Number} tag
*/
- addChild:function (child, zOrder, tag) {
- if(!child)
+ addChild: function (child, zOrder, tag) {
+ if (!child)
throw new Error("cc.ParticleBatchNode.addChild() : child should be non-null");
- if(!(child instanceof cc.ParticleSystem))
+ if (!(child instanceof cc.ParticleSystem))
throw new Error("cc.ParticleBatchNode.addChild() : only supports cc.ParticleSystem as children");
zOrder = (zOrder == null) ? child.zIndex : zOrder;
tag = (tag == null) ? child.tag : tag;
- if(child.getTexture() !== this.textureAtlas.texture)
+ if (child.getTexture() !== this.textureAtlas.texture)
throw new Error("cc.ParticleSystem.addChild() : the child is not using the same texture id");
// If this is the 1st children, then copy blending function
var childBlendFunc = child.getBlendFunc();
if (this._children.length === 0)
this.setBlendFunc(childBlendFunc);
- else{
- if((childBlendFunc.src !== this._blendFunc.src) || (childBlendFunc.dst !== this._blendFunc.dst)){
+ else {
+ if ((childBlendFunc.src !== this._blendFunc.src) || (childBlendFunc.dst !== this._blendFunc.dst)) {
cc.log("cc.ParticleSystem.addChild() : Can't add a ParticleSystem that uses a different blending function");
return;
}
@@ -198,7 +209,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* @param {cc.ParticleSystem} pSystem
* @param {Number} index
*/
- insertChild:function (pSystem, index) {
+ insertChild: function (pSystem, index) {
var totalParticles = pSystem.getTotalParticles();
var locTextureAtlas = this.textureAtlas;
var totalQuads = locTextureAtlas.totalQuads;
@@ -222,14 +233,14 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* @param {cc.ParticleSystem} child
* @param {Boolean} cleanup
*/
- removeChild:function (child, cleanup) {
+ removeChild: function (child, cleanup) {
// explicit nil handling
if (child == null)
return;
- if(!(child instanceof cc.ParticleSystem))
+ if (!(child instanceof cc.ParticleSystem))
throw new Error("cc.ParticleBatchNode.removeChild(): only supports cc.ParticleSystem as children");
- if(this._children.indexOf(child) === -1){
+ if (this._children.indexOf(child) === -1) {
cc.log("cc.ParticleBatchNode.removeChild(): doesn't contain the sprite. Can't remove it");
return;
}
@@ -254,12 +265,12 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* @param {cc.ParticleSystem} child
* @param {Number} zOrder
*/
- reorderChild:function (child, zOrder) {
- if(!child)
+ reorderChild: function (child, zOrder) {
+ if (!child)
throw new Error("cc.ParticleBatchNode.reorderChild(): child should be non-null");
- if(!(child instanceof cc.ParticleSystem))
+ if (!(child instanceof cc.ParticleSystem))
throw new Error("cc.ParticleBatchNode.reorderChild(): only supports cc.QuadParticleSystems as children");
- if(this._children.indexOf(child) === -1){
+ if (this._children.indexOf(child) === -1) {
cc.log("cc.ParticleBatchNode.reorderChild(): Child doesn't belong to batch");
return;
}
@@ -306,14 +317,14 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* @param {Number} index
* @param {Boolean} doCleanup
*/
- removeChildAtIndex:function (index, doCleanup) {
+ removeChildAtIndex: function (index, doCleanup) {
this.removeChild(this._children[i], doCleanup);
},
/**
* @param {Boolean} [doCleanup=true]
*/
- removeAllChildren:function (doCleanup) {
+ removeAllChildren: function (doCleanup) {
var locChildren = this._children;
for (var i = 0; i < locChildren.length; i++) {
locChildren[i].setBatchNode(null);
@@ -326,7 +337,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* disables a particle by inserting a 0'd quad into the texture atlas
* @param {Number} particleIndex
*/
- disableParticle:function (particleIndex) {
+ disableParticle: function (particleIndex) {
var quad = this.textureAtlas.quads[particleIndex];
quad.br.vertices.x = quad.br.vertices.y = quad.tr.vertices.x = quad.tr.vertices.y =
quad.tl.vertices.x = quad.tl.vertices.y = quad.bl.vertices.x = quad.bl.vertices.y = 0.0;
@@ -337,7 +348,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* returns the used texture
* @return {cc.Texture2D}
*/
- getTexture:function () {
+ getTexture: function () {
return this.textureAtlas.texture;
},
@@ -345,7 +356,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* sets a new texture. it will be retained
* @param {cc.Texture2D} texture
*/
- setTexture:function (texture) {
+ setTexture: function (texture) {
this.textureAtlas.texture = texture;
// If the new texture has No premultiplied alpha, AND the blendFunc hasn't been changed, then update it
@@ -361,11 +372,11 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* @param {Number|Object} src
* @param {Number} dst
*/
- setBlendFunc:function (src, dst) {
- if (dst === undefined){
+ setBlendFunc: function (src, dst) {
+ if (dst === undefined) {
this._blendFunc.src = src.src;
this._blendFunc.dst = src.dst;
- } else{
+ } else {
this._blendFunc.src = src;
this._blendFunc.src = dst;
}
@@ -375,11 +386,11 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* returns the blending function used for the texture
* @return {cc.BlendFunc}
*/
- getBlendFunc:function () {
+ getBlendFunc: function () {
return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst);
},
- _updateAllAtlasIndexes:function () {
+ _updateAllAtlasIndexes: function () {
var index = 0;
var locChildren = this._children;
for (var i = 0; i < locChildren.length; i++) {
@@ -389,7 +400,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
}
},
- _increaseAtlasCapacityTo:function (quantity) {
+ _increaseAtlasCapacityTo: function (quantity) {
cc.log("cocos2d: cc.ParticleBatchNode: resizing TextureAtlas capacity from [" + this.textureAtlas.getCapacity()
+ "] to [" + quantity + "].");
@@ -399,7 +410,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
}
},
- _searchNewPositionInChildrenForZ:function (z) {
+ _searchNewPositionInChildrenForZ: function (z) {
var locChildren = this._children;
var count = locChildren.length;
for (var i = 0; i < count; i++) {
@@ -409,7 +420,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
return count;
},
- _getCurrentIndex:function (child, z) {
+ _getCurrentIndex: function (child, z) {
var foundCurrentIdx = false;
var foundNewIdx = false;
@@ -441,7 +452,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
if (!foundNewIdx)
newIndex = count;
newIndex += minusOne;
- return {newIndex:newIndex, oldIndex:oldIndex};
+ return {newIndex: newIndex, oldIndex: oldIndex};
},
//
@@ -457,10 +468,10 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
// @return {Number}
// @private
//
- _addChildHelper:function (child, z, aTag) {
- if(!child)
+ _addChildHelper: function (child, z, aTag) {
+ if (!child)
throw new Error("cc.ParticleBatchNode._addChildHelper(): child should be non-null");
- if(child.parent){
+ if (child.parent) {
cc.log("cc.ParticleBatchNode._addChildHelper(): child already added. It can't be added again");
return null;
}
@@ -477,13 +488,13 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
child._setLocalZOrder(z);
child.parent = this;
if (this._running) {
- child.onEnter();
- child.onEnterTransitionDidFinish();
+ child._performRecursive(cc.Node._stateCallbackType.onEnter);
+ child._performRecursive(cc.Node._stateCallbackType.onEnterTransitionDidFinish);
}
return pos;
},
- _updateBlendFunc:function () {
+ _updateBlendFunc: function () {
if (!this.textureAtlas.texture.hasPremultipliedAlpha()) {
this._blendFunc.src = cc.SRC_ALPHA;
this._blendFunc.dst = cc.ONE_MINUS_SRC_ALPHA;
@@ -494,7 +505,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* return the texture atlas used for drawing the quads
* @return {cc.TextureAtlas}
*/
- getTextureAtlas:function () {
+ getTextureAtlas: function () {
return this.textureAtlas;
},
@@ -502,7 +513,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* set the texture atlas used for drawing the quads
* @param {cc.TextureAtlas} textureAtlas
*/
- setTextureAtlas:function (textureAtlas) {
+ setTextureAtlas: function (textureAtlas) {
this.textureAtlas = textureAtlas;
}
});
diff --git a/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js b/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js
index 36da185ecb..6e0990d140 100644
--- a/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js
+++ b/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js
@@ -22,17 +22,18 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
+(function () {
/**
* cc.ParticleBatchNode's rendering objects of Canvas
*/
- cc.ParticleBatchNode.CanvasRenderCmd = function(renderable){
- cc.Node.CanvasRenderCmd.call(this, renderable);
+ cc.ParticleBatchNode.CanvasRenderCmd = function (renderable) {
+ this._rootCtor(renderable);
this._needDraw = false;
};
var proto = cc.ParticleBatchNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
proto.constructor = cc.ParticleBatchNode.CanvasRenderCmd;
- proto._initWithTexture = function(){};
+ proto._initWithTexture = function () {
+ };
})();
diff --git a/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js b/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js
index 44cea2f052..3dda639728 100644
--- a/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js
+++ b/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js
@@ -22,12 +22,12 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
+(function () {
/**
* cc.ParticleBatchNode's rendering objects of WebGL
*/
- cc.ParticleBatchNode.WebGLRenderCmd = function(renderable){
- cc.Node.WebGLRenderCmd.call(this, renderable);
+ cc.ParticleBatchNode.WebGLRenderCmd = function (renderable) {
+ this._rootCtor(renderable);
this._needDraw = true;
this._matrix = new cc.math.Matrix4();
this._matrix.identity();
@@ -55,29 +55,7 @@
_t.textureAtlas.drawQuads();
};
- proto._initWithTexture = function(){
+ proto._initWithTexture = function () {
this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR);
};
-
- proto.visit = function(parentCmd){
- var node = this._node;
- // CAREFUL:
- // This visit is almost identical to cc.Node#visit
- // with the exception that it doesn't call visit on it's children
- //
- // The alternative is to have a void cc.Sprite#visit, but
- // although this is less mantainable, is faster
- //
- if (!node._visible)
- return;
-
- parentCmd = parentCmd || this.getParentRenderCmd();
- if (parentCmd)
- this._curLevel = parentCmd._curLevel + 1;
- this._syncStatus(parentCmd);
-
- cc.renderer.pushRenderCommand(this);
-
- this._dirtyFlag = 0;
- };
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js
index 6239d7adaa..01e2759c33 100644
--- a/cocos2d/particle/CCParticleSystem.js
+++ b/cocos2d/particle/CCParticleSystem.js
@@ -64,10 +64,10 @@
* @param {cc.Particle.ModeA} [modeB=]
*/
cc.Particle = function (pos, startPos, color, deltaColor, size, deltaSize, rotation, deltaRotation, timeToLive, atlasIndex, modeA, modeB) {
- this.pos = pos ? pos : cc.p(0,0);
- this.startPos = startPos ? startPos : cc.p(0,0);
- this.color = color ? color : {r:0, g: 0, b:0, a:255};
- this.deltaColor = deltaColor ? deltaColor : {r:0, g: 0, b:0, a:255} ;
+ this.pos = pos ? pos : cc.p(0, 0);
+ this.startPos = startPos ? startPos : cc.p(0, 0);
+ this.color = color ? color : {r: 0, g: 0, b: 0, a: 255};
+ this.deltaColor = deltaColor ? deltaColor : {r: 0, g: 0, b: 0, a: 255};
this.size = size || 0;
this.deltaSize = deltaSize || 0;
this.rotation = rotation || 0;
@@ -89,7 +89,7 @@ cc.Particle = function (pos, startPos, color, deltaColor, size, deltaSize, rotat
* @param {Number} tangentialAccel
*/
cc.Particle.ModeA = function (dir, radialAccel, tangentialAccel) {
- this.dir = dir ? dir : cc.p(0,0);
+ this.dir = dir ? dir : cc.p(0, 0);
this.radialAccel = radialAccel || 0;
this.tangentialAccel = tangentialAccel || 0;
};
@@ -111,8 +111,8 @@ cc.Particle.ModeB = function (angle, degreesPerSecond, radius, deltaRadius) {
};
/**
- * Array of Point instances used to optimize particle updates
- */
+ * Array of Point instances used to optimize particle updates
+ */
cc.Particle.TemporaryPoints = [
cc.p(),
cc.p(),
@@ -211,7 +211,7 @@ cc.Particle.TemporaryPoints = [
* emitter.startSpin = 0;
*/
cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
- _className:"ParticleSystem",
+ _className: "ParticleSystem",
//***********variables*************
_plistFile: "",
//! time elapsed since the start of the system (in seconds)
@@ -285,12 +285,12 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Constructor of cc.ParticleSystem
* @param {String|Number} plistFile
*/
- ctor:function (plistFile) {
+ ctor: function (plistFile) {
cc.Node.prototype.ctor.call(this);
this.emitterMode = cc.ParticleSystem.MODE_GRAVITY;
this.modeA = new cc.ParticleSystem.ModeA();
this.modeB = new cc.ParticleSystem.ModeB();
- this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST};
+ this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST};
this._particles = [];
this._sourcePosition = cc.p(0, 0);
@@ -348,8 +348,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
}
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return new cc.ParticleSystem.CanvasRenderCmd(this);
else
return new cc.ParticleSystem.WebGLRenderCmd(this);
@@ -360,8 +360,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* It's very expensive to change color on Canvas mode, so if set it to true, particle system will ignore the changing color operation.
* @param {boolean} ignore
*/
- ignoreColor: function(ignore){
- this._dontTint = ignore;
+ ignoreColor: function (ignore) {
+ this._dontTint = ignore;
},
/**
@@ -370,7 +370,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
*
* @param {cc.Rect} pointRect
*/
- initTexCoordsWithRect:function (pointRect) {
+ initTexCoordsWithRect: function (pointRect) {
this._renderCmd.initTexCoordsWithRect(pointRect);
},
@@ -378,7 +378,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* return weak reference to the cc.SpriteBatchNode that renders the cc.Sprite
* @return {cc.ParticleBatchNode}
*/
- getBatchNode:function () {
+ getBatchNode: function () {
return this._batchNode;
},
@@ -386,7 +386,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set weak reference to the cc.SpriteBatchNode that renders the cc.Sprite
* @param {cc.ParticleBatchNode} batchNode
*/
- setBatchNode:function (batchNode) {
+ setBatchNode: function (batchNode) {
this._renderCmd.setBatchNode(batchNode);
},
@@ -394,7 +394,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* return index of system in batch node array
* @return {Number}
*/
- getAtlasIndex:function () {
+ getAtlasIndex: function () {
return this.atlasIndex;
},
@@ -402,7 +402,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set index of system in batch node array
* @param {Number} atlasIndex
*/
- setAtlasIndex:function (atlasIndex) {
+ setAtlasIndex: function (atlasIndex) {
this.atlasIndex = atlasIndex;
},
@@ -410,7 +410,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return DrawMode of ParticleSystem (Canvas Mode only)
* @return {Number}
*/
- getDrawMode:function () {
+ getDrawMode: function () {
return this._renderCmd.getDrawMode();
},
@@ -418,7 +418,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* DrawMode of ParticleSystem setter (Canvas Mode only)
* @param {Number} drawMode
*/
- setDrawMode:function (drawMode) {
+ setDrawMode: function (drawMode) {
this._renderCmd.setDrawMode(drawMode);
},
@@ -426,7 +426,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return ShapeType of ParticleSystem (Canvas Mode only)
* @return {Number}
*/
- getShapeType:function () {
+ getShapeType: function () {
return this._renderCmd.getShapeType();
},
@@ -434,7 +434,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* ShapeType of ParticleSystem setter (Canvas Mode only)
* @param {Number} shapeType
*/
- setShapeType:function (shapeType) {
+ setShapeType: function (shapeType) {
this._renderCmd.setShapeType(shapeType);
},
@@ -442,7 +442,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return ParticleSystem is active
* @return {Boolean}
*/
- isActive:function () {
+ isActive: function () {
return this._isActive;
},
@@ -450,7 +450,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Quantity of particles that are being simulated at the moment
* @return {Number}
*/
- getParticleCount:function () {
+ getParticleCount: function () {
return this.particleCount;
},
@@ -458,7 +458,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Quantity of particles setter
* @param {Number} particleCount
*/
- setParticleCount:function (particleCount) {
+ setParticleCount: function (particleCount) {
this.particleCount = particleCount;
},
@@ -466,7 +466,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* How many seconds the emitter wil run. -1 means 'forever'
* @return {Number}
*/
- getDuration:function () {
+ getDuration: function () {
return this.duration;
},
@@ -474,7 +474,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set run seconds of the emitter
* @param {Number} duration
*/
- setDuration:function (duration) {
+ setDuration: function (duration) {
this.duration = duration;
},
@@ -482,7 +482,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return sourcePosition of the emitter
* @return {cc.Point | Object}
*/
- getSourcePosition:function () {
+ getSourcePosition: function () {
return {x: this._sourcePosition.x, y: this._sourcePosition.y};
},
@@ -490,15 +490,16 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* sourcePosition of the emitter setter
* @param sourcePosition
*/
- setSourcePosition:function (sourcePosition) {
- this._sourcePosition = sourcePosition;
+ setSourcePosition: function (sourcePosition) {
+ this._sourcePosition.x = sourcePosition.x;
+ this._sourcePosition.y = sourcePosition.y;
},
/**
* Return Position variance of the emitter
* @return {cc.Point | Object}
*/
- getPosVar:function () {
+ getPosVar: function () {
return {x: this._posVar.x, y: this._posVar.y};
},
@@ -506,15 +507,16 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Position variance of the emitter setter
* @param {cc.Point} posVar
*/
- setPosVar:function (posVar) {
- this._posVar = posVar;
+ setPosVar: function (posVar) {
+ this._posVar.x = posVar.x;
+ this._posVar.y = posVar.y;
},
/**
* Return life of each particle
* @return {Number}
*/
- getLife:function () {
+ getLife: function () {
return this.life;
},
@@ -522,7 +524,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* life of each particle setter
* @param {Number} life
*/
- setLife:function (life) {
+ setLife: function (life) {
this.life = life;
},
@@ -530,7 +532,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return life variance of each particle
* @return {Number}
*/
- getLifeVar:function () {
+ getLifeVar: function () {
return this.lifeVar;
},
@@ -538,7 +540,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* life variance of each particle setter
* @param {Number} lifeVar
*/
- setLifeVar:function (lifeVar) {
+ setLifeVar: function (lifeVar) {
this.lifeVar = lifeVar;
},
@@ -546,7 +548,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return angle of each particle
* @return {Number}
*/
- getAngle:function () {
+ getAngle: function () {
return this.angle;
},
@@ -554,7 +556,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* angle of each particle setter
* @param {Number} angle
*/
- setAngle:function (angle) {
+ setAngle: function (angle) {
this.angle = angle;
},
@@ -562,7 +564,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return angle variance of each particle
* @return {Number}
*/
- getAngleVar:function () {
+ getAngleVar: function () {
return this.angleVar;
},
@@ -570,7 +572,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* angle variance of each particle setter
* @param angleVar
*/
- setAngleVar:function (angleVar) {
+ setAngleVar: function (angleVar) {
this.angleVar = angleVar;
},
@@ -579,8 +581,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return Gravity of emitter
* @return {cc.Point}
*/
- getGravity:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ getGravity: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getGravity() : Particle Mode should be Gravity");
var locGravity = this.modeA.gravity;
return cc.p(locGravity.x, locGravity.y);
@@ -590,8 +592,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Gravity of emitter setter
* @param {cc.Point} gravity
*/
- setGravity:function (gravity) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ setGravity: function (gravity) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setGravity() : Particle Mode should be Gravity");
this.modeA.gravity = gravity;
},
@@ -600,8 +602,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return Speed of each particle
* @return {Number}
*/
- getSpeed:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ getSpeed: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getSpeed() : Particle Mode should be Gravity");
return this.modeA.speed;
},
@@ -610,8 +612,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Speed of each particle setter
* @param {Number} speed
*/
- setSpeed:function (speed) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ setSpeed: function (speed) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setSpeed() : Particle Mode should be Gravity");
this.modeA.speed = speed;
},
@@ -620,8 +622,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* return speed variance of each particle. Only available in 'Gravity' mode.
* @return {Number}
*/
- getSpeedVar:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ getSpeedVar: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getSpeedVar() : Particle Mode should be Gravity");
return this.modeA.speedVar;
},
@@ -630,8 +632,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* speed variance of each particle setter. Only available in 'Gravity' mode.
* @param {Number} speedVar
*/
- setSpeedVar:function (speedVar) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ setSpeedVar: function (speedVar) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setSpeedVar() : Particle Mode should be Gravity");
this.modeA.speedVar = speedVar;
},
@@ -640,8 +642,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return tangential acceleration of each particle. Only available in 'Gravity' mode.
* @return {Number}
*/
- getTangentialAccel:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ getTangentialAccel: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getTangentialAccel() : Particle Mode should be Gravity");
return this.modeA.tangentialAccel;
},
@@ -650,8 +652,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Tangential acceleration of each particle setter. Only available in 'Gravity' mode.
* @param {Number} tangentialAccel
*/
- setTangentialAccel:function (tangentialAccel) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ setTangentialAccel: function (tangentialAccel) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setTangentialAccel() : Particle Mode should be Gravity");
this.modeA.tangentialAccel = tangentialAccel;
},
@@ -660,8 +662,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return tangential acceleration variance of each particle. Only available in 'Gravity' mode.
* @return {Number}
*/
- getTangentialAccelVar:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ getTangentialAccelVar: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getTangentialAccelVar() : Particle Mode should be Gravity");
return this.modeA.tangentialAccelVar;
},
@@ -670,8 +672,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* tangential acceleration variance of each particle setter. Only available in 'Gravity' mode.
* @param {Number} tangentialAccelVar
*/
- setTangentialAccelVar:function (tangentialAccelVar) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ setTangentialAccelVar: function (tangentialAccelVar) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setTangentialAccelVar() : Particle Mode should be Gravity");
this.modeA.tangentialAccelVar = tangentialAccelVar;
},
@@ -680,8 +682,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return radial acceleration of each particle. Only available in 'Gravity' mode.
* @return {Number}
*/
- getRadialAccel:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ getRadialAccel: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getRadialAccel() : Particle Mode should be Gravity");
return this.modeA.radialAccel;
},
@@ -690,8 +692,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* radial acceleration of each particle setter. Only available in 'Gravity' mode.
* @param {Number} radialAccel
*/
- setRadialAccel:function (radialAccel) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ setRadialAccel: function (radialAccel) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setRadialAccel() : Particle Mode should be Gravity");
this.modeA.radialAccel = radialAccel;
},
@@ -700,8 +702,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return radial acceleration variance of each particle. Only available in 'Gravity' mode.
* @return {Number}
*/
- getRadialAccelVar:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ getRadialAccelVar: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getRadialAccelVar() : Particle Mode should be Gravity");
return this.modeA.radialAccelVar;
},
@@ -710,8 +712,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* radial acceleration variance of each particle setter. Only available in 'Gravity' mode.
* @param {Number} radialAccelVar
*/
- setRadialAccelVar:function (radialAccelVar) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ setRadialAccelVar: function (radialAccelVar) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setRadialAccelVar() : Particle Mode should be Gravity");
this.modeA.radialAccelVar = radialAccelVar;
},
@@ -720,8 +722,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get the rotation of each particle to its direction Only available in 'Gravity' mode.
* @returns {boolean}
*/
- getRotationIsDir: function(){
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ getRotationIsDir: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getRotationIsDir() : Particle Mode should be Gravity");
return this.modeA.rotationIsDir;
},
@@ -730,8 +732,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set the rotation of each particle to its direction Only available in 'Gravity' mode.
* @param {boolean} t
*/
- setRotationIsDir: function(t){
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ setRotationIsDir: function (t) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setRotationIsDir() : Particle Mode should be Gravity");
this.modeA.rotationIsDir = t;
},
@@ -741,8 +743,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return starting radius of the particles. Only available in 'Radius' mode.
* @return {Number}
*/
- getStartRadius:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ getStartRadius: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.getStartRadius() : Particle Mode should be Radius");
return this.modeB.startRadius;
},
@@ -751,8 +753,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* starting radius of the particles setter. Only available in 'Radius' mode.
* @param {Number} startRadius
*/
- setStartRadius:function (startRadius) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ setStartRadius: function (startRadius) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.setStartRadius() : Particle Mode should be Radius");
this.modeB.startRadius = startRadius;
},
@@ -761,8 +763,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return starting radius variance of the particles. Only available in 'Radius' mode.
* @return {Number}
*/
- getStartRadiusVar:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ getStartRadiusVar: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.getStartRadiusVar() : Particle Mode should be Radius");
return this.modeB.startRadiusVar;
},
@@ -771,8 +773,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* starting radius variance of the particles setter. Only available in 'Radius' mode.
* @param {Number} startRadiusVar
*/
- setStartRadiusVar:function (startRadiusVar) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ setStartRadiusVar: function (startRadiusVar) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.setStartRadiusVar() : Particle Mode should be Radius");
this.modeB.startRadiusVar = startRadiusVar;
},
@@ -781,8 +783,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return ending radius of the particles. Only available in 'Radius' mode.
* @return {Number}
*/
- getEndRadius:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ getEndRadius: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.getEndRadius() : Particle Mode should be Radius");
return this.modeB.endRadius;
},
@@ -791,8 +793,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* ending radius of the particles setter. Only available in 'Radius' mode.
* @param {Number} endRadius
*/
- setEndRadius:function (endRadius) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ setEndRadius: function (endRadius) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.setEndRadius() : Particle Mode should be Radius");
this.modeB.endRadius = endRadius;
},
@@ -801,8 +803,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return ending radius variance of the particles. Only available in 'Radius' mode.
* @return {Number}
*/
- getEndRadiusVar:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ getEndRadiusVar: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.getEndRadiusVar() : Particle Mode should be Radius");
return this.modeB.endRadiusVar;
},
@@ -811,8 +813,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* ending radius variance of the particles setter. Only available in 'Radius' mode.
* @param endRadiusVar
*/
- setEndRadiusVar:function (endRadiusVar) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ setEndRadiusVar: function (endRadiusVar) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.setEndRadiusVar() : Particle Mode should be Radius");
this.modeB.endRadiusVar = endRadiusVar;
},
@@ -821,8 +823,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode.
* @return {Number}
*/
- getRotatePerSecond:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ getRotatePerSecond: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.getRotatePerSecond() : Particle Mode should be Radius");
return this.modeB.rotatePerSecond;
},
@@ -831,8 +833,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode.
* @param {Number} degrees
*/
- setRotatePerSecond:function (degrees) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ setRotatePerSecond: function (degrees) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.setRotatePerSecond() : Particle Mode should be Radius");
this.modeB.rotatePerSecond = degrees;
},
@@ -841,8 +843,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return Variance in degrees for rotatePerSecond. Only available in 'Radius' mode.
* @return {Number}
*/
- getRotatePerSecondVar:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ getRotatePerSecondVar: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.getRotatePerSecondVar() : Particle Mode should be Radius");
return this.modeB.rotatePerSecondVar;
},
@@ -851,30 +853,30 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Variance in degrees for rotatePerSecond setter. Only available in 'Radius' mode.
* @param degrees
*/
- setRotatePerSecondVar:function (degrees) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ setRotatePerSecondVar: function (degrees) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.setRotatePerSecondVar() : Particle Mode should be Radius");
this.modeB.rotatePerSecondVar = degrees;
},
//////////////////////////////////////////////////////////////////////////
//don't use a transform matrix, this is faster
- setScale:function (scale, scaleY) {
+ setScale: function (scale, scaleY) {
this._transformSystemDirty = true;
cc.Node.prototype.setScale.call(this, scale, scaleY);
},
- setRotation:function (newRotation) {
+ setRotation: function (newRotation) {
this._transformSystemDirty = true;
cc.Node.prototype.setRotation.call(this, newRotation);
},
- setScaleX:function (newScaleX) {
+ setScaleX: function (newScaleX) {
this._transformSystemDirty = true;
cc.Node.prototype.setScaleX.call(this, newScaleX);
},
- setScaleY:function (newScaleY) {
+ setScaleY: function (newScaleY) {
this._transformSystemDirty = true;
cc.Node.prototype.setScaleY.call(this, newScaleY);
},
@@ -883,7 +885,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get start size in pixels of each particle
* @return {Number}
*/
- getStartSize:function () {
+ getStartSize: function () {
return this.startSize;
},
@@ -891,7 +893,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set start size in pixels of each particle
* @param {Number} startSize
*/
- setStartSize:function (startSize) {
+ setStartSize: function (startSize) {
this.startSize = startSize;
},
@@ -899,7 +901,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get size variance in pixels of each particle
* @return {Number}
*/
- getStartSizeVar:function () {
+ getStartSizeVar: function () {
return this.startSizeVar;
},
@@ -907,7 +909,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set size variance in pixels of each particle
* @param {Number} startSizeVar
*/
- setStartSizeVar:function (startSizeVar) {
+ setStartSizeVar: function (startSizeVar) {
this.startSizeVar = startSizeVar;
},
@@ -915,7 +917,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get end size in pixels of each particle
* @return {Number}
*/
- getEndSize:function () {
+ getEndSize: function () {
return this.endSize;
},
@@ -923,7 +925,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set end size in pixels of each particle
* @param endSize
*/
- setEndSize:function (endSize) {
+ setEndSize: function (endSize) {
this.endSize = endSize;
},
@@ -931,7 +933,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get end size variance in pixels of each particle
* @return {Number}
*/
- getEndSizeVar:function () {
+ getEndSizeVar: function () {
return this.endSizeVar;
},
@@ -939,7 +941,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set end size variance in pixels of each particle
* @param {Number} endSizeVar
*/
- setEndSizeVar:function (endSizeVar) {
+ setEndSizeVar: function (endSizeVar) {
this.endSizeVar = endSizeVar;
},
@@ -947,7 +949,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set start color of each particle
* @return {cc.Color}
*/
- getStartColor:function () {
+ getStartColor: function () {
return cc.color(this._startColor.r, this._startColor.g, this._startColor.b, this._startColor.a);
},
@@ -955,15 +957,18 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get start color of each particle
* @param {cc.Color} startColor
*/
- setStartColor:function (startColor) {
- this._startColor = cc.color(startColor);
+ setStartColor: function (startColor) {
+ this._startColor.r = startColor.r;
+ this._startColor.g = startColor.g;
+ this._startColor.b = startColor.b;
+ this._startColor.a = startColor.a;
},
/**
* get start color variance of each particle
* @return {cc.Color}
*/
- getStartColorVar:function () {
+ getStartColorVar: function () {
return cc.color(this._startColorVar.r, this._startColorVar.g, this._startColorVar.b, this._startColorVar.a);
},
@@ -971,15 +976,18 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set start color variance of each particle
* @param {cc.Color} startColorVar
*/
- setStartColorVar:function (startColorVar) {
- this._startColorVar = cc.color(startColorVar);
+ setStartColorVar: function (startColorVar) {
+ this._startColorVar.r = startColorVar.r;
+ this._startColorVar.g = startColorVar.g;
+ this._startColorVar.b = startColorVar.b;
+ this._startColorVar.a = startColorVar.a;
},
/**
* get end color and end color variation of each particle
* @return {cc.Color}
*/
- getEndColor:function () {
+ getEndColor: function () {
return cc.color(this._endColor.r, this._endColor.g, this._endColor.b, this._endColor.a);
},
@@ -987,15 +995,18 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set end color and end color variation of each particle
* @param {cc.Color} endColor
*/
- setEndColor:function (endColor) {
- this._endColor = cc.color(endColor);
+ setEndColor: function (endColor) {
+ this._endColor.r = endColor.r;
+ this._endColor.g = endColor.g;
+ this._endColor.b = endColor.b;
+ this._endColor.a = endColor.a;
},
/**
* get end color variance of each particle
* @return {cc.Color}
*/
- getEndColorVar:function () {
+ getEndColorVar: function () {
return cc.color(this._endColorVar.r, this._endColorVar.g, this._endColorVar.b, this._endColorVar.a);
},
@@ -1003,15 +1014,18 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set end color variance of each particle
* @param {cc.Color} endColorVar
*/
- setEndColorVar:function (endColorVar) {
- this._endColorVar = cc.color(endColorVar);
+ setEndColorVar: function (endColorVar) {
+ this._endColorVar.r = endColorVar.r;
+ this._endColorVar.g = endColorVar.g;
+ this._endColorVar.b = endColorVar.b;
+ this._endColorVar.a = endColorVar.a;
},
/**
* get initial angle of each particle
* @return {Number}
*/
- getStartSpin:function () {
+ getStartSpin: function () {
return this.startSpin;
},
@@ -1019,7 +1033,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set initial angle of each particle
* @param {Number} startSpin
*/
- setStartSpin:function (startSpin) {
+ setStartSpin: function (startSpin) {
this.startSpin = startSpin;
},
@@ -1027,7 +1041,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get initial angle variance of each particle
* @return {Number}
*/
- getStartSpinVar:function () {
+ getStartSpinVar: function () {
return this.startSpinVar;
},
@@ -1035,7 +1049,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set initial angle variance of each particle
* @param {Number} startSpinVar
*/
- setStartSpinVar:function (startSpinVar) {
+ setStartSpinVar: function (startSpinVar) {
this.startSpinVar = startSpinVar;
},
@@ -1043,7 +1057,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get end angle of each particle
* @return {Number}
*/
- getEndSpin:function () {
+ getEndSpin: function () {
return this.endSpin;
},
@@ -1051,7 +1065,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set end angle of each particle
* @param {Number} endSpin
*/
- setEndSpin:function (endSpin) {
+ setEndSpin: function (endSpin) {
this.endSpin = endSpin;
},
@@ -1059,7 +1073,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get end angle variance of each particle
* @return {Number}
*/
- getEndSpinVar:function () {
+ getEndSpinVar: function () {
return this.endSpinVar;
},
@@ -1067,7 +1081,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set end angle variance of each particle
* @param {Number} endSpinVar
*/
- setEndSpinVar:function (endSpinVar) {
+ setEndSpinVar: function (endSpinVar) {
this.endSpinVar = endSpinVar;
},
@@ -1075,7 +1089,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get emission rate of the particles
* @return {Number}
*/
- getEmissionRate:function () {
+ getEmissionRate: function () {
return this.emissionRate;
},
@@ -1083,7 +1097,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set emission rate of the particles
* @param {Number} emissionRate
*/
- setEmissionRate:function (emissionRate) {
+ setEmissionRate: function (emissionRate) {
this.emissionRate = emissionRate;
},
@@ -1091,7 +1105,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get maximum particles of the system
* @return {Number}
*/
- getTotalParticles:function () {
+ getTotalParticles: function () {
return this._totalParticles;
},
@@ -1099,7 +1113,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set maximum particles of the system
* @param {Number} tp totalParticles
*/
- setTotalParticles:function (tp) {
+ setTotalParticles: function (tp) {
this._renderCmd.setTotalParticles(tp);
},
@@ -1107,7 +1121,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get Texture of Particle System
* @return {cc.Texture2D}
*/
- getTexture:function () {
+ getTexture: function () {
return this._texture;
},
@@ -1115,15 +1129,15 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set Texture of Particle System
* @param {cc.Texture2D } texture
*/
- setTexture:function (texture) {
- if(!texture)
+ setTexture: function (texture) {
+ if (!texture)
return;
- if(texture.isLoaded()){
+ if (texture.isLoaded()) {
this.setTextureWithRect(texture, cc.rect(0, 0, texture.width, texture.height));
} else {
this._textureLoaded = false;
- texture.addEventListener("load", function(sender){
+ texture.addEventListener("load", function (sender) {
this._textureLoaded = true;
this.setTextureWithRect(sender, cc.rect(0, 0, sender.width, sender.height));
}, this);
@@ -1135,7 +1149,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get BlendFunc of Particle System
* @return {cc.BlendFunc}
*/
- getBlendFunc:function () {
+ getBlendFunc: function () {
return this._blendFunc;
},
@@ -1144,7 +1158,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* @param {Number} src
* @param {Number} dst
*/
- setBlendFunc:function (src, dst) {
+ setBlendFunc: function (src, dst) {
if (dst === undefined) {
if (this._blendFunc !== src) {
this._blendFunc = src;
@@ -1152,7 +1166,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
}
} else {
if (this._blendFunc.src !== src || this._blendFunc.dst !== dst) {
- this._blendFunc = {src:src, dst:dst};
+ this._blendFunc = {src: src, dst: dst};
this._updateBlendFunc();
}
}
@@ -1162,7 +1176,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* does the alpha value modify color getter
* @return {Boolean}
*/
- isOpacityModifyRGB:function () {
+ isOpacityModifyRGB: function () {
return this._opacityModifyRGB;
},
@@ -1170,7 +1184,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* does the alpha value modify color setter
* @param newValue
*/
- setOpacityModifyRGB:function (newValue) {
+ setOpacityModifyRGB: function (newValue) {
this._opacityModifyRGB = newValue;
},
@@ -1183,7 +1197,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* source blend function = GL_SRC_ALPHA;
* dest blend function = GL_ONE;
*/
- isBlendAdditive:function () {
+ isBlendAdditive: function () {
return (( this._blendFunc.src === cc.SRC_ALPHA && this._blendFunc.dst === cc.ONE) || (this._blendFunc.src === cc.ONE && this._blendFunc.dst === cc.ONE));
},
@@ -1193,7 +1207,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
*
* @param {Boolean} isBlendAdditive
*/
- setBlendAdditive:function (isBlendAdditive) {
+ setBlendAdditive: function (isBlendAdditive) {
var locBlendFunc = this._blendFunc;
if (isBlendAdditive) {
locBlendFunc.src = cc.SRC_ALPHA;
@@ -1207,7 +1221,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get particles movement type: Free or Grouped
* @return {Number}
*/
- getPositionType:function () {
+ getPositionType: function () {
return this.positionType;
},
@@ -1215,7 +1229,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set particles movement type: Free or Grouped
* @param {Number} positionType
*/
- setPositionType:function (positionType) {
+ setPositionType: function (positionType) {
this.positionType = positionType;
},
@@ -1225,7 +1239,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
*
* @return {Boolean}
*/
- isAutoRemoveOnFinish:function () {
+ isAutoRemoveOnFinish: function () {
return this.autoRemoveOnFinish;
},
@@ -1235,7 +1249,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
*
* @param {Boolean} isAutoRemoveOnFinish
*/
- setAutoRemoveOnFinish:function (isAutoRemoveOnFinish) {
+ setAutoRemoveOnFinish: function (isAutoRemoveOnFinish) {
this.autoRemoveOnFinish = isAutoRemoveOnFinish;
},
@@ -1243,7 +1257,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* return kind of emitter modes
* @return {Number}
*/
- getEmitterMode:function () {
+ getEmitterMode: function () {
return this.emitterMode;
},
@@ -1254,14 +1268,14 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
*
* @param {Number} emitterMode
*/
- setEmitterMode:function (emitterMode) {
+ setEmitterMode: function (emitterMode) {
this.emitterMode = emitterMode;
},
/**
* initializes a cc.ParticleSystem
*/
- init:function () {
+ init: function () {
return this.initWithTotalParticles(150);
},
@@ -1274,10 +1288,10 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* @param {String} plistFile
* @return {boolean}
*/
- initWithFile:function (plistFile) {
+ initWithFile: function (plistFile) {
this._plistFile = plistFile;
var dict = cc.loader.getRes(plistFile);
- if(!dict){
+ if (!dict) {
cc.log("cc.ParticleSystem.initWithFile(): Particles: file not found");
return false;
}
@@ -1290,7 +1304,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* return bounding box of particle system in world space
* @return {cc.Rect}
*/
- getBoundingBoxToWorld:function () {
+ getBoundingBoxToWorld: function () {
return cc.rect(0, 0, cc._canvas.width, cc._canvas.height);
},
@@ -1300,7 +1314,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* @param {String} dirname
* @return {Boolean}
*/
- initWithDictionary:function (dictionary, dirname) {
+ initWithDictionary: function (dictionary, dirname) {
var ret = false;
var buffer = null;
var image = null;
@@ -1353,7 +1367,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
// position
this.setPosition(parseFloat(locValueForKey("sourcePositionx", dictionary)),
- parseFloat(locValueForKey("sourcePositiony", dictionary)));
+ parseFloat(locValueForKey("sourcePositiony", dictionary)));
this._posVar.x = parseFloat(locValueForKey("sourcePositionVariancex", dictionary));
this._posVar.y = parseFloat(locValueForKey("sourcePositionVariancey", dictionary));
@@ -1391,13 +1405,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
locModeA.tangentialAccelVar = (pszTmp) ? parseFloat(pszTmp) : 0;
// rotation is dir
- var locRotationIsDir = locValueForKey("rotationIsDir", dictionary);
- if (locRotationIsDir !== null) {
- locRotationIsDir = locRotationIsDir.toString().toLowerCase();
- locModeA.rotationIsDir = (locRotationIsDir === "true" || locRotationIsDir === "1");
- }
- else
- locModeA.rotationIsDir = false;
+ var locRotationIsDir = locValueForKey("rotationIsDir", dictionary).toLowerCase();
+ locModeA.rotationIsDir = (locRotationIsDir != null && (locRotationIsDir === "true" || locRotationIsDir === "1"));
} else if (this.emitterMode === cc.ParticleSystem.MODE_RADIUS) {
// or Mode B: radius movement
var locModeB = this.modeB;
@@ -1449,24 +1458,24 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
var imageFormat = cc.getImageFormatByData(buffer);
- if(imageFormat !== cc.FMT_TIFF && imageFormat !== cc.FMT_PNG){
+ if (imageFormat !== cc.FMT_TIFF && imageFormat !== cc.FMT_PNG) {
cc.log("cc.ParticleSystem: unknown image format with Data");
return false;
}
var canvasObj = document.createElement("canvas");
- if(imageFormat === cc.FMT_PNG){
+ if (imageFormat === cc.FMT_PNG) {
var myPngObj = new cc.PNGReader(buffer);
myPngObj.render(canvasObj);
} else {
var myTIFFObj = cc.tiffReader;
- myTIFFObj.parseTIFF(buffer,canvasObj);
+ myTIFFObj.parseTIFF(buffer, canvasObj);
}
cc.textureCache.cacheImage(imgPath, canvasObj);
var addTexture = cc.textureCache.getTextureForKey(imgPath);
- if(!addTexture)
+ if (!addTexture)
cc.log("cc.ParticleSystem.initWithDictionary() : error loading the texture");
this.setTexture(addTexture);
}
@@ -1482,12 +1491,12 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* @param {Number} numberOfParticles
* @return {Boolean}
*/
- initWithTotalParticles:function (numberOfParticles) {
+ initWithTotalParticles: function (numberOfParticles) {
this._totalParticles = numberOfParticles;
var i, locParticles = this._particles;
locParticles.length = 0;
- for(i = 0; i< numberOfParticles; i++){
+ for (i = 0; i < numberOfParticles; i++) {
locParticles[i] = new cc.Particle();
}
@@ -1533,7 +1542,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* @function
* @see scheduleUpdate();
*/
- destroyParticleSystem:function () {
+ destroyParticleSystem: function () {
this.unscheduleUpdate();
},
@@ -1555,7 +1564,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Initializes a particle
* @param {cc.Particle} particle
*/
- initParticle:function (particle) {
+ initParticle: function (particle) {
var locRandomMinus11 = cc.randomMinus1To1;
// timeToLive
// no negative life. prevent division by 0
@@ -1612,7 +1621,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
// position
if (this.positionType === cc.ParticleSystem.TYPE_FREE)
particle.startPos = this.convertToWorldSpace(this._pointZeroForParticle);
- else if (this.positionType === cc.ParticleSystem.TYPE_RELATIVE){
+ else if (this.positionType === cc.ParticleSystem.TYPE_RELATIVE) {
particle.startPos.x = this._position.x;
particle.startPos.y = this._position.y;
}
@@ -1637,7 +1646,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
locParticleModeA.tangentialAccel = locModeA.tangentialAccel + locModeA.tangentialAccelVar * locRandomMinus11();
// rotation is dir
- if(locModeA.rotationIsDir)
+ if (locModeA.rotationIsDir)
particle.rotation = -cc.radiansToDegrees(cc.pToAngle(locParticleModeA.dir));
} else {
// Mode Radius: B
@@ -1658,7 +1667,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
/**
* stop emitting particles. Running particles will continue to run until they die
*/
- stopSystem:function () {
+ stopSystem: function () {
this._isActive = false;
this._elapsed = this.duration;
this._emitCounter = 0;
@@ -1667,19 +1676,19 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
/**
* Kill all living particles.
*/
- resetSystem:function () {
+ resetSystem: function () {
this._isActive = true;
this._elapsed = 0;
var locParticles = this._particles;
for (this._particleIdx = 0; this._particleIdx < this.particleCount; ++this._particleIdx)
- locParticles[this._particleIdx].timeToLive = 0 ;
+ locParticles[this._particleIdx].timeToLive = 0;
},
/**
* whether or not the system is full
* @return {Boolean}
*/
- isFull:function () {
+ isFull: function () {
return (this.particleCount >= this._totalParticles);
},
@@ -1688,14 +1697,14 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* @param {cc.Particle} particle
* @param {cc.Point} newPosition
*/
- updateQuadWithParticle:function (particle, newPosition) {
+ updateQuadWithParticle: function (particle, newPosition) {
this._renderCmd.updateQuadWithParticle(particle, newPosition);
},
/**
* should be overridden by subclasses
*/
- postStep:function () {
+ postStep: function () {
this._renderCmd.postStep();
},
@@ -1832,10 +1841,10 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
} else {
// life < 0
var currentIndex = selParticle.atlasIndex;
- if(this._particleIdx !== this.particleCount -1){
- var deadParticle = locParticles[this._particleIdx];
- locParticles[this._particleIdx] = locParticles[this.particleCount -1];
- locParticles[this.particleCount -1] = deadParticle;
+ if (this._particleIdx !== this.particleCount - 1) {
+ var deadParticle = locParticles[this._particleIdx];
+ locParticles[this._particleIdx] = locParticles[this.particleCount - 1];
+ locParticles[this.particleCount - 1] = deadParticle;
}
if (this._batchNode) {
//disable the switched particle
@@ -1862,7 +1871,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
/**
* update emitter's status (dt = 0)
*/
- updateWithNoTime:function () {
+ updateWithNoTime: function () {
this.update(0);
},
@@ -1873,7 +1882,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
// @return {String} "" if not found; return the string if found.
// @private
//
- _valueForKey:function (key, dict) {
+ _valueForKey: function (key, dict) {
if (dict) {
var pString = dict[key];
return pString != null ? pString : "";
@@ -1881,8 +1890,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
return "";
},
- _updateBlendFunc:function () {
- if(this._batchNode){
+ _updateBlendFunc: function () {
+ if (this._batchNode) {
cc.log("Can't change blending functions when the particle is being batched");
return;
}
@@ -1908,7 +1917,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
*
* @return {cc.ParticleSystem}
*/
- clone:function () {
+ clone: function () {
var retParticle = new cc.ParticleSystem();
// self, not super
@@ -1922,7 +1931,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
// blend function
var blend = this.getBlendFunc();
- retParticle.setBlendFunc(blend.src,blend.dst);
+ retParticle.setBlendFunc(blend.src, blend.dst);
// color
retParticle.setStartColor(this.getStartColor());
@@ -1941,15 +1950,15 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
// position
retParticle.setPosition(cc.p(this.x, this.y));
- retParticle.setPosVar(cc.p(this.getPosVar().x,this.getPosVar().y));
+ retParticle.setPosVar(cc.p(this.getPosVar().x, this.getPosVar().y));
retParticle.setPositionType(this.getPositionType());
// Spinning
- retParticle.setStartSpin(this.getStartSpin()||0);
- retParticle.setStartSpinVar(this.getStartSpinVar()||0);
- retParticle.setEndSpin(this.getEndSpin()||0);
- retParticle.setEndSpinVar(this.getEndSpinVar()||0);
+ retParticle.setStartSpin(this.getStartSpin() || 0);
+ retParticle.setStartSpinVar(this.getStartSpinVar() || 0);
+ retParticle.setEndSpin(this.getEndSpin() || 0);
+ retParticle.setEndSpinVar(this.getEndSpinVar() || 0);
retParticle.setEmitterMode(this.getEmitterMode());
@@ -1957,7 +1966,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
if (this.getEmitterMode() === cc.ParticleSystem.MODE_GRAVITY) {
// gravity
var gra = this.getGravity();
- retParticle.setGravity(cc.p(gra.x,gra.y));
+ retParticle.setGravity(cc.p(gra.x, gra.y));
// speed
retParticle.setSpeed(this.getSpeed());
@@ -1995,7 +2004,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
retParticle.setOpacityModifyRGB(this.isOpacityModifyRGB());
// texture
var texture = this.getTexture();
- if(texture){
+ if (texture) {
var size = texture.getContentSize();
retParticle.setTextureWithRect(texture, cc.rect(0, 0, size.width, size.height));
}
@@ -2042,7 +2051,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* listen the event that coming to foreground on Android (An empty function for native)
* @param {cc.Class} obj
*/
- listenBackToForeground:function (obj) {
+ listenBackToForeground: function (obj) {
//do nothing
}
});
@@ -2174,7 +2183,7 @@ cc.ParticleSystem.createWithTotalParticles = cc.ParticleSystem.create;
*/
cc.ParticleSystem.ModeA = function (gravity, speed, speedVar, tangentialAccel, tangentialAccelVar, radialAccel, radialAccelVar, rotationIsDir) {
/** Gravity value. Only available in 'Gravity' mode. */
- this.gravity = gravity ? gravity : cc.p(0,0);
+ this.gravity = gravity ? gravity : cc.p(0, 0);
/** speed of each particle. Only available in 'Gravity' mode. */
this.speed = speed || 0;
/** speed variance of each particle. Only available in 'Gravity' mode. */
diff --git a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js
index de78252346..781baf7004 100644
--- a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js
+++ b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js
@@ -25,37 +25,37 @@
/**
* ParticleSystem's canvas render command
*/
-(function(){
- cc.ParticleSystem.CanvasRenderCmd = function(renderable){
- cc.Node.CanvasRenderCmd.call(this, renderable);
+(function () {
+ cc.ParticleSystem.CanvasRenderCmd = function (renderable) {
+ this._rootCtor(renderable);
this._needDraw = true;
this._drawMode = cc.ParticleSystem.TEXTURE_MODE;
this._shapeType = cc.ParticleSystem.BALL_SHAPE;
this._pointRect = cc.rect(0, 0, 0, 0);
- this._tintCache = document.createElement("canvas");
+ this._tintCache = null;
};
var proto = cc.ParticleSystem.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
proto.constructor = cc.ParticleSystem.CanvasRenderCmd;
- proto.getDrawMode = function(){
+ proto.getDrawMode = function () {
return this._drawMode;
};
- proto.setDrawMode = function(drawMode){
+ proto.setDrawMode = function (drawMode) {
this._drawMode = drawMode;
};
- proto.getShapeType = function(){
+ proto.getShapeType = function () {
return this._shapeType;
};
- proto.setShapeType = function(shapeType){
+ proto.setShapeType = function (shapeType) {
this._shapeType = shapeType;
};
- proto.setBatchNode = function(batchNode){
+ proto.setBatchNode = function (batchNode) {
if (this._batchNode !== batchNode) {
this._node._batchNode = batchNode;
}
@@ -65,7 +65,7 @@
//do nothing
};
- proto.updateParticlePosition = function(particle, position){
+ proto.updateParticlePosition = function (particle, position) {
cc.pIn(particle.drawPos, position);
};
@@ -143,7 +143,10 @@
cc.g_NumberOfDraws++;
};
- proto._changeTextureColor = function(texture, color, rect){
+ proto._changeTextureColor = function (texture, color, rect) {
+ if (!this._tintCache) {
+ this._tintCache = document.createElement("canvas");
+ }
var tintCache = this._tintCache;
var textureContentSize = texture.getContentSize();
tintCache.width = textureContentSize.width;
@@ -151,16 +154,16 @@
return texture._generateColorTexture(color.r, color.g, color.b, rect, tintCache);
};
- proto.initTexCoordsWithRect = function(pointRect){
+ proto.initTexCoordsWithRect = function (pointRect) {
this._pointRect = pointRect;
};
- proto.setTotalParticles = function(tp){
+ proto.setTotalParticles = function (tp) {
//cc.assert(tp <= this._allocatedParticles, "Particle: resizing particle array only supported for quads");
this._node._totalParticles = (tp < 200) ? tp : 200;
};
- proto.addParticle = function(){
+ proto.addParticle = function () {
var node = this._node,
particles = node._particles,
particle;
@@ -173,21 +176,24 @@
return particle;
};
- proto._setupVBO = function(){};
- proto._allocMemory = function(){
+ proto._setupVBO = function () {
+ };
+ proto._allocMemory = function () {
return true;
};
- proto.postStep = function(){};
+ proto.postStep = function () {
+ };
- proto._setBlendAdditive = function(){
+ proto._setBlendAdditive = function () {
var locBlendFunc = this._node._blendFunc;
locBlendFunc.src = cc.BLEND_SRC;
locBlendFunc.dst = cc.BLEND_DST;
};
- proto._initWithTotalParticles = function(totalParticles){};
- proto._updateDeltaColor = function(selParticle, dt){
+ proto._initWithTotalParticles = function (totalParticles) {
+ };
+ proto._updateDeltaColor = function (selParticle, dt) {
if (!this._node._dontTint) {
selParticle.color.r += selParticle.deltaColor.r * dt;
selParticle.color.g += selParticle.deltaColor.g * dt;
diff --git a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js
index 8e684256d3..892f8a2d21 100644
--- a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js
+++ b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js
@@ -22,16 +22,15 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
+(function () {
/**
* ParticleSystem's WebGL render command
*/
- cc.ParticleSystem.WebGLRenderCmd = function(renderable){
- cc.Node.WebGLRenderCmd.call(this, renderable);
+ cc.ParticleSystem.WebGLRenderCmd = function (renderable) {
+ this._rootCtor(renderable);
this._needDraw = true;
- this._matrix = new cc.math.Matrix4();
- this._matrix.identity();
+ this._matrix = null;
this._buffersVBO = [0, 0];
this._quads = [];
@@ -41,12 +40,16 @@
var proto = cc.ParticleSystem.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
proto.constructor = cc.ParticleSystem.WebGLRenderCmd;
- proto.getDrawMode = function(){};
- proto.setDrawMode = function(drawMode){};
- proto.getShapeType = function(){};
- proto.setShapeType = function(shapeType){};
+ proto.getDrawMode = function () {
+ };
+ proto.setDrawMode = function (drawMode) {
+ };
+ proto.getShapeType = function () {
+ };
+ proto.setShapeType = function (shapeType) {
+ };
- proto.setBatchNode = function(batchNode){
+ proto.setBatchNode = function (batchNode) {
var node = this._node;
if (node._batchNode !== batchNode) {
var oldBatch = node._batchNode;
@@ -91,11 +94,11 @@
}
};
- proto.isDifferentTexture = function(texture1, texture2){
- return (texture1 === texture2);
+ proto.isDifferentTexture = function (texture1, texture2) {
+ return (texture1 === texture2);
};
- proto.updateParticlePosition = function(particle, position){
+ proto.updateParticlePosition = function (particle, position) {
// IMPORTANT: newPos may not be used as a reference here! (as it is just the temporary tpa point)
// the implementation of updateQuadWithParticle must use
// the x and y values directly
@@ -113,9 +116,9 @@
var r, g, b, a;
if (node._opacityModifyRGB) {
- r = 0 | (particle.color.r * particle.color.a/255);
- g = 0 | (particle.color.g * particle.color.a/255);
- b = 0 | (particle.color.b * particle.color.a/255);
+ r = 0 | (particle.color.r * particle.color.a / 255);
+ g = 0 | (particle.color.g * particle.color.a / 255);
+ b = 0 | (particle.color.b * particle.color.a / 255);
} else {
r = 0 | (particle.color.r );
g = 0 | (particle.color.g );
@@ -189,6 +192,10 @@
var gl = ctx || cc._renderContext;
+ if (!this._matrix) {
+ this._matrix = new cc.math.Matrix4();
+ this._matrix.identity();
+ }
var wt = this._worldTransform;
this._matrix.mat[0] = wt.a;
this._matrix.mat[4] = wt.c;
@@ -219,16 +226,16 @@
gl.drawElements(gl.TRIANGLES, node._particleIdx * 6, gl.UNSIGNED_SHORT, 0);
};
- proto.initTexCoordsWithRect = function(pointRect){
+ proto.initTexCoordsWithRect = function (pointRect) {
var node = this._node;
var texture = node.texture;
var scaleFactor = cc.contentScaleFactor();
// convert to pixels coords
var rect = cc.rect(
- pointRect.x * scaleFactor,
- pointRect.y * scaleFactor,
- pointRect.width * scaleFactor,
- pointRect.height * scaleFactor);
+ pointRect.x * scaleFactor,
+ pointRect.y * scaleFactor,
+ pointRect.width * scaleFactor,
+ pointRect.height * scaleFactor);
var wide = pointRect.width;
var high = pointRect.height;
@@ -288,7 +295,7 @@
}
};
- proto.setTotalParticles = function(tp){
+ proto.setTotalParticles = function (tp) {
var node = this._node;
// If we are setting the total numer of particles to a number higher
// than what is allocated, we need to allocate new arrays
@@ -321,7 +328,7 @@
this._setupVBO();
//set the texture coord
- if(node._texture){
+ if (node._texture) {
this.initTexCoordsWithRect(cc.rect(0, 0, node._texture.width, node._texture.height));
}
} else
@@ -329,13 +336,13 @@
node.resetSystem();
};
- proto.addParticle = function(){
+ proto.addParticle = function () {
var node = this._node,
particles = node._particles;
return particles[node.particleCount];
};
- proto._setupVBO = function(){
+ proto._setupVBO = function () {
var node = this;
var gl = cc._renderContext;
@@ -351,10 +358,10 @@
//cc.checkGLErrorDebug();
};
- proto._allocMemory = function(){
- var node = this._node;
+ proto._allocMemory = function () {
+ var node = this._node;
//cc.assert((!this._quads && !this._indices), "Memory already allocated");
- if(node._batchNode){
+ if (node._batchNode) {
cc.log("cc.ParticleSystem._allocMemory(): Memory should not be allocated when not using batchNode");
return false;
}
@@ -376,13 +383,13 @@
return true;
};
- proto.postStep = function(){
+ proto.postStep = function () {
var gl = cc._renderContext;
gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this._quadsArrayBuffer);
};
- proto._setBlendAdditive = function(){
+ proto._setBlendAdditive = function () {
var locBlendFunc = this._node._blendFunc;
if (this._texture && !this._texture.hasPremultipliedAlpha()) {
locBlendFunc.src = cc.SRC_ALPHA;
@@ -393,7 +400,7 @@
}
};
- proto._initWithTotalParticles = function(totalParticles){
+ proto._initWithTotalParticles = function (totalParticles) {
// allocating data space
if (!this._allocMemory())
return false;
@@ -411,4 +418,4 @@
selParticle.color.a += selParticle.deltaColor.a * dt;
selParticle.isChangeColor = true;
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js b/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js
index be1f6f14ba..1adf9a3f49 100644
--- a/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js
+++ b/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js
@@ -25,9 +25,9 @@
/**
* cc.PhysicsDebugNode's rendering objects of Canvas
*/
-(function(){
- cc.PhysicsDebugNode.CanvasRenderCmd = function(renderableObject){
- cc.Node.CanvasRenderCmd.call(this, renderableObject);
+(function () {
+ cc.PhysicsDebugNode.CanvasRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
this._buffer = renderableObject._buffer;
this._needDraw = true;
};
@@ -35,7 +35,7 @@
var proto = cc.PhysicsDebugNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
proto.constructor = cc.PhysicsDebugNode.CanvasRenderCmd;
- proto.rendering = function(ctx, scaleX, scaleY){
+ proto.rendering = function (ctx, scaleX, scaleY) {
var node = this._node;
if (!node._space)
return;
diff --git a/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js b/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js
index e2f16f8560..1c2a9fb69a 100644
--- a/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js
+++ b/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js
@@ -25,9 +25,9 @@
/**
* cc.PhysicsDebugNode's rendering objects of WebGL
*/
-(function(){
+(function () {
cc.PhysicsDebugNode.WebGLRenderCmd = function (renderableObject) {
- cc.Node.WebGLRenderCmd.call(this, renderableObject);
+ this._rootCtor(renderableObject);
this._needDraw = true;
this._matrix = new cc.math.Matrix4();
this._matrix.identity();
@@ -60,4 +60,4 @@
node.clear();
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/physics/CCPhysicsSprite.js b/cocos2d/physics/CCPhysicsSprite.js
index 80df018400..dde3546318 100644
--- a/cocos2d/physics/CCPhysicsSprite.js
+++ b/cocos2d/physics/CCPhysicsSprite.js
@@ -37,10 +37,10 @@
*/
(function () {
var box2dAPI = {
- _ignoreBodyRotation:false,
- _body:null,
- _PTMRatio:32,
- _rotation:1,
+ _ignoreBodyRotation: false,
+ _body: null,
+ _PTMRatio: 32,
+ _rotation: 1,
/**
* Create a PhysicsSprite with filename and rect
* Constructor of cc.PhysicsSprite for Box2d
@@ -66,12 +66,12 @@
* var physicsSprite2 = new cc.PhysicsSprite(texture, cc.rect(0,0,480,320));
*
*/
- ctor:function(fileName, rect){
+ ctor: function (fileName, rect) {
cc.Sprite.prototype.ctor.call(this);
if (fileName === undefined) {
cc.PhysicsSprite.prototype.init.call(this);
- }else if (cc.isString(fileName)) {
+ } else if (cc.isString(fileName)) {
if (fileName[0] === "#") {
//init with a sprite frame name
var frameName = fileName.substr(1, fileName.length - 1);
@@ -81,7 +81,7 @@
//init with filename and rect
this.init(fileName, rect);
}
- }else if (cc.isObject(fileName)) {
+ } else if (cc.isObject(fileName)) {
if (fileName instanceof cc.Texture2D) {
//init with texture and rect
this.initWithTexture(fileName, rect);
@@ -103,7 +103,7 @@
* set body
* @param {Box2D.Dynamics.b2Body} body
*/
- setBody:function (body) {
+ setBody: function (body) {
this._body = body;
},
@@ -111,7 +111,7 @@
* get body
* @return {Box2D.Dynamics.b2Body}
*/
- getBody:function () {
+ getBody: function () {
return this._body;
},
@@ -119,7 +119,7 @@
* set PTM ratio
* @param {Number} r
*/
- setPTMRatio:function (r) {
+ setPTMRatio: function (r) {
this._PTMRatio = r;
},
@@ -127,7 +127,7 @@
* get PTM ration
* @return {Number}
*/
- getPTMRatio:function () {
+ getPTMRatio: function () {
return this._PTMRatio;
},
@@ -135,9 +135,9 @@
* get position
* @return {cc.Point}
*/
- getPosition:function () {
+ getPosition: function () {
var pos = this._body.GetPosition();
- var locPTMRatio =this._PTMRatio;
+ var locPTMRatio = this._PTMRatio;
return cc.p(pos.x * locPTMRatio, pos.y * locPTMRatio);
},
@@ -145,9 +145,9 @@
* set position
* @param {cc.Point} p
*/
- setPosition:function (p) {
+ setPosition: function (p) {
var angle = this._body.GetAngle();
- var locPTMRatio =this._PTMRatio;
+ var locPTMRatio = this._PTMRatio;
this._body.setTransform(Box2D.b2Vec2(p.x / locPTMRatio, p.y / locPTMRatio), angle);
this.setNodeDirty();
},
@@ -156,7 +156,7 @@
* get rotation
* @return {Number}
*/
- getRotation:function () {
+ getRotation: function () {
return (this._ignoreBodyRotation ? cc.radiansToDegrees(this._rotationRadians) : cc.radiansToDegrees(this._body.GetAngle()));
},
@@ -164,7 +164,7 @@
* set rotation
* @param {Number} r
*/
- setRotation:function (r) {
+ setRotation: function (r) {
if (this._ignoreBodyRotation) {
this._rotation = r;
} else {
@@ -175,7 +175,7 @@
this.setNodeDirty();
},
- _syncPosition:function () {
+ _syncPosition: function () {
var locPosition = this._position,
pos = this._body.GetPosition(),
x = pos.x * this._PTMRatio,
@@ -184,7 +184,7 @@
cc.Sprite.prototype.setPosition.call(this, x, y);
}
},
- _syncRotation:function () {
+ _syncRotation: function () {
this._rotationRadians = this._body.GetAngle();
var a = cc.radiansToDegrees(this._rotationRadians);
if (this._rotationX !== a) {
@@ -196,15 +196,15 @@
* set whether to ingore body's rotation
* @param {Boolean} b
*/
- setIgnoreBodyRotation: function(b) {
+ setIgnoreBodyRotation: function (b) {
this._ignoreBodyRotation = b;
}
};
var chipmunkAPI = {
- _ignoreBodyRotation:false,
- _body:null, //physics body
- _rotation:1,
+ _ignoreBodyRotation: false,
+ _body: null, //physics body
+ _rotation: 1,
/**
* Create a PhysicsSprite with filename and rect
@@ -231,12 +231,12 @@
* var physicsSprite2 = new cc.PhysicsSprite(texture, cc.rect(0,0,480,320));
*
*/
- ctor:function(fileName, rect){
+ ctor: function (fileName, rect) {
cc.Sprite.prototype.ctor.call(this);
if (fileName === undefined) {
cc.PhysicsSprite.prototype.init.call(this);
- }else if (cc.isString(fileName)) {
+ } else if (cc.isString(fileName)) {
if (fileName[0] === "#") {
//init with a sprite frame name
var frameName = fileName.substr(1, fileName.length - 1);
@@ -246,7 +246,7 @@
//init with filename and rect
this.init(fileName, rect);
}
- }else if (cc.isObject(fileName)) {
+ } else if (cc.isObject(fileName)) {
if (fileName instanceof cc.Texture2D) {
//init with texture and rect
this.initWithTexture(fileName, rect);
@@ -259,7 +259,7 @@
cc.renderer.pushRenderCommand(this._renderCmd);
},
- visit: function(){
+ visit: function () {
cc.renderer.pushRenderCommand(this._renderCmd);
cc.Sprite.prototype.visit.call(this);
},
@@ -268,7 +268,7 @@
* set body
* @param {cp.Body} body
*/
- setBody:function (body) {
+ setBody: function (body) {
this._body = body;
},
@@ -276,7 +276,7 @@
* get body
* @returns {cp.Body}
*/
- getBody:function () {
+ getBody: function () {
return this._body;
},
@@ -284,16 +284,16 @@
* get position
* @return {cc.Point}
*/
- getPosition:function () {
+ getPosition: function () {
var locBody = this._body;
- return {x:locBody.p.x, y:locBody.p.y};
+ return {x: locBody.p.x, y: locBody.p.y};
},
/**
* get position x
* @return {Number}
*/
- getPositionX:function () {
+ getPositionX: function () {
return this._body.p.x;
},
@@ -301,7 +301,7 @@
* get position y
* @return {Number}
*/
- getPositionY:function () {
+ getPositionY: function () {
return this._body.p.y;
},
@@ -310,7 +310,7 @@
* @param {cc.Point|Number}newPosOrxValue
* @param {Number}yValue
*/
- setPosition:function (newPosOrxValue, yValue) {
+ setPosition: function (newPosOrxValue, yValue) {
if (yValue === undefined) {
this._body.p.x = newPosOrxValue.x;
this._body.p.y = newPosOrxValue.y;
@@ -324,7 +324,7 @@
* set position x
* @param {Number} xValue
*/
- setPositionX:function (xValue) {
+ setPositionX: function (xValue) {
this._body.p.x = xValue;
},
@@ -332,11 +332,11 @@
* set position y
* @param {Number} yValue
*/
- setPositionY:function (yValue) {
+ setPositionY: function (yValue) {
this._body.p.y = yValue;
},
- _syncPosition:function () {
+ _syncPosition: function () {
var locPosition = this._position, locBody = this._body;
if (locPosition.x !== locBody.p.x || locPosition.y !== locBody.p.y) {
cc.Sprite.prototype.setPosition.call(this, locBody.p.x, locBody.p.y);
@@ -347,7 +347,7 @@
* get rotation
* @return {Number}
*/
- getRotation:function () {
+ getRotation: function () {
return this._ignoreBodyRotation ? this._rotationX : -cc.radiansToDegrees(this._body.a);
},
@@ -355,14 +355,14 @@
* set rotation
* @param {Number} r
*/
- setRotation:function (r) {
+ setRotation: function (r) {
if (this._ignoreBodyRotation) {
cc.Sprite.prototype.setRotation.call(this, r);
} else {
this._body.a = -cc.degreesToRadians(r);
}
},
- _syncRotation:function () {
+ _syncRotation: function () {
var a = -cc.radiansToDegrees(this._body.a);
if (this._rotationX !== a) {
cc.Sprite.prototype.setRotation.call(this, a);
@@ -373,7 +373,7 @@
* get the affine transform matrix of node to parent coordinate frame
* @return {cc.AffineTransform}
*/
- getNodeToParentTransform:function () {
+ getNodeToParentTransform: function () {
return this._renderCmd.getNodeToParentTransform();
},
@@ -381,21 +381,22 @@
* whether dirty
* @return {Boolean}
*/
- isDirty:function(){
- return !this._body.isSleeping();
+ isDirty: function () {
+ return !this._body.isSleeping();
+ },
+ setDirty: function () {
},
- setDirty: function(){ },
/**
* set whether to ignore rotation of body
* @param {Boolean} b
*/
- setIgnoreBodyRotation: function(b) {
+ setIgnoreBodyRotation: function (b) {
this._ignoreBodyRotation = b;
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return new cc.PhysicsSprite.CanvasRenderCmd(this);
else
return new cc.PhysicsSprite.WebGLRenderCmd(this);
diff --git a/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js b/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js
index 705749d259..09279e65ea 100644
--- a/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js
+++ b/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js
@@ -25,26 +25,26 @@
/**
* cc.PhysicsSprite's rendering objects of Canvas
*/
-(function(){
- cc.PhysicsSprite.CanvasRenderCmd = function(renderableObject){
- cc.Sprite.CanvasRenderCmd.call(this, renderableObject);
+(function () {
+ cc.PhysicsSprite.CanvasRenderCmd = function (renderableObject) {
+ this._spriteCmdCtor(renderableObject);
this._needDraw = true;
};
var proto = cc.PhysicsSprite.CanvasRenderCmd.prototype = Object.create(cc.Sprite.CanvasRenderCmd.prototype);
proto.constructor = cc.PhysicsSprite.CanvasRenderCmd;
- proto.rendering = function(ctx, scaleX, scaleY){
+ proto.rendering = function (ctx, scaleX, scaleY) {
// This is a special class
// Sprite can not obtain sign
// So here must to calculate of each frame
- var node = this._node;
+ var node = this._node;
node._syncPosition();
- if(!node._ignoreBodyRotation)
+ if (!node._ignoreBodyRotation)
node._syncRotation();
this.transform(this.getParentRenderCmd());
cc.Sprite.CanvasRenderCmd.prototype.rendering.call(this, ctx, scaleX, scaleY);
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js b/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js
index d2e6b25c25..25fc120601 100644
--- a/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js
+++ b/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js
@@ -25,9 +25,9 @@
/**
* cc.PhysicsSprite's rendering objects of WebGL
*/
-(function(){
- cc.PhysicsSprite.WebGLRenderCmd = function(renderableObject){
- cc.Sprite.WebGLRenderCmd.call(this, renderableObject);
+(function () {
+ cc.PhysicsSprite.WebGLRenderCmd = function (renderableObject) {
+ this._spriteCmdCtor(renderableObject);
this._needDraw = true;
};
@@ -40,12 +40,12 @@
// This is a special class
// Sprite can not obtain sign
// So here must to calculate of each frame
- var node = this._node;
+ var node = this._node;
node._syncPosition();
- if(!node._ignoreBodyRotation)
+ if (!node._ignoreBodyRotation)
node._syncRotation();
this.transform(this.getParentRenderCmd(), true);
return this.spUploadData(f32buffer, ui32buffer, vertexDataOffset);
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js
index 2a9c8682a4..4dc2a71b74 100644
--- a/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js
+++ b/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js
@@ -25,9 +25,9 @@
/**
* cc.ProgressTimer's rendering objects of Canvas
*/
-(function(){
- cc.ProgressTimer.CanvasRenderCmd = function(renderableObject){
- cc.Node.CanvasRenderCmd.call(this, renderableObject);
+(function () {
+ cc.ProgressTimer.CanvasRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
this._needDraw = true;
this._PI180 = Math.PI / 180;
@@ -44,7 +44,7 @@
proto.constructor = cc.ProgressTimer.CanvasRenderCmd;
proto.rendering = function (ctx, scaleX, scaleY) {
- var wrapper = ctx || cc._renderContext,context = wrapper.getContext(), node = this._node, locSprite = node._sprite;
+ var wrapper = ctx || cc._renderContext, context = wrapper.getContext(), node = this._node, locSprite = node._sprite;
var locTextureCoord = locSprite._renderCmd._textureCoord, alpha = locSprite._renderCmd._displayedOpacity / 255;
if (locTextureCoord.width === 0 || locTextureCoord.height === 0)
@@ -76,14 +76,14 @@
if (node._type === cc.ProgressTimer.TYPE_BAR) {
var locBarRect = this._barRect;
context.beginPath();
- context.rect(locBarRect.x , locBarRect.y , locBarRect.width , locBarRect.height );
+ context.rect(locBarRect.x, locBarRect.y, locBarRect.width, locBarRect.height);
context.clip();
context.closePath();
} else if (node._type === cc.ProgressTimer.TYPE_RADIAL) {
- var locOriginX = this._origin.x ;
- var locOriginY = this._origin.y ;
+ var locOriginX = this._origin.x;
+ var locOriginY = this._origin.y;
context.beginPath();
- context.arc(locOriginX, locOriginY, this._radius , this._PI180 * this._startAngle, this._PI180 * this._endAngle, this._counterClockWise);
+ context.arc(locOriginX, locOriginY, this._radius, this._PI180 * this._startAngle, this._PI180 * this._endAngle, this._counterClockWise);
context.lineTo(locOriginX, locOriginY);
context.clip();
context.closePath();
@@ -95,21 +95,23 @@
if (locSprite._renderCmd._colorized) {
context.drawImage(image,
0, 0, locTextureCoord.width, locTextureCoord.height,
- locX , locY , locWidth , locHeight );
+ locX, locY, locWidth, locHeight);
} else {
context.drawImage(image,
locTextureCoord.renderX, locTextureCoord.renderY, locTextureCoord.width, locTextureCoord.height,
- locX , locY , locWidth , locHeight );
+ locX, locY, locWidth, locHeight);
}
wrapper.restore();
cc.g_NumberOfDraws++;
};
- proto.releaseData = function(){};
+ proto.releaseData = function () {
+ };
- proto.resetVertexData = function(){};
+ proto.resetVertexData = function () {
+ };
- proto._updateProgress = function(){
+ proto._updateProgress = function () {
this.setDirtyFlag(cc.Node._dirtyFlags.contentDirty);
var node = this._node;
var locSprite = node._sprite;
@@ -197,18 +199,18 @@
proto._syncStatus = function (parentCmd) {
var node = this._node;
- if(!node._sprite)
+ if (!node._sprite)
return;
var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
var parentNode = parentCmd ? parentCmd._node : null;
- if(parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty))
+ if (parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty))
locFlag |= flags.colorDirty;
- if(parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty))
+ if (parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty))
locFlag |= flags.opacityDirty;
- if(parentCmd && (parentCmd._dirtyFlag & flags.transformDirty))
+ if (parentCmd && (parentCmd._dirtyFlag & flags.transformDirty))
locFlag |= flags.transformDirty;
this._dirtyFlag = locFlag;
@@ -219,19 +221,19 @@
var colorDirty = spriteFlag & flags.colorDirty,
opacityDirty = spriteFlag & flags.opacityDirty;
- if (colorDirty){
+ if (colorDirty) {
spriteCmd._syncDisplayColor();
- spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.colorDirty ^ spriteCmd._dirtyFlag;
- this._dirtyFlag = this._dirtyFlag & flags.colorDirty ^ this._dirtyFlag;
+ spriteCmd._dirtyFlag &= ~flags.colorDirty;
+ this._dirtyFlag &= ~flags.colorDirty;
}
- if (opacityDirty){
+ if (opacityDirty) {
spriteCmd._syncDisplayOpacity();
- spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.opacityDirty ^ spriteCmd._dirtyFlag;
- this._dirtyFlag = this._dirtyFlag & flags.opacityDirty ^ this._dirtyFlag;
+ spriteCmd._dirtyFlag &= ~flags.opacityDirty;
+ this._dirtyFlag &= ~flags.opacityDirty;
}
- if(colorDirty || opacityDirty){
+ if (colorDirty || opacityDirty) {
spriteCmd._updateColor();
}
@@ -241,13 +243,13 @@
}
if (locFlag & flags.orderDirty) {
- this._dirtyFlag = this._dirtyFlag & flags.orderDirty ^ this._dirtyFlag;
+ this._dirtyFlag &= ~flags.orderDirty;
}
};
proto.updateStatus = function () {
var node = this._node;
- if(!node._sprite)
+ if (!node._sprite)
return;
var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
var spriteCmd = node._sprite._renderCmd;
@@ -256,23 +258,23 @@
var colorDirty = spriteFlag & flags.colorDirty,
opacityDirty = spriteFlag & flags.opacityDirty;
- if(colorDirty){
+ if (colorDirty) {
spriteCmd._updateDisplayColor();
spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.colorDirty ^ spriteCmd._dirtyFlag;
this._dirtyFlag = this._dirtyFlag & flags.colorDirty ^ this._dirtyFlag;
}
- if(opacityDirty){
+ if (opacityDirty) {
spriteCmd._updateDisplayOpacity();
spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.opacityDirty ^ spriteCmd._dirtyFlag;
this._dirtyFlag = this._dirtyFlag & flags.opacityDirty ^ this._dirtyFlag;
}
- if(colorDirty || opacityDirty){
+ if (colorDirty || opacityDirty) {
spriteCmd._updateColor();
}
- if(locFlag & flags.transformDirty){
+ if (locFlag & flags.transformDirty) {
//update the transform
this.transform(this.getParentRenderCmd(), true);
}
@@ -281,4 +283,4 @@
}
this._dirtyFlag = 0;
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js
index e1be5255ae..8ee5a7da1a 100644
--- a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js
+++ b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js
@@ -25,11 +25,11 @@
/**
* cc.ProgressTimer's rendering objects of WebGL
*/
-(function(){
+(function () {
var MAX_VERTEX_COUNT = 8;
- cc.ProgressTimer.WebGLRenderCmd = function(renderableObject){
- cc.Node.WebGLRenderCmd.call(this, renderableObject);
+ cc.ProgressTimer.WebGLRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
this._needDraw = true;
this._progressDirty = true;
@@ -102,16 +102,16 @@
proto._syncStatus = function (parentCmd) {
var node = this._node;
- if(!node._sprite)
+ if (!node._sprite)
return;
var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
var parentNode = parentCmd ? parentCmd._node : null;
- if(parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty))
+ if (parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty))
locFlag |= flags.colorDirty;
- if(parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty))
+ if (parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty))
locFlag |= flags.opacityDirty;
- if(parentCmd && (parentCmd._dirtyFlag & flags.transformDirty))
+ if (parentCmd && (parentCmd._dirtyFlag & flags.transformDirty))
locFlag |= flags.transformDirty;
this._dirtyFlag = locFlag;
@@ -121,19 +121,19 @@
var colorDirty = (locFlag | spriteFlag) & flags.colorDirty,
opacityDirty = (locFlag | spriteFlag) & flags.opacityDirty;
- if (colorDirty){
+ if (colorDirty) {
spriteCmd._syncDisplayColor();
- spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.colorDirty ^ spriteCmd._dirtyFlag;
- this._dirtyFlag = this._dirtyFlag & flags.colorDirty ^ this._dirtyFlag;
+ spriteCmd._dirtyFlag &= ~flags.colorDirty;
+ this._dirtyFlag &= ~flags.colorDirty;
}
- if (opacityDirty){
+ if (opacityDirty) {
spriteCmd._syncDisplayOpacity();
- spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.opacityDirty ^ spriteCmd._dirtyFlag;
- this._dirtyFlag = this._dirtyFlag & flags.opacityDirty ^ this._dirtyFlag;
+ spriteCmd._dirtyFlag &= ~flags.opacityDirty;
+ this._dirtyFlag &= ~flags.opacityDirty;
}
- if(colorDirty || opacityDirty){
+ if (colorDirty || opacityDirty) {
this._updateColor();
}
@@ -144,7 +144,7 @@
if (locFlag & flags.textureDirty) {
this._updateProgressData();
- this._dirtyFlag = this._dirtyFlag & flags.textureDirty ^ this._dirtyFlag;
+ this._dirtyFlag &= ~flags.textureDirty;
}
spriteCmd._dirtyFlag = 0;
@@ -152,7 +152,7 @@
proto.updateStatus = function () {
var node = this._node;
- if(!node._sprite)
+ if (!node._sprite)
return;
var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
var spriteCmd = node._sprite._renderCmd;
@@ -161,23 +161,23 @@
var colorDirty = (locFlag | spriteFlag) & flags.colorDirty,
opacityDirty = (locFlag | spriteFlag) & flags.opacityDirty;
- if(colorDirty){
+ if (colorDirty) {
spriteCmd._updateDisplayColor();
spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.colorDirty ^ spriteCmd._dirtyFlag;
this._dirtyFlag = this._dirtyFlag & flags.colorDirty ^ this._dirtyFlag;
}
- if(opacityDirty){
+ if (opacityDirty) {
spriteCmd._updateDisplayOpacity();
spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.opacityDirty ^ spriteCmd._dirtyFlag;
this._dirtyFlag = this._dirtyFlag & flags.opacityDirty ^ this._dirtyFlag;
}
- if(colorDirty || opacityDirty){
+ if (colorDirty || opacityDirty) {
this._updateColor();
}
- if(locFlag & flags.transformDirty){
+ if (locFlag & flags.transformDirty) {
//update the transform
this.transform(this.getParentRenderCmd(), true);
}
@@ -192,7 +192,7 @@
}
};
- proto.releaseData = function(){
+ proto.releaseData = function () {
if (this._vertexData) {
//release all previous information
var webglBuffer = this._vertexWebGLBuffer;
@@ -238,9 +238,9 @@
proto._updateProgressData = function () {
var node = this._node;
var locType = node._type;
- if(locType === cc.ProgressTimer.TYPE_RADIAL)
+ if (locType === cc.ProgressTimer.TYPE_RADIAL)
this._updateRadial();
- else if(locType === cc.ProgressTimer.TYPE_BAR)
+ else if (locType === cc.ProgressTimer.TYPE_BAR)
this._updateBar();
this._vertexDataDirty = true;
};
@@ -260,7 +260,7 @@
*
* @private
*/
- proto._updateBar = function(){
+ proto._updateBar = function () {
var node = this._node;
if (!node._sprite)
return;
@@ -268,7 +268,7 @@
var i, alpha = node._percentage / 100.0;
var locBarChangeRate = node._barChangeRate;
var alphaOffset = cc.pMult(cc.p((1.0 - locBarChangeRate.x) + alpha * locBarChangeRate.x,
- (1.0 - locBarChangeRate.y) + alpha * locBarChangeRate.y), 0.5);
+ (1.0 - locBarChangeRate.y) + alpha * locBarChangeRate.y), 0.5);
var min = cc.pSub(node._midPoint, alphaOffset), max = cc.pAdd(node._midPoint, alphaOffset);
if (min.x < 0) {
@@ -478,7 +478,7 @@
else
return cc.p((locProTextCoords >> ((index << 1) + 1)) & 1, (locProTextCoords >> (index << 1)) & 1);
}
- return cc.p(0,0);
+ return cc.p(0, 0);
};
proto._textureCoordFromAlphaPoint = function (coords, ax, ay) {
@@ -510,7 +510,7 @@
vertex.z = this._node._vertexZ;
};
- proto._updateColor = function(){
+ proto._updateColor = function () {
var sp = this._node._sprite;
if (!this._vertexDataCount || !sp)
return;
@@ -536,4 +536,4 @@
}
this._vertexDataDirty = true;
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/render-texture/CCRenderTexture.js b/cocos2d/render-texture/CCRenderTexture.js
index d0e6950e51..ffb443f002 100644
--- a/cocos2d/render-texture/CCRenderTexture.js
+++ b/cocos2d/render-texture/CCRenderTexture.js
@@ -77,26 +77,26 @@ cc.NextPOT = function (x) {
* @property {cc.Color} clearColorVal - Clear color value, valid only when "autoDraw" is true.
*/
cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
- sprite:null,
+ sprite: null,
- //
- //
Code for "auto" update
- // Valid flags: GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
- // They can be OR'ed. Valid when "autoDraw is YES.
- // @public
- //
- clearFlags:0,
+ //
+ //
Code for "auto" update
+ // Valid flags: GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
+ // They can be OR'ed. Valid when "autoDraw is YES.
+ // @public
+ //
+ clearFlags: 0,
- clearDepthVal:0,
- autoDraw:false,
+ clearDepthVal: 0,
+ autoDraw: false,
- _texture:null,
- _pixelFormat:0,
+ _texture: null,
+ _pixelFormat: 0,
- clearStencilVal:0,
- _clearColor:null,
+ clearStencilVal: 0,
+ _clearColor: null,
- _className:"RenderTexture",
+ _className: "RenderTexture",
/**
* creates a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid
@@ -110,33 +110,45 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* var rt = new cc.RenderTexture(width, height, format, depthStencilFormat)
* @function
*/
- ctor: function(width, height, format, depthStencilFormat){
+ ctor: function (width, height, format, depthStencilFormat) {
cc.Node.prototype.ctor.call(this);
this._cascadeColorEnabled = true;
this._cascadeOpacityEnabled = true;
this._pixelFormat = cc.Texture2D.PIXEL_FORMAT_RGBA8888;
- this._clearColor = new cc.Color(0,0,0,255);
+ this._clearColor = new cc.Color(0, 0, 0, 255);
- if(width !== undefined && height !== undefined) {
+ if (width !== undefined && height !== undefined) {
format = format || cc.Texture2D.PIXEL_FORMAT_RGBA8888;
depthStencilFormat = depthStencilFormat || 0;
this.initWithWidthAndHeight(width, height, format, depthStencilFormat);
}
- this.setAnchorPoint(0,0);
+ this.setAnchorPoint(0, 0);
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return new cc.RenderTexture.CanvasRenderCmd(this);
else
return new cc.RenderTexture.WebGLRenderCmd(this);
},
+ visit: function (parent) {
+ // quick return if not visible
+ if (!this._visible)
+ return;
+
+ var renderer = cc.renderer, cmd = this._renderCmd;
+
+ cmd.visit(parent && parent._renderCmd);
+ this.sprite.visit(this);
+ cmd._dirtyFlag = 0;
+ },
+
/**
* Clear RenderTexture.
* @function
*/
- cleanup: function(){
+ cleanup: function () {
cc.Node.prototype.onExit.call(this);
this._renderCmd.cleanup();
},
@@ -145,7 +157,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Gets the sprite
* @return {cc.Sprite}
*/
- getSprite:function () {
+ getSprite: function () {
return this.sprite;
},
@@ -153,7 +165,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Set the sprite
* @param {cc.Sprite} sprite
*/
- setSprite:function (sprite) {
+ setSprite: function (sprite) {
this.sprite = sprite;
},
@@ -163,8 +175,8 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @param {cc.Rect} fullRect
* @param {cc.Rect} fullViewport
*/
- setVirtualViewport: function(rtBegin, fullRect, fullViewport){
- this._renderCmd.setVirtualViewport(rtBegin, fullRect, fullViewport);
+ setVirtualViewport: function (rtBegin, fullRect, fullViewport) {
+ this._renderCmd.setVirtualViewport(rtBegin, fullRect, fullViewport);
},
/**
@@ -176,7 +188,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @param {Number} [depthStencilFormat]
* @return {Boolean}
*/
- initWithWidthAndHeight: function(width, height, format, depthStencilFormat){
+ initWithWidthAndHeight: function (width, height, format, depthStencilFormat) {
return this._renderCmd.initWithWidthAndHeight(width, height, format, depthStencilFormat);
},
@@ -184,7 +196,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* starts grabbing
* @function
*/
- begin: function(){
+ begin: function () {
cc.renderer._turnToCacheMode(this.__instanceId);
this._renderCmd.begin();
},
@@ -198,16 +210,16 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @param {Number} [depthValue=]
* @param {Number} [stencilValue=]
*/
- beginWithClear:function (r, g, b, a, depthValue, stencilValue) {
+ beginWithClear: function (r, g, b, a, depthValue, stencilValue) {
//todo: only for WebGL?
var gl = cc._renderContext;
depthValue = depthValue || gl.COLOR_BUFFER_BIT;
stencilValue = stencilValue || (gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
- this._beginWithClear(r , g , b , a , depthValue, stencilValue, (gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT));
+ this._beginWithClear(r, g, b, a, depthValue, stencilValue, (gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT));
},
- _beginWithClear: function(r, g, b, a, depthValue, stencilValue, flags){
+ _beginWithClear: function (r, g, b, a, depthValue, stencilValue, flags) {
this.begin();
this._renderCmd._beginWithClear(r, g, b, a, depthValue, stencilValue, flags);
},
@@ -216,7 +228,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* ends grabbing
* @function
*/
- end: function(){
+ end: function () {
this._renderCmd.end();
},
@@ -227,7 +239,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @param {Number} b blue 0-1
* @param {Number} a alpha 0-1
*/
- clear:function (r, g, b, a) {
+ clear: function (r, g, b, a) {
this.beginWithClear(r, g, b, a);
this.end();
},
@@ -240,7 +252,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @param {number} width
* @param {number} height
*/
- clearRect: function(x, y, width, height){
+ clearRect: function (x, y, width, height) {
this._renderCmd.clearRect(x, y, width, height);
},
@@ -249,7 +261,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @function
* @param {Number} depthValue
*/
- clearDepth: function(depthValue){
+ clearDepth: function (depthValue) {
this._renderCmd.clearDepth(depthValue);
},
@@ -258,7 +270,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @function
* @param {Number} stencilValue
*/
- clearStencil: function(stencilValue) {
+ clearStencil: function (stencilValue) {
this._renderCmd.clearStencil(stencilValue);
},
@@ -266,7 +278,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Valid flags: GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT. They can be OR'ed. Valid when "autoDraw is YES.
* @return {Number}
*/
- getClearFlags:function () {
+ getClearFlags: function () {
return this.clearFlags;
},
@@ -274,7 +286,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Set the clearFlags
* @param {Number} clearFlags
*/
- setClearFlags:function (clearFlags) {
+ setClearFlags: function (clearFlags) {
this.clearFlags = clearFlags;
},
@@ -283,16 +295,16 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @function
* @return {cc.Color}
*/
- getClearColor:function () {
+ getClearColor: function () {
return this._clearColor;
},
- /**
- * Set the clear color value. Valid only when "autoDraw" is true.
- * @function
- * @param {cc.Color} clearColor The clear color
- */
- setClearColor: function(clearColor){
+ /**
+ * Set the clear color value. Valid only when "autoDraw" is true.
+ * @function
+ * @param {cc.Color} clearColor The clear color
+ */
+ setClearColor: function (clearColor) {
var locClearColor = this._clearColor;
locClearColor.r = clearColor.r;
locClearColor.g = clearColor.g;
@@ -305,7 +317,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Value for clearDepth. Valid only when autoDraw is true.
* @return {Number}
*/
- getClearDepth:function () {
+ getClearDepth: function () {
return this.clearDepthVal;
},
@@ -313,7 +325,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Set value for clearDepth. Valid only when autoDraw is true.
* @param {Number} clearDepth
*/
- setClearDepth:function (clearDepth) {
+ setClearDepth: function (clearDepth) {
this.clearDepthVal = clearDepth;
},
@@ -321,7 +333,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Value for clear Stencil. Valid only when autoDraw is true
* @return {Number}
*/
- getClearStencil:function () {
+ getClearStencil: function () {
return this.clearStencilVal;
},
@@ -329,7 +341,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Set value for clear Stencil. Valid only when autoDraw is true
* @return {Number}
*/
- setClearStencil:function (clearStencil) {
+ setClearStencil: function (clearStencil) {
this.clearStencilVal = clearStencil;
},
@@ -338,7 +350,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Will be enabled in the future.
* @return {Boolean}
*/
- isAutoDraw:function () {
+ isAutoDraw: function () {
return this.autoDraw;
},
@@ -347,7 +359,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Will be enabled in the future.
* @return {Boolean}
*/
- setAutoDraw:function (autoDraw) {
+ setAutoDraw: function (autoDraw) {
this.autoDraw = autoDraw;
},
@@ -359,7 +371,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @param {Number} filePath
* @param {Number} format
*/
- saveToFile:function (filePath, format) {
+ saveToFile: function (filePath, format) {
cc.log("saveToFile isn't supported on Cocos2d-Html5");
},
@@ -367,7 +379,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* creates a new CCImage from with the texture's data. Caller is responsible for releasing it by calling delete.
* @return {*}
*/
- newCCImage:function(flipImage){
+ newCCImage: function (flipImage) {
cc.log("saveToFile isn't supported on cocos2d-html5");
return null;
},
@@ -376,13 +388,15 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Listen "come to background" message, and save render texture. It only has effect on Android.
* @param {cc.Class} obj
*/
- listenToBackground:function (obj) { },
+ listenToBackground: function (obj) {
+ },
/**
* Listen "come to foreground" message and restore the frame buffer object. It only has effect on Android.
* @param {cc.Class} obj
*/
- listenToForeground:function (obj) { }
+ listenToForeground: function (obj) {
+ }
});
var _p = cc.RenderTexture.prototype;
diff --git a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js
index c79b36f34d..3ad126d9f6 100644
--- a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js
+++ b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js
@@ -22,9 +22,9 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- cc.RenderTexture.CanvasRenderCmd = function(renderableObject){
- cc.Node.CanvasRenderCmd.call(this, renderableObject);
+(function () {
+ cc.RenderTexture.CanvasRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
this._needDraw = true;
this._clearColorStr = "rgba(255,255,255,1)";
@@ -35,20 +35,22 @@
var proto = cc.RenderTexture.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
proto.constructor = cc.RenderTexture.CanvasRenderCmd;
- proto.cleanup = function(){
+ proto.cleanup = function () {
this._cacheContext = null;
this._cacheCanvas = null;
};
- proto.clearStencil = function (stencilValue) { };
+ proto.clearStencil = function (stencilValue) {
+ };
- proto.setVirtualViewport = function(rtBegin, fullRect, fullViewport) {};
+ proto.setVirtualViewport = function (rtBegin, fullRect, fullViewport) {
+ };
- proto.updateClearColor = function(clearColor){
+ proto.updateClearColor = function (clearColor) {
this._clearColorStr = "rgba(" + (0 | clearColor.r) + "," + (0 | clearColor.g) + "," + (0 | clearColor.b) + "," + clearColor.a / 255 + ")";
};
- proto.initWithWidthAndHeight = function(width, height, format, depthStencilFormat){
+ proto.initWithWidthAndHeight = function (width, height, format, depthStencilFormat) {
var node = this._node;
var locCacheCanvas = this._cacheCanvas, locScaleFactor = cc.contentScaleFactor();
locCacheCanvas.width = 0 | (width * locScaleFactor);
@@ -67,9 +69,10 @@
return true;
};
- proto.begin = function(){};
+ proto.begin = function () {
+ };
- proto._beginWithClear = function(r, g, b, a, depthValue, stencilValue, flags){
+ proto._beginWithClear = function (r, g, b, a, depthValue, stencilValue, flags) {
r = r || 0;
g = g || 0;
b = b || 0;
@@ -77,13 +80,13 @@
var context = this._cacheContext.getContext();
var locCanvas = this._cacheCanvas;
- context.setTransform(1,0,0,1,0,0);
+ context.setTransform(1, 0, 0, 1, 0, 0);
this._cacheContext.setFillStyle("rgba(" + (0 | r) + "," + (0 | g) + "," + (0 | b) + "," + a / 255 + ")");
context.clearRect(0, 0, locCanvas.width, locCanvas.height);
context.fillRect(0, 0, locCanvas.width, locCanvas.height);
};
- proto.end = function(){
+ proto.end = function () {
var node = this._node;
var scale = cc.contentScaleFactor();
@@ -92,18 +95,11 @@
spriteRenderCmd._notifyRegionStatus && spriteRenderCmd._notifyRegionStatus(cc.Node.CanvasRenderCmd.RegionStatus.Dirty);
};
- proto.clearRect = function(x, y, width, height){
+ proto.clearRect = function (x, y, width, height) {
this._cacheContext.clearRect(x, y, width, -height);
};
- proto.clearDepth = function(depthValue){
+ proto.clearDepth = function (depthValue) {
cc.log("clearDepth isn't supported on Cocos2d-Html5");
};
-
- proto.visit = function(parentCmd){
- var node = this._node;
- this._syncStatus(parentCmd);
- node.sprite.visit(this);
- this._dirtyFlag = 0;
- };
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js
index dd25b8bf73..20cc4dec06 100644
--- a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js
+++ b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js
@@ -22,9 +22,9 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- cc.RenderTexture.WebGLRenderCmd = function(renderableObject){
- cc.Node.WebGLRenderCmd.call(this, renderableObject);
+(function () {
+ cc.RenderTexture.WebGLRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
this._needDraw = true;
this._fBO = null;
@@ -40,7 +40,7 @@
var proto = cc.RenderTexture.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
proto.constructor = cc.RenderTexture.WebGLRenderCmd;
- proto.setVirtualViewport = function(rtBegin, fullRect, fullViewport) {
+ proto.setVirtualViewport = function (rtBegin, fullRect, fullViewport) {
this._rtTextureRect.x = rtBegin.x;
this._rtTextureRect.y = rtBegin.y;
@@ -99,7 +99,7 @@
var locChildren = node._children;
for (var i = 0; i < locChildren.length; i++) {
var getChild = locChildren[i];
- if (getChild !== node.sprite){
+ if (getChild !== node.sprite) {
getChild._renderCmd.visit(node.sprite._renderCmd); //TODO it's very Strange
}
}
@@ -107,7 +107,7 @@
}
};
- proto.clearStencil = function(stencilValue) {
+ proto.clearStencil = function (stencilValue) {
var gl = cc._renderContext;
// save old stencil value
var stencilClearValue = gl.getParameter(gl.STENCIL_CLEAR_VALUE);
@@ -119,7 +119,7 @@
gl.clearStencil(stencilClearValue);
};
- proto.cleanup = function(){
+ proto.cleanup = function () {
var node = this._node;
//node.sprite = null;
this._textureCopy = null;
@@ -130,16 +130,17 @@
gl.deleteRenderbuffer(this._depthRenderBuffer);
};
- proto.updateClearColor = function(clearColor){ };
+ proto.updateClearColor = function (clearColor) {
+ };
- proto.initWithWidthAndHeight = function(width, height, format, depthStencilFormat){
+ proto.initWithWidthAndHeight = function (width, height, format, depthStencilFormat) {
var node = this._node;
- if(format === cc.Texture2D.PIXEL_FORMAT_A8)
- cc.log( "cc.RenderTexture._initWithWidthAndHeightForWebGL() : only RGB and RGBA formats are valid for a render texture;");
+ if (format === cc.Texture2D.PIXEL_FORMAT_A8)
+ cc.log("cc.RenderTexture._initWithWidthAndHeightForWebGL() : only RGB and RGBA formats are valid for a render texture;");
var gl = cc._renderContext, locScaleFactor = cc.contentScaleFactor();
- this._fullRect = new cc.Rect(0,0, width, height);
- this._fullViewport = new cc.Rect(0,0, width, height);
+ this._fullRect = new cc.Rect(0, 0, width, height);
+ this._fullViewport = new cc.Rect(0, 0, width, height);
width = 0 | (width * locScaleFactor);
height = 0 | (height * locScaleFactor);
@@ -147,7 +148,7 @@
this._oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING);
// textures must be power of two squared
- var powW , powH;
+ var powW, powH;
if (cc.configuration.supportsNPOT()) {
powW = width;
@@ -194,16 +195,16 @@
this._depthRenderBuffer = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, this._depthRenderBuffer);
gl.renderbufferStorage(gl.RENDERBUFFER, depthStencilFormat, powW, powH);
- if(depthStencilFormat === gl.DEPTH_STENCIL)
+ if (depthStencilFormat === gl.DEPTH_STENCIL)
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer);
- else if(depthStencilFormat === gl.STENCIL_INDEX || depthStencilFormat === gl.STENCIL_INDEX8)
+ else if (depthStencilFormat === gl.STENCIL_INDEX || depthStencilFormat === gl.STENCIL_INDEX8)
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer);
- else if(depthStencilFormat === gl.DEPTH_COMPONENT16)
+ else if (depthStencilFormat === gl.DEPTH_COMPONENT16)
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer);
}
// check if it worked (probably worth doing :) )
- if(gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE)
+ if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE)
cc.log("Could not attach texture to the framebuffer");
locTexture.setAliasTexParameters();
@@ -223,7 +224,7 @@
return true;
};
- proto.begin = function(){
+ proto.begin = function () {
var node = this._node;
// Save the current matrix
cc.kmGLMatrixMode(cc.KM_GL_PROJECTION);
@@ -274,7 +275,7 @@
}
};
- proto._beginWithClear = function(r, g, b, a, depthValue, stencilValue, flags){
+ proto._beginWithClear = function (r, g, b, a, depthValue, stencilValue, flags) {
r = r / 255;
g = g / 255;
b = b / 255;
@@ -315,7 +316,7 @@
gl.clearStencil(stencilClearValue);
};
- proto.end = function(){
+ proto.end = function () {
var node = this._node;
cc.renderer._renderingToBuffer(node.__instanceId);
@@ -343,11 +344,11 @@
director.setProjection(director.getProjection());*/
};
- proto.clearRect = function(x, y, width, height){
+ proto.clearRect = function (x, y, width, height) {
//TODO need to implement
};
- proto.clearDepth = function(depthValue){
+ proto.clearDepth = function (depthValue) {
var node = this._node;
node.begin();
@@ -363,29 +364,8 @@
node.end();
};
- proto.visit = function(parentCmd){
- var node = this._node;
- if (!node._visible)
- return;
- cc.kmGLPushMatrix();
-
- //TODO using GridNode
- /* var locGrid = this.grid;
- if (locGrid && locGrid.isActive()) {
- locGrid.beforeDraw();
- this.transformAncestors();
- }*/
-
+ proto.visit = function (parentCmd) {
this._syncStatus(parentCmd);
- //this.toRenderer();
cc.renderer.pushRenderCommand(this);
- node.sprite.visit(this);
-
- //TODO GridNode
- /* if (locGrid && locGrid.isActive())
- locGrid.afterDraw(this);*/
-
- this._dirtyFlag = 0;
- cc.kmGLPopMatrix();
};
})();
diff --git a/cocos2d/shaders/CCGLProgram.js b/cocos2d/shaders/CCGLProgram.js
index 829584886f..d9e59b109d 100644
--- a/cocos2d/shaders/CCGLProgram.js
+++ b/cocos2d/shaders/CCGLProgram.js
@@ -39,6 +39,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
_uniforms: null,
_hashForUniforms: null,
_usesTime: false,
+ _projectionUpdated: -1,
// Uniform cache
_updateUniformLocation: function (location) {
@@ -59,10 +60,10 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
updated = true;
} else {
updated = false;
- var count = arguments.length-1;
+ var count = arguments.length - 1;
for (var i = 0; i < count; ++i) {
- if (arguments[i+1] !== element[i]) {
- element[i] = arguments[i+1];
+ if (arguments[i + 1] !== element[i]) {
+ element[i] = arguments[i + 1];
updated = true;
}
}
@@ -106,18 +107,18 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
return ( status === true );
},
- /**
- * Create a cc.GLProgram object
- * @param {String} vShaderFileName
- * @param {String} fShaderFileName
- * @returns {cc.GLProgram}
- */
+ /**
+ * Create a cc.GLProgram object
+ * @param {String} vShaderFileName
+ * @param {String} fShaderFileName
+ * @returns {cc.GLProgram}
+ */
ctor: function (vShaderFileName, fShaderFileName, glContext) {
this._uniforms = {};
this._hashForUniforms = {};
this._glContext = glContext || cc._renderContext;
- vShaderFileName && fShaderFileName && this.init(vShaderFileName, fShaderFileName);
+ vShaderFileName && fShaderFileName && this.init(vShaderFileName, fShaderFileName);
},
/**
@@ -194,9 +195,9 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
*/
initWithVertexShaderFilename: function (vShaderFilename, fShaderFileName) {
var vertexSource = cc.loader.getRes(vShaderFilename);
- if(!vertexSource) throw new Error("Please load the resource firset : " + vShaderFilename);
+ if (!vertexSource) throw new Error("Please load the resource firset : " + vShaderFilename);
var fragmentSource = cc.loader.getRes(fShaderFileName);
- if(!fragmentSource) throw new Error("Please load the resource firset : " + fShaderFileName);
+ if (!fragmentSource) throw new Error("Please load the resource firset : " + fShaderFileName);
return this.initWithVertexShaderByteArray(vertexSource, fragmentSource);
},
@@ -224,7 +225,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* @return {Boolean}
*/
link: function () {
- if(!this._programObj) {
+ if (!this._programObj) {
cc.log("cc.GLProgram.link(): Cannot link invalid program");
return false;
}
@@ -418,7 +419,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* @param {WebGLUniformLocation|String} location
* @param {Int32Array} intArray
*/
- setUniformLocationWith3iv:function(location, intArray){
+ setUniformLocationWith3iv: function (location, intArray) {
var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location;
this._glContext.uniform3iv(locObj, intArray);
},
@@ -428,7 +429,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* @param {WebGLUniformLocation|String} location
* @param {Int32Array} intArray
*/
- setUniformLocationWith4iv:function(location, intArray){
+ setUniformLocationWith4iv: function (location, intArray) {
var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location;
this._glContext.uniform4iv(locObj, intArray);
},
@@ -627,7 +628,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
},
_setUniformsForBuiltinsForRenderer: function (node) {
- if(!node || !node._renderCmd)
+ if (!node || !node._renderCmd)
return;
var matrixP = new cc.math.Matrix4();
@@ -664,7 +665,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
*/
setUniformForModelViewProjectionMatrix: function () {
this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_MVPMATRIX_S], false,
- cc.getMat4MultiplyValue(cc.projection_matrix_stack.top, cc.modelview_matrix_stack.top));
+ cc.getMat4MultiplyValue(cc.projection_matrix_stack.top, cc.modelview_matrix_stack.top));
},
setUniformForModelViewProjectionMatrixWithMat4: function (swapMat4) {
@@ -677,15 +678,19 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX_S], false, cc.projection_matrix_stack.top.mat);
},
- _setUniformForMVPMatrixWithMat4: function(modelViewMatrix){
- if(!modelViewMatrix)
+ _setUniformForMVPMatrixWithMat4: function (modelViewMatrix) {
+ if (!modelViewMatrix)
throw new Error("modelView matrix is undefined.");
this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_MVMATRIX_S], false, modelViewMatrix.mat);
this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX_S], false, cc.projection_matrix_stack.top.mat);
},
- _updateProjectionUniform: function(){
- this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX_S], false, cc.projection_matrix_stack.top.mat);
+ _updateProjectionUniform: function () {
+ var stack = cc.projection_matrix_stack;
+ if (stack.lastUpdated !== this._projectionUpdated) {
+ this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX_S], false, stack.top.mat);
+ this._projectionUpdated = stack.lastUpdated;
+ }
},
/**
@@ -789,8 +794,8 @@ cc.GLProgram.create = function (vShaderFileName, fShaderFileName) {
cc.GLProgram._highpSupported = null;
-cc.GLProgram._isHighpSupported = function(){
- if(cc.GLProgram._highpSupported == null){
+cc.GLProgram._isHighpSupported = function () {
+ if (cc.GLProgram._highpSupported == null) {
var ctx = cc._renderContext;
var highp = ctx.getShaderPrecisionFormat(ctx.FRAGMENT_SHADER, ctx.HIGH_FLOAT);
cc.GLProgram._highpSupported = highp.precision !== 0;
diff --git a/cocos2d/shaders/CCGLStateCache.js b/cocos2d/shaders/CCGLStateCache.js
index edcf86c3b8..626c587a9c 100644
--- a/cocos2d/shaders/CCGLStateCache.js
+++ b/cocos2d/shaders/CCGLStateCache.js
@@ -36,60 +36,6 @@ if (cc.ENABLE_GL_STATE_CACHE) {
cc._GLServerState = 0;
if(cc.TEXTURE_ATLAS_USE_VAO)
cc._uVAO = 0;
-
- var _currBuffers = {};
-
- WebGLRenderingContext.prototype.glBindBuffer = WebGLRenderingContext.prototype.bindBuffer;
- WebGLRenderingContext.prototype.bindBuffer = function (target, buffer) {
- if (_currBuffers[target] !== buffer) {
- this.glBindBuffer(target, buffer);
- _currBuffers[target] = buffer;
- }
- };
-
- WebGLRenderingContext.prototype.glEnableVertexAttribArray = WebGLRenderingContext.prototype.enableVertexAttribArray;
- WebGLRenderingContext.prototype.enableVertexAttribArray = function (index) {
- if (index === cc.VERTEX_ATTRIB_FLAG_POSITION) {
- if (!this._vertexAttribPosition) {
- this.glEnableVertexAttribArray(index);
- this._vertexAttribPosition = true;
- }
- }
- else if (index === cc.VERTEX_ATTRIB_FLAG_COLOR) {
- if (!this._vertexAttribColor) {
- this.glEnableVertexAttribArray(index);
- this._vertexAttribColor = true;
- }
- }
- else if (index === cc.VERTEX_ATTRIB_FLAG_TEX_COORDS) {
- if (!this._vertexAttribTexCoords) {
- this.glEnableVertexAttribArray(index);
- this._vertexAttribTexCoords = true;
- }
- }
- else {
- this.glEnableVertexAttribArray(index);
- }
- };
-
- WebGLRenderingContext.prototype.glDisableVertexAttribArray = WebGLRenderingContext.prototype.disableVertexAttribArray;
- WebGLRenderingContext.prototype.disableVertexAttribArray = function (index) {
- if (index === cc.VERTEX_ATTRIB_FLAG_COLOR) {
- if (this._vertexAttribColor) {
- this.glDisableVertexAttribArray(index);
- this._vertexAttribColor = false;
- }
- }
- else if (index === cc.VERTEX_ATTRIB_FLAG_TEX_COORDS) {
- if (this._vertexAttribTexCoords) {
- this.glDisableVertexAttribArray(index);
- this._vertexAttribTexCoords = false;
- }
- }
- else if (index !== 0) {
- this.glDisableVertexAttribArray(index);
- }
- };
}
// GL State Cache functions
diff --git a/cocos2d/shaders/CCShaderCache.js b/cocos2d/shaders/CCShaderCache.js
index be23a9cc93..f287633114 100644
--- a/cocos2d/shaders/CCShaderCache.js
+++ b/cocos2d/shaders/CCShaderCache.js
@@ -107,67 +107,67 @@ cc.shaderCache = /** @lends cc.shaderCache# */{
_programs: {},
_init: function () {
- this.loadDefaultShaders();
+ // this.loadDefaultShaders();
return true;
},
_loadDefaultShader: function (program, type) {
switch (type) {
- case this.TYPE_POSITION_TEXTURECOLOR:
+ case cc.SHADER_POSITION_TEXTURECOLOR:
program.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_COLOR_VERT, cc.SHADER_POSITION_TEXTURE_COLOR_FRAG);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
break;
- case this.TYPE_SPRITE_POSITION_TEXTURECOLOR:
+ case cc.SHADER_SPRITE_POSITION_TEXTURECOLOR:
program.initWithVertexShaderByteArray(cc.SHADER_SPRITE_POSITION_TEXTURE_COLOR_VERT, cc.SHADER_POSITION_TEXTURE_COLOR_FRAG);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
break;
- case this.TYPE_POSITION_TEXTURECOLOR_ALPHATEST:
+ case cc.SHADER_POSITION_TEXTURECOLORALPHATEST:
program.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_COLOR_VERT, cc.SHADER_POSITION_TEXTURE_COLOR_ALPHATEST_FRAG);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
break;
- case this.TYPE_SPRITE_POSITION_TEXTURECOLOR_ALPHATEST:
+ case cc.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST:
program.initWithVertexShaderByteArray(cc.SHADER_SPRITE_POSITION_TEXTURE_COLOR_VERT, cc.SHADER_POSITION_TEXTURE_COLOR_ALPHATEST_FRAG);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
break;
- case this.TYPE_POSITION_COLOR:
+ case cc.SHADER_POSITION_COLOR:
program.initWithVertexShaderByteArray(cc.SHADER_POSITION_COLOR_VERT, cc.SHADER_POSITION_COLOR_FRAG);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
break;
- case this.TYPE_SPRITE_POSITION_COLOR:
+ case cc.SHADER_SPRITE_POSITION_COLOR:
program.initWithVertexShaderByteArray(cc.SHADER_SPRITE_POSITION_COLOR_VERT, cc.SHADER_POSITION_COLOR_FRAG);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
break;
- case this.TYPE_POSITION_TEXTURE:
+ case cc.SHADER_POSITION_TEXTURE:
program.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_VERT, cc.SHADER_POSITION_TEXTURE_FRAG);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
break;
- case this.TYPE_POSITION_TEXTURE_UCOLOR:
+ case cc.SHADER_POSITION_TEXTURE_UCOLOR:
program.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_UCOLOR_VERT, cc.SHADER_POSITION_TEXTURE_UCOLOR_FRAG);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
break;
- case this.TYPE_POSITION_TEXTURE_A8COLOR:
+ case cc.SHADER_POSITION_TEXTUREA8COLOR:
program.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_A8COLOR_VERT, cc.SHADER_POSITION_TEXTURE_A8COLOR_FRAG);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
break;
- case this.TYPE_POSITION_UCOLOR:
+ case cc.SHADER_POSITION_UCOLOR:
program.initWithVertexShaderByteArray(cc.SHADER_POSITION_UCOLOR_VERT, cc.SHADER_POSITION_UCOLOR_FRAG);
program.addAttribute("aVertex", cc.VERTEX_ATTRIB_POSITION);
break;
- case this.TYPE_POSITION_LENGTH_TEXTURECOLOR:
+ case cc.SHADER_POSITION_LENGTHTEXTURECOLOR:
program.initWithVertexShaderByteArray(cc.SHADER_POSITION_COLOR_LENGTH_TEXTURE_VERT, cc.SHADER_POSITION_COLOR_LENGTH_TEXTURE_FRAG);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
@@ -188,85 +188,6 @@ cc.shaderCache = /** @lends cc.shaderCache# */{
* loads the default shaders
*/
loadDefaultShaders: function () {
- // Position Texture Color shader
- var program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURECOLOR);
- this._programs[cc.SHADER_POSITION_TEXTURECOLOR] = program;
- this._programs["ShaderPositionTextureColor"] = program;
-
- // Position Texture Color shader with position precalculated
- program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_SPRITE_POSITION_TEXTURECOLOR);
- this._programs[cc.SHADER_SPRITE_POSITION_TEXTURECOLOR] = program;
- this._programs["ShaderSpritePositionTextureColor"] = program;
-
- // Position Texture Color alpha test
- program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURECOLOR_ALPHATEST);
- this._programs[cc.SHADER_POSITION_TEXTURECOLORALPHATEST] = program;
- this._programs["ShaderPositionTextureColorAlphaTest"] = program;
-
- // Position Texture Color alpha with position precalculated
- program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_SPRITE_POSITION_TEXTURECOLOR_ALPHATEST);
- this._programs[cc.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST] = program;
- this._programs["ShaderSpritePositionTextureColorAlphaTest"] = program;
-
- //
- // Position, Color shader
- //
- program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_POSITION_COLOR);
- this._programs[cc.SHADER_POSITION_COLOR] = program;
- this._programs["ShaderPositionColor"] = program;
-
- //
- // Position, Color shader with position precalculated
- //
- program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_SPRITE_POSITION_COLOR);
- this._programs[cc.SHADER_SPRITE_POSITION_COLOR] = program;
- this._programs["ShaderSpritePositionColor"] = program;
-
- //
- // Position Texture shader
- //
- program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE);
- this._programs[cc.SHADER_POSITION_TEXTURE] = program;
- this._programs["ShaderPositionTexture"] = program;
-
- //
- // Position, Texture attribs, 1 Color as uniform shader
- //
- program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE_UCOLOR);
- this._programs[cc.SHADER_POSITION_TEXTURE_UCOLOR] = program;
- this._programs["ShaderPositionTextureUColor"] = program;
-
- //
- // Position Texture A8 Color shader
- //
- program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE_A8COLOR);
- this._programs[cc.SHADER_POSITION_TEXTUREA8COLOR] = program;
- this._programs["ShaderPositionTextureA8Color"] = program;
-
- //
- // Position and 1 color passed as a uniform (to similate glColor4ub )
- //
- program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_POSITION_UCOLOR);
- this._programs[cc.SHADER_POSITION_UCOLOR] = program;
- this._programs["ShaderPositionUColor"] = program;
-
- //
- // Position, Legth(TexCoords, Color (used by Draw Node basically )
- //
- program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_POSITION_LENGTH_TEXTURECOLOR);
- this._programs[cc.SHADER_POSITION_LENGTHTEXTURECOLOR] = program;
- this._programs["ShaderPositionLengthTextureColor"] = program;
},
/**
@@ -336,6 +257,12 @@ cc.shaderCache = /** @lends cc.shaderCache# */{
* @param {String} key
*/
programForKey: function (key) {
+ if (!this._programs[key]) {
+ var program = new cc.GLProgram();
+ this._loadDefaultShader(program, key);
+ this._programs[key] = program;
+ }
+
return this._programs[key];
},
@@ -345,7 +272,7 @@ cc.shaderCache = /** @lends cc.shaderCache# */{
* @return {cc.GLProgram}
*/
getProgram: function (shaderName) {
- return this._programs[shaderName];
+ return this.programForKey(shaderName);
},
/**
diff --git a/cocos2d/shape-nodes/CCDrawNode.js b/cocos2d/shape-nodes/CCDrawNode.js
index 48cdf4cccc..732bd8cda8 100644
--- a/cocos2d/shape-nodes/CCDrawNode.js
+++ b/cocos2d/shape-nodes/CCDrawNode.js
@@ -25,61 +25,6 @@
THE SOFTWARE.
****************************************************************************/
-/**
- * Code copied & pasted from SpacePatrol game https://github.com/slembcke/SpacePatrol
- *
- * Renamed and added some changes for cocos2d
- *
- */
-cc.v2fzero = function () {
- return {x: 0, y: 0};
-};
-
-cc.v2f = function (x, y) {
- return {x: x, y: y};
-};
-
-cc.v2fadd = function (v0, v1) {
- return cc.v2f(v0.x + v1.x, v0.y + v1.y);
-};
-
-cc.v2fsub = function (v0, v1) {
- return cc.v2f(v0.x - v1.x, v0.y - v1.y);
-};
-
-cc.v2fmult = function (v, s) {
- return cc.v2f(v.x * s, v.y * s);
-};
-
-cc.v2fperp = function (p0) {
- return cc.v2f(-p0.y, p0.x);
-};
-
-cc.v2fneg = function (p0) {
- return cc.v2f(-p0.x, -p0.y);
-};
-
-cc.v2fdot = function (p0, p1) {
- return p0.x * p1.x + p0.y * p1.y;
-};
-
-cc.v2fforangle = function (_a_) {
- return cc.v2f(Math.cos(_a_), Math.sin(_a_));
-};
-
-cc.v2fnormalize = function (p) {
- var r = cc.pNormalize(cc.p(p.x, p.y));
- return cc.v2f(r.x, r.y);
-};
-
-cc.__v2f = function (v) {
- return cc.v2f(v.x, v.y);
-};
-
-cc.__t = function (v) {
- return {u: v.x, v: v.y};
-};
-
/**
*
The cc.BinaryStreamReader's constructor.
@@ -302,7 +302,7 @@ cc.BinaryStreamReader = cc.Class.extend({
* Override it to extend its behavior, remember to call "this._super()" in the extended "ctor" function.
* @param binaryData
*/
- ctor:function (binaryData) {
+ ctor: function (binaryData) {
this._binaryData = binaryData;
},
@@ -310,7 +310,7 @@ cc.BinaryStreamReader = cc.Class.extend({
* Set the binaryData.
* @param binaryData
*/
- setBinaryData:function (binaryData) {
+ setBinaryData: function (binaryData) {
this._binaryData = binaryData;
this._offset = 0;
},
@@ -319,16 +319,16 @@ cc.BinaryStreamReader = cc.Class.extend({
* Gets the binaryData.
* @returns {Object}
*/
- getBinaryData:function () {
+ getBinaryData: function () {
return this._binaryData;
},
- _checkSize:function (neededBits) {
+ _checkSize: function (neededBits) {
if (!(this._offset + Math.ceil(neededBits / 8) < this._data.length))
throw new Error("Index out of bound");
},
- _decodeFloat:function (precisionBits, exponentBits) {
+ _decodeFloat: function (precisionBits, exponentBits) {
var length = precisionBits + exponentBits + 1;
var size = length >> 3;
this._checkSize(length);
@@ -357,11 +357,11 @@ cc.BinaryStreamReader = cc.Class.extend({
: Math.pow(2, exponent - bias) * (1 + significand) : 0);
},
- _readByte:function (i, size) {
+ _readByte: function (i, size) {
return this._data[this._offset + size - i - 1];
},
- _decodeInt:function (bits, signed) {
+ _decodeInt: function (bits, signed) {
var x = this._readBits(0, bits, bits / 8), max = Math.pow(2, bits);
var result = signed && x >= max / 2 ? x - max : x;
@@ -369,12 +369,13 @@ cc.BinaryStreamReader = cc.Class.extend({
return result;
},
- _shl:function (a, b) {
- for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) === 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1){};
+ _shl: function (a, b) {
+ for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) === 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1) {
+ }
return a;
},
- _readBits:function (start, length, size) {
+ _readBits: function (start, length, size) {
var offsetLeft = (start + length) % 8;
var offsetRight = start % 8;
var curByte = size - (start >> 3) - 1;
@@ -392,33 +393,33 @@ cc.BinaryStreamReader = cc.Class.extend({
return sum;
},
- readInteger:function () {
+ readInteger: function () {
return this._decodeInt(32, true);
},
- readUnsignedInteger:function () {
+ readUnsignedInteger: function () {
return this._decodeInt(32, false);
},
- readSingle:function () {
+ readSingle: function () {
return this._decodeFloat(23, 8);
},
- readShort:function () {
+ readShort: function () {
return this._decodeInt(16, true);
},
- readUnsignedShort:function () {
+ readUnsignedShort: function () {
return this._decodeInt(16, false);
},
- readByte:function () {
+ readByte: function () {
var readByte = this._data[this._offset];
this._offset += 1;
return readByte;
},
- readData:function (start, end) {
+ readData: function (start, end) {
if (this._binaryData instanceof Array) {
return this._binaryData.slice(start, end);
} else {
@@ -427,11 +428,11 @@ cc.BinaryStreamReader = cc.Class.extend({
}
},
- setOffset:function (offset) {
+ setOffset: function (offset) {
this._offset = offset;
},
- getOffset:function () {
+ getOffset: function () {
return this._offset;
}
});
diff --git a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js
index d28a3cde6b..f354284de2 100644
--- a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js
+++ b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js
@@ -22,9 +22,9 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- cc.TMXLayer.CanvasRenderCmd = function(renderable){
- cc.Node.CanvasRenderCmd.call(this, renderable);
+(function () {
+ cc.TMXLayer.CanvasRenderCmd = function (renderable) {
+ this._rootCtor(renderable);
this._needDraw = true;
};
@@ -132,10 +132,10 @@
if (maxRow > rows) maxRow = rows;
}
- var i, row, col, colOffset = startRow * cols, z,
+ var i, row, col, colOffset = startRow * cols, z,
gid, grid, tex, cmd,
mask = cc.TMX_TILE_FLIPPED_MASK,
- top, left, bottom, right, dw = tilew, dh = tileh ,
+ top, left, bottom, right, dw = tilew, dh = tileh,
w = tilew * a, h = tileh * d, gt, gl, gb, gr,
flippedX = false, flippedY = false;
@@ -198,18 +198,18 @@
top = bottom - tileh;
// TMX_ORIENTATION_ISO trim
if (!hasRotation && layerOrientation === cc.TMX_ORIENTATION_ISO) {
- gb = -mapy + bottom*d;
- if (gb < -winh-h) {
- col += Math.floor((-winh - gb)*2/h) - 1;
+ gb = -mapy + bottom * d;
+ if (gb < -winh - h) {
+ col += Math.floor((-winh - gb) * 2 / h) - 1;
continue;
}
- gr = mapx + right*a;
+ gr = mapx + right * a;
if (gr < -w) {
- col += Math.floor((-gr)*2/w) - 1;
+ col += Math.floor((-gr) * 2 / w) - 1;
continue;
}
- gl = mapx + left*a;
- gt = -mapy + top*d;
+ gl = mapx + left * a;
+ gt = -mapy + top * d;
if (gl > winw || gt > 0) {
col = maxCol;
continue;
@@ -256,4 +256,4 @@
}
}
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js
index 36103af82b..d0e90bebc9 100644
--- a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js
+++ b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js
@@ -22,15 +22,15 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- cc.TMXLayer.WebGLRenderCmd = function(renderableObject){
- cc.Node.WebGLRenderCmd.call(this, renderableObject);
+(function () {
+ cc.TMXLayer.WebGLRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
this._needDraw = true;
this._vertices = [
- {x:0, y:0},
- {x:0, y:0},
- {x:0, y:0},
- {x:0, y:0}
+ {x: 0, y: 0},
+ {x: 0, y: 0},
+ {x: 0, y: 0},
+ {x: 0, y: 0}
];
this._color = new Uint32Array(1);
this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST);
@@ -86,7 +86,7 @@
cg *= ca;
cb *= ca;
}
- this._color[0] = ((opacity<<24) | (cb<<16) | (cg<<8) | cr);
+ this._color[0] = ((opacity << 24) | (cb << 16) | (cg << 8) | cr);
// Culling
var startCol = 0, startRow = 0,
@@ -107,7 +107,7 @@
offset = vertexDataOffset,
colOffset = startRow * cols, z, gid, grid,
mask = cc.TMX_TILE_FLIPPED_MASK,
- i, top, left, bottom, right,
+ i, top, left, bottom, right,
w = tilew * a, h = tileh * d, gt, gl, gb, gr,
wa = a, wb = b, wc = c, wd = d, wtx = tx, wty = ty, // world
flagged = false, flippedX = false, flippedY = false,
@@ -156,18 +156,18 @@
top = bottom + tileh;
// TMX_ORIENTATION_ISO trim
if (!hasRotation && layerOrientation === cc.TMX_ORIENTATION_ISO) {
- gb = mapy + bottom*d;
- if (gb > winh+h) {
- col += Math.floor((gb-winh)*2/h) - 1;
+ gb = mapy + bottom * d;
+ if (gb > winh + h) {
+ col += Math.floor((gb - winh) * 2 / h) - 1;
continue;
}
- gr = mapx + right*a;
+ gr = mapx + right * a;
if (gr < -w) {
- col += Math.floor((-gr)*2/w) - 1;
+ col += Math.floor((-gr) * 2 / w) - 1;
continue;
}
- gl = mapx + left*a;
- gt = mapy + top*d;
+ gl = mapx + left * a;
+ gt = mapy + top * d;
if (gl > winw || gt < 0) {
col = maxCol;
continue;
@@ -221,21 +221,21 @@
ui32buffer[offset + 3] = this._color[0];
switch (i) {
case 0: // tl
- f32buffer[offset + 4] = flippedX ? grid.r : grid.l;
- f32buffer[offset + 5] = flippedY ? grid.b : grid.t;
- break;
+ f32buffer[offset + 4] = flippedX ? grid.r : grid.l;
+ f32buffer[offset + 5] = flippedY ? grid.b : grid.t;
+ break;
case 1: // bl
- f32buffer[offset + 4] = flippedX ? grid.r : grid.l;
- f32buffer[offset + 5] = flippedY ? grid.t : grid.b;
- break;
+ f32buffer[offset + 4] = flippedX ? grid.r : grid.l;
+ f32buffer[offset + 5] = flippedY ? grid.t : grid.b;
+ break;
case 2: // tr
- f32buffer[offset + 4] = flippedX ? grid.l : grid.r;
- f32buffer[offset + 5] = flippedY ? grid.b : grid.t;
- break;
+ f32buffer[offset + 4] = flippedX ? grid.l : grid.r;
+ f32buffer[offset + 5] = flippedY ? grid.b : grid.t;
+ break;
case 3: // br
- f32buffer[offset + 4] = flippedX ? grid.l : grid.r;
- f32buffer[offset + 5] = flippedY ? grid.t : grid.b;
- break;
+ f32buffer[offset + 4] = flippedX ? grid.l : grid.r;
+ f32buffer[offset + 5] = flippedY ? grid.t : grid.b;
+ break;
}
offset += 6;
diff --git a/cocos2d/transitions/CCTransition.js b/cocos2d/transitions/CCTransition.js
index 6796074555..09b18228e6 100644
--- a/cocos2d/transitions/CCTransition.js
+++ b/cocos2d/transitions/CCTransition.js
@@ -64,12 +64,12 @@ cc.TRANSITION_ORIENTATION_DOWN_OVER = 1;
* var trans = new TransitionScene(time,scene);
*/
cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
- _inScene:null,
- _outScene:null,
- _duration:null,
- _isInSceneOnTop:false,
- _isSendCleanupToScene:false,
- _className:"TransitionScene",
+ _inScene: null,
+ _outScene: null,
+ _duration: null,
+ _isInSceneOnTop: false,
+ _isSendCleanupToScene: false,
+ _className: "TransitionScene",
/**
* creates a base transition with duration and incoming scene
@@ -77,14 +77,14 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
* @param {Number} t time in seconds
* @param {cc.Scene} scene the scene to transit with
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.Scene.prototype.ctor.call(this);
- if(t !== undefined && scene !== undefined)
+ if (t !== undefined && scene !== undefined)
this.initWithDuration(t, scene);
},
//private
- _setNewScene:function (dt) {
+ _setNewScene: function (dt) {
this.unschedule(this._setNewScene);
// Before replacing, save the "send cleanup to scene"
var director = cc.director;
@@ -99,14 +99,14 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
},
//protected
- _sceneOrder:function () {
+ _sceneOrder: function () {
this._isInSceneOnTop = true;
},
/**
* stuff gets drawn here
*/
- visit:function () {
+ visit: function () {
if (this._isInSceneOnTop) {
this._outScene.visit();
this._inScene.visit();
@@ -125,7 +125,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
* If you override onEnter, you must call its parent's onEnter function with this._super().
*
*/
- onEnter:function () {
+ onEnter: function () {
cc.Node.prototype.onEnter.call(this);
// disable events while transitions
@@ -133,9 +133,9 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
// outScene should not receive the onEnter callback
// only the onExitTransitionDidStart
- this._outScene.onExitTransitionDidStart();
+ this._outScene._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart);
- this._inScene.onEnter();
+ this._inScene._performRecursive(cc.Node._stateCallbackType.onEnter);
},
/**
@@ -146,27 +146,27 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
* If you override onExit, you shall call its parent's onExit with this._super().
*
*/
- onExit:function () {
+ onExit: function () {
cc.Node.prototype.onExit.call(this);
// enable events while transitions
cc.eventManager.setEnabled(true);
- this._outScene.onExit();
+ this._outScene._performRecursive(cc.Node._stateCallbackType.onExit);
// _inScene should not receive the onEnter callback
// only the onEnterTransitionDidFinish
- this._inScene.onEnterTransitionDidFinish();
+ this._inScene._performRecursive(cc.Node._stateCallbackType.onEnterTransitionDidFinish);
},
/**
* custom cleanup
*/
- cleanup:function () {
+ cleanup: function () {
cc.Node.prototype.cleanup.call(this);
if (this._isSendCleanupToScene)
- this._outScene.cleanup();
+ this._outScene._performRecursive(cc.Node._stateCallbackType.cleanup);
},
/**
@@ -175,17 +175,17 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
* @param {cc.Scene} scene a scene to transit to
* @return {Boolean} return false if error
*/
- initWithDuration:function (t, scene) {
- if(!scene)
+ initWithDuration: function (t, scene) {
+ if (!scene)
throw new Error("cc.TransitionScene.initWithDuration(): Argument scene must be non-nil");
if (this.init()) {
this._duration = t;
this.attr({
- x: 0,
- y: 0,
- anchorX: 0,
- anchorY: 0
+ x: 0,
+ y: 0,
+ anchorX: 0,
+ anchorY: 0
});
// retain
this._inScene = scene;
@@ -195,7 +195,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
this._outScene.init();
}
- if(this._inScene === this._outScene)
+ if (this._inScene === this._outScene)
throw new Error("cc.TransitionScene.initWithDuration(): Incoming scene must be different from the outgoing scene");
this._sceneOrder();
@@ -208,22 +208,22 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
/**
* called after the transition finishes
*/
- finish:function () {
+ finish: function () {
// clean up
this._inScene.attr({
- visible: true,
- x: 0,
- y: 0,
- scale: 1.0,
- rotation: 0.0
+ visible: true,
+ x: 0,
+ y: 0,
+ scale: 1.0,
+ rotation: 0.0
});
this._outScene.attr({
- visible: false,
- x: 0,
- y: 0,
- scale: 1.0,
- rotation: 0.0
+ visible: false,
+ x: 0,
+ y: 0,
+ scale: 1.0,
+ rotation: 0.0
});
//[self schedule:@selector(setNewScene:) interval:0];
@@ -233,7 +233,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
/**
* set hide the out scene and show in scene
*/
- hideOutShowIn:function () {
+ hideOutShowIn: function () {
this._inScene.visible = true;
this._outScene.visible = false;
}
@@ -262,7 +262,7 @@ cc.TransitionScene.create = function (t, scene) {
* var trans = new cc.TransitionSceneOriented(time,scene,orientation);
*/
cc.TransitionSceneOriented = cc.TransitionScene.extend(/** @lends cc.TransitionSceneOriented# */{
- _orientation:0,
+ _orientation: 0,
/**
* Constructor of TransitionSceneOriented
@@ -270,7 +270,7 @@ cc.TransitionSceneOriented = cc.TransitionScene.extend(/** @lends cc.TransitionS
* @param {cc.Scene} scene
* @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} orientation
*/
- ctor:function (t, scene, orientation) {
+ ctor: function (t, scene, orientation) {
cc.TransitionScene.prototype.ctor.call(this);
orientation != undefined && this.initWithDuration(t, scene, orientation);
},
@@ -281,7 +281,7 @@ cc.TransitionSceneOriented = cc.TransitionScene.extend(/** @lends cc.TransitionS
* @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} orientation
* @return {Boolean}
*/
- initWithDuration:function (t, scene, orientation) {
+ initWithDuration: function (t, scene, orientation) {
if (cc.TransitionScene.prototype.initWithDuration.call(this, t, scene)) {
this._orientation = orientation;
}
@@ -318,7 +318,7 @@ cc.TransitionRotoZoom = cc.TransitionScene.extend(/** @lends cc.TransitionRotoZo
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionScene.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
@@ -326,19 +326,19 @@ cc.TransitionRotoZoom = cc.TransitionScene.extend(/** @lends cc.TransitionRotoZo
* Custom On Enter callback
* @override
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
- this._inScene.attr({
- scale: 0.001,
- anchorX: 0.5,
- anchorY: 0.5
- });
- this._outScene.attr({
- scale: 1.0,
- anchorX: 0.5,
- anchorY: 0.5
- });
+ this._inScene.attr({
+ scale: 0.001,
+ anchorX: 0.5,
+ anchorY: 0.5
+ });
+ this._outScene.attr({
+ scale: 1.0,
+ anchorX: 0.5,
+ anchorY: 0.5
+ });
var rotoZoom = cc.sequence(
cc.spawn(cc.scaleBy(this._duration / 2, 0.001),
@@ -378,26 +378,26 @@ cc.TransitionJumpZoom = cc.TransitionScene.extend(/** @lends cc.TransitionJumpZo
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionScene.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
/**
* Custom on enter
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
var winSize = cc.director.getWinSize();
- this._inScene.attr({
- scale: 0.5,
- x: winSize.width,
- y: 0,
- anchorX: 0.5,
- anchorY: 0.5
- });
+ this._inScene.attr({
+ scale: 0.5,
+ x: winSize.width,
+ y: 0,
+ anchorX: 0.5,
+ anchorY: 0.5
+ });
this._outScene.anchorX = 0.5;
- this._outScene.anchorY = 0.5;
+ this._outScene.anchorY = 0.5;
var jump = cc.jumpBy(this._duration / 4, cc.p(-winSize.width, 0), winSize.width / 4, 2);
var scaleIn = cc.scaleTo(this._duration / 4, 1.0);
@@ -438,14 +438,14 @@ cc.TransitionMoveInL = cc.TransitionScene.extend(/** @lends cc.TransitionMoveInL
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionScene.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
/**
* Custom on enter
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
this.initScenes();
@@ -458,14 +458,14 @@ cc.TransitionMoveInL = cc.TransitionScene.extend(/** @lends cc.TransitionMoveInL
/**
* initializes the scenes
*/
- initScenes:function () {
+ initScenes: function () {
this._inScene.setPosition(-cc.director.getWinSize().width, 0);
},
/**
* returns the action that will be performed
*/
- action:function () {
+ action: function () {
return cc.moveTo(this._duration, cc.p(0, 0));
},
@@ -474,7 +474,7 @@ cc.TransitionMoveInL = cc.TransitionScene.extend(/** @lends cc.TransitionMoveInL
* @param {cc.ActionInterval} action
* @return {cc.EaseOut}
*/
- easeActionWithAction:function (action) {
+ easeActionWithAction: function (action) {
return new cc.EaseOut(action, 2.0);
}
});
@@ -505,14 +505,14 @@ cc.TransitionMoveInR = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveI
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionMoveInL.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
/**
* Init function
*/
- initScenes:function () {
+ initScenes: function () {
this._inScene.setPosition(cc.director.getWinSize().width, 0);
}
});
@@ -543,14 +543,14 @@ cc.TransitionMoveInT = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveI
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionMoveInL.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
/**
* init function
*/
- initScenes:function () {
+ initScenes: function () {
this._inScene.setPosition(0, cc.director.getWinSize().height);
}
});
@@ -581,7 +581,7 @@ cc.TransitionMoveInB = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveI
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionMoveInL.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
@@ -589,7 +589,7 @@ cc.TransitionMoveInB = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveI
/**
* init function
*/
- initScenes:function () {
+ initScenes: function () {
this._inScene.setPosition(0, -cc.director.getWinSize().height);
}
});
@@ -630,18 +630,18 @@ cc.TransitionSlideInL = cc.TransitionScene.extend(/** @lends cc.TransitionSlideI
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionScene.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
- _sceneOrder:function () {
+ _sceneOrder: function () {
this._isInSceneOnTop = false;
},
/**
* custom on enter
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
this.initScenes();
@@ -657,14 +657,14 @@ cc.TransitionSlideInL = cc.TransitionScene.extend(/** @lends cc.TransitionSlideI
/**
* initializes the scenes
*/
- initScenes:function () {
+ initScenes: function () {
this._inScene.setPosition(-cc.director.getWinSize().width + cc.ADJUST_FACTOR, 0);
},
/**
* returns the action that will be performed by the incoming and outgoing scene
* @return {cc.MoveBy}
*/
- action:function () {
+ action: function () {
return cc.moveBy(this._duration, cc.p(cc.director.getWinSize().width - cc.ADJUST_FACTOR, 0));
},
@@ -672,7 +672,7 @@ cc.TransitionSlideInL = cc.TransitionScene.extend(/** @lends cc.TransitionSlideI
* @param {cc.ActionInterval} action
* @return {*}
*/
- easeActionWithAction:function (action) {
+ easeActionWithAction: function (action) {
return new cc.EaseInOut(action, 2.0);
}
});
@@ -703,24 +703,24 @@ cc.TransitionSlideInR = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionSlideInL.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
- _sceneOrder:function () {
+ _sceneOrder: function () {
this._isInSceneOnTop = true;
},
/**
* initializes the scenes
*/
- initScenes:function () {
+ initScenes: function () {
this._inScene.setPosition(cc.director.getWinSize().width - cc.ADJUST_FACTOR, 0);
},
/**
* returns the action that will be performed by the incoming and outgoing scene
* @return {cc.MoveBy}
*/
- action:function () {
+ action: function () {
return cc.moveBy(this._duration, cc.p(-(cc.director.getWinSize().width - cc.ADJUST_FACTOR), 0));
}
});
@@ -751,18 +751,18 @@ cc.TransitionSlideInB = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionSlideInL.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
- _sceneOrder:function () {
+ _sceneOrder: function () {
this._isInSceneOnTop = false;
},
/**
* initializes the scenes
*/
- initScenes:function () {
+ initScenes: function () {
this._inScene.setPosition(0, -(cc.director.getWinSize().height - cc.ADJUST_FACTOR));
},
@@ -770,7 +770,7 @@ cc.TransitionSlideInB = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli
* returns the action that will be performed by the incoming and outgoing scene
* @return {cc.MoveBy}
*/
- action:function () {
+ action: function () {
return cc.moveBy(this._duration, cc.p(0, cc.director.getWinSize().height - cc.ADJUST_FACTOR));
}
});
@@ -801,18 +801,18 @@ cc.TransitionSlideInT = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionSlideInL.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
- _sceneOrder:function () {
+ _sceneOrder: function () {
this._isInSceneOnTop = true;
},
/**
* initializes the scenes
*/
- initScenes:function () {
+ initScenes: function () {
this._inScene.setPosition(0, cc.director.getWinSize().height - cc.ADJUST_FACTOR);
},
@@ -820,7 +820,7 @@ cc.TransitionSlideInT = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli
* returns the action that will be performed by the incoming and outgoing scene
* @return {cc.MoveBy}
*/
- action:function () {
+ action: function () {
return cc.moveBy(this._duration, cc.p(0, -(cc.director.getWinSize().height - cc.ADJUST_FACTOR)));
}
});
@@ -851,26 +851,26 @@ cc.TransitionShrinkGrow = cc.TransitionScene.extend(/** @lends cc.TransitionShri
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionScene.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
/**
* Custom on enter
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
- this._inScene.attr({
- scale: 0.001,
- anchorX: 2 / 3.0,
- anchorY: 0.5
- });
- this._outScene.attr({
- scale: 1.0,
- anchorX: 1 / 3.0,
- anchorY: 0.5
- });
+ this._inScene.attr({
+ scale: 0.001,
+ anchorX: 2 / 3.0,
+ anchorY: 0.5
+ });
+ this._outScene.attr({
+ scale: 1.0,
+ anchorX: 1 / 3.0,
+ anchorY: 0.5
+ });
var scaleOut = cc.scaleTo(this._duration, 0.01);
var scaleIn = cc.scaleTo(this._duration, 1.0);
@@ -883,7 +883,7 @@ cc.TransitionShrinkGrow = cc.TransitionScene.extend(/** @lends cc.TransitionShri
* @param action
* @return {cc.EaseOut}
*/
- easeActionWithAction:function (action) {
+ easeActionWithAction: function (action) {
return new cc.EaseOut(action, 2.0);
}
});
@@ -910,7 +910,7 @@ cc.TransitionShrinkGrow.create = function (t, scene) {
* var trans = new cc.TransitionFade(time,scene,color)
*/
cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{
- _color:null,
+ _color: null,
/**
* Constructor of TransitionFade
@@ -918,7 +918,7 @@ cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{
* @param {cc.Scene} scene
* @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
*/
- ctor:function (t, scene, color) {
+ ctor: function (t, scene, color) {
cc.TransitionScene.prototype.ctor.call(this);
this._color = cc.color();
scene && this.initWithDuration(t, scene, color);
@@ -927,7 +927,7 @@ cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{
/**
* custom on enter
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
var l = new cc.LayerColor(this._color);
@@ -948,7 +948,7 @@ cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{
/**
* custom on exit
*/
- onExit:function () {
+ onExit: function () {
cc.TransitionScene.prototype.onExit.call(this);
this.removeChildByTag(cc.SCENE_FADE, false);
},
@@ -960,7 +960,7 @@ cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{
* @param {cc.Color} color
* @return {Boolean}
*/
- initWithDuration:function (t, scene, color) {
+ initWithDuration: function (t, scene, color) {
color = color || cc.color.BLACK;
if (cc.TransitionScene.prototype.initWithDuration.call(this, t, scene)) {
this._color.r = color.r;
@@ -1000,14 +1000,14 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionScene.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
/**
* custom on enter
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
// create a transparent color layer
@@ -1020,12 +1020,12 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross
var inTexture = new cc.RenderTexture(winSize.width, winSize.height);
inTexture.sprite.anchorX = 0.5;
- inTexture.sprite.anchorY = 0.5;
+ inTexture.sprite.anchorY = 0.5;
inTexture.attr({
- x: winSize.width / 2,
- y: winSize.height / 2,
- anchorX: 0.5,
- anchorY: 0.5
+ x: winSize.width / 2,
+ y: winSize.height / 2,
+ anchorX: 0.5,
+ anchorY: 0.5
});
// render inScene to its texturebuffer
@@ -1036,8 +1036,8 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross
// create the second render texture for outScene
var outTexture = new cc.RenderTexture(winSize.width, winSize.height);
outTexture.setPosition(winSize.width / 2, winSize.height / 2);
- outTexture.sprite.anchorX = outTexture.anchorX = 0.5;
- outTexture.sprite.anchorY = outTexture.anchorY = 0.5;
+ outTexture.sprite.anchorX = outTexture.anchorX = 0.5;
+ outTexture.sprite.anchorY = outTexture.anchorY = 0.5;
// render outScene to its texturebuffer
outTexture.begin();
@@ -1071,24 +1071,10 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross
/**
* custom on exit
*/
- onExit:function () {
+ onExit: function () {
this.removeChildByTag(cc.SCENE_FADE, false);
cc.TransitionScene.prototype.onExit.call(this);
},
-
- /**
- * stuff gets drawn here
- */
- visit:function () {
- cc.Node.prototype.visit.call(this);
- },
-
- /**
- * overide draw
- */
- draw:function () {
- // override draw since both scenes (textures) are rendered in 1 scene
- }
});
/**
@@ -1118,23 +1104,23 @@ cc.TransitionTurnOffTiles = cc.TransitionScene.extend(/** @lends cc.TransitionTu
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionScene.prototype.ctor.call(this);
this._gridProxy = new cc.NodeGrid();
scene && this.initWithDuration(t, scene);
},
- _sceneOrder:function () {
+ _sceneOrder: function () {
this._isInSceneOnTop = false;
},
/**
* custom on enter
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
this._gridProxy.setTarget(this._outScene);
- this._gridProxy.onEnter();
+ this._gridProxy._performRecursive(cc.Node._stateCallbackType.onEnter);
var winSize = cc.director.getWinSize();
var aspect = winSize.width / winSize.height;
@@ -1145,7 +1131,7 @@ cc.TransitionTurnOffTiles = cc.TransitionScene.extend(/** @lends cc.TransitionTu
this._gridProxy.runAction(cc.sequence(action, cc.callFunc(this.finish, this), cc.stopGrid()));
},
- visit: function(){
+ visit: function () {
this._inScene.visit();
this._gridProxy.visit();
},
@@ -1154,7 +1140,7 @@ cc.TransitionTurnOffTiles = cc.TransitionScene.extend(/** @lends cc.TransitionTu
* @param {cc.ActionInterval} action
* @return {cc.ActionInterval}
*/
- easeActionWithAction:function (action) {
+ easeActionWithAction: function (action) {
return action;
}
});
@@ -1182,7 +1168,7 @@ cc.TransitionTurnOffTiles.create = function (t, scene) {
cc.TransitionSplitCols = cc.TransitionScene.extend(/** @lends cc.TransitionSplitCols# */{
_gridProxy: null,
- _switchTargetToInscene: function(){
+ _switchTargetToInscene: function () {
this._gridProxy.setTarget(this._inScene);
},
@@ -1191,7 +1177,7 @@ cc.TransitionSplitCols = cc.TransitionScene.extend(/** @lends cc.TransitionSplit
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionScene.prototype.ctor.call(this);
this._gridProxy = new cc.NodeGrid();
scene && this.initWithDuration(t, scene);
@@ -1199,11 +1185,11 @@ cc.TransitionSplitCols = cc.TransitionScene.extend(/** @lends cc.TransitionSplit
/**
* custom on enter
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
//this._inScene.visible = false;
this._gridProxy.setTarget(this._outScene);
- this._gridProxy.onEnter();
+ this._gridProxy._performRecursive(cc.Node._stateCallbackType.onEnter);
var split = this.action();
var seq = cc.sequence(
@@ -1214,13 +1200,13 @@ cc.TransitionSplitCols = cc.TransitionScene.extend(/** @lends cc.TransitionSplit
);
},
- onExit: function(){
+ onExit: function () {
this._gridProxy.setTarget(null);
- this._gridProxy.onExit();
+ this._gridProxy._performRecursive(cc.Node._stateCallbackType.onExit);
cc.TransitionScene.prototype.onExit.call(this);
},
- visit: function(){
+ visit: function () {
this._gridProxy.visit();
},
@@ -1228,14 +1214,14 @@ cc.TransitionSplitCols = cc.TransitionScene.extend(/** @lends cc.TransitionSplit
* @param {cc.ActionInterval} action
* @return {cc.EaseInOut}
*/
- easeActionWithAction:function (action) {
+ easeActionWithAction: function (action) {
return new cc.EaseInOut(action, 3.0);
},
/**
* @return {*}
*/
- action:function () {
+ action: function () {
return cc.splitCols(this._duration / 2.0, 3);
}
});
@@ -1267,14 +1253,14 @@ cc.TransitionSplitRows = cc.TransitionSplitCols.extend(/** @lends cc.TransitionS
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionSplitCols.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
/**
* @return {*}
*/
- action:function () {
+ action: function () {
return cc.splitRows(this._duration / 2.0, 3);
}
});
@@ -1306,23 +1292,23 @@ cc.TransitionFadeTR = cc.TransitionScene.extend(/** @lends cc.TransitionFadeTR#
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionScene.prototype.ctor.call(this);
this._gridProxy = new cc.NodeGrid();
scene && this.initWithDuration(t, scene);
},
- _sceneOrder:function () {
+ _sceneOrder: function () {
this._isInSceneOnTop = false;
},
/**
* Custom on enter
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
this._gridProxy.setTarget(this._outScene);
- this._gridProxy.onEnter();
+ this._gridProxy._performRecursive(cc.Node._stateCallbackType.onEnter);
var winSize = cc.director.getWinSize();
var aspect = winSize.width / winSize.height;
@@ -1335,7 +1321,7 @@ cc.TransitionFadeTR = cc.TransitionScene.extend(/** @lends cc.TransitionFadeTR#
);
},
- visit: function(){
+ visit: function () {
this._inScene.visit();
this._gridProxy.visit();
},
@@ -1344,7 +1330,7 @@ cc.TransitionFadeTR = cc.TransitionScene.extend(/** @lends cc.TransitionFadeTR#
* @param {cc.ActionInterval} action
* @return {cc.ActionInterval}
*/
- easeActionWithAction:function (action) {
+ easeActionWithAction: function (action) {
return action;
},
@@ -1352,7 +1338,7 @@ cc.TransitionFadeTR = cc.TransitionScene.extend(/** @lends cc.TransitionFadeTR#
* @param {cc.Size} size
* @return {*}
*/
- actionWithSize:function (size) {
+ actionWithSize: function (size) {
return cc.fadeOutTRTiles(this._duration, size);
}
});
@@ -1383,7 +1369,7 @@ cc.TransitionFadeBL = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeBL#
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionFadeTR.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
@@ -1392,7 +1378,7 @@ cc.TransitionFadeBL = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeBL#
* @param {cc.Size} size
* @return {*}
*/
- actionWithSize:function (size) {
+ actionWithSize: function (size) {
return cc.fadeOutBLTiles(this._duration, size);
}
});
@@ -1425,7 +1411,7 @@ cc.TransitionFadeUp = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeUp#
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionFadeTR.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
@@ -1434,7 +1420,7 @@ cc.TransitionFadeUp = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeUp#
* @param {cc.Size} size
* @return {cc.FadeOutUpTiles}
*/
- actionWithSize:function (size) {
+ actionWithSize: function (size) {
return new cc.FadeOutUpTiles(this._duration, size);
}
});
@@ -1466,7 +1452,7 @@ cc.TransitionFadeDown = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeD
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionFadeTR.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
@@ -1475,8 +1461,8 @@ cc.TransitionFadeDown = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeD
* @param {cc.Size} size
* @return {*}
*/
- actionWithSize:function (size) {
- return cc.fadeOutDownTiles( this._duration, size);
+ actionWithSize: function (size) {
+ return cc.fadeOutDownTiles(this._duration, size);
}
});
diff --git a/cocos2d/transitions/CCTransitionPageTurn.js b/cocos2d/transitions/CCTransitionPageTurn.js
index 6b71fd848b..44a6bedd28 100644
--- a/cocos2d/transitions/CCTransitionPageTurn.js
+++ b/cocos2d/transitions/CCTransitionPageTurn.js
@@ -47,7 +47,7 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu
* @param {cc.Scene} scene
* @param {Boolean} backwards
*/
- ctor:function (t, scene, backwards) {
+ ctor: function (t, scene, backwards) {
cc.TransitionScene.prototype.ctor.call(this);
this._gridProxy = new cc.NodeGrid();
this.initWithDuration(t, scene, backwards);
@@ -56,9 +56,9 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu
/**
* @type Boolean
*/
- _back:true,
+ _back: true,
_gridProxy: null,
- _className:"TransitionPageTurn",
+ _className: "TransitionPageTurn",
/**
* Creates a base transition with duration and incoming scene.
@@ -69,7 +69,7 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu
* @param {Boolean} backwards
* @return {Boolean}
*/
- initWithDuration:function (t, scene, backwards) {
+ initWithDuration: function (t, scene, backwards) {
// XXX: needed before [super init]
this._back = backwards;
@@ -83,7 +83,7 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu
* @param {cc.Size} vector
* @return {cc.ReverseTime|cc.TransitionScene}
*/
- actionWithSize:function (vector) {
+ actionWithSize: function (vector) {
if (this._back)
return cc.reverseTime(cc.pageTurn3D(this._duration, vector)); // Get hold of the PageTurn3DAction
else
@@ -93,7 +93,7 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu
/**
* custom on enter
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
var winSize = cc.director.getWinSize();
var x, y;
@@ -109,11 +109,11 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu
if (!this._back) {
gridProxy.setTarget(this._outScene);
- gridProxy.onEnter();
- gridProxy.runAction( cc.sequence(action,cc.callFunc(this.finish, this),cc.stopGrid()));
+ gridProxy._performRecursive(cc.Node._stateCallbackType.onEnter);
+ gridProxy.runAction(cc.sequence(action, cc.callFunc(this.finish, this), cc.stopGrid()));
} else {
gridProxy.setTarget(this._inScene);
- gridProxy.onEnter();
+ gridProxy._performRecursive(cc.Node._stateCallbackType.onEnter);
// to prevent initial flicker
this._inScene.visible = false;
gridProxy.runAction(
@@ -123,16 +123,16 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu
}
},
- visit: function(){
+ visit: function () {
//cc.TransitionScene.prototype.visit.call(this);
- if(this._back)
+ if (this._back)
this._outScene.visit();
else
this._inScene.visit();
this._gridProxy.visit();
},
- _sceneOrder:function () {
+ _sceneOrder: function () {
this._isInSceneOnTop = this._back;
}
});
diff --git a/extensions/ccb-reader/CCBAnimationManager.js b/extensions/ccb-reader/CCBAnimationManager.js
index b341ea4bbd..54ab341f0c 100644
--- a/extensions/ccb-reader/CCBAnimationManager.js
+++ b/extensions/ccb-reader/CCBAnimationManager.js
@@ -24,43 +24,48 @@
THE SOFTWARE.
****************************************************************************/
+(function () {
+
+var _pos = cc.p();
+
cc.BuilderAnimationManagerDelegate = cc.Class.extend({
- completedAnimationSequenceNamed:function (name) {}
+ completedAnimationSequenceNamed: function (name) {
+ }
});
cc.BuilderAnimationManager = cc.Class.extend({
- _sequences:null,
- _nodeSequences:null,
- _baseValues:null,
- _autoPlaySequenceId:0,
-
- _rootNode:null,
- _owner:null,
- _rootContainerSize:null,
-
- _delegate:null,
- _runningSequence:null,
-
- _documentOutletNames:null,
- _documentOutletNodes:null,
- _documentCallbackNames:null,
- _documentCallbackNodes:null,
- _documentCallbackControlEvents:null,
- _documentControllerName:"",
- _lastCompletedSequenceName:"",
- _keyframeCallbacks:null,
- _keyframeCallFuncs:null,
-
- _animationCompleteCallbackFunc:null,
- _target:null,
- _jsControlled:false,
-
- ctor:function () {
+ _sequences: null,
+ _nodeSequences: null,
+ _baseValues: null,
+ _autoPlaySequenceId: 0,
+
+ _rootNode: null,
+ _owner: null,
+ _rootContainerSize: null,
+
+ _delegate: null,
+ _runningSequence: null,
+
+ _documentOutletNames: null,
+ _documentOutletNodes: null,
+ _documentCallbackNames: null,
+ _documentCallbackNodes: null,
+ _documentCallbackControlEvents: null,
+ _documentControllerName: "",
+ _lastCompletedSequenceName: "",
+ _keyframeCallbacks: null,
+ _keyframeCallFuncs: null,
+
+ _animationCompleteCallbackFunc: null,
+ _target: null,
+ _jsControlled: false,
+
+ ctor: function () {
this._rootContainerSize = cc.size(0, 0);
this.init();
},
- init:function () {
+ init: function () {
this._sequences = [];
this._nodeSequences = new cc._Dictionary();
this._baseValues = new cc._Dictionary();
@@ -77,122 +82,122 @@ cc.BuilderAnimationManager = cc.Class.extend({
return true;
},
- getSequences:function () {
+ getSequences: function () {
return this._sequences;
},
- setSequences:function(seqs){
+ setSequences: function (seqs) {
this._sequences = seqs;
},
- getAutoPlaySequenceId:function () {
+ getAutoPlaySequenceId: function () {
return this._autoPlaySequenceId;
},
- setAutoPlaySequenceId:function (autoPlaySequenceId) {
+ setAutoPlaySequenceId: function (autoPlaySequenceId) {
this._autoPlaySequenceId = autoPlaySequenceId;
},
- getRootNode:function () {
+ getRootNode: function () {
return this._rootNode;
},
- setRootNode:function (rootNode) {
+ setRootNode: function (rootNode) {
this._rootNode = rootNode;
},
- getOwner:function () {
+ getOwner: function () {
return this._owner;
},
- setOwner:function (owner) {
+ setOwner: function (owner) {
this._owner = owner;
},
- addDocumentCallbackNode:function(node){
+ addDocumentCallbackNode: function (node) {
this._documentCallbackNodes.push(node);
},
- addDocumentCallbackName:function(name){
+ addDocumentCallbackName: function (name) {
this._documentCallbackNames.push(name);
},
- addDocumentCallbackControlEvents:function(controlEvents){
+ addDocumentCallbackControlEvents: function (controlEvents) {
this._documentCallbackControlEvents.push(controlEvents);
},
- addDocumentOutletNode:function(node){
+ addDocumentOutletNode: function (node) {
this._documentOutletNodes.push(node);
},
- addDocumentOutletName:function(name){
+ addDocumentOutletName: function (name) {
this._documentOutletNames.push(name);
},
- setDocumentControllerName:function(name){
+ setDocumentControllerName: function (name) {
this._documentControllerName = name;
},
- getDocumentControllerName:function(){
+ getDocumentControllerName: function () {
return this._documentControllerName;
},
- getDocumentCallbackNames:function(){
+ getDocumentCallbackNames: function () {
return this._documentCallbackNames;
},
- getDocumentCallbackNodes:function(){
+ getDocumentCallbackNodes: function () {
return this._documentCallbackNodes;
},
- getDocumentCallbackControlEvents:function(){
+ getDocumentCallbackControlEvents: function () {
return this._documentCallbackControlEvents;
},
- getDocumentOutletNames:function(){
+ getDocumentOutletNames: function () {
return this._documentOutletNames;
},
- getDocumentOutletNodes:function(){
+ getDocumentOutletNodes: function () {
return this._documentOutletNodes;
},
- getLastCompletedSequenceName:function(){
+ getLastCompletedSequenceName: function () {
return this._lastCompletedSequenceName;
},
- getKeyframeCallbacks:function(){
+ getKeyframeCallbacks: function () {
return this._keyframeCallbacks;
},
- getRootContainerSize:function () {
+ getRootContainerSize: function () {
return this._rootContainerSize;
},
- setRootContainerSize:function (rootContainerSize) {
+ setRootContainerSize: function (rootContainerSize) {
this._rootContainerSize = cc.size(rootContainerSize.width, rootContainerSize.height);
},
- getDelegate:function () {
+ getDelegate: function () {
return this._delegate;
},
- setDelegate:function (delegate) {
+ setDelegate: function (delegate) {
this._delegate = delegate;
},
- getRunningSequenceName:function () {
- if(this._runningSequence)
+ getRunningSequenceName: function () {
+ if (this._runningSequence)
return this._runningSequence.getName();
return null;
},
- getContainerSize:function (node) {
+ getContainerSize: function (node) {
if (node)
return node.getContentSize();
else
return this._rootContainerSize;
},
- addNode:function (node, seq) {
+ addNode: function (node, seq) {
this._nodeSequences.setObject(seq, node);
},
- setBaseValue:function (value, node, propName) {
+ setBaseValue: function (value, node, propName) {
var props = this._baseValues.objectForKey(node);
if (!props) {
props = new cc._Dictionary();
@@ -201,11 +206,11 @@ cc.BuilderAnimationManager = cc.Class.extend({
props.setObject(value, propName);
},
- moveAnimationsFromNode:function(fromNode,toNode){
+ moveAnimationsFromNode: function (fromNode, toNode) {
// Move base values
var locBaseValues = this._baseValues;
var baseValue = locBaseValues.objectForKey(fromNode);
- if(baseValue !== null) {
+ if (baseValue !== null) {
locBaseValues.setObject(baseValue, toNode);
locBaseValues.removeObjectForKey(fromNode);
}
@@ -213,13 +218,13 @@ cc.BuilderAnimationManager = cc.Class.extend({
// Move seqs
var locNodeSequences = this._nodeSequences;
var seqs = locNodeSequences.objectForKey(fromNode);
- if(seqs != null) {
+ if (seqs != null) {
locNodeSequences.setObject(seqs, toNode);
locNodeSequences.removeObjectForKey(fromNode);
}
},
- getActionForCallbackChannel:function(channel) {
+ getActionForCallbackChannel: function (channel) {
var lastKeyframeTime = 0;
var actions = [];
@@ -230,7 +235,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
var keyframe = keyframes[i];
var timeSinceLastKeyframe = keyframe.getTime() - lastKeyframeTime;
lastKeyframeTime = keyframe.getTime();
- if(timeSinceLastKeyframe > 0) {
+ if (timeSinceLastKeyframe > 0) {
actions.push(cc.delayTime(timeSinceLastKeyframe));
}
@@ -238,41 +243,41 @@ cc.BuilderAnimationManager = cc.Class.extend({
var selectorName = keyVal[0];
var selectorTarget = keyVal[1];
- if(this._jsControlled) {
+ if (this._jsControlled) {
var callbackName = selectorTarget + ":" + selectorName; //add number to the stream
var callback = this._keyframeCallFuncs[callbackName];
- if(callback != null)
+ if (callback != null)
actions.push(callback);
} else {
var target;
- if(selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT)
+ if (selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT)
target = this._rootNode;
else if (selectorTarget === CCB_TARGETTYPE_OWNER)
target = this._owner;
- if(target != null) {
- if(selectorName.length > 0) {
+ if (target != null) {
+ if (selectorName.length > 0) {
var selCallFunc = 0;
- if(target.onResolveCCBCCCallFuncSelector != null)
+ if (target.onResolveCCBCCCallFuncSelector != null)
selCallFunc = target.onResolveCCBCCCallFuncSelector(target, selectorName);
- if(selCallFunc === 0)
+ if (selCallFunc === 0)
cc.log("Skipping selector '" + selectorName + "' since no CCBSelectorResolver is present.");
else
- actions.push(cc.callFunc(selCallFunc,target));
+ actions.push(cc.callFunc(selCallFunc, target));
} else {
cc.log("Unexpected empty selector.");
}
}
}
}
- if(actions.length < 1)
+ if (actions.length < 1)
return null;
return cc.sequence(actions);
},
- getActionForSoundChannel:function(channel) {
+ getActionForSoundChannel: function (channel) {
var lastKeyframeTime = 0;
var actions = [];
@@ -283,7 +288,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
var keyframe = keyframes[i];
var timeSinceLastKeyframe = keyframe.getTime() - lastKeyframeTime;
lastKeyframeTime = keyframe.getTime();
- if(timeSinceLastKeyframe > 0) {
+ if (timeSinceLastKeyframe > 0) {
actions.push(cc.delayTime(timeSinceLastKeyframe));
}
@@ -293,29 +298,29 @@ cc.BuilderAnimationManager = cc.Class.extend({
actions.push(cc.BuilderSoundEffect.create(soundFile, pitch, pan, gain));
}
- if(actions.length < 1)
+ if (actions.length < 1)
return null;
return cc.sequence(actions);
},
- runAnimationsForSequenceNamed:function(name){
+ runAnimationsForSequenceNamed: function (name) {
this.runAnimationsForSequenceIdTweenDuration(this._getSequenceId(name), 0);
},
- runAnimationsForSequenceNamedTweenDuration:function(name, tweenDuration){
- this.runAnimationsForSequenceIdTweenDuration(this._getSequenceId(name), tweenDuration);
+ runAnimationsForSequenceNamedTweenDuration: function (name, tweenDuration) {
+ this.runAnimationsForSequenceIdTweenDuration(this._getSequenceId(name), tweenDuration);
},
- runAnimationsForSequenceIdTweenDuration:function(nSeqId, tweenDuration){
- if(nSeqId === -1)
+ runAnimationsForSequenceIdTweenDuration: function (nSeqId, tweenDuration) {
+ if (nSeqId === -1)
throw new Error("cc.BuilderAnimationManager.runAnimationsForSequenceIdTweenDuration(): Sequence id should not be -1");
tweenDuration = tweenDuration || 0;
this._rootNode.stopAllActions();
var allKeys = this._nodeSequences.allKeys();
- for(var i = 0,len = allKeys.length ; i< len;i++){
+ for (var i = 0, len = allKeys.length; i < len; i++) {
var node = allKeys[i];
node.stopAllActions();
@@ -323,27 +328,27 @@ cc.BuilderAnimationManager = cc.Class.extend({
var seqNodeProps = seqs.objectForKey(nSeqId);
var j;
var seqNodePropNames = [];
- if(seqNodeProps){
+ if (seqNodeProps) {
var propKeys = seqNodeProps.allKeys();
- for(j = 0; j < propKeys.length; j++){
+ for (j = 0; j < propKeys.length; j++) {
var propName = propKeys[j];
var seqProp = seqNodeProps.objectForKey(propName);
seqNodePropNames.push(propName);
- this._setFirstFrame(node, seqProp,tweenDuration);
- this._runAction(node,seqProp,tweenDuration);
+ this._setFirstFrame(node, seqProp, tweenDuration);
+ this._runAction(node, seqProp, tweenDuration);
}
}
var nodeBaseValues = this._baseValues.objectForKey(node);
- if(nodeBaseValues){
+ if (nodeBaseValues) {
var baseKeys = nodeBaseValues.allKeys();
- for(j = 0; j < baseKeys.length;j++){
- var selBaseKey = baseKeys[j];
- if(seqNodePropNames.indexOf(selBaseKey) === -1){
+ for (j = 0; j < baseKeys.length; j++) {
+ var selBaseKey = baseKeys[j];
+ if (seqNodePropNames.indexOf(selBaseKey) === -1) {
var value = nodeBaseValues.objectForKey(selBaseKey);
- if(value != null)
- this._setAnimatedProperty(selBaseKey,node, value, tweenDuration);
+ if (value != null)
+ this._setAnimatedProperty(selBaseKey, node, value, tweenDuration);
}
}
}
@@ -352,7 +357,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
// Make callback at end of sequence
var seq = this._getSequence(nSeqId);
var completeAction = cc.sequence(cc.delayTime(seq.getDuration() + tweenDuration),
- cc.callFunc(this._sequenceCompleted,this));
+ cc.callFunc(this._sequenceCompleted, this));
this._rootNode.runAction(completeAction);
// Playback callbacks and sounds
@@ -376,10 +381,10 @@ cc.BuilderAnimationManager = cc.Class.extend({
this._runningSequence = this._getSequence(nSeqId);
},
- runAnimations:function (name, tweenDuration) {
+ runAnimations: function (name, tweenDuration) {
tweenDuration = tweenDuration || 0;
var nSeqId;
- if(cc.isString(name))
+ if (cc.isString(name))
nSeqId = this._getSequenceId(name);
else
nSeqId = name;
@@ -387,29 +392,29 @@ cc.BuilderAnimationManager = cc.Class.extend({
this.runAnimationsForSequenceIdTweenDuration(nSeqId, tweenDuration);
},
- setAnimationCompletedCallback:function(target,callbackFunc){
+ setAnimationCompletedCallback: function (target, callbackFunc) {
this._target = target;
this._animationCompleteCallbackFunc = callbackFunc;
},
- setCompletedAnimationCallback:function(target,callbackFunc){
- this.setAnimationCompletedCallback(target,callbackFunc);
+ setCompletedAnimationCallback: function (target, callbackFunc) {
+ this.setAnimationCompletedCallback(target, callbackFunc);
},
- setCallFunc:function(callFunc, callbackNamed) {
+ setCallFunc: function (callFunc, callbackNamed) {
this._keyframeCallFuncs[callbackNamed] = callFunc;
},
- debug:function () {
+ debug: function () {
},
- _getBaseValue:function (node, propName) {
+ _getBaseValue: function (node, propName) {
var props = this._baseValues.objectForKey(node);
if (props)
return props.objectForKey(propName);
return null;
},
- _getSequenceId:function (sequenceName) {
+ _getSequenceId: function (sequenceName) {
var element = null;
var locSequences = this._sequences;
for (var i = 0, len = locSequences.length; i < len; i++) {
@@ -420,7 +425,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
return -1;
},
- _getSequence:function (sequenceId) {
+ _getSequence: function (sequenceId) {
var element = null;
var locSequences = this._sequences;
for (var i = 0, len = locSequences.length; i < len; i++) {
@@ -431,9 +436,9 @@ cc.BuilderAnimationManager = cc.Class.extend({
return null;
},
- _getAction:function (keyframe0, keyframe1, propName, node) {
+ _getAction: function (keyframe0, keyframe1, propName, node) {
var duration = keyframe1.getTime() - (keyframe0 ? keyframe0.getTime() : 0);
- var getArr,type,getValueArr, x, y;
+ var getArr, type, getValueArr, x, y;
if (propName === "rotation") {
return cc.BuilderRotateTo.create(duration, keyframe1.getValue());
@@ -444,7 +449,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
} else if (propName === "opacity") {
return cc.fadeTo(duration, keyframe1.getValue());
} else if (propName === "color") {
- var selColor = keyframe1.getValue().getColor();
+ var selColor = keyframe1.getValue();
return cc.tintTo(duration, selColor.r, selColor.g, selColor.b);
} else if (propName === "visible") {
var isVisible = keyframe1.getValue();
@@ -455,8 +460,8 @@ cc.BuilderAnimationManager = cc.Class.extend({
}
} else if (propName === "displayFrame") {
return cc.sequence(cc.delayTime(duration), cc.BuilderSetSpriteFrame.create(keyframe1.getValue()));
- } else if(propName === "position"){
- getArr = this._getBaseValue(node,propName);
+ } else if (propName === "position") {
+ getArr = this._getBaseValue(node, propName);
type = getArr[2];
//get relative position
@@ -466,11 +471,11 @@ cc.BuilderAnimationManager = cc.Class.extend({
var containerSize = this.getContainerSize(node.getParent());
- var absPos = cc._getAbsolutePosition(x,y, type,containerSize,propName);
+ var absPos = cc.getAbsolutePosition(x, y, type, containerSize, propName);
- return cc.moveTo(duration,absPos);
- } else if( propName === "scale"){
- getArr = this._getBaseValue(node,propName);
+ return cc.moveTo(duration, absPos);
+ } else if (propName === "scale") {
+ getArr = this._getBaseValue(node, propName);
type = getArr[2];
//get relative position
@@ -478,28 +483,28 @@ cc.BuilderAnimationManager = cc.Class.extend({
x = getValueArr[0];
y = getValueArr[1];
- if(type === CCB_SCALETYPE_MULTIPLY_RESOLUTION){
+ if (type === CCB_SCALETYPE_MULTIPLY_RESOLUTION) {
//TODO need to test
var resolutionScale = cc.BuilderReader.getResolutionScale();
x *= resolutionScale;
y *= resolutionScale;
}
- return cc.scaleTo(duration,x,y);
- } else if( propName === "skew") {
+ return cc.scaleTo(duration, x, y);
+ } else if (propName === "skew") {
//get relative position
getValueArr = keyframe1.getValue();
x = getValueArr[0];
y = getValueArr[1];
- return cc.skewTo(duration,x,y);
+ return cc.skewTo(duration, x, y);
} else {
cc.log("BuilderReader: Failed to create animation for property: " + propName);
}
return null;
},
- _setAnimatedProperty:function (propName, node, value, tweenDuration) {
- if(tweenDuration > 0){
+ _setAnimatedProperty: function (propName, node, value, tweenDuration) {
+ if (tweenDuration > 0) {
// Create a fake keyframe to generate the action from
var kf1 = new cc.BuilderKeyframe();
kf1.setValue(value);
@@ -511,64 +516,65 @@ cc.BuilderAnimationManager = cc.Class.extend({
node.runAction(tweenAction);
} else {
// Just set the value
- var getArr, nType, x,y;
- if(propName === "position"){
- getArr = this._getBaseValue(node,propName);
+ var getArr, nType, x, y;
+ if (propName === "position") {
+ getArr = this._getBaseValue(node, propName);
nType = getArr[2];
x = value[0];
y = value[1];
- node.setPosition(cc._getAbsolutePosition(x,y,nType, this.getContainerSize(node.getParent()),propName));
- }else if(propName === "scale"){
- getArr = this._getBaseValue(node,propName);
+ cc.getAbsolutePosition(x, y, nType, this.getContainerSize(node.getParent()), propName, _pos);
+ node._position.x = _pos.x;
+ node._position.y = _pos.y;
+ } else if (propName === "scale") {
+ getArr = this._getBaseValue(node, propName);
nType = getArr[2];
x = value[0];
y = value[1];
- cc.setRelativeScale(node,x,y,nType,propName);
- } else if( propName === "skew") {
+ cc.setRelativeScale(node, x, y, nType, propName);
+ } else if (propName === "skew") {
x = value[0];
y = value[1];
- node.setSkewX(x);
- node.setSkewY(y);
- }else {
+ node._skewX = x;
+ node._skewY = y;
+ } else {
// [node setValue:value forKey:name];
// TODO only handle rotation, opacity, displayFrame, color
- if(propName === "rotation"){
+ if (propName === "rotation") {
node.setRotation(value);
- } else if(propName === "rotationX")
- {
- node.setRotationSkewX(value);
- }else if(propName === "rotationY")
- {
- node.setRotationSkewY(value);
- }else if(propName === "opacity"){
- node.setOpacity(value);
- } else if(propName === "displayFrame"){
+ } else if (propName === "rotationX") {
+ node._rotationX = value;
+ } else if (propName === "rotationY") {
+ node._rotationY = value;
+ } else if (propName === "opacity") {
+ node._realOpacity = value;
+ } else if (propName === "displayFrame") {
node.setSpriteFrame(value);
- } else if(propName === "color"){
- var ccColor3B = value.getColor();
- if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){
- node.setColor(ccColor3B);
+ } else if (propName === "color") {
+ if (value.r !== 255 || value.g !== 255 || value.b !== 255) {
+ node.setColor(value);
}
- } else if( propName === "visible"){
+ } else if (propName === "visible") {
value = value || false;
node.setVisible(value);
} else {
- cc.log("unsupported property name is "+ propName);
+ cc.log("unsupported property name is " + propName);
+ return;
}
}
+ node.setNodeDirty();
}
},
- _setFirstFrame:function (node, seqProp, tweenDuration) {
+ _setFirstFrame: function (node, seqProp, tweenDuration) {
var keyframes = seqProp.getKeyframes();
if (keyframes.length === 0) {
// Use base value (no animation)
var baseValue = this._getBaseValue(node, seqProp.getName());
- if(!baseValue)
+ if (!baseValue)
cc.log("cc.BuilderAnimationManager._setFirstFrame(): No baseValue found for property");
this._setAnimatedProperty(seqProp.getName(), node, baseValue, tweenDuration);
} else {
@@ -578,8 +584,8 @@ cc.BuilderAnimationManager = cc.Class.extend({
}
},
- _getEaseAction:function (action, easingType, easingOpt) {
- if (easingType === CCB_KEYFRAME_EASING_LINEAR || easingType === CCB_KEYFRAME_EASING_INSTANT ) {
+ _getEaseAction: function (action, easingType, easingOpt) {
+ if (easingType === CCB_KEYFRAME_EASING_LINEAR || easingType === CCB_KEYFRAME_EASING_INSTANT) {
return action;
} else if (easingType === CCB_KEYFRAME_EASING_CUBIC_IN) {
return action.easing(cc.easeIn(easingOpt));
@@ -611,7 +617,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
}
},
- _runAction:function (node, seqProp, tweenDuration) {
+ _runAction: function (node, seqProp, tweenDuration) {
var keyframes = seqProp.getKeyframes();
var numKeyframes = keyframes.length;
@@ -628,7 +634,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
for (var i = 0; i < numKeyframes - 1; ++i) {
var kf0 = keyframes[i];
- var kf1 = keyframes[(i+1)];
+ var kf1 = keyframes[(i + 1)];
var action = this._getAction(kf0, kf1, seqProp.getName(), node);
if (action) {
@@ -642,12 +648,12 @@ cc.BuilderAnimationManager = cc.Class.extend({
}
},
- _sequenceCompleted:function () {
+ _sequenceCompleted: function () {
var locRunningSequence = this._runningSequence;
var locRunningName = locRunningSequence.getName();
- if(this._lastCompletedSequenceName != locRunningSequence.getName()){
+ if (this._lastCompletedSequenceName != locRunningSequence.getName()) {
this._lastCompletedSequenceName = locRunningSequence.getName();
}
@@ -660,7 +666,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
if (this._delegate)
this._delegate.completedAnimationSequenceNamed(locRunningName);
- if(this._target && this._animationCompleteCallbackFunc){
+ if (this._target && this._animationCompleteCallbackFunc) {
this._animationCompleteCallbackFunc.call(this._target);
}
}
@@ -668,13 +674,13 @@ cc.BuilderAnimationManager = cc.Class.extend({
cc.BuilderSetSpriteFrame = cc.ActionInstant.extend({
- _spriteFrame:null,
+ _spriteFrame: null,
- initWithSpriteFrame:function (spriteFrame) {
+ initWithSpriteFrame: function (spriteFrame) {
this._spriteFrame = spriteFrame;
return true;
},
- update:function (time) {
+ update: function (time) {
this.target.setSpriteFrame(this._spriteFrame);
}
});
@@ -692,11 +698,11 @@ cc.BuilderSetSpriteFrame.create = function (spriteFrame) {
// cc.BuilderRotateTo
//
cc.BuilderRotateTo = cc.ActionInterval.extend({
- _startAngle:0,
- _dstAngle:0,
- _diffAngle:0,
+ _startAngle: 0,
+ _dstAngle: 0,
+ _diffAngle: 0,
- initWithDuration:function (duration, angle) {
+ initWithDuration: function (duration, angle) {
if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
this._dstAngle = angle;
return true;
@@ -704,11 +710,11 @@ cc.BuilderRotateTo = cc.ActionInterval.extend({
return false;
}
},
- update:function (time) {
+ update: function (time) {
this.target.setRotation(this._startAngle + (this._diffAngle * time));
},
- startWithTarget:function (node) {
+ startWithTarget: function (node) {
cc.ActionInterval.prototype.startWithTarget.call(this, node);
this._startAngle = this.target.getRotation();
this._diffAngle = this._dstAngle - this._startAngle;
@@ -750,19 +756,19 @@ cc.BuilderRotateYTo.create = function (duration, angle) {
// cc.BuilderSoundEffect
//
cc.BuilderSoundEffect = cc.ActionInstant.extend({
- init:function(file) {
+ init: function (file) {
this._file = file;
return true;
},
- update:function(dt) {
+ update: function (dt) {
cc.audioEngine.playEffect(this._file);
}
});
cc.BuilderSoundEffect.create = function (file, pitch, pan, gain) {
var ret = new cc.BuilderSoundEffect();
if (ret && ret.init(file)) {
- return ret;
+ return ret;
}
return null;
};
-
+})();
diff --git a/extensions/ccb-reader/CCBReader.js b/extensions/ccb-reader/CCBReader.js
index d613575d0d..0baa27b4ca 100644
--- a/extensions/ccb-reader/CCBReader.js
+++ b/extensions/ccb-reader/CCBReader.js
@@ -102,58 +102,43 @@ var CCB_SIZETYPE_MULTIPLY_RESOLUTION = 5;
var CCB_SCALETYPE_ABSOLUTE = 0;
var CCB_SCALETYPE_MULTIPLY_RESOLUTION = 1;
-cc.BuilderFile = cc.Node.extend({
- _ccbFileNode:null,
-
- getCCBFileNode:function () {
- return this._ccbFileNode;
- },
- setCCBFileNode:function (node) {
- this._ccbFileNode = node;
- }
-});
-
-cc.BuilderFile.create = function () {
- return new cc.BuilderFile();
-};
-
/**
* Parse CCBI file which is generated by CocosBuilder
*/
cc.BuilderReader = cc.Class.extend({
- _jsControlled:false,
- _data:null,
- _ccbRootPath:"",
+ _jsControlled: false,
+ _data: null,
+ _ccbRootPath: "",
- _bytes:0,
- _currentByte:0,
- _currentBit:0,
+ _bytes: 0,
+ _currentByte: 0,
+ _currentBit: 0,
- _stringCache:null,
- _loadedSpriteSheets:null,
+ _stringCache: null,
+ _loadedSpriteSheets: null,
- _owner:null,
- _animationManager:null,
- _animationManagers:null,
- _animatedProps:null,
+ _owner: null,
+ _animationManager: null,
+ _animationManagers: null,
+ _animatedProps: null,
- _ccNodeLoaderLibrary:null,
- _ccNodeLoaderListener:null,
- _ccbMemberVariableAssigner:null,
- _ccbSelectorResolver:null,
+ _ccNodeLoaderLibrary: null,
+ _ccNodeLoaderListener: null,
+ _ccbMemberVariableAssigner: null,
+ _ccbSelectorResolver: null,
- _ownerOutletNames:null,
- _ownerOutletNodes:null,
- _nodesWithAnimationManagers:null,
- _animationManagerForNodes:null,
+ _ownerOutletNames: null,
+ _ownerOutletNodes: null,
+ _nodesWithAnimationManagers: null,
+ _animationManagerForNodes: null,
- _ownerCallbackNames:null,
- _ownerCallbackNodes:null,
- _ownerCallbackEvents:null,
+ _ownerCallbackNames: null,
+ _ownerCallbackNodes: null,
+ _ownerCallbackEvents: null,
- _readNodeGraphFromData:false,
+ _readNodeGraphFromData: false,
- ctor:function (ccNodeLoaderLibrary, ccbMemberVariableAssigner, ccbSelectorResolver, ccNodeLoaderListener) {
+ ctor: function (ccNodeLoaderLibrary, ccbMemberVariableAssigner, ccbSelectorResolver, ccNodeLoaderListener) {
this._stringCache = [];
this._loadedSpriteSheets = [];
this._currentBit = -1;
@@ -186,15 +171,15 @@ cc.BuilderReader = cc.Class.extend({
}
},
- getCCBRootPath:function () {
+ getCCBRootPath: function () {
return this._ccbRootPath;
},
- setCCBRootPath:function (rootPath) {
+ setCCBRootPath: function (rootPath) {
this._ccbRootPath = rootPath;
},
- initWithData:function (data, owner) {
+ initWithData: function (data, owner) {
//setup action manager
this._animationManager = new cc.BuilderAnimationManager();
@@ -213,7 +198,7 @@ cc.BuilderReader = cc.Class.extend({
return true;
},
- _loadBinarySync : function(url){
+ _loadBinarySync: function (url) {
var self = this;
var req = this.getXMLHttpRequest();
var errInfo = "load " + url + " failed!";
@@ -247,7 +232,7 @@ cc.BuilderReader = cc.Class.extend({
return arrayInfo;
},
- readNodeGraphFromFile:function (ccbFileName, owner, parentSize, animationManager) {
+ readNodeGraphFromFile: function (ccbFileName, owner, parentSize, animationManager) {
if (parentSize == null) {
parentSize = cc.director.getWinSize();
} else if (parentSize instanceof cc.BuilderAnimationManager) {
@@ -256,7 +241,7 @@ cc.BuilderReader = cc.Class.extend({
}
var data = cc.loader.getRes(ccbFileName);
- if(!data){
+ if (!data) {
var realUrl = cc.loader.getUrl(ccbFileName);
data = cc.loader.loadBinarySync(realUrl);
cc.loader.cache[ccbFileName] = data;
@@ -265,7 +250,7 @@ cc.BuilderReader = cc.Class.extend({
return this.readNodeGraphFromData(data, owner, parentSize, animationManager);
},
- readNodeGraphFromData:function (data, owner, parentSize) {
+ readNodeGraphFromData: function (data, owner, parentSize) {
this.initWithData(data, owner);
var locAnimationManager = this._animationManager;
locAnimationManager.setRootContainerSize(parentSize);
@@ -303,50 +288,68 @@ cc.BuilderReader = cc.Class.extend({
return nodeGraph;
},
- createSceneWithNodeGraphFromFile:function (ccbFileName, owner, parentSize, animationManager) {
+ createSceneWithNodeGraphFromFile: function (ccbFileName, owner, parentSize, animationManager) {
var node = this.readNodeGraphFromFile(ccbFileName, owner, parentSize, animationManager);
var scene = new cc.Scene();
scene.addChild(node);
return scene;
},
- getCCBMemberVariableAssigner:function () {
+ getCCBMemberVariableAssigner: function () {
return this._ccbMemberVariableAssigner;
},
- getCCBSelectorResolver:function () {
+ getCCBSelectorResolver: function () {
return this._ccbSelectorResolver;
},
- getAnimationManager:function () {
+ getAnimationManager: function () {
return this._animationManager;
},
- setAnimationManager:function (animationManager) {
+ setAnimationManager: function (animationManager) {
this._animationManager = animationManager;
},
- getAnimatedProperties:function () {
+ getAnimatedProperties: function () {
return this._animatedProps;
},
- getLoadedSpriteSheet:function () {
+ getLoadedSpriteSheet: function () {
return this._loadedSpriteSheets;
},
- getOwner:function () {
+ getOwner: function () {
return this._owner;
},
- readInt:function (signed) {
+ readInt: function (signed) {
var numBits = 0;
- while (!this._getBit()) {
+ var data = this._data[this._currentByte];
+ var bit = !!(data & (1 << this._currentBit++));
+ while (!bit) {
numBits++;
+ bit = !!(data & (1 << this._currentBit++));
+ if (this._currentBit >= 8) {
+ this._currentBit = 0;
+ this._currentByte++;
+ data = this._data[this._currentByte];
+ if (this._currentByte > this._data.length)
+ throw new Error("out of the data bound");
+ }
}
var current = 0;
for (var a = numBits - 1; a >= 0; a--) {
- if (this._getBit()) {
+ bit = !!(data & (1 << this._currentBit++));
+ if (this._currentBit >= 8) {
+ this._currentBit = 0;
+ this._currentByte++;
+ data = this._data[this._currentByte];
+ if (this._currentByte > this._data.length)
+ throw new Error("out of the data bound");
+ }
+ if (bit) {
current |= 1 << a;
}
}
@@ -364,23 +367,26 @@ cc.BuilderReader = cc.Class.extend({
num = current - 1;
}
- this._alignBits();
+ if (this._currentBit) {
+ this._currentBit = 0;
+ this._currentByte++;
+ }
return num;
},
- readByte:function () {
+ readByte: function () {
var byteValue = this._data[this._currentByte];
this._currentByte++;
return byteValue;
},
- readBool:function () {
- return (0 !== this.readByte());
+ readBool: function () {
+ return !!this._data[this._currentByte++];
},
- readFloat:function () {
- var type = this.readByte();
+ readFloat: function () {
+ var type = this._data[this._currentByte++];
switch (type) {
case CCB_FLOAT0:
@@ -403,10 +409,12 @@ cc.BuilderReader = cc.Class.extend({
}
},
- _decodeFloat:function (precisionBits, exponentBits) {
+ _decodeFloat: function (precisionBits, exponentBits) {
var length = precisionBits + exponentBits + 1;
var size = length >> 3;
- this._checkSize(length);
+ if (this._currentByte + size >= this._data.length) {
+ throw new Error("Index out of bound");
+ }
var bias = Math.pow(2, exponentBits - 1) - 1;
var signal = this._readBitsOnly(precisionBits + exponentBits, 1, size);
@@ -415,7 +423,7 @@ cc.BuilderReader = cc.Class.extend({
var divisor = 2;
var curByte = 0; //length + (-precisionBits >> 3) - 1;
do {
- var byteValue = this._readByteOnly(++curByte, size);
+ var byteValue = this._data[this._currentByte + size - (++curByte) - 1];
var startBit = precisionBits % 8 || 8;
var mask = 1 << startBit;
while (mask >>= 1) {
@@ -433,110 +441,102 @@ cc.BuilderReader = cc.Class.extend({
: Math.pow(2, exponent - bias) * (1 + significand) : 0);
},
- _readBitsOnly:function (start, length, size) {
+ _readBitsOnly: function (start, length, size) {
var offsetLeft = (start + length) % 8;
var offsetRight = start % 8;
var curByte = size - (start >> 3) - 1;
var lastByte = size + (-(start + length) >> 3);
var diff = curByte - lastByte;
- var sum = (this._readByteOnly(curByte, size) >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1);
+ var sum = (this._data[this._currentByte + size - curByte - 1] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1);
if (diff && offsetLeft) {
- sum += (this._readByteOnly(lastByte++, size) & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight;
+ sum += (this._data[this._currentByte + size - lastByte - 1] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight;
+ lastByte++;
}
while (diff) {
- sum += this._shl(this._readByteOnly(lastByte++, size), (diff-- << 3) - offsetRight);
+ sum += this._shl(this._data[this._currentByte + size - lastByte - 1], (diff-- << 3) - offsetRight);
+ lastByte++;
}
return sum;
},
- _readByteOnly:function (i, size) {
- return this._data[this._currentByte + size - i - 1];
- },
-
- _shl:function (a, b) {
+ _shl: function (a, b) {
for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) === 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1);
return a;
},
- _checkSize:function (neededBits) {
- if (!(this._currentByte + Math.ceil(neededBits / 8) < this._data.length)) {
- throw new Error("Index out of bound");
- }
- },
-
- readCachedString:function () {
+ readCachedString: function () {
return this._stringCache[this.readInt(false)];
},
- isJSControlled:function () {
+ isJSControlled: function () {
return this._jsControlled;
},
- getOwnerCallbackNames:function () {
+ getOwnerCallbackNames: function () {
return this._ownerCallbackNames;
},
- getOwnerCallbackNodes:function () {
+ getOwnerCallbackNodes: function () {
return this._ownerCallbackNodes;
},
- getOwnerCallbackControlEvents:function(){
+ getOwnerCallbackControlEvents: function () {
return this._ownerCallbackEvents;
},
- getOwnerOutletNames:function () {
+ getOwnerOutletNames: function () {
return this._ownerOutletNames;
},
- getOwnerOutletNodes:function () {
+ getOwnerOutletNodes: function () {
return this._ownerOutletNodes;
},
- getNodesWithAnimationManagers:function () {
+ getNodesWithAnimationManagers: function () {
return this._nodesWithAnimationManagers;
},
- getAnimationManagersForNodes:function () {
+ getAnimationManagersForNodes: function () {
return this._animationManagerForNodes;
},
- getAnimationManagers:function () {
+ getAnimationManagers: function () {
return this._animationManagers;
},
- setAnimationManagers:function (animationManagers) {
+ setAnimationManagers: function (animationManagers) {
this._animationManagers = animationManagers;
},
- addOwnerCallbackName:function (name) {
- this._ownerCallbackNames.push(name)
+ addOwnerCallbackName: function (name) {
+ this._ownerCallbackNames.push(name);
},
- addOwnerCallbackNode:function (node) {
+ addOwnerCallbackNode: function (node) {
this._ownerCallbackNodes.push(node);
},
- addOwnerCallbackControlEvents:function(event){
+ addOwnerCallbackControlEvents: function (event) {
this._ownerCallbackEvents.push(event);
},
- addDocumentCallbackName:function (name) {
+ addDocumentCallbackName: function (name) {
this._animationManager.addDocumentCallbackName(name);
},
- addDocumentCallbackNode:function (node) {
+ addDocumentCallbackNode: function (node) {
this._animationManager.addDocumentCallbackNode(node);
},
- addDocumentCallbackControlEvents:function(controlEvents){
+ addDocumentCallbackControlEvents: function (controlEvents) {
this._animationManager.addDocumentCallbackControlEvents(controlEvents);
},
- readFileWithCleanUp:function (cleanUp) {
+ readFileWithCleanUp: function (cleanUp) {
if (!this._readHeader())
return null;
if (!this._readStringCache())
@@ -552,18 +552,18 @@ cc.BuilderReader = cc.Class.extend({
return node;
},
- addOwnerOutletName: function(name){
- this._ownerOutletNames.push(name);
+ addOwnerOutletName: function (name) {
+ this._ownerOutletNames.push(name);
},
- addOwnerOutletNode: function(node){
- if(node == null)
+ addOwnerOutletNode: function (node) {
+ if (node == null)
return;
this._ownerOutletNodes.push(node);
},
- _cleanUpNodeGraph:function (node) {
+ _cleanUpNodeGraph: function (node) {
node.userObject = null;
var getChildren = node.getChildren();
for (var i = 0, len = getChildren.length; i < len; i++) {
@@ -571,7 +571,7 @@ cc.BuilderReader = cc.Class.extend({
}
},
- _readCallbackKeyframesForSeq:function(seq) {
+ _readCallbackKeyframesForSeq: function (seq) {
var numKeyframes = this.readInt(false);
if (!numKeyframes)
@@ -584,14 +584,14 @@ cc.BuilderReader = cc.Class.extend({
var callbackName = this.readCachedString();
var callbackType = this.readInt(false);
- var value = [ callbackName, callbackType];
+ var value = [callbackName, callbackType];
var keyframe = new cc.BuilderKeyframe();
keyframe.setTime(time);
keyframe.setValue(value);
- if(locJsControlled)
- locAnimationManager.getKeyframeCallbacks().push(callbackType+":"+callbackName);
+ if (locJsControlled)
+ locAnimationManager.getKeyframeCallbacks().push(callbackType + ":" + callbackName);
locKeyframes.push(keyframe);
}
@@ -602,7 +602,7 @@ cc.BuilderReader = cc.Class.extend({
return true;
},
- _readSoundKeyframesForSeq:function(seq) {
+ _readSoundKeyframesForSeq: function (seq) {
var numKeyframes = this.readInt(false);
if (!numKeyframes)
@@ -617,7 +617,7 @@ cc.BuilderReader = cc.Class.extend({
var pan = this.readFloat();
var gain = this.readFloat();
- var value = [soundFile, pitch, pan, gain];
+ var value = [soundFile, pitch, pan, gain];
var keyframe = new cc.BuilderKeyframe();
keyframe.setTime(time);
keyframe.setValue(value);
@@ -629,7 +629,7 @@ cc.BuilderReader = cc.Class.extend({
seq.setSoundChannel(channel);
return true;
},
- _readSequences:function () {
+ _readSequences: function () {
var sequences = this._animationManager.getSequences();
var numSeqs = this.readInt(false);
for (var i = 0; i < numSeqs; i++) {
@@ -650,7 +650,7 @@ cc.BuilderReader = cc.Class.extend({
return true;
},
- readKeyframe:function (type) {
+ readKeyframe: function (type) {
var keyframe = new cc.BuilderKeyframe();
keyframe.setTime(this.readFloat());
var easingType = this.readInt(false);
@@ -670,12 +670,11 @@ cc.BuilderReader = cc.Class.extend({
keyframe.setEasingOpt(easingOpt);
if (type === CCB_PROPTYPE_CHECK) {
- value = this.readBool();
+ value = !!this._data[this._currentByte++];
} else if (type === CCB_PROPTYPE_BYTE) {
- value = this.readByte();
+ value = this._data[this._currentByte++];
} else if (type === CCB_PROPTYPE_COLOR3) {
- var c = cc.color(this.readByte(), this.readByte(), this.readByte());
- value = cc.Color3BWapper.create(c);
+ value = cc.color(this._data[this._currentByte++], this._data[this._currentByte++], this._data[this._currentByte++]);
} else if (type === CCB_PROPTYPE_FLOATXY) {
value = [this.readFloat(), this.readFloat()];
} else if (type === CCB_PROPTYPE_DEGREES) {
@@ -707,7 +706,7 @@ cc.BuilderReader = cc.Class.extend({
return keyframe;
},
- _readHeader:function () {
+ _readHeader: function () {
/* If no bytes loaded, don't crash about it. */
if (!this._data)
return false;
@@ -727,36 +726,36 @@ cc.BuilderReader = cc.Class.extend({
return false;
}
- this._jsControlled = this.readBool();
+ this._jsControlled = !!this._data[this._currentByte++];
this._animationManager._jsControlled = this._jsControlled;
// no need to set if it is "jscontrolled". It is obvious.
return true;
},
- _readStringFromBytes:function (startIndex, strLen, reverse) {
+ _readStringFromBytes: function (startIndex, strLen, reverse) {
reverse = reverse || false;
var strValue = "";
- var i, locData = this._data, locCurrentByte = this._currentByte;
+ var i, locData = this._data;
if (reverse) {
for (i = strLen - 1; i >= 0; i--)
- strValue += String.fromCharCode(locData[locCurrentByte + i]);
+ strValue += String.fromCharCode(locData[startIndex + i]);
} else {
for (i = 0; i < strLen; i++)
- strValue += String.fromCharCode(locData[locCurrentByte + i]);
+ strValue += String.fromCharCode(locData[startIndex + i]);
}
return strValue;
},
- _readStringCache:function () {
+ _readStringCache: function () {
var numStrings = this.readInt(false);
for (var i = 0; i < numStrings; i++)
this._readStringCacheEntry();
return true;
},
- _readStringCacheEntry:function () {
- var b0 = this.readByte();
- var b1 = this.readByte();
+ _readStringCacheEntry: function () {
+ var b0 = this._data[this._currentByte++];
+ var b1 = this._data[this._currentByte++];
var numBytes = b0 << 8 | b1;
@@ -772,7 +771,7 @@ cc.BuilderReader = cc.Class.extend({
this._stringCache.push(str);
},
- _readNodeGraph:function (parent) {
+ _readNodeGraph: function (parent) {
/* Read class name. */
var className = this.readCachedString();
@@ -838,9 +837,9 @@ cc.BuilderReader = cc.Class.extend({
ccNodeLoader.parseProperties(node, parent, this);
//handle sub ccb files(remove middle node)
- var isCCBFileNode = node instanceof cc.BuilderFile;
+ var isCCBFileNode = !!node.ccbFileNode;
if (isCCBFileNode) {
- var embeddedNode = node.getCCBFileNode();
+ var embeddedNode = node.ccbFileNode;
embeddedNode.setPosition(node.getPosition());
embeddedNode.setRotation(node.getRotation());
embeddedNode.setScaleX(node.getScaleX());
@@ -850,7 +849,7 @@ cc.BuilderReader = cc.Class.extend({
//embeddedNode.ignoreAnchorPointForPosition(node.isIgnoreAnchorPointForPosition());
locActionManager.moveAnimationsFromNode(node, embeddedNode);
- node.setCCBFileNode(null);
+ node.ccbFileNode = null;
node = embeddedNode;
}
var target = null, locMemberAssigner = null;
@@ -887,16 +886,16 @@ cc.BuilderReader = cc.Class.extend({
// Assign custom properties.
if (ccNodeLoader.getCustomProperties().length > 0) {
var customAssigned = false;
- if(!locJsControlled) {
+ if (!locJsControlled) {
target = node;
- if(target != null && target.onAssignCCBCustomProperty != null) {
+ if (target != null && target.onAssignCCBCustomProperty != null) {
var customProperties = ccNodeLoader.getCustomProperties();
var customPropKeys = customProperties.allKeys();
- for(i = 0;i < customPropKeys.length;i++){
+ for (i = 0; i < customPropKeys.length; i++) {
var customPropValue = customProperties.objectForKey(customPropKeys[i]);
customAssigned = target.onAssignCCBCustomProperty(target, customPropKeys[i], customPropValue);
locMemberAssigner = this._ccbMemberVariableAssigner;
- if(!customAssigned && (locMemberAssigner != null) && (locMemberAssigner.onAssignCCBCustomProperty != null))
+ if (!customAssigned && (locMemberAssigner != null) && (locMemberAssigner.onAssignCCBCustomProperty != null))
customAssigned = locMemberAssigner.onAssignCCBCustomProperty(target, customPropKeys[i], customPropValue);
}
}
@@ -926,32 +925,12 @@ cc.BuilderReader = cc.Class.extend({
return node;
},
- _getBit:function () {
- var bit = (this._data[this._currentByte] & (1 << this._currentBit)) !== 0;
- this._currentBit++;
-
- if (this._currentBit >= 8) {
- this._currentBit = 0;
- this._currentByte++;
- if(this._currentByte > this._data.length)
- throw new Error("out of the data bound");
- }
- return bit;
- },
-
- _alignBits:function () {
- if (this._currentBit) {
- this._currentBit = 0;
- this._currentByte++;
- }
- },
-
- _readUTF8:function () {
+ _readUTF8: function () {
}
});
cc.BuilderReader._ccbResolutionScale = 1;
-cc.BuilderReader.setResolutionScale = function(scale){
+cc.BuilderReader.setResolutionScale = function (scale) {
cc.BuilderReader._ccbResolutionScale = scale;
};
@@ -970,14 +949,14 @@ cc.BuilderReader.loadAsScene = function (ccbFilePath, owner, parentSize, ccbRoot
};
cc.BuilderReader._controllerClassCache = {};
-cc.BuilderReader.registerController = function(controllerName, controller){
+cc.BuilderReader.registerController = function (controllerName, controller) {
cc.BuilderReader._controllerClassCache[controllerName] = cc.Class.extend(controller);
};
cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) {
ccbRootPath = ccbRootPath || cc.BuilderReader.getResourcePath();
var reader = new cc.BuilderReader(cc.NodeLoaderLibrary.newDefaultCCNodeLoaderLibrary());
reader.setCCBRootPath(ccbRootPath);
- if((ccbFilePath.length < 5)||(ccbFilePath.toLowerCase().lastIndexOf(".ccbi") !== ccbFilePath.length - 5))
+ if ((ccbFilePath.length < 5) || (ccbFilePath.toLowerCase().lastIndexOf(".ccbi") !== ccbFilePath.length - 5))
ccbFilePath = ccbFilePath + ".ccbi";
var node = reader.readNodeGraphFromFile(ccbFilePath, owner, parentSize);
@@ -993,7 +972,7 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) {
callbackName = ownerCallbackNames[i];
callbackNode = ownerCallbackNodes[i];
callbackControlEvents = ownerCallbackControlEvents[i];
- if(callbackNode instanceof cc.ControlButton)
+ if (callbackNode instanceof cc.ControlButton)
callbackNode.addTargetWithActionForControlEvents(owner, owner[callbackName], callbackControlEvents); //register all type of events
else
callbackNode.setCallback(owner[callbackName], owner);
@@ -1011,7 +990,7 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) {
var nodesWithAnimationManagers = reader.getNodesWithAnimationManagers();
var animationManagersForNodes = reader.getAnimationManagersForNodes();
- if(!nodesWithAnimationManagers || !animationManagersForNodes)
+ if (!nodesWithAnimationManagers || !animationManagersForNodes)
return node;
var controllerClassCache = cc.BuilderReader._controllerClassCache;
@@ -1028,7 +1007,7 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) {
// Create a controller
var controllerClass = controllerClassCache[controllerName];
- if(!controllerClass) throw new Error("Can not find controller : " + controllerName);
+ if (!controllerClass) throw new Error("Can not find controller : " + controllerName);
var controller = new controllerClass();
controller.controllerName = controllerName;
@@ -1043,7 +1022,7 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) {
callbackName = documentCallbackNames[j];
callbackNode = documentCallbackNodes[j];
callbackControlEvents = documentCallbackControlEvents[j];
- if(callbackNode instanceof cc.ControlButton)
+ if (callbackNode instanceof cc.ControlButton)
callbackNode.addTargetWithActionForControlEvents(controller, controller[callbackName], callbackControlEvents); //register all type of events
else
callbackNode.setCallback(controller[callbackName], controller);
@@ -1069,7 +1048,7 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) {
var callbackType = callbackSplit[0];
var kfCallbackName = callbackSplit[1];
- if (callbackType == 1){ // Document callback
+ if (callbackType == 1) { // Document callback
animationManager.setCallFunc(cc.callFunc(controller[kfCallbackName], controller), keyframeCallbacks[j]);
} else if (callbackType == 2 && owner) {// Owner callback
animationManager.setCallFunc(cc.callFunc(owner[kfCallbackName], owner), keyframeCallbacks[j]);
@@ -1123,4 +1102,4 @@ cc.BuilderReader.concat = function (stringA, stringB) {
return stringA + stringB;
};
-cc.loader.register(["ccbi"], cc._binaryLoader);
\ No newline at end of file
+cc.loader.register(["ccbi"], cc._binaryLoader);
diff --git a/extensions/ccb-reader/CCBReaderUtil.js b/extensions/ccb-reader/CCBReaderUtil.js
index d3ebcfa821..0de9c4fa30 100644
--- a/extensions/ccb-reader/CCBReaderUtil.js
+++ b/extensions/ccb-reader/CCBReaderUtil.js
@@ -25,17 +25,22 @@
****************************************************************************/
cc.NodeLoaderListener = cc.Class.extend({
- onNodeLoaded:function(node,nodeLoader){}
+ onNodeLoaded: function (node, nodeLoader) {
+ }
});
cc.BuilderSelectorResolver = cc.Class.extend({
- onResolveCCBCCMenuItemSelector:function(target, selectorName){},
- onResolveCCBCCCallFuncSelector:function(target, selectorName){},
- onResolveCCBCCControlSelector:function(target,selectorName){}
+ onResolveCCBCCMenuItemSelector: function (target, selectorName) {
+ },
+ onResolveCCBCCCallFuncSelector: function (target, selectorName) {
+ },
+ onResolveCCBCCControlSelector: function (target, selectorName) {
+ }
});
cc.BuilderScriptOwnerProtocol = cc.Class.extend({
- createNew:function(){}
+ createNew: function () {
+ }
});
cc.BuilderMemberVariableAssigner = cc.Class.extend({
@@ -47,7 +52,9 @@ cc.BuilderMemberVariableAssigner = cc.Class.extend({
* @param {cc.Node} node The member variable.
* @return {Boolean} Whether the assignment was successful.
*/
- onAssignCCBMemberVariable:function(target,memberVariableName, node){ return false;},
+ onAssignCCBMemberVariable: function (target, memberVariableName, node) {
+ return false;
+ },
/**
* The callback function of assigning custom properties.
@@ -57,5 +64,7 @@ cc.BuilderMemberVariableAssigner = cc.Class.extend({
* @param {*} value The value of the property.
* @return {Boolean} Whether the assignment was successful.
*/
- onAssignCCBCustomProperty:function(target, memberVariableName, value){ return false; }
+ onAssignCCBCustomProperty: function (target, memberVariableName, value) {
+ return false;
+ }
});
diff --git a/extensions/ccb-reader/CCBRelativePositioning.js b/extensions/ccb-reader/CCBRelativePositioning.js
index 2b2df87bef..ed0d29a255 100644
--- a/extensions/ccb-reader/CCBRelativePositioning.js
+++ b/extensions/ccb-reader/CCBRelativePositioning.js
@@ -24,40 +24,15 @@
THE SOFTWARE.
****************************************************************************/
-cc.getAbsolutePosition = function(pt, type, containerSize, propName){
- var absPt = cc.p(0,0);
- if(type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_LEFT)
- absPt = pt;
- else if(type === CCB_POSITIONTYPE_RELATIVE_TOP_LEFT){
- absPt.x = pt.x;
- absPt.y = containerSize.height - pt.y;
- } else if(type === CCB_POSITIONTYPE_RELATIVE_TOP_RIGHT){
- absPt.x = containerSize.width - pt.x;
- absPt.y = containerSize.height - pt.y;
- } else if (type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_RIGHT) {
- absPt.x = containerSize.width - pt.x;
- absPt.y = pt.y;
- } else if (type === CCB_POSITIONTYPE_PERCENT) {
- absPt.x = (containerSize.width * pt.x / 100.0);
- absPt.y = (containerSize.height * pt.y / 100.0);
- } else if (type === CCB_POSITIONTYPE_MULTIPLY_RESOLUTION) {
- var resolutionScale = cc.BuilderReader.getResolutionScale();
- absPt.x = pt.x * resolutionScale;
- absPt.y = pt.y * resolutionScale;
- }
-
- return absPt;
-};
-
-cc._getAbsolutePosition = function(x, y, type, containerSize, propName){
- var absPt = cc.p(0,0);
- if(type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_LEFT){
+cc.getAbsolutePosition = function (x, y, type, containerSize, propName, out) {
+ var absPt = out || cc.p(0, 0);
+ if (type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_LEFT) {
absPt.x = x;
absPt.y = y;
- } else if(type === CCB_POSITIONTYPE_RELATIVE_TOP_LEFT){
+ } else if (type === CCB_POSITIONTYPE_RELATIVE_TOP_LEFT) {
absPt.x = x;
absPt.y = containerSize.height - y;
- } else if(type === CCB_POSITIONTYPE_RELATIVE_TOP_RIGHT){
+ } else if (type === CCB_POSITIONTYPE_RELATIVE_TOP_RIGHT) {
absPt.x = containerSize.width - x;
absPt.y = containerSize.height - y;
} else if (type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_RIGHT) {
@@ -74,8 +49,8 @@ cc._getAbsolutePosition = function(x, y, type, containerSize, propName){
return absPt;
};
-cc.setRelativeScale = function(node,scaleX, scaleY, type, propName){
- if(!node)
+cc.setRelativeScale = function (node, scaleX, scaleY, type, propName) {
+ if (!node)
throw new Error("cc.setRelativeScale(): node should be non-null");
if (type === CCB_POSITIONTYPE_MULTIPLY_RESOLUTION) {
@@ -85,6 +60,5 @@ cc.setRelativeScale = function(node,scaleX, scaleY, type, propName){
scaleY *= resolutionScale;
}
- node.setScaleX(scaleX);
- node.setScaleY(scaleY);
-};
\ No newline at end of file
+ node.setScale(scaleX, scaleY);
+};
diff --git a/extensions/ccb-reader/CCBValue.js b/extensions/ccb-reader/CCBValue.js
index 781c25d861..dee4c7ba71 100644
--- a/extensions/ccb-reader/CCBValue.js
+++ b/extensions/ccb-reader/CCBValue.js
@@ -34,43 +34,22 @@ cc.BOOL_VALUE = 3;
cc.UNSIGNEDCHAR_VALUE = 4;
-
-cc.Color3BWapper = cc.Class.extend({
- _color:null,
- ctor:function () {
- this._color = cc.color(0, 0, 0);
- },
- getColor:function () {
- return this._color;
- }
-});
-
-cc.Color3BWapper.create = function (color) {
- var ret = new cc.Color3BWapper();
- if (ret) {
- ret._color.r = color.r;
- ret._color.g = color.g;
- ret._color.b = color.b;
- }
- return ret;
-};
-
cc.BuilderValue = cc.Class.extend({
- _value:null,
- _type:0,
+ _value: null,
+ _type: 0,
- getIntValue:function () {
+ getIntValue: function () {
},
- getFloatValue:function () {
+ getFloatValue: function () {
},
- getBoolValue:function () {
+ getBoolValue: function () {
},
- getByteValue:function () {
+ getByteValue: function () {
},
- getPointer:function () {
+ getPointer: function () {
},
- getValue:function(){
+ getValue: function () {
return this._value;
}
});
diff --git a/extensions/ccb-reader/CCControlLoader.js b/extensions/ccb-reader/CCControlLoader.js
index 901f8509dd..3b1a5d6518 100644
--- a/extensions/ccb-reader/CCControlLoader.js
+++ b/extensions/ccb-reader/CCControlLoader.js
@@ -27,12 +27,14 @@
var PROPERTY_CCBFILE = "ccbFile";
cc.BuilderFileLoader = cc.NodeLoader.extend({
- _createCCNode:function (parent, ccbReader) {
- return cc.BuilderFile.create();
+ _createCCNode: function (parent, ccbReader) {
+ var node = new cc.Node();
+ node.ccbFileNode = null;
+ return node;
},
- onHandlePropTypeCCBFile:function (node, parent, propertyName, ccbFileNode, ccbReader) {
+ onHandlePropTypeCCBFile: function (node, parent, propertyName, ccbFileNode, ccbReader) {
if (propertyName === PROPERTY_CCBFILE) {
- node.setCCBFileNode(ccbFileNode);
+ node.ccbFileNode = ccbFileNode;
} else {
cc.NodeLoader.prototype.onHandlePropTypeCCBFile.call(this, node, parent, propertyName, ccbFileNode, ccbReader);
}
@@ -48,16 +50,16 @@ var PROPERTY_SELECTED = "selected";
var PROPERTY_CCCONTROL = "ccControl";
cc.ControlLoader = cc.NodeLoader.extend({
- _createCCNode:function (parent, ccbReander) {
+ _createCCNode: function (parent, ccbReander) {
},
- onHandlePropTypeBlockCCControl:function (node, parent, propertyName, blockCCControlData, ccbReader) {
+ onHandlePropTypeBlockCCControl: function (node, parent, propertyName, blockCCControlData, ccbReader) {
if (propertyName === PROPERTY_CCCONTROL) {
node.addTargetWithActionForControlEvents(blockCCControlData.target, blockCCControlData.selCCControlHandler, blockCCControlData.controlEvents);
} else {
cc.NodeLoader.prototype.onHandlePropTypeBlockCCControl.call(this, node, parent, propertyName, blockCCControlData, ccbReader);
}
},
- onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) {
+ onHandlePropTypeCheck: function (node, parent, propertyName, check, ccbReader) {
if (propertyName === PROPERTY_ENABLED) {
node.setEnabled(check);
} else if (propertyName === PROPERTY_SELECTED) {
@@ -88,18 +90,18 @@ var PROPERTY_BACKGROUNDSPRITEFRAME_HIGHLIGHTED = "backgroundSpriteFrame|2";
var PROPERTY_BACKGROUNDSPRITEFRAME_DISABLED = "backgroundSpriteFrame|3";
cc.ControlButtonLoader = cc.ControlLoader.extend({
- _createCCNode:function (parent, ccbReader) {
+ _createCCNode: function (parent, ccbReader) {
return new cc.ControlButton();
},
- onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) {
+ onHandlePropTypeCheck: function (node, parent, propertyName, check, ccbReader) {
if (propertyName === PROPERTY_ZOOMONTOUCHDOWN) {
- node.setZoomOnTouchDown(check);
+ node.zoomOnTouchDown = check;
} else {
cc.ControlLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader);
}
},
- onHandlePropTypeString:function (node, parent, propertyName, stringValue, ccbReader) {
+ onHandlePropTypeString: function (node, parent, propertyName, stringValue, ccbReader) {
if (propertyName === PROPERTY_TITLE_NORMAL) {
node.setTitleForState(stringValue, cc.CONTROL_STATE_NORMAL);
} else if (propertyName === PROPERTY_TITLE_HIGHLIGHTED) {
@@ -110,7 +112,7 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({
cc.ControlLoader.prototype.onHandlePropTypeString.call(this, node, parent, propertyName, stringValue, ccbReader);
}
},
- onHandlePropTypeFontTTF:function (node, parent, propertyName, fontTTF, ccbReader) {
+ onHandlePropTypeFontTTF: function (node, parent, propertyName, fontTTF, ccbReader) {
if (propertyName === PROPERTY_TITLETTF_NORMAL) {
node.setTitleTTFForState(fontTTF, cc.CONTROL_STATE_NORMAL);
} else if (propertyName === PROPERTY_TITLETTF_HIGHLIGHTED) {
@@ -121,7 +123,7 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({
cc.ControlLoader.prototype.onHandlePropTypeFontTTF.call(this, node, parent, propertyName, fontTTF, ccbReader);
}
},
- onHandlePropTypeFloatScale:function (node, parent, propertyName, floatScale, ccbReader) {
+ onHandlePropTypeFloatScale: function (node, parent, propertyName, floatScale, ccbReader) {
if (propertyName === PROPERTY_TITLETTFSIZE_NORMAL) {
node.setTitleTTFSizeForState(floatScale, cc.CONTROL_STATE_NORMAL);
} else if (propertyName === PROPERTY_TITLETTFSIZE_HIGHLIGHTED) {
@@ -132,21 +134,21 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({
cc.ControlLoader.prototype.onHandlePropTypeFloatScale.call(this, node, parent, propertyName, floatScale, ccbReader);
}
},
- onHandlePropTypePoint:function (node, parent, propertyName, point, ccbReader) {
+ onHandlePropTypePoint: function (node, parent, propertyName, point, ccbReader) {
if (propertyName === PROPERTY_LABELANCHORPOINT) {
node.setLabelAnchorPoint(point);
} else {
cc.ControlLoader.prototype.onHandlePropTypePoint.call(this, node, parent, propertyName, point, ccbReader);
}
},
- onHandlePropTypeSize:function (node, parent, propertyName, size, ccbReader) {
+ onHandlePropTypeSize: function (node, parent, propertyName, size, ccbReader) {
if (propertyName === PROPERTY_PREFEREDSIZE) {
node.setPreferredSize(size);
} else {
cc.ControlLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size, ccbReader);
}
},
- onHandlePropTypeSpriteFrame:function (node, parent, propertyName, spriteFrame, ccbReader) {
+ onHandlePropTypeSpriteFrame: function (node, parent, propertyName, spriteFrame, ccbReader) {
if (propertyName === PROPERTY_BACKGROUNDSPRITEFRAME_NORMAL) {
if (spriteFrame != null) {
node.setBackgroundSpriteFrameForState(spriteFrame, cc.CONTROL_STATE_NORMAL);
@@ -163,7 +165,7 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({
cc.ControlLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, spriteFrame, ccbReader);
}
},
- onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
+ onHandlePropTypeColor3: function (node, parent, propertyName, ccColor3B, ccbReader) {
if (propertyName === PROPERTY_TITLECOLOR_NORMAL) {
node.setTitleColorForState(ccColor3B, cc.CONTROL_STATE_NORMAL);
} else if (propertyName === PROPERTY_TITLECOLOR_HIGHLIGHTED) {
@@ -187,19 +189,19 @@ var PROPERTY_BOUNCES = "bounces";
var PROPERTY_SCALE = "scale";
cc.ScrollViewLoader = cc.NodeLoader.extend({
- _createCCNode:function (parent, ccbReader) {
+ _createCCNode: function (parent, ccbReader) {
return new cc.ScrollView();
},
- onHandlePropTypeSize:function(node,parent,propertyName,size,ccbReader){
- if(propertyName === PROPERTY_CONTENTSIZE){
+ onHandlePropTypeSize: function (node, parent, propertyName, size, ccbReader) {
+ if (propertyName === PROPERTY_CONTENTSIZE) {
node.setViewSize(size);
- }else{
- cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node,parent,propertyName,size,ccbReader);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size, ccbReader);
}
},
- onHandlePropTypeCCBFile:function (node, parent, propertyName, ccbFileNode, ccbReader) {
+ onHandlePropTypeCCBFile: function (node, parent, propertyName, ccbFileNode, ccbReader) {
if (propertyName === PROPERTY_CONTAINER) {
node.setContainer(ccbFileNode);
node.updateInset();
@@ -207,7 +209,7 @@ cc.ScrollViewLoader = cc.NodeLoader.extend({
cc.NodeLoader.prototype.onHandlePropTypeCCBFile.call(this, node, parent, propertyName, ccbFileNode, ccbReader);
}
},
- onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) {
+ onHandlePropTypeCheck: function (node, parent, propertyName, check, ccbReader) {
if (propertyName === PROPERTY_CLIPSTOBOUNDS) {
node.setClippingToBounds(check);
} else if (propertyName === PROPERTY_BOUNCES) {
@@ -216,14 +218,14 @@ cc.ScrollViewLoader = cc.NodeLoader.extend({
cc.NodeLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader);
}
},
- onHandlePropTypeFloat:function (node, parent, propertyName, floatValue, ccbReader) {
+ onHandlePropTypeFloat: function (node, parent, propertyName, floatValue, ccbReader) {
if (propertyName === PROPERTY_SCALE) {
node.setScale(floatValue);
} else {
cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue, ccbReader);
}
},
- onHandlePropTypeIntegerLabeled:function (node, parent, propertyName, integerLabeled, ccbReader) {
+ onHandlePropTypeIntegerLabeled: function (node, parent, propertyName, integerLabeled, ccbReader) {
if (propertyName === PROPERTY_DIRECTION) {
node.setDirection(integerLabeled);
} else {
@@ -242,12 +244,12 @@ var PROPERTY_COLOR = "color";
var PROPERTY_OPACITY = "opacity";
var PROPERTY_BLENDFUNC = "blendFunc";
var PROPERTY_INSETLEFT = "insetLeft";
-var PROPERTY_INSETTOP = "insetTop" ;
+var PROPERTY_INSETTOP = "insetTop";
var PROPERTY_INSETRIGHT = "insetRight";
var PROPERTY_INSETBOTTOM = "insetBottom";
cc.Scale9SpriteLoader = cc.NodeLoader.extend({
- _createCCNode:function(parent,ccbReader){
+ _createCCNode: function (parent, ccbReader) {
var sprite = new cc.Scale9Sprite();
sprite.setAnchorPoint(0, 0);
@@ -255,63 +257,63 @@ cc.Scale9SpriteLoader = cc.NodeLoader.extend({
return sprite;
},
- onHandlePropTypeColor3:function(node, parent, propertyName, ccColor3B,ccbReader){
- if(propertyName === PROPERTY_COLOR) {
- if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){
+ onHandlePropTypeColor3: function (node, parent, propertyName, ccColor3B, ccbReader) {
+ if (propertyName === PROPERTY_COLOR) {
+ if (ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255) {
node.setColor(ccColor3B);
}
} else {
- cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B,ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader);
}
},
- onHandlePropTypeByte:function(node, parent, propertyName, byteValue,ccbReader){
- if(propertyName === PROPERTY_OPACITY) {
+ onHandlePropTypeByte: function (node, parent, propertyName, byteValue, ccbReader) {
+ if (propertyName === PROPERTY_OPACITY) {
node.setOpacity(byteValue);
} else {
- cc.NodeLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue,ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader);
}
},
- onHandlePropTypeBlendFunc:function(node, parent, propertyName, ccBlendFunc,ccbReader){
- if(propertyName === PROPERTY_BLENDFUNC) {
+ onHandlePropTypeBlendFunc: function (node, parent, propertyName, ccBlendFunc, ccbReader) {
+ if (propertyName === PROPERTY_BLENDFUNC) {
// TODO Not exported by CocosBuilder yet!
// node.setBlendFunc(ccBlendFunc);
} else {
- cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc,ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader);
}
},
- onHandlePropTypeSpriteFrame:function(node, parent, propertyName, spriteFrame,ccbReader){
- if(propertyName === PROPERTY_SPRITEFRAME) {
+ onHandlePropTypeSpriteFrame: function (node, parent, propertyName, spriteFrame, ccbReader) {
+ if (propertyName === PROPERTY_SPRITEFRAME) {
node.setSpriteFrame(spriteFrame);
} else {
- cc.NodeLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, spriteFrame,ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, spriteFrame, ccbReader);
}
},
- onHandlePropTypeSize:function(node, parent, propertyName, size,ccbReader){
- if(propertyName === PROPERTY_CONTENTSIZE) {
+ onHandlePropTypeSize: function (node, parent, propertyName, size, ccbReader) {
+ if (propertyName === PROPERTY_CONTENTSIZE) {
//node.setContentSize(size);
- } else if(propertyName === PROPERTY_PREFEREDSIZE) {
+ } else if (propertyName === PROPERTY_PREFEREDSIZE) {
node.setPreferredSize(size);
} else {
- cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size,ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size, ccbReader);
}
},
- onHandlePropTypeFloat:function(node, parent, propertyName, floatValue,ccbReader){
- if(propertyName === PROPERTY_INSETLEFT) {
+ onHandlePropTypeFloat: function (node, parent, propertyName, floatValue, ccbReader) {
+ if (propertyName === PROPERTY_INSETLEFT) {
node.setInsetLeft(floatValue);
- } else if(propertyName === PROPERTY_INSETTOP) {
+ } else if (propertyName === PROPERTY_INSETTOP) {
node.setInsetTop(floatValue);
- } else if(propertyName === PROPERTY_INSETRIGHT) {
+ } else if (propertyName === PROPERTY_INSETRIGHT) {
node.setInsetRight(floatValue);
- } else if(propertyName === PROPERTY_INSETBOTTOM) {
+ } else if (propertyName === PROPERTY_INSETBOTTOM) {
node.setInsetBottom(floatValue);
} else {
- cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue,ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue, ccbReader);
}
}
});
-cc.Scale9SpriteLoader.loader = function(){
- return new cc.Scale9SpriteLoader();
+cc.Scale9SpriteLoader.loader = function () {
+ return new cc.Scale9SpriteLoader();
};
diff --git a/extensions/ccb-reader/CCNodeLoader.js b/extensions/ccb-reader/CCNodeLoader.js
index 67b575f41a..afa434b4d2 100644
--- a/extensions/ccb-reader/CCNodeLoader.js
+++ b/extensions/ccb-reader/CCNodeLoader.js
@@ -54,19 +54,30 @@ function BlockCCControlData(selCCControlHandler, target, controlEvents) {
}
cc.NodeLoader = cc.Class.extend({
- _customProperties:null,
+ _customProperties: null,
+ _pt: null,
+ _size: null,
+ _arr2: null,
- ctor:function(){
+ ctor: function () {
this._customProperties = new cc._Dictionary();
+ this._pt = cc.p();
+ this._size = cc.size();
+ this._arr2 = new Array(2);
+ this._blockControlData = {
+ selCCControlHandler: null,
+ target: null,
+ controlEvents: null
+ };
},
- loadCCNode:function (parent, ccbReader) {
+ loadCCNode: function (parent, ccbReader) {
return this._createCCNode(parent, ccbReader);
//this.parseProperties(node, parent, ccbReader);
//return node;
},
- parseProperties:function (node, parent, ccbReader) {
+ parseProperties: function (node, parent, ccbReader) {
var numRegularProps = ccbReader.readInt(false);
var numExturaProps = ccbReader.readInt(false);
var propertyCount = numRegularProps + numExturaProps;
@@ -79,26 +90,26 @@ cc.NodeLoader = cc.Class.extend({
// Check if the property can be set for this platform
var setProp = false;
- var platform = ccbReader.readByte();
- if ((platform === CCB_PLATFORM_ALL) ||(platform === CCB_PLATFORM_IOS) ||(platform === CCB_PLATFORM_MAC) )
+ var platform = ccbReader._data[ccbReader._currentByte++];
+ if ((platform === CCB_PLATFORM_ALL) || (platform === CCB_PLATFORM_IOS) || (platform === CCB_PLATFORM_MAC))
setProp = true;
//forward properties for sub ccb files
- if(node instanceof cc.BuilderFile){
- if(node.getCCBFileNode() && isExtraProp){
- node = node.getCCBFileNode();
+ if (isExtraProp) {
+ if (node.ccbFileNode) {
+ node = node.ccbFileNode;
//skip properties that doesn't have a value to override
var getExtraPropsNames = node.userObject;
setProp = getExtraPropsNames.indexOf(propertyName) !== -1;
+ } else if (node === ccbReader._animationManager.getRootNode()) {
+ var extraPropsNames = node.userObject;
+ if (!extraPropsNames) {
+ extraPropsNames = [];
+ node.userObject = extraPropsNames;
+ }
+ extraPropsNames.push(propertyName);
}
- } else if(isExtraProp && node === ccbReader.getAnimationManager().getRootNode()){
- var extraPropsNames = node.userObject;
- if(!extraPropsNames){
- extraPropsNames = [];
- node.userObject = extraPropsNames;
- }
- extraPropsNames.push(propertyName);
- }
+ }
switch (type) {
case CCB_PROPTYPE_POSITION:
@@ -327,53 +338,52 @@ cc.NodeLoader = cc.Class.extend({
}
},
- getCustomProperties:function(){
+ getCustomProperties: function () {
return this._customProperties;
},
- _createCCNode:function (parent, ccbReader) {
+ _createCCNode: function (parent, ccbReader) {
return new cc.Node();
},
- parsePropTypePosition:function (node, parent, ccbReader, propertyName) {
+ parsePropTypePosition: function (node, parent, ccbReader, propertyName) {
var x = ccbReader.readFloat();
var y = ccbReader.readFloat();
var type = ccbReader.readInt(false);
- var containerSize = ccbReader.getAnimationManager().getContainerSize(parent);
- var pt = cc._getAbsolutePosition(x,y,type,containerSize,propertyName);
- node.setPosition(cc.getAbsolutePosition(pt,type,containerSize,propertyName)); //different to -x node.setPosition(pt);
+ // var containerSize = ccbReader._animationManager.getContainerSize(parent);
+ var containerSize = parent ? parent._contentSize : ccbReader._animationManager._rootContainerSize;
+ cc.getAbsolutePosition(x, y, type, containerSize, propertyName, this._pt);
+ node.setPosition(this._pt);
- if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
- var baseValue = [x,y,type];
- ccbReader.getAnimationManager().setBaseValue(baseValue,node,propertyName);
+ if (ccbReader._animatedProps.indexOf(propertyName) > -1) {
+ var baseValue = [x, y, type];
+ ccbReader._animationManager.setBaseValue(baseValue, node, propertyName);
}
-
- return pt;
+ return this._pt;
},
- parsePropTypePoint:function (node, parent, ccbReader) {
- var x = ccbReader.readFloat();
- var y = ccbReader.readFloat();
-
- return cc.p(x, y);
+ parsePropTypePoint: function (node, parent, ccbReader) {
+ this._pt.x = ccbReader.readFloat();
+ this._pt.y = ccbReader.readFloat();
+ return this._pt;
},
- parsePropTypePointLock:function (node, parent, ccbReader) {
- var x = ccbReader.readFloat();
- var y = ccbReader.readFloat();
-
- return cc.p(x, y);
+ parsePropTypePointLock: function (node, parent, ccbReader) {
+ this._pt.x = ccbReader.readFloat();
+ this._pt.y = ccbReader.readFloat();
+ return this._pt;
},
- parsePropTypeSize:function (node, parent, ccbReader) {
+ parsePropTypeSize: function (node, parent, ccbReader) {
var width = ccbReader.readFloat();
var height = ccbReader.readFloat();
var type = ccbReader.readInt(false);
- var containerSize = ccbReader.getAnimationManager().getContainerSize(parent);
+ // var containerSize = ccbReader._animationManager.getContainerSize(parent);
+ var containerSize = parent ? parent._contentSize : ccbReader._animationManager._rootContainerSize;
switch (type) {
case CCB_SIZETYPE_ABSOLUTE:
@@ -402,43 +412,46 @@ cc.NodeLoader = cc.Class.extend({
cc.log("Unknown CCB type.");
break;
}
-
- return cc.size(width, height);
+ this._size.width = width;
+ this._size.height = height;
+ return this._size;
},
- parsePropTypeScaleLock:function (node, parent, ccbReader, propertyName) {
+ parsePropTypeScaleLock: function (node, parent, ccbReader, propertyName) {
var x = ccbReader.readFloat();
var y = ccbReader.readFloat();
var type = ccbReader.readInt(false);
- cc.setRelativeScale(node,x,y,type,propertyName);
+ // cc.setRelativeScale(node, x, y, type, propertyName);
- if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
- ccbReader.getAnimationManager().setBaseValue([x,y,type],node,propertyName);
+ if (ccbReader._animatedProps.indexOf(propertyName) > -1) {
+ ccbReader._animationManager.setBaseValue([x, y, type], node, propertyName);
}
if (type === CCB_SCALETYPE_MULTIPLY_RESOLUTION) {
- x *= cc.BuilderReader.getResolutionScale();
- y *= cc.BuilderReader.getResolutionScale();
+ var resolutionScale = cc.BuilderReader.getResolutionScale();
+ x *= resolutionScale;
+ y *= resolutionScale;
}
-
- return [x, y];
+ this._pt.x = x;
+ this._pt.y = y;
+ return this._pt;
},
- parsePropTypeFloat:function (node, parent, ccbReader) {
+ parsePropTypeFloat: function (node, parent, ccbReader) {
return ccbReader.readFloat();
},
- parsePropTypeDegrees:function (node, parent, ccbReader, propertyName) {
- var ret = ccbReader.readFloat();
- if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
- ccbReader.getAnimationManager().setBaseValue(ret,node, propertyName);
+ parsePropTypeDegrees: function (node, parent, ccbReader, propertyName) {
+ var degrees = ccbReader.readFloat();
+ if (ccbReader._animatedProps.indexOf(propertyName) > -1) {
+ ccbReader._animationManager.setBaseValue(degrees, node, propertyName);
}
- return ret;
+ return degrees;
},
- parsePropTypeFloatScale:function (node, parent, ccbReader) {
+ parsePropTypeFloatScale: function (node, parent, ccbReader) {
var f = ccbReader.readFloat();
var type = ccbReader.readInt(false);
@@ -450,36 +463,36 @@ cc.NodeLoader = cc.Class.extend({
return f;
},
- parsePropTypeInteger:function (node, parent, ccbReader) {
+ parsePropTypeInteger: function (node, parent, ccbReader) {
return ccbReader.readInt(true);
},
- parsePropTypeIntegerLabeled:function (node, parent, ccbReader) {
+ parsePropTypeIntegerLabeled: function (node, parent, ccbReader) {
return ccbReader.readInt(true);
},
- parsePropTypeFloatVar:function (node, parent, ccbReader) {
- var f = ccbReader.readFloat();
- var fVar = ccbReader.readFloat();
- return [f, fVar];
+ parsePropTypeFloatVar: function (node, parent, ccbReader) {
+ this._arr2[0] = ccbReader.readFloat();
+ this._arr2[1] = ccbReader.readFloat();
+ return this._arr2;
},
- parsePropTypeCheck:function (node, parent, ccbReader, propertyName) {
- var ret = ccbReader.readBool();
- if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
- ccbReader.getAnimationManager().setBaseValue(ret,node, propertyName);
+ parsePropTypeCheck: function (node, parent, ccbReader, propertyName) {
+ var check = !!ccbReader._data[ccbReader._currentByte++];
+ if (ccbReader._animatedProps.indexOf(propertyName) > -1) {
+ ccbReader._animationManager.setBaseValue(check, node, propertyName);
}
- return ret;
+ return check;
},
- parsePropTypeSpriteFrame:function (node, parent, ccbReader, propertyName) {
+ parsePropTypeSpriteFrame: function (node, parent, ccbReader, propertyName) {
var spriteSheet = ccbReader.readCachedString();
- var spriteFile = ccbReader.readCachedString();
+ var spriteFile = ccbReader.readCachedString();
var spriteFrame;
- if(spriteFile != null && spriteFile.length !== 0){
- if(spriteSheet.length === 0){
- spriteFile = ccbReader.getCCBRootPath() + spriteFile;
+ if (spriteFile) {
+ if (spriteSheet.length === 0) {
+ spriteFile = ccbReader._ccbRootPath + spriteFile;
var texture = cc.textureCache.addImage(spriteFile);
var locContentSize = texture.getContentSize();
@@ -487,24 +500,24 @@ cc.NodeLoader = cc.Class.extend({
spriteFrame = new cc.SpriteFrame(texture, bounds);
} else {
var frameCache = cc.spriteFrameCache;
- spriteSheet = ccbReader.getCCBRootPath() + spriteSheet;
+ spriteSheet = ccbReader._ccbRootPath + spriteSheet;
//load the sprite sheet only if it is not loaded
- if(ccbReader.getLoadedSpriteSheet().indexOf(spriteSheet) === -1){
+ if (ccbReader._loadedSpriteSheets.indexOf(spriteSheet) === -1) {
frameCache.addSpriteFrames(spriteSheet);
- ccbReader.getLoadedSpriteSheet().push(spriteSheet);
+ ccbReader._loadedSpriteSheets.push(spriteSheet);
}
spriteFrame = frameCache.getSpriteFrame(spriteFile);
}
- if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
- ccbReader.getAnimationManager().setBaseValue(spriteFrame,node,propertyName);
+ if (ccbReader._animatedProps.indexOf(propertyName) > -1) {
+ ccbReader._animationManager.setBaseValue(spriteFrame, node, propertyName);
}
}
return spriteFrame;
},
- parsePropTypeAnimation:function (node, parent, ccbReader) {
- var animationFile = ccbReader.getCCBRootPath() + ccbReader.readCachedString();
+ parsePropTypeAnimation: function (node, parent, ccbReader) {
+ var animationFile = ccbReader._ccbRootPath + ccbReader.readCachedString();
var animation = ccbReader.readCachedString();
var ccAnimation = null;
@@ -517,7 +530,7 @@ cc.NodeLoader = cc.Class.extend({
animation = cc.BuilderReader.lastPathComponent(animation);
animationFile = cc.BuilderReader.lastPathComponent(animationFile);
- if (animation != null && animation !== "") {
+ if (animation) {
var animationCache = cc.animationCache;
animationCache.addAnimations(animationFile);
@@ -526,34 +539,34 @@ cc.NodeLoader = cc.Class.extend({
return ccAnimation;
},
- parsePropTypeTexture:function (node, parent, ccbReader) {
- var spriteFile = ccbReader.getCCBRootPath() + ccbReader.readCachedString();
+ parsePropTypeTexture: function (node, parent, ccbReader) {
+ var spriteFile = ccbReader._ccbRootPath + ccbReader.readCachedString();
- if(spriteFile !== "")
+ if (spriteFile)
return cc.textureCache.addImage(spriteFile);
return null;
},
- parsePropTypeByte:function (node, parent, ccbReader, propertyName) {
- var ret = ccbReader.readByte();
- if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
- ccbReader.getAnimationManager().setBaseValue(ret,node, propertyName);
+ parsePropTypeByte: function (node, parent, ccbReader, propertyName) {
+ var ret = ccbReader._data[ccbReader._currentByte++];
+ if (ccbReader._animatedProps.indexOf(propertyName) > -1) {
+ ccbReader._animationManager.setBaseValue(ret, node, propertyName);
}
return ret;
},
- parsePropTypeColor3:function (node, parent, ccbReader, propertyName) {
- var red = ccbReader.readByte();
- var green = ccbReader.readByte();
- var blue = ccbReader.readByte();
- var color = {r:red, g:green, b:blue };
- if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
- ccbReader.getAnimationManager().setBaseValue(cc.Color3BWapper.create(color),node, propertyName);
+ parsePropTypeColor3: function (node, parent, ccbReader, propertyName) {
+ var red = ccbReader._data[ccbReader._currentByte++];
+ var green = ccbReader._data[ccbReader._currentByte++];
+ var blue = ccbReader._data[ccbReader._currentByte++];
+ var color = cc.color(red, green, blue);
+ if (ccbReader._animatedProps.indexOf(propertyName) > -1) {
+ ccbReader._animationManager.setBaseValue(color, node, propertyName);
}
return color;
},
- parsePropTypeColor4FVar:function (node, parent, ccbReader) {
+ parsePropTypeColor4FVar: function (node, parent, ccbReader) {
//TODO Color4F doesn't supports on HTML5
var red = 0 | (ccbReader.readFloat() * 255);
var green = 0 | (ccbReader.readFloat() * 255);
@@ -566,40 +579,39 @@ cc.NodeLoader = cc.Class.extend({
var alphaVar = ccbReader.readFloat();
alphaVar = alphaVar <= 1 ? (0 | (alphaVar * 255)) : alphaVar;
- var colors = [];
- colors[0] = {r:red, g:green, b:blue, a:alpha};
- colors[1] = {r:redVar, g:greenVar, b:blueVar, a:alphaVar};
+ this._arr2[0] = {r: red, g: green, b: blue, a: alpha};
+ this._arr2[1] = {r: redVar, g: greenVar, b: blueVar, a: alphaVar};
- return colors;
+ return this._arr2;
},
- parsePropTypeFlip:function (node, parent, ccbReader) {
- var flipX = ccbReader.readBool();
- var flipY = ccbReader.readBool();
+ parsePropTypeFlip: function (node, parent, ccbReader) {
+ this._arr2[0] = !!ccbReader._data[ccbReader._currentByte++];
+ this._arr2[1] = !!ccbReader._data[ccbReader._currentByte++];
- return [flipX, flipY];
+ return this._arr2;
},
- parsePropTypeBlendFunc:function (node, parent, ccbReader) {
+ parsePropTypeBlendFunc: function (node, parent, ccbReader) {
var source = ccbReader.readInt(false);
var destination = ccbReader.readInt(false);
return new cc.BlendFunc(source, destination);
},
- parsePropTypeFntFile:function (node, parent, ccbReader) {
+ parsePropTypeFntFile: function (node, parent, ccbReader) {
return ccbReader.readCachedString();
},
- parsePropTypeString:function (node, parent, ccbReader) {
+ parsePropTypeString: function (node, parent, ccbReader) {
return ccbReader.readCachedString();
},
- parsePropTypeText:function (node, parent, ccbReader) {
+ parsePropTypeText: function (node, parent, ccbReader) {
return ccbReader.readCachedString();
},
- parsePropTypeFontTTF:function (node, parent, ccbReader) {
+ parsePropTypeFontTTF: function (node, parent, ccbReader) {
return ccbReader.readCachedString();
//var ttfEnding = ".ttf";
@@ -607,21 +619,21 @@ cc.NodeLoader = cc.Class.extend({
/* If the fontTTF comes with the ".ttf" extension, prepend the absolute path.
* System fonts come without the ".ttf" extension and do not need the path prepended. */
/*if (cc.CCBReader.endsWith(fontTTF.toLowerCase(), ttfEnding)) {
- fontTTF = ccbReader.getCCBRootPath() + fontTTF;
- }*/
+ fontTTF = ccbReader.getCCBRootPath() + fontTTF;
+ }*/
},
- parsePropTypeBlock:function (node, parent, ccbReader) {
+ parsePropTypeBlock: function (node, parent, ccbReader) {
var selectorName = ccbReader.readCachedString();
var selectorTarget = ccbReader.readInt(false);
if (selectorTarget !== CCB_TARGETTYPE_NONE) {
var target = null;
- if(!ccbReader.isJSControlled()) {
+ if (!ccbReader._jsControlled) {
if (selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT) {
- target = ccbReader.getAnimationManager().getRootNode();
+ target = ccbReader._animationManager._rootNode;
} else if (selectorTarget === CCB_TARGETTYPE_OWNER) {
- target = ccbReader.getOwner();
+ target = ccbReader._owner;
}
if (target !== null) {
@@ -633,15 +645,15 @@ cc.NodeLoader = cc.Class.extend({
selMenuHandler = target.onResolveCCBCCMenuItemSelector(target, selectorName);
if (selMenuHandler === 0) {
- var ccbSelectorResolver = ccbReader.getCCBSelectorResolver();
- if (ccbSelectorResolver != null)
+ var ccbSelectorResolver = ccbReader._ccbSelectorResolver;
+ if (ccbSelectorResolver)
selMenuHandler = ccbSelectorResolver.onResolveCCBCCMenuItemSelector(target, selectorName);
}
if (selMenuHandler === 0) {
- cc.log("Skipping selector '" +selectorName+ "' since no CCBSelectorResolver is present.");
+ cc.log("Skipping selector '" + selectorName + "' since no CCBSelectorResolver is present.");
} else {
- return new BlockData(selMenuHandler,target);
+ return new BlockData(selMenuHandler, target);
}
} else {
cc.log("Unexpected empty selector.");
@@ -650,7 +662,7 @@ cc.NodeLoader = cc.Class.extend({
cc.log("Unexpected NULL target for selector.");
}
} else {
- if(selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT){
+ if (selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT) {
ccbReader.addDocumentCallbackNode(node);
ccbReader.addDocumentCallbackName(selectorName);
ccbReader.addDocumentCallbackControlEvents(0);
@@ -664,18 +676,18 @@ cc.NodeLoader = cc.Class.extend({
return null;
},
- parsePropTypeBlockCCControl:function (node, parent, ccbReader) {
+ parsePropTypeBlockCCControl: function (node, parent, ccbReader) {
var selectorName = ccbReader.readCachedString();
var selectorTarget = ccbReader.readInt(false);
var controlEvents = ccbReader.readInt(false);
if (selectorTarget !== CCB_TARGETTYPE_NONE) {
- if(!ccbReader.isJSControlled()){
+ if (!ccbReader._jsControlled) {
var target = null;
if (selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT) {
- target = ccbReader.getAnimationManager().getRootNode();
+ target = ccbReader._animationManager._rootNode;
} else if (selectorTarget === CCB_TARGETTYPE_OWNER) {
- target = ccbReader.getOwner();
+ target = ccbReader._owner;
}
if (target !== null) {
@@ -686,7 +698,7 @@ cc.NodeLoader = cc.Class.extend({
selCCControlHandler = target.onResolveCCBCCControlSelector(target, selectorName);
}
if (selCCControlHandler === 0) {
- var ccbSelectorResolver = ccbReader.getCCBSelectorResolver();
+ var ccbSelectorResolver = ccbReader._ccbSelectorResolver;
if (ccbSelectorResolver != null) {
selCCControlHandler = ccbSelectorResolver.onResolveCCBCCControlSelector(target, selectorName);
}
@@ -695,7 +707,10 @@ cc.NodeLoader = cc.Class.extend({
if (selCCControlHandler === 0) {
cc.log("Skipping selector '" + selectorName + "' since no CCBSelectorResolver is present.");
} else {
- return new BlockCCControlData(selCCControlHandler,target,controlEvents);
+ this._blockControlData.selCCControlHandler = selCCControlHandler;
+ this._blockControlData.target = target;
+ this._blockControlData.controlEvents = controlEvents;
+ return this._blockControlData;
}
} else {
cc.log("Unexpected empty selector.");
@@ -704,7 +719,7 @@ cc.NodeLoader = cc.Class.extend({
cc.log("Unexpected NULL target for selector.");
}
} else {
- if(selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT){
+ if (selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT) {
ccbReader.addDocumentCallbackNode(node);
ccbReader.addDocumentCallbackName(selectorName);
ccbReader.addDocumentCallbackControlEvents(controlEvents);
@@ -718,8 +733,8 @@ cc.NodeLoader = cc.Class.extend({
return null;
},
- parsePropTypeCCBFile:function (node, parent, ccbReader) {
- var ccbFileName = ccbReader.getCCBRootPath() + ccbReader.readCachedString();
+ parsePropTypeCCBFile: function (node, parent, ccbReader) {
+ var ccbFileName = ccbReader._ccbRootPath + ccbReader.readCachedString();
/* Change path extension to .ccbi. */
var ccbFileWithoutPathExtension = cc.BuilderReader.deletePathExtension(ccbFileName);
@@ -728,33 +743,34 @@ cc.NodeLoader = cc.Class.extend({
var myCCBReader = new cc.BuilderReader(ccbReader);
var bytes = cc.loader.getRes(ccbFileName);
- if(!bytes){
+ if (!bytes) {
var realUrl = cc.loader.getUrl(ccbFileName);
+ realUrl = hlddz.convertToDownloadURL(realUrl);
bytes = cc.loader.loadBinarySync(realUrl);
cc.loader.cache[ccbFileName] = bytes;
}
- myCCBReader.initWithData(bytes,ccbReader.getOwner());
- myCCBReader.getAnimationManager().setRootContainerSize(parent.getContentSize());
- myCCBReader.setAnimationManagers(ccbReader.getAnimationManagers());
+ myCCBReader.initWithData(bytes, ccbReader._owner);
+ myCCBReader._animationManager.setRootContainerSize(parent._contentSize);
+ myCCBReader.setAnimationManagers(ccbReader._animationManagers);
- myCCBReader.getAnimationManager().setOwner(ccbReader.getOwner());
+ myCCBReader._animationManager.setOwner(ccbReader._owner);
var ccbFileNode = myCCBReader.readFileWithCleanUp(false);
- ccbReader.setAnimationManagers(myCCBReader.getAnimationManagers());
+ ccbReader.setAnimationManagers(myCCBReader._animationManagers);
- if(ccbFileNode && myCCBReader.getAnimationManager().getAutoPlaySequenceId() !== -1)
- myCCBReader.getAnimationManager().runAnimations(myCCBReader.getAnimationManager().getAutoPlaySequenceId(),0);
+ if (ccbFileNode && myCCBReader._animationManager._autoPlaySequenceId !== -1)
+ myCCBReader._animationManager.runAnimations(myCCBReader._animationManager._autoPlaySequenceId, 0);
return ccbFileNode;
},
- parsePropTypeFloatXY:function(node, parent, ccbReader){
- var x = ccbReader.readFloat();
- var y = ccbReader.readFloat();
- return [x,y];
+ parsePropTypeFloatXY: function (node, parent, ccbReader) {
+ this._pt.x = ccbReader.readFloat();
+ this._pt.y = ccbReader.readFloat();
+ return this._pt;
},
- onHandlePropTypePosition:function (node, parent, propertyName, position, ccbReader) {
+ onHandlePropTypePosition: function (node, parent, propertyName, position, ccbReader) {
if (propertyName === PROPERTY_POSITION) {
node.setPosition(position);
} else {
@@ -762,7 +778,7 @@ cc.NodeLoader = cc.Class.extend({
}
},
- onHandlePropTypePoint:function (node, parent, propertyName, position, ccbReader) {
+ onHandlePropTypePoint: function (node, parent, propertyName, position, ccbReader) {
if (propertyName === PROPERTY_ANCHORPOINT) {
node.setAnchorPoint(position);
} else {
@@ -770,11 +786,11 @@ cc.NodeLoader = cc.Class.extend({
}
},
- onHandlePropTypePointLock:function (node, parent, propertyName, pointLock, ccbReader) {
+ onHandlePropTypePointLock: function (node, parent, propertyName, pointLock, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeSize:function (node, parent, propertyName, sizeValue, ccbReader) {
+ onHandlePropTypeSize: function (node, parent, propertyName, sizeValue, ccbReader) {
if (propertyName === PROPERTY_CONTENTSIZE) {
node.setContentSize(sizeValue);
} else {
@@ -782,35 +798,34 @@ cc.NodeLoader = cc.Class.extend({
}
},
- onHandlePropTypeScaleLock:function (node, parent, propertyName, scaleLock, ccbReader) {
+ onHandlePropTypeScaleLock: function (node, parent, propertyName, scaleLock, ccbReader) {
if (propertyName === PROPERTY_SCALE) {
- node.setScaleX(scaleLock[0]);
- node.setScaleY(scaleLock[1]);
+ node.setScale(scaleLock.x, scaleLock.y);
} else {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
}
},
onHandlePropTypeFloatXY: function (node, parent, propertyName, xy, ccbReader) {
if (propertyName === PROPERTY_SKEW) {
- node.setSkewX(xy[0]);
- node.setSkewY(xy[1]);
+ node._skewX = xy.x;
+ node._skewY = xy.y;
} else {
var nameX = propertyName + "X";
var nameY = propertyName + "Y";
if (!node[nameX] || !node[nameY])
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
//TODO throw an error when source code was confused
- node[nameX](xy[0]);
- node[nameY](xy[1]);
+ node[nameX](xy.x);
+ node[nameY](xy.y);
}
},
- onHandlePropTypeFloat:function (node, parent, propertyName, floatValue, ccbReader) {
+ onHandlePropTypeFloat: function (node, parent, propertyName, floatValue, ccbReader) {
//ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
// It may be a custom property, add it to custom property dictionary.
this._customProperties.setObject(floatValue, propertyName);
},
- onHandlePropTypeDegrees:function (node, parent, propertyName, degrees, ccbReader) {
+ onHandlePropTypeDegrees: function (node, parent, propertyName, degrees, ccbReader) {
if (propertyName === PROPERTY_ROTATION) {
node.setRotation(degrees);
} else {
@@ -818,83 +833,83 @@ cc.NodeLoader = cc.Class.extend({
}
},
- onHandlePropTypeFloatScale:function (node, parent, propertyName, floatScale, ccbReader) {
+ onHandlePropTypeFloatScale: function (node, parent, propertyName, floatScale, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeInteger:function (node, parent, propertyName, integer, ccbReader) {
+ onHandlePropTypeInteger: function (node, parent, propertyName, integer, ccbReader) {
if (propertyName === PROPERTY_TAG) {
- node.setTag(integer);
+ node.tag = integer;
} else {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
}
},
- onHandlePropTypeIntegerLabeled:function (node, parent, propertyName, integerLabeled, ccbReader) {
+ onHandlePropTypeIntegerLabeled: function (node, parent, propertyName, integerLabeled, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeFloatVar:function (node, parent, propertyName, floatVar, ccbReader) {
+ onHandlePropTypeFloatVar: function (node, parent, propertyName, floatVar, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) {
+ onHandlePropTypeCheck: function (node, parent, propertyName, check, ccbReader) {
if (propertyName === PROPERTY_VISIBLE) {
- node.setVisible(check);
+ node._visible = check;
} else if (propertyName === PROPERTY_IGNOREANCHORPOINTFORPOSITION) {
- node.ignoreAnchorPointForPosition(check);
+ node._ignoreAnchorPointForPosition = check;
} else {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
}
},
- onHandlePropTypeSpriteFrame:function (node, parent, propertyName, spriteFrame, ccbReader) {
+ onHandlePropTypeSpriteFrame: function (node, parent, propertyName, spriteFrame, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeAnimation:function (node, parent, propertyName, ccAnimation, ccbReader) {
+ onHandlePropTypeAnimation: function (node, parent, propertyName, ccAnimation, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeTexture:function (node, parent, propertyName, ccTexture2D, ccbReader) {
+ onHandlePropTypeTexture: function (node, parent, propertyName, ccTexture2D, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) {
+ onHandlePropTypeByte: function (node, parent, propertyName, byteValue, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
+ onHandlePropTypeColor3: function (node, parent, propertyName, ccColor3B, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeColor4FVar:function (node, parent, propertyName, ccColor4FVar, ccbReader) {
+ onHandlePropTypeColor4FVar: function (node, parent, propertyName, ccColor4FVar, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeFlip:function (node, parent, propertyName, flip, ccbReader) {
+ onHandlePropTypeFlip: function (node, parent, propertyName, flip, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) {
+ onHandlePropTypeBlendFunc: function (node, parent, propertyName, ccBlendFunc, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeFntFile:function (node, parent, propertyName, fntFile, ccbReader) {
+ onHandlePropTypeFntFile: function (node, parent, propertyName, fntFile, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeString:function (node, parent, propertyName, strValue, ccbReader) {
+ onHandlePropTypeString: function (node, parent, propertyName, strValue, ccbReader) {
//ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
// It may be a custom property, add it to custom property dictionary.
this._customProperties.setObject(strValue, propertyName);
},
- onHandlePropTypeText:function (node, parent, propertyName, textValue, ccbReader) {
+ onHandlePropTypeText: function (node, parent, propertyName, textValue, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeFontTTF:function (node, parent, propertyName, fontTTF, ccbReader) {
+ onHandlePropTypeFontTTF: function (node, parent, propertyName, fontTTF, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeBlock:function (node, parent, propertyName, blockData, ccbReader) {
+ onHandlePropTypeBlock: function (node, parent, propertyName, blockData, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeBlockCCControl:function (node, parent, propertyName, blockCCControlData, ccbReader) {
+ onHandlePropTypeBlockCCControl: function (node, parent, propertyName, blockCCControlData, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeCCBFile:function (node, parent, propertyName, ccbFileNode, ccbReader) {
+ onHandlePropTypeCCBFile: function (node, parent, propertyName, ccbFileNode, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
}
});
diff --git a/extensions/ccpool/CCPool.js b/extensions/ccpool/CCPool.js
index 489ae1d9c6..2159c091c8 100644
--- a/extensions/ccpool/CCPool.js
+++ b/extensions/ccpool/CCPool.js
@@ -62,7 +62,7 @@ cc.pool = /** @lends cc.pool# */{
putInPool: function (obj) {
var pid = obj.constructor.prototype['__pid'];
if (!pid) {
- var desc = { writable: true, enumerable: false, configurable: true };
+ var desc = {writable: true, enumerable: false, configurable: true};
desc.value = ClassManager.getNewID();
Object.defineProperty(obj.constructor.prototype, '__pid', desc);
}
@@ -143,4 +143,4 @@ cc.pool = /** @lends cc.pool# */{
}
this._pool = {};
}
-};
\ No newline at end of file
+};
diff --git a/extensions/ccui/base-classes/CCProtectedNode.js b/extensions/ccui/base-classes/CCProtectedNode.js
index 8407e7e633..4a2bcd367a 100644
--- a/extensions/ccui/base-classes/CCProtectedNode.js
+++ b/extensions/ccui/base-classes/CCProtectedNode.js
@@ -31,7 +31,7 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
_protectedChildren: null,
_reorderProtectedChildDirty: false,
- _insertProtectedChild: function(child, z){
+ _insertProtectedChild: function (child, z) {
this._reorderProtectedChildDirty = true;
this._protectedChildren.push(child);
child._setLocalZOrder(z);
@@ -41,11 +41,67 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
* @function
*/
- ctor: function(){
+ ctor: function () {
cc.Node.prototype.ctor.call(this);
this._protectedChildren = [];
},
+ visit: function (parent) {
+ // quick return if not visible
+ if (!this._visible)
+ return;
+
+ var renderer = cc.renderer, cmd = this._renderCmd;
+ var i, children = this._children, len = children.length, child;
+ var j, pChildren = this._protectedChildren, pLen = pChildren.length, pChild;
+
+ cmd.visit(parent && parent._renderCmd);
+
+ var locGrid = this.grid;
+ if (locGrid && locGrid._active)
+ locGrid.beforeDraw();
+
+ if (this._reorderChildDirty) this.sortAllChildren();
+ if (this._reorderProtectedChildDirty) this.sortAllProtectedChildren();
+
+ // draw children zOrder < 0
+ for (i = 0; i < len; i++) {
+ child = children[i];
+ if (child._localZOrder < 0) {
+ child.visit(this);
+ }
+ else {
+ break;
+ }
+ }
+ for (j = 0; j < pLen; j++) {
+ pChild = pChildren[j];
+ if (pChild && pChild._localZOrder < 0) {
+ cmd._changeProtectedChild(pChild);
+ pChild.visit(this);
+ }
+ else
+ break;
+ }
+
+ renderer.pushRenderCommand(cmd);
+
+ for (; i < len; i++) {
+ children[i].visit(this);
+ }
+ for (; j < pLen; j++) {
+ pChild = pChildren[j];
+ if (!pChild) continue;
+ cmd._changeProtectedChild(pChild);
+ pChild.visit(this);
+ }
+
+ if (locGrid && locGrid._active)
+ locGrid.afterDraw(this);
+
+ cmd._dirtyFlag = 0;
+ },
+
/**
*
* Adds a child to the container with z order and tag
@@ -55,25 +111,25 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
* @param {Number} [localZOrder] Z order for drawing priority. Please refer to `setLocalZOrder(int)`
* @param {Number} [tag] An integer to identify the node easily. Please refer to `setTag(int)`
*/
- addProtectedChild: function(child, localZOrder, tag){
- cc.assert(child != null, "child must be non-nil");
- cc.assert(!child.parent, "child already added. It can't be added again");
+ addProtectedChild: function (child, localZOrder, tag) {
+ cc.assert(child != null, "child must be non-nil");
+ cc.assert(!child.parent, "child already added. It can't be added again");
localZOrder = localZOrder || child.getLocalZOrder();
- if(tag)
+ if (tag)
child.setTag(tag);
this._insertProtectedChild(child, localZOrder);
child.setParent(this);
child.setOrderOfArrival(cc.s_globalOrderOfArrival);
- if(this._running){
- child.onEnter();
+ if (this._running) {
+ child._performRecursive(cc.Node._stateCallbackType.onEnter);
// prevent onEnterTransitionDidFinish to be called twice when a node is added in onEnter
- if(this._isTransitionFinished)
- child.onEnterTransitionDidFinish();
+ if (this._isTransitionFinished)
+ child._performRecursive(cc.Node._stateCallbackType.onEnterTransitionDidFinish);
}
- if(this._cascadeColorEnabled)
+ if (this._cascadeColorEnabled)
this._renderCmd.setCascadeColorEnabledDirty();
if (this._cascadeOpacityEnabled)
this._renderCmd.setCascadeOpacityEnabledDirty();
@@ -84,11 +140,11 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
* @param {Number} tag An identifier to find the child node.
* @return {cc.Node} a Node object whose tag equals to the input parameter
*/
- getProtectedChildByTag: function(tag){
+ getProtectedChildByTag: function (tag) {
cc.assert(tag !== cc.NODE_TAG_INVALID, "Invalid tag");
var locChildren = this._protectedChildren;
- for(var i = 0, len = locChildren.length; i < len; i++)
- if(locChildren.getTag() === tag)
+ for (var i = 0, len = locChildren.length; i < len; i++)
+ if (locChildren.getTag() === tag)
return locChildren[i];
return null;
},
@@ -98,23 +154,23 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
* @param {cc.Node} child The child node which will be removed.
* @param {Boolean} [cleanup=true] true if all running actions and callbacks on the child node will be cleanup, false otherwise.
*/
- removeProtectedChild: function(child, cleanup){
- if(cleanup == null)
+ removeProtectedChild: function (child, cleanup) {
+ if (cleanup == null)
cleanup = true;
- var locChildren = this._protectedChildren;
- if(locChildren.length === 0)
+ var locChildren = this._protectedChildren;
+ if (locChildren.length === 0)
return;
var idx = locChildren.indexOf(child);
- if(idx > -1){
- if(this._running){
- child.onExitTransitionDidStart();
- child.onExit();
- }
+ if (idx > -1) {
+ if (this._running) {
+ child._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart);
+ child._performRecursive(cc.Node._stateCallbackType.onExit);
+ }
// If you don't do cleanup, the child's actions will not get removed and the
// its scheduledSelectors_ dict will not get released!
if (cleanup)
- child.cleanup();
+ child._performRecursive(cc.Node._stateCallbackType.cleanup);
// set parent nil at the end
child.setParent(null);
@@ -128,10 +184,10 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
* @param {Number} tag
* @param {Boolean} [cleanup=true]
*/
- removeProtectedChildByTag: function(tag, cleanup){
- cc.assert( tag !== cc.NODE_TAG_INVALID, "Invalid tag");
+ removeProtectedChildByTag: function (tag, cleanup) {
+ cc.assert(tag !== cc.NODE_TAG_INVALID, "Invalid tag");
- if(cleanup == null)
+ if (cleanup == null)
cleanup = true;
var child = this.getProtectedChildByTag(tag);
@@ -146,7 +202,7 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
* Removes all children from the container with a cleanup.
* @see cc.ProtectedNode#removeAllProtectedChildrenWithCleanup
*/
- removeAllProtectedChildren: function(){
+ removeAllProtectedChildren: function () {
this.removeAllProtectedChildrenWithCleanup(true);
},
@@ -154,23 +210,23 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
* Removes all children from the container, and do a cleanup to all running actions depending on the cleanup parameter.
* @param {Boolean} [cleanup=true] true if all running actions on all children nodes should be cleanup, false otherwise.
*/
- removeAllProtectedChildrenWithCleanup: function(cleanup){
- if(cleanup == null)
+ removeAllProtectedChildrenWithCleanup: function (cleanup) {
+ if (cleanup == null)
cleanup = true;
var locChildren = this._protectedChildren;
// not using detachChild improves speed here
- for (var i = 0, len = locChildren.length; i< len; i++) {
+ for (var i = 0, len = locChildren.length; i < len; i++) {
var child = locChildren[i];
// IMPORTANT:
// -1st do onExit
// -2nd cleanup
- if(this._running){
- child.onExitTransitionDidStart();
- child.onExit();
+ if (this._running) {
+ child._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart);
+ child._performRecursive(cc.Node._stateCallbackType.onExit);
}
if (cleanup)
- child.cleanup();
+ child._performRecursive(cc.Node._stateCallbackType.cleanup);
// set parent nil at the end
child.setParent(null);
}
@@ -182,8 +238,8 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
* @param {cc.Node} child An already added child node. It MUST be already added.
* @param {Number} localZOrder Z order for drawing priority. Please refer to setLocalZOrder(int)
*/
- reorderProtectedChild: function(child, localZOrder){
- cc.assert( child != null, "Child must be non-nil");
+ reorderProtectedChild: function (child, localZOrder) {
+ cc.assert(child != null, "Child must be non-nil");
this._reorderProtectedChildDirty = true;
child.setOrderOfArrival(cc.s_globalOrderOfArrival++);
child._setLocalZOrder(localZOrder);
@@ -196,27 +252,27 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
* @note Don't call this manually unless a child added needs to be removed in the same frame
*
*/
- sortAllProtectedChildren: function(){
+ sortAllProtectedChildren: function () {
if (this._reorderProtectedChildDirty) {
var _children = this._protectedChildren;
// insertion sort
- var len = _children.length, i, j, tmp;
- for(i=1; i= 0){
- if(tmp._localZOrder < _children[j]._localZOrder){
- _children[j+1] = _children[j];
- }else if(tmp._localZOrder === _children[j]._localZOrder && tmp.arrivalOrder < _children[j].arrivalOrder){
- _children[j+1] = _children[j];
- }else
+ while (j >= 0) {
+ if (tmp._localZOrder < _children[j]._localZOrder) {
+ _children[j + 1] = _children[j];
+ } else if (tmp._localZOrder === _children[j]._localZOrder && tmp.arrivalOrder < _children[j].arrivalOrder) {
+ _children[j + 1] = _children[j];
+ } else
break;
j--;
}
- _children[j+1] = tmp;
+ _children[j + 1] = tmp;
}
//don't need to check children recursively, that's done in visit of each child
@@ -224,71 +280,11 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
}
},
- _changePosition: function(){},
-
- /**
- * Stops itself and its children and protected children's all running actions and schedulers
- * @override
- */
- cleanup: function(){
- cc.Node.prototype.cleanup.call(this);
- var locChildren = this._protectedChildren;
- for(var i = 0 , len = locChildren.length; i < len; i++)
- locChildren[i].cleanup();
- },
-
- /**
- * Calls its parent's onEnter and calls its protected children's onEnter
- * @override
- */
- onEnter: function(){
- cc.Node.prototype.onEnter.call(this);
- var locChildren = this._protectedChildren;
- for(var i = 0, len = locChildren.length;i< len;i++)
- locChildren[i].onEnter();
- },
-
- /**
- *
- * Event callback that is invoked when the Node enters in the 'stage'.
- * If the Node enters the 'stage' with a transition, this event is called when the transition finishes.
- * If you override onEnterTransitionDidFinish, you shall call its parent's one, e.g. Node::onEnterTransitionDidFinish()
- *
- * @override
- */
- onEnterTransitionDidFinish: function(){
- cc.Node.prototype.onEnterTransitionDidFinish.call(this);
- var locChildren = this._protectedChildren;
- for(var i = 0, len = locChildren.length;i< len;i++)
- locChildren[i].onEnterTransitionDidFinish();
- },
-
- /**
- * Calls its parent's onExit and calls its protected children's onExit
- * @override
- */
- onExit:function(){
- cc.Node.prototype.onExit.call(this);
- var locChildren = this._protectedChildren;
- for(var i = 0, len = locChildren.length;i< len;i++)
- locChildren[i].onExit();
- },
-
- /**
- *
- * Event callback that is called every time the Node leaves the 'stage'.
- * If the Node leaves the 'stage' with a transition, this callback is called when the transition starts.
- *
- */
- onExitTransitionDidStart: function(){
- cc.Node.prototype.onExitTransitionDidStart.call(this);
- var locChildren = this._protectedChildren;
- for(var i = 0, len = locChildren.length;i< len;i++)
- locChildren[i].onExitTransitionDidStart();
+ _changePosition: function () {
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return new cc.ProtectedNode.CanvasRenderCmd(this);
else
return new cc.ProtectedNode.WebGLRenderCmd(this);
@@ -300,6 +296,6 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
* @deprecated since v3.0, please use new cc.ProtectedNode() instead.
* @return cc.ProtectedNode
*/
-cc.ProtectedNode.create = function(){
+cc.ProtectedNode.create = function () {
return new cc.ProtectedNode();
-};
\ No newline at end of file
+};
diff --git a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js
index 1e36802e0d..1ae8b1e62e 100644
--- a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js
+++ b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js
@@ -22,7 +22,7 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
+(function () {
cc.ProtectedNode.RenderCmd = {
_updateDisplayColor: function (parentColor) {
var node = this._node;
@@ -55,16 +55,16 @@
selChildren = node._children;
for (i = 0, len = selChildren.length; i < len; i++) {
item = selChildren[i];
- if (item && item._renderCmd){
+ if (item && item._renderCmd) {
item._renderCmd._updateDisplayColor(locDispColor);
item._renderCmd._updateColor();
}
}
}
selChildren = node._protectedChildren;
- for(i = 0, len = selChildren.length;i < len; i++){
+ for (i = 0, len = selChildren.length; i < len; i++) {
item = selChildren[i];
- if(item && item._renderCmd){
+ if (item && item._renderCmd) {
item._renderCmd._updateDisplayColor(locDispColor);
item._renderCmd._updateColor();
}
@@ -97,16 +97,16 @@
selChildren = node._children;
for (i = 0, len = selChildren.length; i < len; i++) {
item = selChildren[i];
- if (item && item._renderCmd){
+ if (item && item._renderCmd) {
item._renderCmd._updateDisplayOpacity(this._displayedOpacity);
item._renderCmd._updateColor();
}
}
}
selChildren = node._protectedChildren;
- for(i = 0, len = selChildren.length;i < len; i++){
+ for (i = 0, len = selChildren.length; i < len; i++) {
item = selChildren[i];
- if(item && item._renderCmd){
+ if (item && item._renderCmd) {
item._renderCmd._updateDisplayOpacity(this._displayedOpacity);
item._renderCmd._updateColor();
}
@@ -139,7 +139,7 @@
};
cc.ProtectedNode.CanvasRenderCmd = function (renderable) {
- cc.Node.CanvasRenderCmd.call(this, renderable);
+ this._rootCtor(renderable);
this._cachedParent = null;
this._cacheDirty = false;
};
@@ -147,74 +147,23 @@
var proto = cc.ProtectedNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
cc.inject(cc.ProtectedNode.RenderCmd, proto);
proto.constructor = cc.ProtectedNode.CanvasRenderCmd;
+ proto._pNodeCmdCtor = cc.ProtectedNode.CanvasRenderCmd;
- proto.visit = function(parentCmd){
- var node = this._node;
- // quick return if not visible
- if (!node._visible)
- return;
-
- //visit for canvas
- var i, j;
- var children = node._children, child;
- var locChildren = node._children, locProtectedChildren = node._protectedChildren;
- var childLen = locChildren.length, pLen = locProtectedChildren.length;
-
- this._syncStatus(parentCmd);
-
- node.sortAllChildren();
- node.sortAllProtectedChildren();
-
- var pChild;
- // draw children zOrder < 0
- for (i = 0; i < childLen; i++) {
- child = children[i];
- if (child._localZOrder < 0)
- child.visit(this);
- else
- break;
- }
- for (j = 0; j < pLen; j++) {
- pChild = locProtectedChildren[j];
- if (pChild && pChild._localZOrder < 0){
- this._changeProtectedChild(pChild);
- pChild.visit(this);
- }
- else
- break;
- }
-
- cc.renderer.pushRenderCommand(this);
-
- for (; i < childLen; i++)
- children[i] && children[i].visit(this);
- for (; j < pLen; j++){
- pChild = locProtectedChildren[j];
- if(!pChild) continue;
- this._changeProtectedChild(pChild);
- pChild.visit(this);
- }
-
- this._dirtyFlag = 0;
- this._cacheDirty = false;
- };
-
- proto.transform = function(parentCmd, recursive){
+ proto.transform = function (parentCmd, recursive) {
var node = this._node;
- if(node._changePosition)
+ if (node._changePosition)
node._changePosition();
this.originTransform(parentCmd, recursive);
var i, len, locChildren = node._protectedChildren;
- if(recursive && locChildren && locChildren.length !== 0){
- for(i = 0, len = locChildren.length; i< len; i++){
+ if (recursive && locChildren && locChildren.length !== 0) {
+ for (i = 0, len = locChildren.length; i < len; i++) {
locChildren[i]._renderCmd.transform(this, recursive);
}
}
};
- proto.pNodeVisit = proto.visit;
proto.pNodeTransform = proto.transform;
-})();
\ No newline at end of file
+})();
diff --git a/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js
index 6640c7cf9b..b22907d383 100644
--- a/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js
+++ b/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js
@@ -22,83 +22,29 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- if(!cc.Node.WebGLRenderCmd)
+(function () {
+ if (!cc.Node.WebGLRenderCmd)
return;
cc.ProtectedNode.WebGLRenderCmd = function (renderable) {
- cc.Node.WebGLRenderCmd.call(this, renderable);
+ this._rootCtor(renderable);
};
var proto = cc.ProtectedNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
cc.inject(cc.ProtectedNode.RenderCmd, proto);
proto.constructor = cc.ProtectedNode.WebGLRenderCmd;
+ proto._pNodeCmdCtor = cc.ProtectedNode.WebGLRenderCmd;
- proto.visit = function(parentCmd){
- var node = this._node;
- // quick return if not visible
- if (!node._visible)
- return;
- var i, j;
-
- this._syncStatus(parentCmd);
-
- var locGrid = node.grid;
- if (locGrid && locGrid._active)
- locGrid.beforeDraw();
-
- var locChildren = node._children, locProtectedChildren = node._protectedChildren;
- var childLen = locChildren.length, pLen = locProtectedChildren.length;
- node.sortAllChildren();
- node.sortAllProtectedChildren();
-
- var pChild;
- // draw children zOrder < 0
- for (i = 0; i < childLen; i++) {
- if (locChildren[i] && locChildren[i]._localZOrder < 0)
- locChildren[i].visit(this);
- else
- break;
- }
- for(j = 0; j < pLen; j++){
- pChild = locProtectedChildren[j];
- if (pChild && pChild._localZOrder < 0){
- this._changeProtectedChild(pChild);
- pChild.visit(this);
- }else
- break;
- }
-
- cc.renderer.pushRenderCommand(this);
-
- // draw children zOrder >= 0
- for (; i < childLen; i++) {
- locChildren[i] && locChildren[i].visit(this);
- }
- for (; j < pLen; j++) {
- pChild = locProtectedChildren[j];
- if(!pChild) continue;
- this._changeProtectedChild(pChild);
- pChild.visit(this);
- }
-
- if (locGrid && locGrid._active)
- locGrid.afterDraw(node);
-
- this._dirtyFlag = 0;
- };
-
- proto.transform = function(parentCmd, recursive){
+ proto.transform = function (parentCmd, recursive) {
this.originTransform(parentCmd, recursive);
var i, len,
locChildren = this._node._protectedChildren;
- if(recursive && locChildren && locChildren.length !== 0){
- for(i = 0, len = locChildren.length; i< len; i++){
+ if (recursive && locChildren && locChildren.length !== 0) {
+ for (i = 0, len = locChildren.length; i < len; i++) {
locChildren[i]._renderCmd.transform(this, recursive);
}
}
};
- proto.pNodeVisit = proto.visit;
proto.pNodeTransform = proto.transform;
-})();
\ No newline at end of file
+})();
diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js
index dcb9215268..01fa9eb0b6 100644
--- a/extensions/ccui/base-classes/UIScale9Sprite.js
+++ b/extensions/ccui/base-classes/UIScale9Sprite.js
@@ -3,6 +3,7 @@
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
Copyright (c) 2012 Neofect. All rights reserved.
+ Copyright (c) 2016 zilongshanren. All rights reserved.
http://www.cocos2d-x.org
@@ -26,6 +27,293 @@
Created by Jung Sang-Taik on 2012-03-16
****************************************************************************/
+(function () {
+
+var dataPool = {
+ _pool: {},
+ _lengths: [],
+ put: function (data) {
+ var length = data.length;
+ if (!this._pool[length]) {
+ this._pool[length] = [data];
+ this._lengths.push(length);
+ this._lengths.sort();
+ }
+ else {
+ this._pool[length].push(data);
+ }
+ },
+ get: function (length) {
+ var id;
+ for (var i = 0; i < this._lengths.length; i++) {
+ if (this._lengths[i] >= length) {
+ id = this._lengths[i];
+ break;
+ }
+ }
+ if (id) {
+ return this._pool[id].pop();
+ }
+ else {
+ return undefined;
+ }
+ }
+};
+
+var FIX_ARTIFACTS_BY_STRECHING_TEXEL = cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL, cornerId = [], webgl;
+
+
+var simpleQuadGenerator = {
+ _rebuildQuads_base: function (sprite, spriteFrame, contentSize, isTrimmedContentSize) {
+ //build vertices
+ var vertices = sprite._vertices,
+ wt = sprite._renderCmd._worldTransform,
+ l, b, r, t;
+ if (isTrimmedContentSize) {
+ l = 0;
+ b = 0;
+ r = contentSize.width;
+ t = contentSize.height;
+ } else {
+ var originalSize = spriteFrame._originalSize;
+ var rect = spriteFrame._rect;
+ var offset = spriteFrame._offset;
+ var scaleX = contentSize.width / originalSize.width;
+ var scaleY = contentSize.height / originalSize.height;
+ var trimmLeft = offset.x + (originalSize.width - rect.width) / 2;
+ var trimmRight = offset.x - (originalSize.width - rect.width) / 2;
+ var trimmedBottom = offset.y + (originalSize.height - rect.height) / 2;
+ var trimmedTop = offset.y - (originalSize.height - rect.height) / 2;
+
+ l = trimmLeft * scaleX;
+ b = trimmedBottom * scaleY;
+ r = contentSize.width + trimmRight * scaleX;
+ t = contentSize.height + trimmedTop * scaleY;
+ }
+
+ if (vertices.length < 8) {
+ dataPool.put(vertices);
+ vertices = dataPool.get(8) || new Float32Array(8);
+ sprite._vertices = vertices;
+ }
+ // bl, br, tl, tr
+ if (webgl) {
+ vertices[0] = l * wt.a + b * wt.c + wt.tx;
+ vertices[1] = l * wt.b + b * wt.d + wt.ty;
+ vertices[2] = r * wt.a + b * wt.c + wt.tx;
+ vertices[3] = r * wt.b + b * wt.d + wt.ty;
+ vertices[4] = l * wt.a + t * wt.c + wt.tx;
+ vertices[5] = l * wt.b + t * wt.d + wt.ty;
+ vertices[6] = r * wt.a + t * wt.c + wt.tx;
+ vertices[7] = r * wt.b + t * wt.d + wt.ty;
+ }
+ else {
+ vertices[0] = l;
+ vertices[1] = b;
+ vertices[2] = r;
+ vertices[3] = b;
+ vertices[4] = l;
+ vertices[5] = t;
+ vertices[6] = r;
+ vertices[7] = t;
+ }
+
+ cornerId[0] = 0;
+ cornerId[1] = 2;
+ cornerId[2] = 4;
+ cornerId[3] = 6;
+
+ //build uvs
+ if (sprite._uvsDirty) {
+ this._calculateUVs(sprite, spriteFrame);
+ }
+
+ sprite._vertCount = 4;
+ },
+
+ _calculateUVs: function (sprite, spriteFrame) {
+ var uvs = sprite._uvs;
+ var atlasWidth = spriteFrame._texture._pixelsWide;
+ var atlasHeight = spriteFrame._texture._pixelsHigh;
+ var textureRect = spriteFrame._rect;
+
+ if (uvs.length < 8) {
+ dataPool.put(uvs);
+ uvs = dataPool.get(8) || new Float32Array(8);
+ sprite._uvs = uvs;
+ }
+
+ //uv computation should take spritesheet into account.
+ var l, b, r, t;
+ var texelCorrect = FIX_ARTIFACTS_BY_STRECHING_TEXEL ? 0.5 : 0;
+
+ if (spriteFrame._rotated) {
+ l = (textureRect.x + texelCorrect) / atlasWidth;
+ b = (textureRect.y + textureRect.width - texelCorrect) / atlasHeight;
+ r = (textureRect.x + textureRect.height - texelCorrect) / atlasWidth;
+ t = (textureRect.y + texelCorrect) / atlasHeight;
+ uvs[0] = l; uvs[1] = t;
+ uvs[2] = l; uvs[3] = b;
+ uvs[4] = r; uvs[5] = t;
+ uvs[6] = r; uvs[7] = b;
+ }
+ else {
+ l = (textureRect.x + texelCorrect) / atlasWidth;
+ b = (textureRect.y + textureRect.height - texelCorrect) / atlasHeight;
+ r = (textureRect.x + textureRect.width - texelCorrect) / atlasWidth;
+ t = (textureRect.y + texelCorrect) / atlasHeight;
+ uvs[0] = l; uvs[1] = b;
+ uvs[2] = r; uvs[3] = b;
+ uvs[4] = l; uvs[5] = t;
+ uvs[6] = r; uvs[7] = t;
+ }
+ }
+};
+
+var scale9QuadGenerator = {
+ x: new Array(4),
+ y: new Array(4),
+ _rebuildQuads_base: function (sprite, spriteFrame, contentSize, insetLeft, insetRight, insetTop, insetBottom) {
+ //build vertices
+ var vertices = sprite._vertices;
+ var wt = sprite._renderCmd._worldTransform;
+ var leftWidth, centerWidth, rightWidth;
+ var topHeight, centerHeight, bottomHeight;
+ var rect = spriteFrame._rect;
+
+ leftWidth = insetLeft;
+ rightWidth = insetRight;
+ centerWidth = rect.width - leftWidth - rightWidth;
+ topHeight = insetTop;
+ bottomHeight = insetBottom;
+ centerHeight = rect.height - topHeight - bottomHeight;
+
+ var preferSize = contentSize;
+ var sizableWidth = preferSize.width - leftWidth - rightWidth;
+ var sizableHeight = preferSize.height - topHeight - bottomHeight;
+ var xScale = preferSize.width / (leftWidth + rightWidth);
+ var yScale = preferSize.height / (topHeight + bottomHeight);
+ xScale = xScale > 1 ? 1 : xScale;
+ yScale = yScale > 1 ? 1 : yScale;
+ sizableWidth = sizableWidth < 0 ? 0 : sizableWidth;
+ sizableHeight = sizableHeight < 0 ? 0 : sizableHeight;
+ var x = this.x;
+ var y = this.y;
+ x[0] = 0;
+ x[1] = leftWidth * xScale;
+ x[2] = x[1] + sizableWidth;
+ x[3] = preferSize.width;
+ y[0] = 0;
+ y[1] = bottomHeight * yScale;
+ y[2] = y[1] + sizableHeight;
+ y[3] = preferSize.height;
+
+ if (vertices.length < 32) {
+ dataPool.put(vertices);
+ vertices = dataPool.get(32) || new Float32Array(32);
+ sprite._vertices = vertices;
+ }
+ var offset = 0, row, col;
+ if (webgl) {
+ for (row = 0; row < 4; row++) {
+ for (col = 0; col < 4; col++) {
+ vertices[offset] = x[col] * wt.a + y[row] * wt.c + wt.tx;
+ vertices[offset+1] = x[col] * wt.b + y[row] * wt.d + wt.ty;
+ offset += 2;
+ }
+ }
+ }
+ else {
+ for (row = 0; row < 4; row++) {
+ for (col = 0; col < 4; col++) {
+ vertices[offset] = x[col];
+ vertices[offset+1] = y[row];
+ offset += 2;
+ }
+ }
+ }
+
+ cornerId[0] = 0;
+ cornerId[1] = 6;
+ cornerId[2] = 24;
+ cornerId[3] = 30;
+
+ //build uvs
+ if (sprite._uvsDirty) {
+ this._calculateUVs(sprite, spriteFrame, insetLeft, insetRight, insetTop, insetBottom);
+ }
+ },
+
+ _calculateUVs: function (sprite, spriteFrame, insetLeft, insetRight, insetTop, insetBottom) {
+ var uvs = sprite._uvs;
+ var rect = spriteFrame._rect;
+ var atlasWidth = spriteFrame._texture._pixelsWide;
+ var atlasHeight = spriteFrame._texture._pixelsHigh;
+
+ //caculate texture coordinate
+ var leftWidth, centerWidth, rightWidth;
+ var topHeight, centerHeight, bottomHeight;
+ var textureRect = spriteFrame._rect;
+
+ leftWidth = insetLeft;
+ rightWidth = insetRight;
+ centerWidth = rect.width - leftWidth - rightWidth;
+ topHeight = insetTop;
+ bottomHeight = insetBottom;
+ centerHeight = rect.height - topHeight - bottomHeight;
+
+ if (uvs.length < 32) {
+ dataPool.put(uvs);
+ uvs = dataPool.get(32) || new Float32Array(32);
+ sprite._uvs = uvs;
+ }
+
+ //uv computation should take spritesheet into account.
+ var u = this.x;
+ var v = this.y;
+ var texelCorrect = FIX_ARTIFACTS_BY_STRECHING_TEXEL ? 0.5 : 0;
+ var offset = 0, row, col;
+
+ if (spriteFrame._rotated) {
+ u[0] = (textureRect.x + texelCorrect) / atlasWidth;
+ u[1] = (bottomHeight + textureRect.x) / atlasWidth;
+ u[2] = (bottomHeight + centerHeight + textureRect.x) / atlasWidth;
+ u[3] = (textureRect.x + textureRect.height - texelCorrect) / atlasWidth;
+
+ v[3] = (textureRect.y + texelCorrect) / atlasHeight;
+ v[2] = (leftWidth + textureRect.y) / atlasHeight;
+ v[1] = (leftWidth + centerWidth + textureRect.y) / atlasHeight;
+ v[0] = (textureRect.y + textureRect.width - texelCorrect) / atlasHeight;
+
+ for (row = 0; row < 4; row++) {
+ for (col = 0; col < 4; col++) {
+ uvs[offset] = u[row];
+ uvs[offset+1] = v[3-col];
+ offset += 2;
+ }
+ }
+ }
+ else {
+ u[0] = (textureRect.x + texelCorrect) / atlasWidth;
+ u[1] = (leftWidth + textureRect.x) / atlasWidth;
+ u[2] = (leftWidth + centerWidth + textureRect.x) / atlasWidth;
+ u[3] = (textureRect.x + textureRect.width - texelCorrect) / atlasWidth;
+
+ v[3] = (textureRect.y + texelCorrect) / atlasHeight;
+ v[2] = (topHeight + textureRect.y) / atlasHeight;
+ v[1] = (topHeight + centerHeight + textureRect.y) / atlasHeight;
+ v[0] = (textureRect.y + textureRect.height - texelCorrect) / atlasHeight;
+
+ for (row = 0; row < 4; row++) {
+ for (col = 0; col < 4; col++) {
+ uvs[offset] = u[col];
+ uvs[offset+1] = v[row];
+ offset += 2;
+ }
+ }
+ }
+ }
+};
/**
*
@@ -35,7 +323,6 @@
* to specific areas of a sprite. With 9-slice scaling (3x3 grid),
* you can ensure that the sprite does not become distorted when
* scaled.
- * @note: it will refactor in v3.1
* @see http://yannickloriot.com/library/ios/cccontrolextension/Classes/CCScale9Sprite.html
*
* @class
@@ -50,161 +337,39 @@
*/
ccui.Scale9Sprite = cc.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{
- _spriteRect: null,
- _capInsetsInternal: null,
- _positionsAreDirty: false,
-
+ //resource data, could be async loaded.
+ _spriteFrame: null,
_scale9Image: null,
- _topLeft: null,
- _top: null,
- _topRight: null,
- _left: null,
- _centre: null,
- _right: null,
- _bottomLeft: null,
- _bottom: null,
- _bottomRight: null,
-
- _scale9Enabled: true,
- _brightState: 0,
- _renderers: null,
-
- _opacityModifyRGB: false,
- _originalSize: null,
- _preferredSize: null,
- _opacity: 0,
- _color: null,
- _capInsets: null,
+ //scale 9 data
_insetLeft: 0,
- _insetTop: 0,
_insetRight: 0,
+ _insetTop: 0,
_insetBottom: 0,
-
- _spriteFrameRotated: false,
- _textureLoaded:false,
- _className:"Scale9Sprite",
+ //blend function
+ _blendFunc: null,
+ //sliced or simple
+ _renderingType: 1,
+ //bright or not
+ _brightState: 0,
+ _opacityModifyRGB: false,
+ //rendering quads shared by canvas and webgl
+ _rawVerts: null,
+ _rawUvs: null,
+ _vertices: null,
+ _uvs: null,
+ _vertCount: 0,
+ _quadsDirty: true,
+ _uvsDirty: true,
+ _isTriangle: false,
+ _isTrimmedContentSize: false,
//v3.3
_flippedX: false,
_flippedY: false,
/**
- * return texture is loaded
- * @returns {boolean}
- */
- textureLoaded:function(){
- return this._textureLoaded;
- },
-
- /**
- * add texture loaded event listener
- * @param {Function} callback
- * @param {Object} target
- * @deprecated since 3.1, please use addEventListener instead
- */
- addLoadedEventListener:function(callback, target){
- this.addEventListener("load", callback, target);
- },
-
- _updateCapInset: function () {
- var insets, locInsetLeft = this._insetLeft, locInsetTop = this._insetTop, locInsetRight = this._insetRight;
- var locSpriteRect = this._spriteRect, locInsetBottom = this._insetBottom;
- if (locInsetLeft === 0 && locInsetTop === 0 && locInsetRight === 0 && locInsetBottom === 0) {
- insets = cc.rect(0, 0, 0, 0);
- } else {
- insets = this._spriteFrameRotated ? cc.rect(locInsetBottom, locInsetLeft,
- locSpriteRect.width - locInsetRight - locInsetLeft,
- locSpriteRect.height - locInsetTop - locInsetBottom) :
- cc.rect(locInsetLeft, locInsetTop,
- locSpriteRect.width - locInsetLeft - locInsetRight,
- locSpriteRect.height - locInsetTop - locInsetBottom);
- }
- this.setCapInsets(insets);
- },
-
- _updatePositions: function () {
- // Check that instances are non-NULL
- if (!((this._topLeft) && (this._topRight) && (this._bottomRight) &&
- (this._bottomLeft) && (this._centre))) {
- // if any of the above sprites are NULL, return
- return;
- }
-
- var size = this._contentSize;
- var locTopLeft = this._topLeft, locTopRight = this._topRight, locBottomRight = this._bottomRight, locBottomLeft = this._bottomLeft;
- var locLeft = this._left, locRight = this._right, locTop = this._top, locBottom = this._bottom;
- var locCenter = this._centre, locCenterContentSize = this._centre.getContentSize();
- var locTopLeftContentSize = locTopLeft.getContentSize();
- var locBottomLeftContentSize = locBottomLeft.getContentSize();
-
- var sizableWidth = size.width - locTopLeftContentSize.width - locTopRight.getContentSize().width;
- var sizableHeight = size.height - locTopLeftContentSize.height - locBottomRight.getContentSize().height;
-
- var horizontalScale = sizableWidth / locCenterContentSize.width;
- var verticalScale = sizableHeight / locCenterContentSize.height;
-
- var rescaledWidth = locCenterContentSize.width * horizontalScale;
- var rescaledHeight = locCenterContentSize.height * verticalScale;
-
- var leftWidth = locBottomLeftContentSize.width;
- var bottomHeight = locBottomLeftContentSize.height;
- var centerOffset = cc.p(this._offset.x * horizontalScale, this._offset.y*verticalScale);
-
- if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
- //browser is in canvas mode, need to manually control rounding to prevent overlapping pixels
- var roundedRescaledWidth = Math.round(rescaledWidth);
- if (rescaledWidth !== roundedRescaledWidth) {
- rescaledWidth = roundedRescaledWidth;
- horizontalScale = rescaledWidth / locCenterContentSize.width;
- }
- var roundedRescaledHeight = Math.round(rescaledHeight);
- if (rescaledHeight !== roundedRescaledHeight) {
- rescaledHeight = roundedRescaledHeight;
- verticalScale = rescaledHeight / locCenterContentSize.height;
- }
- }
-
- locCenter.setScaleX(horizontalScale);
- locCenter.setScaleY(verticalScale);
-
- locBottomLeft.setAnchorPoint(1, 1);
- locBottomLeft.setPosition(leftWidth,bottomHeight);
-
- locBottomRight.setAnchorPoint(0, 1);
- locBottomRight.setPosition(leftWidth+rescaledWidth,bottomHeight);
-
-
- locTopLeft.setAnchorPoint(1, 0);
- locTopLeft.setPosition(leftWidth, bottomHeight+rescaledHeight);
-
- locTopRight.setAnchorPoint(0, 0);
- locTopRight.setPosition(leftWidth+rescaledWidth, bottomHeight+rescaledHeight);
-
- locLeft.setAnchorPoint(1, 0.5);
- locLeft.setPosition(leftWidth, bottomHeight+rescaledHeight/2 + centerOffset.y);
- locLeft.setScaleY(verticalScale);
-
- locRight.setAnchorPoint(0, 0.5);
- locRight.setPosition(leftWidth+rescaledWidth,bottomHeight+rescaledHeight/2 + centerOffset.y);
- locRight.setScaleY(verticalScale);
-
- locTop.setAnchorPoint(0.5, 0);
- locTop.setPosition(leftWidth+rescaledWidth/2 + centerOffset.x,bottomHeight+rescaledHeight);
- locTop.setScaleX(horizontalScale);
-
- locBottom.setAnchorPoint(0.5, 1);
- locBottom.setPosition(leftWidth+rescaledWidth/2 + centerOffset.x,bottomHeight);
- locBottom.setScaleX(horizontalScale);
-
- locCenter.setAnchorPoint(0.5, 0.5);
- locCenter.setPosition(leftWidth+rescaledWidth/2 + centerOffset.x, bottomHeight+rescaledHeight/2 + centerOffset.y);
- locCenter.setScaleX(horizontalScale);
- locCenter.setScaleY(verticalScale);
- },
-
- /**
- * Constructor function. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ * Constructor function.
* @function
* @param {string|cc.SpriteFrame} file file name of texture or a SpriteFrame
* @param {cc.Rect} rectOrCapInsets
@@ -213,14 +378,18 @@ ccui.Scale9Sprite = cc.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprit
*/
ctor: function (file, rectOrCapInsets, capInsets) {
cc.Node.prototype.ctor.call(this);
+
+ //for async texture load
this._loader = new cc.Sprite.LoadManager();
- this._spriteRect = cc.rect(0, 0, 0, 0);
- this._capInsetsInternal = cc.rect(0, 0, 0, 0);
- this._originalSize = cc.size(0, 0);
- this._preferredSize = cc.size(0, 0);
- this._capInsets = cc.rect(0, 0, 0, 0);
- this._renderers = [];
+ this._renderCmd.setState(this._brightState);
+ this._blendFunc = cc.BlendFunc._alphaPremultiplied();
+ this.setAnchorPoint(cc.p(0.5, 0.5));
+ // Init vertex data for simple
+ this._rawVerts = null;
+ this._rawUvs = null;
+ this._vertices = dataPool.get(8) || new Float32Array(8);
+ this._uvs = dataPool.get(8) || new Float32Array(8);
if (file !== undefined) {
if (file instanceof cc.SpriteFrame)
@@ -233,97 +402,15 @@ ccui.Scale9Sprite = cc.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprit
this.initWithFile(file, rectOrCapInsets, capInsets);
}
}
- else {
- this.init();
- this.setCascadeColorEnabled(true);
- this.setCascadeOpacityEnabled(true);
- this.setAnchorPoint(0.5, 0.5);
- this._positionsAreDirty = true;
- }
- },
-
- getSprite: function () {
- return this._scale9Image;
- },
- /** Original sprite's size. */
- getOriginalSize: function () {
- return cc.size(this._originalSize);
- },
- //if the preferredSize component is given as -1, it is ignored
- getPreferredSize: function () {
- return cc.size(this._preferredSize);
- },
- _getPreferredWidth: function () {
- return this._preferredSize.width;
- },
- _getPreferredHeight: function () {
- return this._preferredSize.height;
- },
-
- _asyncSetPreferredSize: function () {
- this.removeEventListener('load', this._asyncSetPreferredSize, this);
- this.setPreferredSize(this._cachePreferredSize);
- this._cachePreferredSize = null;
- },
- setPreferredSize: function (preferredSize) {
- if (!preferredSize) return;
- if (!this._textureLoaded) {
- this._cachePreferredSize = preferredSize;
- this.removeEventListener('load', this._asyncSetPreferredSize, this);
- this.addEventListener('load', this._asyncSetPreferredSize, this);
- return false;
+ if (webgl === undefined) {
+ webgl = cc._renderType === cc.game.RENDER_TYPE_WEBGL;
}
- this.setContentSize(preferredSize);
- this._preferredSize = preferredSize;
-
- if (this._positionsAreDirty) {
- this._updatePositions();
- this._positionsAreDirty = false;
- this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.cacheDirty);
- }
- },
- _setPreferredWidth: function (value) {
- this._setWidth(value);
- this._preferredSize.width = value;
- },
- _setPreferredHeight: function (value) {
- this._setHeight(value);
- this._preferredSize.height = value;
- },
-
- /** Opacity: conforms to CCRGBAProtocol protocol */
- setOpacity: function (opacity) {
- cc.Node.prototype.setOpacity.call(this, opacity);
- if(this._scale9Enabled) {
- var pChildren = this._renderers;
- for(var i=0; i 0 && rotatedCenterBounds.height > 0 )
- this._renderers.push(this._centre);
-
- // Top
- if(!this._top)
- this._top = new cc.Sprite();
- this._top.initWithTexture(selTexture, rotatedCenterTopBounds, rotated);
- if(rotatedCenterTopBounds.width > 0 && rotatedCenterTopBounds.height > 0 )
- this._renderers.push(this._top);
-
- // Bottom
- if(!this._bottom)
- this._bottom = new cc.Sprite();
- this._bottom.initWithTexture(selTexture, rotatedCenterBottomBounds, rotated);
- if(rotatedCenterBottomBounds.width > 0 && rotatedCenterBottomBounds.height > 0 )
- this._renderers.push(this._bottom);
-
- // Left
- if(!this._left)
- this._left = new cc.Sprite();
- this._left.initWithTexture(selTexture, rotatedLeftCenterBounds, rotated);
- if(rotatedLeftCenterBounds.width > 0 && rotatedLeftCenterBounds.height > 0 )
- this._renderers.push(this._left);
-
- // Right
- if(!this._right)
- this._right = new cc.Sprite();
- this._right.initWithTexture(selTexture, rotatedRightCenterBounds, rotated);
- if(rotatedRightCenterBounds.width > 0 && rotatedRightCenterBounds.height > 0 )
- this._renderers.push(this._right);
-
- // Top left
- if(!this._topLeft)
- this._topLeft = new cc.Sprite();
- this._topLeft.initWithTexture(selTexture, rotatedLeftTopBounds, rotated);
- if(rotatedLeftTopBounds.width > 0 && rotatedLeftTopBounds.height > 0 )
- this._renderers.push(this._topLeft);
-
- // Top right
- if(!this._topRight)
- this._topRight = new cc.Sprite();
- this._topRight.initWithTexture(selTexture, rotatedRightTopBounds, rotated);
- if(rotatedRightTopBounds.width > 0 && rotatedRightTopBounds.height > 0 )
- this._renderers.push(this._topRight);
-
- // Bottom left
- if(!this._bottomLeft)
- this._bottomLeft = new cc.Sprite();
- this._bottomLeft.initWithTexture(selTexture, rotatedLeftBottomBounds, rotated);
- if(rotatedLeftBottomBounds.width > 0 && rotatedLeftBottomBounds.height > 0 )
- this._renderers.push(this._bottomLeft);
-
- // Bottom right
- if(!this._bottomRight)
- this._bottomRight = new cc.Sprite();
- this._bottomRight.initWithTexture(selTexture, rotatedRightBottomBounds, rotated);
- if(rotatedRightBottomBounds.width > 0 && rotatedRightBottomBounds.height > 0 )
- this._renderers.push(this._bottomRight);
+ else {
+ this._blendFunc.src = blendFunc || cc.BLEND_SRC;
+ this._blendFunc.dst = dst || cc.BLEND_DST;
+ }
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty);
},
+
/**
- * @brief Update Scale9Sprite with a specified sprite.
+ * Returns the blending function that is currently being used.
*
- * @param sprite A sprite pointer.
- * @param spriteRect A delimitation zone.
- * @param spriteFrameRotated Whether the sprite is rotated or not.
- * @param offset The offset when slice the sprite.
- * @param originalSize The origial size of the sprite.
- * @param capInsets The Values to use for the cap insets.
- * @return True if update success, false otherwise.
+ * @return A BlendFunc structure with source and destination factor which specified pixel arithmetic.
*/
- updateWithSprite: function(sprite, spriteRect, spriteFrameRotated, offset, originalSize, capInsets) {
- if (!sprite) return false;
-
- this._loader.clear();
- this._textureLoaded = sprite._textureLoaded;
- if (!sprite._textureLoaded) {
- this._loader.once(sprite, function () {
- this.updateWithSprite(sprite, spriteRect, spriteFrameRotated, offset, originalSize, capInsets);
- this.dispatchEvent("load");
- }, this);
- return false;
- }
+ getBlendFunc: function () {
+ return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst);
+ },
- this._scale9Image = sprite;
- if(!this._scale9Image) return false;
- var tmpTexture = this._scale9Image.getTexture();
- this._textureLoaded = tmpTexture && tmpTexture.isLoaded();
-
- var spriteFrame = sprite.getSpriteFrame();
- if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
- // Clipping will reset the properties - canvas mode
- if (spriteFrame && tmpTexture._htmlElementObj instanceof window.HTMLCanvasElement) {
- spriteFrameRotated = false;
- spriteRect = { x: 0, y: 0, height: spriteRect.height, width: spriteRect.width }
- }
- }
+ setPreferredSize: function (preferredSize) {
+ if (!preferredSize || cc.sizeEqualToSize(this._contentSize, preferredSize)) return;
+ this.setContentSize(preferredSize);
+ },
- var opacity = this.getOpacity();
- var color = this.getColor();
- this._renderers.length = 0;
- var rect = spriteRect;
- var size = originalSize;
+ getPreferredSize: function () {
+ return this.getContentSize();
+ },
- if(cc._rectEqualToZero(rect)) {
- var textureSize = tmpTexture.getContentSize();
- rect = cc.rect(0, 0, textureSize.width, textureSize.height);
+ // overrides
+ setContentSize: function (width, height) {
+ if (height === undefined) {
+ height = width.height;
+ width = width.width;
+ }
+ if (width === this._contentSize.width && height === this._contentSize.height) {
+ return;
}
- if(size.width === 0 && size.height === 0)
- size = cc.size(rect.width, rect.height);
- this._capInsets = capInsets;
- this._spriteRect = rect;
- this._offset = offset;
- this._spriteFrameRotated = spriteFrameRotated;
- this._originalSize = size;
- this._preferredSize = size;
- this._capInsetsInternal = capInsets;
- if(this._scale9Enabled)
- this.createSlicedSprites();
- else
- this._scale9Image.initWithTexture(tmpTexture, this._spriteRect, this._spriteFrameRotated);
- this.setState(this._brightState);
- this.setContentSize(size);
- this.setOpacity(opacity);
- this.setColor(color);
- return true;
+ cc.Node.prototype.setContentSize.call(this, width, height);
+ this._quadsDirty = true;
},
- /**
- * Update the scale9Sprite with a SpriteBatchNode.
- * @param {cc.SpriteBatchNode} batchNode
- * @param {cc.Rect} originalRect
- * @param {boolean} rotated
- * @param {cc.Rect} capInsets
- * @returns {boolean}
- */
- updateWithBatchNode: function (batchNode, originalRect, rotated, capInsets) {
- if (!batchNode) {
- return false;
- }
- var texture = batchNode.getTexture();
- this._loader.clear();
- var loaded = this._textureLoaded = texture.isLoaded();
- if (!loaded) {
- this._loader.once(texture, function () {
- this.updateWithBatchNode(batchNode, originalRect, rotated, capInsets);
- this.dispatchEvent("load");
- }, this);
- return false;
+ getContentSize: function () {
+ if(this._renderingType === ccui.Scale9Sprite.RenderingType.SIMPLE) {
+ if(this._spriteFrame) {
+ return this._spriteFrame._originalSize;
+ }
+ return cc.size(this._contentSize);
+ } else {
+ return cc.size(this._contentSize);
}
+ },
- var sprite = new cc.Sprite(texture);
- var pos = cc.p(0,0);
- var originalSize = cc.size(originalRect.width,originalRect.height);
+ _setWidth: function (value) {
+ cc.Node.prototype._setWidth.call(this, value);
+ this._quadsDirty = true;
+ },
- return this.updateWithSprite(sprite, originalRect, rotated, pos, originalSize, capInsets);
+ _setHeight: function (value) {
+ cc.Node.prototype._setHeight.call(this, value);
+ this._quadsDirty = true;
},
/**
- * set the sprite frame of ccui.Scale9Sprite
- * @param {cc.SpriteFrame} spriteFrame
- * @param {cc.rect} capInsets
+ * Change the state of 9-slice sprite.
+ * @see `State`
+ * @param state A enum value in State.
*/
- setSpriteFrame: function (spriteFrame, capInsets) {
- // Reset insets
- capInsets = capInsets || cc.rect();
- var texture = spriteFrame.getTexture();
- this._textureLoaded = texture._textureLoaded;
- this._loader.clear();
- if (!texture._textureLoaded) {
- this._loader.once(spriteFrame, function () {
- this.setSpriteFrame(spriteFrame, capInsets);
- this.dispatchEvent("load");
- }, this);
- return false;
- }
+ setState: function (state) {
+ this._brightState = state;
+ this._renderCmd.setState(state);
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty);
+ },
- var sprite = new cc.Sprite(spriteFrame.getTexture());
- this.updateWithSprite(sprite, spriteFrame.getRect(),spriteFrame.isRotated(),spriteFrame.getOffset(),spriteFrame.getOriginalSize(),capInsets);
- this._insetLeft = capInsets.x;
- this._insetTop = capInsets.y;
- this._insetRight = this._originalSize.width - this._insetLeft - capInsets.width;
- this._insetBottom = this._originalSize.height - this._insetTop - capInsets.height;
+ /**
+ * Query the current bright state.
+ * @return @see `State`
+ */
+ getState: function () {
+ return this._brightState;
},
- //v3.3
/**
- * Sets ccui.Scale9Sprite's state
- * @since v3.3
- * @param {Number} state
+ * change the rendering type, could be simple or slice
+ * @return @see `RenderingType`
*/
- setState: function (state) {
- if (state === ccui.Scale9Sprite.state.NORMAL || state === ccui.Scale9Sprite.state.GRAY) {
- this._brightState = state;
- this._renderCmd.setState(state);
- }
+ setRenderingType: function (type) {
+ if (this._renderingType === type) return;
+
+ this._renderingType = type;
+ this._quadsDirty = true;
+ this._uvsDirty = true;
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty);
},
/**
- * @brief Toggle 9-slice feature.
- * If Scale9Sprite is 9-slice disabled, the Scale9Sprite will rendered as a normal sprite.
- * @param {boolean} enabled True to enable 9-slice, false otherwise.
+ * get the rendering type, could be simple or slice
+ * @return @see `RenderingType`
*/
- setScale9Enabled: function (enabled) {
- if (this._scale9Enabled === enabled)
- {
- return;
- }
- this._scale9Enabled = enabled;
- this._renderers.length = 0;
- //we must invalide the transform when toggling scale9enabled
- cc.Node.transformDirty = true;
- if (this._scale9Enabled) {
- if (this._scale9Image) {
- this.updateWithSprite(this._scale9Image,
- this._spriteRect,
- this._spriteFrameRotated,
- this._offset,
- this._originalSize,
- this._capInsets);
- }
- }
- this._positionsAreDirty = true;
+ getRenderingType: function () {
+ return this._renderingType;
},
-
- _setRenderersPosition: function() {
- if(this._positionsAreDirty) {
- this._updatePositions();
- this._adjustScale9ImagePosition();
- this._positionsAreDirty = false;
- }
+ /**
+ * change the left border of 9 slice sprite, it should be specified before trimmed.
+ * @param insetLeft left border.
+ */
+ setInsetLeft: function (insetLeft) {
+ this._insetLeft = insetLeft;
+ this._quadsDirty = true;
+ this._uvsDirty = true;
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty);
},
-
- _adjustScale9ImagePosition: function() {
- var image = this._scale9Image;
- var contentSize = this._contentSize;
- if(image) {
- image.x = contentSize.width * image.getAnchorPoint().x;
- image.y = contentSize.height * image.getAnchorPoint().y;
- }
+ /**
+ * get the left border of 9 slice sprite, the result is specified before trimmed.
+ * @return left border.
+ */
+ getInsetLeft: function () {
+ return this._insetLeft;
},
-
- _adjustScale9ImageScale: function() {
- var image = this._scale9Image;
- var contentSize = this._contentSize;
- if(image) {
- image.setScale(contentSize.width/image.width, contentSize.height/image.height);
- }
+ /**
+ * change the top border of 9 slice sprite, it should be specified before trimmed.
+ * @param insetTop top border.
+ */
+ setInsetTop: function (insetTop) {
+ this._insetTop = insetTop;
+ this._quadsDirty = true;
+ this._uvsDirty = true;
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty);
},
/**
- * Sets whether the widget should be flipped horizontally or not.
- * @since v3.3
- * @param flippedX true if the widget should be flipped horizontally, false otherwise.
+ * get the top border of 9 slice sprite, the result is specified before trimmed.
+ * @return top border.
*/
- setFlippedX: function(flippedX){
- var realScale = this.getScaleX();
- this._flippedX = flippedX;
- this.setScaleX(realScale);
- this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.cacheDirty);
+ getInsetTop: function () {
+ return this._insetTop;
},
/**
- *
- * Returns the flag which indicates whether the widget is flipped horizontally or not.
- *
- * It only flips the texture of the widget, and not the texture of the widget's children.
- * Also, flipping the texture doesn't alter the anchorPoint.
- * If you want to flip the anchorPoint too, and/or to flip the children too use:
- * widget->setScaleX(sprite->getScaleX() * -1);
- *
- * @since v3.3
- * @return {Boolean} true if the widget is flipped horizontally, false otherwise.
+ * change the right border of 9 slice sprite, it should be specified before trimmed.
+ * @param insetRight right border.
*/
- isFlippedX: function(){
- return this._flippedX;
+ setInsetRight: function (insetRight) {
+ this._insetRight = insetRight;
+ this._quadsDirty = true;
+ this._uvsDirty = true;
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty);
},
/**
- * Sets whether the widget should be flipped vertically or not.
- * @since v3.3
- * @param flippedY true if the widget should be flipped vertically, false otherwise.
+ * get the right border of 9 slice sprite, the result is specified before trimmed.
+ * @return right border.
*/
- setFlippedY:function(flippedY){
- var realScale = this.getScaleY();
- this._flippedY = flippedY;
- this.setScaleY(realScale);
- this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.cacheDirty);
+ getInsetRight: function () {
+ return this._insetRight;
},
/**
- *
- * Return the flag which indicates whether the widget is flipped vertically or not.
- *
- * It only flips the texture of the widget, and not the texture of the widget's children.
- * Also, flipping the texture doesn't alter the anchorPoint.
- * If you want to flip the anchorPoint too, and/or to flip the children too use:
- * widget->setScaleY(widget->getScaleY() * -1);
- *
- * @since v3.3
- * @return {Boolean} true if the widget is flipped vertically, false otherwise.
+ * change the bottom border of 9 slice sprite, it should be specified before trimmed.
+ * @param insetBottom bottom border.
*/
- isFlippedY:function(){
- return this._flippedY;
+ setInsetBottom: function (insetBottom) {
+ this._insetBottom = insetBottom;
+ this._quadsDirty = true;
+ this._uvsDirty = true;
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty);
},
-
- setScaleX: function (scaleX) {
- if (this._flippedX)
- scaleX = scaleX * -1;
- cc.Node.prototype.setScaleX.call(this, scaleX);
- this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.cacheDirty);
+ /**
+ * get the bottom border of 9 slice sprite, the result is specified before trimmed.
+ * @return bottom border.
+ */
+ getInsetBottom: function () {
+ return this._insetBottom;
},
- setScaleY: function (scaleY) {
- if (this._flippedY)
- scaleY = scaleY * -1;
- cc.Node.prototype.setScaleY.call(this, scaleY);
- this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.cacheDirty);
- },
+ _rebuildQuads: function () {
+ if (!this._spriteFrame || !this._spriteFrame._textureLoaded) {
+ return;
+ }
- setScale: function (scaleX, scaleY) {
- if(scaleY === undefined)
- scaleY = scaleX;
- this.setScaleX(scaleX);
- this.setScaleY(scaleY);
- },
+ this._updateBlendFunc();
- getScaleX: function () {
- var originalScale = cc.Node.prototype.getScaleX.call(this);
- if (this._flippedX)
- originalScale = originalScale * -1.0;
- return originalScale;
- },
+ this._isTriangle = false;
+ switch (this._renderingType) {
+ case RenderingType.SIMPLE:
+ simpleQuadGenerator._rebuildQuads_base(this, this._spriteFrame, this._contentSize, this._isTrimmedContentSize);
+ break;
+ case RenderingType.SLICED:
+ scale9QuadGenerator._rebuildQuads_base(this, this._spriteFrame, this._contentSize, this._insetLeft, this._insetRight, this._insetTop, this._insetBottom);
+ break;
+ default:
+ this._quadsDirty = false;
+ this._uvsDirty = false;
+ cc.error('Can not generate quad');
+ return;
+ }
- getScaleY: function () {
- var originalScale = cc.Node.prototype.getScaleY.call(this);
- if (this._flippedY)
- originalScale = originalScale * -1.0;
- return originalScale;
- },
- getScale: function () {
- if(this.getScaleX() !== this.getScaleY())
- cc.log("Scale9Sprite#scale. ScaleX != ScaleY. Don't know which one to return");
- return this.getScaleX();
+ this._quadsDirty = false;
+ this._uvsDirty = false;
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return new ccui.Scale9Sprite.CanvasRenderCmd(this);
else
return new ccui.Scale9Sprite.WebGLRenderCmd(this);
@@ -1220,3 +907,15 @@ ccui.Scale9Sprite.POSITIONS_TOPLEFT = 6;
ccui.Scale9Sprite.POSITIONS_BOTTOMRIGHT = 7;
ccui.Scale9Sprite.state = {NORMAL: 0, GRAY: 1};
+
+var RenderingType = ccui.Scale9Sprite.RenderingType = {
+ /**
+ * @property {Number} SIMPLE
+ */
+ SIMPLE: 0,
+ /**
+ * @property {Number} SLICED
+ */
+ SLICED: 1
+};
+})();
diff --git a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js
index 57a27ed3c3..12f1bcaf82 100644
--- a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js
+++ b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js
@@ -1,5 +1,5 @@
/****************************************************************************
- Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
@@ -25,170 +25,130 @@
(function() {
ccui.Scale9Sprite.CanvasRenderCmd = function (renderable) {
cc.Node.CanvasRenderCmd.call(this, renderable);
- this._cachedParent = null;
- this._cacheDirty = false;
- this._state = ccui.Scale9Sprite.state.NORMAL;
+ this._needDraw = true;
- var node = this._node;
- var locCacheCanvas = this._cacheCanvas = document.createElement('canvas');
- locCacheCanvas.width = 1;
- locCacheCanvas.height = 1;
- this._cacheContext = new cc.CanvasContextWrapper(locCacheCanvas.getContext("2d"));
- var locTexture = this._cacheTexture = new cc.Texture2D();
- locTexture.initWithElement(locCacheCanvas);
- locTexture.handleLoadedTexture();
- this._cacheSprite = new cc.Sprite(locTexture);
- this._cacheSprite.setAnchorPoint(0,0);
- node.addChild(this._cacheSprite);
+ this._state = ccui.Scale9Sprite.state.NORMAL;
+ this._originalTexture = this._textureToRender = null;
};
var proto = ccui.Scale9Sprite.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
proto.constructor = ccui.Scale9Sprite.CanvasRenderCmd;
- proto.visit = function(parentCmd){
- var node = this._node;
- if(!node._visible)
- return;
-
- if (node._positionsAreDirty) {
- node._updatePositions();
- node._positionsAreDirty = false;
- }
-
- this.originVisit(parentCmd);
+ proto.transform = function(parentCmd, recursive){
+ this.originTransform(parentCmd, recursive);
+ this._node._rebuildQuads();
};
- proto.transform = function(parentCmd){
- var node = this._node;
- cc.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd);
- if (node._positionsAreDirty) {
- node._updatePositions();
- node._positionsAreDirty = false;
- }
-
- var children = node._children;
- for(var i=0; i 0 && sh > 0 && w > 0 && h > 0) {
+ context.drawImage(image,
+ sx, sy, sw, sh,
+ x, y, w, h);
+ }
+ }
}
- else
- break;
+ cc.g_NumberOfDraws += 9;
+ } else {
+ var quadCount = Math.floor(node._vertCount / 4);
+ for (i = 0, off = 0; i < quadCount; i++) {
+ x = vertices[off];
+ y = vertices[off+1];
+ w = vertices[off+6] - x;
+ h = vertices[off+7] - y;
+ y = - y - h;
+
+ sx = uvs[off] * textureWidth;
+ sy = uvs[off+7] * textureHeight;
+ sw = (uvs[off+6] - uvs[off]) * textureWidth;
+ sh = (uvs[off+1] - uvs[off+7]) * textureHeight;
+
+
+ if (this._textureToRender._pattern !== '') {
+ wrapper.setFillStyle(context.createPattern(image, this._textureToRender._pattern));
+ context.fillRect(x, y, w, h);
+ } else {
+ if (sw > 0 && sh > 0 && w > 0 && h > 0) {
+ context.drawImage(image,
+ sx, sy, sw, sh,
+ x, y, w, h);
+ }
+ }
+ off += 8;
+ }
+ cc.g_NumberOfDraws += quadCount;
}
}
- else {
- var tempCmd = node._scale9Image._renderCmd;
- node._adjustScale9ImagePosition();
- node._adjustScale9ImageScale();
- tempCmd.updateStatus();
- cc.renderer.pushRenderCommand(node._scale9Image._renderCmd);
- }
- //draw to cache canvas
- var selTexture = node._scale9Image.getTexture();
- if(selTexture && this._state === ccui.Scale9Sprite.state.GRAY)
- selTexture._switchToGray(true);
- locContext.setTransform(1, 0, 0, 1, 0, 0);
- locContext.clearRect(0, 0, sizeInPixels.width, sizeInPixels.height);
- cc.renderer._renderingToCacheCanvas(wrapper, node.__instanceId, locScaleFactor, locScaleFactor);
- cc.renderer._turnToNormalMode();
- if(selTexture && this._state === ccui.Scale9Sprite.state.GRAY)
- selTexture._switchToGray(false);
-
- if(contentSizeChanged)
- this._cacheSprite.setTextureRect(cc.rect(0,0, size.width, size.height));
-
- if(!this._cacheSprite.getParent())
- node.addChild(this._cacheSprite, -1);
- this._cacheSprite._renderCmd._updateColor();
};
- proto.setState = function(state){
- var locScale9Image = this._node._scale9Image;
- if(!locScale9Image)
- return;
- this._state = state;
- this.setDirtyFlag(cc.Node._dirtyFlags.cacheDirty);
- };
})();
diff --git a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js
index b8541b46d0..7f249e6580 100644
--- a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js
+++ b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js
@@ -1,5 +1,5 @@
/****************************************************************************
- Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
@@ -23,184 +23,158 @@
****************************************************************************/
(function() {
- if(!cc.Node.WebGLRenderCmd)
- return;
+ if(!cc.Node.WebGLRenderCmd) return;
+
ccui.Scale9Sprite.WebGLRenderCmd = function (renderable) {
cc.Node.WebGLRenderCmd.call(this, renderable);
- this._cachedParent = null;
- this._cacheDirty = false;
+
+ this._needDraw = true;
+
+ this._color = new Uint32Array(1);
+ this._dirty = false;
+ this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLOR);
};
+
+
+ var Scale9Sprite = ccui.Scale9Sprite;
var proto = ccui.Scale9Sprite.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
proto.constructor = ccui.Scale9Sprite.WebGLRenderCmd;
- proto.setShaderProgram = function (shaderProgram) {
- var node = this._node;
- if (node._scale9Enabled) {
- var renderers = node._renderers, l = renderers.length;
- for (var i = 0; i < l; i++) {
- if (renderers[i]) {
- renderers[i]._renderCmd._shaderProgram = shaderProgram;
- }
- }
- }
- else {
- node._scale9Image._renderCmd._shaderProgram = shaderProgram;
- }
- this._shaderProgram = shaderProgram;
+ proto.needDraw = function () {
+ return this._needDraw && this._node.loaded();
};
- proto.visit = function(parentCmd) {
- var node = this._node;
- if (!node._visible)
- return;
- if (!node._scale9Image)
- return;
-
- if (node._positionsAreDirty) {
- node._updatePositions();
- node._positionsAreDirty = false;
- }
-
- parentCmd = parentCmd || this.getParentRenderCmd();
- if (node._parent && node._parent._renderCmd)
- this._curLevel = node._parent._renderCmd._curLevel + 1;
-
- this._syncStatus(parentCmd);
-
- if (node._scale9Enabled) {
- var locRenderers = node._renderers;
- var rendererLen = locRenderers.length;
- for (var j=0; j < rendererLen; j++) {
- var renderer = locRenderers[j];
- if (renderer) {
- var tempCmd = renderer._renderCmd;
- tempCmd.visit(this);
- }
- else
- break;
+ proto._uploadSliced = function (vertices, uvs, color, z, f32buffer, ui32buffer, offset) {
+ var off;
+ for (var r = 0; r < 3; ++r) {
+ for (var c = 0; c < 3; ++c) {
+ off = r*8 + c*2;
+ // lb
+ f32buffer[offset] = vertices[off];
+ f32buffer[offset+1] = vertices[off+1];
+ f32buffer[offset+2] = z;
+ ui32buffer[offset+3] = color[0];
+ f32buffer[offset+4] = uvs[off];
+ f32buffer[offset+5] = uvs[off+1];
+ offset += 6;
+ // rb
+ f32buffer[offset] = vertices[off+2];
+ f32buffer[offset + 1] = vertices[off+3];
+ f32buffer[offset + 2] = z;
+ ui32buffer[offset + 3] = color[0];
+ f32buffer[offset + 4] = uvs[off+2];
+ f32buffer[offset + 5] = uvs[off+3];
+ offset += 6;
+ // lt
+ f32buffer[offset] = vertices[off+8];
+ f32buffer[offset + 1] = vertices[off+9];
+ f32buffer[offset + 2] = z;
+ ui32buffer[offset + 3] = color[0];
+ f32buffer[offset + 4] = uvs[off+8];
+ f32buffer[offset + 5] = uvs[off+9];
+ offset += 6;
+ // rt
+ f32buffer[offset] = vertices[off+10];
+ f32buffer[offset + 1] = vertices[off+11];
+ f32buffer[offset + 2] = z;
+ ui32buffer[offset + 3] = color[0];
+ f32buffer[offset + 4] = uvs[off+10];
+ f32buffer[offset + 5] = uvs[off+11];
+ offset += 6;
}
}
- else {
- node._adjustScale9ImageScale();
- node._adjustScale9ImagePosition();
- node._scale9Image._renderCmd.visit(this);
- }
- this._dirtyFlag = 0;
- this.originVisit(parentCmd);
+ return 36;
};
- proto.transform = function(parentCmd, recursive){
- var node = this._node;
- parentCmd = parentCmd || this.getParentRenderCmd();
+ proto.transform = function (parentCmd, recursive) {
this.originTransform(parentCmd, recursive);
- if (node._positionsAreDirty) {
- node._updatePositions();
- node._positionsAreDirty = false;
- }
- if(node._scale9Enabled) {
- var locRenderers = node._renderers;
- var protectChildLen = locRenderers.length;
- var flags = cc.Node._dirtyFlags;
- for(var j=0; j < protectChildLen; j++) {
- var pchild = locRenderers[j];
- if(pchild) {
- pchild._vertexZ = parentCmd._node._vertexZ;
- var tempCmd = pchild._renderCmd;
- tempCmd.transform(this, true);
- tempCmd._dirtyFlag = tempCmd._dirtyFlag & flags.transformDirty ^ tempCmd._dirtyFlag;
- }
- else {
- break;
- }
- }
- }
- else {
- node._adjustScale9ImageScale();
- node._adjustScale9ImagePosition();
- node._scale9Image._renderCmd.transform(this, true);
- }
+ this._node._rebuildQuads();
};
- proto.setDirtyFlag = function (dirtyFlag, child) {
- // ignore cache dirty, it's only for canvas
- if (dirtyFlag === cc.Node._dirtyFlags.cacheDirty)
- dirtyFlag = cc.Node._dirtyFlags.transformDirty;
- cc.Node.RenderCmd.prototype.setDirtyFlag.call(this, dirtyFlag, child);
+ proto._setColorDirty = function () {
};
- proto._syncStatus = function (parentCmd){
- cc.Node.WebGLRenderCmd.prototype._syncStatus.call(this, parentCmd);
- this._updateDisplayColor(this._displayedColor);
- this._updateDisplayOpacity(this._displayedOpacity);
- };
-
- proto._updateDisplayColor = function(parentColor){
- cc.Node.WebGLRenderCmd.prototype._updateDisplayColor.call(this, parentColor);
+ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){
var node = this._node;
- var scale9Image = node._scale9Image;
- parentColor = this._displayedColor;
- if(node._scale9Enabled) {
- var pChildren = node._renderers;
- for(var i=0; i
* Sets whether the widget is enabled
@@ -352,7 +338,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
/**
* initializes renderer of widget.
*/
- _initRenderer: function () {},
+ _initRenderer: function () {
+ },
/**
* Sets _customSize of ccui.Widget, if ignoreSize is true, the content size is its renderer's contentSize, otherwise the content size is parameter.
@@ -362,15 +349,16 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @override
*/
setContentSize: function(contentSize, height){
- var locWidth = (height === undefined) ? contentSize.width : contentSize;
- var locHeight = (height === undefined) ? contentSize.height : height;
- cc.Node.prototype.setContentSize.call(this, locWidth, locHeight);
+ cc.Node.prototype.setContentSize.call(this, contentSize, height);
+
+ var locWidth = this._contentSize.width;
+ var locHeight = this._contentSize.height;
this._customSize.width = locWidth;
this._customSize.height = locHeight;
if(this._unifySize){
//unify size logic
- } else if (this._ignoreSize){
+ } else if (this._ignoreSize) {
this._contentSize = this.getVirtualRendererSize();
}
if (!this._usingLayoutComponent && this._running) {
@@ -379,15 +367,23 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
this._sizePercent.x = (pSize.width > 0.0) ? locWidth / pSize.width : 0.0;
this._sizePercent.y = (pSize.height > 0.0) ? locHeight / pSize.height : 0.0;
}
- this._onSizeChanged();
+
+ if (this._running) {
+ this._onSizeChanged();
+ } else {
+ this._sizeDirty = true;
+ }
},
_setWidth: function (w) {
+ if (w === this._contentSize.width) {
+ return;
+ }
cc.Node.prototype._setWidth.call(this, w);
this._customSize.width = w;
if(this._unifySize){
//unify size logic
- } else if (this._ignoreSize){
+ } else if (this._ignoreSize) {
this._contentSize = this.getVirtualRendererSize();
}
@@ -396,14 +392,23 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
var locWidth = widgetParent ? widgetParent.width : this._parent.width;
this._sizePercent.x = locWidth > 0 ? this._customSize.width / locWidth : 0;
}
- this._onSizeChanged();
+
+ if (this._running) {
+ this._onSizeChanged();
+ } else {
+ this._sizeDirty = true;
+ }
},
_setHeight: function (h) {
+ if (h === this._contentSize.height) {
+ return;
+ }
+
cc.Node.prototype._setHeight.call(this, h);
this._customSize.height = h;
if(this._unifySize){
//unify size logic
- } else if (this._ignoreSize){
+ } else if (this._ignoreSize) {
this._contentSize = this.getVirtualRendererSize();
}
@@ -412,7 +417,12 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
var locH = widgetParent ? widgetParent.height : this._parent.height;
this._sizePercent.y = locH > 0 ? this._customSize.height / locH : 0;
}
- this._onSizeChanged();
+
+ if (this._running) {
+ this._onSizeChanged();
+ } else {
+ this._sizeDirty = true;
+ }
},
/**
@@ -482,9 +492,9 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @param {cc.Size} [parentSize] parent size
*/
updateSizeAndPosition: function (parentSize) {
- if(!parentSize){
+ if (!parentSize) {
var widgetParent = this.getWidgetParent();
- if(widgetParent)
+ if (widgetParent)
parentSize = widgetParent.getLayoutSize();
else
parentSize = this._parent.getContentSize();
@@ -492,7 +502,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
switch (this._sizeType) {
case ccui.Widget.SIZE_ABSOLUTE:
- if(this._ignoreSize)
+ if (this._ignoreSize)
this.setContentSize(this.getVirtualRendererSize());
else
this.setContentSize(this._customSize);
@@ -500,8 +510,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
this._sizePercent.y = (parentSize.height > 0) ? this._customSize.height / parentSize.height : 0;
break;
case ccui.Widget.SIZE_PERCENT:
- var cSize = cc.size(parentSize.width * this._sizePercent.x , parentSize.height * this._sizePercent.y);
- if(this._ignoreSize)
+ var cSize = cc.size(parentSize.width * this._sizePercent.x, parentSize.height * this._sizePercent.y);
+ if (this._ignoreSize)
this.setContentSize(this.getVirtualRendererSize());
else
this.setContentSize(cSize);
@@ -528,9 +538,9 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
default:
break;
}
- if(this._parent instanceof ccui.ImageView){
+ if (this._parent instanceof ccui.ImageView) {
var renderer = this._parent._imageRenderer;
- if(renderer && !renderer._textureLoaded)
+ if (renderer && !renderer._textureLoaded)
return;
}
this.setPosition(absPos);
@@ -566,11 +576,11 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
return;
}
- if(this._ignoreSize === ignore)
+ if (this._ignoreSize === ignore)
return;
this._ignoreSize = ignore;
- this.setContentSize( ignore ? this.getVirtualRendererSize() : this._customSize );
+ this.setContentSize(ignore ? this.getVirtualRendererSize() : this._customSize);
//this._onSizeChanged();
},
@@ -594,7 +604,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* Gets layout size of ccui.Widget.
* @returns {cc.Size}
*/
- getLayoutSize: function(){
+ getLayoutSize: function () {
return cc.size(this._contentSize);
},
@@ -635,7 +645,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
/**
* Gets the content size of widget. Content size is widget's texture size.
*/
- getVirtualRendererSize:function(){
+ getVirtualRendererSize: function () {
return cc.size(this._contentSize);
},
@@ -644,12 +654,13 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
*/
_onSizeChanged: function () {
if(!this._usingLayoutComponent){
- var locChildren = this.getChildren();
+ var locChildren = this.getChildren();
for (var i = 0, len = locChildren.length; i < len; i++) {
var child = locChildren[i];
- if(child instanceof ccui.Widget)
+ if (child instanceof ccui.Widget)
child.updateSizeAndPosition();
}
+ this._sizeDirty = false;
}
},
@@ -663,7 +674,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
this._touchEnabled = enable; //TODO need consider remove and re-add.
if (this._touchEnabled) {
- if(!this._touchListener)
+ if (!this._touchListener)
this._touchListener = cc.EventListener.create({
event: cc.EventListener.TOUCH_ONE_BY_ONE,
swallowTouches: true,
@@ -689,7 +700,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* Determines if the widget is highlighted
* @returns {boolean} true if the widget is highlighted, false if the widget is not highlighted .
*/
- isHighlighted: function(){
+ isHighlighted: function () {
return this._highlight;
},
@@ -697,7 +708,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* Sets whether the widget is highlighted. The default value is false, a widget is default to not highlighted
* @param highlight true if the widget is highlighted, false if the widget is not highlighted.
*/
- setHighlighted:function(highlight){
+ setHighlighted: function (highlight) {
if (highlight === this._highlight)
return;
this._highlight = highlight;
@@ -726,9 +737,9 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
setFocused: function (focus) {
this._focused = focus;
//make sure there is only one focusedWidget
- if (focus){
+ if (focus) {
ccui.Widget._focusedWidget = this;
- if(ccui.Widget._focusNavigationController)
+ if (ccui.Widget._focusNavigationController)
ccui.Widget._focusNavigationController._setFirstFocsuedWidget(this);
}
},
@@ -737,7 +748,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* returns whether the widget could accept focus.
* @returns {boolean} true represent the widget could accept focus, false represent the widget couldn't accept focus
*/
- isFocusEnabled: function(){
+ isFocusEnabled: function () {
return this._focusEnabled;
},
@@ -745,7 +756,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* sets whether the widget could accept focus.
* @param {Boolean} enable true represent the widget could accept focus, false represent the widget couldn't accept focus
*/
- setFocusEnabled: function(enable){
+ setFocusEnabled: function (enable) {
this._focusEnabled = enable;
},
@@ -758,12 +769,12 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @param current the current focused widget
* @return the next focused widget in a layout
*/
- findNextFocusedWidget: function( direction, current){
- if (null === this.onNextFocusedWidget || null == this.onNextFocusedWidget(direction) ) {
+ findNextFocusedWidget: function (direction, current) {
+ if (null === this.onNextFocusedWidget || null == this.onNextFocusedWidget(direction)) {
var isLayout = current instanceof ccui.Layout;
if (this.isFocused() || isLayout) {
var layout = this.getParent();
- if (null === layout || !(layout instanceof ccui.Layout)){
+ if (null === layout || !(layout instanceof ccui.Layout)) {
//the outer layout's default behaviour is : loop focus
if (isLayout)
return current.findNextFocusedWidget(direction, current);
@@ -782,7 +793,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
/**
* when a widget calls this method, it will get focus immediately.
*/
- requestFocus: function(){
+ requestFocus: function () {
if (this === ccui.Widget._focusedWidget)
return;
this.dispatchFocusEvent(ccui.Widget._focusedWidget, this);
@@ -791,7 +802,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
/**
* no matter what widget object you call this method on , it will return you the exact one focused widget
*/
- getCurrentFocusedWidget: function(){
+ getCurrentFocusedWidget: function () {
return ccui.Widget._focusedWidget;
},
@@ -814,10 +825,10 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @param {ccui.Widget} sender
* @param {cc.Touch} touch
*/
- interceptTouchEvent: function(eventType, sender, touch){
+ interceptTouchEvent: function (eventType, sender, touch) {
var widgetParent = this.getWidgetParent();
if (widgetParent)
- widgetParent.interceptTouchEvent(eventType,sender,touch);
+ widgetParent.interceptTouchEvent(eventType, sender, touch);
},
/**
@@ -825,7 +836,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @param {ccui.Widget} widgetLostFocus
* @param {ccui.Widget} widgetGetFocus
*/
- onFocusChange: function(widgetLostFocus, widgetGetFocus){
+ onFocusChange: function (widgetLostFocus, widgetGetFocus) {
//only change focus when there is indeed a get&lose happens
if (widgetLostFocus)
widgetLostFocus.setFocused(false);
@@ -838,12 +849,12 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @param {ccui.Widget} widgetLostFocus
* @param {ccui.Widget} widgetGetFocus
*/
- dispatchFocusEvent: function(widgetLostFocus, widgetGetFocus){
+ dispatchFocusEvent: function (widgetLostFocus, widgetGetFocus) {
//if the widgetLoseFocus doesn't get focus, it will use the previous focused widget instead
if (widgetLostFocus && !widgetLostFocus.isFocused())
widgetLostFocus = ccui.Widget._focusedWidget;
- if (widgetGetFocus !== widgetLostFocus){
+ if (widgetGetFocus !== widgetLostFocus) {
if (widgetGetFocus && widgetGetFocus.onFocusChanged)
widgetGetFocus.onFocusChanged(widgetLostFocus, widgetGetFocus);
if (widgetLostFocus && widgetGetFocus.onFocusChanged)
@@ -887,13 +898,16 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
}
},
- _onPressStateChangedToNormal: function () {},
+ _onPressStateChangedToNormal: function () {
+ },
- _onPressStateChangedToPressed: function () {},
+ _onPressStateChangedToPressed: function () {
+ },
- _onPressStateChangedToDisabled: function () {},
+ _onPressStateChangedToDisabled: function () {
+ },
- _updateChildrenDisplayedRGBA: function(){
+ _updateChildrenDisplayedRGBA: function () {
this.setColor(this.getColor());
this.setOpacity(this.getOpacity());
},
@@ -901,7 +915,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
/**
* A call back function when widget lost of focus.
*/
- didNotSelectSelf: function () {},
+ didNotSelectSelf: function () {
+ },
/**
*
@@ -920,11 +935,11 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
*/
onTouchBegan: function (touch, event) {
this._hit = false;
- if (this.isVisible() && this.isEnabled() && this._isAncestorsEnabled() && this._isAncestorsVisible(this) ){
+ if (this.isVisible() && this.isEnabled() && this._isAncestorsEnabled() && this._isAncestorsVisible(this)) {
var touchPoint = touch.getLocation();
this._touchBeganPosition.x = touchPoint.x;
this._touchBeganPosition.y = touchPoint.y;
- if(this.hitTest(this._touchBeganPosition) && this.isClippingParentContainsPoint(this._touchBeganPosition))
+ if (this.hitTest(this._touchBeganPosition) && this.isClippingParentContainsPoint(this._touchBeganPosition))
this._hit = true;
}
if (!this._hit) {
@@ -943,9 +958,9 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
return true;
},
- propagateTouchEvent: function(event, sender, touch){
+ propagateTouchEvent: function (event, sender, touch) {
var widgetParent = this.getWidgetParent();
- if (widgetParent){
+ if (widgetParent) {
widgetParent.interceptTouchEvent(event, sender, touch);
}
},
@@ -1057,7 +1072,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @param {Object} target
*/
addTouchEventListener: function (selector, target) {
- if(target === undefined)
+ if (target === undefined)
this._touchEventCallback = selector;
else {
this._touchEventSelector = selector;
@@ -1065,7 +1080,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
}
},
- addClickEventListener: function(callback){
+ addClickEventListener: function (callback) {
this._clickEventListener = callback;
},
@@ -1075,7 +1090,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @returns {boolean} true if the point is in widget's space, false otherwise.
*/
hitTest: function (pt) {
- var bb = cc.rect(0,0, this._contentSize.width, this._contentSize.height);
+ var bb = cc.rect(0, 0, this._contentSize.width, this._contentSize.height);
return cc.rectContainsPoint(bb, this.convertToNodeSpace(pt));
},
@@ -1084,7 +1099,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @param {cc.Point} pt location point
* @returns {Boolean}
*/
- isClippingParentContainsPoint: function(pt){
+ isClippingParentContainsPoint: function (pt) {
this._affectByClipping = false;
var parent = this.getParent();
var clippingParent = null;
@@ -1207,6 +1222,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
return;
}
this._positionPercent.x = percent;
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
},
_setYPercent: function (percent) {
if (this._usingLayoutComponent){
@@ -1216,6 +1232,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
return;
}
this._positionPercent.y = percent;
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
},
/**
@@ -1323,7 +1340,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
return this._flippedY;
},
- _adaptRenderers: function(){},
+ _adaptRenderers: function () {
+ },
/**
* Determines if the widget is bright
@@ -1377,15 +1395,15 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* Gets the position of touch began event.
* @returns {cc.Point}
*/
- getTouchBeganPosition: function(){
- return cc.p(this._touchBeganPosition);
+ getTouchBeganPosition: function () {
+ return cc.p(this._touchBeganPosition);
},
/**
* Gets the position of touch moved event
* @returns {cc.Point}
*/
- getTouchMovePosition: function(){
+ getTouchMovePosition: function () {
return cc.p(this._touchMovePosition);
},
@@ -1393,7 +1411,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* Gets the position of touch end event
* @returns {cc.Point}
*/
- getTouchEndPosition:function(){
+ getTouchEndPosition: function () {
return cc.p(this._touchEndPosition);
},
@@ -1410,7 +1428,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @param {ccui.LayoutParameter} parameter
*/
setLayoutParameter: function (parameter) {
- if(!parameter)
+ if (!parameter)
return;
this._layoutParameterDictionary[parameter.getLayoutType()] = parameter;
this._layoutParameterType = parameter.getLayoutType();
@@ -1458,7 +1476,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
}
},
- _copySpecialProperties: function (model) {},
+ _copySpecialProperties: function (model) {
+ },
_copyProperties: function (widget) {
this.setEnabled(widget.isEnabled());
@@ -1510,7 +1529,6 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
if (parameter)
this.setLayoutParameter(parameter.clone());
}
- this._onSizeChanged();
},
/*temp action*/
@@ -1527,7 +1545,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @deprecated since v3.0, please use getLeftBoundary instead.
* @returns {number}
*/
- getLeftInParent: function(){
+ getLeftInParent: function () {
cc.log("getLeftInParent is deprecated. Please use getLeftBoundary instead.");
return this.getLeftBoundary();
},
@@ -1537,7 +1555,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @deprecated since v3.0, please use getBottomBoundary instead.
* @returns {number}
*/
- getBottomInParent: function(){
+ getBottomInParent: function () {
cc.log("getBottomInParent is deprecated. Please use getBottomBoundary instead.");
return this.getBottomBoundary();
},
@@ -1547,7 +1565,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @deprecated since v3.0, please use getRightBoundary instead.
* @returns {number}
*/
- getRightInParent: function(){
+ getRightInParent: function () {
cc.log("getRightInParent is deprecated. Please use getRightBoundary instead.");
return this.getRightBoundary();
},
@@ -1557,7 +1575,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @deprecated since v3.0, please use getTopBoundary instead.
* @returns {number}
*/
- getTopInParent: function(){
+ getTopInParent: function () {
cc.log("getTopInParent is deprecated. Please use getTopBoundary instead.");
return this.getTopBoundary();
},
@@ -1700,14 +1718,14 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
this._nodes.length = 0;
},
- _findLayout: function(){
+ _findLayout: function () {
cc.renderer.childrenOrderDirty = true;
var layout = this._parent;
- while(layout){
- if(layout._doLayout){
+ while (layout) {
+ if (layout._doLayout) {
layout._doLayoutDirty = true;
break;
- }else
+ } else
layout = layout._parent;
}
},
@@ -1735,42 +1753,42 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @since v3.3
* @param {function} callback
*/
- addCCSEventListener: function(callback){
+ addCCSEventListener: function (callback) {
this._ccEventCallback = callback;
},
//override the scale functions.
- setScaleX: function(scaleX){
+ setScaleX: function (scaleX) {
if (this._flippedX)
scaleX = scaleX * -1;
cc.Node.prototype.setScaleX.call(this, scaleX);
},
- setScaleY: function(scaleY){
+ setScaleY: function (scaleY) {
if (this._flippedY)
scaleY = scaleY * -1;
cc.Node.prototype.setScaleY.call(this, scaleY);
},
- setScale: function(scaleX, scaleY){
- if(scaleY === undefined)
+ setScale: function (scaleX, scaleY) {
+ if (scaleY === undefined)
scaleY = scaleX;
this.setScaleX(scaleX);
this.setScaleY(scaleY);
},
- getScaleX: function(){
+ getScaleX: function () {
var originalScale = cc.Node.prototype.getScaleX.call(this);
if (this._flippedX)
originalScale = originalScale * -1.0;
return originalScale;
},
- getScaleY: function(){
+ getScaleY: function () {
var originalScale = cc.Node.prototype.getScaleY.call(this);
if (this._flippedY)
originalScale = originalScale * -1.0;
return originalScale;
},
- getScale: function(){
- if(this.getScaleX() !== this.getScaleY())
+ getScale: function () {
+ if (this.getScaleX() !== this.getScaleY())
cc.log("Widget#scale. ScaleX != ScaleY. Don't know which one to return");
return this.getScaleX();
},
@@ -1780,7 +1798,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @since v3.3
* @param {String} callbackName
*/
- setCallbackName: function(callbackName){
+ setCallbackName: function (callbackName) {
this._callbackName = callbackName;
},
@@ -1789,7 +1807,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @since v3.3
* @returns {String|Null}
*/
- getCallbackName: function(){
+ getCallbackName: function () {
return this._callbackName;
},
@@ -1798,7 +1816,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @since v3.3
* @param {String} callbackType
*/
- setCallbackType: function(callbackType){
+ setCallbackType: function (callbackType) {
this._callbackType = callbackType;
},
@@ -1807,7 +1825,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @since v3.3
* @returns {String|null}
*/
- getCallbackType: function(){
+ getCallbackType: function () {
return this._callbackType;
},
@@ -1829,8 +1847,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
return new ccui.Widget.WebGLRenderCmd(this);
else
return new ccui.Widget.CanvasRenderCmd(this);
@@ -1905,8 +1923,8 @@ ccui.Widget._focusNavigationController = null;
* @note it doesn't implemented on Web
* @param {Boolean} enable set true to enable dpad focus navigation, otherwise disable dpad focus navigation
*/
-ccui.Widget.enableDpadNavigation = function(enable){
- if (enable){
+ccui.Widget.enableDpadNavigation = function (enable) {
+ if (enable) {
if (null == ccui.Widget._focusNavigationController) {
ccui.Widget._focusNavigationController = new ccui._FocusNavigationController();
if (ccui.Widget._focusedWidget) {
@@ -1915,7 +1933,7 @@ ccui.Widget.enableDpadNavigation = function(enable){
}
ccui.Widget._focusNavigationController.enableFocusNavigation(true);
} else {
- if(ccui.Widget._focusNavigationController){
+ if (ccui.Widget._focusNavigationController) {
ccui.Widget._focusNavigationController.enableFocusNavigation(false);
ccui.Widget._focusNavigationController = null;
}
@@ -1927,7 +1945,7 @@ ccui.Widget.enableDpadNavigation = function(enable){
* @function
* @returns {null|ccui.Widget}
*/
-ccui.Widget.getCurrentFocusedWidget = function(){
+ccui.Widget.getCurrentFocusedWidget = function () {
return ccui.Widget._focusedWidget;
};
diff --git a/extensions/ccui/base-classes/UIWidgetRenderCmd.js b/extensions/ccui/base-classes/UIWidgetRenderCmd.js
index 9119c327dd..d424cd39b8 100644
--- a/extensions/ccui/base-classes/UIWidgetRenderCmd.js
+++ b/extensions/ccui/base-classes/UIWidgetRenderCmd.js
@@ -25,7 +25,7 @@
cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
ccui.Widget.CanvasRenderCmd = function (renderable) {
- cc.ProtectedNode.CanvasRenderCmd.call(this, renderable);
+ this._pNodeCmdCtor(renderable);
this._needDraw = false;
};
@@ -33,14 +33,27 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
proto.constructor = ccui.Widget.CanvasRenderCmd;
proto.visit = function (parentCmd) {
- var node = this._node;
- if (node._visible) {
- node._adaptRenderers();
- this.pNodeVisit(parentCmd);
+ var node = this._node, renderer = cc.renderer;
+
+ parentCmd = parentCmd || this.getParentRenderCmd();
+ if (parentCmd)
+ this._curLevel = parentCmd._curLevel + 1;
+
+ if (isNaN(node._customZ)) {
+ node._vertexZ = renderer.assignedZ;
+ renderer.assignedZ += renderer.assignedZStep;
}
+
+ node._adaptRenderers();
+ this._syncStatus(parentCmd);
};
proto.transform = function (parentCmd, recursive) {
+ if (!this._transform) {
+ this._transform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0};
+ this._worldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0};
+ }
+
var node = this._node;
if (node._visible && node._running) {
node._adaptRenderers();
@@ -58,11 +71,10 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
}
};
- proto.widgetVisit = proto.visit;
proto.widgetTransform = proto.transform;
} else {
ccui.Widget.WebGLRenderCmd = function (renderable) {
- cc.ProtectedNode.WebGLRenderCmd.call(this, renderable);
+ this._pNodeCmdCtor(renderable);
this._needDraw = false;
};
@@ -70,14 +82,22 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
proto.constructor = ccui.Widget.WebGLRenderCmd;
proto.visit = function (parentCmd) {
- var node = this._node;
- if (node._visible) {
- node._adaptRenderers();
- this.pNodeVisit(parentCmd);
+ var node = this._node, renderer = cc.renderer;
+
+ parentCmd = parentCmd || this.getParentRenderCmd();
+ if (parentCmd)
+ this._curLevel = parentCmd._curLevel + 1;
+
+ if (isNaN(node._customZ)) {
+ node._vertexZ = renderer.assignedZ;
+ renderer.assignedZ += renderer.assignedZStep;
}
+
+ node._adaptRenderers();
+ this._syncStatus(parentCmd);
};
- proto.transform = function(parentCmd, recursive){
+ proto.transform = function (parentCmd, recursive) {
var node = this._node;
if (node._visible && node._running) {
node._adaptRenderers();
@@ -96,7 +116,6 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
}
};
- proto.widgetVisit = proto.visit;
proto.widgetTransform = proto.transform;
}
});
diff --git a/extensions/ccui/layouts/UILayout.js b/extensions/ccui/layouts/UILayout.js
index ff4d82bf5c..695f7e40f4 100644
--- a/extensions/ccui/layouts/UILayout.js
+++ b/extensions/ccui/layouts/UILayout.js
@@ -63,11 +63,11 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
_finalPositionX: 0,
_finalPositionY: 0,
- _backGroundImageOpacity:0,
+ _backGroundImageOpacity: 0,
_loopFocus: false, //whether enable loop focus or not
__passFocusToChild: true, //on default, it will pass the focus to the next nearest widget
- _isFocusPassing:false, //when finding the next focused widget, use this variable to pass focus between layout & widget
+ _isFocusPassing: false, //when finding the next focused widget, use this variable to pass focus between layout & widget
_isInterceptTouch: false,
/**
@@ -89,7 +89,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
this.ignoreContentAdaptWithSize(false);
this.setContentSize(cc.size(0, 0));
this.setAnchorPoint(0, 0);
- this.onPassFocusToChild = this._findNearestChildWidgetIndex.bind(this);
+ this.onPassFocusToChild = this._findNearestChildWidgetIndex.bind(this);
this._backGroundImageCapInsets = cc.rect(0, 0, 0, 0);
@@ -107,10 +107,10 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* Calls its parent's onEnter, and calls its clippingStencil's onEnter if clippingStencil isn't null.
* @override
*/
- onEnter: function(){
+ onEnter: function () {
ccui.Widget.prototype.onEnter.call(this);
if (this._clippingStencil)
- this._clippingStencil.onEnter();
+ this._clippingStencil._performRecursive(cc.Node._stateCallbackType.onEnter);
this._doLayoutDirty = true;
this._clippingRectDirty = true;
},
@@ -119,17 +119,87 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* Calls its parent's onExit, and calls its clippingStencil's onExit if clippingStencil isn't null.
* @override
*/
- onExit: function(){
+ onExit: function () {
ccui.Widget.prototype.onExit.call(this);
if (this._clippingStencil)
- this._clippingStencil.onExit();
+ this._clippingStencil._performRecursive(cc.Node._stateCallbackType.onExit);
+ },
+
+ /**
+ *
+ * Calls adaptRenderers (its subclass will override it.) and do layout.
+ * If clippingEnabled is true, it will clip/scissor area.
+ *
+ * @override
+ * @param {cc.Node} [parent]
+ */
+ visit: function (parent) {
+ if (!this._visible)
+ return;
+
+ this._adaptRenderers();
+ this._doLayout();
+
+ var renderer = cc.renderer, cmd = this._renderCmd;
+ var parentCmd = parent && parent._renderCmd;
+ cmd.visit(parentCmd);
+
+ var stencilClipping = this._clippingEnabled && this._clippingType === ccui.Layout.CLIPPING_STENCIL;
+ var scissorClipping = this._clippingEnabled && this._clippingType === ccui.Layout.CLIPPING_SCISSOR;
+
+ if (stencilClipping) {
+ cmd.stencilClippingVisit(parentCmd);
+ }
+ else if (scissorClipping) {
+ cmd.scissorClippingVisit(parentCmd);
+ }
+
+ var i, children = this._children, len = children.length, child;
+ var j, pChildren = this._protectedChildren, pLen = pChildren.length, pChild;
+
+ if (this._reorderChildDirty) this.sortAllChildren();
+ if (this._reorderProtectedChildDirty) this.sortAllProtectedChildren();
+ // draw children zOrder < 0
+ for (i = 0; i < len; i++) {
+ child = children[i];
+ if (child._localZOrder < 0) {
+ child.visit(this);
+ }
+ else break;
+ }
+ for (j = 0; j < pLen; j++) {
+ pChild = pChildren[j];
+ if (pChild._localZOrder < 0) {
+ cmd._changeProtectedChild(pChild);
+ pChild.visit(this);
+ }
+ else break;
+ }
+ // draw children zOrder >= 0
+ for (; i < len; i++) {
+ children[i].visit(this);
+ }
+ for (; j < pLen; j++) {
+ pChild = pChildren[j];
+ cmd._changeProtectedChild(pChild);
+ pChild.visit(this);
+ }
+
+ if (stencilClipping) {
+ cmd.postStencilVisit();
+ }
+ else if (scissorClipping) {
+ cmd.postScissorVisit();
+ }
+
+ cmd._dirtyFlag = 0;
},
/**
* If a layout is loop focused which means that the focus movement will be inside the layout
* @param {Boolean} loop pass true to let the focus movement loop inside the layout
*/
- setLoopFocus: function(loop){
+ setLoopFocus: function (loop) {
this._loopFocus = loop;
},
@@ -137,7 +207,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* Gets whether enable focus loop
* @returns {boolean} If focus loop is enabled, then it will return true, otherwise it returns false. The default value is false.
*/
- isLoopFocus: function(){
+ isLoopFocus: function () {
return this._loopFocus;
},
@@ -145,7 +215,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* Specifies whether the layout pass its focus to its child
* @param pass To specify whether the layout pass its focus to its child
*/
- setPassFocusToChild: function(pass){
+ setPassFocusToChild: function (pass) {
this.__passFocusToChild = pass;
},
@@ -153,7 +223,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* Returns whether the layout will pass the focus to its children or not. The default value is true
* @returns {boolean} To query whether the layout will pass the focus to its children or not. The default value is true
*/
- isPassFocusToChild: function(){
+ isPassFocusToChild: function () {
return this.__passFocusToChild;
},
@@ -164,7 +234,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @param {ccui.Widget} current the current focused widget
* @returns {ccui.Widget} return the index of widget in the layout
*/
- findNextFocusedWidget: function(direction, current){
+ findNextFocusedWidget: function (direction, current) {
if (this._isFocusPassing || this.isFocused()) {
var parent = this.getParent();
this._isFocusPassing = false;
@@ -181,31 +251,31 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
return this;
parent._isFocusPassing = true;
return parent.findNextFocusedWidget(direction, this);
- } else if(current.isFocused() || current instanceof ccui.Layout) {
+ } else if (current.isFocused() || current instanceof ccui.Layout) {
if (this._layoutType === ccui.Layout.LINEAR_HORIZONTAL) {
- switch (direction){
+ switch (direction) {
case ccui.Widget.LEFT:
return this._getPreviousFocusedWidget(direction, current);
- break;
+ break;
case ccui.Widget.RIGHT:
return this._getNextFocusedWidget(direction, current);
- break;
+ break;
case ccui.Widget.DOWN:
case ccui.Widget.UP:
- if (this._isLastWidgetInContainer(this, direction)){
+ if (this._isLastWidgetInContainer(this, direction)) {
if (this._isWidgetAncestorSupportLoopFocus(current, direction))
return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this);
return current;
} else {
return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this);
}
- break;
+ break;
default:
cc.assert(0, "Invalid Focus Direction");
return current;
}
} else if (this._layoutType === ccui.Layout.LINEAR_VERTICAL) {
- switch (direction){
+ switch (direction) {
case ccui.Widget.LEFT:
case ccui.Widget.RIGHT:
if (this._isLastWidgetInContainer(this, direction)) {
@@ -215,7 +285,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
}
else
return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this);
- break;
+ break;
case ccui.Widget.DOWN:
return this._getNextFocusedWidget(direction, current);
break;
@@ -282,7 +352,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* and sets the layout dirty flag to true.
* @param {Boolean} cleanup true if all running actions on all children nodes should be cleanup, false otherwise.
*/
- removeAllChildrenWithCleanup: function(cleanup){
+ removeAllChildrenWithCleanup: function (cleanup) {
ccui.Widget.prototype.removeAllChildrenWithCleanup.call(this, cleanup);
this._doLayoutDirty = true;
},
@@ -295,36 +365,6 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
return this._clippingEnabled;
},
- /**
- *
- * Calls adaptRenderers (its subclass will override it.) and do layout.
- * If clippingEnabled is true, it will clip/scissor area.
- *
- * @override
- * @param {cc.Node.RenderCmd} [parentCmd]
- */
- visit: function (parentCmd) {
- if (!this._visible)
- return;
- this._adaptRenderers();
- this._doLayout();
-
- if (this._clippingEnabled) {
- switch (this._clippingType) {
- case ccui.Layout.CLIPPING_STENCIL:
- this._renderCmd.stencilClippingVisit(parentCmd);
- break;
- case ccui.Layout.CLIPPING_SCISSOR:
- this._renderCmd.scissorClippingVisit(parentCmd);
- break;
- default:
- break;
- }
- } else {
- ccui.Widget.prototype.visit.call(this, parentCmd);
- }
- },
-
/**
* Changes if layout can clip it's content and locChild.
* If you really need this, please enable it. But it would reduce the rendering efficiency.
@@ -337,15 +377,15 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
switch (this._clippingType) {
case ccui.Layout.CLIPPING_SCISSOR:
case ccui.Layout.CLIPPING_STENCIL:
- if (able){
+ if (able) {
this._clippingStencil = new cc.DrawNode();
this._renderCmd.rebindStencilRendering(this._clippingStencil);
if (this._running)
- this._clippingStencil.onEnter();
+ this._clippingStencil._performRecursive(cc.Node._stateCallbackType.onEnter);
this._setStencilClippingSize(this._contentSize);
} else {
if (this._running && this._clippingStencil)
- this._clippingStencil.onExit();
+ this._clippingStencil._performRecursive(cc.Node._stateCallbackType.onExit);
this._clippingStencil = null;
}
break;
@@ -415,8 +455,8 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
var right = Math.min(worldPos.x + scissorWidth, parentClippingRect.x + parentClippingRect.width);
var top = Math.min(worldPos.y + scissorHeight, parentClippingRect.y + parentClippingRect.height);
- this._clippingRect.width = Math.max(0.0, right - this._clippingRect.x);
- this._clippingRect.height = Math.max(0.0, top - this._clippingRect.y);
+ this._clippingRect.width = Math.max(0.0, right - this._clippingRect.x);
+ this._clippingRect.height = Math.max(0.0, top - this._clippingRect.y);
} else {
this._clippingRect.x = worldPos.x;
this._clippingRect.y = worldPos.y;
@@ -477,7 +517,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
if (!fileName)
return;
texType = texType || ccui.Widget.LOCAL_TEXTURE;
- if (this._backGroundImage === null){
+ if (this._backGroundImage === null) {
this._addBackGroundImage();
this.setBackGroundImageScale9Enabled(this._backGroundScale9Enabled);
}
@@ -507,7 +547,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @param {cc.Rect} capInsets capinsets of background image.
*/
setBackGroundImageCapInsets: function (capInsets) {
- if(!capInsets)
+ if (!capInsets)
return;
var locInsets = this._backGroundImageCapInsets;
locInsets.x = capInsets.x;
@@ -780,7 +820,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
},
_updateBackGroundImageColor: function () {
- if(this._backGroundImage)
+ if (this._backGroundImage)
this._backGroundImage.setColor(this._backGroundImageColor);
},
@@ -802,7 +842,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
var locChild = null;
for (var i = 0; i < layoutChildrenArray.length; i++) {
locChild = layoutChildrenArray[i];
- if(locChild instanceof ccui.Widget)
+ if (locChild instanceof ccui.Widget)
this._supplyTheLayoutParameterLackToChild(locChild);
}
this._doLayoutDirty = true;
@@ -835,20 +875,20 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
this._doLayoutDirty = false;
},
- _getLayoutContentSize: function(){
+ _getLayoutContentSize: function () {
return this.getContentSize();
},
- _getLayoutElements: function(){
+ _getLayoutElements: function () {
return this.getChildren();
},
- _updateBackGroundImageOpacity: function(){
+ _updateBackGroundImageOpacity: function () {
if (this._backGroundImage)
this._backGroundImage.setOpacity(this._backGroundImageOpacity);
},
- _updateBackGroundImageRGBA: function(){
+ _updateBackGroundImageRGBA: function () {
if (this._backGroundImage) {
this._backGroundImage.setColor(this._backGroundImageColor);
this._backGroundImage.setOpacity(this._backGroundImageOpacity);
@@ -860,13 +900,13 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {cc.Size}
* @private
*/
- _getLayoutAccumulatedSize: function(){
+ _getLayoutAccumulatedSize: function () {
var children = this.getChildren();
- var layoutSize = cc.size(0, 0);
+ var layoutSize = cc.size(0, 0);
var widgetCount = 0, locSize;
- for(var i = 0, len = children.length; i < len; i++) {
+ for (var i = 0, len = children.length; i < len; i++) {
var layout = children[i];
- if (null !== layout && layout instanceof ccui.Layout){
+ if (null !== layout && layout instanceof ccui.Layout) {
locSize = layout._getLayoutAccumulatedSize();
layoutSize.width += locSize.width;
layoutSize.height += locSize.height;
@@ -875,8 +915,8 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
widgetCount++;
var m = layout.getLayoutParameter().getMargin();
locSize = layout.getContentSize();
- layoutSize.width += locSize.width + (m.right + m.left) * 0.5;
- layoutSize.height += locSize.height + (m.top + m.bottom) * 0.5;
+ layoutSize.width += locSize.width + (m.right + m.left) * 0.5;
+ layoutSize.height += locSize.height + (m.top + m.bottom) * 0.5;
}
}
}
@@ -884,10 +924,10 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
//substract extra size
var type = this.getLayoutType();
if (type === ccui.Layout.LINEAR_HORIZONTAL)
- layoutSize.height = layoutSize.height - layoutSize.height/widgetCount * (widgetCount-1);
+ layoutSize.height = layoutSize.height - layoutSize.height / widgetCount * (widgetCount - 1);
if (type === ccui.Layout.LINEAR_VERTICAL)
- layoutSize.width = layoutSize.width - layoutSize.width/widgetCount * (widgetCount-1);
+ layoutSize.width = layoutSize.width - layoutSize.width / widgetCount * (widgetCount - 1);
return layoutSize;
},
@@ -899,7 +939,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {Number}
* @private
*/
- _findNearestChildWidgetIndex: function(direction, baseWidget){
+ _findNearestChildWidgetIndex: function (direction, baseWidget) {
if (baseWidget == null || baseWidget === this)
return this._findFirstFocusEnabledWidgetIndex();
@@ -912,9 +952,9 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
while (index < count) {
var w = locChildren[index];
if (w && w instanceof ccui.Widget && w.isFocusEnabled()) {
- var length = (w instanceof ccui.Layout)? w._calculateNearestDistance(baseWidget)
+ var length = (w instanceof ccui.Layout) ? w._calculateNearestDistance(baseWidget)
: cc.pLength(cc.pSub(this._getWorldCenterPoint(w), widgetPosition));
- if (length < distance){
+ if (length < distance) {
found = index;
distance = length;
}
@@ -935,7 +975,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {Number} The index of child widget in the container
* @private
*/
- _findFarthestChildWidgetIndex: function(direction, baseWidget){
+ _findFarthestChildWidgetIndex: function (direction, baseWidget) {
if (baseWidget == null || baseWidget === this)
return this._findFirstFocusEnabledWidgetIndex();
@@ -944,20 +984,20 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
var distance = -cc.FLT_MAX, found = 0;
if (direction === ccui.Widget.LEFT || direction === ccui.Widget.RIGHT || direction === ccui.Widget.DOWN || direction === ccui.Widget.UP) {
- var widgetPosition = this._getWorldCenterPoint(baseWidget);
- while (index < count) {
+ var widgetPosition = this._getWorldCenterPoint(baseWidget);
+ while (index < count) {
var w = locChildren[index];
if (w && w instanceof ccui.Widget && w.isFocusEnabled()) {
- var length = (w instanceof ccui.Layout)?w._calculateFarthestDistance(baseWidget)
+ var length = (w instanceof ccui.Layout) ? w._calculateFarthestDistance(baseWidget)
: cc.pLength(cc.pSub(this._getWorldCenterPoint(w), widgetPosition));
- if (length > distance){
+ if (length > distance) {
found = index;
distance = length;
}
}
index++;
}
- return found;
+ return found;
}
cc.log("invalid focus direction!!!");
return 0;
@@ -969,9 +1009,9 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {Number} return the nearest distance between the baseWidget and the layout's children
* @private
*/
- _calculateNearestDistance: function(baseWidget){
+ _calculateNearestDistance: function (baseWidget) {
var distance = cc.FLT_MAX;
- var widgetPosition = this._getWorldCenterPoint(baseWidget);
+ var widgetPosition = this._getWorldCenterPoint(baseWidget);
var locChildren = this._children;
for (var i = 0, len = locChildren.length; i < len; i++) {
@@ -996,9 +1036,9 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {number}
* @private
*/
- _calculateFarthestDistance:function(baseWidget){
+ _calculateFarthestDistance: function (baseWidget) {
var distance = -cc.FLT_MAX;
- var widgetPosition = this._getWorldCenterPoint(baseWidget);
+ var widgetPosition = this._getWorldCenterPoint(baseWidget);
var locChildren = this._children;
for (var i = 0, len = locChildren.length; i < len; i++) {
@@ -1026,7 +1066,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @param baseWidget
* @private
*/
- _findProperSearchingFunctor: function(direction, baseWidget){
+ _findProperSearchingFunctor: function (direction, baseWidget) {
if (baseWidget === undefined)
return;
@@ -1038,13 +1078,13 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
} else if (direction === ccui.Widget.RIGHT) {
this.onPassFocusToChild = (previousWidgetPosition.x > widgetPosition.x) ? this._findFarthestChildWidgetIndex
: this._findNearestChildWidgetIndex;
- }else if(direction === ccui.Widget.DOWN) {
+ } else if (direction === ccui.Widget.DOWN) {
this.onPassFocusToChild = (previousWidgetPosition.y > widgetPosition.y) ? this._findNearestChildWidgetIndex
: this._findFarthestChildWidgetIndex;
- }else if(direction === ccui.Widget.UP) {
+ } else if (direction === ccui.Widget.UP) {
this.onPassFocusToChild = (previousWidgetPosition.y < widgetPosition.y) ? this._findNearestChildWidgetIndex
: this._findFarthestChildWidgetIndex;
- }else
+ } else
cc.log("invalid direction!");
},
@@ -1053,15 +1093,15 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {ccui.Widget}
* @private
*/
- _findFirstNonLayoutWidget:function(){
+ _findFirstNonLayoutWidget: function () {
var locChildren = this._children;
- for(var i = 0, len = locChildren.length; i < len; i++) {
+ for (var i = 0, len = locChildren.length; i < len; i++) {
var child = locChildren[i];
- if (child instanceof ccui.Layout){
+ if (child instanceof ccui.Layout) {
var widget = child._findFirstNonLayoutWidget();
- if(widget)
+ if (widget)
return widget;
- } else{
+ } else {
if (child instanceof ccui.Widget)
return child;
}
@@ -1074,7 +1114,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {number}
* @private
*/
- _findFirstFocusEnabledWidgetIndex: function(){
+ _findFirstFocusEnabledWidgetIndex: function () {
var index = 0, locChildren = this.getChildren();
var count = locChildren.length;
while (index < count) {
@@ -1092,9 +1132,9 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {*}
* @private
*/
- _findFocusEnabledChildWidgetByIndex: function(index){
+ _findFocusEnabledChildWidgetByIndex: function (index) {
var widget = this._getChildWidgetByIndex(index);
- if (widget){
+ if (widget) {
if (widget.isFocusEnabled())
return widget;
index = index + 1;
@@ -1109,10 +1149,10 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {cc.Point}
* @private
*/
- _getWorldCenterPoint: function(widget){
+ _getWorldCenterPoint: function (widget) {
//FIXEDME: we don't need to calculate the content size of layout anymore
- var widgetSize = widget instanceof ccui.Layout ? widget._getLayoutAccumulatedSize() : widget.getContentSize();
- return widget.convertToWorldSpace(cc.p(widgetSize.width /2, widgetSize.height /2));
+ var widgetSize = widget instanceof ccui.Layout ? widget._getLayoutAccumulatedSize() : widget.getContentSize();
+ return widget.convertToWorldSpace(cc.p(widgetSize.width / 2, widgetSize.height / 2));
},
/**
@@ -1122,9 +1162,9 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {ccui.Widget} the next focused widget
* @private
*/
- _getNextFocusedWidget: function(direction, current){
+ _getNextFocusedWidget: function (direction, current) {
var nextWidget = null, locChildren = this._children;
- var previousWidgetPos = locChildren.indexOf(current);
+ var previousWidgetPos = locChildren.indexOf(current);
previousWidgetPos = previousWidgetPos + 1;
if (previousWidgetPos < locChildren.length) {
nextWidget = this._getChildWidgetByIndex(previousWidgetPos);
@@ -1159,8 +1199,8 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
return this._getNextFocusedWidget(direction, nextWidget);
} else
return (current instanceof ccui.Layout) ? current : ccui.Widget._focusedWidget;
- } else{
- if (this._isLastWidgetInContainer(current, direction)){
+ } else {
+ if (this._isLastWidgetInContainer(current, direction)) {
if (this._isWidgetAncestorSupportLoopFocus(this, direction))
return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this);
return (current instanceof ccui.Layout) ? current : ccui.Widget._focusedWidget;
@@ -1177,14 +1217,14 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {ccui.Widget} the next focused widget
* @private
*/
- _getPreviousFocusedWidget: function(direction, current){
+ _getPreviousFocusedWidget: function (direction, current) {
var nextWidget = null, locChildren = this._children;
var previousWidgetPos = locChildren.indexOf(current);
previousWidgetPos = previousWidgetPos - 1;
- if (previousWidgetPos >= 0){
+ if (previousWidgetPos >= 0) {
nextWidget = this._getChildWidgetByIndex(previousWidgetPos);
if (nextWidget.isFocusEnabled()) {
- if (nextWidget instanceof ccui.Layout){
+ if (nextWidget instanceof ccui.Layout) {
nextWidget._isFocusPassing = true;
return nextWidget.findNextFocusedWidget(direction, nextWidget);
}
@@ -1192,13 +1232,13 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
return nextWidget;
} else
return this._getPreviousFocusedWidget(direction, nextWidget); //handling the disabled widget, there is no actual focus lose or get, so we don't need any envet
- }else {
- if (this._loopFocus){
+ } else {
+ if (this._loopFocus) {
if (this._checkFocusEnabledChild()) {
- previousWidgetPos = locChildren.length -1;
+ previousWidgetPos = locChildren.length - 1;
nextWidget = this._getChildWidgetByIndex(previousWidgetPos);
- if (nextWidget.isFocusEnabled()){
- if (nextWidget instanceof ccui.Layout){
+ if (nextWidget.isFocusEnabled()) {
+ if (nextWidget instanceof ccui.Layout) {
nextWidget._isFocusPassing = true;
return nextWidget.findNextFocusedWidget(direction, nextWidget);
} else {
@@ -1255,7 +1295,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {Boolean}
* @private
*/
- _isLastWidgetInContainer:function(widget, direction){
+ _isLastWidgetInContainer: function (widget, direction) {
var parent = widget.getParent();
if (parent == null || !(parent instanceof ccui.Layout))
return true;
@@ -1280,8 +1320,8 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
if (direction === ccui.Widget.UP)
return this._isLastWidgetInContainer(parent, direction);
- } else if(parent.getLayoutType() === ccui.Layout.LINEAR_VERTICAL){
- if (direction === ccui.Widget.UP){
+ } else if (parent.getLayoutType() === ccui.Layout.LINEAR_VERTICAL) {
+ if (direction === ccui.Widget.UP) {
if (index === 0)
return this._isLastWidgetInContainer(parent, direction);
else
@@ -1311,7 +1351,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {Boolean}
* @private
*/
- _isWidgetAncestorSupportLoopFocus: function(widget, direction){
+ _isWidgetAncestorSupportLoopFocus: function (widget, direction) {
var parent = widget.getParent();
if (parent == null || !(parent instanceof ccui.Layout))
return false;
@@ -1323,12 +1363,12 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
else
return this._isWidgetAncestorSupportLoopFocus(parent, direction);
}
- if (layoutType === ccui.Layout.LINEAR_VERTICAL){
+ if (layoutType === ccui.Layout.LINEAR_VERTICAL) {
if (direction === ccui.Widget.DOWN || direction === ccui.Widget.UP)
return true;
else
return this._isWidgetAncestorSupportLoopFocus(parent, direction);
- } else{
+ } else {
cc.assert(0, "invalid layout type");
return false;
}
@@ -1343,7 +1383,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {ccui.Widget}
* @private
*/
- _passFocusToChild: function(direction, current){
+ _passFocusToChild: function (direction, current) {
if (this._checkFocusEnabledChild()) {
var previousWidget = ccui.Widget.getCurrentFocusedWidget();
this._findProperSearchingFunctor(direction, previousWidget);
@@ -1357,7 +1397,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
this.dispatchFocusEvent(current, widget);
return widget;
}
- }else
+ } else
return this;
},
@@ -1366,9 +1406,9 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {boolean}
* @private
*/
- _checkFocusEnabledChild: function(){
+ _checkFocusEnabledChild: function () {
var locChildren = this._children;
- for(var i = 0, len = locChildren.length; i < len; i++){
+ for (var i = 0, len = locChildren.length; i < len; i++) {
var widget = locChildren[i];
if (widget && widget instanceof ccui.Widget && widget.isFocusEnabled())
return true;
@@ -1393,7 +1433,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
},
_copySpecialProperties: function (layout) {
- if(!(layout instanceof ccui.Layout))
+ if (!(layout instanceof ccui.Layout))
return;
this.setBackGroundImageScale9Enabled(layout._backGroundScale9Enabled);
this.setBackGroundImage(layout._backGroundImageFileName, layout._bgImageTexType);
@@ -1414,13 +1454,13 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
/**
* force refresh widget layout
*/
- forceDoLayout: function(){
+ forceDoLayout: function () {
this.requestDoLayout();
this._doLayout();
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
return new ccui.Layout.WebGLRenderCmd(this);
else
return new ccui.Layout.CanvasRenderCmd(this);
@@ -1524,4 +1564,4 @@ ccui.Layout.BACKGROUND_IMAGE_ZORDER = -1;
* @type {number}
* @constant
*/
-ccui.Layout.BACKGROUND_RENDERER_ZORDER = -2;
\ No newline at end of file
+ccui.Layout.BACKGROUND_RENDERER_ZORDER = -2;
diff --git a/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js b/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js
index aa78743222..7d847ccedd 100644
--- a/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js
+++ b/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js
@@ -23,54 +23,21 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- ccui.Layout.CanvasRenderCmd = function(renderable){
- ccui.ProtectedNode.CanvasRenderCmd.call(this, renderable);
+(function () {
+ ccui.Layout.CanvasRenderCmd = function (renderable) {
+ this._pNodeCmdCtor(renderable);
this._needDraw = false;
- this._rendererSaveCmd = new cc.CustomRenderCmd(this, this._onRenderSaveCmd);
- this._rendererClipCmd = new cc.CustomRenderCmd(this, this._onRenderClipCmd);
- this._rendererRestoreCmd = new cc.CustomRenderCmd(this, this._onRenderRestoreCmd);
- this._rendererSaveCmd._canUseDirtyRegion = true;
- this._rendererClipCmd._canUseDirtyRegion = true;
- this._rendererRestoreCmd._canUseDirtyRegion = true;
+ this._rendererSaveCmd = null;
+ this._rendererClipCmd = null;
+ this._rendererRestoreCmd = null;
};
var proto = ccui.Layout.CanvasRenderCmd.prototype = Object.create(ccui.ProtectedNode.CanvasRenderCmd.prototype);
proto.constructor = ccui.Layout.CanvasRenderCmd;
+ proto._layoutCmdCtor = ccui.Layout.CanvasRenderCmd;
- cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
- if (ccui.Widget.CanvasRenderCmd) {
- ccui.Layout.CanvasRenderCmd.prototype.widgetVisit = ccui.Widget.CanvasRenderCmd.prototype.widgetVisit;
- }
- });
-
- proto.visit = function(parentCmd){
- var node = this._node;
- if (!node._visible)
- return;
- node._adaptRenderers();
- node._doLayout();
-
- if (node._clippingEnabled) {
- switch (node._clippingType) {
- case ccui.Layout.CLIPPING_STENCIL:
- this.stencilClippingVisit(parentCmd);
- break;
- case ccui.Layout.CLIPPING_SCISSOR:
- this.scissorClippingVisit(parentCmd);
- break;
- default:
- break;
- }
- } else {
- this.widgetVisit(parentCmd);
- }
- };
-
- proto.layoutVisit = proto.visit;
-
- proto._onRenderSaveCmd = function(ctx, scaleX, scaleY){
+ proto._onRenderSaveCmd = function (ctx, scaleX, scaleY) {
var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
wrapper.save();
wrapper.save();
@@ -81,31 +48,31 @@
var element = buffer[i], vertices = element.verts;
var firstPoint = vertices[0];
context.beginPath();
- context.moveTo(firstPoint.x, -firstPoint.y );
+ context.moveTo(firstPoint.x, -firstPoint.y);
for (var j = 1, len = vertices.length; j < len; j++)
- context.lineTo(vertices[j].x , -vertices[j].y );
+ context.lineTo(vertices[j].x, -vertices[j].y);
context.closePath();
}
};
- proto._onRenderClipCmd = function(ctx){
+ proto._onRenderClipCmd = function (ctx) {
var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
wrapper.restore();
context.clip();
};
- proto._onRenderRestoreCmd = function(ctx){
+ proto._onRenderRestoreCmd = function (ctx) {
var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
wrapper.restore();
};
- proto.rebindStencilRendering = function(stencil){
+ proto.rebindStencilRendering = function (stencil) {
stencil._renderCmd.rendering = this.__stencilDraw;
stencil._renderCmd._canUseDirtyRegion = true;
};
- proto.__stencilDraw = function(ctx,scaleX, scaleY){ //Only for Canvas
+ proto.__stencilDraw = function (ctx, scaleX, scaleY) { //Only for Canvas
//do nothing, rendering in layout
};
@@ -114,42 +81,23 @@
if (!node._clippingStencil || !node._clippingStencil.isVisible())
return;
- this._syncStatus(parentCmd);
+ if (!this._rendererSaveCmd) {
+ this._rendererSaveCmd = new cc.CustomRenderCmd(this, this._onRenderSaveCmd);
+ this._rendererClipCmd = new cc.CustomRenderCmd(this, this._onRenderClipCmd);
+ this._rendererRestoreCmd = new cc.CustomRenderCmd(this, this._onRenderRestoreCmd);
+ }
cc.renderer.pushRenderCommand(this._rendererSaveCmd);
node._clippingStencil.visit(this);
cc.renderer.pushRenderCommand(this._rendererClipCmd);
- node.sortAllChildren();
- node.sortAllProtectedChildren();
-
- var children = node._children;
- var j=0, locProtectChildren = node._protectedChildren, i = 0, locChild;
- var iLen = children.length, jLen = locProtectChildren.length;
-
- for( ; i < iLen; i++ ){
- locChild = children[i];
- if ( locChild && locChild.getLocalZOrder() < 0 )
- locChild.visit(this);
- else
- break;
- }
- for( ; j < jLen; j++ ) {
- locChild = locProtectChildren[j];
- if ( locChild && locChild.getLocalZOrder() < 0 )
- locChild.visit(this);
- else
- break;
- }
- for (; i < iLen; i++)
- children[i].visit(this);
- for (; j < jLen; j++)
- locProtectChildren[j].visit(this);
- cc.renderer.pushRenderCommand(this._rendererRestoreCmd);
- this._dirtyFlag = 0;
+ };
+
+ proto.postStencilVisit = proto.postScissorVisit = function () {
+ cc.renderer.pushRenderCommand(this._rendererRestoreCmd);
};
ccui.Layout.CanvasRenderCmd._getSharedCache = function () {
return (cc.ClippingNode._sharedCache) || (cc.ClippingNode._sharedCache = document.createElement("canvas"));
};
-})();
\ No newline at end of file
+})();
diff --git a/extensions/ccui/layouts/UILayoutManager.js b/extensions/ccui/layouts/UILayoutManager.js
index d69a36618c..9f89d13e75 100644
--- a/extensions/ccui/layouts/UILayoutManager.js
+++ b/extensions/ccui/layouts/UILayoutManager.js
@@ -45,7 +45,7 @@ ccui.getLayoutManager = function (type) {
* @name ccui.linearVerticalLayoutManager
*/
ccui.linearVerticalLayoutManager = /** @lends ccui.linearVerticalLayoutManager# */{
- _doLayout: function(layout){
+ _doLayout: function (layout) {
var layoutSize = layout._getLayoutContentSize();
var container = layout._getLayoutElements();
var topBoundary = layoutSize.height;
@@ -55,13 +55,13 @@ ccui.linearVerticalLayoutManager = /** @lends ccui.linearVerticalLayoutManager#
if (child) {
var layoutParameter = child.getLayoutParameter();
- if (layoutParameter){
+ if (layoutParameter) {
var childGravity = layoutParameter.getGravity();
var ap = child.getAnchorPoint();
var cs = child.getContentSize();
var finalPosX = ap.x * cs.width;
var finalPosY = topBoundary - ((1.0 - ap.y) * cs.height);
- switch (childGravity){
+ switch (childGravity) {
case ccui.LinearLayoutParameter.NONE:
case ccui.LinearLayoutParameter.LEFT:
break;
@@ -91,21 +91,21 @@ ccui.linearVerticalLayoutManager = /** @lends ccui.linearVerticalLayoutManager#
* @name ccui.linearHorizontalLayoutManager
*/
ccui.linearHorizontalLayoutManager = /** @lends ccui.linearHorizontalLayoutManager# */{
- _doLayout: function(layout){
+ _doLayout: function (layout) {
var layoutSize = layout._getLayoutContentSize();
var container = layout._getLayoutElements();
var leftBoundary = 0.0;
- for (var i = 0, len = container.length; i < len; i++) {
+ for (var i = 0, len = container.length; i < len; i++) {
var child = container[i];
if (child) {
var layoutParameter = child.getLayoutParameter();
- if (layoutParameter){
+ if (layoutParameter) {
var childGravity = layoutParameter.getGravity();
var ap = child.getAnchorPoint();
var cs = child.getContentSize();
var finalPosX = leftBoundary + (ap.x * cs.width);
var finalPosY = layoutSize.height - (1.0 - ap.y) * cs.height;
- switch (childGravity){
+ switch (childGravity) {
case ccui.LinearLayoutParameter.NONE:
case ccui.LinearLayoutParameter.TOP:
break;
@@ -138,16 +138,16 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
_unlayoutChildCount: 0,
_widgetChildren: [],
_widget: null,
- _finalPositionX:0,
- _finalPositionY:0,
- _relativeWidgetLP:null,
+ _finalPositionX: 0,
+ _finalPositionY: 0,
+ _relativeWidgetLP: null,
- _doLayout: function(layout){
+ _doLayout: function (layout) {
this._widgetChildren = this._getAllWidgets(layout);
var locChildren = this._widgetChildren;
while (this._unlayoutChildCount > 0) {
- for (var i = 0, len = locChildren.length; i < len; i++) {
+ for (var i = 0, len = locChildren.length; i < len; i++) {
this._widget = locChildren[i];
var layoutParameter = this._widget.getLayoutParameter();
@@ -170,11 +170,11 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
this._widgetChildren.length = 0;
},
- _getAllWidgets: function(layout){
+ _getAllWidgets: function (layout) {
var container = layout._getLayoutElements();
var locWidgetChildren = this._widgetChildren;
locWidgetChildren.length = 0;
- for (var i = 0, len = container.length; i < len; i++){
+ for (var i = 0, len = container.length; i < len; i++) {
var child = container[i];
if (child && child instanceof ccui.Widget) {
var layoutParameter = child.getLayoutParameter();
@@ -186,18 +186,18 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
return locWidgetChildren;
},
- _getRelativeWidget: function(widget){
+ _getRelativeWidget: function (widget) {
var relativeWidget = null;
var layoutParameter = widget.getLayoutParameter();
var relativeName = layoutParameter.getRelativeToWidgetName();
if (relativeName && relativeName.length !== 0) {
- var locChildren = this._widgetChildren;
- for(var i = 0, len = locChildren.length; i < len; i++){
+ var locChildren = this._widgetChildren;
+ for (var i = 0, len = locChildren.length; i < len; i++) {
var child = locChildren[i];
if (child){
var rlayoutParameter = child.getLayoutParameter();
- if (rlayoutParameter && rlayoutParameter.getRelativeName() === relativeName) {
+ if (rlayoutParameter && rlayoutParameter.getRelativeName() === relativeName) {
relativeWidget = child;
this._relativeWidgetLP = rlayoutParameter;
break;
@@ -208,7 +208,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
return relativeWidget;
},
- _calculateFinalPositionWithRelativeWidget: function(layout){
+ _calculateFinalPositionWithRelativeWidget: function (layout) {
var locWidget = this._widget;
var ap = locWidget.getAnchorPoint();
var cs = locWidget.getContentSize();
@@ -261,7 +261,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
break;
case ccui.RelativeLayoutParameter.LOCATION_ABOVE_LEFTALIGN:
- if (relativeWidget){
+ if (relativeWidget) {
if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
return false;
this._finalPositionY = relativeWidget.getTopBoundary() + ap.y * cs.height;
@@ -269,7 +269,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
}
break;
case ccui.RelativeLayoutParameter.LOCATION_ABOVE_CENTER:
- if (relativeWidget){
+ if (relativeWidget) {
if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
return false;
var rbs = relativeWidget.getContentSize();
@@ -286,7 +286,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
}
break;
case ccui.RelativeLayoutParameter.LOCATION_LEFT_OF_TOPALIGN:
- if (relativeWidget){
+ if (relativeWidget) {
if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
return false;
this._finalPositionY = relativeWidget.getTopBoundary() - (1.0 - ap.y) * cs.height;
@@ -311,7 +311,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
}
break;
case ccui.RelativeLayoutParameter.LOCATION_RIGHT_OF_TOPALIGN:
- if (relativeWidget){
+ if (relativeWidget) {
if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
return false;
this._finalPositionY = relativeWidget.getTopBoundary() - (1.0 - ap.y) * cs.height;
@@ -319,7 +319,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
}
break;
case ccui.RelativeLayoutParameter.LOCATION_RIGHT_OF_CENTER:
- if (relativeWidget){
+ if (relativeWidget) {
if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
return false;
var rbs = relativeWidget.getContentSize();
@@ -329,7 +329,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
}
break;
case ccui.RelativeLayoutParameter.LOCATION_RIGHT_OF_BOTTOMALIGN:
- if (relativeWidget){
+ if (relativeWidget) {
if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
return false;
this._finalPositionY = relativeWidget.getBottomBoundary() + ap.y * cs.height;
@@ -337,10 +337,10 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
}
break;
case ccui.RelativeLayoutParameter.LOCATION_BELOW_LEFTALIGN:
- if (relativeWidget){
+ if (relativeWidget) {
if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
return false;
- this._finalPositionY = relativeWidget.getBottomBoundary() - (1.0 - ap.y) * cs.height;
+ this._finalPositionY = relativeWidget.getBottomBoundary() - (1.0 - ap.y) * cs.height;
this._finalPositionX = relativeWidget.getLeftBoundary() + ap.x * cs.width;
}
break;
@@ -367,7 +367,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
return true;
},
- _calculateFinalPositionWithRelativeAlign: function(){
+ _calculateFinalPositionWithRelativeAlign: function () {
var layoutParameter = this._widget.getLayoutParameter();
var mg = layoutParameter.getMargin();
@@ -454,4 +454,4 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
break;
}
}
-};
\ No newline at end of file
+};
diff --git a/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js
index 9fd8544f8c..a2ed43eb12 100644
--- a/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js
+++ b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js
@@ -23,11 +23,11 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- if(!ccui.ProtectedNode.WebGLRenderCmd)
+(function () {
+ if (!ccui.ProtectedNode.WebGLRenderCmd)
return;
- ccui.Layout.WebGLRenderCmd = function(renderable){
- ccui.ProtectedNode.WebGLRenderCmd.call(this, renderable);
+ ccui.Layout.WebGLRenderCmd = function (renderable) {
+ this._pNodeCmdCtor(renderable);
this._needDraw = false;
this._currentStencilEnabled = 0;
@@ -36,46 +36,25 @@
this._mask_layer_le = 0;
- this._beforeVisitCmdStencil = new cc.CustomRenderCmd(this, this._onBeforeVisitStencil);
- this._afterDrawStencilCmd = new cc.CustomRenderCmd(this, this._onAfterDrawStencil);
- this._afterVisitCmdStencil = new cc.CustomRenderCmd(this, this._onAfterVisitStencil);
- this._beforeVisitCmdScissor = new cc.CustomRenderCmd(this, this._onBeforeVisitScissor);
- this._afterVisitCmdScissor = new cc.CustomRenderCmd(this, this._onAfterVisitScissor);
+ this._beforeVisitCmdStencil = null;
+ this._afterDrawStencilCmd = null;
+ this._afterVisitCmdStencil = null;
+ this._beforeVisitCmdScissor = null;
+ this._afterVisitCmdScissor = null;
};
var proto = ccui.Layout.WebGLRenderCmd.prototype = Object.create(ccui.ProtectedNode.WebGLRenderCmd.prototype);
proto.constructor = ccui.Layout.WebGLRenderCmd;
+ proto._layoutCmdCtor = ccui.Layout.CanvasRenderCmd;
- proto.visit = function(parentCmd){
- var node = this._node;
- if (!node._visible)
- return;
+ proto._syncStatus = function (parentCmd) {
+ this._originSyncStatus(parentCmd);
- if(parentCmd && (parentCmd._dirtyFlag & cc.Node._dirtyFlags.transformDirty))
- node._clippingRectDirty = true;
-
- node._adaptRenderers();
- node._doLayout();
-
- if (node._clippingEnabled) {
- switch (node._clippingType) {
- case ccui.Layout.CLIPPING_STENCIL:
- this.stencilClippingVisit(parentCmd);
- break;
- case ccui.Layout.CLIPPING_SCISSOR:
- this.scissorClippingVisit(parentCmd);
- break;
- default:
- break;
- }
- } else {
- this.pNodeVisit(parentCmd);
- }
+ if (parentCmd && (parentCmd._dirtyFlag & cc.Node._dirtyFlags.transformDirty))
+ this._node._clippingRectDirty = true;
};
-
- proto.layoutVisit = proto.visit;
-
- proto._onBeforeVisitStencil = function(ctx){
+
+ proto._onBeforeVisitStencil = function (ctx) {
var gl = ctx || cc._renderContext;
ccui.Layout.WebGLRenderCmd._layer++;
@@ -101,20 +80,19 @@
};
- proto._onAfterDrawStencil = function(ctx){
+ proto._onAfterDrawStencil = function (ctx) {
var gl = ctx || cc._renderContext;
gl.depthMask(true);
gl.stencilFunc(gl.EQUAL, this._mask_layer_le, this._mask_layer_le);
gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
};
- proto._onAfterVisitStencil = function(ctx){
+ proto._onAfterVisitStencil = function (ctx) {
var gl = ctx || cc._renderContext;
ccui.Layout.WebGLRenderCmd._layer--;
- if (this._currentStencilEnabled)
- {
+ if (this._currentStencilEnabled) {
var mask_layer = 0x1 << ccui.Layout.WebGLRenderCmd._layer;
var mask_layer_l = mask_layer - 1;
var mask_layer_le = mask_layer | mask_layer_l;
@@ -122,13 +100,12 @@
gl.stencilMask(mask_layer);
gl.stencilFunc(gl.EQUAL, mask_layer_le, mask_layer_le);
}
- else
- {
+ else {
gl.disable(gl.STENCIL_TEST);
}
};
- proto._onBeforeVisitScissor = function(ctx){
+ proto._onBeforeVisitScissor = function (ctx) {
this._node._clippingRectDirty = true;
var clippingRect = this._node._getClippingRect();
var gl = ctx || cc._renderContext;
@@ -146,11 +123,11 @@
}
};
- proto._onAfterVisitScissor = function(ctx){
+ proto._onAfterVisitScissor = function (ctx) {
var gl = ctx || cc._renderContext;
if (this._scissorOldState) {
if (!cc.rectEqualToRect(this._clippingOldRect, this._node._clippingRect)) {
- cc.view.setScissorInPoints( this._clippingOldRect.x,
+ cc.view.setScissorInPoints(this._clippingOldRect.x,
this._clippingOldRect.y,
this._clippingOldRect.width,
this._clippingOldRect.height);
@@ -160,13 +137,14 @@
gl.disable(gl.SCISSOR_TEST);
}
};
-
- proto.rebindStencilRendering = function(stencil){};
- proto.transform = function(parentCmd, recursive){
+ proto.rebindStencilRendering = function (stencil) {
+ };
+
+ proto.transform = function (parentCmd, recursive) {
var node = this._node;
this.pNodeTransform(parentCmd, recursive);
- if(node._clippingStencil)
+ if (node._clippingStencil)
node._clippingStencil._renderCmd.transform(this, recursive);
};
@@ -184,60 +162,41 @@
ccui.Layout.WebGLRenderCmd._visit_once = false;
}
// draw everything, as if there where no stencil
- cc.Node.prototype.visit.call(node, parentCmd);
return;
}
+ if (!this._beforeVisitCmdStencil) {
+ this._beforeVisitCmdStencil = new cc.CustomRenderCmd(this, this._onBeforeVisitStencil);
+ this._afterDrawStencilCmd = new cc.CustomRenderCmd(this, this._onAfterDrawStencil);
+ this._afterVisitCmdStencil = new cc.CustomRenderCmd(this, this._onAfterVisitStencil);
+ }
+
cc.renderer.pushRenderCommand(this._beforeVisitCmdStencil);
//optimize performance for javascript
var currentStack = cc.current_stack;
currentStack.stack.push(currentStack.top);
- this._syncStatus(parentCmd);
- this._dirtyFlag = 0;
currentStack.top = this._stackMatrix;
node._clippingStencil.visit(this);
cc.renderer.pushRenderCommand(this._afterDrawStencilCmd);
+ };
- // draw (according to the stencil test func) this node and its childs
- var i = 0; // used by _children
- var j = 0; // used by _protectedChildren
-
- node.sortAllChildren();
- node.sortAllProtectedChildren();
- var locChildren = node._children, locProtectChildren = node._protectedChildren;
- var iLen = locChildren.length, jLen = locProtectChildren.length, child;
- for( ; i < iLen; i++ ){
- child = locChildren[i];
- if ( child && child.getLocalZOrder() < 0 )
- child.visit(this);
- else
- break;
- }
- for( ; j < jLen; j++ ) {
- child = locProtectChildren[j];
- if ( child && child.getLocalZOrder() < 0 )
- child.visit(this);
- else
- break;
- }
-
- for (; i < iLen; i++)
- locChildren[i].visit(this);
- for (; j < jLen; j++)
- locProtectChildren[j].visit(this);
-
- cc.renderer.pushRenderCommand(this._afterVisitCmdStencil);
-
- //optimize performance for javascript
- currentStack.top = currentStack.stack.pop();
+ proto.postStencilVisit = function () {
+ renderer.pushRenderCommand(cmd._afterVisitCmdStencil);
+ cc.current_stack.top = cc.current_stack.stack.pop();
};
- proto.scissorClippingVisit = function(parentCmd){
+ proto.scissorClippingVisit = function (parentCmd) {
+ if (!this._beforeVisitCmdScissor) {
+ this._beforeVisitCmdScissor = new cc.CustomRenderCmd(this, this._onBeforeVisitScissor);
+ this._afterVisitCmdScissor = new cc.CustomRenderCmd(this, this._onAfterVisitScissor);
+ }
cc.renderer.pushRenderCommand(this._beforeVisitCmdScissor);
- this.pNodeVisit(parentCmd);
+ };
+
+ proto.postScissorVisit = function () {
cc.renderer.pushRenderCommand(this._afterVisitCmdScissor);
};
diff --git a/extensions/ccui/system/UIHelper.js b/extensions/ccui/system/UIHelper.js
index ec4ba83de5..327bf8dca6 100644
--- a/extensions/ccui/system/UIHelper.js
+++ b/extensions/ccui/system/UIHelper.js
@@ -32,71 +32,71 @@
* @name ccui.helper
*/
ccui.helper = {
- /**
- * Finds a widget whose tag equals to param tag from root widget.
- * @param {ccui.Widget} root
- * @param {number} tag
- * @returns {ccui.Widget}
- */
- seekWidgetByTag: function (root, tag) {
- if (!root)
- return null;
- if (root.getTag() === tag)
- return root;
-
- var arrayRootChildren = root.getChildren();
- var length = arrayRootChildren.length;
- for (var i = 0; i < length; i++) {
- var child = arrayRootChildren[i];
- var res = ccui.helper.seekWidgetByTag(child, tag);
- if (res !== null)
- return res;
- }
- return null;
- },
-
- /**
- * Finds a widget whose name equals to param name from root widget.
- * @param {ccui.Widget} root
- * @param {String} name
- * @returns {ccui.Widget}
- */
- seekWidgetByName: function (root, name) {
- if (!root)
- return null;
- if (root.getName() === name)
- return root;
- var arrayRootChildren = root.getChildren();
- var length = arrayRootChildren.length;
- for (var i = 0; i < length; i++) {
- var child = arrayRootChildren[i];
- var res = ccui.helper.seekWidgetByName(child, name);
- if (res !== null)
- return res;
- }
- return null;
- },
-
- /**
- * Finds a widget whose name equals to param name from root widget.
- * RelativeLayout will call this method to find the widget witch is needed.
- * @param {ccui.Widget} root
- * @param {String} name
- * @returns {ccui.Widget}
- */
- seekWidgetByRelativeName: function (root, name) {
- if (!root)
- return null;
- var arrayRootChildren = root.getChildren();
- var length = arrayRootChildren.length;
- for (var i = 0; i < length; i++) {
- var child = arrayRootChildren[i];
- var layoutParameter = child.getLayoutParameter(ccui.LayoutParameter.RELATIVE);
- if (layoutParameter && layoutParameter.getRelativeName() === name)
- return child;
- }
- return null;
- },
+ /**
+ * Finds a widget whose tag equals to param tag from root widget.
+ * @param {ccui.Widget} root
+ * @param {number} tag
+ * @returns {ccui.Widget}
+ */
+ seekWidgetByTag: function (root, tag) {
+ if (!root)
+ return null;
+ if (root.getTag() === tag)
+ return root;
+
+ var arrayRootChildren = root.getChildren();
+ var length = arrayRootChildren.length;
+ for (var i = 0; i < length; i++) {
+ var child = arrayRootChildren[i];
+ var res = ccui.helper.seekWidgetByTag(child, tag);
+ if (res !== null)
+ return res;
+ }
+ return null;
+ },
+
+ /**
+ * Finds a widget whose name equals to param name from root widget.
+ * @param {ccui.Widget} root
+ * @param {String} name
+ * @returns {ccui.Widget}
+ */
+ seekWidgetByName: function (root, name) {
+ if (!root)
+ return null;
+ if (root.getName() === name)
+ return root;
+ var arrayRootChildren = root.getChildren();
+ var length = arrayRootChildren.length;
+ for (var i = 0; i < length; i++) {
+ var child = arrayRootChildren[i];
+ var res = ccui.helper.seekWidgetByName(child, name);
+ if (res !== null)
+ return res;
+ }
+ return null;
+ },
+
+ /**
+ * Finds a widget whose name equals to param name from root widget.
+ * RelativeLayout will call this method to find the widget witch is needed.
+ * @param {ccui.Widget} root
+ * @param {String} name
+ * @returns {ccui.Widget}
+ */
+ seekWidgetByRelativeName: function (root, name) {
+ if (!root)
+ return null;
+ var arrayRootChildren = root.getChildren();
+ var length = arrayRootChildren.length;
+ for (var i = 0; i < length; i++) {
+ var child = arrayRootChildren[i];
+ var layoutParameter = child.getLayoutParameter(ccui.LayoutParameter.RELATIVE);
+ if (layoutParameter && layoutParameter.getRelativeName() === name)
+ return child;
+ }
+ return null;
+ },
/**
* Finds a widget whose action tag equals to param name from root widget.
@@ -104,28 +104,28 @@ ccui.helper = {
* @param {Number} tag
* @returns {ccui.Widget}
*/
- seekActionWidgetByActionTag: function (root, tag) {
- if (!root)
- return null;
- if (root.getActionTag() === tag)
- return root;
- var arrayRootChildren = root.getChildren();
- for (var i = 0; i < arrayRootChildren.length; i++) {
- var child = arrayRootChildren[i];
- var res = ccui.helper.seekActionWidgetByActionTag(child, tag);
- if (res !== null)
- return res;
- }
- return null;
- } ,
+ seekActionWidgetByActionTag: function (root, tag) {
+ if (!root)
+ return null;
+ if (root.getActionTag() === tag)
+ return root;
+ var arrayRootChildren = root.getChildren();
+ for (var i = 0; i < arrayRootChildren.length; i++) {
+ var child = arrayRootChildren[i];
+ var res = ccui.helper.seekActionWidgetByActionTag(child, tag);
+ if (res !== null)
+ return res;
+ }
+ return null;
+ },
_activeLayout: true,
/**
* Refresh object and it's children layout state
* @param {cc.Node} rootNode
*/
- doLayout: function(rootNode){
- if(!this._activeLayout)
+ doLayout: function (rootNode) {
+ if (!this._activeLayout)
return;
var children = rootNode.getChildren(), node;
for(var i = 0, len = children.length;i < len; i++) {
@@ -137,7 +137,7 @@ ccui.helper = {
}
},
- changeLayoutSystemActiveState: function(active){
+ changeLayoutSystemActiveState: function (active) {
this._activeLayout = active;
},
@@ -162,10 +162,10 @@ ccui.helper = {
return cc.rect(x, y, width, height);
},
- _createSpriteFromBase64: function(base64String, key) {
+ _createSpriteFromBase64: function (base64String, key) {
var texture2D = cc.textureCache.getTextureForKey(key);
- if(!texture2D) {
+ if (!texture2D) {
var image = new Image();
image.src = base64String;
cc.textureCache.cacheImage(key, image);
diff --git a/extensions/ccui/uiwidgets/UILoadingBar.js b/extensions/ccui/uiwidgets/UILoadingBar.js
index 9113121c6d..1fdba04c17 100644
--- a/extensions/ccui/uiwidgets/UILoadingBar.js
+++ b/extensions/ccui/uiwidgets/UILoadingBar.js
@@ -61,9 +61,9 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
this._capInsets = cc.rect(0, 0, 0, 0);
ccui.Widget.prototype.ctor.call(this);
- if(textureName !== undefined)
+ if (textureName !== undefined)
this.loadTexture(textureName);
- if(percentage !== undefined)
+ if (percentage !== undefined)
this.setPercent(percentage);
},
@@ -86,16 +86,16 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
switch (this._direction) {
case ccui.LoadingBar.TYPE_LEFT:
this._barRenderer.setAnchorPoint(0, 0.5);
- this._barRenderer.setPosition(0, this._contentSize.height*0.5);
- if (!this._scale9Enabled)
- this._barRenderer.setFlippedX(false);
+ this._barRenderer.setPosition(0, this._contentSize.height * 0.5);
+ if (!this._scale9Enabled)
+ this._barRenderer.setFlippedX(false);
break;
case ccui.LoadingBar.TYPE_RIGHT:
this._barRenderer.setAnchorPoint(1, 0.5);
- this._barRenderer.setPosition(this._totalLength,this._contentSize.height*0.5);
- if (!this._scale9Enabled)
- this._barRenderer.setFlippedX(true);
+ this._barRenderer.setPosition(this._totalLength, this._contentSize.height * 0.5);
+ if (!this._scale9Enabled)
+ this._barRenderer.setFlippedX(true);
break;
}
@@ -124,8 +124,8 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
var barRenderer = this._barRenderer;
var self = this;
- if(!barRenderer._textureLoaded){
- barRenderer.addEventListener("load", function(){
+ if (!barRenderer._textureLoaded) {
+ barRenderer.addEventListener("load", function () {
self.loadTexture(self._textureFile, self._renderBarTexType);
self._setPercent(self._percent);
});
@@ -148,12 +148,12 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
switch (this._direction) {
case ccui.LoadingBar.TYPE_LEFT:
- barRenderer.setAnchorPoint(0,0.5);
+ barRenderer.setAnchorPoint(0, 0.5);
if (!this._scale9Enabled)
barRenderer.setFlippedX(false);
break;
case ccui.LoadingBar.TYPE_RIGHT:
- barRenderer.setAnchorPoint(1,0.5);
+ barRenderer.setAnchorPoint(1, 0.5);
if (!this._scale9Enabled)
barRenderer.setFlippedX(true);
break;
@@ -207,7 +207,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
* @param {cc.Rect} capInsets
*/
setCapInsets: function (capInsets) {
- if(!capInsets)
+ if (!capInsets)
return;
var locInsets = this._capInsets;
locInsets.x = capInsets.x;
@@ -232,9 +232,9 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
* @param {number} percent percent value from 1 to 100.
*/
setPercent: function (percent) {
- if(percent > 100)
+ if (percent > 100)
percent = 100;
- if(percent < 0)
+ if (percent < 0)
percent = 0;
if (percent === this._percent)
return;
@@ -242,7 +242,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
this._setPercent(percent);
},
- _setPercent: function(){
+ _setPercent: function () {
var res, rect, spriteRenderer, spriteTextureRect;
if (this._totalLength <= 0)
@@ -274,7 +274,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
* @param {Number|cc.Size} contentSize
* @param {Number} [height]
*/
- setContentSize: function(contentSize, height){
+ setContentSize: function (contentSize, height) {
ccui.Widget.prototype.setContentSize.call(this, contentSize, height);
this._totalLength = (height === undefined) ? contentSize.width : contentSize;
},
@@ -292,8 +292,8 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
this._barRendererAdaptDirty = true;
},
- _adaptRenderers: function(){
- if (this._barRendererAdaptDirty){
+ _adaptRenderers: function () {
+ if (this._barRendererAdaptDirty) {
this._barRendererScaleChangedWithSize();
this._barRendererAdaptDirty = false;
}
@@ -315,7 +315,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
* Returns the texture size of renderer.
* @returns {cc.Size|*}
*/
- getVirtualRendererSize:function(){
+ getVirtualRendererSize: function () {
return cc.size(this._barRendererTextureSize);
},
@@ -340,7 +340,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
}
} else {
this._totalLength = locContentSize.width;
- if (this._scale9Enabled){
+ if (this._scale9Enabled) {
this._setScale9Scale();
locBarRender.setScale(1.0);
} else {
@@ -385,7 +385,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
},
_copySpecialProperties: function (loadingBar) {
- if(loadingBar instanceof ccui.LoadingBar){
+ if (loadingBar instanceof ccui.LoadingBar) {
this._prevIgnoreSize = loadingBar._prevIgnoreSize;
this.setScale9Enabled(loadingBar._scale9Enabled);
this.loadTexture(loadingBar._textureFile, loadingBar._renderBarTexType);
@@ -440,4 +440,4 @@ ccui.LoadingBar.TYPE_RIGHT = 1;
* @constant
* @type {number}
*/
-ccui.LoadingBar.RENDERER_ZORDER = -1;
\ No newline at end of file
+ccui.LoadingBar.RENDERER_ZORDER = -1;
diff --git a/extensions/ccui/uiwidgets/UIRichText.js b/extensions/ccui/uiwidgets/UIRichText.js
index 1247d00f7d..c0572561f4 100644
--- a/extensions/ccui/uiwidgets/UIRichText.js
+++ b/extensions/ccui/uiwidgets/UIRichText.js
@@ -32,7 +32,7 @@ ccui.RichElement = ccui.Class.extend(/** @lends ccui.RichElement# */{
_type: 0,
_tag: 0,
_color: null,
- _opacity:0,
+ _opacity: 0,
/**
* Constructor of ccui.RichElement
*/
@@ -46,7 +46,7 @@ ccui.RichElement = ccui.Class.extend(/** @lends ccui.RichElement# */{
this._color.b = color.b;
}
this._opacity = opacity || 0;
- if(opacity === undefined) {
+ if (opacity === undefined) {
this._color.a = color.a;
}
else {
@@ -256,7 +256,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{
removeElement: function (element) {
if (cc.isNumber(element))
this._richElements.splice(element, 1);
- else
+ else
cc.arrayRemoveObject(this._richElements, element);
this._formatTextDirty = true;
},
@@ -276,7 +276,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{
var elementRenderer = null;
switch (element._type) {
case ccui.RichElement.TEXT:
- if( element._fontDefinition)
+ if (element._fontDefinition)
elementRenderer = new cc.LabelTTF(element._text, element._fontDefinition);
else //todo: There may be ambiguous
elementRenderer = new cc.LabelTTF(element._text, element._fontName, element._fontSize);
@@ -300,7 +300,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{
element = locRichElements[i];
switch (element._type) {
case ccui.RichElement.TEXT:
- if( element._fontDefinition)
+ if (element._fontDefinition)
this._handleTextRenderer(element._text, element._fontDefinition, element._fontDefinition.fontSize, element._fontDefinition.fillStyle);
else
this._handleTextRenderer(element._text, element._fontName, element._fontSize, element._color);
@@ -329,10 +329,10 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{
* @private
*/
_handleTextRenderer: function (text, fontNameOrFontDef, fontSize, color) {
- if(text === "")
+ if (text === "")
return;
- if(text === "\n"){ //Force Line Breaking
+ if (text === "\n") { //Force Line Breaking
this._addNewLine();
return;
}
@@ -349,21 +349,20 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{
var cutWords = curText.substr(leftLength, curText.length - 1);
var validLeftLength = leftLength > 0;
- if(this._lineBreakOnSpace){
+ if (this._lineBreakOnSpace) {
var lastSpaceIndex = leftWords.lastIndexOf(' ');
- leftLength = lastSpaceIndex === -1 ? leftLength : lastSpaceIndex+1 ;
+ leftLength = lastSpaceIndex === -1 ? leftLength : lastSpaceIndex + 1;
cutWords = curText.substr(leftLength, curText.length - 1);
validLeftLength = leftLength > 0 && cutWords !== " ";
}
if (validLeftLength) {
var leftRenderer = null;
- if( fontNameOrFontDef instanceof cc.FontDefinition)
- {
+ if (fontNameOrFontDef instanceof cc.FontDefinition) {
leftRenderer = new cc.LabelTTF(leftWords.substr(0, leftLength), fontNameOrFontDef);
leftRenderer.setOpacity(fontNameOrFontDef.fillStyle.a); //TODO: Verify that might not be needed...
- }else{
- leftRenderer = new cc.LabelTTF(leftWords.substr(0, leftLength), fontNameOrFontDef, fontSize);
+ } else {
+ leftRenderer = new cc.LabelTTF(leftWords.substr(0, leftLength), fontNameOrFontDef, fontSize);
leftRenderer.setColor(color);
leftRenderer.setOpacity(color.a);
}
@@ -373,9 +372,9 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{
this._addNewLine();
this._handleTextRenderer(cutWords, fontNameOrFontDef, fontSize, color);
} else {
- if( fontNameOrFontDef instanceof cc.FontDefinition) {
+ if (fontNameOrFontDef instanceof cc.FontDefinition) {
textRenderer.setOpacity(fontNameOrFontDef.fillStyle.a); //TODO: Verify that might not be needed...
- }else {
+ } else {
textRenderer.setColor(color);
textRenderer.setOpacity(color.a);
}
@@ -432,7 +431,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{
}
//Text flow horizontal alignment:
- if(this._textHorizontalAlignment !== cc.TEXT_ALIGNMENT_LEFT) {
+ if (this._textHorizontalAlignment !== cc.TEXT_ALIGNMENT_LEFT) {
offsetX = 0;
if (this._textHorizontalAlignment === cc.TEXT_ALIGNMENT_RIGHT)
offsetX = this._contentSize.width - nextPosX;
@@ -473,7 +472,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{
nextPosX += l.getContentSize().width;
}
//Text flow alignment(s)
- if( this._textHorizontalAlignment !== cc.TEXT_ALIGNMENT_LEFT || this._textVerticalAlignment !== cc.VERTICAL_TEXT_ALIGNMENT_TOP) {
+ if (this._textHorizontalAlignment !== cc.TEXT_ALIGNMENT_LEFT || this._textVerticalAlignment !== cc.VERTICAL_TEXT_ALIGNMENT_TOP) {
offsetX = 0;
if (this._textHorizontalAlignment === cc.TEXT_ALIGNMENT_RIGHT)
offsetX = this._contentSize.width - nextPosX;
@@ -498,12 +497,12 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{
}
var length = locElementRenders.length;
- for (i = 0; i= ballRect.x &&
nsp.x <= (ballRect.x + ballRect.width) &&
nsp.y >= ballRect.y &&
@@ -507,7 +506,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{
* @returns {number}
*/
_getPercentWithBallPos: function (px) {
- return ((px/this._barLength)*100);
+ return ((px / this._barLength) * 100);
},
/**
@@ -525,13 +524,13 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{
* @param {Function} selector
* @param {Object} [target=]
*/
- addEventListener: function(selector, target){
+ addEventListener: function (selector, target) {
this._sliderEventSelector = selector; //when target is undefined, _sliderEventSelector = _eventCallback
this._sliderEventListener = target;
},
_percentChangedEvent: function () {
- if(this._sliderEventSelector){
+ if (this._sliderEventSelector) {
if (this._sliderEventListener)
this._sliderEventSelector.call(this._sliderEventListener, this, ccui.Slider.EVENT_PERCENT_CHANGED);
else
@@ -555,14 +554,12 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{
this._progressBarRendererDirty = true;
},
- _adaptRenderers: function(){
- if (this._barRendererAdaptDirty)
- {
+ _adaptRenderers: function () {
+ if (this._barRendererAdaptDirty) {
this._barRendererScaleChangedWithSize();
this._barRendererAdaptDirty = false;
}
- if (this._progressBarRendererDirty)
- {
+ if (this._progressBarRendererDirty) {
this._progressBarRendererScaleChangedWithSize();
this._progressBarRendererDirty = false;
}
@@ -572,7 +569,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{
* Returns the content size of bar renderer.
* @returns {cc.Size}
*/
- getVirtualRendererSize: function(){
+ getVirtualRendererSize: function () {
return this._barRenderer.getContentSize();
},
@@ -585,13 +582,13 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{
},
_barRendererScaleChangedWithSize: function () {
- if (this._unifySize){
+ if (this._unifySize) {
this._barLength = this._contentSize.width;
this._barRenderer.setPreferredSize(this._contentSize);
- }else if(this._ignoreSize) {
+ } else if (this._ignoreSize) {
this._barRenderer.setScale(1.0);
this._barLength = this._contentSize.width;
- }else {
+ } else {
this._barLength = this._contentSize.width;
if (this._scale9Enabled) {
this._barRenderer.setPreferredSize(this._contentSize);
@@ -600,7 +597,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{
var btextureSize = this._barTextureSize;
if (btextureSize.width <= 0.0 || btextureSize.height <= 0.0) {
this._barRenderer.setScale(1.0);
- }else{
+ } else {
var bscaleX = this._contentSize.width / btextureSize.width;
var bscaleY = this._contentSize.height / btextureSize.height;
this._barRenderer.setScaleX(bscaleX);
@@ -613,9 +610,9 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{
},
_progressBarRendererScaleChangedWithSize: function () {
- if(this._unifySize){
+ if (this._unifySize) {
this._progressBarRenderer.setPreferredSize(this._contentSize);
- }else if(this._ignoreSize) {
+ } else if (this._ignoreSize) {
if (!this._scale9Enabled) {
var ptextureSize = this._progressBarTextureSize;
var pscaleX = this._contentSize.width / ptextureSize.width;
@@ -654,9 +651,9 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{
},
_onPressStateChangedToPressed: function () {
- if (!this._slidBallPressedTextureFile){
+ if (!this._slidBallPressedTextureFile) {
this._slidBallNormalRenderer.setScale(this._sliderBallNormalTextureScaleX + this._zoomScale, this._sliderBallNormalTextureScaleY + this._zoomScale);
- }else{
+ } else {
this._slidBallNormalRenderer.setVisible(false);
this._slidBallPressedRenderer.setVisible(true);
this._slidBallDisabledRenderer.setVisible(false);
@@ -664,7 +661,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{
},
_onPressStateChangedToDisabled: function () {
- if (this._slidBallDisabledTextureFile){
+ if (this._slidBallDisabledTextureFile) {
this._slidBallNormalRenderer.setVisible(false);
this._slidBallDisabledRenderer.setVisible(true);
}
@@ -672,27 +669,27 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{
this._slidBallPressedRenderer.setVisible(false);
},
- setZoomScale: function(scale){
+ setZoomScale: function (scale) {
this._zoomScale = scale;
},
- getZoomScale: function(){
+ getZoomScale: function () {
return this._zoomScale;
},
- getSlidBallNormalRenderer : function () {
+ getSlidBallNormalRenderer: function () {
return this._slidBallNormalRenderer;
},
- getSlidBallPressedRenderer : function () {
+ getSlidBallPressedRenderer: function () {
return this._slidBallPressedRenderer;
},
- getSlidBallDisabledRenderer : function () {
+ getSlidBallDisabledRenderer: function () {
return this._slidBallDisabledRenderer;
},
- getSlidBallRenderer : function () {
+ getSlidBallRenderer: function () {
return this._slidBallRenderer;
},
@@ -770,4 +767,4 @@ ccui.Slider.PROGRESSBAR_RENDERER_ZORDER = -2;
* @constant
* @type {number}
*/
-ccui.Slider.BALL_RENDERER_ZORDER = -1;
\ No newline at end of file
+ccui.Slider.BALL_RENDERER_ZORDER = -1;
diff --git a/extensions/ccui/uiwidgets/UIText.js b/extensions/ccui/uiwidgets/UIText.js
index bfa1198a77..adc25f3573 100644
--- a/extensions/ccui/uiwidgets/UIText.js
+++ b/extensions/ccui/uiwidgets/UIText.js
@@ -45,7 +45,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
_normalScaleValueY: 1,
_fontName: "Arial",
_fontSize: 16,
- _onSelectedScaleOffset:0.5,
+ _onSelectedScaleOffset: 0.5,
_labelRenderer: null,
_textAreaSize: null,
_textVerticalAlignment: 0,
@@ -98,13 +98,20 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
* @param {String} text
*/
setString: function (text) {
- if(text === this._labelRenderer.getString())
- return;
+ if(text === this._labelRenderer.getString()) return;
+
this._labelRenderer.setString(text);
this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize());
this._labelRendererAdaptDirty = true;
},
+ _setString: function (text) {
+ if(text === this._labelRenderer.getString()) return;
+
+ this._labelRenderer.setString(text);
+ this._labelRendererAdaptDirty = true;
+ },
+
/**
* Gets the string value of ccui.Text.
* @deprecated since v3.0, please use getString instead.
@@ -142,6 +149,12 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
this._labelRendererAdaptDirty = true;
},
+ _setFontSize: function (size) {
+ this._labelRenderer.setFontSize(size);
+ this._fontSize = size;
+ this._labelRendererAdaptDirty = true;
+ },
+
/**
* Returns font Size of ccui.Text
* @returns {Number}
@@ -161,6 +174,16 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
this._labelRendererAdaptDirty = true;
},
+ _setFontName: function (name) {
+ this._fontName = name;
+ this._labelRenderer.setFontName(name);
+ this._labelRendererAdaptDirty = true;
+ },
+
+ _updateUITextContentSize: function () {
+ this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize());
+ },
+
/**
* Returns font name of ccui.Text.
* @returns {string}
@@ -186,8 +209,8 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
* Returns the type of ccui.Text.
* @returns {null}
*/
- getType: function(){
- return this._type;
+ getType: function () {
+ return this._type;
},
/**
@@ -196,18 +219,26 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
*/
setTextAreaSize: function (size) {
this._labelRenderer.setDimensions(size);
- if (!this._ignoreSize){
+ if (!this._ignoreSize) {
this._customSize = size;
}
this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize());
this._labelRendererAdaptDirty = true;
},
+ _setTextAreaSize: function (size) {
+ this._labelRenderer.setDimensions(size);
+ if (!this._ignoreSize){
+ this._customSize = size;
+ }
+ this._labelRendererAdaptDirty = true;
+ },
+
/**
* Returns renderer's dimension.
* @returns {cc.Size}
*/
- getTextAreaSize: function(){
+ getTextAreaSize: function () {
return this._labelRenderer.getDimensions();
},
@@ -221,6 +252,12 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
this._labelRendererAdaptDirty = true;
},
+
+ _setTextHorizontalAlignment: function (alignment) {
+ this._labelRenderer.setHorizontalAlignment(alignment);
+ this._labelRendererAdaptDirty = true;
+ },
+
/**
* Returns Horizontal Alignment of label
* @returns {TEXT_ALIGNMENT_LEFT|TEXT_ALIGNMENT_CENTER|TEXT_ALIGNMENT_RIGHT}
@@ -239,6 +276,10 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
this._labelRendererAdaptDirty = true;
},
+ _setTextVerticalAlignment: function (alignment) {
+ this._labelRenderer.setVerticalAlignment(alignment);
+ this._labelRendererAdaptDirty = true;
+ },
/**
* Gets text vertical alignment.
* @returns {VERTICAL_TEXT_ALIGNMENT_TOP|VERTICAL_TEXT_ALIGNMENT_CENTER|VERTICAL_TEXT_ALIGNMENT_BOTTOM}
@@ -285,7 +326,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
this._labelRendererAdaptDirty = true;
},
- _adaptRenderers: function(){
+ _adaptRenderers: function () {
if (this._labelRendererAdaptDirty) {
this._labelScaleChangedWithSize();
this._labelRendererAdaptDirty = false;
@@ -297,7 +338,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
* @override
* @returns {cc.Size}
*/
- getVirtualRendererSize: function(){
+ getVirtualRendererSize: function () {
return this._labelRenderer.getContentSize();
},
@@ -310,7 +351,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
},
//@since v3.3
- getAutoRenderSize: function(){
+ getAutoRenderSize: function () {
var virtualSize = this._labelRenderer.getContentSize();
if (!this._ignoreSize) {
this._labelRenderer.setDimensions(0, 0);
@@ -323,7 +364,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
_labelScaleChangedWithSize: function () {
var locContentSize = this._contentSize;
if (this._ignoreSize) {
- this._labelRenderer.setDimensions(0,0);
+ this._labelRenderer.setDimensions(0, 0);
this._labelRenderer.setScale(1.0);
this._normalScaleValueX = this._normalScaleValueY = 1;
} else {
@@ -357,7 +398,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
* @param {cc.Size} offset
* @param {Number} blurRadius
*/
- enableShadow: function(shadowColor, offset, blurRadius){
+ enableShadow: function (shadowColor, offset, blurRadius) {
this._labelRenderer.enableShadow(shadowColor, offset, blurRadius);
},
@@ -366,7 +407,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
* @param {cc.Color} outlineColor
* @param {cc.Size} outlineSize
*/
- enableOutline: function(outlineColor, outlineSize){
+ enableOutline: function (outlineColor, outlineSize) {
this._labelRenderer.enableStroke(outlineColor, outlineSize);
},
@@ -374,7 +415,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
* Enables glow color
* @param glowColor
*/
- enableGlow: function(glowColor){
+ enableGlow: function (glowColor) {
if (this._type === ccui.Text.Type.TTF)
this._labelRenderer.enableGlow(glowColor);
},
@@ -382,8 +423,8 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
/**
* Disables renderer's effect.
*/
- disableEffect: function(){
- if(this._labelRenderer.disableEffect)
+ disableEffect: function () {
+ if (this._labelRenderer.disableEffect)
this._labelRenderer.disableEffect();
},
@@ -392,7 +433,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
},
_copySpecialProperties: function (uiLabel) {
- if(uiLabel instanceof ccui.Text){
+ if (uiLabel instanceof ccui.Text) {
this.setFontName(uiLabel._fontName);
this.setFontSize(uiLabel.getFontSize());
this.setString(uiLabel.getString());
@@ -422,20 +463,20 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
return this._textAreaSize.height;
},
- _changePosition: function(){
+ _changePosition: function () {
this._adaptRenderers();
},
- setColor: function(color){
+ setColor: function (color) {
cc.ProtectedNode.prototype.setColor.call(this, color);
this._labelRenderer.setColor(color);
},
- setTextColor: function(color){
+ setTextColor: function (color) {
this._labelRenderer.setFontFillColor(color);
},
- getTextColor: function(){
+ getTextColor: function () {
return this._labelRenderer._getFillStyle();
}
});
@@ -495,4 +536,4 @@ ccui.Text.RENDERER_ZORDER = -1;
ccui.Text.Type = {
SYSTEM: 0,
TTF: 1
-};
\ No newline at end of file
+};
diff --git a/extensions/ccui/uiwidgets/UITextAtlas.js b/extensions/ccui/uiwidgets/UITextAtlas.js
index b13b34d67e..98c4b89e63 100644
--- a/extensions/ccui/uiwidgets/UITextAtlas.js
+++ b/extensions/ccui/uiwidgets/UITextAtlas.js
@@ -63,6 +63,11 @@ ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{
this._labelAtlasRenderer = new cc.LabelAtlas();
this._labelAtlasRenderer.setAnchorPoint(cc.p(0.5, 0.5));
this.addProtectedChild(this._labelAtlasRenderer, ccui.TextAtlas.RENDERER_ZORDER, -1);
+
+ this._labelAtlasRenderer.addEventListener('load', function () {
+ this._updateContentSizeWithTextureSize(this._labelAtlasRenderer.getContentSize());
+ this._findLayout();
+ }, this);
},
/**
@@ -97,7 +102,7 @@ ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{
* @param {String} value
*/
setString: function (value) {
- if(value === this._labelAtlasRenderer.getString())
+ if (value === this._labelAtlasRenderer.getString())
return;
this._stringValue = value;
this._labelAtlasRenderer.setString(value);
@@ -137,7 +142,7 @@ ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{
* Returns the length of string.
* @returns {*|Number|long|int}
*/
- getStringLength: function(){
+ getStringLength: function () {
return this._labelAtlasRenderer.getStringLength();
},
@@ -146,8 +151,8 @@ ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{
this._labelAtlasRendererAdaptDirty = true;
},
- _adaptRenderers: function(){
- if (this._labelAtlasRendererAdaptDirty){
+ _adaptRenderers: function () {
+ if (this._labelAtlasRendererAdaptDirty) {
this._labelAtlasScaleChangedWithSize();
this._labelAtlasRendererAdaptDirty = false;
}
@@ -158,7 +163,7 @@ ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{
* @overrider
* @returns {cc.Size}
*/
- getVirtualRendererSize: function(){
+ getVirtualRendererSize: function () {
return this._labelAtlasRenderer.getContentSize();
},
@@ -195,7 +200,7 @@ ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{
},
_copySpecialProperties: function (labelAtlas) {
- if (labelAtlas){
+ if (labelAtlas) {
this.setProperty(labelAtlas._stringValue, labelAtlas._charMapFileName, labelAtlas._itemWidth, labelAtlas._itemHeight, labelAtlas._startCharMap);
}
},
@@ -228,4 +233,4 @@ ccui.TextAtlas.create = function (stringValue, charMapFile, itemWidth, itemHeigh
* The zOrder value of ccui.TextAtlas's renderer.
* @type {number}
*/
-ccui.TextAtlas.RENDERER_ZORDER = -1;
\ No newline at end of file
+ccui.TextAtlas.RENDERER_ZORDER = -1;
diff --git a/extensions/ccui/uiwidgets/UITextBMFont.js b/extensions/ccui/uiwidgets/UITextBMFont.js
index 1430d4aafd..25c92315cb 100644
--- a/extensions/ccui/uiwidgets/UITextBMFont.js
+++ b/extensions/ccui/uiwidgets/UITextBMFont.js
@@ -49,6 +49,7 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo
*/
ctor: function (text, filename) {
ccui.Widget.prototype.ctor.call(this);
+ this._loader = new cc.Sprite.LoadManager();
if (filename !== undefined) {
this.setFntFile(filename);
@@ -77,18 +78,10 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo
var _self = this;
var locRenderer = _self._labelBMFontRenderer;
- if(!locRenderer._textureLoaded){
- locRenderer.addEventListener("load", function(){
- _self.setFntFile(_self._fntFileName);
- var parent = _self.parent;
- while (parent) {
- if (parent.requestDoLayout) {
- parent.requestDoLayout();
- break;
- }
- parent = parent.parent;
- }
- });
+ if (!locRenderer._textureLoaded) {
+ locRenderer.addEventListener("load", function () {
+ _self.setFntFile(_self._fntFileName);
+ });
}
},
@@ -107,7 +100,14 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo
* @param {String} value
*/
setString: function (value) {
- if(value === this._labelBMFontRenderer.getString())
+ this._loader.clear();
+ if (!this._labelBMFontRenderer._textureLoaded) {
+ this._loader.add(this._labelBMFontRenderer, function () {
+ this.setString(value);
+ }, this);
+ return;
+ }
+ if (value === this._labelBMFontRenderer.getString())
return;
this._stringValue = value;
this._labelBMFontRenderer.setString(value);
@@ -129,7 +129,7 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo
* Returns the length of TextBMFont's string.
* @returns {Number}
*/
- getStringLength: function(){
+ getStringLength: function () {
return this._labelBMFontRenderer.getStringLength();
},
@@ -138,8 +138,8 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo
this._labelBMFontRendererAdaptDirty = true;
},
- _adaptRenderers: function(){
- if (this._labelBMFontRendererAdaptDirty){
+ _adaptRenderers: function () {
+ if (this._labelBMFontRendererAdaptDirty) {
this._labelBMFontScaleChangedWithSize();
this._labelBMFontRendererAdaptDirty = false;
}
@@ -150,7 +150,7 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo
* @override
* @returns {cc.Size}
*/
- getVirtualRendererSize: function(){
+ getVirtualRendererSize: function () {
return this._labelBMFontRenderer.getContentSize();
},
diff --git a/extensions/ccui/uiwidgets/UIVideoPlayer.js b/extensions/ccui/uiwidgets/UIVideoPlayer.js
index afff6fd2a7..38279832ce 100644
--- a/extensions/ccui/uiwidgets/UIVideoPlayer.js
+++ b/extensions/ccui/uiwidgets/UIVideoPlayer.js
@@ -38,24 +38,51 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
_playing: false,
_stopped: true,
- ctor: function(path){
+ ctor: function (path) {
ccui.Widget.prototype.ctor.call(this);
this._EventList = {};
- if(path)
+ if (path)
this.setURL(path);
},
- _createRenderCmd: function(){
+ _createRenderCmd: function () {
return new ccui.VideoPlayer.RenderCmd(this);
},
+ visit: function () {
+ var cmd = this._renderCmd,
+ div = cmd._div,
+ container = cc.container,
+ eventManager = cc.eventManager;
+ if (this._visible) {
+ container.appendChild(cmd._video);
+ if (this._listener === null)
+ this._listener = cc.eventManager.addCustomListener(cc.game.EVENT_RESIZE, function () {
+ cmd.resize();
+ });
+ } else {
+ var hasChild = false;
+ if ('contains' in container) {
+ hasChild = container.contains(cmd._video);
+ } else {
+ hasChild = container.compareDocumentPosition(cmd._video) % 16;
+ }
+ if (hasChild)
+ container.removeChild(cmd._video);
+ eventManager.removeListener(cmd._listener);
+ cmd._listener = null;
+ }
+ cmd.updateStatus();
+ cmd.resize();
+ },
+
/**
* Set the video address
* Automatically replace extname
* All supported video formats will be added to the video
* @param {String} address
*/
- setURL: function(address){
+ setURL: function (address) {
this._renderCmd.updateURL(address);
},
@@ -63,28 +90,28 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
* Get the video path
* @returns {String}
*/
- getURL: function() {
+ getURL: function () {
return this._renderCmd._url;
},
/**
* Play the video
*/
- play: function(){
+ play: function () {
var self = this,
video = this._renderCmd._video;
- if(video){
+ if (video) {
this._played = true;
video.pause();
- if(this._stopped !== false || this._playing !== false || this._played !== true)
+ if (this._stopped !== false || this._playing !== false || this._played !== true)
video.currentTime = 0;
- if(ccui.VideoPlayer._polyfill.autoplayAfterOperation){
- setTimeout(function(){
+ if (ccui.VideoPlayer._polyfill.autoplayAfterOperation) {
+ setTimeout(function () {
video.play();
self._playing = true;
self._stopped = false;
}, 20);
- }else{
+ } else {
video.play();
this._playing = true;
this._stopped = false;
@@ -95,9 +122,9 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
/**
* Pause the video
*/
- pause: function(){
+ pause: function () {
var video = this._renderCmd._video;
- if(video && this._playing === true && this._stopped === false){
+ if (video && this._playing === true && this._stopped === false) {
video.pause();
this._playing = false;
}
@@ -106,8 +133,8 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
/**
* Resume the video
*/
- resume: function(){
- if(this._stopped === false && this._playing === false && this._played === true){
+ resume: function () {
+ if (this._stopped === false && this._playing === false && this._played === true) {
this.play();
}
},
@@ -115,17 +142,17 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
/**
* Stop the video
*/
- stop: function(){
+ stop: function () {
var self = this,
video = this._renderCmd._video;
- if(video){
+ if (video) {
video.pause();
video.currentTime = 0;
this._playing = false;
this._stopped = true;
}
- setTimeout(function(){
+ setTimeout(function () {
self._dispatchEvent(ccui.VideoPlayer.EventType.STOPPED);
}, 0);
},
@@ -133,12 +160,12 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
* Jump to the specified point in time
* @param {Number} sec
*/
- seekTo: function(sec){
+ seekTo: function (sec) {
var video = this._renderCmd._video;
- if(video){
+ if (video) {
video.currentTime = sec;
- if(ccui.VideoPlayer._polyfill.autoplayAfterOperation && this.isPlaying()){
- setTimeout(function(){
+ if (ccui.VideoPlayer._polyfill.autoplayAfterOperation && this.isPlaying()) {
+ setTimeout(function () {
video.play();
}, 20);
}
@@ -149,9 +176,9 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
* Whether the video is playing
* @returns {boolean}
*/
- isPlaying: function(){
- if(ccui.VideoPlayer._polyfill.autoplayAfterOperation && this._playing){
- setTimeout(function(){
+ isPlaying: function () {
+ if (ccui.VideoPlayer._polyfill.autoplayAfterOperation && this._playing) {
+ setTimeout(function () {
video.play();
}, 20);
}
@@ -161,10 +188,10 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
/**
* Whether to keep the aspect ratio
*/
- setKeepAspectRatioEnabled: function(enable){
+ setKeepAspectRatioEnabled: function (enable) {
cc.log("On the web is always keep the aspect ratio");
},
- isKeepAspectRatioEnabled: function(){
+ isKeepAspectRatioEnabled: function () {
return false;
},
@@ -173,10 +200,10 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
* May appear inconsistent in different browsers
* @param {boolean} enable
*/
- setFullScreenEnabled: function(enable){
+ setFullScreenEnabled: function (enable) {
var video = this._renderCmd._video;
- if(video){
- if(enable)
+ if (video) {
+ if (enable)
cc.screen.requestFullScreen(video);
else
cc.screen.exitFullScreen(video);
@@ -186,7 +213,7 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
/**
* Determine whether already full screen
*/
- isFullScreenEnabled: function(){
+ isFullScreenEnabled: function () {
cc.log("Can't know status");
},
@@ -195,7 +222,7 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
* @param {ccui.VideoPlayer.EventType} event
* @param {Function} callback
*/
- setEventListener: function(event, callback){
+ setEventListener: function (event, callback) {
this._EventList[event] = callback;
},
@@ -203,11 +230,11 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
* Delete events
* @param {ccui.VideoPlayer.EventType} event
*/
- removeEventListener: function(event){
+ removeEventListener: function (event) {
this._EventList[event] = null;
},
- _dispatchEvent: function(event) {
+ _dispatchEvent: function (event) {
var callback = this._EventList[event];
if (callback)
callback.call(this, this, this._renderCmd._video.src);
@@ -216,43 +243,40 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
/**
* Trigger playing events
*/
- onPlayEvent: function(){
+ onPlayEvent: function () {
var list = this._EventList[ccui.VideoPlayer.EventType.PLAYING];
- if(list)
- for(var i=0; i -1)
+ if (index > -1)
this._items.splice(index, 1);
this._onItemListChanged();
@@ -269,7 +265,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
/**
* Removes all children from ccui.ListView.
*/
- removeAllChildren: function(){
+ removeAllChildren: function () {
this.removeAllChildrenWithCleanup(true);
},
@@ -277,7 +273,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Removes all children from ccui.ListView and do a cleanup all running actions depending on the cleanup parameter.
* @param {Boolean} cleanup
*/
- removeAllChildrenWithCleanup: function(cleanup){
+ removeAllChildrenWithCleanup: function (cleanup) {
ccui.ScrollView.prototype.removeAllChildrenWithCleanup.call(this, cleanup);
this._items = [];
@@ -320,7 +316,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
/**
* Removes all items from ccui.ListView.
*/
- removeAllItems: function(){
+ removeAllItems: function () {
this.removeAllChildren();
},
@@ -349,7 +345,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* @returns {Number} the index of item.
*/
getIndex: function (item) {
- if(item == null)
+ if (item == null)
return -1;
return this._items.indexOf(item);
},
@@ -369,8 +365,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Set magnetic type of ListView.
* @param {ccui.ListView.MAGNETIC_NONE|ccui.ListView.MAGNETIC_CENTER,ccui.ListView.MAGNETIC_BOTH_END|ccui.ListView.MAGNETIC_LEFT|ccui.ListView.MAGNETIC_RIGHT|ccui.ListView.MAGNETIC_TOP|ccui.ListView.MAGNETIC_BOTTOM} magneticType
*/
- setMagneticType: function(magneticType)
- {
+ setMagneticType: function (magneticType) {
this._magneticType = magneticType;
this._onItemListChanged();
this._startMagneticScroll();
@@ -380,8 +375,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Get magnetic type of ListView.
* @returns {number}
*/
- getMagneticType: function()
- {
+ getMagneticType: function () {
return this._magneticType;
},
@@ -389,8 +383,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Set magnetic allowed out of boundary.
* @param {boolean} magneticAllowedOutOfBoundary
*/
- setMagneticAllowedOutOfBoundary: function(magneticAllowedOutOfBoundary)
- {
+ setMagneticAllowedOutOfBoundary: function (magneticAllowedOutOfBoundary) {
this._magneticAllowedOutOfBoundary = magneticAllowedOutOfBoundary;
},
@@ -398,8 +391,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Query whether the magnetic out of boundary is allowed.
* @returns {boolean}
*/
- getMagneticAllowedOutOfBoundary: function()
- {
+ getMagneticAllowedOutOfBoundary: function () {
return this._magneticAllowedOutOfBoundary;
},
@@ -418,7 +410,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Returns the margin between each item.
* @returns {Number}
*/
- getItemsMargin:function(){
+ getItemsMargin: function () {
return this._itemsMargin;
},
@@ -443,21 +435,17 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
ccui.ScrollView.prototype.setDirection.call(this, dir);
},
- _getHowMuchOutOfBoundary: function(addition)
- {
- if(addition === undefined)
+ _getHowMuchOutOfBoundary: function (addition) {
+ if (addition === undefined)
addition = cc.p(0, 0);
- if(!this._magneticAllowedOutOfBoundary || this._items.length === 0)
- {
+ if (!this._magneticAllowedOutOfBoundary || this._items.length === 0) {
return ccui.ScrollView.prototype._getHowMuchOutOfBoundary.call(this, addition);
}
- else if(this._magneticType === ccui.ListView.MAGNETIC_NONE || this._magneticType === ccui.ListView.MAGNETIC_BOTH_END)
- {
+ else if (this._magneticType === ccui.ListView.MAGNETIC_NONE || this._magneticType === ccui.ListView.MAGNETIC_BOTH_END) {
return ccui.ScrollView.prototype._getHowMuchOutOfBoundary.call(this, addition);
}
- else if(addition.x === 0 && addition.y === 0 && !this._outOfBoundaryAmountDirty)
- {
+ else if (addition.x === 0 && addition.y === 0 && !this._outOfBoundaryAmountDirty) {
return this._outOfBoundaryAmount;
}
@@ -472,8 +460,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
var firstItemAdjustment = cc.p(0, 0);
var lastItemAdjustment = cc.p(0, 0);
- switch (this._magneticType)
- {
+ switch (this._magneticType) {
case ccui.ListView.MAGNETIC_CENTER:
firstItemAdjustment.x = (contentSize.width - this._items[0].width) / 2;
firstItemAdjustment.y = (contentSize.height - this._items[0].height) / 2;
@@ -503,55 +490,44 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
// Calculate the actual amount
var outOfBoundaryAmount = cc.p(0, 0);
- if(this._innerContainer.getLeftBoundary() + addition.x > leftBoundary)
- {
+ if (this._innerContainer.getLeftBoundary() + addition.x > leftBoundary) {
outOfBoundaryAmount.x = leftBoundary - (this._innerContainer.getLeftBoundary() + addition.x);
}
- else if(this._innerContainer.getRightBoundary() + addition.x < rightBoundary)
- {
+ else if (this._innerContainer.getRightBoundary() + addition.x < rightBoundary) {
outOfBoundaryAmount.x = rightBoundary - (this._innerContainer.getRightBoundary() + addition.x);
}
- if(this._innerContainer.getTopBoundary() + addition.y < topBoundary)
- {
+ if (this._innerContainer.getTopBoundary() + addition.y < topBoundary) {
outOfBoundaryAmount.y = topBoundary - (this._innerContainer.getTopBoundary() + addition.y);
}
- else if(this._innerContainer.getBottomBoundary() + addition.y > bottomBoundary)
- {
+ else if (this._innerContainer.getBottomBoundary() + addition.y > bottomBoundary) {
outOfBoundaryAmount.y = bottomBoundary - (this._innerContainer.getBottomBoundary() + addition.y);
}
- if(addition.x === 0 && addition.y === 0)
- {
+ if (addition.x === 0 && addition.y === 0) {
this._outOfBoundaryAmount = outOfBoundaryAmount;
this._outOfBoundaryAmountDirty = false;
}
return outOfBoundaryAmount;
},
- _calculateItemPositionWithAnchor: function(item, itemAnchorPoint)
- {
+ _calculateItemPositionWithAnchor: function (item, itemAnchorPoint) {
var origin = cc.p(item.getLeftBoundary(), item.getBottomBoundary());
var size = item.getContentSize();
- return cc.p(origin. x + size.width * itemAnchorPoint.x, origin.y + size.height * itemAnchorPoint.y);
+ return cc.p(origin.x + size.width * itemAnchorPoint.x, origin.y + size.height * itemAnchorPoint.y);
},
- _findClosestItem: function(targetPosition, items, itemAnchorPoint, firstIndex, distanceFromFirst, lastIndex, distanceFromLast)
- {
+ _findClosestItem: function (targetPosition, items, itemAnchorPoint, firstIndex, distanceFromFirst, lastIndex, distanceFromLast) {
cc.assert(firstIndex >= 0 && lastIndex < items.length && firstIndex <= lastIndex, "");
- if (firstIndex === lastIndex)
- {
+ if (firstIndex === lastIndex) {
return items[firstIndex];
}
- if (lastIndex - firstIndex === 1)
- {
- if (distanceFromFirst <= distanceFromLast)
- {
+ if (lastIndex - firstIndex === 1) {
+ if (distanceFromFirst <= distanceFromLast) {
return items[firstIndex];
}
- else
- {
+ else {
return items[lastIndex];
}
}
@@ -561,13 +537,11 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
var itemPosition = this._calculateItemPositionWithAnchor(items[midIndex], itemAnchorPoint);
var distanceFromMid = cc.pLength(cc.pSub(targetPosition, itemPosition));
- if (distanceFromFirst <= distanceFromLast)
- {
+ if (distanceFromFirst <= distanceFromLast) {
// Left half
return this._findClosestItem(targetPosition, items, itemAnchorPoint, firstIndex, distanceFromFirst, midIndex, distanceFromMid);
}
- else
- {
+ else {
// Right half
return this._findClosestItem(targetPosition, items, itemAnchorPoint, midIndex, distanceFromMid, lastIndex, distanceFromLast);
}
@@ -580,10 +554,8 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* @param {cc.Point} itemAnchorPoint Specifies an anchor point of each item for position to calculate distance.
* @returns {?ccui.Widget} A item instance if list view is not empty. Otherwise, returns null.
*/
- getClosestItemToPosition: function(targetPosition, itemAnchorPoint)
- {
- if (this._items.length === 0)
- {
+ getClosestItemToPosition: function (targetPosition, itemAnchorPoint) {
+ if (this._items.length === 0) {
return null;
}
@@ -608,8 +580,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* @returns {?ccui.Widget} A item instance if list view is not empty. Otherwise, returns null.
*/
- getClosestItemToPositionInCurrentView: function(positionRatioInView, itemAnchorPoint)
- {
+ getClosestItemToPositionInCurrentView: function (positionRatioInView, itemAnchorPoint) {
// Calculate the target position
var contentSize = this.getContentSize();
var targetPosition = cc.pMult(this._innerContainer.getPosition(), -1);
@@ -623,8 +594,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Query the center item
* @returns {?ccui.Widget} A item instance.
*/
- getCenterItemInCurrentView: function()
- {
+ getCenterItemInCurrentView: function () {
return this.getClosestItemToPositionInCurrentView(cc.p(0.5, 0.5), cc.p(0.5, 0.5));
},
@@ -632,10 +602,8 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Query the leftmost item in horizontal list
* @returns {?ccui.Widget} A item instance.
*/
- getLeftmostItemInCurrentView: function()
- {
- if(this._direction === ccui.ScrollView.DIR_HORIZONTAL)
- {
+ getLeftmostItemInCurrentView: function () {
+ if (this._direction === ccui.ScrollView.DIR_HORIZONTAL) {
return this.getClosestItemToPositionInCurrentView(cc.p(0, 0.5), cc.p(0.5, 0.5));
}
@@ -646,10 +614,8 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Query the rightmost item in horizontal list
* @returns {?ccui.Widget} A item instance.
*/
- getRightmostItemInCurrentView: function()
- {
- if(this._direction === ccui.ScrollView.DIR_HORIZONTAL)
- {
+ getRightmostItemInCurrentView: function () {
+ if (this._direction === ccui.ScrollView.DIR_HORIZONTAL) {
return this.getClosestItemToPositionInCurrentView(cc.p(1, 0.5), cc.p(0.5, 0.5));
}
@@ -660,10 +626,8 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Query the topmost item in horizontal list
* @returns {?ccui.Widget} A item instance.
*/
- getTopmostItemInCurrentView: function()
- {
- if(this._direction === ccui.ScrollView.DIR_VERTICAL)
- {
+ getTopmostItemInCurrentView: function () {
+ if (this._direction === ccui.ScrollView.DIR_VERTICAL) {
return this.getClosestItemToPositionInCurrentView(cc.p(0.5, 1), cc.p(0.5, 0.5));
}
@@ -674,18 +638,15 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Query the topmost item in horizontal list
* @returns {?ccui.Widget} A item instance.
*/
- getBottommostItemInCurrentView: function()
- {
- if(this._direction === ccui.ScrollView.DIR_VERTICAL)
- {
+ getBottommostItemInCurrentView: function () {
+ if (this._direction === ccui.ScrollView.DIR_VERTICAL) {
return this.getClosestItemToPositionInCurrentView(cc.p(0.5, 0), cc.p(0.5, 0.5));
}
return null;
},
- _calculateItemDestination: function(positionRatioInView, item, itemAnchorPoint)
- {
+ _calculateItemDestination: function (positionRatioInView, item, itemAnchorPoint) {
var contentSize = this.getContentSize();
var positionInView = cc.p(0, 0);
positionInView.x += contentSize.width * positionRatioInView.x;
@@ -695,68 +656,57 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
return cc.pMult(cc.pSub(itemPosition, positionInView), -1);
},
- jumpToBottom: function()
- {
+ jumpToBottom: function () {
this.doLayout();
ccui.ScrollView.prototype.jumpToBottom.call(this);
},
- jumpToTop: function()
- {
+ jumpToTop: function () {
this.doLayout();
ccui.ScrollView.prototype.jumpToTop.call(this);
},
- jumpToLeft: function()
- {
+ jumpToLeft: function () {
this.doLayout();
ccui.ScrollView.prototype.jumpToLeft.call(this);
},
- jumpToRight: function()
- {
+ jumpToRight: function () {
this.doLayout();
ccui.ScrollView.prototype.jumpToRight.call(this);
},
- jumpToTopLeft: function()
- {
+ jumpToTopLeft: function () {
this.doLayout();
ccui.ScrollView.prototype.jumpToTopLeft.call(this);
},
- jumpToTopRight: function()
- {
+ jumpToTopRight: function () {
this.doLayout();
ccui.ScrollView.prototype.jumpToTopRight.call(this);
},
- jumpToBottomLeft: function()
- {
+ jumpToBottomLeft: function () {
this.doLayout();
ccui.ScrollView.prototype.jumpToBottomLeft.call(this);
},
- jumpToBottomRight: function()
- {
+ jumpToBottomRight: function () {
this.doLayout();
ccui.ScrollView.prototype.jumpToBottomRight.call(this);
},
- jumpToPercentVertical: function(percent)
- {
+ jumpToPercentVertical: function (percent) {
this.doLayout();
ccui.ScrollView.prototype.jumpToPercentVertical.call(this, percent);
},
- jumpToPercentHorizontal: function(percent)
- {
+ jumpToPercentHorizontal: function (percent) {
this.doLayout();
ccui.ScrollView.prototype.jumpToPercentHorizontal.call(this, percent);
},
- jumpToPercentBothDirection: function(percent)
- {
+ jumpToPercentBothDirection: function (percent) {
this.doLayout();
ccui.ScrollView.prototype.jumpToPercentBothDirection.call(this, percent);
},
@@ -767,19 +717,17 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* @param {cc.Point} positionRatioInView Specifies the position with ratio in list view's content size.
* @param {cc.Point} itemAnchorPoint Specifies an anchor point of each item for position to calculate distance.
*/
- jumpToItem: function(itemIndex, positionRatioInView, itemAnchorPoint)
- {
+ jumpToItem: function (itemIndex, positionRatioInView, itemAnchorPoint) {
var item = this.getItem(itemIndex);
- if(!item)
+ if (!item)
return;
this.doLayout();
var destination = this._calculateItemDestination(positionRatioInView, item, itemAnchorPoint);
- if(!this.bounceEnabled)
- {
+ if (!this.bounceEnabled) {
var delta = cc.pSub(destination, this._innerContainer.getPosition());
var outOfBoundary = this._getHowMuchOutOfBoundary(delta);
destination.x += outOfBoundary.x;
@@ -796,14 +744,13 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* @param {cc.Point} itemAnchorPoint Specifies an anchor point of each item for position to calculate distance.
* @param {number} [timeInSec = 1.0] Scroll time
*/
- scrollToItem: function(itemIndex, positionRatioInView, itemAnchorPoint, timeInSec)
- {
- if(timeInSec === undefined)
+ scrollToItem: function (itemIndex, positionRatioInView, itemAnchorPoint, timeInSec) {
+ if (timeInSec === undefined)
timeInSec = 1;
var item = this.getItem(itemIndex);
- if(!item)
+ if (!item)
return;
var destination = this._calculateItemDestination(positionRatioInView, item, itemAnchorPoint);
@@ -829,16 +776,15 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
/**
* provides a public _doLayout function for Editor. it calls _doLayout.
*/
- doLayout: function(){
+ doLayout: function () {
this._doLayout();
},
- requestDoLayout: function()
- {
+ requestDoLayout: function () {
this._refreshViewDirty = true;
},
- _doLayout: function(){
+ _doLayout: function () {
//ccui.Layout.prototype._doLayout.call(this);
if (this._refreshViewDirty) {
var locItems = this._items;
@@ -868,19 +814,19 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Adds callback function called ListView event triggered
* @param {Function} selector
*/
- addEventListener: function(selector){
+ addEventListener: function (selector) {
this._ccListViewEventCallback = selector;
},
_selectedItemEvent: function (event) {
var eventEnum = (event === ccui.Widget.TOUCH_BEGAN) ? ccui.ListView.ON_SELECTED_ITEM_START : ccui.ListView.ON_SELECTED_ITEM_END;
- if(this._listViewEventSelector){
+ if (this._listViewEventSelector) {
if (this._listViewEventListener)
this._listViewEventSelector.call(this._listViewEventListener, this, eventEnum);
else
this._listViewEventSelector(this, eventEnum);
}
- if(this._ccListViewEventCallback)
+ if (this._ccListViewEventCallback)
this._ccListViewEventCallback(this, eventEnum);
},
@@ -943,7 +889,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
},
_copySpecialProperties: function (listView) {
- if(listView instanceof ccui.ListView){
+ if (listView instanceof ccui.ListView) {
ccui.ScrollView.prototype._copySpecialProperties.call(this, listView);
this.setItemModel(listView._model);
this.setItemsMargin(listView._itemsMargin);
@@ -954,27 +900,21 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
}
},
- _startAttenuatingAutoScroll: function(deltaMove, initialVelocity)
- {
+ _startAttenuatingAutoScroll: function (deltaMove, initialVelocity) {
var adjustedDeltaMove = deltaMove;
- if(this._items.length !== 0 && this._magneticType !== ccui.ListView.MAGNETIC_NONE)
- {
+ if (this._items.length !== 0 && this._magneticType !== ccui.ListView.MAGNETIC_NONE) {
adjustedDeltaMove = this._flattenVectorByDirection(adjustedDeltaMove);
var howMuchOutOfBoundary = this._getHowMuchOutOfBoundary(adjustedDeltaMove);
// If the destination is out of boundary, do nothing here. Because it will be handled by bouncing back.
- if(howMuchOutOfBoundary.x === 0 && howMuchOutOfBoundary.y === 0 )
- {
+ if (howMuchOutOfBoundary.x === 0 && howMuchOutOfBoundary.y === 0) {
var magType = this._magneticType;
- if(magType === ccui.ListView.MAGNETIC_BOTH_END)
- {
- if(this._direction === ccui.ScrollView.DIR_HORIZONTAL)
- {
+ if (magType === ccui.ListView.MAGNETIC_BOTH_END) {
+ if (this._direction === ccui.ScrollView.DIR_HORIZONTAL) {
magType = (adjustedDeltaMove.x > 0 ? ccui.ListView.MAGNETIC_LEFT : ccui.ListView.MAGNETIC_RIGHT);
}
- else if(this._direction === ccui.ScrollView.DIR_VERTICAL)
- {
+ else if (this._direction === ccui.ScrollView.DIR_VERTICAL) {
magType = (adjustedDeltaMove.y > 0 ? ccui.ListView.MAGNETIC_BOTTOM : ccui.ListView.MAGNETIC_TOP);
}
}
@@ -990,34 +930,37 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
adjustedDeltaMove = cc.pSub(magneticPosition, itemPosition);
}
}
- ccui.ScrollView.prototype._startAttenuatingAutoScroll.call(this,adjustedDeltaMove, initialVelocity);
- },
-
- _getAnchorPointByMagneticType: function(magneticType)
- {
- switch(magneticType)
- {
- case ccui.ListView.MAGNETIC_NONE: return cc.p(0, 0);
- case ccui.ListView.MAGNETIC_BOTH_END: return cc.p(0, 1);
- case ccui.ListView.MAGNETIC_CENTER: return cc.p(0.5, 0.5);
- case ccui.ListView.MAGNETIC_LEFT: return cc.p(0, 0.5);
- case ccui.ListView.MAGNETIC_RIGHT: return cc.p(1, 0.5);
- case ccui.ListView.MAGNETIC_TOP: return cc.p(0.5, 1);
- case ccui.ListView.MAGNETIC_BOTTOM: return cc.p(0.5, 0);
+ ccui.ScrollView.prototype._startAttenuatingAutoScroll.call(this, adjustedDeltaMove, initialVelocity);
+ },
+
+ _getAnchorPointByMagneticType: function (magneticType) {
+ switch (magneticType) {
+ case ccui.ListView.MAGNETIC_NONE:
+ return cc.p(0, 0);
+ case ccui.ListView.MAGNETIC_BOTH_END:
+ return cc.p(0, 1);
+ case ccui.ListView.MAGNETIC_CENTER:
+ return cc.p(0.5, 0.5);
+ case ccui.ListView.MAGNETIC_LEFT:
+ return cc.p(0, 0.5);
+ case ccui.ListView.MAGNETIC_RIGHT:
+ return cc.p(1, 0.5);
+ case ccui.ListView.MAGNETIC_TOP:
+ return cc.p(0.5, 1);
+ case ccui.ListView.MAGNETIC_BOTTOM:
+ return cc.p(0.5, 0);
}
return cc.p(0, 0);
},
- _startMagneticScroll: function()
- {
- if(this._items.length === 0 || this._magneticType === ccui.ListView.MAGNETIC_NONE)
- {
+ _startMagneticScroll: function () {
+ if (this._items.length === 0 || this._magneticType === ccui.ListView.MAGNETIC_NONE) {
return;
}
// Find the closest item
- var magneticAnchorPoint =this._getAnchorPointByMagneticType(this._magneticType);
+ var magneticAnchorPoint = this._getAnchorPointByMagneticType(this._magneticType);
var magneticPosition = cc.pMult(this._innerContainer.getPosition(), -1);
magneticPosition.x += this.width * magneticAnchorPoint.x;
magneticPosition.y += this.height * magneticAnchorPoint.y;
diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js b/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js
index 6c48c6e743..e37853778a 100644
--- a/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js
+++ b/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js
@@ -38,7 +38,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
_childFocusCancelOffset: 0,
_pageViewEventListener: null,
_pageViewEventSelector: null,
- _className:"PageView",
+ _className: "PageView",
_indicator: null,
_indicatorPositionAsAnchorPoint: null,
@@ -77,8 +77,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Insert a page into the end of PageView.
* @param {ccui.Widget} page Page to be inserted.
*/
- addPage: function(page)
- {
+ addPage: function (page) {
this.pushBackCustomItem(page);
},
@@ -87,8 +86,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* @param {ccui.Widget} page Page to be inserted.
* @param {number} idx A given index.
*/
- insertPage: function(page, idx)
- {
+ insertPage: function (page, idx) {
this.insertCustomItem(page, idx);
},
@@ -111,7 +109,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
/**
* Removes all pages from PageView
*/
- removeAllPages: function(){
+ removeAllPages: function () {
this.removeAllItems();
},
@@ -132,14 +130,13 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
},
- _doLayout: function(){
+ _doLayout: function () {
if (!this._refreshViewDirty)
return;
ccui.ListView.prototype._doLayout.call(this);
- if(this._indicator)
- {
+ if (this._indicator) {
var index = this.getIndex(this.getCenterItemInCurrentView());
this._indicator.indicate(index);
}
@@ -151,20 +148,16 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Changes scroll direction of ccui.PageView.
* @param {ccui.ScrollView.DIR_NONE | ccui.ScrollView.DIR_VERTICAL | ccui.ScrollView.DIR_HORIZONTAL | ccui.ScrollView.DIR_BOTH} direction
*/
- setDirection: function(direction)
- {
+ setDirection: function (direction) {
ccui.ListView.prototype.setDirection.call(this, direction);
- if(direction === ccui.ScrollView.DIR_HORIZONTAL)
- {
+ if (direction === ccui.ScrollView.DIR_HORIZONTAL) {
this._indicatorPositionAsAnchorPoint = cc.p(0.5, 0.1);
}
- else if(direction === ccui.ScrollView.DIR_VERTICAL)
- {
+ else if (direction === ccui.ScrollView.DIR_VERTICAL) {
this._indicatorPositionAsAnchorPoint = cc.p(0.1, 0.5);
}
- if(this._indicator)
- {
+ if (this._indicator) {
this._indicator.setDirection(direction);
this._refreshIndicatorPosition();
}
@@ -176,7 +169,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* @param threshold
* @deprecated Since v3.9, this method has no effect.
*/
- setCustomScrollThreshold: function(threshold){
+ setCustomScrollThreshold: function (threshold) {
},
@@ -185,7 +178,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* @since v3.2
* @deprecated Since v3.9, this method always returns 0.
*/
- getCustomScrollThreshold: function(){
+ getCustomScrollThreshold: function () {
return 0;
},
@@ -194,52 +187,44 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* @since v3.2
* @deprecated Since v3.9, this method has no effect.
*/
- setUsingCustomScrollThreshold: function(flag){
+ setUsingCustomScrollThreshold: function (flag) {
},
/**
* Queries whether we are using user defined scroll page threshold or not
* @deprecated Since v3.9, this method always returns false.
*/
- isUsingCustomScrollThreshold: function(){
+ isUsingCustomScrollThreshold: function () {
return false;
},
- _moveInnerContainer: function(deltaMove, canStartBounceBack)
- {
+ _moveInnerContainer: function (deltaMove, canStartBounceBack) {
ccui.ListView.prototype._moveInnerContainer.call(this, deltaMove, canStartBounceBack);
this._curPageIdx = this.getIndex(this.getCenterItemInCurrentView());
- if(this._indicator)
- {
+ if (this._indicator) {
this._indicator.indicate(this._curPageIdx);
}
},
- _onItemListChanged: function()
- {
+ _onItemListChanged: function () {
ccui.ListView.prototype._onItemListChanged.call(this);
- if(this._indicator)
- {
+ if (this._indicator) {
this._indicator.reset(this._items.length);
}
},
- _onSizeChanged: function()
- {
+ _onSizeChanged: function () {
ccui.ListView.prototype._onSizeChanged.call(this);
this._refreshIndicatorPosition();
},
- _remedyLayoutParameter: function (item)
- {
+ _remedyLayoutParameter: function (item) {
item.setContentSize(this.getContentSize());
ccui.ListView.prototype._remedyLayoutParameter.call(this, item);
},
-
- _refreshIndicatorPosition: function()
- {
- if(this._indicator)
- {
+
+ _refreshIndicatorPosition: function () {
+ if (this._indicator) {
var contentSize = this.getContentSize();
var posX = contentSize.width * this._indicatorPositionAsAnchorPoint.x;
var posY = contentSize.height * this._indicatorPositionAsAnchorPoint.y;
@@ -257,12 +242,10 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
var touchMoveVelocity = this._flattenVectorByDirection(this._calculateTouchMoveVelocity());
var INERTIA_THRESHOLD = 500;
- if(cc.pLength(touchMoveVelocity) < INERTIA_THRESHOLD)
- {
+ if (cc.pLength(touchMoveVelocity) < INERTIA_THRESHOLD) {
this._startMagneticScroll();
}
- else
- {
+ else {
// Handle paging by inertia force.
var currentPage = this.getItem(this._curPageIdx);
var destination = this._calculateItemDestination(cc.p(0.5, 0.5), currentPage, cc.p(0.5, 0.5));
@@ -271,18 +254,14 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
// If the direction of displacement to current page and the direction of touch are same, just start magnetic scroll to the current page.
// Otherwise, move to the next page of touch direction.
- if(touchMoveVelocity.x * deltaToCurrentPage.x > 0 || touchMoveVelocity.y * deltaToCurrentPage.y > 0)
- {
+ if (touchMoveVelocity.x * deltaToCurrentPage.x > 0 || touchMoveVelocity.y * deltaToCurrentPage.y > 0) {
this._startMagneticScroll();
}
- else
- {
- if(touchMoveVelocity.x < 0 || touchMoveVelocity.y > 0)
- {
+ else {
+ if (touchMoveVelocity.x < 0 || touchMoveVelocity.y > 0) {
++this._curPageIdx;
}
- else
- {
+ else {
--this._curPageIdx;
}
this._curPageIdx = Math.min(this._curPageIdx, this._items.length);
@@ -293,19 +272,18 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
},
- _getAutoScrollStopEpsilon: function()
- {
+ _getAutoScrollStopEpsilon: function () {
return 0.001;
},
_pageTurningEvent: function () {
- if(this._pageViewEventSelector){
+ if (this._pageViewEventSelector) {
if (this._pageViewEventListener)
this._pageViewEventSelector.call(this._pageViewEventListener, this, ccui.PageView.EVENT_TURNING);
else
this._pageViewEventSelector(this, ccui.PageView.EVENT_TURNING);
}
- if(this._ccEventCallback)
+ if (this._ccEventCallback)
this._ccEventCallback(this, ccui.PageView.EVENT_TURNING);
},
@@ -320,9 +298,9 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
this._pageViewEventListener = target;
},
- addEventListener: function(selector){
- this._ccEventCallback = function(ref, eventType) {
- if(eventType == ccui.ScrollView.EVENT_AUTOSCROLL_ENDED)
+ addEventListener: function (selector) {
+ this._ccEventCallback = function (ref, eventType) {
+ if (eventType == ccui.ScrollView.EVENT_AUTOSCROLL_ENDED)
selector(this, eventType)
};
},
@@ -332,8 +310,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* This is the different between scrollToPage.
* @param {number} index A given index in PageView. Index start from 0 to pageCount -1.
*/
- setCurrentPageIndex: function(index)
- {
+ setCurrentPageIndex: function (index) {
this.jumpToItem(index, cc.p(0.5, 0.5), cc.p(0.5, 0.5));
},
@@ -343,8 +320,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* @param {number} index A given index in PageView. Index start from 0 to pageCount -1.
* @deprecated since v3.9, this is deprecated. Use `setCurrentPageIndex()` instead.
*/
- setCurPageIndex: function(index)
- {
+ setCurPageIndex: function (index) {
this.setCurrentPageIndex(index);
},
@@ -370,7 +346,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Returns all pages of PageView
* @returns {Array}
*/
- getPages:function(){
+ getPages: function () {
return this.getItems();
},
@@ -379,7 +355,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* @param {Number} index
* @returns {ccui.Layout}
*/
- getPage: function(index){
+ getPage: function (index) {
return this.getItem(index);
},
@@ -416,20 +392,16 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Toggle page indicator enabled.
* @param {boolean} enabled True if enable page indicator, false otherwise.
*/
- setIndicatorEnabled: function(enabled)
- {
- if(enabled == (this._indicator !== null))
- {
+ setIndicatorEnabled: function (enabled) {
+ if (enabled == (this._indicator !== null)) {
return;
}
- if(!enabled)
- {
+ if (!enabled) {
this.removeProtectedChild(this._indicator);
this._indicator = null;
}
- else
- {
+ else {
this._indicator = new ccui.PageViewIndicator();
this._indicator.setDirection(this.getDirection());
this.addProtectedChild(this._indicator, 10000);
@@ -442,8 +414,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Query page indicator state.
* @returns {boolean} True if page indicator is enabled, false otherwise.
*/
- getIndicatorEnabled: function()
- {
+ getIndicatorEnabled: function () {
return this._indicator !== null;
},
@@ -451,8 +422,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Set the page indicator's position using anchor point.
* @param {cc.Point} positionAsAnchorPoint The position as anchor point.
*/
- setIndicatorPositionAsAnchorPoint: function(positionAsAnchorPoint)
- {
+ setIndicatorPositionAsAnchorPoint: function (positionAsAnchorPoint) {
this._indicatorPositionAsAnchorPoint = positionAsAnchorPoint;
this._refreshIndicatorPosition();
},
@@ -461,8 +431,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Get the page indicator's position as anchor point.
* @returns {cc.Point}
*/
- getIndicatorPositionAsAnchorPoint: function()
- {
+ getIndicatorPositionAsAnchorPoint: function () {
return this._indicatorPositionAsAnchorPoint;
},
@@ -470,10 +439,8 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Set the page indicator's position in page view.
* @param {cc.Point} position The position in page view
*/
- setIndicatorPosition: function(position)
- {
- if(this._indicator)
- {
+ setIndicatorPosition: function (position) {
+ if (this._indicator) {
var contentSize = this.getContentSize();
this._indicatorPositionAsAnchorPoint.x = position.x / contentSize.width;
this._indicatorPositionAsAnchorPoint.y = position.y / contentSize.height;
@@ -485,8 +452,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Get the page indicator's position.
* @returns {cc.Point}
*/
- getIndicatorPosition: function()
- {
+ getIndicatorPosition: function () {
cc.assert(this._indicator !== null, "");
return this._indicator.getPosition();
},
@@ -495,10 +461,8 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Set space between page indicator's index nodes.
* @param {number} spaceBetweenIndexNodes Space between nodes in pixel.
*/
- setIndicatorSpaceBetweenIndexNodes: function(spaceBetweenIndexNodes)
- {
- if(this._indicator)
- {
+ setIndicatorSpaceBetweenIndexNodes: function (spaceBetweenIndexNodes) {
+ if (this._indicator) {
this._indicator.setSpaceBetweenIndexNodes(spaceBetweenIndexNodes);
}
},
@@ -507,8 +471,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Get the space between page indicator's index nodes.
* @returns {number}
*/
- getIndicatorSpaceBetweenIndexNodes: function()
- {
+ getIndicatorSpaceBetweenIndexNodes: function () {
cc.assert(this._indicator !== null, "");
return this._indicator.getSpaceBetweenIndexNodes();
},
@@ -517,10 +480,8 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Set color of page indicator's selected index.
* @param {cc.Color} color Color for indicator
*/
- setIndicatorSelectedIndexColor: function(color)
- {
- if(this._indicator)
- {
+ setIndicatorSelectedIndexColor: function (color) {
+ if (this._indicator) {
this._indicator.setSelectedIndexColor(color);
}
},
@@ -529,8 +490,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Get the color of page indicator's selected index.
* @returns {cc.Color}
*/
- getIndicatorSelectedIndexColor: function()
- {
+ getIndicatorSelectedIndexColor: function () {
cc.assert(this._indicator !== null, "");
return this._indicator.getSelectedIndexColor();
},
@@ -539,10 +499,8 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Set color of page indicator's index nodes.
* @param {cc.Color} color Color for indicator
*/
- setIndicatorIndexNodesColor: function(color)
- {
- if(this._indicator)
- {
+ setIndicatorIndexNodesColor: function (color) {
+ if (this._indicator) {
this._indicator.setIndexNodesColor(color);
}
},
@@ -551,8 +509,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Get the color of page indicator's index nodes.
* @returns {cc.Color}
*/
- getIndicatorIndexNodesColor: function()
- {
+ getIndicatorIndexNodesColor: function () {
cc.assert(this._indicator !== null, "");
return this._indicator.getIndexNodesColor();
},
@@ -561,10 +518,8 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Set scale of page indicator's index nodes.
* @param {Number} scale Scale for indicator
*/
- setIndicatorIndexNodesScale: function(indexNodesScale)
- {
- if(this._indicator)
- {
+ setIndicatorIndexNodesScale: function (indexNodesScale) {
+ if (this._indicator) {
this._indicator.setIndexNodesScale(indexNodesScale);
this._indicator.indicate(this._curPageIdx);
}
@@ -574,8 +529,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Get the scale of page indicator's index nodes.
* @returns {Number}
*/
- getIndicatorIndexNodesScale: function()
- {
+ getIndicatorIndexNodesScale: function () {
cc.assert(this._indicator !== null, "");
return this._indicator.getIndexNodesScale();
},
@@ -585,10 +539,8 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* @param {String} texName
* @param {ccui.Widget.LOCAL_TEXTURE | ccui.Widget.PLIST_TEXTURE} [texType = ccui.Widget.LOCAL_TEXTURE]
*/
- setIndicatorIndexNodesTexture: function(texName, texType)
- {
- if(this._indicator)
- {
+ setIndicatorIndexNodesTexture: function (texName, texType) {
+ if (this._indicator) {
this._indicator.setIndexNodesTexture(texName, texType);
this._indicator.indicate(this._curPageIdx);
}
diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIPageViewIndicator.js b/extensions/ccui/uiwidgets/scroll-widget/UIPageViewIndicator.js
index 4ffb42b51d..8044ba2269 100644
--- a/extensions/ccui/uiwidgets/scroll-widget/UIPageViewIndicator.js
+++ b/extensions/ccui/uiwidgets/scroll-widget/UIPageViewIndicator.js
@@ -67,8 +67,7 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* Sets direction of indicator
* @param {ccui.ScrollView.DIR_NONE | ccui.ScrollView.DIR_VERTICAL | ccui.ScrollView.DIR_HORIZONTAL | ccui.ScrollView.DIR_BOTH} direction
*/
- setDirection: function(direction)
- {
+ setDirection: function (direction) {
this._direction = direction;
this._rearrange();
},
@@ -77,14 +76,11 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* resets indicator with new page count.
* @param {number} numberOfTotalPages
*/
- reset: function(numberOfTotalPages)
- {
- while(this._indexNodes.length < numberOfTotalPages)
- {
+ reset: function (numberOfTotalPages) {
+ while (this._indexNodes.length < numberOfTotalPages) {
this._increaseNumberOfPages();
}
- while(this._indexNodes.length > numberOfTotalPages)
- {
+ while (this._indexNodes.length > numberOfTotalPages) {
this._decreaseNumberOfPages();
}
this._rearrange();
@@ -95,19 +91,15 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* Indicates node by index
* @param {number} index
*/
- indicate: function(index)
- {
- if (index < 0 || index >= this._indexNodes.length)
- {
+ indicate: function (index) {
+ if (index < 0 || index >= this._indexNodes.length) {
return;
}
this._currentIndexNode.setPosition(this._indexNodes[index].getPosition());
},
- _rearrange: function()
- {
- if(this._indexNodes.length === 0)
- {
+ _rearrange: function () {
+ if (this._indexNodes.length === 0) {
return;
}
@@ -121,15 +113,12 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
var totalSizeValue = sizeValue * numberOfItems + this._spaceBetweenIndexNodes * (numberOfItems - 1);
var posValue = -(totalSizeValue / 2) + (sizeValue / 2);
- for(var i = 0; i < this._indexNodes.length; ++i)
- {
+ for (var i = 0; i < this._indexNodes.length; ++i) {
var position;
- if(horizontal)
- {
+ if (horizontal) {
position = cc.p(posValue, indexNodeSize.height / 2.0);
}
- else
- {
+ else {
position = cc.p(indexNodeSize.width / 2.0, -posValue);
}
this._indexNodes[i].setPosition(position);
@@ -141,10 +130,8 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* Sets space between index nodes.
* @param {number} spaceBetweenIndexNodes
*/
- setSpaceBetweenIndexNodes: function(spaceBetweenIndexNodes)
- {
- if(this._spaceBetweenIndexNodes === spaceBetweenIndexNodes)
- {
+ setSpaceBetweenIndexNodes: function (spaceBetweenIndexNodes) {
+ if (this._spaceBetweenIndexNodes === spaceBetweenIndexNodes) {
return;
}
this._spaceBetweenIndexNodes = spaceBetweenIndexNodes;
@@ -155,8 +142,7 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* Gets space between index nodes.
* @returns {number}
*/
- getSpaceBetweenIndexNodes: function()
- {
+ getSpaceBetweenIndexNodes: function () {
return this._spaceBetweenIndexNodes;
},
@@ -164,8 +150,7 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* Sets color of selected index node
* @param {cc.Color} color
*/
- setSelectedIndexColor: function(color)
- {
+ setSelectedIndexColor: function (color) {
this._currentIndexNode.setColor(color);
},
@@ -173,8 +158,7 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* Gets color of selected index node
* @returns {cc.Color}
*/
- getSelectedIndexColor: function()
- {
+ getSelectedIndexColor: function () {
return this._currentIndexNode.getColor();
},
@@ -182,12 +166,10 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* Sets color of index nodes
* @param {cc.Color} indexNodesColor
*/
- setIndexNodesColor: function(indexNodesColor)
- {
+ setIndexNodesColor: function (indexNodesColor) {
this._indexNodesColor = indexNodesColor;
- for(var i = 0 ; i < this._indexNodes.length; ++i)
- {
+ for (var i = 0; i < this._indexNodes.length; ++i) {
this._indexNodes[i].setColor(indexNodesColor);
}
},
@@ -196,8 +178,7 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* Gets color of index nodes
* @returns {cc.Color}
*/
- getIndexNodesColor: function()
- {
+ getIndexNodesColor: function () {
var locRealColor = this._indexNodesColor;
return cc.color(locRealColor.r, locRealColor.g, locRealColor.b, locRealColor.a);
},
@@ -206,19 +187,16 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* Sets scale of index nodes
* @param {Number} indexNodesScale
*/
- setIndexNodesScale: function(indexNodesScale)
- {
- if(this._indexNodesScale === indexNodesScale)
- {
+ setIndexNodesScale: function (indexNodesScale) {
+ if (this._indexNodesScale === indexNodesScale) {
return;
}
this._indexNodesScale = indexNodesScale;
this._currentIndexNode.setScale(indexNodesScale);
- for(var i = 0 ; i < this._indexNodes.length; ++i)
- {
- this._indexNodes[i].setScale(this,_indexNodesScale);
+ for (var i = 0; i < this._indexNodes.length; ++i) {
+ this._indexNodes[i].setScale(this, _indexNodesScale);
}
this._rearrange();
@@ -228,8 +206,7 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* Gets scale of index nodes
* @returns {Number}
*/
- getIndexNodesScale: function()
- {
+ getIndexNodesScale: function () {
return this._indexNodesScale;
},
@@ -238,28 +215,24 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* @param {String} texName
* @param {ccui.Widget.LOCAL_TEXTURE | ccui.Widget.PLIST_TEXTURE} [texType = ccui.Widget.LOCAL_TEXTURE]
*/
- setIndexNodesTexture: function(texName, texType)
- {
- if(texType === undefined)
+ setIndexNodesTexture: function (texName, texType) {
+ if (texType === undefined)
texType = ccui.Widget.LOCAL_TEXTURE;
this._useDefaultTexture = false;
this._indexNodesTextureFile = texName;
this._indexNodesTexType = texType;
- switch (texType)
- {
+ switch (texType) {
case ccui.Widget.LOCAL_TEXTURE:
this._currentIndexNode.setTexture(texName);
- for(var i = 0 ; i < this._indexNodes.length; ++i)
- {
+ for (var i = 0; i < this._indexNodes.length; ++i) {
this._indexNodes[i].setTexture(texName);
}
break;
case ccui.Widget.PLIST_TEXTURE:
this._currentIndexNode.setSpriteFrame(texName);
- for(var i = 0 ; i < this._indexNodes.length; ++i)
- {
+ for (var i = 0; i < this._indexNodes.length; ++i) {
this._indexNodes[i].setSpriteFrame(texName);
}
break;
@@ -270,19 +243,15 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
this._rearrange();
},
- _increaseNumberOfPages: function()
- {
+ _increaseNumberOfPages: function () {
var indexNode;
- if(this._useDefaultTexture)
- {
+ if (this._useDefaultTexture) {
indexNode = ccui.helper._createSpriteFromBase64(ccui.PageViewIndicator.CIRCLE_IMAGE, ccui.PageViewIndicator.CIRCLE_IMAGE_KEY);
}
- else
- {
+ else {
indexNode = new cc.Sprite();
- switch (this._indexNodesTexType)
- {
+ switch (this._indexNodesTexType) {
case ccui.Widget.LOCAL_TEXTURE:
indexNode.initWithFile(this._indexNodesTextureFile);
break;
@@ -301,10 +270,8 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
this._indexNodes.push(indexNode);
},
- _decreaseNumberOfPages: function()
- {
- if(this._indexNodes.length === 0)
- {
+ _decreaseNumberOfPages: function () {
+ if (this._indexNodes.length === 0) {
return;
}
this.removeProtectedChild(this._indexNodes[0]);
@@ -314,10 +281,8 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
/**
* Removes all index nodes.
*/
- clear: function()
- {
- for(var i = 0; i < this._indexNodes.length; ++i)
- {
+ clear: function () {
+ for (var i = 0; i < this._indexNodes.length; ++i) {
this.removeProtectedChild(this._indexNodes[i]);
}
this._indexNodes.length = 0;
diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js
index 0a71cdf1a3..cbdadaad21 100644
--- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js
+++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js
@@ -47,12 +47,12 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
_touchMoveDisplacements: null,
_touchMoveTimeDeltas: null,
_touchMovePreviousTimestamp: 0,
- _touchTotalTimeThreshold : 0.5,
+ _touchTotalTimeThreshold: 0.5,
_autoScrolling: false,
_autoScrollTargetDelta: null,
_autoScrollAttenuate: true,
- _autoScrollStartPosition : null,
+ _autoScrollStartPosition: null,
_autoScrollTotalTime: 0,
_autoScrollAccumulatedTime: 0,
_autoScrollCurrentlyOutOfBoundary: false,
@@ -109,19 +109,6 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
this.setTouchEnabled(true);
},
- /**
- * Initializes a ccui.ScrollView. Please do not call this function by yourself, you should pass the parameters to constructor to initialize it.
- * @returns {boolean}
- */
- init: function () {
- if (ccui.Layout.prototype.init.call(this)) {
-
-
- return true;
- }
- return false;
- },
-
/**
* Calls the parent class' onEnter and schedules update function.
* @override
@@ -136,6 +123,69 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
ccui.Layout.prototype.onExit.call(this);
},
+ visit: function (parent) {
+ if (!this._visible)
+ return;
+
+ this._adaptRenderers();
+ this._doLayout();
+
+ var renderer = cc.renderer, cmd = this._renderCmd;
+ var parentCmd = parent && parent._renderCmd;
+ cmd.visit(parentCmd);
+
+ renderer.pushRenderCommand(cmd);
+ if (cmd instanceof ccui.ScrollView.WebGLRenderCmd) {
+ var currentID = this.__instanceId;
+ renderer._turnToCacheMode(currentID);
+ }
+
+ var stencilClipping = this._clippingEnabled && this._clippingType === ccui.Layout.CLIPPING_STENCIL;
+ var scissorClipping = this._clippingEnabled && this._clippingType === ccui.Layout.CLIPPING_SCISSOR;
+
+ if (stencilClipping) {
+ cmd.stencilClippingVisit(parentCmd);
+ }
+ else if (scissorClipping) {
+ cmd.scissorClippingVisit(parentCmd);
+ }
+
+ var i, children = this._children, len = children.length, child;
+ var j, pChildren = this._protectedChildren, pLen = pChildren.length, pChild;
+
+ if (this._reorderChildDirty) this.sortAllChildren();
+ if (this._reorderProtectedChildDirty) this.sortAllProtectedChildren();
+ for (i = 0; i < len; i++) {
+ child = children[i];
+ if (child && child._visible) {
+ child.visit(this);
+ }
+ }
+ for (j = 0; j < pLen; j++) {
+ pChild = pChildren[j];
+ if (pChild && pChild._visible) {
+ cmd._changeProtectedChild(pChild);
+ pChild.visit(this);
+ }
+ }
+
+ if (stencilClipping) {
+ cmd.postStencilVisit();
+ }
+ else if (scissorClipping) {
+ cmd.postScissorVisit();
+ }
+
+ if (cmd instanceof ccui.ScrollView.WebGLRenderCmd) {
+ renderer._turnToNormalMode();
+ }
+
+ // Need to update children after do layout
+ this.updateChildren();
+
+ cmd._dirtyFlag = 0;
+ },
+
/**
* When a widget is in a layout, you could call this method to get the next focused widget within a specified _direction.
* If the widget is not in a layout, it will return itself
@@ -144,7 +194,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
* @param {ccui.Widget} current the current focused widget
* @returns {ccui.Widget}
*/
- findNextFocusedWidget: function(direction, current){
+ findNextFocusedWidget: function (direction, current) {
if (this.getLayoutType() === ccui.Layout.LINEAR_VERTICAL
|| this.getLayoutType() === ccui.Layout.LINEAR_HORIZONTAL) {
return this._innerContainer.findNextFocusedWidget(direction, current);
@@ -156,7 +206,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
ccui.Layout.prototype._initRenderer.call(this);
this._innerContainer = new ccui.Layout();
- this._innerContainer.setColor(cc.color(255,255,255));
+ this._innerContainer.setColor(cc.color(255, 255, 255));
this._innerContainer.setOpacity(255);
this._innerContainer.setCascadeColorEnabled(true);
this._innerContainer.setCascadeOpacityEnabled(true);
@@ -164,8 +214,8 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
this.addProtectedChild(this._innerContainer, 1, 1);
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
return new ccui.ScrollView.WebGLRenderCmd(this);
else
return new ccui.ScrollView.CanvasRenderCmd(this);
@@ -193,7 +243,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
* @param {cc.Size} size inner container size.
*/
setInnerContainerSize: function (size) {
- var innerContainer = this._innerContainer,
+ var innerContainer = this._innerContainer,
locSize = this._contentSize,
innerSizeWidth = locSize.width, innerSizeHeight = locSize.height;
@@ -283,23 +333,18 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
*
* @param {cc.Point} position Inner container position.
*/
- setInnerContainerPosition: function(position)
- {
- if(position.x === this._innerContainer.getPositionX() && position.y === this._innerContainer.getPositionY())
- {
+ setInnerContainerPosition: function (position) {
+ if (position.x === this._innerContainer.getPositionX() && position.y === this._innerContainer.getPositionY()) {
return;
}
this._innerContainer.setPosition(position);
this._outOfBoundaryAmountDirty = true;
// Process bouncing events
- if(this.bounceEnabled)
- {
- for(var _direction = ccui.ScrollView.MOVEDIR_TOP; _direction < ccui.ScrollView.MOVEDIR_RIGHT; ++_direction)
- {
- if(this._isOutOfBoundary(_direction))
- {
- this._processScrollEvent(_direction, true);
+ if (this.bounceEnabled) {
+ for (var _direction = ccui.ScrollView.MOVEDIR_TOP; _direction < ccui.ScrollView.MOVEDIR_RIGHT; ++_direction) {
+ if (this._isOutOfBoundary(_direction)) {
+ this._processScrollEvent(_direction, true);
}
}
}
@@ -312,8 +357,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
*
* @return The inner container position.
*/
- getInnerContainerPosition: function()
- {
+ getInnerContainerPosition: function () {
return this._innerContainer.getPosition();
},
@@ -334,7 +378,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
},
_isInContainer: function (widget) {
- if(!this._clippingEnabled)
+ if (!this._clippingEnabled)
return true;
var wPos = widget._position,
wSize = widget._contentSize,
@@ -359,9 +403,9 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
updateChildren: function () {
var child, i, l;
var childrenArray = this._innerContainer._children;
- for(i = 0, l = childrenArray.length; i < l; i++) {
+ for (i = 0, l = childrenArray.length; i < l; i++) {
child = childrenArray[i];
- if(child._inViewRect === true && this._isInContainer(child) === false)
+ if (child._inViewRect === true && this._isInContainer(child) === false)
child._inViewRect = false;
else if (child._inViewRect === false && this._isInContainer(child) === true)
child._inViewRect = true;
@@ -375,9 +419,9 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
* @returns {boolean}
*/
addChild: function (widget, zOrder, tag) {
- if(!widget)
+ if (!widget)
return false;
- if(this._isInContainer(widget) === false)
+ if (this._isInContainer(widget) === false)
widget._inViewRect = false;
zOrder = zOrder || widget.getLocalZOrder();
tag = tag || widget.getTag();
@@ -395,7 +439,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
* Removes all children.
* @param {Boolean} cleanup
*/
- removeAllChildrenWithCleanup: function(cleanup){
+ removeAllChildrenWithCleanup: function (cleanup) {
this._innerContainer.removeAllChildrenWithCleanup(cleanup);
},
@@ -444,59 +488,48 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
return this._innerContainer.getChildByName(name);
},
- _flattenVectorByDirection: function(vector)
- {
- var result = cc.p(0 ,0);
+ _flattenVectorByDirection: function (vector) {
+ var result = cc.p(0, 0);
result.x = (this._direction === ccui.ScrollView.DIR_VERTICAL ? 0 : vector.x);
result.y = (this._direction === ccui.ScrollView.DIR_HORIZONTAL ? 0 : vector.y);
return result;
},
- _getHowMuchOutOfBoundary: function(addition)
- {
- if(addition === undefined)
+ _getHowMuchOutOfBoundary: function (addition) {
+ if (addition === undefined)
addition = cc.p(0, 0);
- if(addition.x === 0 && addition.y === 0 && !this._outOfBoundaryAmountDirty)
- {
+ if (addition.x === 0 && addition.y === 0 && !this._outOfBoundaryAmountDirty) {
return this._outOfBoundaryAmount;
}
var outOfBoundaryAmount = cc.p(0, 0);
- if(this._innerContainer.getLeftBoundary() + addition.x > this._leftBoundary)
- {
+ if (this._innerContainer.getLeftBoundary() + addition.x > this._leftBoundary) {
outOfBoundaryAmount.x = this._leftBoundary - (this._innerContainer.getLeftBoundary() + addition.x);
}
- else if(this._innerContainer.getRightBoundary() + addition.x < this._rightBoundary)
- {
+ else if (this._innerContainer.getRightBoundary() + addition.x < this._rightBoundary) {
outOfBoundaryAmount.x = this._rightBoundary - (this._innerContainer.getRightBoundary() + addition.x);
}
- if(this._innerContainer.getTopBoundary() + addition.y < this._topBoundary)
- {
+ if (this._innerContainer.getTopBoundary() + addition.y < this._topBoundary) {
outOfBoundaryAmount.y = this._topBoundary - (this._innerContainer.getTopBoundary() + addition.y);
}
- else if(this._innerContainer.getBottomBoundary() + addition.y > this._bottomBoundary)
- {
+ else if (this._innerContainer.getBottomBoundary() + addition.y > this._bottomBoundary) {
outOfBoundaryAmount.y = this._bottomBoundary - (this._innerContainer.getBottomBoundary() + addition.y);
}
- if(addition.x === 0 && addition.y === 0 )
- {
+ if (addition.x === 0 && addition.y === 0) {
this._outOfBoundaryAmount = outOfBoundaryAmount;
this._outOfBoundaryAmountDirty = false;
}
return outOfBoundaryAmount;
},
- _isOutOfBoundary: function(dir)
- {
+ _isOutOfBoundary: function (dir) {
var outOfBoundary = this._getHowMuchOutOfBoundary();
- if(dir !== undefined)
- {
- switch (dir)
- {
+ if (dir !== undefined) {
+ switch (dir) {
case ccui.ScrollView.MOVEDIR_TOP:
return outOfBoundary.y > 0;
case ccui.ScrollView.MOVEDIR_BOTTOM:
@@ -507,8 +540,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
return outOfBoundary.x > 0;
}
}
- else
- {
+ else {
return !this._fltEqualZero(outOfBoundary);
}
@@ -516,17 +548,15 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
},
- _moveInnerContainer: function(deltaMove, canStartBounceBack)
- {
+ _moveInnerContainer: function (deltaMove, canStartBounceBack) {
var adjustedMove = this._flattenVectorByDirection(deltaMove);
this.setInnerContainerPosition(cc.pAdd(this.getInnerContainerPosition(), adjustedMove));
- var outOfBoundary =this._getHowMuchOutOfBoundary();
+ var outOfBoundary = this._getHowMuchOutOfBoundary();
this._updateScrollBar(outOfBoundary);
- if(this.bounceEnabled && canStartBounceBack)
- {
+ if (this.bounceEnabled && canStartBounceBack) {
this._startBounceBackIfNeeded();
}
},
@@ -543,22 +573,18 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
}
},
- _calculateTouchMoveVelocity: function()
- {
+ _calculateTouchMoveVelocity: function () {
var totalTime = 0;
- for(var i = 0; i < this._touchMoveTimeDeltas.length; ++i)
- {
+ for (var i = 0; i < this._touchMoveTimeDeltas.length; ++i) {
totalTime += this._touchMoveTimeDeltas[i];
}
- if(totalTime == 0 || totalTime >= this._touchTotalTimeThreshold)
- {
+ if (totalTime == 0 || totalTime >= this._touchTotalTimeThreshold) {
return cc.p(0, 0);
}
- var totalMovement = cc.p(0 ,0);
+ var totalMovement = cc.p(0, 0);
- for(var i = 0; i < this._touchMoveDisplacements.length; ++i)
- {
+ for (var i = 0; i < this._touchMoveDisplacements.length; ++i) {
totalMovement.x += this._touchMoveDisplacements[i].x;
totalMovement.y += this._touchMoveDisplacements[i].y;
}
@@ -570,8 +596,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
* Set the touch total time threshold
* @param {Number} touchTotalTimeThreshold
*/
- setTouchTotalTimeThreshold: function(touchTotalTimeThreshold)
- {
+ setTouchTotalTimeThreshold: function (touchTotalTimeThreshold) {
this._touchTotalTimeThreshold = touchTotalTimeThreshold;
},
@@ -580,27 +605,22 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
* Get the touch total time threshold
* @returns {Number}
*/
- getTouchTotalTimeThreshold: function()
- {
+ getTouchTotalTimeThreshold: function () {
return this._touchTotalTimeThreshold;
},
- _startInertiaScroll: function(touchMoveVelocity)
- {
+ _startInertiaScroll: function (touchMoveVelocity) {
var MOVEMENT_FACTOR = 0.7;
var inertiaTotalMovement = cc.pMult(touchMoveVelocity, MOVEMENT_FACTOR);
this._startAttenuatingAutoScroll(inertiaTotalMovement, touchMoveVelocity);
},
- _startBounceBackIfNeeded: function()
- {
- if (!this.bounceEnabled)
- {
+ _startBounceBackIfNeeded: function () {
+ if (!this.bounceEnabled) {
return false;
}
var bounceBackAmount = this._getHowMuchOutOfBoundary();
- if(this._fltEqualZero(bounceBackAmount))
- {
+ if (this._fltEqualZero(bounceBackAmount)) {
return false;
}
@@ -609,25 +629,21 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
return true;
},
- _startAutoScrollToDestination: function(destination, timeInSec, attenuated)
- {
- this._startAutoScroll(cc.pSub(destination , this._innerContainer.getPosition()), timeInSec, attenuated);
+ _startAutoScrollToDestination: function (destination, timeInSec, attenuated) {
+ this._startAutoScroll(cc.pSub(destination, this._innerContainer.getPosition()), timeInSec, attenuated);
},
- _calculateAutoScrollTimeByInitialSpeed: function(initialSpeed)
- {
+ _calculateAutoScrollTimeByInitialSpeed: function (initialSpeed) {
// Calculate the time from the initial speed according to quintic polynomial.
return Math.sqrt(Math.sqrt(initialSpeed / 5));
},
- _startAttenuatingAutoScroll: function(deltaMove, initialVelocity)
- {
- var time = this._calculateAutoScrollTimeByInitialSpeed(cc.pLength(initialVelocity));
+ _startAttenuatingAutoScroll: function (deltaMove, initialVelocity) {
+ var time = this._calculateAutoScrollTimeByInitialSpeed(cc.pLength(initialVelocity));
this._startAutoScroll(deltaMove, time, true);
},
- _startAutoScroll: function(deltaMove, timeInSec, attenuated)
- {
+ _startAutoScroll: function (deltaMove, timeInSec, attenuated) {
var adjustedDeltaMove = this._flattenVectorByDirection(deltaMove);
this._autoScrolling = true;
@@ -637,16 +653,14 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
this._autoScrollTotalTime = timeInSec;
this._autoScrollAccumulatedTime = 0;
this._autoScrollBraking = false;
- this._autoScrollBrakingStartPosition = cc.p(0,0 );
+ this._autoScrollBrakingStartPosition = cc.p(0, 0);
// If the destination is also out of boundary of same side, start brake from beggining.
var currentOutOfBoundary = this._getHowMuchOutOfBoundary();
- if(!this._fltEqualZero(currentOutOfBoundary))
- {
+ if (!this._fltEqualZero(currentOutOfBoundary)) {
this._autoScrollCurrentlyOutOfBoundary = true;
var afterOutOfBoundary = this._getHowMuchOutOfBoundary(adjustedDeltaMove);
- if(currentOutOfBoundary.x * afterOutOfBoundary.x > 0 || currentOutOfBoundary.y * afterOutOfBoundary.y > 0)
- {
+ if (currentOutOfBoundary.x * afterOutOfBoundary.x > 0 || currentOutOfBoundary.y * afterOutOfBoundary.y > 0) {
this._autoScrollBraking = true;
}
}
@@ -655,51 +669,42 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
/**
* Immediately stops inner container scroll initiated by any of the "scrollTo*" member functions
*/
- stopAutoScroll: function()
- {
+ stopAutoScroll: function () {
this._autoScrolling = false;
this._autoScrollAttenuate = true;
this._autoScrollTotalTime = 0;
this._autoScrollAccumulatedTime = 0;
},
- _isNecessaryAutoScrollBrake: function()
- {
- if(this._autoScrollBraking)
- {
+ _isNecessaryAutoScrollBrake: function () {
+ if (this._autoScrollBraking) {
return true;
}
- if(this._isOutOfBoundary())
- {
+ if (this._isOutOfBoundary()) {
// It just went out of boundary.
- if(!this._autoScrollCurrentlyOutOfBoundary)
- {
+ if (!this._autoScrollCurrentlyOutOfBoundary) {
this._autoScrollCurrentlyOutOfBoundary = true;
this._autoScrollBraking = true;
this._autoScrollBrakingStartPosition = this.getInnerContainerPosition();
return true;
}
}
- else
- {
+ else {
this._autoScrollCurrentlyOutOfBoundary = false;
}
return false;
},
- _getAutoScrollStopEpsilon: function()
- {
+ _getAutoScrollStopEpsilon: function () {
return 0.0001;
},
- _fltEqualZero: function(point)
- {
- return (Math.abs(point.x) <= 0.0001 && Math.abs(point.y) <= 0.0001);
+ _fltEqualZero: function (point) {
+ return (Math.abs(point.x) <= 0.0001 && Math.abs(point.y) <= 0.0001);
},
- _processAutoScrolling: function(deltaTime)
- {
+ _processAutoScrolling: function (deltaTime) {
var OUT_OF_BOUNDARY_BREAKING_FACTOR = 0.05;
// Make auto scroll shorter if it needs to deaccelerate.
var brakingFactor = (this._isNecessaryAutoScrollBrake() ? OUT_OF_BOUNDARY_BREAKING_FACTOR : 1);
@@ -709,28 +714,24 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
// Calculate the progress percentage
var percentage = Math.min(1, this._autoScrollAccumulatedTime / this._autoScrollTotalTime);
- if(this._autoScrollAttenuate)
- {
+ if (this._autoScrollAttenuate) {
percentage -= 1;
percentage = percentage * percentage * percentage * percentage * percentage + 1;
}
// Calculate the new position
- var newPosition = cc.pAdd(this._autoScrollStartPosition, cc.pMult(this._autoScrollTargetDelta,percentage));
+ var newPosition = cc.pAdd(this._autoScrollStartPosition, cc.pMult(this._autoScrollTargetDelta, percentage));
var reachedEnd = Math.abs(percentage - 1) <= this._getAutoScrollStopEpsilon();
- if(this.bounceEnabled)
- {
+ if (this.bounceEnabled) {
// The new position is adjusted if out of boundary
newPosition = cc.pAdd(this._autoScrollBrakingStartPosition, cc.pMult(cc.pSub(newPosition, this._autoScrollBrakingStartPosition), brakingFactor));
}
- else
- {
+ else {
// Don't let go out of boundary
var moveDelta = cc.pSub(newPosition, this.getInnerContainerPosition());
var outOfBoundary = this._getHowMuchOutOfBoundary(moveDelta);
- if(!this._fltEqualZero(outOfBoundary))
- {
+ if (!this._fltEqualZero(outOfBoundary)) {
newPosition.x += outOfBoundary.x;
newPosition.y += outOfBoundary.y;
@@ -739,8 +740,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
}
// Finish auto scroll if it ended
- if(reachedEnd)
- {
+ if (reachedEnd) {
this._autoScrolling = false;
this._dispatchEvent(ccui.ScrollView.EVENT_AUTOSCROLL_ENDED);
}
@@ -748,10 +748,8 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
this._moveInnerContainer(cc.pSub(newPosition, this.getInnerContainerPosition()), reachedEnd);
},
- _jumpToDestination: function (desOrX, y)
- {
- if(desOrX.x === undefined)
- {
+ _jumpToDestination: function (desOrX, y) {
+ if (desOrX.x === undefined) {
desOrX = cc.p(desOrX, y);
}
@@ -759,19 +757,16 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
this._moveInnerContainer(cc.pSub(desOrX, this.getInnerContainerPosition()), true);
},
- _scrollChildren: function(deltaMove)
- {
+ _scrollChildren: function (deltaMove) {
var realMove = deltaMove;
- if(this.bounceEnabled)
- {
+ if (this.bounceEnabled) {
// If the position of the inner container is out of the boundary, the offsets should be divided by two.
var outOfBoundary = this._getHowMuchOutOfBoundary();
realMove.x *= (outOfBoundary.x == 0 ? 1 : 0.5);
realMove.y *= (outOfBoundary.y == 0 ? 1 : 0.5);
}
- if(!this.bounceEnabled)
- {
+ if (!this.bounceEnabled) {
var outOfBoundary = this._getHowMuchOutOfBoundary(realMove);
realMove.x += outOfBoundary.x;
realMove.y += outOfBoundary.y;
@@ -785,16 +780,14 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
if (realMove.y > 0.0) // up
{
var icBottomPos = this._innerContainer.getBottomBoundary();
- if (icBottomPos + realMove.y >= this._bottomBoundary)
- {
+ if (icBottomPos + realMove.y >= this._bottomBoundary) {
scrolledToBottom = true;
}
}
else if (realMove.y < 0.0) // down
{
var icTopPos = this._innerContainer.getTopBoundary();
- if (icTopPos + realMove.y <= this._topBoundary)
- {
+ if (icTopPos + realMove.y <= this._topBoundary) {
scrolledToTop = true;
}
}
@@ -802,39 +795,32 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
if (realMove.x < 0.0) // left
{
var icRightPos = this._innerContainer.getRightBoundary();
- if (icRightPos + realMove.x <= this._rightBoundary)
- {
+ if (icRightPos + realMove.x <= this._rightBoundary) {
scrolledToRight = true;
}
}
else if (realMove.x > 0.0) // right
{
var icLeftPos = this._innerContainer.getLeftBoundary();
- if (icLeftPos + realMove.x >= this._leftBoundary)
- {
+ if (icLeftPos + realMove.x >= this._leftBoundary) {
scrolledToLeft = true;
}
}
this._moveInnerContainer(realMove, false);
- if(realMove.x != 0 || realMove.y != 0)
- {
+ if (realMove.x != 0 || realMove.y != 0) {
this._processScrollingEvent();
}
- if(scrolledToBottom)
- {
+ if (scrolledToBottom) {
this._processScrollEvent(ccui.ScrollView.MOVEDIR_BOTTOM, false);
}
- if(scrolledToTop)
- {
+ if (scrolledToTop) {
this._processScrollEvent(ccui.ScrollView.MOVEDIR_TOP, false);
}
- if(scrolledToLeft)
- {
+ if (scrolledToLeft) {
this._processScrollEvent(ccui.ScrollView.MOVEDIR_LEFT, false);
}
- if(scrolledToRight)
- {
+ if (scrolledToRight) {
this._processScrollEvent(ccui.ScrollView.MOVEDIR_RIGHT, false);
}
},
@@ -902,7 +888,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
}
var inSize = this._innerContainer.getContentSize();
this._startAutoScrollToDestination(cc.p(this._contentSize.width - inSize.width,
- this._contentSize.height - inSize.height), time, attenuated);
+ this._contentSize.height - inSize.height), time, attenuated);
},
/**
@@ -1075,13 +1061,11 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
this._jumpToDestination(-(percent.x * w / 100), minY + percent.y * h / 100);
},
- _gatherTouchMove: function(delta)
- {
+ _gatherTouchMove: function (delta) {
var NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED = 5;
- while(this._touchMoveDisplacements.length >= NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED)
- {
- this._touchMoveDisplacements.splice(0,1);
- this._touchMoveTimeDeltas.splice(0,1)
+ while (this._touchMoveDisplacements.length >= NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED) {
+ this._touchMoveDisplacements.splice(0, 1);
+ this._touchMoveTimeDeltas.splice(0, 1)
}
this._touchMoveDisplacements.push(delta);
@@ -1131,11 +1115,9 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
this._bePressed = false;
var bounceBackStarted = this._startBounceBackIfNeeded();
- if(!bounceBackStarted && this.inertiaScrollEnabled)
- {
+ if (!bounceBackStarted && this.inertiaScrollEnabled) {
var touchMoveVelocity = this._calculateTouchMoveVelocity();
- if(touchMoveVelocity.x !== 0 || touchMoveVelocity.y !== 0)
- {
+ if (touchMoveVelocity.x !== 0 || touchMoveVelocity.y !== 0) {
this._startInertiaScroll(touchMoveVelocity);
}
}
@@ -1158,7 +1140,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
*/
onTouchBegan: function (touch, event) {
var pass = ccui.Layout.prototype.onTouchBegan.call(this, touch, event);
- if(!this._isInterceptTouch){
+ if (!this._isInterceptTouch) {
if (this._hit)
this._handlePressLogic(touch);
}
@@ -1172,7 +1154,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
*/
onTouchMoved: function (touch, event) {
ccui.Layout.prototype.onTouchMoved.call(this, touch, event);
- if(!this._isInterceptTouch)
+ if (!this._isInterceptTouch)
this._handleMoveLogic(touch);
},
@@ -1183,7 +1165,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
*/
onTouchEnded: function (touch, event) {
ccui.Layout.prototype.onTouchEnded.call(this, touch, event);
- if(!this._isInterceptTouch)
+ if (!this._isInterceptTouch)
this._handleReleaseLogic(touch);
this._isInterceptTouch = false;
},
@@ -1222,7 +1204,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
return;
}
- if(this._direction === ccui.ScrollView.DIR_NONE)
+ if (this._direction === ccui.ScrollView.DIR_NONE)
return;
var touchPoint = touch.getLocation();
@@ -1253,12 +1235,10 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
}
},
- _processScrollEvent: function(_directionEvent, bounce)
- {
+ _processScrollEvent: function (_directionEvent, bounce) {
var event = 0;
- switch(_directionEvent)
- {
+ switch (_directionEvent) {
case ccui.ScrollView.MOVEDIR_TOP:
event = (bounce ? ccui.ScrollView.EVENT_BOUNCE_TOP : ccui.ScrollView.EVENT_SCROLL_TO_TOP);
break;
@@ -1276,20 +1256,18 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
this._dispatchEvent(event);
},
- _processScrollingEvent: function()
- {
- this._dispatchEvent( ccui.ScrollView.EVENT_SCROLLING);
+ _processScrollingEvent: function () {
+ this._dispatchEvent(ccui.ScrollView.EVENT_SCROLLING);
},
- _dispatchEvent: function(event)
- {
- if(this._scrollViewEventSelector){
+ _dispatchEvent: function (event) {
+ if (this._scrollViewEventSelector) {
if (this._scrollViewEventListener)
this._scrollViewEventSelector.call(this._scrollViewEventListener, this, event);
else
this._scrollViewEventSelector(this, event);
}
- if(this._ccEventCallback)
+ if (this._ccEventCallback)
this._ccEventCallback(this, event);
},
@@ -1308,7 +1286,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
* Adds callback function called ScrollView event triggered
* @param {Function} selector
*/
- addEventListener: function(selector){
+ addEventListener: function (selector) {
this._ccEventCallback = selector;
},
@@ -1670,7 +1648,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
return "ScrollView";
},
- _createCloneInstance: function(){
+ _createCloneInstance: function () {
return new ccui.ScrollView();
},
@@ -1679,7 +1657,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
},
_copySpecialProperties: function (scrollView) {
- if(scrollView instanceof ccui.ScrollView) {
+ if (scrollView instanceof ccui.ScrollView) {
ccui.Layout.prototype._copySpecialProperties.call(this, scrollView);
this.setInnerContainerSize(scrollView.getInnerContainerSize());
this.setInnerContainerPosition(scrollView.getInnerContainerPosition());
diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewBar.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewBar.js
index ab425afcc6..4e9c1840a7 100644
--- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewBar.js
+++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewBar.js
@@ -41,16 +41,16 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
_lowerHalfCircle: null,
_body: null,
- _opacity : 255,
+ _opacity: 255,
- _marginFromBoundary : 0,
+ _marginFromBoundary: 0,
_marginForLength: 0,
_touching: false,
_autoHideEnabled: true,
- autoHideTime : 0,
- _autoHideRemainingTime : 0,
+ autoHideTime: 0,
+ _autoHideRemainingTime: 0,
_className: "ScrollViewBar",
/**
@@ -62,7 +62,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
ctor: function (parent, direction) {
cc.ProtectedNode.prototype.ctor.call(this);
this._direction = direction;
- this._parentScroll = parent;
+ this._parentScroll = parent;
this._marginFromBoundary = ccui.ScrollViewBar.DEFAULT_MARGIN;
this._marginForLength = ccui.ScrollViewBar.DEFAULT_MARGIN;
@@ -91,7 +91,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
this.addProtectedChild(this._upperHalfCircle);
this.addProtectedChild(this._lowerHalfCircle);
- this._body = ccui.helper._createSpriteFromBase64(ccui.ScrollViewBar.BODY_IMAGE_1_PIXEL_HEIGHT, ccui.ScrollViewBar.BODY_IMAGE_1_PIXEL_HEIGHT_KEY);
+ this._body = ccui.helper._createSpriteFromBase64(ccui.ScrollViewBar.BODY_IMAGE_1_PIXEL_HEIGHT, ccui.ScrollViewBar.BODY_IMAGE_1_PIXEL_HEIGHT_KEY);
this._body.setAnchorPoint(cc.p(0.5, 0));
this.addProtectedChild(this._body);
@@ -100,8 +100,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
cc.ProtectedNode.prototype.setOpacity.call(this, 0);
this._autoHideRemainingTime = 0;
- if(this._direction === ccui.ScrollView.DIR_HORIZONTAL)
- {
+ if (this._direction === ccui.ScrollView.DIR_HORIZONTAL) {
this.setRotation(90);
}
},
@@ -110,22 +109,18 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
* Set the scroll bar position from the left-bottom corner (horizontal) or right-top corner (vertical).
* @param {cc.Point} positionFromCorner The position from the left-bottom corner (horizontal) or right-top corner (vertical).
*/
- setPositionFromCorner: function(positionFromCorner)
- {
- if(this._direction === ccui.ScrollView.DIR_VERTICAL)
- {
+ setPositionFromCorner: function (positionFromCorner) {
+ if (this._direction === ccui.ScrollView.DIR_VERTICAL) {
this._marginForLength = positionFromCorner.y;
this._marginFromBoundary = positionFromCorner.x;
}
- else
- {
+ else {
this._marginForLength = positionFromCorner.x;
this._marginFromBoundary = positionFromCorner.y;
}
},
- onEnter: function()
- {
+ onEnter: function () {
cc.ProtectedNode.prototype.onEnter.call(this);
this.scheduleUpdate();
},
@@ -134,14 +129,11 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
* Get the scroll bar position from the left-bottom corner (horizontal) or right-top corner (vertical).
* @returns {cc.Point}
*/
- getPositionFromCorner: function()
- {
- if(this._direction === ccui.ScrollView.DIR_VERTICAL)
- {
+ getPositionFromCorner: function () {
+ if (this._direction === ccui.ScrollView.DIR_VERTICAL) {
return cc.p(this._marginFromBoundary, this._marginForLength);
}
- else
- {
+ else {
return cc.p(this._marginForLength, this._marginFromBoundary);
}
},
@@ -149,8 +141,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
* Set the scroll bar's width
* @param {number} width The scroll bar's width
*/
- setWidth: function(width)
- {
+ setWidth: function (width) {
var scale = width / this._body.width;
this._body.setScaleX(scale);
this._upperHalfCircle.setScale(scale);
@@ -161,8 +152,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
* Get the scroll bar's width
* @returns {number} the scroll bar's width
*/
- getWidth: function()
- {
+ getWidth: function () {
return this._body.getBoundingBox().width;
},
@@ -170,11 +160,10 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
* Set scroll bar auto hide state
* @param {boolean} autoHideEnabled scroll bar auto hide state
*/
- setAutoHideEnabled: function(autoHideEnabled)
- {
+ setAutoHideEnabled: function (autoHideEnabled) {
this._autoHideEnabled = autoHideEnabled;
- if(!this._autoHideEnabled && !this._touching && this._autoHideRemainingTime <= 0)
+ if (!this._autoHideEnabled && !this._touching && this._autoHideRemainingTime <= 0)
cc.ProtectedNode.prototype.setOpacity.call(this, this.opacity);
else
cc.ProtectedNode.prototype.setOpacity.call(this, 0);
@@ -183,8 +172,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
* Query scroll bar auto hide state
* @returns {boolean} True if scroll bar auto hide is enabled, false otherwise.
*/
- isAutoHideEnabled: function()
- {
+ isAutoHideEnabled: function () {
return this._autoHideEnabled;
},
@@ -192,8 +180,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
* Set scroll bar opacity
* @param {number} opacity scroll bar opacity
*/
- setOpacity: function(opacity)
- {
+ setOpacity: function (opacity) {
this._opacity = opacity;
},
@@ -201,51 +188,42 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
* Get scroll bar opacity
* @returns {number}
*/
- getOpacity: function()
- {
+ getOpacity: function () {
return this._opacity;
},
- _updateLength: function(length)
- {
+ _updateLength: function (length) {
var ratio = length / this._body.getTextureRect().height;
this._body.setScaleY(ratio);
this._upperHalfCircle.setPositionY(this._body.getPositionY() + length);
},
- _processAutoHide: function(dt)
- {
- if(!this._autoHideEnabled || this._autoHideRemainingTime <= 0)
- {
+ _processAutoHide: function (dt) {
+ if (!this._autoHideEnabled || this._autoHideRemainingTime <= 0) {
return;
}
- else if(this._touching)
- {
+ else if (this._touching) {
// If it is touching, don't auto hide.
return;
}
this._autoHideRemainingTime -= dt;
- if(this._autoHideRemainingTime <= this.autoHideTime)
- {
- this. _autoHideRemainingTime = Math.max(0, this._autoHideRemainingTime);
+ if (this._autoHideRemainingTime <= this.autoHideTime) {
+ this._autoHideRemainingTime = Math.max(0, this._autoHideRemainingTime);
cc.ProtectedNode.prototype.setOpacity.call(this, this._opacity * (this._autoHideRemainingTime / this.autoHideTime));
}
},
- update: function(dt)
- {
+ update: function (dt) {
this._processAutoHide(dt);
},
/**
* This is called by parent ScrollView when a touch is began. Don't call this directly.
*/
- onTouchBegan: function()
- {
- if(!this._autoHideEnabled)
- {
+ onTouchBegan: function () {
+ if (!this._autoHideEnabled) {
return;
}
this._touching = true;
@@ -254,16 +232,13 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
/**
* This is called by parent ScrollView when a touch is ended. Don't call this directly.
*/
- onTouchEnded: function()
- {
- if(!this._autoHideEnabled)
- {
+ onTouchEnded: function () {
+ if (!this._autoHideEnabled) {
return;
}
this._touching = false;
- if(this._autoHideRemainingTime <= 0)
- {
+ if (this._autoHideRemainingTime <= 0) {
// If the remaining time is 0, it means that it didn't moved after touch started so scroll bar is not showing.
return;
}
@@ -275,10 +250,8 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
*
* @param {cc.Point} outOfBoundary amount how much the inner container of ScrollView is out of boundary
*/
- onScrolled: function(outOfBoundary)
- {
- if(this._autoHideEnabled)
- {
+ onScrolled: function (outOfBoundary) {
+ if (this._autoHideEnabled) {
this._autoHideRemainingTime = this.autoHideTime;
cc.ProtectedNode.prototype.setOpacity.call(this, this.opacity);
}
@@ -290,15 +263,13 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
var outOfBoundaryValue = 0;
var innerContainerPosition = 0;
- if(this._direction === ccui.ScrollView.DIR_VERTICAL)
- {
+ if (this._direction === ccui.ScrollView.DIR_VERTICAL) {
innerContainerMeasure = innerContainer.height;
scrollViewMeasure = this._parentScroll.height;
outOfBoundaryValue = outOfBoundary.y;
innerContainerPosition = -innerContainer.getPositionY();
}
- else if(this._direction === ccui.ScrollView.DIR_HORIZONTAL)
- {
+ else if (this._direction === ccui.ScrollView.DIR_HORIZONTAL) {
innerContainerMeasure = innerContainer.width;
scrollViewMeasure = this._parentScroll.width;
outOfBoundaryValue = outOfBoundary.x;
@@ -311,11 +282,9 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
this.setPosition(position);
},
- _calculateLength: function(innerContainerMeasure, scrollViewMeasure, outOfBoundaryValue)
- {
+ _calculateLength: function (innerContainerMeasure, scrollViewMeasure, outOfBoundaryValue) {
var denominatorValue = innerContainerMeasure;
- if(outOfBoundaryValue !== 0)
- {
+ if (outOfBoundaryValue !== 0) {
// If it is out of boundary, the length of scroll bar gets shorter quickly.
var GETTING_SHORTER_FACTOR = 20;
denominatorValue += (outOfBoundaryValue > 0 ? outOfBoundaryValue : -outOfBoundaryValue) * GETTING_SHORTER_FACTOR;
@@ -325,18 +294,15 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
return Math.abs(scrollViewMeasure - 2 * this._marginForLength) * lengthRatio;
},
- _calculatePosition: function(innerContainerMeasure, scrollViewMeasure, innerContainerPosition, outOfBoundaryValue, length)
- {
+ _calculatePosition: function (innerContainerMeasure, scrollViewMeasure, innerContainerPosition, outOfBoundaryValue, length) {
var denominatorValue = innerContainerMeasure - scrollViewMeasure;
- if(outOfBoundaryValue !== 0)
- {
+ if (outOfBoundaryValue !== 0) {
denominatorValue += Math.abs(outOfBoundaryValue);
}
var positionRatio = 0;
- if(denominatorValue !== 0)
- {
+ if (denominatorValue !== 0) {
positionRatio = innerContainerPosition / denominatorValue;
positionRatio = Math.max(positionRatio, 0);
positionRatio = Math.min(positionRatio, 1);
@@ -344,12 +310,10 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
var position = (scrollViewMeasure - length - 2 * this._marginForLength) * positionRatio + this._marginForLength;
- if(this._direction === ccui.ScrollView.DIR_VERTICAL)
- {
+ if (this._direction === ccui.ScrollView.DIR_VERTICAL) {
return cc.p(this._parentScroll.width - this._marginFromBoundary, position);
}
- else
- {
+ else {
return cc.p(position, this._marginFromBoundary);
}
}
diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js
index a96de5790a..4607932e9d 100644
--- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js
+++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js
@@ -1,8 +1,8 @@
-(function(){
- if(!ccui.ProtectedNode.CanvasRenderCmd)
+(function () {
+ if (!ccui.ProtectedNode.CanvasRenderCmd)
return;
- ccui.ScrollView.CanvasRenderCmd = function(renderable){
- ccui.Layout.CanvasRenderCmd.call(this, renderable);
+ ccui.ScrollView.CanvasRenderCmd = function (renderable) {
+ this._layoutCmdCtor(renderable);
//this._needDraw = true;
this._dirty = false;
};
@@ -10,24 +10,9 @@
var proto = ccui.ScrollView.CanvasRenderCmd.prototype = Object.create(ccui.Layout.CanvasRenderCmd.prototype);
proto.constructor = ccui.ScrollView.CanvasRenderCmd;
- proto.visit = function(parentCmd) {
- var node = this._node;
- if (!node._visible)
- return;
- var currentID = node.__instanceId;
-
- cc.renderer.pushRenderCommand(this);
- //cc.renderer._turnToCacheMode(currentID);
-
- this.layoutVisit(parentCmd);
-
- this._dirtyFlag = 0;
- //cc.renderer._turnToNormalMode();
- };
-
proto.rendering = function (ctx) {
var currentID = this._node.__instanceId;
- var locCmds = cc.renderer._cacheToCanvasCmds[currentID], i, len,
+ var i, locCmds = cc.renderer._cacheToCanvasCmds[currentID], len,
scaleX = cc.view.getScaleX(),
scaleY = cc.view.getScaleY();
var context = ctx || cc._renderContext;
@@ -37,9 +22,9 @@
for (i = 0, len = locCmds.length; i < len; i++) {
var checkNode = locCmds[i]._node;
- if(checkNode instanceof ccui.ScrollView)
+ if (checkNode instanceof ccui.ScrollView)
continue;
- if(checkNode && checkNode._parent && checkNode._parent._inViewRect === false)
+ if (checkNode && checkNode._parent && checkNode._parent._inViewRect === false)
continue;
locCmds[i].rendering(context, scaleX, scaleY);
}
diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js
index 413d23aff0..45d0aa3b2a 100644
--- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js
+++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js
@@ -1,9 +1,8 @@
-
-(function(){
- if(!ccui.ProtectedNode.WebGLRenderCmd)
+(function () {
+ if (!ccui.ProtectedNode.WebGLRenderCmd)
return;
- ccui.ScrollView.WebGLRenderCmd = function(renderable){
- ccui.Layout.WebGLRenderCmd.call(this, renderable);
+ ccui.ScrollView.WebGLRenderCmd = function (renderable) {
+ this._layoutCmdCtor(renderable);
this._needDraw = true;
this._dirty = false;
};
@@ -11,24 +10,7 @@
var proto = ccui.ScrollView.WebGLRenderCmd.prototype = Object.create(ccui.Layout.WebGLRenderCmd.prototype);
proto.constructor = ccui.ScrollView.WebGLRenderCmd;
- proto.visit = function(parentCmd) {
- var node = this._node;
- if (!node._visible)
- return;
- var currentID = this._node.__instanceId;
-
- cc.renderer.pushRenderCommand(this);
- cc.renderer._turnToCacheMode(currentID);
-
- this.layoutVisit(parentCmd);
- // Need to update children after do layout
- node.updateChildren();
-
- this._dirtyFlag = 0;
- cc.renderer._turnToNormalMode();
- };
-
- proto.rendering = function(ctx){
+ proto.rendering = function (ctx) {
var currentID = this._node.__instanceId,
locCmds = cc.renderer._cacheToBufferCmds[currentID],
i, len, checkNode, cmd,
@@ -45,9 +27,9 @@
for (i = 0, len = locCmds.length; i < len; i++) {
cmd = locCmds[i];
checkNode = cmd._node;
- if(checkNode instanceof ccui.ScrollView)
+ if (checkNode instanceof ccui.ScrollView)
continue;
- if(checkNode && checkNode._parent && checkNode._parent._inViewRect === false)
+ if (checkNode && checkNode._parent && checkNode._parent._inViewRect === false)
continue;
if (cmd.uploadData) {
diff --git a/extensions/cocostudio/action/CCActionManager.js b/extensions/cocostudio/action/CCActionManager.js
index 434fb83327..0a5dc68b9f 100644
--- a/extensions/cocostudio/action/CCActionManager.js
+++ b/extensions/cocostudio/action/CCActionManager.js
@@ -84,8 +84,8 @@ ccs.actionManager = /** @lends ccs.actionManager# */{
if (action)
action.play(fun);
},
-
- /**
+
+ /**
* Stop an Action with a name.
* @param {String} jsonName
* @param {String} actionName
@@ -103,10 +103,10 @@ ccs.actionManager = /** @lends ccs.actionManager# */{
this._actionDic = {};
},
- /**
- * Clear data: Release all actions.
- */
- clear: function() {
- this._actionDic = {};
- }
+ /**
+ * Clear data: Release all actions.
+ */
+ clear: function () {
+ this._actionDic = {};
+ }
};
diff --git a/extensions/cocostudio/action/CCActionNode.js b/extensions/cocostudio/action/CCActionNode.js
index 199c7d110f..d029830088 100644
--- a/extensions/cocostudio/action/CCActionNode.js
+++ b/extensions/cocostudio/action/CCActionNode.js
@@ -72,12 +72,12 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{
var actionFrameDic = actionFrameList[i];
var frameIndex = actionFrameDic["frameid"];
var frameTweenType = actionFrameDic["tweenType"];
- if(frameTweenType == null)
+ if (frameTweenType == null)
frameTweenType = 0;
var frameTweenParameterNum = actionFrameDic["tweenParameter"];
var frameTweenParameter = [];
- for (var j = 0; j < frameTweenParameterNum; j++){
+ for (var j = 0; j < frameTweenParameterNum; j++) {
var value = actionFrameDic["tweenParameter"][j];
frameTweenParameter.push(value);
}
@@ -86,7 +86,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{
if (actionFrameDic["positionx"] !== undefined) {
var positionX = actionFrameDic["positionx"];
var positionY = actionFrameDic["positiony"];
- if(positionOffset && node.parent){
+ if (positionOffset && node.parent) {
var AnchorPointIn = node.parent.getAnchorPointInPoints();
positionX += AnchorPointIn.x;
positionY += AnchorPointIn.y;
@@ -249,7 +249,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{
* @param {ccs.ActionFrame} frame
*/
deleteFrame: function (frame) {
- if (frame == null)
+ if (frame === undefined)
return;
var frameType = frame.frameType;
var array = this._frameArray[frameType];
@@ -265,7 +265,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{
},
_refreshActionProperty: function () {
- if (this._object === null)
+ if (!this._object)
return null;
var locSpawnArray = [];
for (var i = 0; i < this._frameArrayNum; i++) {
@@ -284,10 +284,10 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{
else {
locAction = locFrame.getAction(0);
}
- if(locAction)
+ if (locAction)
locSequenceArray.push(locAction);
}
- if(locSequenceArray){
+ if (locSequenceArray) {
var locSequence = cc.sequence(locSequenceArray);
if (locSequence !== null)
locSpawnArray.push(locSequence);
@@ -304,9 +304,9 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{
* @param {cc.CallFunc} fun
*/
playAction: function (fun) {
- if (this._object === null || this._actionSpawn === null)
+ if (!this._object || !this._actionSpawn)
return;
- if(fun)
+ if (fun)
this._action = cc.sequence(this._actionSpawn, fun);
else
this._action = cc.sequence(this._actionSpawn);
@@ -325,7 +325,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{
stopAction: function () {
var node = this.getActionNode();
if (node !== null && this._action !== null) {
- if(!this._action.isDone())
+ if (!this._action.isDone())
node.stopAction(this._action);
}
},
@@ -356,7 +356,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{
*/
getLastFrameIndex: function () {
var locFrameindex = -1;
- var locIsFindFrame = false ,locFrameArray = this._frameArray;
+ var locIsFindFrame = false, locFrameArray = this._frameArray;
for (var i = 0, len = this._frameArrayNum; i < len; i++) {
var locArray = locFrameArray[i];
if (locArray.length <= 0)
@@ -381,7 +381,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{
var locUnitTime = this.getUnitTime();
for (var i = 0; i < this._frameArrayNum; i++) {
var locArray = this._frameArray[i];
- if (locArray === null)
+ if (!locArray)
continue;
for (var j = 0; j < locArray.length; j++) {
@@ -423,7 +423,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{
* @returns {Boolean} that if the action is done once time
*/
isActionDoneOnce: function () {
- if (this._action === null)
+ if (!this._action)
return true;
return this._action.isDone();
}
diff --git a/extensions/cocostudio/armature/CCArmature.js b/extensions/cocostudio/armature/CCArmature.js
index 2f03c1710e..80235b9dd2 100644
--- a/extensions/cocostudio/armature/CCArmature.js
+++ b/extensions/cocostudio/armature/CCArmature.js
@@ -79,7 +79,6 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{
* @return {Boolean}
*/
init: function (name, parentBone) {
- cc.Node.prototype.init.call(this);
if (parentBone)
this._parentBone = parentBone;
this.removeAllChildren();
@@ -150,8 +149,17 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{
return true;
},
+ visit: function (parent) {
+ // quick return if not visible
+ if (!this._visible)
+ return;
+
+ this._renderCmd.visit(parent && parent._renderCmd);
+ this._renderCmd._dirtyFlag = 0;
+ },
+
addChild: function (child, localZOrder, tag) {
- if(child instanceof ccui.Widget){
+ if (child instanceof ccui.Widget) {
cc.log("Armature doesn't support to add Widget as its child, it will be fix soon.");
return;
}
@@ -194,7 +202,7 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{
addBone: function (bone, parentName) {
cc.assert(bone, "Argument must be non-nil");
var locBoneDic = this._boneDic;
- if(bone.getName())
+ if (bone.getName())
cc.assert(!locBoneDic[bone.getName()], "bone already added. It can't be added again");
if (parentName) {
@@ -282,7 +290,7 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{
this.setAnchorPoint(locOffsetPoint.x / rect.width, locOffsetPoint.y / rect.height);
},
- getOffsetPoints: function(){
+ getOffsetPoints: function () {
return {x: this._offsetPoint.x, y: this._offsetPoint.y};
},
@@ -345,21 +353,21 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{
* This boundingBox will calculate all bones' boundingBox every time
* @returns {cc.Rect}
*/
- getBoundingBox: function(){
+ getBoundingBox: function () {
var minX, minY, maxX, maxY = 0;
var first = true;
var boundingBox = cc.rect(0, 0, 0, 0), locChildren = this._children;
var len = locChildren.length;
- for (var i=0; i= ccs.CONST_VERSION_COMBINED){
+ if (this._dataVersion >= ccs.CONST_VERSION_COMBINED) {
ccs.TransformHelp.nodeConcat(locTweenData, this._boneData);
locTweenData.scaleX -= 1;
locTweenData.scaleY -= 1;
@@ -182,7 +182,7 @@ ccs.Bone = ccs.Node.extend(/** @lends ccs.Bone# */{
locWorldInfo.skewX = locTweenData.skewX + this._skewX + cc.degreesToRadians(this._rotationX);
locWorldInfo.skewY = locTweenData.skewY + this._skewY - cc.degreesToRadians(this._rotationY);
- if(this._parentBone)
+ if (this._parentBone)
this._applyParentTransform(this._parentBone);
else {
if (this._armatureParentBone)
@@ -195,7 +195,7 @@ ccs.Bone = ccs.Node.extend(/** @lends ccs.Bone# */{
}
ccs.displayFactory.updateDisplay(this, delta, this._boneTransformDirty || this._armature.getArmatureTransformDirty());
- for(var i=0; i 0 && this._children.getIndex(bone) !== -1 ) {
- if(recursion) {
+ if (this._children.length > 0 && this._children.getIndex(bone) !== -1) {
+ if (recursion) {
var ccbones = bone._children;
- for(var i=0; i= 0) && (index < locDisplayList.length) )
+ if ((index >= 0) && (index < locDisplayList.length))
decoDisplay = locDisplayList[index];
- else{
+ else {
decoDisplay = new ccs.DecorativeDisplay();
locDisplayList.push(decoDisplay);
}
- if(display instanceof ccs.DisplayData){
+ if (display instanceof ccs.DisplayData) {
ccs.displayFactory.addDisplay(this._bone, decoDisplay, display);
//! if changed display index is current display index, then change current display to the new display
- if(index === this._displayIndex) {
+ if (index === this._displayIndex) {
this._displayIndex = -1;
this.changeDisplayWithIndex(index, false);
}
@@ -117,14 +117,14 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
if (!find)
display.setSkinData(new ccs.BaseData());
}
- } else if (display instanceof cc.ParticleSystem){
+ } else if (display instanceof cc.ParticleSystem) {
displayData = new ccs.ParticleDisplayData();
display.removeFromParent();
- display.cleanup();
+ display._performRecursive(cc.Node._stateCallbackType.cleanup);
var armature = this._bone.getArmature();
if (armature)
display.setParent(armature);
- } else if(display instanceof ccs.Armature) {
+ } else if (display instanceof ccs.Armature) {
displayData = new ccs.ArmatureDisplayData();
displayData.displayName = display.getName();
display.setParentBone(this._bone);
@@ -134,15 +134,15 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
decoDisplay.setDisplayData(displayData);
//! if changed display index is current display index, then change current display to the new display
- if(index === this._displayIndex) {
+ if (index === this._displayIndex) {
this._displayIndex = -1;
this.changeDisplayWithIndex(index, false);
}
},
- _addDisplayOther:function(decoDisplay,display){
+ _addDisplayOther: function (decoDisplay, display) {
var displayData = null;
- if (display instanceof ccs.Skin){
+ if (display instanceof ccs.Skin) {
var skin = display;
skin.setBone(this._bone);
displayData = new ccs.SpriteDisplayData();
@@ -151,7 +151,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
var spriteDisplayData = decoDisplay.getDisplayData();
if (spriteDisplayData instanceof ccs.SpriteDisplayData)
skin.setSkinData(spriteDisplayData.skinData);
- else{
+ else {
var find = false;
for (var i = this._decoDisplayList.length - 2; i >= 0; i--) {
var dd = this._decoDisplayList[i];
@@ -170,16 +170,16 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
}
}
- else if (display instanceof cc.ParticleSystem){
+ else if (display instanceof cc.ParticleSystem) {
displayData = new ccs.ParticleDisplayData();
displayData.displayName = display._plistFile;
}
- else if (display instanceof ccs.Armature){
+ else if (display instanceof ccs.Armature) {
displayData = new ccs.ArmatureDisplayData();
displayData.displayName = display.getName();
display.setParentBone(this._bone);
}
- else {
+ else {
displayData = new ccs.DisplayData();
}
decoDisplay.setDisplay(display);
@@ -190,7 +190,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
* Removes display node from list.
* @param {Number} index
*/
- removeDisplay:function (index) {
+ removeDisplay: function (index) {
this._decoDisplayList.splice(index, 1);
if (index === this._displayIndex) {
this.setCurrentDecorativeDisplay(null);
@@ -202,7 +202,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
* Returns the display node list.
* @returns {Array}
*/
- getDecorativeDisplayList:function(){
+ getDecorativeDisplayList: function () {
return this._decoDisplayList;
},
@@ -215,7 +215,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
* @param {Number} index The index of the display you want to change
* @param {Boolean} force If true, then force change display to specified display, or current display will set to display index edit in the flash every key frame.
*/
- changeDisplayWithIndex:function (index, force) {
+ changeDisplayWithIndex: function (index, force) {
if (index >= this._decoDisplayList.length) {
cc.log("the index value is out of range");
return;
@@ -230,7 +230,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
//! If displayIndex < 0, it means you want to hide you display
if (index < 0) {
- if(this._displayRenderNode) {
+ if (this._displayRenderNode) {
this._displayRenderNode.removeFromParent(true);
this.setCurrentDecorativeDisplay(null);
}
@@ -258,7 +258,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
* Sets current decorative display.
* @param {ccs.DecorativeDisplay} decoDisplay
*/
- setCurrentDecorativeDisplay:function (decoDisplay) {
+ setCurrentDecorativeDisplay: function (decoDisplay) {
var locCurrentDecoDisplay = this._currentDecoDisplay;
if (ccs.ENABLE_PHYSICS_CHIPMUNK_DETECT || ccs.ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX) {
if (locCurrentDecoDisplay && locCurrentDecoDisplay.getColliderDetector())
@@ -299,7 +299,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
this._displayRenderNode.setVisible(this._visible);
this._displayType = this._currentDecoDisplay.getDisplayData().displayType;
- }else
+ } else
this._displayType = ccs.DISPLAY_TYPE_MAX;
@@ -310,7 +310,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
* Returns the current display render node.
* @returns {cc.Node}
*/
- getDisplayRenderNode:function () {
+ getDisplayRenderNode: function () {
return this._displayRenderNode;
},
@@ -318,7 +318,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
* Returns the type of display render node.
* @returns {Number}
*/
- getDisplayRenderNodeType:function(){
+ getDisplayRenderNodeType: function () {
return this._displayType;
},
@@ -326,7 +326,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
* Returns the index of display render node.
* @returns {Number}
*/
- getCurrentDisplayIndex:function () {
+ getCurrentDisplayIndex: function () {
return this._displayIndex;
},
@@ -334,7 +334,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
* Returns the current decorative display
* @returns {ccs.DecorativeDisplay}
*/
- getCurrentDecorativeDisplay:function () {
+ getCurrentDecorativeDisplay: function () {
return this._currentDecoDisplay;
},
@@ -343,7 +343,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
* @param index
* @returns {ccs.DecorativeDisplay}
*/
- getDecorativeDisplayByIndex:function (index) {
+ getDecorativeDisplayByIndex: function (index) {
return this._decoDisplayList[index];
},
@@ -355,7 +355,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
*
* @param {ccs.BoneData} boneData
*/
- initDisplayList:function (boneData) {
+ initDisplayList: function (boneData) {
this._decoDisplayList.length = 0;
if (!boneData)
return;
@@ -382,7 +382,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
if (y !== undefined)
point = cc.p(point, y);
- if(this._currentDecoDisplay.getDisplayData().displayType === ccs.DISPLAY_TYPE_SPRITE){
+ if (this._currentDecoDisplay.getDisplayData().displayType === ccs.DISPLAY_TYPE_SPRITE) {
/*
* First we first check if the point is in the sprite content rect. If false, then we continue to check
* the contour point. If this step is also false, then we can say the bone not contain this point.
@@ -402,7 +402,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
*
* @param {boolean} visible
*/
- setVisible:function (visible) {
+ setVisible: function (visible) {
if (!this._displayRenderNode)
return;
this._visible = visible;
@@ -413,39 +413,39 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
* Determines if the display is visible
* @returns {boolean} true if the node is visible, false if the node is hidden.
*/
- isVisible:function () {
+ isVisible: function () {
return this._visible;
},
- getContentSize:function () {
+ getContentSize: function () {
if (!this._displayRenderNode)
return cc.size(0, 0);
return this._displayRenderNode.getContentSize();
},
- getBoundingBox:function () {
+ getBoundingBox: function () {
if (!this._displayRenderNode)
return cc.rect(0, 0, 0, 0);
return this._displayRenderNode.getBoundingBox();
},
- getAnchorPoint:function () {
+ getAnchorPoint: function () {
if (!this._displayRenderNode)
- return cc.p(0, 0);
+ return cc.p(0, 0);
return this._displayRenderNode.getAnchorPoint();
},
- getAnchorPointInPoints:function () {
+ getAnchorPointInPoints: function () {
if (!this._displayRenderNode)
- return cc.p(0, 0);
+ return cc.p(0, 0);
return this._displayRenderNode.getAnchorPointInPoints();
},
- getForceChangeDisplay:function () {
+ getForceChangeDisplay: function () {
return this._forceChangeDisplay;
},
- release:function () {
+ release: function () {
this._decoDisplayList = null;
if (this._displayRenderNode) {
this._displayRenderNode.removeFromParent(true);
@@ -462,4 +462,4 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
*/
ccs.DisplayManager.create = function (bone) {
return new ccs.DisplayManager(bone);
-};
\ No newline at end of file
+};
diff --git a/extensions/cocostudio/armature/display/CCSkinRenderCmd.js b/extensions/cocostudio/armature/display/CCSkinRenderCmd.js
index a57b625494..eabcd02f00 100644
--- a/extensions/cocostudio/armature/display/CCSkinRenderCmd.js
+++ b/extensions/cocostudio/armature/display/CCSkinRenderCmd.js
@@ -23,10 +23,15 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
+(function () {
ccs.Skin.RenderCmd = {
_realWorldTM: null,
transform: function (parentCmd, recursive) {
+ if (!this._transform) {
+ this._transform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0};
+ this._worldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0};
+ }
+
var node = this._node,
pt = parentCmd ? parentCmd._worldTransform : null,
t = this._transform,
@@ -35,15 +40,15 @@
if (dirty || pt) {
this.originTransform();
- cc.affineTransformConcatIn(t, node.bone.getNodeToArmatureTransform());
- this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.transformDirty ^ this._dirtyFlag;
+ cc.affineTransformConcatIn(this._transform, node.bone.getNodeToArmatureTransform());
+ this._dirtyFlag &= ~cc.Node._dirtyFlags.transformDirty;
}
if (pt) {
- wt.a = t.a * pt.a + t.b * pt.c;
- wt.b = t.a * pt.b + t.b * pt.d;
- wt.c = t.c * pt.a + t.d * pt.c;
- wt.d = t.c * pt.b + t.d * pt.d;
+ wt.a = t.a * pt.a + t.b * pt.c;
+ wt.b = t.a * pt.b + t.b * pt.d;
+ wt.c = t.c * pt.a + t.d * pt.c;
+ wt.d = t.c * pt.b + t.d * pt.d;
wt.tx = t.tx * pt.a + t.ty * pt.c + pt.tx;
wt.ty = t.tx * pt.b + t.ty * pt.d + pt.ty;
@@ -63,16 +68,16 @@
}
}
else {
- wt.a = t.a;
- wt.b = t.b;
- wt.c = t.c;
- wt.d = t.d;
+ wt.a = t.a;
+ wt.b = t.b;
+ wt.c = t.c;
+ wt.d = t.d;
wt.tx = t.tx;
wt.ty = t.ty;
}
var rwtm = this._realWorldTM;
- if(rwtm) {
- rwtm.a = t.a; rwtm.b = t.b; rwtm.c = t.c; rwtm.d = t.d; rwtm.tx= t.tx; rwtm.ty = t.ty;
+ if (rwtm) {
+ rwtm.a = t.a; rwtm.b = t.b; rwtm.c = t.c; rwtm.d = t.d; rwtm.tx = t.tx; rwtm.ty = t.ty;
cc.affineTransformConcatIn(rwtm, this._node.bone.getArmature()._renderCmd._worldTransform);
}
},
@@ -90,8 +95,8 @@
}
};
- ccs.Skin.CanvasRenderCmd = function(renderable){
- cc.Sprite.CanvasRenderCmd.call(this, renderable);
+ ccs.Skin.CanvasRenderCmd = function (renderable) {
+ this._spriteCmdCtor(renderable);
this._realWorldTM = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0};
};
@@ -111,8 +116,8 @@
this._currentRegion.updateRegion(this.getLocalBB(), this._realWorldTM);
};
- ccs.Skin.WebGLRenderCmd = function(renderable){
- cc.Sprite.WebGLRenderCmd.call(this, renderable);
+ ccs.Skin.WebGLRenderCmd = function (renderable) {
+ this._spriteCmdCtor(renderable);
};
proto = ccs.Skin.WebGLRenderCmd.prototype = Object.create(cc.Sprite.WebGLRenderCmd.prototype);
diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js
index 46ac7eab01..bf75cce354 100644
--- a/extensions/cocostudio/loader/load.js
+++ b/extensions/cocostudio/loader/load.js
@@ -22,7 +22,7 @@
THE SOFTWARE.
****************************************************************************/
-ccs._load = (function(){
+ccs._load = (function () {
/**
* load file
@@ -31,43 +31,43 @@ ccs._load = (function(){
* @param {String} [path=] - Resource search path
* @returns {*}
*/
- var load = function(file, type, path){
+ var load = function (file, type, path) {
var json = cc.loader.getRes(file);
- if(!json)
+ if (!json)
return cc.log("%s does not exist", file);
var ext = extname(file).toLocaleLowerCase();
- if(ext !== "json" && ext !== "exportjson")
+ if (ext !== "json" && ext !== "exportjson")
return cc.log("%s load error, must be json file", file);
var parse;
- if(!type){
- if(json["widgetTree"])
+ if (!type) {
+ if (json["widgetTree"])
parse = parser["ccui"];
- else if(json["nodeTree"])
+ else if (json["nodeTree"])
parse = parser["timeline"];
- else if(json["Content"] && json["Content"]["Content"])
+ else if (json["Content"] && json["Content"]["Content"])
parse = parser["timeline"];
- else if(json["gameobjects"])
+ else if (json["gameobjects"])
parse = parser["scene"];
- }else{
+ } else {
parse = parser[type];
}
- if(!parse){
+ if (!parse) {
cc.log("Can't find the parser : %s", file);
return new cc.Node();
}
var version = json["version"] || json["Version"];
- if(!version && json["armature_data"]){
+ if (!version && json["armature_data"]) {
cc.warn("%s is armature. please use:", file);
cc.warn(" ccs.armatureDataManager.addArmatureFileInfoAsync(%s);", file);
cc.warn(" var armature = new ccs.Armature('name');");
return new cc.Node();
}
var currentParser = getParser(parse, version);
- if(!currentParser){
+ if (!currentParser) {
cc.log("Can't find the parser : %s", file);
return new cc.Node();
}
@@ -82,24 +82,24 @@ ccs._load = (function(){
"scene": {}
};
- load.registerParser = function(name, version, target){
- if(!name || !version || !target)
+ load.registerParser = function (name, version, target) {
+ if (!name || !version || !target)
return cc.log("register parser error");
- if(!parser[name])
+ if (!parser[name])
parser[name] = {};
parser[name][version] = target;
};
- load.getParser = function(name, version){
- if(name && version)
+ load.getParser = function (name, version) {
+ if (name && version)
return parser[name] ? parser[name][version] : undefined;
- if(name)
+ if (name)
return parser[name];
return parser;
};
//Gets the file extension
- var extname = function(fileName){
+ var extname = function (fileName) {
var arr = fileName.match(extnameReg);
return ( arr && arr[1] ) ? arr[1] : null;
};
@@ -107,10 +107,10 @@ ccs._load = (function(){
var parserReg = /([^\.](\.\*)?)*$/;
- var getParser = function(parser, version){
- if(parser[version])
+ var getParser = function (parser, version) {
+ if (parser[version])
return parser[version];
- else if(version === "*")
+ else if (version === "*")
return null;
else
return getParser(parser, version.replace(parserReg, "*"));
@@ -122,25 +122,25 @@ ccs._load = (function(){
ccs._parser = cc.Class.extend({
- ctor: function(){
+ ctor: function () {
this.parsers = {};
},
_dirnameReg: /\S*\//,
- _dirname: function(path){
+ _dirname: function (path) {
var arr = path.match(this._dirnameReg);
return (arr && arr[0]) ? arr[0] : "";
},
- getClass: function(json){
+ getClass: function (json) {
return json["classname"];
},
- getNodeJson: function(json){
+ getNodeJson: function (json) {
return json["widgetTree"];
},
- parse: function(file, json, resourcePath){
+ parse: function (file, json, resourcePath) {
resourcePath = resourcePath || this._dirname(file);
this.pretreatment(json, resourcePath);
var node = this.parseNode(this.getNodeJson(json), resourcePath, file);
@@ -148,14 +148,16 @@ ccs._parser = cc.Class.extend({
return node;
},
- pretreatment: function(json, resourcePath, file){},
+ pretreatment: function (json, resourcePath, file) {
+ },
- deferred: function(json, resourcePath, node, file){},
+ deferred: function (json, resourcePath, node, file) {
+ },
- parseNode: function(json, resourcePath){
+ parseNode: function (json, resourcePath) {
var parser = this.parsers[this.getClass(json)];
var widget = null;
- if(parser)
+ if (parser)
widget = parser.call(this, json, resourcePath);
else
cc.log("Can't find the parser : %s", this.getClass(json));
@@ -163,7 +165,7 @@ ccs._parser = cc.Class.extend({
return widget;
},
- registerParser: function(widget, parse){
+ registerParser: function (widget, parse) {
this.parsers[widget] = parse;
}
});
@@ -180,7 +182,7 @@ ccs._parser = cc.Class.extend({
* @param {String} [path=] Resource path
* @returns {{node: cc.Node, action: cc.Action}}
*/
-ccs.load = function(file, path){
+ccs.load = function (file, path) {
var object = {
node: null,
action: null
@@ -188,7 +190,7 @@ ccs.load = function(file, path){
object.node = ccs._load(file, null, path);
object.action = ccs._load(file, "action", path);
- if(object.action && object.action.tag === -1 && object.node)
+ if (object.action && object.action.tag === -1 && object.node)
object.action.tag = object.node.tag;
return object;
};
@@ -208,10 +210,10 @@ ccs.load.preload = true;
* @param {String} [path=] Resource path
* @returns {{node: cc.Node, action: cc.Action}}
*/
-ccs.loadWithVisibleSize = function(file, path){
+ccs.loadWithVisibleSize = function (file, path) {
var object = ccs.load(file, path);
var size = cc.director.getVisibleSize();
- if(object.node && size){
+ if (object.node && size) {
object.node.setContentSize(size.width, size.height);
ccui.helper.doLayout(object.node);
}
@@ -229,7 +231,7 @@ ccs.actionTimelineCache = {
* @param file
* @returns {*}
*/
- createAction: function(file){
+ createAction: function (file) {
return ccs._load(file, "action");
}
};
@@ -242,37 +244,37 @@ ccs.csLoader = {
* @param file
* @returns {*}
*/
- createNode: function(file){
+ createNode: function (file) {
return ccs._load(file);
}
};
cc.loader.register(["json"], {
- load : function(realUrl, url, res, cb){
- cc.loader.loadJson(realUrl, function(error, data){
+ load: function (realUrl, url, res, cb) {
+ cc.loader.loadJson(realUrl, function (error, data) {
var path = cc.path;
- if(data && data["Content"] && data["Content"]["Content"]["UsedResources"]){
+ if (data && data["Content"] && data["Content"]["Content"]["UsedResources"]) {
var UsedResources = data["Content"]["Content"]["UsedResources"],
dirname = path.dirname(url),
list = [],
tmpUrl, normalUrl;
- for(var i=0; i= 1700){
+ if (!version || versionNum >= 1700) {
cc.warn("Not supported file types, Please try use the ccs.load");
return null;
}
@@ -63,16 +63,16 @@
* @param callback
* @deprecated This function will be deprecated sooner or later please use parser.registerParser
*/
- registerTypeAndCallBack: function(classType, ins, object, callback){
+ registerTypeAndCallBack: function (classType, ins, object, callback) {
var parser = ccs._load.getParser("ccui")["*"];
var func = callback.bind(object);
- parser.registerParser(classType, function(options, resourcePath){
+ parser.registerParser(classType, function (options, resourcePath) {
var widget = new ins();
var uiOptions = options["options"];
object.setPropsFromJsonDictionary && object.setPropsFromJsonDictionary(widget, uiOptions);
this.generalAttributes(widget, uiOptions);
var customProperty = uiOptions["customProperty"];
- if(customProperty)
+ if (customProperty)
customProperty = JSON.parse(customProperty);
else
customProperty = {};
@@ -90,13 +90,13 @@
* @param {String} version version string.
* @returns {Number}
*/
- getVersionInteger: function(version){
- if(!version || typeof version !== "string") return 0;
+ getVersionInteger: function (version) {
+ if (!version || typeof version !== "string") return 0;
var arr = version.split(".");
if (arr.length !== 4)
return 0;
var num = 0;
- arr.forEach(function(n, i){
+ arr.forEach(function (n, i) {
num += n * Math.pow(10, 3 - i);
});
return num;
@@ -127,12 +127,12 @@
* Returns the file path
* @returns {string}
*/
- getFilePath: function(){
+ getFilePath: function () {
return this._filePath;
},
//@deprecated This function will be deprecated sooner or later
- setFilePath: function(path){
+ setFilePath: function (path) {
this._filePath = path;
},
@@ -141,7 +141,7 @@
* Returns the parsed object map. (analytic function)
* @returns {Object}
*/
- getParseObjectMap: function(){
+ getParseObjectMap: function () {
return ccs._load.getParser("ccui")["*"]["parsers"];
},
@@ -150,31 +150,32 @@
* Returns the parsed callback map. (analytic function)
* @returns {*}
*/
- getParseCallBackMap: function(){
+ getParseCallBackMap: function () {
return ccs._load.getParser("ccui")["*"]["parsers"];
},
//@deprecated This function will be deprecated sooner or later
- clear: function(){}
+ clear: function () {
+ }
};
var parser = ccs._load.getParser("ccui")["*"];
- ccs.imageViewReader = {setPropsFromJsonDictionary: parser.ImageViewAttributes};
- ccs.buttonReader = {setPropsFromJsonDictionary: parser.ButtonAttributes};
- ccs.checkBoxReader = {setPropsFromJsonDictionary: parser.CheckBoxAttributes};
+ ccs.imageViewReader = {setPropsFromJsonDictionary: parser.ImageViewAttributes};
+ ccs.buttonReader = {setPropsFromJsonDictionary: parser.ButtonAttributes};
+ ccs.checkBoxReader = {setPropsFromJsonDictionary: parser.CheckBoxAttributes};
ccs.labelAtlasReader = {setPropsFromJsonDictionary: parser.TextAtlasAttributes};
- ccs.labelBMFontReader= {setPropsFromJsonDictionary: parser.TextBMFontAttributes};
- ccs.labelReader = {setPropsFromJsonDictionary: parser.TextAttributes};
- ccs.layoutReader = {setPropsFromJsonDictionary: parser.LayoutAttributes};
- ccs.listViewReader = {setPropsFromJsonDictionary: parser.ListViewAttributes};
+ ccs.labelBMFontReader = {setPropsFromJsonDictionary: parser.TextBMFontAttributes};
+ ccs.labelReader = {setPropsFromJsonDictionary: parser.TextAttributes};
+ ccs.layoutReader = {setPropsFromJsonDictionary: parser.LayoutAttributes};
+ ccs.listViewReader = {setPropsFromJsonDictionary: parser.ListViewAttributes};
ccs.loadingBarReader = {setPropsFromJsonDictionary: parser.LoadingBarAttributes};
- ccs.pageViewReader = {setPropsFromJsonDictionary: parser.PageViewAttributes};
+ ccs.pageViewReader = {setPropsFromJsonDictionary: parser.PageViewAttributes};
ccs.scrollViewReader = {setPropsFromJsonDictionary: parser.ScrollViewAttributes};
- ccs.sliderReader = {setPropsFromJsonDictionary: parser.SliderAttributes};
- ccs.textFieldReader = {setPropsFromJsonDictionary: parser.TextFieldAttributes};
+ ccs.sliderReader = {setPropsFromJsonDictionary: parser.SliderAttributes};
+ ccs.textFieldReader = {setPropsFromJsonDictionary: parser.TextFieldAttributes};
})();
-(function(){
+(function () {
ccs.sceneReader = {
_node: null,
@@ -185,7 +186,7 @@
* @param file
* @returns {*}
*/
- createNodeWithSceneFile: function(file){
+ createNodeWithSceneFile: function (file) {
var node = ccs._load(file, "scene");
this._node = node;
return node;
@@ -196,7 +197,7 @@
* @param {Number} tag
* @returns {cc.Node|null}
*/
- getNodeByTag: function(tag){
+ getNodeByTag: function (tag) {
if (this._node == null)
return null;
if (this._node.getTag() === tag)
@@ -228,7 +229,7 @@
* Returns the version of ccs.SceneReader.
* @returns {string}
*/
- version: function(){
+ version: function () {
return "*";
},
@@ -237,15 +238,16 @@
* Sets the listener to reader.
* Cannot use
*/
- setTarget: function(){},
+ setTarget: function () {
+ },
//@deprecated This function will be deprecated sooner or later
/**
* Clear all triggers and stops all sounds.
*/
- clear: function(){
+ clear: function () {
ccs.triggerManager.removeAll();
cc.audioEngine.end();
}
};
-})();
\ No newline at end of file
+})();
diff --git a/extensions/cocostudio/loader/parsers/scene-1.x.js b/extensions/cocostudio/loader/parsers/scene-1.x.js
index 04569cb17f..8982f26bfc 100644
--- a/extensions/cocostudio/loader/parsers/scene-1.x.js
+++ b/extensions/cocostudio/loader/parsers/scene-1.x.js
@@ -22,18 +22,18 @@
THE SOFTWARE.
****************************************************************************/
-(function(load, baseParser){
+(function (load, baseParser) {
var Parser = baseParser.extend({
- getNodeJson: function(json){
+ getNodeJson: function (json) {
return json;
},
- parseNode: function(json, resourcePath){
+ parseNode: function (json, resourcePath) {
var parser = this.parsers[this.getClass(json)];
var node = null;
- if(parser)
+ if (parser)
node = parser.call(this, json, resourcePath);
else
cc.log("Can't find the parser : %s", this.getClass(json));
@@ -41,32 +41,32 @@
return node;
},
- deferred: function(json, resourcePath, node, file){
- ccs.triggerManager.parse(json["Triggers"]||[]);
- if(ccs.sceneReader)
+ deferred: function (json, resourcePath, node, file) {
+ ccs.triggerManager.parse(json["Triggers"] || []);
+ if (ccs.sceneReader)
ccs.sceneReader._node = node;
},
- setPropertyFromJsonDict: function(node, json){
- var x = (cc.isUndefined(json["x"]))?0:json["x"];
- var y = (cc.isUndefined(json["y"]))?0:json["y"];
+ setPropertyFromJsonDict: function (node, json) {
+ var x = (cc.isUndefined(json["x"])) ? 0 : json["x"];
+ var y = (cc.isUndefined(json["y"])) ? 0 : json["y"];
node.setPosition(x, y);
- var bVisible = Boolean((cc.isUndefined(json["visible"]))?1:json["visible"]);
+ var bVisible = Boolean((cc.isUndefined(json["visible"])) ? 1 : json["visible"]);
node.setVisible(bVisible);
- var nTag = (cc.isUndefined(json["objecttag"]))?-1:json["objecttag"];
+ var nTag = (cc.isUndefined(json["objecttag"])) ? -1 : json["objecttag"];
node.setTag(nTag);
- var nZorder = (cc.isUndefined(json["zorder"]))?0:json["zorder"];
+ var nZorder = (cc.isUndefined(json["zorder"])) ? 0 : json["zorder"];
node.setLocalZOrder(nZorder);
- var fScaleX = (cc.isUndefined(json["scalex"]))?1:json["scalex"];
- var fScaleY = (cc.isUndefined(json["scaley"]))?1:json["scaley"];
+ var fScaleX = (cc.isUndefined(json["scalex"])) ? 1 : json["scalex"];
+ var fScaleY = (cc.isUndefined(json["scaley"])) ? 1 : json["scaley"];
node.setScaleX(fScaleX);
node.setScaleY(fScaleY);
- var fRotationZ = (cc.isUndefined(json["rotation"]))?0:json["rotation"];
+ var fRotationZ = (cc.isUndefined(json["rotation"])) ? 0 : json["rotation"];
node.setRotation(fRotationZ);
var sName = json["name"] || "";
@@ -77,24 +77,24 @@
var parser = new Parser();
- parser.parseChild = function(node, objects, resourcePath){
+ parser.parseChild = function (node, objects, resourcePath) {
for (var i = 0; i < objects.length; i++) {
var child,
options = objects[i];
- if(options)
+ if (options)
child = this.parseNode(options, resourcePath);
- if(child)
+ if (child)
node.addChild(child);
}
};
var componentsParser = {
- "CCSprite": function(node, component, resourcePath){
+ "CCSprite": function (node, component, resourcePath) {
var child = new cc.Sprite();
- loadTexture(component["fileData"], resourcePath, function(path, type){
- if(type === 0)
+ loadTexture(component["fileData"], resourcePath, function (path, type) {
+ if (type === 0)
child.setTexture(path);
- else if(type === 1){
+ else if (type === 1) {
var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path);
child.setSpriteFrame(spriteFrame);
}
@@ -103,20 +103,20 @@
node.addComponent(render);
return render;
},
- "CCTMXTiledMap": function(node, component, resourcePath){
+ "CCTMXTiledMap": function (node, component, resourcePath) {
var child = null;
- loadTexture(component["fileData"], resourcePath, function(path, type){
- if(type === 0)
+ loadTexture(component["fileData"], resourcePath, function (path, type) {
+ if (type === 0)
child = new cc.TMXTiledMap(path);
});
var render = new ccs.ComRender(child, "CCTMXTiledMap");
node.addComponent(render);
return render;
},
- "CCParticleSystemQuad": function(node, component, resourcePath){
+ "CCParticleSystemQuad": function (node, component, resourcePath) {
var child = null;
- loadTexture(component["fileData"], resourcePath, function(path, type){
- if(type === 0)
+ loadTexture(component["fileData"], resourcePath, function (path, type) {
+ if (type === 0)
child = new cc.ParticleSystem(path);
else
cc.log("unknown resourcetype on CCParticleSystemQuad!");
@@ -126,10 +126,10 @@
node.addComponent(render);
return render;
},
- "CCArmature": function(node, component, resourcePath){
+ "CCArmature": function (node, component, resourcePath) {
var child = null;
- loadTexture(component["fileData"], resourcePath, function(path, type){
- if(type === 0){
+ loadTexture(component["fileData"], resourcePath, function (path, type) {
+ if (type === 0) {
var jsonDict = cc.loader.getRes(path);
if (!jsonDict) cc.log("Please load the resource [%s] first!", path);
var armature_data = jsonDict["armature_data"];
@@ -139,7 +139,7 @@
child = new ccs.Armature(name);
}
});
- if(child){
+ if (child) {
var render = new ccs.ComRender(child, "CCArmature");
node.addComponent(render);
var actionName = component["selectedactionname"];
@@ -150,101 +150,103 @@
}
},
- "CCComAudio": function(node, component, resourcePath){
+ "CCComAudio": function (node, component, resourcePath) {
var audio = null;
- loadTexture(component["fileData"], resourcePath, function(path, type){
- if(type === 0){
+ loadTexture(component["fileData"], resourcePath, function (path, type) {
+ if (type === 0) {
audio = new ccs.ComAudio();
audio.preloadEffect(path);
var name = component["name"];
- if(name)
+ if (name)
audio.setName(name);
node.addComponent(audio);
}
});
},
- "CCComAttribute": function(node, component, resourcePath){
+ "CCComAttribute": function (node, component, resourcePath) {
var attribute = null;
- loadTexture(component["fileData"], resourcePath, function(path, type){
- if(type === 0){
+ loadTexture(component["fileData"], resourcePath, function (path, type) {
+ if (type === 0) {
attribute = new ccs.ComAttribute();
if (path !== "")
attribute.parse(path);
node.addComponent(attribute);
- }else
+ } else
cc.log("unknown resourcetype on CCComAttribute!");
});
return attribute;
},
- "CCBackgroundAudio": function(node, component, resourcePath){
+ "CCBackgroundAudio": function (node, component, resourcePath) {
var audio = null;
- loadTexture(component["fileData"], resourcePath, function(path, type){
- if(type === 0){
+ loadTexture(component["fileData"], resourcePath, function (path, type) {
+ if (type === 0) {
audio = new ccs.ComAudio();
audio.preloadBackgroundMusic(path);
- audio.setFile(path);var bLoop = Boolean(component["loop"] || 0);
+ audio.setFile(path);
+ var bLoop = Boolean(component["loop"] || 0);
audio.setLoop(bLoop);
var name = component["name"];
- if(name)
+ if (name)
audio.setName(name);
node.addComponent(audio);
audio.playBackgroundMusic(path, bLoop);
}
});
},
- "GUIComponent": function(node, component, resourcePath){
+ "GUIComponent": function (node, component, resourcePath) {
var widget = null;
- loadTexture(component["fileData"], resourcePath, function(path, type){
+ loadTexture(component["fileData"], resourcePath, function (path, type) {
widget = ccs._load(path, "ccui");
});
var render = new ccs.ComRender(widget, "GUIComponent");
node.addComponent(render);
return render;
},
- "CCScene": function(){}
+ "CCScene": function () {
+ }
};
var loadedPlist = {};
- var loadTexture = function(json, resourcePath, cb){
- if(json != null){
+ var loadTexture = function (json, resourcePath, cb) {
+ if (json != null) {
var path = json["path"];
var type = json["resourceType"];
var plist = json["plist"];
- if(!path)
+ if (!path)
return;
- if(plist){
- if(cc.loader.getRes(resourcePath + plist)){
+ if (plist) {
+ if (cc.loader.getRes(resourcePath + plist)) {
loadedPlist[resourcePath + plist] = true;
cc.spriteFrameCache.addSpriteFrames(resourcePath + plist);
- }else{
- if(!loadedPlist[resourcePath + plist])
+ } else {
+ if (!loadedPlist[resourcePath + plist])
cc.log("%s need to be preloaded", resourcePath + plist);
}
}
- if(type !== 0)
+ if (type !== 0)
cb(path, type);
else
cb(resourcePath + path, type);
}
};
- parser.parseComponents = function(node, json, resourcePath){
- if(!node || !json)
+ parser.parseComponents = function (node, json, resourcePath) {
+ if (!node || !json)
return;
- json.forEach(function(component){
+ json.forEach(function (component) {
var parser = componentsParser[component["classname"]];
var render = null;
- if(parser)
+ if (parser)
render = parser(node, component, resourcePath);
else
cc.log("Can't find the component parser : %s", component["classname"]);
var name = component["name"];
- if(render && name){
+ if (render && name) {
render.setName(name);
}
});
};
- parser.registerParser("CCNode", function(options, resourcePath){
+ parser.registerParser("CCNode", function (options, resourcePath) {
var node = new cc.Node();
this.setPropertyFromJsonDict(node, options);
this.parseChild.call(this, node, options["gameobjects"], resourcePath);
diff --git a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js
index 61a04a2fbf..1e9d907805 100644
--- a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js
+++ b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js
@@ -22,22 +22,22 @@
THE SOFTWARE.
****************************************************************************/
-(function(load, baseParser){
+(function (load, baseParser) {
var loadedPlist = {};
var Parser = baseParser.extend({
- getNodeJson: function(json){
+ getNodeJson: function (json) {
return json["nodeTree"];
},
- addSpriteFrame: function(plists, pngs, resourcePath){
- if(!plists || !pngs || plists.length !== pngs.length)
+ addSpriteFrame: function (plists, pngs, resourcePath) {
+ if (!plists || !pngs || plists.length !== pngs.length)
return;
for (var i = 0; i < plists.length; i++) {
var plist = resourcePath + plists[i];
- if(!cc.loader.getRes(plist) && !loadedPlist[plist])
+ if (!cc.loader.getRes(plist) && !loadedPlist[plist])
cc.log("%s need to be preloaded", plist);
else
loadedPlist[plist] = true;
@@ -48,67 +48,65 @@
}
},
- pretreatment: function(json, resourcePath, file){
+ pretreatment: function (json, resourcePath, file) {
this.addSpriteFrame(json["textures"], json["texturesPng"], resourcePath);
}
});
var parser = new Parser();
- parser.generalAttributes = function(node, options){
- var width = options["width"] !=null ? options["width"] : 0;
- var height = options["height"] !=null ? options["height"] : 0;
- var x = options["x"] !=null ? options["x"] : 0;
- var y = options["y"] !=null ? options["y"] : 0;
- var scalex = options["scaleX"] !=null ? options["scaleX"] : 1;
- var scaley = options["scaleY"] !=null ? options["scaleY"] : 1;
- var rotation = options["rotation"] !=null ? options["rotation"] : 0;
- var rotationSkewX = options["rotationSkewX"]!=null ? options["rotationSkewX"] : 0;
- var rotationSkewY = options["rotationSkewY"]!=null ? options["rotationSkewY"] : 0;
- var skewx = options["skewX"] !=null ? options["skewX"] : 0;
- var skewy = options["skewY"] !=null ? options["skewY"] : 0;
- var anchorx = options["anchorPointX"] !=null ? options["anchorPointX"] : 0.5;
- var anchory = options["anchorPointY"] !=null ? options["anchorPointY"] : 0.5;
- var alpha = options["opacity"] !=null ? options["opacity"] : 255;
- var red = options["colorR"] !=null ? options["colorR"] : 255;
- var green = options["colorG"] !=null ? options["colorG"] : 255;
- var blue = options["colorB"] !=null ? options["colorB"] : 255;
- var zorder = options["colorR"] !=null ? options["colorR"] : 0;
- var tag = options["tag"] !=null ? options["tag"] : 0;
- var actionTag = options["actionTag"] !=null ? options["actionTag"] : 0;
- var visible = options["visible"] !=null ? options["visible"] : true;
+ parser.generalAttributes = function (node, options) {
+ var width = options["width"] != null ? options["width"] : 0;
+ var height = options["height"] != null ? options["height"] : 0;
+ var x = options["x"] != null ? options["x"] : 0;
+ var y = options["y"] != null ? options["y"] : 0;
+ var scalex = options["scaleX"] != null ? options["scaleX"] : 1;
+ var scaley = options["scaleY"] != null ? options["scaleY"] : 1;
+ var rotation = options["rotation"] != null ? options["rotation"] : 0;
+ var rotationSkewX = options["rotationSkewX"] != null ? options["rotationSkewX"] : 0;
+ var rotationSkewY = options["rotationSkewY"] != null ? options["rotationSkewY"] : 0;
+ var skewx = options["skewX"] != null ? options["skewX"] : 0;
+ var skewy = options["skewY"] != null ? options["skewY"] : 0;
+ var anchorx = options["anchorPointX"] != null ? options["anchorPointX"] : 0.5;
+ var anchory = options["anchorPointY"] != null ? options["anchorPointY"] : 0.5;
+ var alpha = options["opacity"] != null ? options["opacity"] : 255;
+ var red = options["colorR"] != null ? options["colorR"] : 255;
+ var green = options["colorG"] != null ? options["colorG"] : 255;
+ var blue = options["colorB"] != null ? options["colorB"] : 255;
+ var zorder = options["colorR"] != null ? options["colorR"] : 0;
+ var tag = options["tag"] != null ? options["tag"] : 0;
+ var actionTag = options["actionTag"] != null ? options["actionTag"] : 0;
+ var visible = options["visible"] != null ? options["visible"] : true;
- if(x != 0 || y != 0)
+ if (x != 0 || y != 0)
node.setPosition(cc.p(x, y));
- if(scalex != 1)
+ if (scalex != 1)
node.setScaleX(scalex);
- if(scaley != 1)
+ if (scaley != 1)
node.setScaleY(scaley);
if (rotation != 0)
node.setRotation(rotation);
- if(rotationSkewX != 0)
+ if (rotationSkewX != 0)
node.setRotationX(rotationSkewX);
- if(rotationSkewY != 0)
+ if (rotationSkewY != 0)
node.setRotationY(rotationSkewY);
- if(skewx != 0)
+ if (skewx != 0)
node.setSkewX(skewx);
- if(skewy != 0)
+ if (skewy != 0)
node.setSkewY(skewy);
- if(anchorx != 0.5 || anchory != 0.5)
+ if (anchorx != 0.5 || anchory != 0.5)
node.setAnchorPoint(cc.p(anchorx, anchory));
- if(width != 0 || height != 0)
+ if (width != 0 || height != 0)
node.setContentSize(cc.size(width, height));
- if(zorder != 0)
+ if (zorder != 0)
node.setLocalZOrder(zorder);
- if(visible != true)
+ if (visible != true)
node.setVisible(visible);
- if(alpha != 255)
- {
+ if (alpha != 255) {
node.setOpacity(alpha);
}
- if(red != 255 || green != 255 || blue != 255)
- {
+ if (red != 255 || green != 255 || blue != 255) {
node.setColor(cc.color(red, green, blue));
}
@@ -117,32 +115,32 @@
node.setUserObject(new ccs.ActionTimelineData(actionTag));
};
- parser.parseComponent = function(node, options){
- if(!options) return;
- for (var i = 0; i < options.length; ++i){
+ parser.parseComponent = function (node, options) {
+ if (!options) return;
+ for (var i = 0; i < options.length; ++i) {
var dic = options[i];
var component = this.loadComponent(dic);
- if (component){
+ if (component) {
node.addComponent(component);
}
}
};
- parser.parseChild = function(parse, widget, options, resourcePath){
+ parser.parseChild = function (parse, widget, options, resourcePath) {
var children = options["children"];
for (var i = 0; i < children.length; i++) {
var child = this.parseNode(children[i], resourcePath);
- if(child){
- if(widget instanceof ccui.PageView){
- if(child instanceof ccui.Layout)
+ if (child) {
+ if (widget instanceof ccui.PageView) {
+ if (child instanceof ccui.Layout)
widget.addPage(child);
} else {
- if(widget instanceof ccui.ListView){
- if(child instanceof ccui.Widget)
+ if (widget instanceof ccui.ListView) {
+ if (child instanceof ccui.Widget)
widget.pushBackCustomItem(child);
} else {
- if(!(widget instanceof ccui.Layout) && child instanceof ccui.Widget) {
- if(child.getPositionType() === ccui.Widget.POSITION_PERCENT) {
+ if (!(widget instanceof ccui.Layout) && child instanceof ccui.Widget) {
+ if (child.getPositionType() === ccui.Widget.POSITION_PERCENT) {
var position = child.getPositionPercent();
var anchor = widget.getAnchorPoint();
child.setPositionPercent(cc.p(position.x + anchor.x, position.y + anchor.y));
@@ -158,53 +156,53 @@
}
};
- parser.initNode = function(options){
+ parser.initNode = function (options) {
var node = new cc.Node();
this.generalAttributes(node, options);
return node;
};
- parser.initSubGraph = function(options){
+ parser.initSubGraph = function (options) {
var filePath = options["fileName"];
var node;
- if (filePath && "" !== filePath){
+ if (filePath && "" !== filePath) {
node = this.createNode(filePath);
- }else{
+ } else {
node = new ccs.Node();
}
this.generalAttributes(node, options);
return node;
};
- parser.initSprite = function(options, resourcePath){
+ parser.initSprite = function (options, resourcePath) {
var path = options["fileName"];
var sprite;
- if(path != null){
+ if (path != null) {
var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path);
- if(!spriteFrame){
+ if (!spriteFrame) {
path = resourcePath + path;
sprite = new ccs.Sprite(path);
- }else{
+ } else {
sprite = ccs.Sprite.createWithSpriteFrame(spriteFrame);
}
- if(!sprite){
+ if (!sprite) {
sprite = new cc.Sprite();
cc.log("filePath is empty. Create a sprite with no texture");
}
- }else{
+ } else {
sprite = new ccs.Sprite();
}
this.generalAttributes(sprite, options);
var flipX = options["flipX"];
var flipY = options["flipY"];
- if(flipX != false)
+ if (flipX != false)
sprite.setFlippedX(flipX);
- if(flipY != false)
+ if (flipY != false)
sprite.setFlippedY(flipY);
return sprite;
};
- parser.initParticle = function(options, resourcePath){
+ parser.initParticle = function (options, resourcePath) {
var filePath = options["plistFile"];
var num = options["tmxFile"];
var particle = new cc.ParticleSystemQuad(filePath);
@@ -212,41 +210,41 @@
this.generalAttributes(particle, options);
return particle;
};
- parser.initTMXTiledMap = function(options, resourcePath){
+ parser.initTMXTiledMap = function (options, resourcePath) {
var tmxFile = options["tmxFile"];
var tmxString = options["tmxString"];
//todo check path and resourcePath
var path = options["resourcePath"];
var tmx = null;
- if (tmxFile && "" !== tmxFile){
+ if (tmxFile && "" !== tmxFile) {
tmx = new cc.TMXTiledMap(tmxFile);
- }else if (tmxString && "" !== tmxString && path && "" !== path){
+ } else if (tmxString && "" !== tmxString && path && "" !== path) {
tmx = new cc.TMXTiledMap(tmxString, path);
}
return tmx;
};
var uiParser = load.getParser("ccui")["*"];
- parser.initWidget = function(options, resourcePath){
+ parser.initWidget = function (options, resourcePath) {
var type = options["classname"];
var parser = uiParser.parsers[type];
- if(!parser)
+ if (!parser)
return cc.log("%s parser is not found", type);
var node = parser.call(uiParser, options, resourcePath);
- if(node){
+ if (node) {
var rotationSkewX = options["rotationSkewX"];
var rotationSkewY = options["rotationSkewY"];
- var skewx = options["skewX"];
- var skewy = options["skewY"];
- if(rotationSkewX != 0)
+ var skewx = options["skewX"];
+ var skewy = options["skewY"];
+ if (rotationSkewX != 0)
node.setRotationX(rotationSkewX);
- if(rotationSkewY != 0)
+ if (rotationSkewY != 0)
node.setRotationY(rotationSkewY);
- if(skewx != 0)
+ if (skewx != 0)
node.setSkewX(skewx);
- if(skewy != 0)
+ if (skewy != 0)
node.setSkewY(skewy);
var actionTag = options["actionTag"];
@@ -278,8 +276,8 @@
{name: "TextField", handle: parser.initWidget}
];
- register.forEach(function(item){
- parser.registerParser(item.name, function(options, parse, resourcePath){
+ register.forEach(function (item) {
+ parser.registerParser(item.name, function (options, parse, resourcePath) {
var node = item.handle.call(this, options["options"]);
this.parseComponent(node, options["components"]);
this.parseChild(parse, node, options, resourcePath);
diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js
index f8da6b0210..e79ab9b791 100644
--- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js
+++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js
@@ -22,15 +22,15 @@
THE SOFTWARE.
****************************************************************************/
-(function(load, baseParser){
+(function (load, baseParser) {
var DEBUG = false;
var Parser = baseParser.extend({
- parse: function(file, json, path){
+ parse: function (file, json, path) {
var resourcePath;
- if(path !== undefined)
+ if (path !== undefined)
resourcePath = path;
else
resourcePath = this._dirname(file);
@@ -40,15 +40,15 @@
return node;
},
- getNodeJson: function(json){
+ getNodeJson: function (json) {
var content = json["Content"];
- if(content["ObjectData"])
+ if (content["ObjectData"])
return content["ObjectData"];
return content["Content"]["ObjectData"];
},
- getClass: function(json){
+ getClass: function (json) {
return json["ctype"];
}
@@ -56,8 +56,8 @@
var parser = new Parser();
- var getParam = function(value, dValue){
- if(value === undefined)
+ var getParam = function (value, dValue) {
+ if (value === undefined)
return dValue;
else
return value;
@@ -67,19 +67,19 @@
// NODE //
//////////
- parser.generalAttributes = function(node, json){
- if(json["Name"] != null)
+ parser.generalAttributes = function (node, json) {
+ if (json["Name"] != null)
node.setName(json["Name"]);
var position = json["Position"];
- if(position != null && (position["X"] != null || position["Y"] != null))
- node.setPosition(cc.p(position["X"]||0, position["Y"]||0));
+ if (position != null && (position["X"] != null || position["Y"] != null))
+ node.setPosition(cc.p(position["X"] || 0, position["Y"] || 0));
var scale = json["Scale"];
- if(scale != null){
- if(scale["ScaleX"] != null)
+ if (scale != null) {
+ if (scale["ScaleX"] != null)
node.setScaleX(scale["ScaleX"]);
- if(scale["ScaleY"] != null)
+ if (scale["ScaleY"] != null)
node.setScaleY(scale["ScaleY"]);
}
@@ -93,12 +93,12 @@
var anchor = json["AnchorPoint"];
- if(anchor != null){
- if(anchor["ScaleX"] == null)
+ if (anchor != null) {
+ if (anchor["ScaleX"] == null)
anchor["ScaleX"] = 0;
- if(anchor["ScaleY"] == null)
+ if (anchor["ScaleY"] == null)
anchor["ScaleY"] = 0;
- if(anchor["ScaleX"] != 0.5 || anchor["ScaleY"] != 0.5)
+ if (anchor["ScaleX"] != 0.5 || anchor["ScaleY"] != 0.5)
node.setAnchorPoint(cc.p(anchor["ScaleX"], anchor["ScaleY"]));
}
@@ -109,7 +109,7 @@
node.setVisible(visible);
var size = json["Size"];
- if(size)
+ if (size)
setContentSize(node, size);
if (json["Alpha"] != null)
@@ -120,7 +120,7 @@
var actionTag = json["ActionTag"] || 0;
var extensionData = new ccs.ComExtensionData();
var customProperty = json["UserData"];
- if(customProperty !== undefined)
+ if (customProperty !== undefined)
extensionData.setCustomProperty(customProperty);
extensionData.setActionTag(actionTag);
if (node.getComponent("ComExtensionData"))
@@ -133,21 +133,21 @@
setLayoutComponent(node, json);
};
- parser.parseChild = function(node, children, resourcePath){
- if(!node || !children) return;
+ parser.parseChild = function (node, children, resourcePath) {
+ if (!node || !children) return;
for (var i = 0; i < children.length; i++) {
var child = this.parseNode(children[i], resourcePath);
- if(child){
- if(node instanceof ccui.PageView){
- if(child instanceof ccui.Layout)
+ if (child) {
+ if (node instanceof ccui.PageView) {
+ if (child instanceof ccui.Layout)
node.addPage(child);
} else {
- if(node instanceof ccui.ListView){
- if(child instanceof ccui.Widget)
+ if (node instanceof ccui.ListView) {
+ if (child instanceof ccui.Widget)
node.pushBackCustomItem(child);
} else {
- if(!(node instanceof ccui.Layout) && child instanceof ccui.Widget) {
- if(child.getPositionType() === ccui.Widget.POSITION_PERCENT) {
+ if (!(node instanceof ccui.Layout) && child instanceof ccui.Widget) {
+ if (child.getPositionType() === ccui.Widget.POSITION_PERCENT) {
var position = child.getPositionPercent();
var anchor = node.getAnchorPoint();
child.setPositionPercent(cc.p(position.x + anchor.x, position.y + anchor.y));
@@ -165,12 +165,12 @@
* @param json
* @returns {cc.Node}
*/
- parser.initSingleNode = function(json){
+ parser.initSingleNode = function (json) {
var node = new cc.Node();
this.generalAttributes(node, json);
var color = json["CColor"];
- if(color != null)
+ if (color != null)
node.setColor(getColor(color));
return node;
@@ -182,21 +182,21 @@
* @param resourcePath
* @returns {cc.Sprite}
*/
- parser.initSprite = function(json, resourcePath){
- var node = new cc.Sprite();
+ parser.initSprite = function (json, resourcePath) {
+ var node = new cc.Sprite();
- loadTexture(json["FileData"], resourcePath, function(path, type){
- if(type === 0)
+ loadTexture(json["FileData"], resourcePath, function (path, type) {
+ if (type === 0)
node.setTexture(path);
- else if(type === 1){
+ else if (type === 1) {
var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path);
- if(spriteFrame)
+ if (spriteFrame)
node.setSpriteFrame(spriteFrame);
}
});
var blendData = json["BlendFunc"];
- if(json["BlendFunc"]) {
+ if (json["BlendFunc"]) {
var blendFunc = cc.BlendFunc.ALPHA_PREMULTIPLIED;
if (blendData["Src"] !== undefined)
blendFunc.src = blendData["Src"];
@@ -205,14 +205,14 @@
node.setBlendFunc(blendFunc);
}
- if(json["FlipX"])
+ if (json["FlipX"])
node.setFlippedX(true);
- if(json["FlipY"])
+ if (json["FlipY"])
node.setFlippedY(true);
this.generalAttributes(node, json);
var color = json["CColor"];
- if(color != null)
+ if (color != null)
node.setColor(getColor(color));
return node;
@@ -224,11 +224,11 @@
* @param resourcePath
* @returns {*}
*/
- parser.initParticle = function(json, resourcePath){
+ parser.initParticle = function (json, resourcePath) {
var node,
self = this;
- loadTexture(json["FileData"], resourcePath, function(path, type){
- if(!cc.loader.getRes(path))
+ loadTexture(json["FileData"], resourcePath, function (path, type) {
+ if (!cc.loader.getRes(path))
cc.log("%s need to be preloaded", path);
node = new cc.ParticleSystem(path);
self.generalAttributes(node, json);
@@ -236,11 +236,11 @@
!cc.sys.isNative && node.setDrawMode(cc.ParticleSystem.TEXTURE_MODE);
var blendData = json["BlendFunc"];
- if(json["BlendFunc"]){
+ if (json["BlendFunc"]) {
var blendFunc = cc.BlendFunc.ALPHA_PREMULTIPLIED;
- if(blendData["Src"] !== undefined)
+ if (blendData["Src"] !== undefined)
blendFunc.src = blendData["Src"];
- if(blendData["Dst"] !== undefined)
+ if (blendData["Dst"] !== undefined)
blendFunc.dst = blendData["Dst"];
node.setBlendFunc(blendFunc);
}
@@ -270,7 +270,7 @@
widget.setActionTag(actionTag);
var extensionData = new ccs.ComExtensionData();
var customProperty = json["UserData"];
- if(customProperty !== undefined)
+ if (customProperty !== undefined)
extensionData.setCustomProperty(customProperty);
extensionData.setActionTag(actionTag);
if (widget.getComponent("ComExtensionData"))
@@ -347,26 +347,26 @@
bindCallback(widget, json);
};
- var bindCallback = function(widget, json){
+ var bindCallback = function (widget, json) {
var callBackType = json["CallBackType"];
var callBackName = json["CallBackName"];
- var callBack = function(e){
- if(typeof widget[callBackName] === "function")
+ var callBack = function (e) {
+ if (typeof widget[callBackName] === "function")
widget[callBackName](e);
};
- if(callBackType === "Click"){
+ if (callBackType === "Click") {
widget.addClickEventListener(callBack);
- }else if(callBackType === "Touch"){
+ } else if (callBackType === "Touch") {
widget.addTouchEventListener(callBack);
- }else if(callBackType === "Event"){
+ } else if (callBackType === "Event") {
widget.addCCSEventListener(callBack);
}
};
- var setLayoutComponent = function(widget, json){
+ var setLayoutComponent = function (widget, json) {
var layoutComponent = ccui.LayoutComponent.bindLayoutComponent(widget);
- if(!layoutComponent)
+ if (!layoutComponent)
return;
var positionXPercentEnabled = json["PositionPercentXEnable"] || json["PositionPercentXEnabled"] || false;
@@ -378,8 +378,8 @@
positionXPercent = PrePosition["X"] || 0;
positionYPercent = PrePosition["Y"] || 0;
}
- var sizeXPercentEnable = json["PercentWidthEnable"] || json["PercentWidthEnabled"] || false;
- var sizeYPercentEnable = json["PercentHeightEnable"]|| json["PercentHeightEnabled"] || false;
+ var sizeXPercentEnable = json["PercentWidthEnable"] || json["PercentWidthEnabled"] || false;
+ var sizeYPercentEnable = json["PercentHeightEnable"] || json["PercentHeightEnabled"] || false;
var sizeXPercent = 0,
sizeYPercent = 0,
PreSize = json["PreSize"];
@@ -441,18 +441,18 @@
layoutComponent.setRightMargin(rightMargin);
};
- var setLayoutBackground = function(layout, single, first, end){
- if( layout.getBackGroundColorType() === 2 ){
+ var setLayoutBackground = function (layout, single, first, end) {
+ if (layout.getBackGroundColorType() === 2) {
first = first || {};
end = end || {};
layout.setBackGroundColor(getColor(first), getColor(end));
- }else{
+ } else {
single = single || {};
layout.setBackGroundColor(getColor(single));
}
};
- var setLayoutBackgroundVector = function(widget, vector){
+ var setLayoutBackgroundVector = function (widget, vector) {
var x = vector["ScaleX"] || 0;
var y = vector["ScaleY"] || 0;
widget.setBackGroundColorVector(cc.p(x, y));
@@ -464,34 +464,34 @@
* @param resourcePath
* @returns {ccui.Layout}
*/
- parser.initPanel = function(json, resourcePath){
+ parser.initPanel = function (json, resourcePath) {
var widget = new ccui.Layout();
this.widgetAttributes(widget, json);
var clipEnabled = json["ClipAble"] || false;
- if(clipEnabled != null)
+ if (clipEnabled != null)
widget.setClippingEnabled(clipEnabled);
var colorType = getParam(json["ComboBoxIndex"], 0);
widget.setBackGroundColorType(colorType);
var bgColorOpacity = getParam(json["BackColorAlpha"], 255);
- if(bgColorOpacity != null)
+ if (bgColorOpacity != null)
widget.setBackGroundColorOpacity(bgColorOpacity);
var backGroundScale9Enabled = json["Scale9Enable"];
- if(backGroundScale9Enabled != null)
+ if (backGroundScale9Enabled != null)
widget.setBackGroundImageScale9Enabled(backGroundScale9Enabled);
var opacity = getParam(json["Alpha"], 255);
widget.setOpacity(opacity);
- loadTexture(json["FileData"], resourcePath, function(path, type){
+ loadTexture(json["FileData"], resourcePath, function (path, type) {
widget.setBackGroundImage(path, type);
});
- if(backGroundScale9Enabled){
+ if (backGroundScale9Enabled) {
var scale9OriginX = json["Scale9OriginX"] || 0;
var scale9OriginY = json["Scale9OriginY"] || 0;
@@ -503,8 +503,8 @@
));
setContentSize(widget, json["Size"]);
- }else{
- if (!widget.isIgnoreContentAdaptWithSize()){
+ } else {
+ if (!widget.isIgnoreContentAdaptWithSize()) {
setContentSize(widget, json["Size"]);
}
@@ -521,37 +521,39 @@
* @param json
* @param resourcePath
*/
- parser.initText = function(json, resourcePath){
+ parser.initText = function (json, resourcePath) {
var widget = new ccui.Text();
var touchScaleEnabled = json["TouchScaleChangeAble"];
- if(touchScaleEnabled != null)
+ if (touchScaleEnabled != null)
widget.setTouchScaleChangeEnabled(touchScaleEnabled);
var text = json["LabelText"];
- if(text != null)
+ if (text != null)
widget.setString(text);
var fontSize = json["FontSize"];
- if(fontSize != null)
+ if (fontSize != null)
widget.setFontSize(fontSize);
var fontName = json["FontName"];
- if(fontName != null)
+ if (fontName != null)
widget.setFontName(fontName);
var areaWidth = json["AreaWidth"];
var areaHeight = json["areaHeight"];
- if(areaWidth && areaHeight)
+ if (areaWidth && areaHeight)
widget.setTextAreaSize(cc.size(areaWidth, areaHeight));
var h_alignment = json["HorizontalAlignmentType"] || "HT_Left";
- switch(h_alignment){
+ switch (h_alignment) {
case "HT_Right":
- h_alignment = 2; break;
+ h_alignment = 2;
+ break;
case "HT_Center":
- h_alignment = 1; break;
+ h_alignment = 1;
+ break;
case "HT_Left":
default:
h_alignment = 0;
@@ -559,11 +561,13 @@
widget.setTextHorizontalAlignment(h_alignment);
var v_alignment = json["VerticalAlignmentType"] || "VT_Top";
- switch(v_alignment){
+ switch (v_alignment) {
case "VT_Bottom":
- v_alignment = 2; break;
+ v_alignment = 2;
+ break;
case "VT_Center":
- v_alignment = 1; break;
+ v_alignment = 1;
+ break;
case "VT_Top":
default:
v_alignment = 0;
@@ -571,10 +575,10 @@
widget.setTextVerticalAlignment(v_alignment);
var fontResource = json["FontResource"];
- if(fontResource != null){
+ if (fontResource != null) {
var path = fontResource["Path"];
//resoutceType = fontResource["Type"];
- if(path != null){
+ if (path != null) {
if (cc.sys.isNative) {
fontName = cc.path.join(cc.loader.resPath, resourcePath, path);
} else {
@@ -585,10 +589,10 @@
}
}
- if(json["OutlineEnabled"] && json["OutlineColor"] && widget.enableOutline)
+ if (json["OutlineEnabled"] && json["OutlineColor"] && widget.enableOutline)
widget.enableOutline(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1));
- if(json["ShadowEnabled"] && json["ShadowColor"] && widget.enableShadow)
+ if (json["ShadowEnabled"] && json["ShadowColor"] && widget.enableShadow)
widget.enableShadow(
getColor(json["ShadowColor"]),
cc.size(getParam(json["ShadowOffsetX"], 2), getParam(json["ShadowOffsetY"], -2)),
@@ -596,7 +600,7 @@
);
var isCustomSize = json["IsCustomSize"];
- if(isCustomSize != null)
+ if (isCustomSize != null)
widget.ignoreContentAdaptWithSize(!isCustomSize);
widget.setUnifySizeEnabled(false);
@@ -615,39 +619,39 @@
* @param json
* @param resourcePath
*/
- parser.initButton = function(json, resourcePath){
+ parser.initButton = function (json, resourcePath) {
var widget = new ccui.Button();
- loadTexture(json["NormalFileData"], resourcePath, function(path, type){
+ loadTexture(json["NormalFileData"], resourcePath, function (path, type) {
widget.loadTextureNormal(path, type);
});
- loadTexture(json["PressedFileData"], resourcePath, function(path, type){
+ loadTexture(json["PressedFileData"], resourcePath, function (path, type) {
widget.loadTexturePressed(path, type);
});
- loadTexture(json["DisabledFileData"], resourcePath, function(path, type){
+ loadTexture(json["DisabledFileData"], resourcePath, function (path, type) {
widget.loadTextureDisabled(path, type);
});
var scale9Enabled = getParam(json["Scale9Enable"], false);
- if(scale9Enabled) {
+ if (scale9Enabled) {
widget.setScale9Enabled(scale9Enabled);
}
var text = json["ButtonText"];
- if(text != null)
+ if (text != null)
widget.setTitleText(text);
var fontSize = json["FontSize"];
- if(fontSize != null)
+ if (fontSize != null)
widget.setTitleFontSize(fontSize);
var fontName = json["FontName"];
- if(fontName != null)
+ if (fontName != null)
widget.setTitleFontName(fontName);
var textColor = json["TextColor"];
- if(textColor != null)
+ if (textColor != null)
widget.setTitleColor(getColor(textColor));
var displaystate = getParam(json["DisplayState"], true);
@@ -655,10 +659,10 @@
widget.setEnabled(displaystate);
var fontResource = json["FontResource"];
- if(fontResource != null){
+ if (fontResource != null) {
var path = fontResource["Path"];
//resoutceType = fontResource["Type"];
- if(path != null){
+ if (path != null) {
if (cc.sys.isNative) {
fontName = cc.path.join(cc.loader.resPath, resourcePath, path);
} else {
@@ -670,26 +674,26 @@
}
var label = widget.getTitleRenderer();
- if(label && json["ShadowEnabled"] && json["ShadowColor"] && label.enableShadow){
+ if (label && json["ShadowEnabled"] && json["ShadowColor"] && label.enableShadow) {
label.enableShadow(
getColor(json["ShadowColor"]),
cc.size(getParam(json["ShadowOffsetX"], 2), getParam(json["ShadowOffsetY"], -2)),
json["ShadowBlurRadius"] || 0
);
}
- if(label && json["OutlineEnabled"] && json["OutlineColor"] && label.enableStroke)
+ if (label && json["OutlineEnabled"] && json["OutlineColor"] && label.enableStroke)
label.enableStroke(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1));
this.widgetAttributes(widget, json);
- if(scale9Enabled) {
+ if (scale9Enabled) {
widget.setUnifySizeEnabled(false);
widget.ignoreContentAdaptWithSize(false);
var capInsets = cc.rect(
- json["Scale9OriginX"] || 0,
- json["Scale9OriginY"] || 0,
- json["Scale9Width"] || 0,
- json["Scale9Height"] || 0
+ json["Scale9OriginX"] || 0,
+ json["Scale9OriginY"] || 0,
+ json["Scale9Width"] || 0,
+ json["Scale9Height"] || 0
);
widget.setCapInsets(capInsets);
@@ -706,7 +710,7 @@
* @param json
* @param resourcePath
*/
- parser.initCheckBox = function(json, resourcePath){
+ parser.initCheckBox = function (json, resourcePath) {
var widget = new ccui.CheckBox();
@@ -720,8 +724,8 @@
{name: "NodeDisableFileData", handle: widget.loadTextureFrontCrossDisabled}
];
- dataList.forEach(function(item){
- loadTexture(json[item.name], resourcePath, function(path, type){
+ dataList.forEach(function (item) {
+ loadTexture(json[item.name], resourcePath, function (path, type) {
item.handle.call(widget, path, type);
});
});
@@ -741,12 +745,12 @@
* @param json
* @param resourcePath
*/
- parser.initScrollView = function(json, resourcePath){
+ parser.initScrollView = function (json, resourcePath) {
var widget = new ccui.ScrollView();
this.widgetAttributes(widget, json);
- loadTexture(json["FileData"], resourcePath, function(path, type){
+ loadTexture(json["FileData"], resourcePath, function (path, type) {
widget.setBackGroundImage(path, type);
});
@@ -757,11 +761,11 @@
widget.setBackGroundColorType(colorType);
var bgColorOpacity = json["BackColorAlpha"];
- if(bgColorOpacity != null)
+ if (bgColorOpacity != null)
widget.setBackGroundColorOpacity(bgColorOpacity);
var backGroundScale9Enabled = json["Scale9Enable"];
- if(backGroundScale9Enabled){
+ if (backGroundScale9Enabled) {
widget.setBackGroundImageScale9Enabled(true);
@@ -773,7 +777,7 @@
scale9OriginX, scale9OriginY, scale9Width, scale9Height
));
setContentSize(widget, json["Size"]);
- }else if(!widget.isIgnoreContentAdaptWithSize()){
+ } else if (!widget.isIgnoreContentAdaptWithSize()) {
setContentSize(widget, json["Size"]);
}
@@ -788,9 +792,9 @@
widget.setInnerContainerSize(innerSize);
var direction = 0;
- if(json["ScrollDirectionType"] === "Vertical") direction = 1;
- if(json["ScrollDirectionType"] === "Horizontal") direction = 2;
- if(json["ScrollDirectionType"] === "Vertical_Horizontal") direction = 3;
+ if (json["ScrollDirectionType"] === "Vertical") direction = 1;
+ if (json["ScrollDirectionType"] === "Horizontal") direction = 2;
+ if (json["ScrollDirectionType"] === "Vertical_Horizontal") direction = 3;
widget.setDirection(direction);
var bounceEnabled = getParam(json["IsBounceEnabled"], false);
@@ -804,19 +808,19 @@
* @param json
* @param resourcePath
*/
- parser.initImageView = function(json, resourcePath){
+ parser.initImageView = function (json, resourcePath) {
var widget = new ccui.ImageView();
- loadTexture(json["FileData"], resourcePath, function(path, type){
+ loadTexture(json["FileData"], resourcePath, function (path, type) {
widget.loadTexture(path, type);
});
- loadTexture(json["ImageFileData"], resourcePath, function(path, type){
+ loadTexture(json["ImageFileData"], resourcePath, function (path, type) {
widget.loadTexture(path, type);
});
var scale9Enabled = json["Scale9Enable"];
- if(scale9Enabled){
+ if (scale9Enabled) {
widget.setScale9Enabled(true);
widget.setUnifySizeEnabled(false);
widget.ignoreContentAdaptWithSize(false);
@@ -826,7 +830,7 @@
var scale9Width = json["Scale9Width"] || 0;
var scale9Height = json["Scale9Height"] || 0;
widget.setCapInsets(cc.rect(
- scale9OriginX ,
+ scale9OriginX,
scale9OriginY,
scale9Width,
scale9Height
@@ -845,13 +849,13 @@
* @param resourcePath
* @returns {ccui.LoadingBar}
*/
- parser.initLoadingBar = function(json, resourcePath){
+ parser.initLoadingBar = function (json, resourcePath) {
var widget = new ccui.LoadingBar();
this.widgetAttributes(widget, json);
- loadTexture(json["ImageFileData"], resourcePath, function(path, type){
+ loadTexture(json["ImageFileData"], resourcePath, function (path, type) {
widget.loadTexture(path, type);
});
@@ -859,7 +863,7 @@
widget.setDirection(direction);
var percent = getParam(json["ProgressInfo"], 80);
- if(percent != null)
+ if (percent != null)
widget.setPercent(percent);
return widget;
@@ -871,7 +875,7 @@
* @param json
* @param resourcePath
*/
- parser.initSlider = function(json, resourcePath){
+ parser.initSlider = function (json, resourcePath) {
var widget = new ccui.Slider();
var loader = cc.loader;
@@ -885,9 +889,9 @@
{name: "BallDisabledData", handle: widget.loadSlidBallTextureDisabled},
{name: "ProgressBarData", handle: widget.loadProgressBarTexture}
];
- textureList.forEach(function(item){
- loadTexture(json[item.name], resourcePath, function(path, type){
- if(type === 0 && !loader.getRes(path))
+ textureList.forEach(function (item) {
+ loadTexture(json[item.name], resourcePath, function (path, type) {
+ if (type === 0 && !loader.getRes(path))
cc.log("%s need to be preloaded", path);
item.handle.call(widget, path, type);
});
@@ -908,13 +912,13 @@
* @param json
* @param resourcePath
*/
- parser.initPageView = function(json, resourcePath){
+ parser.initPageView = function (json, resourcePath) {
var widget = new ccui.PageView();
this.widgetAttributes(widget, json);
- loadTexture(json["FileData"], resourcePath, function(path, type){
+ loadTexture(json["FileData"], resourcePath, function (path, type) {
widget.setBackGroundImage(path, type);
});
@@ -922,7 +926,7 @@
widget.setClippingEnabled(clipEnabled);
var backGroundScale9Enabled = json["Scale9Enable"];
- if(backGroundScale9Enabled){
+ if (backGroundScale9Enabled) {
widget.setBackGroundImageScale9Enabled(true);
var scale9OriginX = json["Scale9OriginX"] || 0;
@@ -944,7 +948,7 @@
setLayoutBackgroundVector(widget, json["ColorVector"]);
var bgColorOpacity = json["BackColorAlpha"];
- if(bgColorOpacity != null)
+ if (bgColorOpacity != null)
widget.setBackGroundColorOpacity(bgColorOpacity);
setContentSize(widget, json["Size"]);
@@ -959,13 +963,13 @@
* @param resourcePath
* @returns {ccui.ListView}
*/
- parser.initListView = function(json, resourcePath){
+ parser.initListView = function (json, resourcePath) {
var widget = new ccui.ListView();
this.widgetAttributes(widget, json);
- loadTexture(json["FileData"], resourcePath, function(path, type){
+ loadTexture(json["FileData"], resourcePath, function (path, type) {
widget.setBackGroundImage(path, type);
});
@@ -977,7 +981,7 @@
var bgColorOpacity = getParam(json["BackColorAlpha"], 255);
var backGroundScale9Enabled = json["Scale9Enable"];
- if(backGroundScale9Enabled){
+ if (backGroundScale9Enabled) {
widget.setBackGroundImageScale9Enabled(true);
var scale9OriginX = json["Scale9OriginX"] || 0;
@@ -995,15 +999,15 @@
var directionType = getParam(json["DirectionType"], ccui.ListView.DIR_HORIZONTAL);
var verticalType = getParam(json["VerticalType"], "Align_Left");
var horizontalType = getParam(json["HorizontalType"], "Align_Top");
- if(!directionType){
+ if (!directionType) {
widget.setDirection(ccui.ScrollView.DIR_HORIZONTAL);
- if(verticalType === "Align_Bottom")
+ if (verticalType === "Align_Bottom")
widget.setGravity(ccui.ListView.GRAVITY_BOTTOM);
- else if(verticalType === "Align_VerticalCenter")
+ else if (verticalType === "Align_VerticalCenter")
widget.setGravity(ccui.ListView.GRAVITY_CENTER_VERTICAL);
else
widget.setGravity(ccui.ListView.GRAVITY_TOP);
- }else if(directionType === "Vertical"){
+ } else if (directionType === "Vertical") {
widget.setDirection(ccui.ScrollView.DIR_VERTICAL);
if (horizontalType === "")
widget.setGravity(ccui.ListView.GRAVITY_LEFT);
@@ -1022,13 +1026,13 @@
var innerSize = json["InnerNodeSize"];
//Width
- if(innerSize != null)
- widget.setInnerContainerSize(cc.size(innerSize["Widget"]||0, innerSize["Height"]||0));
+ if (innerSize != null)
+ widget.setInnerContainerSize(cc.size(innerSize["Widget"] || 0, innerSize["Height"] || 0));
setLayoutBackground(widget, json["SingleColor"], json["FirstColor"], json["EndColor"]);
setLayoutBackgroundVector(widget, json["ColorVector"]);
- if(bgColorOpacity != null)
+ if (bgColorOpacity != null)
widget.setBackGroundColorOpacity(bgColorOpacity);
setContentSize(widget, json["Size"]);
@@ -1042,7 +1046,7 @@
* @param resourcePath
* @returns {ccui.TextAtlas}
*/
- parser.initTextAtlas = function(json, resourcePath){
+ parser.initTextAtlas = function (json, resourcePath) {
var widget = new ccui.TextAtlas();
@@ -1052,10 +1056,10 @@
var startCharMap = json["StartChar"];
- loadTexture(json["LabelAtlasFileImage_CNB"], resourcePath, function(path, type){
- if(!cc.loader.getRes(path))
+ loadTexture(json["LabelAtlasFileImage_CNB"], resourcePath, function (path, type) {
+ if (!cc.loader.getRes(path))
cc.log("%s need to be preloaded", path);
- if(type === 0){
+ if (type === 0) {
widget.setProperty(stringValue, path, itemWidth, itemHeight, startCharMap);
}
});
@@ -1073,7 +1077,7 @@
* @param resourcePath
* @returns {ccui.TextBMFont}
*/
- parser.initTextBMFont = function(json, resourcePath){
+ parser.initTextBMFont = function (json, resourcePath) {
var widget = new ccui.TextBMFont();
this.widgetAttributes(widget, json);
@@ -1081,8 +1085,8 @@
var text = json["LabelText"];
widget.setString(text);
- loadTexture(json["LabelBMFontFile_CNB"], resourcePath, function(path, type){
- if(!cc.loader.getRes(path))
+ loadTexture(json["LabelBMFontFile_CNB"], resourcePath, function (path, type) {
+ if (!cc.loader.getRes(path))
cc.log("%s need to be pre loaded", path);
widget.setFntFile(path);
});
@@ -1096,30 +1100,30 @@
* @param resourcePath
* @returns {ccui.TextField}
*/
- parser.initTextField = function(json, resourcePath){
+ parser.initTextField = function (json, resourcePath) {
var widget = new ccui.TextField();
var passwordEnabled = json["PasswordEnable"];
- if(passwordEnabled){
+ if (passwordEnabled) {
widget.setPasswordEnabled(true);
var passwordStyleText = json["PasswordStyleText"] || "*";
widget.setPasswordStyleText(passwordStyleText);
}
var placeHolder = json["PlaceHolderText"];
- if(placeHolder != null)
+ if (placeHolder != null)
widget.setPlaceHolder(placeHolder);
var fontSize = json["FontSize"];
- if(fontSize != null)
+ if (fontSize != null)
widget.setFontSize(fontSize);
var fontName = json["FontName"];
- if(fontName != null)
+ if (fontName != null)
widget.setFontName(fontName);
var maxLengthEnabled = json["MaxLengthEnable"];
- if(maxLengthEnabled){
+ if (maxLengthEnabled) {
widget.setMaxLengthEnabled(true);
var maxLength = json["MaxLengthText"] || 0;
widget.setMaxLength(maxLength);
@@ -1129,14 +1133,14 @@
this.widgetAttributes(widget, json);
var text = json["LabelText"];
- if(text != null)
+ if (text != null)
widget.setString(text);
var fontResource = json["FontResource"];
- if(fontResource != null){
+ if (fontResource != null) {
var path = fontResource["Path"];
//resoutceType = fontResource["Type"];
- if(path != null){
+ if (path != null) {
if (cc.sys.isNative) {
fontName = cc.path.join(cc.loader.resPath, resourcePath, path);
} else {
@@ -1151,10 +1155,10 @@
widget.ignoreContentAdaptWithSize(false);
var color = json["CColor"];
- if(color != null)
+ if (color != null)
widget.setTextColor(getColor(color));
- if (!widget.isIgnoreContentAdaptWithSize()){
+ if (!widget.isIgnoreContentAdaptWithSize()) {
setContentSize(widget, json["Size"]);
if (cc.sys.isNative)
widget.getVirtualRenderer().setLineBreakWithoutSpace(true);
@@ -1170,14 +1174,14 @@
* @param json
* @param resourcePath
*/
- parser.initSimpleAudio = function(json, resourcePath){
+ parser.initSimpleAudio = function (json, resourcePath) {
var node = new ccs.ComAudio();
var loop = json["Loop"] || false;
//var volume = json["Volume"] || 0;
//cc.audioEngine.setMusicVolume(volume);
node.setLoop(loop);
- loadTexture(json["FileData"], resourcePath, function(path, type){
+ loadTexture(json["FileData"], resourcePath, function (path, type) {
node.setFile(path);
});
@@ -1189,12 +1193,12 @@
* @param resourcePath
* @returns {*}
*/
- parser.initGameMap = function(json, resourcePath){
+ parser.initGameMap = function (json, resourcePath) {
var node = null;
- loadTexture(json["FileData"], resourcePath, function(path, type){
- if(type === 0)
+ loadTexture(json["FileData"], resourcePath, function (path, type) {
+ if (type === 0)
node = new cc.TMXTiledMap(path);
parser.generalAttributes(node, json);
@@ -1209,17 +1213,17 @@
* @param resourcePath
* @returns {*}
*/
- parser.initProjectNode = function(json, resourcePath){
+ parser.initProjectNode = function (json, resourcePath) {
var projectFile = json["FileData"];
- if(projectFile != null && projectFile["Path"]){
+ if (projectFile != null && projectFile["Path"]) {
var file = resourcePath + projectFile["Path"];
- if(cc.loader.getRes(file)){
+ if (cc.loader.getRes(file)) {
var obj = ccs.load(file, resourcePath);
parser.generalAttributes(obj.node, json);
- if(obj.action && obj.node){
+ if (obj.action && obj.node) {
obj.action.tag = obj.node.tag;
var InnerActionSpeed = json["InnerActionSpeed"];
- if(InnerActionSpeed !== undefined)
+ if (InnerActionSpeed !== undefined)
obj.action.setTimeSpeed(InnerActionSpeed);
obj.node.runAction(obj.action);
obj.action.gotoFrameAndPause(0);
@@ -1230,10 +1234,10 @@
}
};
- var getFileName = function(name){
- if(!name) return "";
+ var getFileName = function (name) {
+ if (!name) return "";
var arr = name.match(/([^\/]+)\.[^\/]+$/);
- if(arr && arr[1])
+ if (arr && arr[1])
return arr[1];
else
return "";
@@ -1244,7 +1248,7 @@
* @param json
* @param resourcePath
*/
- parser.initArmature = function(json, resourcePath){
+ parser.initArmature = function (json, resourcePath) {
var node = new ccs.Armature();
@@ -1254,24 +1258,24 @@
var currentAnimationName = json["CurrentAnimationName"];
- loadTexture(json["FileData"], resourcePath, function(path, type){
+ loadTexture(json["FileData"], resourcePath, function (path, type) {
var plists, pngs;
var armJson = cc.loader.getRes(path);
- if(!armJson)
+ if (!armJson)
cc.log("%s need to be preloaded", path);
- else{
+ else {
plists = armJson["config_file_path"];
pngs = armJson["config_png_path"];
- plists.forEach(function(plist, index){
- if(pngs[index])
+ plists.forEach(function (plist, index) {
+ if (pngs[index])
cc.spriteFrameCache.addSpriteFrames(plist, pngs[index]);
});
}
ccs.armatureDataManager.addArmatureFileInfo(path);
node.init(getFileName(path));
- if(isAutoPlay)
+ if (isAutoPlay)
node.getAnimation().play(currentAnimationName, -1, isLoop);
- else{
+ else {
node.getAnimation().play(currentAnimationName);
node.getAnimation().gotoAndPause(0);
}
@@ -1286,65 +1290,65 @@
return node;
};
- parser.initBoneNode = function(json, resourcePath){
+ parser.initBoneNode = function (json, resourcePath) {
var node = new ccs.BoneNode();
var length = json["Length"];
- if(length !== undefined)
+ if (length !== undefined)
node.setDebugDrawLength(length);
var blendFunc = json["BlendFunc"];
- if(blendFunc && blendFunc["Src"] !== undefined && blendFunc["Dst"] !== undefined)
+ if (blendFunc && blendFunc["Src"] !== undefined && blendFunc["Dst"] !== undefined)
node.setBlendFunc(new cc.BlendFunc(blendFunc["Src"], blendFunc["Dst"]));
parser.generalAttributes(node, json);
var color = json["CColor"];
- if(color && (color["R"] !== undefined || color["G"] !== undefined || color["B"] !== undefined))
+ if (color && (color["R"] !== undefined || color["G"] !== undefined || color["B"] !== undefined))
node.setColor(getColor(color));
return node;
};
- parser.initSkeletonNode = function(json){
+ parser.initSkeletonNode = function (json) {
var node = new ccs.SkeletonNode();
parser.generalAttributes(node, json);
var color = json["CColor"];
- if(color && (color["R"] !== undefined || color["G"] !== undefined || color["B"] !== undefined))
+ if (color && (color["R"] !== undefined || color["G"] !== undefined || color["B"] !== undefined))
node.setColor(getColor(color));
return node;
};
var loadedPlist = {};
- var loadTexture = function(json, resourcePath, cb){
- if(json != null){
+ var loadTexture = function (json, resourcePath, cb) {
+ if (json != null) {
var path = json["Path"];
var type;
- if(json["Type"] === "Default" || json["Type"] === "Normal")
+ if (json["Type"] === "Default" || json["Type"] === "Normal")
type = 0;
else
type = 1;
var plist = json["Plist"];
- if(plist){
- if(cc.loader.getRes(resourcePath + plist)){
+ if (plist) {
+ if (cc.loader.getRes(resourcePath + plist)) {
loadedPlist[resourcePath + plist] = true;
cc.spriteFrameCache.addSpriteFrames(resourcePath + plist);
- }else{
- if(!loadedPlist[resourcePath + plist] && !cc.spriteFrameCache.getSpriteFrame(path))
+ } else {
+ if (!loadedPlist[resourcePath + plist] && !cc.spriteFrameCache.getSpriteFrame(path))
cc.log("%s need to be preloaded", resourcePath + plist);
}
}
- if(type !== 0){
- if(cc.spriteFrameCache.getSpriteFrame(path))
+ if (type !== 0) {
+ if (cc.spriteFrameCache.getSpriteFrame(path))
cb(path, type);
else
cc.log("failed to get spriteFrame: %s", path);
- }else
+ } else
cb(resourcePath + path, type);
}
};
- var getColor = function(json){
- if(!json) return;
+ var getColor = function (json) {
+ if (!json) return;
var r = json["R"] != null ? json["R"] : 255;
var g = json["G"] != null ? json["G"] : 255;
var b = json["B"] != null ? json["B"] : 255;
@@ -1352,10 +1356,10 @@
return cc.color(r, g, b, a);
};
- var setContentSize = function(node, size){
+ var setContentSize = function (node, size) {
var x = size["X"] || 0;
var y = size["Y"] || 0;
- if(size)
+ if (size)
node.setContentSize(cc.size(x, y));
};
@@ -1388,8 +1392,8 @@
{name: "SkeletonNodeObjectData", handle: parser.initSkeletonNode}
];
- register.forEach(function(item){
- parser.registerParser(item.name, function(options, resourcePath){
+ register.forEach(function (item) {
+ parser.registerParser(item.name, function (options, resourcePath) {
var node = item.handle.call(this, options, resourcePath);
this.parseChild(node, options["Children"], resourcePath);
DEBUG && node && (node.__parserName = item.name);
diff --git a/extensions/cocostudio/loader/parsers/uiParser-1.x.js b/extensions/cocostudio/loader/parsers/uiParser-1.x.js
index 8c345d4128..6c58029fe5 100644
--- a/extensions/cocostudio/loader/parsers/uiParser-1.x.js
+++ b/extensions/cocostudio/loader/parsers/uiParser-1.x.js
@@ -22,49 +22,120 @@
THE SOFTWARE.
****************************************************************************/
-(function(load, baseParser){
+(function (load, baseParser) {
+
+ var _stack = new Array(50);
var Parser = baseParser.extend({
- addSpriteFrame: function(textures, resourcePath){
- if(!textures) return;
+ addSpriteFrame: function (textures, resourcePath) {
+ if (!textures) return;
for (var i = 0; i < textures.length; i++) {
cc.spriteFrameCache.addSpriteFrames(resourcePath + textures[i]);
}
},
- pretreatment: function(json, resourcePath){
+ pretreatment: function (json, resourcePath) {
this.addSpriteFrame(json["textures"], resourcePath);
},
- deferred: function(json, resourcePath, node, file){
- if(node){
- ccs.actionManager.initWithDictionary(file, json["animation"], node);
- node.setContentSize(cc.size(json["designWidth"], json["designHeight"]));
+ parseRecursive: function (json, resourcePath) {
+ var index = 1;
+ var rootNode = null;
+ var parser, curr, className, options, position, anchor, anchorPP,
+ node, parent, child, children;
+ _stack[0] = json;
+ while (index > 0) {
+ index--;
+ curr = _stack[index];
+ // Avoid memory leak
+ _stack[index] = null;
+ if (!curr) continue;
+
+ // Parse node
+ className = curr["classname"];
+ parser = this.parsers[className];
+ if (!parser) {
+ cc.log("Can't find the parser : %s", className);
+ continue;
+ }
+ node = new parser.object();
+ if (!node) continue;
+ if (!rootNode) {
+ rootNode = node;
+ }
+
+ // Parse attributes
+ options = curr["options"];
+ this.generalAttributes(node, options);
+ parser.handle(node, options, resourcePath);
+ this.colorAttributes(node, options);
+
+ parent = curr.parent;
+ curr.parent = null;
+ if (parent instanceof ccui.PageView) {
+ parent.addPage(node);
+ }
+ else if (parent instanceof ccui.ListView) {
+ parent.pushBackCustomItem(node);
+ }
+ else if (parent) {
+ if (!(parent instanceof ccui.Layout)) {
+ if (node.getPositionType() === ccui.Widget.POSITION_PERCENT) {
+ position = node._positionPercent;
+ anchor = parent._anchorPoint;
+ node._positionPercent.x = position.x + anchor.x;
+ node._positionPercent.y = position.y + anchor.y;
+ }
+ anchorPP = parent._renderCmd._anchorPointInPoints;
+ node._position.x += anchorPP.x;
+ node._position.y += anchorPP.y;
+ node.setNodeDirty();
+ }
+ parent.addChild(node);
+ }
+
+ children = curr["children"];
+ if (children && children.length > 0) {
+ for (var i = children.length - 1; i >= 0; i--) {
+ _stack[index] = children[i];
+ _stack[index].parent = node;
+ index++;
+ }
+ }
}
- }
+ return rootNode;
+ },
- });
- var parser = new Parser();
+ parse: function (file, json, resourcePath) {
+ resourcePath = resourcePath || this._dirname(file);
+ this.pretreatment(json, resourcePath);
+ var node = this.parseRecursive(json["widgetTree"], resourcePath);
- parser.generalAttributes = function(widget, options){
- var ignoreSizeExsit = options["ignoreSize"];
- if(ignoreSizeExsit != null)
- widget.ignoreContentAdaptWithSize(ignoreSizeExsit);
+ node && this.deferred(json, resourcePath, node, file);
+ return node;
+ },
- if (options["sizeType"])
- {
- widget.setSizeType(options["sizeType"]);
+ deferred: function (json, resourcePath, node, file) {
+ if (node) {
+ ccs.actionManager.initWithDictionary(file, json["animation"], node);
+ node.setContentSize(json["designWidth"], json["designHeight"]);
+ }
}
- if (options["positionType"])
- {
- widget.setPositionType(options["positionType"]);
- }
+ });
+ var parser = new Parser();
- widget.setSizePercent(cc.p(options["sizePercentX"], options["sizePercentY"]));
- widget.setPositionPercent(cc.p(options["positionPercentX"], options["positionPercentY"]));
+ parser.generalAttributes = function (widget, options) {
+ widget._ignoreSize = options["ignoreSize"] || false;
+ widget._sizeType = options["sizeType"] || 0;
+ widget._positionType = options["positionType"] || 0;
+
+ widget._sizePercent.x = options["sizePercentX"] || 0;
+ widget._sizePercent.y = options["sizePercentY"] || 0;
+ widget._positionPercent.x = options["positionPercentX"] || 0;
+ widget._positionPercent.y = options["positionPercentY"] || 0;
/* adapt screen */
var w = 0, h = 0;
@@ -74,77 +145,69 @@
w = screenSize.width;
h = screenSize.height;
} else {
- w = options["width"];
- h = options["height"];
+ w = options["width"] || 0;
+ h = options["height"] || 0;
}
+
+ var anchorPointX = options["anchorPointX"];
+ var anchorPointY = options["anchorPointY"];
+
+ widget._anchorPoint.x = isNaN(anchorPointX) ? 0.5 : anchorPointX;
+ widget._anchorPoint.y = isNaN(anchorPointY) ? 0.5 : anchorPointY;
+
widget.setContentSize(w, h);
widget.setTag(options["tag"]);
widget.setActionTag(options["actiontag"]);
widget.setTouchEnabled(options["touchAble"]);
- var name = options["name"];
- var widgetName = name ? name : "default";
- widget.setName(widgetName);
-
- var x = options["x"];
- var y = options["y"];
- widget.setPosition(x, y);
-
- var sx = options["scaleX"]!=null ? options["scaleX"] : 1;
- widget.setScaleX(sx);
- var sy = options["scaleY"]!=null ? options["scaleY"] : 1;
- widget.setScaleY(sy);
+ widget._name = options["name"] || "default";
- var rt = options["rotation"] || 0;
- widget.setRotation(rt);
+ widget._position.x = options["x"] || 0;
+ widget._position.y = options["y"] || 0;
+ widget._scaleX = options["scaleX"] || 1;
+ widget._scaleY = options["scaleY"] || 1;
+ widget._rotationX = widget._rotationY = options["rotation"] || 0;
- var vb = options["visible"] || false;
- if(vb != null)
- widget.setVisible(vb);
- widget.setLocalZOrder(options["ZOrder"]);
+ widget._visible = options["visible"] || false;
+ widget._localZOrder = options["ZOrder"] || 0;
var layout = options["layoutParameter"];
- if(layout != null){
+ if (layout != null) {
var layoutParameterDic = options["layoutParameter"];
- var paramType = layoutParameterDic["type"];
+ var paramType = isNaN(layoutParameterDic["type"]) ? 2 : layoutParameterDic["type"];
var parameter = null;
- switch(paramType){
+ switch (paramType) {
case 0:
break;
case 1:
parameter = new ccui.LinearLayoutParameter();
- var gravity = layoutParameterDic["gravity"];
- parameter.setGravity(gravity);
+ parameter._linearGravity = layoutParameterDic["gravity"] || 0;
break;
case 2:
parameter = new ccui.RelativeLayoutParameter();
- var rParameter = parameter;
- var relativeName = layoutParameterDic["relativeName"];
- rParameter.setRelativeName(relativeName);
- var relativeToName = layoutParameterDic["relativeToName"];
- rParameter.setRelativeToWidgetName(relativeToName);
- var align = layoutParameterDic["align"];
- rParameter.setAlign(align);
+ parameter._relativeLayoutName = layoutParameterDic["relativeName"];
+ parameter._relativeWidgetName = layoutParameterDic["relativeToName"];
+ parameter._relativeAlign = layoutParameterDic["align"] || 0;
break;
default:
break;
}
- if(parameter != null){
- var mgl = layoutParameterDic["marginLeft"]||0;
- var mgt = layoutParameterDic["marginTop"]||0;
- var mgr = layoutParameterDic["marginRight"]||0;
- var mgb = layoutParameterDic["marginDown"]||0;
- parameter.setMargin(mgl, mgt, mgr, mgb);
+ if (parameter != null) {
+ var margin = parameter._margin;
+ margin.left = layoutParameterDic["marginLeft"] || 0;
+ margin.top = layoutParameterDic["marginTop"] || 0;
+ margin.right = layoutParameterDic["marginRight"] || 0;
+ margin.bottom = layoutParameterDic["marginDown"] || 0;
widget.setLayoutParameter(parameter);
}
}
};
- parser.colorAttributes = function(widget, options){
- var op = options["opacity"];
- if(op != null)
+ parser.colorAttributes = function (widget, options) {
+ var op = options["opacity"] !== null ? options["opacity"] : 255;
+ if (op != null)
widget.setOpacity(op);
var colorR = options["colorR"];
var colorG = options["colorG"];
@@ -155,55 +218,9 @@
widget.setFlippedY(options["flipY"]);
};
- parser.anchorPointAttributes = function(widget, options){
- var isAnchorPointXExists = options["anchorPointX"];
- var anchorPointXInFile;
- if (isAnchorPointXExists != null)
- anchorPointXInFile = options["anchorPointX"];
- else
- anchorPointXInFile = widget.getAnchorPoint().x;
-
- var isAnchorPointYExists = options["anchorPointY"];
- var anchorPointYInFile;
- if (isAnchorPointYExists != null)
- anchorPointYInFile = options["anchorPointY"];
- else
- anchorPointYInFile = widget.getAnchorPoint().y;
-
- if (isAnchorPointXExists != null || isAnchorPointYExists != null)
- widget.setAnchorPoint(cc.p(anchorPointXInFile, anchorPointYInFile));
- };
-
- parser.parseChild = function(widget, options, resourcePath){
- var children = options["children"];
- for (var i = 0; i < children.length; i++) {
- var child = this.parseNode(children[i], resourcePath);
- if(child){
- if(widget instanceof ccui.PageView)
- widget.addPage(child);
- else {
- if(widget instanceof ccui.ListView){
- widget.pushBackCustomItem(child);
- } else {
- if(!(widget instanceof ccui.Layout)) {
- if(child.getPositionType() === ccui.Widget.POSITION_PERCENT) {
- var position = child.getPositionPercent();
- var anchor = widget.getAnchorPoint();
- child.setPositionPercent(cc.p(position.x + anchor.x, position.y + anchor.y));
- }
- var AnchorPointIn = widget.getAnchorPointInPoints();
- child.setPosition(cc.p(child.getPositionX() + AnchorPointIn.x, child.getPositionY() + AnchorPointIn.y));
- }
- widget.addChild(child);
- }
- }
- }
- }
- };
-
- var getPath = function(res, type, path, cb){
- if(path){
- if(type === 0)
+ var getPath = function (res, type, path, cb) {
+ if (path) {
+ if (type === 0)
cb(res + path, type);
else
cb(path, type);
@@ -213,16 +230,16 @@
/**
* Panel parser (UILayout)
*/
- parser.LayoutAttributes = function(widget, options, resourcePath){
+ parser.LayoutAttributes = function (widget, options, resourcePath) {
var w = 0, h = 0;
var adaptScreen = options["adaptScreen"];
- if (adaptScreen){
+ if (adaptScreen) {
var screenSize = cc.director.getWinSize();
w = screenSize.width;
h = screenSize.height;
- }else{
- w = options["width"];
- h = options["height"];
+ } else {
+ w = options["width"] || 0;
+ h = options["height"] || 0;
}
widget.setSize(cc.size(w, h));
@@ -230,25 +247,25 @@
var backGroundScale9Enable = options["backGroundScale9Enable"];
widget.setBackGroundImageScale9Enabled(backGroundScale9Enable);
- var cr = options["bgColorR"];
- var cg = options["bgColorG"];
- var cb = options["bgColorB"];
+ var cr = options["bgColorR"] || 0;
+ var cg = options["bgColorG"] || 0;
+ var cb = options["bgColorB"] || 0;
- var scr = options["bgStartColorR"];
- var scg = options["bgStartColorG"];
- var scb = options["bgStartColorB"];
+ var scr = isNaN(options["bgStartColorR"]) ? 255 : options["bgStartColorR"];
+ var scg = isNaN(options["bgStartColorG"]) ? 255 : options["bgStartColorG"];
+ var scb = isNaN(options["bgStartColorB"]) ? 255 : options["bgStartColorB"];
- var ecr = options["bgEndColorR"];
- var ecg = options["bgEndColorG"];
- var ecb = options["bgEndColorB"];
+ var ecr = isNaN(options["bgEndColorR"]) ? 255 : options["bgEndColorR"];
+ var ecg = isNaN(options["bgEndColorG"]) ? 255 : options["bgEndColorG"];
+ var ecb = isNaN(options["bgEndColorB"]) ? 255 : options["bgEndColorB"];
- var bgcv1 = options["vectorX"];
- var bgcv2 = options["vectorY"];
+ var bgcv1 = options["vectorX"] || 0;
+ var bgcv2 = options["vectorY"] || 0;
widget.setBackGroundColorVector(cc.p(bgcv1, bgcv2));
- var co = options["bgColorOpacity"];
+ var co = options["bgColorOpacity"] || 0;
- var colorType = options["colorType"];
+ var colorType = options["colorType"] || 0;
widget.setBackGroundColorType(colorType/*ui.LayoutBackGroundColorType(colorType)*/);
widget.setBackGroundColor(cc.color(scr, scg, scb), cc.color(ecr, ecg, ecb));
widget.setBackGroundColor(cc.color(cr, cg, cb));
@@ -256,82 +273,82 @@
var imageFileNameDic = options["backGroundImageData"];
- if(imageFileNameDic){
- getPath(resourcePath, imageFileNameDic["resourceType"], imageFileNameDic["path"], function(path, type){
+ if (imageFileNameDic) {
+ getPath(resourcePath, imageFileNameDic["resourceType"] || 0, imageFileNameDic["path"], function (path, type) {
widget.setBackGroundImage(path, type);
});
}
- if (backGroundScale9Enable){
- var cx = options["capInsetsX"];
- var cy = options["capInsetsY"];
- var cw = options["capInsetsWidth"];
- var ch = options["capInsetsHeight"];
+ if (backGroundScale9Enable) {
+ var cx = options["capInsetsX"] || 0;
+ var cy = options["capInsetsY"] || 0;
+ var cw = isNaN(options["capInsetsWidth"]) ? 1 : options["capInsetsWidth"];
+ var ch = isNaN(options["capInsetsHeight"]) ? 1 : options["capInsetsHeight"];
widget.setBackGroundImageCapInsets(cc.rect(cx, cy, cw, ch));
}
- if (options["layoutType"])
- {
+ if (options["layoutType"]) {
widget.setLayoutType(options["layoutType"]);
}
};
/**
* Button parser (UIButton)
*/
- parser.ButtonAttributes = function(widget, options, resourcePath){
+ parser.ButtonAttributes = function (widget, options, resourcePath) {
var button = widget;
var scale9Enable = options["scale9Enable"];
button.setScale9Enabled(scale9Enable);
var normalDic = options["normalData"];
- getPath(resourcePath, normalDic["resourceType"], normalDic["path"], function(path, type){
+ getPath(resourcePath, normalDic["resourceType"] || 0, normalDic["path"], function (path, type) {
button.loadTextureNormal(path, type);
});
var pressedDic = options["pressedData"];
- getPath(resourcePath, pressedDic["resourceType"], pressedDic["path"], function(path, type){
+ getPath(resourcePath, pressedDic["resourceType"] || 0, pressedDic["path"], function (path, type) {
button.loadTexturePressed(path, type);
});
var disabledDic = options["disabledData"];
- getPath(resourcePath, disabledDic["resourceType"], disabledDic["path"], function(path, type){
+ getPath(resourcePath, disabledDic["resourceType"] || 0, disabledDic["path"], function (path, type) {
button.loadTextureDisabled(path, type);
});
if (scale9Enable) {
- var cx = options["capInsetsX"];
- var cy = options["capInsetsY"];
- var cw = options["capInsetsWidth"];
- var ch = options["capInsetsHeight"];
+ var cx = options["capInsetsX"] || 0;
+ var cy = options["capInsetsY"] || 0;
+ var cw = isNaN(options["capInsetsWidth"]) ? 1 : options["capInsetsWidth"];
+ var ch = isNaN(options["capInsetsHeight"]) ? 1 : options["capInsetsHeight"];
button.setCapInsets(cc.rect(cx, cy, cw, ch));
- var sw = options["scale9Width"];
- var sh = options["scale9Height"];
+ var sw = options["scale9Width"] || 0;
+ var sh = options["scale9Height"] || 0;
if (sw != null && sh != null)
button.setSize(cc.size(sw, sh));
}
- var text = options["text"];
- if (text != null)
+ var text = options["text"] || "";
+ if (text) {
button.setTitleText(text);
- var cr = options["textColorR"];
- var cg = options["textColorG"];
- var cb = options["textColorB"];
- var cri = cr!==null?options["textColorR"]:255;
- var cgi = cg!==null?options["textColorG"]:255;
- var cbi = cb!==null?options["textColorB"]:255;
-
- button.setTitleColor(cc.color(cri,cgi,cbi));
- var fs = options["fontSize"];
- if (fs != null)
- button.setTitleFontSize(options["fontSize"]);
- var fn = options["fontName"];
- if (fn)
- button.setTitleFontName(options["fontName"]);
+ var cr = options["textColorR"];
+ var cg = options["textColorG"];
+ var cb = options["textColorB"];
+ var cri = (cr !== null) ? options["textColorR"] : 255;
+ var cgi = (cg !== null) ? options["textColorG"] : 255;
+ var cbi = (cb !== null) ? options["textColorB"] : 255;
+
+ button.setTitleColor(cc.color(cri, cgi, cbi));
+ var fs = options["fontSize"];
+ if (fs != null)
+ button.setTitleFontSize(options["fontSize"]);
+ var fn = options["fontName"];
+ if (fn)
+ button.setTitleFontName(options["fontName"]);
+ }
};
/**
* CheckBox parser (UICheckBox)
*/
- parser.CheckBoxAttributes = function(widget, options, resourcePath){
+ parser.CheckBoxAttributes = function (widget, options, resourcePath) {
//load background image
var backGroundDic = options["backGroundBoxData"];
- getPath(resourcePath, backGroundDic["resourceType"], backGroundDic["path"], function(path, type){
+ getPath(resourcePath, backGroundDic["resourceType"] || 0, backGroundDic["path"], function (path, type) {
widget.loadTextureBackGround(path, type);
});
@@ -341,13 +358,13 @@
resourcePath,
backGroundSelectedDic["resourceType"] || backGroundDic["resourceType"],
backGroundSelectedDic["path"] || backGroundDic["path"],
- function(path, type){
- widget.loadTextureBackGroundSelected(path, type);
- });
+ function (path, type) {
+ widget.loadTextureBackGroundSelected(path, type);
+ });
//load frontCross image
var frontCrossDic = options["frontCrossData"];
- getPath(resourcePath, frontCrossDic["resourceType"], frontCrossDic["path"], function(path, type){
+ getPath(resourcePath, frontCrossDic["resourceType"] || 0, frontCrossDic["path"], function (path, type) {
widget.loadTextureFrontCross(path, type);
});
@@ -357,13 +374,13 @@
resourcePath,
backGroundDisabledDic["resourceType"] || frontCrossDic["resourceType"],
backGroundDisabledDic["path"] || frontCrossDic["path"],
- function(path, type){
- widget.loadTextureBackGroundDisabled(path, type);
- });
+ function (path, type) {
+ widget.loadTextureBackGroundDisabled(path, type);
+ });
///load frontCrossDisabledData
var frontCrossDisabledDic = options["frontCrossDisabledData"];
- getPath(resourcePath, frontCrossDisabledDic["resourceType"], frontCrossDisabledDic["path"], function(path, type){
+ getPath(resourcePath, frontCrossDisabledDic["resourceType"] || 0, frontCrossDisabledDic["path"], function (path, type) {
widget.loadTextureFrontCrossDisabled(path, type);
});
@@ -373,33 +390,32 @@
/**
* ImageView parser (UIImageView)
*/
- parser.ImageViewAttributes = function(widget, options, resourcePath){
+ parser.ImageViewAttributes = function (widget, options, resourcePath) {
var imageFileNameDic = options["fileNameData"]
- getPath(resourcePath, imageFileNameDic["resourceType"], imageFileNameDic["path"], function(path, type){
+ getPath(resourcePath, imageFileNameDic["resourceType"] || 0, imageFileNameDic["path"], function (path, type) {
widget.loadTexture(path, type);
});
var scale9EnableExist = options["scale9Enable"];
var scale9Enable = false;
- if (scale9EnableExist){
+ if (scale9EnableExist) {
scale9Enable = options["scale9Enable"];
}
widget.setScale9Enabled(scale9Enable);
- if (scale9Enable){
- var sw = options["scale9Width"];
- var sh = options["scale9Height"];
- if (sw && sh)
- {
- var swf = options["scale9Width"];
- var shf = options["scale9Height"];
+ if (scale9Enable) {
+ var sw = options["scale9Width"] || 0;
+ var sh = options["scale9Height"] || 0;
+ if (sw && sh) {
+ var swf = options["scale9Width"] || 0;
+ var shf = options["scale9Height"] || 0;
widget.setSize(cc.size(swf, shf));
}
- var cx = options["capInsetsX"];
- var cy = options["capInsetsY"];
- var cw = options["capInsetsWidth"];
- var ch = options["capInsetsHeight"];
+ var cx = options["capInsetsX"] || 0;
+ var cy = options["capInsetsY"] || 0;
+ var cw = isNaN(options["capInsetsWidth"]) ? 1 : options["capInsetsWidth"];
+ var ch = isNaN(options["capInsetsHeight"]) ? 1 : options["capInsetsHeight"];
widget.setCapInsets(cc.rect(cx, cy, cw, ch));
@@ -408,16 +424,16 @@
/**
* TextAtlas parser (UITextAtlas)
*/
- parser.TextAtlasAttributes = function(widget, options, resourcePath){
+ parser.TextAtlasAttributes = function (widget, options, resourcePath) {
var sv = options["stringValue"];
var cmf = options["charMapFileData"]; // || options["charMapFile"];
var iw = options["itemWidth"];
var ih = options["itemHeight"];
var scm = options["startCharMap"];
- if (sv != null && cmf && iw != null && ih != null && scm != null){
+ if (sv != null && cmf && iw != null && ih != null && scm != null) {
var cmftDic = options["charMapFileData"];
- var cmfType = cmftDic["resourceType"];
- switch (cmfType){
+ var cmfType = cmftDic["resourceType"] || 0;
+ switch (cmfType) {
case 0:
var tp_c = resourcePath;
var cmfPath = cmftDic["path"];
@@ -435,9 +451,9 @@
/**
* TextBMFont parser (UITextBMFont)
*/
- parser.TextBMFontAttributes = function(widget, options, resourcePath){
+ parser.TextBMFontAttributes = function (widget, options, resourcePath) {
var cmftDic = options["fileNameData"];
- var cmfType = cmftDic["resourceType"];
+ var cmfType = cmftDic["resourceType"] || 0;
switch (cmfType) {
case 0:
var tp_c = resourcePath;
@@ -452,88 +468,92 @@
break;
}
- var text = options["text"];
+ var text = options["text"] || "";
widget.setString(text);
};
/**
* Text parser (UIText)
*/
var regTTF = /\.ttf$/;
- parser.TextAttributes = function(widget, options, resourcePath){
+ parser.TextAttributes = function (widget, options, resourcePath) {
var touchScaleChangeAble = options["touchScaleEnable"];
widget.setTouchScaleChangeEnabled(touchScaleChangeAble);
- var text = options["text"];
- widget.setString(text);
+ var text = options["text"] || "";
+ if(text) {
+ widget._setString(text);
+ }
+
var fs = options["fontSize"];
- if (fs != null){
- widget.setFontSize(options["fontSize"]);
+ if (fs != null) {
+ widget._setFontSize(options["fontSize"]);
}
var fn = options["fontName"];
- if (fn != null){
- if(cc.sys.isNative){
- if(regTTF.test(fn)){
+ if (fn != null) {
+ if (cc.sys.isNative) {
+ if (regTTF.test(fn)) {
widget.setFontName(cc.path.join(cc.loader.resPath, resourcePath, fn));
- }else{
+ } else {
widget.setFontName(fn);
}
- }else{
- widget.setFontName(fn.replace(regTTF, ''));
+ } else {
+ widget._setFontName(fn.replace(regTTF, ''));
}
}
- var aw = options["areaWidth"];
- var ah = options["areaHeight"];
- if (aw != null && ah != null){
+ var aw = options["areaWidth"] || 0;
+ var ah = options["areaHeight"] || 0;
+ if (aw && ah) {
var size = cc.size(options["areaWidth"], options["areaHeight"]);
- widget.setTextAreaSize(size);
+ widget._setTextAreaSize(size);
}
- var ha = options["hAlignment"];
- if (ha != null){
- widget.setTextHorizontalAlignment(options["hAlignment"]);
+ var ha = options["hAlignment"] || 0;
+ if (ha != null) {
+ widget._setTextHorizontalAlignment(ha);
}
- var va = options["vAlignment"];
- if (va != null){
- widget.setTextVerticalAlignment(options["vAlignment"]);
+ var va = options["vAlignment"] || 0;
+ if (va != null) {
+ widget._setTextVerticalAlignment(va);
}
+ widget._updateUITextContentSize();
};
/**
* ListView parser (UIListView)
*/
- parser.ListViewAttributes = function(widget, options, resoutcePath){
- parser.ScrollViewAttributes(widget, options,resoutcePath);
- var direction = options["direction"];
+ parser.ListViewAttributes = function (widget, options, resoutcePath) {
+ parser.ScrollViewAttributes(widget, options, resoutcePath);
+ var direction = options["direction"] || 1;
widget.setDirection(direction);
- var gravity = options["gravity"];
+ var gravity = options["gravity"] || 0;
widget.setGravity(gravity);
- var itemMargin = options["itemMargin"];
+ var itemMargin = options["itemMargin"] || 0;
widget.setItemsMargin(itemMargin);
};
/**
* LoadingBar parser (UILoadingBar)
*/
- parser.LoadingBarAttributes = function(widget, options, resourcePath){
+ parser.LoadingBarAttributes = function (widget, options, resourcePath) {
var imageFileNameDic = options["textureData"];
- getPath(resourcePath, imageFileNameDic["resourceType"], imageFileNameDic["path"], function(path, type){
+ getPath(resourcePath, imageFileNameDic["resourceType"] || 0, imageFileNameDic["path"], function (path, type) {
widget.loadTexture(path, type);
});
var scale9Enable = options["scale9Enable"];
widget.setScale9Enabled(scale9Enable);
- if (scale9Enable){
- var cx = options["capInsetsX"];
- var cy = options["capInsetsY"];
- var cw = options["capInsetsWidth"];
- var ch = options["capInsetsHeight"];
+ if (scale9Enable) {
+ var cx = options["capInsetsX"] || 0;
+ var cy = options["capInsetsY"] || 0;
+ var cw = isNaN(options["capInsetsWidth"]) ? 1 : options["capInsetsWidth"];
+ var ch = isNaN(options["capInsetsHeight"]) ? 1 : options["capInsetsHeight"];
widget.setCapInsets(cc.rect(cx, cy, cw, ch));
- var width = options["width"];
- var height = options["height"];
+ var width = options["width"] || 0;
+ var height = options["height"] || 0;
widget.setSize(cc.size(width, height));
}
- widget.setDirection(options["direction"]);
- widget.setPercent(options["percent"]);
+ widget.setDirection(options["direction"] || 0);
+ widget.setPercent(options["percent"] || 0);
};
/**
* PageView parser (UIPageView)
@@ -542,20 +562,20 @@
/**
* ScrollView parser (UIScrollView)
*/
- parser.ScrollViewAttributes = function(widget, options, resoutcePath){
- parser.LayoutAttributes(widget, options,resoutcePath);
- var innerWidth = options["innerWidth"]!=null ? options["innerWidth"] : 200;
- var innerHeight = options["innerHeight"]!=null ? options["innerHeight"] : 200;
+ parser.ScrollViewAttributes = function (widget, options, resoutcePath) {
+ parser.LayoutAttributes(widget, options, resoutcePath);
+ var innerWidth = options["innerWidth"] != null ? options["innerWidth"] : 200;
+ var innerHeight = options["innerHeight"] != null ? options["innerHeight"] : 200;
widget.setInnerContainerSize(cc.size(innerWidth, innerHeight));
- var direction = options["direction"]!=null ? options["direction"] : 1;
+ var direction = options["direction"] != null ? options["direction"] : 1;
widget.setDirection(direction);
widget.setBounceEnabled(options["bounceEnable"]);
};
/**
* Slider parser (UISlider)
*/
- parser.SliderAttributes = function(widget, options, resourcePath){
+ parser.SliderAttributes = function (widget, options, resourcePath) {
var slider = widget;
@@ -565,24 +585,24 @@
var barLength = options["length"];
var imageFileNameDic = options["barFileNameData"];
- var imageFileType = imageFileNameDic["resourceType"];
+ var imageFileType = imageFileNameDic["resourceType"] || 0;
var imageFileName = imageFileNameDic["path"];
- if(bt != null){
- if(barTextureScale9Enable){
- getPath(resourcePath, imageFileType, imageFileName, function(path, type){
+ if (bt != null) {
+ if (barTextureScale9Enable) {
+ getPath(resourcePath, imageFileType, imageFileName, function (path, type) {
slider.loadBarTexture(path, type);
});
slider.setSize(cc.size(barLength, slider.getContentSize().height));
}
- }else{
- getPath(resourcePath, imageFileType, imageFileName, function(path, type){
+ } else {
+ getPath(resourcePath, imageFileType, imageFileName, function (path, type) {
slider.loadBarTexture(path, type);
});
}
var normalDic = options["ballNormalData"];
- getPath(resourcePath, normalDic["resourceType"], normalDic["path"], function(path, type){
+ getPath(resourcePath, normalDic["resourceType"] || 0, normalDic["path"], function (path, type) {
slider.loadSlidBallTextureNormal(path, type);
});
@@ -591,115 +611,100 @@
resourcePath,
pressedDic["resourceType"] || normalDic["resourceType"],
pressedDic["path"] || normalDic["path"],
- function(path, type){
+ function (path, type) {
slider.loadSlidBallTexturePressed(path, type);
- });
+ });
var disabledDic = options["ballDisabledData"];
- getPath(resourcePath, disabledDic["resourceType"], disabledDic["path"], function(path, type){
+ getPath(resourcePath, disabledDic["resourceType"] || 0, disabledDic["path"], function (path, type) {
slider.loadSlidBallTextureDisabled(path, type);
});
var progressBarDic = options["progressBarData"];
- getPath(resourcePath, progressBarDic["resourceType"], progressBarDic["path"], function(path, type){
+ getPath(resourcePath, progressBarDic["resourceType"] || 0, progressBarDic["path"], function (path, type) {
slider.loadProgressBarTexture(path, type);
});
};
/**
* TextField parser (UITextField)
*/
- parser.TextFieldAttributes = function(widget, options, resourcePath){
- var ph = options["placeHolder"];
- if(ph)
+ parser.TextFieldAttributes = function (widget, options, resourcePath) {
+ var ph = options["placeHolder"] || "";
+ if (ph)
widget.setPlaceHolder(ph);
- widget.setString(options["text"]||"");
+ widget.setString(options["text"] || "");
var fs = options["fontSize"];
- if(fs)
+ if (fs)
widget.setFontSize(fs);
var fn = options["fontName"];
- if (fn != null){
- if(cc.sys.isNative){
- if(regTTF.test(fn)){
+ if (fn != null) {
+ if (cc.sys.isNative) {
+ if (regTTF.test(fn)) {
widget.setFontName(cc.path.join(cc.loader.resPath, resourcePath, fn));
- }else{
+ } else {
widget.setFontName(fn);
}
- }else{
+ } else {
widget.setFontName(fn.replace(regTTF, ''));
}
}
- var tsw = options["touchSizeWidth"];
- var tsh = options["touchSizeHeight"];
- if(tsw!=null && tsh!=null)
+ var tsw = options["touchSizeWidth"] || 0;
+ var tsh = options["touchSizeHeight"] || 0;
+ if (tsw != null && tsh != null)
widget.setTouchSize(tsw, tsh);
- var dw = options["width"];
- var dh = options["height"];
- if(dw > 0 || dh > 0){
+ var dw = options["width"] || 0;
+ var dh = options["height"] || 0;
+ if (dw > 0 || dh > 0) {
//textField.setSize(cc.size(dw, dh));
}
var maxLengthEnable = options["maxLengthEnable"];
widget.setMaxLengthEnabled(maxLengthEnable);
- if(maxLengthEnable){
+ if (maxLengthEnable) {
var maxLength = options["maxLength"];
widget.setMaxLength(maxLength);
}
var passwordEnable = options["passwordEnable"];
widget.setPasswordEnabled(passwordEnable);
- if(passwordEnable)
+ if (passwordEnable)
widget.setPasswordStyleText(options["passwordStyleText"]);
- var aw = options["areaWidth"];
- var ah = options["areaHeight"];
- if(aw && ah){
+ var aw = options["areaWidth"] || 0;
+ var ah = options["areaHeight"] || 0;
+ if (aw && ah) {
var size = cc.size(aw, ah);
widget.setTextAreaSize(size);
}
- var ha = options["hAlignment"];
- if(ha)
+ var ha = options["hAlignment"] || 0;
+ if (ha)
widget.setTextHorizontalAlignment(ha);
- var va = options["vAlignment"];
- if(va)
+ var va = options["vAlignment"] || 0;
+ if (va)
widget.setTextVerticalAlignment(va);
- var r = options["colorR"];
- var g = options["colorG"];
- var b = options["colorB"];
- if (r !== undefined && g !== undefined && b !== undefined) {
- widget.setTextColor(cc.color(r, g, b));
- }
+ var r = isNaN(options["colorR"]) ? 255 : options["colorR"];
+ var g = isNaN(options["colorG"]) ? 255 : options["colorG"];
+ var b = isNaN(options["colorB"]) ? 255 : options["colorB"];
+ widget.setTextColor(cc.color(r, g, b));
};
- var register = [
- {name: "Panel", object: ccui.Layout, handle: parser.LayoutAttributes},
- {name: "Button", object: ccui.Button, handle: parser.ButtonAttributes},
- {name: "CheckBox", object: ccui.CheckBox, handle: parser.CheckBoxAttributes},
- {name: "ImageView", object: ccui.ImageView, handle: parser.ImageViewAttributes},
- {name: "LabelAtlas", object: ccui.TextAtlas, handle: parser.TextAtlasAttributes},
- {name: "LabelBMFont", object: ccui.TextBMFont, handle: parser.TextBMFontAttributes},
- {name: "Label", object: ccui.Text, handle: parser.TextAttributes},
- {name: "ListView", object: ccui.ListView, handle: parser.ListViewAttributes},
- {name: "LoadingBar", object: ccui.LoadingBar, handle: parser.LoadingBarAttributes},
- {name: "PageView", object: ccui.PageView, handle: parser.PageViewAttributes},
- {name: "ScrollView", object: ccui.ScrollView, handle: parser.ScrollViewAttributes},
- {name: "Slider", object: ccui.Slider, handle: parser.SliderAttributes},
- {name: "TextField", object: ccui.TextField, handle: parser.TextFieldAttributes}
- ];
-
- register.forEach(function(item){
- parser.registerParser(item.name, function(options, resourcePath){
- var widget = new item.object;
- var uiOptions = options["options"];
- parser.generalAttributes(widget, uiOptions);
- item.handle(widget, uiOptions, resourcePath);
- parser.colorAttributes(widget, uiOptions);
- parser.anchorPointAttributes(widget, uiOptions);
- parser.parseChild.call(this, widget, options, resourcePath);
- return widget;
- });
- });
+ parser.parsers = {
+ "Panel": {object: ccui.Layout, handle: parser.LayoutAttributes},
+ "Button": {object: ccui.Button, handle: parser.ButtonAttributes},
+ "CheckBox": {object: ccui.CheckBox, handle: parser.CheckBoxAttributes},
+ "ImageView": {object: ccui.ImageView, handle: parser.ImageViewAttributes},
+ "LabelAtlas": {object: ccui.TextAtlas, handle: parser.TextAtlasAttributes},
+ "LabelBMFont": {object: ccui.TextBMFont, handle: parser.TextBMFontAttributes},
+ "Label": {object: ccui.Text, handle: parser.TextAttributes},
+ "ListView": {object: ccui.ListView, handle: parser.ListViewAttributes},
+ "LoadingBar": {object: ccui.LoadingBar, handle: parser.LoadingBarAttributes},
+ "PageView": {object: ccui.PageView, handle: parser.PageViewAttributes},
+ "ScrollView": {object: ccui.ScrollView, handle: parser.ScrollViewAttributes},
+ "Slider": {object: ccui.Slider, handle: parser.SliderAttributes},
+ "TextField": {object: ccui.TextField, handle: parser.TextFieldAttributes}
+ };
load.registerParser("ccui", "*", parser);
-})(ccs._load, ccs._parser);
\ No newline at end of file
+})(ccs._load, ccs._parser);
diff --git a/extensions/cocostudio/timeline/ActionTimeline.js b/extensions/cocostudio/timeline/ActionTimeline.js
index cdf57b58dc..fd899ae120 100644
--- a/extensions/cocostudio/timeline/ActionTimeline.js
+++ b/extensions/cocostudio/timeline/ActionTimeline.js
@@ -34,11 +34,11 @@ ccs.ActionTimelineData = ccs.Class.extend({
_actionTag: 0,
- ctor: function(actionTag){
+ ctor: function (actionTag) {
this._init(actionTag);
},
- _init: function(actionTag){
+ _init: function (actionTag) {
this._actionTag = actionTag;
return true;
},
@@ -47,20 +47,20 @@ ccs.ActionTimelineData = ccs.Class.extend({
* Set the action tag.
* @param {number} actionTag
*/
- setActionTag: function(actionTag){
+ setActionTag: function (actionTag) {
this._actionTag = actionTag;
},
/**
* Gets the action tag.
*/
- getActionTag: function(){
+ getActionTag: function () {
return this._actionTag;
}
});
-ccs.AnimationInfo = function(name, start, end){
+ccs.AnimationInfo = function (name, start, end) {
this.name = name;
this.startIndex = start;
this.endIndex = end;
@@ -110,7 +110,7 @@ ccs.ComExtensionData.create = function(){
* @param actionTag
* @returns {ccs.ActionTimelineData}
*/
-ccs.ActionTimelineData.create = function(actionTag){
+ccs.ActionTimelineData.create = function (actionTag) {
return new ccs.ActionTimelineData(actionTag);
};
@@ -130,7 +130,7 @@ ccs.ActionTimeline = cc.Action.extend({
_duration: 0,
_time: null,
_timeSpeed: 1,
- _frameInternal: 1/60,
+ _frameInternal: 1 / 60,
_playing: false,
_currentFrame: 0,
_startFrame: 0,
@@ -140,7 +140,7 @@ ccs.ActionTimeline = cc.Action.extend({
_animationInfos: null,
_lastFrameListener: null,
- ctor: function(){
+ ctor: function () {
cc.Action.prototype.ctor.call(this);
this._timelineMap = {};
this._timelineList = [];
@@ -148,29 +148,28 @@ ccs.ActionTimeline = cc.Action.extend({
this.init();
},
- _gotoFrame: function(frameIndex){
+ _gotoFrame: function (frameIndex) {
var size = this._timelineList.length;
- for(var i = 0; i < size; i++)
- {
+ for (var i = 0; i < size; i++) {
this._timelineList[i]._gotoFrame(frameIndex);
}
},
- _stepToFrame: function(frameIndex){
+ _stepToFrame: function (frameIndex) {
var size = this._timelineList.length;
- for(var i = 0; i < size; i++){
+ for (var i = 0; i < size; i++) {
this._timelineList[i]._stepToFrame(frameIndex);
}
},
//emit frame event, call it when enter a frame
- _emitFrameEvent: function(frame){
- if(this._frameEventListener){
+ _emitFrameEvent: function (frame) {
+ if (this._frameEventListener) {
this._frameEventListener(frame);
}
},
- init: function(){
+ init: function () {
return true;
},
@@ -181,23 +180,23 @@ ccs.ActionTimeline = cc.Action.extend({
* @param [currentFrameIndex=] set current frame index.
* @param [loop=] Whether or not the animation need loop.
*/
- gotoFrameAndPlay: function(startIndex, endIndex, currentFrameIndex, loop){
+ gotoFrameAndPlay: function (startIndex, endIndex, currentFrameIndex, loop) {
//Consolidation parameters
var i = 0,
argLen = arguments.length;
var num = [],
bool;
- for(i; i= this._startFrame && frameIndex <= this._endFrame){
+ setCurrentFrame: function (frameIndex) {
+ if (frameIndex >= this._startFrame && frameIndex <= this._endFrame) {
this._currentFrame = frameIndex;
this._time = this._currentFrame * this._frameInternal;
- }else{
+ } else {
cc.log("frame index is not between start frame and end frame");
}
@@ -309,7 +308,7 @@ ccs.ActionTimeline = cc.Action.extend({
* Get current frame.
* @returns {number}
*/
- getCurrentFrame: function(){
+ getCurrentFrame: function () {
return this._currentFrame;
},
@@ -317,7 +316,7 @@ ccs.ActionTimeline = cc.Action.extend({
* add Timeline to ActionTimeline
* @param {ccs.Timeline} timeline
*/
- addTimeline: function(timeline){
+ addTimeline: function (timeline) {
var tag = timeline.getActionTag();
if (!this._timelineMap[tag]) {
this._timelineMap[tag] = [];
@@ -335,13 +334,13 @@ ccs.ActionTimeline = cc.Action.extend({
* remove Timeline to ActionTimeline
* @param {ccs.Timeline} timeline
*/
- removeTimeline: function(timeline){
+ removeTimeline: function (timeline) {
var tag = timeline.getActionTag();
if (this._timelineMap[tag]) {
- if(this._timelineMap[tag].some(function(item){
- if(item === timeline)
- return true;
- })) {
+ if (this._timelineMap[tag].some(function (item) {
+ if (item === timeline)
+ return true;
+ })) {
cc.arrayRemoveObject(this._timelineMap[tag], timeline);
cc.arrayRemoveObject(this._timelineList, timeline);
timeline.setActionTimeline(null);
@@ -353,7 +352,7 @@ ccs.ActionTimeline = cc.Action.extend({
* Gets the timeline list
* @returns {array | null}
*/
- getTimelines: function(){
+ getTimelines: function () {
return this._timelineList;
},
@@ -361,14 +360,14 @@ ccs.ActionTimeline = cc.Action.extend({
* Set the Frame event
* @param {function} listener
*/
- setFrameEventCallFunc: function(listener){
+ setFrameEventCallFunc: function (listener) {
this._frameEventListener = listener;
},
/**
* remove event
*/
- clearFrameEventCallFunc: function(){
+ clearFrameEventCallFunc: function () {
this._frameEventListener = null;
},
@@ -376,15 +375,14 @@ ccs.ActionTimeline = cc.Action.extend({
* Clone this timeline
* @returns {ccs.ActionTimeline}
*/
- clone: function(){
+ clone: function () {
var newAction = new ccs.ActionTimeline();
newAction.setDuration(this._duration);
newAction.setTimeSpeed(this._timeSpeed);
- for (var a in this._timelineMap){
+ for (var a in this._timelineMap) {
var timelines = this._timelineMap[a];
- for(var b in timelines)
- {
+ for (var b in timelines) {
var timeline = timelines[b];
var newTimeline = timeline.clone();
newAction.addTimeline(newTimeline);
@@ -399,7 +397,7 @@ ccs.ActionTimeline = cc.Action.extend({
* Reverse is not defined;
* @returns {null}
*/
- reverse: function(){
+ reverse: function () {
return null;
},
@@ -407,42 +405,40 @@ ccs.ActionTimeline = cc.Action.extend({
* Stepping of this time line.
* @param {number} delta
*/
- step: function(delta){
- if (!this._playing || this._timelineMap.length === 0 || this._duration === 0)
- {
+ step: function (delta) {
+ if (!this._playing || this._timelineMap.length === 0 || this._duration === 0) {
return;
}
this._time += delta * this._timeSpeed;
var endoffset = this._time - this._endFrame * this._frameInternal;
- if(endoffset < this._frameInternal){
+ if (endoffset < this._frameInternal) {
this._currentFrame = Math.floor(this._time / this._frameInternal);
this._stepToFrame(this._currentFrame);
- if(endoffset >= 0 && this._lastFrameListener)
+ if (endoffset >= 0 && this._lastFrameListener)
this._lastFrameListener();
- }else{
+ } else {
this._playing = this._loop;
- if(!this._playing){
+ if (!this._playing) {
this._time = this._endFrame * this._frameInternal;
- if (this._currentFrame != this._endFrame){
+ if (this._currentFrame != this._endFrame) {
this._currentFrame = this._endFrame;
this._stepToFrame(this._currentFrame);
- if(this._lastFrameListener)
+ if (this._lastFrameListener)
this._lastFrameListener();
}
- }else
+ } else
this.gotoFrameAndPlay(this._startFrame, this._endFrame, this._loop);
}
},
- _foreachNodeDescendant: function(parent, callback){
+ _foreachNodeDescendant: function (parent, callback) {
callback(parent);
var children = parent.getChildren();
- for (var i=0; i 0){
+ while (boneStack.length > 0) {
var top = boneStack.pop();
var topCmd = top._renderCmd;
topCmd._syncStatus(topCmd.getParentRenderCmd());
@@ -205,7 +205,7 @@ ccs.SkeletonNode = (function(){
var topChildren = top.getChildBones();
- for (var childbone, i=0; i= this._frames[0].getFrameIndex())
+ do {
+ if (frameIndex < this._frames[0].getFrameIndex()) {
+ if (this._currentKeyFrameIndex >= this._frames[0].getFrameIndex())
needEnterFrame = true;
this._fromIndex = 0;
@@ -211,7 +209,7 @@ ccs.Timeline = ccs.Class.extend({
this._currentKeyFrameIndex = 0;
this._betweenDuration = this._frames[0].getFrameIndex();
break;
- }else if(frameIndex >= this._frames[length - 1].getFrameIndex()){
+ } else if (frameIndex >= this._frames[length - 1].getFrameIndex()) {
this._fromIndex = length - 1;
this._toIndex = 0;
@@ -225,14 +223,13 @@ ccs.Timeline = ccs.Class.extend({
var low = 0,
high = length - 1,
mid = 0;
- while(low <= high){
- mid = Math.ceil(( low + high )/2);
- if(frameIndex >= this._frames[mid].getFrameIndex() && frameIndex < this._frames[mid + 1].getFrameIndex())
- {
+ while (low <= high) {
+ mid = Math.ceil(( low + high ) / 2);
+ if (frameIndex >= this._frames[mid].getFrameIndex() && frameIndex < this._frames[mid + 1].getFrameIndex()) {
target = mid;
break;
}
- if(this._frames[mid].getFrameIndex()>frameIndex)
+ if (this._frames[mid].getFrameIndex() > frameIndex)
high = mid - 1;
else
low = mid + 1;
@@ -240,37 +237,36 @@ ccs.Timeline = ccs.Class.extend({
this._fromIndex = target;
- if(length > 1)
+ if (length > 1)
this._toIndex = (target + 1) | 0;
else
this._toIndex = (target) | 0;
from = this._frames[this._fromIndex];
- to = this._frames[this._toIndex];
+ to = this._frames[this._toIndex];
from = this._frames[target];
- to = this._frames[target+1];
+ to = this._frames[target + 1];
- if(target === 0 && this._currentKeyFrameIndex < from.getFrameIndex())
+ if (target === 0 && this._currentKeyFrameIndex < from.getFrameIndex())
needEnterFrame = true;
this._currentKeyFrameIndex = from.getFrameIndex();
this._betweenDuration = to.getFrameIndex() - from.getFrameIndex();
} while (0);
- if(needEnterFrame || this._currentKeyFrame != from) {
+ if (needEnterFrame || this._currentKeyFrame != from) {
this._currentKeyFrame = from;
this._currentKeyFrame.onEnter(to);
}
},
- _updateCurrentKeyFrame: function(frameIndex){
- if(frameIndex > 60)
+ _updateCurrentKeyFrame: function (frameIndex) {
+ if (frameIndex > 60)
var a = 0;
//! If play to current frame's front or back, then find current frame again
- if (frameIndex < this._currentKeyFrameIndex || frameIndex >= this._currentKeyFrameIndex + this._betweenDuration)
- {
+ if (frameIndex < this._currentKeyFrameIndex || frameIndex >= this._currentKeyFrameIndex + this._betweenDuration) {
var from = null;
var to = null;
@@ -278,29 +274,26 @@ ccs.Timeline = ccs.Class.extend({
{
var length = this._frames.length;
- if (frameIndex < this._frames[0].getFrameIndex())
- {
+ if (frameIndex < this._frames[0].getFrameIndex()) {
from = to = this._frames[0];
this._currentKeyFrameIndex = 0;
this._betweenDuration = this._frames[0].getFrameIndex();
break;
}
- else if(frameIndex >= this._frames[length - 1].getFrameIndex())
- {
+ else if (frameIndex >= this._frames[length - 1].getFrameIndex()) {
var lastFrameIndex = this._frames[length - 1].getFrameIndex();
- if(this._currentKeyFrameIndex >= lastFrameIndex)
+ if (this._currentKeyFrameIndex >= lastFrameIndex)
return;
frameIndex = lastFrameIndex;
}
- do{
+ do {
this._fromIndex = this._toIndex;
from = this._frames[this._fromIndex];
- this._currentKeyFrameIndex = from.getFrameIndex();
+ this._currentKeyFrameIndex = from.getFrameIndex();
this._toIndex = this._fromIndex + 1;
- if (this._toIndex >= length)
- {
+ if (this._toIndex >= length) {
this._toIndex = 0;
}
@@ -308,11 +301,11 @@ ccs.Timeline = ccs.Class.extend({
if (frameIndex === from.getFrameIndex())
break;
- if(frameIndex > from.getFrameIndex() && frameIndex < to.getFrameIndex())
+ if (frameIndex > from.getFrameIndex() && frameIndex < to.getFrameIndex())
break;
- if(from.isEnterWhenPassed())
+ if (from.isEnterWhenPassed())
from.onEnter(to);
- }while (true);
+ } while (true);
this._betweenDuration = to.getFrameIndex() - from.getFrameIndex();
@@ -331,6 +324,6 @@ ccs.Timeline = ccs.Class.extend({
* @deprecated v3.0, please use new ccs.Timeline() instead.
* @returns {ccs.Timeline}
*/
-ccs.Timeline.create = function(){
+ccs.Timeline.create = function () {
return new ccs.Timeline();
-};
\ No newline at end of file
+};
diff --git a/extensions/editbox/CCEditBox.js b/extensions/editbox/CCEditBox.js
index 5d3f23a25a..758f04934f 100644
--- a/extensions/editbox/CCEditBox.js
+++ b/extensions/editbox/CCEditBox.js
@@ -208,7 +208,7 @@ cc.EditBoxDelegate = cc.Class.extend({
cc.EditBox = cc.Node.extend({
_backgroundSprite: null,
_delegate: null,
- _editBoxInputMode: cc.EDITBOX_INPUT_MODE_SINGLELINE,
+ _editBoxInputMode: cc.EDITBOX_INPUT_MODE_ANY,
_editBoxInputFlag: cc.EDITBOX_INPUT_FLAG_SENSITIVE,
_keyboardReturnType: cc.KEYBOARD_RETURNTYPE_DEFAULT,
_maxLength: 50,
@@ -267,39 +267,39 @@ cc.EditBox = cc.Node.extend({
this._updateEditBoxSize(width, height);
},
- setVisible: function ( visible ) {
+ setVisible: function (visible) {
cc.Node.prototype.setVisible.call(this, visible);
this._renderCmd.updateVisibility();
},
createDomElementIfNeeded: function () {
- if(!this._renderCmd._edTxt) {
+ if (!this._renderCmd._edTxt) {
this._renderCmd.createNativeControl();
}
},
- setTabIndex: function(index) {
- if(this._renderCmd._edTxt) {
+ setTabIndex: function (index) {
+ if (this._renderCmd._edTxt) {
this._renderCmd._edTxt.tabIndex = index;
}
},
- getTabIndex: function() {
- if(this._renderCmd._edTxt) {
+ getTabIndex: function () {
+ if (this._renderCmd._edTxt) {
return this._renderCmd._edTxt.tabIndex;
}
cc.warn('The dom control is not created!');
return -1;
},
- setFocus: function() {
- if(this._renderCmd._edTxt) {
+ setFocus: function () {
+ if (this._renderCmd._edTxt) {
this._renderCmd._edTxt.focus();
}
},
- isFocused: function() {
- if(this._renderCmd._edTxt) {
+ isFocused: function () {
+ if (this._renderCmd._edTxt) {
return document.activeElement === this._renderCmd._edTxt;
}
cc.warn('The dom control is not created!');
@@ -307,7 +307,7 @@ cc.EditBox = cc.Node.extend({
},
stayOnTop: function (flag) {
- if(this._alwaysOnTop === flag) return;
+ if (this._alwaysOnTop === flag) return;
this._alwaysOnTop = flag;
this._renderCmd.stayOnTop(this._alwaysOnTop);
@@ -321,9 +321,9 @@ cc.EditBox = cc.Node.extend({
_onTouchBegan: function (touch) {
var touchPoint = touch.getLocation();
- var bb = cc.rect(0,0, this._contentSize.width, this._contentSize.height);
+ var bb = cc.rect(0, 0, this._contentSize.width, this._contentSize.height);
var hitted = cc.rectContainsPoint(bb, this.convertToNodeSpace(touchPoint));
- if(hitted) {
+ if (hitted) {
return true;
}
else {
@@ -337,12 +337,12 @@ cc.EditBox = cc.Node.extend({
},
_updateBackgroundSpriteSize: function (width, height) {
- if(this._backgroundSprite) {
+ if (this._backgroundSprite) {
this._backgroundSprite.setContentSize(width, height);
}
},
- _updateEditBoxSize: function(size, height) {
+ _updateEditBoxSize: function (size, height) {
var newWidth = (typeof size.width === 'number') ? size.width : size;
var newHeight = (typeof size.height === 'number') ? size.height : height;
@@ -367,7 +367,7 @@ cc.EditBox = cc.Node.extend({
this._renderCmd._setFont(fontStyle);
},
- getBackgroundSprite: function() {
+ getBackgroundSprite: function () {
return this._backgroundSprite;
},
@@ -415,7 +415,7 @@ cc.EditBox = cc.Node.extend({
*/
setMaxLength: function (maxLength) {
if (!isNaN(maxLength)) {
- if(maxLength < 0) {
+ if (maxLength < 0) {
//we can't set Number.MAX_VALUE to input's maxLength property
//so we use a magic number here, it should works at most use cases.
maxLength = 65535;
@@ -515,13 +515,13 @@ cc.EditBox = cc.Node.extend({
* @param {cc.Color | cc.Scale9Sprite} normal9SpriteBg
*/
initWithSizeAndBackgroundSprite: function (size, normal9SpriteBg) {
- if(this._backgroundSprite) {
+ if (this._backgroundSprite) {
this._backgroundSprite.removeFromParent();
}
this._backgroundSprite = normal9SpriteBg;
this.setContentSize(size);
- if(this._backgroundSprite && !this._backgroundSprite.parent) {
+ if (this._backgroundSprite && !this._backgroundSprite.parent) {
this._backgroundSprite.setAnchorPoint(cc.p(0, 0));
this.addChild(this._backgroundSprite);
@@ -662,7 +662,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
if (cc.sys.OS_ANDROID === cc.sys.os
&& (cc.sys.browserType === cc.sys.BROWSER_TYPE_SOUGOU
- || cc.sys.browserType === cc.sys.BROWSER_TYPE_360)) {
+ || cc.sys.browserType === cc.sys.BROWSER_TYPE_360)) {
editbox._polyfill.zoomInvalid = true;
}
})(cc.EditBox);
@@ -673,31 +673,33 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
var TIMER_NAME = 400;
var LEFT_PADDING = 2;
- function scrollWindowUp (editBox) {
- if (cc.sys.os === cc.sys.OS_IOS && cc.sys.osMainVersion === 9) {
- var worldPos = editBox.convertToWorldSpace(cc.p(0,0));
- var windowHeight = cc.visibleRect.height;
- var windowWidth = cc.visibleRect.width;
- var factor = 0.5;
- if(windowWidth > windowHeight) {
- factor = 0.7;
- }
- setTimeout(function() {
- if(window.scrollY < SCROLLY && worldPos.y < windowHeight * factor) {
- var scrollOffset = windowHeight * factor - worldPos.y - window.scrollY;
- if (scrollOffset < 35) scrollOffset = 35;
- if (scrollOffset > 320) scrollOffset = 320;
- window.scrollTo(0, scrollOffset);
- }
- }, TIMER_NAME);
+ function scrollWindowUp(editBox) {
+ // if (cc.sys.os === cc.sys.OS_IOS && cc.sys.osMainVersion === 9) {
+ var worldPos = editBox.convertToWorldSpace(cc.p(0, 0));
+ var windowHeight = cc.visibleRect.height;
+ var windowWidth = cc.visibleRect.width;
+ var factor = 0.5;
+ if (windowWidth > windowHeight) {
+ factor = 0.7;
}
+ setTimeout(function () {
+ if (window.scrollY < SCROLLY && worldPos.y < windowHeight * factor) {
+ var scrollOffset = windowHeight * factor - worldPos.y - window.scrollY;
+ if (scrollOffset < 35) scrollOffset = 35;
+ if (scrollOffset > 320) scrollOffset = 320;
+ window.scrollTo(0, scrollOffset);
+ }
+ }, TIMER_NAME);
+ // }
}
- function capitalize (string) {
- return string.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
+ function capitalize(string) {
+ return string.replace(/(?:^|\s)\S/g, function (a) {
+ return a.toUpperCase();
+ });
}
- function capitalizeFirstLetter (string) {
+ function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
@@ -718,7 +720,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
var container = cc.game.container;
var a = t.a * scaleX, b = t.b, c = t.c, d = t.d * scaleY;
- var offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft);
+ var offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft);
var offsetY = container && container.style.paddingBottom && parseInt(container.style.paddingBottom);
var tx = t.tx * scaleX + offsetX, ty = t.ty * scaleY + offsetY;
@@ -746,18 +748,18 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
} else {
editBox.style.visibility = 'hidden';
var hasChild = false;
- if('contains' in cc.game.container) {
+ if ('contains' in cc.game.container) {
hasChild = cc.game.container.contains(editBox);
- }else {
+ } else {
hasChild = cc.game.container.compareDocumentPosition(editBox) % 16;
}
- if(hasChild)
+ if (hasChild)
cc.game.container.removeChild(editBox);
}
};
proto.stayOnTop = function (flag) {
- if(flag) {
+ if (flag) {
this._removeLabels();
this._edTxt.style.display = '';
} else {
@@ -812,7 +814,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
if (e.keyCode === cc.KEY.enter) {
e.stopPropagation();
e.preventDefault();
- if(this.value === '') {
+ if (this.value === '') {
this.style.fontSize = editBox._placeholderFontSize + 'px';
this.style.color = cc.colorToHex(editBox._placeholderColor);
}
@@ -833,7 +835,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
this.style.color = cc.colorToHex(editBox._textColor);
thisPointer._hiddenLabels();
- if(cc.view.isAutoFullScreenEnabled()) {
+ if (cc.view.isAutoFullScreenEnabled()) {
thisPointer.__fullscreen = true;
cc.view.enableAutoFullScreen(false);
cc.screen.exitFullScreen();
@@ -853,7 +855,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
var editBox = thisPointer._editBox;
editBox._text = this.value;
thisPointer._updateEditBoxContentStyle();
- if(thisPointer.__fullscreen) {
+ if (thisPointer.__fullscreen) {
cc.view.enableAutoFullScreen(true);
}
if (this.__autoResize) {
@@ -904,7 +906,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
var editBox = thisPointer._editBox;
if (editBox._delegate && editBox._delegate.editBoxTextChanged) {
- if(editBox._text.toLowerCase() !== this.value.toLowerCase()) {
+ if (editBox._text.toLowerCase() !== this.value.toLowerCase()) {
editBox._text = this.value;
thisPointer._updateEditBoxContentStyle();
editBox._delegate.editBoxTextChanged(editBox, editBox._text);
@@ -918,13 +920,15 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
this.style.fontSize = thisPointer._edFontSize + 'px';
this.style.color = cc.colorToHex(editBox._textColor);
- if(cc.view.isAutoFullScreenEnabled()) {
+ if (cc.view.isAutoFullScreenEnabled()) {
thisPointer.__fullscreen = true;
cc.view.enableAutoFullScreen(false);
cc.screen.exitFullScreen();
} else {
thisPointer.__fullscreen = false;
}
+ this.__autoResize = cc.view.__resizeWithBrowserSize;
+ cc.view.resizeWithBrowserSize(false);
scrollWindowUp(editBox);
@@ -949,9 +953,12 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
editBox._text = this.value;
thisPointer._updateEditBoxContentStyle();
window.scrollY = 0;
- if(thisPointer.__fullscreen) {
+ if (thisPointer.__fullscreen) {
cc.view.enableAutoFullScreen(true);
}
+ if (this.__autoResize) {
+ cc.view.resizeWithBrowserSize(true);
+ }
if (editBox._delegate && editBox._delegate.editBoxEditingDidEnded) {
editBox._delegate.editBoxEditingDidEnded(editBox);
@@ -970,14 +977,14 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
proto._createLabels = function () {
var editBoxSize = this._editBox.getContentSize();
- if(!this._textLabel) {
+ if (!this._textLabel) {
this._textLabel = new cc.LabelTTF();
this._textLabel.setVisible(false);
this._textLabel.setAnchorPoint(cc.p(0, 1));
this._editBox.addChild(this._textLabel, 100);
}
- if(!this._placeholderLabel) {
+ if (!this._placeholderLabel) {
this._placeholderLabel = new cc.LabelTTF();
this._placeholderLabel.setAnchorPoint(cc.p(0, 1));
this._placeholderLabel.setColor(cc.color.GRAY);
@@ -988,14 +995,14 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
};
proto._removeLabels = function () {
- if(!this._textLabel) return;
+ if (!this._textLabel) return;
this._editBox.removeChild(this._textLabel);
this._textLabel = null;
};
proto._updateLabelPosition = function (editBoxSize) {
- if(!this._textLabel || !this._placeholderLabel) return;
+ if (!this._textLabel || !this._placeholderLabel) return;
var labelContentSize = cc.size(editBoxSize.width - LEFT_PADDING, editBoxSize.height);
this._textLabel.setContentSize(labelContentSize);
@@ -1003,7 +1010,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
this._placeholderLabel.setLineHeight(editBoxSize.height);
var placeholderLabelSize = this._placeholderLabel.getContentSize();
- if (this._editBox._editBoxInputMode === cc.EDITBOX_INPUT_MODE_ANY){
+ if (this._editBox._editBoxInputMode === cc.EDITBOX_INPUT_MODE_ANY) {
this._textLabel.setPosition(LEFT_PADDING, editBoxSize.height);
this._placeholderLabel.setPosition(LEFT_PADDING, editBoxSize.height);
this._placeholderLabel.setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_TOP);
@@ -1021,22 +1028,22 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
};
proto.setLineHeight = function (lineHeight) {
- if(this._textLabel) {
+ if (this._textLabel) {
this._textLabel.setLineHeight(lineHeight);
}
};
proto._hiddenLabels = function () {
- if(this._textLabel) {
+ if (this._textLabel) {
this._textLabel.setVisible(false);
}
- if(this._placeholderLabel) {
+ if (this._placeholderLabel) {
this._placeholderLabel.setVisible(false);
}
};
- proto._updateEditBoxContentStyle = function() {
+ proto._updateEditBoxContentStyle = function () {
var inputFlag = this._editBox._editBoxInputFlag;
if (inputFlag === cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_ALL_CHARACTERS) {
this._editBox._text = this._editBox._text.toUpperCase();
@@ -1049,10 +1056,10 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
}
};
- proto._updateLabelString = function() {
+ proto._updateLabelString = function () {
this._updateInputType();
- if(this._textLabel) {
+ if (this._textLabel) {
this._textLabel.setVisible(true);
this._textLabel.setString(this._editBox._text);
}
@@ -1063,12 +1070,12 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
for (var i = 0; i < len; ++i) {
passwordString += '\u25CF';
}
- if(this._textLabel) {
+ if (this._textLabel) {
this._textLabel.setString(passwordString);
}
} else {
this._updateEditBoxContentStyle();
- if(this._textLabel) {
+ if (this._textLabel) {
this._textLabel.setString(this._editBox._text);
}
}
@@ -1077,7 +1084,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
proto._showLabels = function () {
this._hiddenLabels();
if (this._edTxt.value === '') {
- if(this._placeholderLabel) {
+ if (this._placeholderLabel) {
this._placeholderLabel.setVisible(true);
this._placeholderLabel.setString(this._editBox._placeholderText);
}
@@ -1087,8 +1094,8 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
}
};
- proto.show = function() {
- if(!this._editBox._alwaysOnTop) {
+ proto.show = function () {
+ if (!this._editBox._alwaysOnTop) {
if (this._edTxt.style.display === 'none') {
this._edTxt.style.display = '';
this._edTxt.focus();
@@ -1097,8 +1104,8 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
this._hiddenLabels();
};
- proto.hidden = function() {
- if(!this._editBox._alwaysOnTop) {
+ proto.hidden = function () {
+ if (!this._editBox._alwaysOnTop) {
this._edTxt.style.display = 'none';
}
this._showLabels();
@@ -1130,12 +1137,12 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
};
proto.setFontColor = function (color) {
- if(!this._edTxt) return;
+ if (!this._edTxt) return;
if (this._edTxt.value !== this._editBox._placeholderText) {
this._edTxt.style.color = cc.colorToHex(color);
}
- if(this._textLabel) {
+ if (this._textLabel) {
this._textLabel.setColor(color);
}
};
@@ -1145,7 +1152,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
};
proto.setMaxLength = function (maxLength) {
- if(!this._edTxt) return;
+ if (!this._edTxt) return;
this._edTxt.maxLength = maxLength;
};
@@ -1159,20 +1166,20 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
};
proto._updateInputType = function () {
- if(this._editBox._keyboardReturnType === cc.KEYBOARD_RETURNTYPE_SEARCH) {
+ if (this._editBox._keyboardReturnType === cc.KEYBOARD_RETURNTYPE_SEARCH) {
this._edTxt.type = 'search';
}
var inputMode = this._editBox._editBoxInputMode;
- if(inputMode === cc.EDITBOX_INPUT_MODE_EMAILADDR) {
+ if (inputMode === cc.EDITBOX_INPUT_MODE_EMAILADDR) {
this._edTxt.type = 'email';
- } else if(inputMode === cc.EDITBOX_INPUT_MODE_DECIMAL ||
- inputMode === cc.EDITBOX_INPUT_MODE_NUMERIC) {
+ } else if (inputMode === cc.EDITBOX_INPUT_MODE_DECIMAL ||
+ inputMode === cc.EDITBOX_INPUT_MODE_NUMERIC) {
this._edTxt.type = 'number';
- } else if(inputMode === cc.EDITBOX_INPUT_MODE_PHONENUMBER) {
+ } else if (inputMode === cc.EDITBOX_INPUT_MODE_PHONENUMBER) {
this._edTxt.type = 'number';
this._edTxt.pattern = '[0-9]*';
- } else if(inputMode === cc.EDITBOX_INPUT_MODE_URL) {
+ } else if (inputMode === cc.EDITBOX_INPUT_MODE_URL) {
this._edTxt.type = 'url';
} else {
this._edTxt.type = 'text';
@@ -1185,7 +1192,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
};
proto.setInputFlag = function (inputFlag) {
- if(!this._edTxt) return;
+ if (!this._edTxt) return;
this._updateInputType();
@@ -1216,28 +1223,28 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
};
proto.setString = function (text) {
- if(!this._edTxt) return;
+ if (!this._edTxt) return;
if (text !== null) {
this._edTxt.value = text;
if (text === '') {
- if(this._placeholderLabel) {
+ if (this._placeholderLabel) {
this._placeholderLabel.setString(this._editBox._placeholderText);
this._placeholderLabel.setColor(this._editBox._placeholderColor);
this._placeholderLabel.setVisible(true);
}
- if(this._textLabel) {
+ if (this._textLabel) {
this._textLabel.setVisible(false);
}
}
else {
this._edTxt.style.color = cc.colorToHex(this._editBox._textColor);
- if(this._textLabel) {
+ if (this._textLabel) {
this._textLabel.setColor(this._editBox._textColor);
}
- if(this._placeholderLabel) {
+ if (this._placeholderLabel) {
this._placeholderLabel.setVisible(false);
}
@@ -1246,21 +1253,21 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
}
};
- proto._updateDOMFontStyle = function() {
- if(!this._edTxt) return;
+ proto._updateDOMFontStyle = function () {
+ if (!this._edTxt) return;
if (this._edTxt.value !== '') {
this._edTxt.style.fontFamily = this._edFontName;
this._edTxt.style.fontSize = this._edFontSize + 'px';
}
- if(this._textLabel) {
+ if (this._textLabel) {
this._textLabel.setFontSize(this._edFontSize);
this._textLabel.setFontName(this._edFontName);
}
};
- proto.updateSize = function(newWidth, newHeight) {
+ proto.updateSize = function (newWidth, newHeight) {
var editboxDomNode = this._edTxt;
if (!editboxDomNode) return;
@@ -1270,7 +1277,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
this._updateLabelPosition(cc.size(newWidth, newHeight));
};
- proto.createNativeControl = function() {
+ proto.createNativeControl = function () {
this._createDomTextArea();
this._addDomInputControl();
};
@@ -1281,14 +1288,14 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
proto._removeDomInputControl = function () {
var editBox = this._edTxt;
- if(editBox){
+ if (editBox) {
var hasChild = false;
- if('contains' in cc.game.container) {
+ if ('contains' in cc.game.container) {
hasChild = cc.game.container.contains(editBox);
- }else {
+ } else {
hasChild = cc.game.container.compareDocumentPosition(editBox) % 16;
}
- if(hasChild)
+ if (hasChild)
cc.game.container.removeChild(editBox);
}
this._edTxt = null;
@@ -1306,13 +1313,13 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
//define the canvas render command
cc.EditBox.CanvasRenderCmd = function (node) {
- cc.Node.CanvasRenderCmd.call(this, node);
+ this._rootCtor(node);
this.initializeRenderCmd(node);
};
var canvasRenderCmdProto = cc.EditBox.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
- function _getPropertyDescriptor (obj, name) {
+ function _getPropertyDescriptor(obj, name) {
var pd = Object.getOwnPropertyDescriptor(obj, name);
if (pd) {
return pd;
@@ -1340,8 +1347,8 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
cc.error('cc.js.mixin: arguments must be type object:', source);
continue;
}
- for ( var name in source) {
- _copyprop( name, source, obj);
+ for (var name in source) {
+ _copyprop(name, source, obj);
}
}
}
@@ -1359,7 +1366,7 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
//define the webgl render command
cc.EditBox.WebGLRenderCmd = function (node) {
- cc.Node.WebGLRenderCmd.call(this, node);
+ this._rootCtor(node);
this.initializeRenderCmd(node);
};
diff --git a/extensions/gui/control-extension/CCControl.js b/extensions/gui/control-extension/CCControl.js
index 2ff72a7ee7..e4071a3ef2 100644
--- a/extensions/gui/control-extension/CCControl.js
+++ b/extensions/gui/control-extension/CCControl.js
@@ -148,29 +148,26 @@ cc.Control = cc.Layer.extend(/** @lends cc.Control# */{
},
init: function () {
- if (cc.Layer.prototype.init.call(this)) {
- // Initialise instance variables
- this._state = cc.CONTROL_STATE_NORMAL;
- this._enabled = true;
- this._selected = false;
- this._highlighted = false;
-
- var listener = cc.EventListener.create({
- event: cc.EventListener.TOUCH_ONE_BY_ONE,
- swallowTouches: true
- });
- if (this.onTouchBegan)
- listener.onTouchBegan = this.onTouchBegan.bind(this);
- if (this.onTouchMoved)
- listener.onTouchMoved = this.onTouchMoved.bind(this);
- if (this.onTouchEnded)
- listener.onTouchEnded = this.onTouchEnded.bind(this);
- if (this.onTouchCancelled)
- listener.onTouchCancelled = this.onTouchCancelled.bind(this);
- this._touchListener = listener;
- return true;
- } else
- return false;
+ // Initialise instance variables
+ this._state = cc.CONTROL_STATE_NORMAL;
+ this._enabled = true;
+ this._selected = false;
+ this._highlighted = false;
+
+ var listener = cc.EventListener.create({
+ event: cc.EventListener.TOUCH_ONE_BY_ONE,
+ swallowTouches: true
+ });
+ if (this.onTouchBegan)
+ listener.onTouchBegan = this.onTouchBegan.bind(this);
+ if (this.onTouchMoved)
+ listener.onTouchMoved = this.onTouchMoved.bind(this);
+ if (this.onTouchEnded)
+ listener.onTouchEnded = this.onTouchEnded.bind(this);
+ if (this.onTouchCancelled)
+ listener.onTouchCancelled = this.onTouchCancelled.bind(this);
+ this._touchListener = listener;
+ return true;
},
onEnter: function () {
diff --git a/extensions/gui/scrollview/CCScrollView.js b/extensions/gui/scrollview/CCScrollView.js
index f28592f67b..d29e6db0ac 100644
--- a/extensions/gui/scrollview/CCScrollView.js
+++ b/extensions/gui/scrollview/CCScrollView.js
@@ -40,19 +40,19 @@ var SCROLL_DEACCEL_RATE = 0.95;
var SCROLL_DEACCEL_DIST = 1.0;
var BOUNCE_DURATION = 0.15;
var INSET_RATIO = 0.2;
-var MOVE_INCH = 7.0/160.0;
+var MOVE_INCH = 7.0 / 160.0;
var BOUNCE_BACK_FACTOR = 0.35;
-cc.convertDistanceFromPointToInch = function(pointDis){
+cc.convertDistanceFromPointToInch = function (pointDis) {
var eglViewer = cc.view;
- var factor = (eglViewer.getScaleX() + eglViewer.getScaleY())/2;
+ var factor = (eglViewer.getScaleX() + eglViewer.getScaleY()) / 2;
return (pointDis * factor) / 160; // CCDevice::getDPI() default value
};
cc.ScrollViewDelegate = cc.Class.extend({
- scrollViewDidScroll:function (view) {
+ scrollViewDidScroll: function (view) {
},
- scrollViewDidZoom:function (view) {
+ scrollViewDidZoom: function (view) {
}
});
@@ -72,35 +72,35 @@ cc.ScrollViewDelegate = cc.Class.extend({
* @property {Boolean} clippingToBounds - Indicate whether the scroll view clips its children
*/
cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
- _zoomScale:0,
- _minZoomScale:0,
- _maxZoomScale:0,
- _delegate:null,
- _direction:cc.SCROLLVIEW_DIRECTION_BOTH,
- _dragging:false,
- _contentOffset:null,
- _container:null,
- _touchMoved:false,
- _maxInset:null,
- _minInset:null,
- _bounceable:false,
- _clippingToBounds:false,
- _scrollDistance:null,
- _touchPoint:null,
- _touchLength:0,
- _touches:null,
- _viewSize:null,
- _minScale:0,
- _maxScale:0,
+ _zoomScale: 0,
+ _minZoomScale: 0,
+ _maxZoomScale: 0,
+ _delegate: null,
+ _direction: cc.SCROLLVIEW_DIRECTION_BOTH,
+ _dragging: false,
+ _contentOffset: null,
+ _container: null,
+ _touchMoved: false,
+ _maxInset: null,
+ _minInset: null,
+ _bounceable: false,
+ _clippingToBounds: false,
+ _scrollDistance: null,
+ _touchPoint: null,
+ _touchLength: 0,
+ _touches: null,
+ _viewSize: null,
+ _minScale: 0,
+ _maxScale: 0,
//scissor rect for parent, just for restoring GL_SCISSOR_BOX
- _parentScissorRect:null,
- _scissorRestored:false,
+ _parentScissorRect: null,
+ _scissorRestored: false,
// cache object
- _tmpViewRect:null,
+ _tmpViewRect: null,
_touchListener: null,
- _className:"ScrollView",
+ _className: "ScrollView",
/**
* @contructor
@@ -108,26 +108,26 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
* @param container
* @returns {ScrollView}
*/
- ctor:function (size, container) {
+ ctor: function (size, container) {
cc.Layer.prototype.ctor.call(this);
- this._contentOffset = cc.p(0,0);
+ this._contentOffset = cc.p(0, 0);
this._maxInset = cc.p(0, 0);
this._minInset = cc.p(0, 0);
this._scrollDistance = cc.p(0, 0);
this._touchPoint = cc.p(0, 0);
this._touches = [];
this._viewSize = cc.size(0, 0);
- this._parentScissorRect = new cc.Rect(0,0,0,0);
- this._tmpViewRect = new cc.Rect(0,0,0,0);
+ this._parentScissorRect = new cc.Rect(0, 0, 0, 0);
+ this._tmpViewRect = new cc.Rect(0, 0, 0, 0);
- if(container != undefined)
+ if (container != undefined)
this.initWithViewSize(size, container);
else
this.initWithViewSize(cc.size(200, 200), null);
},
- init:function () {
+ init: function () {
return this.initWithViewSize(cc.size(200, 200), null);
},
@@ -137,8 +137,8 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
* @param {cc.Node} container
* @return {Boolean}
*/
- initWithViewSize:function (size, container) {
- var pZero = cc.p(0,0);
+ initWithViewSize: function (size, container) {
+ var pZero = cc.p(0, 0);
if (cc.Layer.prototype.init.call(this)) {
if (!container && !this._container) {
container = new cc.Layer();
@@ -165,6 +165,34 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
return false;
},
+ visit: function (parent) {
+ if (!this._visible) {
+ return;
+ }
+
+ var renderer = cc.renderer, cmd = this._renderCmd;
+ cmd.visit(parent && parent._renderCmd);
+
+ if (this._clippingToBounds) {
+ renderer.pushRenderCommand(cmd.startCmd);
+ }
+
+ var i, children = this._children, len = children.length;
+ if (len > 0) {
+ if (this._reorderChildDirty) {
+ this.sortAllChildren();
+ }
+ for (i = 0; i < len; i++) {
+ children[i].visit(this);
+ }
+ }
+
+ if (this._clippingToBounds) {
+ renderer.pushRenderCommand(cmd.endCmd);
+ }
+ cmd._dirtyFlag = 0;
+ },
+
/**
* Sets a new content offset. It ignores max/min offset. It just sets what's given. (just like UIKit's UIScrollView)
*
@@ -192,7 +220,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
},
- getContentOffset:function () {
+ getContentOffset: function () {
var locPos = this._container.getPosition();
return cc.p(locPos.x, locPos.y);
},
@@ -204,7 +232,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
* @param {cc.Point} offset new offset
* @param {Number} dt animation duration
*/
- setContentOffsetInDuration:function (offset, dt) {
+ setContentOffsetInDuration: function (offset, dt) {
var scroll = cc.moveTo(dt, offset);
var expire = cc.callFunc(this._stoppedAnimatedScroll, this);
this._container.runAction(cc.sequence(scroll, expire));
@@ -246,7 +274,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
}
},
- getZoomScale:function () {
+ getZoomScale: function () {
return this._container.getScale();
},
@@ -256,7 +284,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
* @param {Number} s a new scale value
* @param {Number} dt animation duration
*/
- setZoomScaleInDuration:function (s, dt) {
+ setZoomScaleInDuration: function (s, dt) {
if (dt > 0) {
var locScale = this._container.getScale();
if (locScale !== s) {
@@ -272,7 +300,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
* Returns the current container's minimum offset. You may want this while you animate scrolling by yourself
* @return {cc.Point} Returns the current container's minimum offset.
*/
- minContainerOffset:function () {
+ minContainerOffset: function () {
var locContainer = this._container;
var locContentSize = locContainer.getContentSize(), locViewSize = this._viewSize;
return cc.p(locViewSize.width - locContentSize.width * locContainer.getScaleX(),
@@ -283,7 +311,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
* Returns the current container's maximum offset. You may want this while you animate scrolling by yourself
* @return {cc.Point} Returns the current container's maximum offset.
*/
- maxContainerOffset:function () {
+ maxContainerOffset: function () {
return cc.p(0.0, 0.0);
},
@@ -292,7 +320,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
* @param {cc.Node} node
* @return {Boolean} YES if it is in visible bounds
*/
- isNodeVisible:function (node) {
+ isNodeVisible: function (node) {
var offset = this.getContentOffset();
var size = this.getViewSize();
var scale = this.getZoomScale();
@@ -305,7 +333,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
/**
* Provided to make scroll view compatible with SWLayer's pause method
*/
- pause:function (sender) {
+ pause: function (sender) {
this._container.pause();
var selChildren = this._container.getChildren();
for (var i = 0; i < selChildren.length; i++) {
@@ -317,7 +345,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
/**
* Provided to make scroll view compatible with SWLayer's resume method
*/
- resume:function (sender) {
+ resume: function (sender) {
var selChildren = this._container.getChildren();
for (var i = 0, len = selChildren.length; i < len; i++) {
selChildren[i].resume();
@@ -326,16 +354,16 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
this._super();
},
- isDragging:function () {
+ isDragging: function () {
return this._dragging;
},
- isTouchMoved:function () {
+ isTouchMoved: function () {
return this._touchMoved;
},
- isBounceable:function () {
+ isBounceable: function () {
return this._bounceable;
},
- setBounceable:function (bounceable) {
+ setBounceable: function (bounceable) {
this._bounceable = bounceable;
},
@@ -346,20 +374,20 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
* Hence, this scroll view will use a separate size property.
*
*/
- getViewSize:function () {
+ getViewSize: function () {
return this._viewSize;
},
- setViewSize:function (size) {
+ setViewSize: function (size) {
this._viewSize = size;
- cc.Node.prototype.setContentSize.call(this,size);
+ cc.Node.prototype.setContentSize.call(this, size);
},
- getContainer:function () {
+ getContainer: function () {
return this._container;
},
- setContainer:function (container) {
+ setContainer: function (container) {
// Make sure that 'm_pContainer' has a non-NULL value since there are
// lots of logic that use 'm_pContainer'.
if (!container)
@@ -378,23 +406,23 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
/**
* direction allowed to scroll. CCScrollViewDirectionBoth by default.
*/
- getDirection:function () {
+ getDirection: function () {
return this._direction;
},
- setDirection:function (direction) {
+ setDirection: function (direction) {
this._direction = direction;
},
- getDelegate:function () {
+ getDelegate: function () {
return this._delegate;
},
- setDelegate:function (delegate) {
+ setDelegate: function (delegate) {
this._delegate = delegate;
},
/** override functions */
// optional
- onTouchBegan:function (touch, event) {
+ onTouchBegan: function (touch, event) {
for (var c = this; c != null; c = c.parent) {
if (!c.isVisible())
return false;
@@ -430,7 +458,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
return true;
},
- onTouchMoved:function (touch, event) {
+ onTouchMoved: function (touch, event) {
if (!this.isVisible())
return;
@@ -447,17 +475,17 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
var moveDistance = cc.pSub(newPoint, this._touchPoint);
var dis = 0.0, locDirection = this._direction, pos;
- if (locDirection === cc.SCROLLVIEW_DIRECTION_VERTICAL){
+ if (locDirection === cc.SCROLLVIEW_DIRECTION_VERTICAL) {
dis = moveDistance.y;
pos = this._container.getPositionY();
if (!(this.minContainerOffset().y <= pos && pos <= this.maxContainerOffset().y))
moveDistance.y *= BOUNCE_BACK_FACTOR;
- } else if (locDirection === cc.SCROLLVIEW_DIRECTION_HORIZONTAL){
+ } else if (locDirection === cc.SCROLLVIEW_DIRECTION_HORIZONTAL) {
dis = moveDistance.x;
pos = this._container.getPositionX();
if (!(this.minContainerOffset().x <= pos && pos <= this.maxContainerOffset().x))
moveDistance.x *= BOUNCE_BACK_FACTOR;
- }else {
+ } else {
dis = Math.sqrt(moveDistance.x * moveDistance.x + moveDistance.y * moveDistance.y);
pos = this._container.getPositionY();
@@ -470,12 +498,12 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
moveDistance.x *= BOUNCE_BACK_FACTOR;
}
- if (!this._touchMoved && Math.abs(cc.convertDistanceFromPointToInch(dis)) < MOVE_INCH ){
+ if (!this._touchMoved && Math.abs(cc.convertDistanceFromPointToInch(dis)) < MOVE_INCH) {
//CCLOG("Invalid movement, distance = [%f, %f], disInch = %f", moveDistance.x, moveDistance.y);
return;
}
- if (!this._touchMoved){
+ if (!this._touchMoved) {
moveDistance.x = 0;
moveDistance.y = 0;
}
@@ -509,7 +537,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
}
},
- onTouchEnded:function (touch, event) {
+ onTouchEnded: function (touch, event) {
if (!this.isVisible())
return;
@@ -521,7 +549,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
this._touchMoved = false;
},
- onTouchCancelled:function (touch, event) {
+ onTouchCancelled: function (touch, event) {
if (!this.isVisible())
return;
@@ -532,33 +560,33 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
setContentSize: function (size, height) {
if (this.getContainer() !== null) {
- if(height === undefined)
+ if (height === undefined)
this.getContainer().setContentSize(size);
else
this.getContainer().setContentSize(size, height);
this.updateInset();
}
},
- _setWidth: function (value) {
- var container = this.getContainer();
- if (container !== null) {
- container._setWidth(value);
- this.updateInset();
- }
- },
- _setHeight: function (value) {
- var container = this.getContainer();
- if (container !== null) {
- container._setHeight(value);
- this.updateInset();
- }
- },
-
- getContentSize:function () {
+ _setWidth: function (value) {
+ var container = this.getContainer();
+ if (container !== null) {
+ container._setWidth(value);
+ this.updateInset();
+ }
+ },
+ _setHeight: function (value) {
+ var container = this.getContainer();
+ if (container !== null) {
+ container._setHeight(value);
+ this.updateInset();
+ }
+ },
+
+ getContentSize: function () {
return this._container.getContentSize();
},
- updateInset:function () {
+ updateInset: function () {
if (this.getContainer() !== null) {
var locViewSize = this._viewSize;
var tempOffset = this.maxContainerOffset();
@@ -573,15 +601,15 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
/**
* Determines whether it clips its children or not.
*/
- isClippingToBounds:function () {
+ isClippingToBounds: function () {
return this._clippingToBounds;
},
- setClippingToBounds:function (clippingToBounds) {
+ setClippingToBounds: function (clippingToBounds) {
this._clippingToBounds = clippingToBounds;
},
- addChild:function (child, zOrder, tag) {
+ addChild: function (child, zOrder, tag) {
if (!child)
throw new Error("child must not nil!");
@@ -597,12 +625,12 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
}
},
- isTouchEnabled: function(){
+ isTouchEnabled: function () {
return this._touchListener !== null;
},
- setTouchEnabled:function (e) {
- if(this._touchListener)
+ setTouchEnabled: function (e) {
+ if (this._touchListener)
cc.eventManager.removeListener(this._touchListener);
this._touchListener = null;
if (!e) {
@@ -613,13 +641,13 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
var listener = cc.EventListener.create({
event: cc.EventListener.TOUCH_ONE_BY_ONE
});
- if(this.onTouchBegan)
+ if (this.onTouchBegan)
listener.onTouchBegan = this.onTouchBegan.bind(this);
- if(this.onTouchMoved)
+ if (this.onTouchMoved)
listener.onTouchMoved = this.onTouchMoved.bind(this);
- if(this.onTouchEnded)
+ if (this.onTouchEnded)
listener.onTouchEnded = this.onTouchEnded.bind(this);
- if(this.onTouchCancelled)
+ if (this.onTouchCancelled)
listener.onTouchCancelled = this.onTouchCancelled.bind(this);
this._touchListener = listener;
cc.eventManager.addListener(listener, this);
@@ -632,7 +660,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
* @param size view size
* @return initialized scroll view object
*/
- _initWithViewSize:function (size) {
+ _initWithViewSize: function (size) {
return null;
},
@@ -641,7 +669,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
*
* @param animated If YES, relocation is animated
*/
- _relocateContainer:function (animated) {
+ _relocateContainer: function (animated) {
var min = this.minContainerOffset();
var max = this.maxContainerOffset();
var locDirection = this._direction;
@@ -669,7 +697,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
*
* @param {Number} dt delta
*/
- _deaccelerateScrolling:function (dt) {
+ _deaccelerateScrolling: function (dt) {
if (this._dragging) {
this.unschedule(this._deaccelerateScrolling);
return;
@@ -678,7 +706,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
var maxInset, minInset;
var oldPosition = this._container.getPosition();
var locScrollDistance = this._scrollDistance;
- this._container.setPosition(oldPosition.x + locScrollDistance.x , oldPosition.y + locScrollDistance.y);
+ this._container.setPosition(oldPosition.x + locScrollDistance.x, oldPosition.y + locScrollDistance.y);
if (this._bounceable) {
maxInset = this._maxInset;
minInset = this._minInset;
@@ -709,7 +737,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
/**
* This method makes sure auto scrolling causes delegate to invoke its method
*/
- _performedAnimatedScroll:function (dt) {
+ _performedAnimatedScroll: function (dt) {
if (this._dragging) {
this.unschedule(this._performedAnimatedScroll);
return;
@@ -721,7 +749,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
/**
* Expire animated scroll delegate calls
*/
- _stoppedAnimatedScroll:function (node) {
+ _stoppedAnimatedScroll: function (node) {
this.unschedule(this._performedAnimatedScroll);
// After the animation stopped, "scrollViewDidScroll" should be invoked, this could fix the bug of lack of tableview cells.
if (this._delegate && this._delegate.scrollViewDidScroll) {
@@ -732,11 +760,11 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
/**
* Zoom handling
*/
- _handleZoom:function () {
+ _handleZoom: function () {
},
- _getViewRect:function(){
- var screenPos = this.convertToWorldSpace(cc.p(0,0));
+ _getViewRect: function () {
+ var screenPos = this.convertToWorldSpace(cc.p(0, 0));
var locViewSize = this._viewSize;
var scaleX = this.getScaleX();
@@ -767,7 +795,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
return locViewRect;
},
- _createRenderCmd: function(){
+ _createRenderCmd: function () {
if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
return new cc.ScrollView.CanvasRenderCmd(this);
} else {
@@ -815,4 +843,4 @@ _p = null;
*/
cc.ScrollView.create = function (size, container) {
return new cc.ScrollView(size, container);
-};
\ No newline at end of file
+};
diff --git a/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js b/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js
index 7b5e89c715..0cc063f846 100644
--- a/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js
+++ b/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js
@@ -22,9 +22,9 @@
THE SOFTWARE.
****************************************************************************/
-(function() {
- cc.ScrollView.CanvasRenderCmd = function(renderable){
- cc.Layer.CanvasRenderCmd.call(this, renderable);
+(function () {
+ cc.ScrollView.CanvasRenderCmd = function (renderable) {
+ this._layerCmdCtor(renderable);
this._needDraw = false;
this.startCmd = new cc.CustomRenderCmd(this, this._startCmd);
@@ -36,7 +36,7 @@
var proto = cc.ScrollView.CanvasRenderCmd.prototype = Object.create(cc.Layer.CanvasRenderCmd.prototype);
proto.constructor = cc.ScrollView.CanvasRenderCmd;
- proto._startCmd = function(ctx, scaleX, scaleY){
+ proto._startCmd = function (ctx, scaleX, scaleY) {
var node = this._node;
var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
wrapper.save();
@@ -57,29 +57,8 @@
}
};
- proto._endCmd = function(wrapper){
+ proto._endCmd = function (wrapper) {
wrapper = wrapper || cc._renderContext;
wrapper.restore();
};
-
- proto.visit = function(parentCmd){
- var node = this._node;
- if (!node._visible) return;
-
- var i, locChildren = node._children, childrenLen;
-
- this._syncStatus(parentCmd);
- cc.renderer.pushRenderCommand(this.startCmd);
-
- if (locChildren && locChildren.length > 0) {
- childrenLen = locChildren.length;
- node.sortAllChildren();
- for (i = 0; i < childrenLen; i++) {
- locChildren[i]._renderCmd.visit(this);
- }
- }
- cc.renderer.pushRenderCommand(this.endCmd);
-
- this._dirtyFlag = 0;
- };
})();
diff --git a/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js b/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js
index d435aac834..3d837db14f 100644
--- a/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js
+++ b/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js
@@ -22,9 +22,9 @@
THE SOFTWARE.
****************************************************************************/
-(function() {
- cc.ScrollView.WebGLRenderCmd = function(renderable){
- cc.Layer.WebGLRenderCmd.call(this, renderable);
+(function () {
+ cc.ScrollView.WebGLRenderCmd = function (renderable) {
+ this._layerCmdCtor(renderable);
this._needDraw = false;
this.startCmd = new cc.CustomRenderCmd(this, this._startCmd);
@@ -34,11 +34,11 @@
var proto = cc.ScrollView.WebGLRenderCmd.prototype = Object.create(cc.Layer.WebGLRenderCmd.prototype);
proto.constructor = cc.ScrollView.WebGLRenderCmd;
- proto._startCmd = function(){
+ proto._startCmd = function () {
var node = this._node;
var EGLViewer = cc.view;
var frame = node._getViewRect();
- if(EGLViewer.isScissorEnabled()){
+ if (EGLViewer.isScissorEnabled()) {
node._scissorRestored = true;
node._parentScissorRect = EGLViewer.getScissorRect();
//set the intersection of m_tParentScissorRect and frame as the new scissor rect
@@ -50,7 +50,7 @@
var yy = Math.min(frame.y + frame.height, locPSRect.y + locPSRect.height);
EGLViewer.setScissorInPoints(x, y, xx - x, yy - y);
}
- }else{
+ } else {
var ctx = cc._renderContext;
ctx.enable(ctx.SCISSOR_TEST);
//clip
@@ -58,49 +58,14 @@
}
};
- proto._endCmd = function(){
+ proto._endCmd = function () {
var node = this._node;
if (node._scissorRestored) { //restore the parent's scissor rect
var rect = node._parentScissorRect;
cc.view.setScissorInPoints(rect.x, rect.y, rect.width, rect.height);
- }else{
+ } else {
var ctx = cc._renderContext;
ctx.disable(ctx.SCISSOR_TEST);
}
};
-
- proto.visit = function(parentCmd){
- var node = this._node;
- if (!node._visible) return;
-
- var i, locChildren = node._children, selChild, childrenLen;
-
- this._syncStatus(parentCmd);
-
- if (node._clippingToBounds) {
- cc.renderer.pushRenderCommand(this.startCmd);
- }
-
- if (locChildren && locChildren.length > 0) {
- childrenLen = locChildren.length;
- // draw children zOrder < 0
- for (i = 0; i < childrenLen; i++) {
- selChild = locChildren[i];
- if (selChild && selChild._localZOrder < 0)
- selChild._renderCmd.visit();
- else
- break;
- }
-
- // draw children zOrder >= 0
- for (; i < childrenLen; i++)
- locChildren[i]._renderCmd.visit();
- }
-
- if (node._clippingToBounds) {
- cc.renderer.pushRenderCommand(this.endCmd);
- }
-
- this._dirtyFlag = 0;
- };
-})();
\ No newline at end of file
+})();
diff --git a/extensions/gui/scrollview/CCTableView.js b/extensions/gui/scrollview/CCTableView.js
index b7b8ef044f..a197ada84a 100644
--- a/extensions/gui/scrollview/CCTableView.js
+++ b/extensions/gui/scrollview/CCTableView.js
@@ -48,30 +48,30 @@ cc.TABLEVIEW_FILL_BOTTOMUP = 1;
* @property {Number} objectId - The index used internally by SWTableView and its subclasses
*/
cc.TableViewCell = cc.Node.extend(/** @lends cc.TableViewCell# */{
- _idx:0,
- _className:"TableViewCell",
+ _idx: 0,
+ _className: "TableViewCell",
/**
* The index used internally by SWTableView and its subclasses
*/
- getIdx:function () {
+ getIdx: function () {
return this._idx;
},
- setIdx:function (idx) {
+ setIdx: function (idx) {
this._idx = idx;
},
/**
* Cleans up any resources linked to this cell and resets idx property.
*/
- reset:function () {
+ reset: function () {
this._idx = cc.INVALID_INDEX;
},
- setObjectID:function (idx) {
+ setObjectID: function (idx) {
this._idx = idx;
},
- getObjectID:function () {
+ getObjectID: function () {
return this._idx;
}
});
@@ -94,7 +94,7 @@ cc.TableViewDelegate = cc.ScrollViewDelegate.extend(/** @lends cc.TableViewDeleg
* @param {cc.TableView} table table contains the given cell
* @param {cc.TableViewCell} cell cell that is touched
*/
- tableCellTouched:function (table, cell) {
+ tableCellTouched: function (table, cell) {
},
/**
@@ -103,7 +103,7 @@ cc.TableViewDelegate = cc.ScrollViewDelegate.extend(/** @lends cc.TableViewDeleg
* @param {cc.TableView} table table contains the given cell
* @param {cc.TableViewCell} cell cell that is pressed
*/
- tableCellHighlight:function(table, cell){
+ tableCellHighlight: function (table, cell) {
},
/**
@@ -112,7 +112,7 @@ cc.TableViewDelegate = cc.ScrollViewDelegate.extend(/** @lends cc.TableViewDeleg
* @param {cc.TableView} table table contains the given cell
* @param {cc.TableViewCell} cell cell that is pressed
*/
- tableCellUnhighlight:function(table, cell){
+ tableCellUnhighlight: function (table, cell) {
},
@@ -125,7 +125,7 @@ cc.TableViewDelegate = cc.ScrollViewDelegate.extend(/** @lends cc.TableViewDeleg
* @param table table contains the given cell
* @param cell cell that is pressed
*/
- tableCellWillRecycle:function(table, cell){
+ tableCellWillRecycle: function (table, cell) {
}
});
@@ -140,7 +140,7 @@ cc.TableViewDataSource = cc.Class.extend(/** @lends cc.TableViewDataSource# */{
* @param {Number} idx the index of a cell to get a size
* @return {cc.Size} size of a cell at given index
*/
- tableCellSizeForIndex:function(table, idx){
+ tableCellSizeForIndex: function (table, idx) {
return this.cellSizeForTable(table);
},
/**
@@ -149,8 +149,8 @@ cc.TableViewDataSource = cc.Class.extend(/** @lends cc.TableViewDataSource# */{
* @param {cc.TableView} table table to hold the instances of Class
* @return {cc.Size} cell size
*/
- cellSizeForTable:function (table) {
- return cc.size(0,0);
+ cellSizeForTable: function (table) {
+ return cc.size(0, 0);
},
/**
@@ -159,7 +159,7 @@ cc.TableViewDataSource = cc.Class.extend(/** @lends cc.TableViewDataSource# */{
* @param idx index to search for a cell
* @return {cc.TableView} cell found at idx
*/
- tableCellAtIndex:function (table, idx) {
+ tableCellAtIndex: function (table, idx) {
return null;
},
@@ -168,7 +168,7 @@ cc.TableViewDataSource = cc.Class.extend(/** @lends cc.TableViewDataSource# */{
* @param {cc.TableView} table table to hold the instances of Class
* @return {Number} number of cells
*/
- numberOfCellsInTableView:function (table) {
+ numberOfCellsInTableView: function (table) {
return 0;
}
});
@@ -186,14 +186,14 @@ cc.TableViewDataSource = cc.Class.extend(/** @lends cc.TableViewDataSource# */{
*
*/
cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
- _vOrdering:null,
- _indices:null,
- _cellsFreed:null,
- _dataSource:null,
- _tableViewDelegate:null,
- _oldDirection:null,
- _cellsPositions:null, //vector with all cell positions
- _touchedCell:null,
+ _vOrdering: null,
+ _indices: null,
+ _cellsFreed: null,
+ _dataSource: null,
+ _tableViewDelegate: null,
+ _oldDirection: null,
+ _cellsPositions: null, //vector with all cell positions
+ _touchedCell: null,
/**
* The
@@ -201,7 +201,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
* @param size
* @param container
*/
- ctor:function (dataSource, size, container) {
+ ctor: function (dataSource, size, container) {
cc.ScrollView.prototype.ctor.call(this);
this._oldDirection = cc.SCROLLVIEW_DIRECTION_NONE;
this._cellsPositions = [];
@@ -212,7 +212,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
this._updateContentSize();
},
- __indexFromOffset:function (offset) {
+ __indexFromOffset: function (offset) {
var low = 0;
var high = this._dataSource.numberOfCellsInTableView(this) - 1;
var search;
@@ -226,16 +226,16 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
}
var locCellsPositions = this._cellsPositions;
- while (high >= low){
- var index = 0|(low + (high - low) / 2);
+ while (high >= low) {
+ var index = 0 | (low + (high - low) / 2);
var cellStart = locCellsPositions[index];
var cellEnd = locCellsPositions[index + 1];
- if (search >= cellStart && search <= cellEnd){
+ if (search >= cellStart && search <= cellEnd) {
return index;
- } else if (search < cellStart){
+ } else if (search < cellStart) {
high = index - 1;
- }else {
+ } else {
low = index + 1;
}
}
@@ -245,7 +245,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
return -1;
},
- _indexFromOffset:function (offset) {
+ _indexFromOffset: function (offset) {
var locOffset = {x: offset.x, y: offset.y};
var locDataSource = this._dataSource;
var maxIdx = locDataSource.numberOfCellsInTableView(this) - 1;
@@ -262,7 +262,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
return index;
},
- __offsetFromIndex:function (index) {
+ __offsetFromIndex: function (index) {
var offset;
switch (this.getDirection()) {
case cc.SCROLLVIEW_DIRECTION_HORIZONTAL:
@@ -276,7 +276,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
return offset;
},
- _offsetFromIndex:function (index) {
+ _offsetFromIndex: function (index) {
var offset = this.__offsetFromIndex(index);
var cellSize = this._dataSource.tableCellSizeForIndex(this, index);
@@ -286,14 +286,14 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
return offset;
},
- _updateCellPositions:function(){
+ _updateCellPositions: function () {
var cellsCount = this._dataSource.numberOfCellsInTableView(this);
var locCellsPositions = this._cellsPositions;
- if (cellsCount > 0){
+ if (cellsCount > 0) {
var currentPos = 0;
var cellSize, locDataSource = this._dataSource;
- for (var i=0; i < cellsCount; i++) {
+ for (var i = 0; i < cellsCount; i++) {
locCellsPositions[i] = currentPos;
cellSize = locDataSource.tableCellSizeForIndex(this, i);
switch (this.getDirection()) {
@@ -309,12 +309,12 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
}
},
- _updateContentSize:function () {
+ _updateContentSize: function () {
var size = cc.size(0, 0);
var cellsCount = this._dataSource.numberOfCellsInTableView(this);
- if(cellsCount > 0){
+ if (cellsCount > 0) {
var maxPosition = this._cellsPositions[cellsCount];
switch (this.getDirection()) {
case cc.SCROLLVIEW_DIRECTION_HORIZONTAL:
@@ -338,8 +338,8 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
}
},
- _moveCellOutOfSight:function (cell) {
- if(this._tableViewDelegate && this._tableViewDelegate.tableCellWillRecycle)
+ _moveCellOutOfSight: function (cell) {
+ if (this._tableViewDelegate && this._tableViewDelegate.tableCellWillRecycle)
this._tableViewDelegate.tableCellWillRecycle(this, cell);
this._cellsFreed.addObject(cell);
@@ -352,50 +352,52 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
}
},
- _setIndexForCell:function (index, cell) {
+ _setIndexForCell: function (index, cell) {
cell.setAnchorPoint(0, 0);
cell.setPosition(this._offsetFromIndex(index));
cell.setIdx(index);
},
- _addCellIfNecessary:function (cell) {
+ _addCellIfNecessary: function (cell) {
if (cell.getParent() !== this.getContainer()) {
this.getContainer().addChild(cell);
}
this._cellsUsed.insertSortedObject(cell);
var locIndices = this._indices, addIdx = cell.getIdx();
- if(locIndices.indexOf(addIdx) === -1){
+ if (locIndices.indexOf(addIdx) === -1) {
locIndices.push(addIdx);
//sort
- locIndices.sort(function(a,b){return a-b;});
+ locIndices.sort(function (a, b) {
+ return a - b;
+ });
}
},
/**
* data source
*/
- getDataSource:function () {
+ getDataSource: function () {
return this._dataSource;
},
- setDataSource:function (source) {
+ setDataSource: function (source) {
this._dataSource = source;
},
/**
* delegate
*/
- getDelegate:function () {
+ getDelegate: function () {
return this._tableViewDelegate;
},
- setDelegate:function (delegate) {
+ setDelegate: function (delegate) {
this._tableViewDelegate = delegate;
},
/**
* determines how cell is ordered and filled in the view.
*/
- setVerticalFillOrder:function (fillOrder) {
+ setVerticalFillOrder: function (fillOrder) {
if (this._vOrdering !== fillOrder) {
this._vOrdering = fillOrder;
if (this._cellsUsed.count() > 0) {
@@ -403,11 +405,11 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
}
}
},
- getVerticalFillOrder:function () {
+ getVerticalFillOrder: function () {
return this._vOrdering;
},
- initWithViewSize:function (size, container) {
+ initWithViewSize: function (size, container) {
if (cc.ScrollView.prototype.initWithViewSize.call(this, size, container)) {
this._cellsUsed = new cc.ArrayForObjectSorting();
this._cellsFreed = new cc.ArrayForObjectSorting();
@@ -427,7 +429,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
*
* @param idx index to find a cell
*/
- updateCellAtIndex:function (idx) {
+ updateCellAtIndex: function (idx) {
if (idx === cc.INVALID_INDEX || idx > this._dataSource.numberOfCellsInTableView(this) - 1)
return;
@@ -445,7 +447,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
*
* @param idx location to insert
*/
- insertCellAtIndex:function (idx) {
+ insertCellAtIndex: function (idx) {
if (idx === cc.INVALID_INDEX || idx > this._dataSource.numberOfCellsInTableView(this) - 1)
return;
@@ -473,7 +475,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
*
* @param idx index to find a cell
*/
- removeCellAtIndex:function (idx) {
+ removeCellAtIndex: function (idx) {
if (idx === cc.INVALID_INDEX || idx > this._dataSource.numberOfCellsInTableView(this) - 1)
return;
@@ -498,13 +500,13 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
/**
* reloads data from data source. the view will be refreshed.
*/
- reloadData:function () {
+ reloadData: function () {
this._oldDirection = cc.SCROLLVIEW_DIRECTION_NONE;
var locCellsUsed = this._cellsUsed, locCellsFreed = this._cellsFreed, locContainer = this.getContainer();
for (var i = 0, len = locCellsUsed.count(); i < len; i++) {
var cell = locCellsUsed.objectAtIndex(i);
- if(this._tableViewDelegate && this._tableViewDelegate.tableCellWillRecycle)
+ if (this._tableViewDelegate && this._tableViewDelegate.tableCellWillRecycle)
this._tableViewDelegate.tableCellWillRecycle(this, cell);
locCellsFreed.addObject(cell);
@@ -529,7 +531,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
*
* @return {TableViewCell} free cell
*/
- dequeueCell:function () {
+ dequeueCell: function () {
if (this._cellsFreed.count() === 0) {
return null;
} else {
@@ -545,14 +547,14 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
* @param idx index
* @return {cc.TableViewCell} a cell at a given index
*/
- cellAtIndex:function (idx) {
+ cellAtIndex: function (idx) {
var i = this._indices.indexOf(idx);
if (i === -1)
return null;
return this._cellsUsed.objectWithObjectID(idx);
},
- scrollViewDidScroll:function (view) {
+ scrollViewDidScroll: function (view) {
var locDataSource = this._dataSource;
var countOfItems = locDataSource.numberOfCellsInTableView(this);
if (0 === countOfItems)
@@ -561,24 +563,24 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
if (this._tableViewDelegate !== null && this._tableViewDelegate.scrollViewDidScroll)
this._tableViewDelegate.scrollViewDidScroll(this);
- var idx = 0, locViewSize = this._viewSize, locContainer = this.getContainer();
+ var idx = 0, locViewSize = this._viewSize, locContainer = this.getContainer();
var offset = this.getContentOffset();
offset.x *= -1;
offset.y *= -1;
- var maxIdx = Math.max(countOfItems-1, 0);
+ var maxIdx = Math.max(countOfItems - 1, 0);
if (this._vOrdering === cc.TABLEVIEW_FILL_TOPDOWN)
- offset.y = offset.y + locViewSize.height/locContainer.getScaleY();
+ offset.y = offset.y + locViewSize.height / locContainer.getScaleY();
var startIdx = this._indexFromOffset(offset);
if (startIdx === cc.INVALID_INDEX)
startIdx = countOfItems - 1;
if (this._vOrdering === cc.TABLEVIEW_FILL_TOPDOWN)
- offset.y -= locViewSize.height/locContainer.getScaleY();
+ offset.y -= locViewSize.height / locContainer.getScaleY();
else
- offset.y += locViewSize.height/locContainer.getScaleY();
- offset.x += locViewSize.width/locContainer.getScaleX();
+ offset.y += locViewSize.height / locContainer.getScaleY();
+ offset.x += locViewSize.width / locContainer.getScaleX();
var endIdx = this._indexFromOffset(offset);
if (endIdx === cc.INVALID_INDEX)
@@ -619,24 +621,24 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
}
},
- scrollViewDidZoom:function (view) {
+ scrollViewDidZoom: function (view) {
},
- onTouchEnded:function (touch, event) {
+ onTouchEnded: function (touch, event) {
if (!this.isVisible())
return;
- if (this._touchedCell){
+ if (this._touchedCell) {
var bb = this.getBoundingBox();
var tmpOrigin = cc.p(bb.x, bb.y);
tmpOrigin = this._parent.convertToWorldSpace(tmpOrigin);
bb.x = tmpOrigin.x;
bb.y = tmpOrigin.y;
var locTableViewDelegate = this._tableViewDelegate;
- if (cc.rectContainsPoint(bb, touch.getLocation()) && locTableViewDelegate !== null){
- if(locTableViewDelegate.tableCellUnhighlight)
+ if (cc.rectContainsPoint(bb, touch.getLocation()) && locTableViewDelegate !== null) {
+ if (locTableViewDelegate.tableCellUnhighlight)
locTableViewDelegate.tableCellUnhighlight(this, this._touchedCell);
- if(locTableViewDelegate.tableCellTouched)
+ if (locTableViewDelegate.tableCellTouched)
locTableViewDelegate.tableCellTouched(this, this._touchedCell);
}
this._touchedCell = null;
@@ -644,7 +646,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
cc.ScrollView.prototype.onTouchEnded.call(this, touch, event);
},
- onTouchBegan:function(touch, event){
+ onTouchBegan: function (touch, event) {
for (var c = this; c != null; c = c.parent) {
if (!c.isVisible())
return false;
@@ -652,7 +654,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
var touchResult = cc.ScrollView.prototype.onTouchBegan.call(this, touch, event);
- if(this._touches.length === 1) {
+ if (this._touches.length === 1) {
var index, point;
point = this.getContainer().convertTouchToNodeSpace(touch);
@@ -661,12 +663,12 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
if (index === cc.INVALID_INDEX)
this._touchedCell = null;
else
- this._touchedCell = this.cellAtIndex(index);
+ this._touchedCell = this.cellAtIndex(index);
if (this._touchedCell && this._tableViewDelegate !== null && this._tableViewDelegate.tableCellHighlight)
this._tableViewDelegate.tableCellHighlight(this, this._touchedCell);
- } else if(this._touchedCell) {
- if(this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight)
+ } else if (this._touchedCell) {
+ if (this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight)
this._tableViewDelegate.tableCellUnhighlight(this, this._touchedCell);
this._touchedCell = null;
}
@@ -674,21 +676,21 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
return touchResult;
},
- onTouchMoved: function(touch, event){
+ onTouchMoved: function (touch, event) {
cc.ScrollView.prototype.onTouchMoved.call(this, touch, event);
if (this._touchedCell && this.isTouchMoved()) {
- if(this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight)
+ if (this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight)
this._tableViewDelegate.tableCellUnhighlight(this, this._touchedCell);
this._touchedCell = null;
}
},
- onTouchCancelled: function(touch, event){
+ onTouchCancelled: function (touch, event) {
cc.ScrollView.prototype.onTouchCancelled.call(this, touch, event);
if (this._touchedCell) {
- if(this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight)
+ if (this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight)
this._tableViewDelegate.tableCellUnhighlight(this, this._touchedCell);
this._touchedCell = null;
}
diff --git a/extensions/spine/CCSkeletonAnimation.js b/extensions/spine/CCSkeletonAnimation.js
index f78d56cc89..b5308f2b52 100644
--- a/extensions/spine/CCSkeletonAnimation.js
+++ b/extensions/spine/CCSkeletonAnimation.js
@@ -343,6 +343,6 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{
* @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations.
* @returns {sp.Skeleton}
*/
-sp.SkeletonAnimation.create = function (skeletonDataFile, atlasFile/* or atlas*/, scale) {
+sp.SkeletonAnimation.createWithJsonFile = sp.SkeletonAnimation.create = function (skeletonDataFile, atlasFile/* or atlas*/, scale) {
return new sp.SkeletonAnimation(skeletonDataFile, atlasFile, scale);
};
\ No newline at end of file
diff --git a/extensions/spine/CCSkeletonCanvasRenderCmd.js b/extensions/spine/CCSkeletonCanvasRenderCmd.js
index 589ab62c53..073c8ab045 100644
--- a/extensions/spine/CCSkeletonCanvasRenderCmd.js
+++ b/extensions/spine/CCSkeletonCanvasRenderCmd.js
@@ -22,9 +22,9 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- sp.Skeleton.CanvasRenderCmd = function(renderableObject){
- cc.Node.CanvasRenderCmd.call(this, renderableObject);
+(function () {
+ sp.Skeleton.CanvasRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
this._needDraw = true;
};
@@ -36,10 +36,10 @@
wrapper = wrapper || cc._renderContext;
var locSkeleton = node._skeleton, drawOrder = locSkeleton.drawOrder;
- for(i = 0, n = drawOrder.length; i < n; i++){
+ for (i = 0, n = drawOrder.length; i < n; i++) {
slot = drawOrder[i];
slotNode = slot._slotNode;
- if(slotNode._visible && slotNode._renderCmd && slot.currentSprite){
+ if (slotNode._visible && slotNode._renderCmd && slot.currentSprite) {
slotNode._renderCmd.transform(this, true);
slot.currentSprite._renderCmd.rendering(wrapper, scaleX, scaleY);
slotNode._renderCmd._dirtyFlag = slot.currentSprite._renderCmd._dirtyFlag = 0;
@@ -96,8 +96,8 @@
}
};
- proto._updateRegionAttachmentSlot = function(attachment, slot, points) {
- if(!points)
+ proto._updateRegionAttachmentSlot = function (attachment, slot, points) {
+ if (!points)
return;
var vertices = {}, VERTEX = sp.VERTEX_INDEX, bone = slot.bone;
@@ -109,7 +109,7 @@
points.push(cc.p(vertices[VERTEX.X2], vertices[VERTEX.Y2]));
};
- proto._createChildFormSkeletonData = function(){
+ proto._createChildFormSkeletonData = function () {
var node = this._node;
var locSkeleton = node._skeleton, spriteName, sprite;
for (var i = 0, n = locSkeleton.slots.length; i < n; i++) {
@@ -117,13 +117,13 @@
var slotNode = new cc.Node();
slot._slotNode = slotNode;
- if(attachment instanceof spine.RegionAttachment){
+ if (attachment instanceof spine.RegionAttachment) {
spriteName = attachment.rendererObject.name;
sprite = this._createSprite(slot, attachment);
slot.currentSprite = sprite;
slot.currentSpriteName = spriteName;
slotNode.addChild(sprite);
- } else if(attachment instanceof spine.MeshAttachment){
+ } else if (attachment instanceof spine.MeshAttachment) {
//todo for mesh
}
}
@@ -140,7 +140,7 @@
rendererObject.height / rendererObject.originalHeight * attachment.scaleY);
};
- proto._createSprite = function(slot, attachment){
+ proto._createSprite = function (slot, attachment) {
var rendererObject = attachment.rendererObject;
var texture = rendererObject.page._texture;
var sprite = new cc.Sprite();
@@ -156,30 +156,30 @@
return sprite;
};
- proto._updateChild = function(){
+ proto._updateChild = function () {
var locSkeleton = this._node._skeleton, slots = locSkeleton.slots;
var i, n, selSprite;
var slot, attachment, slotNode;
- for(i = 0, n = slots.length; i < n; i++){
+ for (i = 0, n = slots.length; i < n; i++) {
slot = slots[i];
attachment = slot.attachment;
slotNode = slot._slotNode;
- if(!attachment){
+ if (!attachment) {
slotNode.setVisible(false);
continue;
}
var type = attachment.type;
- if (type === spine.AttachmentType.region){
- if(attachment.rendererObject){
- if(!slot.currentSpriteName || slot.currentSpriteName !== attachment.name){
- var spriteName = attachment.rendererObject.name;
- if(slot.currentSprite !== undefined)
+ if (type === spine.AttachmentType.region) {
+ if (attachment.rendererObject) {
+ if (!slot.currentSpriteName || slot.currentSpriteName !== attachment.name) {
+ var spriteName = attachment.rendererObject.name;
+ if (slot.currentSprite !== undefined)
slot.currentSprite.setVisible(false);
- slot.sprites = slot.sprites ||{};
- if(slot.sprites[spriteName] !== undefined)
+ slot.sprites = slot.sprites || {};
+ if (slot.sprites[spriteName] !== undefined)
slot.sprites[spriteName].setVisible(true);
- else{
+ else {
var sprite = this._createSprite(slot, attachment);
slotNode.addChild(sprite);
}
@@ -196,10 +196,10 @@
selSprite = slot.currentSprite;
selSprite._flippedX = bone.worldFlipX;
selSprite._flippedY = bone.worldFlipY;
- if(selSprite._flippedY || selSprite._flippedX){
+ if (selSprite._flippedY || selSprite._flippedX) {
slotNode.setRotation(bone.worldRotation);
selSprite.setRotation(attachment.rotation);
- }else{
+ } else {
slotNode.setRotation(-bone.worldRotation);
selSprite.setRotation(-attachment.rotation);
}
@@ -207,7 +207,7 @@
//hack for sprite
selSprite._renderCmd._displayedOpacity = 0 | (this._node.getOpacity() * locSkeleton.a * slot.a);
var r = 0 | (locSkeleton.r * slot.r * 255), g = 0 | (locSkeleton.g * slot.g * 255), b = 0 | (locSkeleton.b * slot.b * 255);
- selSprite.setColor(cc.color(r,g,b));
+ selSprite.setColor(cc.color(r, g, b));
selSprite._renderCmd._updateColor();
} else if (type === spine.AttachmentType.skinnedmesh) {
//todo for mesh
@@ -218,4 +218,4 @@
slotNode.setVisible(true);
}
};
-})();
\ No newline at end of file
+})();
diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js
index 77f4d76573..ce0c5fb366 100644
--- a/extensions/spine/CCSkeletonWebGLRenderCmd.js
+++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js
@@ -22,9 +22,9 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
+(function () {
sp.Skeleton.WebGLRenderCmd = function (renderableObject) {
- cc.Node.WebGLRenderCmd.call(this, renderableObject);
+ this._rootCtor(renderableObject);
this._needDraw = true;
this._matrix = new cc.math.Matrix4();
this._matrix.identity();
@@ -71,7 +71,7 @@
continue;
attachment = slot.attachment;
- switch(slot.attachment.type) {
+ switch (slot.attachment.type) {
case sp.ATTACHMENT_TYPE.REGION:
this._updateRegionAttachmentQuad(attachment, slot, tmpQuad, premultiAlpha);
break;
@@ -184,13 +184,15 @@
}
};
- proto._createChildFormSkeletonData = function(){};
+ proto._createChildFormSkeletonData = function () {
+ };
- proto._updateChild = function(){};
+ proto._updateChild = function () {
+ };
- proto._updateRegionAttachmentQuad = function(self, slot, quad, premultipliedAlpha) {
+ proto._updateRegionAttachmentQuad = function (attachment, slot, quad, premultipliedAlpha) {
var vertices = {};
- self.computeVertices(slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices);
+ attachment.computeVertices(slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices);
var a = slot.bone.skeleton.a * slot.a * attachment.a * 255;
var multiplier = premultipliedAlpha ? a : 255;
var r = slot.bone.skeleton.r * slot.r * attachment.r * multiplier;
@@ -212,19 +214,19 @@
quad.br.vertices.x = vertices[VERTEX.X4];
quad.br.vertices.y = vertices[VERTEX.Y4];
- quad.bl.texCoords.u = self.uvs[VERTEX.X1];
- quad.bl.texCoords.v = self.uvs[VERTEX.Y1];
- quad.tl.texCoords.u = self.uvs[VERTEX.X2];
- quad.tl.texCoords.v = self.uvs[VERTEX.Y2];
- quad.tr.texCoords.u = self.uvs[VERTEX.X3];
- quad.tr.texCoords.v = self.uvs[VERTEX.Y3];
- quad.br.texCoords.u = self.uvs[VERTEX.X4];
- quad.br.texCoords.v = self.uvs[VERTEX.Y4];
+ quad.bl.texCoords.u = attachment.uvs[VERTEX.X1];
+ quad.bl.texCoords.v = attachment.uvs[VERTEX.Y1];
+ quad.tl.texCoords.u = attachment.uvs[VERTEX.X2];
+ quad.tl.texCoords.v = attachment.uvs[VERTEX.Y2];
+ quad.tr.texCoords.u = attachment.uvs[VERTEX.X3];
+ quad.tr.texCoords.v = attachment.uvs[VERTEX.Y3];
+ quad.br.texCoords.u = attachment.uvs[VERTEX.X4];
+ quad.br.texCoords.v = attachment.uvs[VERTEX.Y4];
};
- proto._updateMeshAttachmentQuad = function(self, slot, quad, premultipliedAlpha) {
+ proto._updateMeshAttachmentQuad = function (attachment, slot, quad, premultipliedAlpha) {
var vertices = {};
- self.computeWorldVertices(slot.bone.x, slot.bone.y, slot, vertices);
+ attachment.computeWorldVertices(slot.bone.x, slot.bone.y, slot, vertices);
var r = slot.bone.skeleton.r * slot.r * 255;
var g = slot.bone.skeleton.g * slot.g * 255;
var b = slot.bone.skeleton.b * slot.b * 255;
@@ -251,13 +253,13 @@
quad.br.vertices.x = vertices[VERTEX.X4];
quad.br.vertices.y = vertices[VERTEX.Y4];
- quad.bl.texCoords.u = self.uvs[VERTEX.X1];
- quad.bl.texCoords.v = self.uvs[VERTEX.Y1];
- quad.tl.texCoords.u = self.uvs[VERTEX.X2];
- quad.tl.texCoords.v = self.uvs[VERTEX.Y2];
- quad.tr.texCoords.u = self.uvs[VERTEX.X3];
- quad.tr.texCoords.v = self.uvs[VERTEX.Y3];
- quad.br.texCoords.u = self.uvs[VERTEX.X4];
- quad.br.texCoords.v = self.uvs[VERTEX.Y4];
+ quad.bl.texCoords.u = attachment.uvs[VERTEX.X1];
+ quad.bl.texCoords.v = attachment.uvs[VERTEX.Y1];
+ quad.tl.texCoords.u = attachment.uvs[VERTEX.X2];
+ quad.tl.texCoords.v = attachment.uvs[VERTEX.Y2];
+ quad.tr.texCoords.u = attachment.uvs[VERTEX.X3];
+ quad.tr.texCoords.v = attachment.uvs[VERTEX.Y3];
+ quad.br.texCoords.u = attachment.uvs[VERTEX.X4];
+ quad.br.texCoords.v = attachment.uvs[VERTEX.Y4];
};
})();
diff --git a/moduleConfig.json b/moduleConfig.json
index cc5570bc42..99e383e35f 100644
--- a/moduleConfig.json
+++ b/moduleConfig.json
@@ -34,9 +34,7 @@
"core",
"cocos2d/compression/ZipUtils.js",
- "cocos2d/compression/base64.js",
- "cocos2d/compression/gzip.js",
- "cocos2d/compression/zlib.min.js"
+ "cocos2d/compression/base64.js"
],
"core" : [
"cocos2d/core/event-manager/CCEventHelper.js",
@@ -51,8 +49,6 @@
"cocos2d/core/platform/CCConfig.js",
"cocos2d/core/platform/miniFramework.js",
"cocos2d/core/platform/CCMacro.js",
- "cocos2d/core/platform/CCTypesWebGL.js",
- "cocos2d/core/platform/CCTypesPropertyDefine.js",
"cocos2d/core/platform/CCTypes.js",
"cocos2d/core/platform/CCEGLView.js",
"cocos2d/core/platform/CCScreen.js",
@@ -72,6 +68,7 @@
"cocos2d/core/event-manager/CCEventManager.js",
"cocos2d/core/event-manager/CCEventExtension.js",
+ "cocos2d/core/renderer/GlobalVertexBuffer.js",
"cocos2d/core/renderer/RendererCanvas.js",
"cocos2d/core/renderer/RendererWebGL.js",
"cocos2d/core/renderer/DirtyRegion.js",
@@ -250,6 +247,9 @@
"tilemap" : [
"core", "compression",
+ "cocos2d/compression/gzip.js",
+ "cocos2d/compression/zlib.min.js",
+
"cocos2d/tilemap/CCTGAlib.js",
"cocos2d/tilemap/CCTMXTiledMap.js",
"cocos2d/tilemap/CCTMXXMLParser.js",
@@ -490,4 +490,4 @@
"external" : ["box2d", "chipmunk", "socketio", "pluginx", "gaf"]
},
"bootFile" : "CCBoot.js"
-}
\ No newline at end of file
+}