From 5b9b882fc360e23aaa076f8ef8fd4ee165d8d953 Mon Sep 17 00:00:00 2001
From: "shengxiang.chen"
Date: Sat, 13 Jul 2013 13:14:20 +0800
Subject: [PATCH 001/141] optimize
---
cocos2d/CCCamera.js | 3 +-
cocos2d/base_nodes/CCNode.js | 207 ++++++++----------
.../CCLayer.js | 17 +-
3 files changed, 93 insertions(+), 134 deletions(-)
diff --git a/cocos2d/CCCamera.js b/cocos2d/CCCamera.js
index eef780d2e2..a3e3469c08 100644
--- a/cocos2d/CCCamera.js
+++ b/cocos2d/CCCamera.js
@@ -59,9 +59,10 @@ cc.Camera = cc.Class.extend(/** @lends cc.Action# */{
_upZ:null,
_dirty:null,
- _lookupMatrix:new cc.kmMat4(),
+ _lookupMatrix:null,
ctor:function () {
+ this._lookupMatrix = new cc.kmMat4();
this.restore();
},
diff --git a/cocos2d/base_nodes/CCNode.js b/cocos2d/base_nodes/CCNode.js
index ee492ad9d9..832a76c37d 100644
--- a/cocos2d/base_nodes/CCNode.js
+++ b/cocos2d/base_nodes/CCNode.js
@@ -165,15 +165,14 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
this._anchorPointInPoints = cc.p(0, 0);
this._contentSize = cc.size(0, 0);
this._position = cc.p(0, 0);
+ this._children = [];
var director = cc.Director.getInstance();
this._actionManager = director.getActionManager();
this._scheduler = director.getScheduler();
this._initializedNode = true;
this._additionalTransform = cc.AffineTransformMakeIdentity();
- this._additionalTransformDirty = false;
this._componentContainer = new cc.ComponentContainer(this);
- this._isTransitionFinished = false;
},
/**
@@ -195,49 +194,56 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
if (!array || array.length === 0)
return;
- var i, len = array.length;
+ var i, len = array.length,node;
var nodeCallbackType = cc.Node.StateCallbackType;
switch (callbackType) {
case nodeCallbackType.onEnter:
for (i = 0; i < len; i++) {
- if (array[i])
- array[i].onEnter();
+ node = array[i];
+ if (node)
+ node.onEnter();
}
break;
case nodeCallbackType.onExit:
for (i = 0; i < len; i++) {
- if (array[i])
- array[i].onExit();
+ node = array[i];
+ if (node)
+ node.onExit();
}
break;
case nodeCallbackType.onEnterTransitionDidFinish:
for (i = 0; i < len; i++) {
- if (array[i])
- array[i].onEnterTransitionDidFinish();
+ node = array[i];
+ if (node)
+ node.onEnterTransitionDidFinish();
}
break;
case nodeCallbackType.cleanup:
for (i = 0; i < len; i++) {
- if (array[i])
- array[i].cleanup();
+ node = array[i];
+ if (node)
+ node.cleanup();
}
break;
case nodeCallbackType.updateTransform:
for (i = 0; i < len; i++) {
- if (array[i])
- array[i].updateTransform();
+ node = array[i];
+ if (node)
+ node.updateTransform();
}
break;
case nodeCallbackType.onExitTransitionDidStart:
for (i = 0; i < len; i++) {
- if (array[i])
- array[i].onExitTransitionDidStart();
+ node = array[i];
+ if (node)
+ node.onExitTransitionDidStart();
}
break;
case nodeCallbackType.sortAllChildren:
for (i = 0; i < len; i++) {
- if (array[i])
- array[i].sortAllChildren();
+ node = array[i];
+ if (node)
+ node.sortAllChildren();
}
break;
default :
@@ -246,13 +252,6 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
}
},
- /**
- * set the dirty node
- */
- setNodeDirty:function () {
- this._transformDirty = this._inverseDirty = true;
- },
-
/**
*
get the skew degrees in X
* The X skew angle of the node in degrees.
@@ -589,7 +588,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
* @return {Number} The amount of children.
*/
getChildrenCount:function () {
- return this._children ? this._children.length : 0;
+ return this._children.length;
},
/**
@@ -604,8 +603,6 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
* }
*/
getChildren:function () {
- if (!this._children)
- this._children = [];
return this._children;
},
@@ -941,10 +938,6 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
return "";
},
- _childrenAlloc:function () {
- this._children = [];
- },
-
// composition: GET
/**
* Gets a child from the container given its tag
@@ -985,16 +978,12 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
cc.Assert(child._parent === null, "child already added. It can't be added again");
return;
}
- var tempzOrder = (zOrder != null) ? zOrder : child.getZOrder();
- var tmptag = (tag != null) ? tag : child.getTag();
- child.setTag(tmptag);
- if (!this._children)
- this._childrenAlloc();
-
- this._insertChild(child, tempzOrder);
+ var tmpzOrder = (zOrder != null) ? zOrder : child._zOrder;
+ child._tag = (tag != null) ? tag : child._tag;
+ this._insertChild(child, tmpzOrder);
+ child._parent = this;
- child.setParent(this);
if (this._running) {
child.onEnter();
// prevent onEnterTransitionDidFinish to be called twice when a node is added in onEnter
@@ -1041,7 +1030,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
*/
removeChild:function (child, cleanup) {
// explicit nil handling
- if (this._children == null)
+ if (this._children.length === 0)
return;
if (cleanup == null)
@@ -1181,20 +1170,22 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
*/
sortAllChildren:function () {
if (this._reorderChildDirty) {
- var i, j, length = this._children.length;
- var localChildren = this._children;
+ var _children = this._children;
+ var i, j, length = _children.length,tempChild;
+
// insertion sort
for (i = 0; i < length; i++) {
- var tempItem = localChildren[i];
+ var tempItem = _children[i];
j = i - 1;
+ tempChild = _children[j];
//continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
- while (j >= 0 && ( tempItem._zOrder < localChildren[j]._zOrder ||
- ( tempItem._zOrder == localChildren[j]._zOrder && tempItem._orderOfArrival < localChildren[j]._orderOfArrival ))) {
- localChildren[j + 1] = localChildren[j];
+ while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
+ ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
+ _children[j + 1] = tempChild;
j = j - 1;
}
- localChildren[j + 1] = tempItem;
+ _children[j + 1] = tempItem;
}
//don't need to check children recursively, that's done in visit of each child
@@ -2045,15 +2036,14 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
this._anchorPointInPoints = cc.p(0, 0);
this._contentSize = cc.size(0, 0);
this._position = cc.p(0, 0);
+ this._children = [];
var director = cc.Director.getInstance();
this._actionManager = director.getActionManager();
this._scheduler = director.getScheduler();
this._initializedNode = true;
this._additionalTransform = cc.AffineTransformMakeIdentity();
- this._additionalTransformDirty = false;
this._componentContainer = new cc.ComponentContainer(this);
- this._isTransitionFinished = false;
},
/**
@@ -2075,49 +2065,56 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
if (!array || array.length === 0)
return;
- var i, len = array.length;
+ var i, len = array.length,node;
var nodeCallbackType = cc.Node.StateCallbackType;
switch (callbackType) {
case nodeCallbackType.onEnter:
for (i = 0; i < len; i++) {
- if (array[i])
- array[i].onEnter();
+ node = array[i];
+ if (node)
+ node.onEnter();
}
break;
case nodeCallbackType.onExit:
for (i = 0; i < len; i++) {
- if (array[i])
- array[i].onExit();
+ node = array[i];
+ if (node)
+ node.onExit();
}
break;
case nodeCallbackType.onEnterTransitionDidFinish:
for (i = 0; i < len; i++) {
- if (array[i])
- array[i].onEnterTransitionDidFinish();
+ node = array[i];
+ if (node)
+ node.onEnterTransitionDidFinish();
}
break;
case nodeCallbackType.cleanup:
for (i = 0; i < len; i++) {
- if (array[i])
- array[i].cleanup();
+ node = array[i];
+ if (node)
+ node.cleanup();
}
break;
case nodeCallbackType.updateTransform:
for (i = 0; i < len; i++) {
- if (array[i])
- array[i].updateTransform();
+ node = array[i];
+ if (node)
+ node.updateTransform();
}
break;
case nodeCallbackType.onExitTransitionDidStart:
for (i = 0; i < len; i++) {
- if (array[i])
- array[i].onExitTransitionDidStart();
+ node = array[i];
+ if (node)
+ node.onExitTransitionDidStart();
}
break;
case nodeCallbackType.sortAllChildren:
for (i = 0; i < len; i++) {
- if (array[i])
- array[i].sortAllChildren();
+ node = array[i];
+ if (node)
+ node.sortAllChildren();
}
break;
default :
@@ -2126,13 +2123,6 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
}
},
- /**
- * set the dirty node
- */
- setNodeDirty:function () {
- this._transformDirty = this._inverseDirty = true;
- },
-
/**
*
get the skew degrees in X
* The X skew angle of the node in degrees.
@@ -2468,7 +2458,7 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
* @return {Number} The amount of children.
*/
getChildrenCount:function () {
- return this._children ? this._children.length : 0;
+ return this._children.length;
},
/**
@@ -2483,8 +2473,6 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
* }
*/
getChildren:function () {
- if (!this._children)
- this._children = [];
return this._children;
},
@@ -2821,10 +2809,6 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
return "";
},
- _childrenAlloc:function () {
- this._children = [];
- },
-
// composition: GET
/**
* Gets a child from the container given its tag
@@ -2865,16 +2849,12 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
cc.Assert(child._parent === null, "child already added. It can't be added again");
return;
}
- var tempzOrder = (zOrder != null) ? zOrder : child.getZOrder();
- var tmptag = (tag != null) ? tag : child.getTag();
- child.setTag(tmptag);
-
- if (!this._children)
- this._childrenAlloc();
- this._insertChild(child, tempzOrder);
+ var tmpzOrder = (zOrder != null) ? zOrder : child._zOrder;
+ child._tag = (tag != null) ? tag : child._tag;
+ this._insertChild(child, tmpzOrder);
+ child._parent = this;
- child.setParent(this);
if (this._running) {
child.onEnter();
// prevent onEnterTransitionDidFinish to be called twice when a node is added in onEnter
@@ -2920,7 +2900,7 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
*/
removeChild:function (child, cleanup) {
// explicit nil handling
- if (this._children == null)
+ if (this._children.length === 0)
return;
if (cleanup == null)
@@ -3010,7 +2990,7 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
child.cleanup();
// set parent nil at the end
- child.setParent(null);
+ child._parent = null;
cc.ArrayRemoveObject(this._children, child);
},
@@ -3060,20 +3040,22 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
*/
sortAllChildren:function () {
if (this._reorderChildDirty) {
- var i, j, length = this._children.length;
+ var _children = this._children;
+ var i, j, length = _children.length,tempChild;
// insertion sort
for (i = 0; i < length; i++) {
- var tempItem = this._children[i];
+ var tempItem = _children[i];
j = i - 1;
+ tempChild = _children[j];
//continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
- while (j >= 0 && ( tempItem._zOrder < this._children[j]._zOrder ||
- ( tempItem._zOrder == this._children[j]._zOrder && tempItem._orderOfArrival < this._children[j]._orderOfArrival ))) {
- this._children[j + 1] = this._children[j];
+ while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
+ ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
+ _children[j + 1] = tempChild;
j = j - 1;
}
- this._children[j + 1] = tempItem;
+ _children[j + 1] = tempItem;
}
//don't need to check children recursively, that's done in visit of each child
@@ -3561,7 +3543,7 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
//visit for canvas
var context = ctx || cc.renderContext, i;
- var children = this._children;
+ var children = this._children,child;
context.save();
this.transform(context);
if (children && children.length > 0) {
@@ -3569,15 +3551,17 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
this.sortAllChildren();
// draw children zOrder < 0
for (i = 0; i < len; i++) {
- if (children[i] && children[i]._zOrder < 0)
- children[i].visit(context);
+ child = children[i];
+ if (child && child._zOrder < 0)
+ child.visit(context);
else
break;
}
this.draw(context);
for (; i < len; i++) {
- if (children[i] && children[i]._zOrder >= 0)
- children[i].visit(context);
+ child = children[i];
+ if (child && child._zOrder >= 0)
+ child.visit(context);
}
} else
@@ -3755,30 +3739,15 @@ cc.Node = cc.Browser.supportWebGL ? cc.NodeWebGL : cc.NodeCanvas;
*/
cc.NodeRGBA = cc.Node.extend(/** @lends cc.NodeRGBA# */{
RGBAProtocol:true,
- _displayedOpacity:0,
- _realOpacity:0,
- _displayedColor:null,
- _realColor:null,
+ _displayedOpacity:255,
+ _realOpacity:255,
+ _displayedColor:cc.WHITE,
+ _realColor:cc.WHITE,
_cascadeColorEnabled:false,
_cascadeOpacityEnabled:false,
- ctor:function(){
- cc.Node.prototype.ctor.call(this);
- this._displayedOpacity = 255;
- this._realOpacity = 255;
- this._displayedColor = cc.WHITE;
- this._realColor = cc.WHITE;
- this._cascadeColorEnabled = false;
- this._cascadeOpacityEnabled = false;
- },
-
-
init:function(){
if(cc.Node.prototype.init.call(this)){
- this._displayedOpacity = this._realOpacity = 255;
- this._displayedColor = cc.WHITE;
- this._realColor = cc.WHITE;
- this._cascadeOpacityEnabled = this._cascadeColorEnabled = false;
return true;
}
return false;
@@ -3871,4 +3840,4 @@ cc.NodeRGBA = cc.Node.extend(/** @lends cc.NodeRGBA# */{
isOpacityModifyRGB:function(){
return false;
}
-});
+});
\ No newline at end of file
diff --git a/cocos2d/layers_scenes_transitions_nodes/CCLayer.js b/cocos2d/layers_scenes_transitions_nodes/CCLayer.js
index ce43b27e32..4298cddf0b 100644
--- a/cocos2d/layers_scenes_transitions_nodes/CCLayer.js
+++ b/cocos2d/layers_scenes_transitions_nodes/CCLayer.js
@@ -47,26 +47,15 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{
_isMouseEnabled:false,
_mousePriority:0,
- _initLayer:function () {
- this.setAnchorPoint(cc.p(0.5, 0.5));
- this._ignoreAnchorPointForPosition = true;
-
- var director = cc.Director.getInstance();
- this.setContentSize(director.getWinSize());
- this._isTouchEnabled = false;
- this._isAccelerometerEnabled = false;
- this._isMouseEnabled = false;
- this._touchMode = cc.TOUCH_ALL_AT_ONCE;
- this._touchPriority = 0;
- },
-
/**
*
* @return {Boolean}
*/
init:function () {
cc.Node.prototype.init.call(this);
- this._initLayer();
+ this._ignoreAnchorPointForPosition = true;
+ this.setAnchorPoint(cc.p(0.5, 0.5));
+ this.setContentSize(cc.Director.getInstance().getWinSize());
return true;
},
From 66d568f4c9bc415f78dcadd40359396f0099ba52 Mon Sep 17 00:00:00 2001
From: "shengxiang.chen"
Date: Thu, 25 Jul 2013 00:19:53 +0800
Subject: [PATCH 002/141] optimize
---
cocos2d/base_nodes/CCNode.js | 41 ++++++++++++++++++++++---------
cocos2d/platform/CCApplication.js | 14 +++++------
2 files changed, 36 insertions(+), 19 deletions(-)
diff --git a/cocos2d/base_nodes/CCNode.js b/cocos2d/base_nodes/CCNode.js
index 832a76c37d..7ac7c5d73c 100644
--- a/cocos2d/base_nodes/CCNode.js
+++ b/cocos2d/base_nodes/CCNode.js
@@ -3546,23 +3546,40 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
var children = this._children,child;
context.save();
this.transform(context);
- if (children && children.length > 0) {
- var len = children.length;
+ var len = children.length;
+ if (len > 0) {
this.sortAllChildren();
// draw children zOrder < 0
- for (i = 0; i < len; i++) {
- child = children[i];
- if (child && child._zOrder < 0)
- child.visit(context);
- else
- break;
+ /*var tag = children[0]._zOrder,tmpTag;
+ if(tag >= 0){
+ this.draw();
}
- this.draw(context);
- for (; i < len; i++) {
+ for(i = 0; i < len;i++){
child = children[i];
- if (child && child._zOrder >= 0)
- child.visit(context);
+ tmpTag = child._zOrder;
+ if(tmpTag>=0 && tag < 0){
+ this.draw();
+ }
+ child.visit(context);
+ tag = tmpTag;
}
+ if(tag<0){
+ this.draw();
+ }*/
+
+ for (i = 0; i < len; i++) {
+ child = children[i];
+ if (child._zOrder < 0)
+ child.visit(context);
+ else
+ break;
+ }
+ this.draw(context);
+ for (; i < len; i++) {
+ child = children[i];
+ if (child._zOrder >= 0)
+ child.visit(context);
+ }
} else
this.draw(context);
diff --git a/cocos2d/platform/CCApplication.js b/cocos2d/platform/CCApplication.js
index 2333a44075..ec22b28636 100644
--- a/cocos2d/platform/CCApplication.js
+++ b/cocos2d/platform/CCApplication.js
@@ -341,17 +341,17 @@ cc.Application = cc.Class.extend(/** @lends cc.Application# */{
if (!this.applicationDidFinishLaunching())
return 0;
- var callback;
- if (window.requestAnimFrame && this._animationInterval == 1 / 60) {
+ var callback, director = cc.Director.getInstance(), w = window;
+ if (w.requestAnimFrame && this._animationInterval == 1 / 60) {
callback = function () {
- cc.Director.getInstance().mainLoop();
- window.requestAnimFrame(callback);
+ director.mainLoop();
+ w.requestAnimFrame(callback);
};
- cc.log(window.requestAnimFrame);
- window.requestAnimFrame(callback);
+ //cc.log(window.requestAnimFrame);
+ w.requestAnimFrame(callback);
} else {
callback = function () {
- cc.Director.getInstance().mainLoop();
+ director.mainLoop();
};
setInterval(callback, this._animationInterval * 1000);
}
From 7e30cfceb39338359548fa37dffee268ec30b1f9 Mon Sep 17 00:00:00 2001
From: "shengxiang.chen"
Date: Tue, 30 Jul 2013 16:29:27 +0800
Subject: [PATCH 003/141] fixed #2452:optimize javascript code
---
cocos2d/base_nodes/CCNode.js | 38 ++++++++++--------------------------
1 file changed, 10 insertions(+), 28 deletions(-)
diff --git a/cocos2d/base_nodes/CCNode.js b/cocos2d/base_nodes/CCNode.js
index 6e1eb36288..876efdc95c 100644
--- a/cocos2d/base_nodes/CCNode.js
+++ b/cocos2d/base_nodes/CCNode.js
@@ -3549,37 +3549,19 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
if (len > 0) {
this.sortAllChildren();
// draw children zOrder < 0
- /*var tag = children[0]._zOrder,tmpTag;
- if(tag >= 0){
- this.draw();
+ for (i = 0; i < len; i++) {
+ child = children[i];
+ if (child._zOrder < 0)
+ child.visit(context);
+ else
+ break;
}
- for(i = 0; i < len;i++){
+ this.draw(context);
+ for (; i < len; i++) {
child = children[i];
- tmpTag = child._zOrder;
- if(tmpTag>=0 && tag < 0){
- this.draw();
- }
- child.visit(context);
- tag = tmpTag;
+ if (child._zOrder >= 0)
+ child.visit(context);
}
- if(tag<0){
- this.draw();
- }*/
-
- for (i = 0; i < len; i++) {
- child = children[i];
- if (child._zOrder < 0)
- child.visit(context);
- else
- break;
- }
- this.draw(context);
- for (; i < len; i++) {
- child = children[i];
- if (child._zOrder >= 0)
- child.visit(context);
- }
-
} else
this.draw(context);
From d885745130f3aca85bd9fc3cffa2fb24c3ecb0fd Mon Sep 17 00:00:00 2001
From: "shengxiang.chen"
Date: Tue, 30 Jul 2013 16:48:31 +0800
Subject: [PATCH 004/141] fixed #2452:optimize javascript code
---
cocos2d/layers_scenes_transitions_nodes/CCLayer.js | 1 +
1 file changed, 1 insertion(+)
diff --git a/cocos2d/layers_scenes_transitions_nodes/CCLayer.js b/cocos2d/layers_scenes_transitions_nodes/CCLayer.js
index 80632ba72f..42e3f5401e 100644
--- a/cocos2d/layers_scenes_transitions_nodes/CCLayer.js
+++ b/cocos2d/layers_scenes_transitions_nodes/CCLayer.js
@@ -580,6 +580,7 @@ cc.LayerRGBA = cc.Layer.extend(/** @lends cc.LayerRGBA# */{
_cascadeColorEnabled: false,
ctor: function () {
+ cc.Layer.prototype.ctor.call(this);
this.RGBAProtocol = true;
this._displayedOpacity = 255;
this._realOpacity = 255;
From 4b2c707d30bfe215acd1df499ff0150c2025114a Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Wed, 31 Jul 2013 11:43:31 +0800
Subject: [PATCH 005/141] Fixed #2441 avoid using temp cc.p for cc.Follow
---
cocos2d/actions/CCAction.js | 33 ++++++++++++++++++---------------
1 file changed, 18 insertions(+), 15 deletions(-)
diff --git a/cocos2d/actions/CCAction.js b/cocos2d/actions/CCAction.js
index 0f5a7e7cf4..82890d79b0 100644
--- a/cocos2d/actions/CCAction.js
+++ b/cocos2d/actions/CCAction.js
@@ -48,8 +48,8 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{
_tag:cc.ACTION_TAG_INVALID,
//**************Public Functions***********
- ctor:function(){
- this._originalTarget = null;
+ ctor:function () {
+ this._originalTarget = null;
this._target = null;
this._tag = cc.ACTION_TAG_INVALID;
},
@@ -73,7 +73,7 @@ cc.Action = cc.Class.extend(/** @lends cc.Action# */{
* returns a clone of action
* @return {cc.Action}
*/
- clone:function(){
+ clone:function () {
var action = new cc.Action();
action._originalTarget = null;
action._target = null;
@@ -211,7 +211,7 @@ cc.FiniteTimeAction = cc.Action.extend(/** @lends cc.FiniteTimeAction# */{
//! duration in seconds
_duration:0,
- ctor: function () {
+ ctor:function () {
cc.Action.prototype.ctor.call(this);
this._duration = 0;
},
@@ -244,7 +244,7 @@ cc.FiniteTimeAction = cc.Action.extend(/** @lends cc.FiniteTimeAction# */{
/**
*
*/
- clone:function(){
+ clone:function () {
return new cc.FiniteTimeAction();
}
});
@@ -261,8 +261,8 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{
_speed:0.0,
_innerAction:null,
- ctor:function(){
- cc.Action.prototype.ctor.call(this);
+ ctor:function () {
+ cc.Action.prototype.ctor.call(this);
this._speed = 0;
this._innerAction = null;
},
@@ -297,7 +297,7 @@ cc.Speed = cc.Action.extend(/** @lends cc.Speed# */{
* returns a clone of action
* @returns {cc.Speed}
*/
- clone:function(){
+ clone:function () {
var action = new cc.Speed();
action.initWithAction(this._innerAction.clone(), this._speed);
return action;
@@ -411,7 +411,7 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{
bottomBoundary:0.0,
_worldRect:null,
- ctor: function () {
+ ctor:function () {
cc.Action.prototype.ctor.call(this);
this._followedNode = null;
this._boundarySet = false;
@@ -427,7 +427,7 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{
this._worldRect = cc.RectZero();
},
- clone:function(){
+ clone:function () {
var action = new cc.Follow();
var locRect = this._worldRect;
var rect = new cc.Rect(locRect.x, locRect.y, locRect.width, locRect.height);
@@ -497,17 +497,20 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{
* @param {Number} dt
*/
step:function (dt) {
+ var tempPosX = this._followedNode.getPositionX();
+ var tempPosY = this._followedNode.getPositionY();
+ tempPosX = this._halfScreenSize.x - tempPosX;
+ tempPosY = this._halfScreenSize.y - tempPosY;
+
if (this._boundarySet) {
// whole map fits inside a single screen, no need to modify the position - unless map boundaries are increased
if (this._boundaryFullyCovered)
return;
- var tempPos = cc.pSub(this._halfScreenSize, this._followedNode.getPosition());
-
- this._target.setPosition(cc.p(cc.clampf(tempPos.x, this.leftBoundary, this.rightBoundary),
- cc.clampf(tempPos.y, this.bottomBoundary, this.topBoundary)));
+ this._target.setPosition(cc.clampf(tempPosX, this.leftBoundary, this.rightBoundary),
+ cc.clampf(tempPosY, this.bottomBoundary, this.topBoundary));
} else {
- this._target.setPosition(cc.pSub(this._halfScreenSize, this._followedNode.getPosition()));
+ this._target.setPosition(tempPosX, tempPosY);
}
},
From b6c89966474283f42201a1e3292ec2ee3753408e Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Wed, 31 Jul 2013 11:45:48 +0800
Subject: [PATCH 006/141] Fixed #2441 avoid using temp cc.p for
cc.CardinalSplineTo/cc.CardinalSplineBy
---
cocos2d/actions/CCActionCatmullRom.js | 73 +++++++++++++++------------
1 file changed, 41 insertions(+), 32 deletions(-)
diff --git a/cocos2d/actions/CCActionCatmullRom.js b/cocos2d/actions/CCActionCatmullRom.js
index bba06639c0..7407e7a7be 100644
--- a/cocos2d/actions/CCActionCatmullRom.js
+++ b/cocos2d/actions/CCActionCatmullRom.js
@@ -45,7 +45,7 @@
* @param {Number} t
* @return {cc.Point}
*/
- cc.CardinalSplineAt = function (p0, p1, p2, p3, tension, t) {
+cc.CardinalSplineAt = function (p0, p1, p2, p3, tension, t) {
var t2 = t * t;
var t3 = t2 * t;
@@ -69,7 +69,7 @@
* returns a new copy of the array reversed.
* @return {Array}
*/
-cc.reverseControlPoints = function( controlPoints ) {
+cc.reverseControlPoints = function (controlPoints) {
var newArray = [];
for (var i = controlPoints.length - 1; i >= 0; i--) {
newArray.push(cc.p(controlPoints[i].x, controlPoints[i].y));
@@ -77,9 +77,9 @@ cc.reverseControlPoints = function( controlPoints ) {
return newArray;
};
-cc.copyControlPoints = function( controlPoints){
+cc.copyControlPoints = function (controlPoints) {
var newArray = [];
- for (var i = 0; i< controlPoints.length; i++)
+ for (var i = 0; i < controlPoints.length; i++)
newArray.push(cc.p(controlPoints[i].x, controlPoints[i].y));
return newArray;
};
@@ -90,8 +90,8 @@ cc.copyControlPoints = function( controlPoints){
* @param {Number} pos
* @return {Array}
*/
-cc.getControlPointAt = function( controlPoints, pos ) {
- var p = Math.min( controlPoints.length-1, Math.max(pos,0));
+cc.getControlPointAt = function (controlPoints, pos) {
+ var p = Math.min(controlPoints.length - 1, Math.max(pos, 0));
return controlPoints[p];
};
@@ -160,8 +160,8 @@ cc.CardinalSplineTo = cc.ActionInterval.extend(/** @lends cc.CardinalSplineTo# *
* returns a new clone of the action
* @returns {cc.CardinalSplineTo}
*/
- clone:function(){
- var action = new cc.CardinalSplineTo();
+ clone:function () {
+ var action = new cc.CardinalSplineTo();
action.initWithDuration(this._duration, cc.copyControlPoints(this._points), this._tension);
return action;
},
@@ -172,7 +172,7 @@ cc.CardinalSplineTo = cc.ActionInterval.extend(/** @lends cc.CardinalSplineTo# *
startWithTarget:function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
// Issue #1441 from cocos2d-iphone
- this._deltaT = 1 / (this._points.length-1);
+ this._deltaT = 1 / (this._points.length - 1);
this._previousPosition = this._target.getPosition();
this._accumulatedDiff = cc.p(0, 0);
@@ -197,18 +197,21 @@ cc.CardinalSplineTo = cc.ActionInterval.extend(/** @lends cc.CardinalSplineTo# *
}
var newPos = cc.CardinalSplineAt(
- cc.getControlPointAt( this._points, p - 1),
- cc.getControlPointAt( this._points, p - 0),
- cc.getControlPointAt( this._points, p + 1),
- cc.getControlPointAt( this._points, p + 2),
+ cc.getControlPointAt(this._points, p - 1),
+ cc.getControlPointAt(this._points, p - 0),
+ cc.getControlPointAt(this._points, p + 1),
+ cc.getControlPointAt(this._points, p + 2),
this._tension, lt);
- if(cc.ENABLE_STACKABLE_ACTIONS){
- var node = this._target;
- var diff = cc.pSub(node.getPosition(), this._previousPosition);
- if (diff.x != 0 || diff.y != 0) {
- this._accumulatedDiff = cc.pAdd(this._accumulatedDiff, diff);
- newPos = cc.pAdd(newPos, this._accumulatedDiff);
+ if (cc.ENABLE_STACKABLE_ACTIONS) {
+ var tempX, tempY;
+ tempX = this._target.getPositionX() - this._previousPosition.x;
+ tempY = this._target.getPositionY() - this._previousPosition.y;
+ if (tempX != 0 || tempY != 0) {
+ this._accumulatedDiff.x += tempX;
+ this._accumulatedDiff.y += tempY;
+ newPos.x += this._accumulatedDiff.x;
+ newPos.y += this._accumulatedDiff.y;
}
}
this.updatePosition(newPos);
@@ -315,20 +318,24 @@ cc.CardinalSplineBy = cc.CardinalSplineTo.extend(/** @lends cc.CardinalSplineBy#
}
// convert to "diffs" to "reverse absolute"
- var reverseArray = cc.reverseControlPoints( copyConfig );
+ var reverseArray = cc.reverseControlPoints(copyConfig);
// 1st element (which should be 0,0) should be here too
p = reverseArray[ reverseArray.length - 1 ];
reverseArray.pop();
- p = cc.pNeg(p);
+ p.x = -p.x;
+ p.y = -p.y;
+
reverseArray.unshift(p);
- for (i = 1; i < reverseArray.length; ++i) {
+ for (var i = 1; i < reverseArray.length; ++i) {
current = reverseArray[i];
- current = cc.pNeg(current);
- var abs = cc.pAdd(current, p);
- reverseArray[i] = abs;
- p = abs;
+ current.x = -current.x;
+ current.y = -current.y;
+ current.x += p.x;
+ current.y += p.y;
+ reverseArray[i] = current;
+ p = current;
}
return cc.CardinalSplineBy.create(this._duration, reverseArray, this._tension);
},
@@ -338,16 +345,18 @@ cc.CardinalSplineBy = cc.CardinalSplineTo.extend(/** @lends cc.CardinalSplineBy#
* @param {cc.Point} newPos
*/
updatePosition:function (newPos) {
- var p = cc.pAdd(newPos, this._startPosition);
- this._target.setPosition(p);
- this._previousPosition = p;
+ var posX = newPos.x + this._startPosition.x;
+ var posY = newPos.y + this._startPosition.y;
+ this._target.setPosition(posX, posY);
+ this._previousPosition.x = posX;
+ this._previousPosition.y = posY;
},
/**
* returns a new clone of the action
* @returns {cc.CardinalSplineBy}
*/
- clone:function(){
+ clone:function () {
var a = new cc.CardinalSplineBy();
a.initWithDuration(this._duration, cc.copyControlPoints(this._points), this._tension);
return a;
@@ -393,7 +402,7 @@ cc.CatmullRomTo = cc.CardinalSplineTo.extend(/** @lends cc.CatmullRomTo# */{
* returns a new clone of the action
* @returns {cc.CatmullRomTo}
*/
- clone:function(){
+ clone:function () {
var action = new cc.CatmullRomTo();
action.initWithDuration(this._duration, cc.copyControlPoints(this._points));
return action;
@@ -438,7 +447,7 @@ cc.CatmullRomBy = cc.CardinalSplineBy.extend({
* returns a new clone of the action
* @returns {cc.CatmullRomBy}
*/
- clone:function(){
+ clone:function () {
var action = new cc.CatmullRomBy();
action.initWithDuration(this._duration, cc.copyControlPoints(this._points));
return action;
From 1a1736182e9b7c2ad273cfd2168f2258d15442a3 Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Wed, 31 Jul 2013 11:48:32 +0800
Subject: [PATCH 007/141] Fixed #2441 avoid using temp cc.p for cc.Grid3DAction
---
cocos2d/actions/CCActionGrid3D.js | 113 ++++++++++++++++++------------
1 file changed, 69 insertions(+), 44 deletions(-)
diff --git a/cocos2d/actions/CCActionGrid3D.js b/cocos2d/actions/CCActionGrid3D.js
index 36eb310623..3a7c812544 100644
--- a/cocos2d/actions/CCActionGrid3D.js
+++ b/cocos2d/actions/CCActionGrid3D.js
@@ -25,8 +25,8 @@
****************************************************************************/
cc.RAND_MAX = 0xffffff;
-cc.rand = function(){
- return Math.random() * cc.RAND_MAX;
+cc.rand = function () {
+ return Math.random() * cc.RAND_MAX;
};
/**
* cc.Waves3D action
@@ -38,7 +38,7 @@ cc.Waves3D = cc.Grid3DAction.extend(/** @lends cc.Waves3D# */{
_amplitude:null,
_amplitudeRate:null,
- ctor:function(){
+ ctor:function () {
cc.GridAction.prototype.ctor.call(this);
this._waves = 0;
@@ -98,7 +98,7 @@ cc.Waves3D = cc.Grid3DAction.extend(/** @lends cc.Waves3D# */{
update:function (time) {
var locGridSize = this._gridSize;
- var locAmplitude = this._amplitude, locPos = cc.p(0,0);
+ var locAmplitude = this._amplitude, locPos = cc.p(0, 0);
var locAmplitudeRate = this._amplitudeRate, locWaves = this._waves;
for (var i = 0; i < locGridSize.width + 1; ++i) {
for (var j = 0; j < locGridSize.height + 1; ++j) {
@@ -164,9 +164,11 @@ cc.FlipX3D = cc.Grid3DAction.extend(/** @lends cc.Waves3D# */{
var mx = Math.cos(angle);
var diff = new cc.Vertex3F();
-
- var v0 = this.originalVertex(cc.p(1, 1));
- var v1 = this.originalVertex(cc.p(0, 0));
+ var tempVer = cc.p(0, 0);
+ tempVer.x = tempVer.y = 1;
+ var v0 = this.originalVertex(tempVer);
+ tempVer.x = tempVer.y = 0;
+ var v1 = this.originalVertex(tempVer);
var x0 = v0.x;
var x1 = v1.x;
@@ -243,8 +245,11 @@ cc.FlipY3D = cc.FlipX3D.extend(/** @lends cc.FlipY3D# */{
var diff = new cc.Vertex3F();
- var v0 = this.originalVertex(cc.p(1, 1));
- var v1 = this.originalVertex(cc.p(0, 0));
+ var tempP = cc.p(0, 0);
+ tempP.x = tempP.y = 1;
+ var v0 = this.originalVertex(tempP);
+ tempP.x = tempP.y = 0;
+ var v1 = this.originalVertex(tempP);
var y0 = v0.y;
var y1 = v1.y;
@@ -322,10 +327,10 @@ cc.Lens3D = cc.Grid3DAction.extend(/** @lends cc.Lens3D# */{
_concave:false,
_dirty:false,
- ctor:function(){
+ ctor:function () {
cc.GridAction.prototype.ctor.call(this);
- this._position = null;
+ this._position = cc.p(0, 0);
this._radius = 0;
this._lensEffect = 0;
this._concave = false;
@@ -352,7 +357,7 @@ cc.Lens3D = cc.Grid3DAction.extend(/** @lends cc.Lens3D# */{
* Set whether lens is concave
* @param {Boolean} concave
*/
- setConcave:function(concave){
+ setConcave:function (concave) {
this._concave = concave;
},
@@ -385,7 +390,8 @@ cc.Lens3D = cc.Grid3DAction.extend(/** @lends cc.Lens3D# */{
*/
initWithDuration:function (duration, gridSize, position, radius) {
if (cc.Grid3DAction.prototype.initWithDuration.call(this, duration, gridSize)) {
- this._position = cc.p(-1, -1);
+ this._position.x = -1;
+ this._position.y = -1;
this.setPosition(position);
this._radius = radius;
this._lensEffect = 0.7;
@@ -399,27 +405,35 @@ cc.Lens3D = cc.Grid3DAction.extend(/** @lends cc.Lens3D# */{
if (this._dirty) {
var locGridSizeWidth = this._gridSize.width, locGridSizeHeight = this._gridSize.height;
var locRadius = this._radius, locLensEffect = this._lensEffect;
- var locPos = cc.p(0,0);
+ var locPos = cc.p(0, 0);
+ var vect = cc.p(0, 0);
+ var v, r, l, new_r, pre_log;
for (var i = 0; i < locGridSizeWidth + 1; ++i) {
for (var j = 0; j < locGridSizeHeight + 1; ++j) {
locPos.x = i;
locPos.y = j;
- var v = this.originalVertex(locPos);
- var vect = cc.pSub(this._position, v);
- var r = cc.pLength(vect);
+ v = this.originalVertex(locPos);
+ vect.x = this._position.x - v.x;
+ vect.y = this._position.y - v.y;
+ r = cc.pLength(vect);
if (r < locRadius) {
r = locRadius - r;
- var pre_log = r / locRadius;
+ pre_log = r / locRadius;
if (pre_log == 0)
pre_log = 0.001;
- var l = Math.log(pre_log) * locLensEffect;
- var new_r = Math.exp(l) * locRadius;
+ l = Math.log(pre_log) * locLensEffect;
+ new_r = Math.exp(l) * locRadius;
+
+ r = cc.pLength(vect);
+ if (r > 0) {
+ vect.x = vect.x / r;
+ vect.y = vect.y / r;
- if (cc.pLength(vect) > 0) {
- vect = cc.pNormalize(vect);
- v.z += cc.pLength(cc.pMult(vect, new_r)) * locLensEffect;
+ vect.x = vect.x * new_r;
+ vect.y = vect.y * new_r;
+ v.z += cc.pLength(vect) * locLensEffect;
}
}
this.setVertex(locPos, v);
@@ -457,7 +471,7 @@ cc.Ripple3D = cc.Grid3DAction.extend(/** @lends cc.Ripple3D# */{
_amplitude:null,
_amplitudeRate:null,
- ctor:function(){
+ ctor:function () {
cc.GridAction.prototype.ctor.call(this);
this._position = null;
@@ -539,14 +553,18 @@ cc.Ripple3D = cc.Grid3DAction.extend(/** @lends cc.Ripple3D# */{
update:function (time) {
var locGridSizeWidth = this._gridSize.width, locGridSizeHeight = this._gridSize.height;
- var locPos = cc.p(0,0), locRadius = this._radius;
+ var locPos = cc.p(0, 0), locRadius = this._radius;
var locWaves = this._waves, locAmplitude = this._amplitude, locAmplitudeRate = this._amplitudeRate;
+ var v, r, tempPos = cc.p(0, 0);
for (var i = 0; i < (locGridSizeWidth + 1); ++i) {
for (var j = 0; j < (locGridSizeHeight + 1); ++j) {
locPos.x = i;
locPos.y = j;
- var v = this.originalVertex(locPos);
- var r = cc.pLength(cc.pSub(this._position, v));
+ v = this.originalVertex(locPos);
+
+ tempPos.x = this._position.x - v.x;
+ tempPos.y = this._position.y - v.y;
+ r = cc.pLength(tempPos);
if (r < locRadius) {
r = locRadius - r;
@@ -584,7 +602,7 @@ cc.Shaky3D = cc.Grid3DAction.extend(/** @lends cc.Shaky3D# */{
_randRange:null,
_shakeZ:null,
- ctor:function(){
+ ctor:function () {
cc.GridAction.prototype.ctor.call(this);
this._randRange = 0;
@@ -610,12 +628,13 @@ cc.Shaky3D = cc.Grid3DAction.extend(/** @lends cc.Shaky3D# */{
update:function (time) {
var locGridSizeWidth = this._gridSize.width, locGridSizeHeight = this._gridSize.height;
- var locRandRange = this._randRange, locShakeZ = this._shakeZ, locP = cc.p(0,0);
+ var locRandRange = this._randRange, locShakeZ = this._shakeZ, locP = cc.p(0, 0);
+ var v;
for (var i = 0; i < (locGridSizeWidth + 1); ++i) {
for (var j = 0; j < (locGridSizeHeight + 1); ++j) {
locP.x = i;
locP.y = j;
- var v = this.originalVertex(locP);
+ v = this.originalVertex(locP);
v.x += (cc.rand() % (locRandRange * 2)) - locRandRange;
v.y += (cc.rand() % (locRandRange * 2)) - locRandRange;
if (locShakeZ)
@@ -650,7 +669,7 @@ cc.Liquid = cc.Grid3DAction.extend(/** @lends cc.Liquid# */{
_amplitude:null,
_amplitudeRate:null,
- ctor:function(){
+ ctor:function () {
cc.GridAction.prototype.ctor.call(this);
this._waves = 0;
@@ -709,13 +728,14 @@ cc.Liquid = cc.Grid3DAction.extend(/** @lends cc.Liquid# */{
},
update:function (time) {
- var locSizeWidth = this._gridSize.width, locSizeHeight = this._gridSize.height, locPos = cc.p(0,0);
+ var locSizeWidth = this._gridSize.width, locSizeHeight = this._gridSize.height, locPos = cc.p(0, 0);
var locWaves = this._waves, locAmplitude = this._amplitude, locAmplitudeRate = this._amplitudeRate;
+ var v;
for (var i = 1; i < locSizeWidth; ++i) {
for (var j = 1; j < locSizeHeight; ++j) {
locPos.x = i;
locPos.y = j;
- var v = this.originalVertex(locPos);
+ v = this.originalVertex(locPos);
v.x = (v.x + (Math.sin(time * Math.PI * locWaves * 2 + v.x * .01) * locAmplitude * locAmplitudeRate));
v.y = (v.y + (Math.sin(time * Math.PI * locWaves * 2 + v.y * .01) * locAmplitude * locAmplitudeRate));
this.setVertex(locPos, v);
@@ -750,7 +770,7 @@ cc.Waves = cc.Grid3DAction.extend(/** @lends cc.Waves# */{
_vertical:null,
_horizontal:null,
- ctor:function(){
+ ctor:function () {
cc.GridAction.prototype.ctor.call(this);
this._waves = 0;
@@ -815,14 +835,15 @@ cc.Waves = cc.Grid3DAction.extend(/** @lends cc.Waves# */{
},
update:function (time) {
- var locSizeWidth = this._gridSize.width, locSizeHeight = this._gridSize.height, locPos = cc.p(0,0);
+ var locSizeWidth = this._gridSize.width, locSizeHeight = this._gridSize.height, locPos = cc.p(0, 0);
var locVertical = this._vertical, locHorizontal = this._horizontal;
var locWaves = this._waves, locAmplitude = this._amplitude, locAmplitudeRate = this._amplitudeRate;
+ var v;
for (var i = 0; i < locSizeWidth + 1; ++i) {
for (var j = 0; j < locSizeHeight + 1; ++j) {
locPos.x = i;
locPos.y = j;
- var v = this.originalVertex(locPos);
+ v = this.originalVertex(locPos);
if (locVertical)
v.x = (v.x + (Math.sin(time * Math.PI * locWaves * 2 + v.y * .01) * locAmplitude * locAmplitudeRate));
if (locHorizontal)
@@ -862,7 +883,7 @@ cc.Twirl = cc.Grid3DAction.extend({
_amplitude:null,
_amplitudeRate:null,
- ctor:function(){
+ ctor:function () {
cc.GridAction.prototype.ctor.call(this);
this._position = null;
@@ -933,22 +954,26 @@ cc.Twirl = cc.Grid3DAction.extend({
update:function (time) {
var c = this._position;
- var locSizeWidth = this._gridSize.width, locSizeHeight = this._gridSize.height, locPos = cc.p(0,0);
+ var locSizeWidth = this._gridSize.width, locSizeHeight = this._gridSize.height, locPos = cc.p(0, 0);
var amp = 0.1 * this._amplitude * this._amplitudeRate;
var locTwirls = this._twirls;
+ var v, a, dX, dY, avg = cc.p(0, 0);
for (var i = 0; i < (locSizeWidth + 1); ++i) {
for (var j = 0; j < (locSizeHeight + 1); ++j) {
locPos.x = i;
locPos.y = j;
- var v = this.originalVertex(locPos);
+ v = this.originalVertex(locPos);
+
+ avg.x = i - (locSizeWidth / 2.0);
+ avg.y = j - (locSizeHeight / 2.0);
- var avg = cc.p(i - (locSizeWidth / 2.0), j - (locSizeHeight / 2.0));
+ a = cc.pLength(avg) * Math.cos(Math.PI / 2.0 + time * Math.PI * locTwirls * 2) * amp;
- var a = cc.pLength(avg) * Math.cos(Math.PI / 2.0 + time * Math.PI * locTwirls * 2) * amp;
- var d = cc.p(Math.sin(a) * (v.y - c.y) + Math.cos(a) * (v.x - c.x), Math.cos(a) * (v.y - c.y) - Math.sin(a) * (v.x - c.x));
+ dX = Math.sin(a) * (v.y - c.y) + Math.cos(a) * (v.x - c.x);
+ dY = Math.cos(a) * (v.y - c.y) - Math.sin(a) * (v.x - c.x);
- v.x = c.x + d.x;
- v.y = c.y + d.y;
+ v.x = c.x + dX;
+ v.y = c.y + dY;
this.setVertex(locPos, v);
}
From 53a086d5eb51573f59c2b6cb782a4dc6edd4aeb4 Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Wed, 31 Jul 2013 11:52:12 +0800
Subject: [PATCH 008/141] Fixed #2441 avoid using temp cc.p for
cc.ActionInterval
---
cocos2d/actions/CCActionInterval.js | 271 +++++++++++++++-------------
1 file changed, 147 insertions(+), 124 deletions(-)
diff --git a/cocos2d/actions/CCActionInterval.js b/cocos2d/actions/CCActionInterval.js
index 8029c44972..7bc4f0abb9 100644
--- a/cocos2d/actions/CCActionInterval.js
+++ b/cocos2d/actions/CCActionInterval.js
@@ -47,7 +47,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{
_elapsed:0,
_firstTick:false,
- ctor:function(){
+ ctor:function () {
cc.FiniteTimeAction.prototype.ctor.call(this);
this._elapsed = 0;
this._firstTick = false;
@@ -85,7 +85,7 @@ cc.ActionInterval = cc.FiniteTimeAction.extend(/** @lends cc.ActionInterval# */{
* returns a new clone of the action
* @returns {cc.ActionInterval}
*/
- clone:function(){
+ clone:function () {
var action = new cc.ActionInterval();
action.initWithDuration(this._duration);
return action;
@@ -197,7 +197,7 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{
* returns a new clone of the action
* @returns {cc.Sequence}
*/
- clone:function(){
+ clone:function () {
var action = new cc.Sequence();
action.initOneTwo(this._actions[0].clone(), this._actions[1].clone());
return action;
@@ -232,7 +232,7 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{
// action[0]
new_t = (locSplit) ? time / locSplit : 1;
- if(found === 0 && locLast === 1){
+ if (found === 0 && locLast === 1) {
// Reverse mode ?
// XXX: Bug. this case doesn't contemplate when _last==-1, found=0 and in "reverse mode"
// since it will require a hack to know if an action is on reverse mode or not.
@@ -259,7 +259,7 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{
}
// Last action found and it is done.
- if(locLast === found && locActions[found].isDone())
+ if (locLast === found && locActions[found].isDone())
return;
// Last action found and it is done
@@ -298,7 +298,7 @@ cc.Sequence = cc.ActionInterval.extend(/** @lends cc.Sequence# */{
*/
cc.Sequence.create = function (/*Multiple Arguments*/tempArray) {
var paraArray = (tempArray instanceof Array) ? tempArray : arguments;
- if((paraArray.length > 0) && (paraArray[paraArray.length-1] == null))
+ if ((paraArray.length > 0) && (paraArray[paraArray.length - 1] == null))
cc.log("parameters should not be ending with null in Javascript");
var prev = paraArray[0];
@@ -334,7 +334,7 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{
_actionInstant:false,
_innerAction:null, //CCFiniteTimeAction
- ctor: function () {
+ ctor:function () {
cc.ActionInterval.prototype.ctor.call(this);
this._times = 0;
this._total = 0;
@@ -366,7 +366,7 @@ cc.Repeat = cc.ActionInterval.extend(/** @lends cc.Repeat# */{
* returns a new clone of the action
* @returns {cc.Repeat}
*/
- clone:function(){
+ clone:function () {
var action = new cc.Repeat();
action.initWithAction(this._innerAction.clone(), this._times);
return action;
@@ -481,7 +481,7 @@ cc.Repeat.create = function (action, times) {
cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{
_innerAction:null, //CCActionInterval
- ctor:function(){
+ ctor:function () {
cc.ActionInterval.prototype.ctor.call(this);
this._innerAction = null;
},
@@ -501,7 +501,7 @@ cc.RepeatForever = cc.ActionInterval.extend(/** @lends cc.RepeatForever# */{
* returns a new clone of the action
* @returns {cc.RepeatForever}
*/
- clone:function(){
+ clone:function () {
var action = new cc.RepeatForever();
action.initWithAction(this._innerAction.clone());
return action;
@@ -586,7 +586,7 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{
_one:null,
_two:null,
- ctor: function(){
+ ctor:function () {
cc.ActionInterval.prototype.ctor.call(this);
this._one = null;
this._two = null;
@@ -625,7 +625,7 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{
* returns a new clone of the action
* @returns {cc.Spawn}
*/
- clone:function(){
+ clone:function () {
var action = new cc.Spawn();
action.initOneTwo(this._one.clone(), this._two.clone());
return action;
@@ -676,7 +676,7 @@ cc.Spawn = cc.ActionInterval.extend(/** @lends cc.Spawn# */{
*/
cc.Spawn.create = function (/*Multiple Arguments*/tempArray) {
var paramArray = (tempArray instanceof Array) ? tempArray : arguments;
- if((paramArray.length > 0) && (paramArray[paramArray.length-1] == null))
+ if ((paramArray.length > 0) && (paramArray[paramArray.length - 1] == null))
cc.log("parameters should not be ending with null in Javascript");
var prev = paramArray[0];
@@ -715,7 +715,7 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{
_startAngleY:0,
_diffAngleY:0,
- ctor: function () {
+ ctor:function () {
cc.ActionInterval.prototype.ctor.call(this);
this._dstAngleX = 0;
this._startAngleX = 0;
@@ -745,7 +745,7 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{
* returns a new clone of the action
* @returns {cc.RotateTo}
*/
- clone:function(){
+ clone:function () {
var action = new cc.RotateTo();
action.initWithDuration(this._duration, this._dstAngleX, this._dstAngleY);
return action;
@@ -760,9 +760,9 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{
// Calculate X
var locStartAngleX = target.getRotationX() % 360.0;
var locDiffAngleX = this._dstAngleX - locStartAngleX;
- if(locDiffAngleX > 180)
+ if (locDiffAngleX > 180)
locDiffAngleX -= 360;
- if(locDiffAngleX < -180)
+ if (locDiffAngleX < -180)
locDiffAngleX += 360;
this._startAngleX = locStartAngleX;
this._diffAngleX = locDiffAngleX;
@@ -770,11 +770,11 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{
// Calculate Y It's duplicated from calculating X since the rotation wrap should be the same
this._startAngleY = target.getRotationY() % 360.0;
var locDiffAngleY = this._dstAngleY - this._startAngleY;
- if(locDiffAngleY > 180)
+ if (locDiffAngleY > 180)
locDiffAngleY -= 360;
- if(locDiffAngleY < -180)
+ if (locDiffAngleY < -180)
locDiffAngleY += 360;
- this._diffAngleY = locDiffAngleY
+ this._diffAngleY = locDiffAngleY
},
/**
@@ -788,7 +788,7 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{
* @param {Number} time time in seconds
*/
update:function (time) {
- if (this._target){
+ if (this._target) {
this._target.setRotationX(this._startAngleX + this._diffAngleX * time);
this._target.setRotationY(this._startAngleY + this._diffAngleY * time);
}
@@ -807,7 +807,7 @@ cc.RotateTo = cc.ActionInterval.extend(/** @lends cc.RotateTo# */{
*/
cc.RotateTo.create = function (duration, deltaAngleX, deltaAngleY) {
var rotateTo = new cc.RotateTo();
- rotateTo.initWithDuration(duration, deltaAngleX,deltaAngleY);
+ rotateTo.initWithDuration(duration, deltaAngleX, deltaAngleY);
return rotateTo;
};
@@ -822,7 +822,7 @@ cc.RotateBy = cc.ActionInterval.extend(/** @lends cc.RotateBy# */{
_angleY:0,
_startAngleY:0,
- ctor: function () {
+ ctor:function () {
cc.ActionInterval.prototype.ctor.call(this);
this._angleX = 0;
this._startAngleX = 0;
@@ -849,7 +849,7 @@ cc.RotateBy = cc.ActionInterval.extend(/** @lends cc.RotateBy# */{
* returns a new clone of the action
* @returns {cc.RotateBy}
*/
- clone:function(){
+ clone:function () {
var action = new cc.RotateBy();
action.initWithDuration(this._duration, this._angleX, this._angleY);
return action;
@@ -913,7 +913,7 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{
_startPosition:null,
_previousPosition:null,
- ctor: function () {
+ ctor:function () {
cc.ActionInterval.prototype.ctor.call(this);
this._positionDelta = cc.p(0, 0);
@@ -938,7 +938,7 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{
* returns a new clone of the action
* @returns {cc.MoveBy}
*/
- clone: function () {
+ clone:function () {
var action = new cc.MoveBy();
action.initWithDuration(this._duration, this._positionDelta)
return action;
@@ -949,9 +949,12 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{
*/
startWithTarget:function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
- var locPos = target.getPosition();
- this._previousPosition = cc.p(locPos.x, locPos.y);
- this._startPosition = cc.p(locPos.x, locPos.y);
+ var locPosX = target.getPositionX();
+ var locPosY = target.getPositionY();
+ this._previousPosition.x = locPosX;
+ this._previousPosition.y = locPosY;
+ this._startPosition.x = locPosX;
+ this._startPosition.y = locPosY;
},
/**
@@ -959,16 +962,22 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{
*/
update:function (time) {
if (this._target) {
- if(cc.ENABLE_STACKABLE_ACTIONS){
- var currentPos = this._target.getPosition();
- var diff = cc.pSub(currentPos, this._previousPosition);
- this._startPosition = cc.pAdd(this._startPosition, diff);
- var newPos = cc.p(this._startPosition.x + this._positionDelta.x * time,
- this._startPosition.y + this._positionDelta.y * time);
- this._target.setPosition(newPos);
- this._previousPosition = newPos;
- } else{
- this._target.setPosition(cc.pAdd(this._startPosition, cc.pMult(this._positionDelta, t)));
+ var x = this._positionDelta.x * time;
+ var y = this._positionDelta.y * time;
+
+ if (cc.ENABLE_STACKABLE_ACTIONS) {
+ var targetX = this._target.getPositionX();
+ var targetY = this._target.getPositionY();
+ this._startPosition.x = this._startPosition.x + targetX - this._previousPosition.x;
+ this._startPosition.y = this._startPosition.y + targetY - this._previousPosition.y;
+ x = x + this._startPosition.x;
+ y = y + this._startPosition.y;
+
+ this._target.setPosition(x, y);
+ this._previousPosition.x = x;
+ this._previousPosition.y = y;
+ } else {
+ this._target.setPosition(this._startPosition.x + x, this._startPosition.y + y);
}
}
},
@@ -977,7 +986,7 @@ cc.MoveBy = cc.ActionInterval.extend(/** @lends cc.MoveBy# */{
* MoveTo reverse is not implemented
*/
reverse:function () {
- return cc.MoveBy.create(this._duration, cc.p( -this._positionDelta.x, -this._positionDelta.y));
+ return cc.MoveBy.create(this._duration, cc.p(-this._positionDelta.x, -this._positionDelta.y));
}
});
@@ -1005,7 +1014,7 @@ cc.MoveBy.create = function (duration, deltaPosition) {
*/
cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{
_endPosition:null,
- ctor: function () {
+ ctor:function () {
cc.MoveBy.prototype.ctor.call(this);
this._endPosition = cc.p(0, 0);
},
@@ -1027,7 +1036,7 @@ cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{
* returns a new clone of the action
* @returns {cc.MoveTo}
*/
- clone: function () {
+ clone:function () {
var action = new cc.MoveTo();
action.initWithDuration(this._duration, this._endPosition);
return action;
@@ -1038,7 +1047,8 @@ cc.MoveTo = cc.MoveBy.extend(/** @lends cc.MoveTo# */{
*/
startWithTarget:function (target) {
cc.MoveBy.prototype.startWithTarget.call(this, target);
- this._positionDelta = cc.pSub(this._endPosition, target.getPosition());
+ this._positionDelta.x = this._endPosition.x - target.getPositionX();
+ this._positionDelta.y = this._endPosition.y - target.getPositionY();
}
});
/**
@@ -1070,7 +1080,7 @@ cc.SkewTo = cc.ActionInterval.extend(/** @lends cc.SkewTo# */{
_deltaX:0,
_deltaY:0,
- ctor: function () {
+ ctor:function () {
cc.ActionInterval.prototype.ctor.call(this);
this._skewX = 0;
this._skewY = 0;
@@ -1102,7 +1112,7 @@ cc.SkewTo = cc.ActionInterval.extend(/** @lends cc.SkewTo# */{
* returns a new clone of the action
* @returns {cc.SkewTo}
*/
- clone: function () {
+ clone:function () {
var action = new cc.SkewTo();
action.initWithDuration(this._duration, this._endSkewX, this._endSkewY);
return action;
@@ -1178,7 +1188,7 @@ cc.SkewBy = cc.SkewTo.extend(/** @lends cc.SkewBy# */{
* returns a new clone of the action
* @returns {cc.SkewBy}
*/
- clone: function () {
+ clone:function () {
var action = new cc.SkewBy();
action.initWithDuration(this._duration, this._skewX, this._skewY);
return action;
@@ -1230,7 +1240,7 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{
_jumps:0,
_previousPosition:null,
- ctor: function () {
+ ctor:function () {
cc.ActionInterval.prototype.ctor.call(this);
this._startPosition = cc.p(0, 0);
this._previousPosition = cc.p(0, 0);
@@ -1259,7 +1269,7 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{
* returns a new clone of the action
* @returns {cc.JumpBy}
*/
- clone: function () {
+ clone:function () {
var action = new cc.JumpBy();
action.initWithDuration(this._duration, this._delta, this._height, this._jumps);
return action;
@@ -1270,9 +1280,12 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{
*/
startWithTarget:function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
- var locPos = target.getPosition();
- this._previousPosition = cc.p(locPos.x, locPos.y);
- this._startPosition = cc.p(locPos.x, locPos.y);
+ var locPosX = target.getPositionX();
+ var locPosY = target.getPositionY();
+ this._previousPosition.x = locPosX;
+ this._previousPosition.y = locPosY;
+ this._startPosition.x = locPosX;
+ this._startPosition.y = locPosY;
},
/**
@@ -1285,16 +1298,19 @@ cc.JumpBy = cc.ActionInterval.extend(/** @lends cc.JumpBy# */{
y += this._delta.y * time;
var x = this._delta.x * time;
- if(cc.ENABLE_STACKABLE_ACTIONS){
- var currentPos = this._target.getPosition();
-
- var diff = cc.pSub(currentPos, this._previousPosition);
- this._startPosition = cc.pAdd(diff, this._startPosition);
- var newPos = cc.pAdd(this._startPosition, cc.p(x, y));
- this._target.setPosition(newPos);
- this._previousPosition = newPos;
+ if (cc.ENABLE_STACKABLE_ACTIONS) {
+ var targetX = this._target.getPositionX();
+ var targetY = this._target.getPositionY();
+ this._startPosition.x = this._startPosition.x + targetX - this._previousPosition.x;
+ this._startPosition.y = this._startPosition.y + targetY - this._previousPosition.y;
+ x = x + this._startPosition.x;
+ y = y + this._startPosition.y;
+
+ this._target.setPosition(x, y);
+ this._previousPosition.x = x;
+ this._previousPosition.y = y;
} else {
- this._target.setPosition(cc.pAdd(this._startPosition, cc.p(x,y)));
+ this._target.setPosition(this._startPosition.x + x, this._startPosition.y + y);
}
}
},
@@ -1333,14 +1349,15 @@ cc.JumpTo = cc.JumpBy.extend(/** @lends cc.JumpTo# */{
*/
startWithTarget:function (target) {
cc.JumpBy.prototype.startWithTarget.call(this, target);
- this._delta = cc.p(this._delta.x - this._startPosition.x, this._delta.y - this._startPosition.y);
+ this._delta.x = this._delta.x - this._startPosition.x;
+ this._delta.y = this._delta.y - this._startPosition.y;
},
/**
* returns a new clone of the action
* @returns {cc.JumpTo}
*/
- clone: function(){
+ clone:function () {
var action = new cc.JumpTo();
action.initWithDuration(this._duration, this._delta, this._height, this._jumps);
return action;
@@ -1384,14 +1401,14 @@ cc.bezierAt = function (a, b, c, d, t) {
* @extends cc.ActionInterval
*/
cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{
- _config: null,
- _startPosition: null,
- _previousPosition: null,
+ _config:null,
+ _startPosition:null,
+ _previousPosition:null,
/**
* Constructor
*/
- ctor: function () {
+ ctor:function () {
cc.ActionInterval.prototype.ctor.call(this);
this._config = [];
this._startPosition = cc.p(0, 0);
@@ -1414,10 +1431,10 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{
* returns a new clone of the action
* @returns {cc.BezierBy}
*/
- clone:function(){
+ clone:function () {
var action = new cc.BezierBy();
var newConfigs = [];
- for(var i = 0; i < this._config.length; i++){
+ for (var i = 0; i < this._config.length; i++) {
var selConf = this._config[i];
newConfigs.push(cc.p(selConf.x, selConf.y));
}
@@ -1430,9 +1447,12 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{
*/
startWithTarget:function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
- var locPos = target.getPosition();
- this._previousPosition = cc.p(locPos.x, locPos.y);
- this._startPosition = cc.p(locPos.x, locPos.y);
+ var locPosX = target.getPositionX();
+ var locPosY = target.getPositionY();
+ this._previousPosition.x = locPosX;
+ this._previousPosition.y = locPosY;
+ this._startPosition.x = locPosX;
+ this._startPosition.y = locPosY;
},
/**
@@ -1454,16 +1474,18 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{
var x = cc.bezierAt(xa, xb, xc, xd, time);
var y = cc.bezierAt(ya, yb, yc, yd, time);
- if(cc.ENABLE_STACKABLE_ACTIONS){
- var currentPos = this._target.getPosition();
- var diff = cc.pSub(currentPos, this._previousPosition);
- this._startPosition = cc.pAdd(this._startPosition, diff);
- var newPos = cc.pAdd(this._startPosition, cc.p(x, y));
-
- this._target.setPosition(newPos);
- this._previousPosition = newPos;
+ if (cc.ENABLE_STACKABLE_ACTIONS) {
+ var targetX = this._target.getPositionX();
+ var targetY = this._target.getPositionY();
+ this._startPosition.x = this._startPosition.x + targetX - this._previousPosition.x;
+ this._startPosition.y = this._startPosition.y + targetY - this._previousPosition.y;
+ x = x + this._startPosition.x;
+ y = y + this._startPosition.y;
+ this._target.setPosition(x, y);
+ this._previousPosition.x = x;
+ this._previousPosition.y = y;
} else {
- this._target.setPosition(cc.pAdd(this._startPosition, cc.p(x,y)));
+ this._target.setPosition(this._startPosition.x + x, this._startPosition.y + y);
}
}
},
@@ -1474,8 +1496,8 @@ cc.BezierBy = cc.ActionInterval.extend(/** @lends cc.BezierBy# */{
reverse:function () {
var locConfig = this._config;
var r = [
- cc.pAdd(locConfig[1], cc.pNeg(locConfig[2]) ),
- cc.pAdd(locConfig[0], cc.pNeg(locConfig[2]) ),
+ cc.pAdd(locConfig[1], cc.pNeg(locConfig[2])),
+ cc.pAdd(locConfig[0], cc.pNeg(locConfig[2])),
cc.pNeg(locConfig[2]) ];
return cc.BezierBy.create(this._duration, r);
}
@@ -1505,7 +1527,7 @@ cc.BezierBy.create = function (t, c) {
cc.BezierTo = cc.BezierBy.extend(/** @lends cc.BezierTo# */{
_toConfig:null,
- ctor: function () {
+ ctor:function () {
cc.BezierBy.prototype.ctor.call(this);
this._toConfig = [];
},
@@ -1516,7 +1538,7 @@ cc.BezierTo = cc.BezierBy.extend(/** @lends cc.BezierTo# */{
* @return {Boolean}
*/
initWithDuration:function (t, c) {
- if(cc.ActionInterval.prototype.initWithDuration.call(this, t)){
+ if (cc.ActionInterval.prototype.initWithDuration.call(this, t)) {
this._toConfig = c;
return true;
}
@@ -1527,7 +1549,7 @@ cc.BezierTo = cc.BezierBy.extend(/** @lends cc.BezierTo# */{
* returns a new clone of the action
* @returns {cc.BezierTo}
*/
- clone: function () {
+ clone:function () {
var action = new cc.BezierTo();
action.initWithDuration(this._duration, this._toConfig);
return action;
@@ -1541,6 +1563,7 @@ cc.BezierTo = cc.BezierBy.extend(/** @lends cc.BezierTo# */{
var locStartPos = this._startPosition;
var locToConfig = this._toConfig;
var locConfig = this._config;
+
locConfig[0] = cc.pSub(locToConfig[0], locStartPos);
locConfig[1] = cc.pSub(locToConfig[1], locStartPos);
locConfig[2] = cc.pSub(locToConfig[2], locStartPos);
@@ -1577,7 +1600,7 @@ cc.ScaleTo = cc.ActionInterval.extend(/** @lends cc.ScaleTo# */{
_deltaX:0,
_deltaY:0,
- ctor: function () {
+ ctor:function () {
cc.ActionInterval.prototype.ctor.call(this);
this._scaleX = 1;
this._scaleY = 1;
@@ -1608,7 +1631,7 @@ cc.ScaleTo = cc.ActionInterval.extend(/** @lends cc.ScaleTo# */{
* returns a new clone of the action
* @returns {cc.ScaleTo}
*/
- clone: function(){
+ clone:function () {
var action = new cc.ScaleTo();
action.initWithDuration(this._duration, this._endScaleX, this._endScaleY);
return action;
@@ -1646,7 +1669,7 @@ cc.ScaleTo = cc.ActionInterval.extend(/** @lends cc.ScaleTo# */{
* // It scales to 0.5 in x and 2 in Y
* var actionTo = cc.ScaleTo.create(2, 0.5, 2);
*/
-cc.ScaleTo.create = function (duration, sx, sy){ //function overload
+cc.ScaleTo.create = function (duration, sx, sy) { //function overload
var scaleTo = new cc.ScaleTo();
scaleTo.initWithDuration(duration, sx, sy);
return scaleTo;
@@ -1678,7 +1701,7 @@ cc.ScaleBy = cc.ScaleTo.extend(/** @lends cc.ScaleBy# */{
* returns a new clone of the action
* @returns {cc.ScaleBy}
*/
- clone: function(){
+ clone:function () {
var action = new cc.ScaleBy();
action.initWithDuration(this._duration, this._endScaleX, this._endScaleY);
return action;
@@ -1710,7 +1733,7 @@ cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{
_times:0,
_originalState:false,
- ctor: function(){
+ ctor:function () {
cc.ActionInterval.prototype.ctor.call(this);
this._times = 0;
this._originalState = false;
@@ -1733,7 +1756,7 @@ cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{
* returns a new clone of the action
* @returns {cc.Blink}
*/
- clone: function(){
+ clone:function () {
var action = new cc.Blink();
action.initWithDuration(this._duration, this._times);
return action;
@@ -1750,12 +1773,12 @@ cc.Blink = cc.ActionInterval.extend(/** @lends cc.Blink# */{
}
},
- startWithTarget:function(target){
+ startWithTarget:function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
this._originalState = target.isVisible();
},
- stop:function(){
+ stop:function () {
this._target.setVisible(this._originalState);
cc.ActionInterval.prototype.stop.call(this);
},
@@ -1805,7 +1828,7 @@ cc.FadeIn = cc.ActionInterval.extend(/** @lends cc.FadeIn# */{
* returns a new clone of the action
* @returns {cc.FadeIn}
*/
- clone: function () {
+ clone:function () {
var action = new cc.FadeIn();
action.initWithDuration(this._duration);
return action;
@@ -1850,7 +1873,7 @@ cc.FadeOut = cc.ActionInterval.extend(/** @lends cc.FadeOut# */{
* returns a new clone of the action
* @returns {cc.FadeOut}
*/
- clone: function(){
+ clone:function () {
var action = new cc.FadeOut();
action.initWithDuration(this._duration);
return action;
@@ -1876,10 +1899,10 @@ cc.FadeOut.create = function (d) {
* @extends cc.ActionInterval
*/
cc.FadeTo = cc.ActionInterval.extend(/** @lends cc.FadeTo# */{
- _toOpacity: null,
- _fromOpacity: null,
+ _toOpacity:null,
+ _fromOpacity:null,
- ctor: function () {
+ ctor:function () {
cc.ActionInterval.prototype.ctor.call(this);
this._toOpacity = 0;
this._fromOpacity = 0;
@@ -1902,7 +1925,7 @@ cc.FadeTo = cc.ActionInterval.extend(/** @lends cc.FadeTo# */{
* returns a new clone of the action
* @returns {cc.FadeTo}
*/
- clone: function(){
+ clone:function () {
var action = new cc.FadeTo();
action.initWithDuration(this._duration, this._toOpacity);
return action;
@@ -1947,7 +1970,7 @@ cc.TintTo = cc.ActionInterval.extend(/** @lends cc.TintTo# */{
_to:null,
_from:null,
- ctor: function(){
+ ctor:function () {
cc.ActionInterval.prototype.ctor.call(this);
this._to = cc.c3b(0, 0, 0);
this._from = cc.c3b(0, 0, 0);
@@ -1972,7 +1995,7 @@ cc.TintTo = cc.ActionInterval.extend(/** @lends cc.TintTo# */{
* returns a new clone of the action
* @returns {cc.TintTo}
*/
- clone:function(){
+ clone:function () {
var action = new cc.TintTo();
var locTo = this._to;
action.initWithDuration(this._duration, locTo.r, locTo.g, locTo.b);
@@ -1993,7 +2016,7 @@ cc.TintTo = cc.ActionInterval.extend(/** @lends cc.TintTo# */{
update:function (time) {
var locFrom = this._from, locTo = this._to;
this._target.setColor(cc.c3b(locFrom.r + (locTo.r - locFrom.r) * time,
- (locFrom.g + (locTo.g - locFrom.g) * time),(locFrom.b + (locTo.b - locFrom.b) * time)));
+ (locFrom.g + (locTo.g - locFrom.g) * time), (locFrom.b + (locTo.b - locFrom.b) * time)));
}
});
@@ -2027,14 +2050,14 @@ cc.TintBy = cc.ActionInterval.extend(/** @lends cc.TintBy# */{
_fromG:0,
_fromB:0,
- ctor:function(){
+ ctor:function () {
cc.ActionInterval.prototype.ctor.call(this);
- this._deltaR=0;
- this._deltaG=0;
- this._deltaB=0;
- this._fromR=0;
- this._fromG=0;
- this._fromB=0;
+ this._deltaR = 0;
+ this._deltaG = 0;
+ this._deltaB = 0;
+ this._fromR = 0;
+ this._fromG = 0;
+ this._fromB = 0;
},
/**
@@ -2058,7 +2081,7 @@ cc.TintBy = cc.ActionInterval.extend(/** @lends cc.TintBy# */{
* returns a new clone of the action
* @returns {cc.TintBy}
*/
- clone: function(){
+ clone:function () {
var action = new cc.TintBy();
action.initWithDuration(this._duration, this._deltaR, this._deltaG, this._deltaB);
return action;
@@ -2134,8 +2157,8 @@ cc.DelayTime = cc.ActionInterval.extend(/** @lends cc.DelayTime# */{
* returns a new clone of the action
* @returns {cc.DelayTime}
*/
- clone: function(){
- var action = new cc.DelayTime();
+ clone:function () {
+ var action = new cc.DelayTime();
action.initWithDuration(this._duration);
return action;
}
@@ -2166,7 +2189,7 @@ cc.DelayTime.create = function (d) {
cc.ReverseTime = cc.ActionInterval.extend(/** @lends cc.ReverseTime# */{
_other:null,
- ctor:function(){
+ ctor:function () {
cc.ActionInterval.prototype.ctor.call(this);
this._other = null;
},
@@ -2191,7 +2214,7 @@ cc.ReverseTime = cc.ActionInterval.extend(/** @lends cc.ReverseTime# */{
* returns a new clone of the action
* @returns {cc.ReverseTime}
*/
- clone: function(){
+ clone:function () {
var action = new cc.ReverseTime();
action.initWithAction(this._other.clone());
return action;
@@ -2254,13 +2277,13 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{
_executedLoops:0,
_splitTimes:null,
- ctor:function(){
+ ctor:function () {
cc.ActionInterval.prototype.ctor.call(this);
- this._animation=null;
- this._nextFrame=0;
- this._origFrame=null;
- this._executedLoops=0;
- this._splitTimes=null;
+ this._animation = null;
+ this._nextFrame = 0;
+ this._origFrame = null;
+ this._executedLoops = 0;
+ this._splitTimes = null;
},
/**
@@ -2314,7 +2337,7 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{
* returns a new clone of the action
* @returns {cc.Animate}
*/
- clone: function(){
+ clone:function () {
var action = new cc.Animate();
action.initWithAnimation(this._animation.clone());
return action;
@@ -2356,7 +2379,7 @@ cc.Animate = cc.ActionInterval.extend(/** @lends cc.Animate# */{
if (locSplitTimes[i] <= time) {
this._target.setDisplayFrame(frames[i].getSpriteFrame());
this._nextFrame = i + 1;
- }else{
+ } else {
// Issue 1438. Could be more than one frame per tick, due to low frame rate or frame delta < 1/FPS
break;
}
@@ -2421,7 +2444,7 @@ cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{
_action:null,
_forcedTarget:null,
- ctor: function(){
+ ctor:function () {
cc.ActionInterval.prototype.ctor.call(this);
this._action = null;
this._forcedTarget = null;
@@ -2446,7 +2469,7 @@ cc.TargetedAction = cc.ActionInterval.extend(/** @lends cc.TargetedAction# */{
* returns a new clone of the action
* @returns {cc.TargetedAction}
*/
- clone:function(){
+ clone:function () {
var action = new cc.TargetedAction();
action.initWithTarget(this._forcedTarget, this._action.clone());
return action;
From 85151f9816b211afb76417938e6398aeb9f202f6 Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Wed, 31 Jul 2013 11:52:54 +0800
Subject: [PATCH 009/141] Fixed #2441 avoid using temp cc.p for cc.PageTurn3D
---
cocos2d/actions/CCActionPageTurn3D.js | 7 +++++--
1 file changed, 5 insertions(+), 2 deletions(-)
diff --git a/cocos2d/actions/CCActionPageTurn3D.js b/cocos2d/actions/CCActionPageTurn3D.js
index 0f7980e8a6..7341694a25 100644
--- a/cocos2d/actions/CCActionPageTurn3D.js
+++ b/cocos2d/actions/CCActionPageTurn3D.js
@@ -52,10 +52,13 @@ cc.PageTurn3D = cc.Grid3DAction.extend(/** @lends cc.PageTurn3D# */{
var cosTheta = Math.cos(theta);
var locGridSize = this._gridSize;
+ var locVer = cc.p(0, 0);
for (var i = 0; i <= locGridSize.width; ++i) {
for (var j = 0; j <= locGridSize.height; ++j) {
+ locVer.x = i;
+ locVer.y = j;
// Get original vertex
- var p = this.originalVertex(cc.p(i, j));
+ var p = this.originalVertex(locVer);
var R = Math.sqrt((p.x * p.x) + ((p.y - ay) * (p.y - ay)));
var r = R * sinTheta;
@@ -82,7 +85,7 @@ cc.PageTurn3D = cc.Grid3DAction.extend(/** @lends cc.PageTurn3D# */{
p.z = 0.5;
// Set new coords
- this.setVertex(cc.p(i, j), p);
+ this.setVertex(locVer, p);
}
}
}
From e8c71d012328f177e8ebdea111d028de74a429e5 Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Wed, 31 Jul 2013 11:53:39 +0800
Subject: [PATCH 010/141] Fixed #2441 avoid using temp cc.p for
cc.TiledGrid3DAction
---
cocos2d/actions/CCActionTiledGrid.js | 107 +++++++++++++++++----------
1 file changed, 68 insertions(+), 39 deletions(-)
diff --git a/cocos2d/actions/CCActionTiledGrid.js b/cocos2d/actions/CCActionTiledGrid.js
index da347808a9..4cd0a55bce 100644
--- a/cocos2d/actions/CCActionTiledGrid.js
+++ b/cocos2d/actions/CCActionTiledGrid.js
@@ -33,7 +33,7 @@ cc.ShakyTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.ShakyTiles3D# */{
_randRange:0,
_shakeZ:false,
- ctor:function(){
+ ctor:function () {
cc.GridAction.prototype.ctor.call(this);
this._randRange = 0;
this._shakeZ = false;
@@ -58,9 +58,12 @@ cc.ShakyTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.ShakyTiles3D# */{
update:function (time) {
var locGridSize = this._gridSize, locRandRange = this._randRange;
+ var locPos = cc.p(0, 0);
for (var i = 0; i < locGridSize.width; ++i) {
for (var j = 0; j < locGridSize.height; ++j) {
- var coords = this.originalTile(cc.p(i, j));
+ locPos.x = i;
+ locPos.y = j;
+ var coords = this.originalTile(locPos);
// X
coords.bl.x += ( cc.rand() % (locRandRange * 2) ) - locRandRange;
@@ -81,7 +84,7 @@ cc.ShakyTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.ShakyTiles3D# */{
coords.tr.z += ( cc.rand() % (locRandRange * 2) ) - locRandRange;
}
- this.setTile(cc.p(i, j), coords);
+ this.setTile(locPos, coords);
}
}
}
@@ -111,7 +114,7 @@ cc.ShatteredTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.ShatteredTiles3D
_once:false,
_shatterZ:false,
- ctor:function(){
+ ctor:function () {
cc.GridAction.prototype.ctor.call(this);
this._randRange = 0;
this._shakeZ = false;
@@ -139,9 +142,12 @@ cc.ShatteredTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.ShatteredTiles3D
update:function (time) {
if (this._once === false) {
var locGridSize = this._gridSize, locRandRange = this._randRange;
+ var coords, locPos = cc.p(0, 0);
for (var i = 0; i < locGridSize.width; ++i) {
for (var j = 0; j < locGridSize.height; ++j) {
- var coords = this.originalTile(cc.p(i, j));
+ locPos.x = i;
+ locPos.y = j;
+ coords = this.originalTile(locPos);
// X
coords.bl.x += ( cc.rand() % (locRandRange * 2) ) - locRandRange;
@@ -161,7 +167,7 @@ cc.ShatteredTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.ShatteredTiles3D
coords.tl.z += ( cc.rand() % (locRandRange * 2) ) - locRandRange;
coords.tr.z += ( cc.rand() % (locRandRange * 2) ) - locRandRange;
}
- this.setTile(cc.p(i, j), coords);
+ this.setTile(locPos, coords);
}
}
this._once = true;
@@ -319,11 +325,15 @@ cc.ShuffleTiles = cc.TiledGrid3DAction.extend(/** @lends cc.ShuffleTiles# */{
update:function (time) {
var tileIndex = 0, locGridSize = this._gridSize, locTiles = this._tiles;
+ var selTile, locPos = cc.p(0, 0);
for (var i = 0; i < locGridSize.width; ++i) {
for (var j = 0; j < locGridSize.height; ++j) {
- var selTile = locTiles[tileIndex];
- selTile.position = cc.pMult(cc.p(selTile.delta.width, selTile.delta.height), time);
- this.placeTile(cc.p(i, j), selTile);
+ locPos.x = i;
+ locPos.y = j;
+ selTile = locTiles[tileIndex];
+ selTile.position.x = selTile.delta.width * time;
+ selTile.position.y = selTile.delta.height * time;
+ this.placeTile(locPos, selTile);
++tileIndex;
}
}
@@ -354,10 +364,11 @@ cc.FadeOutTRTiles = cc.TiledGrid3DAction.extend(/** @lends cc.FadeOutTRTiles# */
* @param {Number} time
*/
testFunc:function (pos, time) {
- var n = cc.pMult(cc.p(this._gridSize.width, this._gridSize.height), time);
- if ((n.x + n.y) == 0.0)
+ var locX = this._gridSize.width * time;
+ var locY = this._gridSize.height * time;
+ if ((locX + locY) == 0.0)
return 1.0;
- return Math.pow((pos.width + pos.height) / (n.x + n.y), 6);
+ return Math.pow((pos.width + pos.height) / (locX + locY), 6);
},
/**
@@ -402,15 +413,20 @@ cc.FadeOutTRTiles = cc.TiledGrid3DAction.extend(/** @lends cc.FadeOutTRTiles# */
update:function (time) {
var locGridSize = this._gridSize;
+ var locPos = cc.p(0, 0), locSize = cc.size(0, 0), distance;
for (var i = 0; i < locGridSize.width; ++i) {
for (var j = 0; j < locGridSize.height; ++j) {
- var distance = this.testFunc(cc.SizeMake(i, j), time);
+ locPos.x = i;
+ locPos.y = j;
+ locSize.width = i;
+ locSize.height = j;
+ distance = this.testFunc(locSize, time);
if (distance == 0)
- this.turnOffTile(cc.p(i, j));
+ this.turnOffTile(locPos);
else if (distance < 1)
- this.transformTile(cc.p(i, j), distance);
+ this.transformTile(locPos, distance);
else
- this.turnOnTile(cc.p(i, j));
+ this.turnOnTile(locPos);
}
}
}
@@ -439,11 +455,12 @@ cc.FadeOutBLTiles = cc.FadeOutTRTiles.extend(/** @lends cc.FadeOutBLTiles# */{
* @param {Number} time
*/
testFunc:function (pos, time) {
- var n = cc.pMult(cc.p(this._gridSize.width, this._gridSize.height), (1.0 - time));
+ var locX = this._gridSize.width * (1.0 - time);
+ var locY = this._gridSize.height * (1.0 - time);
if ((pos.width + pos.height) == 0)
return 1.0;
- return Math.pow((n.x + n.y) / (pos.width + pos.height), 6);
+ return Math.pow((locX + locY) / (pos.width + pos.height), 6);
}
});
@@ -466,10 +483,10 @@ cc.FadeOutBLTiles.create = function (duration, gridSize) {
*/
cc.FadeOutUpTiles = cc.FadeOutTRTiles.extend(/** @lends cc.FadeOutUpTiles# */{
testFunc:function (pos, time) {
- var n = cc.pMult(cc.p(this._gridSize.width, this._gridSize.height), time);
- if (n.y == 0.0)
+ var locY = this._gridSize.height * time;
+ if (locY == 0.0)
return 1.0;
- return Math.pow(pos.height / n.y, 6);
+ return Math.pow(pos.height / locY, 6);
},
transformTile:function (pos, distance) {
@@ -504,10 +521,10 @@ cc.FadeOutUpTiles.create = function (duration, gridSize) {
*/
cc.FadeOutDownTiles = cc.FadeOutUpTiles.extend(/** @lends cc.FadeOutDownTiles# */{
testFunc:function (pos, time) {
- var n = cc.pMult(cc.p(this._gridSize.width, this._gridSize.height), (1.0 - time));
+ var locY = this._gridSize.height * (1.0 - time);
if (pos.height == 0)
return 1.0;
- return Math.pow(n.y / pos.height, 6);
+ return Math.pow(locY / pos.height, 6);
}
});
@@ -603,9 +620,11 @@ cc.TurnOffTiles = cc.TiledGrid3DAction.extend(/** @lends cc.TurnOffTiles# */{
*/
update:function (time) {
var l = 0 | (time * this._tilesCount), locGridSize = this._gridSize;
+ var t,tilePos = cc.p(0,0);
for (var i = 0; i < this._tilesCount; i++) {
- var t = this._tilesOrder[i];
- var tilePos = cc.p(0 | (t / locGridSize.height), t % (0 | locGridSize.height));
+ t = this._tilesOrder[i];
+ tilePos.x = 0 | (t / locGridSize.height);
+ tilePos.y = t % (0 | locGridSize.height);
if (i < l)
this.turnOffTile(tilePos);
else
@@ -645,7 +664,7 @@ cc.WavesTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.WavesTiles3D# */{
_amplitude:0,
_amplitudeRate:0,
- ctor:function(){
+ ctor:function () {
cc.GridAction.prototype.ctor.call(this);
this._waves = 0;
this._amplitude = 0;
@@ -704,15 +723,18 @@ cc.WavesTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.WavesTiles3D# */{
update:function (time) {
var locGridSize = this._gridSize, locWaves = this._waves, locAmplitude = this._amplitude, locAmplitudeRate = this._amplitudeRate;
+ var locPos = cc.p(0, 0), coords;
for (var i = 0; i < locGridSize.width; i++) {
for (var j = 0; j < locGridSize.height; j++) {
- var coords = this.originalTile(cc.p(i, j));
+ locPos.x = i;
+ locPos.y = j;
+ coords = this.originalTile(locPos);
coords.bl.z = (Math.sin(time * Math.PI * locWaves * 2 +
(coords.bl.y + coords.bl.x) * 0.01) * locAmplitude * locAmplitudeRate);
coords.br.z = coords.bl.z;
coords.tl.z = coords.bl.z;
coords.tr.z = coords.bl.z;
- this.setTile(cc.p(i, j), coords);
+ this.setTile(locPos, coords);
}
}
}
@@ -742,7 +764,7 @@ cc.JumpTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.JumpTiles3D# */{
_amplitude:0,
_amplitudeRate:0,
- ctor:function(){
+ ctor:function () {
cc.GridAction.prototype.ctor.call(this);
this._jumps = 0;
this._amplitude = 0;
@@ -804,11 +826,14 @@ cc.JumpTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.JumpTiles3D# */{
var locGridSize = this._gridSize;
var locGrid = this._target.getGrid();
+ var coords, locPos = cc.p(0, 0);
for (var i = 0; i < locGridSize.width; i++) {
for (var j = 0; j < locGridSize.height; j++) {
+ locPos.x = i;
+ locPos.y = j;
//hack for html5
//var coords = this.originalTile(cc.p(i, j));
- var coords = locGrid.originalTile(cc.p(i, j));
+ coords = locGrid.originalTile(locPos);
if (((i + j) % 2) == 0) {
coords.bl.z += sinz;
@@ -823,7 +848,7 @@ cc.JumpTiles3D = cc.TiledGrid3DAction.extend(/** @lends cc.JumpTiles3D# */{
}
//hack for html5
//this.setTile(cc.p(i, j), coords);
- locGrid.setTile(cc.p(i, j), coords);
+ locGrid.setTile(locPos, coords);
}
}
}
@@ -852,7 +877,7 @@ cc.SplitRows = cc.TiledGrid3DAction.extend(/** @lends cc.SplitRows# */{
_rows:0,
_winSize:null,
- ctor:function(){
+ ctor:function () {
cc.GridAction.prototype.ctor.call(this);
this._rows = 0;
this._winSize = null;
@@ -871,9 +896,11 @@ cc.SplitRows = cc.TiledGrid3DAction.extend(/** @lends cc.SplitRows# */{
update:function (time) {
var locGridSize = this._gridSize, locWinSizeWidth = this._winSize.width;
+ var coords, direction, locPos = cc.p(0, 0);
for (var j = 0; j < locGridSize.height; ++j) {
- var coords = this.originalTile(cc.p(0, j));
- var direction = 1;
+ locPos.y = j;
+ coords = this.originalTile(locPos);
+ direction = 1;
if ((j % 2 ) == 0)
direction = -1;
@@ -883,7 +910,7 @@ cc.SplitRows = cc.TiledGrid3DAction.extend(/** @lends cc.SplitRows# */{
coords.tl.x += direction * locWinSizeWidth * time;
coords.tr.x += direction * locWinSizeWidth * time;
- this.setTile(cc.p(0, j), coords);
+ this.setTile(locPos, coords);
}
},
@@ -914,7 +941,7 @@ cc.SplitCols = cc.TiledGrid3DAction.extend(/** @lends cc.SplitCols# */{
_cols:0,
_winSize:null,
- ctor:function(){
+ ctor:function () {
cc.GridAction.prototype.ctor.call(this);
this._cols = 0;
this._winSize = null;
@@ -932,9 +959,11 @@ cc.SplitCols = cc.TiledGrid3DAction.extend(/** @lends cc.SplitCols# */{
update:function (time) {
var locGridSizeWidth = this._gridSize.width, locWinSizeHeight = this._winSize.height;
+ var coords, direction, locPos = cc.p(0, 0);
for (var i = 0; i < locGridSizeWidth; ++i) {
- var coords = this.originalTile(cc.p(i, 0));
- var direction = 1;
+ locPos.x = i;
+ coords = this.originalTile(locPos);
+ direction = 1;
if ((i % 2 ) == 0)
direction = -1;
@@ -944,7 +973,7 @@ cc.SplitCols = cc.TiledGrid3DAction.extend(/** @lends cc.SplitCols# */{
coords.tl.y += direction * locWinSizeHeight * time;
coords.tr.y += direction * locWinSizeHeight * time;
- this.setTile(cc.p(i, 0), coords);
+ this.setTile(locPos, coords);
}
},
From cfbbdd78bdae481d881144b756f7fe73696e0c05 Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Wed, 31 Jul 2013 14:22:13 +0800
Subject: [PATCH 011/141] Issue #2445 refactor code for rendering classes
---
cocos2d/base_nodes/CCNode.js | 201 ++++++++++------------
cocos2d/kazmath/mat4.js | 3 +-
cocos2d/label_nodes/CCLabelTTF.js | 64 ++-----
cocos2d/platform/CCApplication.js | 4 +-
cocos2d/sprite_nodes/CCAnimation.js | 6 +-
cocos2d/sprite_nodes/CCAnimationCache.js | 1 -
cocos2d/sprite_nodes/CCSprite.js | 172 +++---------------
cocos2d/sprite_nodes/CCSpriteBatchNode.js | 148 +++++++---------
cocos2d/sprite_nodes/CCSpriteFrame.js | 10 +-
9 files changed, 198 insertions(+), 411 deletions(-)
diff --git a/cocos2d/base_nodes/CCNode.js b/cocos2d/base_nodes/CCNode.js
index 553ec00c9b..0b34abf088 100644
--- a/cocos2d/base_nodes/CCNode.js
+++ b/cocos2d/base_nodes/CCNode.js
@@ -48,9 +48,6 @@ cc.NODE_ON_EXIT = null;
cc.s_globalOrderOfArrival = 1;
-
-//cc.NodeBase = cc.Class.extend(/** @lends cc.Node# */{
-
/**
cc.Node is the main element. Anything thats gets drawn or contains things that get drawn is a cc.Node.
The most popular cc.Nodes are: cc.Scene, cc.Layer, cc.Sprite, cc.Menu. (WebGL implement)
Position (x,y) of the node in OpenGL coordinates. (0,0) is the left-bottom corner.
+ * @const
* @return {cc.Point}
*/
getPosition:function () {
- return cc.p(this._position.x, this._position.y);
+ return this._position; //cc.p(this._position.x, this._position.y);
},
/**
@@ -634,10 +626,11 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
* The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner.
* But you can use values higher than (1,1) and lower than (0,0) too.
* The default anchorPoint is (0.5,0.5), so it starts in the center of the node.
+ * @const
* @return {cc.Point} The anchor point of node.
*/
getAnchorPoint:function () {
- return cc.p(this._anchorPoint.x, this._anchorPoint.y);
+ return this._anchorPoint; //cc.p(this._anchorPoint.x, this._anchorPoint.y);
},
/**
@@ -653,9 +646,13 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
* @param {cc.Point} point The anchor point of node.
*/
setAnchorPoint:function (point) {
- if (!cc.pointEqualToPoint(point, this._anchorPoint)) {
- this._anchorPoint = new cc.Point(point.x, point.y);
- this._anchorPointInPoints = new cc.Point(this._contentSize.width * point.x, this._contentSize.height * point.y);
+ var locAnchorPoint = this._anchorPoint;
+ if (!cc.pointEqualToPoint(point, locAnchorPoint)) {
+ locAnchorPoint.x = point.x;
+ locAnchorPoint.y = point.y;
+ var locAPP = this._anchorPointInPoints, locSize = this._contentSize;
+ locAPP.x = locSize.width * point.x;
+ locAPP.y = locSize.height * point.y;
this.setNodeDirty();
}
},
@@ -664,20 +661,22 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
* The anchorPoint in absolute pixels.
* you can only read it. If you wish to modify it, use anchorPoint instead
* @see getAnchorPoint()
+ * @const
* @return {cc.Point} The anchor point in absolute pixels.
*/
getAnchorPointInPoints:function () {
- return cc.p(this._anchorPointInPoints.x, this._anchorPointInPoints.y);
+ return this._anchorPointInPoints; //cc.p(this._anchorPointInPoints.x, this._anchorPointInPoints.y);
},
/**
*
The untransformed size of the node.
* The contentSize remains the same no matter the node is scaled or rotated.
* All nodes has a size. Layer and Scene has the same size of the screen.
+ * @const
* @return {cc.Size} The untransformed size of the node.
*/
getContentSize:function () {
- return cc.size(this._contentSize.width, this._contentSize.height);
+ return this._contentSize; //cc.size(this._contentSize.width, this._contentSize.height);
},
/**
@@ -690,9 +689,13 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
* @param {cc.Size} size The untransformed size of the node.
*/
setContentSize:function (size) {
- if (!cc.sizeEqualToSize(size, this._contentSize)) {
- this._contentSize = new cc.Size(size.width, size.height);
- this._anchorPointInPoints = new cc.Point(this._contentSize.width * this._anchorPoint.x, this._contentSize.height * this._anchorPoint.y);
+ var locContentSize = this._contentSize;
+ if (!cc.sizeEqualToSize(size, locContentSize)) {
+ locContentSize.width = size.width;
+ locContentSize.height = size.height;
+ var locAPP = this._anchorPointInPoints, locAnchorPoint = this._anchorPoint;
+ locAPP.x = locContentSize.width * locAnchorPoint.x;
+ locAPP.y = locContentSize.height * locAnchorPoint.y;
this.setNodeDirty();
}
},
@@ -915,6 +918,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
* Returns a "local" axis aligned bounding box of the node.
* The returned box is relative only to its parent.
* @note This method returns a temporaty variable, so it can't returns const CCRect&
+ * @const
* @return {cc.Rect}
*/
getBoundingBox:function () {
@@ -1688,7 +1692,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
if (!this._visible)
return;
var context = cc.renderContext, i, currentStack = cc.current_stack;
- this._stackMatrix = this._stackMatrix || new cc.kmMat4();
+
//cc.kmGLPushMatrixWitMat4(this._stackMatrix);
//optimize performance for javascript
currentStack.stack.push(currentStack.top);
@@ -1737,12 +1741,6 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
transform:function () {
//optimize performance for javascript
var t4x4 = this._transform4x4, topMat4 = cc.current_stack.top;
- if(!t4x4){
- t4x4 = new cc.kmMat4();
- t4x4.mat[2] = t4x4.mat[3] = t4x4.mat[6] = t4x4.mat[7] = t4x4.mat[8] = t4x4.mat[9] = t4x4.mat[11] = t4x4.mat[14] = 0.0;
- t4x4.mat[10] = t4x4.mat[15] = 1.0;
- this._transform4x4 = t4x4;
- }
// Convert 3x3 into 4x4 matrix
//cc.CGAffineToGL(this.nodeToParentTransform(), this._transform4x4.mat);
@@ -1839,13 +1837,6 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
return this._transform;
},
- /**
- * set the dirty node
- */
- setNodeDirty:function () {
- this._transformDirty = this._inverseDirty = true;
- },
-
/**
* Returns a camera object that lets you move the node using a gluLookAt
* @return {cc.Camera} A CCCamera object that lets you move the node using a gluLookAt
@@ -1917,25 +1908,6 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
}
});
-/**
- * cc.Node's state callback type
- * @constant
- * @type Number
- */
-cc.NodeWebGL.StateCallbackType = {onEnter:1, onExit:2, cleanup:3, onEnterTransitionDidFinish:4, updateTransform:5, onExitTransitionDidStart:6, sortAllChildren:7};
-
-/**
- * allocates and initializes a node.
- * @constructs
- * @return {cc.NodeWebGL}
- * @example
- * // example
- * var node = cc.NodeWebGL.create();
- */
-cc.NodeWebGL.create = function () {
- return new cc.NodeWebGL();
-};
-
/**
cc.Node is the main element. Anything thats gets drawn or contains things that get drawn is a cc.Node.
The most popular cc.Nodes are: cc.Scene, cc.Layer, cc.Sprite, cc.Menu. (Canvas implement)
get the skew degrees in X
* The X skew angle of the node in degrees.
@@ -2263,8 +2231,6 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
return this._rotationX;
},
- _rotationRadiansX:0,
- _rotationRadiansY:0,
/**
*
Position (x,y) of the node in OpenGL coordinates. (0,0) is the left-bottom corner.
+ * @const
* @return {cc.Point} The position (x,y) of the node in OpenGL coordinates
*/
getPosition:function () {
- return cc.p(this._position.x, this._position.y);
+ return this._position; //cc.p(this._position.x, this._position.y);
},
/**
@@ -2512,10 +2471,11 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
* The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner.
* But you can use values higher than (1,1) and lower than (0,0) too.
* The default anchorPoint is (0.5,0.5), so it starts in the center of the node.
+ * @const
* @return {cc.Point} The anchor point of node.
*/
getAnchorPoint:function () {
- return cc.p(this._anchorPoint.x, this._anchorPoint.y);
+ return this._anchorPoint; //cc.p(this._anchorPoint.x, this._anchorPoint.y);
},
/**
@@ -2531,9 +2491,13 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
* @param {cc.Point} point The anchor point of node.
*/
setAnchorPoint:function (point) {
- if (!cc.pointEqualToPoint(point, this._anchorPoint)) {
- this._anchorPoint = new cc.Point(point.x, point.y);
- this._anchorPointInPoints = new cc.Point(this._contentSize.width * point.x, this._contentSize.height * point.y);
+ var locAnchorPoint = this._anchorPoint;
+ if (!cc.pointEqualToPoint(point, locAnchorPoint)) {
+ locAnchorPoint.x = point.x;
+ locAnchorPoint.y = point.y;
+ var locAPP = this._anchorPointInPoints, locSize = this._contentSize;
+ locAPP.x = locSize.width * point.x;
+ locAPP.y = locSize.height * point.y;
this.setNodeDirty();
}
},
@@ -2542,20 +2506,22 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
* The anchorPoint in absolute pixels.
* you can only read it. If you wish to modify it, use anchorPoint instead
* @see getAnchorPoint()
+ * @const
* @return {cc.Point} The anchor point in absolute pixels.
*/
getAnchorPointInPoints:function () {
- return cc.p(this._anchorPointInPoints.x, this._anchorPointInPoints.y);
+ return this._anchorPointInPoints; //cc.p(this._anchorPointInPoints.x, this._anchorPointInPoints.y);
},
/**
*
The untransformed size of the node.
* The contentSize remains the same no matter the node is scaled or rotated.
* All nodes has a size. Layer and Scene has the same size of the screen.
The scale factor of the node. 1.0 is the default scale factor.
* It modifies the X and Y scale at the same time. (override cc.Node )
* @param {Number} scale
+ * @param {Number} [scaleY=]
* @override
*/
setScale:function (scale, scaleY) {
@@ -1047,22 +1048,23 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
//cc.Assert(this._batchNode, "updateTransform is only valid when cc.Sprite is being rendered using an cc.SpriteBatchNode");
// recaculate matrix only if it is dirty
- if (this.isDirty()) {
+ if (this._dirty) {
// If it is not visible, or one of its ancestors is not visible, then do nothing:
- if (!this._visible || ( this._parent && this._parent != this._batchNode && this._parent._shouldBeHidden)) {
+ var locParent = this._parent;
+ if (!this._visible || ( locParent && locParent != this._batchNode && locParent._shouldBeHidden)) {
this._shouldBeHidden = true;
} else {
this._shouldBeHidden = false;
- if (!this._parent || this._parent == this._batchNode) {
+ if (!locParent || locParent == this._batchNode) {
this._transformToBatch = this.nodeToParentTransform();
} else {
//cc.Assert(this._parent instanceof cc.Sprite, "Logic error in CCSprite. Parent must be a CCSprite");
- this._transformToBatch = cc.AffineTransformConcat(this.nodeToParentTransform(), this._parent._transformToBatch);
+ this._transformToBatch = cc.AffineTransformConcat(this.nodeToParentTransform(), locParent._transformToBatch);
}
}
this._recursiveDirty = false;
- this.setDirty(false);
+ this._dirty = false;
}
// recursively iterate over children
@@ -1125,7 +1127,11 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
*/
setDisplayFrame:function (newFrame) {
this.setNodeDirty();
- this._unflippedOffsetPositionFromCenter = newFrame.getOffset();
+
+ var frameOffset = newFrame.getOffset();
+ this._unflippedOffsetPositionFromCenter.x = frameOffset.x;
+ this._unflippedOffsetPositionFromCenter.y = frameOffset.y;
+
var pNewTexture = newFrame.getTexture();
// update texture before updating texture rect
if (pNewTexture != this._texture)
@@ -1283,140 +1289,6 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
}
});
-/**
- *
- * Creates a sprite with an exsiting texture contained
- * After creation, the rect will be the size of the texture, and the offset will be (0,0).
- *
- * @constructs
- * @param {HTMLImageElement|HTMLCanvasElement|cc.Texture2D} texture A pointer to an existing CCTexture2D object. You can use a CCTexture2D object for many sprites.
- * @param {cc.Rect} rect Only the contents inside the rect of this texture will be applied for this sprite.
- * @param {cc.Point} offset offset of the texture
- * @return {cc.Sprite} A valid sprite object
- * @example
- * //get an image
- * var img = cc.TextureCache.getInstance().addImage("HelloHTML5World.png");
- *
- * //create a sprite with texture
- * var sprite1 = cc.Sprite.createWithTexture(img);
- *
- * //create a sprite with texture and rect
- * var sprite2 = cc.Sprite.createWithTexture(img, cc.rect(0,0,480,320));
- *
- * //create a sprite with texture and rect and offset
- * var sprite3 = cc.Sprite.createWithTexture(img, cc.rect(0,0,480,320),cc.p(0,0));
- */
-cc.SpriteCanvas.createWithTexture = function (texture, rect, offset) {
- var argnum = arguments.length;
- var sprite = new cc.SpriteCanvas();
- switch (argnum) {
- case 1:
- /** Creates an sprite with a texture.
- The rect used will be the size of the texture.
- The offset will be (0,0).
- */
- if (sprite && sprite.initWithTexture(texture)) {
- return sprite;
- }
- return null;
- break;
-
- case 2:
- /** Creates an sprite with a texture and a rect.
- The offset will be (0,0).
- */
- if (sprite && sprite.initWithTexture(texture, rect)) {
- return sprite;
- }
- return null;
- break;
-
- case 3:
- /** Creates an sprite with a texture, a rect and offset. */
- // not implement
- cc.Assert(0, "");
- return null;
- break;
-
- default:
- throw "Sprite.createWithTexture(): Argument must be non-nil ";
- break;
- }
-};
-
-/**
- * Create a sprite with filename and rect
- * @constructs
- * @param {String} fileName The string which indicates a path to image file, e.g., "scene1/monster.png".
- * @param {cc.Rect} rect Only the contents inside rect of pszFileName's texture will be applied for this sprite.
- * @return {cc.Sprite} A valid sprite object
- * @example
- * //create a sprite with filename
- * var sprite1 = cc.Sprite.create("HelloHTML5World.png");
- *
- * //create a sprite with filename and rect
- * var sprite2 = cc.Sprite.create("HelloHTML5World.png",cc.rect(0,0,480,320));
- */
-cc.SpriteCanvas.create = function (fileName, rect) {
- var argnum = arguments.length;
- var sprite = new cc.SpriteCanvas();
- if (argnum === 0) {
- if (sprite.init())
- return sprite;
- } else {
- if (sprite && sprite.init(fileName, rect))
- return sprite;
- }
- return null;
-};
-
-/**
- * Creates a sprite with a sprite frame name
- * @param {String} spriteFrameName name
- * @return {cc.Sprite} A valid sprite object
- * @example
- *
- * //create a sprite with a sprite frame
- * var sprite = cc.Sprite.createWithSpriteFrameName('grossini_dance_01.png');
- */
-cc.SpriteCanvas.createWithSpriteFrameName = function (spriteFrameName) {
- var spriteFrame = null;
- if (typeof(spriteFrameName) == 'string') {
- spriteFrame = cc.SpriteFrameCache.getInstance().getSpriteFrame(spriteFrameName);
- if (!spriteFrame) {
- cc.log("Invalid spriteFrameName: " + spriteFrameName);
- return null;
- }
- } else {
- cc.log("Invalid argument. Expecting string.");
- return null;
- }
- var sprite = new cc.SpriteCanvas();
- if (sprite && sprite.initWithSpriteFrame(spriteFrame)) {
- return sprite;
- }
- return null;
-};
-
-/**
- * Creates a sprite with a sprite frame.
- * @param {cc.SpriteFrame} spriteFrame A sprite frame which involves a texture and a rect
- * @return {cc.Sprite} A valid sprite object
- * @example
- * //get a sprite frame
- * var spriteFrame = cc.SpriteFrameCache.getInstance().getSpriteFrame("grossini_dance_01.png");
- *
- * //create a sprite with a sprite frame
- * var sprite = cc.Sprite.createWithSpriteFrame(spriteFrame);
- */
-cc.SpriteCanvas.createWithSpriteFrame = function (spriteFrame) {
- var sprite = new cc.SpriteCanvas();
- if (sprite && sprite.initWithSpriteFrame(spriteFrame)) {
- return sprite;
- }
- return null;
-};
-
/**
*
* Creates a sprite with an exsiting texture contained in a CCTexture2D object
@@ -2705,9 +2579,9 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
* //create a sprite with texture and rect and offset
* var sprite3 = cc.Sprite.createWithTexture(img, cc.rect(0,0,480,320),cc.p(0,0));
*/
-cc.SpriteWebGL.createWithTexture = function (texture, rect, offset) {
+cc.Sprite.createWithTexture = function (texture, rect, offset) {
var argnum = arguments.length;
- var sprite = new cc.SpriteWebGL();
+ var sprite = new cc.Sprite();
switch (argnum) {
case 1:
/** Creates an sprite with a texture.
@@ -2756,9 +2630,9 @@ cc.SpriteWebGL.createWithTexture = function (texture, rect, offset) {
* //create a sprite with filename and rect
* var sprite2 = cc.Sprite.create("HelloHTML5World.png",cc.rect(0,0,480,320));
*/
-cc.SpriteWebGL.create = function (fileName, rect) {
+cc.Sprite.create = function (fileName, rect) {
var argnum = arguments.length;
- var sprite = new cc.SpriteWebGL();
+ var sprite = new cc.Sprite();
if (argnum === 0) {
if (sprite.init())
return sprite;
@@ -2787,7 +2661,7 @@ cc.SpriteWebGL.create = function (fileName, rect) {
* //create a sprite with a sprite frame
* var sprite = cc.Sprite.createWithSpriteFrameName('grossini_dance_01.png');
*/
-cc.SpriteWebGL.createWithSpriteFrameName = function (spriteFrameName) {
+cc.Sprite.createWithSpriteFrameName = function (spriteFrameName) {
var spriteFrame = null;
if (typeof(spriteFrameName) == 'string') {
spriteFrame = cc.SpriteFrameCache.getInstance().getSpriteFrame(spriteFrameName);
@@ -2799,7 +2673,7 @@ cc.SpriteWebGL.createWithSpriteFrameName = function (spriteFrameName) {
cc.log("Invalid argument. Expecting string.");
return null;
}
- var sprite = new cc.SpriteWebGL();
+ var sprite = new cc.Sprite();
if (sprite && sprite.initWithSpriteFrame(spriteFrame)) {
return sprite;
}
@@ -2822,12 +2696,10 @@ cc.SpriteWebGL.createWithSpriteFrameName = function (spriteFrameName) {
* //create a sprite with a sprite frame
* var sprite = cc.Sprite.createWithSpriteFrame(spriteFrame);
*/
-cc.SpriteWebGL.createWithSpriteFrame = function (spriteFrame) {
- var sprite = new cc.SpriteWebGL();
+cc.Sprite.createWithSpriteFrame = function (spriteFrame) {
+ var sprite = new cc.Sprite();
if (sprite && sprite.initWithSpriteFrame(spriteFrame)) {
return sprite;
}
return null;
};
-
-cc.Sprite = cc.Browser.supportWebGL ? cc.SpriteWebGL : cc.SpriteCanvas;
diff --git a/cocos2d/sprite_nodes/CCSpriteBatchNode.js b/cocos2d/sprite_nodes/CCSpriteBatchNode.js
index 04e42a2131..d037c01f08 100644
--- a/cocos2d/sprite_nodes/CCSpriteBatchNode.js
+++ b/cocos2d/sprite_nodes/CCSpriteBatchNode.js
@@ -78,15 +78,15 @@ cc.SpriteBatchNodeCanvas = cc.Node.extend(/** @lends cc.SpriteBatchNodeCanvas# *
child.setAtlasIndex(z);
// XXX: optimize with a binary search
- var i = 0;
- if (this._descendants && this._descendants.length > 0) {
- for (var index = 0; index < this._descendants.length; index++) {
- var obj = this._descendants[index];
+ var i = 0, locDescendants = this._descendants;
+ if (locDescendants && locDescendants.length > 0) {
+ for (var index = 0; index < locDescendants.length; index++) {
+ var obj = locDescendants[index];
if (obj && (obj.getAtlasIndex() >= z))
++i;
}
}
- this._descendants = cc.ArrayAppendObjectToIndex(this._descendants, child, i);
+ this._descendants = cc.ArrayAppendObjectToIndex(locDescendants, child, i);
// IMPORTANT: Call super, and not self. Avoid adding it to the texture atlas array
cc.Node.prototype.addChild.call(this, child, z, aTag);
@@ -372,8 +372,9 @@ cc.SpriteBatchNodeCanvas = cc.Node.extend(/** @lends cc.SpriteBatchNodeCanvas# *
if (fileImage)
this.init(fileImage, cc.DEFAULT_SPRITE_BATCH_CAPACITY);
- this._renderTexture = cc.RenderTexture.create(cc.canvas.width, cc.canvas.height);
- this.setContentSize(cc.size(cc.canvas.width, cc.canvas.height));
+ var locCanvas = cc.canvas;
+ this._renderTexture = cc.RenderTexture.create(locCanvas.width, locCanvas.height);
+ this.setContentSize(cc.size(locCanvas.width, locCanvas.height));
},
/**
@@ -462,7 +463,7 @@ cc.SpriteBatchNodeCanvas = cc.Node.extend(/** @lends cc.SpriteBatchNodeCanvas# *
sprite.setBatchNode(this);
sprite.setDirty(true);
- cc.ArrayAppendObject(this._descendants, sprite);
+ this._descendants.push(sprite);
var index = this._descendants.length - 1;
sprite.setAtlasIndex(index);
@@ -479,15 +480,15 @@ cc.SpriteBatchNodeCanvas = cc.Node.extend(/** @lends cc.SpriteBatchNodeCanvas# *
removeSpriteFromAtlas:function (sprite) {
// Cleanup sprite. It might be reused (issue #569)
sprite.setBatchNode(null);
-
- var index = cc.ArrayGetIndexOfObject(this._descendants, sprite);
+ var locDescendants = this._descendants;
+ var index = cc.ArrayGetIndexOfObject(locDescendants, sprite);
if (index != -1) {
- cc.ArrayRemoveObjectAtIndex(this._descendants, index);
+ cc.ArrayRemoveObjectAtIndex(locDescendants, index);
// update all sprites beyond this one
- var len = this._descendants.length;
+ var len = locDescendants.length;
for (; index < len; ++index) {
- var s = this._descendants[index];
+ var s = locDescendants[index];
s.setAtlasIndex(s.getAtlasIndex() - 1);
}
}
@@ -517,14 +518,15 @@ cc.SpriteBatchNodeCanvas = cc.Node.extend(/** @lends cc.SpriteBatchNodeCanvas# *
*/
setTexture:function (texture) {
this._textureForCanvas = texture;
- for (var i = 0; i < this._children.length; i++)
- this._children[i].setTexture(texture);
+ var locChildren = this._children;
+ for (var i = 0; i < locChildren.length; i++)
+ locChildren[i].setTexture(texture);
},
/**
* don't call visit on it's children ( override visit of cc.Node )
* @override
- * @param {CanvasContext} ctx
+ * @param {CanvasRenderingContext2D} ctx
*/
visit:function (ctx) {
var context = ctx || cc.renderContext;
@@ -534,31 +536,32 @@ cc.SpriteBatchNodeCanvas = cc.Node.extend(/** @lends cc.SpriteBatchNodeCanvas# *
context.save();
this.transform(ctx);
- var i;
+ var i, locChildren = this._children;
if (this._useCache) {
if (this._cacheDirty) {
//add dirty region
- this._renderTexture.clear();
- this._renderTexture.context.save();
- this._renderTexture.context.translate(this._anchorPointInPoints.x, -(this._anchorPointInPoints.y ));
- if (this._children) {
+ var locRenderTexture = this._renderTexture;
+ locRenderTexture.clear();
+ locRenderTexture.context.save();
+ locRenderTexture.context.translate(this._anchorPointInPoints.x, -(this._anchorPointInPoints.y ));
+ if (locChildren) {
this.sortAllChildren();
- for (i = 0; i < this._children.length; i++) {
- if (this._children[i])
- this._children[i].visit(this._renderTexture.context);
+ for (i = 0; i < locChildren.length; i++) {
+ if (locChildren[i])
+ locChildren[i].visit(locRenderTexture.context);
}
}
- this._renderTexture.context.restore();
+ locRenderTexture.context.restore();
this._cacheDirty = false;
}
// draw RenderTexture
this.draw(ctx);
} else {
- if (this._children) {
+ if (locChildren) {
this.sortAllChildren();
- for (i = 0; i < this._children.length; i++) {
- if (this._children[i])
- this._children[i].visit(context);
+ for (i = 0; i < locChildren.length; i++) {
+ if (locChildren[i])
+ locChildren[i].visit(context);
}
}
}
@@ -602,10 +605,11 @@ cc.SpriteBatchNodeCanvas = cc.Node.extend(/** @lends cc.SpriteBatchNodeCanvas# *
removeAllChildren:function (cleanup) {
// Invalidate atlas index. issue #569
// useSelfRender should be performed on all descendants. issue #1216
- if (this._descendants && this._descendants.length > 0) {
- for (var i = 0; i < this._descendants.length; i++) {
- if (this._descendants[i])
- this._descendants[i].setBatchNode(null);
+ var locDescendants = this._descendants;
+ if (locDescendants && locDescendants.length > 0) {
+ for (var i = 0; i < locDescendants.length; i++) {
+ if (locDescendants[i])
+ locDescendants[i].setBatchNode(null);
}
}
@@ -615,25 +619,26 @@ cc.SpriteBatchNodeCanvas = cc.Node.extend(/** @lends cc.SpriteBatchNodeCanvas# *
sortAllChildren:function () {
if (this._reorderChildDirty) {
- var i = 0, j = 0, length = this._children.length;
+ var i, j = 0, locChildren = this._children;
+ var length = locChildren.length;
//insertion sort
for (i = 1; i < length; i++) {
- var tempItem = this._children[i];
+ var tempItem = locChildren[i];
j = i - 1;
//continue moving element downwards while zOrder is smaller or when zOrder is the same but orderOfArrival is smaller
- while (j >= 0 && (tempItem.getZOrder() < this._children[j].getZOrder() ||
- (tempItem.getZOrder() == this._children[j].getZOrder() && tempItem.getOrderOfArrival() < this._children[j].getOrderOfArrival()))) {
- this._children[j + 1] = this._children[j];
+ while (j >= 0 && (tempItem.getZOrder() < locChildren[j].getZOrder() ||
+ (tempItem.getZOrder() == locChildren[j].getZOrder() && tempItem.getOrderOfArrival() < locChildren[j].getOrderOfArrival()))) {
+ locChildren[j + 1] = locChildren[j];
j--;
}
- this._children[j + 1] = tempItem;
+ locChildren[j + 1] = tempItem;
}
//sorted now check all children
- if (this._children.length > 0) {
+ if (locChildren.length > 0) {
//first sort all children recursively based on zOrder
- this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.sortAllChildren);
+ this._arrayMakeObjectsPerformSelector(locChildren, cc.Node.StateCallbackType.sortAllChildren);
}
this._reorderChildDirty = false;
}
@@ -641,54 +646,19 @@ cc.SpriteBatchNodeCanvas = cc.Node.extend(/** @lends cc.SpriteBatchNodeCanvas# *
/**
* draw cc.SpriteBatchNode (override draw of cc.Node)
- * @param {CanvasContext} ctx
+ * @param {CanvasRenderingContext2D} ctx
*/
draw:function (ctx) {
var context = ctx || cc.renderContext;
//context.globalAlpha = this._opacity / 255;
- var pos = cc.p(0 | ( -this._anchorPointInPoints.x), 0 | ( -this._anchorPointInPoints.y));
+ var posX = 0 | ( -this._anchorPointInPoints.x), posY = 0 | ( -this._anchorPointInPoints.y);
+ var locRenderTexture = this._renderTexture;
//direct draw image by canvas drawImage
- if (this._renderTexture)
- context.drawImage(this._renderTexture.getCanvas(), pos.x, -(pos.y + this._renderTexture.getCanvas().height));
+ if (locRenderTexture)
+ context.drawImage(locRenderTexture.getCanvas(), posX, -(posY + locRenderTexture.getCanvas().height));
}
});
-/**
- *
- * creates a cc.SpriteBatchNodeCanvas with a file image (.png, .jpg etc) with a default capacity of 29 children.
- * The capacity will be increased in 33% in runtime if it run out of space.
- * The file will be loaded using the TextureMgr.
- *
- * creates a cc.SpriteBatchNodeCanvas with a texture2d and a default capacity of 29 children.
- * The capacity will be increased in 33% in runtime if it run out of space.
- *
* In WebGL render mode ,cc.SpriteBatchNode is like a batch node: if it contains children, it will draw them in 1 single OpenGL call
@@ -1426,6 +1396,8 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
}
});
+cc.SpriteBatchNode = (cc.Browser.supportWebGL)?cc.SpriteBatchNodeWebGL:cc.SpriteBatchNodeCanvas;
+
/**
*
* creates a cc.SpriteBatchNodeCanvas with a file image (.png, .jpg etc) with a default capacity of 29 children.
@@ -1434,14 +1406,14 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
*
* @param {String} fileImage
* @param {Number} capacity
- * @return {cc.SpriteBatchNodeWebGL}
+ * @return {cc.SpriteBatchNode}
* @example
* //create a SpriteBatchNode
* var parent2 = cc.SpriteBatchNode.create("res/animations/grossini.png", 50);
*/
-cc.SpriteBatchNodeWebGL.create = function (fileImage, capacity) {
+cc.SpriteBatchNode.create = function (fileImage, capacity) {
capacity = capacity || cc.DEFAULT_SPRITE_BATCH_CAPACITY;
- var batchNode = new cc.SpriteBatchNodeWebGL();
+ var batchNode = new cc.SpriteBatchNode();
batchNode.init(fileImage, capacity);
return batchNode;
};
@@ -1453,15 +1425,13 @@ cc.SpriteBatchNodeWebGL.create = function (fileImage, capacity) {
*
CCDrawNode for WebGL
* Node that draws dots, segments and polygons.
@@ -276,20 +265,21 @@ cc.DrawNodeWebGL = cc.Node.extend(/** @lends cc.DrawNodeWebGL# */{
_ensureCapacity:function(count){
if(this._buffer.length + count > this._bufferCapacity){
+ var TriangleLength = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT;
this._bufferCapacity += Math.max(this._bufferCapacity, count);
//re alloc
if((this._buffer == null) || (this._buffer.length === 0)){
//init
this._buffer = [];
- this._trianglesArrayBuffer = new ArrayBuffer(cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT * this._bufferCapacity);
+ this._trianglesArrayBuffer = new ArrayBuffer(TriangleLength * this._bufferCapacity);
this._trianglesReader = new Uint8Array(this._trianglesArrayBuffer);
} else {
var newTriangles = [];
- var newArrayBuffer = new ArrayBuffer(cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT * this._bufferCapacity);
+ var newArrayBuffer = new ArrayBuffer(TriangleLength * this._bufferCapacity);
for(var i = 0; i < this._buffer.length;i++){
newTriangles[i] = new cc.V2F_C4B_T2F_Triangle(this._buffer[i].a,this._buffer[i].b,this._buffer[i].c,
- newArrayBuffer,i * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT);
+ newArrayBuffer,i * TriangleLength);
}
this._trianglesReader = new Uint8Array(newArrayBuffer);
this._buffer = newTriangles;
@@ -351,29 +341,30 @@ cc.DrawNodeWebGL = cc.Node.extend(/** @lends cc.DrawNodeWebGL# */{
var v6 = cc.v2fsub(a, cc.v2fsub(nw, tw));
var v7 = cc.v2fadd(a, cc.v2fadd(nw, tw));
+ var TriangleLength = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, triangleBuffer = this._trianglesArrayBuffer;
this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v0, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(cc.v2fadd(n, t)))},
{vertices: v1, colors: c4bColor, texCoords: cc.__t(cc.v2fsub(n, t))}, {vertices: v2, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))},
- this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT));
+ triangleBuffer, this._buffer.length * TriangleLength));
this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v3, colors: c4bColor, texCoords: cc.__t(n)},
{vertices: v1, colors: c4bColor, texCoords: cc.__t(cc.v2fsub(n, t))}, {vertices: v2, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))},
- this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT));
+ triangleBuffer, this._buffer.length * TriangleLength));
this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v3, colors: c4bColor, texCoords: cc.__t(n)},
{vertices: v4, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))}, {vertices: v2, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))},
- this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT));
+ triangleBuffer, this._buffer.length * TriangleLength));
this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v3, colors: c4bColor, texCoords: cc.__t(n)},
{vertices: v4, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))}, {vertices: v5, colors: c4bColor, texCoords: cc.__t(n)},
- this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT));
+ triangleBuffer, this._buffer.length * TriangleLength));
this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v6, colors: c4bColor, texCoords: cc.__t(cc.v2fsub(t, n))},
{vertices: v4, colors: c4bColor, texCoords: cc.__t(cc.v2fneg(n))}, {vertices: v5, colors: c4bColor, texCoords: cc.__t(n)},
- this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT));
+ triangleBuffer, this._buffer.length * TriangleLength));
this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v6, colors: c4bColor, texCoords: cc.__t(cc.v2fsub(t, n))},
{vertices: v7, colors: c4bColor, texCoords: cc.__t(cc.v2fadd(n, t))}, {vertices: v5, colors: c4bColor, texCoords: cc.__t(n)},
- this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT));
+ triangleBuffer, this._buffer.length * TriangleLength));
this._dirty = true;
},
@@ -405,14 +396,16 @@ cc.DrawNodeWebGL = cc.Node.extend(/** @lends cc.DrawNodeWebGL# */{
var vertexCount = 3 * triangleCount;
this._ensureCapacity(vertexCount);
+ var triangleBytesLen = cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT, trianglesBuffer = this._trianglesArrayBuffer;
+ var locBuffer = this._buffer;
var inset = (outline == false ? 0.5 : 0.0);
for (i = 0; i < count - 2; i++) {
v0 = cc.v2fsub(cc.__v2f(verts[0]), cc.v2fmult(extrude[0].offset, inset));
v1 = cc.v2fsub(cc.__v2f(verts[i + 1]), cc.v2fmult(extrude[i + 1].offset, inset));
v2 = cc.v2fsub(cc.__v2f(verts[i + 2]), cc.v2fmult(extrude[i + 2].offset, inset));
- this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v0, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())},
+ locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: v0, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())},
{vertices: v1, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, {vertices: v2, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())},
- this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT));
+ trianglesBuffer, locBuffer.length * triangleBytesLen));
}
for (i = 0; i < count; i++) {
@@ -429,19 +422,19 @@ cc.DrawNodeWebGL = cc.Node.extend(/** @lends cc.DrawNodeWebGL# */{
var outer1 = outline ? cc.v2fadd(v1, cc.v2fmult(offset1, borderWidth)) : cc.v2fadd(v1, cc.v2fmult(offset1, 0.5));
if (outline) {
- this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))},
+ locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))},
{vertices: inner1, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))}, {vertices: outer1, colors: c4bBorderColor, texCoords: cc.__t(n0)},
- this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT));
- this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))},
+ trianglesBuffer, locBuffer.length * triangleBytesLen));
+ locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bBorderColor, texCoords: cc.__t(cc.v2fneg(n0))},
{vertices: outer0, colors: c4bBorderColor, texCoords: cc.__t(n0)}, {vertices: outer1, colors: c4bBorderColor, texCoords: cc.__t(n0)},
- this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT));
+ trianglesBuffer, locBuffer.length * triangleBytesLen));
} else {
- this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())},
+ locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())},
{vertices: inner1, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())}, {vertices: outer1, colors: c4bFillColor, texCoords: cc.__t(n0)},
- this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT));
- this._buffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())},
+ trianglesBuffer, locBuffer.length * triangleBytesLen));
+ locBuffer.push(new cc.V2F_C4B_T2F_Triangle({vertices: inner0, colors: c4bFillColor, texCoords: cc.__t(cc.v2fzero())},
{vertices: outer0, colors: c4bFillColor, texCoords: cc.__t(n0)}, {vertices: outer1, colors: c4bFillColor, texCoords: cc.__t(n0)},
- this._trianglesArrayBuffer, this._buffer.length * cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT));
+ trianglesBuffer, locBuffer.length * triangleBytesLen));
}
}
extrude = null;
@@ -457,23 +450,23 @@ cc.DrawNodeWebGL = cc.Node.extend(/** @lends cc.DrawNodeWebGL# */{
}
});
+cc.DrawNode = cc.Browser.supportWebGL ? cc.DrawNodeWebGL : cc.DrawNodeCanvas;
+
/**
- * Creates a DrawNodeCanvas
- * @return {cc.DrawNodeWebGL}
+ * Creates a DrawNode
+ * @return {cc.DrawNode}
*/
-cc.DrawNodeWebGL.create = function () {
- var ret = new cc.DrawNodeWebGL();
+cc.DrawNode.create = function () {
+ var ret = new cc.DrawNode();
if (ret && ret.init())
return ret;
return null;
};
-cc.DrawNode = cc.Browser.supportWebGL ? cc.DrawNodeWebGL : cc.DrawNodeCanvas;
-
cc._DrawNodeElement = function (type) {
this.type = type;
};
-cc.DRAWNODE_TYPE_DOT = 0;
-cc.DRAWNODE_TYPE_SEGMENT = 1;
-cc.DRAWNODE_TYPE_POLY = 2;
+cc.DrawNode.TYPE_DOT = 0;
+cc.DrawNode.TYPE_SEGMENT = 1;
+cc.DrawNode.TYPE_POLY = 2;
diff --git a/cocos2d/label_nodes/CCLabelAtlas.js b/cocos2d/label_nodes/CCLabelAtlas.js
index aa417c5e58..f04bbbfe8b 100644
--- a/cocos2d/label_nodes/CCLabelAtlas.js
+++ b/cocos2d/label_nodes/CCLabelAtlas.js
@@ -184,27 +184,6 @@ cc.LabelAtlasCanvas = cc.AtlasNode.extend(/** @lends cc.LabelAtlasCanvas# */{
}
});
-/**
- * It accepts two groups of parameters:
- * a) string, fntFile
- * b) label, textureFilename, width, height, startChar
- * @return {cc.LabelAtlas|Null} returns the LabelAtlas object on success
- * @example
- * //Example
- * //creates the cc.LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas
- * var myLabel = cc.LabelAtlas.create('Text to display', 'CharMapfile.png', 12, 20, ' ')
- *
- * //creates the cc.LabelAtlas with a string, a fnt file
- * var myLabel = cc.LabelAtlas.create('Text to display', 'CharMapFile.plist‘);
- */
-cc.LabelAtlasCanvas.create = function (strText, charMapFile, itemWidth, itemHeight, startCharMap) {
- var ret = new cc.LabelAtlasCanvas();
- if (ret && cc.LabelAtlasCanvas.prototype.initWithString.apply(ret,arguments)) {
- return ret;
- }
- return null;
-};
-
/**
* using image file to print text label on the screen, might be a bit slower than cc.Label, similar to cc.LabelBMFont (WebGL version)
* @class
@@ -390,6 +369,8 @@ cc.LabelAtlasWebGL = cc.AtlasNode.extend(/** @lends cc.LabelAtlasWebGL# */{
}
});
+cc.LabelAtlas = cc.Browser.supportWebGL ? cc.LabelAtlasWebGL : cc.LabelAtlasCanvas;
+
/**
* It accepts two groups of parameters:
* a) string, fntFile
@@ -408,13 +389,11 @@ cc.LabelAtlasWebGL = cc.AtlasNode.extend(/** @lends cc.LabelAtlasWebGL# */{
* //creates the cc.LabelAtlas with a string, a fnt file
* var myLabel = cc.LabelAtlas.create('Text to display', 'CharMapFile.plist‘);
*/
-cc.LabelAtlasWebGL.create = function (strText, charMapFile, itemWidth, itemHeight, startCharMap) {
- var ret = new cc.LabelAtlasWebGL();
- if (ret && cc.LabelAtlasWebGL.prototype.initWithString.apply(ret,arguments)) {
+cc.LabelAtlas.create = function (strText, charMapFile, itemWidth, itemHeight, startCharMap) {
+ var ret = new cc.LabelAtlas();
+ if (ret && cc.LabelAtlas.prototype.initWithString.apply(ret,arguments)) {
return ret;
}
return null;
};
-cc.LabelAtlas = cc.Browser.supportWebGL ? cc.LabelAtlasWebGL : cc.LabelAtlasCanvas;
-
diff --git a/cocos2d/layers_scenes_transitions_nodes/CCLayer.js b/cocos2d/layers_scenes_transitions_nodes/CCLayer.js
index 2cf2d02271..bb8fa342d6 100644
--- a/cocos2d/layers_scenes_transitions_nodes/CCLayer.js
+++ b/cocos2d/layers_scenes_transitions_nodes/CCLayer.js
@@ -840,7 +840,7 @@ cc.LayerColorCanvas = cc.LayerRGBA.extend(/** @lends cc.LayerColorCanvas# */{
/**
* renders the layer
- * @param {CanvasContext|Null} ctx
+ * @param {CanvasRenderingContext2D|Null} ctx
*/
draw:function (ctx) {
var context = ctx || cc.renderContext;
@@ -856,41 +856,6 @@ cc.LayerColorCanvas = cc.LayerRGBA.extend(/** @lends cc.LayerColorCanvas# */{
}
});
-/**
- * creates a cc.LayerColorCanvas with color, width and height in Points
- * @param {cc.Color4B} color
- * @param {Number|Null} width
- * @param {Number|Null} height
- * @return {cc.LayerColor}
- * @example
- * // Example
- * //Create a yellow color layer as background
- * var yellowBackground = cc.LayerColor.create(cc.c4b(255,255,0,255));
- * //If you didnt pass in width and height, it defaults to the same size as the canvas
- *
- * //create a yellow box, 200 by 200 in size
- * var yellowBox = cc.LayerColorCanvas.create(cc.c3b(255,255,0,255), 200, 200);
- */
-cc.LayerColorCanvas.create = function (color, width, height) {
- var ret = new cc.LayerColorCanvas();
- switch (arguments.length) {
- case 0:
- ret.init();
- break;
- case 1:
- ret.init(color);
- break;
- case 3:
- ret.init(color, width, height);
- break;
- default :
- ret.init();
- break;
- }
- return ret;
-};
-
-
/**
* CCLayerColor is a subclass of CCLayer that implements the CCRGBAProtocol protocol. (WebGL implement)
* All features from CCLayer are valid, plus the following new features:
@@ -1098,11 +1063,13 @@ cc.LayerColorWebGL = cc.LayerRGBA.extend(/** @lends cc.LayerColorCanvas# */{
}
});
+cc.LayerColor = cc.Browser.supportWebGL ? cc.LayerColorWebGL : cc.LayerColorCanvas;
+
/**
* creates a cc.Layer with color, width and height in Points
* @param {cc.Color4B} color
- * @param {Number|Null} width
- * @param {Number|Null} height
+ * @param {Number|Null} [width=]
+ * @param {Number|Null} [height=]
* @return {cc.LayerColor}
* @example
* // Example
@@ -1113,8 +1080,8 @@ cc.LayerColorWebGL = cc.LayerRGBA.extend(/** @lends cc.LayerColorCanvas# */{
* //create a yellow box, 200 by 200 in size
* var yellowBox = cc.LayerColor.create(cc.c4b(255,255,0,255), 200, 200);
*/
-cc.LayerColorWebGL.create = function (color, width, height) {
- var ret = new cc.LayerColorWebGL();
+cc.LayerColor.create = function (color, width, height) {
+ var ret = new cc.LayerColor();
switch (arguments.length) {
case 0:
ret.init();
@@ -1132,8 +1099,6 @@ cc.LayerColorWebGL.create = function (color, width, height) {
return ret;
};
-cc.LayerColor = cc.Browser.supportWebGL ? cc.LayerColorWebGL : cc.LayerColorCanvas;
-
/**
*
* CCLayerGradient is a subclass of cc.LayerColor that draws gradients across the background.
diff --git a/cocos2d/sprite_nodes/CCSpriteFrame.js b/cocos2d/sprite_nodes/CCSpriteFrame.js
index 8ffd2bf9d6..09aa85ae7f 100644
--- a/cocos2d/sprite_nodes/CCSpriteFrame.js
+++ b/cocos2d/sprite_nodes/CCSpriteFrame.js
@@ -153,7 +153,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* @return {cc.Size}
*/
getOriginalSize:function () {
- return this._originalSize; //cc.size(this._originalSize.width, this._originalSize.height);
+ return cc.size(this._originalSize.width, this._originalSize.height);
},
/**
@@ -192,7 +192,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* @return {cc.Point}
*/
getOffset:function () {
- return this._offset; //cc.p(this._offset.x, this._offset.y);
+ return cc.p(this._offset.x, this._offset.y);
},
/**
diff --git a/cocos2d/textures/CCTextureCache.js b/cocos2d/textures/CCTextureCache.js
index 8b3363e41b..dd7a4b2cde 100644
--- a/cocos2d/textures/CCTextureCache.js
+++ b/cocos2d/textures/CCTextureCache.js
@@ -406,23 +406,11 @@ cc.TextureCacheCanvas = cc.Class.extend(/** @lends cc.TextureCacheCanvas# */{
});
/**
- * Return ths shared instance of the cache
- * @return {cc.TextureCache}
- */
-cc.TextureCacheCanvas.getInstance = function () {
- if (!cc.g_sharedTextureCache)
- cc.g_sharedTextureCache = new cc.TextureCacheCanvas();
- return cc.g_sharedTextureCache;
-};
-
-/**
- * Purges the cache. It releases the retained instance.
+ * Implementation TextureCache (WebGL implement)
+ * @class
+ * @extends cc.Class
*/
-cc.TextureCacheCanvas.purgeSharedTextureCache = function () {
- cc.g_sharedTextureCache = null;
-};
-
-cc.TextureCacheWebGL = cc.Class.extend({
+cc.TextureCacheWebGL = cc.Class.extend(/** @lends cc.TextureCacheWebGL# */{
/// ---- common properties start ----
_textures:null,
_textureColorsCache:null,
@@ -821,23 +809,21 @@ cc.TextureCacheWebGL = cc.Class.extend({
}
});
+cc.TextureCache = cc.Browser.supportWebGL ? cc.TextureCacheWebGL : cc.TextureCacheCanvas;
+
/**
* Return ths shared instance of the cache
* @return {cc.TextureCache}
*/
-cc.TextureCacheWebGL.getInstance = function () {
+cc.TextureCache.getInstance = function () {
if (!cc.g_sharedTextureCache)
- cc.g_sharedTextureCache = new cc.TextureCacheWebGL();
+ cc.g_sharedTextureCache = new cc.TextureCache();
return cc.g_sharedTextureCache;
};
/**
* Purges the cache. It releases the retained instance.
*/
-cc.TextureCacheWebGL.purgeSharedTextureCache = function () {
+cc.TextureCache.purgeSharedTextureCache = function () {
cc.g_sharedTextureCache = null;
};
-
-cc.TextureCache = cc.Browser.supportWebGL ? cc.TextureCacheWebGL : cc.TextureCacheCanvas;
-
-
diff --git a/extensions/GUI/CCControlExtension/CCScale9Sprite.js b/extensions/GUI/CCControlExtension/CCScale9Sprite.js
index 2b1b1fd5fa..4e33fc42c3 100644
--- a/extensions/GUI/CCControlExtension/CCScale9Sprite.js
+++ b/extensions/GUI/CCControlExtension/CCScale9Sprite.js
@@ -82,16 +82,18 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
_spriteFrameRotated: false,
_updateCapInset: function () {
- var insets;
- if (this._insetLeft == 0 && this._insetTop == 0 && this._insetRight == 0 && this._insetBottom == 0) {
+ 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.RectZero();
} else {
- insets = this._spriteFrameRotated ? cc.RectMake(this._insetBottom, this._insetLeft,
- this._spriteRect.width - this._insetRight - this._insetLeft,
- this._spriteRect.height - this._insetTop - this._insetBottom) :
- cc.RectMake(this._insetLeft, this._insetTop,
- this._spriteRect.width - this._insetLeft - this._insetRight,
- this._spriteRect.height - this._insetTop - this._insetBottom);
+
+ insets = this._spriteFrameRotated ? cc.RectMake(locInsetBottom, locInsetLeft,
+ locSpriteRect.width - locInsetRight - locInsetLeft,
+ locSpriteRect.height - locInsetTop - locInsetBottom) :
+ cc.RectMake(locInsetLeft, locInsetTop,
+ locSpriteRect.width - locInsetLeft - locInsetRight,
+ locSpriteRect.height - locInsetTop - locInsetBottom);
}
this.setCapInsets(insets);
},
@@ -105,64 +107,70 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
}
var size = this._contentSize;
- var sizableWidth = size.width - this._topLeft.getContentSize().width - this._topRight.getContentSize().width;
- var sizableHeight = size.height - this._topLeft.getContentSize().height - this._bottomRight.getContentSize().height;
- var horizontalScale = sizableWidth / this._centre.getContentSize().width;
- var verticalScale = sizableHeight / this._centre.getContentSize().height;
- var rescaledWidth = this._centre.getContentSize().width * horizontalScale;
- var rescaledHeight = this._centre.getContentSize().height * verticalScale;
+ var locTopLeft = this._topLeft, locTopRight = this._topRight, locBottomRight = this._bottomRight;
+ var locCenter = this._centre, locCenterContentSize = this._centre.getContentSize();
+
+ var sizableWidth = size.width - locTopLeft.getContentSize().width - locTopRight.getContentSize().width;
+ var sizableHeight = size.height - locTopLeft.getContentSize().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 = this._bottomLeft.getContentSize().width;
- var bottomHeight = this._bottomLeft.getContentSize().height;
+ var locBottomLeft = this._bottomLeft;
+ var leftWidth = locBottomLeft.getContentSize().width;
+ var bottomHeight = locBottomLeft.getContentSize().height;
if(!cc.Browser.supportWebGL) {
//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/this._centre.getContentSize().width;
+ horizontalScale = rescaledWidth/locCenterContentSize.width;
}
var roundedRescaledHeight = Math.round(rescaledHeight);
if(rescaledHeight != roundedRescaledHeight) {
rescaledHeight = roundedRescaledHeight;
- verticalScale = rescaledHeight/this._centre.getContentSize().height;
+ verticalScale = rescaledHeight/locCenterContentSize.height;
}
}
- this._centre.setScaleX(horizontalScale);
- this._centre.setScaleY(verticalScale);
-
- this._bottomLeft.setAnchorPoint(cc.p(0, 0));
- this._bottomRight.setAnchorPoint(cc.p(0, 0));
- this._topLeft.setAnchorPoint(cc.p(0, 0));
- this._topRight.setAnchorPoint(cc.p(0, 0));
- this._left.setAnchorPoint(cc.p(0, 0));
- this._right.setAnchorPoint(cc.p(0, 0));
- this._top.setAnchorPoint(cc.p(0, 0));
- this._bottom.setAnchorPoint(cc.p(0, 0));
- this._centre.setAnchorPoint(cc.p(0, 0));
+ locCenter.setScaleX(horizontalScale);
+ locCenter.setScaleY(verticalScale);
+
+ var locLeft = this._left, locRight = this._right, locTop = this._top, locBottom = this._bottom;
+ var tempAP = cc.p(0, 0);
+ locBottomLeft.setAnchorPoint(tempAP);
+ locBottomRight.setAnchorPoint(tempAP);
+ locTopLeft.setAnchorPoint(tempAP);
+ locTopRight.setAnchorPoint(tempAP);
+ locLeft.setAnchorPoint(tempAP);
+ locRight.setAnchorPoint(tempAP);
+ locTop.setAnchorPoint(tempAP);
+ locBottom.setAnchorPoint(tempAP);
+ locCenter.setAnchorPoint(tempAP);
// Position corners
- this._bottomLeft.setPosition(cc.p(0, 0));
- this._bottomRight.setPosition(cc.p(leftWidth + rescaledWidth, 0));
- this._topLeft.setPosition(cc.p(0, bottomHeight + rescaledHeight));
- this._topRight.setPosition(cc.p(leftWidth + rescaledWidth, bottomHeight + rescaledHeight));
+ locBottomLeft.setPosition(0, 0);
+ locBottomRight.setPosition(leftWidth + rescaledWidth, 0);
+ locTopLeft.setPosition(0, bottomHeight + rescaledHeight);
+ locTopRight.setPosition(leftWidth + rescaledWidth, bottomHeight + rescaledHeight);
// Scale and position borders
- this._left.setPosition(cc.p(0, bottomHeight));
- this._left.setScaleY(verticalScale);
- this._right.setPosition(cc.p(leftWidth + rescaledWidth, bottomHeight));
- this._right.setScaleY(verticalScale);
- this._bottom.setPosition(cc.p(leftWidth, 0));
- this._bottom.setScaleX(horizontalScale);
- this._top.setPosition(cc.p(leftWidth, bottomHeight + rescaledHeight));
- this._top.setScaleX(horizontalScale);
+ locLeft.setPosition(0, bottomHeight);
+ locLeft.setScaleY(verticalScale);
+ locRight.setPosition(leftWidth + rescaledWidth, bottomHeight);
+ locRight.setScaleY(verticalScale);
+ locBottom.setPosition(leftWidth, 0);
+ locBottom.setScaleX(horizontalScale);
+ locTop.setPosition(leftWidth, bottomHeight + rescaledHeight);
+ locTop.setScaleX(horizontalScale);
// Position centre
- this._centre.setPosition(cc.p(leftWidth, bottomHeight));
+ locCenter.setPosition(leftWidth, bottomHeight);
},
ctor: function () {
- this._super();
+ cc.Node.prototype.ctor.call(this);
this._spriteRect = cc.RectZero();
this._capInsetsInternal = cc.RectZero();
@@ -196,9 +204,9 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
this._opacity = opacity;
var scaleChildren = this._scale9Image.getChildren();
for (var i = 0; i < scaleChildren.length; i++) {
- if (scaleChildren[i] && scaleChildren[i].RGBAProtocol) {
- scaleChildren[i].setOpacity(this._opacity);
- }
+ var selChild = scaleChildren[i];
+ if (selChild && selChild.RGBAProtocol)
+ selChild.setOpacity(opacity);
}
},
@@ -210,9 +218,9 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
this._color = color;
var scaleChildren = this._scale9Image.getChildren();
for (var i = 0; i < scaleChildren.length; i++) {
- if (scaleChildren[i] && scaleChildren[i].RGBAProtocol) {
- scaleChildren[i].setColor(this._color);
- }
+ var selChild = scaleChildren[i];
+ if (selChild && selChild.RGBAProtocol)
+ selChild.setColor(color);
}
},
@@ -443,10 +451,11 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
if (this._scale9Image != batchNode)
this._scale9Image = batchNode;
- this._scale9Image.removeAllChildren(true);
+ var locScale9Image = this._scale9Image;
+ locScale9Image.removeAllChildren(true);
this._capInsets = capInsets;
- var selTexture = this._scale9Image.getTexture();
+ var selTexture = locScale9Image.getTexture();
var rectZero = cc.RectZero();
// If there is no given rect
@@ -463,24 +472,36 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
// Set the given rect's size as original size
this._spriteRect = rect;
var rectSize = rect.size;
- this._originalSize = new cc.Size(rectSize.width, rectSize.height);
- this._preferredSize = new cc.Size(rectSize.width, rectSize.height);
- this._capInsetsInternal = capInsets || cc.RectZero();
+ this._originalSize.width = rectSize.width;
+ this._originalSize.height = rectSize.height;
+ this._preferredSize.width = rectSize.width;
+ this._preferredSize.height = rectSize.height;
+
+ var locCapInsetsInternal = this._capInsetsInternal;
+ if(!capInsets){
+ locCapInsetsInternal.x = capInsets.x;
+ locCapInsetsInternal.y = capInsets.y;
+ locCapInsetsInternal.width = capInsets.width;
+ locCapInsetsInternal.height = capInsets.height;
+ }
var w = rectSize.width;
var h = rectSize.height;
// If there is no specified center region
- if (cc.rectEqualToRect(this._capInsetsInternal, rectZero)) {
+ if (cc.rectEqualToRect(locCapInsetsInternal, rectZero)) {
// CCLog("... cap insets not specified : using default cap insets ...");
- this._capInsetsInternal = cc.rect(w / 3, h / 3, w / 3, h / 3);
+ locCapInsetsInternal.x = w / 3;
+ locCapInsetsInternal.y = h / 3;
+ locCapInsetsInternal.width = w / 3;
+ locCapInsetsInternal.height = h / 3;
}
- var left_w = this._capInsetsInternal.x;
- var center_w = this._capInsetsInternal.width;
+ var left_w = locCapInsetsInternal.x;
+ var center_w = locCapInsetsInternal.width;
var right_w = w - (left_w + center_w);
- var top_h = this._capInsetsInternal.y;
- var center_h = this._capInsetsInternal.height;
+ var top_h = locCapInsetsInternal.y;
+ var center_h = locCapInsetsInternal.height;
var bottom_h = h - (top_h + center_h);
// calculate rects
@@ -532,9 +553,9 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
x += center_w;
var rightbottombounds = cc.RectMake(x, y, right_w, bottom_h);
+ var t = cc.AffineTransformMakeIdentity();
if (!rotated) {
// CCLog("!rotated");
- var t = cc.AffineTransformMakeIdentity();
t = cc.AffineTransformTranslate(t, rect.x, rect.y);
centerbounds = cc.RectApplyAffineTransform(centerbounds, t);
@@ -550,55 +571,52 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
// Centre
this._centre = new cc.Sprite();
this._centre.initWithTexture(selTexture, centerbounds);
- this._scale9Image.addChild(this._centre, 0, cc.POSITIONS_CENTRE);
+ locScale9Image.addChild(this._centre, 0, cc.POSITIONS_CENTRE);
// Top
this._top = new cc.Sprite();
this._top.initWithTexture(selTexture, centertopbounds);
- this._scale9Image.addChild(this._top, 1, cc.POSITIONS_TOP);
+ locScale9Image.addChild(this._top, 1, cc.POSITIONS_TOP);
// Bottom
this._bottom = new cc.Sprite();
this._bottom.initWithTexture(selTexture, centerbottombounds);
- this._scale9Image.addChild(this._bottom, 1, cc.POSITIONS_BOTTOM);
+ locScale9Image.addChild(this._bottom, 1, cc.POSITIONS_BOTTOM);
// Left
this._left = new cc.Sprite();
this._left.initWithTexture(selTexture, leftcenterbounds);
- this._scale9Image.addChild(this._left, 1, cc.POSITIONS_LEFT);
+ locScale9Image.addChild(this._left, 1, cc.POSITIONS_LEFT);
// Right
this._right = new cc.Sprite();
this._right.initWithTexture(selTexture, rightcenterbounds);
- this._scale9Image.addChild(this._right, 1, cc.POSITIONS_RIGHT);
+ locScale9Image.addChild(this._right, 1, cc.POSITIONS_RIGHT);
// Top left
this._topLeft = new cc.Sprite();
this._topLeft.initWithTexture(selTexture, lefttopbounds);
- this._scale9Image.addChild(this._topLeft, 2, cc.POSITIONS_TOPLEFT);
+ locScale9Image.addChild(this._topLeft, 2, cc.POSITIONS_TOPLEFT);
// Top right
this._topRight = new cc.Sprite();
this._topRight.initWithTexture(selTexture, righttopbounds);
- this._scale9Image.addChild(this._topRight, 2, cc.POSITIONS_TOPRIGHT);
+ locScale9Image.addChild(this._topRight, 2, cc.POSITIONS_TOPRIGHT);
// Bottom left
this._bottomLeft = new cc.Sprite();
this._bottomLeft.initWithTexture(selTexture, leftbottombounds);
- this._scale9Image.addChild(this._bottomLeft, 2, cc.POSITIONS_BOTTOMLEFT);
+ locScale9Image.addChild(this._bottomLeft, 2, cc.POSITIONS_BOTTOMLEFT);
// Bottom right
this._bottomRight = new cc.Sprite();
this._bottomRight.initWithTexture(selTexture, rightbottombounds);
- this._scale9Image.addChild(this._bottomRight, 2, cc.POSITIONS_BOTTOMRIGHT);
+ locScale9Image.addChild(this._bottomRight, 2, cc.POSITIONS_BOTTOMRIGHT);
} else {
// set up transformation of coordinates
// to handle the case where the sprite is stored rotated
// in the spritesheet
// CCLog("rotated");
-
- var t = cc.AffineTransformMakeIdentity();
-
var rotatedcenterbounds = centerbounds;
var rotatedrightbottombounds = rightbottombounds;
var rotatedleftbottombounds = leftbottombounds;
@@ -622,64 +640,81 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
centerbottombounds = cc.RectApplyAffineTransform(centerbottombounds, t);
centertopbounds = cc.RectApplyAffineTransform(centertopbounds, t);
- rotatedcenterbounds.origin = {x: centerbounds.x, y: centerbounds.y};
- rotatedrightbottombounds.origin = {x: rightbottombounds.x, y: rightbottombounds.y};
- rotatedleftbottombounds.origin = {x: leftbottombounds.x, y: leftbottombounds.y};
- rotatedrighttopbounds.origin = {x: righttopbounds.x, y: righttopbounds.y};
- rotatedlefttopbounds.origin = {x: lefttopbounds.x, y: lefttopbounds.y};
- rotatedrightcenterbounds.origin = {x: rightcenterbounds.x, y: rightcenterbounds.y};
- rotatedleftcenterbounds.origin = {x: leftcenterbounds.x, y: leftcenterbounds.y};
- rotatedcenterbottombounds.origin = {x: centerbottombounds.x, y: centerbottombounds.y};
- rotatedcentertopbounds.origin = {x: centertopbounds.x, y: centertopbounds.y};
+ rotatedcenterbounds.x = centerbounds.x;
+ rotatedcenterbounds.y = centerbounds.y;
+
+ rotatedrightbottombounds.x = rightbottombounds.x;
+ rotatedrightbottombounds.y = rightbottombounds.y;
+
+ rotatedleftbottombounds.x = leftbottombounds.x;
+ rotatedleftbottombounds.y = leftbottombounds.y;
+
+ rotatedrighttopbounds.x = righttopbounds.x;
+ rotatedrighttopbounds.y = righttopbounds.y;
+
+ rotatedlefttopbounds.x = lefttopbounds.x;
+ rotatedlefttopbounds.y = lefttopbounds.y;
+
+ rotatedrightcenterbounds.x = rightcenterbounds.x;
+ rotatedrightcenterbounds.y = rightcenterbounds.y;
+
+ rotatedleftcenterbounds.x = leftcenterbounds.x;
+ rotatedleftcenterbounds.y = leftcenterbounds.y;
+
+ rotatedcenterbottombounds.x = centerbottombounds.x;
+ rotatedcenterbottombounds.y = centerbottombounds.y;
+
+ rotatedcentertopbounds.x = centertopbounds.x;
+ rotatedcentertopbounds.y = centertopbounds.y;
// Centre
this._centre = new cc.Sprite();
this._centre.initWithTexture(selTexture, rotatedcenterbounds, true);
- this._scale9Image.addChild(this._centre, 0, cc.POSITIONS_CENTRE);
+ locScale9Image.addChild(this._centre, 0, cc.POSITIONS_CENTRE);
// Top
this._top = new cc.Sprite();
this._top.initWithTexture(selTexture, rotatedcentertopbounds, true);
- this._scale9Image.addChild(this._top, 1, cc.POSITIONS_TOP);
+ locScale9Image.addChild(this._top, 1, cc.POSITIONS_TOP);
// Bottom
this._bottom = new cc.Sprite();
this._bottom.initWithTexture(selTexture, rotatedcenterbottombounds, true);
- this._scale9Image.addChild(this._bottom, 1, cc.POSITIONS_BOTTOM);
+ locScale9Image.addChild(this._bottom, 1, cc.POSITIONS_BOTTOM);
// Left
this._left = new cc.Sprite();
this._left.initWithTexture(selTexture, rotatedleftcenterbounds, true);
- this._scale9Image.addChild(this._left, 1, cc.POSITIONS_LEFT);
+ locScale9Image.addChild(this._left, 1, cc.POSITIONS_LEFT);
// Right
this._right = new cc.Sprite();
this._right.initWithTexture(selTexture, rotatedrightcenterbounds, true);
- this._scale9Image.addChild(this._right, 1, cc.POSITIONS_RIGHT);
+ locScale9Image.addChild(this._right, 1, cc.POSITIONS_RIGHT);
// Top left
this._topLeft = new cc.Sprite();
this._topLeft.initWithTexture(selTexture, rotatedlefttopbounds, true);
- this._scale9Image.addChild(this._topLeft, 2, cc.POSITIONS_TOPLEFT);
+ locScale9Image.addChild(this._topLeft, 2, cc.POSITIONS_TOPLEFT);
// Top right
this._topRight = new cc.Sprite();
this._topRight.initWithTexture(selTexture, rotatedrighttopbounds, true);
- this._scale9Image.addChild(this._topRight, 2, cc.POSITIONS_TOPRIGHT);
+ locScale9Image.addChild(this._topRight, 2, cc.POSITIONS_TOPRIGHT);
// Bottom left
this._bottomLeft = new cc.Sprite();
this._bottomLeft.initWithTexture(selTexture, rotatedleftbottombounds, true);
- this._scale9Image.addChild(this._bottomLeft, 2, cc.POSITIONS_BOTTOMLEFT);
+ locScale9Image.addChild(this._bottomLeft, 2, cc.POSITIONS_BOTTOMLEFT);
// Bottom right
this._bottomRight = new cc.Sprite();
this._bottomRight.initWithTexture(selTexture, rotatedrightbottombounds, true);
- this._scale9Image.addChild(this._bottomRight, 2, cc.POSITIONS_BOTTOMRIGHT);
+ locScale9Image.addChild(this._bottomRight, 2, cc.POSITIONS_BOTTOMRIGHT);
}
this.setContentSize(rect.size);
- this.addChild(this._scale9Image);
+ this.addChild(locScale9Image);
if (this._spritesGenerated) {
// Restore color and opacity
diff --git a/extensions/GUI/CCScrollView/CCScrollView.js b/extensions/GUI/CCScrollView/CCScrollView.js
index a384204931..670cffbadd 100644
--- a/extensions/GUI/CCScrollView/CCScrollView.js
+++ b/extensions/GUI/CCScrollView/CCScrollView.js
@@ -79,14 +79,20 @@ cc.ScrollView = cc.Layer.extend({
_parentScissorRect:null,
_scissorRestored:false,
+ // cache object
+ _tmpViewRect:null,
+
ctor:function () {
- this._super();
+ cc.Layer.prototype.ctor.call(this);
+ this._contentOffset = new cc.Point(0,0);
this._maxInset = new cc.Point(0, 0);
this._minInset = new cc.Point(0, 0);
this._scrollDistance = new cc.Point(0, 0);
this._touchPoint = new cc.Point(0, 0);
this._touches = [];
this._viewSize = new cc.Size(0, 0);
+ this._parentScissorRect = new cc.Rect(0,0,0,0);
+ this._tmpViewRect = new cc.Rect(0,0,0,0);
},
init:function () {
@@ -104,26 +110,27 @@ cc.ScrollView = cc.Layer.extend({
* @return {Boolean}
*/
initWithViewSize:function (size, container) {
+ var pZero = cc.p(0,0);
if (cc.Layer.prototype.init.call(this)) {
this._container = container;
if (!this._container) {
this._container = cc.Layer.create();
this._container.ignoreAnchorPointForPosition(false);
- this._container.setAnchorPoint(cc.p(0.0, 0.0));
+ this._container.setAnchorPoint(pZero);
}
this.setViewSize(size);
this.setTouchEnabled(true);
- this._touches = [];
+ this._touches.length = 0;
this._delegate = null;
this._bounceable = true;
this._clippingToBounds = true;
//this._container.setContentSize(CCSizeZero);
this._direction = cc.SCROLLVIEW_DIRECTION_BOTH;
- this._container.setPosition(cc.p(0.0, 0.0));
+ this._container.setPosition(pZero);
this._touchLength = 0.0;
this.addChild(this._container);
@@ -137,7 +144,7 @@ cc.ScrollView = cc.Layer.extend({
* Sets a new content offset. It ignores max/min offset. It just sets what's given. (just like UIKit's UIScrollView)
*
* @param {cc.Point} offset new offset
- * @param {Number} animated If YES, the view scrolls to the new offset
+ * @param {Number} [animated=] If YES, the view scrolls to the new offset
*/
setContentOffset:function (offset, animated) {
if (animated) { //animate scrolling
@@ -152,8 +159,9 @@ cc.ScrollView = cc.Layer.extend({
}
this._container.setPosition(offset);
- if (this._delegate != null && this._delegate.scrollViewDidScroll) {
- this._delegate.scrollViewDidScroll(this);
+ var locDelegate = this._delegate;
+ if (locDelegate != null && locDelegate.scrollViewDidScroll) {
+ locDelegate.scrollViewDidScroll(this);
}
}
},
@@ -184,7 +192,8 @@ cc.ScrollView = cc.Layer.extend({
*/
setZoomScale:function (scale, animated) {
if (arguments.length === 1) {
- if (this._container.getScale() != scale) {
+ var locContainer = this._container;
+ if (locContainer.getScale() != scale) {
var oldCenter, newCenter;
var center;
@@ -194,15 +203,15 @@ cc.ScrollView = cc.Layer.extend({
} else
center = this._touchPoint;
- oldCenter = this._container.convertToNodeSpace(center);
- this._container.setScale(Math.max(this._minScale, Math.min(this._maxScale, scale)));
- newCenter = this._container.convertToWorldSpace(oldCenter);
+ oldCenter = locContainer.convertToNodeSpace(center);
+ locContainer.setScale(Math.max(this._minScale, Math.min(this._maxScale, scale)));
+ newCenter = locContainer.convertToWorldSpace(oldCenter);
var offset = cc.pSub(center, newCenter);
if (this._delegate != null) {
this._delegate.scrollViewDidZoom(this);
}
- this.setContentOffset(cc.pAdd(this._container.getPosition(), offset));
+ this.setContentOffset(cc.pAdd(locContainer.getPosition(), offset));
}
} else if (arguments.length === 2) {
if (animated)
@@ -237,8 +246,9 @@ cc.ScrollView = cc.Layer.extend({
* Returns the current container's minimum offset. You may want this while you animate scrolling by yourself
*/
minContainerOffset:function () {
- return cc.p(this._viewSize.width - this._container.getContentSize().width * this._container.getScaleX(),
- this._viewSize.height - this._container.getContentSize().height * this._container.getScaleY());
+ var locContentSize = this._container.getContentSize();
+ return cc.p(this._viewSize.width - locContentSize.width * this._container.getScaleX(),
+ this._viewSize.height - locContentSize.height * this._container.getScaleY());
},
/**
@@ -260,7 +270,7 @@ cc.ScrollView = cc.Layer.extend({
var viewRect = cc.RectMake(-offset.x / scale, -offset.y / scale, size.width / scale, size.height / scale);
- return cc.CCRectIntersectsRect(viewRect, node.getBoundingBox());
+ return cc.rectIntersectsRect(viewRect, node.getBoundingBox());
},
/**
@@ -362,25 +372,28 @@ cc.ScrollView = cc.Layer.extend({
var frame = this._getViewRect();
//dispatcher does not know about clipping. reject touches outside visible bounds.
- var locPoint = this._container.convertToWorldSpace(this._container.convertTouchToNodeSpace(touch));
- if (this._touches.length > 2 || this._touchMoved || !cc.rectContainsPoint(frame, locPoint))
+ var locContainer = this._container;
+ var locPoint = locContainer.convertToWorldSpace(locContainer.convertTouchToNodeSpace(touch));
+ var locTouches = this._touches;
+ if (locTouches.length > 2 || this._touchMoved || !cc.rectContainsPoint(frame, locPoint))
return false;
//if (!cc.ArrayContainsObject(this._touches, touch)) {
- this._touches.push(touch);
+ locTouches.push(touch);
//}
- if (this._touches.length == 1) { // scrolling
+ if (locTouches.length == 1) { // scrolling
this._touchPoint = this.convertTouchToNodeSpace(touch);
this._touchMoved = false;
this._dragging = true; //dragging started
- this._scrollDistance = cc.p(0.0, 0.0);
+ this._scrollDistance.x = 0;
+ this._scrollDistance.y = 0;
this._touchLength = 0.0;
- } else if (this._touches.length == 2) {
- this._touchPoint = cc.pMidpoint(this.convertTouchToNodeSpace(this._touches[0]),
- this.convertTouchToNodeSpace(this._touches[1]));
- this._touchLength = cc.pDistance(this._container.convertTouchToNodeSpace(this._touches[0]),
- this._container.convertTouchToNodeSpace(this._touches[1]));
+ } else if (locTouches.length == 2) {
+ this._touchPoint = cc.pMidpoint(this.convertTouchToNodeSpace(locTouches[0]),
+ this.convertTouchToNodeSpace(locTouches[1]));
+ this._touchLength = cc.pDistance(locContainer.convertTouchToNodeSpace(locTouches[0]),
+ locContainer.convertTouchToNodeSpace(locTouches[1]));
this._dragging = false;
}
return true;
@@ -407,7 +420,7 @@ cc.ScrollView = cc.Layer.extend({
else if (this._direction === cc.SCROLLVIEW_DIRECTION_HORIZONTAL)
dis = moveDistance.x;
else
- dis = Math.sqrt(moveDistance.x * moveDistance.x + moveDistance.y*moveDistance.y);
+ dis = Math.sqrt(moveDistance.x * moveDistance.x + moveDistance.y * moveDistance.y);
if (!this._touchMoved && Math.abs(cc.convertDistanceFromPointToInch(dis)) < MOVE_INCH ){
//CCLOG("Invalid movement, distance = [%f, %f], disInch = %f", moveDistance.x, moveDistance.y);
@@ -425,22 +438,23 @@ cc.ScrollView = cc.Layer.extend({
if (cc.rectContainsPoint(frame, this.convertToWorldSpace(newPoint))) {
switch (this._direction) {
case cc.SCROLLVIEW_DIRECTION_VERTICAL:
- moveDistance = cc.p(0.0, moveDistance.y);
+ moveDistance.x = 0.0;
break;
case cc.SCROLLVIEW_DIRECTION_HORIZONTAL:
- moveDistance = cc.p(moveDistance.x, 0.0);
+ moveDistance.y = 0.0;
break;
default:
break;
}
- var newX = this._container.getPosition().x + moveDistance.x;
- var newY = this._container.getPosition().y + moveDistance.y;
+ var locPosition = this._container.getPosition();
+ var newX = locPosition.x + moveDistance.x;
+ var newY = locPosition.y + moveDistance.y;
this._scrollDistance = moveDistance;
this.setContentOffset(cc.p(newX, newY));
}
- } else if (this._touches.length == 2 && !this._dragging) {
+ } else if (this._touches.length === 2 && !this._dragging) {
var len = cc.pDistance(this._container.convertTouchToNodeSpace(this._touches[0]),
this._container.convertTouchToNodeSpace(this._touches[1]));
this.setZoomScale(this.getZoomScale() * len / this._touchLength);
@@ -481,12 +495,13 @@ cc.ScrollView = cc.Layer.extend({
updateInset:function () {
if (this.getContainer() != null) {
- this._maxInset = this.maxContainerOffset();
- this._maxInset = cc.p(this._maxInset.x + this._viewSize.width * INSET_RATIO,
- this._maxInset.y + this._viewSize.height * INSET_RATIO);
- this._minInset = this.minContainerOffset();
- this._minInset = cc.p(this._minInset.x - this._viewSize.width * INSET_RATIO,
- this._minInset.y - this._viewSize.height * INSET_RATIO);
+ var locViewSize = this._viewSize;
+ var tempOffset = this.maxContainerOffset();
+ this._maxInset.x = tempOffset.x + locViewSize.width * INSET_RATIO;
+ this._maxInset.y = tempOffset.y + locViewSize.height * INSET_RATIO;
+ tempOffset = this.minContainerOffset();
+ this._minInset.x = tempOffset.x - locViewSize.width * INSET_RATIO;
+ this._minInset.y = tempOffset.y - locViewSize.height * INSET_RATIO;
}
},
@@ -507,18 +522,20 @@ cc.ScrollView = cc.Layer.extend({
return;
var context = ctx || cc.renderContext;
- var i;
+ var i, locChildren = this._children, selChild, childrenLen;
if (cc.renderContextType === cc.CANVAS) {
context.save();
this.transform(context);
this._beforeDraw(context);
- if (this._children && this._children.length > 0) {
+ if (locChildren && locChildren.length > 0) {
+ childrenLen = locChildren.length;
this.sortAllChildren();
// draw children zOrder < 0
- for (i = 0; i < this._children.length; i++) {
- if (this._children[i] && this._children[i]._zOrder < 0)
- this._children[i].visit(context);
+ for (i = 0; i < childrenLen; i++) {
+ selChild = locChildren[i];
+ if (selChild && selChild._zOrder < 0)
+ selChild.visit(context);
else
break;
}
@@ -526,12 +543,8 @@ cc.ScrollView = cc.Layer.extend({
this.draw(context); // self draw
// draw children zOrder >= 0
- if (this._children) {
- for (; i < this._children.length; i++) {
- if (this._children[i] && this._children[i]._zOrder >= 0)
- this._children[i].visit(context);
- }
- }
+ for (; i < childrenLen; i++)
+ locChildren[i].visit(context);
} else
this.draw(context); // self draw
@@ -540,19 +553,21 @@ cc.ScrollView = cc.Layer.extend({
context.restore();
} else {
cc.kmGLPushMatrix();
- if (this._grid && this._grid.isActive()) {
- this._grid.beforeDraw();
+ var locGrid = this._grid;
+ if (locGrid && locGrid.isActive()) {
+ locGrid.beforeDraw();
this.transformAncestors();
}
this.transform(context);
this._beforeDraw(context);
- if (this._children) {
- i = 0;
+ if (locChildren && locChildren.length > 0) {
+ childrenLen = locChildren.length;
// draw children zOrder < 0
- for (; i < this._children.length; i++) {
- if (this._children[i].getZOrder() < 0)
- this._children[i].visit();
+ for (i = 0; i < childrenLen; i++) {
+ selChild = locChildren[i];
+ if (selChild && selChild._zOrder < 0)
+ selChild.visit();
else
break;
}
@@ -561,14 +576,14 @@ cc.ScrollView = cc.Layer.extend({
this.draw(context);
// draw children zOrder >= 0
- for (; i < this._children.length; i++)
- this._children[i].visit();
+ for (; i < childrenLen; i++)
+ locChildren[i].visit();
} else
this.draw(context);
this._afterDraw(context);
- if (this._grid && this._grid.isActive())
- this._grid.afterDraw(this);
+ if (locGrid && locGrid.isActive())
+ locGrid.afterDraw(this);
cc.kmGLPopMatrix();
}
@@ -617,16 +632,17 @@ cc.ScrollView = cc.Layer.extend({
_relocateContainer:function (animated) {
var min = this.minContainerOffset();
var max = this.maxContainerOffset();
+ var locDirection = this._direction;
var oldPoint = this._container.getPosition();
var newX = oldPoint.x;
var newY = oldPoint.y;
- if (this._direction == cc.SCROLLVIEW_DIRECTION_BOTH || this._direction == cc.SCROLLVIEW_DIRECTION_HORIZONTAL) {
+ if (locDirection === cc.SCROLLVIEW_DIRECTION_BOTH || locDirection === cc.SCROLLVIEW_DIRECTION_HORIZONTAL) {
newX = Math.max(newX, min.x);
newX = Math.min(newX, max.x);
}
- if (this._direction == cc.SCROLLVIEW_DIRECTION_BOTH || this._direction == cc.SCROLLVIEW_DIRECTION_VERTICAL) {
+ if (locDirection == cc.SCROLLVIEW_DIRECTION_BOTH || locDirection == cc.SCROLLVIEW_DIRECTION_VERTICAL) {
newY = Math.min(newY, max.y);
newY = Math.max(newY, min.y);
}
@@ -648,7 +664,9 @@ cc.ScrollView = cc.Layer.extend({
}
var maxInset, minInset;
- this._container.setPosition(cc.pAdd(this._container.getPosition(), this._scrollDistance));
+ var oldPosition = this._container.getPosition();
+ var locScrollDistance = this._scrollDistance;
+ this._container.setPosition(oldPosition.x + locScrollDistance.x , oldPosition.y + locScrollDistance.y);
if (this._bounceable) {
maxInset = this._maxInset;
minInset = this._minInset;
@@ -662,15 +680,21 @@ cc.ScrollView = cc.Layer.extend({
newX = Math.max(newX, minInset.x);
var newY = Math.min(this._container.getPosition().y, maxInset.y);
newY = Math.max(newY, minInset.y);*/
- var newX = this._container.getPosition().x;
- var newY = this._container.getPosition().y;
+ oldPosition = this._container.getPosition();
+ var newX = oldPosition.x;
+ var newY = oldPosition.y;
+
+ //this._scrollDistance = cc.pSub(this._scrollDistance, cc.p(newX - this._container.getPosition().x, newY - this._container.getPosition().y));
+ //= this._scrollDistance = cc.pSub(this._scrollDistance, cc.p(0, 0)); = do nothing
+
+ //this._scrollDistance = cc.pMult(this._scrollDistance, SCROLL_DEACCEL_RATE);
+ locScrollDistance.x = locScrollDistance.x * SCROLL_DEACCEL_RATE;
+ locScrollDistance.y = locScrollDistance.y * SCROLL_DEACCEL_RATE;
- this._scrollDistance = cc.pSub(this._scrollDistance, cc.p(newX - this._container.getPosition().x, newY - this._container.getPosition().y));
- this._scrollDistance = cc.pMult(this._scrollDistance, SCROLL_DEACCEL_RATE);
this.setContentOffset(cc.p(newX, newY));
- if ((Math.abs(this._scrollDistance.x) <= SCROLL_DEACCEL_DIST &&
- Math.abs(this._scrollDistance.y) <= SCROLL_DEACCEL_DIST) ||
+ if ((Math.abs(locScrollDistance.x) <= SCROLL_DEACCEL_DIST &&
+ Math.abs(locScrollDistance.y) <= SCROLL_DEACCEL_DIST) ||
newY > maxInset.y || newY < minInset.y ||
newX > maxInset.x || newX < minInset.x ||
newX == maxInset.x || newX == minInset.x ||
@@ -726,9 +750,10 @@ cc.ScrollView = cc.Layer.extend({
ctx.clip();
ctx.closePath();
} else {
- if(cc.EGLView.getInstance().isScissorEnabled()){
+ var EGLViewer = cc.EGLView.getInstance();
+ if(EGLViewer.isScissorEnabled()){
this._scissorRestored = true;
- this._parentScissorRect = cc.EGLView.getInstance().getScissorRect();
+ this._parentScissorRect = EGLViewer.getScissorRect();
//set the intersection of m_tParentScissorRect and frame as the new scissor rect
if (cc.rectIntersection(frame, this._parentScissorRect)) {
var locPSRect = this._parentScissorRect;
@@ -736,12 +761,12 @@ cc.ScrollView = cc.Layer.extend({
var y = Math.max(frame.y, locPSRect.y);
var xx = Math.min(frame.x + frame.width, locPSRect.x + locPSRect.width);
var yy = Math.min(frame.y + frame.height, locPSRect.y + locPSRect.height);
- cc.EGLView.getInstance().setScissorInPoints(x, y, xx - x, yy - y);
+ EGLViewer.setScissorInPoints(x, y, xx - x, yy - y);
}
}else{
ctx.enable(ctx.SCISSOR_TEST);
//clip
- cc.EGLView.getInstance().setScissorInPoints(frame.x, frame.y, frame.width, frame.height);
+ EGLViewer.setScissorInPoints(frame.x, frame.y, frame.width, frame.height);
}
}
@@ -770,6 +795,7 @@ cc.ScrollView = cc.Layer.extend({
_getViewRect:function(){
var screenPos = this.convertToWorldSpace(cc.PointZero());
+ var locViewSize = this._viewSize;
var scaleX = this.getScaleX();
var scaleY = this.getScaleY();
@@ -782,15 +808,21 @@ cc.ScrollView = cc.Layer.extend({
// Support negative scaling. Not doing so causes intersectsRect calls
// (eg: to check if the touch was within the bounds) to return false.
// Note, CCNode::getScale will assert if X and Y scales are different.
- if(scaleX<0) {
- screenPos.x += this._viewSize.width*scaleX;
+ if (scaleX < 0) {
+ screenPos.x += locViewSize.width * scaleX;
scaleX = -scaleX;
}
- if(scaleY<0) {
- screenPos.y += this._viewSize.height*scaleY;
+ if (scaleY < 0) {
+ screenPos.y += locViewSize.height * scaleY;
scaleY = -scaleY;
}
- return cc.RectMake(screenPos.x, screenPos.y, this._viewSize.width * scaleX, this._viewSize.height * scaleY);
+
+ var locViewRect = this._tmpViewRect;
+ locViewRect.x = screenPos.x;
+ locViewRect.y = screenPos.y;
+ locViewRect.width = locViewSize.width * scaleX;
+ locViewRect.height = locViewSize.height * scaleY;
+ return locViewRect;
}
});
diff --git a/extensions/GUI/CCScrollView/CCTableView.js b/extensions/GUI/CCScrollView/CCTableView.js
index a015bc0ee1..dcb5afbeaf 100644
--- a/extensions/GUI/CCScrollView/CCTableView.js
+++ b/extensions/GUI/CCScrollView/CCTableView.js
@@ -175,9 +175,9 @@ cc.TableView = cc.ScrollView.extend({
var offset = this.__offsetFromIndex(index);
var cellSize = this._dataSource.cellSizeForTable(this);
- if (this._vOrdering == cc.TABLEVIEW_FILL_TOPDOWN) {
+ if (this._vOrdering === cc.TABLEVIEW_FILL_TOPDOWN)
offset.y = this.getContainer().getContentSize().height - offset.y - cellSize.height;
- }
+
return offset;
},
@@ -262,11 +262,7 @@ cc.TableView = cc.ScrollView.extend({
return this._tableViewDelegate;
},
- setDelegate:function (delegate, isDirectCall) {
- if (isDirectCall != null && isDirectCall == true) {
- this._super(delegate);
- return;
- }
+ setDelegate:function (delegate) {
this._tableViewDelegate = delegate;
},
@@ -286,7 +282,7 @@ cc.TableView = cc.ScrollView.extend({
},
initWithViewSize:function (size, container) {
- if (this._super(size, container)) {
+ if (cc.ScrollView.prototype.initWithViewSize.call(this, size, container)) {
this._cellsUsed = new cc.ArrayForObjectSorting();
this._cellsFreed = new cc.ArrayForObjectSorting();
this._indices = new cc.Set();
@@ -294,7 +290,7 @@ cc.TableView = cc.ScrollView.extend({
this._vOrdering = cc.TABLEVIEW_FILL_BOTTOMUP;
this.setDirection(cc.SCROLLVIEW_DIRECTION_VERTICAL);
- this.setDelegate(this, true);
+ cc.ScrollView.prototype.setDelegate.call(this, this);
return true;
}
return false;
@@ -311,9 +307,8 @@ cc.TableView = cc.ScrollView.extend({
}
var cell = this._cellWithIndex(idx);
- if (cell) {
+ if (cell)
this._moveCellOutOfSight(cell);
- }
cell = this._dataSource.tableCellAtIndex(this, idx);
this._setIndexForCell(idx, cell);
@@ -330,13 +325,12 @@ cc.TableView = cc.ScrollView.extend({
return;
}
- var newIdx;
-
- var cell = this._cellsUsed.objectWithObjectID(idx);
+ var newIdx, locCellsUsed = this._cellsUsed;
+ var cell = locCellsUsed.objectWithObjectID(idx);
if (cell) {
- newIdx = this._cellsUsed.indexOfSortedObject(cell);
- for (var i = newIdx; i < this._cellsUsed.count(); i++) {
- cell = this._cellsUsed.objectAtIndex(i);
+ newIdx = locCellsUsed.indexOfSortedObject(cell);
+ for (var i = newIdx; i < locCellsUsed.count(); i++) {
+ cell = locCellsUsed.objectAtIndex(i);
this._setIndexForCell(cell.getIdx() + 1, cell);
}
}
@@ -360,11 +354,11 @@ cc.TableView = cc.ScrollView.extend({
}
var cell = this._cellWithIndex(idx);
- if (!cell) {
+ if (!cell)
return;
- }
- var newIdx = this._cellsUsed.indexOfSortedObject(cell);
+ var locCellsUsed = this._cellsUsed;
+ var newIdx = locCellsUsed.indexOfSortedObject(cell);
//remove first
this._moveCellOutOfSight(cell);
@@ -372,8 +366,8 @@ cc.TableView = cc.ScrollView.extend({
this._indices.removeObject(idx);
//cc.ArrayRemoveObjectAtIndex(this._indices,idx);
- for (var i = this._cellsUsed.count() - 1; i > newIdx; i--) {
- cell = this._cellsUsed.objectAtIndex(i);
+ for (var i = locCellsUsed.count() - 1; i > newIdx; i--) {
+ cell = locCellsUsed.objectAtIndex(i);
this._setIndexForCell(cell.getIdx() - 1, cell);
}
},
@@ -382,8 +376,9 @@ cc.TableView = cc.ScrollView.extend({
* reloads data from data source. the view will be refreshed.
*/
reloadData:function () {
- for (var i = 0; i < this._cellsUsed.count(); i++) {
- var cell = this._cellsUsed.objectAtIndex(i);
+ var locCellsUsed = this._cellsUsed;
+ for (var i = 0; i < locCellsUsed.count(); i++) {
+ var cell = locCellsUsed.objectAtIndex(i);
this._cellsFreed.addObject(cell);
cell.reset();
if (cell.getParent() == this.getContainer()) {
@@ -426,7 +421,8 @@ cc.TableView = cc.ScrollView.extend({
},
scrollViewDidScroll:function (view) {
- var countOfItems = this._dataSource.numberOfCellsInTableView(this);
+ var locDataSource = this._dataSource;
+ var countOfItems = locDataSource.numberOfCellsInTableView(this);
if (0 === countOfItems)
return;
@@ -435,32 +431,32 @@ cc.TableView = cc.ScrollView.extend({
var idx = 0;
var offset = cc.pMult(this.getContentOffset(), -1);
- var maxIdx = Math.max(this._dataSource.numberOfCellsInTableView(this) - 1, 0);
-
- var cellSize = this._dataSource.cellSizeForTable(this);
+ var maxIdx = Math.max(locDataSource.numberOfCellsInTableView(this) - 1, 0);
- if (this._vOrdering == cc.TABLEVIEW_FILL_TOPDOWN) {
- offset.y = offset.y + this._viewSize.height / this.getContainer().getScaleY() - cellSize.height;
+ var cellSize = locDataSource.cellSizeForTable(this);
+ var locViewSize = this._viewSize, locContainer = this.getContainer();
+ if (this._vOrdering === cc.TABLEVIEW_FILL_TOPDOWN) {
+ offset.y = offset.y + locViewSize.height / locContainer.getScaleY() - cellSize.height;
}
var startIdx = 0 | this._indexFromOffset(offset);
- if (this._vOrdering == cc.TABLEVIEW_FILL_TOPDOWN) {
- offset.y -= this._viewSize.height / this.getContainer().getScaleY();
+ if (this._vOrdering === cc.TABLEVIEW_FILL_TOPDOWN) {
+ offset.y -= locViewSize.height / locContainer.getScaleY();
} else {
- offset.y += this._viewSize.height / this.getContainer().getScaleY();
+ offset.y += locViewSize.height / locContainer.getScaleY();
}
- offset.x += this._viewSize.width / this.getContainer().getScaleX();
+ offset.x += locViewSize.width / locContainer.getScaleX();
var endIdx = 0 | this._indexFromOffset(offset);
- var cell;
- if (this._cellsUsed.count() > 0) {
- cell = this._cellsUsed.objectAtIndex(0);
+ var cell, locCellsUsed = this._cellsUsed;
+ if (locCellsUsed.count() > 0) {
+ cell = locCellsUsed.objectAtIndex(0);
idx = cell.getIdx();
while (idx < startIdx) {
this._moveCellOutOfSight(cell);
- if (this._cellsUsed.count() > 0) {
- cell = this._cellsUsed.objectAtIndex(0);
+ if (locCellsUsed.count() > 0) {
+ cell = locCellsUsed.objectAtIndex(0);
idx = cell.getIdx();
} else {
break;
@@ -468,13 +464,13 @@ cc.TableView = cc.ScrollView.extend({
}
}
- if (this._cellsUsed.count() > 0) {
- cell = this._cellsUsed.lastObject();
+ if (locCellsUsed.count() > 0) {
+ cell = locCellsUsed.lastObject();
idx = cell.getIdx();
while (idx <= maxIdx && idx > endIdx) {
this._moveCellOutOfSight(cell);
- if (this._cellsUsed.count() > 0) {
- cell = this._cellsUsed.lastObject();
+ if (locCellsUsed.count() > 0) {
+ cell = locCellsUsed.lastObject();
idx = cell.getIdx();
} else {
break;
@@ -483,9 +479,8 @@ cc.TableView = cc.ScrollView.extend({
}
for (var i = startIdx; i <= endIdx; i++) {
- if (this._indices.containsObject(i)) {
+ if (this._indices.containsObject(i))
continue;
- }
this.updateCellAtIndex(i);
}
},
@@ -494,12 +489,12 @@ cc.TableView = cc.ScrollView.extend({
},
onTouchEnded:function (touch, event) {
- if (!this.isVisible()) {
+ if (!this.isVisible())
return;
- }
+
if (this._touches.length == 1 && !this.isTouchMoved()) {
var point = this.getContainer().convertTouchToNodeSpace(touch);
- if (this._vOrdering == cc.TABLEVIEW_FILL_TOPDOWN) {
+ if (this._vOrdering === cc.TABLEVIEW_FILL_TOPDOWN) {
var cellSize = this._dataSource.cellSizeForTable(this);
point.y -= cellSize.height;
}
@@ -510,17 +505,17 @@ cc.TableView = cc.ScrollView.extend({
this._tableViewDelegate.tableCellTouched(this, cell);
}
}
- this._super(touch, event);
+ cc.ScrollView.prototype.call(this, touch, event);
}
});
/**
* An initialized table view object
*
- * @param dataSource data source;
- * @param size view size
- * @param container parent object for cells
- * @return table view
+ * @param {cc.TableViewDataSource} dataSource data source;
+ * @param {cc.Size} size view size
+ * @param {cc.Node} container parent object for cells
+ * @return {cc.TableView} table view
*/
cc.TableView.create = function (dataSource, size, container) {
var table = new cc.TableView();
From 744e5143e607301a6ce632dd441753a9168fe5c1 Mon Sep 17 00:00:00 2001
From: ShengxiangChen
Date: Thu, 1 Aug 2013 15:30:06 +0800
Subject: [PATCH 016/141] fixed #2459: fix Accelerometer bug on UCWeb version
9.0 and below.
---
.../CCLayer.js | 7 +---
cocos2d/platform/CCAccelerometer.js | 37 ++++++++++---------
2 files changed, 21 insertions(+), 23 deletions(-)
diff --git a/cocos2d/layers_scenes_transitions_nodes/CCLayer.js b/cocos2d/layers_scenes_transitions_nodes/CCLayer.js
index 42e3f5401e..7e8ef55fd3 100644
--- a/cocos2d/layers_scenes_transitions_nodes/CCLayer.js
+++ b/cocos2d/layers_scenes_transitions_nodes/CCLayer.js
@@ -222,15 +222,12 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{
*/
setAccelerometerInterval:function (interval) {
if (this._isAccelerometerEnabled) {
- if (this._running) {
- var director = cc.Director.getInstance();
- director.getAccelerometer().setAccelerometerInterval(interval);
- }
+ cc.Director.getInstance().getAccelerometer().setAccelerometerInterval(interval);
}
},
onAccelerometer:function (accelerationValue) {
- //Layer#onAccelerometer override me
+ cc.Assert(false, "Layer#onAccelerometer override me");
},
/**
diff --git a/cocos2d/platform/CCAccelerometer.js b/cocos2d/platform/CCAccelerometer.js
index 19ac9788a2..322a97cf29 100644
--- a/cocos2d/platform/CCAccelerometer.js
+++ b/cocos2d/platform/CCAccelerometer.js
@@ -47,10 +47,10 @@ cc.Acceleration = function (x, y, z, timestamp) {
* @extends cc.Class
*/
cc.Accelerometer = cc.Class.extend(/** @lends cc.Accelerometer# */{
- setDelegate:function (delegate) {
+ setDelegate: function (delegate) {
cc.AccelerometerDispatcher.getInstance().addDelegate(delegate);
},
- setAccelerometerInterval:function (interval) {
+ setAccelerometerInterval: function (interval) {
cc.AccelerometerDispatcher.getInstance().setAccelerometerInterval(interval);
}
});
@@ -63,31 +63,31 @@ cc.Accelerometer = cc.Class.extend(/** @lends cc.Accelerometer# */{
* @extends cc.Class
*/
cc.AccelerometerDispatcher = cc.Class.extend(/** @lends cc.AccelerometerDispatcher# */{
- _delegate:null,
- _acceleration:null,
- _deviceEvent:null,
- //_orientation:0,
- _interval:0.1,
- _minus:1,
- init:function () {
+ _delegate: null,
+ _acceleration: null,
+ _deviceEvent: null,
+ _interval: 0,
+ _minus: 1,
+ init: function () {
this._acceleration = new cc.Acceleration();
this._deviceEvent = window.DeviceMotionEvent || window.DeviceOrientationEvent;
var ua = navigator.userAgent;
- if(/Android/.test(ua)){
+ if (/Android/.test(ua) || (/Adr/.test(ua) && cc.Browser.type == "ucbrowser")) {
this._minus = -1;
}
+
//TODO fix DeviceMotionEvent bug on QQ Browser version 4.1 and below.
- /*if(ua.indexOf("qqbrowser")){
+ if (cc.Browser.type == "mqqbrowser") {
this._deviceEvent = window.DeviceOrientationEvent;
- }*/
+ }
return true;
},
- getDelegate:function () {
+ getDelegate: function () {
return this._delegate;
},
- addDelegate:function (delegate) {
+ addDelegate: function (delegate) {
this._delegate = delegate;
var acc = this.didAccelerate.bind(this);
@@ -109,18 +109,20 @@ cc.AccelerometerDispatcher = cc.Class.extend(/** @lends cc.AccelerometerDispatch
}
},
- setAccelerometerInterval:function (interval) {
- //not available on browser
+ setAccelerometerInterval: function (interval) {
if (this._interval !== interval) {
this._interval = interval;
}
},
- didAccelerate:function (eventData) {
+ didAccelerate: function (eventData) {
if (!this._delegate) {
return;
}
+ var now = Date.now();
+ if ((now - this._acceleration.timestamp) / 1000 < this._interval) return;
+
if (this._deviceEvent == window.DeviceMotionEvent) {
var acceleration = eventData.accelerationIncludingGravity;
this._acceleration.x = this._minus * acceleration.x * 0.1;
@@ -132,7 +134,6 @@ cc.AccelerometerDispatcher = cc.Class.extend(/** @lends cc.AccelerometerDispatch
this._acceleration.y = -(eventData.beta / 90) * 0.981;
this._acceleration.z = (eventData.alpha / 90) * 0.981;
}
-
this._acceleration.timestamp = Date.now();
var tmp = this._acceleration.x;
From 24d41a4ef37444a78f1ac8e9eb8c9fc6fc089f3b Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Thu, 1 Aug 2013 17:06:45 +0800
Subject: [PATCH 017/141] fixed #2445 refactor code for rendering classes to
optimize performance
---
extensions/GUI/CCScrollView/CCTableView.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/extensions/GUI/CCScrollView/CCTableView.js b/extensions/GUI/CCScrollView/CCTableView.js
index dcb5afbeaf..2948ee6e89 100644
--- a/extensions/GUI/CCScrollView/CCTableView.js
+++ b/extensions/GUI/CCScrollView/CCTableView.js
@@ -505,7 +505,7 @@ cc.TableView = cc.ScrollView.extend({
this._tableViewDelegate.tableCellTouched(this, cell);
}
}
- cc.ScrollView.prototype.call(this, touch, event);
+ cc.ScrollView.prototype.onTouchEnded.call(this, touch, event);
}
});
From e16afc6a36bc7800306029ae5dcbca1679fb5185 Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Thu, 1 Aug 2013 17:36:59 +0800
Subject: [PATCH 018/141] Fixed #2445 correct a mistake in CCScheduler.js when
refactoring code for performance
---
cocos2d/CCScheduler.js | 18 ++++++++----------
1 file changed, 8 insertions(+), 10 deletions(-)
diff --git a/cocos2d/CCScheduler.js b/cocos2d/CCScheduler.js
index da3ebf5812..5fd64c219e 100644
--- a/cocos2d/CCScheduler.js
+++ b/cocos2d/CCScheduler.js
@@ -332,34 +332,33 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{
this._timesExecuted = 0;
} else {
var locTarget = this._target, locSelector = this._selector;
- var locElapsed = this._elapsed;
if (this._runForever && !this._useDelay) {
//standard timer usage
- locElapsed += dt;
+ this._elapsed += dt;
- if (locElapsed >= this._interval) {
+ if (this._elapsed >= this._interval) {
if (locTarget && locSelector)
this._callSelector();
- locElapsed = 0;
+ this._elapsed = 0;
}
} else {
//advanced usage
- locElapsed += dt;
+ this._elapsed += dt;
if (this._useDelay) {
- if (locElapsed >= this._delay) {
+ if (this._elapsed >= this._delay) {
if (locTarget && locSelector)
this._callSelector();
- locElapsed = locElapsed - this._delay;
+ this._elapsed = this._elapsed - this._delay;
this._timesExecuted += 1;
this._useDelay = false;
}
} else {
- if (locElapsed >= this._interval) {
+ if (this._elapsed >= this._interval) {
if (locTarget && locSelector)
this._callSelector();
- locElapsed = 0;
+ this._elapsed = 0;
this._timesExecuted += 1;
}
}
@@ -367,7 +366,6 @@ cc.Timer = cc.Class.extend(/** @lends cc.Timer# */{
if (this._timesExecuted > this._repeat)
cc.Director.getInstance().getScheduler().unscheduleCallbackForTarget(locTarget, locSelector);
}
- this._elapsed = locElapsed;
}
}
});
From 22244e30b9a5d28b867639814be14d2292707d17 Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Fri, 2 Aug 2013 17:28:00 +0800
Subject: [PATCH 019/141] fixed #2468 Fixed a bug of CCBReader that
ControlButton doesn't work when controller is _jsControlled
---
extensions/CCBReader/CCBReader.js | 5 ++++-
extensions/CCEditBox.js | 2 +-
extensions/GUI/CCControlExtension/CCControl.js | 4 ++--
3 files changed, 7 insertions(+), 4 deletions(-)
diff --git a/extensions/CCBReader/CCBReader.js b/extensions/CCBReader/CCBReader.js
index 219a091310..a45b1f3f00 100644
--- a/extensions/CCBReader/CCBReader.js
+++ b/extensions/CCBReader/CCBReader.js
@@ -974,7 +974,10 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) {
callbackName = documentCallbackNames[j];
callbackNode = documentCallbackNodes[j];
- callbackNode.setCallback(controller[callbackName], controller);
+ if(callbackNode instanceof cc.ControlButton)
+ callbackNode.addTargetWithActionForControlEvents(controller, controller[callbackName], 255); //register all type of events
+ else
+ callbackNode.setCallback(controller[callbackName], controller);
}
// Variables
diff --git a/extensions/CCEditBox.js b/extensions/CCEditBox.js
index e38dac23e2..73b94bf9a5 100644
--- a/extensions/CCEditBox.js
+++ b/extensions/CCEditBox.js
@@ -417,7 +417,7 @@ cc.EditBox = cc.ControlButton.extend({
this.setZoomOnTouchDown(false);
this.setPreferredSize(size);
this.setPosition(cc.p(0, 0));
- this.addTargetWithActionForControlEvent(this, this.touchDownAction, cc.CONTROL_EVENT_TOUCH_UP_INSIDE);
+ this._addTargetWithActionForControlEvent(this, this.touchDownAction, cc.CONTROL_EVENT_TOUCH_UP_INSIDE);
return true;
}
return false;
diff --git a/extensions/GUI/CCControlExtension/CCControl.js b/extensions/GUI/CCControlExtension/CCControl.js
index 3acede8898..905942a8b8 100644
--- a/extensions/GUI/CCControlExtension/CCControl.js
+++ b/extensions/GUI/CCControlExtension/CCControl.js
@@ -217,7 +217,7 @@ cc.Control = cc.LayerRGBA.extend({
for (var i = 0; i < cc.CONTROL_EVENT_TOTAL_NUMBER; i++) {
// If the given controlEvents bitmask contains the curent event
if ((controlEvents & (1 << i))) {
- this.addTargetWithActionForControlEvent(target, action, 1 << i);
+ this._addTargetWithActionForControlEvent(target, action, 1 << i);
}
}
},
@@ -321,7 +321,7 @@ cc.Control = cc.LayerRGBA.extend({
* @param controlEvent A control event for which the action message is sent.
* See "CCControlEvent" for constants.
*/
- addTargetWithActionForControlEvent:function (target, action, controlEvent) {
+ _addTargetWithActionForControlEvent:function (target, action, controlEvent) {
// Create the invocation object
var invocation = new cc.Invocation(target, action, controlEvent);
From f59d9f0e5cef7ed82bb426c74b09ea79d426e293 Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Mon, 5 Aug 2013 11:24:34 +0800
Subject: [PATCH 020/141] fixed #2468 CCBReader has supported loading
ControlEvents of ControlButton on _jsControlled Mode
---
extensions/CCBReader/CCBAnimationManager.js | 10 ++++++++++
extensions/CCBReader/CCBReader.js | 16 ++++++++++++----
extensions/CCBReader/CCNodeLoader.js | 2 ++
3 files changed, 24 insertions(+), 4 deletions(-)
diff --git a/extensions/CCBReader/CCBAnimationManager.js b/extensions/CCBReader/CCBAnimationManager.js
index 9174416846..3005295504 100644
--- a/extensions/CCBReader/CCBAnimationManager.js
+++ b/extensions/CCBReader/CCBAnimationManager.js
@@ -45,6 +45,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
_documentOutletNodes:null,
_documentCallbackNames:null,
_documentCallbackNodes:null,
+ _documentCallbackControlEvents:null,
_documentControllerName:"",
_lastCompletedSequenceName:"",
_keyframeCallbacks:null,
@@ -68,6 +69,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
this._documentOutletNodes = [];
this._documentCallbackNames = [];
this._documentCallbackNodes = [];
+ this._documentCallbackControlEvents = [];
this._keyframeCallbacks = [];
this._keyframeCallFuncs = {};
@@ -112,6 +114,10 @@ cc.BuilderAnimationManager = cc.Class.extend({
this._documentCallbackNames.push(name);
},
+ addDocumentCallbackControlEvents:function(controlEvents){
+ this._documentCallbackControlEvents.push(controlEvents);
+ },
+
addDocumentOutletNode:function(node){
this._documentOutletNodes.push(node);
},
@@ -136,6 +142,10 @@ cc.BuilderAnimationManager = cc.Class.extend({
return this._documentCallbackNodes;
},
+ getDocumentCallbackControlEvents:function(){
+ return this._documentCallbackControlEvents;
+ },
+
getDocumentOutletNames:function(){
return this._documentOutletNames;
},
diff --git a/extensions/CCBReader/CCBReader.js b/extensions/CCBReader/CCBReader.js
index a45b1f3f00..6d791ed86e 100644
--- a/extensions/CCBReader/CCBReader.js
+++ b/extensions/CCBReader/CCBReader.js
@@ -486,6 +486,10 @@ cc.BuilderReader = cc.Class.extend({
this._actionManager.addDocumentCallbackNode(node);
},
+ addDocumentCallbackControlEvents:function(controlEvents){
+ this._actionManager.addDocumentCallbackControlEvents(controlEvents);
+ },
+
readFileWithCleanUp:function (cleanUp) {
if (!this._readHeader())
return null;
@@ -922,7 +926,7 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) {
var node = reader.readNodeGraphFromFile(ccbFilePath, owner, parentSize);
var i;
- var callbackName, callbackNode, outletName, outletNode;
+ var callbackName, callbackNode, callbackControlEvents, outletName, outletNode;
// Assign owner callbacks & member variables
if (owner) {
// Callbacks
@@ -931,7 +935,10 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) {
for (i = 0; i < ownerCallbackNames.length; i++) {
callbackName = ownerCallbackNames[i];
callbackNode = ownerCallbackNodes[i];
- callbackNode.setCallback(owner[callbackName], owner);
+ if(callbackNode instanceof cc.ControlButton)
+ callbackNode.addTargetWithActionForControlEvents(owner, owner[callbackName], 255); //register all type of events
+ else
+ callbackNode.setCallback(owner[callbackName], owner);
}
// Variables
@@ -970,12 +977,13 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) {
// Callbacks
var documentCallbackNames = animationManager.getDocumentCallbackNames();
var documentCallbackNodes = animationManager.getDocumentCallbackNodes();
+ var documentCallbackControlEvents = animationManager.getDocumentCallbackControlEvents();
for (j = 0; j < documentCallbackNames.length; j++) {
callbackName = documentCallbackNames[j];
callbackNode = documentCallbackNodes[j];
-
+ callbackControlEvents = documentCallbackControlEvents[j];
if(callbackNode instanceof cc.ControlButton)
- callbackNode.addTargetWithActionForControlEvents(controller, controller[callbackName], 255); //register all type of events
+ callbackNode.addTargetWithActionForControlEvents(controller, controller[callbackName], callbackControlEvents); //register all type of events
else
callbackNode.setCallback(controller[callbackName], controller);
}
diff --git a/extensions/CCBReader/CCNodeLoader.js b/extensions/CCBReader/CCNodeLoader.js
index 4f42cc1127..b986d6ea45 100644
--- a/extensions/CCBReader/CCNodeLoader.js
+++ b/extensions/CCBReader/CCNodeLoader.js
@@ -662,6 +662,7 @@ cc.NodeLoader = cc.Class.extend({
if(selectorTarget == CCB_TARGETTYPE_DOCUMENTROOT){
ccbReader.addDocumentCallbackNode(node);
ccbReader.addDocumentCallbackName(selectorName);
+ ccbReader.addDocumentCallbackControlEvents(0);
} else {
ccbReader.addOwnerCallbackNode(node);
ccbReader.addOwnerCallbackName(selectorName);
@@ -714,6 +715,7 @@ cc.NodeLoader = cc.Class.extend({
if(selectorTarget == CCB_TARGETTYPE_DOCUMENTROOT){
ccbReader.addDocumentCallbackNode(node);
ccbReader.addDocumentCallbackName(selectorName);
+ ccbReader.addDocumentCallbackControlEvents(controlEvents);
} else {
ccbReader.addOwnerCallbackNode(node);
ccbReader.addOwnerCallbackName(selectorName);
From 8727c49c107edcf8a492a249afd05ff0aa00825d Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Mon, 5 Aug 2013 11:45:09 +0800
Subject: [PATCH 021/141] Fixed #2445 Fixed bug for sortAllChildren ,that
tempChild is a changing var
---
cocos2d/base_nodes/CCNode.js | 1 +
1 file changed, 1 insertion(+)
diff --git a/cocos2d/base_nodes/CCNode.js b/cocos2d/base_nodes/CCNode.js
index f620db75ac..d148aae0ee 100644
--- a/cocos2d/base_nodes/CCNode.js
+++ b/cocos2d/base_nodes/CCNode.js
@@ -1193,6 +1193,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
//continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
+ tempChild = _children[j];
_children[j + 1] = tempChild;
j = j - 1;
}
From 9669d08a6d968e2868519b3cfef3ab42957afc19 Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Mon, 5 Aug 2013 11:52:05 +0800
Subject: [PATCH 022/141] Fixed #2445 Fixed bug for sortAllChildren ,that
tempChild is a changing Var.
---
cocos2d/base_nodes/CCNode.js | 1 +
1 file changed, 1 insertion(+)
diff --git a/cocos2d/base_nodes/CCNode.js b/cocos2d/base_nodes/CCNode.js
index d148aae0ee..f57ebb7ca6 100644
--- a/cocos2d/base_nodes/CCNode.js
+++ b/cocos2d/base_nodes/CCNode.js
@@ -3036,6 +3036,7 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
//continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
+ tempChild = _children[j];
_children[j + 1] = tempChild;
j = j - 1;
}
From c27186e8f064381dba385a646192eb64935b3ee9 Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Mon, 5 Aug 2013 15:00:28 +0800
Subject: [PATCH 023/141] fixed #1056 The bug of cc.ProgressTimer has fixed
that Midpoint is wrong on Canvas Mode.
---
cocos2d/misc_nodes/CCProgressTimer.js | 11 +++++------
1 file changed, 5 insertions(+), 6 deletions(-)
diff --git a/cocos2d/misc_nodes/CCProgressTimer.js b/cocos2d/misc_nodes/CCProgressTimer.js
index a27babe44f..42b181adf1 100644
--- a/cocos2d/misc_nodes/CCProgressTimer.js
+++ b/cocos2d/misc_nodes/CCProgressTimer.js
@@ -165,10 +165,10 @@ cc.ProgressTimerCanvas = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerCanvas# *
},
/// ---- common properties end ----
- _origin:cc.PointZero(),
- _originSize:cc.SizeZero(),
- _drawSize:cc.SizeZero(),
- _drawPosition:cc.PointZero(),
+ _origin:null,
+ _originSize:null,
+ _drawSize:null,
+ _drawPosition:null,
_startAngle:270,
_endAngle:270,
_radius:0,
@@ -364,8 +364,7 @@ cc.ProgressTimerCanvas = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerCanvas# *
var textureSize = this._sprite.getTextureRect().size;
var locMidPoint = this._midPoint;
if (this._type == cc.PROGRESS_TIMER_TYPE_RADIAL) {
-
- this._origin = cc.p(-(size.width * (0.5 - locMidPoint.x)), -(size.height * (0.5 - locMidPoint.y)));
+ this._origin = cc.p(-(size.width * (0.5 - locMidPoint.x)), -(size.height * (locMidPoint.y - 0.5)));
this._radius = Math.round(Math.sqrt(size.width * size.width + size.height * size.height));
if (this._reverseDirection) {
this._startAngle = 270 - 3.6 * this._percentage;
From fd27bb73f0537b59fe321cfcce2d298067aeb75f Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Mon, 5 Aug 2013 15:48:13 +0800
Subject: [PATCH 024/141] fixed #2468 Corrected a mistake of cc.NodeLoader
---
extensions/CCBReader/CCNodeLoader.js | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/extensions/CCBReader/CCNodeLoader.js b/extensions/CCBReader/CCNodeLoader.js
index b986d6ea45..4505a08bd7 100644
--- a/extensions/CCBReader/CCNodeLoader.js
+++ b/extensions/CCBReader/CCNodeLoader.js
@@ -491,9 +491,10 @@ cc.NodeLoader = cc.Class.extend({
var texture = cc.TextureCache.getInstance().addImage(spriteFile);
var bounds;
if(texture instanceof cc.Texture2D){
- bounds = cc.RectMake(0, 0, texture.getContentSize().width, texture.getContentSize().height);
+ var locContentSize = texture.getContentSize();
+ bounds = cc.RectMake(0, 0, locContentSize.width, locContentSize.height);
}else{
- bounds = cc.RECT_PIXELS_TO_POINTS(bounds);
+ bounds = cc.RECT_PIXELS_TO_POINTS(cc.RectMake(0, 0, texture.width, texture.height));
}
spriteFrame = cc.SpriteFrame.createWithTexture(texture, bounds);
} else {
From eb7f801842bc30e75b28f66e1a9756bc7ad56079 Mon Sep 17 00:00:00 2001
From: NeroChan
Date: Wed, 7 Aug 2013 15:34:59 +0800
Subject: [PATCH 025/141] fixed #2497 : setSearchPaths Bug
---
cocos2d/platform/CCFileUtils.js | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/cocos2d/platform/CCFileUtils.js b/cocos2d/platform/CCFileUtils.js
index 4fdf1b9f3a..a6f5ee816d 100644
--- a/cocos2d/platform/CCFileUtils.js
+++ b/cocos2d/platform/CCFileUtils.js
@@ -158,6 +158,7 @@ cc.FileUtils = cc.Class.extend({
* @warning If you get the file data succeed,you must delete it after used.
*/
getByteArrayFromFile:function (fileName, mode, size) {
+ fileName = this.fullPathForFilename(fileName);
if (this._fileDataCache.hasOwnProperty(fileName))
return this._fileDataCache[fileName];
return this._loadBinaryFileData(fileName);
@@ -177,7 +178,7 @@ cc.FileUtils = cc.Class.extend({
},
preloadBinaryFileData:function (fileUrl) {
- fileUrl = this.fullPathFromRelativePath(fileUrl);
+ fileUrl = this.fullPathForFilename(fileUrl);
var selfPointer = this;
var xhr = this._getXMLHttpRequest();
@@ -254,7 +255,7 @@ cc.FileUtils = cc.Class.extend({
},
preloadTextFileData:function (fileUrl) {
- fileUrl = this.fullPathFromRelativePath(fileUrl);
+ fileUrl = this.fullPathForFilename(fileUrl);
var selfPointer = this;
var xhr = this._getXMLHttpRequest();
From 64740a06f6be135c94269744daf27dd67628f2cc Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Wed, 7 Aug 2013 16:23:37 +0800
Subject: [PATCH 026/141] Fixed #2481 Re-write Canvas Mode of RenderTexture to
adapt WebGL interface
---
cocos2d/misc_nodes/CCRenderTexture.js | 578 ++++++++++++------
cocos2d/particle_nodes/CCParticleSystem.js | 2 -
cocos2d/platform/CCApplication.js | 3 +-
cocos2d/sprite_nodes/CCSprite.js | 25 +-
cocos2d/sprite_nodes/CCSpriteBatchNode.js | 97 +--
cocos2d/tileMap_parallax_nodes/CCTMXLayer.js | 89 ++-
.../GUI/CCControlExtension/CCControl.js | 2 +-
.../GUI/CCControlExtension/CCControlButton.js | 2 +-
8 files changed, 538 insertions(+), 260 deletions(-)
diff --git a/cocos2d/misc_nodes/CCRenderTexture.js b/cocos2d/misc_nodes/CCRenderTexture.js
index 4d3fb87708..99df12b674 100644
--- a/cocos2d/misc_nodes/CCRenderTexture.js
+++ b/cocos2d/misc_nodes/CCRenderTexture.js
@@ -69,23 +69,18 @@ cc.NextPOT = function (x) {
* @class
* @extends cc.Node
*/
-cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
+cc.RenderTextureCanvas = cc.Node.extend(/** @lends cc.RenderTextureCanvas# */{
/**
* the offscreen canvas for rendering and storing the texture
* @type HTMLCanvasElement
*/
- canvas:null,
+ _cacheCanvas:null,
/**
* stores a reference to the canvas context object
- * @type CanvasContext
+ * @type CanvasRenderingContext2D
*/
- context:null,
- _fBO:0,
- _depthRenderBuffer:0,
- _oldFBO:0,
- _texture:null,
- _textureCopy:null,
- _uITextureImage:null,
+ _cacheContext:null,
+
_pixelFormat:cc.TEXTURE_2D_PIXEL_FORMAT_RGBA8888,
_sprite:null,
@@ -96,35 +91,25 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
_clearStencil:0,
_autoDraw:false,
+ _clearColorStr:null,
+
/**
* Constructor
*/
ctor:function () {
cc.Node.prototype.ctor.call(this);
+ this._clearColor = cc.c4f(1,1,1,1);
+ this._clearColorStr = "rgba(255,255,255,1)";
- if (cc.renderContextType === cc.CANVAS) {
- this.canvas = document.createElement('canvas');
- this.context = this.canvas.getContext('2d');
- this.setAnchorPoint(cc.p(0, 0));
- } else {
- this._clearColor = cc.c4f(0, 0, 0, 0);
- }
+ this._cacheCanvas = document.createElement('canvas');
+ this._cacheContext = this._cacheCanvas.getContext('2d');
+ this.setAnchorPoint(cc.p(0, 0));
},
onExit:function () {
cc.Node.prototype.onExit.call(this);
- if (cc.renderContextType === cc.WEBGL) {
- this._sprite = null;
- this._textureCopy = null;
-
- var gl = cc.renderContext;
- gl.deleteFramebuffer(this._fBO);
- if (this._depthRenderBuffer)
- gl.deleteRenderbuffer(this._depthRenderBuffer);
- this._uITextureImage = null;
- if(this._texture)
- this._texture.releaseTexture();
- }
+ this._cacheContext = null;
+ this._cacheCanvas = null;
},
/**
@@ -143,27 +128,314 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
},
/**
- * @return {HTMLCanvasElement}
+ * @param {Number} width
+ * @param {Number} height
+ * @param {cc.IMAGE_FORMAT_JPEG|cc.IMAGE_FORMAT_PNG|cc.IMAGE_FORMAT_RAWDATA} format
+ * @param {Number} depthStencilFormat
+ * @return {Boolean}
+ */
+ initWithWidthAndHeight:function (width, height, format, depthStencilFormat) {
+ this._cacheCanvas.width = width || 10;
+ this._cacheCanvas.height = height || 10;
+ this._cacheContext.translate(0, this._cacheCanvas.height);
+ this._sprite = cc.Sprite.createWithTexture(this._cacheCanvas);
+ return true;
+ },
+
+ /**
+ * starts grabbing
+ */
+ begin:function () {
+ cc.renderContext = this._cacheContext;
+
+ /*// Save the current matrix
+ cc.kmGLMatrixMode(cc.KM_GL_PROJECTION);
+ cc.kmGLPushMatrix();
+ cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW);
+ cc.kmGLPushMatrix();*/
+ },
+
+ /**
+ * starts rendering to the texture while clearing the texture first.
+ * This is more efficient then calling -clear first and then -begin
+ * @param {Number} r red 0-1
+ * @param {Number} g green 0-1
+ * @param {Number} b blue 0-1
+ * @param {Number} a alpha 0-1 0 is transparent
+ * @param {Number} depthValue
+ * @param {Number} stencilValue
+ */
+ beginWithClear:function (r, g, b, a, depthValue, stencilValue) {
+ 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));
+ },
+
+ _beginWithClear:function (r, g, b, a, depthValue, stencilValue, flags) {
+ this.begin();
+
+ r = r || 0;
+ g = g || 0;
+ b = b || 0;
+ a = a || 1;
+
+ var context = cc.renderContext;
+ var locCanvas = this._cacheCanvas;
+ context.save();
+ context.fillStyle = "rgba(" + (0 | (r * 255)) + "," + (0 | (g * 255)) + "," + (0 | (b * 255)) + "," + a + ")";
+ context.clearRect(0,0,locCanvas.width, -locCanvas.height);
+ context.fillRect(0,0,locCanvas.width, -locCanvas.height);
+ context.restore();
+ },
+
+ /**
+ * ends grabbing
*/
- getCanvas:function () {
- return this.canvas;
+ end:function () {
+ cc.renderContext = cc.mainRenderContextBackup;
+
+ //TODO
+ /*//restore viewport
+ director.setViewport();
+ cc.kmGLMatrixMode(cc.KM_GL_PROJECTION);
+ cc.kmGLPopMatrix();
+ cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW);
+ cc.kmGLPopMatrix();*/
+ },
+
+ /**
+ * clears the texture with a color
+ * @param {Number|cc.Rect} r red 0-1
+ * @param {Number} g green 0-1
+ * @param {Number} b blue 0-1
+ * @param {Number} a alpha 0-1
+ */
+ clear:function (r, g, b, a) {
+ this.beginWithClear(r, g, b, a);
+ this.end();
},
/**
- * @param {cc.Size} size
+ * clears the texture with a specified depth value
+ * @param {Number} depthValue
*/
- setContentSize:function (size) {
- if (!size)
+ clearDepth:function (depthValue) {
+ cc.log("clearDepth isn't supported on Cocos2d-Html5");
+ },
+
+ /**
+ * clears the texture with a specified stencil value
+ * @param {Number} stencilValue
+ */
+ clearStencil:function (stencilValue) {
+ cc.log("clearDepth isn't supported on Cocos2d-Html5");
+ },
+
+ visit:function (ctx) {
+ // override visit.
+ // Don't call visit on its children
+ if (!this._visible)
return;
- //if (!cc.Size.CCSizeEqualToSize(size, this._contentSize)) {
- this._super(size);
- if(cc.renderContextType === cc.CANVAS){
- this.canvas.width = size.width * 1.5;
- this.canvas.height = size.height * 1.5;
- this.context.translate(0, this.canvas.height);
+ ctx = ctx || cc.renderContext;
+ ctx.save();
+
+ this.draw(ctx); // update children of RenderTexture before
+ this.transform(ctx);
+ this._sprite.visit(); // draw the RenderTexture
+
+ ctx.restore();
+
+ this._orderOfArrival = 0;
+ },
+
+ draw:function (ctx) {
+ ctx = ctx || cc.renderContext;
+ if (this._autoDraw) {
+ this.begin();
+
+ if (this._clearFlags) {
+ var locCanvas = this._cacheCanvas;
+ ctx.save();
+ ctx.fillStyle = this._clearColorStr;
+ ctx.clearRect(0,0,locCanvas.width, -locCanvas.height);
+ ctx.fillRect(0,0,locCanvas.width, -locCanvas.height);
+ ctx.restore();
+ }
+
+ //! make sure all children are drawn
+ this.sortAllChildren();
+ var locChildren = this._children;
+ for (var i = 0; i < locChildren.length; i++) {
+ var getChild = locChildren[i];
+ if (getChild != this._sprite)
+ getChild.visit();
+ }
+
+ this.end();
}
- //}
+ },
+
+ /**
+ * creates a new CCImage from with the texture's data. Caller is responsible for releasing it by calling delete.
+ * @return {cc.Image}
+ */
+ newCCImage:function (flipImage) {
+ cc.log("saveToFile isn't supported on Cocos2d-Html5");
+ return null;
+ },
+
+ _memcpy:function (destArr, destIndex, srcArr, srcIndex, size) {
+ for (var i = 0; i < size; i++) {
+ destArr[destIndex + i] = srcArr[srcIndex + i];
+ }
+ },
+
+ /**
+ * saves the texture into a file using JPEG format. The file will be saved in the Documents folder.
+ * Returns YES if the operation is successful.
+ * (doesn't support in HTML5)
+ * @param {Number} filePath
+ * @param {Number} format
+ */
+ saveToFile:function (filePath, format) {
+ cc.log("saveToFile isn't supported on Cocos2d-Html5");
+ },
+
+ /**
+ * Listen "come to background" message, and save render texture. It only has effect on Android.
+ * @param {cc.Class} obj
+ */
+ listenToBackground:function (obj) {
+ cc.log("listenToBackground isn't supported on Cocos2d-Html5");
+ },
+
+ /**
+ * Listen "come to foreground" message and restore the frame buffer object. It only has effect on Android.
+ * @param {cc.Class} obj
+ */
+ listenToForeground:function (obj) {
+ cc.log("listenToForeground isn't supported on Cocos2d-Html5");
+ },
+
+ /**
+ * 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 () {
+ return this._clearFlags;
+ },
+
+ setClearFlags:function (clearFlags) {
+ this._clearFlags = clearFlags;
+ },
+
+ /**
+ * Clear color value. Valid only when "autoDraw" is true.
+ * @return {cc.Color4F}
+ */
+ getClearColor:function () {
+ return this._clearColor;
+ },
+
+ setClearColor:function (clearColor) {
+ this._clearColor = cc.c4f(clearColor.r, clearColor.g, clearColor.b, clearColor.a);
+ this._clearColorStr = "rgba(" + (0 | (clearColor.r * 255)) + "," + (0 | (clearColor.g * 255)) + "," + (0 | (clearColor.b * 255)) + "," + clearColor.a + ")";
+ },
+
+ /**
+ * Value for clearDepth. Valid only when autoDraw is true.
+ * @return {Number}
+ */
+ getClearDepth:function () {
+ return this._clearDepth;
+ },
+
+ setClearDepth:function (clearDepth) {
+ this._clearDepth = clearDepth;
+ },
+
+ /**
+ * Value for clear Stencil. Valid only when autoDraw is true
+ * @return {Number}
+ */
+ getClearStencil:function () {
+ return this._clearStencil;
+ },
+
+ setClearStencil:function (clearStencil) {
+ this._clearStencil = clearStencil;
+ },
+
+ /**
+ * When enabled, it will render its children into the texture automatically. Disabled by default for compatiblity reasons.
+ * Will be enabled in the future.
+ * @return {Boolean}
+ */
+ isAutoDraw:function () {
+ return this._autoDraw;
+ },
+
+ setAutoDraw:function (autoDraw) {
+ this._autoDraw = autoDraw;
+ }
+});
+
+cc.RenderTextureWebGL = cc.Node.extend(/** @lends cc.RenderTextureWebGL# */{
+ _fBO:0,
+ _depthRenderBuffer:0,
+ _oldFBO:0,
+ _texture:null,
+ _textureCopy:null,
+ _uITextureImage:null,
+ _pixelFormat:cc.TEXTURE_2D_PIXEL_FORMAT_RGBA8888,
+ _sprite:null,
+
+ //code for "auto" update
+ _clearFlags:0,
+ _clearColor:null,
+ _clearDepth:0,
+ _clearStencil:0,
+ _autoDraw:false,
+
+ /**
+ * Constructor
+ */
+ ctor:function () {
+ cc.Node.prototype.ctor.call(this);
+ this._clearColor = cc.c4f(0, 0, 0, 0);
+ },
+
+ onExit: function () {
+ cc.Node.prototype.onExit.call(this);
+
+ this._sprite = null;
+ this._textureCopy = null;
+
+ var gl = cc.renderContext;
+ gl.deleteFramebuffer(this._fBO);
+ if (this._depthRenderBuffer)
+ gl.deleteRenderbuffer(this._depthRenderBuffer);
+ this._uITextureImage = null;
+ if (this._texture)
+ this._texture.releaseTexture();
+ },
+
+ /**
+ * The sprite
+ * @return {cc.Sprite}
+ */
+ getSprite:function () {
+ return this._sprite;
+ },
+
+ /**
+ * @param {cc.Sprite} sprite
+ */
+ setSprite:function (sprite) {
+ this._sprite = sprite;
},
/**
@@ -174,108 +446,95 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @return {Boolean}
*/
initWithWidthAndHeight:function (width, height, format, depthStencilFormat) {
- if (cc.renderContextType === cc.CANVAS) {
- this.canvas.width = width || 10;
- this.canvas.height = height || 10;
+ cc.Assert(format != cc.TEXTURE_2D_PIXEL_FORMAT_A8, "only RGB and RGBA formats are valid for a render texture");
- this.context.translate(0, this.canvas.height);
- this._sprite = cc.Sprite.createWithTexture(this.canvas);
-
- return true;
- } else {
- cc.Assert(format != cc.TEXTURE_2D_PIXEL_FORMAT_A8, "only RGB and RGBA formats are valid for a render texture");
-
- var gl = cc.renderContext;
+ var gl = cc.renderContext;
- width = 0 | (width * cc.CONTENT_SCALE_FACTOR());
- height = 0 | (height * cc.CONTENT_SCALE_FACTOR());
+ width = 0 | (width * cc.CONTENT_SCALE_FACTOR());
+ height = 0 | (height * cc.CONTENT_SCALE_FACTOR());
- this._oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING);
+ this._oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING);
- // textures must be power of two squared
- var powW , powH;
+ // textures must be power of two squared
+ var powW , powH;
- if (cc.Configuration.getInstance().supportsNPOT()) {
- powW = width;
- powH = height;
- } else {
- powW = cc.NextPOT(width);
- powH = cc.NextPOT(height);
- }
+ if (cc.Configuration.getInstance().supportsNPOT()) {
+ powW = width;
+ powH = height;
+ } else {
+ powW = cc.NextPOT(width);
+ powH = cc.NextPOT(height);
+ }
- //void *data = malloc(powW * powH * 4);
- var dataLen = powW * powH * 4;
- var data = new Uint8Array(dataLen);
- //memset(data, 0, (int)(powW * powH * 4));
- for (var i = 0; i < powW * powH * 4; i++)
- data[i] = 0;
+ //void *data = malloc(powW * powH * 4);
+ var dataLen = powW * powH * 4;
+ var data = new Uint8Array(dataLen);
+ //memset(data, 0, (int)(powW * powH * 4));
+ for (var i = 0; i < powW * powH * 4; i++)
+ data[i] = 0;
- this._pixelFormat = format;
+ this._pixelFormat = format;
- this._texture = new cc.Texture2D();
- if (!this._texture)
- return false;
+ this._texture = new cc.Texture2D();
+ if (!this._texture)
+ return false;
- this._texture.initWithData(data, this._pixelFormat, powW, powH, cc.size(width, height));
- //free( data );
+ this._texture.initWithData(data, this._pixelFormat, powW, powH, cc.size(width, height));
+ //free( data );
- var oldRBO = gl.getParameter(gl.RENDERBUFFER_BINDING);
+ var oldRBO = gl.getParameter(gl.RENDERBUFFER_BINDING);
- if (cc.Configuration.getInstance().checkForGLExtension("GL_QCOM")) {
- this._textureCopy = new cc.Texture2D();
- if (!this._textureCopy) {
- return false;
- }
- this._textureCopy.initWithData(data, this._pixelFormat, powW, powH, cc.size(width, height));
+ if (cc.Configuration.getInstance().checkForGLExtension("GL_QCOM")) {
+ this._textureCopy = new cc.Texture2D();
+ if (!this._textureCopy) {
+ return false;
}
+ this._textureCopy.initWithData(data, this._pixelFormat, powW, powH, cc.size(width, height));
+ }
- // generate FBO
- this._fBO = gl.createFramebuffer();
- gl.bindFramebuffer(gl.FRAMEBUFFER, this._fBO);
+ // generate FBO
+ this._fBO = gl.createFramebuffer();
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this._fBO);
- // associate texture with FBO
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this._texture._webTextureObj, 0);
+ // associate texture with FBO
+ gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, this._texture._webTextureObj, 0);
- if (depthStencilFormat != 0) {
- //create and attach depth buffer
- this._depthRenderBuffer = gl.createRenderbuffer();
- gl.bindRenderbuffer(gl.RENDERBUFFER, this._depthRenderBuffer);
- gl.renderbufferStorage(gl.RENDERBUFFER, depthStencilFormat, powW, powH);
- gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer);
+ if (depthStencilFormat != 0) {
+ //create and attach depth buffer
+ this._depthRenderBuffer = gl.createRenderbuffer();
+ gl.bindRenderbuffer(gl.RENDERBUFFER, this._depthRenderBuffer);
+ gl.renderbufferStorage(gl.RENDERBUFFER, depthStencilFormat, powW, powH);
+ gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer);
- // if depth format is the one with stencil part, bind same render buffer as stencil attachment
- //if (depthStencilFormat == gl.DEPTH24_STENCIL8)
- // gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer);
- }
+ // if depth format is the one with stencil part, bind same render buffer as stencil attachment
+ //if (depthStencilFormat == gl.DEPTH24_STENCIL8)
+ // gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer);
+ }
- // check if it worked (probably worth doing :) )
- cc.Assert(gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE, "Could not attach texture to framebuffer");
+ // check if it worked (probably worth doing :) )
+ cc.Assert(gl.checkFramebufferStatus(gl.FRAMEBUFFER) === gl.FRAMEBUFFER_COMPLETE, "Could not attach texture to framebuffer");
- this._texture.setAliasTexParameters();
+ this._texture.setAliasTexParameters();
- this._sprite = cc.Sprite.createWithTexture(this._texture);
- this._sprite.setScaleY(-1);
- this._sprite.setBlendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
+ this._sprite = cc.Sprite.createWithTexture(this._texture);
+ this._sprite.setScaleY(-1);
+ this._sprite.setBlendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
- gl.bindRenderbuffer(gl.RENDERBUFFER, oldRBO);
- gl.bindFramebuffer(gl.FRAMEBUFFER, this._oldFBO);
+ gl.bindRenderbuffer(gl.RENDERBUFFER, oldRBO);
+ gl.bindFramebuffer(gl.FRAMEBUFFER, this._oldFBO);
- // Diabled by default.
- this._autoDraw = false;
+ // Diabled by default.
+ this._autoDraw = false;
- // add sprite for backward compatibility
- this.addChild(this._sprite);
- return true;
- }
+ // add sprite for backward compatibility
+ this.addChild(this._sprite);
+ return true;
},
/**
* starts grabbing
*/
begin:function () {
- if (cc.renderContextType === cc.CANVAS)
- return;
-
// Save the current matrix
cc.kmGLMatrixMode(cc.KM_GL_PROJECTION);
cc.kmGLPushMatrix();
@@ -338,9 +597,6 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
},
_beginWithClear:function (r, g, b, a, depthValue, stencilValue, flags) {
- if (cc.renderContextType === cc.CANVAS)
- return;
-
this.begin();
var gl = cc.renderContext;
@@ -382,9 +638,6 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* ends grabbing
*/
end:function () {
- if (cc.renderContextType === cc.CANVAS)
- return;
-
var gl = cc.renderContext;
var director = cc.Director.getInstance();
gl.bindFramebuffer(gl.FRAMEBUFFER, this._oldFBO);
@@ -398,15 +651,15 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
/* var size = director.getWinSizeInPixels();
- // restore viewport
- gl.viewport(0, 0, size.width * cc.CONTENT_SCALE_FACTOR(), size.height * cc.CONTENT_SCALE_FACTOR());
+ // restore viewport
+ gl.viewport(0, 0, size.width * cc.CONTENT_SCALE_FACTOR(), size.height * cc.CONTENT_SCALE_FACTOR());
- // special viewport for 3d projection + retina display
- if (director.getProjection() == cc.DIRECTOR_PROJECTION_3D && cc.CONTENT_SCALE_FACTOR() != 1) {
- gl.viewport((-size.width / 2), (-size.height / 2), (size.width * cc.CONTENT_SCALE_FACTOR()), (size.height * cc.CONTENT_SCALE_FACTOR()));
- }
+ // special viewport for 3d projection + retina display
+ if (director.getProjection() == cc.DIRECTOR_PROJECTION_3D && cc.CONTENT_SCALE_FACTOR() != 1) {
+ gl.viewport((-size.width / 2), (-size.height / 2), (size.width * cc.CONTENT_SCALE_FACTOR()), (size.height * cc.CONTENT_SCALE_FACTOR()));
+ }
- director.setProjection(director.getProjection());*/
+ director.setProjection(director.getProjection());*/
},
/**
@@ -417,16 +670,8 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @param {Number} a alpha 0-1
*/
clear:function (r, g, b, a) {
- if (cc.renderContextType === cc.CANVAS) {
- var rect = r;
- if (rect)
- this.context.clearRect(rect.x, rect.y, rect.width, rect.height);
- else
- this.context.clearRect(0, 0, this.canvas.width, -this.canvas.height);
- } else {
- this.beginWithClear(r, g, b, a);
- this.end();
- }
+ this.beginWithClear(r, g, b, a);
+ this.end();
},
/**
@@ -434,9 +679,6 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @param {Number} depthValue
*/
clearDepth:function (depthValue) {
- if (cc.renderContextType === cc.CANVAS)
- return;
-
this.begin();
var gl = cc.renderContext;
@@ -456,9 +698,6 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @param {Number} stencilValue
*/
clearStencil:function (stencilValue) {
- if (cc.renderContextType === cc.CANVAS)
- return;
-
var gl = cc.renderContext;
// save old stencil value
var stencilClearValue = gl.getParameter(gl.STENCIL_CLEAR_VALUE);
@@ -471,10 +710,6 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
},
visit:function (ctx) {
- if (cc.renderContextType === cc.CANVAS) {
- this._super(ctx);
- return;
- }
// override visit.
// Don't call visit on its children
if (!this._visible)
@@ -482,8 +717,9 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
cc.kmGLPushMatrix();
- if (this._grid && this._grid.isActive()) {
- this._grid.beforeDraw();
+ var locGrid = this._grid;
+ if (locGrid && locGrid.isActive()) {
+ locGrid.beforeDraw();
this.transformAncestors();
}
@@ -491,8 +727,8 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
this._sprite.visit();
this.draw(ctx);
- if (this._grid && this._grid.isActive())
- this._grid.afterDraw(this);
+ if (locGrid && locGrid.isActive())
+ locGrid.afterDraw(this);
cc.kmGLPopMatrix();
@@ -500,55 +736,51 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
},
draw:function (ctx) {
- if (cc.renderContextType === cc.CANVAS) {
- this._super(ctx);
- return;
- }
-
var gl = cc.renderContext;
if (this._autoDraw) {
this.begin();
- if (this._clearFlags) {
+ var locClearFlags = this._clearFlags;
+ if (locClearFlags) {
var oldClearColor = [0.0, 0.0, 0.0, 0.0];
var oldDepthClearValue = 0.0;
var oldStencilClearValue = 0;
// backup and set
- if (this._clearFlags & gl.COLOR_BUFFER_BIT) {
+ if (locClearFlags & gl.COLOR_BUFFER_BIT) {
oldClearColor = gl.getParameter(gl.COLOR_CLEAR_VALUE);
gl.clearColor(this._clearColor.r, this._clearColor.g, this._clearColor.b, this._clearColor.a);
}
- if (this._clearFlags & gl.DEPTH_BUFFER_BIT) {
+ if (locClearFlags & gl.DEPTH_BUFFER_BIT) {
oldDepthClearValue = gl.getParameter(gl.DEPTH_CLEAR_VALUE);
gl.clearDepth(this._clearDepth);
}
- if (this._clearFlags & gl.STENCIL_BUFFER_BIT) {
+ if (locClearFlags & gl.STENCIL_BUFFER_BIT) {
oldStencilClearValue = gl.getParameter(gl.STENCIL_CLEAR_VALUE);
gl.clearStencil(this._clearStencil);
}
// clear
- gl.clear(this._clearFlags);
+ gl.clear(locClearFlags);
// restore
- if (this._clearFlags & gl.COLOR_BUFFER_BIT)
+ if (locClearFlags & gl.COLOR_BUFFER_BIT)
gl.clearColor(oldClearColor[0], oldClearColor[1], oldClearColor[2], oldClearColor[3]);
- if (this._clearFlags & gl.DEPTH_BUFFER_BIT)
+ if (locClearFlags & gl.DEPTH_BUFFER_BIT)
gl.clearDepth(oldDepthClearValue);
- if (this._clearFlags & gl.STENCIL_BUFFER_BIT)
+ if (locClearFlags & gl.STENCIL_BUFFER_BIT)
gl.clearStencil(oldStencilClearValue);
}
//! make sure all children are drawn
this.sortAllChildren();
-
- for (var i = 0; i < this._children.length; i++) {
- var getChild = this._children[i];
+ var locChildren = this._children;
+ for (var i = 0; i < locChildren.length; i++) {
+ var getChild = locChildren[i];
if (getChild != this._sprite)
getChild.visit();
}
@@ -621,7 +853,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @param {Number} format
*/
saveToFile:function (filePath, format) {
- cc.log("saveToFile is NoSupported on Cocos2d-Html5");
+ cc.log("saveToFile isn't supported on Cocos2d-Html5");
},
/**
@@ -629,7 +861,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @param {cc.Class} obj
*/
listenToBackground:function (obj) {
- cc.log("listenToBackground is NoSupported on Cocos2d-Html5");
+ cc.log("listenToBackground isn't supported on Cocos2d-Html5");
},
/**
@@ -637,7 +869,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @param {cc.Class} obj
*/
listenToForeground:function (obj) {
- cc.log("listenToForeground is NoSupported on Cocos2d-Html5");
+ cc.log("listenToForeground isn't supported on Cocos2d-Html5");
},
/**
@@ -702,6 +934,8 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
}
});
+cc.RenderTexture = cc.Browser.supportWebGL ? cc.RenderTextureWebGL : cc.RenderTextureCanvas;
+
/**
* creates a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid
* @param {Number} width
diff --git a/cocos2d/particle_nodes/CCParticleSystem.js b/cocos2d/particle_nodes/CCParticleSystem.js
index 1d33a1740e..79e8c43f9c 100644
--- a/cocos2d/particle_nodes/CCParticleSystem.js
+++ b/cocos2d/particle_nodes/CCParticleSystem.js
@@ -1889,8 +1889,6 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
if (!this._batchNode)
this.postStep();
-
- //cc.PROFILER_STOP_CATEGORY(kCCProfilerCategoryParticles , "cc.ParticleSystem - update");
},
updateWithNoTime:function () {
diff --git a/cocos2d/platform/CCApplication.js b/cocos2d/platform/CCApplication.js
index 3c7099284a..6fbc4adb15 100644
--- a/cocos2d/platform/CCApplication.js
+++ b/cocos2d/platform/CCApplication.js
@@ -208,11 +208,12 @@ cc.setup = function (el, width, height) {
cc.renderContext = cc.webglContext = cc.create3DContext(cc.canvas,{'stencil': true, 'preserveDrawingBuffer': true, 'alpha': false });
if(cc.renderContext){
cc.renderContextType = cc.WEBGL;
- gl = cc.renderContext; // global variable declared in CCMacro.js
+ window.gl = cc.renderContext; // global variable declared in CCMacro.js
cc.drawingUtil = new cc.DrawingPrimitiveWebGL(cc.renderContext);
cc.TextureCache.getInstance()._initializingRenderer();
} else {
cc.renderContext = cc.canvas.getContext("2d");
+ cc.mainRenderContextBackup = cc.renderContext;
cc.renderContextType = cc.CANVAS;
cc.renderContext.translate(0, cc.canvas.height);
cc.drawingUtil = new cc.DrawingPrimitiveCanvas(cc.renderContext);
diff --git a/cocos2d/sprite_nodes/CCSprite.js b/cocos2d/sprite_nodes/CCSprite.js
index 460545df8b..aa8a5540a1 100644
--- a/cocos2d/sprite_nodes/CCSprite.js
+++ b/cocos2d/sprite_nodes/CCSprite.js
@@ -478,18 +478,19 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
sortAllChildren:function () {
if (this._reorderChildDirty) {
- var j, tempItem, locChildren = this._children;
+ var j, tempItem, locChildren = this._children, tempChild;
for (var i = 1; i < locChildren.length; i++) {
tempItem = locChildren[i];
j = i - 1;
+ tempChild = locChildren[j];
- //continue moving element downwards while zOrder is smaller or when zOrder is the same but orderOfArrival is smaller
- while (j >= 0 && ( tempItem.getZOrder() < locChildren[j].getZOrder() || ( tempItem.getZOrder() === locChildren[j].getZOrder()
- && tempItem.getOrderOfArrival() < locChildren[j].getOrderOfArrival() ) )) {
- locChildren[j + 1] = locChildren[j];
+ //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
+ while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
+ ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
+ tempChild = locChildren[j];
+ locChildren[j + 1] = tempChild;
j = j - 1;
}
-
locChildren[j + 1] = tempItem;
}
@@ -1522,15 +1523,17 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
sortAllChildren:function () {
if (this._reorderChildDirty) {
- var j, tempItem, locChildren = this._children;
+ var j, tempItem, locChildren = this._children, tempChild;
for (var i = 1; i < locChildren.length; i++) {
tempItem = locChildren[i];
j = i - 1;
+ tempChild = locChildren[j];
- //continue moving element downwards while zOrder is smaller or when zOrder is the same but orderOfArrival is smaller
- while (j >= 0 && ( tempItem.getZOrder() < locChildren[j].getZOrder() || ( tempItem.getZOrder() === locChildren[j].getZOrder()
- && tempItem.getOrderOfArrival() < locChildren[j].getOrderOfArrival() ) )) {
- locChildren[j + 1] = locChildren[j];
+ //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
+ while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
+ ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
+ tempChild = locChildren[j];
+ locChildren[j + 1] = tempChild;
j = j - 1;
}
locChildren[j + 1] = tempItem;
diff --git a/cocos2d/sprite_nodes/CCSpriteBatchNode.js b/cocos2d/sprite_nodes/CCSpriteBatchNode.js
index d037c01f08..855a89bbf3 100644
--- a/cocos2d/sprite_nodes/CCSpriteBatchNode.js
+++ b/cocos2d/sprite_nodes/CCSpriteBatchNode.js
@@ -359,7 +359,6 @@ cc.SpriteBatchNodeCanvas = cc.Node.extend(/** @lends cc.SpriteBatchNodeCanvas# *
/// ---- common properties end ----
_textureForCanvas:null,
- _renderTexture:null,
_useCache:false,
_originalTexture:null,
@@ -371,10 +370,6 @@ cc.SpriteBatchNodeCanvas = cc.Node.extend(/** @lends cc.SpriteBatchNodeCanvas# *
cc.Node.prototype.ctor.call(this);
if (fileImage)
this.init(fileImage, cc.DEFAULT_SPRITE_BATCH_CAPACITY);
-
- var locCanvas = cc.canvas;
- this._renderTexture = cc.RenderTexture.create(locCanvas.width, locCanvas.height);
- this.setContentSize(cc.size(locCanvas.width, locCanvas.height));
},
/**
@@ -427,13 +422,6 @@ cc.SpriteBatchNodeCanvas = cc.Node.extend(/** @lends cc.SpriteBatchNodeCanvas# *
this._children = cc.ArrayAppendObjectToIndex(this._children, sprite, index);
},
- setContentSize:function (size) {
- if (!size)
- return;
- cc.Node.prototype.setContentSize.call(this, size);
- this._renderTexture.setContentSize(size);
- },
-
/**
*
* initializes a CCSpriteBatchNode with a texture2d and capacity of children.
@@ -507,8 +495,6 @@ cc.SpriteBatchNodeCanvas = cc.Node.extend(/** @lends cc.SpriteBatchNodeCanvas# *
* @return {cc.Texture2D|HTMLImageElement|HTMLCanvasElement}
*/
getTexture:function () {
- if (this._useCache)
- return this._renderTexture.getCanvas();
return this._textureForCanvas;
},
@@ -537,34 +523,15 @@ cc.SpriteBatchNodeCanvas = cc.Node.extend(/** @lends cc.SpriteBatchNodeCanvas# *
context.save();
this.transform(ctx);
var i, locChildren = this._children;
- if (this._useCache) {
- if (this._cacheDirty) {
- //add dirty region
- var locRenderTexture = this._renderTexture;
- locRenderTexture.clear();
- locRenderTexture.context.save();
- locRenderTexture.context.translate(this._anchorPointInPoints.x, -(this._anchorPointInPoints.y ));
- if (locChildren) {
- this.sortAllChildren();
- for (i = 0; i < locChildren.length; i++) {
- if (locChildren[i])
- locChildren[i].visit(locRenderTexture.context);
- }
- }
- locRenderTexture.context.restore();
- this._cacheDirty = false;
- }
- // draw RenderTexture
- this.draw(ctx);
- } else {
- if (locChildren) {
- this.sortAllChildren();
- for (i = 0; i < locChildren.length; i++) {
- if (locChildren[i])
- locChildren[i].visit(context);
- }
+
+ if (locChildren) {
+ this.sortAllChildren();
+ for (i = 0; i < locChildren.length; i++) {
+ if (locChildren[i])
+ locChildren[i].visit(context);
}
}
+
context.restore();
},
@@ -620,17 +587,19 @@ cc.SpriteBatchNodeCanvas = cc.Node.extend(/** @lends cc.SpriteBatchNodeCanvas# *
sortAllChildren:function () {
if (this._reorderChildDirty) {
var i, j = 0, locChildren = this._children;
- var length = locChildren.length;
+ var length = locChildren.length, tempChild;
//insertion sort
for (i = 1; i < length; i++) {
var tempItem = locChildren[i];
j = i - 1;
-
- //continue moving element downwards while zOrder is smaller or when zOrder is the same but orderOfArrival is smaller
- while (j >= 0 && (tempItem.getZOrder() < locChildren[j].getZOrder() ||
- (tempItem.getZOrder() == locChildren[j].getZOrder() && tempItem.getOrderOfArrival() < locChildren[j].getOrderOfArrival()))) {
- locChildren[j + 1] = locChildren[j];
- j--;
+ tempChild = locChildren[j];
+
+ //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
+ while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
+ ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
+ tempChild = locChildren[j];
+ locChildren[j + 1] = tempChild;
+ j = j - 1;
}
locChildren[j + 1] = tempItem;
}
@@ -642,20 +611,6 @@ cc.SpriteBatchNodeCanvas = cc.Node.extend(/** @lends cc.SpriteBatchNodeCanvas# *
}
this._reorderChildDirty = false;
}
- },
-
- /**
- * draw cc.SpriteBatchNode (override draw of cc.Node)
- * @param {CanvasRenderingContext2D} ctx
- */
- draw:function (ctx) {
- var context = ctx || cc.renderContext;
- //context.globalAlpha = this._opacity / 255;
- var posX = 0 | ( -this._anchorPointInPoints.x), posY = 0 | ( -this._anchorPointInPoints.y);
- var locRenderTexture = this._renderTexture;
- //direct draw image by canvas drawImage
- if (locRenderTexture)
- context.drawImage(locRenderTexture.getCanvas(), posX, -(posY + locRenderTexture.getCanvas().height));
}
});
@@ -1265,11 +1220,10 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
/**
* don't call visit on it's children ( override visit of cc.Node )
* @override
- * @param {CanvasContext} ctx
+ * @param {WebGLRenderingContext} ctx
*/
visit:function (ctx) {
var gl = ctx || cc.renderContext;
- //cc.PROFILER_START_CATEGORY(kCCProfilerCategoryBatchSprite, "CCSpriteBatchNode - visit");
// CAREFUL:
// This visit is almost identical to CocosNode#visit
@@ -1292,7 +1246,6 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
this._grid.afterDraw(this);
cc.kmGLPopMatrix();
this.setOrderOfArrival(0);
- //cc.PROFILER_STOP_CATEGORY(kCCProfilerCategoryBatchSprite, "CCSpriteBatchNode - visit");
},
/**
@@ -1349,17 +1302,19 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
sortAllChildren:function () {
if (this._reorderChildDirty) {
var childrenArr = this._children;
- var i, j = 0, length = childrenArr.length;
+ var i, j = 0, length = childrenArr.length, tempChild;
//insertion sort
for (i = 1; i < length; i++) {
var tempItem = childrenArr[i];
j = i - 1;
-
- //continue moving element downwards while zOrder is smaller or when zOrder is the same but orderOfArrival is smaller
- while (j >= 0 && (tempItem.getZOrder() < childrenArr[j].getZOrder() ||
- (tempItem.getZOrder() == childrenArr[j].getZOrder() && tempItem.getOrderOfArrival() < childrenArr[j].getOrderOfArrival()))) {
- childrenArr[j + 1] = childrenArr[j];
- j--;
+ tempChild = childrenArr[j];
+
+ //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
+ while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
+ ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
+ tempChild = childrenArr[j];
+ childrenArr[j + 1] = tempChild;
+ j = j - 1;
}
childrenArr[j + 1] = tempItem;
}
diff --git a/cocos2d/tileMap_parallax_nodes/CCTMXLayer.js b/cocos2d/tileMap_parallax_nodes/CCTMXLayer.js
index 4a4539ffc8..47aa16b306 100644
--- a/cocos2d/tileMap_parallax_nodes/CCTMXLayer.js
+++ b/cocos2d/tileMap_parallax_nodes/CCTMXLayer.js
@@ -69,6 +69,9 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{
//used for retina display
_contentScaleFactor: null,
+ _cacheCanvas:null,
+ _cacheContext:null,
+
/**
* Constructor
*/
@@ -76,9 +79,93 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{
cc.SpriteBatchNode.prototype.ctor.call(this);
this._children = [];
this._descendants = [];
- this._useCache = true;
+
this._layerSize = cc.SizeZero();
this._mapTileSize = cc.SizeZero();
+
+ if(cc.renderContextType === cc.CANVAS){
+ var locCanvas = cc.canvas;
+ var tmpCanvas = document.createElement('canvas');
+ tmpCanvas.width = locCanvas.width;
+ tmpCanvas.height = locCanvas.height;
+ this._cacheCanvas = tmpCanvas;
+ this._cacheContext = this._cacheCanvas.getContext('2d');
+ this.setContentSize(cc.size(locCanvas.width, locCanvas.height));
+ }
+ },
+
+ setContentSize:function (size) {
+ if (!size)
+ return;
+ cc.Node.prototype.setContentSize.call(this, size);
+
+ if(cc.renderContextType === cc.CANVAS){
+ this._cacheCanvas.width = size.width * 1.5;
+ this._cacheCanvas.height = size.height * 1.5;
+ this._cacheContext.translate(0, this._cacheCanvas.height);
+ }
+ },
+
+ /**
+ * Return texture of cc.SpriteBatchNode
+ * @return {cc.Texture2D|HTMLImageElement|HTMLCanvasElement}
+ */
+ getTexture:function () {
+ return this._cacheCanvas;
+ },
+
+ /**
+ * don't call visit on it's children ( override visit of cc.Node )
+ * @override
+ * @param {CanvasRenderingContext2D} ctx
+ */
+ visit:function (ctx) {
+ if (cc.renderContextType === cc.WEBGL) {
+ cc.SpriteBatchNode.prototype.visit.call(this, ctx);
+ return;
+ }
+ var context = ctx || cc.renderContext;
+ // quick return if not visible
+ if (!this._visible)
+ return;
+
+ context.save();
+ this.transform(ctx);
+ var i, locChildren = this._children;
+
+ if (this._cacheDirty) {
+ //add dirty region
+ var locCacheContext = this._cacheContext, locCacheCanvas = this._cacheCanvas;
+ locCacheContext.clearRect(0, 0, locCacheCanvas.width, -locCacheCanvas.height);
+ locCacheContext.save();
+ locCacheContext.translate(this._anchorPointInPoints.x, -(this._anchorPointInPoints.y ));
+ if (locChildren) {
+ this.sortAllChildren();
+ for (i = 0; i < locChildren.length; i++) {
+ if (locChildren[i])
+ locChildren[i].visit(locCacheContext);
+ }
+ }
+ locCacheContext.restore();
+ this._cacheDirty = false;
+ }
+ // draw RenderTexture
+ this.draw(ctx);
+ context.restore();
+ },
+
+ /**
+ * draw cc.SpriteBatchNode (override draw of cc.Node)
+ * @param {CanvasRenderingContext2D} ctx
+ */
+ draw:function (ctx) {
+ var context = ctx || cc.renderContext;
+ //context.globalAlpha = this._opacity / 255;
+ var posX = 0 | ( -this._anchorPointInPoints.x), posY = 0 | ( -this._anchorPointInPoints.y);
+ var locCacheCanvas = this._cacheCanvas;
+ //direct draw image by canvas drawImage
+ if (locCacheCanvas)
+ context.drawImage(locCacheCanvas, posX, -(posY + locCacheCanvas.height));
},
/**
diff --git a/extensions/GUI/CCControlExtension/CCControl.js b/extensions/GUI/CCControlExtension/CCControl.js
index 905942a8b8..79b890e607 100644
--- a/extensions/GUI/CCControlExtension/CCControl.js
+++ b/extensions/GUI/CCControlExtension/CCControl.js
@@ -176,7 +176,7 @@ cc.Control = cc.LayerRGBA.extend({
this._super();
},
registerWithTouchDispatcher:function () {
- cc.Director.getInstance().getTouchDispatcher().addTargetedDelegate(this, cc.MENU_HANDLER_PRIORITY, true);
+ cc.Director.getInstance().getTouchDispatcher().addTargetedDelegate(this, this.getTouchPriority(), true);
},
/**
diff --git a/extensions/GUI/CCControlExtension/CCControlButton.js b/extensions/GUI/CCControlExtension/CCControlButton.js
index 159996cf82..4612689f3e 100644
--- a/extensions/GUI/CCControlExtension/CCControlButton.js
+++ b/extensions/GUI/CCControlExtension/CCControlButton.js
@@ -490,7 +490,7 @@ cc.ControlButton = cc.Control.extend({
* If a property is not specified for a state, the default is to use
* the CCButtonStateNormal value.
*
- * @param title The title label to use for the specified state.
+ * @param titleLabel The title label to use for the specified state.
* @param state The state that uses the specified title. The values are described
* in "CCControlState".
*/
From eeaef0222157798e048c9360e4967dabcad2621d Mon Sep 17 00:00:00 2001
From: NeroChan
Date: Wed, 7 Aug 2013 17:04:22 +0800
Subject: [PATCH 027/141] fixed #2497 : setSearchPaths Bug
---
cocos2d/sprite_nodes/CCSprite.js | 2 ++
1 file changed, 2 insertions(+)
diff --git a/cocos2d/sprite_nodes/CCSprite.js b/cocos2d/sprite_nodes/CCSprite.js
index a514f31fe3..64fb10c0eb 100644
--- a/cocos2d/sprite_nodes/CCSprite.js
+++ b/cocos2d/sprite_nodes/CCSprite.js
@@ -929,6 +929,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
var selfPointer = this;
var texture = cc.TextureCache.getInstance().textureForKey(filename);
if (!texture) {
+ filename = cc.FileUtils.getInstance().fullPathForFilename(filename);
this._visible = false;
var loadImg = new Image();
loadImg.addEventListener("load", function () {
@@ -2127,6 +2128,7 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
var texture = cc.TextureCache.getInstance().textureForKey(filename);
if (!texture) {
+ filename = cc.FileUtils.getInstance().fullPathForFilename(filename);
this._visible = false;
var loadImg = new Image();
loadImg.addEventListener("load", function () {
From 285555b22af1c0dbf6903c8d147130eef03ae2da Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Fri, 2 Aug 2013 15:35:23 +0800
Subject: [PATCH 028/141] Fixed #2444 Re-write cc.Texture for Canvas Mode.
Texture2D was used Image/Canvas instead on Canvas Mode , now rewritten it.
Conflicts:
cocos2d/misc_nodes/CCRenderTexture.js
cocos2d/sprite_nodes/CCSprite.js
extensions/GUI/CCControlExtension/CCScale9Sprite.js
---
cocos2d/CCLoader.js | 13 +-
cocos2d/base_nodes/CCAtlasNode.js | 20 +-
cocos2d/label_nodes/CCLabelBMFont.js | 7 +-
cocos2d/misc_nodes/CCProgressTimer.js | 17 +-
cocos2d/particle_nodes/CCParticleSystem.js | 5 +-
.../particle_nodes/CCParticleSystemQuad.js | 37 +--
cocos2d/sprite_nodes/CCAnimation.js | 6 +-
cocos2d/sprite_nodes/CCSprite.js | 151 +++++----
cocos2d/sprite_nodes/CCSpriteFrameCache.js | 13 +-
cocos2d/textures/CCTexture2D.js | 309 ++++++++++--------
cocos2d/textures/CCTextureCache.js | 46 ++-
cocos2d/tileMap_parallax_nodes/CCTMXLayer.js | 3 +-
extensions/CCBReader/CCBReader.js | 6 +-
.../GUI/CCControlExtension/CCControlSwitch.js | 21 +-
.../GUI/CCControlExtension/CCScale9Sprite.js | 9 +-
samples | 2 +-
16 files changed, 342 insertions(+), 323 deletions(-)
diff --git a/cocos2d/CCLoader.js b/cocos2d/CCLoader.js
index f2ea27542d..3b4b6d8cb5 100644
--- a/cocos2d/CCLoader.js
+++ b/cocos2d/CCLoader.js
@@ -437,14 +437,11 @@ cc.LoaderScene = cc.Scene.extend(/** @lends cc.LoaderScene# */{
},
_initStage: function (centerPos) {
- if (cc.renderContextType === cc.CANVAS) {
- this._logo = cc.Sprite.createWithTexture(this._logoTexture);
- } else {
- this._texture2d = new cc.Texture2D();
- this._texture2d.initWithElement(this._logoTexture);
- this._texture2d.handleLoadedTexture();
- this._logo = cc.Sprite.createWithTexture(this._texture2d);
- }
+ this._texture2d = new cc.Texture2D();
+ this._texture2d.initWithElement(this._logoTexture);
+ this._texture2d.handleLoadedTexture();
+ this._logo = cc.Sprite.createWithTexture(this._texture2d);
+
this._logo.setPosition(centerPos);
this._bgLayer.addChild(this._logo, 10);
diff --git a/cocos2d/base_nodes/CCAtlasNode.js b/cocos2d/base_nodes/CCAtlasNode.js
index fa64826a00..fb3e1d34cb 100644
--- a/cocos2d/base_nodes/CCAtlasNode.js
+++ b/cocos2d/base_nodes/CCAtlasNode.js
@@ -201,13 +201,19 @@ cc.AtlasNodeCanvas = cc.NodeRGBA.extend(/** @lends cc.AtlasNode# */{
temp.b = temp.b * this._displayedOpacity / 255;
}
cc.NodeRGBA.prototype.setColor.call(this, color3);
+
if (this.getTexture()) {
- var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(this._originalTexture);
+ var element = this._originalTexture.getHtmlElementObj();
+ if(!element)
+ return;
+ var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(element);
if (cacheTextureForColor) {
- var tx = this._originalTexture;
- var textureRect = cc.rect(0, 0, tx.width, tx.height);
- var colorTexture = cc.generateTintImage(tx, cacheTextureForColor, this._realColor, textureRect);
- this.setTexture(colorTexture);
+ var textureRect = cc.rect(0, 0, element.width, element.height);
+ element = cc.generateTintImage(element, cacheTextureForColor, this._realColor, textureRect);
+ var locTexture = new cc.Texture2D();
+ locTexture.initWithElement(element);
+ locTexture.handleLoadedTexture();
+ this.setTexture(locTexture);
}
}
},
@@ -234,7 +240,7 @@ cc.AtlasNodeCanvas = cc.NodeRGBA.extend(/** @lends cc.AtlasNode# */{
},
/** sets a new texture. it will be retained
- * @param {HTMLCanvasElement|HTMLImageElement} texture
+ * @param {cc.Texture2D} texture
*/
setTexture:function (texture) {
this._textureForCanvas = texture;
@@ -242,7 +248,7 @@ cc.AtlasNodeCanvas = cc.NodeRGBA.extend(/** @lends cc.AtlasNode# */{
_calculateMaxItems:function () {
var selTexture = this.getTexture();
- var size = cc.size(selTexture.width, selTexture.height);
+ var size = selTexture.getContentSize();
this._itemsPerColumn = 0 | (size.height / this._itemHeight);
this._itemsPerRow = 0 | (size.width / this._itemWidth);
diff --git a/cocos2d/label_nodes/CCLabelBMFont.js b/cocos2d/label_nodes/CCLabelBMFont.js
index 421d707939..fc25cc3aec 100644
--- a/cocos2d/label_nodes/CCLabelBMFont.js
+++ b/cocos2d/label_nodes/CCLabelBMFont.js
@@ -643,8 +643,11 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
this._configuration = newConf;
this._fntFile = fntFile;
texture = cc.TextureCache.getInstance().addImage(this._configuration.getAtlasName());
- } else
- texture = (cc.renderContextType === cc.CANVAS) ? new Image() : new cc.Texture2D();
+ } else{
+ texture = new cc.Texture2D();
+ var image = new Image();
+ texture.initWithElement(image);
+ }
if (this.initWithTexture(texture, theString.length)) {
this._alignment = alignment || cc.TEXT_ALIGNMENT_LEFT;
diff --git a/cocos2d/misc_nodes/CCProgressTimer.js b/cocos2d/misc_nodes/CCProgressTimer.js
index 42b181adf1..2d14f6ef45 100644
--- a/cocos2d/misc_nodes/CCProgressTimer.js
+++ b/cocos2d/misc_nodes/CCProgressTimer.js
@@ -311,21 +311,22 @@ cc.ProgressTimerCanvas = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerCanvas# *
var pos;
var offsetPixels = locSprite._offsetPosition, locSpriteTexture = locSprite._texture, locSpriteRect = locSprite._rect;
var locOrigin = this._origin;
+ var locElement = locSpriteTexture.getHtmlElementObj();
if (this._type == cc.PROGRESS_TIMER_TYPE_BAR) {
pos = cc.p(( -spriteAnchorPoint.x + offsetPixels.x + this._drawPosition.x),
( -spriteAnchorPoint.y + offsetPixels.y + this._drawPosition.y));
var locOriginSize = this._originSize;
- if (locSpriteTexture instanceof HTMLImageElement) {
+ if (locElement instanceof HTMLImageElement) {
if ((locOriginSize.width != 0) && (locOriginSize.height != 0)) {
- context.drawImage(locSpriteTexture,
+ context.drawImage(locElement,
locSpriteRect.x + locOrigin.x, locSpriteRect.y + locOrigin.y,
locOriginSize.width, locOriginSize.height,
pos.x, -(pos.y + this._drawSize.height),
locOriginSize.width, locOriginSize.height);
}
- } else if (locSpriteTexture instanceof HTMLCanvasElement) {
+ } else if (locElement instanceof HTMLCanvasElement) {
if ((locOriginSize.width != 0) && (locOriginSize.height != 0)) {
- context.drawImage(locSpriteTexture,
+ context.drawImage(locElement,
locOrigin.x, locOrigin.y,
locOriginSize.width, locOriginSize.height,
pos.x, -(pos.y + this._drawSize.height),
@@ -342,14 +343,14 @@ cc.ProgressTimerCanvas = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerCanvas# *
pos = cc.p(0 | ( -spriteAnchorPoint.x + offsetPixels.x),
0 | ( -spriteAnchorPoint.y + offsetPixels.y));
- if (locSpriteTexture instanceof HTMLImageElement) {
- context.drawImage(locSpriteTexture,
+ if (locElement instanceof HTMLImageElement) {
+ context.drawImage(locElement,
locSpriteRect.x, locSpriteRect.y,
locSpriteRect.width, locSpriteRect.height,
pos.x, -(pos.y + locSpriteRect.height),
locSpriteRect.width, locSpriteRect.height);
- } else if (locSpriteTexture instanceof HTMLCanvasElement) {
- context.drawImage(locSpriteTexture,
+ } else if (locElement instanceof HTMLCanvasElement) {
+ context.drawImage(locElement,
0, 0,
locSpriteRect.width, locSpriteRect.height,
pos.x, -(pos.y + locSpriteRect.height),
diff --git a/cocos2d/particle_nodes/CCParticleSystem.js b/cocos2d/particle_nodes/CCParticleSystem.js
index 79e8c43f9c..7a2ec5c0b6 100644
--- a/cocos2d/particle_nodes/CCParticleSystem.js
+++ b/cocos2d/particle_nodes/CCParticleSystem.js
@@ -1454,10 +1454,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
cc.Assert(addTexture != null, "cc.ParticleSystem: error loading the texture");
- if (cc.renderContextType === cc.CANVAS)
- this.setTexture(canvasObj);
- else
- this.setTexture(addTexture);
+ this.setTexture(addTexture);
}
}
diff --git a/cocos2d/particle_nodes/CCParticleSystemQuad.js b/cocos2d/particle_nodes/CCParticleSystemQuad.js
index d8b9a4f132..743932d362 100644
--- a/cocos2d/particle_nodes/CCParticleSystemQuad.js
+++ b/cocos2d/particle_nodes/CCParticleSystemQuad.js
@@ -108,13 +108,8 @@ cc.ParticleSystemQuad = cc.ParticleSystem.extend(/** @lends cc.ParticleSystemQua
var high = pointRect.height;
if (this._texture) {
- if ((this._texture instanceof HTMLImageElement) || (this._texture instanceof HTMLCanvasElement)) {
- wide = this._texture.width;
- high = this._texture.height;
- } else {
- wide = this._texture.getPixelsWide();
- high = this._texture.getPixelsHigh();
- }
+ wide = this._texture.getPixelsWide();
+ high = this._texture.getPixelsHigh();
}
if(cc.renderContextType === cc.CANVAS)
@@ -273,10 +268,7 @@ cc.ParticleSystemQuad = cc.ParticleSystem.extend(/** @lends cc.ParticleSystemQua
retParticle._opacityModifyRGB = this._opacityModifyRGB;
// texture
- if (this._texture instanceof cc.Texture2D)
- retParticle._texture = this._texture;
- else
- retParticle._texture = this._texture;
+ retParticle._texture = this._texture;
}
}
return retParticle;
@@ -358,11 +350,8 @@ cc.ParticleSystemQuad = cc.ParticleSystem.extend(/** @lends cc.ParticleSystemQua
cc.ParticleSystem.prototype.setTexture.call(this, texture);
return;
}
- var size = null;
- if ((texture instanceof HTMLImageElement) || (texture instanceof HTMLCanvasElement))
- size = cc.size(texture.width, texture.height);
- else
- size = texture.getContentSize();
+
+ var size = texture.getContentSize();
this.setTextureWithRect(texture, cc.rect(0, 0, size.width, size.height));
},
@@ -531,10 +520,10 @@ cc.ParticleSystemQuad = cc.ParticleSystem.extend(/** @lends cc.ParticleSystemQua
if (this._drawMode == cc.PARTICLE_TEXTURE_MODE) {
- var drawTexture = this.getTexture();
+ var element = this._texture.getHtmlElementObj();
// Delay drawing until the texture is fully loaded by the browser
- if (!drawTexture.width || !drawTexture.height)
+ if (!element.width || !element.height)
continue;
context.save();
@@ -557,21 +546,21 @@ cc.ParticleSystemQuad = cc.ParticleSystem.extend(/** @lends cc.ParticleSystemQua
context.translate(-(0 | (w / 2)), -(0 | (h / 2)));
if (particle.isChangeColor) {
- var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(drawTexture);
+ var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(element);
if (cacheTextureForColor) {
// Create another cache for the tinted version
// This speeds up things by a fair bit
if (!cacheTextureForColor.tintCache) {
cacheTextureForColor.tintCache = document.createElement('canvas');
- cacheTextureForColor.tintCache.width = drawTexture.width;
- cacheTextureForColor.tintCache.height = drawTexture.height;
+ cacheTextureForColor.tintCache.width = element.width;
+ cacheTextureForColor.tintCache.height = element.height;
}
- cc.generateTintImage(drawTexture, cacheTextureForColor, particle.color, this._pointRect, cacheTextureForColor.tintCache);
- drawTexture = cacheTextureForColor.tintCache;
+ cc.generateTintImage(element, cacheTextureForColor, particle.color, this._pointRect, cacheTextureForColor.tintCache);
+ element = cacheTextureForColor.tintCache;
}
}
- context.drawImage(drawTexture, 0, 0);
+ context.drawImage(element, 0, 0);
context.restore();
} else {
diff --git a/cocos2d/sprite_nodes/CCAnimation.js b/cocos2d/sprite_nodes/CCAnimation.js
index e1cc01cdcb..912b042855 100644
--- a/cocos2d/sprite_nodes/CCAnimation.js
+++ b/cocos2d/sprite_nodes/CCAnimation.js
@@ -199,11 +199,7 @@ cc.Animation = cc.Class.extend(/** @lends cc.Animation# */{
addSpriteFrameWithFile:function (fileName) {
var texture = cc.TextureCache.getInstance().addImage(fileName);
var rect = cc.RectZero();
- if ((texture instanceof HTMLImageElement) || (texture instanceof HTMLCanvasElement)) {
- rect.size = cc.size(texture.width, texture.height);
- } else {
- rect.size = texture.getContentSize();
- }
+ rect.size = texture.getContentSize();
var frame = cc.SpriteFrame.createWithTexture(texture, rect);
this.addSpriteFrame(frame);
},
diff --git a/cocos2d/sprite_nodes/CCSprite.js b/cocos2d/sprite_nodes/CCSprite.js
index aa8a5540a1..3a88542f5d 100644
--- a/cocos2d/sprite_nodes/CCSprite.js
+++ b/cocos2d/sprite_nodes/CCSprite.js
@@ -207,7 +207,7 @@ cc.generateTintImage = function (texture, tintedImgCache, color, rect, renderCan
ctx.drawImage(tintedImgCache[2], rect.x, rect.y, w, h, 0, 0, w, h);
}
- if((selColor.r === 0) && (selColor.g === 0) &&(selColor.b === 0)){
+ if ((selColor.r === 0) && (selColor.g === 0) && (selColor.b === 0)) {
ctx.globalAlpha = a;
ctx.drawImage(tintedImgCache[3], rect.x, rect.y, w, h, 0, 0, w, h);
}
@@ -257,7 +257,7 @@ cc.TransformValues = function (pos, scale, rotation, skew, ap, visible) {
cc.RENDER_IN_SUBPIXEL = function (A) {
return (0 | A);
};
-if(cc.SPRITEBATCHNODE_RENDER_SUBPIXEL){
+if (cc.SPRITEBATCHNODE_RENDER_SUBPIXEL) {
cc.RENDER_IN_SUBPIXEL = function (A) {
return A;
};
@@ -298,28 +298,28 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
//
// Data used when the sprite is rendered using a CCSpriteSheet
//
- _textureAtlas:null, //cc.SpriteBatchNode texture atlas
+ _textureAtlas:null, //cc.SpriteBatchNode texture atlas
_atlasIndex:0,
_batchNode:null,
- _dirty:false, //Whether the sprite needs to be updated
- _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
+ _dirty:false, //Whether the sprite needs to be updated
+ _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:cc.rect(0, 0, 0, 0), //Retangle of cc.Texture2D
- _rectRotated:false, //Whether the texture is rotated
+ _rect:cc.rect(0, 0, 0, 0), //Retangle of cc.Texture2D
+ _rectRotated:false, //Whether the texture is rotated
// Offset Position (used by Zwoptex)
_offsetPosition:null, // absolute
@@ -328,8 +328,8 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
_opacityModifyRGB:false,
// image is flipped
- _flipX:false, //Whether the sprite is flipped horizontally or not.
- _flipY:false, //Whether the sprite is flipped vertically or not.
+ _flipX:false, //Whether the sprite is flipped horizontally or not.
+ _flipY:false, //Whether the sprite is flipped vertically or not.
/**
* Whether or not the Sprite needs to be updated in the Atlas
@@ -703,7 +703,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
*/
ignoreAnchorPointForPosition:function (relative) {
cc.Assert(!this._batchNode, "ignoreAnchorPointForPosition is invalid in cc.Sprite");
- cc.Node.prototype.ignoreAnchorPointForPosition.call(this,relative);
+ cc.Node.prototype.ignoreAnchorPointForPosition.call(this, relative);
},
/**
@@ -768,7 +768,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
* @param {Boolean} modify
*/
setOpacityModifyRGB:function (modify) {
- if(this._opacityModifyRGB !== modify){
+ if (this._opacityModifyRGB !== modify) {
this._opacityModifyRGB = modify;
this.setNodeDirty();
}
@@ -782,7 +782,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
return this._opacityModifyRGB;
},
- updateDisplayedOpacity:function(parentOpacity){
+ updateDisplayedOpacity:function (parentOpacity) {
cc.NodeRGBA.prototype.updateDisplayedOpacity.call(this, parentOpacity);
this._changeTextureColor();
this.setNodeDirty();
@@ -860,6 +860,11 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
this.initWithBatchNode(fileName, rect);
}
} else if ((fileName instanceof HTMLImageElement) || (fileName instanceof HTMLCanvasElement)) {
+ var texture2d = new cc.Texture2D();
+ texture2d.initWithElement(fileName);
+ texture2d.handleLoadedTexture();
+ this.initWithTexture(texture2d)
+ } else if (fileName instanceof cc.Texture2D) {
this.initWithTexture(fileName)
}
}
@@ -884,7 +889,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
* @return {Boolean}
*/
init:function () {
- if(arguments.length > 0)
+ if (arguments.length > 0)
return this.initWithFile(arguments[0], arguments[1]);
cc.NodeRGBA.prototype.init.call(this);
@@ -938,7 +943,10 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
rect = cc.rect(0, 0, loadImg.width, loadImg.height);
rect = cc.RECT_PIXELS_TO_POINTS(rect);
}
- selfPointer.initWithTexture(loadImg, rect);
+ var texture2d = new cc.Texture2D();
+ texture2d.initWithElement(loadImg);
+ texture2d.handleLoadedTexture();
+ selfPointer.initWithTexture(texture2d, rect);
cc.TextureCache.getInstance().cacheImage(filename, loadImg);
selfPointer._visible = true;
});
@@ -948,13 +956,11 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
loadImg.src = filename;
return true;
} else {
- if (texture) {
- if (!rect) {
- rect = cc.rect(0, 0, texture.width, texture.height);
- rect = cc.RECT_PIXELS_TO_POINTS(rect);
- }
- return this.initWithTexture(texture, rect);
+ if (!rect) {
+ var size = texture.getContentSize();
+ rect = cc.rect(0, 0, size.width, size.height);
}
+ return this.initWithTexture(texture, rect);
}
return false;
},
@@ -978,7 +984,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
rotated = rotated || false;
- if(!cc.NodeRGBA.prototype.init.call(this))
+ if (!cc.NodeRGBA.prototype.init.call(this))
return false;
this._batchNode = null;
@@ -1001,8 +1007,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
if (!rect) {
rect = cc.rect(0, 0, 0, 0);
- if ((texture instanceof HTMLImageElement) || (texture instanceof HTMLCanvasElement)) {
- rect.size = cc.size(texture.width, texture.height);
+ rect.size = texture.getContentSize();
rect = cc.RECT_PIXELS_TO_POINTS(rect);
}
}
@@ -1120,7 +1125,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
this.setNodeDirty();
},
- updateDisplayedColor:function(parentColor){
+ updateDisplayedColor:function (parentColor) {
cc.NodeRGBA.prototype.updateDisplayedColor.call(this, parentColor);
this._changeTextureColor();
this.setNodeDirty();
@@ -1211,14 +1216,9 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
*/
setTexture:function (texture) {
// CCSprite: setTexture doesn't work when the sprite is rendered using a CCSpriteSheet
- cc.Assert(!texture || texture instanceof HTMLImageElement || texture instanceof HTMLCanvasElement, "setTexture expects a CCTexture2D. Invalid argument");
-
+ cc.Assert(!texture || texture instanceof cc.Texture2D, "setTexture expects a CCTexture2D. Invalid argument");
if (this._texture != texture) {
- if (texture instanceof HTMLImageElement) {
- if (!this._rect || cc.rectEqualToRect(this._rect, cc.RectZero())) {
- this._rect = cc.rect(0, 0, texture.width, texture.height);
- this._rect = cc.RECT_PIXELS_TO_POINTS(this._rect);
- }
+ if(texture&&texture.getHtmlElementObj() instanceof HTMLImageElement){
this._originalTexture = texture;
}
this._texture = texture;
@@ -1226,17 +1226,25 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
},
_changeTextureColor:function () {
- if (this.getTexture()) {
- var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(this._originalTexture);
+ var locElement, locTexture = this._texture;
+ if (locTexture) {
+ locElement = locTexture.getHtmlElementObj();
+ if (!locElement)
+ return;
+
+ var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(this._originalTexture.getHtmlElementObj());
if (cacheTextureForColor) {
this._colorized = true;
//generate color texture cache
- var rect = cc.RECT_POINTS_TO_PIXELS(this._rect);
- if (this._texture instanceof HTMLCanvasElement && !this._rectRotated)
- cc.generateTintImage(this.getTexture(), cacheTextureForColor, this._displayedColor, rect, this._texture);
+ if (locElement instanceof HTMLCanvasElement && !this._rectRotated)
+ cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, this.getTextureRect(), locElement);
else {
- var colorTexture = cc.generateTintImage(this.getTexture(), cacheTextureForColor, this._displayedColor, rect);
- this.setTexture(colorTexture);
+
+ locElement = cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, this.getTextureRect());
+ locTexture = new cc.Texture2D();
+ locTexture.initWithElement(locElement);
+ locTexture.handleLoadedTexture();
+ this.setTexture(locTexture);
}
}
}
@@ -1263,13 +1271,13 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
context.scale(1, -1);
}
if (this._texture) {
- var scaleFactor = cc.CONTENT_SCALE_FACTOR();
+ var image = this._texture.getHtmlElementObj();
if (this._colorized) {
- context.drawImage(this._texture,
+ context.drawImage(image,
0, 0, locRect.width * scaleFactor, locRect.height * scaleFactor,
flipXOffset, flipYOffset, locRect.width, locRect.height);
} else {
- context.drawImage(this._texture,
+ context.drawImage(image,
locRect.x * scaleFactor, locRect.y * scaleFactor, locRect.width * scaleFactor, locRect.height * scaleFactor,
flipXOffset, flipYOffset, locRect.width, locRect.height);
}
@@ -1334,28 +1342,28 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
//
// Data used when the sprite is rendered using a CCSpriteSheet
//
- _textureAtlas:null, //cc.SpriteBatchNode texture atlas
+ _textureAtlas:null, //cc.SpriteBatchNode texture atlas
_atlasIndex:0,
_batchNode:null,
- _dirty:false, //Whether the sprite needs to be updated
- _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
+ _dirty:false, //Whether the sprite needs to be updated
+ _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:cc.rect(0, 0, 0, 0), //Retangle of cc.Texture2D
- _rectRotated:false, //Whether the texture is rotated
+ _rect:cc.rect(0, 0, 0, 0), //Retangle of cc.Texture2D
+ _rectRotated:false, //Whether the texture is rotated
// Offset Position (used by Zwoptex)
_offsetPosition:null, // absolute
@@ -1365,8 +1373,8 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
_opacityModifyRGB:false,
// image is flipped
- _flipX:false, //Whether the sprite is flipped horizontally or not.
- _flipY:false, //Whether the sprite is flipped vertically or not.
+ _flipX:false, //Whether the sprite is flipped horizontally or not.
+ _flipY:false, //Whether the sprite is flipped vertically or not.
/**
* Whether or not the Sprite needs to be updated in the Atlas
@@ -1750,7 +1758,7 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
*/
ignoreAnchorPointForPosition:function (relative) {
cc.Assert(!this._batchNode, "ignoreAnchorPointForPosition is invalid in cc.Sprite");
- cc.Node.prototype.ignoreAnchorPointForPosition.call(this,relative);
+ cc.Node.prototype.ignoreAnchorPointForPosition.call(this, relative);
},
/**
@@ -1829,7 +1837,7 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
return this._opacityModifyRGB;
},
- updateDisplayedOpacity:function(parentOpacity){
+ updateDisplayedOpacity:function (parentOpacity) {
cc.NodeRGBA.prototype.updateDisplayedOpacity.call(this, parentOpacity);
this.updateColor();
},
@@ -1877,7 +1885,7 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
},
/// ---- common properties end ----
- _quad:null, // vertex coords, texture coords and color info
+ _quad:null, // vertex coords, texture coords and color info
_quadWebBuffer:null,
_quadDirty:false,
@@ -1946,7 +1954,7 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
* @return {Boolean}
*/
init:function () {
- if(arguments.length > 0)
+ if (arguments.length > 0)
return this.initWithFile(arguments[0], arguments[1]);
cc.NodeRGBA.prototype.init.call(this);
@@ -2051,7 +2059,7 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
rotated = rotated || false;
- if(!cc.NodeRGBA.prototype.init.call(this))
+ if (!cc.NodeRGBA.prototype.init.call(this))
return false;
this._batchNode = null;
@@ -2252,11 +2260,10 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
updateColor:function () {
var color4 = {r:this._displayedColor.r, g:this._displayedColor.g, b:this._displayedColor.b, a:this._displayedOpacity};
// special opacity for premultiplied textures
- if (this._opacityModifyRGB)
- {
- color4.r *= this._displayedOpacity/255.0;
- color4.g *= this._displayedOpacity/255.0;
- color4.b *= this._displayedOpacity/255.0;
+ if (this._opacityModifyRGB) {
+ color4.r *= this._displayedOpacity / 255.0;
+ color4.g *= this._displayedOpacity / 255.0;
+ color4.b *= this._displayedOpacity / 255.0;
}
this._quad.bl.colors = color4;
this._quad.br.colors = color4;
@@ -2297,7 +2304,7 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
this.updateColor();
},
- updateDisplayedColor:function(parentColor){
+ updateDisplayedColor:function (parentColor) {
cc.NodeRGBA.prototype.updateDisplayedColor.call(this, parentColor);
this.updateColor();
},
@@ -2390,7 +2397,7 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
// If batchnode, then texture id should be the same
cc.Assert(!this._batchNode, "cc.Sprite: Batched sprites should use the same texture as the batchnode");
- if(texture)
+ if (texture)
this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_TEXTURECOLOR));
else
this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_COLOR));
@@ -2504,7 +2511,7 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
//cc.Assert(!this._batchNode, "If cc.Sprite is being rendered by cc.SpriteBatchNode, cc.Sprite#draw SHOULD NOT be called");
if (locTexture) {
- if(locTexture._isLoaded){
+ if (locTexture._isLoaded) {
this._shaderProgram.use();
this._shaderProgram.setUniformForModelViewAndProjectionMatrixWithMat4();
@@ -2514,7 +2521,7 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSCOLORTEX);
gl.bindBuffer(gl.ARRAY_BUFFER, this._quadWebBuffer);
- if(this._quadDirty){
+ if (this._quadDirty) {
gl.bufferData(gl.ARRAY_BUFFER, this._quad.arrayBuffer, gl.DYNAMIC_DRAW);
this._quadDirty = false;
}
@@ -2534,7 +2541,7 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_COLOR);
gl.bindBuffer(gl.ARRAY_BUFFER, this._quadWebBuffer);
- if(this._quadDirty){
+ if (this._quadDirty) {
cc.renderContext.bufferData(cc.renderContext.ARRAY_BUFFER, this._quad.arrayBuffer, cc.renderContext.STATIC_DRAW);
this._quadDirty = false;
}
@@ -2543,7 +2550,7 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
}
cc.g_NumberOfDraws++;
- if(cc.SPRITE_DEBUG_DRAW === 0)
+ if (cc.SPRITE_DEBUG_DRAW === 0)
return;
if (cc.SPRITE_DEBUG_DRAW === 1) {
diff --git a/cocos2d/sprite_nodes/CCSpriteFrameCache.js b/cocos2d/sprite_nodes/CCSpriteFrameCache.js
index c6d7b9da23..f0dc3faadb 100644
--- a/cocos2d/sprite_nodes/CCSpriteFrameCache.js
+++ b/cocos2d/sprite_nodes/CCSpriteFrameCache.js
@@ -138,10 +138,16 @@ cc.SpriteFrameCache = cc.Class.extend(/** @lends cc.SpriteFrameCache# */{
if(cc.renderContextType === cc.CANVAS && spriteFrame.isRotated()){
//clip to canvas
- var tempTexture = cc.cutRotateImageToCanvas(spriteFrame.getTexture(), spriteFrame.getRect());
+ var tempElement = spriteFrame.getTexture().getHtmlElementObj();
+ tempElement = cc.cutRotateImageToCanvas(tempElement, spriteFrame.getRect());
+ var tempTexture = new cc.Texture2D();
+ tempTexture.initWithElement(tempElement);
+ tempTexture.handleLoadedTexture();
+ spriteFrame.setTexture(tempTexture);
+
var rect = spriteFrame.getRect();
spriteFrame.setRect(cc.rect(0, 0, rect.width, rect.height));
- spriteFrame.setTexture(tempTexture);
+
}
// add sprite frame
@@ -225,7 +231,8 @@ cc.SpriteFrameCache = cc.Class.extend(/** @lends cc.SpriteFrameCache# */{
}
break;
case 2:
- if ((texture instanceof cc.Texture2D) || (texture instanceof HTMLImageElement) || (texture instanceof HTMLCanvasElement)) {
+ //if ((texture instanceof cc.Texture2D) || (texture instanceof HTMLImageElement) || (texture instanceof HTMLCanvasElement)) {
+ if (texture instanceof cc.Texture2D) {
/** Adds multiple Sprite Frames from a plist file. The texture will be associated with the created sprite frames. */
this._addSpriteFramesWithDictionary(dict, texture);
} else {
diff --git a/cocos2d/textures/CCTexture2D.js b/cocos2d/textures/CCTexture2D.js
index 03fc2d2867..8d56928595 100644
--- a/cocos2d/textures/CCTexture2D.js
+++ b/cocos2d/textures/CCTexture2D.js
@@ -170,9 +170,9 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
this._webTextureObj = null;
},
- releaseTexture:function(){
- if(this._webTextureObj)
- cc.renderContext.deleteTexture(this._webTextureObj);
+ releaseTexture:function () {
+ if (this._webTextureObj)
+ cc.renderContext.deleteTexture(this._webTextureObj);
},
/**
@@ -185,7 +185,7 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
/**
* width in pixels
- * @return {Number}
+ * @return {Number}
*/
getPixelsWide:function () {
return this._pixelsWide;
@@ -211,7 +211,7 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
* content size
* @return {cc.Size}
*/
- getContentSize:function(){
+ getContentSize:function () {
return cc.size(this._contentSize.width / cc.CONTENT_SCALE_FACTOR(), this._contentSize.height / cc.CONTENT_SCALE_FACTOR());
},
@@ -241,7 +241,7 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
* return shader program used by drawAtPoint and drawInRect
* @return {cc.GLProgram}
*/
- getShaderProgram:function(){
+ getShaderProgram:function () {
return this._shaderProgram;
},
@@ -249,7 +249,7 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
* set shader program used by drawAtPoint and drawInRect
* @param {cc.GLProgram} shaderProgram
*/
- setShaderProgram:function(shaderProgram){
+ setShaderProgram:function (shaderProgram) {
this._shaderProgram = shaderProgram;
},
@@ -261,7 +261,7 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
return this._hasPremultipliedAlpha;
},
- hasMipmaps:function(){
+ hasMipmaps:function () {
return this._hasMipmaps;
},
@@ -293,64 +293,66 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
* @return {Boolean}
*/
initWithData:function (data, pixelFormat, pixelsWide, pixelsHigh, contentSize) {
- var gl = cc.renderContext;
-
- var bitsPerPixel = 0;
- //Hack: bitsPerPixelForFormat returns wrong number for RGB_888 textures. See function.
- if(pixelFormat === cc.TEXTURE_2D_PIXEL_FORMAT_RGBA8888){
- bitsPerPixel = 24;
- }else{
- bitsPerPixel = this.bitsPerPixelForFormat(pixelFormat);
- }
+ if (cc.Browser.supportWebGL) {
+ var gl = cc.renderContext;
- var bytesPerRow = pixelsWide * bitsPerPixel/8;
- if(bytesPerRow % 8 === 0){
- gl.pixelStorei(gl.UNPACK_ALIGNMENT,8);
- } else if(bytesPerRow % 4 === 0){
- gl.pixelStorei(gl.UNPACK_ALIGNMENT,4);
- } else if(bytesPerRow % 2 === 0){
- gl.pixelStorei(gl.UNPACK_ALIGNMENT,2);
- } else {
- gl.pixelStorei(gl.UNPACK_ALIGNMENT,1);
- }
-
- this._webTextureObj = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, this._webTextureObj);
+ var bitsPerPixel = 0;
+ //Hack: bitsPerPixelForFormat returns wrong number for RGB_888 textures. See function.
+ if (pixelFormat === cc.TEXTURE_2D_PIXEL_FORMAT_RGBA8888) {
+ bitsPerPixel = 24;
+ } else {
+ bitsPerPixel = this.bitsPerPixelForFormat(pixelFormat);
+ }
- gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR );
- gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR );
- gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE );
- gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE );
+ var bytesPerRow = pixelsWide * bitsPerPixel / 8;
+ if (bytesPerRow % 8 === 0) {
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 8);
+ } else if (bytesPerRow % 4 === 0) {
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
+ } else if (bytesPerRow % 2 === 0) {
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 2);
+ } else {
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
+ }
- // Specify OpenGL texture image
- switch (pixelFormat) {
- case cc.TEXTURE_2D_PIXEL_FORMAT_RGBA8888:
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, pixelsWide, pixelsHigh, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
- break;
- case cc.TEXTURE_2D_PIXEL_FORMAT_RGB888:
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, pixelsWide, pixelsHigh, 0, gl.RGB, gl.UNSIGNED_BYTE, data);
- break;
- case cc.TEXTURE_2D_PIXEL_FORMAT_RGBA4444:
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, pixelsWide, pixelsHigh, 0, gl.RGBA, gl.UNSIGNED_SHORT_4_4_4_4, data);
- break;
- case cc.TEXTURE_2D_PIXEL_FORMAT_RGB5A1:
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, pixelsWide, pixelsHigh, 0, gl.RGBA, gl.UNSIGNED_SHORT_5_5_5_1, data);
- break;
- case cc.TEXTURE_2D_PIXEL_FORMAT_RGB565:
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, pixelsWide, pixelsHigh, 0, gl.RGB, gl.UNSIGNED_SHORT_5_6_5, data);
- break;
- case cc.TEXTURE_2D_PIXEL_FORMAT_AI88:
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE_ALPHA, pixelsWide, pixelsHigh, 0, gl.LUMINANCE_ALPHA, gl.UNSIGNED_BYTE, data);
- break;
- case cc.TEXTURE_2D_PIXEL_FORMAT_A8:
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA, pixelsWide, pixelsHigh, 0, gl.ALPHA, gl.UNSIGNED_BYTE, data);
- break;
- case cc.TEXTURE_2D_PIXEL_FORMAT_I8:
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE, pixelsWide, pixelsHigh, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, data);
- break;
- default:
- cc.Assert(0, "NSInternalInconsistencyException");
- break;
+ this._webTextureObj = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, this._webTextureObj);
+
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+
+ // Specify OpenGL texture image
+ switch (pixelFormat) {
+ case cc.TEXTURE_2D_PIXEL_FORMAT_RGBA8888:
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, pixelsWide, pixelsHigh, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
+ break;
+ case cc.TEXTURE_2D_PIXEL_FORMAT_RGB888:
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, pixelsWide, pixelsHigh, 0, gl.RGB, gl.UNSIGNED_BYTE, data);
+ break;
+ case cc.TEXTURE_2D_PIXEL_FORMAT_RGBA4444:
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, pixelsWide, pixelsHigh, 0, gl.RGBA, gl.UNSIGNED_SHORT_4_4_4_4, data);
+ break;
+ case cc.TEXTURE_2D_PIXEL_FORMAT_RGB5A1:
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, pixelsWide, pixelsHigh, 0, gl.RGBA, gl.UNSIGNED_SHORT_5_5_5_1, data);
+ break;
+ case cc.TEXTURE_2D_PIXEL_FORMAT_RGB565:
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, pixelsWide, pixelsHigh, 0, gl.RGB, gl.UNSIGNED_SHORT_5_6_5, data);
+ break;
+ case cc.TEXTURE_2D_PIXEL_FORMAT_AI88:
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE_ALPHA, pixelsWide, pixelsHigh, 0, gl.LUMINANCE_ALPHA, gl.UNSIGNED_BYTE, data);
+ break;
+ case cc.TEXTURE_2D_PIXEL_FORMAT_A8:
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA, pixelsWide, pixelsHigh, 0, gl.ALPHA, gl.UNSIGNED_BYTE, data);
+ break;
+ case cc.TEXTURE_2D_PIXEL_FORMAT_I8:
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE, pixelsWide, pixelsHigh, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, data);
+ break;
+ default:
+ cc.Assert(0, "NSInternalInconsistencyException");
+ break;
+ }
}
this._contentSize = contentSize;
@@ -394,11 +396,11 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
point.x, height + point.y, 0.0,
width + point.x, height + point.y, 0.0 ];
- cc.glEnableVertexAttribs( cc.VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_TEXCOORDS );
+ cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_TEXCOORDS);
this._shaderProgram.use();
this._shaderProgram.setUniformsForBuiltins();
- cc.glBindTexture2D( this );
+ cc.glBindTexture2D(this);
var gl = cc.renderContext;
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, vertices);
@@ -423,11 +425,11 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
rect.x, rect.y + rect.height, /*0.0,*/
rect.x + rect.width, rect.y + rect.height /*0.0*/ ];
- cc.glEnableVertexAttribs( cc.VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_TEXCOORDS );
+ cc.glEnableVertexAttribs(cc.VERTEX_ATTRIB_FLAG_POSITION | cc.VERTEX_ATTRIB_FLAG_TEXCOORDS);
this._shaderProgram.use();
this._shaderProgram.setUniformsForBuiltins();
- cc.glBindTexture2D( this );
+ cc.glBindTexture2D(this);
var gl = cc.renderContext;
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, vertices);
@@ -459,7 +461,7 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
var maxTextureSize = conf.getMaxTextureSize();
if (imageWidth > maxTextureSize || imageHeight > maxTextureSize) {
- cc.log("cocos2d: WARNING: Image (" + imageWidth + " x " + imageHeight+ ") is bigger than the supported " + maxTextureSize + " x " + maxTextureSize);
+ cc.log("cocos2d: WARNING: Image (" + imageWidth + " x " + imageHeight + ") is bigger than the supported " + maxTextureSize + " x " + maxTextureSize);
return false;
}
this._isLoaded = true;
@@ -468,39 +470,53 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
return this._initPremultipliedATextureWithImage(uiImage, imageWidth, imageHeight);
},
- initWithElement:function(element){
- if(!element)
+ initWithElement:function (element) {
+ if (!element)
return;
-
- this._webTextureObj = cc.renderContext.createTexture();
+ if (cc.Browser.supportWebGL) {
+ this._webTextureObj = cc.renderContext.createTexture();
+ }
this._htmlElementObj = element;
},
- isLoaded:function(){
- return this._isLoaded;
+ /**
+ * HTMLElement Object getter
+ * @return {HTMLElement}
+ */
+ getHtmlElementObj:function(){
+ return this._htmlElementObj;
+ },
+
+ isLoaded:function () {
+ return this._isLoaded;
},
- handleLoadedTexture:function(){
+ handleLoadedTexture:function () {
this._isLoaded = true;
//upload image to buffer
- var gl = cc.renderContext;
+ if (cc.Browser.supportWebGL) {
+ var gl = cc.renderContext;
- var pixelsWide = this._htmlElementObj.width;
- var pixelsHigh = this._htmlElementObj.height;
+ cc.glBindTexture2D(this);
- cc.glBindTexture2D(this);
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
+
+ // Specify OpenGL texture image
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._htmlElementObj);
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- // Specify OpenGL texture image
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._htmlElementObj);
+ this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_TEXTURE));
+ gl.bindTexture(gl.TEXTURE_2D, null);
+ }
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ var pixelsWide = this._htmlElementObj.width;
+ var pixelsHigh = this._htmlElementObj.height;
- this._contentSize = new cc.Size(pixelsWide,pixelsHigh);
+ this._contentSize = new cc.Size(pixelsWide, pixelsHigh);
this._pixelsWide = pixelsWide;
this._pixelsHigh = pixelsHigh;
this._pixelFormat = cc.TEXTURE_2D_PIXEL_FORMAT_RGBA8888;
@@ -510,9 +526,6 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
this._hasPremultipliedAlpha = false;
this._hasMipmaps = false;
- this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_TEXTURE));
-
- gl.bindTexture(gl.TEXTURE_2D, null);
},
/**
@@ -539,20 +552,20 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
}
/*if (cc.ENABLE_CACHE_TEXTURE_DATA) {
- // cache the texture data
- cc.VolatileTexture.addStringTexture(this, text, dimensions, alignment, fontName, fontSize);
- }*/
+ // cache the texture data
+ cc.VolatileTexture.addStringTexture(this, text, dimensions, alignment, fontName, fontSize);
+ }*/
var image = new cc.Image();
- var eAlign ;
+ var eAlign;
- if(cc.VERTICAL_TEXT_ALIGNMENT_TOP === vAlignment){
+ if (cc.VERTICAL_TEXT_ALIGNMENT_TOP === vAlignment) {
eAlign = (cc.TEXT_ALIGNMENT_CENTER === hAlignment) ? cc.ALIGN_TOP
: (cc.TEXT_ALIGNMENT_LEFT === hAlignment) ? cc.ALIGN_TOP_LEFT : cc.ALIGN_TOP_RIGHT;
- }else if(cc.VERTICAL_TEXT_ALIGNMENT_CENTER === vAlignment){
+ } else if (cc.VERTICAL_TEXT_ALIGNMENT_CENTER === vAlignment) {
eAlign = (cc.TEXT_ALIGNMENT_CENTER === hAlignment) ? cc.ALIGN_CENTER
: (cc.TEXT_ALIGNMENT_LEFT === hAlignment) ? cc.ALIGN_LEFT : cc.ALIGN_RIGHT;
- }else if(cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM === vAlignment){
+ } else if (cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM === vAlignment) {
eAlign = (cc.TEXT_ALIGNMENT_CENTER === hAlignment) ? cc.ALIGN_BOTTOM
: (cc.TEXT_ALIGNMENT_LEFT === hAlignment) ? cc.ALIGN_BOTTOM_LEFT : cc.ALIGN_BOTTOM_RIGHT;
} else {
@@ -571,7 +584,7 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
* @param {String} file
* @return {Boolean}
*/
- initWithETCFile:function(file){
+ initWithETCFile:function (file) {
return false;
},
@@ -635,20 +648,22 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
* @param texParams
*/
setTexParameters:function (texParams) {
- var gl = cc.renderContext;
+ if (cc.Browser.supportWebGL) {
+ var gl = cc.renderContext;
- cc.Assert((this._pixelsWide == cc.NextPOT(this._pixelsWide) && this._pixelsHigh == cc.NextPOT(this._pixelsHigh)) ||
- (texParams.wrapS == gl.CLAMP_TO_EDGE && texParams.wrapT == gl.CLAMP_TO_EDGE),
- "WebGLRenderingContext.CLAMP_TO_EDGE should be used in NPOT textures");
+ cc.Assert((this._pixelsWide == cc.NextPOT(this._pixelsWide) && this._pixelsHigh == cc.NextPOT(this._pixelsHigh)) ||
+ (texParams.wrapS == gl.CLAMP_TO_EDGE && texParams.wrapT == gl.CLAMP_TO_EDGE),
+ "WebGLRenderingContext.CLAMP_TO_EDGE should be used in NPOT textures");
- cc.glBindTexture2D(this);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texParams.minFilter);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texParams.magFilter);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, texParams.wrapS);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, texParams.wrapT);
+ cc.glBindTexture2D(this);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texParams.minFilter);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texParams.magFilter);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, texParams.wrapS);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, texParams.wrapT);
- //TODO
- //VolatileTexture::setTexParameters(this, texParams);
+ //TODO
+ //VolatileTexture::setTexParameters(this, texParams);
+ }
},
/**
@@ -657,19 +672,21 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
* - GL_TEXTURE_MAG_FILTER = GL_NEAREST
*/
setAntiAliasTexParameters:function () {
- var gl = cc.renderContext;
-
- cc.glBindTexture2D(this);
- if(!this._hasMipmaps)
- gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- else
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
- gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
- //TODO
- /*#if CC_ENABLE_CACHE_TEXTURE_DATA
- ccTexParams texParams = {m_bHasMipmaps?GL_LINEAR_MIPMAP_NEAREST:GL_LINEAR,GL_LINEAR,GL_NONE,GL_NONE};
- VolatileTexture::setTexParameters(this, &texParams);
- #endif*/
+ if (cc.Browser.supportWebGL) {
+ var gl = cc.renderContext;
+
+ cc.glBindTexture2D(this);
+ if (!this._hasMipmaps)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ else
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+ //TODO
+ /*#if CC_ENABLE_CACHE_TEXTURE_DATA
+ ccTexParams texParams = {m_bHasMipmaps?GL_LINEAR_MIPMAP_NEAREST:GL_LINEAR,GL_LINEAR,GL_NONE,GL_NONE};
+ VolatileTexture::setTexParameters(this, &texParams);
+ #endif*/
+ }
},
/**
@@ -677,21 +694,23 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
* GL_TEXTURE_MIN_FILTER = GL_NEAREST
* GL_TEXTURE_MAG_FILTER = GL_NEAREST
*/
- setAliasTexParameters:function(){
- var gl = cc.renderContext;
-
- cc.glBindTexture2D(this);
- if(!this._hasMipmaps)
- gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER, gl.NEAREST);
- else
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_NEAREST);
- gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST );
-
- //TODO
- /*#if CC_ENABLE_CACHE_TEXTURE_DATA
- ccTexParams texParams = {m_bHasMipmaps?GL_NEAREST_MIPMAP_NEAREST:GL_NEAREST,GL_NEAREST,GL_NONE,GL_NONE};
- VolatileTexture::setTexParameters(this, &texParams);
- #endif*/
+ setAliasTexParameters:function () {
+ if (cc.Browser.supportWebGL) {
+ var gl = cc.renderContext;
+
+ cc.glBindTexture2D(this);
+ if (!this._hasMipmaps)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
+ else
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+
+ //TODO
+ /*#if CC_ENABLE_CACHE_TEXTURE_DATA
+ ccTexParams texParams = {m_bHasMipmaps?GL_NEAREST_MIPMAP_NEAREST:GL_NEAREST,GL_NEAREST,GL_NONE,GL_NONE};
+ VolatileTexture::setTexParameters(this, &texParams);
+ #endif*/
+ }
},
/**
@@ -699,18 +718,20 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
* It only works if the texture size is POT (power of 2).
*/
generateMipmap:function () {
- cc.Assert(this._pixelsWide == cc.NextPOT(this._pixelsWide) && this._pixelsHigh == cc.NextPOT(this._pixelsHigh), "Mimpap texture only works in POT textures");
+ if (cc.Browser.supportWebGL) {
+ cc.Assert(this._pixelsWide == cc.NextPOT(this._pixelsWide) && this._pixelsHigh == cc.NextPOT(this._pixelsHigh), "Mimpap texture only works in POT textures");
- cc.glBindTexture2D(this);
- cc.renderContext.generateMipmap(cc.renderContext.TEXTURE_2D);
- this._hasMipmaps = true;
+ cc.glBindTexture2D(this);
+ cc.renderContext.generateMipmap(cc.renderContext.TEXTURE_2D);
+ this._hasMipmaps = true;
+ }
},
/**
* returns the pixel format.
* @return {String}
*/
- stringForFormat:function(){
+ stringForFormat:function () {
switch (this._pixelFormat) {
case cc.TEXTURE_2D_PIXEL_FORMAT_RGBA8888:
return "RGBA8888";
@@ -743,11 +764,11 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
return "PVRTC2";
default:
- cc.Assert(false , "unrecognized pixel format");
+ cc.Assert(false, "unrecognized pixel format");
cc.log("stringForFormat: " + this._pixelFormat + ", cannot give useful result");
break;
}
- return "";
+ return "";
},
/**
diff --git a/cocos2d/textures/CCTextureCache.js b/cocos2d/textures/CCTextureCache.js
index dd7a4b2cde..6c8925edf6 100644
--- a/cocos2d/textures/CCTextureCache.js
+++ b/cocos2d/textures/CCTextureCache.js
@@ -295,7 +295,9 @@ cc.TextureCacheCanvas = cc.Class.extend(/** @lends cc.TextureCacheCanvas# */{
delete that._textures[path];
});
texture.src = path;
- this._textures[path] = texture;
+ var texture2d = new cc.Texture2D();
+ texture2d.initWithElement(texture);
+ this._textures[path] = texture2d;
}
return this._textures[path];
},
@@ -327,6 +329,8 @@ cc.TextureCacheCanvas = cc.Class.extend(/** @lends cc.TextureCacheCanvas# */{
var that = this;
texture.addEventListener("load", function () {
cc.Loader.getInstance().onResLoaded();
+ if (that._textures.hasOwnProperty(path))
+ that._textures[path].handleLoadedTexture();
});
texture.addEventListener("error", function () {
cc.Loader.getInstance().onResLoadingErr(path);
@@ -335,7 +339,9 @@ cc.TextureCacheCanvas = cc.Class.extend(/** @lends cc.TextureCacheCanvas# */{
delete that._textures[path];
});
texture.src = path;
- this._textures[path] = texture;
+ var texture2d = new cc.Texture2D();
+ texture2d.initWithElement(texture);
+ this._textures[path] = texture2d;
}
return this._textures[path];
@@ -347,7 +353,14 @@ cc.TextureCacheCanvas = cc.Class.extend(/** @lends cc.TextureCacheCanvas# */{
* @param {Image|HTMLImageElement|HTMLCanvasElement} texture
*/
cacheImage:function (path, texture) {
- this._textures[path] = texture;
+ if(texture instanceof cc.Texture2D){
+ this._textures[path] = texture;
+ return ;
+ }
+ var texture2d = new cc.Texture2D();
+ texture2d.initWithElement(texture);
+ texture2d.handleLoadedTexture();
+ this._textures[path] = texture2d;
},
/**
@@ -363,16 +376,19 @@ cc.TextureCacheCanvas = cc.Class.extend(/** @lends cc.TextureCacheCanvas# */{
addUIImage:function (image, key) {
cc.Assert(image != null, "TextureCache: image MUST not be nulll");
- if (key && this._textures.hasOwnProperty(key) && this._textures[key])
- return this._textures[key];
+ if (key) {
+ if (this._textures.hasOwnProperty(key) && this._textures[key])
+ return this._textures[key];
+ }
// prevents overloading the autorelease pool
- if ((key != null) && (image != null))
- this._textures[key] = image;
+ var texture = new cc.Texture2D();
+ texture.initWithImage(image);
+ if ((key != null) && (texture != null))
+ this._textures[key] = texture;
else
cc.log("cocos2d: Couldn't add UIImage in TextureCache");
-
- return image;
+ return texture;
},
/**
@@ -385,19 +401,19 @@ cc.TextureCacheCanvas = cc.Class.extend(/** @lends cc.TextureCacheCanvas# */{
for (var key in this._textures) {
var selTexture = this._textures[key];
count++;
- if (selTexture instanceof HTMLImageElement)
- cc.log("cocos2d: '" + key + "' id=" + selTexture.src + " " + selTexture.width + " x " + selTexture.height);
+ if (selTexture.getHtmlElementObj() instanceof HTMLImageElement)
+ cc.log("cocos2d: '" + key + "' id=" + selTexture.getHtmlElementObj().src + " " + selTexture.getPixelsWide() + " x " + selTexture.getPixelsHigh());
else {
- cc.log("cocos2d: '" + key + "' id= HTMLCanvasElement " + selTexture.width + " x " + selTexture.height);
- totalBytes += selTexture.width * selTexture.height * 4;
+ cc.log("cocos2d: '" + key + "' id= HTMLCanvasElement " + selTexture.getPixelsWide() + " x " + selTexture.getPixelsHigh());
+ totalBytes += selTexture.getPixelsWide() * selTexture.getPixelsHigh() * 4;
}
}
for (key in this._textureColorsCache) {
var selCanvas = this._textureColorsCache[key];
count++;
- cc.log("cocos2d: '" + key + "' id= HTMLCanvasElement " + selCanvas.width + " x " + selCanvas.height);
- totalBytes += selCanvas.width * selCanvas.height * 4;
+ cc.log("cocos2d: '" + key + "' id= HTMLCanvasElement " + selCanvas.getPixelsWide() + " x " + selCanvas.getPixelsHigh());
+ totalBytes += selCanvas.getPixelsWide() * selCanvas.getPixelsHigh() * 4;
}
cc.log("cocos2d: TextureCache dumpDebugInfo: " + count + " textures, HTMLCanvasElement for "
diff --git a/cocos2d/tileMap_parallax_nodes/CCTMXLayer.js b/cocos2d/tileMap_parallax_nodes/CCTMXLayer.js
index 47aa16b306..6a54eb99f4 100644
--- a/cocos2d/tileMap_parallax_nodes/CCTMXLayer.js
+++ b/cocos2d/tileMap_parallax_nodes/CCTMXLayer.js
@@ -525,8 +525,7 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{
setupTiles:function () {
// Optimization: quick hack that sets the image size on the tileset
if (cc.renderContextType === cc.CANVAS) {
- var textureCache = this._originalTexture;
- this._tileSet.imageSize = cc.size(textureCache.width, textureCache.height);
+ this._tileSet.imageSize = this._originalTexture.getContentSizeInPixels();
} else {
this._tileSet.imageSize = this._textureAtlas.getTexture().getContentSizeInPixels();
diff --git a/extensions/CCBReader/CCBReader.js b/extensions/CCBReader/CCBReader.js
index 6d791ed86e..d2fb41301b 100644
--- a/extensions/CCBReader/CCBReader.js
+++ b/extensions/CCBReader/CCBReader.js
@@ -634,11 +634,7 @@ cc.BuilderReader = cc.Class.extend({
if (spriteSheet == "") {
spriteFile = this._ccbRootPath + spriteFile;
var texture = cc.TextureCache.getInstance().addImage(spriteFile);
- var bounds;
- if (cc.renderContextType == cc.CANVAS)
- bounds = cc.RectMake(0, 0, texture.width, texture.height);
- else
- bounds = cc.RectMake(0, 0, texture.getContentSize().width, texture.getContentSize().height);
+ var bounds = cc.RectMake(0, 0, texture.getContentSize().width, texture.getContentSize().height);
value = cc.SpriteFrame.createWithTexture(texture, bounds);
} else {
spriteSheet = this._ccbRootPath + spriteSheet;
diff --git a/extensions/GUI/CCControlExtension/CCControlSwitch.js b/extensions/GUI/CCControlExtension/CCControlSwitch.js
index eaa20a029d..d551196e1e 100644
--- a/extensions/GUI/CCControlExtension/CCControlSwitch.js
+++ b/extensions/GUI/CCControlExtension/CCControlSwitch.js
@@ -222,11 +222,7 @@ cc.ControlSwitchSprite = cc.Sprite.extend({
//this._maskLocation = cc.renderContext.getUniformLocation(this.getShaderProgram().getProgram(), "u_mask");
//cc.CHECK_GL_ERROR_DEBUG();
- if(cc.renderContextType==cc.CANVAS){
- this.setContentSize(cc.size(this._maskTexture.width,this._maskTexture.height));
- }else{
- this.setContentSize(this._maskTexture.getContentSize());
- }
+ this.setContentSize(this._maskTexture.getContentSize());
this.needsLayout();
return true;
@@ -283,17 +279,10 @@ cc.ControlSwitchSprite = cc.Sprite.extend({
this._offLabel.setPosition(cc.p(this._offSprite.getPosition().x + this._thumbSprite.getContentSize().width / 6,
this._offSprite.getContentSize().height / 2));
}
- var rt ;
- if(cc.renderContextType==cc.CANVAS){
- this._thumbSprite.setPosition(cc.p(this._onSprite.getContentSize().width + this._sliderXPosition,
- this._maskTexture.height / 2));
- rt = cc.RenderTexture.create(this._maskTexture.width, this._maskTexture.height);
- }else{
- this._thumbSprite.setPosition(cc.p(this._onSprite.getContentSize().width + this._sliderXPosition,
- this._maskTexture.getContentSize().height / 2));
- rt = cc.RenderTexture.create(this._maskTexture.getContentSize().width, this._maskTexture.getContentSize().height);
- }
-
+ var locMaskSize = this._maskTexture.getContentSize();
+ this._thumbSprite.setPosition(cc.p(this._onSprite.getContentSize().width + this._sliderXPosition,
+ locMaskSize.height / 2));
+ var rt = cc.RenderTexture.create(locMaskSize.width, locMaskSize.height);
rt.begin();
this._onSprite.visit();
diff --git a/extensions/GUI/CCControlExtension/CCScale9Sprite.js b/extensions/GUI/CCControlExtension/CCScale9Sprite.js
index 1a88e7a41b..bc26ba5c56 100644
--- a/extensions/GUI/CCControlExtension/CCScale9Sprite.js
+++ b/extensions/GUI/CCControlExtension/CCScale9Sprite.js
@@ -461,13 +461,8 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
// If there is no given rect
if (cc.rectEqualToRect(rect, rectZero)) {
// Get the texture size as original
- if (selTexture instanceof cc.Texture2D) {
- var textureSize = selTexture.getContentSize();
- rect = cc.RectMake(0, 0, textureSize.width, textureSize.height);
- } else {
- rect = cc.RectMake(0, 0, selTexture.width, selTexture.height);
- rect = cc.RECT_PIXELS_TO_POINTS(rect);
- }
+ var textureSize = selTexture.getContentSize();
+ rect = cc.RectMake(0, 0, textureSize.width, textureSize.height);
}
// Set the given rect's size as original size
diff --git a/samples b/samples
index 714ea94824..703281713b 160000
--- a/samples
+++ b/samples
@@ -1 +1 @@
-Subproject commit 714ea9482432a94a2d58ca265c97c61b5b369919
+Subproject commit 703281713bb75cef546907443ef565b3523124db
From 90649baa78f16e8fe74e7cf47d65e509f1c8a23b Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Wed, 7 Aug 2013 14:14:59 +0800
Subject: [PATCH 029/141] Fixed #2444 Split cc.Texture2D as
cc.Texture2DWebGL and cc.Texture2DCanvas
---
cocos2d/textures/CCTexture2D.js | 562 +++++++++++++++++++++++++-------
1 file changed, 439 insertions(+), 123 deletions(-)
diff --git a/cocos2d/textures/CCTexture2D.js b/cocos2d/textures/CCTexture2D.js
index 8d56928595..a3a93013e9 100644
--- a/cocos2d/textures/CCTexture2D.js
+++ b/cocos2d/textures/CCTexture2D.js
@@ -131,7 +131,7 @@ cc._texParams = function (minFilter, magFilter, wrapS, wrapT) {
* @class
* @extends cc.Class
*/
-cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
+cc.Texture2DWebGL = cc.Class.extend(/** @lends cc.Texture2D# */{
// By default PVR images are treated as if they don't have the alpha channel premultiplied
_pVRHaveAlphaPremultiplied:null,
_pixelFormat:null,
@@ -293,68 +293,67 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
* @return {Boolean}
*/
initWithData:function (data, pixelFormat, pixelsWide, pixelsHigh, contentSize) {
- if (cc.Browser.supportWebGL) {
- var gl = cc.renderContext;
+ var gl = cc.renderContext;
- var bitsPerPixel = 0;
- //Hack: bitsPerPixelForFormat returns wrong number for RGB_888 textures. See function.
- if (pixelFormat === cc.TEXTURE_2D_PIXEL_FORMAT_RGBA8888) {
- bitsPerPixel = 24;
- } else {
- bitsPerPixel = this.bitsPerPixelForFormat(pixelFormat);
- }
+ var bitsPerPixel = 0;
+ //Hack: bitsPerPixelForFormat returns wrong number for RGB_888 textures. See function.
+ if (pixelFormat === cc.TEXTURE_2D_PIXEL_FORMAT_RGBA8888) {
+ bitsPerPixel = 24;
+ } else {
+ bitsPerPixel = this.bitsPerPixelForFormat(pixelFormat);
+ }
- var bytesPerRow = pixelsWide * bitsPerPixel / 8;
- if (bytesPerRow % 8 === 0) {
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 8);
- } else if (bytesPerRow % 4 === 0) {
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
- } else if (bytesPerRow % 2 === 0) {
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 2);
- } else {
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
- }
+ var bytesPerRow = pixelsWide * bitsPerPixel / 8;
+ if (bytesPerRow % 8 === 0) {
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 8);
+ } else if (bytesPerRow % 4 === 0) {
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
+ } else if (bytesPerRow % 2 === 0) {
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 2);
+ } else {
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
+ }
- this._webTextureObj = gl.createTexture();
- gl.bindTexture(gl.TEXTURE_2D, this._webTextureObj);
+ this._webTextureObj = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, this._webTextureObj);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
-
- // Specify OpenGL texture image
- switch (pixelFormat) {
- case cc.TEXTURE_2D_PIXEL_FORMAT_RGBA8888:
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, pixelsWide, pixelsHigh, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
- break;
- case cc.TEXTURE_2D_PIXEL_FORMAT_RGB888:
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, pixelsWide, pixelsHigh, 0, gl.RGB, gl.UNSIGNED_BYTE, data);
- break;
- case cc.TEXTURE_2D_PIXEL_FORMAT_RGBA4444:
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, pixelsWide, pixelsHigh, 0, gl.RGBA, gl.UNSIGNED_SHORT_4_4_4_4, data);
- break;
- case cc.TEXTURE_2D_PIXEL_FORMAT_RGB5A1:
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, pixelsWide, pixelsHigh, 0, gl.RGBA, gl.UNSIGNED_SHORT_5_5_5_1, data);
- break;
- case cc.TEXTURE_2D_PIXEL_FORMAT_RGB565:
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, pixelsWide, pixelsHigh, 0, gl.RGB, gl.UNSIGNED_SHORT_5_6_5, data);
- break;
- case cc.TEXTURE_2D_PIXEL_FORMAT_AI88:
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE_ALPHA, pixelsWide, pixelsHigh, 0, gl.LUMINANCE_ALPHA, gl.UNSIGNED_BYTE, data);
- break;
- case cc.TEXTURE_2D_PIXEL_FORMAT_A8:
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA, pixelsWide, pixelsHigh, 0, gl.ALPHA, gl.UNSIGNED_BYTE, data);
- break;
- case cc.TEXTURE_2D_PIXEL_FORMAT_I8:
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE, pixelsWide, pixelsHigh, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, data);
- break;
- default:
- cc.Assert(0, "NSInternalInconsistencyException");
- break;
- }
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+
+ // Specify OpenGL texture image
+ switch (pixelFormat) {
+ case cc.TEXTURE_2D_PIXEL_FORMAT_RGBA8888:
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, pixelsWide, pixelsHigh, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
+ break;
+ case cc.TEXTURE_2D_PIXEL_FORMAT_RGB888:
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, pixelsWide, pixelsHigh, 0, gl.RGB, gl.UNSIGNED_BYTE, data);
+ break;
+ case cc.TEXTURE_2D_PIXEL_FORMAT_RGBA4444:
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, pixelsWide, pixelsHigh, 0, gl.RGBA, gl.UNSIGNED_SHORT_4_4_4_4, data);
+ break;
+ case cc.TEXTURE_2D_PIXEL_FORMAT_RGB5A1:
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, pixelsWide, pixelsHigh, 0, gl.RGBA, gl.UNSIGNED_SHORT_5_5_5_1, data);
+ break;
+ case cc.TEXTURE_2D_PIXEL_FORMAT_RGB565:
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, pixelsWide, pixelsHigh, 0, gl.RGB, gl.UNSIGNED_SHORT_5_6_5, data);
+ break;
+ case cc.TEXTURE_2D_PIXEL_FORMAT_AI88:
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE_ALPHA, pixelsWide, pixelsHigh, 0, gl.LUMINANCE_ALPHA, gl.UNSIGNED_BYTE, data);
+ break;
+ case cc.TEXTURE_2D_PIXEL_FORMAT_A8:
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.ALPHA, pixelsWide, pixelsHigh, 0, gl.ALPHA, gl.UNSIGNED_BYTE, data);
+ break;
+ case cc.TEXTURE_2D_PIXEL_FORMAT_I8:
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.LUMINANCE, pixelsWide, pixelsHigh, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, data);
+ break;
+ default:
+ cc.Assert(0, "NSInternalInconsistencyException");
+ break;
}
+
this._contentSize = contentSize;
this._pixelsWide = pixelsWide;
this._pixelsHigh = pixelsHigh;
@@ -473,9 +472,7 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
initWithElement:function (element) {
if (!element)
return;
- if (cc.Browser.supportWebGL) {
- this._webTextureObj = cc.renderContext.createTexture();
- }
+ this._webTextureObj = cc.renderContext.createTexture();
this._htmlElementObj = element;
},
@@ -494,24 +491,22 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
handleLoadedTexture:function () {
this._isLoaded = true;
//upload image to buffer
- if (cc.Browser.supportWebGL) {
- var gl = cc.renderContext;
+ var gl = cc.renderContext;
- cc.glBindTexture2D(this);
+ cc.glBindTexture2D(this);
- gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
+ gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
- // Specify OpenGL texture image
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._htmlElementObj);
+ // Specify OpenGL texture image
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this._htmlElementObj);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
- this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_TEXTURE));
- gl.bindTexture(gl.TEXTURE_2D, null);
- }
+ this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_TEXTURE));
+ gl.bindTexture(gl.TEXTURE_2D, null);
var pixelsWide = this._htmlElementObj.width;
var pixelsHigh = this._htmlElementObj.height;
@@ -648,22 +643,20 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
* @param texParams
*/
setTexParameters:function (texParams) {
- if (cc.Browser.supportWebGL) {
- var gl = cc.renderContext;
+ var gl = cc.renderContext;
- cc.Assert((this._pixelsWide == cc.NextPOT(this._pixelsWide) && this._pixelsHigh == cc.NextPOT(this._pixelsHigh)) ||
- (texParams.wrapS == gl.CLAMP_TO_EDGE && texParams.wrapT == gl.CLAMP_TO_EDGE),
- "WebGLRenderingContext.CLAMP_TO_EDGE should be used in NPOT textures");
+ cc.Assert((this._pixelsWide == cc.NextPOT(this._pixelsWide) && this._pixelsHigh == cc.NextPOT(this._pixelsHigh)) ||
+ (texParams.wrapS == gl.CLAMP_TO_EDGE && texParams.wrapT == gl.CLAMP_TO_EDGE),
+ "WebGLRenderingContext.CLAMP_TO_EDGE should be used in NPOT textures");
- cc.glBindTexture2D(this);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texParams.minFilter);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texParams.magFilter);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, texParams.wrapS);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, texParams.wrapT);
+ cc.glBindTexture2D(this);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texParams.minFilter);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texParams.magFilter);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, texParams.wrapS);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, texParams.wrapT);
- //TODO
- //VolatileTexture::setTexParameters(this, texParams);
- }
+ //TODO
+ //VolatileTexture::setTexParameters(this, texParams);
},
/**
@@ -672,21 +665,19 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
* - GL_TEXTURE_MAG_FILTER = GL_NEAREST
*/
setAntiAliasTexParameters:function () {
- if (cc.Browser.supportWebGL) {
- var gl = cc.renderContext;
-
- cc.glBindTexture2D(this);
- if (!this._hasMipmaps)
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
- else
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
- //TODO
- /*#if CC_ENABLE_CACHE_TEXTURE_DATA
- ccTexParams texParams = {m_bHasMipmaps?GL_LINEAR_MIPMAP_NEAREST:GL_LINEAR,GL_LINEAR,GL_NONE,GL_NONE};
- VolatileTexture::setTexParameters(this, &texParams);
- #endif*/
- }
+ var gl = cc.renderContext;
+
+ cc.glBindTexture2D(this);
+ if (!this._hasMipmaps)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ else
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+ //TODO
+ /*#if CC_ENABLE_CACHE_TEXTURE_DATA
+ ccTexParams texParams = {m_bHasMipmaps?GL_LINEAR_MIPMAP_NEAREST:GL_LINEAR,GL_LINEAR,GL_NONE,GL_NONE};
+ VolatileTexture::setTexParameters(this, &texParams);
+ #endif*/
},
/**
@@ -695,22 +686,20 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
* GL_TEXTURE_MAG_FILTER = GL_NEAREST
*/
setAliasTexParameters:function () {
- if (cc.Browser.supportWebGL) {
- var gl = cc.renderContext;
-
- cc.glBindTexture2D(this);
- if (!this._hasMipmaps)
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
- else
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_NEAREST);
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
-
- //TODO
- /*#if CC_ENABLE_CACHE_TEXTURE_DATA
- ccTexParams texParams = {m_bHasMipmaps?GL_NEAREST_MIPMAP_NEAREST:GL_NEAREST,GL_NEAREST,GL_NONE,GL_NONE};
- VolatileTexture::setTexParameters(this, &texParams);
- #endif*/
- }
+ var gl = cc.renderContext;
+
+ cc.glBindTexture2D(this);
+ if (!this._hasMipmaps)
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
+ else
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_NEAREST);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
+
+ //TODO
+ /*#if CC_ENABLE_CACHE_TEXTURE_DATA
+ ccTexParams texParams = {m_bHasMipmaps?GL_NEAREST_MIPMAP_NEAREST:GL_NEAREST,GL_NEAREST,GL_NONE,GL_NONE};
+ VolatileTexture::setTexParameters(this, &texParams);
+ #endif*/
},
/**
@@ -718,13 +707,11 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
* It only works if the texture size is POT (power of 2).
*/
generateMipmap:function () {
- if (cc.Browser.supportWebGL) {
- cc.Assert(this._pixelsWide == cc.NextPOT(this._pixelsWide) && this._pixelsHigh == cc.NextPOT(this._pixelsHigh), "Mimpap texture only works in POT textures");
+ cc.Assert(this._pixelsWide == cc.NextPOT(this._pixelsWide) && this._pixelsHigh == cc.NextPOT(this._pixelsHigh), "Mimpap texture only works in POT textures");
- cc.glBindTexture2D(this);
- cc.renderContext.generateMipmap(cc.renderContext.TEXTURE_2D);
- this._hasMipmaps = true;
- }
+ cc.glBindTexture2D(this);
+ cc.renderContext.generateMipmap(cc.renderContext.TEXTURE_2D);
+ this._hasMipmaps = true;
},
/**
@@ -919,6 +906,335 @@ cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */{
}
});
+/**
+ *
+ * This class allows to easily create Canvas 2D textures from images, text or raw data.
+ * The created cc.Texture2D object will always have power-of-two dimensions.
+ * Depending on how you create the cc.Texture2D object, the actual image area of the texture might be smaller than the texture dimensions
+ * i.e. "contentSize" != (pixelsWide, pixelsHigh) and (maxS, maxT) != (1.0, 1.0).
+ * Be aware that the content of the generated textures will be upside-down!
+ * @class
+ * @extends cc.Class
+ */
+cc.Texture2DCanvas = cc.Class.extend(/** @lends cc.Texture2D# */{
+ _contentSize:null,
+ _isLoaded:false,
+ _htmlElementObj:null,
+ /*public:*/
+ ctor:function () {
+ this._contentSize = cc.size(0,0);
+ this._isLoaded = false;
+ this._htmlElementObj = null;
+ },
+
+ /**
+ * width in pixels
+ * @return {Number}
+ */
+ getPixelsWide:function () {
+ return this._contentSize.width;
+ },
+
+ /**
+ * hight in pixels
+ * @return {Number}
+ */
+ getPixelsHigh:function () {
+ return this._contentSize.height;
+ },
+
+ /**
+ * content size
+ * @return {cc.Size}
+ */
+ getContentSize:function () {
+ return cc.size(this._contentSize.width / cc.CONTENT_SCALE_FACTOR(), this._contentSize.height / cc.CONTENT_SCALE_FACTOR());
+ },
+
+ getContentSizeInPixels:function () {
+ return this._contentSize;
+ },
+
+ initWithElement:function (element) {
+ if (!element)
+ return;
+ this._htmlElementObj = element;
+ },
+
+ /**
+ * HTMLElement Object getter
+ * @return {HTMLElement}
+ */
+ getHtmlElementObj:function(){
+ return this._htmlElementObj;
+ },
+
+ isLoaded:function () {
+ return this._isLoaded;
+ },
+
+ handleLoadedTexture:function () {
+ this._isLoaded = true;
+
+ var pixelsWide = this._htmlElementObj.width;
+ var pixelsHigh = this._htmlElementObj.height;
+
+ this._contentSize = new cc.Size(pixelsWide, pixelsHigh);
+ },
+
+ description:function () {
+ return "";
+ },
+
+ /**
+ * Intializes with a texture2d with data
+ * @param {Array} data
+ * @param {Number} pixelFormat
+ * @param {Number} pixelsWide
+ * @param {Number} pixelsHigh
+ * @param {cc.Size} contentSize
+ * @return {Boolean}
+ */
+ initWithData:function (data, pixelFormat, pixelsWide, pixelsHigh, contentSize) {
+ //support only in WebGl rendering mode
+ return false;
+ },
+
+ /**
+ Extensions to make it easy to create a CCTexture2D object from an image file.
+ Note that RGBA type textures will have their alpha premultiplied - use the blending mode (gl.ONE, gl.ONE_MINUS_SRC_ALPHA).
+ */
+ /**
+ * Initializes a texture from a UIImage object
+ * @param uiImage
+ * @return {Boolean}
+ */
+ initWithImage:function (uiImage) {
+ //support only in WebGl rendering mode
+ return false;
+ },
+
+ /**
+ Extensions to make it easy to create a cc.Texture2D object from a string of text.
+ Note that the generated textures are of type A8 - use the blending mode (gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA).
+ */
+ /**
+ * Initializes a texture from a string with dimensions, alignment, font name and font size (note: initWithString does not support on HTML5)
+ * @param {String} text
+ * @param {String | cc.FontDefinition} fontName or fontDefinition
+ * @param {Number} fontSize
+ * @param {cc.Size} dimensions
+ * @param {Number} hAlignment
+ * @param {Number} vAlignment
+ * @return {Boolean}
+ */
+ initWithString:function (text, fontName, fontSize, dimensions, hAlignment, vAlignment) {
+ //support only in WebGl rendering mode
+ return false;
+ },
+
+ releaseTexture:function () {
+ //support only in WebGl rendering mode
+ },
+
+ /**
+ * get WebGLTexture Object
+ * @return {WebGLTexture}
+ */
+ getName:function () {
+ //support only in WebGl rendering mode
+ return null;
+ },
+
+ /** texture max S */
+ getMaxS:function () {
+ //support only in WebGl rendering mode
+ return 1;
+ },
+
+ setMaxS:function (maxS) {
+ //support only in WebGl rendering mode
+ },
+
+ /** texture max T */
+ getMaxT:function () {
+ return 1;
+ },
+
+ setMaxT:function (maxT) {
+ //support only in WebGl rendering mode
+ },
+
+ /**
+ * return shader program used by drawAtPoint and drawInRect
+ * @return {cc.GLProgram}
+ */
+ getShaderProgram:function () {
+ //support only in WebGl rendering mode
+ return null;
+ },
+
+ /**
+ * set shader program used by drawAtPoint and drawInRect
+ * @param {cc.GLProgram} shaderProgram
+ */
+ setShaderProgram:function (shaderProgram) {
+ //support only in WebGl rendering mode
+ },
+
+ /**
+ * whether or not the texture has their Alpha premultiplied
+ * @return {Boolean}
+ */
+ hasPremultipliedAlpha:function () {
+ //support only in WebGl rendering mode
+ return false;
+ },
+
+ hasMipmaps:function () {
+ //support only in WebGl rendering mode
+ return false;
+ },
+
+
+
+ /**
+ * These functions are needed to create mutable textures
+ * @param {Array} data
+ */
+ releaseData:function (data) {
+ //support only in WebGl rendering mode
+ data = null;
+ },
+
+ keepData:function (data, length) {
+ //support only in WebGl rendering mode
+ return data;
+ },
+
+
+
+ /**
+ Drawing extensions to make it easy to draw basic quads using a CCTexture2D object.
+ These functions require gl.TEXTURE_2D and both gl.VERTEX_ARRAY and gl.TEXTURE_COORD_ARRAY client states to be enabled.
+ */
+
+ /**
+ * draws a texture at a given point
+ * @param {cc.Point} point
+ */
+ drawAtPoint:function (point) {
+ //support only in WebGl rendering mode
+ },
+
+ /**
+ * draws a texture inside a rect
+ * @param {cc.Rect} rect
+ */
+ drawInRect:function (rect) {
+ //support only in WebGl rendering mode
+ },
+
+
+
+ /**
+ * Initializes a texture from a ETC file (note: initWithETCFile does not support on HTML5)
+ * @note Compatible to Cocos2d-x
+ * @param {String} file
+ * @return {Boolean}
+ */
+ initWithETCFile:function (file) {
+ //support only in WebGl rendering mode
+ return false;
+ },
+
+ /**
+ * Initializes a texture from a PVR file
+ * @param {String} file
+ * @return {Boolean}
+ */
+ initWithPVRFile:function (file) {
+ //support only in WebGl rendering mode
+ return false;
+ },
+
+ /**
+ Extensions to make it easy to create a cc.Texture2D object from a PVRTC file
+ Note that the generated textures don't have their alpha premultiplied - use the blending mode (gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA).
+ */
+ /**
+ * Initializes a texture from a PVRTC buffer
+ * @note compatible to cocos2d-iphone interface.
+ * @param {Array} data
+ * @param {Number} level
+ * @param {Number} bpp
+ * @param {Boolean} hasAlpha
+ * @param {Number} length
+ * @param {Number} pixelFormat
+ * @return {Boolean}
+ */
+ initWithPVRTCData:function (data, level, bpp, hasAlpha, length, pixelFormat) {
+ //support only in WebGl rendering mode
+ return true;
+ },
+
+ /**
+ * sets the min filter, mag filter, wrap s and wrap t texture parameters.
+ * If the texture size is NPOT (non power of 2), then in can only use gl.CLAMP_TO_EDGE in gl.TEXTURE_WRAP_{S,T}.
+ * @param texParams
+ */
+ setTexParameters:function (texParams) {
+ //support only in WebGl rendering mode
+ },
+
+ /**
+ * sets antialias texture parameters:
+ * - GL_TEXTURE_MIN_FILTER = GL_NEAREST
+ * - GL_TEXTURE_MAG_FILTER = GL_NEAREST
+ */
+ setAntiAliasTexParameters:function () {
+ //support only in WebGl rendering mode
+ },
+
+ /**
+ * sets alias texture parameters:
+ * GL_TEXTURE_MIN_FILTER = GL_NEAREST
+ * GL_TEXTURE_MAG_FILTER = GL_NEAREST
+ */
+ setAliasTexParameters:function () {
+ //support only in WebGl rendering mode
+ },
+
+ /**
+ * Generates mipmap images for the texture.
+ * It only works if the texture size is POT (power of 2).
+ */
+ generateMipmap:function () {
+ //support only in WebGl rendering mode
+ },
+
+ /**
+ * returns the pixel format.
+ * @return {String}
+ */
+ stringForFormat:function () {
+ //support only in WebGl rendering mode
+ return "";
+ },
+
+ /**
+ * returns the bits-per-pixel of the in-memory OpenGL texture
+ * @return {Number}
+ */
+ bitsPerPixelForFormat:function (format) {
+ //support only in WebGl rendering mode
+ return -1;
+ }
+
+});
+
+cc.Texture2D = cc.Browser.supportWebGL ? cc.Texture2DWebGL : cc.Texture2DCanvas;
+
/**
*
* sets the default pixel format for UIImagescontains alpha channel.
From e0a6d44ece7a4f3c1bac2b38b03845435463d2fd Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Wed, 7 Aug 2013 14:16:46 +0800
Subject: [PATCH 030/141] Fixed #2444 Fixed bug that cc.PointZero use as a
value ,but it is a function.
---
extensions/GUI/CCControlExtension/CCControlColourPicker.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/extensions/GUI/CCControlExtension/CCControlColourPicker.js b/extensions/GUI/CCControlExtension/CCControlColourPicker.js
index 024cf1dfd2..d6cf2706f7 100644
--- a/extensions/GUI/CCControlExtension/CCControlColourPicker.js
+++ b/extensions/GUI/CCControlExtension/CCControlColourPicker.js
@@ -101,7 +101,7 @@ cc.ControlColourPicker = cc.Control.extend({
this._hsv = new cc.HSV(0, 0, 0);
// Add image
- this._background = cc.ControlUtils.addSpriteToTargetWithPosAndAnchor("menuColourPanelBackground.png", spriteSheet, cc.PointZero, cc.p(0.5, 0.5));
+ this._background = cc.ControlUtils.addSpriteToTargetWithPosAndAnchor("menuColourPanelBackground.png", spriteSheet, cc.PointZero(), cc.p(0.5, 0.5));
var backgroundPointZero = cc.pSub(this._background.getPosition(),
cc.p(this._background.getContentSize().width / 2, this._background.getContentSize().height / 2));
From e81726b2866e66975532b410b9978ae605fdd865 Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Thu, 8 Aug 2013 10:21:33 +0800
Subject: [PATCH 031/141] Fixed #2444 Fixed some bug about merged the code
---
cocos2d/misc_nodes/CCRenderTexture.js | 5 ++++-
cocos2d/sprite_nodes/CCSprite.js | 6 ++----
2 files changed, 6 insertions(+), 5 deletions(-)
diff --git a/cocos2d/misc_nodes/CCRenderTexture.js b/cocos2d/misc_nodes/CCRenderTexture.js
index 99df12b674..8d5b8ac8e9 100644
--- a/cocos2d/misc_nodes/CCRenderTexture.js
+++ b/cocos2d/misc_nodes/CCRenderTexture.js
@@ -138,7 +138,10 @@ cc.RenderTextureCanvas = cc.Node.extend(/** @lends cc.RenderTextureCanvas# */{
this._cacheCanvas.width = width || 10;
this._cacheCanvas.height = height || 10;
this._cacheContext.translate(0, this._cacheCanvas.height);
- this._sprite = cc.Sprite.createWithTexture(this._cacheCanvas);
+ var texture = new cc.Texture2D();
+ texture.initWithElement(this._cacheCanvas);
+ texture.handleLoadedTexture();
+ this._sprite = cc.Sprite.createWithTexture(texture);
return true;
},
diff --git a/cocos2d/sprite_nodes/CCSprite.js b/cocos2d/sprite_nodes/CCSprite.js
index 3a88542f5d..c08dd723fe 100644
--- a/cocos2d/sprite_nodes/CCSprite.js
+++ b/cocos2d/sprite_nodes/CCSprite.js
@@ -1008,8 +1008,6 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
if (!rect) {
rect = cc.rect(0, 0, 0, 0);
rect.size = texture.getContentSize();
- rect = cc.RECT_PIXELS_TO_POINTS(rect);
- }
}
this._originalTexture = texture;
@@ -1274,11 +1272,11 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
var image = this._texture.getHtmlElementObj();
if (this._colorized) {
context.drawImage(image,
- 0, 0, locRect.width * scaleFactor, locRect.height * scaleFactor,
+ 0, 0, locRect.width , locRect.height ,
flipXOffset, flipYOffset, locRect.width, locRect.height);
} else {
context.drawImage(image,
- locRect.x * scaleFactor, locRect.y * scaleFactor, locRect.width * scaleFactor, locRect.height * scaleFactor,
+ locRect.x , locRect.y , locRect.width , locRect.height ,
flipXOffset, flipYOffset, locRect.width, locRect.height);
}
} else if (this._contentSize.width !== 0) {
From 34743c157663463b80556d4345ab43736f73e313 Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Thu, 8 Aug 2013 10:45:49 +0800
Subject: [PATCH 032/141] Fixed #2496 Fixed a bug of cc.TextureCache that the
status of texture is wrong in callback
---
cocos2d/textures/CCTextureCache.js | 100 ++++++++++++++++++++---------
1 file changed, 69 insertions(+), 31 deletions(-)
diff --git a/cocos2d/textures/CCTextureCache.js b/cocos2d/textures/CCTextureCache.js
index 6c8925edf6..ae44271464 100644
--- a/cocos2d/textures/CCTextureCache.js
+++ b/cocos2d/textures/CCTextureCache.js
@@ -277,26 +277,37 @@ cc.TextureCacheCanvas = cc.Class.extend(/** @lends cc.TextureCacheCanvas# */{
cc.Assert(path != null, "TextureCache: path MUST not be null");
path = cc.FileUtils.getInstance().fullPathForFilename(path);
var texture = this._textures[path];
-
+ var image;
if (texture) {
- this._addImageAsyncCallBack(target, selector);
+ if(texture.isLoaded()){
+ this._addImageAsyncCallBack(target, selector);
+ }else{
+ var that = this;
+ image = texture.getHtmlElementObj();
+ image.addEventListener("load", function () {
+ texture.handleLoadedTexture();
+ that._addImageAsyncCallBack(target, selector);
+ });
+ }
} else {
- texture = new Image();
- texture.crossOrigin = "Anonymous";
+ image = new Image();
+ image.crossOrigin = "Anonymous";
var that = this;
- texture.addEventListener("load", function () {
+ image.addEventListener("load", function () {
+ if (that._textures.hasOwnProperty(path))
+ that._textures[path].handleLoadedTexture();
that._addImageAsyncCallBack(target, selector);
});
- texture.addEventListener("error", function () {
+ image.addEventListener("error", function () {
cc.Loader.getInstance().onResLoadingErr(path);
//remove from cache
if (that._textures.hasOwnProperty(path))
delete that._textures[path];
});
- texture.src = path;
+ image.src = path;
var texture2d = new cc.Texture2D();
- texture2d.initWithElement(texture);
+ texture2d.initWithElement(image);
this._textures[path] = texture2d;
}
return this._textures[path];
@@ -320,27 +331,36 @@ cc.TextureCacheCanvas = cc.Class.extend(/** @lends cc.TextureCacheCanvas# */{
path = cc.FileUtils.getInstance().fullPathForFilename(path);
var texture = this._textures[path];
+ var image;
if (texture) {
- cc.Loader.getInstance().onResLoaded();
+ if (texture.isLoaded()) {
+ cc.Loader.getInstance().onResLoaded();
+ } else {
+ image = texture.getHtmlElementObj();
+ image.addEventListener("load", function () {
+ texture.handleLoadedTexture();
+ cc.Loader.getInstance().onResLoaded();
+ });
+ }
} else {
- texture = new Image();
- texture.crossOrigin = "Anonymous";
+ image = new Image();
+ image.crossOrigin = "Anonymous";
var that = this;
- texture.addEventListener("load", function () {
+ image.addEventListener("load", function () {
cc.Loader.getInstance().onResLoaded();
if (that._textures.hasOwnProperty(path))
that._textures[path].handleLoadedTexture();
});
- texture.addEventListener("error", function () {
+ image.addEventListener("error", function () {
cc.Loader.getInstance().onResLoadingErr(path);
//remove from cache
if (that._textures.hasOwnProperty(path))
delete that._textures[path];
});
- texture.src = path;
+ image.src = path;
var texture2d = new cc.Texture2D();
- texture2d.initWithElement(texture);
+ texture2d.initWithElement(image);
this._textures[path] = texture2d;
}
@@ -668,28 +688,37 @@ cc.TextureCacheWebGL = cc.Class.extend(/** @lends cc.TextureCacheWebGL# */{
cc.Assert(path != null, "TextureCache: path MUST not be null");
path = cc.FileUtils.getInstance().fullPathForFilename(path);
var texture = this._textures[path];
-
+ var image;
if (texture) {
- this._addImageAsyncCallBack(target, selector);
+ if(texture.isLoaded()){
+ this._addImageAsyncCallBack(target, selector);
+ }else{
+ var that = this;
+ image = texture.getHtmlElementObj();
+ image.addEventListener("load", function () {
+ texture.handleLoadedTexture();
+ that._addImageAsyncCallBack(target, selector);
+ });
+ }
} else {
- texture = new Image();
- texture.crossOrigin = "Anonymous";
+ image = new Image();
+ image.crossOrigin = "Anonymous";
var that = this;
- texture.addEventListener("load", function () {
+ image.addEventListener("load", function () {
if (that._textures.hasOwnProperty(path))
that._textures[path].handleLoadedTexture();
that._addImageAsyncCallBack(target, selector);
});
- texture.addEventListener("error", function () {
+ image.addEventListener("error", function () {
cc.Loader.getInstance().onResLoadingErr(path);
//remove from cache
if (that._textures.hasOwnProperty(path))
delete that._textures[path];
});
- texture.src = path;
+ image.src = path;
var texture2d = new cc.Texture2D();
- texture2d.initWithElement(texture);
+ texture2d.initWithElement(image);
this._textures[path] = texture2d;
}
return this._textures[path];
@@ -726,34 +755,43 @@ cc.TextureCacheWebGL = cc.Class.extend(/** @lends cc.TextureCacheWebGL# */{
*/
addImage:function (path) {
cc.Assert(path != null, "TextureCache: path MUST not be null");
- if(!this._rendererInitialized)
+ if (!this._rendererInitialized)
return this._addImageBeforeRenderer(path);
path = cc.FileUtils.getInstance().fullPathForFilename(path);
var texture = this._textures[path];
+ var image;
if (texture) {
- cc.Loader.getInstance().onResLoaded();
+ if (texture.isLoaded()) {
+ cc.Loader.getInstance().onResLoaded();
+ } else {
+ image = texture.getHtmlElementObj();
+ image.addEventListener("load", function () {
+ texture.handleLoadedTexture();
+ cc.Loader.getInstance().onResLoaded();
+ });
+ }
} else {
- texture = new Image();
- texture.crossOrigin = "Anonymous";
+ image = new Image();
+ image.crossOrigin = "Anonymous";
var that = this;
- texture.addEventListener("load", function () {
+ image.addEventListener("load", function () {
cc.Loader.getInstance().onResLoaded();
if (that._textures.hasOwnProperty(path))
that._textures[path].handleLoadedTexture();
});
- texture.addEventListener("error", function () {
+ image.addEventListener("error", function () {
cc.Loader.getInstance().onResLoadingErr(path);
//remove from cache
if (that._textures.hasOwnProperty(path))
delete that._textures[path];
});
- texture.src = path;
+ image.src = path;
var texture2d = new cc.Texture2D();
- texture2d.initWithElement(texture);
+ texture2d.initWithElement(image);
this._textures[path] = texture2d;
}
From 3ee3082a81ac6d3312804b31e4c9f8c74ccc63db Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Thu, 8 Aug 2013 11:56:15 +0800
Subject: [PATCH 033/141] Fixed #2482 Add the deprecated information to
function of cc.UserDefault
---
cocos2d/support/CCUserDefault.js | 10 ++++++++++
1 file changed, 10 insertions(+)
diff --git a/cocos2d/support/CCUserDefault.js b/cocos2d/support/CCUserDefault.js
index 109888daa5..6c40730469 100644
--- a/cocos2d/support/CCUserDefault.js
+++ b/cocos2d/support/CCUserDefault.js
@@ -69,6 +69,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @return {Boolean}
*/
getBoolForKey:function (key, defaultValue) {
+ cc.log("cc.UserDefault will not be supported in the future,i suggest you to use sys.localStorage.getItem instead of getBoolForKey.");
var value = this._getValueForKey(key);
var ret = defaultValue || false;
if (value == "true") {
@@ -93,6 +94,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @return {Number}
*/
getIntegerForKey:function (key, defaultValue) {
+ cc.log("cc.UserDefault will not be supported in the future,i suggest you to use sys.localStorage.getItem instead of getIntegerForKey.");
var value = this._getValueForKey(key);
var ret = defaultValue || 0;
@@ -112,6 +114,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @return {Number}
*/
getFloatForKey:function (key, defaultValue) {
+ cc.log("cc.UserDefault will not be supported in the future,i suggest you to use sys.localStorage.getItem instead of getFloatForKey.");
var value = this._getValueForKey(key);
var ret = defaultValue || 0;
@@ -131,6 +134,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @return {Number}
*/
getDoubleForKey:function (key, defaultValue) {
+ cc.log("cc.UserDefault will not be supported in the future,i suggest you to use sys.localStorage.getItem instead of getDoubleForKey.");
return this.getFloatForKey(key, defaultValue);
},
@@ -143,6 +147,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @return {String}
*/
getStringForKey:function (key, defaultValue) {
+ cc.log("cc.UserDefault will not be supported in the future,i suggest you to use sys.localStorage.getItem instead of getStringForKey.");
var value = this._getValueForKey(key);
var ret = defaultValue || "";
@@ -169,6 +174,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @param {Boolean} value
*/
setBoolForKey:function (key, value) {
+ cc.log("cc.UserDefault will not be supported in the future,i suggest you to use sys.localStorage.setItem instead of setBoolForKey.");
// save bool value as sring
this.setStringForKey(key, String(value));
},
@@ -180,6 +186,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @param {Number} value
*/
setIntegerForKey:function (key, value) {
+ cc.log("cc.UserDefault will not be supported in the future,i suggest you to use sys.localStorage.setItem instead of setIntegerForKey.");
// check key
if (!key) {
return;
@@ -195,6 +202,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @param {Number} value
*/
setFloatForKey:function (key, value) {
+ cc.log("cc.UserDefault will not be supported in the future,i suggest you to use sys.localStorage.setItem instead of setFloatForKey.");
// check key
if (!key) {
return;
@@ -210,6 +218,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @param {Number} value
*/
setDoubleForKey:function (key, value) {
+ cc.log("cc.UserDefault will not be supported in the future,i suggest you to use sys.localStorage.setItem instead of setDoubleForKey.");
return this.setFloatForKey(key, value);
},
@@ -220,6 +229,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @param {String} value
*/
setStringForKey:function (key, value) {
+ cc.log("cc.UserDefault will not be supported in the future,i suggest you to use sys.localStorage.setItem instead of setStringForKey.");
// check key
if (!key) {
return;
From 41a6c525785a02c869b8862254bfabb6c7b129f7 Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Thu, 8 Aug 2013 13:58:43 +0800
Subject: [PATCH 034/141] Fixed #2482 Add the deprecated information to
function of cc.UserDefault
---
cocos2d/support/CCUserDefault.js | 21 +++++++++++----------
1 file changed, 11 insertions(+), 10 deletions(-)
diff --git a/cocos2d/support/CCUserDefault.js b/cocos2d/support/CCUserDefault.js
index 6c40730469..fd53f8c3d0 100644
--- a/cocos2d/support/CCUserDefault.js
+++ b/cocos2d/support/CCUserDefault.js
@@ -69,7 +69,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @return {Boolean}
*/
getBoolForKey:function (key, defaultValue) {
- cc.log("cc.UserDefault will not be supported in the future,i suggest you to use sys.localStorage.getItem instead of getBoolForKey.");
+ cc.log("getBoolForKey is deprecated. Use sys.localStorage.getItem instead.");
var value = this._getValueForKey(key);
var ret = defaultValue || false;
if (value == "true") {
@@ -94,7 +94,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @return {Number}
*/
getIntegerForKey:function (key, defaultValue) {
- cc.log("cc.UserDefault will not be supported in the future,i suggest you to use sys.localStorage.getItem instead of getIntegerForKey.");
+ cc.log("getIntegerForKey is deprecated. Use sys.localStorage.getItem instead.");
var value = this._getValueForKey(key);
var ret = defaultValue || 0;
@@ -114,7 +114,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @return {Number}
*/
getFloatForKey:function (key, defaultValue) {
- cc.log("cc.UserDefault will not be supported in the future,i suggest you to use sys.localStorage.getItem instead of getFloatForKey.");
+ cc.log("getFloatForKey is deprecated. Use sys.localStorage.getItem instead.");
var value = this._getValueForKey(key);
var ret = defaultValue || 0;
@@ -134,7 +134,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @return {Number}
*/
getDoubleForKey:function (key, defaultValue) {
- cc.log("cc.UserDefault will not be supported in the future,i suggest you to use sys.localStorage.getItem instead of getDoubleForKey.");
+ cc.log("getDoubleForKey is deprecated. Use sys.localStorage.getItem instead.");
return this.getFloatForKey(key, defaultValue);
},
@@ -147,7 +147,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @return {String}
*/
getStringForKey:function (key, defaultValue) {
- cc.log("cc.UserDefault will not be supported in the future,i suggest you to use sys.localStorage.getItem instead of getStringForKey.");
+ cc.log("getStringForKey is deprecated. Use sys.localStorage.getItem instead.");
var value = this._getValueForKey(key);
var ret = defaultValue || "";
@@ -174,7 +174,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @param {Boolean} value
*/
setBoolForKey:function (key, value) {
- cc.log("cc.UserDefault will not be supported in the future,i suggest you to use sys.localStorage.setItem instead of setBoolForKey.");
+ cc.log("setBoolForKey is deprecated. Use sys.localStorage.setItem instead.");
// save bool value as sring
this.setStringForKey(key, String(value));
},
@@ -186,7 +186,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @param {Number} value
*/
setIntegerForKey:function (key, value) {
- cc.log("cc.UserDefault will not be supported in the future,i suggest you to use sys.localStorage.setItem instead of setIntegerForKey.");
+ cc.log("setIntegerForKey is deprecated. Use sys.localStorage.setItem instead.");
// check key
if (!key) {
return;
@@ -202,7 +202,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @param {Number} value
*/
setFloatForKey:function (key, value) {
- cc.log("cc.UserDefault will not be supported in the future,i suggest you to use sys.localStorage.setItem instead of setFloatForKey.");
+ cc.log("setFloatForKey is deprecated. Use sys.localStorage.setItem instead.");
// check key
if (!key) {
return;
@@ -218,7 +218,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @param {Number} value
*/
setDoubleForKey:function (key, value) {
- cc.log("cc.UserDefault will not be supported in the future,i suggest you to use sys.localStorage.setItem instead of setDoubleForKey.");
+ cc.log("setDoubleForKey is deprecated. Use sys.localStorage.setItem instead.");
return this.setFloatForKey(key, value);
},
@@ -229,7 +229,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @param {String} value
*/
setStringForKey:function (key, value) {
- cc.log("cc.UserDefault will not be supported in the future,i suggest you to use sys.localStorage.setItem instead of setStringForKey.");
+ cc.log("setStringForKey is deprecated. Use sys.localStorage.setItem instead.");
// check key
if (!key) {
return;
@@ -251,6 +251,7 @@ cc.UserDefault = cc.Class.extend(/** @lends cc.UserDefault# */{
* @return {cc.UserDefault|}
*/
cc.UserDefault.getInstance = function () {
+ cc.log("cc.UserDefault is deprecated. Use sys.localStorage instead.");
if (!this._sUserDefault) {
this._sUserDefault = new cc.UserDefault();
this._sUserDefault.init();
From bc1bcba133bd677f69b6ecbada8179ba8607072a Mon Sep 17 00:00:00 2001
From: SmallJun <536762164@qq.com>
Date: Thu, 8 Aug 2013 14:51:04 +0800
Subject: [PATCH 035/141] fixed the bug of ScrollView while change the position
of it`s parent node.
---
extensions/GUI/CCScrollView/CCScrollView.js | 13 ++++++-------
1 file changed, 6 insertions(+), 7 deletions(-)
diff --git a/extensions/GUI/CCScrollView/CCScrollView.js b/extensions/GUI/CCScrollView/CCScrollView.js
index a384204931..fd54271d79 100644
--- a/extensions/GUI/CCScrollView/CCScrollView.js
+++ b/extensions/GUI/CCScrollView/CCScrollView.js
@@ -710,16 +710,15 @@ cc.ScrollView = cc.Layer.extend({
this._scissorRestored = false;
var frame = this._getViewRect();
- var screenPos;
- var scaleValue = this.getScale();
+ var scaleX = this.getScaleX();
+ var scaleY = this.getScaleY();
var ctx = context || cc.renderContext;
if (cc.renderContextType === cc.CANVAS) {
- screenPos = this.getParent().getPosition();
- var getWidth = (this._viewSize.width * scaleValue);
- var getHeight = (this._viewSize.height * scaleValue);
- var startX = screenPos.x * scaleValue;
- var startY = screenPos.y * scaleValue;// + this._anchorPointInPoints.y;
+ var getWidth = (this._viewSize.width * scaleX);
+ var getHeight = (this._viewSize.height * scaleY);
+ var startX = 0;
+ var startY = 0;
ctx.beginPath();
ctx.rect(startX, startY, getWidth, -getHeight);
From e71329e1ff04c3b9968c4f002396bbbd9f5cf418 Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Fri, 9 Aug 2013 16:40:41 +0800
Subject: [PATCH 036/141] Fixed #2511 fixed a bug of cc.EditBox and a bug of
cc.Scale9Sprite
---
cocos2d/base_nodes/CCdomNode.js | 82 +++++++++----------
cocos2d/label_nodes/CCLabelTTF.js | 2 +-
.../GUI/CCControlExtension/CCScale9Sprite.js | 1 +
3 files changed, 43 insertions(+), 42 deletions(-)
diff --git a/cocos2d/base_nodes/CCdomNode.js b/cocos2d/base_nodes/CCdomNode.js
index 79da7fbe80..89357a38fc 100644
--- a/cocos2d/base_nodes/CCdomNode.js
+++ b/cocos2d/base_nodes/CCdomNode.js
@@ -285,7 +285,7 @@ cc.DOM.methods = /** @lends cc.DOM# */{
redraw:function () {
if (this.isSprite) {
var tmp = this._children;
- this._children = null;
+ this._children = [];
cc.Sprite.prototype.visit.call(this, this.ctx);
this._children = tmp;
}
@@ -351,47 +351,47 @@ cc.DOM.parentDOM = function (x) {
cc.DOM.parentDOM(p);
} else {
//parent has no more parent, if its running, then add it to the container
- //if (p.isRunning()) {
- //find EGLView div
- var eglViewDiv = cc.$("#EGLViewDiv");
- if(eglViewDiv){
- p.dom.appendTo(eglViewDiv);
- } else {
- eglViewDiv = cc.$new("div");
- eglViewDiv.id = "EGLViewDiv";
-
- var eglViewer = cc.EGLView.getInstance();
- var designSize = eglViewer.getDesignResolutionSize();
- var viewPortRect = eglViewer.getViewPortRect();
- var screenSize = eglViewer.getFrameSize();
- var designSizeWidth = designSize.width, designSizeHeight = designSize.height;
- if((designSize.width === 0) && (designSize.height === 0)){
- designSizeWidth = screenSize.width;
- designSizeHeight = screenSize.height;
- }
-
- var viewPortWidth = viewPortRect.size.width, viewPortHeight = viewPortRect.size.height;
- if((viewPortRect.size.width === 0) && (viewPortRect.size.height === 0)){
- viewPortWidth = screenSize.width;
- viewPortHeight = screenSize.height;
+ if (p.isRunning()) {
+ //find EGLView div
+ var eglViewDiv = cc.$("#EGLViewDiv");
+ if (eglViewDiv) {
+ p.dom.appendTo(eglViewDiv);
+ } else {
+ eglViewDiv = cc.$new("div");
+ eglViewDiv.id = "EGLViewDiv";
+
+ var eglViewer = cc.EGLView.getInstance();
+ var designSize = eglViewer.getDesignResolutionSize();
+ var viewPortRect = eglViewer.getViewPortRect();
+ var screenSize = eglViewer.getFrameSize();
+ var designSizeWidth = designSize.width, designSizeHeight = designSize.height;
+ if ((designSize.width === 0) && (designSize.height === 0)) {
+ designSizeWidth = screenSize.width;
+ designSizeHeight = screenSize.height;
+ }
+
+ var viewPortWidth = viewPortRect.size.width, viewPortHeight = viewPortRect.size.height;
+ if ((viewPortRect.size.width === 0) && (viewPortRect.size.height === 0)) {
+ viewPortWidth = screenSize.width;
+ viewPortHeight = screenSize.height;
+ }
+
+ eglViewDiv.style.position = 'absolute';
+ eglViewDiv.style.bottom = 0;
+ //x.dom.style.display='block';
+ eglViewDiv.style.width = designSizeWidth + "px";
+ eglViewDiv.style.maxHeight = designSizeHeight + "px";
+ eglViewDiv.style.margin = 0;
+
+ eglViewDiv.resize(eglViewer.getScaleX(), eglViewer.getScaleY());
+ eglViewDiv.style.left = ((viewPortWidth - designSizeWidth) / 2
+ + (screenSize.width - viewPortWidth ) / 2) + "px";
+ eglViewDiv.style.bottom = ((screenSize.height - viewPortHeight ) / 2) + "px";
+
+ p.dom.appendTo(eglViewDiv);
+ eglViewDiv.appendTo(cc.container);
}
-
- eglViewDiv.style.position = 'absolute';
- eglViewDiv.style.bottom = 0;
- //x.dom.style.display='block';
- eglViewDiv.style.width = designSizeWidth + "px";
- eglViewDiv.style.maxHeight = designSizeHeight + "px";
- eglViewDiv.style.margin = 0;
-
- eglViewDiv.resize(eglViewer.getScaleX(), eglViewer.getScaleY());
- eglViewDiv.style.left = ((viewPortWidth - designSizeWidth) / 2
- + (screenSize.width - viewPortWidth ) / 2) + "px";
- eglViewDiv.style.bottom = ((screenSize.height - viewPortHeight ) / 2) + "px";
-
- p.dom.appendTo(eglViewDiv);
- eglViewDiv.appendTo(cc.container);
}
- //}
}
return true;
};
@@ -410,7 +410,7 @@ cc.DOM.setTransform = function (x) {
x.ctx.translate(x.getAnchorPointInPoints().x, x.getAnchorPointInPoints().y);
if (x.isSprite) {
var tmp = x._children;
- x._children = null;
+ x._children = [];
cc.Sprite.prototype.visit.call(x, x.ctx);
x._children = tmp;
}
diff --git a/cocos2d/label_nodes/CCLabelTTF.js b/cocos2d/label_nodes/CCLabelTTF.js
index 9317c9b566..1db1d04de5 100644
--- a/cocos2d/label_nodes/CCLabelTTF.js
+++ b/cocos2d/label_nodes/CCLabelTTF.js
@@ -1265,7 +1265,7 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{
},
setPosition:function(posX, posY){
- if(posY)
+ if (arguments.length == 2)
this._originalPosition = cc.p(posX, posY);
else
this._originalPosition = cc.p(posX.x, posX.y);
diff --git a/extensions/GUI/CCControlExtension/CCScale9Sprite.js b/extensions/GUI/CCControlExtension/CCScale9Sprite.js
index bc26ba5c56..78cb10bfed 100644
--- a/extensions/GUI/CCControlExtension/CCScale9Sprite.js
+++ b/extensions/GUI/CCControlExtension/CCScale9Sprite.js
@@ -230,6 +230,7 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
setCapInsets: function (capInsets) {
var contentSize = this._contentSize;
+ contentSize = new cc.Size(contentSize.width,contentSize.height);
this.updateWithBatchNode(this._scale9Image, this._spriteRect, this._spriteFrameRotated, capInsets);
this.setContentSize(contentSize);
},
From 05b55f0faaee92923c1b8311d7a25bb120740494 Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Wed, 14 Aug 2013 16:51:30 +0800
Subject: [PATCH 037/141] Fixed #2454: Fixed a bug of EditBox that position is
wrong when EGLView Mode is NOBORDER
---
cocos2d/base_nodes/CCdomNode.js | 34 +++++++++++++++++++++++++--------
1 file changed, 26 insertions(+), 8 deletions(-)
diff --git a/cocos2d/base_nodes/CCdomNode.js b/cocos2d/base_nodes/CCdomNode.js
index 89357a38fc..7bd78d3300 100644
--- a/cocos2d/base_nodes/CCdomNode.js
+++ b/cocos2d/base_nodes/CCdomNode.js
@@ -315,16 +315,25 @@ cc.DOM._resetEGLViewDiv = function(){
}
eglViewDiv.style.position = 'absolute';
- eglViewDiv.style.bottom = 0;
//x.dom.style.display='block';
eglViewDiv.style.width = designSizeWidth + "px";
eglViewDiv.style.maxHeight = designSizeHeight + "px";
eglViewDiv.style.margin = 0;
eglViewDiv.resize(eglViewer.getScaleX(), eglViewer.getScaleY());
- eglViewDiv.style.left = ((viewPortWidth - designSizeWidth) / 2
- + (screenSize.width - viewPortWidth ) / 2) + "px";
- eglViewDiv.style.bottom = ((screenSize.height - viewPortHeight ) / 2) + "px";
+
+ if (viewPortWidth < screenSize.width) {
+ eglViewDiv.style.left = ((viewPortWidth - designSizeWidth) / 2
+ + (screenSize.width - viewPortWidth ) / 2) + "px";
+ } else {
+ eglViewDiv.style.left = (viewPortWidth - designSizeWidth) / 2 + "px";
+ }
+
+ if (viewPortHeight < screenSize.height) {
+ eglViewDiv.style.bottom = ((screenSize.height - viewPortHeight ) / 2) + "px";
+ } else {
+ eglViewDiv.style.bottom = "0px";
+ }
}
};
@@ -377,16 +386,25 @@ cc.DOM.parentDOM = function (x) {
}
eglViewDiv.style.position = 'absolute';
- eglViewDiv.style.bottom = 0;
//x.dom.style.display='block';
eglViewDiv.style.width = designSizeWidth + "px";
eglViewDiv.style.maxHeight = designSizeHeight + "px";
eglViewDiv.style.margin = 0;
eglViewDiv.resize(eglViewer.getScaleX(), eglViewer.getScaleY());
- eglViewDiv.style.left = ((viewPortWidth - designSizeWidth) / 2
- + (screenSize.width - viewPortWidth ) / 2) + "px";
- eglViewDiv.style.bottom = ((screenSize.height - viewPortHeight ) / 2) + "px";
+
+ if (viewPortWidth < screenSize.width) {
+ eglViewDiv.style.left = ((viewPortWidth - designSizeWidth) / 2
+ + (screenSize.width - viewPortWidth ) / 2) + "px";
+ } else {
+ eglViewDiv.style.left = (viewPortWidth - designSizeWidth) / 2 + "px";
+ }
+
+ if (viewPortHeight < screenSize.height) {
+ eglViewDiv.style.bottom = ((screenSize.height - viewPortHeight ) / 2) + "px";
+ } else {
+ eglViewDiv.style.bottom = "0px";
+ }
p.dom.appendTo(eglViewDiv);
eglViewDiv.appendTo(cc.container);
From 0e6f84632cb27610f16519a3308fba05a40c147c Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Wed, 14 Aug 2013 16:57:17 +0800
Subject: [PATCH 038/141] Fixed #2454 Fixed a bug that preloadTextFileData have
a wrong cache
---
cocos2d/platform/CCFileUtils.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/cocos2d/platform/CCFileUtils.js b/cocos2d/platform/CCFileUtils.js
index a6f5ee816d..ad90b6d610 100644
--- a/cocos2d/platform/CCFileUtils.js
+++ b/cocos2d/platform/CCFileUtils.js
@@ -279,7 +279,7 @@ cc.FileUtils = cc.Class.extend({
xhr.onload = function (e) {
if (xhr.responseText) {
cc.Loader.getInstance().onResLoaded();
- selfPointer._fileDataCache[fileUrl] = xhr.responseText;
+ selfPointer._textFileCache[fileUrl] = xhr.responseText;
}
};
}
From 71e82f56ab4b259a145cec6be2df7360e8d0f536 Mon Sep 17 00:00:00 2001
From: 06wj <06wj@163.com>
Date: Thu, 15 Aug 2013 23:47:19 +0800
Subject: [PATCH 039/141] update cc.RectApplyAffineTransform
---
cocos2d/cocoa/CCAffineTransform.js | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
diff --git a/cocos2d/cocoa/CCAffineTransform.js b/cocos2d/cocoa/CCAffineTransform.js
index e5642b93c7..fbf7f30a9d 100644
--- a/cocos2d/cocoa/CCAffineTransform.js
+++ b/cocos2d/cocoa/CCAffineTransform.js
@@ -127,10 +127,10 @@ cc.RectApplyAffineTransform = function (rect, anAffineTransform) {
var bottomLeft = cc.PointApplyAffineTransform(cc.p(left, bottom), anAffineTransform);
var bottomRight = cc.PointApplyAffineTransform(cc.p(right, bottom), anAffineTransform);
- var minX = Math.min(Math.min(topLeft.x, topRight.x), Math.min(bottomLeft.x, bottomRight.x));
- var maxX = Math.max(Math.max(topLeft.x, topRight.x), Math.max(bottomLeft.x, bottomRight.x));
- var minY = Math.min(Math.min(topLeft.y, topRight.y), Math.min(bottomLeft.y, bottomRight.y));
- var maxY = Math.max(Math.max(topLeft.y, topRight.y), Math.max(bottomLeft.y, bottomRight.y));
+ var minX = Math.min(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x);
+ var maxX = Math.max(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x);
+ var minY = Math.min(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y);
+ var maxY = Math.max(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y);
return cc.rect(minX, minY, (maxX - minX), (maxY - minY));
};
From 46f3a133b74f25239306e7966019ecc009d8c68b Mon Sep 17 00:00:00 2001
From: 06wj <06wj@163.com>
Date: Thu, 15 Aug 2013 23:57:18 +0800
Subject: [PATCH 040/141] use native sort function when sort children
---
cocos2d/base_nodes/CCNode.js | 50 ++++++++----------------------------
1 file changed, 10 insertions(+), 40 deletions(-)
diff --git a/cocos2d/base_nodes/CCNode.js b/cocos2d/base_nodes/CCNode.js
index f57ebb7ca6..26d54ae743 100644
--- a/cocos2d/base_nodes/CCNode.js
+++ b/cocos2d/base_nodes/CCNode.js
@@ -402,8 +402,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
*/
setRotation: function (newRotation) {
this._rotationX = this._rotationY = newRotation;
- this._rotationRadiansX = this._rotationX * (Math.PI / 180);
- this._rotationRadiansY = this._rotationY * (Math.PI / 180);
+ this._rotationRadiansX = this._rotationRadiansY = newRotation * (Math.PI / 180);
this.setNodeDirty();
},
@@ -473,7 +472,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
*/
setScale:function (scale, scaleY) {
this._scaleX = scale;
- this._scaleY = (scaleY || scaleY === 0) ? scaleY : scale;
+ this._scaleY = scaleY === undefined ? scale : scaleY;
this.setNodeDirty();
},
@@ -1181,24 +1180,10 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
*/
sortAllChildren:function () {
if (this._reorderChildDirty) {
- var _children = this._children;
- var i, j, length = _children.length,tempChild;
-
// insertion sort
- for (i = 0; i < length; i++) {
- var tempItem = _children[i];
- j = i - 1;
- tempChild = _children[j];
-
- //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
- while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
- ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
- tempChild = _children[j];
- _children[j + 1] = tempChild;
- j = j - 1;
- }
- _children[j + 1] = tempItem;
- }
+ this._children.sort(function(a, b){
+ return a._zOrder === b._zOrder ? a._orderOfArrival - b._orderOfArrival : a._zOrder - b._zOrder;
+ });
//don't need to check children recursively, that's done in visit of each child
this._reorderChildDirty = false;
@@ -2247,8 +2232,7 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
*/
setRotation:function (newRotation) {
this._rotationX = this._rotationY = newRotation;
- this._rotationRadiansX = this._rotationX * 0.017453292519943295; //(Math.PI / 180);
- this._rotationRadiansY = this._rotationY * 0.017453292519943295; //(Math.PI / 180);
+ this._rotationRadiansX = this._rotationRadiansY = newRotation * 0.017453292519943295; //(Math.PI / 180);
this.setNodeDirty();
},
@@ -2318,7 +2302,7 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
*/
setScale:function (scale, scaleY) {
this._scaleX = scale;
- this._scaleY = scaleY || scale;
+ this._scaleY = scaleY === undefined ? scale : scaleY;
this.setNodeDirty();
},
@@ -3024,24 +3008,10 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
*/
sortAllChildren:function () {
if (this._reorderChildDirty) {
- var _children = this._children;
- var i, j, length = _children.length,tempChild;
-
// insertion sort
- for (i = 0; i < length; i++) {
- var tempItem = _children[i];
- j = i - 1;
- tempChild = _children[j];
-
- //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
- while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
- ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
- tempChild = _children[j];
- _children[j + 1] = tempChild;
- j = j - 1;
- }
- _children[j + 1] = tempItem;
- }
+ this._childre.sort(function(a, b){
+ return a._zOrder === b._zOrder ? a._orderOfArrival - b._orderOfArrival : a._zOrder - b._zOrder;
+ });
//don't need to check children recursively, that's done in visit of each child
this._reorderChildDirty = false;
From 4065f898072f535c4f6a22b808818a870d2c3cc2 Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Fri, 16 Aug 2013 10:18:17 +0800
Subject: [PATCH 041/141] fixed #2530 LabelTTF's Stroke style has been modified
to outer stroke
---
cocos2d/label_nodes/CCLabelTTF.js | 49 ++++++++++++++++++-------------
1 file changed, 28 insertions(+), 21 deletions(-)
diff --git a/cocos2d/label_nodes/CCLabelTTF.js b/cocos2d/label_nodes/CCLabelTTF.js
index 9317c9b566..965717b8b2 100644
--- a/cocos2d/label_nodes/CCLabelTTF.js
+++ b/cocos2d/label_nodes/CCLabelTTF.js
@@ -334,6 +334,7 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
this._fontName = textDefinition.fontName;
this._fontSize = textDefinition.fontSize;
this._fontStyleStr = this._fontSize + "px '" + this._fontName + "'";
+ this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(this._fontName,this._fontSize);
// shadow
if ( textDefinition.shadowEnabled)
@@ -537,9 +538,8 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
/**
* renders the label
* @param {CanvasRenderingContext2D|Null} ctx
- * @param {Number} renderType
*/
- draw:function (ctx, renderType) {
+ draw:function (ctx) {
var context = ctx || cc.renderContext;
if (this._flipX)
context.scale(-1, 1);
@@ -553,8 +553,9 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
context.font = this._fontStyleStr;
//stroke style setup
- if(this._strokeEnabled){
- context.lineWidth = this._strokeSize;
+ var locStrokeEnabled = this._strokeEnabled;
+ if(locStrokeEnabled){
+ context.lineWidth = this._strokeSize * 2;
context.strokeStyle = this._strokeColorStr;
}
@@ -579,29 +580,34 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
else if (locHAlignment === cc.TEXT_ALIGNMENT_CENTER)
xoffset = locContentSizeWidth / 2;
if (this._isMultiLine) {
+ var locStrings = this._strings;
var yOffset = 0, strLen = this._strings.length;
if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM)
yOffset = locFontHeight + locContentSizeHeight - locFontHeight * strLen;
else if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_CENTER)
yOffset = locFontHeight / 2 + (locContentSizeHeight - locFontHeight * strLen) / 2;
+ var tmpLineStr = null, tmpYOffset = null;
for (var i = 0; i < strLen; i++) {
- var line = this._strings[i];
- context.fillText(line, xoffset, -locContentSizeHeight + (locFontHeight * i) + yOffset);
+ tmpLineStr = locStrings[i];
+ tmpYOffset = -locContentSizeHeight + (locFontHeight * i) + yOffset;
+ if(locStrokeEnabled)
+ context.strokeText(tmpLineStr, xoffset, tmpYOffset);
+ context.fillText(tmpLineStr, xoffset, tmpYOffset);
}
} else {
if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM){
- context.fillText(this._string, xoffset, 0);
- if(this._strokeEnabled)
+ if(locStrokeEnabled)
context.strokeText(this._string, xoffset, 0);
+ context.fillText(this._string, xoffset, 0);
}else if(locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_TOP){
- context.fillText(this._string, xoffset, -locContentSizeHeight);
- if(this._strokeEnabled)
+ if(locStrokeEnabled)
context.strokeText(this._string, xoffset, -locContentSizeHeight);
+ context.fillText(this._string, xoffset, -locContentSizeHeight);
}else{
- context.fillText(this._string, xoffset, -locContentSizeHeight/2);
- if(this._strokeEnabled)
+ if(locStrokeEnabled)
context.strokeText(this._string, xoffset, -locContentSizeHeight/2);
+ context.fillText(this._string, xoffset, -locContentSizeHeight/2);
}
}
@@ -1107,7 +1113,8 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{
context.fillStyle = this._fillColorStr;
//stroke style setup
- if (this._strokeEnabled) {
+ var locStrokeEnabled = this._strokeEnabled;
+ if (locStrokeEnabled) {
context.lineWidth = this._strokeSize;
context.strokeStyle = this._strokeColorStr;
}
@@ -1156,26 +1163,26 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{
for (var i = 0; i < locStrLen; i++) {
var line = this._strings[i];
var tmpOffsetY = -locContentSizeHeight + (locFontHeight * i) + yOffset;
- context.fillText(line, xOffset, tmpOffsetY);
- if (this._strokeEnabled)
+ if (locStrokeEnabled)
context.strokeText(line, xOffset, tmpOffsetY);
+ context.fillText(line, xOffset, tmpOffsetY);
}
} else {
if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM) {
yOffset = isNegForOffsetY ? -locStrokeShadowOffsetY : 0;
- context.fillText(this._string, xOffset, yOffset);
- if (this._strokeEnabled)
+ if (locStrokeEnabled)
context.strokeText(this._string, xOffset, yOffset);
+ context.fillText(this._string, xOffset, yOffset);
} else if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_TOP) {
yOffset = isNegForOffsetY ? -locStrokeShadowOffsetY/2 -locContentSizeHeight : - locContentSizeHeight + locStrokeShadowOffsetY/2;
- context.fillText(this._string, xOffset, yOffset);
- if (this._strokeEnabled)
+ if (locStrokeEnabled)
context.strokeText(this._string, xOffset, yOffset);
+ context.fillText(this._string, xOffset, yOffset);
} else {
yOffset = isNegForOffsetY ? -locStrokeShadowOffsetY -locContentSizeHeight / 2 : - locContentSizeHeight / 2;
- context.fillText(this._string, xOffset, yOffset);
- if (this._strokeEnabled)
+ if (locStrokeEnabled)
context.strokeText(this._string, xOffset, yOffset);
+ context.fillText(this._string, xOffset, yOffset);
}
}
},
From a148f3770b1ce80042456457cc81bca4a4d1867b Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Fri, 16 Aug 2013 11:06:27 +0800
Subject: [PATCH 042/141] fixed #2481 add a clearRect function to
cc.RenderTexture
---
cocos2d/misc_nodes/CCRenderTexture.js | 10 ++++++++--
1 file changed, 8 insertions(+), 2 deletions(-)
diff --git a/cocos2d/misc_nodes/CCRenderTexture.js b/cocos2d/misc_nodes/CCRenderTexture.js
index 8d5b8ac8e9..d6506e8017 100644
--- a/cocos2d/misc_nodes/CCRenderTexture.js
+++ b/cocos2d/misc_nodes/CCRenderTexture.js
@@ -220,6 +220,10 @@ cc.RenderTextureCanvas = cc.Node.extend(/** @lends cc.RenderTextureCanvas# */{
this.end();
},
+ clearRect:function(x, y, width, height){
+ this._cacheContext.clearRect(x, y, width, height);
+ },
+
/**
* clears the texture with a specified depth value
* @param {Number} depthValue
@@ -271,9 +275,11 @@ cc.RenderTextureCanvas = cc.Node.extend(/** @lends cc.RenderTextureCanvas# */{
//! make sure all children are drawn
this.sortAllChildren();
var locChildren = this._children;
- for (var i = 0; i < locChildren.length; i++) {
+ var childrenLen = locChildren.length;
+ var selfSprite = this._sprite;
+ for (var i = 0; i < childrenLen; i++) {
var getChild = locChildren[i];
- if (getChild != this._sprite)
+ if (getChild != selfSprite)
getChild.visit();
}
From 76b339805735e0098b0d5417ede262666b07a79e Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Fri, 16 Aug 2013 11:13:09 +0800
Subject: [PATCH 043/141] fixed #2481 add a clearRect function to
cc.RenderTexture
---
cocos2d/misc_nodes/CCRenderTexture.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/cocos2d/misc_nodes/CCRenderTexture.js b/cocos2d/misc_nodes/CCRenderTexture.js
index d6506e8017..24a472fdbc 100644
--- a/cocos2d/misc_nodes/CCRenderTexture.js
+++ b/cocos2d/misc_nodes/CCRenderTexture.js
@@ -221,7 +221,7 @@ cc.RenderTextureCanvas = cc.Node.extend(/** @lends cc.RenderTextureCanvas# */{
},
clearRect:function(x, y, width, height){
- this._cacheContext.clearRect(x, y, width, height);
+ this._cacheContext.clearRect(x, y, width, -height);
},
/**
From 9b29125679e0ca22f91a656291dc3aa3783f17ad Mon Sep 17 00:00:00 2001
From: 06wj <06wj@163.com>
Date: Fri, 16 Aug 2013 21:30:24 +0800
Subject: [PATCH 044/141] Revert "use native sort function when sort children"
This reverts commit 46f3a133b74f25239306e7966019ecc009d8c68b.
---
cocos2d/base_nodes/CCNode.js | 50 ++++++++++++++++++++++++++++--------
1 file changed, 40 insertions(+), 10 deletions(-)
diff --git a/cocos2d/base_nodes/CCNode.js b/cocos2d/base_nodes/CCNode.js
index 26d54ae743..f57ebb7ca6 100644
--- a/cocos2d/base_nodes/CCNode.js
+++ b/cocos2d/base_nodes/CCNode.js
@@ -402,7 +402,8 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
*/
setRotation: function (newRotation) {
this._rotationX = this._rotationY = newRotation;
- this._rotationRadiansX = this._rotationRadiansY = newRotation * (Math.PI / 180);
+ this._rotationRadiansX = this._rotationX * (Math.PI / 180);
+ this._rotationRadiansY = this._rotationY * (Math.PI / 180);
this.setNodeDirty();
},
@@ -472,7 +473,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
*/
setScale:function (scale, scaleY) {
this._scaleX = scale;
- this._scaleY = scaleY === undefined ? scale : scaleY;
+ this._scaleY = (scaleY || scaleY === 0) ? scaleY : scale;
this.setNodeDirty();
},
@@ -1180,10 +1181,24 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
*/
sortAllChildren:function () {
if (this._reorderChildDirty) {
+ var _children = this._children;
+ var i, j, length = _children.length,tempChild;
+
// insertion sort
- this._children.sort(function(a, b){
- return a._zOrder === b._zOrder ? a._orderOfArrival - b._orderOfArrival : a._zOrder - b._zOrder;
- });
+ for (i = 0; i < length; i++) {
+ var tempItem = _children[i];
+ j = i - 1;
+ tempChild = _children[j];
+
+ //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
+ while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
+ ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
+ tempChild = _children[j];
+ _children[j + 1] = tempChild;
+ j = j - 1;
+ }
+ _children[j + 1] = tempItem;
+ }
//don't need to check children recursively, that's done in visit of each child
this._reorderChildDirty = false;
@@ -2232,7 +2247,8 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
*/
setRotation:function (newRotation) {
this._rotationX = this._rotationY = newRotation;
- this._rotationRadiansX = this._rotationRadiansY = newRotation * 0.017453292519943295; //(Math.PI / 180);
+ this._rotationRadiansX = this._rotationX * 0.017453292519943295; //(Math.PI / 180);
+ this._rotationRadiansY = this._rotationY * 0.017453292519943295; //(Math.PI / 180);
this.setNodeDirty();
},
@@ -2302,7 +2318,7 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
*/
setScale:function (scale, scaleY) {
this._scaleX = scale;
- this._scaleY = scaleY === undefined ? scale : scaleY;
+ this._scaleY = scaleY || scale;
this.setNodeDirty();
},
@@ -3008,10 +3024,24 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
*/
sortAllChildren:function () {
if (this._reorderChildDirty) {
+ var _children = this._children;
+ var i, j, length = _children.length,tempChild;
+
// insertion sort
- this._childre.sort(function(a, b){
- return a._zOrder === b._zOrder ? a._orderOfArrival - b._orderOfArrival : a._zOrder - b._zOrder;
- });
+ for (i = 0; i < length; i++) {
+ var tempItem = _children[i];
+ j = i - 1;
+ tempChild = _children[j];
+
+ //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
+ while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
+ ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
+ tempChild = _children[j];
+ _children[j + 1] = tempChild;
+ j = j - 1;
+ }
+ _children[j + 1] = tempItem;
+ }
//don't need to check children recursively, that's done in visit of each child
this._reorderChildDirty = false;
From 51093cdd911e295dc443027f3e43a84ca7d85c3e Mon Sep 17 00:00:00 2001
From: 06wj <06wj@163.com>
Date: Fri, 16 Aug 2013 21:32:58 +0800
Subject: [PATCH 045/141] fix setScale bug
---
cocos2d/base_nodes/CCNode.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/cocos2d/base_nodes/CCNode.js b/cocos2d/base_nodes/CCNode.js
index f57ebb7ca6..ea08902136 100644
--- a/cocos2d/base_nodes/CCNode.js
+++ b/cocos2d/base_nodes/CCNode.js
@@ -2318,7 +2318,7 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
*/
setScale:function (scale, scaleY) {
this._scaleX = scale;
- this._scaleY = scaleY || scale;
+ this._scaleY = scaleY === undefined ? scale : scaleY;
this.setNodeDirty();
},
From a347ebe4ac7a631553146562d22a3ca888578eae Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Mon, 19 Aug 2013 17:02:31 +0800
Subject: [PATCH 046/141] Fixed #2550 Fixed TableView's bug that contentSize is
wrong when changing datasource
---
extensions/GUI/CCScrollView/CCTableView.js | 1 +
1 file changed, 1 insertion(+)
diff --git a/extensions/GUI/CCScrollView/CCTableView.js b/extensions/GUI/CCScrollView/CCTableView.js
index 2948ee6e89..0cc114dcd8 100644
--- a/extensions/GUI/CCScrollView/CCTableView.js
+++ b/extensions/GUI/CCScrollView/CCTableView.js
@@ -376,6 +376,7 @@ cc.TableView = cc.ScrollView.extend({
* reloads data from data source. the view will be refreshed.
*/
reloadData:function () {
+ this._oldDirection = cc.SCROLLVIEW_DIRECTION_NONE;
var locCellsUsed = this._cellsUsed;
for (var i = 0; i < locCellsUsed.count(); i++) {
var cell = locCellsUsed.objectAtIndex(i);
From 5b278dc6855377c3f02acc33b6da70eb61b378e1 Mon Sep 17 00:00:00 2001
From: WanderWang
Date: Mon, 19 Aug 2013 18:06:37 +0800
Subject: [PATCH 047/141] Improve performance cost when creating lots of
CCLabelTTF
add cc.LabelTTF.__fontHeightCache to cache cc.LabelTTF.__getFontHeightByDiv 's result
---
cocos2d/label_nodes/CCLabelTTF.js | 8 +++++++-
1 file changed, 7 insertions(+), 1 deletion(-)
diff --git a/cocos2d/label_nodes/CCLabelTTF.js b/cocos2d/label_nodes/CCLabelTTF.js
index 9317c9b566..df62f64150 100644
--- a/cocos2d/label_nodes/CCLabelTTF.js
+++ b/cocos2d/label_nodes/CCLabelTTF.js
@@ -1432,11 +1432,17 @@ cc.LabelTTF.__labelHeightDiv.style.lineHeight = "normal";
document.body.appendChild(cc.LabelTTF.__labelHeightDiv);
cc.LabelTTF.__getFontHeightByDiv = function(fontName, fontSize){
+ var clientHeight = cc.LabelTTF.__fontHeightCache[fontName + "." + fontSize];
+ if (clientHeight > 0) return clientHeight;
var labelDiv = cc.LabelTTF.__labelHeightDiv;
labelDiv.style.fontFamily = fontName;
labelDiv.style.fontSize = fontSize + "px";
- return labelDiv.clientHeight ;
+ clientHeight = labelDiv.clientHeight ;
+ cc.LabelTTF.__fontHeightCache[fontName + "." + fontSize] = clientHeight;
+ return clientHeight;
};
+cc.LabelTTF.__fontHeightCache = {};
+
From ee4c9b7b8b24b8698a8dc4291a1c96258eef87c0 Mon Sep 17 00:00:00 2001
From: "christian.schwartz@gmail.com"
Date: Mon, 19 Aug 2013 12:56:50 +0200
Subject: [PATCH 048/141] fixed SpriteFrame.initWithTextureFilename converted
(pixel-based) rect to pixels
---
cocos2d/sprite_nodes/CCSpriteFrame.js | 7 +++----
1 file changed, 3 insertions(+), 4 deletions(-)
diff --git a/cocos2d/sprite_nodes/CCSpriteFrame.js b/cocos2d/sprite_nodes/CCSpriteFrame.js
index 09aa85ae7f..8f90447d3b 100644
--- a/cocos2d/sprite_nodes/CCSpriteFrame.js
+++ b/cocos2d/sprite_nodes/CCSpriteFrame.js
@@ -278,14 +278,13 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* @param {cc.Size} originalSize
*/
initWithTextureFilename:function (filename, rect, rotated, offset, originalSize) {
- var rectInPixels = cc.RECT_POINTS_TO_PIXELS(rect);
offset = offset || cc.size(0, 0);
- originalSize = originalSize || rectInPixels.size;
+ originalSize = originalSize || rect.size;
this._texture = null;
this._textureFilename = filename;
- this._rectInPixels = rectInPixels;
- this._rect = cc.RECT_PIXELS_TO_POINTS(rectInPixels);
+ this._rectInPixels = rect;
+ this._rect = cc.RECT_PIXELS_TO_POINTS(rect);
this._rotated = rotated || false;
this._offsetInPixels = offset;
this._offset = cc.POINT_PIXELS_TO_POINTS(offset);
From 1061b359dccff486d911372ef4b24d9a6b359a5a Mon Sep 17 00:00:00 2001
From: "christian.schwartz@gmail.com"
Date: Tue, 20 Aug 2013 08:58:03 +0200
Subject: [PATCH 049/141] fixed UnitTest.SpriteFrame.initWithTexture
---
cocos2d/sprite_nodes/CCSpriteFrame.js | 3 +--
1 file changed, 1 insertion(+), 2 deletions(-)
diff --git a/cocos2d/sprite_nodes/CCSpriteFrame.js b/cocos2d/sprite_nodes/CCSpriteFrame.js
index 8f90447d3b..1c1920e525 100644
--- a/cocos2d/sprite_nodes/CCSpriteFrame.js
+++ b/cocos2d/sprite_nodes/CCSpriteFrame.js
@@ -242,8 +242,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
It is assumed that the frame was not trimmed.
*/
case 2:
- var rectInPixels = cc.RECT_POINTS_TO_PIXELS(rect);
- return this.initWithTexture(texture, rectInPixels, false, cc.PointZero(), rectInPixels.size);
+ return this.initWithTexture(texture, rect, false, cc.PointZero(), rect.size);
break;
/** Initializes a cc.SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels.
From 17d94574087111a3ca4c3cdc255147c08583b508 Mon Sep 17 00:00:00 2001
From: WanderWang
Date: Tue, 20 Aug 2013 16:42:52 +0800
Subject: [PATCH 050/141] Update CCScheduler.scheduleCallbackForTarget 's
comment
Update CCScheduler.scheduleCallbackForTarget 's comment @example has a mistake
---
cocos2d/CCScheduler.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/cocos2d/CCScheduler.js b/cocos2d/CCScheduler.js
index 5fd64c219e..1936d460cd 100644
--- a/cocos2d/CCScheduler.js
+++ b/cocos2d/CCScheduler.js
@@ -641,7 +641,7 @@ cc.Scheduler = cc.Class.extend(/** @lends cc.Scheduler# */{
* @param {Boolean} paused
* @example
* //register a schedule to scheduler
- * cc.Director.getInstance().getScheduler().scheduleCallbackForTarget(function, this, interval, repeat, delay, !this._isRunning );
+ * cc.Director.getInstance().getScheduler().scheduleCallbackForTarget(this, function, interval, repeat, delay, !this._isRunning );
*/
scheduleCallbackForTarget:function (target, callback_fn, interval, repeat, delay, paused) {
cc.Assert(callback_fn, "scheduler.scheduleCallbackForTarget() Argument callback_fn must be non-NULL");
From 381a77d4f049bfddd0b49e991900b9006dd7ae0b Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Tue, 20 Aug 2013 17:18:25 +0800
Subject: [PATCH 051/141] Fixed #2467 Fixed a bug of cc.LabelBMFont that it's
very slow when calling setString
---
cocos2d/label_nodes/CCLabelBMFont.js | 63 ++++++++++++++++++++++------
cocos2d/sprite_nodes/CCSprite.js | 21 +++++-----
2 files changed, 61 insertions(+), 23 deletions(-)
diff --git a/cocos2d/label_nodes/CCLabelBMFont.js b/cocos2d/label_nodes/CCLabelBMFont.js
index fc25cc3aec..1d7eb2e581 100644
--- a/cocos2d/label_nodes/CCLabelBMFont.js
+++ b/cocos2d/label_nodes/CCLabelBMFont.js
@@ -574,8 +574,15 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
this._displayedOpacity = this._realOpacity * parentOpacity/255.0;
var locChildren = this._children;
for(var i = 0; i< locChildren; i++){
- locChildren[i].updateDisplayedOpacity(this._displayedOpacity);
+ var locChild = locChildren[i];
+ if(cc.Browser.supportWebGL){
+ locChild.updateDisplayedOpacity(this._displayedOpacity);
+ }else{
+ cc.NodeRGBA.prototype.updateDisplayedOpacity.call(locChild, this._displayedOpacity);
+ locChild.setNodeDirty();
+ }
}
+ this._changeTextureColor();
},
isCascadeOpacityEnabled:function(){
@@ -603,7 +610,38 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
var locChildren = this._children;
for(var i = 0;i < locChildren.length;i++){
- locChildren[i].updateDisplayedColor(this._displayedColor);
+ var locChild = locChildren[i];
+ if(cc.Browser.supportWebGL){
+ locChild.updateDisplayedColor(this._displayedColor);
+ }else{
+ cc.NodeRGBA.prototype.updateDisplayedColor.call(locChild, this._displayedColor);
+ locChild.setNodeDirty();
+ }
+ }
+ this._changeTextureColor();
+ },
+
+ _changeTextureColor:function(){
+ if(cc.Browser.supportWebGL){
+ return;
+ }
+ var locElement, locTexture = this.getTexture();
+ if (locTexture) {
+ locElement = locTexture.getHtmlElementObj();
+ if (!locElement)
+ return;
+ var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(this._originalTexture.getHtmlElementObj());
+ if (cacheTextureForColor) {
+ if (locElement instanceof HTMLCanvasElement && !this._rectRotated)
+ cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, null, locElement);
+ else{
+ locElement = cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor);
+ locTexture = new cc.Texture2D();
+ locTexture.initWithElement(locElement);
+ locTexture.handleLoadedTexture();
+ this.setTexture(locTexture);
+ }
+ }
}
},
@@ -744,22 +782,17 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
if (!fontChar) {
fontChar = new cc.Sprite();
if ((key === 32) && (locContextType === cc.CANVAS)) {
- fontChar.init();
- fontChar.setTextureRect(cc.RectZero(), false, cc.SizeZero());
+ fontChar.initWithTexture(locTexture, cc.RectZero(), false);
} else
fontChar.initWithTexture(locTexture, rect, false);
this.addChild(fontChar, 0, i);
} else {
if ((key === 32) && (locContextType === cc.CANVAS)) {
- fontChar.init();
- fontChar.setTextureRect(cc.RectZero(), false, cc.SizeZero());
+ fontChar.setTextureRect(rect, false, cc.SizeZero());
} else {
// updating previous sprite
- if (locContextType === cc.CANVAS)
- fontChar.initWithTexture(locTexture, rect, false);
- else
- fontChar.setTextureRect(rect, false, rect.size);
+ fontChar.setTextureRect(rect, false, rect.size);
// restore to default in case they were modified
fontChar.setVisible(true);
}
@@ -767,8 +800,14 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
// Apply label properties
fontChar.setOpacityModifyRGB(this._opacityModifyRGB);
// Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on
- fontChar.updateDisplayedColor(this._displayedColor);
- fontChar.updateDisplayedOpacity(this._displayedOpacity);
+ if(cc.Browser.supportWebGL){
+ fontChar.updateDisplayedColor(this._displayedColor);
+ fontChar.updateDisplayedOpacity(this._displayedOpacity);
+ }else{
+ cc.NodeRGBA.prototype.updateDisplayedColor.call(fontChar, this._displayedColor);
+ cc.NodeRGBA.prototype.updateDisplayedOpacity.call(fontChar, this._displayedOpacity);
+ fontChar.setNodeDirty();
+ }
var yOffset = this._configuration.commonHeight - fontDef.yOffset;
var fontPos = cc.p(nextFontPositionX + fontDef.xOffset + fontDef.rect.width * 0.5 + kerningAmount,
diff --git a/cocos2d/sprite_nodes/CCSprite.js b/cocos2d/sprite_nodes/CCSprite.js
index d7083774f0..206353645f 100644
--- a/cocos2d/sprite_nodes/CCSprite.js
+++ b/cocos2d/sprite_nodes/CCSprite.js
@@ -1224,9 +1224,9 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
}
},
- _changeTextureColor:function () {
- var locElement, locTexture = this._texture;
- if (locTexture) {
+ _changeTextureColor: function () {
+ var locElement, locTexture = this._texture, locRect = this.getTextureRect();
+ if (locTexture && locRect.width > 0) {
locElement = locTexture.getHtmlElementObj();
if (!locElement)
return;
@@ -1235,16 +1235,15 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
if (cacheTextureForColor) {
this._colorized = true;
//generate color texture cache
- if (locElement instanceof HTMLCanvasElement && !this._rectRotated)
- cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, this.getTextureRect(), locElement);
- else {
-
- locElement = cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, this.getTextureRect());
+ /*if (locElement instanceof HTMLCanvasElement && !this._rectRotated)
+ cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, locRect, locElement);
+ else {*/
+ locElement = cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, locRect);
locTexture = new cc.Texture2D();
locTexture.initWithElement(locElement);
locTexture.handleLoadedTexture();
this.setTexture(locTexture);
- }
+ //}
}
}
},
@@ -1258,7 +1257,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
if (this._isLighterMode)
context.globalCompositeOperation = 'lighter';
- context.globalAlpha = this._realOpacity / 255;
+ context.globalAlpha = this._displayedOpacity / 255;
var locRect = this._rect;
var flipXOffset = 0 | (this._offsetPosition.x), flipYOffset = -this._offsetPosition.y - locRect.height;
if (this._flipX) {
@@ -1269,7 +1268,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
flipYOffset = this._offsetPosition.y;
context.scale(1, -1);
}
- if (this._texture) {
+ if (this._texture && locRect.width > 0 && locRect.height > 0) {
var image = this._texture.getHtmlElementObj();
if (this._colorized) {
context.drawImage(image,
From 7b1ff857a0738f836115a6e7af59d425e0e419e9 Mon Sep 17 00:00:00 2001
From: xbruce
Date: Tue, 20 Aug 2013 21:44:10 +0800
Subject: [PATCH 052/141] Update CCSAXParser.js
Improve Plist file loading error message to more friendly
---
cocos2d/platform/CCSAXParser.js | 5 +++--
1 file changed, 3 insertions(+), 2 deletions(-)
diff --git a/cocos2d/platform/CCSAXParser.js b/cocos2d/platform/CCSAXParser.js
index b2067405bc..9654aef41e 100644
--- a/cocos2d/platform/CCSAXParser.js
+++ b/cocos2d/platform/CCSAXParser.js
@@ -46,6 +46,7 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{
* @return {Array} plist object array
*/
parse:function (textxml) {
+ var path = textxml;
textxml = this.getList(textxml);
// get a reference to the requested corresponding xml file
if (window.DOMParser) {
@@ -61,7 +62,7 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{
var plist = this.xmlDoc.documentElement;
if (plist.tagName != 'plist')
- throw "cocos2d:Not a plist file";
+ throw "cocos2d: " + path + " is not a plist file";
// Get first real node
var node = null;
@@ -245,4 +246,4 @@ cc.SAXParser.getInstance = function () {
return this._instance;
};
-cc.SAXParser._instance = null;
\ No newline at end of file
+cc.SAXParser._instance = null;
From 24091bdb069174b5c80c8416bf61ee87fdc87700 Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Wed, 21 Aug 2013 10:03:43 +0800
Subject: [PATCH 053/141] fixed #2531 Asynchronous loading resources for
rendering classes has been implemented.
---
HelloHTML5World/cocos2d.js | 2 +-
cocos2d/CCLoader.js | 4 +-
cocos2d/label_nodes/CCLabelTTF.js | 6 +
cocos2d/menu_nodes/CCMenuItem.js | 56 +++-
.../particle_nodes/CCParticleSystemQuad.js | 27 +-
cocos2d/sprite_nodes/CCSprite.js | 270 ++++++++++++------
cocos2d/sprite_nodes/CCSpriteFrame.js | 124 ++++----
cocos2d/sprite_nodes/CCSpriteFrameCache.js | 22 +-
cocos2d/textures/CCTexture2D.js | 47 ++-
cocos2d/textures/CCTextureCache.js | 6 +-
extensions/CCBReader/CCNodeLoader.js | 10 +-
.../GUI/CCControlExtension/CCControlButton.js | 12 +-
.../GUI/CCControlExtension/CCScale9Sprite.js | 19 +-
13 files changed, 404 insertions(+), 201 deletions(-)
diff --git a/HelloHTML5World/cocos2d.js b/HelloHTML5World/cocos2d.js
index 30638e6410..fb091f964f 100644
--- a/HelloHTML5World/cocos2d.js
+++ b/HelloHTML5World/cocos2d.js
@@ -33,7 +33,7 @@
showFPS:true,
frameRate:60,
loadExtension:false,
- renderMode:0, //Choose of RenderMode: 0(default), 1(Canvas only), 2(WebGL only)
+ renderMode:1, //Choose of RenderMode: 0(default), 1(Canvas only), 2(WebGL only)
tag:'gameCanvas', //the dom element to run cocos2d on
engineDir:'../cocos2d/',
//SingleEngineFile:'',
diff --git a/cocos2d/CCLoader.js b/cocos2d/CCLoader.js
index 3b4b6d8cb5..68c55b566e 100644
--- a/cocos2d/CCLoader.js
+++ b/cocos2d/CCLoader.js
@@ -223,7 +223,6 @@ cc.Loader = cc.Class.extend(/** @lends cc.Loader# */{
}
},
-
_schedulePreload: function () {
var _self = this;
this._interval = setInterval(function () {
@@ -235,7 +234,6 @@ cc.Loader = cc.Class.extend(/** @lends cc.Loader# */{
clearInterval(this._interval);
},
-
_getResType: function (resInfo) {
var isFont = resInfo.fontName;
if (isFont != null) {
@@ -270,9 +268,9 @@ cc.Loader = cc.Class.extend(/** @lends cc.Loader# */{
this._selector(this);
}
-
this._curNumber = 0;
this._loadedNumber = 0;
+ this._totalNumber = 0;
},
_registerFaceFont: function (fontRes) {
diff --git a/cocos2d/label_nodes/CCLabelTTF.js b/cocos2d/label_nodes/CCLabelTTF.js
index e5f1d8d315..680c8f2d6d 100644
--- a/cocos2d/label_nodes/CCLabelTTF.js
+++ b/cocos2d/label_nodes/CCLabelTTF.js
@@ -540,6 +540,9 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
* @param {CanvasRenderingContext2D|Null} ctx
*/
draw:function (ctx) {
+ if(!this._string || this._string == "")
+ return;
+
var context = ctx || cc.renderContext;
if (this._flipX)
context.scale(-1, 1);
@@ -1334,6 +1337,9 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{
* @param {WebGLRenderingContext} ctx 3d context of canvas
*/
draw:function (ctx) {
+ if(!this._string || this._string == "")
+ return;
+
var gl = ctx || cc.renderContext, locTexture = this._texture;
//cc.Assert(!this._batchNode, "If cc.Sprite is being rendered by cc.SpriteBatchNode, cc.Sprite#draw SHOULD NOT be called");
diff --git a/cocos2d/menu_nodes/CCMenuItem.js b/cocos2d/menu_nodes/CCMenuItem.js
index 65b8f313af..ea1ff9fc7a 100644
--- a/cocos2d/menu_nodes/CCMenuItem.js
+++ b/cocos2d/menu_nodes/CCMenuItem.js
@@ -601,14 +601,14 @@ cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{
},
/**
- * @return {cc.Node}
+ * @return {cc.Sprite}
*/
getNormalImage:function () {
return this._normalImage;
},
/**
- * @param {cc.Node} normalImage
+ * @param {cc.Sprite} normalImage
*/
setNormalImage:function (normalImage) {
if (this._normalImage == normalImage) {
@@ -623,19 +623,26 @@ cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{
}
this._normalImage = normalImage;
- this.setContentSize(this._normalImage.getContentSize());
- this._updateImagesVisibility();
+ if(normalImage.textureLoaded()){
+ this.setContentSize(this._normalImage.getContentSize());
+ this._updateImagesVisibility();
+ } else {
+ normalImage.addLoadedEventListener(function(sender){
+ this.setContentSize(sender.getContentSize());
+ this._updateImagesVisibility();
+ }, this);
+ }
},
/**
- * @return {cc.Node}
+ * @return {cc.Sprite}
*/
getSelectedImage:function () {
return this._selectedImage;
},
/**
- * @param {cc.Node} selectedImage
+ * @param {cc.Sprite} selectedImage
*/
setSelectedImage:function (selectedImage) {
if (this._selectedImage == selectedImage)
@@ -651,7 +658,13 @@ cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{
}
this._selectedImage = selectedImage;
- this._updateImagesVisibility();
+ if(selectedImage.textureLoaded()){
+ this._updateImagesVisibility();
+ } else {
+ selectedImage.addLoadedEventListener(function(sender){
+ this._updateImagesVisibility();
+ }, this);
+ }
},
/**
@@ -662,7 +675,7 @@ cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{
},
/**
- * @param {cc.Node} disabledImage
+ * @param {cc.Sprite} disabledImage
*/
setDisabledImage:function (disabledImage) {
if (this._disabledImage == disabledImage)
@@ -677,7 +690,13 @@ cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{
this.removeChild(this._disabledImage, true);
this._disabledImage = disabledImage;
- this._updateImagesVisibility();
+ if(disabledImage.textureLoaded()){
+ this._updateImagesVisibility();
+ } else {
+ disabledImage.addLoadedEventListener(function(sender){
+ this._updateImagesVisibility();
+ }, this);
+ }
},
/**
@@ -693,11 +712,22 @@ cc.MenuItemSprite = cc.MenuItem.extend(/** @lends cc.MenuItemSprite# */{
this.setNormalImage(normalSprite);
this.setSelectedImage(selectedSprite);
this.setDisabledImage(disabledSprite);
- if (this._normalImage)
- this.setContentSize(this._normalImage.getContentSize());
+ var locNormalImage = this._normalImage;
+ if (locNormalImage){
+ if(locNormalImage.textureLoaded()){
+ this.setContentSize(locNormalImage.getContentSize());
+ this.setCascadeColorEnabled(true);
+ this.setCascadeOpacityEnabled(true);
+ } else{
+ locNormalImage.addLoadedEventListener(function(sender){
+ this.setContentSize(sender.getContentSize());
+ this.setCascadeColorEnabled(true);
+ this.setCascadeOpacityEnabled(true);
+ }, this);
+ }
+ }
+
- this.setCascadeColorEnabled(true);
- this.setCascadeOpacityEnabled(true);
return true;
},
diff --git a/cocos2d/particle_nodes/CCParticleSystemQuad.js b/cocos2d/particle_nodes/CCParticleSystemQuad.js
index 743932d362..8eb273f696 100644
--- a/cocos2d/particle_nodes/CCParticleSystemQuad.js
+++ b/cocos2d/particle_nodes/CCParticleSystemQuad.js
@@ -55,6 +55,8 @@ cc.ParticleSystemQuad = cc.ParticleSystem.extend(/** @lends cc.ParticleSystemQua
_buffersVBO:null,
_pointRect:null,
+ _textureLoaded: null,
+
/**
* Constructor
* @override
@@ -65,6 +67,7 @@ cc.ParticleSystemQuad = cc.ParticleSystem.extend(/** @lends cc.ParticleSystemQua
this._quads = [];
this._indices = [];
this._pointRect = cc.RectZero();
+ this._textureLoaded = true;
if (cc.renderContextType === cc.WEBGL) {
this._quadsArrayBuffer = null;
@@ -342,18 +345,20 @@ cc.ParticleSystemQuad = cc.ParticleSystem.extend(/** @lends cc.ParticleSystemQua
/**
* set Texture of Particle System
* @override
- * @param {HTMLImageElement|HTMLCanvasElement|cc.Texture2D} texture
- * @param {Boolean} isCallSuper is direct call super method
+ * @param {cc.Texture2D} texture
*/
- setTexture:function (texture, isCallSuper) {
- if (isCallSuper != null && isCallSuper === true) {
- cc.ParticleSystem.prototype.setTexture.call(this, texture);
- return;
+ setTexture:function (texture) {
+ if(texture.isLoaded()){
+ var size = texture.getContentSize();
+ this.setTextureWithRect(texture, cc.rect(0, 0, size.width, size.height));
+ } else {
+ this._textureLoaded = false;
+ texture.addLoadedEventListener(function(sender){
+ this._textureLoaded = true;
+ var size = sender.getContentSize();
+ this.setTextureWithRect(sender, cc.rect(0, 0, size.width, size.height));
+ }, this);
}
-
- var size = texture.getContentSize();
-
- this.setTextureWithRect(texture, cc.rect(0, 0, size.width, size.height));
},
/**
@@ -497,6 +502,8 @@ cc.ParticleSystemQuad = cc.ParticleSystem.extend(/** @lends cc.ParticleSystemQua
*/
draw:function (ctx) {
cc.Assert(!this._batchNode, "draw should not be called when added to a particleBatchNode");
+ if(!this._textureLoaded)
+ return;
if (cc.renderContextType === cc.CANVAS)
this._drawForCanvas(ctx);
diff --git a/cocos2d/sprite_nodes/CCSprite.js b/cocos2d/sprite_nodes/CCSprite.js
index d7083774f0..3a98068113 100644
--- a/cocos2d/sprite_nodes/CCSprite.js
+++ b/cocos2d/sprite_nodes/CCSprite.js
@@ -331,6 +331,26 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
_flipX:false, //Whether the sprite is flipped horizontally or not.
_flipY:false, //Whether the sprite is flipped vertically or not.
+ _textureLoaded:false,
+ _loadedEventListeners:null,
+
+ textureLoaded:function(){
+ return this._textureLoaded;
+ },
+
+ addLoadedEventListener:function(callback, target){
+ this._loadedEventListeners.push({eventCallback:callback, eventTarget:target});
+ },
+
+ _callLoadedEventCallbacks:function(){
+ var locListeners = this._loadedEventListeners;
+ for(var i = 0, len = locListeners.length; i < len; i++){
+ var selCallback = locListeners[i];
+ selCallback.eventCallback.call(selCallback.eventTarget, this);
+ }
+ locListeners.length = 0;
+ },
+
/**
* 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.
@@ -431,12 +451,27 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
*/
initWithSpriteFrame:function (spriteFrame) {
cc.Assert(spriteFrame != null, "");
+ if(!spriteFrame.textureLoaded()){
+ //add event listener
+ this._textureLoaded = false;
+ spriteFrame.addLoadedEventListener(this._spriteFrameLoadedCallback, this);
+ }
var ret = this.initWithTexture(spriteFrame.getTexture(), spriteFrame.getRect());
this.setDisplayFrame(spriteFrame);
return ret;
},
+ _spriteFrameLoadedCallback:function(spriteFrame){
+ this.setNodeDirty();
+ this.setTextureRect(spriteFrame.getRect(), spriteFrame.isRotated(), spriteFrame.getOriginalSize());
+ var curColor = this.getColor();
+ if (curColor.r !== 255 || curColor.g !== 255 || curColor.b !== 255)
+ this._changeTextureColor();
+
+ this._callLoadedEventCallbacks();
+ },
+
/**
* Initializes a sprite with a sprite frame name.
* A cc.SpriteFrame will be fetched from the cc.SpriteFrameCache by name.
@@ -539,10 +574,10 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
* @override
*/
removeAllChildren:function (cleanup) {
- var locChildren = this._children;
- if (this._batchNode && locChildren != null) {
- for (var i = 0; i < locChildren.length; i++)
- this._batchNode.removeSpriteFromAtlas(locChildren[i]);
+ var locChildren = this._children, locBatchNode = this._batchNode;
+ if (locBatchNode && locChildren != null) {
+ for (var i = 0, len = locChildren.length; i < len; i++)
+ locBatchNode.removeSpriteFromAtlas(locChildren[i]);
}
cc.Node.prototype.removeAllChildren.call(this, cleanup);
@@ -845,6 +880,8 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
this._offsetPosition = cc.p(0, 0);
this._unflippedOffsetPositionFromCenter = cc.p(0, 0);
this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST};
+ this._textureLoaded = true;
+ this._loadedEventListeners = [];
if (fileName) {
if (typeof(fileName) == "string") {
@@ -853,12 +890,6 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
} else if (typeof(fileName) === "object") {
if (fileName instanceof cc.SpriteFrame) {
this.initWithSpriteFrame(fileName);
- } else if (fileName instanceof cc.SpriteBatchNode) {
- if (arguments.length > 1) {
- var rect = arguments[1];
- if (rect instanceof cc.Rect)
- this.initWithBatchNode(fileName, rect);
- }
} else if ((fileName instanceof HTMLImageElement) || (fileName instanceof HTMLCanvasElement)) {
var texture2d = new cc.Texture2D();
texture2d.initWithElement(fileName);
@@ -901,6 +932,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
// update texture (calls _updateBlendFunc)
this.setTexture(null);
+ this._textureLoaded = true;
this._flipX = this._flipY = false;
// default transform anchor: center
@@ -933,29 +965,11 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
*/
initWithFile:function (filename, rect) {
cc.Assert(filename != null, "Sprite#initWithFile():Invalid filename for sprite");
- var selfPointer = this;
var texture = cc.TextureCache.getInstance().textureForKey(filename);
if (!texture) {
filename = cc.FileUtils.getInstance().fullPathForFilename(filename);
- this._visible = false;
- var loadImg = new Image();
- loadImg.addEventListener("load", function () {
- if (!rect) {
- rect = cc.rect(0, 0, loadImg.width, loadImg.height);
- rect = cc.RECT_PIXELS_TO_POINTS(rect);
- }
- var texture2d = new cc.Texture2D();
- texture2d.initWithElement(loadImg);
- texture2d.handleLoadedTexture();
- selfPointer.initWithTexture(texture2d, rect);
- cc.TextureCache.getInstance().cacheImage(filename, loadImg);
- selfPointer._visible = true;
- });
- loadImg.addEventListener("error", function () {
- cc.log("load failure:" + filename);
- });
- loadImg.src = filename;
- return true;
+ texture = cc.TextureCache.getInstance().addImage(filename);
+ return this.initWithTexture(texture, rect);
} else {
if (!rect) {
var size = texture.getContentSize();
@@ -963,7 +977,6 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
}
return this.initWithTexture(texture, rect);
}
- return false;
},
/**
@@ -1006,6 +1019,16 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
this._offsetPosition = cc.p(0, 0);
this._hasChildren = false;
+ var locTextureLoaded = texture.isLoaded();
+ this._textureLoaded = locTextureLoaded;
+
+ if(!locTextureLoaded){
+ this._rectRotated = rotated || false;
+ this._rect = rect;
+ texture.addLoadedEventListener(this._textureLoadedCallback, this);
+ return true;
+ }
+
if (!rect) {
rect = cc.rect(0, 0, 0, 0);
rect.size = texture.getContentSize();
@@ -1021,6 +1044,25 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
return true;
},
+ _textureLoadedCallback:function(sender){
+ this._textureLoaded = true;
+ var locRect = this._rect;
+ if (!locRect) {
+ locRect = cc.rect(0, 0, 0, 0);
+ locRect.size = sender.getContentSize();
+ }
+ this._originalTexture = sender;
+
+ this.setTexture(sender);
+ this.setTextureRect(locRect, this._rectRotated, locRect.size);
+
+ // by default use "Self Render".
+ // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render"
+ this.setBatchNode(null);
+
+ this._callLoadedEventCallbacks();
+ },
+
/**
* updates the texture rect of the CCSprite in points.
* @param {cc.Rect} rect a rect of texture
@@ -1142,22 +1184,36 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
this._unflippedOffsetPositionFromCenter.x = frameOffset.x;
this._unflippedOffsetPositionFromCenter.y = frameOffset.y;
+ // update rect
+ this._rectRotated = newFrame.isRotated();
+
var pNewTexture = newFrame.getTexture();
+ var locTextureLoaded = newFrame.textureLoaded();
+ if(!locTextureLoaded){
+ this._textureLoaded = false;
+ newFrame.addLoadedEventListener(function(sender){
+ this._textureLoaded = true;
+ var locNewTexture = sender.getTexture();
+ if (locNewTexture != this._texture)
+ this.setTexture(locNewTexture);
+ this.setTextureRect(sender.getRect(), this._rectRotated, sender.getOriginalSize());
+ this._callLoadedEventCallbacks();
+ },this);
+ }
// update texture before updating texture rect
if (pNewTexture != this._texture)
this.setTexture(pNewTexture);
- // update rect
- this._rectRotated = newFrame.isRotated();
-
if (this._rectRotated)
this._originalTexture = pNewTexture;
this.setTextureRect(newFrame.getRect(), this._rectRotated, newFrame.getOriginalSize());
this._colorized = false;
- var curColor = this.getColor();
- if (curColor.r !== 255 || curColor.g !== 255 || curColor.b !== 255)
- this._changeTextureColor();
+ if (locTextureLoaded) {
+ var curColor = this.getColor();
+ if (curColor.r !== 255 || curColor.g !== 255 || curColor.b !== 255)
+ this._changeTextureColor();
+ }
},
/**
@@ -1217,7 +1273,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
// CCSprite: setTexture doesn't work when the sprite is rendered using a CCSpriteSheet
cc.Assert(!texture || texture instanceof cc.Texture2D, "setTexture expects a CCTexture2D. Invalid argument");
if (this._texture != texture) {
- if(texture&&texture.getHtmlElementObj() instanceof HTMLImageElement){
+ if(texture && texture.getHtmlElementObj() instanceof HTMLImageElement){
this._originalTexture = texture;
}
this._texture = texture;
@@ -1238,7 +1294,6 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
if (locElement instanceof HTMLCanvasElement && !this._rectRotated)
cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, this.getTextureRect(), locElement);
else {
-
locElement = cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, this.getTextureRect());
locTexture = new cc.Texture2D();
locTexture.initWithElement(locElement);
@@ -1251,9 +1306,12 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
/**
* draw sprite to canvas
- * @param {CanvasContext} ctx 2d context of canvas
+ * @param {CanvasRenderingContext2D} ctx 2d context of canvas
*/
draw:function (ctx) {
+ if(!this._textureLoaded)
+ return;
+
var context = ctx || cc.renderContext;
if (this._isLighterMode)
context.globalCompositeOperation = 'lighter';
@@ -1375,6 +1433,25 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
_flipX:false, //Whether the sprite is flipped horizontally or not.
_flipY:false, //Whether the sprite is flipped vertically or not.
+ _textureLoaded:false,
+
+ textureLoaded:function(){
+ return this._textureLoaded;
+ },
+
+ addLoadedEventListener:function(callback, target){
+ this._loadedEventListeners.push({eventCallback:callback, eventTarget:target});
+ },
+
+ _callLoadedEventCallbacks:function(){
+ var locListeners = this._loadedEventListeners;
+ for(var i = 0, len = locListeners.length; i < len; i++){
+ var selCallback = locListeners[i];
+ selCallback.eventCallback.call(selCallback.eventTarget, this);
+ }
+ locListeners.length = 0;
+ },
+
/**
* 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.
@@ -1483,12 +1560,23 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
*/
initWithSpriteFrame:function (spriteFrame) {
cc.Assert(spriteFrame != null, "");
+ if(!spriteFrame.textureLoaded()){
+ //add event listener
+ this._textureLoaded = false;
+ spriteFrame.addLoadedEventListener(this._spriteFrameLoadedCallback, this);
+ }
var ret = this.initWithTexture(spriteFrame.getTexture(), spriteFrame.getRect());
this.setDisplayFrame(spriteFrame);
return ret;
},
+ _spriteFrameLoadedCallback:function(spriteFrame){
+ this.setNodeDirty();
+ this.setTextureRect(spriteFrame.getRect(), spriteFrame.isRotated(), spriteFrame.getOriginalSize());
+ this._callLoadedEventCallbacks();
+ },
+
/**
* Initializes a sprite with a sprite frame name.
* A cc.SpriteFrame will be fetched from the cc.SpriteFrameCache by name.
@@ -1591,10 +1679,10 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
* @override
*/
removeAllChildren:function (cleanup) {
- var locChildren = this._children;
- if (this._batchNode && locChildren != null) {
- for (var i = 0; i < locChildren.length; i++)
- this._batchNode.removeSpriteFromAtlas(locChildren[i]);
+ var locChildren = this._children, locBatchNode = this._batchNode;
+ if (locBatchNode && locChildren != null) {
+ for (var i = 0, len = locChildren.length; i < len; i++)
+ locBatchNode.removeSpriteFromAtlas(locChildren[i]);
}
cc.Node.prototype.removeAllChildren.call(this, cleanup);
@@ -1902,6 +1990,8 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
this._quad = new cc.V3F_C4B_T2F_Quad();
this._quadWebBuffer = cc.renderContext.createBuffer();
this._quadDirty = true;
+ this._textureLoaded = true;
+ this._loadedEventListeners = [];
if (fileName) {
if (typeof(fileName) == "string") {
@@ -1910,19 +2000,13 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
} else if (typeof(fileName) == "object") {
if (fileName instanceof cc.SpriteFrame) {
this.initWithSpriteFrame(fileName);
- } else if (fileName instanceof cc.SpriteBatchNode) {
- if (arguments.length > 1) {
- var rect = arguments[1];
- if (rect instanceof cc.Rect)
- this.initWithBatchNode(fileName, rect);
- }
} else if ((fileName instanceof HTMLImageElement) || (fileName instanceof HTMLCanvasElement)) {
var texture2d = new cc.Texture2D();
texture2d.initWithElement(fileName);
texture2d.handleLoadedTexture();
- this.initWithTexture(texture2d)
+ this.initWithTexture(texture2d);
} else if (fileName instanceof cc.Texture2D) {
- this.initWithTexture(fileName)
+ this.initWithTexture(fileName);
}
}
}
@@ -1965,7 +2049,7 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
// update texture (calls _updateBlendFunc)
this.setTexture(null);
-
+ this._textureLoaded = true;
this._flipX = this._flipY = false;
// default transform anchor: center
@@ -2005,39 +2089,18 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
*/
initWithFile:function (filename, rect) {
cc.Assert(filename != null, "Sprite#initWithFile():Invalid filename for sprite");
- var selfPointer = this;
-
var texture = cc.TextureCache.getInstance().textureForKey(filename);
if (!texture) {
filename = cc.FileUtils.getInstance().fullPathForFilename(filename);
- this._visible = false;
- var loadImg = new Image();
- loadImg.addEventListener("load", function () {
- if (!rect) {
- rect = cc.rect(0, 0, loadImg.width, loadImg.height);
- }
- var texture2d = new cc.Texture2D();
- texture2d.initWithElement(loadImg);
- texture2d.handleLoadedTexture();
- selfPointer.initWithTexture(texture2d, rect);
- cc.TextureCache.getInstance().cacheImage(filename, loadImg);
- selfPointer._visible = true;
- });
- loadImg.addEventListener("error", function () {
- cc.log("load failure:" + filename);
- });
- loadImg.src = filename;
- return true;
+ texture = cc.TextureCache.getInstance().addImage(filename);
+ return this.initWithTexture(texture, rect);
} else {
- if (texture) {
- if (!rect) {
- var size = texture.getContentSize();
- rect = cc.rect(0, 0, size.width, size.height);
- }
- return this.initWithTexture(texture, rect);
+ if (!rect) {
+ var size = texture.getContentSize();
+ rect = cc.rect(0, 0, size.width, size.height);
}
+ return this.initWithTexture(texture, rect);
}
- return false;
},
/**
@@ -2086,6 +2149,16 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
this._quad.tl.colors = tmpColor;
this._quad.tr.colors = tmpColor;
+ var locTextureLoaded = texture.isLoaded();
+ this._textureLoaded = locTextureLoaded;
+
+ if(!locTextureLoaded){
+ this._rectRotated = rotated || false;
+ this._rect = rect;
+ texture.addLoadedEventListener(this._textureLoadedCallback, this);
+ return true;
+ }
+
if (!rect) {
rect = cc.rect(0, 0, 0, 0);
rect.size = texture.getContentSize();
@@ -2099,6 +2172,23 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
this._quadDirty = true;
return true;
},
+
+ _textureLoadedCallback:function(sender){
+ this._textureLoaded = true;
+ var locRect = this._rect;
+ if (!locRect) {
+ locRect = cc.rect(0, 0, 0, 0);
+ locRect.size = sender.getContentSize();
+ }
+
+ this.setTexture(sender);
+ this.setTextureRect(locRect, this._rectRotated, locRect.size);
+
+ // by default use "Self Render".
+ // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render"
+ this.setBatchNode(null);
+ this._quadDirty = true;
+ },
/**
* updates the texture rect of the CCSprite in points.
* @param {cc.Rect} rect a rect of texture
@@ -2316,8 +2406,23 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
*/
setDisplayFrame:function (newFrame) {
this.setNodeDirty();
- this._unflippedOffsetPositionFromCenter = newFrame.getOffset();
+ var frameOffset = newFrame.getOffset();
+ this._unflippedOffsetPositionFromCenter.x = frameOffset.x;
+ this._unflippedOffsetPositionFromCenter.y = frameOffset.y;
+
var pNewTexture = newFrame.getTexture();
+ var locTextureLoaded = newFrame.textureLoaded();
+ if(!locTextureLoaded){
+ this._textureLoaded = false;
+ newFrame.addLoadedEventListener(function(sender){
+ this._textureLoaded = true;
+ var locNewTexture = sender.getTexture();
+ if (locNewTexture != this._texture)
+ this.setTexture(locNewTexture);
+ this.setTextureRect(sender.getRect(), sender._rectRotated, sender.getOriginalSize());
+ this._callLoadedEventCallbacks();
+ },this);
+ }
// update texture before updating texture rect
if (pNewTexture != this._texture)
this.setTexture(pNewTexture);
@@ -2507,6 +2612,9 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
* draw sprite to canvas
*/
draw:function () {
+ if(!this._textureLoaded)
+ return;
+
var gl = cc.renderContext, locTexture = this._texture;
//cc.Assert(!this._batchNode, "If cc.Sprite is being rendered by cc.SpriteBatchNode, cc.Sprite#draw SHOULD NOT be called");
diff --git a/cocos2d/sprite_nodes/CCSpriteFrame.js b/cocos2d/sprite_nodes/CCSpriteFrame.js
index 09aa85ae7f..cf836776dd 100644
--- a/cocos2d/sprite_nodes/CCSpriteFrame.js
+++ b/cocos2d/sprite_nodes/CCSpriteFrame.js
@@ -49,6 +49,8 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
_originalSizeInPixels:null,
_texture:null,
_textureFilename:"",
+ _textureLoaded:false,
+ _eventListeners:null,
ctor:function () {
this._offset = cc.p(0, 0);
@@ -60,9 +62,28 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
this._originalSizeInPixels = cc.size(0, 0);
this._textureFilename = "";
this._texture = null;
+ this._textureLoaded = false;
+ this._eventListeners = [];
},
// attributes
+ textureLoaded:function(){
+ return this._textureLoaded;
+ },
+
+ addLoadedEventListener:function(callback, target){
+ this._eventListeners.push({eventCallback:callback, eventTarget:target});
+ },
+
+ _callLoadedEventCallbacks:function(){
+ var locListeners = this._eventListeners;
+ for(var i = 0, len = locListeners.length; i < len; i++){
+ var selCallback = locListeners[i];
+ selCallback.eventCallback.call(selCallback.eventTarget, this);
+ }
+ locListeners.length = 0;
+ },
+
/**
* @return {cc.Rect}
*/
@@ -166,7 +187,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
/**
* get texture of the frame
- * @return {cc.Texture2D|HTMLImageElement}
+ * @return {cc.Texture2D}
*/
getTexture:function () {
if (this._texture)
@@ -178,11 +199,41 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
/**
* set texture of the frame, the texture is retained
- * @param {cc.Texture2D|HTMLImageElement} texture
+ * @param {cc.Texture2D} texture
*/
setTexture:function (texture) {
if (this._texture != texture) {
+ var locLoaded = texture.isLoaded();
+ this._textureLoaded = locLoaded;
this._texture = texture;
+ if(!locLoaded){
+ texture.addLoadedEventListener(function(sender){
+ this._textureLoaded = true;
+ if(this._rotated){
+ var tempElement = sender.getHtmlElementObj();
+ tempElement = cc.cutRotateImageToCanvas(tempElement, this.getRect());
+ var tempTexture = new cc.Texture2D();
+ tempTexture.initWithElement(tempElement);
+ tempTexture.handleLoadedTexture();
+ this.setTexture(tempTexture);
+
+ var rect = this.getRect();
+ this.setRect(cc.rect(0, 0, rect.width, rect.height));
+ }
+ var locRect = this._rect;
+ if(locRect.width === 0 && locRect.height === 0){
+ var locContentSize = sender.getContentSize();
+ this._rect.width = locContentSize.width;
+ this._rect.height = locContentSize.height;
+ this._rectInPixels = cc.RECT_POINTS_TO_PIXELS(this._rect);
+ this._originalSizeInPixels.width = this._rectInPixels.width;
+ this._originalSizeInPixels.height = this._rectInPixels.height;
+ this._originalSize.width = locContentSize.width;
+ this._originalSize.height = locContentSize.height;
+ }
+ this._callLoadedEventCallbacks();
+ }, this);
+ }
}
},
@@ -236,34 +287,20 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* @return {Boolean}
*/
initWithTexture:function (texture, rect, rotated, offset, originalSize) {
- var argnum = arguments.length;
- switch (argnum) {
- /** Initializes a cc.SpriteFrame with a texture, rect in points.
- It is assumed that the frame was not trimmed.
- */
- case 2:
- var rectInPixels = cc.RECT_POINTS_TO_PIXELS(rect);
- return this.initWithTexture(texture, rectInPixels, false, cc.PointZero(), rectInPixels.size);
- break;
-
- /** Initializes a cc.SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels.
- The originalSize is the size in points of the frame before being trimmed.
- */
- case 5:
- this._texture = texture;
- this._rectInPixels = rect;
- this._rect = cc.RECT_PIXELS_TO_POINTS(rect);
- this._offsetInPixels = offset;
- this._offset = cc.POINT_PIXELS_TO_POINTS(this._offsetInPixels);
- this._originalSizeInPixels = originalSize;
- this._originalSize = cc.SIZE_PIXELS_TO_POINTS(this._originalSizeInPixels);
- this._rotated = rotated;
- return true;
- break;
- default:
- throw "Argument must be non-nil ";
- break;
- }
+ var rectInPixels = cc.RECT_POINTS_TO_PIXELS(rect);
+ rotated = rotated || false;
+ offset = offset || cc.PointZero();
+ originalSize = originalSize || rectInPixels.size;
+
+ this.setTexture(texture);
+ this._rectInPixels = rectInPixels;
+ this._rect = cc.RECT_PIXELS_TO_POINTS(rectInPixels);
+ this._offsetInPixels = offset;
+ this._offset = cc.POINT_PIXELS_TO_POINTS(this._offsetInPixels);
+ this._originalSizeInPixels = originalSize;
+ this._originalSize = cc.SIZE_PIXELS_TO_POINTS(this._originalSizeInPixels);
+ this._rotated = rotated;
+ return true;
},
/**
@@ -326,11 +363,11 @@ cc.SpriteFrame.create = function (filename, rect, rotated, offset, originalSize)
/**
* Create a cc.SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels.
- * @param {cc.Texture2D|HTMLImageElement} texture
+ * @param {cc.Texture2D} texture
* @param {cc.Rect} rect
- * @param {Boolean} rotated
- * @param {cc.Point} offset
- * @param {cc.Size} originalSize
+ * @param {Boolean} [rotated=]
+ * @param {cc.Point} [offset=]
+ * @param {cc.Size} [originalSize=]
* @return {cc.SpriteFrame}
* @example
* //Create a cc.SpriteFrame with a texture, rect in texture.
@@ -340,25 +377,8 @@ cc.SpriteFrame.create = function (filename, rect, rotated, offset, originalSize)
* var frame2 = cc.SpriteFrame.createWithTexture(texture, frameRect, rotated, offset, sourceSize);
*/
cc.SpriteFrame.createWithTexture = function (texture, rect, rotated, offset, originalSize) {
- var argnum = arguments.length;
var spriteFrame = new cc.SpriteFrame();
- switch (argnum) {
- /** Create a cc.SpriteFrame with a texture, rect in points.
- It is assumed that the frame was not trimmed.
- */
- case 2:
- spriteFrame.initWithTexture(texture, rect);
- break;
- /** Create a cc.SpriteFrame with a texture, rect, rotated, offset and originalSize in pixels.
- The originalSize is the size in points of the frame before being trimmed.
- */
- case 5:
- spriteFrame.initWithTexture(texture, rect, rotated, offset, originalSize);
- break;
- default:
- throw "Argument must be non-nil ";
- break;
- }
+ spriteFrame.initWithTexture(texture, rect, rotated, offset, originalSize);
return spriteFrame;
};
diff --git a/cocos2d/sprite_nodes/CCSpriteFrameCache.js b/cocos2d/sprite_nodes/CCSpriteFrameCache.js
index f0dc3faadb..90f7336750 100644
--- a/cocos2d/sprite_nodes/CCSpriteFrameCache.js
+++ b/cocos2d/sprite_nodes/CCSpriteFrameCache.js
@@ -138,16 +138,18 @@ cc.SpriteFrameCache = cc.Class.extend(/** @lends cc.SpriteFrameCache# */{
if(cc.renderContextType === cc.CANVAS && spriteFrame.isRotated()){
//clip to canvas
- var tempElement = spriteFrame.getTexture().getHtmlElementObj();
- tempElement = cc.cutRotateImageToCanvas(tempElement, spriteFrame.getRect());
- var tempTexture = new cc.Texture2D();
- tempTexture.initWithElement(tempElement);
- tempTexture.handleLoadedTexture();
- spriteFrame.setTexture(tempTexture);
-
- var rect = spriteFrame.getRect();
- spriteFrame.setRect(cc.rect(0, 0, rect.width, rect.height));
-
+ var locTexture = spriteFrame.getTexture();
+ if(locTexture.isLoaded()){
+ var tempElement = spriteFrame.getTexture().getHtmlElementObj();
+ tempElement = cc.cutRotateImageToCanvas(tempElement, spriteFrame.getRect());
+ var tempTexture = new cc.Texture2D();
+ tempTexture.initWithElement(tempElement);
+ tempTexture.handleLoadedTexture();
+ spriteFrame.setTexture(tempTexture);
+
+ var rect = spriteFrame.getRect();
+ spriteFrame.setRect(cc.rect(0, 0, rect.width, rect.height));
+ }
}
// add sprite frame
diff --git a/cocos2d/textures/CCTexture2D.js b/cocos2d/textures/CCTexture2D.js
index a3a93013e9..1033043f5d 100644
--- a/cocos2d/textures/CCTexture2D.js
+++ b/cocos2d/textures/CCTexture2D.js
@@ -150,6 +150,8 @@ cc.Texture2DWebGL = cc.Class.extend(/** @lends cc.Texture2D# */{
_htmlElementObj:null,
_webTextureObj:null,
+ _loadedEventListeners:null,
+
/*public:*/
ctor:function () {
this._pixelsWide = 0;
@@ -168,6 +170,7 @@ cc.Texture2DWebGL = cc.Class.extend(/** @lends cc.Texture2D# */{
this._isLoaded = false;
this._htmlElementObj = null;
this._webTextureObj = null;
+ this._loadedEventListeners = [];
},
releaseTexture:function () {
@@ -521,6 +524,7 @@ cc.Texture2DWebGL = cc.Class.extend(/** @lends cc.Texture2D# */{
this._hasPremultipliedAlpha = false;
this._hasMipmaps = false;
+ this._callLoadedEventCallbacks();
},
/**
@@ -903,6 +907,19 @@ cc.Texture2DWebGL = cc.Class.extend(/** @lends cc.Texture2D# */{
this._hasPremultipliedAlpha = uiImage.isPremultipliedAlpha();
return true;
+ },
+
+ addLoadedEventListener: function (callback, target) {
+ this._loadedEventListeners.push({eventCallback: callback, eventTarget: target});
+ },
+
+ _callLoadedEventCallbacks: function () {
+ var locListeners = this._loadedEventListeners;
+ for (var i = 0, len = locListeners.length; i < len; i++) {
+ var selCallback = locListeners[i];
+ selCallback.eventCallback.call(selCallback.eventTarget, this);
+ }
+ locListeners.length = 0;
}
});
@@ -920,11 +937,14 @@ cc.Texture2DCanvas = cc.Class.extend(/** @lends cc.Texture2D# */{
_contentSize:null,
_isLoaded:false,
_htmlElementObj:null,
+
+ _loadedEventListeners:null,
/*public:*/
ctor:function () {
this._contentSize = cc.size(0,0);
this._isLoaded = false;
this._htmlElementObj = null;
+ this._loadedEventListeners = [];
},
/**
@@ -975,11 +995,10 @@ cc.Texture2DCanvas = cc.Class.extend(/** @lends cc.Texture2D# */{
handleLoadedTexture:function () {
this._isLoaded = true;
+ var locElement = this._htmlElementObj;
+ this._contentSize = new cc.Size(locElement.width, locElement.height);
- var pixelsWide = this._htmlElementObj.width;
- var pixelsHigh = this._htmlElementObj.height;
-
- this._contentSize = new cc.Size(pixelsWide, pixelsHigh);
+ this._callLoadedEventCallbacks();
},
description:function () {
@@ -1096,8 +1115,6 @@ cc.Texture2DCanvas = cc.Class.extend(/** @lends cc.Texture2D# */{
return false;
},
-
-
/**
* These functions are needed to create mutable textures
* @param {Array} data
@@ -1112,8 +1129,6 @@ cc.Texture2DCanvas = cc.Class.extend(/** @lends cc.Texture2D# */{
return data;
},
-
-
/**
Drawing extensions to make it easy to draw basic quads using a CCTexture2D object.
These functions require gl.TEXTURE_2D and both gl.VERTEX_ARRAY and gl.TEXTURE_COORD_ARRAY client states to be enabled.
@@ -1135,8 +1150,6 @@ cc.Texture2DCanvas = cc.Class.extend(/** @lends cc.Texture2D# */{
//support only in WebGl rendering mode
},
-
-
/**
* Initializes a texture from a ETC file (note: initWithETCFile does not support on HTML5)
* @note Compatible to Cocos2d-x
@@ -1229,8 +1242,20 @@ cc.Texture2DCanvas = cc.Class.extend(/** @lends cc.Texture2D# */{
bitsPerPixelForFormat:function (format) {
//support only in WebGl rendering mode
return -1;
- }
+ },
+
+ addLoadedEventListener:function(callback, target){
+ this._loadedEventListeners.push({eventCallback:callback, eventTarget:target});
+ },
+ _callLoadedEventCallbacks:function(){
+ var locListeners = this._loadedEventListeners;
+ for(var i = 0, len = locListeners.length; i < len; i++){
+ var selCallback = locListeners[i];
+ selCallback.eventCallback.call(selCallback.eventTarget, this);
+ }
+ locListeners.length = 0;
+ }
});
cc.Texture2D = cc.Browser.supportWebGL ? cc.Texture2DWebGL : cc.Texture2DCanvas;
diff --git a/cocos2d/textures/CCTextureCache.js b/cocos2d/textures/CCTextureCache.js
index ae44271464..e59158e110 100644
--- a/cocos2d/textures/CCTextureCache.js
+++ b/cocos2d/textures/CCTextureCache.js
@@ -277,12 +277,12 @@ cc.TextureCacheCanvas = cc.Class.extend(/** @lends cc.TextureCacheCanvas# */{
cc.Assert(path != null, "TextureCache: path MUST not be null");
path = cc.FileUtils.getInstance().fullPathForFilename(path);
var texture = this._textures[path];
- var image;
+ var image,that;
if (texture) {
if(texture.isLoaded()){
this._addImageAsyncCallBack(target, selector);
}else{
- var that = this;
+ that = this;
image = texture.getHtmlElementObj();
image.addEventListener("load", function () {
texture.handleLoadedTexture();
@@ -293,7 +293,7 @@ cc.TextureCacheCanvas = cc.Class.extend(/** @lends cc.TextureCacheCanvas# */{
image = new Image();
image.crossOrigin = "Anonymous";
- var that = this;
+ that = this;
image.addEventListener("load", function () {
if (that._textures.hasOwnProperty(path))
that._textures[path].handleLoadedTexture();
diff --git a/extensions/CCBReader/CCNodeLoader.js b/extensions/CCBReader/CCNodeLoader.js
index 4505a08bd7..8e879cf9d7 100644
--- a/extensions/CCBReader/CCNodeLoader.js
+++ b/extensions/CCBReader/CCNodeLoader.js
@@ -489,13 +489,9 @@ cc.NodeLoader = cc.Class.extend({
if(spriteSheet.length == 0){
spriteFile = ccbReader.getCCBRootPath() + spriteFile;
var texture = cc.TextureCache.getInstance().addImage(spriteFile);
- var bounds;
- if(texture instanceof cc.Texture2D){
- var locContentSize = texture.getContentSize();
- bounds = cc.RectMake(0, 0, locContentSize.width, locContentSize.height);
- }else{
- bounds = cc.RECT_PIXELS_TO_POINTS(cc.RectMake(0, 0, texture.width, texture.height));
- }
+
+ var locContentSize = texture.getContentSize();
+ var bounds = cc.RectMake(0, 0, locContentSize.width, locContentSize.height);
spriteFrame = cc.SpriteFrame.createWithTexture(texture, bounds);
} else {
var frameCache = cc.SpriteFrameCache.getInstance();
diff --git a/extensions/GUI/CCControlExtension/CCControlButton.js b/extensions/GUI/CCControlExtension/CCControlButton.js
index 4612689f3e..6c41fc1a6c 100644
--- a/extensions/GUI/CCControlExtension/CCControlButton.js
+++ b/extensions/GUI/CCControlExtension/CCControlButton.js
@@ -226,7 +226,7 @@ cc.ControlButton = cc.Control.extend({
},
setPreferredSize:function (size) {
- if (size.width == 0 && size.height == 0) {
+ if (size.width === 0 && size.height === 0) {
this._adjustBackgroundImage = true;
} else {
this._adjustBackgroundImage = false;
@@ -598,12 +598,12 @@ cc.ControlButton = cc.Control.extend({
sprite.setAnchorPoint(cc.p(0.5, 0.5));
this.addChild(sprite);
- if (this._preferredSize.width != 0 || this._preferredSize.height != 0) {
+ if (this._preferredSize.width !== 0 || this._preferredSize.height !== 0) {
sprite.setPreferredSize(this._preferredSize);
}
// If the current state if equal to the given state we update the layout
- if (this.getState() == state) {
+ if (this._state === state) {
this.needsLayout();
}
},
@@ -621,7 +621,7 @@ cc.ControlButton = cc.Control.extend({
}
});
-cc.ControlButton.create = function (label, backgroundSprite) {
+cc.ControlButton.create = function(label, backgroundSprite) {
var controlButton;
if (arguments.length == 0) {
controlButton = new cc.ControlButton();
@@ -632,16 +632,14 @@ cc.ControlButton.create = function (label, backgroundSprite) {
} else if (arguments.length == 1) {
controlButton = new cc.ControlButton();
controlButton.initWithBackgroundSprite(arguments[0]);
- return controlButton;
} else if (arguments.length == 2) {
controlButton = new cc.ControlButton();
controlButton.initWithLabelAndBackgroundSprite(label, backgroundSprite);
- return controlButton;
} else if (arguments.length == 3) {
controlButton = new cc.ControlButton();
controlButton.initWithTitleAndFontNameAndFontSize(arguments[0], arguments[1], arguments[2]);
- return controlButton;
}
+ return controlButton;
};
diff --git a/extensions/GUI/CCControlExtension/CCScale9Sprite.js b/extensions/GUI/CCControlExtension/CCScale9Sprite.js
index 78cb10bfed..052216834b 100644
--- a/extensions/GUI/CCControlExtension/CCScale9Sprite.js
+++ b/extensions/GUI/CCControlExtension/CCScale9Sprite.js
@@ -319,7 +319,7 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
},
initWithBatchNode: function (batchNode, rect, rotated, capInsets) {
- if (arguments.length == 3) {
+ if (arguments.length === 3) {
capInsets = rotated;
rotated = false;
}
@@ -377,6 +377,16 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
var selTexture = spriteFrame.getTexture();
cc.Assert(selTexture != null, "Texture must be not nil");
+ if(!spriteFrame.textureLoaded()){
+ spriteFrame.addLoadedEventListener(function(sender){
+ // the texture is rotated on Canvas render mode, so isRotated always is false.
+ var preferredSize = this._preferredSize;
+ preferredSize = cc.size(preferredSize.width, preferredSize.height);
+ this.updateWithBatchNode(this._scale9Image, sender.getRect(), cc.Browser.supportWebGL ? sender.isRotated() : false, this._capInsets);
+ this.setPreferredSize(preferredSize);
+ this.m_positionsAreDirty = true;
+ },this);
+ }
var batchNode = cc.SpriteBatchNode.createWithTexture(selTexture, 9);
// the texture is rotated on Canvas render mode, so isRotated always is false.
return this.initWithBatchNode(batchNode, spriteFrame.getRect(), cc.Browser.supportWebGL ? spriteFrame.isRotated() : false, capInsets);
@@ -471,8 +481,11 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
var rectSize = rect.size;
this._originalSize.width = rectSize.width;
this._originalSize.height = rectSize.height;
- this._preferredSize.width = rectSize.width;
- this._preferredSize.height = rectSize.height;
+ var locPreferredSize = this._preferredSize;
+ if(locPreferredSize.width === 0 && locPreferredSize.height === 0){
+ locPreferredSize.width = rectSize.width;
+ locPreferredSize.height = rectSize.height;
+ }
var locCapInsetsInternal = this._capInsetsInternal;
if(!capInsets){
From 6449f2a64959fb6f271dc074ee70bf68821160ad Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Wed, 21 Aug 2013 11:27:06 +0800
Subject: [PATCH 054/141] fixed #2531 Asynchronous loading texture for
LabelBMFont on Canvas Mode has been implemented
---
cocos2d/label_nodes/CCLabelBMFont.js | 54 +++++++++++++++++++++-------
1 file changed, 42 insertions(+), 12 deletions(-)
diff --git a/cocos2d/label_nodes/CCLabelBMFont.js b/cocos2d/label_nodes/CCLabelBMFont.js
index 1d7eb2e581..f570f28364 100644
--- a/cocos2d/label_nodes/CCLabelBMFont.js
+++ b/cocos2d/label_nodes/CCLabelBMFont.js
@@ -445,6 +445,8 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
_cascadeColorEnabled:false,
_cascadeOpacityEnabled:false,
+ _textureLoaded: false,
+
_setString:function(newString, needUpdateLabel){
if(!needUpdateLabel){
this._string = newString;
@@ -489,10 +491,10 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
this._reusedChar = [];
},
/**
- * @param {CanvasContext} ctx
+ * @param {CanvasRenderingContext2D} ctx
*/
draw:function (ctx) {
- this._super();
+ this._super(ctx);
//LabelBMFont - Debug draw
if (cc.LABELBMFONT_DEBUG_DRAW) {
@@ -510,17 +512,19 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
* @param {cc.Color3B} color3
*/
setColor:function (color3) {
- if ((this._realColor.r == color3.r) && (this._realColor.g == color3.g) && (this._realColor.b == color3.b))
+ if (((this._realColor.r == color3.r) && (this._realColor.g == color3.g) && (this._realColor.b == color3.b)))
return;
this._displayedColor = {r:color3.r, g:color3.g, b:color3.b};
this._realColor = {r:color3.r, g:color3.g, b:color3.b};
- if(this._cascadeColorEnabled){
- var parentColor = cc.white();
- var locParent = this._parent;
- if(locParent && locParent.RGBAProtocol && locParent.isCascadeColorEnabled())
- parentColor = locParent.getDisplayedColor();
- this.updateDisplayedColor(parentColor);
+ if(this._textureLoaded){
+ if(this._cascadeColorEnabled){
+ var parentColor = cc.white();
+ var locParent = this._parent;
+ if(locParent && locParent.RGBAProtocol && locParent.isCascadeColorEnabled())
+ parentColor = locParent.getDisplayedColor();
+ this.updateDisplayedColor(parentColor);
+ }
}
},
@@ -681,10 +685,22 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
this._configuration = newConf;
this._fntFile = fntFile;
texture = cc.TextureCache.getInstance().addImage(this._configuration.getAtlasName());
+ var locIsLoaded = texture.isLoaded();
+ this._textureLoaded = locIsLoaded;
+ if(!locIsLoaded){
+ this._textureLoaded = false;
+ texture.addLoadedEventListener(function(sender){
+ this._textureLoaded = true;
+ //reset the LabelBMFont
+ this.initWithTexture(texture, theString.length)
+ this.setString(theString,true);
+ }, this);
+ }
} else{
texture = new cc.Texture2D();
var image = new Image();
texture.initWithElement(image);
+ this._textureLoaded = false;
}
if (this.initWithTexture(texture, theString.length)) {
@@ -1131,11 +1147,25 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
this._fntFile = fntFile;
this._configuration = newConf;
- this.setTexture(cc.TextureCache.getInstance().addImage(this._configuration.getAtlasName()));
- if (cc.renderContextType === cc.CANVAS) {
+ var texture = cc.TextureCache.getInstance().addImage(this._configuration.getAtlasName());
+ var locIsLoaded = texture.isLoaded();
+ this._textureLoaded = locIsLoaded;
+ this.setTexture(texture);
+ if (cc.renderContextType === cc.CANVAS)
this._originalTexture = this.getTexture();
- }
this.createFontChars();
+ if(!locIsLoaded){
+ texture.addLoadedEventListener(function(){
+ this._textureLoaded = true;
+ if(this._cascadeColorEnabled){
+ var parentColor = cc.white();
+ var locParent = this._parent;
+ if(locParent && locParent.RGBAProtocol && locParent.isCascadeColorEnabled())
+ parentColor = locParent.getDisplayedColor();
+ this.updateDisplayedColor(parentColor);
+ }
+ }, this);
+ }
}
},
From 4ca2a4baf41d5ac3782a9570a773cf659f34c073 Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Wed, 21 Aug 2013 14:56:59 +0800
Subject: [PATCH 055/141] fixed #2531 use direct calling function of parent
class instead this._super
---
HelloHTML5World/cocos2d.js | 2 +-
cocos2d/CCDrawingPrimitives.js | 2 +-
cocos2d/CCLoader.js | 2 +-
cocos2d/base_nodes/CCAtlasNode.js | 4 +-
cocos2d/draw_nodes/CCDrawNode.js | 6 +--
cocos2d/label_nodes/CCLabelAtlas.js | 24 +++++----
cocos2d/label_nodes/CCLabelBMFont.js | 13 ++---
.../CCTransition.js | 50 +++++++++----------
.../CCTransitionPageTurn.js | 4 +-
.../CCTransitionProgress.js | 27 ++++------
cocos2d/particle_nodes/CCParticleBatchNode.js | 15 +++---
cocos2d/physics_nodes/CCPhysicsDebugNode.js | 2 +-
cocos2d/physics_nodes/CCPhysicsSprite.js | 9 ++--
cocos2d/text_input_node/CCTextFieldTTF.js | 20 +++-----
cocos2d/tileMap_parallax_nodes/CCTMXLayer.js | 2 +-
cocos2d/touch_dispatcher/CCTouchHandler.js | 7 +--
16 files changed, 85 insertions(+), 104 deletions(-)
diff --git a/HelloHTML5World/cocos2d.js b/HelloHTML5World/cocos2d.js
index fb091f964f..30638e6410 100644
--- a/HelloHTML5World/cocos2d.js
+++ b/HelloHTML5World/cocos2d.js
@@ -33,7 +33,7 @@
showFPS:true,
frameRate:60,
loadExtension:false,
- renderMode:1, //Choose of RenderMode: 0(default), 1(Canvas only), 2(WebGL only)
+ renderMode:0, //Choose of RenderMode: 0(default), 1(Canvas only), 2(WebGL only)
tag:'gameCanvas', //the dom element to run cocos2d on
engineDir:'../cocos2d/',
//SingleEngineFile:'',
diff --git a/cocos2d/CCDrawingPrimitives.js b/cocos2d/CCDrawingPrimitives.js
index d21fd0d6a1..2851e42c54 100644
--- a/cocos2d/CCDrawingPrimitives.js
+++ b/cocos2d/CCDrawingPrimitives.js
@@ -608,7 +608,7 @@ cc.DrawingPrimitiveWebGL = cc.DrawingPrimitive.extend({
if (!ctx instanceof WebGLRenderingContext)
throw "Can't initialise DrawingPrimitiveWebGL. context need is WebGLRenderingContext";
- this._super(ctx);
+ cc.DrawingPrimitive.prototype.ctor.call(this, ctx);
this._color = new cc.Color4F(1.0, 1.0, 1.0, 1.0);
},
diff --git a/cocos2d/CCLoader.js b/cocos2d/CCLoader.js
index 68c55b566e..bcdad56b23 100644
--- a/cocos2d/CCLoader.js
+++ b/cocos2d/CCLoader.js
@@ -402,7 +402,7 @@ cc.LoaderScene = cc.Scene.extend(/** @lends cc.LoaderScene# */{
* Constructor
*/
ctor: function () {
- this._super();
+ cc.Scene.prototype.ctor.call(this);
this._winSize = cc.Director.getInstance().getWinSize();
},
init:function(){
diff --git a/cocos2d/base_nodes/CCAtlasNode.js b/cocos2d/base_nodes/CCAtlasNode.js
index fb3e1d34cb..1c1f4e042f 100644
--- a/cocos2d/base_nodes/CCAtlasNode.js
+++ b/cocos2d/base_nodes/CCAtlasNode.js
@@ -59,7 +59,7 @@ cc.AtlasNodeCanvas = cc.NodeRGBA.extend(/** @lends cc.AtlasNode# */{
_ignoreContentScaleFactor:false, // This variable is only used for CCLabelAtlas FPS display. So plz don't modify its value.
ctor:function () {
- this._super();
+ cc.NodeRGBA.prototype.ctor.call(this);
this._colorUnmodified = cc.white();
this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST};
this._ignoreContentScaleFactor = false;
@@ -294,7 +294,7 @@ cc.AtlasNodeWebGL = cc.NodeRGBA.extend({
_ignoreContentScaleFactor:false, // This variable is only used for CCLabelAtlas FPS display. So plz don't modify its value.
ctor:function () {
- this._super();
+ cc.NodeRGBA.prototype.ctor.call(this);
this._colorUnmodified = cc.white();
this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST};
this._ignoreContentScaleFactor = false;
diff --git a/cocos2d/draw_nodes/CCDrawNode.js b/cocos2d/draw_nodes/CCDrawNode.js
index 866379fa9e..3626cdfcc1 100644
--- a/cocos2d/draw_nodes/CCDrawNode.js
+++ b/cocos2d/draw_nodes/CCDrawNode.js
@@ -102,7 +102,7 @@ cc.DrawNodeCanvas = cc.Node.extend(/** @lends cc.DrawNodeCanvas# */{
// ----common function end ----
ctor:function () {
- this._super();
+ cc.Node.prototype.ctor.call(this);
this._buffer = [];
this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST);
},
@@ -224,13 +224,13 @@ cc.DrawNodeWebGL = cc.Node.extend(/** @lends cc.DrawNodeWebGL# */{
// ----common function end ----
ctor:function () {
- this._super();
+ cc.Node.prototype.ctor.call(this);
this._buffer = [];
this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST);
},
init:function () {
- if (this._super()) {
+ if (cc.Node.prototype.init.call(this)) {
this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_LENGTHTEXTURECOLOR));
this._ensureCapacity(512);
this._trianglesWebBuffer = cc.renderContext.createBuffer();
diff --git a/cocos2d/label_nodes/CCLabelAtlas.js b/cocos2d/label_nodes/CCLabelAtlas.js
index f04bbbfe8b..b12b1888e2 100644
--- a/cocos2d/label_nodes/CCLabelAtlas.js
+++ b/cocos2d/label_nodes/CCLabelAtlas.js
@@ -88,7 +88,7 @@ cc.LabelAtlasCanvas = cc.AtlasNode.extend(/** @lends cc.LabelAtlasCanvas# */{
* @param {cc.Color3B} color3
*/
setColor:function (color3) {
- this._super(color3);
+ cc.AtlasNode.prototype.setColor.call(this, color3);
this.updateAtlasValues();
},
/**
@@ -103,7 +103,7 @@ cc.LabelAtlasCanvas = cc.AtlasNode.extend(/** @lends cc.LabelAtlasCanvas# */{
* draw the label
*/
draw:function () {
- this._super();
+ cc.AtlasNode.prototype.draw.call(this);
if (cc.LABELATLAS_DEBUG_DRAW) {
var s = this.getContentSize();
var vertices = [cc.p(0, 0), cc.p(s.width, 0),
@@ -162,8 +162,9 @@ cc.LabelAtlasCanvas = cc.AtlasNode.extend(/** @lends cc.LabelAtlasCanvas# */{
this._string = label;
this.setContentSize(cc.size(len * this._itemWidth, this._itemHeight));
if (this._children) {
- for (var i = 0; i < this._children.length; i++) {
- var node = this._children[i];
+ var locChildren = this._children;
+ for (var i = 0, len = locChildren.length; i < len; i++) {
+ var node = locChildren[i];
if (node)
node.setVisible(false);
}
@@ -175,10 +176,11 @@ cc.LabelAtlasCanvas = cc.AtlasNode.extend(/** @lends cc.LabelAtlasCanvas# */{
setOpacity:function (opacity) {
if (this._opacity != opacity) {
- this._super(opacity);
- for (var i = 0; i < this._children.length; i++) {
- if (this._children[i])
- this._children[i].setOpacity(opacity);
+ cc.AtlasNode.prototype.setOpacity.call(this, opacity);
+ var locChildren = this._children;
+ for (var i = 0, len = locChildren.length; i < len; i++) {
+ if (locChildren[i])
+ locChildren[i].setOpacity(opacity);
}
}
}
@@ -248,7 +250,7 @@ cc.LabelAtlasWebGL = cc.AtlasNode.extend(/** @lends cc.LabelAtlasWebGL# */{
* @param {cc.Color3B} color3
*/
setColor:function (color3) {
- this._super(color3);
+ cc.AtlasNode.prototype.setColor.call(this, color3);
this.updateAtlasValues();
},
/**
@@ -263,7 +265,7 @@ cc.LabelAtlasWebGL = cc.AtlasNode.extend(/** @lends cc.LabelAtlasWebGL# */{
* draw the label
*/
draw:function () {
- this._super();
+ cc.AtlasNode.prototype.draw.call(this);
if (cc.LABELATLAS_DEBUG_DRAW) {
var s = this.getContentSize();
var vertices = [cc.p(0, 0), cc.p(s.width, 0),
@@ -364,7 +366,7 @@ cc.LabelAtlasWebGL = cc.AtlasNode.extend(/** @lends cc.LabelAtlasWebGL# */{
setOpacity:function (opacity) {
if (this._opacity !== opacity) {
- this._super(opacity);
+ cc.AtlasNode.prototype.setOpacity.call(this, opacity);
}
}
});
diff --git a/cocos2d/label_nodes/CCLabelBMFont.js b/cocos2d/label_nodes/CCLabelBMFont.js
index f570f28364..87ebcdeb1f 100644
--- a/cocos2d/label_nodes/CCLabelBMFont.js
+++ b/cocos2d/label_nodes/CCLabelBMFont.js
@@ -494,7 +494,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
* @param {CanvasRenderingContext2D} ctx
*/
draw:function (ctx) {
- this._super(ctx);
+ cc.SpriteBatchNode.prototype.draw.call(this, ctx);
//LabelBMFont - Debug draw
if (cc.LABELBMFONT_DEBUG_DRAW) {
@@ -1111,9 +1111,10 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
/**
* @param {Number} scale
+ * @param {Number} [scaleY=null]
*/
setScale:function (scale, scaleY) {
- this._super(scale, scaleY);
+ cc.Node.prototype.setScale.call(this, scale, scaleY);
this.updateLabel();
},
@@ -1121,7 +1122,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
* @param {Number} scaleX
*/
setScaleX:function (scaleX) {
- this._super(scaleX);
+ cc.Node.prototype.setScaleX.call(this,scaleX);
this.updateLabel();
},
@@ -1129,7 +1130,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
* @param {Number} scaleY
*/
setScaleY:function (scaleY) {
- this._super(scaleY);
+ cc.Node.prototype.setScaleY.call(this,scaleY);
this.updateLabel();
},
@@ -1177,12 +1178,12 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
},
/**
- * set the anchorpoint of the label
+ * set the AnchorPoint of the label
* @param {cc.Point} point
*/
setAnchorPoint:function (point) {
if (!cc.pointEqualToPoint(point, this._anchorPoint)) {
- this._super(point);
+ cc.Node.prototype.setAnchorPoint.call(this, point);
this.updateLabel();
}
},
diff --git a/cocos2d/layers_scenes_transitions_nodes/CCTransition.js b/cocos2d/layers_scenes_transitions_nodes/CCTransition.js
index 1ac114cc56..24ea00d9d9 100644
--- a/cocos2d/layers_scenes_transitions_nodes/CCTransition.js
+++ b/cocos2d/layers_scenes_transitions_nodes/CCTransition.js
@@ -102,8 +102,6 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
* stuff gets drawn here
*/
draw:function () {
- this._super();
-
if (this._isInSceneOnTop) {
this._outScene.visit();
this._inScene.visit();
@@ -117,7 +115,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
* custom onEnter
*/
onEnter:function () {
- cc.Scene.prototype.onEnter.call(this);
+ cc.Node.prototype.onEnter.call(this);
// disable events while transitions
cc.Director.getInstance().getTouchDispatcher().setDispatchEvents(false);
@@ -133,7 +131,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
* custom onExit
*/
onExit:function () {
- cc.Scene.prototype.onExit.call(this);
+ cc.Node.prototype.onExit.call(this);
// enable events while transitions
cc.Director.getInstance().getTouchDispatcher().setDispatchEvents(true);
@@ -149,7 +147,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
* custom cleanup
*/
cleanup:function () {
- this._super();
+ cc.Node.prototype.cleanup.call(this);
if (this._isSendCleanupToScene)
this._outScene.cleanup();
@@ -249,7 +247,7 @@ cc.TransitionSceneOriented = cc.TransitionScene.extend(/** @lends cc.TransitionS
* @return {Boolean}
*/
initWithDuration:function (t, scene, orientation) {
- if (this._super(t, scene)) {
+ if (cc.TransitionScene.prototype.initWithDuration.call(this, t, scene)) {
this._orientation = orientation;
}
return true;
@@ -290,7 +288,7 @@ cc.TransitionRotoZoom = cc.TransitionScene.extend(/** @lends cc.TransitionRotoZo
* @override
*/
onEnter:function () {
- this._super();
+ cc.TransitionScene.prototype.onEnter.call(this);
this._inScene.setScale(0.001);
this._outScene.setScale(1.0);
@@ -337,7 +335,7 @@ cc.TransitionJumpZoom = cc.TransitionScene.extend(/** @lends cc.TransitionJumpZo
* Custom on enter
*/
onEnter:function () {
- this._super();
+ cc.TransitionScene.prototype.onEnter.call(this);
var winSize = cc.Director.getInstance().getWinSize();
this._inScene.setScale(0.5);
@@ -383,7 +381,7 @@ cc.TransitionMoveInL = cc.TransitionScene.extend(/** @lends cc.TransitionMoveInL
* Custom on enter
*/
onEnter:function () {
- this._super();
+ cc.TransitionScene.prototype.onEnter.call(this);
this.initScenes();
var action = this.action();
@@ -559,7 +557,7 @@ cc.TransitionSlideInL = cc.TransitionScene.extend(/** @lends cc.TransitionSlideI
* custom on enter
*/
onEnter:function () {
- this._super();
+ cc.TransitionScene.prototype.onEnter.call(this);
this.initScenes();
var inA = this.action();
@@ -749,7 +747,7 @@ cc.TransitionShrinkGrow = cc.TransitionScene.extend(/** @lends cc.TransitionShri
* Custom on enter
*/
onEnter:function () {
- this._super();
+ cc.TransitionScene.prototype.onEnter.call(this);
this._inScene.setScale(0.001);
this._outScene.setScale(1.0);
@@ -804,7 +802,7 @@ cc.TransitionFlipX = cc.TransitionSceneOriented.extend(/** @lends cc.TransitionF
* custom on enter
*/
onEnter:function () {
- this._super();
+ cc.TransitionScene.prototype.onEnter.call(this);
var inA, outA;
this._inScene.setVisible(false);
@@ -874,7 +872,7 @@ cc.TransitionFlipY = cc.TransitionSceneOriented.extend(/** @lends cc.TransitionF
* custom on enter
*/
onEnter:function () {
- this._super();
+ cc.TransitionScene.prototype.onEnter.call(this);
var inA, outA;
this._inScene.setVisible(false);
@@ -943,7 +941,7 @@ cc.TransitionFlipAngular = cc.TransitionSceneOriented.extend(/** @lends cc.Trans
* custom on enter
*/
onEnter:function () {
- this._super();
+ cc.TransitionScene.prototype.onEnter.call(this);
var inA, outA;
this._inScene.setVisible(false);
@@ -1013,7 +1011,7 @@ cc.TransitionZoomFlipX = cc.TransitionSceneOriented.extend(/** @lends cc.Transit
* custom on enter
*/
onEnter:function () {
- this._super();
+ cc.TransitionScene.prototype.onEnter.call(this);
var inA, outA;
this._inScene.setVisible(false);
@@ -1089,7 +1087,7 @@ cc.TransitionZoomFlipY = cc.TransitionSceneOriented.extend(/** @lends cc.Transit
* custom on enter
*/
onEnter:function () {
- this._super();
+ cc.TransitionScene.prototype.onEnter.call(this);
var inA, outA;
this._inScene.setVisible(false);
@@ -1163,7 +1161,7 @@ cc.TransitionZoomFlipAngular = cc.TransitionSceneOriented.extend(/** @lends cc.T
* custom on enter
*/
onEnter:function () {
- this._super();
+ cc.TransitionScene.prototype.onEnter.call(this);
var inA, outA;
this._inScene.setVisible(false);
@@ -1236,7 +1234,7 @@ cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{
* Constructor
*/
ctor:function () {
- this._super();
+ cc.TransitionScene.prototype.ctor.call(this);
this._color = new cc.Color3B()
},
@@ -1244,7 +1242,7 @@ cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{
* custom on enter
*/
onEnter:function () {
- this._super();
+ cc.TransitionScene.prototype.onEnter.call(this);
var l = cc.LayerColor.create(this._color);
this._inScene.setVisible(false);
@@ -1265,7 +1263,7 @@ cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{
* custom on exit
*/
onExit:function () {
- this._super();
+ cc.TransitionScene.prototype.onExit.call(this);
this.removeChildByTag(cc.SCENE_FADE, false);
},
@@ -1278,7 +1276,7 @@ cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{
*/
initWithDuration:function (t, scene, color) {
color = color || cc.black();
- if (this._super(t, scene)) {
+ if (cc.TransitionScene.prototype.initWithDuration.call(this, t, scene)) {
this._color.r = color.r;
this._color.g = color.g;
this._color.b = color.b;
@@ -1315,7 +1313,7 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross
* custom on enter
*/
onEnter:function () {
- this._super();
+ cc.TransitionScene.prototype.onEnter.call(this);
// create a transparent color layer
// in which we are going to add our rendertextures
@@ -1378,7 +1376,7 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross
*/
onExit:function () {
this.removeChildByTag(cc.SCENE_FADE, false);
- this._super();
+ cc.TransitionScene.prototype.onExit.call(this);
},
/**
@@ -1418,7 +1416,7 @@ cc.TransitionTurnOffTiles = cc.TransitionScene.extend(/** @lends cc.TransitionTu
* custom on enter
*/
onEnter:function () {
- this._super();
+ cc.TransitionScene.prototype.onEnter.call(this);
var winSize = cc.Director.getInstance().getWinSize();
var aspect = winSize.width / winSize.height;
var x = 0 | (12 * aspect);
@@ -1465,7 +1463,7 @@ cc.TransitionSplitCols = cc.TransitionScene.extend(/** @lends cc.TransitionSplit
* custom on enter
*/
onEnter:function () {
- this._super();
+ cc.TransitionScene.prototype.onEnter.call(this);
this._inScene.setVisible(false);
var split = this.action();
@@ -1555,7 +1553,7 @@ cc.TransitionFadeTR = cc.TransitionScene.extend(/** @lends cc.TransitionFadeTR#
* Custom on enter
*/
onEnter:function () {
- this._super();
+ cc.TransitionScene.prototype.onEnter.call(this);
var winSize = cc.Director.getInstance().getWinSize();
var aspect = winSize.width / winSize.height;
diff --git a/cocos2d/layers_scenes_transitions_nodes/CCTransitionPageTurn.js b/cocos2d/layers_scenes_transitions_nodes/CCTransitionPageTurn.js
index 93e0d6c750..f5c8d2546f 100644
--- a/cocos2d/layers_scenes_transitions_nodes/CCTransitionPageTurn.js
+++ b/cocos2d/layers_scenes_transitions_nodes/CCTransitionPageTurn.js
@@ -54,7 +54,7 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu
// XXX: needed before [super init]
this._back = backwards;
- if (this._super(t, scene)) {
+ if (cc.TransitionScene.prototype.initWithDuration(this, t, scene)) {
// do something
}
return true;
@@ -75,7 +75,7 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu
* custom on enter
*/
onEnter:function () {
- this._super();
+ cc.TransitionScene.prototype.onEnter.call(this);
var winSize = cc.Director.getInstance().getWinSize();
var x, y;
if (winSize.width > winSize.height) {
diff --git a/cocos2d/layers_scenes_transitions_nodes/CCTransitionProgress.js b/cocos2d/layers_scenes_transitions_nodes/CCTransitionProgress.js
index e4d5b3e276..9d5b6ba404 100644
--- a/cocos2d/layers_scenes_transitions_nodes/CCTransitionProgress.js
+++ b/cocos2d/layers_scenes_transitions_nodes/CCTransitionProgress.js
@@ -45,8 +45,7 @@ cc.TransitionProgress = cc.TransitionScene.extend(/** @lends cc.TransitionProgre
* @override
*/
onEnter:function () {
- this._super();
-
+ cc.TransitionScene.prototype.onEnter.call(this);
this._setupTransition();
// create a transparent color layer
@@ -59,21 +58,16 @@ cc.TransitionProgress = cc.TransitionScene.extend(/** @lends cc.TransitionProgre
texture.setPosition(cc.p(winSize.width / 2, winSize.height / 2));
texture.setAnchorPoint(cc.p(0.5, 0.5));
- if (cc.renderContextType === cc.CANVAS) {
- // render outScene to its texturebuffer
- texture.clear();
- this._sceneToBeModified.visit(texture.context);
- } else {
- // render outScene to its texturebuffer
- texture.clear(0, 0, 0, 1);
- texture.begin();
- this._sceneToBeModified.visit();
- texture.end();
- }
+ // render outScene to its texturebuffer
+ texture.clear(0, 0, 0, 1);
+ texture.begin();
+ this._sceneToBeModified.visit();
+ texture.end();
+
// Since we've passed the outScene to the texture we don't need it.
- if (this._sceneToBeModified == this._outScene) {
+ if (this._sceneToBeModified == this._outScene)
this.hideOutShowIn();
- }
+
// We need the texture in RenderTexture.
var pNode = this._progressTimerNodeWithRenderTexture(texture);
@@ -86,7 +80,6 @@ cc.TransitionProgress = cc.TransitionScene.extend(/** @lends cc.TransitionProgre
// add the layer (which contains our two rendertextures) to the scene
this.addChild(pNode, 2, cc.SCENE_RADIAL);
-
},
/**
@@ -95,7 +88,7 @@ cc.TransitionProgress = cc.TransitionScene.extend(/** @lends cc.TransitionProgre
onExit:function () {
// remove our layer and release all containing objects
this.removeChildByTag(cc.SCENE_RADIAL, true);
- this._super();
+ cc.TransitionScene.prototype.onExit.call(this);
},
_setupTransition:function () {
diff --git a/cocos2d/particle_nodes/CCParticleBatchNode.js b/cocos2d/particle_nodes/CCParticleBatchNode.js
index 431796d110..00a0aee906 100644
--- a/cocos2d/particle_nodes/CCParticleBatchNode.js
+++ b/cocos2d/particle_nodes/CCParticleBatchNode.js
@@ -62,7 +62,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
_textureAtlas:null,
ctor:function () {
- this._super();
+ cc.Node.prototype.ctor.call(this);
this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST};
},
@@ -180,7 +180,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
cc.Assert(child instanceof cc.ParticleSystem, "cc.ParticleBatchNode only supports cc.ParticleSystemQuads as children");
cc.Assert(this._children.indexOf(child) > -1, "cc.ParticleBatchNode doesn't contain the sprite. Can't remove it");
- this._super(child, cleanup);
+ cc.Node.prototype.removeChild.call(this, child, cleanup);
// remove child helper
this._textureAtlas.removeQuadsAtIndex(child.getAtlasIndex(), child.getTotalParticles());
@@ -253,10 +253,11 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* @param {Boolean} doCleanup
*/
removeAllChildren:function (doCleanup) {
- for (var i = 0; i < this._children.length; i++) {
- this._children[i].setBatchNode(null);
+ var locChildren = this._children;
+ for (var i = 0; i < locChildren.length; i++) {
+ locChildren[i].setBatchNode(null);
}
- this._super(doCleanup);
+ cc.Node.prototype.removeAllChildren.call(this, doCleanup);
this._textureAtlas.removeAllQuads();
},
@@ -335,10 +336,8 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
// override visit.
// Don't call visit on it's children
visit:function (ctx) {
- if (cc.renderContextType === cc.CANVAS) {
- this._super(ctx);
+ if (cc.renderContextType === cc.CANVAS)
return;
- }
// CAREFUL:
// This visit is almost identical to cc.Node#visit
diff --git a/cocos2d/physics_nodes/CCPhysicsDebugNode.js b/cocos2d/physics_nodes/CCPhysicsDebugNode.js
index f5c3e2de3a..d598ba7732 100644
--- a/cocos2d/physics_nodes/CCPhysicsDebugNode.js
+++ b/cocos2d/physics_nodes/CCPhysicsDebugNode.js
@@ -136,7 +136,7 @@ cc.PhysicsDebugNode = cc.DrawNode.extend({
this._spacePtr.eachShape(cc.DrawShape.bind(this));
this._spacePtr.eachConstraint(cc.DrawConstraint.bind(this));
- this._super();
+ cc.DrawNode.prototype.draw.call(this);
this.clear();
}
});
diff --git a/cocos2d/physics_nodes/CCPhysicsSprite.js b/cocos2d/physics_nodes/CCPhysicsSprite.js
index cfee963008..10873ea427 100644
--- a/cocos2d/physics_nodes/CCPhysicsSprite.js
+++ b/cocos2d/physics_nodes/CCPhysicsSprite.js
@@ -119,9 +119,8 @@
},
setRotation:function (r) {
if (this._ignoreBodyRotation) {
- this._super(r);
- }
- else {
+ cc.Sprite.prototype.setRotation.call(this, r);
+ } else {
this._body.a = -cc.DEGREES_TO_RADIANS(r);
//this._syncRotation();
}
@@ -255,7 +254,7 @@
/**
* Creates a PhysicsSprite with a sprite frame name
- * @param {String} spriteFrame name
+ * @param {String} spriteFrameName
* @return {cc.Sprite}
* @example
*
@@ -299,6 +298,4 @@
}
return null;
};
-
-
})();
diff --git a/cocos2d/text_input_node/CCTextFieldTTF.js b/cocos2d/text_input_node/CCTextFieldTTF.js
index 61f02c6209..52a16a5eb3 100644
--- a/cocos2d/text_input_node/CCTextFieldTTF.js
+++ b/cocos2d/text_input_node/CCTextFieldTTF.js
@@ -98,7 +98,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{
ctor:function () {
this._ColorSpaceHolder = new cc.Color3B(127, 127, 127);
cc.IMEDispatcher.getInstance().addDelegate(this);
- this._super();
+ cc.LabelTTF.prototype.ctor.call(this);
},
/**
@@ -176,22 +176,16 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{
/**
* Input text property
* @param {String} text
- * @param {Boolean} isCallParent
*/
- setString:function (text, isCallParent) {
+ setString:function (text) {
text = String(text);
- if (isCallParent && isCallParent == true) {
- this._super(text);
- return;
- }
-
this._inputText = text || "";
// if there is no input text, display placeholder instead
if (!this._inputText.length)
- this._super(this._placeHolder);
+ cc.LabelTTF.prototype.setString.call(this, this._placeHolder);
else
- this._super(this._inputText);
+ cc.LabelTTF.prototype.setString.call(this,this._inputText);
this._charCount = this._inputText.length;
},
@@ -229,14 +223,14 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{
return;
if (this._inputText && this._inputText.length > 0) {
- this._super(context);
+ cc.LabelTTF.prototype.draw.call(this, context);
return;
}
// draw placeholder
var color = this.getColor();
this.setColor(this._ColorSpaceHolder);
- this._super(context);
+ cc.LabelTTF.prototype.draw.call(this, context);
this.setColor(color);
},
@@ -311,7 +305,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{
// set new input text
var sText = this._inputText.substring(0, strLen - deleteLen);
- this.setString(sText, false);
+ this.setString(sText);
},
/**
diff --git a/cocos2d/tileMap_parallax_nodes/CCTMXLayer.js b/cocos2d/tileMap_parallax_nodes/CCTMXLayer.js
index 6a54eb99f4..7211b3e37c 100644
--- a/cocos2d/tileMap_parallax_nodes/CCTMXLayer.js
+++ b/cocos2d/tileMap_parallax_nodes/CCTMXLayer.js
@@ -592,7 +592,7 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{
var zz = this._atlasIndexArray[atlasIndex];
this._tiles[zz] = 0;
cc.ArrayRemoveObjectAtIndex(this._atlasIndexArray, atlasIndex);
- this._super(sprite, cleanup);
+ cc.SpriteBatchNode.prototype.removeChild.call(this, sprite, cleanup);
},
/**
diff --git a/cocos2d/touch_dispatcher/CCTouchHandler.js b/cocos2d/touch_dispatcher/CCTouchHandler.js
index a67f2130e3..90f010cceb 100644
--- a/cocos2d/touch_dispatcher/CCTouchHandler.js
+++ b/cocos2d/touch_dispatcher/CCTouchHandler.js
@@ -121,10 +121,7 @@ cc.StandardTouchHandler = cc.TouchHandler.extend(/** @lends cc.StandardTouchHand
* @return {Boolean}
*/
initWithDelegate:function (delegate, priority) {
- if (this._super(delegate, priority)) {
- return true;
- }
- return false;
+ return cc.TouchHandler.prototype.initWithDelegate.call(this, delegate, priority);
}
});
@@ -181,7 +178,7 @@ cc.TargetedTouchHandler = cc.TouchHandler.extend(/** @lends cc.TargetedTouchHand
* @return {Boolean}
*/
initWithDelegate:function (delegate, priority, swallow) {
- if (this._super(delegate, priority)) {
+ if (cc.TouchHandler.prototype.initWithDelegate.call(this, delegate, priority)) {
this._claimedTouches = [];
this._swallowsTouches = swallow;
return true;
From 64a9d326c50a1d7a3397da18fff168c301463300 Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Thu, 22 Aug 2013 13:46:58 +0800
Subject: [PATCH 056/141] fixed #2531 Async loading textures for cc.LabelBMFont
has been implemented.
---
cocos2d/label_nodes/CCLabelBMFont.js | 34 +++++++++++------------
cocos2d/sprite_nodes/CCSprite.js | 33 +++++++++++-----------
cocos2d/sprite_nodes/CCSpriteBatchNode.js | 2 +-
cocos2d/textures/CCTexture2D.js | 22 ++++++++++++++-
4 files changed, 56 insertions(+), 35 deletions(-)
diff --git a/cocos2d/label_nodes/CCLabelBMFont.js b/cocos2d/label_nodes/CCLabelBMFont.js
index 87ebcdeb1f..2e430c64dc 100644
--- a/cocos2d/label_nodes/CCLabelBMFont.js
+++ b/cocos2d/label_nodes/CCLabelBMFont.js
@@ -461,10 +461,12 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
selNode.setVisible(false);
}
}
- this.createFontChars();
+ if(this._textureLoaded){
+ this.createFontChars();
- if(needUpdateLabel)
- this.updateLabel();
+ if(needUpdateLabel)
+ this.updateLabel();
+ }
},
/**
* Constructor
@@ -692,7 +694,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
texture.addLoadedEventListener(function(sender){
this._textureLoaded = true;
//reset the LabelBMFont
- this.initWithTexture(texture, theString.length)
+ this.initWithTexture(sender, theString.length)
this.setString(theString,true);
}, this);
}
@@ -794,14 +796,14 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
rect.y += this._imageOffset.y;
var fontChar = this.getChildByTag(i);
- var hasSprite = true;
+ //var hasSprite = true;
if (!fontChar) {
fontChar = new cc.Sprite();
if ((key === 32) && (locContextType === cc.CANVAS)) {
fontChar.initWithTexture(locTexture, cc.RectZero(), false);
} else
fontChar.initWithTexture(locTexture, rect, false);
-
+ fontChar._newTextureWhenChangeColor = true;
this.addChild(fontChar, 0, i);
} else {
if ((key === 32) && (locContextType === cc.CANVAS)) {
@@ -816,10 +818,10 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
// Apply label properties
fontChar.setOpacityModifyRGB(this._opacityModifyRGB);
// Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on
- if(cc.Browser.supportWebGL){
+ if (cc.Browser.supportWebGL) {
fontChar.updateDisplayedColor(this._displayedColor);
fontChar.updateDisplayedOpacity(this._displayedOpacity);
- }else{
+ } else {
cc.NodeRGBA.prototype.updateDisplayedColor.call(fontChar, this._displayedColor);
cc.NodeRGBA.prototype.updateDisplayedOpacity.call(fontChar, this._displayedOpacity);
fontChar.setNodeDirty();
@@ -1154,18 +1156,16 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
this.setTexture(texture);
if (cc.renderContextType === cc.CANVAS)
this._originalTexture = this.getTexture();
- this.createFontChars();
if(!locIsLoaded){
- texture.addLoadedEventListener(function(){
+ texture.addLoadedEventListener(function(sender){
this._textureLoaded = true;
- if(this._cascadeColorEnabled){
- var parentColor = cc.white();
- var locParent = this._parent;
- if(locParent && locParent.RGBAProtocol && locParent.isCascadeColorEnabled())
- parentColor = locParent.getDisplayedColor();
- this.updateDisplayedColor(parentColor);
- }
+ this.setTexture(sender);
+ this.createFontChars();
+ this._changeTextureColor();
+ this.updateLabel();
}, this);
+ } else {
+ this.createFontChars();
}
}
},
diff --git a/cocos2d/sprite_nodes/CCSprite.js b/cocos2d/sprite_nodes/CCSprite.js
index c74da2042c..ce9bb97102 100644
--- a/cocos2d/sprite_nodes/CCSprite.js
+++ b/cocos2d/sprite_nodes/CCSprite.js
@@ -166,7 +166,7 @@ cc.generateTintImage = function (texture, tintedImgCache, color, rect, renderCan
rect = cc.rect(0, 0, texture.width, texture.height);
var selColor;
- if (color instanceof cc.Color3B) {
+ if (color.a == null) {
// Optimization for the particle system which mainly uses c4f colors
selColor = cc.c4f(color.r / 255.0, color.g / 255.0, color.b / 255, 1);
} else {
@@ -331,8 +331,9 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
_flipX:false, //Whether the sprite is flipped horizontally or not.
_flipY:false, //Whether the sprite is flipped vertically or not.
- _textureLoaded:false,
- _loadedEventListeners:null,
+ _textureLoaded: false,
+ _loadedEventListeners: null,
+ _newTextureWhenChangeColor: null, //hack property for LabelBMFont
textureLoaded:function(){
return this._textureLoaded;
@@ -882,6 +883,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST};
this._textureLoaded = true;
this._loadedEventListeners = [];
+ this._newTextureWhenChangeColor = false;
if (fileName) {
if (typeof(fileName) == "string") {
@@ -1291,15 +1293,15 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
if (cacheTextureForColor) {
this._colorized = true;
//generate color texture cache
- /*if (locElement instanceof HTMLCanvasElement && !this._rectRotated)
+ if (locElement instanceof HTMLCanvasElement && !this._rectRotated && !this._newTextureWhenChangeColor)
cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, locRect, locElement);
- else {*/
+ else {
locElement = cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, locRect);
locTexture = new cc.Texture2D();
locTexture.initWithElement(locElement);
locTexture.handleLoadedTexture();
this.setTexture(locTexture);
- //}
+ }
}
}
},
@@ -1317,31 +1319,31 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
context.globalCompositeOperation = 'lighter';
context.globalAlpha = this._displayedOpacity / 255;
- var locRect = this._rect;
- var flipXOffset = 0 | (this._offsetPosition.x), flipYOffset = -this._offsetPosition.y - locRect.height;
+ var locRect = this._rect, locContentSize = this._contentSize, locOffsetPosition = this._offsetPosition;
+ var flipXOffset = 0 | (locOffsetPosition.x), flipYOffset = -locOffsetPosition.y - locRect.height;
if (this._flipX) {
- flipXOffset = -this._offsetPosition.x - locRect.width;
+ flipXOffset = -locOffsetPosition.x - locRect.width;
context.scale(-1, 1);
}
if (this._flipY) {
- flipYOffset = this._offsetPosition.y;
+ flipYOffset = locOffsetPosition.y;
context.scale(1, -1);
}
- if (this._texture && locRect.width > 0 && locRect.height > 0) {
+ if (this._texture && locRect.width > 0) {
var image = this._texture.getHtmlElementObj();
if (this._colorized) {
context.drawImage(image,
- 0, 0, locRect.width , locRect.height ,
+ 0, 0, locRect.width, locRect.height,
flipXOffset, flipYOffset, locRect.width, locRect.height);
} else {
context.drawImage(image,
- locRect.x , locRect.y , locRect.width , locRect.height ,
+ locRect.x, locRect.y, locRect.width, locRect.height,
flipXOffset, flipYOffset, locRect.width, locRect.height);
}
- } else if (this._contentSize.width !== 0) {
+ } else if (locContentSize.width !== 0) {
var curColor = this.getColor();
context.fillStyle = "rgba(" + curColor.r + "," + curColor.g + "," + curColor.b + ",1)";
- context.fillRect(flipXOffset, flipYOffset, this._contentSize.width, this._contentSize.height);
+ context.fillRect(flipXOffset, flipYOffset, locContentSize.width, locContentSize.height);
}
if (cc.SPRITE_DEBUG_DRAW === 1) {
@@ -2091,7 +2093,6 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
cc.Assert(filename != null, "Sprite#initWithFile():Invalid filename for sprite");
var texture = cc.TextureCache.getInstance().textureForKey(filename);
if (!texture) {
- filename = cc.FileUtils.getInstance().fullPathForFilename(filename);
texture = cc.TextureCache.getInstance().addImage(filename);
return this.initWithTexture(texture, rect);
} else {
diff --git a/cocos2d/sprite_nodes/CCSpriteBatchNode.js b/cocos2d/sprite_nodes/CCSpriteBatchNode.js
index 855a89bbf3..1e7a5d6bb4 100644
--- a/cocos2d/sprite_nodes/CCSpriteBatchNode.js
+++ b/cocos2d/sprite_nodes/CCSpriteBatchNode.js
@@ -1273,7 +1273,7 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
cc.Assert((child instanceof cc.Sprite), "cc.SpriteBatchNode only supports cc.Sprites as children");
// check cc.Sprite is using the same texture id
- cc.Assert(child.getTexture()._webTextureObj == this._textureAtlas.getTexture()._webTextureObj,
+ cc.Assert(child.getTexture() == this._textureAtlas.getTexture(),
"SpriteBatchNode.addChild():cc.Sprite is not using the same texture id");
cc.Node.prototype.addChild.call(this, child, zOrder, tag);
this.appendChild(child);
diff --git a/cocos2d/textures/CCTexture2D.js b/cocos2d/textures/CCTexture2D.js
index 1033043f5d..b9f12d0089 100644
--- a/cocos2d/textures/CCTexture2D.js
+++ b/cocos2d/textures/CCTexture2D.js
@@ -160,7 +160,7 @@ cc.Texture2DWebGL = cc.Class.extend(/** @lends cc.Texture2D# */{
this._maxS = 0;
this._maxT = 0;
this._hasPremultipliedAlpha = false;
- this._contentSize = null;
+ this._contentSize = cc.size(0, 0);
this._hasMipmaps = false;
this._pVRHaveAlphaPremultiplied = true;
@@ -913,6 +913,16 @@ cc.Texture2DWebGL = cc.Class.extend(/** @lends cc.Texture2D# */{
this._loadedEventListeners.push({eventCallback: callback, eventTarget: target});
},
+ removeLoadedEventListener:function(target){
+ var locListeners = this._loadedEventListeners;
+ for(var i = 0; i < locListeners.length; i++){
+ var selCallback = locListeners[i];
+ if(selCallback.eventTarget == target){
+ locListeners.splice(i, 1);
+ }
+ }
+ },
+
_callLoadedEventCallbacks: function () {
var locListeners = this._loadedEventListeners;
for (var i = 0, len = locListeners.length; i < len; i++) {
@@ -1248,6 +1258,16 @@ cc.Texture2DCanvas = cc.Class.extend(/** @lends cc.Texture2D# */{
this._loadedEventListeners.push({eventCallback:callback, eventTarget:target});
},
+ removeLoadedEventListener:function(target){
+ var locListeners = this._loadedEventListeners;
+ for(var i = 0; i < locListeners.length; i++){
+ var selCallback = locListeners[i];
+ if(selCallback.eventTarget == target){
+ locListeners.splice(i, 1);
+ }
+ }
+ },
+
_callLoadedEventCallbacks:function(){
var locListeners = this._loadedEventListeners;
for(var i = 0, len = locListeners.length; i < len; i++){
From aa8a5fa5601c06fee67220443e0e1a176cce1052 Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Thu, 22 Aug 2013 14:32:01 +0800
Subject: [PATCH 057/141] fixed #1089 fixed a bug of cc.LayerColorCanvas that
respecting incorrect opacity passed into init method
---
cocos2d/layers_scenes_transitions_nodes/CCLayer.js | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
diff --git a/cocos2d/layers_scenes_transitions_nodes/CCLayer.js b/cocos2d/layers_scenes_transitions_nodes/CCLayer.js
index 19977ec8c3..6b3839212f 100644
--- a/cocos2d/layers_scenes_transitions_nodes/CCLayer.js
+++ b/cocos2d/layers_scenes_transitions_nodes/CCLayer.js
@@ -828,7 +828,9 @@ cc.LayerColorCanvas = cc.LayerRGBA.extend(/** @lends cc.LayerColorCanvas# */{
this._realColor.g = color.g;
this._realColor.b = color.b;
- this._opacity = color.a;
+ this._displayedOpacity = color.a;
+ this._realOpacity = color.a;
+
this.setContentSize(cc.size(width, height));
this._updateColor();
return true;
From 25efe68d9375dca73f55af7bd5179fc062dfe525 Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Fri, 23 Aug 2013 11:35:08 +0800
Subject: [PATCH 058/141] issue #2506: use direct call parent's function
instead this._super for extensions
---
cocos2d/base_nodes/CCNode.js | 36 ++-------
cocos2d/sprite_nodes/CCSprite.js | 4 +-
cocos2d/sprite_nodes/CCSpriteBatchNode.js | 4 +-
extensions/CCBReader/CCBAnimationManager.js | 4 +-
extensions/CCBReader/CCControlLoader.js | 44 +++++------
extensions/CCBReader/CCSpriteLoader.js | 74 +++++++++----------
extensions/CCEditBox.js | 2 +-
.../GUI/CCControlExtension/CCControl.js | 10 +--
.../GUI/CCControlExtension/CCControlButton.js | 8 +-
.../GUI/CCControlExtension/CCScale9Sprite.js | 4 +-
extensions/GUI/CCScrollView/CCScrollView.js | 4 +-
extensions/GUI/CCScrollView/CCTableView.js | 2 +-
12 files changed, 82 insertions(+), 114 deletions(-)
diff --git a/cocos2d/base_nodes/CCNode.js b/cocos2d/base_nodes/CCNode.js
index ea08902136..e9dfe0c8d4 100644
--- a/cocos2d/base_nodes/CCNode.js
+++ b/cocos2d/base_nodes/CCNode.js
@@ -1143,19 +1143,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
*/
_insertChild:function (child, z) {
this._reorderChildDirty = true;
- var __children = this._children;
- var a = __children[__children.length - 1];
- if (!a || a.getZOrder() <= z)
- __children.push(child);
- else {
- for (var i = 0; i < __children.length; i++) {
- var node = __children[i];
- if (node && (node.getZOrder() > z )) {
- this._children = cc.ArrayAppendObjectToIndex(__children, child, i);
- break;
- }
- }
- }
+ this._children.push(child);
child._setZOrder(z);
},
@@ -1193,9 +1181,9 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
//continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
- tempChild = _children[j];
_children[j + 1] = tempChild;
j = j - 1;
+ tempChild = _children[j];
}
_children[j + 1] = tempItem;
}
@@ -2986,19 +2974,7 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
*/
_insertChild:function (child, z) {
this._reorderChildDirty = true;
- var __children = this._children;
- var a = __children[__children.length - 1];
- if (!a || a.getZOrder() <= z)
- __children.push(child);
- else {
- for (var i = 0; i < __children.length; i++) {
- var node = __children[i];
- if (node && (node.getZOrder() > z )) {
- this._children = cc.ArrayAppendObjectToIndex(__children, child, i);
- break;
- }
- }
- }
+ this._children.push(child);
child._setZOrder(z);
},
@@ -3036,9 +3012,9 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
//continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
- tempChild = _children[j];
_children[j + 1] = tempChild;
j = j - 1;
+ tempChild = _children[j];
}
_children[j + 1] = tempItem;
}
@@ -3544,9 +3520,7 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
}
this.draw(context);
for (; i < len; i++) {
- child = children[i];
- if (child._zOrder >= 0)
- child.visit(context);
+ children[i].visit(context);
}
} else
this.draw(context);
diff --git a/cocos2d/sprite_nodes/CCSprite.js b/cocos2d/sprite_nodes/CCSprite.js
index ce9bb97102..f3fdcdbba0 100644
--- a/cocos2d/sprite_nodes/CCSprite.js
+++ b/cocos2d/sprite_nodes/CCSprite.js
@@ -523,9 +523,9 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
//continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
- tempChild = locChildren[j];
locChildren[j + 1] = tempChild;
j = j - 1;
+ tempChild = locChildren[j];
}
locChildren[j + 1] = tempItem;
}
@@ -1629,9 +1629,9 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
//continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
- tempChild = locChildren[j];
locChildren[j + 1] = tempChild;
j = j - 1;
+ tempChild = locChildren[j];
}
locChildren[j + 1] = tempItem;
}
diff --git a/cocos2d/sprite_nodes/CCSpriteBatchNode.js b/cocos2d/sprite_nodes/CCSpriteBatchNode.js
index 1e7a5d6bb4..92e3a00c66 100644
--- a/cocos2d/sprite_nodes/CCSpriteBatchNode.js
+++ b/cocos2d/sprite_nodes/CCSpriteBatchNode.js
@@ -597,9 +597,9 @@ cc.SpriteBatchNodeCanvas = cc.Node.extend(/** @lends cc.SpriteBatchNodeCanvas# *
//continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
- tempChild = locChildren[j];
locChildren[j + 1] = tempChild;
j = j - 1;
+ tempChild = locChildren[j];
}
locChildren[j + 1] = tempItem;
}
@@ -1312,9 +1312,9 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
//continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
- tempChild = childrenArr[j];
childrenArr[j + 1] = tempChild;
j = j - 1;
+ tempChild = childrenArr[j];
}
childrenArr[j + 1] = tempItem;
}
diff --git a/extensions/CCBReader/CCBAnimationManager.js b/extensions/CCBReader/CCBAnimationManager.js
index 3005295504..0f67fb02ce 100644
--- a/extensions/CCBReader/CCBAnimationManager.js
+++ b/extensions/CCBReader/CCBAnimationManager.js
@@ -665,7 +665,7 @@ cc.BuilderRotateTo = cc.ActionInterval.extend({
_diffAngle:0,
initWithDuration:function (duration, angle) {
- if (this._super(duration)) {
+ if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
this._dstAngle = angle;
return true;
} else {
@@ -677,7 +677,7 @@ cc.BuilderRotateTo = cc.ActionInterval.extend({
},
startWithTarget:function (node) {
- this._super(node);
+ cc.ActionInterval.prototype.startWithTarget.call(this, node);
this._startAngle = this._target.getRotation();
this._diffAngle = this._dstAngle - this._startAngle;
}
diff --git a/extensions/CCBReader/CCControlLoader.js b/extensions/CCBReader/CCControlLoader.js
index 4924cc5379..c1c4a56e31 100644
--- a/extensions/CCBReader/CCControlLoader.js
+++ b/extensions/CCBReader/CCControlLoader.js
@@ -34,7 +34,7 @@ cc.BuilderFileLoader = cc.NodeLoader.extend({
if (propertyName == PROPERTY_CCBFILE) {
node.setCCBFileNode(ccbFileNode);
} else {
- this._super(node, parent, propertyName, ccbFileNode, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeCCBFile.call(this, node, parent, propertyName, ccbFileNode, ccbReader);
}
}
});
@@ -54,7 +54,7 @@ cc.ControlLoader = cc.NodeLoader.extend({
if (propertyName == PROPERTY_CCCONTROL) {
node.addTargetWithActionForControlEvents(blockCCControlData.target, blockCCControlData.selCCControlHandler, blockCCControlData.controlEvents);
} else {
- this._super(node, parent, propertyName, blockCCControlData, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeBlockCCControl.call(this, node, parent, propertyName, blockCCControlData, ccbReader);
}
},
onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) {
@@ -63,7 +63,7 @@ cc.ControlLoader = cc.NodeLoader.extend({
} else if (propertyName == PROPERTY_SELECTED) {
node.setSelected(check);
} else {
- this._super(node, parent, propertyName, check, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader);
}
}
});
@@ -96,7 +96,7 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({
if (propertyName == PROPERTY_ZOOMONTOUCHDOWN) {
node.setZoomOnTouchDown(check);
} else {
- this._super(node, parent, propertyName, check, ccbReader);
+ cc.ControlLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader);
}
},
onHandlePropTypeString:function (node, parent, propertyName, stringValue, ccbReader) {
@@ -107,7 +107,7 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({
} else if (propertyName == PROPERTY_TITLE_DISABLED) {
node.setTitleForState(stringValue, cc.CONTROL_STATE_DISABLED);
} else {
- this._super(node, parent, propertyName, stringValue, ccbReader);
+ cc.ControlLoader.prototype.onHandlePropTypeString.call(this, node, parent, propertyName, stringValue, ccbReader);
}
},
onHandlePropTypeFontTTF:function (node, parent, propertyName, fontTTF, ccbReader) {
@@ -118,7 +118,7 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({
} else if (propertyName == PROPERTY_TITLETTF_DISABLED) {
node.setTitleTTFForState(fontTTF, cc.CONTROL_STATE_DISABLED);
} else {
- this._super(node, parent, propertyName, fontTTF, ccbReader);
+ cc.ControlLoader.prototype.onHandlePropTypeFontTTF.call(this, node, parent, propertyName, fontTTF, ccbReader);
}
},
onHandlePropTypeFloatScale:function (node, parent, propertyName, floatScale, ccbReader) {
@@ -129,21 +129,21 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({
} else if (propertyName == PROPERTY_TITLETTFSIZE_DISABLED) {
node.setTitleTTFSizeForState(floatScale, cc.CONTROL_STATE_DISABLED);
} else {
- this._super(node, parent, propertyName, floatScale, ccbReader);
+ cc.ControlLoader.prototype.onHandlePropTypeFloatScale.call(this, node, parent, propertyName, floatScale, ccbReader);
}
},
onHandlePropTypePoint:function (node, parent, propertyName, point, ccbReader) {
if (propertyName == PROPERTY_LABELANCHORPOINT) {
node.setLabelAnchorPoint(point);
} else {
- this._super(node, parent, propertyName, point, ccbReader);
+ cc.ControlLoader.prototype.onHandlePropTypePoint.call(this, node, parent, propertyName, point, ccbReader);
}
},
onHandlePropTypeSize:function (node, parent, propertyName, size, ccbReader) {
if (propertyName == PROPERTY_PREFEREDSIZE) {
node.setPreferredSize(size);
} else {
- this._super(node, parent, propertyName, size, ccbReader);
+ cc.ControlLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size, ccbReader);
}
},
onHandlePropTypeSpriteFrame:function (node, parent, propertyName, spriteFrame, ccbReader) {
@@ -160,7 +160,7 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({
node.setBackgroundSpriteFrameForState(spriteFrame, cc.CONTROL_STATE_DISABLED);
}
} else {
- this._super(node, parent, propertyName, spriteFrame, ccbReader);
+ cc.ControlLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, spriteFrame, ccbReader);
}
},
onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
@@ -171,7 +171,7 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({
} else if (propertyName == PROPERTY_TITLECOLOR_DISABLED) {
node.setTitleColorForState(ccColor3B, cc.CONTROL_STATE_DISABLED);
} else {
- this._super(node, parent, propertyName, ccColor3B, ccbReader);
+ cc.ControlLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader);
}
}
});
@@ -195,7 +195,7 @@ cc.ScrollViewLoader = cc.NodeLoader.extend({
if(propertyName == PROPERTY_CONTENTSIZE){
node.setViewSize(size);
}else{
- this._super(node,parent,propertyName.size,ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node,parent,propertyName.size,ccbReader);
}
},
@@ -204,7 +204,7 @@ cc.ScrollViewLoader = cc.NodeLoader.extend({
node.setContainer(ccbFileNode);
node.updateInset();
} else {
- this._super(node, parent, propertyName, ccbFileNode, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeCCBFile.call(this, node, parent, propertyName, ccbFileNode, ccbReader);
}
},
onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) {
@@ -213,21 +213,21 @@ cc.ScrollViewLoader = cc.NodeLoader.extend({
} else if (propertyName == PROPERTY_BOUNCES) {
node.setBounceable(check);
} else {
- this._super(node, parent, propertyName, check, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader);
}
},
onHandlePropTypeFloat:function (node, parent, propertyName, floatValue, ccbReader) {
if (propertyName == PROPERTY_SCALE) {
node.setScale(floatValue);
} else {
- this._super(node, parent, propertyName, floatValue, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue, ccbReader);
}
},
onHandlePropTypeIntegerLabeled:function (node, parent, propertyName, integerLabeled, ccbReader) {
if (propertyName == PROPERTY_DIRECTION) {
node.setDirection(integerLabeled);
} else {
- this._super(node, parent, propertyName, integerLabeled, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeIntegerLabeled.call(this, node, parent, propertyName, integerLabeled, ccbReader);
}
}
});
@@ -255,14 +255,14 @@ cc.Scale9SpriteLoader = cc.NodeLoader.extend({
if(propertyName == PROPERTY_COLOR) {
node.setColor(ccColor3B);
} else {
- this._super(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) {
node.setOpacity(byteValue);
} else {
- this._super(node, parent, propertyName, byteValue,ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue,ccbReader);
}
},
onHandlePropTypeBlendFunc:function(node, parent, propertyName, ccBlendFunc,ccbReader){
@@ -270,14 +270,14 @@ cc.Scale9SpriteLoader = cc.NodeLoader.extend({
// TODO Not exported by CocosBuilder yet!
// node.setBlendFunc(ccBlendFunc);
} else {
- this._super(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) {
node.initWithSpriteFrame(spriteFrame);
} else {
- this._super(node, parent, propertyName, spriteFrame,ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, spriteFrame,ccbReader);
}
},
onHandlePropTypeSize:function(node, parent, propertyName, size,ccbReader){
@@ -286,7 +286,7 @@ cc.Scale9SpriteLoader = cc.NodeLoader.extend({
} else if(propertyName == PROPERTY_PREFEREDSIZE) {
node.setPreferredSize(size);
} else {
- this._super(node, parent, propertyName, size,ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size,ccbReader);
}
},
onHandlePropTypeFloat:function(node, parent, propertyName, floatValue,ccbReader){
@@ -299,7 +299,7 @@ cc.Scale9SpriteLoader = cc.NodeLoader.extend({
} else if(propertyName == PROPERTY_INSETBOTTOM) {
node.setInsetBottom(floatValue);
} else {
- this._super(node, parent, propertyName, floatValue,ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue,ccbReader);
}
}
});
diff --git a/extensions/CCBReader/CCSpriteLoader.js b/extensions/CCBReader/CCSpriteLoader.js
index 9674be90d0..85e841282f 100644
--- a/extensions/CCBReader/CCSpriteLoader.js
+++ b/extensions/CCBReader/CCSpriteLoader.js
@@ -39,28 +39,28 @@ cc.SpriteLoader = cc.NodeLoader.extend({
if (propertyName == PROPERTY_COLOR) {
node.setColor(color3BValue);
} else {
- this._super(node, parent, propertyName, color3BValue, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, color3BValue, ccbReader);
}
},
onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) {
if (propertyName == PROPERTY_OPACITY) {
node.setOpacity(byteValue);
} else {
- this._super(node, parent, propertyName, byteValue, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader);
}
},
onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccbBlendFunc, ccbReader) {
if (propertyName == PROPERTY_BLENDFUNC) {
node.setBlendFunc(ccbBlendFunc);
} else {
- this._super(node, parent, propertyName, ccbBlendFunc, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccbBlendFunc, ccbReader);
}
},
onHandlePropTypeSpriteFrame:function (node, parent, propertyName, ccSpriteFrame, ccbReader) {
if (propertyName == PROPERTY_DISPLAYFRAME) {
node.setDisplayFrame(ccSpriteFrame);
} else {
- this._super(node, parent, propertyName, ccSpriteFrame, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, ccSpriteFrame, ccbReader);
}
},
onHandlePropTypeFlip:function (node, parent, propertyName, flip, ccbReader) {
@@ -68,7 +68,7 @@ cc.SpriteLoader = cc.NodeLoader.extend({
node.setFlipX(flip[0]);
node.setFlipY(flip[1]);
} else {
- this._super(node, parent, propertyName, flip, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeFlip.call(this, node, parent, propertyName, flip, ccbReader);
}
}
});
@@ -106,7 +106,7 @@ cc.LayerLoader = cc.NodeLoader.extend({
// This comes closest: ((CCLayer *)pNode).setKeypadEnabled(pCheck);
}
} else {
- this._super(node, parent, propertyName, check, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader);
}
}
});
@@ -125,21 +125,21 @@ cc.LayerColorLoader = cc.LayerLoader.extend({
if (propertyName == PROPERTY_COLOR) {
node.setColor(ccColor3B);
} else {
- this._super(node, parent, propertyName, ccColor3B, ccbReader);
+ cc.LayerLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader);
}
},
onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) {
if (propertyName == PROPERTY_OPACITY) {
node.setOpacity(byteValue);
} else {
- this._super(node, parent, propertyName, byteValue, ccbReader);
+ cc.LayerLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader);
}
},
onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) {
if (propertyName == PROPERTY_BLENDFUNC) {
node.setBlendFunc(ccBlendFunc);
} else {
- this._super(node, parent, propertyName, ccBlendFunc, ccbReader);
+ cc.LayerLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader);
}
}
});
@@ -164,7 +164,7 @@ cc.LayerGradientLoader = cc.LayerLoader.extend({
} else if (propertyName == PROPERTY_ENDCOLOR) {
node.setEndColor(ccColor3B);
} else {
- this._super(node, parent, propertyName, ccColor3B, ccbReader);
+ cc.LayerLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader);
}
},
onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) {
@@ -173,7 +173,7 @@ cc.LayerGradientLoader = cc.LayerLoader.extend({
} else if (propertyName == PROPERTY_ENDOPACITY) {
node.setEndOpacity(byteValue);
} else {
- this._super(node, parent, propertyName, byteValue, ccbReader);
+ cc.LayerLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader);
}
},
onHandlePropTypePoint:function (node, parent, propertyName, point, ccbReader) {
@@ -182,14 +182,14 @@ cc.LayerGradientLoader = cc.LayerLoader.extend({
// TODO Not passed along the ccbi file.
// node.setCompressedInterpolation(true);
} else {
- this._super(node, parent, propertyName, point, ccbReader);
+ cc.LayerLoader.prototype.onHandlePropTypePoint.call(this, node, parent, propertyName, point, ccbReader);
}
},
onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) {
if (propertyName == PROPERTY_BLENDFUNC) {
node.setBlendFunc(ccBlendFunc);
} else {
- this._super(node, parent, propertyName, ccBlendFunc, ccbReader);
+ cc.LayerLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader);
}
}
});
@@ -222,14 +222,14 @@ cc.MenuItemLoader = cc.NodeLoader.extend({
node.setTarget(blockData.selMenuHander, blockData.target);
}
} else {
- this._super(node, parent, propertyName, blockData, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeBlock.call(this, node, parent, propertyName, blockData, ccbReader);
}
},
onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) {
if (propertyName == PROPERTY_ISENABLED) {
node.setEnabled(check);
} else {
- this._super(node, parent, propertyName, check, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader);
}
}
});
@@ -257,7 +257,7 @@ cc.MenuItemImageLoader = cc.MenuItemLoader.extend({
node.setDisabledSpriteFrame(spriteFrame);
}
} else {
- this._super(node, parent, propertyName, spriteFrame, ccbReader);
+ cc.MenuItemLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, spriteFrame, ccbReader);
}
}
});
@@ -281,42 +281,42 @@ cc.LabelTTFLoader = cc.NodeLoader.extend({
if (propertyName == PROPERTY_COLOR) {
node.setColor(ccColor3B);
} else {
- this._super(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) {
node.setOpacity(byteValue);
} else {
- this._super(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) {
node.setBlendFunc(ccBlendFunc);
} else {
- this._super(pNode, pParent, propertyName, ccBlendFunc, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader);
}
},
onHandlePropTypeFontTTF:function (node, parent, propertyName, fontTTF, ccbReader) {
if (propertyName == PROPERTY_FONTNAME) {
node.setFontName(fontTTF);
} else {
- this._super(node, parent, propertyName, fontTTF, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeFontTTF.call(this, node, parent, propertyName, fontTTF, ccbReader);
}
},
onHandlePropTypeText:function (node, parent, propertyName, textValue, ccbReader) {
if (propertyName == PROPERTY_STRING) {
node.setString(textValue);
} else {
- this._super(node, parent, propertyName, textValue, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeText.call(this, node, parent, propertyName, textValue, ccbReader);
}
},
onHandlePropTypeFloatScale:function (node, parent, propertyName, floatScale, ccbReader) {
if (propertyName == PROPERTY_FONTSIZE) {
node.setFontSize(floatScale);
} else {
- this._super(node, parent, propertyName, floatScale, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeFloatScale.call(this, node, parent, propertyName, floatScale, ccbReader);
}
},
onHandlePropTypeIntegerLabeled:function (node, parent, propertyName, integerLabeled, ccbReader) {
@@ -325,14 +325,14 @@ cc.LabelTTFLoader = cc.NodeLoader.extend({
} else if (propertyName == PROPERTY_VERTICALALIGNMENT) {
node.setVerticalAlignment(integerLabeled);
} else {
- this._super(node, parent, propertyName, integerLabeled, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeIntegerLabeled.call(this, node, parent, propertyName, integerLabeled, ccbReader);
}
},
onHandlePropTypeSize:function (node, parent, propertyName, size, ccbReader) {
if (propertyName == PROPERTY_DIMENSIONS) {
node.setDimensions(size);
} else {
- this._super(node, parent, propertyName, size, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size, ccbReader);
}
}
});
@@ -352,35 +352,35 @@ cc.LabelBMFontLoader = cc.NodeLoader.extend({
if (propertyName == PROPERTY_COLOR) {
node.setColor(ccColor3B);
} else {
- this._super(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) {
node.setOpacity(byteValue);
} else {
- this._super(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) {
node.setBlendFunc(ccBlendFunc);
} else {
- this._super(node, parent, propertyName, ccBlendFunc, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader);
}
},
onHandlePropTypeFntFile:function (node, parent, propertyName, fntFile, ccbReader) {
if (propertyName == PROPERTY_FNTFILE) {
node.setFntFile(fntFile);
} else {
- this._super(node, parent, propertyName, fntFile, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeFntFile.call(this, node, parent, propertyName, fntFile, ccbReader);
}
},
onHandlePropTypeText:function (node, parent, propertyName, textValue, ccbReader) {
if (propertyName == PROPERTY_STRING) {
node.setString(textValue);
} else {
- this._super(node, parent, propertyName, textValue, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeText.call(this, node, parent, propertyName, textValue, ccbReader);
}
}
});
@@ -418,7 +418,7 @@ cc.ParticleSystemQuadLoader = cc.NodeLoader.extend({
if (propertyName == PROPERTY_EMITERMODE) {
node.setEmitterMode(integerLabeled);
} else {
- this._super(node, parent, propertyName, integerLabeled, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeIntegerLabeled.call(this, node, parent, propertyName, integerLabeled, ccbReader);
}
},
onHandlePropTypePoint:function (node, parent, propertyName, point, ccbReader) {
@@ -427,7 +427,7 @@ cc.ParticleSystemQuadLoader = cc.NodeLoader.extend({
} else if (propertyName == PROPERTY_GRAVITY) {
node.setGravity(point);
} else {
- this._super(node, parent, propertyName, point, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypePoint.call(this, node, parent, propertyName, point, ccbReader);
}
},
onHandlePropTypeFloat:function (node, parent, propertyName, floatValue, ccbReader) {
@@ -436,14 +436,14 @@ cc.ParticleSystemQuadLoader = cc.NodeLoader.extend({
} else if (propertyName == PROPERTY_DURATION) {
node.setDuration(floatValue);
} else {
- this._super(node, parent, propertyName, floatValue, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue, ccbReader);
}
},
onHandlePropTypeInteger:function (node, parent, propertyName, integerValue, ccbReader) {
if (propertyName == PROPERTY_TOTALPARTICLES) {
node.setTotalParticles(integerValue);
} else {
- this._super(node, parent, propertyName, integerValue, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeInteger.call(this, node, parent, propertyName, integerValue, ccbReader);
}
},
onHandlePropTypeFloatVar:function (node, parent, propertyName, floatVar, ccbReader) {
@@ -484,7 +484,7 @@ cc.ParticleSystemQuadLoader = cc.NodeLoader.extend({
node.setRotatePerSecond(floatVar[0]);
node.setRotatePerSecondVar(floatVar[1]);
} else {
- this._super(node, parent, propertyName, floatVar, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeFloatVar.call(this, node, parent, propertyName, floatVar, ccbReader);
}
},
onHandlePropTypeColor4FVar:function (node, parent, propertyName, ccColor4FVar, ccbReader) {
@@ -495,21 +495,21 @@ cc.ParticleSystemQuadLoader = cc.NodeLoader.extend({
node.setEndColor(ccColor4FVar[0]);
node.setEndColorVar(ccColor4FVar[1]);
} else {
- this._super(node, parent, propertyName, ccColor4FVar, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeColor4FVar.call(this, node, parent, propertyName, ccColor4FVar, ccbReader);
}
},
onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) {
if (propertyName == PROPERTY_BLENDFUNC) {
node.setBlendFunc(ccBlendFunc);
} else {
- this._super(node, parent, propertyName, ccBlendFunc, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader);
}
},
onHandlePropTypeTexture:function (node, parent, propertyName, ccTexture2D, ccbReader) {
if (propertyName == PROPERTY_TEXTURE) {
node.setTexture(ccTexture2D);
} else {
- this._super(node, parent, propertyName, ccTexture2D, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeTexture.call(this, node, parent, propertyName, ccTexture2D, ccbReader);
}
}
});
diff --git a/extensions/CCEditBox.js b/extensions/CCEditBox.js
index 73b94bf9a5..e738d17aba 100644
--- a/extensions/CCEditBox.js
+++ b/extensions/CCEditBox.js
@@ -209,7 +209,7 @@ cc.EditBox = cc.ControlButton.extend({
* * Constructor.
* */
ctor: function (boxSize) {
- this._super();
+ cc.ControlButton.prototype.ctor.call(this);
this._textColor = cc.WHITE;
this._placeholderColor = cc.GRAY;
diff --git a/extensions/GUI/CCControlExtension/CCControl.js b/extensions/GUI/CCControlExtension/CCControl.js
index 79b890e607..c3a7dc14e2 100644
--- a/extensions/GUI/CCControlExtension/CCControl.js
+++ b/extensions/GUI/CCControlExtension/CCControl.js
@@ -142,13 +142,13 @@ cc.Control = cc.LayerRGBA.extend({
},
ctor:function () {
- this._super();
+ cc.LayerRGBA.prototype.ctor.call(this);
this._dispatchTable = {};
this._color = cc.white();
},
init:function () {
- if (this._super()) {
+ if (cc.LayerRGBA.prototype.init.call(this)) {
//this.setTouchEnabled(true);
//m_bIsTouchEnabled=true;
// Initialise instance variables
@@ -169,12 +169,6 @@ cc.Control = cc.LayerRGBA.extend({
return false;
},
- onEnter:function () {
- this._super();
- },
- onExit:function () {
- this._super();
- },
registerWithTouchDispatcher:function () {
cc.Director.getInstance().getTouchDispatcher().addTargetedDelegate(this, this.getTouchPriority(), true);
},
diff --git a/extensions/GUI/CCControlExtension/CCControlButton.js b/extensions/GUI/CCControlExtension/CCControlButton.js
index 6c41fc1a6c..79d8ce3038 100644
--- a/extensions/GUI/CCControlExtension/CCControlButton.js
+++ b/extensions/GUI/CCControlExtension/CCControlButton.js
@@ -48,7 +48,7 @@ cc.ControlButton = cc.Control.extend({
_marginH:0,
ctor:function () {
- this._super();
+ cc.Control.prototype.ctor.call(this);
this._preferredSize = new cc.Size(0, 0);
this._labelAnchorPoint = new cc.Point(0, 0);
@@ -309,11 +309,11 @@ cc.ControlButton = cc.Control.extend({
},
setEnabled:function (enabled) {
- this._super(enabled);
+ cc.Control.prototype.setEnabled.call(this, enabled);
this.needsLayout();
},
setSelected:function (enabled) {
- this._super(enabled);
+ cc.Control.prototype.setSelected.call(this, enabled);
this.needsLayout();
},
@@ -324,7 +324,7 @@ cc.ControlButton = cc.Control.extend({
else {
this._state = cc.CONTROL_STATE_NORMAL;
}
- this._super(enabled);
+ cc.Control.prototype.setHighlighted.call(this, enabled);
var action = this.getActionByTag(cc.CONTROL_ZOOM_ACTION_TAG);
if (action) {
this.stopAction(action);
diff --git a/extensions/GUI/CCControlExtension/CCScale9Sprite.js b/extensions/GUI/CCControlExtension/CCScale9Sprite.js
index 052216834b..37d767ad11 100644
--- a/extensions/GUI/CCControlExtension/CCScale9Sprite.js
+++ b/extensions/GUI/CCControlExtension/CCScale9Sprite.js
@@ -302,7 +302,7 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
},
setContentSize: function (size) {
- this._super(size);
+ cc.Node.prototype.setContentSize.call(this, size);
this.m_positionsAreDirty = true;
},
@@ -311,7 +311,7 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
this._updatePositions();
this.m_positionsAreDirty = false;
}
- this._super();
+ cc.Node.prototype.visit.call(this);
},
init: function () {
diff --git a/extensions/GUI/CCScrollView/CCScrollView.js b/extensions/GUI/CCScrollView/CCScrollView.js
index f222a6d9cb..04ef5034c4 100644
--- a/extensions/GUI/CCScrollView/CCScrollView.js
+++ b/extensions/GUI/CCScrollView/CCScrollView.js
@@ -601,12 +601,12 @@ cc.ScrollView = cc.Layer.extend({
if (this._container != child) {
this._container.addChild(child, zOrder, tag);
} else {
- this._super(child, zOrder, tag);
+ cc.Layer.prototype.addChild.call(this, child, zOrder, tag);
}
},
setTouchEnabled:function (e) {
- this._super(e);
+ cc.Layer.prototype.setTouchEnabled.call(this, e);
if (!e) {
this._dragging = false;
this._touchMoved = false;
diff --git a/extensions/GUI/CCScrollView/CCTableView.js b/extensions/GUI/CCScrollView/CCTableView.js
index 0cc114dcd8..d86de079e7 100644
--- a/extensions/GUI/CCScrollView/CCTableView.js
+++ b/extensions/GUI/CCScrollView/CCTableView.js
@@ -120,7 +120,7 @@ cc.TableView = cc.ScrollView.extend({
_oldDirection:null,
ctor:function () {
- this._super();
+ cc.ScrollView.prototype.ctor.call(this);
this._oldDirection = cc.SCROLLVIEW_DIRECTION_NONE;
},
From a861869ce5031f719c7c03506dca88311f88d24d Mon Sep 17 00:00:00 2001
From: 06wj <06wj@163.com>
Date: Mon, 26 Aug 2013 17:19:09 +0800
Subject: [PATCH 059/141] added js loading image
---
cocos2d/platform/jsloader.js | 29 ++++++++++++++++++++++++++---
template/cocos2d.js | 12 ++++++++++++
2 files changed, 38 insertions(+), 3 deletions(-)
diff --git a/cocos2d/platform/jsloader.js b/cocos2d/platform/jsloader.js
index 33ca17c25b..d8546fd53d 100644
--- a/cocos2d/platform/jsloader.js
+++ b/cocos2d/platform/jsloader.js
@@ -38,7 +38,7 @@
'platform/CCMacro.js',
'platform/CCFileUtils.js',
'platform/CCTypes.js',
- 'platform/CCAccelerometer.js',
+ 'platform/CCAccelerometer.js',
'platform/zlib.min.js',
'platform/CCEGLView.js',
'platform/CCImage.js',
@@ -248,6 +248,27 @@
}
+ var loadJsImg = document.getElementById("cocos2d_loadJsImg");
+ if(!loadJsImg){
+ loadJsImg = new Image();
+ loadJsImg.src = "data:image/gif;base64,R0lGODlhEAAQALMNAD8/P7+/vyoqKlVVVX9/fxUVFUBAQGBgYMDAwC8vL5CQkP///wAAAP///wAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFAAANACwAAAAAEAAQAAAEO5DJSau9OOvNex0IMnDIsiCkiW6g6BmKYlBFkhSUEgQKlQCARG6nEBwOgl+QApMdCIRD7YZ5RjlGpCUCACH5BAUAAA0ALAAAAgAOAA4AAAQ6kLGB0JA4M7QW0hrngRllkYyhKAYqKUGguAws0ypLS8JxCLQDgXAIDg+FRKIA6v0SAECCBpXSkstMBAAh+QQFAAANACwAAAAACgAQAAAEOJDJORAac6K1kDSKYmydpASBUl0mqmRfaGTCcQgwcxDEke+9XO2WkxQSiUIuAQAkls0n7JgsWq8RACH5BAUAAA0ALAAAAAAOAA4AAAQ6kMlplDIzTxWC0oxwHALnDQgySAdBHNWFLAvCukc215JIZihVIZEogDIJACBxnCSXTcmwGK1ar1hrBAAh+QQFAAANACwAAAAAEAAKAAAEN5DJKc4RM+tDyNFTkSQF5xmKYmQJACTVpQSBwrpJNteZSGYoFWjIGCAQA2IGsVgglBOmEyoxIiMAIfkEBQAADQAsAgAAAA4ADgAABDmQSVZSKjPPBEDSGucJxyGA1XUQxAFma/tOpDlnhqIYN6MEAUXvF+zldrMBAjHoIRYLhBMqvSmZkggAIfkEBQAADQAsBgAAAAoAEAAABDeQyUmrnSWlYhMASfeFVbZdjHAcgnUQxOHCcqWylKEohqUEAYVkgEAMfkEJYrFA6HhKJsJCNFoiACH5BAUAAA0ALAIAAgAOAA4AAAQ3kMlJq704611SKloCAEk4lln3DQgyUMJxCBKyLAh1EMRR3wiDQmHY9SQslyIQUMRmlmVTIyRaIgA7";
+
+ var canvasNode = document.getElementById(c.tag);
+ canvasNode.style.backgroundColor = "black";
+ canvasNode.parentNode.appendChild(loadJsImg);
+
+ var canvasStyle = getComputedStyle?getComputedStyle(canvasNode):canvasNode.currentStyle;
+ loadJsImg.style.left = canvasNode.offsetLeft + (parseFloat(canvasStyle.width) - loadJsImg.width)/2 + "px";
+ loadJsImg.style.top = canvasNode.offsetTop + (parseFloat(canvasStyle.height) - loadJsImg.height)/2 + "px";
+ loadJsImg.style.position = "absolute";
+ }
+
+ var updateLoading = function(p){
+ if(p>=1) {
+ loadJsImg.parentNode.removeChild(loadJsImg);
+ }
+ }
+
var loaded = 0;
var que = engine.concat(c.appFiles);
que.push('main.js');
@@ -263,8 +284,9 @@
f.onload = loadNext;
d.body.appendChild(f);
//TODO: code for updating progress bar
- //p = s / (que.length - 1);
}
+ var p = s / (que.length - 1);
+ updateLoading(p);
};
loadNext();
}
@@ -276,7 +298,8 @@
s.onload = function () {
loaded++;
//TODO: code for updating progress bar
- //p = loaded / que.length;
+ var p = loaded / que.length;
+ updateLoading(p);
};
d.body.appendChild(s);
que[i] = s;
diff --git a/template/cocos2d.js b/template/cocos2d.js
index f657b9d7fc..b0d1b1c9ca 100644
--- a/template/cocos2d.js
+++ b/template/cocos2d.js
@@ -63,6 +63,18 @@
/*********Delete this section if you have packed all files into one*******/
if (c.SingleEngineFile && !c.engineDir) {
s.src = c.SingleEngineFile;
+
+ var loadJsImg = new Image();
+ loadJsImg.src = "data:image/gif;base64,R0lGODlhEAAQALMNAD8/P7+/vyoqKlVVVX9/fxUVFUBAQGBgYMDAwC8vL5CQkP///wAAAP///wAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh+QQFAAANACwAAAAAEAAQAAAEO5DJSau9OOvNex0IMnDIsiCkiW6g6BmKYlBFkhSUEgQKlQCARG6nEBwOgl+QApMdCIRD7YZ5RjlGpCUCACH5BAUAAA0ALAAAAgAOAA4AAAQ6kLGB0JA4M7QW0hrngRllkYyhKAYqKUGguAws0ypLS8JxCLQDgXAIDg+FRKIA6v0SAECCBpXSkstMBAAh+QQFAAANACwAAAAACgAQAAAEOJDJORAac6K1kDSKYmydpASBUl0mqmRfaGTCcQgwcxDEke+9XO2WkxQSiUIuAQAkls0n7JgsWq8RACH5BAUAAA0ALAAAAAAOAA4AAAQ6kMlplDIzTxWC0oxwHALnDQgySAdBHNWFLAvCukc215JIZihVIZEogDIJACBxnCSXTcmwGK1ar1hrBAAh+QQFAAANACwAAAAAEAAKAAAEN5DJKc4RM+tDyNFTkSQF5xmKYmQJACTVpQSBwrpJNteZSGYoFWjIGCAQA2IGsVgglBOmEyoxIiMAIfkEBQAADQAsAgAAAA4ADgAABDmQSVZSKjPPBEDSGucJxyGA1XUQxAFma/tOpDlnhqIYN6MEAUXvF+zldrMBAjHoIRYLhBMqvSmZkggAIfkEBQAADQAsBgAAAAoAEAAABDeQyUmrnSWlYhMASfeFVbZdjHAcgnUQxOHCcqWylKEohqUEAYVkgEAMfkEJYrFA6HhKJsJCNFoiACH5BAUAAA0ALAIAAgAOAA4AAAQ3kMlJq704611SKloCAEk4lln3DQgyUMJxCBKyLAh1EMRR3wiDQmHY9SQslyIQUMRmlmVTIyRaIgA7";
+
+ var canvasNode = document.getElementById(c.tag);
+ canvasNode.style.backgroundColor = "black";
+ canvasNode.parentNode.appendChild(loadJsImg);
+
+ var canvasStyle = getComputedStyle?getComputedStyle(canvasNode):canvasNode.currentStyle;
+ loadJsImg.style.left = canvasNode.offsetLeft + (parseFloat(canvasStyle.width) - loadJsImg.width)/2 + "px";
+ loadJsImg.style.top = canvasNode.offsetTop + (parseFloat(canvasStyle.height) - loadJsImg.height)/2 + "px";
+ loadJsImg.style.position = "absolute";
}
else if (c.engineDir && !c.SingleEngineFile) {
s.src = c.engineDir + 'platform/jsloader.js';
From 76cd18e620f9a626bcff7106685d4ace3fa78af9 Mon Sep 17 00:00:00 2001
From: 06wj <06wj@163.com>
Date: Mon, 26 Aug 2013 17:38:36 +0800
Subject: [PATCH 060/141] give loading image a id
---
template/cocos2d.js | 1 +
1 file changed, 1 insertion(+)
diff --git a/template/cocos2d.js b/template/cocos2d.js
index b0d1b1c9ca..47358d580a 100644
--- a/template/cocos2d.js
+++ b/template/cocos2d.js
@@ -75,6 +75,7 @@
loadJsImg.style.left = canvasNode.offsetLeft + (parseFloat(canvasStyle.width) - loadJsImg.width)/2 + "px";
loadJsImg.style.top = canvasNode.offsetTop + (parseFloat(canvasStyle.height) - loadJsImg.height)/2 + "px";
loadJsImg.style.position = "absolute";
+ loadJsImg.id = "cocos2d_loadJsImg";
}
else if (c.engineDir && !c.SingleEngineFile) {
s.src = c.engineDir + 'platform/jsloader.js';
From 1e0158010103d729eb8fe1f43a2ff8645781654b Mon Sep 17 00:00:00 2001
From: WanderWang
Date: Mon, 26 Aug 2013 23:44:09 +0800
Subject: [PATCH 061/141] =?UTF-8?q?=E4=BF=AE=E5=A4=8DBrowserTypes=E6=AD=A3?=
=?UTF-8?q?=E5=88=99=E8=A1=A8=E8=BE=BE=E5=BC=8F=E5=8C=B9=E9=85=8D=E5=A4=B1?=
=?UTF-8?q?=E8=B4=A5=E6=97=B6=E7=9A=84=E6=8A=A5=E9=94=99?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
修复BrowserTypes正则表达式匹配失败时的报错
---
cocos2d/platform/miniFramework.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/cocos2d/platform/miniFramework.js b/cocos2d/platform/miniFramework.js
index ba8eb80354..dea0805b08 100644
--- a/cocos2d/platform/miniFramework.js
+++ b/cocos2d/platform/miniFramework.js
@@ -59,7 +59,7 @@ cc.Browser = {};
cc.Browser.isMobile = (cc.Browser.ua.indexOf('mobile') != -1 || cc.Browser.ua.indexOf('android') != -1);
cc.Browser.type = (function () {
var browserTypes = cc.Browser.ua.match(/micromessenger|qqbrowser|mqqbrowser|ucbrowser|360browser|baidubrowser|maxthon|ie|opera|firefox/) || cc.Browser.ua.match(/chrome|safari/);
- if (browserTypes.length > 0) {
+ if (browserTypes && browserTypes.length > 0) {
var el = browserTypes[0];
if (el == 'micromessenger') {
return 'wechat';
From d86d249fef223e6ba86cefb9328f90e3261f4ed2 Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Tue, 27 Aug 2013 09:58:31 +0800
Subject: [PATCH 062/141] fixed #2506: Optimize performance for ContolButton,
ScrollView and TableView etc
---
cocos2d/CCLoader.js | 2 +-
cocos2d/actions/CCAction.js | 2 +-
cocos2d/base_nodes/CCNode.js | 2 +-
cocos2d/cocoa/CCAffineTransform.js | 45 +-
cocos2d/cocoa/CCGeometry.js | 6 +
cocos2d/label_nodes/CCLabelAtlas.js | 2 +-
.../CCTransition.js | 29 +-
.../CCTransitionProgress.js | 14 +-
cocos2d/menu_nodes/CCMenu.js | 54 ++-
cocos2d/menu_nodes/CCMenuItem.js | 2 +-
cocos2d/particle_nodes/CCParticleExamples.js | 22 +-
cocos2d/particle_nodes/CCParticleSystem.js | 2 +-
cocos2d/sprite_nodes/CCSprite.js | 4 +
.../tileMap_parallax_nodes/CCParallaxNode.js | 2 +-
cocos2d/tileMap_parallax_nodes/CCTMXLayer.js | 4 +-
extensions/CCBReader/CCBReader.js | 8 +-
extensions/CCEditBox.js | 4 +-
.../GUI/CCControlExtension/CCControl.js | 142 +++----
.../GUI/CCControlExtension/CCControlButton.js | 400 +++++++++---------
.../CCControlColourPicker.js | 2 +-
.../CCControlExtension/CCControlHuePicker.js | 2 +-
.../CCControlPotentiometer.js | 2 +-
.../CCControlSaturationBrightnessPicker.js | 2 +-
.../GUI/CCControlExtension/CCControlSlider.js | 2 +-
.../CCControlExtension/CCControlStepper.js | 3 +-
.../GUI/CCControlExtension/CCControlSwitch.js | 2 +-
.../GUI/CCControlExtension/CCControlUtils.js | 1 -
.../GUI/CCControlExtension/CCScale9Sprite.js | 49 +--
extensions/GUI/CCScrollView/CCScrollView.js | 122 +++---
extensions/GUI/CCScrollView/CCSorting.js | 15 +-
extensions/GUI/CCScrollView/CCTableView.js | 84 +++-
31 files changed, 544 insertions(+), 488 deletions(-)
diff --git a/cocos2d/CCLoader.js b/cocos2d/CCLoader.js
index bcdad56b23..6bfa53e296 100644
--- a/cocos2d/CCLoader.js
+++ b/cocos2d/CCLoader.js
@@ -423,7 +423,7 @@ cc.LoaderScene = cc.Scene.extend(/** @lends cc.LoaderScene# */{
// bg
this._bgLayer = cc.LayerColor.create(cc.c4(32, 32, 32, 255));
- this._bgLayer.setPosition(cc.p(0, 0));
+ this._bgLayer.setPosition(0, 0);
this.addChild(this._bgLayer, 0);
//loading percent
diff --git a/cocos2d/actions/CCAction.js b/cocos2d/actions/CCAction.js
index 82890d79b0..34fbec375c 100644
--- a/cocos2d/actions/CCAction.js
+++ b/cocos2d/actions/CCAction.js
@@ -462,7 +462,7 @@ cc.Follow = cc.Action.extend(/** @lends cc.Follow# */{
this._followedNode = followedNode;
this._worldRect = rect;
- this._boundarySet = !cc.rectEqualToRect(rect, cc.RectZero());
+ this._boundarySet = !cc._rectEqualToZero(rect);
this._boundaryFullyCovered = false;
diff --git a/cocos2d/base_nodes/CCNode.js b/cocos2d/base_nodes/CCNode.js
index e9dfe0c8d4..1c0bd68ebd 100644
--- a/cocos2d/base_nodes/CCNode.js
+++ b/cocos2d/base_nodes/CCNode.js
@@ -2758,7 +2758,7 @@ cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
*/
getBoundingBox:function () {
var rect = cc.rect(0, 0, this._contentSize.width, this._contentSize.height);
- return cc.RectApplyAffineTransform(rect, this.nodeToParentTransform());
+ return cc._RectApplyAffineTransformIn(rect, this.nodeToParentTransform());
},
/**
diff --git a/cocos2d/cocoa/CCAffineTransform.js b/cocos2d/cocoa/CCAffineTransform.js
index fbf7f30a9d..2437f5ca18 100644
--- a/cocos2d/cocoa/CCAffineTransform.js
+++ b/cocos2d/cocoa/CCAffineTransform.js
@@ -76,6 +76,11 @@ cc.PointApplyAffineTransform = function (point, t) {
return {x: t.a * point.x + t.c * point.y + t.tx, y: t.b * point.x + t.d * point.y + t.ty};
};
+cc._PointApplyAffineTransform = function (x, y, t) {
+ return {x: t.a * x + t.c * y + t.tx,
+ y: t.b * x + t.d * y + t.ty};
+};
+
cc.__SizeApplyAffineTransform = function (size, t) {
return {width: t.a * size.width + t.c * size.height, height: t.b * size.width + t.d * size.height};
};
@@ -122,10 +127,10 @@ cc.RectApplyAffineTransform = function (rect, anAffineTransform) {
var right = cc.rectGetMaxX(rect);
var bottom = cc.rectGetMaxY(rect);
- var topLeft = cc.PointApplyAffineTransform(cc.p(left, top), anAffineTransform);
- var topRight = cc.PointApplyAffineTransform(cc.p(right, top), anAffineTransform);
- var bottomLeft = cc.PointApplyAffineTransform(cc.p(left, bottom), anAffineTransform);
- var bottomRight = cc.PointApplyAffineTransform(cc.p(right, bottom), anAffineTransform);
+ var topLeft = cc._PointApplyAffineTransform(left, top, anAffineTransform);
+ var topRight = cc._PointApplyAffineTransform(right, top, anAffineTransform);
+ var bottomLeft = cc._PointApplyAffineTransform(left, bottom, anAffineTransform);
+ var bottomRight = cc._PointApplyAffineTransform(right, bottom, anAffineTransform);
var minX = Math.min(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x);
var maxX = Math.max(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x);
@@ -135,6 +140,29 @@ cc.RectApplyAffineTransform = function (rect, anAffineTransform) {
return cc.rect(minX, minY, (maxX - minX), (maxY - minY));
};
+cc._RectApplyAffineTransformIn = function(rect, anAffineTransform){
+ var top = cc.rectGetMinY(rect);
+ var left = cc.rectGetMinX(rect);
+ var right = cc.rectGetMaxX(rect);
+ var bottom = cc.rectGetMaxY(rect);
+
+ var topLeft = cc._PointApplyAffineTransform(left, top, anAffineTransform);
+ var topRight = cc._PointApplyAffineTransform(right, top, anAffineTransform);
+ var bottomLeft = cc._PointApplyAffineTransform(left, bottom, anAffineTransform);
+ var bottomRight = cc._PointApplyAffineTransform(right, bottom, anAffineTransform);
+
+ var minX = Math.min(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x);
+ var maxX = Math.max(topLeft.x, topRight.x, bottomLeft.x, bottomRight.x);
+ var minY = Math.min(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y);
+ var maxY = Math.max(topLeft.y, topRight.y, bottomLeft.y, bottomRight.y);
+
+ rect.x = minX;
+ rect.y = minY;
+ rect.width = maxX - minX;
+ rect.height = maxY - minY;
+ return rect;
+};
+
/**
* @function
* @param {cc.AffineTransform} t
@@ -144,7 +172,14 @@ cc.RectApplyAffineTransform = function (rect, anAffineTransform) {
* Constructor
*/
cc.AffineTransformTranslate = function (t, tx, ty) {
- return {a: t.a, b: t.b, c: t.c, d: t.d, tx: t.tx + t.a * tx + t.c * ty, ty: t.ty + t.b * tx + t.d * ty};
+ return {
+ a: t.a,
+ b: t.b,
+ c: t.c,
+ d: t.d,
+ tx: t.tx + t.a * tx + t.c * ty,
+ ty: t.ty + t.b * tx + t.d * ty
+ };
};
/**
diff --git a/cocos2d/cocoa/CCGeometry.js b/cocos2d/cocoa/CCGeometry.js
index 4944efb269..6cca20be8a 100644
--- a/cocos2d/cocoa/CCGeometry.js
+++ b/cocos2d/cocoa/CCGeometry.js
@@ -270,6 +270,12 @@ cc.rectEqualToRect = function (rect1, rect2) {
(cc.sizeEqualToSize(rect1.size, rect2.size)));
};
+cc._rectEqualToZero = function(rect){
+ if(!rect)
+ return false;
+ return (rect.x === 0) && (rect.y === 0) && (rect.width === 0) && (rect.height === 0);
+};
+
/**
* @function
* @param {cc.Rect} rect1
diff --git a/cocos2d/label_nodes/CCLabelAtlas.js b/cocos2d/label_nodes/CCLabelAtlas.js
index b12b1888e2..12dd596cdc 100644
--- a/cocos2d/label_nodes/CCLabelAtlas.js
+++ b/cocos2d/label_nodes/CCLabelAtlas.js
@@ -148,7 +148,7 @@ cc.LabelAtlasCanvas = cc.AtlasNode.extend(/** @lends cc.LabelAtlasCanvas# */{
fontChar.setOpacity(this._opacity);
}
}
- fontChar.setPosition(cc.p(i * locItemWidth + locItemWidth / 2, locItemHeight / 2));
+ fontChar.setPosition(i * locItemWidth + locItemWidth / 2, locItemHeight / 2);
}
},
diff --git a/cocos2d/layers_scenes_transitions_nodes/CCTransition.js b/cocos2d/layers_scenes_transitions_nodes/CCTransition.js
index 24ea00d9d9..96b5e330c6 100644
--- a/cocos2d/layers_scenes_transitions_nodes/CCTransition.js
+++ b/cocos2d/layers_scenes_transitions_nodes/CCTransition.js
@@ -165,7 +165,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
if (this.init()) {
this._duration = t;
this.setAnchorPoint(cc.p(0, 0));
- this.setPosition(cc.p(0, 0));
+ this.setPosition(0, 0);
// retain
this._inScene = scene;
this._outScene = cc.Director.getInstance().getRunningScene();
@@ -190,14 +190,14 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
finish:function () {
// clean up
this._inScene.setVisible(true);
- this._inScene.setPosition(cc.p(0, 0));
+ this._inScene.setPosition(0, 0);
this._inScene.setScale(1.0);
this._inScene.setRotation(0.0);
if(cc.renderContextType === cc.WEBGL)
this._inScene.getCamera().restore();
this._outScene.setVisible(false);
- this._outScene.setPosition(cc.p(0, 0));
+ this._outScene.setPosition(0, 0);
this._outScene.setScale(1.0);
this._outScene.setRotation(0.0);
if(cc.renderContextType === cc.WEBGL)
@@ -339,7 +339,7 @@ cc.TransitionJumpZoom = cc.TransitionScene.extend(/** @lends cc.TransitionJumpZo
var winSize = cc.Director.getInstance().getWinSize();
this._inScene.setScale(0.5);
- this._inScene.setPosition(cc.p(winSize.width, 0));
+ this._inScene.setPosition(winSize.width, 0);
this._inScene.setAnchorPoint(cc.p(0.5, 0.5));
this._outScene.setAnchorPoint(cc.p(0.5, 0.5));
@@ -394,7 +394,7 @@ cc.TransitionMoveInL = cc.TransitionScene.extend(/** @lends cc.TransitionMoveInL
* initializes the scenes
*/
initScenes:function () {
- this._inScene.setPosition(cc.p(-cc.Director.getInstance().getWinSize().width, 0));
+ this._inScene.setPosition(-cc.Director.getInstance().getWinSize().width, 0);
},
/**
@@ -437,12 +437,11 @@ cc.TransitionMoveInL.create = function (t, scene) {
* @extends cc.TransitionMoveInL
*/
cc.TransitionMoveInR = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveInR# */{
-
/**
* Init
*/
initScenes:function () {
- this._inScene.setPosition(cc.p(cc.Director.getInstance().getWinSize().width, 0));
+ this._inScene.setPosition(cc.Director.getInstance().getWinSize().width, 0);
}
});
@@ -474,7 +473,7 @@ cc.TransitionMoveInT = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveI
* init
*/
initScenes:function () {
- this._inScene.setPosition(cc.p(0, cc.Director.getInstance().getWinSize().height));
+ this._inScene.setPosition(0, cc.Director.getInstance().getWinSize().height);
}
});
@@ -506,7 +505,7 @@ cc.TransitionMoveInB = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveI
* init
*/
initScenes:function () {
- this._inScene.setPosition(cc.p(0, -cc.Director.getInstance().getWinSize().height));
+ this._inScene.setPosition(0, -cc.Director.getInstance().getWinSize().height);
}
});
@@ -573,7 +572,7 @@ cc.TransitionSlideInL = cc.TransitionScene.extend(/** @lends cc.TransitionSlideI
* initializes the scenes
*/
initScenes:function () {
- this._inScene.setPosition(cc.p(-(cc.Director.getInstance().getWinSize().width - cc.ADJUST_FACTOR), 0));
+ this._inScene.setPosition(-(cc.Director.getInstance().getWinSize().width - cc.ADJUST_FACTOR), 0);
},
/**
* returns the action that will be performed by the incomming and outgoing scene
@@ -622,7 +621,7 @@ cc.TransitionSlideInR = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli
* initializes the scenes
*/
initScenes:function () {
- this._inScene.setPosition(cc.p(cc.Director.getInstance().getWinSize().width - cc.ADJUST_FACTOR, 0));
+ this._inScene.setPosition(cc.Director.getInstance().getWinSize().width - cc.ADJUST_FACTOR, 0);
},
/**
* returns the action that will be performed by the incomming and outgoing scene
@@ -664,7 +663,7 @@ cc.TransitionSlideInB = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli
* initializes the scenes
*/
initScenes:function () {
- this._inScene.setPosition(cc.p(0, cc.Director.getInstance().getWinSize().height - cc.ADJUST_FACTOR));
+ this._inScene.setPosition(0, cc.Director.getInstance().getWinSize().height - cc.ADJUST_FACTOR);
},
/**
@@ -707,7 +706,7 @@ cc.TransitionSlideInT = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli
* initializes the scenes
*/
initScenes:function () {
- this._inScene.setPosition(cc.p(0, -(cc.Director.getInstance().getWinSize().height - cc.ADJUST_FACTOR)));
+ this._inScene.setPosition(0, -(cc.Director.getInstance().getWinSize().height - cc.ADJUST_FACTOR));
},
/**
@@ -1328,7 +1327,7 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross
return;
inTexture.getSprite().setAnchorPoint(cc.p(0.5, 0.5));
- inTexture.setPosition(cc.p(winSize.width / 2, winSize.height / 2));
+ inTexture.setPosition(winSize.width / 2, winSize.height / 2);
inTexture.setAnchorPoint(cc.p(0.5, 0.5));
// render inScene to its texturebuffer
@@ -1339,7 +1338,7 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross
// create the second render texture for outScene
var outTexture = cc.RenderTexture.create(winSize.width, winSize.height);
outTexture.getSprite().setAnchorPoint(cc.p(0.5, 0.5));
- outTexture.setPosition(cc.p(winSize.width / 2, winSize.height / 2));
+ outTexture.setPosition(winSize.width / 2, winSize.height / 2);
outTexture.setAnchorPoint(cc.p(0.5, 0.5));
// render outScene to its texturebuffer
diff --git a/cocos2d/layers_scenes_transitions_nodes/CCTransitionProgress.js b/cocos2d/layers_scenes_transitions_nodes/CCTransitionProgress.js
index 9d5b6ba404..c75fe1c65e 100644
--- a/cocos2d/layers_scenes_transitions_nodes/CCTransitionProgress.js
+++ b/cocos2d/layers_scenes_transitions_nodes/CCTransitionProgress.js
@@ -55,7 +55,7 @@ cc.TransitionProgress = cc.TransitionScene.extend(/** @lends cc.TransitionProgre
// create the second render texture for outScene
var texture = cc.RenderTexture.create(winSize.width, winSize.height);
texture.getSprite().setAnchorPoint(cc.p(0.5, 0.5));
- texture.setPosition(cc.p(winSize.width / 2, winSize.height / 2));
+ texture.setPosition(winSize.width / 2, winSize.height / 2);
texture.setAnchorPoint(cc.p(0.5, 0.5));
// render outScene to its texturebuffer
@@ -142,7 +142,7 @@ cc.TransitionProgressRadialCCW = cc.TransitionProgress.extend(/** @lends cc.Tran
// Return the radial type that we want to use
pNode.setReverseDirection(false);
pNode.setPercentage(100);
- pNode.setPosition(cc.p(size.width / 2, size.height / 2));
+ pNode.setPosition(size.width / 2, size.height / 2);
pNode.setAnchorPoint(cc.p(0.5, 0.5));
return pNode;
@@ -184,7 +184,7 @@ cc.TransitionProgressRadialCW = cc.TransitionProgress.extend(/** @lends cc.Trans
// Return the radial type that we want to use
pNode.setReverseDirection(true);
pNode.setPercentage(100);
- pNode.setPosition(cc.p(size.width / 2, size.height / 2));
+ pNode.setPosition(size.width / 2, size.height / 2);
pNode.setAnchorPoint(cc.p(0.5, 0.5));
return pNode;
@@ -227,7 +227,7 @@ cc.TransitionProgressHorizontal = cc.TransitionProgress.extend(/** @lends cc.Tra
pNode.setBarChangeRate(cc.p(1, 0));
pNode.setPercentage(100);
- pNode.setPosition(cc.p(size.width / 2, size.height / 2));
+ pNode.setPosition(size.width / 2, size.height / 2);
pNode.setAnchorPoint(cc.p(0.5, 0.5));
return pNode;
@@ -269,7 +269,7 @@ cc.TransitionProgressVertical = cc.TransitionProgress.extend(/** @lends cc.Trans
pNode.setBarChangeRate(cc.p(0, 1));
pNode.setPercentage(100);
- pNode.setPosition(cc.p(size.width / 2, size.height / 2));
+ pNode.setPosition(size.width / 2, size.height / 2);
pNode.setAnchorPoint(cc.p(0.5, 0.5));
return pNode;
@@ -310,7 +310,7 @@ cc.TransitionProgressInOut = cc.TransitionProgress.extend(/** @lends cc.Transiti
pNode.setBarChangeRate(cc.p(1, 1));
pNode.setPercentage(0);
- pNode.setPosition(cc.p(size.width / 2, size.height / 2));
+ pNode.setPosition(size.width / 2, size.height / 2);
pNode.setAnchorPoint(cc.p(0.5, 0.5));
return pNode;
@@ -359,7 +359,7 @@ cc.TransitionProgressOutIn = cc.TransitionProgress.extend(/** @lends cc.Transiti
pNode.setBarChangeRate(cc.p(1, 1));
pNode.setPercentage(100);
- pNode.setPosition(cc.p(size.width / 2, size.height / 2));
+ pNode.setPosition(size.width / 2, size.height / 2);
pNode.setAnchorPoint(cc.p(0.5, 0.5));
return pNode;
diff --git a/cocos2d/menu_nodes/CCMenu.js b/cocos2d/menu_nodes/CCMenu.js
index 8f90bd77a9..407df91346 100644
--- a/cocos2d/menu_nodes/CCMenu.js
+++ b/cocos2d/menu_nodes/CCMenu.js
@@ -154,7 +154,7 @@ cc.Menu = cc.LayerRGBA.extend(/** @lends cc.Menu# */{
this.ignoreAnchorPointForPosition(true);
this.setAnchorPoint(cc.p(0.5, 0.5));
this.setContentSize(winSize);
- this.setPosition(cc.p(winSize.width / 2, winSize.height / 2));
+ this.setPosition(winSize.width / 2, winSize.height / 2);
if (arrayOfItems) {
for (var i = 0; i < arrayOfItems.length; i++)
@@ -204,7 +204,7 @@ cc.Menu = cc.LayerRGBA.extend(/** @lends cc.Menu# */{
var y = height / 2.0;
if (this._children && this._children.length > 0) {
for (i = 0; i < this._children.length; i++) {
- this._children[i].setPosition(cc.p(0, y - this._children[i].getContentSize().height * this._children[i].getScaleY() / 2));
+ this._children[i].setPosition(0, y - this._children[i].getContentSize().height * this._children[i].getScaleY() / 2);
y -= this._children[i].getContentSize().height * this._children[i].getScaleY() + padding;
}
}
@@ -232,7 +232,7 @@ cc.Menu = cc.LayerRGBA.extend(/** @lends cc.Menu# */{
var x = -width / 2.0;
if (this._children && this._children.length > 0) {
for (i = 0; i < this._children.length; i++) {
- this._children[i].setPosition(cc.p(x + this._children[i].getContentSize().width * this._children[i].getScaleX() / 2, 0));
+ this._children[i].setPosition(x + this._children[i].getContentSize().width * this._children[i].getScaleX() / 2, 0);
x += this._children[i].getContentSize().width * this._children[i].getScaleX() + padding;
}
}
@@ -258,16 +258,17 @@ cc.Menu = cc.LayerRGBA.extend(/** @lends cc.Menu# */{
var row = 0;
var rowHeight = 0;
var columnsOccupied = 0;
- var rowColumns;
- if (this._children && this._children.length > 0) {
- for (i = 0; i < this._children.length; i++) {
+ var rowColumns, tmp, len;
+ var locChildren = this._children;
+ if (locChildren && locChildren.length > 0) {
+ for (i = 0, len = locChildren.length; i < len; i++) {
cc.Assert(row < rows.length, "");
rowColumns = rows[row];
// can not have zero columns on a row
cc.Assert(rowColumns, "");
- var tmp = this._children[i].getContentSize().height;
+ tmp = locChildren[i].getContentSize().height;
rowHeight = ((rowHeight >= tmp || isNaN(tmp)) ? rowHeight : tmp);
++columnsOccupied;
@@ -291,27 +292,24 @@ cc.Menu = cc.LayerRGBA.extend(/** @lends cc.Menu# */{
var x = 0.0;
var y = (height / 2);
- if (this._children && this._children.length > 0) {
- for (i = 0; i < this._children.length; i++) {
- var child = this._children[i];
+ if (locChildren && locChildren.length > 0) {
+ for (i = 0, len = locChildren.length; i < len; i++) {
+ var child = locChildren[i];
if (rowColumns == 0) {
rowColumns = rows[row];
w = winSize.width / (1 + rowColumns);
x = w;
}
- var tmp = child.getContentSize().height;
+ tmp = child.getContentSize().height;
rowHeight = ((rowHeight >= tmp || isNaN(tmp)) ? rowHeight : tmp);
-
- child.setPosition(cc.p(x - winSize.width / 2,
- y - child.getContentSize().height / 2));
+ child.setPosition(x - winSize.width / 2, y - tmp / 2);
x += w;
++columnsOccupied;
if (columnsOccupied >= rowColumns) {
y -= rowHeight + 5;
-
columnsOccupied = 0;
rowColumns = 0;
rowHeight = 0;
@@ -331,8 +329,8 @@ cc.Menu = cc.LayerRGBA.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 = [];
- for (var i = 0; i < arguments.length; i++) {
+ var columns = [], i;
+ for (i = 0; i < arguments.length; i++) {
columns.push(arguments[i]);
}
var columnWidths = [];
@@ -343,11 +341,12 @@ cc.Menu = cc.LayerRGBA.extend(/** @lends cc.Menu# */{
var column = 0;
var columnWidth = 0;
var rowsOccupied = 0;
- var columnRows;
+ var columnRows, child, len, tmp;
- if (this._children && this._children.length > 0) {
- for (var i = 0; i < this._children.length; i++) {
- var child = this._children[i];
+ var locChildren = this._children;
+ if (locChildren && locChildren.length > 0) {
+ for (i = 0, len = locChildren.length; i < len; i++) {
+ child = locChildren[i];
// check if too many menu items for the amount of rows/columns
cc.Assert(column < columns.length, "");
@@ -356,7 +355,7 @@ cc.Menu = cc.LayerRGBA.extend(/** @lends cc.Menu# */{
cc.Assert(columnRows, "");
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
- var tmp = child.getContentSize().width;
+ tmp = child.getContentSize().width;
columnWidth = ((columnWidth >= tmp || isNaN(tmp)) ? columnWidth : tmp);
columnHeight += (child.getContentSize().height + 5);
@@ -385,20 +384,19 @@ cc.Menu = cc.LayerRGBA.extend(/** @lends cc.Menu# */{
var x = -width / 2;
var y = 0.0;
- if (this._children && this._children.length > 0) {
- for (var i = 0; i < this._children.length; i++) {
- var child = this._children[i];
+ if (locChildren && locChildren.length > 0) {
+ for (i = 0, len = locChildren.length; i < len; i++) {
+ child = locChildren[i];
if (columnRows == 0) {
columnRows = columns[column];
y = columnHeights[column];
}
// columnWidth = fmaxf(columnWidth, [item contentSize].width);
- var tmp = child.getContentSize().width;
+ tmp = child.getContentSize().width;
columnWidth = ((columnWidth >= tmp || isNaN(tmp)) ? columnWidth : tmp);
- child.setPosition(cc.p(x + columnWidths[column] / 2,
- y - winSize.height / 2));
+ child.setPosition(x + columnWidths[column] / 2, y - winSize.height / 2);
y -= child.getContentSize().height + 10;
++rowsOccupied;
diff --git a/cocos2d/menu_nodes/CCMenuItem.js b/cocos2d/menu_nodes/CCMenuItem.js
index ea1ff9fc7a..8985d195ef 100644
--- a/cocos2d/menu_nodes/CCMenuItem.js
+++ b/cocos2d/menu_nodes/CCMenuItem.js
@@ -1060,7 +1060,7 @@ cc.MenuItemToggle = cc.MenuItem.extend(/** @lends cc.MenuItemToggle# */{
this.addChild(item, 0, cc.CURRENT_ITEM);
var s = item.getContentSize();
this.setContentSize(s);
- item.setPosition(cc.p(s.width / 2, s.height / 2));
+ item.setPosition(s.width / 2, s.height / 2);
}
},
diff --git a/cocos2d/particle_nodes/CCParticleExamples.js b/cocos2d/particle_nodes/CCParticleExamples.js
index 4d33780e8e..27d99061a0 100644
--- a/cocos2d/particle_nodes/CCParticleExamples.js
+++ b/cocos2d/particle_nodes/CCParticleExamples.js
@@ -71,7 +71,7 @@ cc.ParticleFire = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleFire# */{
// emitter position
var winSize = cc.Director.getInstance().getWinSize();
- this.setPosition(cc.p(winSize.width / 2, 60));
+ this.setPosition(winSize.width / 2, 60);
this._posVar = cc.p(40, 20);
// life of particles
@@ -171,7 +171,7 @@ cc.ParticleFireworks = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleFirewo
// emitter position
var winSize = cc.Director.getInstance().getWinSize();
- this.setPosition(cc.p(winSize.width / 2, winSize.height / 2));
+ this.setPosition(winSize.width / 2, winSize.height / 2);
// angle
this._angle = 90;
@@ -280,7 +280,7 @@ cc.ParticleSun = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleSun# */{
// emitter position
var winSize = cc.Director.getInstance().getWinSize();
- this.setPosition(cc.p(winSize.width / 2, winSize.height / 2));
+ this.setPosition(winSize.width / 2, winSize.height / 2);
this.setPosVar(cc.PointZero());
// life of particles
@@ -387,7 +387,7 @@ cc.ParticleGalaxy = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleGalaxy# *
// emitter position
var winSize = cc.Director.getInstance().getWinSize();
- this.setPosition(cc.p(winSize.width / 2, winSize.height / 2));
+ this.setPosition(winSize.width / 2, winSize.height / 2);
this._posVar = cc.PointZero();
// life of particles
@@ -493,7 +493,7 @@ cc.ParticleFlower = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleFlower# *
// emitter position
var winSize = cc.Director.getInstance().getWinSize();
- this.setPosition(cc.p(winSize.width / 2, winSize.height / 2));
+ this.setPosition(winSize.width / 2, winSize.height / 2);
this._posVar = cc.PointZero();
// life of particles
@@ -601,7 +601,7 @@ cc.ParticleMeteor = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleMeteor# *
// emitter position
var winSize = cc.Director.getInstance().getWinSize();
- this.setPosition(cc.p(winSize.width / 2, winSize.height / 2));
+ this.setPosition(winSize.width / 2, winSize.height / 2);
this._posVar = cc.PointZero();
// life of particles
@@ -708,7 +708,7 @@ cc.ParticleSpiral = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleSpiral# *
// emitter position
var winSize = cc.Director.getInstance().getWinSize();
- this.setPosition(cc.p(winSize.width / 2, winSize.height / 2));
+ this.setPosition(winSize.width / 2, winSize.height / 2);
this._posVar = cc.PointZero();
// life of particles
@@ -815,7 +815,7 @@ cc.ParticleExplosion = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleExplos
// emitter position
var winSize = cc.Director.getInstance().getWinSize();
- this.setPosition(cc.p(winSize.width / 2, winSize.height / 2));
+ this.setPosition(winSize.width / 2, winSize.height / 2);
this._posVar = cc.PointZero();
// life of particles
@@ -919,7 +919,7 @@ cc.ParticleSmoke = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleSmoke# */{
// emitter position
var winSize = cc.Director.getInstance().getWinSize();
- this.setPosition(cc.p(winSize.width / 2, 0));
+ this.setPosition(winSize.width / 2, 0);
this._posVar = cc.p(20, 0);
// life of particles
@@ -1022,7 +1022,7 @@ cc.ParticleSnow = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleSnow# */{
// emitter position
var winSize = cc.Director.getInstance().getWinSize();
- this.setPosition(cc.p(winSize.width / 2, winSize.height + 10));
+ this.setPosition(winSize.width / 2, winSize.height + 10);
this._posVar = cc.p(winSize.width / 2, 0);
// angle
@@ -1134,7 +1134,7 @@ cc.ParticleRain = cc.ParticleSystemQuad.extend(/** @lends cc.ParticleRain# */{
// emitter position
var winSize = cc.Director.getInstance().getWinSize();
- this.setPosition(cc.p(winSize.width / 2, winSize.height));
+ this.setPosition(winSize.width / 2, winSize.height);
this._posVar = cc.p(winSize.width / 2, 0);
// life of particles
diff --git a/cocos2d/particle_nodes/CCParticleSystem.js b/cocos2d/particle_nodes/CCParticleSystem.js
index 7a2ec5c0b6..05834c754b 100644
--- a/cocos2d/particle_nodes/CCParticleSystem.js
+++ b/cocos2d/particle_nodes/CCParticleSystem.js
@@ -1340,7 +1340,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
// position
var x = parseFloat(locValueForKey("sourcePositionx", dictionary));
var y = parseFloat(locValueForKey("sourcePositiony", dictionary));
- this.setPosition(cc.p(x, y));
+ this.setPosition(x, y);
this._posVar.x = parseFloat(locValueForKey("sourcePositionVariancex", dictionary));
this._posVar.y = parseFloat(locValueForKey("sourcePositionVariancey", dictionary));
diff --git a/cocos2d/sprite_nodes/CCSprite.js b/cocos2d/sprite_nodes/CCSprite.js
index f3fdcdbba0..78b022bab7 100644
--- a/cocos2d/sprite_nodes/CCSprite.js
+++ b/cocos2d/sprite_nodes/CCSprite.js
@@ -1052,6 +1052,8 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
if (!locRect) {
locRect = cc.rect(0, 0, 0, 0);
locRect.size = sender.getContentSize();
+ } else if(cc._rectEqualToZero(locRect)){
+ locRect.size = sender.getContentSize();
}
this._originalTexture = sender;
@@ -2180,6 +2182,8 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
if (!locRect) {
locRect = cc.rect(0, 0, 0, 0);
locRect.size = sender.getContentSize();
+ } else if(cc._rectEqualToZero(locRect)){
+ locRect.size = sender.getContentSize();
}
this.setTexture(sender);
diff --git a/cocos2d/tileMap_parallax_nodes/CCParallaxNode.js b/cocos2d/tileMap_parallax_nodes/CCParallaxNode.js
index c5c29f91fa..9d512e30b5 100644
--- a/cocos2d/tileMap_parallax_nodes/CCParallaxNode.js
+++ b/cocos2d/tileMap_parallax_nodes/CCParallaxNode.js
@@ -202,7 +202,7 @@ cc.ParallaxNode = cc.Node.extend(/** @lends cc.ParallaxNode# */{
var point = locParallaxArray[i];
var x = -pos.x + pos.x * point.getRatio().x + point.getOffset().x;
var y = -pos.y + pos.y * point.getRatio().y + point.getOffset().y;
- point.getChild().setPosition(cc.p(x, y));
+ point.getChild().setPosition(x, y);
}
this._lastPosition = pos;
}
diff --git a/cocos2d/tileMap_parallax_nodes/CCTMXLayer.js b/cocos2d/tileMap_parallax_nodes/CCTMXLayer.js
index 7211b3e37c..b139fad240 100644
--- a/cocos2d/tileMap_parallax_nodes/CCTMXLayer.js
+++ b/cocos2d/tileMap_parallax_nodes/CCTMXLayer.js
@@ -760,8 +760,8 @@ cc.TMXLayer = cc.SpriteBatchNode.extend(/** @lends cc.TMXLayer# */{
if ((gid & cc.TMX_TILE_DIAGONAL_FLAG) >>> 0) {
// put the anchor in the middle for ease of rotation.
sprite.setAnchorPoint(cc.p(0.5, 0.5));
- sprite.setPosition(cc.p(this.getPositionAt(pos).x + sprite.getContentSize().height / 2,
- this.getPositionAt(pos).y + sprite.getContentSize().width / 2));
+ sprite.setPosition(this.getPositionAt(pos).x + sprite.getContentSize().height / 2,
+ this.getPositionAt(pos).y + sprite.getContentSize().width / 2);
var flag = (gid & (cc.TMX_TILE_HORIZONTAL_FLAG | cc.TMX_TILE_VERTICAL_FLAG) >>> 0) >>> 0;
// handle the 4 diagonally flipped states.
diff --git a/extensions/CCBReader/CCBReader.js b/extensions/CCBReader/CCBReader.js
index d2fb41301b..d0ceb994e8 100644
--- a/extensions/CCBReader/CCBReader.js
+++ b/extensions/CCBReader/CCBReader.js
@@ -227,7 +227,7 @@ cc.BuilderReader = cc.Class.extend({
return this.readNodeGraphFromData(data, owner, parentSize, animationManager);
},
- readNodeGraphFromData:function (data, owner, parentSize, animationManager) {
+ readNodeGraphFromData:function (data, owner, parentSize) {
this.initWithData(data, owner);
this._actionManager.setRootContainerSize(parentSize);
this._actionManager.setOwner(owner);
@@ -256,12 +256,6 @@ cc.BuilderReader = cc.Class.extend({
}
}
- // Return action manager by reference
- //if (ppAnimationManager)
- //{
- // *ppAnimationManager = mActionManager;
- //}
-
return nodeGraph;
},
diff --git a/extensions/CCEditBox.js b/extensions/CCEditBox.js
index e738d17aba..176181e246 100644
--- a/extensions/CCEditBox.js
+++ b/extensions/CCEditBox.js
@@ -412,11 +412,11 @@ cc.EditBox = cc.ControlButton.extend({
*/
initWithSizeAndBackgroundSprite: function (size, normal9SpriteBg) {
if (this.initWithBackgroundSprite(normal9SpriteBg)) {
- this._domInputSprite.setPosition(cc.p(3, 3));
+ this._domInputSprite.setPosition(3, 3);
this.setZoomOnTouchDown(false);
this.setPreferredSize(size);
- this.setPosition(cc.p(0, 0));
+ this.setPosition(0, 0);
this._addTargetWithActionForControlEvent(this, this.touchDownAction, cc.CONTROL_EVENT_TOUCH_UP_INSIDE);
return true;
}
diff --git a/extensions/GUI/CCControlExtension/CCControl.js b/extensions/GUI/CCControlExtension/CCControl.js
index c3a7dc14e2..14836390d0 100644
--- a/extensions/GUI/CCControlExtension/CCControl.js
+++ b/extensions/GUI/CCControlExtension/CCControl.js
@@ -1,4 +1,4 @@
-/*
+/**
*
* Copyright (c) 2010-2012 cocos2d-x.org
* Copyright 2011 Yannick Loriot.
@@ -69,11 +69,10 @@ cc.Control = cc.LayerRGBA.extend({
this._isOpacityModifyRGB = opacityModifyRGB;
var children = this.getChildren();
- for (var i = 0; i < children.length; i++) {
+ for (var i = 0, len = children.length; i < len; i++) {
var selNode = children[i];
- if (selNode && selNode.RGBAProtocol) {
+ if (selNode && selNode.RGBAProtocol)
selNode.setOpacityModifyRGB(opacityModifyRGB);
- }
}
},
@@ -87,7 +86,7 @@ cc.Control = cc.LayerRGBA.extend({
_selected:false,
_highlighted:false,
- _dispatchTable:{},
+ _dispatchTable:null,
/**
* Tells whether the control is enabled
@@ -95,11 +94,7 @@ cc.Control = cc.LayerRGBA.extend({
*/
setEnabled:function (enabled) {
this._enabled = enabled;
- if (this._enabled) {
- this._state = cc.CONTROL_STATE_NORMAL;
- } else {
- this._state = cc.CONTROL_STATE_DISABLED;
- }
+ this._state = enabled ? cc.CONTROL_STATE_NORMAL:cc.CONTROL_STATE_DISABLED;
this.needsLayout();
},
@@ -134,9 +129,8 @@ cc.Control = cc.LayerRGBA.extend({
hasVisibleParents:function () {
var parent = this.getParent();
for (var c = parent; c != null; c = c.getParent()) {
- if (!c.isVisible()) {
+ if (!c.isVisible())
return false;
- }
}
return true;
},
@@ -161,7 +155,7 @@ cc.Control = cc.LayerRGBA.extend({
this._defaultTouchPriority = 1;
this.setTouchPriority(1);
// Initialise the tables
- this._dispatchTable = {};
+ //this._dispatchTable = {};
//dispatchTable.autorelease();
// dispatchTable_ = [[NSMutableDictionary alloc] initWithCapacity:1];
return true;
@@ -176,17 +170,17 @@ cc.Control = cc.LayerRGBA.extend({
/**
* Sends action messages for the given control events.
* which action messages are sent. See "CCControlEvent" for bitmask constants.
- * @param controlEvents A bitmask whose set flags specify the control events for
+ * @param {Number} controlEvents A bitmask whose set flags specify the control events for
*/
sendActionsForControlEvents:function (controlEvents) {
// For each control events
- for (var i = 0; i < cc.CONTROL_EVENT_TOTAL_NUMBER; i++) {
+ for (var i = 0, len = cc.CONTROL_EVENT_TOTAL_NUMBER; i < len; i++) {
// If the given controlEvents bitmask contains the curent event
if ((controlEvents & (1 << i))) {
// Call invocations
//
var invocationList = this._dispatchListforControlEvent(1 << i);
- for (var j = 0; j < invocationList.length; j++) {
+ for (var j = 0, inLen = invocationList.length; j < inLen; j++) {
invocationList[j].invoke(this);
}
}
@@ -194,69 +188,57 @@ cc.Control = cc.LayerRGBA.extend({
},
/**
- * Adds a target and action for a particular event (or events) to an internal
- * dispatch table.
- * The action message may optionnaly include the sender and the event as
- * parameters, in that order.
+ *
+ * Adds a target and action for a particular event (or events) to an internal
+ * dispatch table.
+ * The action message may optionally include the sender and the event as
+ * parameters, in that order.
* When you call this method, target is not retained.
- *
- * @param target The target object梩hat is, the object to which the action
- * message is sent. It cannot be nil. The target is not retained.
- * @param action A selector identifying an action message. It cannot be NULL.
- * @param controlEvents A bitmask specifying the control events for which the
- * action message is sent. See "CCControlEvent" for bitmask constants.
+ *
+ * @param {Object} target The target object that is, the object to which the action message is sent. It cannot be nil. The target is not retained.
+ * @param {function} action A selector identifying an action message. It cannot be NULL.
+ * @param {Number} controlEvents A bitmask specifying the control events for which the action message is sent. See "CCControlEvent" for bitmask constants.
*/
addTargetWithActionForControlEvents:function (target, action, controlEvents) {
// For each control events
- for (var i = 0; i < cc.CONTROL_EVENT_TOTAL_NUMBER; i++) {
- // If the given controlEvents bitmask contains the curent event
- if ((controlEvents & (1 << i))) {
+ for (var i = 0, len = cc.CONTROL_EVENT_TOTAL_NUMBER; i < len; i++) {
+ // If the given controlEvents bit mask contains the current event
+ if ((controlEvents & (1 << i)))
this._addTargetWithActionForControlEvent(target, action, 1 << i);
- }
}
},
/**
- * Removes a target and action for a particular event (or events) from an
- * internal dispatch table.
+ * Removes a target and action for a particular event (or events) from an internal dispatch table.
*
- * @param target The target object梩hat is, the object to which the action
- * message is sent. Pass nil to remove all targets paired with action and the
- * specified control events.
- * @param action A selector identifying an action message. Pass NULL to remove
- * all action messages paired with target.
- * @param controlEvents A bitmask specifying the control events associated with
- * target and action. See "CCControlEvent" for bitmask constants.
+ * @param {Object} target The target object that is, the object to which the action message is sent. Pass nil to remove all targets paired with action and the specified control events.
+ * @param {function} action A selector identifying an action message. Pass NULL to remove all action messages paired with target.
+ * @param {Number} controlEvents A bitmask specifying the control events associated with target and action. See "CCControlEvent" for bitmask constants.
*/
removeTargetWithActionForControlEvents:function (target, action, controlEvents) {
// For each control events
- for (var i = 0; i < cc.CONTROL_EVENT_TOTAL_NUMBER; i++) {
- // If the given controlEvents bitmask contains the curent event
- if ((controlEvents & (1 << i))) {
+ for (var i = 0, len = cc.CONTROL_EVENT_TOTAL_NUMBER; i < len; i++) {
+ // If the given controlEvents bitmask contains the current event
+ if ((controlEvents & (1 << i)))
this.removeTargetWithActionForControlEvent(target, action, 1 << i);
- }
}
},
/**
* Returns a point corresponding to the touh location converted into the
* control space coordinates.
- * @param touch A CCTouch object that represents a touch.
+ * @param {cc.Touch} touch A CCTouch object that represents a touch.
*/
getTouchLocation:function (touch) {
var touchLocation = touch.getLocation(); // Get the touch position
- touchLocation = this.convertToNodeSpace(touchLocation); // Convert to the node space of this class
-
- return touchLocation;
+ return this.convertToNodeSpace(touchLocation); // Convert to the node space of this class
},
/**
- * Returns a boolean value that indicates whether a touch is inside the bounds
- * of the receiver. The given touch must be relative to the world.
+ * Returns a boolean value that indicates whether a touch is inside the bounds of the receiver. The given touch must be relative to the world.
*
- * @param touch A CCTouch object that represents a touch.
- *
- * @return YES whether a touch is inside the receiver抯 rect.
+ * @param {cc.Touch} touch A cc.Touch object that represents a touch.
+ * @return {Boolean} YES whether a touch is inside the receiver's rect.
*/
isTouchInside:function (touch) {
var touchLocation = touch.getLocation(); // Get the touch position
@@ -265,51 +247,43 @@ cc.Control = cc.LayerRGBA.extend({
},
/**
- * Returns an CCInvocation object able to construct messages using a given
- * target-action pair. (The invocation may optionnaly include the sender and
+ *
+ * Returns an cc.Invocation object able to construct messages using a given
+ * target-action pair. (The invocation may optionally include the sender and
* the event as parameters, in that order)
+ *
+ * @param {Object} target The target object.
+ * @param {function} action A selector identifying an action message.
+ * @param {Number} controlEvent A control events for which the action message is sent. See "CCControlEvent" for constants.
*
- * @param target The target object.
- * @param action A selector identifying an action message.
- * @param controlEvent A control events for which the action message is sent.
- * See "CCControlEvent" for constants.
- *
- * @return an CCInvocation object able to construct messages using a given
- * target-action pair.
+ * @return {cc.Invocation} an CCInvocation object able to construct messages using a given target-action pair.
*/
_invocationWithTargetAndActionForControlEvent:function (target, action, controlEvent) {
+ return null;
},
/**
- * Returns the CCInvocation list for the given control event. If the list does
- * not exist, it'll create an empty array before returning it.
- *
- * @param controlEvent A control events for which the action message is sent.
- * See "CCControlEvent" for constants.
+ * Returns the cc.Invocation list for the given control event. If the list does not exist, it'll create an empty array before returning it.
*
- * @return the CCInvocation list for the given control event.
+ * @param {Number} controlEvent A control events for which the action message is sent. See "CCControlEvent" for constants.
+ * @return {cc.Invocation} the cc.Invocation list for the given control event.
*/
_dispatchListforControlEvent:function (controlEvent) {
controlEvent = controlEvent.toString();
- if (this._dispatchTable.hasOwnProperty(controlEvent))
- return this._dispatchTable[controlEvent];
-
// If the invocation list does not exist for the dispatch table, we create it
-
- var invocationList = [];
- this._dispatchTable[controlEvent] = invocationList;
-
- return invocationList;
+ if (!this._dispatchTable.hasOwnProperty(controlEvent))
+ this._dispatchTable[controlEvent] = [];
+ return this._dispatchTable[controlEvent];
},
/**
* Adds a target and action for a particular event to an internal dispatch
* table.
- * The action message may optionnaly include the sender and the event as
+ * The action message may optionally include the sender and the event as
* parameters, in that order.
* When you call this method, target is not retained.
*
- * @param target The target object梩hat is, the object to which the action
+ * @param target The target object that is, the object to which the action
* message is sent. It cannot be nil. The target is not retained.
* @param action A selector identifying an action message. It cannot be NULL.
* @param controlEvent A control event for which the action message is sent.
@@ -325,16 +299,11 @@ cc.Control = cc.LayerRGBA.extend({
},
/**
- * Removes a target and action for a particular event from an internal dispatch
- * table.
+ * Removes a target and action for a particular event from an internal dispatch table.
*
- * @param target The target object梩hat is, the object to which the action
- * message is sent. Pass nil to remove all targets paired with action and the
- * specified control events.
- * @param action A selector identifying an action message. Pass NULL to remove
- * all action messages paired with target.
- * @param controlEvent A control event for which the action message is sent.
- * See "CCControlEvent" for constants.
+ * @param {Object} target The target object that is, the object to which the action message is sent. Pass nil to remove all targets paired with action and the specified control events.
+ * @param {function} action A selector identifying an action message. Pass NULL to remove all action messages paired with target.
+ * @param {Number} controlEvent A control event for which the action message is sent. See "CCControlEvent" for constants.
*/
removeTargetWithActionForControlEvent:function (target, action, controlEvent) {
// Retrieve all invocations for the given control event
@@ -367,7 +336,6 @@ cc.Control = cc.LayerRGBA.extend({
* Updates the control layout using its current internal state.
*/
needsLayout:function () {
-
}
});
diff --git a/extensions/GUI/CCControlExtension/CCControlButton.js b/extensions/GUI/CCControlExtension/CCControlButton.js
index 79d8ce3038..ee479f8240 100644
--- a/extensions/GUI/CCControlExtension/CCControlButton.js
+++ b/extensions/GUI/CCControlExtension/CCControlButton.js
@@ -1,4 +1,4 @@
-/*
+/**
* CCControlButton.m
*
* Copyright (c) 2010-2012 cocos2d-x.org
@@ -28,16 +28,16 @@ cc.CONTROL_ZOOM_ACTION_TAG = 0xCCCB0001;
/** @class CCControlButton Button control for Cocos2D. */
cc.ControlButton = cc.Control.extend({
- _adjustBackgroundImage:false,
+ _doesAdjustBackgroundImage:false,
_zoomOnTouchDown:false,
- _preferredSize:new cc.Size(0, 0),
- _labelAnchorPoint:new cc.Point(0, 0),
- _currentTitle:"",
- _currentTitleColor:cc.white(),
+ _preferredSize: null,
+ _labelAnchorPoint: null,
+ _currentTitle: null,
+ _currentTitleColor: null,
_titleLabel:null,
_backgroundSprite:null,
_opacity:0,
- _pushed:false,
+ _isPushed:false,
_titleDispatchTable:null,
_titleColorDispatchTable:null,
_titleLabelDispatchTable:null,
@@ -51,7 +51,7 @@ cc.ControlButton = cc.Control.extend({
cc.Control.prototype.ctor.call(this);
this._preferredSize = new cc.Size(0, 0);
this._labelAnchorPoint = new cc.Point(0, 0);
-
+ this._currentTitle = "";
this._currentTitleColor = cc.white();
this._titleDispatchTable = {};
this._titleColorDispatchTable = {};
@@ -60,7 +60,7 @@ cc.ControlButton = cc.Control.extend({
},
init:function () {
- return this.initWithLabelAndBackgroundSprite(cc.LabelTTF.create("", "Helvetica", 12), cc.Scale9Sprite.create());
+ return this.initWithLabelAndBackgroundSprite(cc.LabelTTF.create("", "Arial", 12), cc.Scale9Sprite.create());
},
needsLayout:function () {
@@ -68,63 +68,74 @@ cc.ControlButton = cc.Control.extend({
return;
}
// Hide the background and the label
- this._titleLabel.setVisible(false);
- this._backgroundSprite.setVisible(false);
+ if(this._titleLabel)
+ this._titleLabel.setVisible(false);
+ if(this._backgroundSprite)
+ this._backgroundSprite.setVisible(false);
// Update anchor of all labels
this.setLabelAnchorPoint(this._labelAnchorPoint);
// Update the label to match with the current state
//CC_SAFE_RELEASE(this._currentTitle)
+ var locState = this._state;
- this._currentTitle = this.getTitleForState(this._state);
- this._currentTitleColor = this.getTitleColorForState(this._state);
-
- this._titleLabel = this.getTitleLabelForState(this._state);
+ this._currentTitle = this.getTitleForState(locState);
+ this._currentTitleColor = this.getTitleColorForState(locState);
+ this._titleLabel = this.getTitleLabelForState(locState);
var label = this._titleLabel;
if (label && label.setString)
label.setString(this._currentTitle);
+ if (label && label.RGBAProtocol)
+ label.setColor(this._currentTitleColor);
- if (this._titleLabel && this._titleLabel.RGBAProtocol)
- this._titleLabel.setColor(this._currentTitleColor);
- this._titleLabel.setPosition(cc.p(this.getContentSize().width / 2, this.getContentSize().height / 2));
-
+ var locContentSize = this.getContentSize();
+ if(label)
+ label.setPosition(locContentSize.width / 2, locContentSize.height / 2);
// Update the background sprite
- this._backgroundSprite = this.getBackgroundSpriteForState(this._state);
- this._backgroundSprite.setPosition(cc.p(this.getContentSize().width / 2, this.getContentSize().height / 2));
+ this._backgroundSprite = this.getBackgroundSpriteForState(locState);
+ var locBackgroundSprite = this._backgroundSprite;
+ if(locBackgroundSprite)
+ locBackgroundSprite.setPosition(locContentSize.width / 2, locContentSize.height / 2);
// Get the title label size
- var titleLabelSize = this._titleLabel.getBoundingBox().size;
+ var titleLabelSize = label ? label.getBoundingBox().size : cc.size(0, 0);
// Adjust the background image if necessary
- if (this._adjustBackgroundImage) {
+ if (this._doesAdjustBackgroundImage) {
// Add the margins
- this._backgroundSprite.setContentSize(cc.SizeMake(titleLabelSize.width + this._marginH * 2, titleLabelSize.height + this._marginV * 2));
+ if(locBackgroundSprite)
+ locBackgroundSprite.setContentSize(cc.size(titleLabelSize.width + this._marginH * 2, titleLabelSize.height + this._marginV * 2));
} else {
//TODO: should this also have margins if one of the preferred sizes is relaxed?
- var preferredSize = this._backgroundSprite.getPreferredSize();
- if (preferredSize.width <= 0) {
- preferredSize.width = titleLabelSize.width;
+ if(locBackgroundSprite){
+ var preferredSize = locBackgroundSprite.getPreferredSize();
+ preferredSize = cc.size(preferredSize.width, preferredSize.height);
+ if (preferredSize.width <= 0)
+ preferredSize.width = titleLabelSize.width;
+ if (preferredSize.height <= 0)
+ preferredSize.height = titleLabelSize.height;
+
+ locBackgroundSprite.setContentSize(preferredSize);
}
- if (preferredSize.height <= 0) {
- preferredSize.height = titleLabelSize.height;
- }
-
- this._backgroundSprite.setContentSize(preferredSize);
}
// Set the content size
- var maxRect = cc.ControlUtils.CCRectUnion(this._titleLabel.getBoundingBox(), this._backgroundSprite.getBoundingBox());
- this.setContentSize(cc.SizeMake(maxRect.width, maxRect.height));
-
- this._titleLabel.setPosition(cc.p(this.getContentSize().width / 2, this.getContentSize().height / 2));
- this._backgroundSprite.setPosition(cc.p(this.getContentSize().width / 2, this.getContentSize().height / 2));
-
- // Make visible the background and the label
- this._titleLabel.setVisible(true);
- this._backgroundSprite.setVisible(true);
+ var rectTitle = label? label.getBoundingBox():cc.rect(0,0,0,0);
+ var rectBackground = locBackgroundSprite? locBackgroundSprite.getBoundingBox():cc.rect(0,0,0,0);
+ var maxRect = cc.rectUnion(rectTitle, rectBackground);
+ this.setContentSize(cc.size(maxRect.width, maxRect.height));
+ locContentSize = this.getContentSize();
+ if(label){
+ label.setPosition(locContentSize.width / 2, locContentSize.height / 2);
+ label.setVisible(true);
+ }
+ if(locBackgroundSprite){
+ locBackgroundSprite.setPosition(locContentSize.width / 2, locContentSize.height / 2);
+ locBackgroundSprite.setVisible(true);
+ }
},
initWithLabelAndBackgroundSprite:function (label, backgroundSprite) {
@@ -132,15 +143,23 @@ cc.ControlButton = cc.Control.extend({
cc.Assert(label != null, "node must not be nil");
cc.Assert(label != null || label.RGBAProtocol || backgroundSprite != null, "");
- this.setTouchEnabled(true);
- this._pushed = false;
this._parentInited = true;
+
+ // Initialize the button state tables
+ this._titleDispatchTable = {};
+ this._titleColorDispatchTable = {};
+ this._titleLabelDispatchTable = {};
+ this._backgroundSpriteDispatchTable = {};
+
+ this.setTouchEnabled(true);
+ this._isPushed = false;
this._zoomOnTouchDown = true;
- this._state = cc.CONTROL_STATE_INITIAL;
+
this._currentTitle = null;
// Adjust the background image by default
- this._adjustBackgroundImage = true;
+ this.setAdjustBackgroundImage(true);
+ this.setPreferredSize(cc.size(0,0));
// Zooming button by default
this._zoomOnTouchDown = true;
@@ -153,13 +172,6 @@ cc.ControlButton = cc.Control.extend({
this._titleLabel = label;
this._backgroundSprite = backgroundSprite;
-
- // Initialize the button state tables
- this._titleDispatchTable = {};
- this._titleColorDispatchTable = {};
- this._titleLabelDispatchTable = {};
- this._backgroundSpriteDispatchTable = {};
-
// Set the default color and opacity
this.setColor(cc.c3(255, 255, 255));
this.setOpacity(255);
@@ -185,7 +197,6 @@ cc.ControlButton = cc.Control.extend({
// Layout update
this.needsLayout();
-
return true;
}//couldn't init the CCControl
else
@@ -202,13 +213,16 @@ cc.ControlButton = cc.Control.extend({
return this.initWithLabelAndBackgroundSprite(label, sprite);
},
- /** Adjust the background image. YES by default. If the property is set to NO, the
- background will use the prefered size of the background image. */
- getAdjustBackgroundImage:function () {
- return this._adjustBackgroundImage;
+ /**
+ * Adjust the background image. YES by default. If the property is set to NO, the background will use the prefered size of the background image.
+ * @return {Boolean}
+ */
+ doesAdjustBackgroundImage:function () {
+ return this._doesAdjustBackgroundImage;
},
+
setAdjustBackgroundImage:function (adjustBackgroundImage) {
- this._adjustBackgroundImage = adjustBackgroundImage;
+ this._doesAdjustBackgroundImage = adjustBackgroundImage;
this.needsLayout();
},
@@ -216,6 +230,7 @@ cc.ControlButton = cc.Control.extend({
getZoomOnTouchDown:function () {
return this._zoomOnTouchDown;
},
+
setZoomOnTouchDown:function (zoomOnTouchDown) {
return this._zoomOnTouchDown = zoomOnTouchDown;
},
@@ -227,12 +242,12 @@ cc.ControlButton = cc.Control.extend({
setPreferredSize:function (size) {
if (size.width === 0 && size.height === 0) {
- this._adjustBackgroundImage = true;
+ this._doesAdjustBackgroundImage = true;
} else {
- this._adjustBackgroundImage = false;
- for (var itemKey in this._backgroundSpriteDispatchTable) {
- this._backgroundSpriteDispatchTable[itemKey].setPreferredSize(size);
- }
+ this._doesAdjustBackgroundImage = false;
+ var locTable = this._backgroundSpriteDispatchTable;
+ for (var itemKey in locTable)
+ locTable[itemKey].setPreferredSize(size);
}
this._preferredSize = size;
this.needsLayout();
@@ -243,17 +258,20 @@ cc.ControlButton = cc.Control.extend({
},
setLabelAnchorPoint:function (labelAnchorPoint) {
this._labelAnchorPoint = labelAnchorPoint;
-
- this._titleLabel.setAnchorPoint(labelAnchorPoint);
+ if(this._titleLabel)
+ this._titleLabel.setAnchorPoint(labelAnchorPoint);
},
- /** The current title that is displayed on the button. */
- getCurrentTitle:function () {
+ /**
+ * The current title that is displayed on the button.
+ * @return {string}
+ */
+ _getCurrentTitle:function () {
return this._currentTitle;
},
/** The current color used to display the title. */
- getCurrentTitleColor:function () {
+ _getCurrentTitleColor:function () {
return this._currentTitleColor;
},
@@ -263,45 +281,51 @@ cc.ControlButton = cc.Control.extend({
},
setOpacity:function (opacity) {
- this._opacity = opacity;
-
+ // XXX fixed me if not correct
+ cc.Control.prototype.setOpacity.call(opacity);
+ /*this._opacity = opacity;
var controlChildren = this.getChildren();
-
for (var i = 0; i < controlChildren.length; i++) {
- if (controlChildren[i] && controlChildren[i].RGBAProtocol) {
- controlChildren[i].setOpacity(opacity);
- }
- }
- for (var itemKey in this._backgroundSpriteDispatchTable) {
- this._backgroundSpriteDispatchTable[itemKey].setOpacity(opacity);
- }
+ var selChild = controlChildren[i];
+ if (selChild && selChild.RGBAProtocol)
+ selChild.setOpacity(opacity);
+ }*/
+ var locTable = this._backgroundSpriteDispatchTable;
+ for (var itemKey in locTable)
+ locTable[itemKey].setOpacity(opacity);
},
setColor:function(color){
cc.Control.prototype.setColor.call(this,color);
- for(var key in this._backgroundSpriteDispatchTable){
- this._backgroundSpriteDispatchTable[key].setColor(color);
- }
+ var locTable = this._backgroundSpriteDispatchTable;
+ for(var key in locTable)
+ locTable[key].setColor(color);
},
getColor:function(){
return this._realColor;
},
+
/** Flag to know if the button is currently pushed. */
- getIsPushed:function () {
- return this._pushed;
+ isPushed:function () {
+ return this._isPushed;
},
/* Define the button margin for Top/Bottom edge */
- getVerticalMargin:function () {
+ _getVerticalMargin:function () {
return this._marginV;
},
/* Define the button margin for Left/Right edge */
- getHorizontalOrigin:function () {
+ _getHorizontalOrigin:function () {
return this._marginH;
},
- //set the margins at once (so we only have to do one call of needsLayout)
+
+ /**
+ * set the margins at once (so we only have to do one call of needsLayout)
+ * @param {Number} marginH
+ * @param {Number} marginV
+ */
setMargins:function (marginH, marginV) {
this._marginV = marginV;
this._marginH = marginH;
@@ -318,17 +342,13 @@ cc.ControlButton = cc.Control.extend({
},
setHighlighted:function (enabled) {
- if (enabled == true) {
- this._state = cc.CONTROL_STATE_HIGHLIGHTED;
- }
- else {
- this._state = cc.CONTROL_STATE_NORMAL;
- }
+ this._state = enabled?cc.CONTROL_STATE_HIGHLIGHTED:cc.CONTROL_STATE_NORMAL;
+
cc.Control.prototype.setHighlighted.call(this, enabled);
var action = this.getActionByTag(cc.CONTROL_ZOOM_ACTION_TAG);
- if (action) {
+ if (action)
this.stopAction(action);
- }
+
this.needsLayout();
if (this._zoomOnTouchDown) {
var scaleValue = (this.isHighlighted() && this.isEnabled() && !this.isSelected()) ? 1.1 : 1.0;
@@ -339,33 +359,29 @@ cc.ControlButton = cc.Control.extend({
},
onTouchBegan:function (touch, event) {
- if (!this.isTouchInside(touch) || !this.isEnabled()|| !this.isVisible()||!this.hasVisibleParents()) {
+ if (!this.isTouchInside(touch) || !this.isEnabled()|| !this.isVisible()||!this.hasVisibleParents())
return false;
- }
- this._pushed = true;
+ this._isPushed = true;
this.setHighlighted(true);
this.sendActionsForControlEvents(cc.CONTROL_EVENT_TOUCH_DOWN);
return true;
},
onTouchMoved:function (touch, event) {
- if (!this._enabled || !this._pushed || this._selected) {
- if (this._highlighted) {
+ if (!this._enabled || !this._isPushed || this._selected) {
+ if (this._highlighted)
this.setHighlighted(false);
- }
return;
}
var isTouchMoveInside = this.isTouchInside(touch);
if (isTouchMoveInside && !this._highlighted) {
- this._state = cc.CONTROL_STATE_HIGHLIGHTED;
this.setHighlighted(true);
this.sendActionsForControlEvents(cc.CONTROL_EVENT_TOUCH_DRAG_ENTER);
} else if (isTouchMoveInside && this._highlighted) {
this.sendActionsForControlEvents(cc.CONTROL_EVENT_TOUCH_DRAG_INSIDE);
} else if (!isTouchMoveInside && this._highlighted) {
- this._state = cc.CONTROL_STATE_NORMAL;
this.setHighlighted(false);
this.sendActionsForControlEvents(cc.CONTROL_EVENT_TOUCH_DRAG_EXIT);
} else if (!isTouchMoveInside && !this._highlighted) {
@@ -373,7 +389,7 @@ cc.ControlButton = cc.Control.extend({
}
},
onTouchEnded:function (touch, event) {
- this._pushed = false;
+ this._isPushed = false;
this.setHighlighted(false);
if (this.isTouchInside(touch)) {
@@ -384,7 +400,7 @@ cc.ControlButton = cc.Control.extend({
},
onTouchCancelled:function (touch, event) {
- this._pushed = false;
+ this._isPushed = false;
this.setHighlighted(false);
this.sendActionsForControlEvents(cc.CONTROL_EVENT_TOUCH_CANCEL);
},
@@ -392,127 +408,110 @@ cc.ControlButton = cc.Control.extend({
/**
* Returns the title used for a state.
*
- * @param state The state that uses the title. Possible values are described in
- * "CCControlState".
- *
- * @return The title for the specified state.
+ * @param {Number} state The state that uses the title. Possible values are described in "CCControlState".
+ * @return {string} The title for the specified state.
*/
getTitleForState:function (state) {
- if (this._titleDispatchTable) {
- if (this._titleDispatchTable[state])
- return this._titleDispatchTable[state];
- return this._titleDispatchTable[cc.CONTROL_STATE_NORMAL];
+ var locTable = this._titleDispatchTable;
+ if (locTable) {
+ if (locTable[state])
+ return locTable[state];
+ return locTable[cc.CONTROL_STATE_NORMAL];
}
return "";
},
/**
- * Sets the title string to use for the specified state.
- * If a property is not specified for a state, the default is to use
- * the CCButtonStateNormal value.
- *
- * @param title The title string to use for the specified state.
- * @param state The state that uses the specified title. The values are described
- * in "CCControlState".
+ *
+ * Sets the title string to use for the specified state.
+ * If a property is not specified for a state, the default is to use the CCButtonStateNormal value.
+ *
+ * @param {string} title The title string to use for the specified state.
+ * @param {Number} state The state that uses the specified title. The values are described in "CCControlState".
*/
setTitleForState:function (title, state) {
- if (title) {
- this._titleDispatchTable[state] = title;
- } else {
- this._titleDispatchTable[state] = "";
- }
+ this._titleDispatchTable[state] = title || "";
// If the current state if equal to the given state we update the layout
- if (this.getState() == state) {
+ if (this.getState() == state)
this.needsLayout();
- }
},
/**
* Returns the title color used for a state.
*
- * @param state The state that uses the specified color. The values are described
- * in "CCControlState".
- *
- * @return The color of the title for the specified state.
+ * @param {Number} state The state that uses the specified color. The values are described in "CCControlState".
+ * @return {cc.Color3B} The color of the title for the specified state.
*/
- getTitleColorForState:function (state) {
- var returnColor = cc.white();
- do {
- var colorObject = this._titleColorDispatchTable[state];
- if (colorObject) {
- returnColor = colorObject;
- break;
- }
- colorObject = this._titleColorDispatchTable[cc.CONTROL_STATE_NORMAL];
- if (colorObject) {
- returnColor = colorObject;
- break;
- }
-
- } while (0);
-
- return returnColor;
+ getTitleColorForState: function (state) {
+ var colorObject = this._titleColorDispatchTable[state];
+ if (colorObject)
+ return colorObject;
+ colorObject = this._titleColorDispatchTable[cc.CONTROL_STATE_NORMAL];
+ if (colorObject)
+ return colorObject;
+ return cc.white();
},
/**
* Sets the color of the title to use for the specified state.
*
- * @param color The color of the title to use for the specified state.
- * @param state The state that uses the specified color. The values are described
- * in "CCControlState".
+ * @param {cc.Color3B} color The color of the title to use for the specified state.
+ * @param {Number} state The state that uses the specified color. The values are described in "CCControlState".
*/
setTitleColorForState:function (color, state) {
//ccColor3B* colorValue=&color;
this._titleColorDispatchTable[state] = color;
// If the current state if equal to the given state we update the layout
- if (this.getState() == state) {
+ if (this.getState() == state)
this.needsLayout();
- }
},
/**
* Returns the title label used for a state.
*
- * @param state The state that uses the title label. Possible values are described
- * in "CCControlState".
+ * @param state The state that uses the title label. Possible values are described in "CCControlState".
+ * @return {cc.Node} the title label used for a state.
*/
getTitleLabelForState:function (state) {
- if (this._titleLabelDispatchTable.hasOwnProperty(state) && this._titleLabelDispatchTable[state]) {
- return this._titleLabelDispatchTable[state];
- }
- return this._titleLabelDispatchTable[cc.CONTROL_STATE_NORMAL];
+ var locTable = this._titleLabelDispatchTable;
+ if (locTable.hasOwnProperty(state) && locTable[state])
+ return locTable[state];
+
+ return locTable[cc.CONTROL_STATE_NORMAL];
},
/**
- * Sets the title label to use for the specified state.
- * If a property is not specified for a state, the default is to use
- * the CCButtonStateNormal value.
+ *
Sets the title label to use for the specified state.
+ * If a property is not specified for a state, the default is to use the CCButtonStateNormal value.
*
- * @param titleLabel The title label to use for the specified state.
- * @param state The state that uses the specified title. The values are described
- * in "CCControlState".
+ * @param {cc.Node} titleLabel The title label to use for the specified state.
+ * @param {Number} state The state that uses the specified title. The values are described in "CCControlState".
*/
setTitleLabelForState:function (titleLabel, state) {
- if (this._titleLabelDispatchTable.hasOwnProperty(state)) {
- var previousLabel = this._titleLabelDispatchTable[state];
- if (previousLabel) {
+ var locTable = this._titleLabelDispatchTable;
+ if (locTable.hasOwnProperty(state)) {
+ var previousLabel = locTable[state];
+ if (previousLabel)
this.removeChild(previousLabel, true);
- }
}
- this._titleLabelDispatchTable[state] = titleLabel;
+ locTable[state] = titleLabel;
titleLabel.setVisible(false);
titleLabel.setAnchorPoint(cc.p(0.5, 0.5));
this.addChild(titleLabel, 1);
// If the current state if equal to the given state we update the layout
- if (this.getState() == state) {
+ if (this.getState() == state)
this.needsLayout();
- }
},
+ /**
+ * Sets the title TTF filename to use for the specified state.
+ * @param {string} fntFile
+ * @param {Number} state
+ */
setTitleTTFForState:function (fntFile, state) {
var title = this.getTitleForState(state);
if (!title)
@@ -520,6 +519,11 @@ cc.ControlButton = cc.Control.extend({
this.setTitleLabelForState(cc.LabelTTF.create(title, fntFile, 12), state);
},
+ /**
+ * return the title TTF filename to use for the specified state.
+ * @param {Number} state
+ * @returns {string}
+ */
getTitleTTFForState:function (state) {
var labelTTF = this.getTitleLabelForState(state);
if ((labelTTF != null) && (labelTTF instanceof cc.LabelTTF)) {
@@ -529,6 +533,10 @@ cc.ControlButton = cc.Control.extend({
}
},
+ /**
+ * @param {Number} size
+ * @param {Number} state
+ */
setTitleTTFSizeForState:function (size, state) {
var labelTTF = this.getTitleLabelForState(state);
if ((labelTTF != null) && (labelTTF instanceof cc.LabelTTF)) {
@@ -536,6 +544,11 @@ cc.ControlButton = cc.Control.extend({
}
},
+ /**
+ * return the font size of LabelTTF to use for the specified state
+ * @param {Number} state
+ * @returns {Number}
+ */
getTitleTTFSizeForState:function (state) {
var labelTTF = this.getTitleLabelForState(state);
if ((labelTTF != null) && (labelTTF instanceof cc.LabelTTF)) {
@@ -545,10 +558,9 @@ cc.ControlButton = cc.Control.extend({
},
/**
- * Sets the font of the label, changes the label to a CCLabelBMFont if neccessary.
- * @param fntFile The name of the font to change to
- * @param state The state that uses the specified fntFile. The values are described
- * in "CCControlState".
+ * Sets the font of the label, changes the label to a CCLabelBMFont if necessary.
+ * @param {string} fntFile The name of the font to change to
+ * @param {Number} state The state that uses the specified fntFile. The values are described in "CCControlState".
*/
setTitleBMFontForState:function (fntFile, state) {
var title = this.getTitleForState(state);
@@ -568,52 +580,50 @@ cc.ControlButton = cc.Control.extend({
/**
* Returns the background sprite used for a state.
*
- * @param state The state that uses the background sprite. Possible values are
- * described in "CCControlState".
+ * @param {Number} state The state that uses the background sprite. Possible values are described in "CCControlState".
*/
getBackgroundSpriteForState:function (state) {
- if (this._backgroundSpriteDispatchTable.hasOwnProperty(state) && this._backgroundSpriteDispatchTable[state]) {
- return this._backgroundSpriteDispatchTable[state];
+ var locTable = this._backgroundSpriteDispatchTable;
+ if (locTable.hasOwnProperty(state) && locTable[state]) {
+ return locTable[state];
}
- return this._backgroundSpriteDispatchTable[cc.CONTROL_STATE_NORMAL];
+ return locTable[cc.CONTROL_STATE_NORMAL];
},
/**
* Sets the background sprite to use for the specified button state.
*
- * @param sprite The background sprite to use for the specified state.
- * @param state The state that uses the specified image. The values are described
- * in "CCControlState".
+ * @param {Scale9Sprite} sprite The background sprite to use for the specified state.
+ * @param {Number} state The state that uses the specified image. The values are described in "CCControlState".
*/
setBackgroundSpriteForState:function (sprite, state) {
- if (this._backgroundSpriteDispatchTable.hasOwnProperty(state)) {
- var previousSprite = this._backgroundSpriteDispatchTable[state];
- if (previousSprite) {
+ var locTable = this._backgroundSpriteDispatchTable;
+ if (locTable.hasOwnProperty(state)) {
+ var previousSprite = locTable[state];
+ if (previousSprite)
this.removeChild(previousSprite, true);
- }
}
- this._backgroundSpriteDispatchTable[state] = sprite;
+ locTable[state] = sprite;
sprite.setVisible(false);
sprite.setAnchorPoint(cc.p(0.5, 0.5));
this.addChild(sprite);
- if (this._preferredSize.width !== 0 || this._preferredSize.height !== 0) {
- sprite.setPreferredSize(this._preferredSize);
+ var locPreferredSize = this._preferredSize;
+ if (locPreferredSize.width !== 0 || locPreferredSize.height !== 0) {
+ sprite.setPreferredSize(locPreferredSize);
}
// If the current state if equal to the given state we update the layout
- if (this._state === state) {
+ if (this._state === state)
this.needsLayout();
- }
},
/**
* Sets the background spriteFrame to use for the specified button state.
*
- * @param spriteFrame The background spriteFrame to use for the specified state.
- * @param state The state that uses the specified image. The values are described
- * in "CCControlState".
+ * @param {SpriteFrame} spriteFrame The background spriteFrame to use for the specified state.
+ * @param {Number} state The state that uses the specified image. The values are described in "CCControlState".
*/
setBackgroundSpriteFrameForState:function (spriteFrame, state) {
var sprite = cc.Scale9Sprite.createWithSpriteFrame(spriteFrame);
diff --git a/extensions/GUI/CCControlExtension/CCControlColourPicker.js b/extensions/GUI/CCControlExtension/CCControlColourPicker.js
index d6cf2706f7..a456f5eb71 100644
--- a/extensions/GUI/CCControlExtension/CCControlColourPicker.js
+++ b/extensions/GUI/CCControlExtension/CCControlColourPicker.js
@@ -1,4 +1,4 @@
-/*
+/**
*
* Copyright (c) 2010-2012 cocos2d-x.org
*
diff --git a/extensions/GUI/CCControlExtension/CCControlHuePicker.js b/extensions/GUI/CCControlExtension/CCControlHuePicker.js
index e9a34159c8..10952b4370 100644
--- a/extensions/GUI/CCControlExtension/CCControlHuePicker.js
+++ b/extensions/GUI/CCControlExtension/CCControlHuePicker.js
@@ -1,4 +1,4 @@
-/*
+/**
*
* Copyright (c) 2010-2012 cocos2d-x.org
*
diff --git a/extensions/GUI/CCControlExtension/CCControlPotentiometer.js b/extensions/GUI/CCControlExtension/CCControlPotentiometer.js
index 693cd9646d..a7245ef9ec 100644
--- a/extensions/GUI/CCControlExtension/CCControlPotentiometer.js
+++ b/extensions/GUI/CCControlExtension/CCControlPotentiometer.js
@@ -1,4 +1,4 @@
-/*
+/**
* Copyright (c) 2012 cocos2d-x.org
* http://www.cocos2d-x.org
*
diff --git a/extensions/GUI/CCControlExtension/CCControlSaturationBrightnessPicker.js b/extensions/GUI/CCControlExtension/CCControlSaturationBrightnessPicker.js
index 66e985338a..7957a55e83 100644
--- a/extensions/GUI/CCControlExtension/CCControlSaturationBrightnessPicker.js
+++ b/extensions/GUI/CCControlExtension/CCControlSaturationBrightnessPicker.js
@@ -1,4 +1,4 @@
-/*
+/**
*
* Copyright (c) 2010-2012 cocos2d-x.org
*
diff --git a/extensions/GUI/CCControlExtension/CCControlSlider.js b/extensions/GUI/CCControlExtension/CCControlSlider.js
index 2b3e9bb107..bf93540ff3 100644
--- a/extensions/GUI/CCControlExtension/CCControlSlider.js
+++ b/extensions/GUI/CCControlExtension/CCControlSlider.js
@@ -1,4 +1,4 @@
-/*
+/**
*
* Copyright (c) 2010-2012 cocos2d-x.org
*
diff --git a/extensions/GUI/CCControlExtension/CCControlStepper.js b/extensions/GUI/CCControlExtension/CCControlStepper.js
index 4a16c0eae7..e0985fe77b 100644
--- a/extensions/GUI/CCControlExtension/CCControlStepper.js
+++ b/extensions/GUI/CCControlExtension/CCControlStepper.js
@@ -1,4 +1,4 @@
-/*
+/**
* Copyright (c) 2012 cocos2d-x.org
* http://www.cocos2d-x.org
*
@@ -55,6 +55,7 @@ cc.ControlStepper = cc.Control.extend({
_touchedPart:cc.CONTROL_STEPPER_PARTNONE,
_autorepeatCount:0,
ctor:function () {
+ cc.Control.prototype.ctor.call(this);
this._minusSprite = null;
this._plusSprite = null;
this._minusLabel = null;
diff --git a/extensions/GUI/CCControlExtension/CCControlSwitch.js b/extensions/GUI/CCControlExtension/CCControlSwitch.js
index d551196e1e..292a4a93c2 100644
--- a/extensions/GUI/CCControlExtension/CCControlSwitch.js
+++ b/extensions/GUI/CCControlExtension/CCControlSwitch.js
@@ -1,4 +1,4 @@
-/*
+/**
*
* Copyright (c) 2010-2012 cocos2d-x.org
*
diff --git a/extensions/GUI/CCControlExtension/CCControlUtils.js b/extensions/GUI/CCControlExtension/CCControlUtils.js
index 3acd0e3483..c31fdf1db6 100644
--- a/extensions/GUI/CCControlExtension/CCControlUtils.js
+++ b/extensions/GUI/CCControlExtension/CCControlUtils.js
@@ -153,7 +153,6 @@ cc.ControlUtils.RGBfromHSV = function(hsvValue){
out.g = p;
out.b = hsvValue.v;
break;
- case 5:
default:
out.r = hsvValue.v;
out.g = p;
diff --git a/extensions/GUI/CCControlExtension/CCScale9Sprite.js b/extensions/GUI/CCControlExtension/CCScale9Sprite.js
index 37d767ad11..352fc6d010 100644
--- a/extensions/GUI/CCControlExtension/CCScale9Sprite.js
+++ b/extensions/GUI/CCControlExtension/CCScale9Sprite.js
@@ -87,7 +87,6 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
if (locInsetLeft === 0 && locInsetTop === 0 && locInsetRight === 0 && locInsetBottom === 0) {
insets = cc.RectZero();
} else {
-
insets = this._spriteFrameRotated ? cc.RectMake(locInsetBottom, locInsetLeft,
locSpriteRect.width - locInsetRight - locInsetLeft,
locSpriteRect.height - locInsetTop - locInsetBottom) :
@@ -439,9 +438,8 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
this._opacityModifyRGB = value;
var scaleChildren = this._scale9Image.getChildren();
if (scaleChildren) {
- for (var i = 0; i < scaleChildren.length; i++) {
- scaleChildren[i].setOpacityModifyRGB(this._opacityModifyRGB);
- }
+ for (var i = 0, len = scaleChildren.length; i < len; i++)
+ scaleChildren[i].setOpacityModifyRGB(value);
}
},
@@ -468,12 +466,11 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
this._capInsets = capInsets;
var selTexture = locScale9Image.getTexture();
- var rectZero = cc.RectZero();
// If there is no given rect
- if (cc.rectEqualToRect(rect, rectZero)) {
+ if (cc._rectEqualToZero(rect)) {
// Get the texture size as original
var textureSize = selTexture.getContentSize();
- rect = cc.RectMake(0, 0, textureSize.width, textureSize.height);
+ rect = cc.rect(0, 0, textureSize.width, textureSize.height);
}
// Set the given rect's size as original size
@@ -498,7 +495,7 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
var h = rectSize.height;
// If there is no specified center region
- if (cc.rectEqualToRect(locCapInsetsInternal, rectZero)) {
+ if (cc._rectEqualToZero(locCapInsetsInternal)) {
// CCLog("... cap insets not specified : using default cap insets ...");
locCapInsetsInternal.x = w / 3;
locCapInsetsInternal.y = h / 3;
@@ -520,15 +517,15 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
var y = 0.0;
// top left
- var lefttopbounds = cc.RectMake(x, y, left_w, top_h);
+ var lefttopbounds = cc.rect(x, y, left_w, top_h);
// top center
x += left_w;
- var centertopbounds = cc.RectMake(x, y, center_w, top_h);
+ var centertopbounds = cc.rect(x, y, center_w, top_h);
// top right
x += center_w;
- var righttopbounds = cc.RectMake(x, y, right_w, top_h);
+ var righttopbounds = cc.rect(x, y, right_w, top_h);
// ... center row
x = 0.0;
@@ -536,15 +533,15 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
// center left
y += top_h;
- var leftcenterbounds = cc.RectMake(x, y, left_w, center_h);
+ var leftcenterbounds = cc.rect(x, y, left_w, center_h);
// center center
x += left_w;
- var centerbounds = cc.RectMake(x, y, center_w, center_h);
+ var centerbounds = cc.rect(x, y, center_w, center_h);
// center right
x += center_w;
- var rightcenterbounds = cc.RectMake(x, y, right_w, center_h);
+ var rightcenterbounds = cc.rect(x, y, right_w, center_h);
// ... bottom row
x = 0.0;
@@ -553,30 +550,30 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
y += center_h;
// bottom left
- var leftbottombounds = cc.RectMake(x, y, left_w, bottom_h);
+ var leftbottombounds = cc.rect(x, y, left_w, bottom_h);
// bottom center
x += left_w;
- var centerbottombounds = cc.RectMake(x, y, center_w, bottom_h);
+ var centerbottombounds = cc.rect(x, y, center_w, bottom_h);
// bottom right
x += center_w;
- var rightbottombounds = cc.RectMake(x, y, right_w, bottom_h);
+ var rightbottombounds = cc.rect(x, y, right_w, bottom_h);
var t = cc.AffineTransformMakeIdentity();
if (!rotated) {
// CCLog("!rotated");
t = cc.AffineTransformTranslate(t, rect.x, rect.y);
- centerbounds = cc.RectApplyAffineTransform(centerbounds, t);
- rightbottombounds = cc.RectApplyAffineTransform(rightbottombounds, t);
- leftbottombounds = cc.RectApplyAffineTransform(leftbottombounds, t);
- righttopbounds = cc.RectApplyAffineTransform(righttopbounds, t);
- lefttopbounds = cc.RectApplyAffineTransform(lefttopbounds, t);
- rightcenterbounds = cc.RectApplyAffineTransform(rightcenterbounds, t);
- leftcenterbounds = cc.RectApplyAffineTransform(leftcenterbounds, t);
- centerbottombounds = cc.RectApplyAffineTransform(centerbottombounds, t);
- centertopbounds = cc.RectApplyAffineTransform(centertopbounds, t);
+ cc._RectApplyAffineTransformIn(centerbounds, t);
+ cc._RectApplyAffineTransformIn(rightbottombounds, t);
+ cc._RectApplyAffineTransformIn(leftbottombounds, t);
+ cc._RectApplyAffineTransformIn(righttopbounds, t);
+ cc._RectApplyAffineTransformIn(lefttopbounds, t);
+ cc._RectApplyAffineTransformIn(rightcenterbounds, t);
+ cc._RectApplyAffineTransformIn(leftcenterbounds, t);
+ cc._RectApplyAffineTransformIn(centerbottombounds, t);
+ cc._RectApplyAffineTransformIn(centertopbounds, t);
// Centre
this._centre = new cc.Sprite();
diff --git a/extensions/GUI/CCScrollView/CCScrollView.js b/extensions/GUI/CCScrollView/CCScrollView.js
index 04ef5034c4..2d2180a775 100644
--- a/extensions/GUI/CCScrollView/CCScrollView.js
+++ b/extensions/GUI/CCScrollView/CCScrollView.js
@@ -38,7 +38,8 @@ var INSET_RATIO = 0.2;
var MOVE_INCH = 7.0/160.0;
cc.convertDistanceFromPointToInch = function(pointDis){
- var factor = (cc.EGLView.getInstance().getScaleX() + cc.EGLView.getInstance().getScaleY())/2;
+ var eglViewer = cc.EGLView.getInstance();
+ var factor = (eglViewer.getScaleX() + eglViewer.getScaleY())/2;
return (pointDis * factor) / 160; // CCDevice::getDPI() default value
};
@@ -104,7 +105,7 @@ cc.ScrollView = cc.Layer.extend({
},
/**
- * Returns a scroll view object
+ * initialized whether success or fail
* @param {cc.Size} size
* @param {cc.Node} container
* @return {Boolean}
@@ -146,24 +147,25 @@ cc.ScrollView = cc.Layer.extend({
* @param {cc.Point} offset new offset
* @param {Number} [animated=] If YES, the view scrolls to the new offset
*/
- setContentOffset:function (offset, animated) {
+ setContentOffset: function (offset, animated) {
if (animated) { //animate scrolling
this.setContentOffsetInDuration(offset, BOUNCE_DURATION);
- } else { //set the container position directly
- if (!this._bounceable) {
- var minOffset = this.minContainerOffset();
- var maxOffset = this.maxContainerOffset();
+ return;
+ }
+ if (!this._bounceable) {
+ var minOffset = this.minContainerOffset();
+ var maxOffset = this.maxContainerOffset();
- offset.x = Math.max(minOffset.x, Math.min(maxOffset.x, offset.x));
- offset.y = Math.max(minOffset.y, Math.min(maxOffset.y, offset.y));
- }
+ offset.x = Math.max(minOffset.x, Math.min(maxOffset.x, offset.x));
+ offset.y = Math.max(minOffset.y, Math.min(maxOffset.y, offset.y));
+ }
- this._container.setPosition(offset);
- var locDelegate = this._delegate;
- if (locDelegate != null && locDelegate.scrollViewDidScroll) {
- locDelegate.scrollViewDidScroll(this);
- }
+ this._container.setPosition(offset);
+ var locDelegate = this._delegate;
+ if (locDelegate != null && locDelegate.scrollViewDidScroll) {
+ locDelegate.scrollViewDidScroll(this);
}
+
},
getContentOffset:function () {
@@ -188,36 +190,34 @@ cc.ScrollView = cc.Layer.extend({
* Sets a new scale and does that for a predefined duration.
*
* @param {Number} scale a new scale vale
- * @param {Boolean} animated if YES, scaling is animated
+ * @param {Boolean} [animated=null] if YES, scaling is animated
*/
- setZoomScale:function (scale, animated) {
- if (arguments.length === 1) {
- var locContainer = this._container;
- if (locContainer.getScale() != scale) {
- var oldCenter, newCenter;
- var center;
-
- if (this._touchLength == 0.0) {
- center = cc.p(this._viewSize.width * 0.5, this._viewSize.height * 0.5);
- center = this.convertToWorldSpace(center);
- } else
- center = this._touchPoint;
-
- oldCenter = locContainer.convertToNodeSpace(center);
- locContainer.setScale(Math.max(this._minScale, Math.min(this._maxScale, scale)));
- newCenter = locContainer.convertToWorldSpace(oldCenter);
-
- var offset = cc.pSub(center, newCenter);
- if (this._delegate != null) {
- this._delegate.scrollViewDidZoom(this);
- }
- this.setContentOffset(cc.pAdd(locContainer.getPosition(), offset));
- }
- } else if (arguments.length === 2) {
- if (animated)
- this.setZoomScaleInDuration(scale, BOUNCE_DURATION);
- else
- this.setZoomScale(scale);
+ setZoomScale: function (scale, animated) {
+ if (animated) {
+ this.setZoomScaleInDuration(scale, BOUNCE_DURATION);
+ return;
+ }
+
+ var locContainer = this._container;
+ if (locContainer.getScale() != scale) {
+ var oldCenter, newCenter;
+ var center;
+
+ if (this._touchLength == 0.0) {
+ var locViewSize = this._viewSize;
+ center = cc.p(locViewSize.width * 0.5, locViewSize.height * 0.5);
+ center = this.convertToWorldSpace(center);
+ } else
+ center = this._touchPoint;
+
+ oldCenter = locContainer.convertToNodeSpace(center);
+ locContainer.setScale(Math.max(this._minScale, Math.min(this._maxScale, scale)));
+ newCenter = locContainer.convertToWorldSpace(oldCenter);
+
+ var offset = cc.pSub(center, newCenter);
+ if (this._delegate != null)
+ this._delegate.scrollViewDidZoom(this);
+ this.setContentOffset(cc.pAdd(locContainer.getPosition(), offset));
}
},
@@ -233,8 +233,9 @@ cc.ScrollView = cc.Layer.extend({
*/
setZoomScaleInDuration:function (s, dt) {
if (dt > 0) {
- if (this._container.getScale() != s) {
- var scaleAction = cc.ActionTween.create(dt, "zoomScale", this._container.getScale(), s);
+ var locScale = this._container.getScale();
+ if (locScale != s) {
+ var scaleAction = cc.ActionTween.create(dt, "zoomScale", locScale, s);
this.runAction(scaleAction);
}
} else {
@@ -244,15 +245,18 @@ cc.ScrollView = cc.Layer.extend({
/**
* 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 () {
- var locContentSize = this._container.getContentSize();
- return cc.p(this._viewSize.width - locContentSize.width * this._container.getScaleX(),
- this._viewSize.height - locContentSize.height * this._container.getScaleY());
+ var locContainer = this._container;
+ var locContentSize = locContainer.getContentSize(), locViewSize = this._viewSize;
+ return cc.p(locViewSize.width - locContentSize.width * locContainer.getScaleX(),
+ locViewSize.height - locContentSize.height * locContainer.getScaleY());
},
/**
* 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 () {
return cc.p(0.0, 0.0);
@@ -289,7 +293,7 @@ cc.ScrollView = cc.Layer.extend({
*/
resume:function (sender) {
var selChildren = this._container.getChildren();
- for (var i = 0; i < selChildren.length; i++) {
+ for (var i = 0, len = selChildren.length; i < len; i++) {
selChildren[i].resumeSchedulerAndActions();
}
@@ -338,10 +342,10 @@ cc.ScrollView = cc.Layer.extend({
this.removeAllChildren(true);
this._container = container;
- this._container.ignoreAnchorPointForPosition(false);
- this._container.setAnchorPoint(cc.p(0.0, 0.0));
+ container.ignoreAnchorPointForPosition(false);
+ container.setAnchorPoint(cc.p(0.0, 0.0));
- this.addChild(this._container);
+ this.addChild(container);
this.setViewSize(this._viewSize);
},
@@ -414,10 +418,10 @@ cc.ScrollView = cc.Layer.extend({
var newPoint = this.convertTouchToNodeSpace(touch);
var moveDistance = cc.pSub(newPoint, this._touchPoint);
- var dis = 0.0;
- if (this._direction === cc.SCROLLVIEW_DIRECTION_VERTICAL)
+ var dis = 0.0, locDirection = this._direction;
+ if (locDirection === cc.SCROLLVIEW_DIRECTION_VERTICAL)
dis = moveDistance.y;
- else if (this._direction === cc.SCROLLVIEW_DIRECTION_HORIZONTAL)
+ else if (locDirection === cc.SCROLLVIEW_DIRECTION_HORIZONTAL)
dis = moveDistance.x;
else
dis = Math.sqrt(moveDistance.x * moveDistance.x + moveDistance.y * moveDistance.y);
@@ -436,7 +440,7 @@ cc.ScrollView = cc.Layer.extend({
this._touchMoved = true;
if (cc.rectContainsPoint(frame, this.convertToWorldSpace(newPoint))) {
- switch (this._direction) {
+ switch (locDirection) {
case cc.SCROLLVIEW_DIRECTION_VERTICAL:
moveDistance.x = 0.0;
break;
@@ -680,7 +684,8 @@ cc.ScrollView = cc.Layer.extend({
newX = Math.max(newX, minInset.x);
var newY = Math.min(this._container.getPosition().y, maxInset.y);
newY = Math.max(newY, minInset.y);*/
- oldPosition = this._container.getPosition();
+ oldPosition.x = this._container.getPositionX();
+ oldPosition.y = this._container.getPositionY();
var newX = oldPosition.x;
var newY = oldPosition.y;
@@ -767,7 +772,6 @@ cc.ScrollView = cc.Layer.extend({
//clip
EGLViewer.setScissorInPoints(frame.x, frame.y, frame.width, frame.height);
}
-
}
}
},
diff --git a/extensions/GUI/CCScrollView/CCSorting.js b/extensions/GUI/CCScrollView/CCSorting.js
index ede6e0811c..205cfa8fe0 100644
--- a/extensions/GUI/CCScrollView/CCSorting.js
+++ b/extensions/GUI/CCScrollView/CCSorting.js
@@ -52,7 +52,7 @@ var _compareObject = function (val1, val2) {
};
cc.ArrayForObjectSorting = cc.Class.extend({
- _saveObjectArr:[],
+ _saveObjectArr:null,
ctor:function () {
this._saveObjectArr = [];
@@ -128,9 +128,8 @@ cc.ArrayForObjectSorting = cc.Class.extend({
var idx = this.indexOfSortedObject(foundObj);
if (idx < this.count() && idx != cc.INVALID_INDEX) {
foundObj = this.objectAtIndex(idx);
- if (foundObj.getObjectID() != tag) {
+ if (foundObj.getObjectID() != tag)
foundObj = null;
- }
}
return foundObj;
},
@@ -167,8 +166,9 @@ cc.ArrayForObjectSorting = cc.Class.extend({
var uPrevObjectID = 0;
var uOfSortObjectID = idxObj.getObjectID();
- for (var i = 0; i < this._saveObjectArr.length; i++) {
- var pSortableObj = this._saveObjectArr[i];
+ var locObjectArr = this._saveObjectArr;
+ for (var i = 0; i < locObjectArr.length; i++) {
+ var pSortableObj = locObjectArr[i];
var curObjectID = pSortableObj.getObjectID();
if ((uOfSortObjectID == curObjectID) ||
(uOfSortObjectID >= uPrevObjectID && uOfSortObjectID < curObjectID)) {
@@ -189,9 +189,10 @@ cc.ArrayForObjectSorting = cc.Class.extend({
},
lastObject:function () {
- if (this._saveObjectArr.length == 0)
+ var locObjectArr = this._saveObjectArr;
+ if (locObjectArr.length == 0)
return null;
- return this._saveObjectArr[this._saveObjectArr.length - 1];
+ return locObjectArr[locObjectArr.length - 1];
},
objectAtIndex:function (idx) {
diff --git a/extensions/GUI/CCScrollView/CCTableView.js b/extensions/GUI/CCScrollView/CCTableView.js
index d86de079e7..67003ebe76 100644
--- a/extensions/GUI/CCScrollView/CCTableView.js
+++ b/extensions/GUI/CCScrollView/CCTableView.js
@@ -64,10 +64,42 @@ cc.TableViewDelegate = cc.ScrollViewDelegate.extend({
/**
* Delegate to respond touch event
*
- * @param table table contains the given cell
- * @param cell cell that is touched
+ * @param {cc.TableView} table table contains the given cell
+ * @param {cc.TableViewCell} cell cell that is touched
*/
tableCellTouched:function (table, cell) {
+ },
+
+ /**
+ * Delegate to respond a table cell press event.
+ *
+ * @param {cc.TableView} table table contains the given cell
+ * @param {cc.TableViewCell} cell cell that is pressed
+ */
+ tableCellHighlight:function(table, cell){
+ },
+
+ /**
+ * Delegate to respond a table cell release event
+ *
+ * @param {cc.TableView} table table contains the given cell
+ * @param {cc.TableViewCell} cell cell that is pressed
+ */
+ tableCellUnhighlight:function(table, cell){
+
+ },
+
+ /**
+ *
+ * Delegate called when the cell is about to be recycled. Immediately
+ * after this call the cell will be removed from the scene graph and
+ * recycled.
+ *
+ * @param table table contains the given cell
+ * @param cell cell that is pressed
+ */
+ tableCellWillRecycle:function(table, cell){
+
}
});
@@ -75,30 +107,39 @@ cc.TableViewDelegate = cc.ScrollViewDelegate.extend({
* Data source that governs table backend data.
*/
cc.TableViewDataSource = cc.Class.extend({
+ /**
+ * cell size for a given index
+ * @param {cc.TableView} table table to hold the instances of Class
+ * @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){
+ return this.cellSizeForTable(table);
+ },
/**
* cell height for a given table.
*
- * @param table table to hold the instances of Class
- * @return cell size
+ * @param {cc.TableView} table table to hold the instances of Class
+ * @return {cc.Size} cell size
*/
cellSizeForTable:function (table) {
- return 0;
+ return cc.SIZE_ZERO;
},
/**
* a cell instance at a given index
- *
+ * @param {cc.TableView} table table to hold the instances of Class
* @param idx index to search for a cell
- * @return cell found at idx
+ * @return {cc.TableView} cell found at idx
*/
tableCellAtIndex:function (table, idx) {
- return 0;
+ return null;
},
/**
* Returns number of cells in a given table view.
- *
- * @return number of cells
+ * @param {cc.TableView} table table to hold the instances of Class
+ * @return {Number} number of cells
*/
numberOfCellsInTableView:function (table) {
return 0;
@@ -140,11 +181,12 @@ cc.TableView = cc.ScrollView.extend({
},
_indexFromOffset:function (offset) {
- var maxIdx = this._dataSource.numberOfCellsInTableView(this) - 1;
+ var locDataSource = this._dataSource;
+ var maxIdx = locDataSource.numberOfCellsInTableView(this) - 1;
var offset1 = new cc.Point(offset.x, offset.y);
- var cellSize = this._dataSource.cellSizeForTable(this);
+ var cellSize = locDataSource.cellSizeForTable(this);
if (this._vOrdering == cc.TABLEVIEW_FILL_TOPDOWN) {
offset1.y = this.getContainer().getContentSize().height - offset.y - cellSize.height;
}
@@ -377,23 +419,21 @@ cc.TableView = cc.ScrollView.extend({
*/
reloadData:function () {
this._oldDirection = cc.SCROLLVIEW_DIRECTION_NONE;
- var locCellsUsed = this._cellsUsed;
+ var locCellsUsed = this._cellsUsed, locCellsFreed = this._cellsFreed, locContainer = this.getContainer();
for (var i = 0; i < locCellsUsed.count(); i++) {
var cell = locCellsUsed.objectAtIndex(i);
- this._cellsFreed.addObject(cell);
+ locCellsFreed.addObject(cell);
cell.reset();
- if (cell.getParent() == this.getContainer()) {
- this.getContainer().removeChild(cell, true);
- }
+ if (cell.getParent() == locContainer)
+ locContainer.removeChild(cell, true);
}
this._indices = new cc.Set();
this._cellsUsed = new cc.ArrayForObjectSorting();
this._updateContentSize();
- if (this._dataSource.numberOfCellsInTableView(this) > 0) {
+ if (this._dataSource.numberOfCellsInTableView(this) > 0)
this.scrollViewDidScroll(this);
- }
},
/**
@@ -479,8 +519,9 @@ cc.TableView = cc.ScrollView.extend({
}
}
+ var locIndices = this._indices;
for (var i = startIdx; i <= endIdx; i++) {
- if (this._indices.containsObject(i))
+ if (locIndices.containsObject(i))
continue;
this.updateCellAtIndex(i);
}
@@ -502,9 +543,8 @@ cc.TableView = cc.ScrollView.extend({
var index = 0 | this._indexFromOffset(point);
var cell = this._cellWithIndex(index);
- if (cell) {
+ if (cell)
this._tableViewDelegate.tableCellTouched(this, cell);
- }
}
cc.ScrollView.prototype.onTouchEnded.call(this, touch, event);
}
From a1f75f0ff577ea8a539a6f532f63c4d5be04aed4 Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Tue, 27 Aug 2013 11:38:45 +0800
Subject: [PATCH 063/141] fixed #2723: Function prototype have not method of
bind in iphone safari.
---
cocos2d/platform/CCClass.js | 10 ++++++++++
1 file changed, 10 insertions(+)
diff --git a/cocos2d/platform/CCClass.js b/cocos2d/platform/CCClass.js
index 6f96df7edb..cfe9295024 100644
--- a/cocos2d/platform/CCClass.js
+++ b/cocos2d/platform/CCClass.js
@@ -199,6 +199,15 @@ ClassManager.getNewID=function(){
};
return Class;
};
+
+ Function.prototype.bind = Function.prototype.bind || function (bind) {
+ var self = this;
+ return function () {
+ var args = Array.prototype.slice.call(arguments);
+ return self.apply(bind || null, args);
+ };
+ };
+
})();
//
@@ -259,3 +268,4 @@ cc.concatObjectProperties = function(dstObject, srcObject){
}
return dstObject;
};
+
From 27f140a13bcd2c4920b3491ea400f51a553b2769 Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Tue, 27 Aug 2013 11:39:52 +0800
Subject: [PATCH 064/141] fixed #2723: Append a div child to body bottom,and
tag to it.
---
cocos2d/platform/CCApplication.js | 12 +++++++++++-
1 file changed, 11 insertions(+), 1 deletion(-)
diff --git a/cocos2d/platform/CCApplication.js b/cocos2d/platform/CCApplication.js
index 6fbc4adb15..5ccf92c4bb 100644
--- a/cocos2d/platform/CCApplication.js
+++ b/cocos2d/platform/CCApplication.js
@@ -235,8 +235,10 @@ cc.setup = function (el, width, height) {
}
}, true);
*/
- if(cc.Browser.isMobile)
+ if(cc.Browser.isMobile){
cc._addUserSelectStatus();
+ cc._addBottomTag();
+ }
var hidden, visibilityChange;
if (typeof document.hidden !== "undefined") {
@@ -276,6 +278,14 @@ cc._addUserSelectStatus = function(){
+"-webkit-tap-highlight-color:rgba(0,0,0,0);}";
};
+cc._addBottomTag = function () {
+ var bottom = document.createElement("div");
+ bottom.id = "bottom";
+ bottom.style.border = bottom.style.margin = bottom.style.padding = bottom.style.height = bottom.style.lineHeight = bottom.style.fontSize = "0px";
+ document.body.appendChild(bottom);
+ window.location.href="#bottom";
+};
+
cc._isContextMenuEnable = false;
/**
* enable/disable contextMenu for Canvas
From 2bf91e529c4cb84fd30764c3b203578ec7ed69d4 Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Tue, 27 Aug 2013 11:41:07 +0800
Subject: [PATCH 065/141] fixed #2723: Hide url address bar for mobile
browser,it can work in iphone safari and android default browser .
---
cocos2d/platform/CCEGLView.js | 43 +++++++++++++++++++++++++++--------
1 file changed, 34 insertions(+), 9 deletions(-)
diff --git a/cocos2d/platform/CCEGLView.js b/cocos2d/platform/CCEGLView.js
index eb3d974ef3..c551ced119 100644
--- a/cocos2d/platform/CCEGLView.js
+++ b/cocos2d/platform/CCEGLView.js
@@ -88,29 +88,50 @@ cc.EGLView = cc.Class.extend(/** @lends cc.EGLView# */{
ctor:function () {
this._ele = (cc.container.parentNode === document.body) ? document.documentElement : cc.container.parentNode;
this._viewName = "Cocos2dHTML5";
- this._screenSize = cc.size(this._ele.clientWidth, this._ele.clientHeight);
+
this._designResolutionSize = cc.SizeZero();
this._viewPortRect = cc.RectZero();
this._delegate = cc.Director.getInstance().getTouchDispatcher();
this._contentTranslateLeftTop = {left:0, top:0};
+ this._screenSize = cc.SizeZero();
this._hDC = cc.canvas;
this._hRC = cc.renderContext;
+ this._initScreenSize();
},
/**
* init
*/
initialize:function () {
+ this._scrollToBottom();
this._initialize = true;
- this._adjustSize();
-
var adjustSize = this._adjustSize.bind(this);
window.addEventListener('resize', adjustSize, false);
+ if(cc.Browser.isMobile){
+ setTimeout(adjustSize,300);
+ }else{
+ this._adjustSize();
+ }
+ },
+
+ _scrollToBottom:function(){
+ if(cc.Browser.isMobile){
+ cc.canvas.height = this._ele.clientHeight+500;
+ window.location.href="#bottom";
+ }
},
+ _initScreenSize:function(){
+ this._screenSize.width = this._ele.clientWidth;
+ this._screenSize.height = this._ele.clientHeight;
+ if(navigator.userAgent.match(/iPhone/i)){
+ this._screenSize.height +=(this._screenSize.width/320)*60;
+ }
+ },
_adjustSize:function () {
- this._screenSize = cc.size(this._ele.clientWidth, this._ele.clientHeight);
+ this._scrollToBottom();
+ this._initScreenSize();
cc.canvas.width = this._screenSize.width;
cc.canvas.height = this._screenSize.height;
@@ -269,19 +290,23 @@ cc.EGLView = cc.Class.extend(/** @lends cc.EGLView# */{
setDesignResolutionSize:function (width, height, resolutionPolicy) {
cc.Assert(resolutionPolicy !== cc.RESOLUTION_POLICY.UNKNOWN, "should set resolutionPolicy");
- if (!this._initialize) {
- this.initialize();
- }
-
if (width == 0 || height == 0)
return;
- if ((width != null) && (height != null))
+ if ((width != null) && (height != null)){
this._designResolutionSize = cc.size(width, height);
+ }
if (resolutionPolicy != null)
this._resolutionPolicy = resolutionPolicy;
+ if (!this._initialize) {
+ this.initialize();
+ return;
+ }
+
+
+
this._scaleX = this._screenSize.width / this._designResolutionSize.width;
this._scaleY = this._screenSize.height / this._designResolutionSize.height;
From ed7dc5257607ce7e749b9213f236a5c15d2338a0 Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Tue, 27 Aug 2013 15:45:14 +0800
Subject: [PATCH 066/141] fixed #2725: Implement unloadPlist function of
cc.SAXParser
---
cocos2d/platform/CCSAXParser.js | 9 +++++++++
1 file changed, 9 insertions(+)
diff --git a/cocos2d/platform/CCSAXParser.js b/cocos2d/platform/CCSAXParser.js
index 9654aef41e..58f729bd32 100644
--- a/cocos2d/platform/CCSAXParser.js
+++ b/cocos2d/platform/CCSAXParser.js
@@ -200,6 +200,15 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{
cc.Assert("cocos2d:Your browser does not support XMLHTTP.");
},
+ /**
+ * Unload the preloaded plist from xmlList
+ * @param {String} filePath
+ */
+ unloadPlist:function(filePath){
+ if (this._xmlDict.hasOwnProperty(filePath))
+ delete this._xmlDict[filePath];
+ },
+
/**
* get filename from filepath
* @param {String} filePath
From b6370ebdaf5cbbc0342dc664b8002feadad41ada Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Tue, 27 Aug 2013 15:53:08 +0800
Subject: [PATCH 067/141] issue #1088: add onResLoadingErr for preload file
---
cocos2d/platform/CCFileUtils.js | 69 ++++++++++++++++-----------------
1 file changed, 33 insertions(+), 36 deletions(-)
diff --git a/cocos2d/platform/CCFileUtils.js b/cocos2d/platform/CCFileUtils.js
index ad90b6d610..4d1ba82d65 100644
--- a/cocos2d/platform/CCFileUtils.js
+++ b/cocos2d/platform/CCFileUtils.js
@@ -192,6 +192,8 @@ cc.FileUtils = cc.Class.extend({
var fileContents = cc._convertResponseBodyToText(xhr["responseBody"]);
if (fileContents)
selfPointer._fileDataCache[fileUrl] = selfPointer._stringConvertToArray(fileContents);
+ } else {
+ cc.Loader.getInstance().onResLoadingErr(fileUrl);
}
cc.Loader.getInstance().onResLoaded();
}
@@ -199,11 +201,17 @@ cc.FileUtils = cc.Class.extend({
} else {
if (xhr.overrideMimeType)
xhr.overrideMimeType("text\/plain; charset=x-user-defined");
- xhr.onload = function (e) {
- var arrayStr = xhr.responseText;
- if (arrayStr) {
+
+ xhr.onreadystatechange = function (event) {
+ if (xhr.readyState == 4) {
+ if (xhr.status == 200) {
+ var fileContents = xhr.responseText;
+ if (fileContents)
+ selfPointer._fileDataCache[fileUrl] = selfPointer._stringConvertToArray(fileContents);
+ } else {
+ cc.Loader.getInstance().onResLoadingErr(fileUrl);
+ }
cc.Loader.getInstance().onResLoaded();
- selfPointer._fileDataCache[fileUrl] = selfPointer._stringConvertToArray(arrayStr);
}
};
}
@@ -263,55 +271,44 @@ cc.FileUtils = cc.Class.extend({
if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
// IE-specific logic here
xhr.setRequestHeader("Accept-Charset", "utf-8");
- xhr.onreadystatechange = function (event) {
- if (xhr.readyState == 4) {
- if (xhr.status == 200) {
- var fileContents = xhr.responseText;
- if (fileContents)
- selfPointer._textFileCache[fileUrl] = fileContents;
- }
- cc.Loader.getInstance().onResLoaded();
- }
- };
} else {
if (xhr.overrideMimeType)
xhr.overrideMimeType("text\/plain; charset=utf-8");
- xhr.onload = function (e) {
- if (xhr.responseText) {
- cc.Loader.getInstance().onResLoaded();
- selfPointer._textFileCache[fileUrl] = xhr.responseText;
- }
- };
}
+ xhr.onreadystatechange = function (event) {
+ if (xhr.readyState == 4) {
+ if (xhr.status == 200) {
+ var fileContents = xhr.responseText;
+ if (fileContents)
+ selfPointer._textFileCache[fileUrl] = fileContents;
+ } else {
+ cc.Loader.getInstance().onResLoadingErr(fileUrl);
+ }
+ cc.Loader.getInstance().onResLoaded();
+ }
+ };
xhr.send(null);
},
_loadTextFileData:function (fileUrl) {
var req = this._getXMLHttpRequest();
req.open('GET', fileUrl, false);
- var arrayInfo = null;
+ var fileContents = null;
if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
req.setRequestHeader("Accept-Charset", "utf-8");
- req.send(null);
- if (req.status != 200)
- return null;
-
- var fileContents = req.responseText;
- if (fileContents) {
- arrayInfo = fileContents;
- this._textFileCache[fileUrl] = fileContents;
- }
} else {
if (req.overrideMimeType)
req.overrideMimeType('text\/plain; charset=utf-8');
- req.send(null);
- if (req.status != 200)
- return null;
+ }
+ req.send(null);
+ if (req.status != 200)
+ return null;
- arrayInfo = req.responseText;
- this._textFileCache[fileUrl] = arrayInfo;
+ fileContents = req.responseText;
+ if (fileContents) {
+ this._textFileCache[fileUrl] = fileContents;
}
- return arrayInfo;
+ return fileContents;
},
/**
From f4de13c0b82ce84f717b6e147c25ae21e58790d6 Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Thu, 29 Aug 2013 11:29:39 +0800
Subject: [PATCH 068/141] closed #2741: Modify LabelTTF's rendering from direct
draw to pre-render
---
cocos2d/CCDirector.js | 2 +-
cocos2d/base_nodes/CCNode.js | 3 +-
cocos2d/label_nodes/CCLabelTTF.js | 462 +++++++++++++---------
cocos2d/support/CCNotificationCenter.js | 1 -
cocos2d/text_input_node/CCTextFieldTTF.js | 6 +-
5 files changed, 278 insertions(+), 196 deletions(-)
diff --git a/cocos2d/CCDirector.js b/cocos2d/CCDirector.js
index 9b7a3dcc44..3e727378df 100644
--- a/cocos2d/CCDirector.js
+++ b/cocos2d/CCDirector.js
@@ -770,6 +770,7 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
setOpenGLView:function (openGLView) {
// set size
this._winSizeInPoints = cc.size(cc.canvas.width, cc.canvas.height); //this._openGLView.getDesignResolutionSize();
+ this._openGLView = openGLView || cc.EGLView.getInstance();
if (cc.renderContextType === cc.CANVAS)
return;
@@ -785,7 +786,6 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
//if (this._openGLView != openGLView) {
// because EAGLView is not kind of CCObject
- this._openGLView = openGLView || cc.EGLView.getInstance();
this._createStatsLabel();
diff --git a/cocos2d/base_nodes/CCNode.js b/cocos2d/base_nodes/CCNode.js
index 1c0bd68ebd..b1d6a76239 100644
--- a/cocos2d/base_nodes/CCNode.js
+++ b/cocos2d/base_nodes/CCNode.js
@@ -3762,7 +3762,8 @@ cc.NodeRGBA = cc.Node.extend(/** @lends cc.NodeRGBA# */{
},
getColor:function(){
- return this._realColor;
+ var locRealColor = this._realColor;
+ return new cc.Color3B(locRealColor.r, locRealColor.g, locRealColor.b);
},
getDisplayedColor:function(){
diff --git a/cocos2d/label_nodes/CCLabelTTF.js b/cocos2d/label_nodes/CCLabelTTF.js
index b642548e9b..c237a95c7e 100644
--- a/cocos2d/label_nodes/CCLabelTTF.js
+++ b/cocos2d/label_nodes/CCLabelTTF.js
@@ -38,7 +38,7 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
_dimensions:null,
_hAlignment:cc.TEXT_ALIGNMENT_CENTER,
_vAlignment:cc.VERTICAL_TEXT_ALIGNMENT_TOP,
- _fontName:"Arial",
+ _fontName: null,
_fontSize:0.0,
_string:"",
_isMultiLine:false,
@@ -60,13 +60,21 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
// font tint
_textFillColor:null,
+ _strokeShadowOffsetX:0,
+ _strokeShadowOffsetY:0,
+ _originalPosition:null,
+ _needUpdateTexture:false,
+
+ _labelCanvas:null,
+ _labelContext:null,
+
/**
* Constructor
*/
ctor:function () {
cc.Sprite.prototype.ctor.call(this);
this._dimensions = cc.SizeZero();
- this._hAlignment = cc.TEXT_ALIGNMENT_CENTER;
+ this._hAlignment = cc.TEXT_ALIGNMENT_LEFT;
this._vAlignment = cc.VERTICAL_TEXT_ALIGNMENT_TOP;
this._opacityModifyRGB = false;
this._fontStyleStr = "";
@@ -85,11 +93,16 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
this._strokeColorStr = "";
this._textFillColor = cc.white();
+ this._strokeShadowOffsetX = 0;
+ this._strokeShadowOffsetY = 0;
+ this._originalPosition = cc.PointZero();
+ this._needUpdateTexture = false;
+
this._setColorStyleStr();
},
init:function () {
- return this.initWithString([" ", this._fontName, this._fontSize]);
+ return this.initWithString(" ", this._fontName, this._fontSize);
},
/**
* Prints out a description of this class
@@ -103,16 +116,21 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
this.setFontFillColor(color3, true);
},
+ getColor:function(){
+ return this._textFillColor;
+ },
+
setOpacity:function (opacity) {
if (this._opacity === opacity)
return;
cc.Sprite.prototype.setOpacity.call(this, opacity);
this._setColorStyleStr();
+ this._needUpdateTexture = true;
},
_setColorStyleStr:function () {
var locFillColor = this._textFillColor;
- this._colorStyleStr = "rgba(" + locFillColor.r + "," + locFillColor.g + "," + locFillColor.b + ", " + this._realOpacity / 255 + ")";
+ this._colorStyleStr = "rgba(" + locFillColor.r + "," + locFillColor.g + "," + locFillColor.b + ", " + this._displayedOpacity / 255 + ")";
},
/**
@@ -165,46 +183,36 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
/**
* initializes the cc.LabelTTF with a font name, alignment, dimension and font size
- * @param {String} initialize string
+ * @param {String} label string
* @param {String} fontName
* @param {Number} fontSize
- * @param {cc.Size} dimensions
- * @param {cc.TEXT_ALIGNMENT_LEFT|cc.TEXT_ALIGNMENT_CENTER|cc.TEXT_ALIGNMENT_RIGHT} alignment
+ * @param {cc.Size} [dimensions=]
+ * @param {Number} [hAlignment=]
+ * @param {Number} [vAlignment=]
* @return {Boolean} return false on error
*/
- initWithString:function (arg) {
- var strInfo = arg[0] + "", fontName, fontSize, dimensions, hAlignment, vAlignment;
+ initWithString:function (label, fontName, fontSize, dimensions, hAlignment, vAlignment) {
+ var strInfo = label + "";
cc.Assert(strInfo != null, "cc.LabelTTF.initWithString() label is null");
- if (arg.length == 6) {
- fontName = arg[1];
- fontSize = arg[2];
- dimensions = arg[3];
- hAlignment = arg[4];
- vAlignment = arg[5];
- } else if (arg.length == 5) {
- fontName = arg[1];
- fontSize = arg[2];
- dimensions = arg[3];
- hAlignment = arg[4];
- vAlignment = cc.VERTICAL_TEXT_ALIGNMENT_TOP;
- } else {
- fontName = arg[1] || "Arial";
- fontSize = arg[2] || 16;
- dimensions = cc.size(0, arg[2]);
- hAlignment = cc.TEXT_ALIGNMENT_LEFT;
- vAlignment = cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM;
- }
+
+ fontSize = fontSize || 16;
+ dimensions = dimensions || cc.size(0, fontSize);
+ hAlignment = hAlignment || cc.TEXT_ALIGNMENT_LEFT;
+ vAlignment = vAlignment || cc.VERTICAL_TEXT_ALIGNMENT_TOP;
if (cc.Sprite.prototype.init.call(this)) {
this._opacityModifyRGB = false;
this._dimensions = cc.size(dimensions.width, dimensions.height);
- this._fontName = fontName;
+ this._fontName = fontName || "Arial";
this._hAlignment = hAlignment;
this._vAlignment = vAlignment;
this._fontSize = fontSize * cc.CONTENT_SCALE_FACTOR();
this._fontStyleStr = this._fontSize + "px '" + fontName + "'";
this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(fontName,this._fontSize);
this.setString(strInfo);
+ this._setColorStyleStr();
+ this._updateTexture();
+ this._needUpdateTexture = false;
return true;
}
@@ -212,6 +220,169 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
},
/// ---- common properties end ----
+ _getLabelContext:function () {
+ if (this._labelContext)
+ return this._labelContext;
+
+ if (!this._labelCanvas) {
+ var locCanvas = document.createElement("canvas");
+ var labelTexture = new cc.Texture2D();
+ labelTexture.initWithElement(locCanvas);
+ this.setTexture(labelTexture);
+ this._labelCanvas = locCanvas;
+ }
+ this._labelContext = this._labelCanvas.getContext("2d");
+ return this._labelContext;
+ },
+
+ _updateTexture:function () {
+ var locContext = this._getLabelContext();
+ var locContentSize = this._contentSize;
+
+ if(this._string.length === 0){
+ this._labelCanvas.width = 1;
+ this._labelCanvas.height = locContentSize.height;
+ this.setTextureRect(cc.rect(0, 0, 1, locContentSize.height));
+ return true;
+ }
+
+ //set size for labelCanvas
+ locContext.font = this._fontStyleStr;
+ this._updateTTF();
+ var width = locContentSize.width, height = locContentSize.height;
+ this._labelCanvas.width = width;
+ this._labelCanvas.height = height;
+
+ //draw text to labelCanvas
+ this._drawTTFInCanvas(locContext);
+ this._texture.handleLoadedTexture();
+
+ this.setTextureRect(cc.rect(0, 0, width, height));
+ return true;
+ },
+
+ _drawTTFInCanvas: function (context) {
+ if (!context)
+ return;
+
+ var locContentSizeHeight = this._contentSize.height, locVAlignment = this._vAlignment, locHAlignment = this._hAlignment,
+ locFontHeight = this._fontClientHeight;
+
+ context.setTransform(1, 0, 0, 1, 0, locContentSizeHeight);
+ //this is fillText for canvas
+ if (context.font != this._fontStyleStr)
+ context.font = this._fontStyleStr;
+ context.fillStyle = this._colorStyleStr;
+
+ //stroke style setup
+ var locStrokeEnabled = this._strokeEnabled;
+ if (locStrokeEnabled) {
+ context.lineWidth = this._strokeSize;
+ context.strokeStyle = this._strokeColorStr;
+ }
+
+ var isNegForOffsetX = false, isNegForOffsetY = false;
+ //shadow style setup
+ if (this._shadowEnabled) {
+ var locShadowOffset = this._shadowOffset;
+ context.shadowColor = "rgba(128,128,128,1)";
+ isNegForOffsetX = locShadowOffset.width < 0;
+ isNegForOffsetY = locShadowOffset.height < 0;
+ context.shadowOffsetX = locShadowOffset.width;
+ context.shadowOffsetY = -locShadowOffset.height;
+ context.shadowBlur = this._shadowBlur;
+ }
+
+ context.textBaseline = cc.LabelTTF._textBaseline[locVAlignment];
+ context.textAlign = cc.LabelTTF._textAlign[locHAlignment];
+
+ var xOffset = 0, locStrokeShadowOffsetX = this._strokeShadowOffsetX, locStrokeShadowOffsetY = this._strokeShadowOffsetY;
+ var yOffset = 0;
+ var locContentWidth = this._contentSize.width - locStrokeShadowOffsetX;
+ if (locHAlignment === cc.TEXT_ALIGNMENT_RIGHT)
+ xOffset = isNegForOffsetX ? locContentWidth + locStrokeShadowOffsetX : locContentWidth;
+ else if (locHAlignment === cc.TEXT_ALIGNMENT_CENTER)
+ xOffset = isNegForOffsetX ? locContentWidth / 2 + locStrokeShadowOffsetX : locContentWidth / 2;
+ else
+ xOffset = isNegForOffsetX ? locStrokeShadowOffsetX : 0;
+ if (this._isMultiLine) {
+ var locStrLen = this._strings.length;
+ if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM){
+ yOffset = locFontHeight + locContentSizeHeight - locFontHeight * locStrLen;
+ if(isNegForOffsetY)
+ yOffset -= locStrokeShadowOffsetY;
+ } else if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_CENTER){
+ yOffset = locFontHeight / 2 + (locContentSizeHeight - locFontHeight * locStrLen) / 2;
+ if(isNegForOffsetY)
+ yOffset -= locStrokeShadowOffsetY;
+ } else{
+ if(isNegForOffsetY)
+ yOffset -= locStrokeShadowOffsetY/2;
+ else
+ yOffset += locStrokeShadowOffsetY/2;
+ }
+
+ for (var i = 0; i < locStrLen; i++) {
+ var line = this._strings[i];
+ var tmpOffsetY = -locContentSizeHeight + (locFontHeight * i) + yOffset;
+ if (locStrokeEnabled)
+ context.strokeText(line, xOffset, tmpOffsetY);
+ context.fillText(line, xOffset, tmpOffsetY);
+ }
+ } else {
+ if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM) {
+ yOffset = isNegForOffsetY ? -locStrokeShadowOffsetY : 0;
+ if (locStrokeEnabled)
+ context.strokeText(this._string, xOffset, yOffset);
+ context.fillText(this._string, xOffset, yOffset);
+ } else if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_TOP) {
+ yOffset = isNegForOffsetY ? -locStrokeShadowOffsetY/2 -locContentSizeHeight : - locContentSizeHeight + locStrokeShadowOffsetY/2;
+ if (locStrokeEnabled)
+ context.strokeText(this._string, xOffset, yOffset);
+ context.fillText(this._string, xOffset, yOffset);
+ } else {
+ yOffset = isNegForOffsetY ? -locStrokeShadowOffsetY -locContentSizeHeight / 2 : - locContentSizeHeight / 2;
+ if (locStrokeEnabled)
+ context.strokeText(this._string, xOffset, yOffset);
+ context.fillText(this._string, xOffset, yOffset);
+ }
+ }
+ },
+
+ visit:function(){
+ if(!this._string || this._string == "")
+ return;
+
+ if(this._needUpdateTexture ){
+ this._needUpdateTexture = false;
+ this._updateTexture();
+ }
+ cc.Sprite.prototype.visit.call(this);
+ },
+
+ setPosition:function(posX, posY){
+ if (arguments.length == 2)
+ this._originalPosition = cc.p(posX, posY);
+ else
+ this._originalPosition = cc.p(posX.x, posX.y);
+
+ //get real position
+ var locStrokeShadowOffsetX = 0, locStrokeShadowOffsetY = 0;
+ if(this._strokeEnabled)
+ locStrokeShadowOffsetX = locStrokeShadowOffsetY = this._strokeSize * 2;
+ if(this._shadowEnabled){
+ var locOffsetSize = this._shadowOffset;
+ locStrokeShadowOffsetX += locOffsetSize.width> 0?0:locOffsetSize.width;
+ locStrokeShadowOffsetY += locOffsetSize.height>0?0:locOffsetSize.height;
+ }
+ var realPosition = cc.p(this._originalPosition.x + locStrokeShadowOffsetX, this._originalPosition.y + locStrokeShadowOffsetY);
+ cc.Sprite.prototype.setPosition.call(this, realPosition);
+ },
+
+ getPosition:function(){
+ return cc.p(this._originalPosition.x, this._originalPosition.y);
+ },
+
/**
* initializes the CCLabelTTF with a font name, alignment, dimension and font size
* @param {String} text
@@ -270,6 +441,8 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
if (this._shadowBlur != shadowBlur)
this._shadowBlur = shadowBlur;
+
+ this._needUpdateTexture = true;
},
/**
@@ -279,6 +452,7 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
disableShadow:function(mustUpdateTexture){
if (this._shadowEnabled) {
this._shadowEnabled = false;
+ this._needUpdateTexture = true;
}
},
@@ -299,7 +473,9 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
}
if (this._strokeSize!== strokeSize)
- this._strokeSize = strokeSize;
+ this._strokeSize = strokeSize || 0;
+
+ this._needUpdateTexture = true;
},
/**
@@ -309,6 +485,7 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
disableStroke:function(mustUpdateTexture){
if (this._strokeEnabled){
this._strokeEnabled = false;
+ this._needUpdateTexture = true;
}
},
@@ -322,6 +499,7 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
if (locTextFillColor.r != tintColor.r || locTextFillColor.g != tintColor.g || locTextFillColor.b != tintColor.b){
this._textFillColor = tintColor;
this._setColorStyleStr();
+ this._needUpdateTexture = true;
}
},
@@ -346,6 +524,9 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
// fill color
this.setFontFillColor(textDefinition.fontFillColor, false);
+
+ if (mustUpdateTexture)
+ this._updateTexture();
},
_prepareTextDefinition:function(adjustForResolution){
@@ -400,8 +581,7 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
this._string = text + "";
// Force update
- if (this._string.length > 0)
- this._updateTTF();
+ this._needUpdateTexture = true;
}
},
@@ -414,8 +594,7 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
this._hAlignment = alignment;
// Force update
- if (this._string.length > 0)
- this._updateTTF();
+ this._needUpdateTexture = true;
}
},
@@ -428,8 +607,7 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
this._vAlignment = verticalAlignment;
// Force update
- if (this._string.length > 0)
- this._updateTTF();
+ this._needUpdateTexture = true;
}
},
@@ -442,8 +620,7 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
this._dimensions = dim;
// Force udpate
- if (this._string.length > 0)
- this._updateTTF();
+ this._needUpdateTexture = true;
}
},
@@ -457,8 +634,7 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
this._fontStyleStr = this._fontSize + "px '" + this._fontName + "'";
this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(this._fontName,this._fontSize);
// Force update
- if (this._string.length > 0)
- this._updateTTF();
+ this._needUpdateTexture = true;
}
},
@@ -467,29 +643,25 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
* @param {String} fontName
*/
setFontName:function (fontName) {
- if (this._fontName != fontName) {
- this._fontName = new String(fontName);
+ if (this._fontName != fontName ) {
+ this._fontName = fontName;
this._fontStyleStr = this._fontSize + "px '" + this._fontName + "'";
this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(this._fontName,this._fontSize);
// Force update
- if (this._string.length > 0)
- this._updateTTF();
+ this._needUpdateTexture = true;
}
},
_updateTTF:function () {
- var context = cc.renderContext;
- if (context.font != this._fontStyleStr)
- context.font = this._fontStyleStr;
- // we need to find out if the label needs multiline, if its automatic new line or specified newline
- var stringWidth = context.measureText(this._string).width;
- var locDimensionsWidth = this._dimensions.width;
- if (this._string.indexOf('\n') !== -1 || (locDimensionsWidth !== 0 && stringWidth > locDimensionsWidth && this._string.indexOf(" ") !== -1)) {
+ var locDimensionsWidth = this._dimensions.width, locLabelContext = this._labelContext;
+
+ var stringWidth = locLabelContext.measureText(this._string).width;
+ if(this._string.indexOf('\n') !== -1 || (locDimensionsWidth !== 0 && stringWidth > locDimensionsWidth && this._string.indexOf(" ") !== -1)) {
var strings = this._strings = this._string.split('\n');
var lineWidths = this._lineWidths = [];
for (var i = 0; i < strings.length; i++) {
if (strings[i].indexOf(" ") !== -1 && locDimensionsWidth > 0) {
- var percent = locDimensionsWidth / context.measureText(this._strings[i]).width;
+ var percent = locDimensionsWidth / locLabelContext.measureText(this._strings[i]).width;
var startSearch = 0 | (percent * strings[i].length + 1);
var cutoff = startSearch;
var tempLineWidth = 0;
@@ -497,7 +669,7 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
do {
cutoff = strings[i].lastIndexOf(" ", cutoff - 1);
var str = strings[i].substring(0, cutoff);
- tempLineWidth = context.measureText(str).width;
+ tempLineWidth = locLabelContext.measureText(str).width;
if (cutoff === -1) {
cutoff = strings[i].indexOf(" ", startSearch);
break;
@@ -508,122 +680,46 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
strings[i] = str;
}
}
- lineWidths[i] = tempLineWidth || context.measureText(strings[i]).width;
+ lineWidths[i] = tempLineWidth || locLabelContext.measureText(strings[i]).width;
}
this._isMultiLine = true;
} else
this._isMultiLine = false;
- // we will need to change contentSize to cater this
- //if dimension is not set, set contentSize according to actual size
+ var locSize, locStrokeShadowOffsetX = 0, locStrokeShadowOffsetY = 0;
+ if(this._strokeEnabled)
+ locStrokeShadowOffsetX = locStrokeShadowOffsetY = this._strokeSize * 2;
+ if(this._shadowEnabled){
+ var locOffsetSize = this._shadowOffset;
+ locStrokeShadowOffsetX += Math.abs(locOffsetSize.width);
+ locStrokeShadowOffsetY += Math.abs(locOffsetSize.height);
+ }
+
+ //get offset for stroke and shadow
if (locDimensionsWidth === 0) {
if (this._isMultiLine)
- this.setContentSize(cc.size(Math.max.apply(Math, this._lineWidths), this._fontClientHeight * this._strings.length));
+ locSize = cc.size(Math.max.apply(Math, this._lineWidths) + locStrokeShadowOffsetX, (this._fontClientHeight * this._strings.length) + locStrokeShadowOffsetY);
else
- this.setContentSize(cc.size(stringWidth, this._fontClientHeight));
+ locSize = cc.size(stringWidth + locStrokeShadowOffsetX, this._fontClientHeight + locStrokeShadowOffsetY);
} else {
- if(this._dimensions.height === 0) {
+ if(this._dimensions.height === 0){
if (this._isMultiLine)
- this.setContentSize(cc.size(locDimensionsWidth, this._fontClientHeight * this._strings.length));
+ locSize = cc.size(locDimensionsWidth + locStrokeShadowOffsetX, (this._fontClientHeight * this._strings.length) + locStrokeShadowOffsetY);
else
- this.setContentSize(cc.size(locDimensionsWidth, this._fontClientHeight));
+ locSize = cc.size(locDimensionsWidth + locStrokeShadowOffsetX, this._fontClientHeight + locStrokeShadowOffsetY);
} else {
//dimension is already set, contentSize must be same as dimension
- this.setContentSize(cc.size(locDimensionsWidth, this._dimensions.height));
+ locSize = cc.size(locDimensionsWidth + locStrokeShadowOffsetX, this._dimensions.height + locStrokeShadowOffsetY);
}
}
+ this.setContentSize(locSize);
+ this._strokeShadowOffsetX = locStrokeShadowOffsetX;
+ this._strokeShadowOffsetY = locStrokeShadowOffsetY;
+
this._anchorPointInPoints.x = this._contentSize.width * this._anchorPoint.x;
this._anchorPointInPoints.y = this._contentSize.height * this._anchorPoint.y;
- },
- /**
- * renders the label
- * @param {CanvasRenderingContext2D|Null} ctx
- */
- draw:function (ctx) {
- if(!this._string || this._string == "")
- return;
- var context = ctx || cc.renderContext;
- if (this._flipX)
- context.scale(-1, 1);
- if (this._flipY)
- context.scale(1, -1);
-
- //this is fillText for canvas
- context.fillStyle = this._colorStyleStr;
-
- if (context.font != this._fontStyleStr)
- context.font = this._fontStyleStr;
-
- //stroke style setup
- var locStrokeEnabled = this._strokeEnabled;
- if(locStrokeEnabled){
- context.lineWidth = this._strokeSize * 2;
- context.strokeStyle = this._strokeColorStr;
- }
-
- //shadow style setup
- if(this._shadowEnabled){
- var locShadowOffset = this._shadowOffset;
- context.shadowColor = "rgba(128,128,128,1)";
- context.shadowOffsetX = locShadowOffset.width;
- context.shadowOffsetY = -locShadowOffset.height;
- context.shadowBlur = this._shadowBlur;
- }
-
- var locVAlignment = this._vAlignment, locHAlignment = this._hAlignment,
- locContentSizeWidth = this._contentSize.width, locContentSizeHeight = this._contentSize.height;
- var locFontHeight = this._fontClientHeight;
-
- context.textBaseline = cc.LabelTTF._textBaseline[locVAlignment];
- context.textAlign = cc.LabelTTF._textAlign[locHAlignment];
- var xoffset = 0;
- if (locHAlignment === cc.TEXT_ALIGNMENT_RIGHT)
- xoffset = locContentSizeWidth;
- else if (locHAlignment === cc.TEXT_ALIGNMENT_CENTER)
- xoffset = locContentSizeWidth / 2;
- if (this._isMultiLine) {
- var locStrings = this._strings;
- var yOffset = 0, strLen = this._strings.length;
- if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM)
- yOffset = locFontHeight + locContentSizeHeight - locFontHeight * strLen;
- else if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_CENTER)
- yOffset = locFontHeight / 2 + (locContentSizeHeight - locFontHeight * strLen) / 2;
-
- var tmpLineStr = null, tmpYOffset = null;
- for (var i = 0; i < strLen; i++) {
- tmpLineStr = locStrings[i];
- tmpYOffset = -locContentSizeHeight + (locFontHeight * i) + yOffset;
- if(locStrokeEnabled)
- context.strokeText(tmpLineStr, xoffset, tmpYOffset);
- context.fillText(tmpLineStr, xoffset, tmpYOffset);
- }
- } else {
- if (locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM){
- if(locStrokeEnabled)
- context.strokeText(this._string, xoffset, 0);
- context.fillText(this._string, xoffset, 0);
- }else if(locVAlignment === cc.VERTICAL_TEXT_ALIGNMENT_TOP){
- if(locStrokeEnabled)
- context.strokeText(this._string, xoffset, -locContentSizeHeight);
- context.fillText(this._string, xoffset, -locContentSizeHeight);
- }else{
- if(locStrokeEnabled)
- context.strokeText(this._string, xoffset, -locContentSizeHeight/2);
- context.fillText(this._string, xoffset, -locContentSizeHeight/2);
- }
- }
-
- if (cc.SPRITE_DEBUG_DRAW === 1) {
- context.fillStyle = "rgba(255,0,0,0.2)";
- context.lineWidth = 1;
- context.shadowColor = "";
- context.shadowOffsetX = 0;
- context.shadowOffsetY = 0;
- context.shadowBlur = 0;
- context.fillRect(this._offsetPosition.x, this._offsetPosition.y, locContentSizeWidth, -locContentSizeHeight);
- }
- cc.INCREMENT_GL_DRAWS(1);
+ this.setPosition(this._originalPosition);
}
});
@@ -666,6 +762,9 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{
_strokeShadowOffsetX:0,
_strokeShadowOffsetY:0,
_originalPosition:null,
+ _needUpdateTexture:false,
+ _labelCanvas:null,
+ _labelContext:null,
/**
* Constructor
@@ -699,12 +798,13 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{
this._strokeShadowOffsetX = 0;
this._strokeShadowOffsetY = 0;
this._originalPosition = cc.PointZero();
+ this._needUpdateTexture = false;
this._setColorStyleStr();
},
init:function () {
- return this.initWithString([" ", this._fontName, this._fontSize]);
+ return this.initWithString(" ", this._fontName, this._fontSize);
},
/**
* Prints out a description of this class
@@ -714,15 +814,9 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{
return "";
},
- setOpacity:function (opacity) {
- if (this._opacity === opacity)
- return;
- cc.Sprite.prototype.setOpacity.call(this, opacity);
- this._setColorStyleStr();
- },
-
_setColorStyleStr:function () {
- this._colorStyleStr = "rgba(" + this._color.r + "," + this._color.g + "," + this._color.b + ", " + this._opacity / 255 + ")";
+ var locFillColor = this._textFillColor;
+ this._colorStyleStr = "rgba(" + locFillColor.r + "," + locFillColor.g + "," + locFillColor.b + ", " + this._displayedOpacity / 255 + ")";
},
/**
@@ -775,40 +869,27 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{
/**
* initializes the cc.LabelTTF with a font name, alignment, dimension and font size
- * @param {String} initialize string
+ * @param {String} label string
* @param {String} fontName
* @param {Number} fontSize
* @param {cc.Size} dimensions
- * @param {cc.TEXT_ALIGNMENT_LEFT|cc.TEXT_ALIGNMENT_CENTER|cc.TEXT_ALIGNMENT_RIGHT} alignment
+ * @param {Number} hAlignment
+ * @param {Number} vAlignment
* @return {Boolean} return false on error
*/
- initWithString:function (arg) {
- var strInfo = (arg[0] == undefined ) ? " " : arg[0] + "", fontName, fontSize, dimensions, hAlignment, vAlignment;
+ initWithString:function (label, fontName, fontSize, dimensions, hAlignment, vAlignment) {
+ var strInfo = label + "";
cc.Assert(strInfo != null, "cc.LabelTTF.initWithString() label is null");
- if (arg.length == 6) {
- fontName = arg[1];
- fontSize = arg[2];
- dimensions = arg[3];
- hAlignment = arg[4];
- vAlignment = arg[5];
- } else if (arg.length == 5) {
- fontName = arg[1];
- fontSize = arg[2];
- dimensions = arg[3];
- hAlignment = arg[4];
- vAlignment = cc.VERTICAL_TEXT_ALIGNMENT_TOP;
- } else {
- fontName = arg[1] || "Arial";
- fontSize = arg[2] || 16;
- dimensions = cc.size(0, arg[2]);
- hAlignment = cc.TEXT_ALIGNMENT_LEFT;
- vAlignment = cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM;
- }
+
+ fontSize = fontSize || 16;
+ dimensions = dimensions || cc.size(0, fontSize);
+ hAlignment = hAlignment || cc.TEXT_ALIGNMENT_LEFT;
+ vAlignment = vAlignment || cc.VERTICAL_TEXT_ALIGNMENT_TOP;
if (cc.Sprite.prototype.init.call(this)) {
this._opacityModifyRGB = false;
this._dimensions = cc.size(dimensions.width, dimensions.height);
- this._fontName = fontName;
+ this._fontName = fontName || "Arial";
this._hAlignment = hAlignment;
this._vAlignment = vAlignment;
this._fontSize = fontSize * cc.CONTENT_SCALE_FACTOR();
@@ -873,7 +954,6 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{
if (false === this._shadowEnabled)
this._shadowEnabled = true;
-
if(this._shadowOffset){
if ((this._shadowOffset.width != shadowOffset.width) || (this._shadowOffset.height != shadowOffset.height)) {
this._shadowOffset.width = shadowOffset.width;
@@ -1113,7 +1193,7 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{
//this is fillText for canvas
if (context.font != this._fontStyleStr)
context.font = this._fontStyleStr;
- context.fillStyle = this._fillColorStr;
+ context.fillStyle = "rgba(255,255,255,1)";
//stroke style setup
var locStrokeEnabled = this._strokeEnabled;
@@ -1323,7 +1403,6 @@ cc.LabelTTFWebGL = cc.Sprite.extend(/** @lends cc.LabelTTFWebGL# */{
return true;
},
- _needUpdateTexture:false,
visit:function(){
if(this._needUpdateTexture ){
this._needUpdateTexture = false;
@@ -1403,16 +1482,17 @@ cc.LabelTTF._textBaseline = ["top", "middle", "bottom"];
* @param {String} label
* @param {String} fontName
* @param {Number} fontSize
- * @param {cc.Size} dimensions
- * @param {cc.TEXT_ALIGNMENT_LEFT|cc.TEXT_ALIGNMENT_CENTER|cc.TEXT_ALIGNMENT_RIGHT} alignment
+ * @param {cc.Size} [dimensions=cc.SIZE_ZERO]
+ * @param {Number} [hAlignment]
+ * @param {Number} [vAlignment=cc.VERTICAL_TEXT_ALIGNMENT_TOP]
* @return {cc.LabelTTF|Null}
* @example
* // Example
* var myLabel = cc.LabelTTF.create('label text', 'Times New Roman', 32, cc.size(32,16), cc.TEXT_ALIGNMENT_LEFT);
*/
-cc.LabelTTF.create = function (/* Multi arguments */) {
+cc.LabelTTF.create = function (label, fontName, fontSize, dimensions, hAlignment, vAlignment) {
var ret = new cc.LabelTTF();
- if (ret.initWithString(arguments))
+ if (ret.initWithString(label, fontName, fontSize, dimensions, hAlignment, vAlignment))
return ret;
return null;
};
diff --git a/cocos2d/support/CCNotificationCenter.js b/cocos2d/support/CCNotificationCenter.js
index 84a283aa41..60188057bf 100644
--- a/cocos2d/support/CCNotificationCenter.js
+++ b/cocos2d/support/CCNotificationCenter.js
@@ -126,7 +126,6 @@ cc.NotificationCenter.getInstance = function() {
};
cc.NotificationObserver = cc.Class.extend({
-
/**
* @param {cc.Class} target
* @param {String} selector
diff --git a/cocos2d/text_input_node/CCTextFieldTTF.js b/cocos2d/text_input_node/CCTextFieldTTF.js
index 52a16a5eb3..67f69be2db 100644
--- a/cocos2d/text_input_node/CCTextFieldTTF.js
+++ b/cocos2d/text_input_node/CCTextFieldTTF.js
@@ -157,7 +157,7 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{
if (placeholder) {
this._placeHolder = placeholder;
}
- return this.initWithString(this._placeHolder, dimensions, alignment, fontName, fontSize);
+ return this.initWithString(this._placeHolder,fontName, fontSize, dimensions, alignment);
break;
case 3:
if (placeholder) {
@@ -230,6 +230,8 @@ cc.TextFieldTTF = cc.LabelTTF.extend(/** @lends cc.TextFieldTTF# */{
// draw placeholder
var color = this.getColor();
this.setColor(this._ColorSpaceHolder);
+ if(cc.renderContextType === cc.CANVAS)
+ this._updateTexture();
cc.LabelTTF.prototype.draw.call(this, context);
this.setColor(color);
},
@@ -400,7 +402,7 @@ cc.TextFieldTTF.create = function (placeholder, dimensions, alignment, fontName,
ret = new cc.TextFieldTTF();
fontName = arguments[1];
fontSize = arguments[2];
- if (ret && ret.initWithString(["", fontName, fontSize])) {
+ if (ret && ret.initWithString("", fontName, fontSize)) {
if (placeholder)
ret.setPlaceHolder(placeholder);
return ret;
From ec76afe15ada206f57abc7ba7958e87e26d717af Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Thu, 29 Aug 2013 17:06:18 +0800
Subject: [PATCH 069/141] Closed 2741: Solved the problem that LabelTTF didn't
work on mobile browser.
---
cocos2d/label_nodes/CCLabelTTF.js | 10 +++++-----
cocos2d/sprite_nodes/CCSprite.js | 8 ++++++--
2 files changed, 11 insertions(+), 7 deletions(-)
diff --git a/cocos2d/label_nodes/CCLabelTTF.js b/cocos2d/label_nodes/CCLabelTTF.js
index c237a95c7e..fd41ecccef 100644
--- a/cocos2d/label_nodes/CCLabelTTF.js
+++ b/cocos2d/label_nodes/CCLabelTTF.js
@@ -698,18 +698,18 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
//get offset for stroke and shadow
if (locDimensionsWidth === 0) {
if (this._isMultiLine)
- locSize = cc.size(Math.max.apply(Math, this._lineWidths) + locStrokeShadowOffsetX, (this._fontClientHeight * this._strings.length) + locStrokeShadowOffsetY);
+ locSize = cc.size(0 | (Math.max.apply(Math, this._lineWidths) + locStrokeShadowOffsetX), 0 | ((this._fontClientHeight * this._strings.length) + locStrokeShadowOffsetY));
else
- locSize = cc.size(stringWidth + locStrokeShadowOffsetX, this._fontClientHeight + locStrokeShadowOffsetY);
+ locSize = cc.size(0 | (stringWidth + locStrokeShadowOffsetX), 0 | (this._fontClientHeight + locStrokeShadowOffsetY));
} else {
if(this._dimensions.height === 0){
if (this._isMultiLine)
- locSize = cc.size(locDimensionsWidth + locStrokeShadowOffsetX, (this._fontClientHeight * this._strings.length) + locStrokeShadowOffsetY);
+ locSize = cc.size(0 | (locDimensionsWidth + locStrokeShadowOffsetX), 0 | ((this._fontClientHeight * this._strings.length) + locStrokeShadowOffsetY));
else
- locSize = cc.size(locDimensionsWidth + locStrokeShadowOffsetX, this._fontClientHeight + locStrokeShadowOffsetY);
+ locSize = cc.size(0 | (locDimensionsWidth + locStrokeShadowOffsetX), 0 | (this._fontClientHeight + locStrokeShadowOffsetY));
} else {
//dimension is already set, contentSize must be same as dimension
- locSize = cc.size(locDimensionsWidth + locStrokeShadowOffsetX, this._dimensions.height + locStrokeShadowOffsetY);
+ locSize = cc.size(0 | (locDimensionsWidth + locStrokeShadowOffsetX), 0 | (this._dimensions.height + locStrokeShadowOffsetY));
}
}
this.setContentSize(locSize);
diff --git a/cocos2d/sprite_nodes/CCSprite.js b/cocos2d/sprite_nodes/CCSprite.js
index 78b022bab7..8f14031cd3 100644
--- a/cocos2d/sprite_nodes/CCSprite.js
+++ b/cocos2d/sprite_nodes/CCSprite.js
@@ -1335,12 +1335,16 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
var image = this._texture.getHtmlElementObj();
if (this._colorized) {
context.drawImage(image,
- 0, 0, locRect.width, locRect.height,
+ 0, 0, 0 | locRect.width, 0 | locRect.height,
flipXOffset, flipYOffset, locRect.width, locRect.height);
} else {
+ try{
context.drawImage(image,
- locRect.x, locRect.y, locRect.width, locRect.height,
+ 0 | locRect.x, 0 | locRect.y, 0 | locRect.width, 0 | locRect.height,
flipXOffset, flipYOffset, locRect.width, locRect.height);
+ }catch(ex){
+ console.log(ex);
+ }
}
} else if (locContentSize.width !== 0) {
var curColor = this.getColor();
From f518e85c25a1478fffeeeaa368039949980da7b2 Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Thu, 29 Aug 2013 17:08:26 +0800
Subject: [PATCH 070/141] Closed #2741: remove the debug codes.
---
cocos2d/sprite_nodes/CCSprite.js | 4 ----
1 file changed, 4 deletions(-)
diff --git a/cocos2d/sprite_nodes/CCSprite.js b/cocos2d/sprite_nodes/CCSprite.js
index 8f14031cd3..15b7a80359 100644
--- a/cocos2d/sprite_nodes/CCSprite.js
+++ b/cocos2d/sprite_nodes/CCSprite.js
@@ -1338,13 +1338,9 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
0, 0, 0 | locRect.width, 0 | locRect.height,
flipXOffset, flipYOffset, locRect.width, locRect.height);
} else {
- try{
context.drawImage(image,
0 | locRect.x, 0 | locRect.y, 0 | locRect.width, 0 | locRect.height,
flipXOffset, flipYOffset, locRect.width, locRect.height);
- }catch(ex){
- console.log(ex);
- }
}
} else if (locContentSize.width !== 0) {
var curColor = this.getColor();
From e45d057d328204191eedae68f915d2158865be28 Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Thu, 29 Aug 2013 17:53:19 +0800
Subject: [PATCH 071/141] Closed #2741: fixed a bug of SpriteCanvas that
loading texture doesn't work when calling initWithFile
---
cocos2d/sprite_nodes/CCSprite.js | 1 -
1 file changed, 1 deletion(-)
diff --git a/cocos2d/sprite_nodes/CCSprite.js b/cocos2d/sprite_nodes/CCSprite.js
index 15b7a80359..2903ae8c78 100644
--- a/cocos2d/sprite_nodes/CCSprite.js
+++ b/cocos2d/sprite_nodes/CCSprite.js
@@ -969,7 +969,6 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
cc.Assert(filename != null, "Sprite#initWithFile():Invalid filename for sprite");
var texture = cc.TextureCache.getInstance().textureForKey(filename);
if (!texture) {
- filename = cc.FileUtils.getInstance().fullPathForFilename(filename);
texture = cc.TextureCache.getInstance().addImage(filename);
return this.initWithTexture(texture, rect);
} else {
From 1372e0df5ffff2a4db4a15f82c42d1c413f3ff65 Mon Sep 17 00:00:00 2001
From: SmallJun <536762164@qq.com>
Date: Fri, 30 Aug 2013 17:54:28 +0800
Subject: [PATCH 072/141] fixed #2754: Fixed the bug that _getResType error
when the url of res is like "a.png?arg=value".
---
cocos2d/CCLoader.js | 4 ++++
1 file changed, 4 insertions(+)
diff --git a/cocos2d/CCLoader.js b/cocos2d/CCLoader.js
index 6bfa53e296..a5a806c2f1 100644
--- a/cocos2d/CCLoader.js
+++ b/cocos2d/CCLoader.js
@@ -241,6 +241,10 @@ cc.Loader = cc.Class.extend(/** @lends cc.Loader# */{
} else {
var src = resInfo.src;
var ext = src.substring(src.lastIndexOf(".") + 1, src.length);
+
+ var index = ext.indexOf("?");
+ if(index > 0) ext = ext.substring(0, index);
+
for (var resType in cc.RESOURCE_TYPE) {
if (cc.RESOURCE_TYPE[resType].indexOf(ext) != -1) {
return resType;
From 78f08915b580c26a8c4dad0751e9af539d037cb0 Mon Sep 17 00:00:00 2001
From: NeroChan
Date: Sun, 1 Sep 2013 12:41:28 +0800
Subject: [PATCH 073/141] fixed #2760 : removeEventListener bug
---
CocosDenshion/SimpleAudioEngine.js | 1 +
HelloHTML5World/cocos2d.js | 1 +
cocos2d/CCDirector.js | 1 +
cocos2d/CCLoader.js | 1 +
cocos2d/platform/jsloader.js | 33 +++++++++---------
cocos2d/textures/CCTextureCache.js | 34 +++++++++++++++++--
.../PluginX/samples/HelloSocial/cocos2d.js | 1 +
template/cocos2d.js | 1 +
8 files changed, 54 insertions(+), 19 deletions(-)
diff --git a/CocosDenshion/SimpleAudioEngine.js b/CocosDenshion/SimpleAudioEngine.js
index 6a1b0c664f..6f399baec3 100644
--- a/CocosDenshion/SimpleAudioEngine.js
+++ b/CocosDenshion/SimpleAudioEngine.js
@@ -177,6 +177,7 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
sfxCache.audio.addEventListener('canplaythrough', function (e) {
cc.Loader.getInstance().onResLoaded();
this.removeEventListener('canplaythrough', arguments.callee, false);
+ this.removeEventListener('error', arguments.callee, false);
}, false);
sfxCache.audio.addEventListener("error", function (e) {
diff --git a/HelloHTML5World/cocos2d.js b/HelloHTML5World/cocos2d.js
index 30638e6410..c4c6cd9cbb 100644
--- a/HelloHTML5World/cocos2d.js
+++ b/HelloHTML5World/cocos2d.js
@@ -58,6 +58,7 @@
}
window.addEventListener('DOMContentLoaded', function () {
+ this.removeEventListener('DOMContentLoaded', arguments.callee, false);
//first load engine file if specified
var s = d.createElement('script');
/*********Delete this section if you have packed all files into one*******/
diff --git a/cocos2d/CCDirector.js b/cocos2d/CCDirector.js
index 3e727378df..d3d6ecdb72 100644
--- a/cocos2d/CCDirector.js
+++ b/cocos2d/CCDirector.js
@@ -1273,6 +1273,7 @@ cc.defaultFPS = 60;
cc.Director._fpsImage = new Image();
cc.Director._fpsImage.addEventListener("load", function () {
cc.Director._fpsImageLoaded = true;
+ this.removeEventListener('load', arguments.callee, false);
});
cc.Director._fpsImage.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAAgCAYAAAD9qabkAAAKQ2lDQ1BJQ0MgcHJvZmlsZQAAeNqdU3dYk/cWPt/3ZQ9WQtjwsZdsgQAiI6wIyBBZohCSAGGEEBJAxYWIClYUFRGcSFXEgtUKSJ2I4qAouGdBiohai1VcOO4f3Ke1fXrv7e371/u855zn/M55zw+AERImkeaiagA5UoU8Otgfj09IxMm9gAIVSOAEIBDmy8JnBcUAAPADeXh+dLA//AGvbwACAHDVLiQSx+H/g7pQJlcAIJEA4CIS5wsBkFIAyC5UyBQAyBgAsFOzZAoAlAAAbHl8QiIAqg0A7PRJPgUA2KmT3BcA2KIcqQgAjQEAmShHJAJAuwBgVYFSLALAwgCgrEAiLgTArgGAWbYyRwKAvQUAdo5YkA9AYACAmUIszAAgOAIAQx4TzQMgTAOgMNK/4KlfcIW4SAEAwMuVzZdL0jMUuJXQGnfy8ODiIeLCbLFCYRcpEGYJ5CKcl5sjE0jnA0zODAAAGvnRwf44P5Dn5uTh5mbnbO/0xaL+a/BvIj4h8d/+vIwCBAAQTs/v2l/l5dYDcMcBsHW/a6lbANpWAGjf+V0z2wmgWgrQevmLeTj8QB6eoVDIPB0cCgsL7SViob0w44s+/zPhb+CLfvb8QB7+23rwAHGaQJmtwKOD/XFhbnauUo7nywRCMW735yP+x4V//Y4p0eI0sVwsFYrxWIm4UCJNx3m5UpFEIcmV4hLpfzLxH5b9CZN3DQCshk/ATrYHtctswH7uAQKLDljSdgBAfvMtjBoLkQAQZzQyefcAAJO/+Y9AKwEAzZek4wAAvOgYXKiUF0zGCAAARKCBKrBBBwzBFKzADpzBHbzAFwJhBkRADCTAPBBCBuSAHAqhGJZBGVTAOtgEtbADGqARmuEQtMExOA3n4BJcgetwFwZgGJ7CGLyGCQRByAgTYSE6iBFijtgizggXmY4EImFINJKApCDpiBRRIsXIcqQCqUJqkV1II/ItchQ5jVxA+pDbyCAyivyKvEcxlIGyUQPUAnVAuagfGorGoHPRdDQPXYCWomvRGrQePYC2oqfRS+h1dAB9io5jgNExDmaM2WFcjIdFYIlYGibHFmPlWDVWjzVjHVg3dhUbwJ5h7wgkAouAE+wIXoQQwmyCkJBHWExYQ6gl7CO0EroIVwmDhDHCJyKTqE+0JXoS+cR4YjqxkFhGrCbuIR4hniVeJw4TX5NIJA7JkuROCiElkDJJC0lrSNtILaRTpD7SEGmcTCbrkG3J3uQIsoCsIJeRt5APkE+S+8nD5LcUOsWI4kwJoiRSpJQSSjVlP+UEpZ8yQpmgqlHNqZ7UCKqIOp9aSW2gdlAvU4epEzR1miXNmxZDy6Qto9XQmmlnafdoL+l0ugndgx5Fl9CX0mvoB+nn6YP0dwwNhg2Dx0hiKBlrGXsZpxi3GS+ZTKYF05eZyFQw1zIbmWeYD5hvVVgq9ip8FZHKEpU6lVaVfpXnqlRVc1U/1XmqC1SrVQ+rXlZ9pkZVs1DjqQnUFqvVqR1Vu6k2rs5Sd1KPUM9RX6O+X/2C+mMNsoaFRqCGSKNUY7fGGY0hFsYyZfFYQtZyVgPrLGuYTWJbsvnsTHYF+xt2L3tMU0NzqmasZpFmneZxzQEOxrHg8DnZnErOIc4NznstAy0/LbHWaq1mrX6tN9p62r7aYu1y7Rbt69rvdXCdQJ0snfU6bTr3dQm6NrpRuoW623XP6j7TY+t56Qn1yvUO6d3RR/Vt9KP1F+rv1u/RHzcwNAg2kBlsMThj8MyQY+hrmGm40fCE4agRy2i6kcRoo9FJoye4Ju6HZ+M1eBc+ZqxvHGKsNN5l3Gs8YWJpMtukxKTF5L4pzZRrmma60bTTdMzMyCzcrNisyeyOOdWca55hvtm82/yNhaVFnMVKizaLx5balnzLBZZNlvesmFY+VnlW9VbXrEnWXOss623WV2xQG1ebDJs6m8u2qK2brcR2m23fFOIUjynSKfVTbtox7PzsCuya7AbtOfZh9iX2bfbPHcwcEh3WO3Q7fHJ0dcx2bHC866ThNMOpxKnD6VdnG2ehc53zNRemS5DLEpd2lxdTbaeKp26fesuV5RruutK10/Wjm7ub3K3ZbdTdzD3Ffav7TS6bG8ldwz3vQfTw91jicczjnaebp8LzkOcvXnZeWV77vR5Ps5wmntYwbcjbxFvgvct7YDo+PWX6zukDPsY+Ap96n4e+pr4i3z2+I37Wfpl+B/ye+zv6y/2P+L/hefIW8U4FYAHBAeUBvYEagbMDawMfBJkEpQc1BY0FuwYvDD4VQgwJDVkfcpNvwBfyG/ljM9xnLJrRFcoInRVaG/owzCZMHtYRjobPCN8Qfm+m+UzpzLYIiOBHbIi4H2kZmRf5fRQpKjKqLupRtFN0cXT3LNas5Fn7Z72O8Y+pjLk722q2cnZnrGpsUmxj7Ju4gLiquIF4h/hF8ZcSdBMkCe2J5MTYxD2J43MC52yaM5zkmlSWdGOu5dyiuRfm6c7Lnnc8WTVZkHw4hZgSl7I/5YMgQlAvGE/lp25NHRPyhJuFT0W+oo2iUbG3uEo8kuadVpX2ON07fUP6aIZPRnXGMwlPUit5kRmSuSPzTVZE1t6sz9lx2S05lJyUnKNSDWmWtCvXMLcot09mKyuTDeR55m3KG5OHyvfkI/lz89sVbIVM0aO0Uq5QDhZML6greFsYW3i4SL1IWtQz32b+6vkjC4IWfL2QsFC4sLPYuHhZ8eAiv0W7FiOLUxd3LjFdUrpkeGnw0n3LaMuylv1Q4lhSVfJqedzyjlKD0qWlQyuCVzSVqZTJy26u9Fq5YxVhlWRV72qX1VtWfyoXlV+scKyorviwRrjm4ldOX9V89Xlt2treSrfK7etI66Trbqz3Wb+vSr1qQdXQhvANrRvxjeUbX21K3nShemr1js20zcrNAzVhNe1bzLas2/KhNqP2ep1/XctW/a2rt77ZJtrWv913e/MOgx0VO97vlOy8tSt4V2u9RX31btLugt2PGmIbur/mft24R3dPxZ6Pe6V7B/ZF7+tqdG9s3K+/v7IJbVI2jR5IOnDlm4Bv2pvtmne1cFoqDsJB5cEn36Z8e+NQ6KHOw9zDzd+Zf7f1COtIeSvSOr91rC2jbaA9ob3v6IyjnR1eHUe+t/9+7zHjY3XHNY9XnqCdKD3x+eSCk+OnZKeenU4/PdSZ3Hn3TPyZa11RXb1nQ8+ePxd07ky3X/fJ897nj13wvHD0Ivdi2yW3S609rj1HfnD94UivW2/rZffL7Vc8rnT0Tes70e/Tf/pqwNVz1/jXLl2feb3vxuwbt24m3Ry4Jbr1+Hb27Rd3Cu5M3F16j3iv/L7a/eoH+g/qf7T+sWXAbeD4YMBgz8NZD+8OCYee/pT/04fh0kfMR9UjRiONj50fHxsNGr3yZM6T4aeypxPPyn5W/3nrc6vn3/3i+0vPWPzY8Av5i8+/rnmp83Lvq6mvOscjxx+8znk98ab8rc7bfe+477rfx70fmSj8QP5Q89H6Y8en0E/3Pud8/vwv94Tz+4A5JREAAAAGYktHRAD/AP8A/6C9p5MAAAAJcEhZcwAACxMAAAsTAQCanBgAAAAHdElNRQfcAgcQLxxUBNp/AAAQZ0lEQVR42u2be3QVVZbGv1N17829eRLyIKAEOiISEtPhJTJAYuyBDmhWjAEx4iAGBhxA4wABbVAMWUAeykMCM+HRTcBRWkNH2l5moS0LCCrQTkYeQWBQSCAIgYRXEpKbW/XNH5zS4noR7faPEeu31l0h4dSpvc+t/Z199jkFWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhY/H9D/MR9qfKnLj/00U71aqfJn9+HCkCR/Wk36ddsgyJ/1wF4fkDfqqm9/gPsUeTnVr6a2xlQfnxdI7zs0W7irzD17Ytb2WT7EeNv/r4ox1O3Quf2QP2pgt9utwfout4FQE8AVBSlnaRmfvAURQkg2RlAbwB9AThlW5L0GaiKojhJhgOIBqDa7XaPrusdPtr5kQwF0BVAAoBIABRCKDd5aFUhRDAAw57eAOwAhKIoupft3zoqhB1AqLwuHIBut9uFt02qqvqRDJR2dAEQJj/BAOjn56dqmma+xiaECAEQAWAggLsB6A6HQ2iaZggBhBAqgEAAnQB0kzaEmT4hAITT6VQ8Ho/HJAKKECJQtr8LwD1y/A1/vcdfEUIEyfZ9AcQbYvZ942Px88L2UwlJR0dH0EMPPbRj5syZPUeNGrXR7Xb/641xIwJ1XY9NSUlZm52dfW+XLl1w8uRJzJ8//+OGhoYJqqqe1TSt1Wsm9NN1PSIqKmr12rVrR5WUlHy1bdu2AQCumWc3IYRD1/UwVVXnFRQUTIuNjUVzczN2797dWFJSkq8oymZd15sAGAEnFEUJ1nX9nzIzM1dnZmZGh4SE4OTJk5g5c+Zf29vbp9pstrMej6fVOyhIhgAYU1hY+B+hoaGoqKg4XVlZea+XTULTNFdCQsLGiRMnPuR2u3UhBOV9eeDAAWXTpk095DUe6WsoyRE5OTlr0tLSAux2O/bs2cO5c+e+pijKUpIXSHaQVAGkvPLKK++6XK4OksJLCFlXV2cvKSlJBFAjhU+x2WwhHo9nUHp6+urMzMy7wsLCUF9fjxdffPHjxsbGiTab7WuPx9NiEutOuq4PyMjI+M+srKyYqKgoHD58GDNmzNjq8XhyVFU9b/q+LH7hBAEYu3PnTlZVVRFAGgCX6f/tAHoOHDjwa0p27txp/JO9e/f+QM7cipw9nfL3kQBKt2zZQpJ87rnn6mQmoHilw2EACs+cOUOSrK+vZ1NTE0nyo48+IoBpxswoBcMJ4Ndjx471kOTFixe5d+9ekqTH42H//v13A4jyzpAURfEH0H/OnDnthu1z5sw558MmFUCPWbNmnaMP3nrrLZoyDmP8Hl68eDFJ8siRI9/Yc+zYMQKYKdtAztrTrl27xptRXV1NAKMAOAyBBBA/Y8aMdpLs6Ojgxx9//E37+++//29yvFXppwvAwMcee8xjtDHsuXLlCqOjo//ia3wsfpkoALqFhoZuIckJEyackimm3dQmEMDUmpoakmRISMhhAHOHDx/eQJIbN24kgKEyMAHAFRMTs2XXrl1saWkhSZ0kp0+ffhrAr3wEW/S8efOukORLL72kA1gKYMPWrVtJkk899dRJAHeYrgsEsIQkjx8/TgDvAPjd448/3kaSb7zxBmUa7vC6z53BwcFbSHL9+vU6Sc6aNes8gF5ewWAH0PfVV18lSQL4DMBGIcQ6AKtcLleBFC2jXtFt8ODBe0iyoqKCAJYByC8qKmJDQwOzsrK+MAmqo1OnTveHhoa+GRkZ+XZkZOSWiIiIvzgcjk9mzpypkWRmZuZpmbYbGV4AgPnNzc1sa2sjgN0A5iQmJtaSZHl5OQHcb/K3s81mW0uSTU1NBFAFYFbfvn1Pk+Tbb79NAA8IIVzW42/hByA+Pz/fLR/2ZXIda05NI/z9/TeR5J49ewhgqlxTrtI0jY2NjQQw3zTLuWJiYjaUlJToS5Ys6fjkk080kwDEeAmADcA9GzZsIElGRUW9CyAWwLApU6Y0kOSKFSsog9QICGdERMTGsrIyZmVlEcC9AB4IDw/fTpLbtm0jgN94CUAnAJmVlZVcs2aNZ/LkyRdJcvbs2b4EwAkgZfPmzTxw4AABFAN4BkC6vFeUSewcAO5duXIlSTIhIaEawGMAxgKYAmAGgCS73e5vrKVk/yGythANYEhCQsIhkly+fDkBpKqqGmL6DgIALDKN/3yZpVWQZGVlJQE8aPI3KiMjo5okV61aRQAjAPQBMPfIkSN0u90EUCBtsPiFEwpgbn19PdetW2fM5N4zQ9ekpKQqkty0aRMBpMjiWM6JEydIkoqirJUFJ6iq6pAPVy8A6cZMehMBUACEuVyuFwG8HBwcPEIWx367ZMkSjSQXLVrUJouTRorrkAHdA8BdQogsAOsKCwtJkmPGjDkvMw2bDDo/ADEjRoz4XylyFbm5uY0mAbjLyyZ/AOOrq6tZVlbWsWDBgo69e/eyoqKCgwcPPg4gSQaoIRbp27dvN7KF+tLSUr28vJwFBQXtMpvpYRIM7+wrAkDeqVOnePbsWQIoNKfzpiXPg8uXLydJJicnNwF4f+nSpW6STEtLq5fjYwhk1wkTJtSQ5Ouvv04AqTKj+N2xY8dIkgEBAW/Ie1v8wncRegwZMmQvSfbr12+3Ua33WqPfOWbMmP0kWVpaSgCDZAqcfejQIWNZsEGKgvnh9gfQb9myZd8nAEJVVZtMkUNk8CcNHTq0liR1XWdYWNhmH1mJIme80OnTp18x1rp5eXkEsNJms92Fb7e/IgEsvHz5Mp999tkmAI/l5uZeMC0B7vEqqAYAyL106RJJsra2lpWVld+sucePH38ZQG+5NncBeOrgwYMkqbe3t/Po0aOsra011wAWyl0H7x0JJ4DE+fPnu0kyPT29DsDdUrBuyNKEEAkAdpw/f/6GeoEM8GUmfwEgPCIiopwkGxsbabPZPgOw6L777vvm4p49e26VGYjFLxUhhD+ApLKyMp44ccIoVnXybgbgzkcfffRzklyzZg0BDJYCMMmoCwQFBXkLgLGWvvcWAgBToSsKwNPTp09vMR7UuLi4rwH0lgU8c/Db5ezbeeTIkRWzZ8++aMxu+fn5BPCADBwHgP4LFy701NXVEUAJgAnPP/98kyxMNgHo53A4zH77BQQETMvPz7+Um5vbBuAlAFMSExPPmdbVL0qh8Acw8fDhw5SCchVAEYAVb775JknyhRdeaJYztHfxMwLAaqNwCGC2FArv8x0hAHKNLGPKlCme5OTk/Zs3bzb7O0wKiiG8KXl5ed8IxenTp0mSR48e1UmyW7duWywBuD2xyQcgFECgoih+8H1gyJgZV5Lkyy+/3CbTRIePtl2HDBmyw1QBHyGDdXZdXR1JUghRKkXBjOMHCoBdpr0L3nvvPZLkF198wejo6O0A4lVVDTb74HQ6AwD8Wq7Jh8rgGgDgQ13XjVR8qaxJuADMbmlpYXl5uV5UVNRWUFDgfv/993Vj/ZydnU1c37eHXML4S3viAcQqitJD2l104cIFY8lTKsXSBWBMVVWVcd9yed2A1NTUQ6Zl00CvLMMOoHdubm6zFIlWOf5+PsY/Kj09vdrU11QAwwGsv3jxIk21m2DZr10I0RXAuAcffPBgaWkpV69eTYfDcdiwUxY0w6xw+flX8L1xApjevXv3lREREaW6rofB93aPDUDQpEmTMgHgtddeqwBwEd/utZvpqK6uPgEAcXFxkA94NwB9unfvjrNnz4LklwDcf08iIqv66Zs2bXrl4YcfxooVKxAbG7uqrq5uAYA2TdOEqqpGYIi2tjbl6aeffu/YsWPv5uTk7JaC1wHg4Pnz542MwoVvTx+21dbWYvjw4WLixIl+2dnZ9lGjRgmSTE1NRUpKCkwFTGiaxtTU1OXTpk3707Bhw/6g67pDipnT4biuj7qut+Lbk3Vf1tTUXI9qu91Pjq1QFEUBgJaWFgBo8yGOQ8eNGxcAAOvXr/8QwBUfYygAKL169eoCABcuXACAWtn2hOGv0+kMNO1KiPDw8F4A4rZv3/7R1KlTR0+bNu1ht9u9r1+/fqitrQXJgwDarRC6/QjPzs4+QJIffPCB9/aQmSAA43ft2mW0e1QGoi8CAPyLsZccExNTC2BlRkbGRdOyYJCP2csBIN6UAZzCd7cBbQCijYp/dXU1ExMTz6SmptaMHj36f9LS0vYlJCRsl6mxIWSdu3fv/g5J7t+/nwC2AShMTk6+SJKff/45AWRLYbD7+fndAeDf5BJnLoCCyZMnt5JkdnZ2C4B/F0KEm1Pu+Pj4rST55ZdfEsBWAK+mpaVdMo3raDn7KwDuSEpK+m+S3LBhAwG8DuCtHTt2UBbpjgC408vvcFVV15HkuXPnjMp+p5uMf0RcXNyHJNnQ0EBVVfcCWBQXF3fG+Jv0yxABPwB5LS0tRmFxN4BlTzzxxGWSXLx4sS5F3GGFy+1Hp5SUlJq6ujoWFxdTpsZ2H+0iIyMj/0iSWVlZX5mr5jfJFroPGzasxlhTnjp1iiTZ3NxMl8tlrCd9pfa9SkpKSJI5OTmnZOageLUZZqxvfVFWVkZcPwdgNwnSCKPqb17jkmR8fPzfZMDZ5CRsFBmNI7h95s2b1yhT7/MAYmStwCx4vy0uLqa3v5qmEcCfvSr1QQAeXb16NY3Cm3HQ55133iGAp+SxZTNhKSkpfzUddkrFjYevzAQCeGjp0qXfsYckY2NjTwD4leGDLCL2HTdunNtoY+zWSHFcIHdsFCtcfuZ1vO9Eqs3m7/F47sb1k2qX/f3997W2tl7BjWfpBYDOzzzzzIVJkyZh0KBBCwEsB3AJvl9AETabLcDj8dwRFRW1ctasWb8JCgpSzp07d62wsPC/Wltb8xRFadR1/ZqPXYbgAQMGbI2Pjw/+6quv9ldVVT0r01ezuPRJSUn5Y9euXXVd11WzDaqq6kePHm3+7LPPRgO4KlNuxWazhXo8nuTk5OSXMjIyEl0uFxoaGtqKior+dPXq1VdUVT0jj7r68ieoT58+vx8yZMjdx48fP1JVVTVF9m20VW02WyfZf97YsWPjXS4X6urqWvPy8jYCWCyEuEDS8FdVFKWzruv//OSTTy5OTk7uqWkaPv3007qysrJ8RVH+LI8ym8/rB3Tu3HnRI488knLo0KG2ffv2ZQI4C98vP6mqqoZqmpaclpa2cOTIkX39/f3R0NDQUVxc/G5TU9PLqqrWa5rWLH1QVFUN0TStX1JSUvH48eP7BwYG4uDBg1cKCgpeBbBe2u+2Qug2EwD5N5sMPuNtMe8XP4TT6Qxoa2sbIGeXvUKIK7d4IISiKC5d1wPljOfA9bPwzYqiXNV13dd6Uqiq6qdpml2mpe02m63d4/G4vcTF5fF47LJf71nJA6BZVVW3pmntuPHlmAD5wk6Q9NnbHp9vHaqq6tA0zU/64PZhk1FfCZB9G/23ALiqKEqzD39tpvbGUqoFwFUhRLP3yzpCCDtJpxyXDulfG27+pqRR3DXsUWVd4Yq0x/taVQjhIhksC8L+ABpM9ljBf5sKwI8pIBr75L5E4vvu+UNeG/a+hv+AL7yFH8qPtOfHjtOP6V/Bja8D6z/B2Nys/1u9Xv33tLf4GfF/LC4GCJwByWIAAAAASUVORK5CYII=";
diff --git a/cocos2d/CCLoader.js b/cocos2d/CCLoader.js
index 6bfa53e296..6e62d676a1 100644
--- a/cocos2d/CCLoader.js
+++ b/cocos2d/CCLoader.js
@@ -416,6 +416,7 @@ cc.LoaderScene = cc.Scene.extend(/** @lends cc.LoaderScene# */{
var _this = this;
this._logoTexture.addEventListener("load", function () {
_this._initStage(centerPos);
+ this.removeEventListener('load', arguments.callee, false);
});
this._logoTexture.src = "data:image/jpeg;base64,/9j/4QAYRXhpZgAASUkqAAgAAAAAAAAAAAAAAP/sABFEdWNreQABAAQAAAAlAAD/4QMpaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wLwA8P3hwYWNrZXQgYmVnaW49Iu+7vyIgaWQ9Ilc1TTBNcENlaGlIenJlU3pOVGN6a2M5ZCI/PiA8eDp4bXBtZXRhIHhtbG5zOng9ImFkb2JlOm5zOm1ldGEvIiB4OnhtcHRrPSJBZG9iZSBYTVAgQ29yZSA1LjAtYzA2MCA2MS4xMzQ3NzcsIDIwMTAvMDIvMTItMTc6MzI6MDAgICAgICAgICI+IDxyZGY6UkRGIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyI+IDxyZGY6RGVzY3JpcHRpb24gcmRmOmFib3V0PSIiIHhtbG5zOnhtcE1NPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvbW0vIiB4bWxuczpzdFJlZj0iaHR0cDovL25zLmFkb2JlLmNvbS94YXAvMS4wL3NUeXBlL1Jlc291cmNlUmVmIyIgeG1sbnM6eG1wPSJodHRwOi8vbnMuYWRvYmUuY29tL3hhcC8xLjAvIiB4bXBNTTpEb2N1bWVudElEPSJ4bXAuZGlkOjM4MDBEMDY2QTU1MjExRTFBQTAzQjEzMUNFNzMxRkQwIiB4bXBNTTpJbnN0YW5jZUlEPSJ4bXAuaWlkOjM4MDBEMDY1QTU1MjExRTFBQTAzQjEzMUNFNzMxRkQwIiB4bXA6Q3JlYXRvclRvb2w9IkFkb2JlIFBob3Rvc2hvcCBDUzUgV2luZG93cyI+IDx4bXBNTTpEZXJpdmVkRnJvbSBzdFJlZjppbnN0YW5jZUlEPSJ4bXAuaWlkOkU2RTk0OEM4OERCNDExRTE5NEUyRkE3M0M3QkE1NTlEIiBzdFJlZjpkb2N1bWVudElEPSJ4bXAuZGlkOkU2RTk0OEM5OERCNDExRTE5NEUyRkE3M0M3QkE1NTlEIi8+IDwvcmRmOkRlc2NyaXB0aW9uPiA8L3JkZjpSREY+IDwveDp4bXBtZXRhPiA8P3hwYWNrZXQgZW5kPSJyIj8+/+4ADkFkb2JlAGTAAAAAAf/bAIQADQkJCQoJDQoKDRMMCwwTFhENDREWGhUVFhUVGhkUFhUVFhQZGR0fIB8dGScnKionJzk4ODg5QEBAQEBAQEBAQAEODAwOEA4RDw8RFA4RDhQVERISERUfFRUXFRUfKB0ZGRkZHSgjJiAgICYjLCwoKCwsNzc1NzdAQEBAQEBAQEBA/8AAEQgAyACgAwEiAAIRAQMRAf/EALAAAAEFAQEAAAAAAAAAAAAAAAQAAgMFBgcBAQEAAwEBAAAAAAAAAAAAAAAAAQMEAgUQAAIBAgIEBwoLBgQGAwAAAAECAwAEEQUhMRIGQVFxsTITFGGBwdEiQlKSMzWRoeFicqKyI1NzFYJjJDQWB9KjVCbxwkNkJWXik3QRAAIBAgMFBQcDBQEAAAAAAAABAhEDIRIEMUFRcTJhwVIUBZGhsSJyEzOB0ULhYpIjUxX/2gAMAwEAAhEDEQA/AMJSpUqAVKlXuFAeUq9wpUB5XuFe4V6ooDzZHDox0CnGMinzwl7Z8NajaHeoO3vmTBZBtp9YUIqTEV5ROxHKnWRnaU8VRMhFBUjpV7hSoSeUq9pUB5Sr2lhQHlKvcK8oBV7hSFSRrtaKAZs07YNPM1pG2xJIAw1jSeandry/8X4m8VCKkWwaWwam7Xl/4v1W8VLtmX/i/VbxUoKkWwakSM407tmX/i/VbxUmzGwjQsjdY41IARie/U0IbZO0kNtCXnOCkEBeFu4KI3Bs7DNb27ya+jDx3kJeEnpJJEcQVbWDsk17u5urd591ucZkWhym2Vnd9RkCDEpFxDRpbw0bunu5mlp2De2FMLYXOD2wB2xbOeraUcYGJ72mlSUiqzzdzMd3Z3mixltA2yzcK/NlHM1DQyRXce1HocdNOEfJXZ88y9ZojOqhiBszIRiHQ8Y4cK5TvHuzLljHNMqxNoDjLFraHHnjPxcNCGVbxEUzYNTx5jZSxhpW6qTzlwJ+DCvO2Zf+L9VvFSgqyHYNLYNTdssPxfibxUu15f8Ai/VPiqCakOwa82DU/a8v/F+JvFTDdWPBL8R8VKCvYRYV5UzoMAy6QdIIqI0B4KJtxiRQwou16QoGUkntH5Tz0RbZbmF2hktraSVBo2lUkY8tDye0flPPXTslVUyiyVRsjqUOA4yMT8dW2ram2m6UVTNq9S7EIyUVJydMTn/6DnP+im9Wl+g5z/opvVrpteEhQWY4AaSTwAVf5WPiZh/9S5/zj7zltzlmYWkfWXNvJDGTgGcYDHirR7i7mSbwXParsFMrgb7w6jKw/wCmnc9I14kF3vpvCljbMyWMOJL4aEiB8qU/ObUK7HYWVrl1pFZWiCOCBQqKOLjPGTrNZZqKbUXVHq2nNwTuJRk1VpbgXN8s7Rk5ym0UQQzhIG2NAjhxHWbI+gCBVjBBFbwxwQqEiiUJGg1BVGAFe7dV28WYLYZFmF2Th1UD7JGjymGyn1iK5OyzIBGB1HgrLZhamzumQAGJwSqnSCh1q3GOCodxt4cxurdcpzuN4cyhiWaF5Bg09udUmnWw1H/jV9nFuJ7Quo+8h8peThFA+047vduyMtk7fYqTl07YFdfUufMPzT5p71UdtlmYXaGS2t3mQHAsgxANdadYJopLe4QS2867EsZ4QfCNYrCFbjdDPmgkYyWFxgVf04ifJf6ScNdRUW1XBb6FU5TjF5EpSSrGu/s5lN+g5z/opvVpfoOc/wCim9WtdHnatvObJXDW7xLGhB8nrPaY9/HCr+tEdPCVaSeDoYLnqF63lzW4/PFSW3ecxbI84VSzWUwUaSdg0DXXK5nvAipnd6qgKvWnQO7pri9ZUEmm3Vl2j1kr8pRlFRyquBNZjGxQ/S56Y1S2fu9OVueon11Szahoou06QoQUXadIVCD2FJJ7R+U89dMydv8Axdn+TH9muZye0flPPXQstlK5Tbka1gUjlC1q0vVLkeb6r+O3Tx9xcY1nt8c0NrZCyiOE1108NYjGv1joo7Js1jzKyScYLIvkzL6LDwHXVJksH9Sb49dKNq0tj1jA6uriOCL+02FWX7iVtZX1/AzaHTyeoauKn2MX9W79zebiZCuR5MjSrhfXuEtwTrUeZH+yNfdrRNcxI6IzhXlJEak6WIGJ2Rw4ChWnChndtlVBLMdQA0k1gbXNMzzDfDLs6mjaPKppJbWwJ1bOwwxw43OnHh71YT3DpfWUJmFlb5jHHDdeXBHIsrRea5TSqvxqG04cNN62vetoCS4tre5mgnkGE9q+3DKOkuI2WX6LDQRRHWDh1UCtwj7QRg2wdl8Djgw1qe7XvW0BQ3kfZ7mSLgU+T9E6RVbnuVrnWVSWqj+Lt8ZbRuHEdKPkYVcZ2MJY5fSGyeVar45+rkWQHAqccalPE5km1htWK5nK4Wnt5FuUBUwOMG4nGkA/BXUrW4S6torlOjMgcd/xVn7rLo7zKs0uEjCNeSvdwoBhgsZxX1l2j36k3Lu+uyprdj5Vs5A+i/lD48a0aaVJOPi7jB6lbzWozpjB48pf1NDXNN4vfl7+Z4BXS65pvF78vfzPAK71XTHmZ/S/yT+jvJ7L3fHytz1E+upbL+Qj5W56jfXWRnsIYKLtekKEFGWvSFQgyjk9o/Keet3YthlMP/5x9msJJ7R+U89biyb/AMXEv7gD6tadL1T+kwepRrC39ZkLDMbiwMvUHRPG0bjlGg8ore/23sxBldxfMPLupNhT8yL/AORNZbdzJ484scytxgLqJY5LZj6Q2sV5G1Vud1mjjyG0ij0NEGSZToKyhjtqw4waztuiXA3qKTbSxltfGhbZlE95ZtZqxVbgiOZhrER9ph3Svk9+pJILZ4Y4DGBFCUMKjRsGPobPFhUfW0NJmljE2xJcIrcI2vFUEln1lRXd6lrazXT9GCNpD+yNqoI7mOVduNw6nzlOIoPOUa6yye1XXcbMR5GdQ3xY0BSbj31/FcTQZirJ+q431q7anbHCTZ72Bw7lbPrKBMcBWNNgbMBBh+bsjBdni0VJ1lARZs6yWiupxCuMDy6KpS2IwOo6DTr3Mre3e5tZZVUM4ZBjqOOJoWO4jkXajcOOMHGgDISvWIrdAkKR80+TzVl908bPPL3LzxOuHdifxVfiTAg92qI/w+/8gGgSyN/mR7XPVlp0lF/3L3mbVKtu5Hjbk/8AHE2Fc03i9+Xv5ngFdKNc13i9+Xv5ngFaNV0x5nn+l/kn9HeEWXu+PlbnqJ9dS2Xu9OVueon11kZ7CGCjLXpCgxRlr0hUIPYUcntH5Tz1s8vb+Bt1/dqPirGSe0flPPWusG/g4Py15q06XqlyMWvVYQ+ruI9xJOqzO9hOto/sP8tbGOFIrmWeM7IuMDMnAXXQJOUjQeOsJk0nY96ip0CYunrjaHx1t+srPJUbXBm2LrFPikwTOb+T+VhbZxGMrDXp83x1QSy2tucJpUjPETp+Cn5/ftaRvKvtp3Kx48HG3erHMzOxZiWZtLMdJNQSbbL71Vk6yynViOkqnEEfOWtPbXi3EQkGg6mXiNckjeSJxJGxR10qw0GtxuxmvbImD4CZMFlA4fRfv0BqesqqzTMZNMEDbIHtHH2QeCiZJSqMQdOGiue53mz3czQwsRbIcNHnkec3c4qAMuriz68gTIToxwOOnlp0MjxMJYW741Gs3RVldtbygE/dMcHX/moDaxTiWNZB53B3arb8/wC+4SOF4sf/AKxU9kcBsfOGHfoUHtG/RbzY5Die5HHhXdvavqiZ9Q8Jdlq4/gbKua7xe/L38zwCuhpf2Uk/Zo50kmwJKIdogDjw1VzzeL35e/meAVp1LTgqY4nn+mRauzqmqwrjzCLL3fHytz1E+upLL+Qj5W56jfXWRnroYKLtekKEFF2vSFQg9hSSe0flPPWosm/hIfoLzVl5PaPynnrRWb/w0X0F5q06XqlyM2sVYx5gmbFre/t71NY2T+0h8VbSO5SWNJUOKSAMp7jDGspmMPaLRlXS6eWve1/FRO7WYdbZm1Y/eW/R7qHxHRXGojlm3ulid6aVbaW+OALvgCLq2Hm9WxHKWqjhj6xsK1e8dm15l4niG1LZkswGsxtrPeOmsvayBJA1VItlWjptLuTdPMo7LtjRDq9naK4+WF9IrUW7BaHOljGqVHB7w2hzVoZt87d8vaNYSLl02CcRsDEbJbj71Uu7UBkvJ7/D7q2QoDxySaAO8MTXdxRVMpRp5XZOWdF/ms7R5XdyKfKWJsO/5PhrG5XlNxmEywW6bTnTxAAcJNbGSMXkM1pjgbiNo1PziPJ+Os7u7m/6ReM00ZOgxSpqYYHT3wRXMKN4ll9zUG4bQfNshu8sZVuEA2hirA4qe/VOwwrVbzbww5mI44UKRRYkbWG0S3JWctbd7u5WFfOOLHiUdJqmaipfLsIsObhWe001lMkMVvJNjhghIALMcBxCs7fxXQmkupx1bXDswGPlaTidVaEyKNXkoo4eBV+Sq7L7Vs9zcBgeyQ4GQ/MB1crmoim2orezqcowTuSeEY48jQ7oZX2PLzdyLhNd6RjrEY6I7+uspvH78vfzPAK6UAAAFGAGgAcArmu8Xvy9/M8ArTfio24RW5nnaG67uou3H/KPuqT2X8hHytz1G+upLL3enK3PUb66ys9RDBRdr0hQgou06QqEGUkntH5Tz1e238vF9BeaqKT2j8p56vbb+Xi+gvNWjTdUuRn1XTHmTh8KrJTJlt8t1CPIY44cGnpJVjTJYkmjaN9Ib4u7V923njTethRauZJV3PaW1rfLIiXEDYg6R4VYc9CXW7thfOZbKdbGZtLW8uPVY/u3GrkNUkM9zlcxUjbhfWOA90cRq4gv4LhdqN+VToNYWmnRm9NNVWNTyHc6VWBv8wt4YeHqm6xyPmroq1Z7WGFLSxTq7WLSuPSdjrkfumq5yHXDUeA92oO2SKpVumNAaoJLMXH3myp0rpJ4uKhc3tbDM5BMri1zAj79j7KTiY8TcdBpcsith0286o+sPCagEX9Pzg4zXUCp6QYse8oouCG3tk6m1BYv05W6T+IdyolxbHDAAa2OgDlNCz3ryN2WxBd5PJMg1t81eId2ukqnLlTBbfcuY+9uJLiRcvtPvHdsHK+cfRHcHDWsyawjyy0WBcDI3lTP6TeIcFV+S5OmXx9bJg1048o8Cj0V8Jq2DVu09nL80up7OxHi+oal3P8AXB/IsZS8T/YOV65zvCcc7vfzPAK3ivWCz445zeH954BXOr6I8yfSfyz+jvCLP3fHytz1G+upLP3fHytz1E+usbPaQ0UXadIUIKLtekKhB7Ckk9o/Keer22/l4/oLzVRSe0flPPV7b/y8X0F5q0abqlyM+q6Y8yQsBTDMor1o8aiaE1pbluMqS3sbLLHIhSRQyngqukhaJ9uBjo+H5aOa3ao2t34qouRlLajTalGP8v0IY8ylXQ+PKPFU/bYXOLPge6CKia0LaxTOxHu1Q7cuBd9yPEJ7TbjXKO8CajbMIF6CNIeNvJHjqIWJ7tSpYkalqVblwIdyG+RGXur0hXYJFxal+Dhq5y3slkv3Y2pD0pTr+QUClpJRUdo9XW4OLrTHtM16cZLLWkeC7y4jvlNEpcRtw1Ux27Ci448NZrTFy3nn3IQWxlgGrDZ3pza7/M8ArZo+ArF5171uvp+CqdV0R5l/psUrs2vB3hdl7vTlbnqJ9dS2Xu+PlbnqJ9dY2eshooq16QoQUXa9IVCD2FLJ7RuU89WNtmUSQqkgYMgw0accKrpPaPynnrZWG4Vi+VWmY5tnMWXG+XrIYnA0rhj0mdcTgdNdwnKDqjmduM1SRR/qlr8/4KX6pa8T/BVzDuLZXudRZblmbxXcPUNPc3KqCIwrbOzgrHEnHjoyD+3eSXkht7DeKG4umDGOJVUklfouThXfmbnZ7Cvy1vt9pmv1W1+d8FL9VteJvgq5yrcOGfLmzHN80iyyETPbptAEFo2ZG8pmUa1OFNn3Ky6W/sbDKM5hv5bx2WTZA+7RF2y52WOPJTzE+z2Dy1vt9pT/AKpacTerS/U7Tib1a04/t7kDXPY03jhN0W6sQ7K7W3q2dnrMccaDy/8At80kuZfqWYxWNtlcvUPPhiGYhWDeUy7IwYU8xPs9g8tb7faUn6pacTerTxm9oOBvVq3v9z927aynuId44LiWKNnjhAXF2UYhRg516qpsryjLr21665zFLSTaK9U2GOA87SwqY37knRU+BzOzags0s1Oyr+BKM6sxwP6tSDPLMen6vy0rvdm3Sxlu7K/S7WDDrFUDUTxgnTU826eXW7KlxmqQuwDBXUKcD+1Xee/wXuKX5XDGWLapSVcOyhEM/seJ/V+WnjeGx4pPV+Wkm6kKZlFay3Jlt7iFpYZY8ASVK6DjtDDA0f8A0Tl340/1f8Ndx8xJVWXB0KbktFFpNzdVXAC/qOwA0CQni2flrO3Vwbm5lnI2TKxbDirX/wBE5d+NcfV/wVR7xZPa5U9utvI8nWhmbbw0YEAYYAVxfhfy5rlKR4Fulu6X7mW1mzT8S4Yis/5CPlbnqJ9dSWfu9OVueon11mZvQ2i7XpChKKtekKhBlNJ7R+U89bDfGTb3a3ZX0Lcj6kdY+T2j8p560288m1kWQr6MJ+ylSAr+2cnV5renjs3H1loX+3j9XvbbtxLN9lqW4UnV5jdnjtXHxihtyZNjeSBu5J9k1BJe7xy7W5CJ/wCzuD/mTVTf2+fq97LJuLrPsNRueS7W6aJ/38x+vLVXuY+xvHaNxbf2GoCezf8A36j/APsSf8w1sLnqczTefJluYoLm5uo5F61sBshItP1cNFYe1f8A3ir/APfE/wCZUe9bB94r5jwuPsrQFhmG4l/Z2M17HdW90tuu3IkTHaCjWdIw0VVZdks9/C06yJFEp2dp+E1bbqybGTZ8vpQD7L1XRv8A7blT96Oda7tpNuuNE37Cq9KSisjyuUoxrStKllHbLlWTXsMs8chuSuwEPDqwoLe5y+YRE/gLzmqRekvKKtd4327yM/ulHxmrHJStySWVRyrjxKI2XC/CTlnlPPKTpTdFbP0L1bgrf5Lp0G3dPhQHwV0S1lzBsns3sESR8Crh9WAJGjSOKuU3E+zdZQ3oJh8IArdZXFDmOTpHa3i2+YrI2KtKy4ricBsBuHHgFXSo440+Wa2qqxjvM9uMoy+WvzWpLCWWWE28HxL6e43ojgkeSCBY1Ri5BGIUDT51cl3vm276BBqSEH4WbxV0tlkyXJcxTMb+OW6uY9mGHrCzDQwwAbTp2uKuTZ9N1uYsfRRR8WPhrm419mSSjRyiqxVK7y23B/ftuTm2oSdJyzNVw3BFn7vTlbnqF9dS2fu9OVueon11lZuQ2iLdsGFD05H2dNQGV0ntG5Tz1dWm9N1b2kVq8EVwsI2UaQaQOKhmitZGLOmk68DhSFvY+gfWNSAg7z3Qvo7yKCKIohiaNR5LKxx8qpxvjcqS0VpbxvwOAcRQPZ7D0G9Y0uz2HoH1jUCpLY7zXlpbm3eKO5QuzjrBqZji3x17PvNcyT288VvDBJbMWUovS2hslW7mFQ9nsPQPrGl2ew9A+saCod/WNxtbYsrfb17WBxx5ddD2281xC88klvDcSXEnWuzrqOGGC9zRUPZ7D0G9Y0uzWHoH1jQVCLreq6ntZbaO3it1mGy7RjTs1X2mYy20ZiCq8ZOODcdEdmsPQb1jS7PYegfWNdJuLqnQiSUlRqpFLmryxtH1Ma7Qw2gNNPOdSt0oI27p007s9h6B9Y0uz2HoH1jXX3Z+I4+1b8IJdX89xLHKQFMXQUahpxoiPN5P+onfU+A0/s9h6DesaXZ7D0D6xpG7OLbUtu0StW5JJx2bBsmbtiSiEk+cxoCWWSaVpZOk2vDVo0VYdnsPQb1jSNvZcCH1jSd2c+p1XAmFqEOmOPEfaH+BQd1ueo211IzrgFUYKNAAqI1WztCpUqVCRUqVKgFSpUqAVKlSoBUqVKgFSpUqAVKlSoBUqVKgFSpUqAVKlSoD/9k=";
this._logoTexture.width = 160;
diff --git a/cocos2d/platform/jsloader.js b/cocos2d/platform/jsloader.js
index d8546fd53d..df804a8cd5 100644
--- a/cocos2d/platform/jsloader.js
+++ b/cocos2d/platform/jsloader.js
@@ -267,26 +267,28 @@
if(p>=1) {
loadJsImg.parentNode.removeChild(loadJsImg);
}
- }
+ };
var loaded = 0;
var que = engine.concat(c.appFiles);
que.push('main.js');
+
if (navigator.userAgent.indexOf("Trident/5") > -1) {
//ie9
- this.serial = -1;
+ var i = -1;
var loadNext = function () {
- var s = this.serial + 1;
- if (s < que.length) {
+ i++;
+ if (i < que.length) {
var f = d.createElement('script');
- f.src = que[s];
- f.serial = s;
- f.onload = loadNext;
+ f.src = que[i];
+ f.addEventListener('load',function(){
+ loadNext();
+ updateLoading(loaded / que.length);
+ this.removeEventListener('load', arguments.callee, false);
+ },false);
d.body.appendChild(f);
- //TODO: code for updating progress bar
}
- var p = s / (que.length - 1);
- updateLoading(p);
+ updateLoading(i / (que.length - 1));
};
loadNext();
}
@@ -295,15 +297,12 @@
var s = d.createElement('script');
s.async = false;
s.src = f;
- s.onload = function () {
+ s.addEventListener('load',function(){
loaded++;
- //TODO: code for updating progress bar
- var p = loaded / que.length;
- updateLoading(p);
- };
+ updateLoading(loaded / que.length);
+ this.removeEventListener('load', arguments.callee, false);
+ },false);
d.body.appendChild(s);
- que[i] = s;
-
});
}
})();
diff --git a/cocos2d/textures/CCTextureCache.js b/cocos2d/textures/CCTextureCache.js
index e59158e110..f1abdbaaaa 100644
--- a/cocos2d/textures/CCTextureCache.js
+++ b/cocos2d/textures/CCTextureCache.js
@@ -43,9 +43,10 @@ cc.loadImage = function (imageUrl) {
}
var image = new Image();
image.src = imageUrl;
- image.onLoad = function (e) {
+ image.addEventListener('load',function(){
cc.TextureCache.getInstance().cacheImage(imageUrl, image);
- };
+ this.removeEventListener('load', arguments.callee, false);
+ },false);
};
/**
@@ -287,6 +288,7 @@ cc.TextureCacheCanvas = cc.Class.extend(/** @lends cc.TextureCacheCanvas# */{
image.addEventListener("load", function () {
texture.handleLoadedTexture();
that._addImageAsyncCallBack(target, selector);
+ this.removeEventListener('load', arguments.callee, false);
});
}
} else {
@@ -298,12 +300,16 @@ cc.TextureCacheCanvas = cc.Class.extend(/** @lends cc.TextureCacheCanvas# */{
if (that._textures.hasOwnProperty(path))
that._textures[path].handleLoadedTexture();
that._addImageAsyncCallBack(target, selector);
+ this.removeEventListener('load', arguments.callee, false);
+ this.removeEventListener('error', arguments.callee, false);
});
image.addEventListener("error", function () {
cc.Loader.getInstance().onResLoadingErr(path);
//remove from cache
if (that._textures.hasOwnProperty(path))
delete that._textures[path];
+
+ this.removeEventListener('error', arguments.callee, false);
});
image.src = path;
var texture2d = new cc.Texture2D();
@@ -340,6 +346,7 @@ cc.TextureCacheCanvas = cc.Class.extend(/** @lends cc.TextureCacheCanvas# */{
image.addEventListener("load", function () {
texture.handleLoadedTexture();
cc.Loader.getInstance().onResLoaded();
+ this.removeEventListener('load', arguments.callee, false);
});
}
} else {
@@ -351,12 +358,16 @@ cc.TextureCacheCanvas = cc.Class.extend(/** @lends cc.TextureCacheCanvas# */{
cc.Loader.getInstance().onResLoaded();
if (that._textures.hasOwnProperty(path))
that._textures[path].handleLoadedTexture();
+ this.removeEventListener('load', arguments.callee, false);
+ this.removeEventListener('error', arguments.callee, false);
});
image.addEventListener("error", function () {
cc.Loader.getInstance().onResLoadingErr(path);
//remove from cache
if (that._textures.hasOwnProperty(path))
delete that._textures[path];
+
+ this.removeEventListener('error', arguments.callee, false);
});
image.src = path;
var texture2d = new cc.Texture2D();
@@ -698,6 +709,8 @@ cc.TextureCacheWebGL = cc.Class.extend(/** @lends cc.TextureCacheWebGL# */{
image.addEventListener("load", function () {
texture.handleLoadedTexture();
that._addImageAsyncCallBack(target, selector);
+
+ this.removeEventListener('load', arguments.callee, false);
});
}
} else {
@@ -709,12 +722,17 @@ cc.TextureCacheWebGL = cc.Class.extend(/** @lends cc.TextureCacheWebGL# */{
if (that._textures.hasOwnProperty(path))
that._textures[path].handleLoadedTexture();
that._addImageAsyncCallBack(target, selector);
+
+ this.removeEventListener('load', arguments.callee, false);
+ this.removeEventListener('error', arguments.callee, false);
});
image.addEventListener("error", function () {
cc.Loader.getInstance().onResLoadingErr(path);
//remove from cache
if (that._textures.hasOwnProperty(path))
delete that._textures[path];
+
+ this.removeEventListener('error', arguments.callee, false);
});
image.src = path;
var texture2d = new cc.Texture2D();
@@ -732,10 +750,15 @@ cc.TextureCacheWebGL = cc.Class.extend(/** @lends cc.TextureCacheWebGL# */{
cc.Loader.getInstance().onResLoaded();
that._loadedTexturesBefore[path] = texture;
delete that._loadingTexturesBefore[path];
+
+ this.removeEventListener('load', arguments.callee, false);
+ this.removeEventListener('error', arguments.callee, false);
});
texture.addEventListener("error", function () {
cc.Loader.getInstance().onResLoadingErr(path);
delete that._loadingTexturesBefore[path];
+
+ this.removeEventListener('error', arguments.callee, false);
});
texture.src = path;
this._loadingTexturesBefore[path] = texture;
@@ -770,6 +793,8 @@ cc.TextureCacheWebGL = cc.Class.extend(/** @lends cc.TextureCacheWebGL# */{
image.addEventListener("load", function () {
texture.handleLoadedTexture();
cc.Loader.getInstance().onResLoaded();
+
+ this.removeEventListener('load', arguments.callee, false);
});
}
} else {
@@ -781,12 +806,17 @@ cc.TextureCacheWebGL = cc.Class.extend(/** @lends cc.TextureCacheWebGL# */{
cc.Loader.getInstance().onResLoaded();
if (that._textures.hasOwnProperty(path))
that._textures[path].handleLoadedTexture();
+
+ this.removeEventListener('load', arguments.callee, false);
+ this.removeEventListener('error', arguments.callee, false);
});
image.addEventListener("error", function () {
cc.Loader.getInstance().onResLoadingErr(path);
//remove from cache
if (that._textures.hasOwnProperty(path))
delete that._textures[path];
+
+ this.removeEventListener('error', arguments.callee, false);
});
image.src = path;
diff --git a/extensions/PluginX/samples/HelloSocial/cocos2d.js b/extensions/PluginX/samples/HelloSocial/cocos2d.js
index f3f3a40733..851a010f79 100644
--- a/extensions/PluginX/samples/HelloSocial/cocos2d.js
+++ b/extensions/PluginX/samples/HelloSocial/cocos2d.js
@@ -60,6 +60,7 @@
window.addEventListener('DOMContentLoaded', function () {
+ this.removeEventListener('DOMContentLoaded', arguments.callee, false);
//first load engine file if specified
var s = d.createElement('script');
/*********Delete this section if you have packed all files into one*******/
diff --git a/template/cocos2d.js b/template/cocos2d.js
index 47358d580a..26f3954ca6 100644
--- a/template/cocos2d.js
+++ b/template/cocos2d.js
@@ -58,6 +58,7 @@
window.addEventListener('DOMContentLoaded', function () {
+ this.removeEventListener('DOMContentLoaded', arguments.callee, false);
//first load engine file if specified
var s = d.createElement('script');
/*********Delete this section if you have packed all files into one*******/
From 70590f9f230759cf185c157d045e3e0859d22441 Mon Sep 17 00:00:00 2001
From: guozhuc
Date: Mon, 2 Sep 2013 16:47:45 +0800
Subject: [PATCH 074/141] fix for simple audio enginee loading and playing
error on browser that doesn't support audio tag
---
CocosDenshion/SimpleAudioEngine.js | 11 +++++++++--
1 file changed, 9 insertions(+), 2 deletions(-)
diff --git a/CocosDenshion/SimpleAudioEngine.js b/CocosDenshion/SimpleAudioEngine.js
index 6a1b0c664f..b87f2ba4bd 100644
--- a/CocosDenshion/SimpleAudioEngine.js
+++ b/CocosDenshion/SimpleAudioEngine.js
@@ -195,8 +195,9 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
cc.Loader.getInstance().onResLoaded();
}
}
-
- //cc.Loader.getInstance().onResLoaded();
+ else {
+ cc.Loader.getInstance().onResLoaded();
+ }
},
/**
@@ -208,6 +209,9 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
* cc.AudioEngine.getInstance().playMusic(path, false);
*/
playMusic:function (path, loop) {
+ if (!this._soundEnable)
+ return;
+
var keyname = this._getPathWithoutExt(path);
var extName = this._getExtFromFullPath(path);
var au;
@@ -370,6 +374,9 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
* var soundId = cc.AudioEngine.getInstance().playEffect(path);
*/
playEffect:function (path, loop) {
+ if (!this._soundEnable)
+ return;
+
var keyname = this._getPathWithoutExt(path), actExt;
if (this._soundList.hasOwnProperty(keyname)) {
actExt = this._soundList[keyname].ext;
From dd8e32b696a5f0d8831228534d52a5a234a1aa45 Mon Sep 17 00:00:00 2001
From: WanderWang
Date: Mon, 2 Sep 2013 20:39:15 +0800
Subject: [PATCH 075/141] Update CCLabelTTF.js
add param context to method visit()
---
cocos2d/label_nodes/CCLabelTTF.js | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/cocos2d/label_nodes/CCLabelTTF.js b/cocos2d/label_nodes/CCLabelTTF.js
index fd41ecccef..66e8b83353 100644
--- a/cocos2d/label_nodes/CCLabelTTF.js
+++ b/cocos2d/label_nodes/CCLabelTTF.js
@@ -349,15 +349,15 @@ cc.LabelTTFCanvas = cc.Sprite.extend(/** @lends cc.LabelTTFCanvas# */{
}
},
- visit:function(){
+ visit:function(ctx){
if(!this._string || this._string == "")
return;
-
if(this._needUpdateTexture ){
this._needUpdateTexture = false;
this._updateTexture();
}
- cc.Sprite.prototype.visit.call(this);
+ var context = ctx || cc.renderContext;
+ cc.Sprite.prototype.visit.call(this,context);
},
setPosition:function(posX, posY){
From 27cfe60ad0de21656828da196b76d284f873e982 Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Tue, 3 Sep 2013 10:56:20 +0800
Subject: [PATCH 076/141] Closed #2514: Migrate CCBReader to Cocos2d-x v2.1.4
---
cocos2d/base_nodes/CCNode.js | 7 -
cocos2d/platform/CCTypes.js | 215 ++++++++++--------
extensions/CCBReader/CCBAnimationManager.js | 93 +++++---
extensions/CCBReader/CCBReader.js | 182 ++++++++-------
extensions/CCBReader/CCBReaderUtil.js | 8 +-
.../CCBReader/CCBRelativePositioning.js | 39 +++-
extensions/CCBReader/CCBSequence.js | 1 -
extensions/CCBReader/CCNodeLoader.js | 46 ++--
extensions/CCBReader/CCSpriteLoader.js | 123 +++++-----
9 files changed, 395 insertions(+), 319 deletions(-)
diff --git a/cocos2d/base_nodes/CCNode.js b/cocos2d/base_nodes/CCNode.js
index b1d6a76239..040ae3bc6f 100644
--- a/cocos2d/base_nodes/CCNode.js
+++ b/cocos2d/base_nodes/CCNode.js
@@ -3715,13 +3715,6 @@ cc.NodeRGBA = cc.Node.extend(/** @lends cc.NodeRGBA# */{
this._cascadeOpacityEnabled = false;
},
- init:function(){
- if(cc.Node.prototype.init.call(this)){
- return true;
- }
- return false;
- },
-
getOpacity:function(){
return this._realOpacity;
},
diff --git a/cocos2d/platform/CCTypes.js b/cocos2d/platform/CCTypes.js
index 05b2e22836..8658a80a4e 100644
--- a/cocos2d/platform/CCTypes.js
+++ b/cocos2d/platform/CCTypes.js
@@ -458,7 +458,6 @@ cc.Quad2 = function (tl1, tr1, bl1, br1) {
* @param {cc.Vertex3F} tr1
*/
cc.Quad3 = function (bl1, br1, tl1, tr1) {
- //TODO need redefine by ArrayBuffer
this.bl = bl1 || new cc.Vertex3F(0, 0, 0);
this.br = br1 || new cc.Vertex3F(0, 0, 0);
this.tl = tl1 || new cc.Vertex3F(0, 0, 0);
@@ -608,7 +607,7 @@ cc.V3F_C4B_T2F_QuadZero = function () {
cc.V3F_C4B_T2F_QuadCopy = function (sourceQuad) {
if (!sourceQuad)
return cc.V3F_C4B_T2F_QuadZero();
-
+ var tl = sourceQuad.tl, bl = sourceQuad.bl, tr = sourceQuad.tr, br = sourceQuad.br;
return new cc.V3F_C4B_T2F_Quad(
new cc.V3F_C4B_T2F(new cc.Vertex3F(sourceQuad.tl.vertices.x, sourceQuad.tl.vertices.y, sourceQuad.tl.vertices.z),
new cc.Color4B(sourceQuad.tl.colors.r, sourceQuad.tl.colors.g, sourceQuad.tl.colors.b, sourceQuad.tl.colors.a),
@@ -718,10 +717,11 @@ if(cc.Browser.supportWebGL){
this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Color4B.BYTES_PER_ELEMENT);
this._offset = offset || 0;
- this._rU8 = new Uint8Array(this._arrayBuffer, this._offset, 1);
- this._gU8 = new Uint8Array(this._arrayBuffer, this._offset + Uint8Array.BYTES_PER_ELEMENT, 1);
- this._bU8 = new Uint8Array(this._arrayBuffer, this._offset + Uint8Array.BYTES_PER_ELEMENT * 2, 1);
- this._aU8 = new Uint8Array(this._arrayBuffer, this._offset + Uint8Array.BYTES_PER_ELEMENT * 3, 1);
+ var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = Uint8Array.BYTES_PER_ELEMENT;
+ this._rU8 = new Uint8Array(locArrayBuffer, locOffset, 1);
+ this._gU8 = new Uint8Array(locArrayBuffer, locOffset + locElementLen, 1);
+ this._bU8 = new Uint8Array(locArrayBuffer, locOffset + locElementLen * 2, 1);
+ this._aU8 = new Uint8Array(locArrayBuffer, locOffset + locElementLen * 3, 1);
this._rU8[0] = r || 0;
this._gU8[0] = g || 0;
@@ -769,17 +769,18 @@ if(cc.Browser.supportWebGL){
});
//redefine cc.Color4F
- cc.Color4F = function(r,g,b,a, arrayBuffer, offset){
+ cc.Color4F = function (r, g, b, a, arrayBuffer, offset) {
this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Color4F.BYTES_PER_ELEMENT);
this._offset = offset || 0;
- this._rF32 = new Float32Array(this._arrayBuffer,this._offset, 1);
+ var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = Float32Array.BYTES_PER_ELEMENT;
+ this._rF32 = new Float32Array(locArrayBuffer, locOffset, 1);
this._rF32[0] = r || 0;
- this._gF32 = new Float32Array(this._arrayBuffer,this._offset + Float32Array.BYTES_PER_ELEMENT, 1);
+ this._gF32 = new Float32Array(locArrayBuffer, locOffset + locElementLen, 1);
this._gF32[0] = g || 0;
- this._bF32 = new Float32Array(this._arrayBuffer,this._offset + Float32Array.BYTES_PER_ELEMENT * 2, 1);
+ this._bF32 = new Float32Array(locArrayBuffer, locOffset + locElementLen * 2, 1);
this._bF32[0] = b || 0;
- this._aF32 = new Float32Array(this._arrayBuffer,this._offset + Float32Array.BYTES_PER_ELEMENT * 3, 1);
+ this._aF32 = new Float32Array(locArrayBuffer, locOffset + locElementLen * 3, 1);
this._aF32[0] = a || 0;
};
cc.Color4F.BYTES_PER_ELEMENT = 16;
@@ -859,11 +860,12 @@ if(cc.Browser.supportWebGL){
this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Vertex3F.BYTES_PER_ELEMENT);
this._offset = offset || 0;
- this._xF32 = new Float32Array(this._arrayBuffer, this._offset, 1);
+ var locArrayBuffer = this._arrayBuffer, locOffset = this._offset;
+ this._xF32 = new Float32Array(locArrayBuffer, locOffset, 1);
this._xF32[0] = x || 0;
- this._yF32 = new Float32Array(this._arrayBuffer, this._offset + Float32Array.BYTES_PER_ELEMENT, 1);
+ this._yF32 = new Float32Array(locArrayBuffer, locOffset + Float32Array.BYTES_PER_ELEMENT, 1);
this._yF32[0] = y || 0;
- this._zF32 = new Float32Array(this._arrayBuffer, this._offset + Float32Array.BYTES_PER_ELEMENT * 2, 1);
+ this._zF32 = new Float32Array(locArrayBuffer, locOffset + Float32Array.BYTES_PER_ELEMENT * 2, 1);
this._zF32[0] = z || 0;
};
cc.Vertex3F.BYTES_PER_ELEMENT = 12;
@@ -934,13 +936,11 @@ if(cc.Browser.supportWebGL){
this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.Quad2.BYTES_PER_ELEMENT);
this._offset = offset || 0;
- this._tl = tl ? new cc.Vertex2F(tl.x, tl.y, this._arrayBuffer, 0) : new cc.Vertex2F(0, 0, this._arrayBuffer, 0);
- this._tr = tr ? new cc.Vertex2F(tr.x, tr.y, this._arrayBuffer, cc.Vertex2F.BYTES_PER_ELEMENT) :
- new cc.Vertex2F(0, 0, this._arrayBuffer, cc.Vertex2F.BYTES_PER_ELEMENT);
- this._bl = bl ? new cc.Vertex2F(bl.x, bl.y, this._arrayBuffer, cc.Vertex2F.BYTES_PER_ELEMENT * 2) :
- new cc.Vertex2F(0, 0, this._arrayBuffer, cc.Vertex2F.BYTES_PER_ELEMENT * 2);
- this._br = br ? new cc.Vertex2F(br.x, br.y, this._arrayBuffer, cc.Vertex2F.BYTES_PER_ELEMENT * 3) :
- new cc.Vertex2F(0, 0, this._arrayBuffer, cc.Vertex2F.BYTES_PER_ELEMENT * 3);
+ var locArrayBuffer = this._arrayBuffer, locElementLen = cc.Vertex2F.BYTES_PER_ELEMENT;
+ this._tl = tl ? new cc.Vertex2F(tl.x, tl.y, locArrayBuffer, 0) : new cc.Vertex2F(0, 0, locArrayBuffer, 0);
+ this._tr = tr ? new cc.Vertex2F(tr.x, tr.y, locArrayBuffer, locElementLen) : new cc.Vertex2F(0, 0, locArrayBuffer, locElementLen);
+ this._bl = bl ? new cc.Vertex2F(bl.x, bl.y, locArrayBuffer, locElementLen * 2) : new cc.Vertex2F(0, 0, locArrayBuffer, locElementLen * 2);
+ this._br = br ? new cc.Vertex2F(br.x, br.y, locArrayBuffer, locElementLen * 3) : new cc.Vertex2F(0, 0, locArrayBuffer, locElementLen * 3);
};
cc.Quad2.BYTES_PER_ELEMENT = 32;
Object.defineProperties(cc.Quad2.prototype, {
@@ -991,12 +991,13 @@ if(cc.Browser.supportWebGL){
this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V3F_C4B_T2F.BYTES_PER_ELEMENT);
this._offset = offset || 0;
- this._vertices = vertices ? new cc.Vertex3F(vertices.x, vertices.y, vertices.z, this._arrayBuffer, this._offset) :
- new cc.Vertex3F(0, 0, 0, this._arrayBuffer, this._offset);
- this._colors = colors ? new cc.Color4B(colors.r, colors.g, colors.b, colors.a, this._arrayBuffer, this._offset + cc.Vertex3F.BYTES_PER_ELEMENT) :
- new cc.Color4B(0, 0, 0, 0, this._arrayBuffer, this._offset + cc.Vertex3F.BYTES_PER_ELEMENT);
- this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, this._arrayBuffer, this._offset + cc.Vertex3F.BYTES_PER_ELEMENT + cc.Color4B.BYTES_PER_ELEMENT) :
- new cc.Tex2F(0, 0, this._arrayBuffer, this._offset + cc.Vertex3F.BYTES_PER_ELEMENT + cc.Color4B.BYTES_PER_ELEMENT);
+ var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.Vertex3F.BYTES_PER_ELEMENT;
+ this._vertices = vertices ? new cc.Vertex3F(vertices.x, vertices.y, vertices.z, locArrayBuffer, locOffset) :
+ new cc.Vertex3F(0, 0, 0, locArrayBuffer, locOffset);
+ this._colors = colors ? new cc.Color4B(colors.r, colors.g, colors.b, colors.a, locArrayBuffer, locOffset + locElementLen) :
+ new cc.Color4B(0, 0, 0, 0, locArrayBuffer, locOffset + locElementLen);
+ this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, locArrayBuffer, locOffset + locElementLen + cc.Color4B.BYTES_PER_ELEMENT) :
+ new cc.Tex2F(0, 0, locArrayBuffer, locOffset + locElementLen + cc.Color4B.BYTES_PER_ELEMENT);
};
cc.V3F_C4B_T2F.BYTES_PER_ELEMENT = 24;
Object.defineProperties(cc.V3F_C4B_T2F.prototype, {
@@ -1005,9 +1006,10 @@ if(cc.Browser.supportWebGL){
return this._vertices;
},
set: function (verticesValue) {
- this._vertices.x = verticesValue.x;
- this._vertices.y = verticesValue.y;
- this._vertices.z = verticesValue.z;
+ var locVertices = this._vertices;
+ locVertices.x = verticesValue.x;
+ locVertices.y = verticesValue.y;
+ locVertices.z = verticesValue.z;
},
enumerable: true
},
@@ -1016,10 +1018,11 @@ if(cc.Browser.supportWebGL){
return this._colors;
},
set: function (colorValue) {
- this._colors.r = colorValue.r;
- this._colors.g = colorValue.g;
- this._colors.b = colorValue.b;
- this._colors.a = colorValue.a;
+ var locColors = this._colors;
+ locColors.r = colorValue.r;
+ locColors.g = colorValue.g;
+ locColors.b = colorValue.b;
+ locColors.a = colorValue.a;
},
enumerable: true
},
@@ -1040,14 +1043,15 @@ if(cc.Browser.supportWebGL){
this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT);
this._offset = offset || 0;
- this._tl = tl ? new cc.V3F_C4B_T2F(tl.vertices, tl.colors, tl.texCoords, this._arrayBuffer, this._offset) :
- new cc.V3F_C4B_T2F(null, null, null, this._arrayBuffer, this._offset);
- this._bl = bl ? new cc.V3F_C4B_T2F(bl.vertices, bl.colors, bl.texCoords, this._arrayBuffer, this._offset + cc.V3F_C4B_T2F.BYTES_PER_ELEMENT) :
- new cc.V3F_C4B_T2F(null, null, null, this._arrayBuffer, this._offset + cc.V3F_C4B_T2F.BYTES_PER_ELEMENT);
- this._tr = tr ? new cc.V3F_C4B_T2F(tr.vertices, tr.colors, tr.texCoords, this._arrayBuffer, this._offset + cc.V3F_C4B_T2F.BYTES_PER_ELEMENT * 2) :
- new cc.V3F_C4B_T2F(null, null, null, this._arrayBuffer, this._offset + cc.V3F_C4B_T2F.BYTES_PER_ELEMENT * 2);
- this._br = br ? new cc.V3F_C4B_T2F(br.vertices, br.colors, br.texCoords, this._arrayBuffer, this._offset + cc.V3F_C4B_T2F.BYTES_PER_ELEMENT * 3) :
- new cc.V3F_C4B_T2F(null, null, null, this._arrayBuffer, this._offset + cc.V3F_C4B_T2F.BYTES_PER_ELEMENT * 3);
+ var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.V3F_C4B_T2F.BYTES_PER_ELEMENT;
+ this._tl = tl ? new cc.V3F_C4B_T2F(tl.vertices, tl.colors, tl.texCoords, locArrayBuffer, locOffset) :
+ new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset);
+ this._bl = bl ? new cc.V3F_C4B_T2F(bl.vertices, bl.colors, bl.texCoords, locArrayBuffer, locOffset + locElementLen) :
+ new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset + locElementLen);
+ this._tr = tr ? new cc.V3F_C4B_T2F(tr.vertices, tr.colors, tr.texCoords, locArrayBuffer, locOffset + locElementLen * 2) :
+ new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset + locElementLen * 2);
+ this._br = br ? new cc.V3F_C4B_T2F(br.vertices, br.colors, br.texCoords, locArrayBuffer, locOffset + locElementLen * 3) :
+ new cc.V3F_C4B_T2F(null, null, null, locArrayBuffer, locOffset + locElementLen * 3);
};
cc.V3F_C4B_T2F_Quad.BYTES_PER_ELEMENT = 96;
Object.defineProperties(cc.V3F_C4B_T2F_Quad.prototype, {
@@ -1056,9 +1060,10 @@ if(cc.Browser.supportWebGL){
return this._tl;
},
set: function (tlValue) {
- this._tl.vertices = tlValue.vertices;
- this._tl.colors = tlValue.colors;
- this._tl.texCoords = tlValue.texCoords;
+ var locTl = this._tl;
+ locTl.vertices = tlValue.vertices;
+ locTl.colors = tlValue.colors;
+ locTl.texCoords = tlValue.texCoords;
},
enumerable: true
},
@@ -1067,9 +1072,10 @@ if(cc.Browser.supportWebGL){
return this._bl;
},
set: function (blValue) {
- this._bl.vertices = blValue.vertices;
- this._bl.colors = blValue.colors;
- this._bl.texCoords = blValue.texCoords;
+ var locBl = this._bl;
+ locBl.vertices = blValue.vertices;
+ locBl.colors = blValue.colors;
+ locBl.texCoords = blValue.texCoords;
},
enumerable: true
},
@@ -1078,9 +1084,10 @@ if(cc.Browser.supportWebGL){
return this._tr;
},
set: function (trValue) {
- this._tr.vertices = trValue.vertices;
- this._tr.colors = trValue.colors;
- this._tr.texCoords = trValue.texCoords;
+ var locTr = this._tr;
+ locTr.vertices = trValue.vertices;
+ locTr.colors = trValue.colors;
+ locTr.texCoords = trValue.texCoords;
},
enumerable: true
},
@@ -1089,9 +1096,10 @@ if(cc.Browser.supportWebGL){
return this._br;
},
set: function (brValue) {
- this._br.vertices = brValue.vertices;
- this._br.colors = brValue.colors;
- this._br.texCoords = brValue.texCoords;
+ var locBr = this._br;
+ locBr.vertices = brValue.vertices;
+ locBr.colors = brValue.colors;
+ locBr.texCoords = brValue.texCoords;
},
enumerable: true
},
@@ -1111,19 +1119,20 @@ if(cc.Browser.supportWebGL){
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: sourceQuad.tl.vertices.x, y: sourceQuad.tl.vertices.y, z: sourceQuad.tl.vertices.z},
- colors: {r: sourceQuad.tl.colors.r, g: sourceQuad.tl.colors.g, b: sourceQuad.tl.colors.b, a: sourceQuad.tl.colors.a},
- texCoords: {u: sourceQuad.tl.texCoords.u, v: sourceQuad.tl.texCoords.v}},
- bl: {vertices: {x: sourceQuad.bl.vertices.x, y: sourceQuad.bl.vertices.y, z: sourceQuad.bl.vertices.z},
- colors: {r: sourceQuad.bl.colors.r, g: sourceQuad.bl.colors.g, b: sourceQuad.bl.colors.b, a: sourceQuad.bl.colors.a},
- texCoords: {u: sourceQuad.bl.texCoords.u, v: sourceQuad.bl.texCoords.v}},
- tr: {vertices: {x: sourceQuad.tr.vertices.x, y: sourceQuad.tr.vertices.y, z: sourceQuad.tr.vertices.z},
- colors: {r: sourceQuad.tr.colors.r, g: sourceQuad.tr.colors.g, b: sourceQuad.tr.colors.b, a: sourceQuad.tr.colors.a},
- texCoords: {u: sourceQuad.tr.texCoords.u, v: sourceQuad.tr.texCoords.v}},
- br: {vertices: {x: sourceQuad.br.vertices.x, y: sourceQuad.br.vertices.y, z: sourceQuad.br.vertices.z},
- colors: {r: sourceQuad.br.colors.r, g: sourceQuad.br.colors.g, b: sourceQuad.br.colors.b, a: sourceQuad.br.colors.a},
- texCoords: {u: sourceQuad.br.texCoords.u, v: sourceQuad.br.texCoords.v}}
+ 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},
+ 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},
+ 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},
+ 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}}
};
};
@@ -1132,12 +1141,13 @@ if(cc.Browser.supportWebGL){
this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V2F_C4B_T2F.BYTES_PER_ELEMENT);
this._offset = offset || 0;
- this._vertices = vertices ? new cc.Vertex2F(vertices.x, vertices.y, this._arrayBuffer, this._offset) :
- new cc.Vertex2F(0, 0, this._arrayBuffer, this._offset);
- this._colors = colors ? new cc.Color4B(colors.r, colors.g, colors.b, colors.a, this._arrayBuffer, this._offset + cc.Vertex2F.BYTES_PER_ELEMENT) :
- new cc.Color4B(0, 0, 0, 0, this._arrayBuffer, this._offset + cc.Vertex2F.BYTES_PER_ELEMENT);
- this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, this._arrayBuffer, this._offset + cc.Vertex2F.BYTES_PER_ELEMENT + cc.Color4B.BYTES_PER_ELEMENT) :
- new cc.Tex2F(0, 0, this._arrayBuffer, this._offset + cc.Vertex2F.BYTES_PER_ELEMENT + cc.Color4B.BYTES_PER_ELEMENT);
+ var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.Vertex2F.BYTES_PER_ELEMENT;
+ this._vertices = vertices ? new cc.Vertex2F(vertices.x, vertices.y, locArrayBuffer, locOffset) :
+ new cc.Vertex2F(0, 0, locArrayBuffer, locOffset);
+ this._colors = colors ? new cc.Color4B(colors.r, colors.g, colors.b, colors.a, locArrayBuffer, locOffset + locElementLen) :
+ new cc.Color4B(0, 0, 0, 0, locArrayBuffer, locOffset + locElementLen);
+ this._texCoords = texCoords ? new cc.Tex2F(texCoords.u, texCoords.v, locArrayBuffer, locOffset + locElementLen + cc.Color4B.BYTES_PER_ELEMENT) :
+ new cc.Tex2F(0, 0, locArrayBuffer, locOffset + locElementLen + cc.Color4B.BYTES_PER_ELEMENT);
};
cc.V2F_C4B_T2F.BYTES_PER_ELEMENT = 20;
Object.defineProperties(cc.V2F_C4B_T2F.prototype, {
@@ -1156,10 +1166,11 @@ if(cc.Browser.supportWebGL){
return this._colors;
},
set: function (colorValue) {
- this._colors.r = colorValue.r;
- this._colors.g = colorValue.g;
- this._colors.b = colorValue.b;
- this._colors.a = colorValue.a;
+ var locColors = this._colors;
+ locColors.r = colorValue.r;
+ locColors.g = colorValue.g;
+ locColors.b = colorValue.b;
+ locColors.a = colorValue.a;
},
enumerable: true
},
@@ -1180,12 +1191,13 @@ if(cc.Browser.supportWebGL){
this._arrayBuffer = arrayBuffer || new ArrayBuffer(cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT);
this._offset = offset || 0;
- this._a = a ? new cc.V2F_C4B_T2F(a.vertices, a.colors, a.texCoords, this._arrayBuffer, this._offset) :
- new cc.V2F_C4B_T2F(null, null, null, this._arrayBuffer, this._offset);
- this._b = b ? new cc.V2F_C4B_T2F(b.vertices, b.colors, b.texCoords, this._arrayBuffer, this._offset + cc.V2F_C4B_T2F.BYTES_PER_ELEMENT) :
- new cc.V2F_C4B_T2F(null, null, null, this._arrayBuffer, this._offset + cc.V2F_C4B_T2F.BYTES_PER_ELEMENT);
- this._c = c ? new cc.V2F_C4B_T2F(c.vertices, c.colors, c.texCoords, this._arrayBuffer, this._offset + cc.V2F_C4B_T2F.BYTES_PER_ELEMENT * 2) :
- new cc.V2F_C4B_T2F(null, null, null, this._arrayBuffer, this._offset + cc.V2F_C4B_T2F.BYTES_PER_ELEMENT * 2);
+ var locArrayBuffer = this._arrayBuffer, locOffset = this._offset, locElementLen = cc.V2F_C4B_T2F.BYTES_PER_ELEMENT;
+ this._a = a ? new cc.V2F_C4B_T2F(a.vertices, a.colors, a.texCoords, locArrayBuffer, locOffset) :
+ new cc.V2F_C4B_T2F(null, null, null, locArrayBuffer, locOffset);
+ this._b = b ? new cc.V2F_C4B_T2F(b.vertices, b.colors, b.texCoords, locArrayBuffer, locOffset + locElementLen) :
+ new cc.V2F_C4B_T2F(null, null, null, locArrayBuffer, locOffset + locElementLen);
+ this._c = c ? new cc.V2F_C4B_T2F(c.vertices, c.colors, c.texCoords, locArrayBuffer, locOffset + locElementLen * 2) :
+ new cc.V2F_C4B_T2F(null, null, null, locArrayBuffer, locOffset + locElementLen * 2);
};
cc.V2F_C4B_T2F_Triangle.BYTES_PER_ELEMENT = 60;
Object.defineProperties(cc.V2F_C4B_T2F_Triangle.prototype, {
@@ -1194,9 +1206,10 @@ if(cc.Browser.supportWebGL){
return this._a;
},
set: function (aValue) {
- this._a.vertices = aValue.vertices;
- this._a.colors = aValue.colors;
- this._a.texCoords = aValue.texCoords;
+ var locA = this._a;
+ locA.vertices = aValue.vertices;
+ locA.colors = aValue.colors;
+ locA.texCoords = aValue.texCoords;
},
enumerable: true
},
@@ -1205,9 +1218,10 @@ if(cc.Browser.supportWebGL){
return this._b;
},
set: function (bValue) {
- this._b.vertices = bValue.vertices;
- this._b.colors = bValue.colors;
- this._b.texCoords = bValue.texCoords;
+ var locB = this._b;
+ locB.vertices = bValue.vertices;
+ locB.colors = bValue.colors;
+ locB.texCoords = bValue.texCoords;
},
enumerable: true
},
@@ -1216,9 +1230,10 @@ if(cc.Browser.supportWebGL){
return this._c;
},
set: function (cValue) {
- this._c.vertices = cValue.vertices;
- this._c.colors = cValue.colors;
- this._c.texCoords = cValue.texCoords;
+ var locC = this._c;
+ locC.vertices = cValue.vertices;
+ locC.colors = cValue.colors;
+ locC.texCoords = cValue.texCoords;
},
enumerable: true
}
@@ -1311,8 +1326,9 @@ cc._Dictionary = cc.Class.extend({
if (key == null)
return null;
- for (var keyId in this._keyMapTb) {
- if (this._keyMapTb[keyId] === key)
+ var locKeyMapTb = this._keyMapTb;
+ for (var keyId in locKeyMapTb) {
+ if (locKeyMapTb[keyId] === key)
return this._valueMapTb[keyId];
}
return null;
@@ -1326,10 +1342,11 @@ cc._Dictionary = cc.Class.extend({
if (key == null)
return;
- for (var keyId in this._keyMapTb) {
- if (this._keyMapTb[keyId] === key) {
+ var locKeyMapTb = this._keyMapTb;
+ for (var keyId in locKeyMapTb) {
+ if (locKeyMapTb[keyId] === key) {
delete this._valueMapTb[keyId];
- delete this._keyMapTb[keyId];
+ delete locKeyMapTb[keyId];
return;
}
}
@@ -1344,9 +1361,9 @@ cc._Dictionary = cc.Class.extend({
},
allKeys: function () {
- var keyArr = [];
- for (var key in this._keyMapTb)
- keyArr.push(this._keyMapTb[key]);
+ var keyArr = [], locKeyMapTb = this._keyMapTb;
+ for (var key in locKeyMapTb)
+ keyArr.push(locKeyMapTb[key]);
return keyArr;
},
diff --git a/extensions/CCBReader/CCBAnimationManager.js b/extensions/CCBReader/CCBAnimationManager.js
index 0f67fb02ce..82867a3528 100644
--- a/extensions/CCBReader/CCBAnimationManager.js
+++ b/extensions/CCBReader/CCBAnimationManager.js
@@ -177,7 +177,9 @@ cc.BuilderAnimationManager = cc.Class.extend({
},
getRunningSequenceName:function () {
- return this._runningSequence.getName();
+ if(this._runningSequence)
+ return this._runningSequence.getName();
+ return null;
},
getContainerSize:function (node) {
@@ -201,17 +203,19 @@ cc.BuilderAnimationManager = cc.Class.extend({
moveAnimationsFromNode:function(fromNode,toNode){
// Move base values
- var baseValue = this._baseValues.objectForKey(fromNode);
+ var locBaseValues = this._baseValues;
+ var baseValue = locBaseValues.objectForKey(fromNode);
if(baseValue != null) {
- this._baseValues.setObject(baseValue, toNode);
- this._baseValues.removeObjectForKey(fromNode);
+ locBaseValues.setObject(baseValue, toNode);
+ locBaseValues.removeObjectForKey(fromNode);
}
// Move seqs
- var seqs = this._nodeSequences.objectForKey(fromNode);
+ var locNodeSequences = this._nodeSequences;
+ var seqs = locNodeSequences.objectForKey(fromNode);
if(seqs != null) {
- this._nodeSequences.setObject(seqs, toNode);
- this._nodeSequences.removeObjectForKey(fromNode);
+ locNodeSequences.setObject(seqs, toNode);
+ locNodeSequences.removeObjectForKey(fromNode);
}
},
@@ -296,24 +300,24 @@ cc.BuilderAnimationManager = cc.Class.extend({
return cc.Sequence.create(actions);
},
+
runAnimationsForSequenceNamed:function(name){
- this.runAnimations(name);
+ this.runAnimationsForSequenceIdTweenDuration(this._getSequenceId(name), 0);
},
- runAnimations:function (name, tweenDuration) {
+ runAnimationsForSequenceNamedTweenDuration:function(name, tweenDuration){
+ this.runAnimationsForSequenceIdTweenDuration(this._getSequenceId(name), tweenDuration);
+ },
+
+ runAnimationsForSequenceIdTweenDuration:function(nSeqId, tweenDuration){
tweenDuration = tweenDuration || 0;
- var nSeqId;
- if(typeof(name) === "string")
- nSeqId = this._getSequenceId(name);
- else
- nSeqId = name;
cc.Assert(nSeqId != -1, "Sequence id couldn't be found");
this._rootNode.stopAllActions();
var allKeys = this._nodeSequences.allKeys();
- for(var i = 0 ; i< allKeys.length;i++){
+ for(var i = 0,len = allKeys.length ; i< len;i++){
var node = allKeys[i];
node.stopAllActions();
@@ -353,10 +357,11 @@ cc.BuilderAnimationManager = cc.Class.extend({
cc.CallFunc.create(this._sequenceCompleted,this));
this._rootNode.runAction(completeAction);
- // Playback callbacks and sounds
+ // Playback callbacks and sounds
+ var action;
if (seq.getCallbackChannel()) {
// Build sound actions for channel
- var action = this.getActionForCallbackChannel(seq.getCallbackChannel());
+ action = this.getActionForCallbackChannel(seq.getCallbackChannel());
if (action) {
this._rootNode.runAction(action);
}
@@ -364,15 +369,26 @@ cc.BuilderAnimationManager = cc.Class.extend({
if (seq.getSoundChannel()) {
// Build sound actions for channel
- var action = this.getActionForSoundChannel(seq.getSoundChannel());
+ action = this.getActionForSoundChannel(seq.getSoundChannel());
if (action) {
this._rootNode.runAction(action);
}
}
- // Set the running scene
+ // Set the running scene
this._runningSequence = this._getSequence(nSeqId);
},
+ runAnimations:function (name, tweenDuration) {
+ tweenDuration = tweenDuration || 0;
+ var nSeqId;
+ if(typeof(name) === "string")
+ nSeqId = this._getSequenceId(name);
+ else
+ nSeqId = name;
+
+ this.runAnimationsForSequenceIdTweenDuration(nSeqId, tweenDuration);
+ },
+
setAnimationCompletedCallback:function(target,callbackFunc){
this._target = target;
this._animationCompleteCallbackFunc = callbackFunc;
@@ -384,6 +400,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
setCallFunc:function(callFunc, callbackNamed) {
this._keyframeCallFuncs[callbackNamed] = callFunc;
},
+
debug:function () {
},
@@ -396,9 +413,10 @@ cc.BuilderAnimationManager = cc.Class.extend({
_getSequenceId:function (sequenceName) {
var element = null;
- for (var i = 0; i < this._sequences.length; i++) {
- element = this._sequences[i];
- if (element && element.getName() == sequenceName)
+ var locSequences = this._sequences;
+ for (var i = 0, len = locSequences.length; i < len; i++) {
+ element = locSequences[i];
+ if (element && element.getName() === sequenceName)
return element.getSequenceId();
}
return -1;
@@ -406,8 +424,9 @@ cc.BuilderAnimationManager = cc.Class.extend({
_getSequence:function (sequenceId) {
var element = null;
- for (var i = 0; i < this._sequences.length; i++) {
- element = this._sequences[i];
+ var locSequences = this._sequences;
+ for (var i = 0, len = locSequences.length; i < len; i++) {
+ element = locSequences[i];
if (element && element.getSequenceId() === sequenceId)
return element;
}
@@ -449,7 +468,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
var containerSize = this.getContainerSize(node.getParent());
- var absPos = cc.getAbsolutePosition(cc.p(x,y), type,containerSize,propName);
+ var absPos = cc._getAbsolutePosition(x,y, type,containerSize,propName);
return cc.MoveTo.create(duration,absPos);
} else if( propName === "scale"){
@@ -461,8 +480,13 @@ cc.BuilderAnimationManager = cc.Class.extend({
x = getValueArr[0];
y = getValueArr[1];
- if(type == CCB_SCALETYPE_MULTIPLY_RESOLUTION)
- var resolutionScale = cc.BuilderReader.getResolutionScale();
+ if(type === CCB_SCALETYPE_MULTIPLY_RESOLUTION){
+ //TODO need to test
+ var resolutionScale = cc.BuilderReader.getResolutionScale();
+ x *= resolutionScale;
+ y *= resolutionScale;
+ }
+
return cc.ScaleTo.create(duration,x,y);
} else if( propName === "skew") {
//get relative position
@@ -496,7 +520,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
x = value[0];
y = value[1];
- node.setPosition(cc.getAbsolutePosition(cc.p(x,y),nType, this.getContainerSize(node.getParent()),propName));
+ node.setPosition(cc._getAbsolutePosition(x,y,nType, this.getContainerSize(node.getParent()),propName));
}else if(propName === "scale"){
getArr = this._getBaseValue(node,propName);
nType = getArr[2];
@@ -506,8 +530,6 @@ cc.BuilderAnimationManager = cc.Class.extend({
cc.setRelativeScale(node,x,y,nType,propName);
} else if( propName === "skew") {
- getArr = this._getBaseValue(node,propName);
- nType = getArr[2];
x = value[0];
y = value[1];
node.setSkewX(x);
@@ -537,7 +559,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
_setFirstFrame:function (node, seqProp, tweenDuration) {
var keyframes = seqProp.getKeyframes();
- if (keyframes.length == 0) {
+ if (keyframes.length === 0) {
// Use base value (no animation)
var baseValue = this._getBaseValue(node, seqProp.getName());
cc.Assert(baseValue, "No baseValue found for property");
@@ -615,18 +637,19 @@ cc.BuilderAnimationManager = cc.Class.extend({
},
_sequenceCompleted:function () {
- if(this._lastCompletedSequenceName != this._runningSequence.getName()){
- this._lastCompletedSequenceName = this._runningSequence.getName();
+ var locRunningSequence = this._runningSequence;
+ if(this._lastCompletedSequenceName != locRunningSequence.getName()){
+ this._lastCompletedSequenceName = locRunningSequence.getName();
}
if (this._delegate)
- this._delegate.completedAnimationSequenceNamed(this._runningSequence.getName());
+ this._delegate.completedAnimationSequenceNamed(locRunningSequence.getName());
if(this._target && this._animationCompleteCallbackFunc){
this._animationCompleteCallbackFunc.call(this._target);
}
- var nextSeqId = this._runningSequence.getChainedSequenceId();
+ var nextSeqId = locRunningSequence.getChainedSequenceId();
this._runningSequence = null;
if (nextSeqId != -1)
diff --git a/extensions/CCBReader/CCBReader.js b/extensions/CCBReader/CCBReader.js
index d0ceb994e8..142da066c3 100644
--- a/extensions/CCBReader/CCBReader.js
+++ b/extensions/CCBReader/CCBReader.js
@@ -152,7 +152,7 @@ cc.BuilderReader = cc.Class.extend({
_ownerCallbackNames:null,
_ownerCallbackNodes:null,
- _hasScriptingOwner:false,
+ _readNodeGraphFromData:false,
ctor:function (ccNodeLoaderLibrary, ccbMemberVariableAssigner, ccbSelectorResolver, ccNodeLoaderListener) {
this._stringCache = [];
@@ -220,17 +220,18 @@ cc.BuilderReader = cc.Class.extend({
animationManager = parentSize;
parentSize = cc.Director.getInstance().getWinSize();
}
-
- var path = cc.FileUtils.getInstance().fullPathFromRelativePath(ccbFileName);
- var data = cc.FileUtils.getInstance().getByteArrayFromFile(path);
+ var fileUtils = cc.FileUtils.getInstance();
+ var path = fileUtils.fullPathFromRelativePath(ccbFileName);
+ var data = fileUtils.getByteArrayFromFile(path);
return this.readNodeGraphFromData(data, owner, parentSize, animationManager);
},
readNodeGraphFromData:function (data, owner, parentSize) {
this.initWithData(data, owner);
- this._actionManager.setRootContainerSize(parentSize);
- this._actionManager.setOwner(owner);
+ var locActionManager = this._actionManager;
+ locActionManager.setRootContainerSize(parentSize);
+ locActionManager.setOwner(owner);
this._ownerOutletNames = [];
this._ownerOutletNodes = [];
@@ -240,20 +241,24 @@ cc.BuilderReader = cc.Class.extend({
var nodeGraph = this.readFileWithCleanUp(true);
- if (nodeGraph && this._actionManager.getAutoPlaySequenceId() != -1) {
+ if (nodeGraph && locActionManager.getAutoPlaySequenceId() != -1) {
//auto play animations
- this._actionManager.runAnimations(this._actionManager.getAutoPlaySequenceId(), 0);
+ locActionManager.runAnimations(locActionManager.getAutoPlaySequenceId(), 0);
}
if (this._jsControlled) {
- this._nodesWithAnimationManagers = [];
- this._animationManagerForNodes = [];
+ var locNodes = [];
+ var locAnimations = [];
- var getAllKeys = this._animationManagers.allKeys();
+ var locAnimationManager = this._animationManagers;
+ var getAllKeys = locAnimationManager.allKeys();
for (var i = 0; i < getAllKeys.length; i++) {
- this._nodesWithAnimationManagers.push(getAllKeys[i]);
- this._animationManagerForNodes.push(this._animationManagers.objectForKey(getAllKeys[i]));
+ locNodes.push(getAllKeys[i]);
+ locAnimations.push(locAnimationManager.objectForKey(getAllKeys[i]));
}
+
+ this._nodesWithAnimationManagers = locNodes;
+ this._animationManagerForNodes = locAnimations;
}
return nodeGraph;
@@ -500,10 +505,21 @@ cc.BuilderReader = cc.Class.extend({
return node;
},
+ addOwnerOutletName: function(name){
+ this._ownerOutletNames.push(name);
+ },
+
+ addOwnerOutletNode: function(node){
+ if(node == null)
+ return;
+
+ this._ownerOutletNodes.push(node);
+ },
+
_cleanUpNodeGraph:function (node) {
node.setUserObject(null);
var getChildren = node.getChildren();
- for (var i = 0; i < getChildren.length; i++) {
+ for (var i = 0, len = getChildren.length; i < len; i++) {
this._cleanUpNodeGraph(getChildren[i]);
}
},
@@ -515,9 +531,8 @@ cc.BuilderReader = cc.Class.extend({
return true;
var channel = new cc.BuilderSequenceProperty();
-
- for (var i = 0; i < numKeyframes; i++)
- {
+ var locJsControlled = this._jsControlled, locActionManager = this._actionManager, locKeyframes = channel.getKeyframes();
+ for (var i = 0; i < numKeyframes; i++) {
var time = this.readFloat();
var callbackName = this.readCachedString();
var callbackType = this.readInt(false);
@@ -528,10 +543,10 @@ cc.BuilderReader = cc.Class.extend({
keyframe.setTime(time);
keyframe.setValue(value);
- if(this._jsControlled) {
- this._actionManager.getKeyframeCallbacks().push(callbackType+":"+callbackName);
- }
- channel.getKeyframes().push(keyframe);
+ if(locJsControlled)
+ locActionManager.getKeyframeCallbacks().push(callbackType+":"+callbackName);
+
+ locKeyframes.push(keyframe);
}
// Assign to sequence
@@ -543,12 +558,12 @@ cc.BuilderReader = cc.Class.extend({
_readSoundKeyframesForSeq:function(seq) {
var numKeyframes = this.readInt(false);
- if (!numKeyframes) return true;
+ if (!numKeyframes)
+ return true;
var channel = new cc.BuilderSequenceProperty();
-
- for (var i = 0; i < numKeyframes; i++)
- {
+ var locKeyframes = channel.getKeyframes();
+ for (var i = 0; i < numKeyframes; i++) {
var time = this.readFloat();
var soundFile = this.readCachedString();
var pitch = this.readFloat();
@@ -560,12 +575,11 @@ cc.BuilderReader = cc.Class.extend({
keyframe.setTime(time);
keyframe.setValue(value);
- channel.getKeyframes().push(keyframe);
+ locKeyframes.push(keyframe);
}
// Assign to sequence
seq.setSoundChannel(channel);
-
return true;
},
_readSequences:function () {
@@ -628,7 +642,8 @@ cc.BuilderReader = cc.Class.extend({
if (spriteSheet == "") {
spriteFile = this._ccbRootPath + spriteFile;
var texture = cc.TextureCache.getInstance().addImage(spriteFile);
- var bounds = cc.RectMake(0, 0, texture.getContentSize().width, texture.getContentSize().height);
+ var locContentSize = texture.getContentSize();
+ var bounds = cc.RectMake(0, 0, locContentSize.width, locContentSize.height);
value = cc.SpriteFrame.createWithTexture(texture, bounds);
} else {
spriteSheet = this._ccbRootPath + spriteSheet;
@@ -675,24 +690,21 @@ cc.BuilderReader = cc.Class.extend({
_readStringFromBytes:function (startIndex, strLen, reverse) {
reverse = reverse || false;
var strValue = "";
- var i;
+ var i, locData = this._data, locCurrentByte = this._currentByte;
if (reverse) {
- for (i = strLen - 1; i >= 0; i--) {
- strValue += String.fromCharCode(this._data[this._currentByte + i]);
- }
+ for (i = strLen - 1; i >= 0; i--)
+ strValue += String.fromCharCode(locData[locCurrentByte + i]);
} else {
- for (i = 0; i < strLen; i++) {
- strValue += String.fromCharCode(this._data[this._currentByte + i]);
- }
+ for (i = 0; i < strLen; i++)
+ strValue += String.fromCharCode(locData[locCurrentByte + i]);
}
return strValue;
},
_readStringCache:function () {
var numStrings = this.readInt(false);
- for (var i = 0; i < numStrings; i++) {
+ for (var i = 0; i < numStrings; i++)
this._readStringCacheEntry();
- }
return true;
},
@@ -702,9 +714,9 @@ cc.BuilderReader = cc.Class.extend({
var numBytes = b0 << 8 | b1;
- var str = "";
+ var str = "", locData = this._data, locCurrentByte = this._currentByte;
for (var i = 0; i < numBytes; i++) {
- var hexChar = this._data[this._currentByte + i].toString("16").toUpperCase();
+ var hexChar = locData[locCurrentByte + i].toString("16").toUpperCase();
hexChar = hexChar.length > 1 ? hexChar : "0" + hexChar;
str += "%" + hexChar;
}
@@ -718,8 +730,8 @@ cc.BuilderReader = cc.Class.extend({
/* Read class name. */
var className = this.readCachedString();
- var jsControlledName;
- if (this._jsControlled)
+ var jsControlledName, locJsControlled = this._jsControlled, locActionManager = this._actionManager;
+ if (locJsControlled)
jsControlledName = this.readCachedString();
var memberVarAssignmentType = this.readInt(false);
@@ -737,19 +749,18 @@ cc.BuilderReader = cc.Class.extend({
var node = ccNodeLoader.loadCCNode(parent, this);
//set root node
- if (!this._actionManager.getRootNode())
- this._actionManager.setRootNode(node);
+ if (!locActionManager.getRootNode())
+ locActionManager.setRootNode(node);
- if (this._jsControlled && node == this._actionManager.getRootNode()) {
- this._actionManager.setDocumentControllerName(jsControlledName);
+ if (locJsControlled && node == locActionManager.getRootNode()) {
+ locActionManager.setDocumentControllerName(jsControlledName);
}
-
//read animated properties
var seqs = new cc._Dictionary();
this._animatedProps = [];
- var i;
+ var i, locAnimatedProps = this._animatedProps;
var numSequence = this.readInt(false);
for (i = 0; i < numSequence; ++i) {
var seqId = this.readInt(false);
@@ -762,12 +773,12 @@ cc.BuilderReader = cc.Class.extend({
seqProp.setName(this.readCachedString());
seqProp.setType(this.readInt(false));
- this._animatedProps.push(seqProp.getName());
+ locAnimatedProps.push(seqProp.getName());
var numKeyframes = this.readInt(false);
-
+ var locKeyframes = seqProp.getKeyframes();
for (var k = 0; k < numKeyframes; ++k) {
var keyFrame = this.readKeyframe(seqProp.getType());
- seqProp.getKeyframes().push(keyFrame);
+ locKeyframes.push(keyFrame);
}
seqNodeProps.setObject(seqProp, seqProp.getName());
}
@@ -775,31 +786,33 @@ cc.BuilderReader = cc.Class.extend({
}
if (seqs.count() > 0)
- this._actionManager.addNode(node, seqs);
+ locActionManager.addNode(node, seqs);
//read properties
ccNodeLoader.parseProperties(node, parent, this);
//handle sub ccb files(remove middle node)
- if (node instanceof cc.BuilderFile) {
+ var isCCBFileNode = node instanceof cc.BuilderFile;
+ if (isCCBFileNode) {
var embeddedNode = node.getCCBFileNode();
embeddedNode.setPosition(node.getPosition());
embeddedNode.setRotation(node.getRotation());
- embeddedNode.setScale(node.getScale());
+ embeddedNode.setScaleX(node.getScaleX());
+ embeddedNode.setScaleY(node.getScaleY());
embeddedNode.setTag(node.getTag());
embeddedNode.setVisible(true);
- embeddedNode.ignoreAnchorPointForPosition(node.isIgnoreAnchorPointForPosition());
+ //embeddedNode.ignoreAnchorPointForPosition(node.isIgnoreAnchorPointForPosition());
+ locActionManager.moveAnimationsFromNode(node, embeddedNode);
node.setCCBFileNode(null);
node = embeddedNode;
}
-
+ var target = null, locMemberAssigner = null;
if (memberVarAssignmentType != CCB_TARGETTYPE_NONE) {
- if (!this._jsControlled) {
- var target = null;
- if (memberVarAssignmentType == CCB_TARGETTYPE_DOCUMENTROOT) {
- target = this._actionManager.getRootNode();
- } else if (memberVarAssignmentType == CCB_TARGETTYPE_OWNER) {
+ if (!locJsControlled) {
+ if (memberVarAssignmentType === CCB_TARGETTYPE_DOCUMENTROOT) {
+ target = locActionManager.getRootNode();
+ } else if (memberVarAssignmentType === CCB_TARGETTYPE_OWNER) {
target = this._owner;
}
@@ -809,15 +822,15 @@ cc.BuilderReader = cc.Class.extend({
if (target != null && (target.onAssignCCBMemberVariable)) {
assigned = target.onAssignCCBMemberVariable(target, memberVarAssignmentName, node);
}
-
- if (!assigned && this._ccbMemberVariableAssigner != null && this._ccbMemberVariableAssigner.onAssignCCBMemberVariable) {
- this._ccbMemberVariableAssigner.onAssignCCBMemberVariable(target, memberVarAssignmentName, node);
+ locMemberAssigner = this._ccbMemberVariableAssigner;
+ if (!assigned && locMemberAssigner != null && locMemberAssigner.onAssignCCBMemberVariable) {
+ locMemberAssigner.onAssignCCBMemberVariable(target, memberVarAssignmentName, node);
}
}
} else {
if (memberVarAssignmentType == CCB_TARGETTYPE_DOCUMENTROOT) {
- this._actionManager.addDocumentOutletName(memberVarAssignmentName);
- this._actionManager.addDocumentOutletNode(node);
+ locActionManager.addDocumentOutletName(memberVarAssignmentName);
+ locActionManager.addDocumentOutletNode(node);
} else {
this._ownerOutletNames.push(memberVarAssignmentName);
this._ownerOutletNodes.push(node);
@@ -828,18 +841,17 @@ cc.BuilderReader = cc.Class.extend({
// Assign custom properties.
if (ccNodeLoader.getCustomProperties().length > 0) {
var customAssigned = false;
-
- if(!this._jsControlled) {
- var target = node;
+ if(!locJsControlled) {
+ target = node;
if(target != null && target.onAssignCCBCustomProperty != null) {
var customProperties = ccNodeLoader.getCustomProperties();
var customPropKeys = customProperties.allKeys();
for(i = 0;i < customPropKeys.length;i++){
var customPropValue = customProperties.objectForKey(customPropKeys[i]);
customAssigned = target.onAssignCCBCustomProperty(target, customPropKeys[i], customPropValue);
-
- if(!customAssigned && (this._ccbMemberVariableAssigner != null) && (this._ccbMemberVariableAssigner.onAssignCCBCustomProperty != null))
- customAssigned = this._ccbMemberVariableAssigner.onAssignCCBCustomProperty(target, customPropKeys[i], customPropValue);
+ locMemberAssigner = this._ccbMemberVariableAssigner;
+ if(!customAssigned && (locMemberAssigner != null) && (locMemberAssigner.onAssignCCBCustomProperty != null))
+ customAssigned = locMemberAssigner.onAssignCCBCustomProperty(target, customPropKeys[i], customPropValue);
}
}
}
@@ -854,11 +866,15 @@ cc.BuilderReader = cc.Class.extend({
node.addChild(child);
}
- // Call onNodeLoaded
- if (node != null && node.onNodeLoaded) {
- node.onNodeLoaded(node, ccNodeLoader);
- } else if (this._ccNodeLoaderListener != null) {
- this._ccNodeLoaderListener.onNodeLoaded(node, ccNodeLoader);
+ // FIX ISSUE #1860: "onNodeLoaded will be called twice if ccb was added as a CCBFile".
+ // If it's a sub-ccb node, skip notification to CCNodeLoaderListener since it will be
+ // notified at LINE #734: CCNode * child = this->readNodeGraph(node);
+ if (!isCCBFileNode) {
+ // Call onNodeLoaded
+ if (node != null && node.onNodeLoaded)
+ node.onNodeLoaded(node, ccNodeLoader);
+ else if (this._ccNodeLoaderListener != null)
+ this._ccNodeLoaderListener.onNodeLoaded(node, ccNodeLoader);
}
return node;
@@ -951,14 +967,21 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) {
var animationManager = animationManagersForNodes[i];
var j;
-
innerNode.animationManager = animationManager;
var documentControllerName = animationManager.getDocumentControllerName();
if (!documentControllerName) continue;
// Create a document controller
- var controller = new _ccbGlobalContext[documentControllerName]();
+ var controller;
+ if(documentControllerName.indexOf(".") > -1){
+ var controllerNameArr = documentControllerName.split(".");
+ controller = _ccbGlobalContext[controllerNameArr[0]];
+ for(var ni = 1, niLen = controllerNameArr.length - 1; ni < niLen; ni++)
+ controller = controller[controllerNameArr[ni]];
+ controller = new controller[controllerNameArr[controllerNameArr.length - 1]]();
+ }else
+ controller = new _ccbGlobalContext[documentControllerName]();
controller.controllerName = documentControllerName;
innerNode.controller = controller;
@@ -988,9 +1011,8 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) {
controller[outletName] = outletNode;
}
- if (controller.onDidLoadFromCCB && typeof(controller.onDidLoadFromCCB) == "function") {
+ if (controller.onDidLoadFromCCB && typeof(controller.onDidLoadFromCCB) == "function")
controller.onDidLoadFromCCB();
- }
// Setup timeline callbacks
var keyframeCallbacks = animationManager.getKeyframeCallbacks();
diff --git a/extensions/CCBReader/CCBReaderUtil.js b/extensions/CCBReader/CCBReaderUtil.js
index b8c63196d6..ec327c8533 100644
--- a/extensions/CCBReader/CCBReaderUtil.js
+++ b/extensions/CCBReader/CCBReaderUtil.js
@@ -45,9 +45,9 @@ cc.BuilderMemberVariableAssigner = cc.Class.extend({
* @param {Object} target The custom class
* @param {string} memberVariableName The name of the member variable.
* @param {cc.Node} node The member variable.
- * @return Whether the assignment was successful.
+ * @return {Boolean} Whether the assignment was successful.
*/
- onAssignCCBMemberVariable:function(target,memberVariableName, node){},
+ onAssignCCBMemberVariable:function(target,memberVariableName, node){ return false;},
/**
* The callback function of assigning custom properties.
@@ -55,7 +55,7 @@ cc.BuilderMemberVariableAssigner = cc.Class.extend({
* @param {Object} target The custom class.
* @param {string} memberVariableName The name of the member variable.
* @param {*} value The value of the property.
- * @return Whether the assignment was successful.
+ * @return {Boolean} Whether the assignment was successful.
*/
- onAssignCCBCustomProperty:function(target, memberVariableName, value){}
+ onAssignCCBCustomProperty:function(target, memberVariableName, value){ return false; }
});
diff --git a/extensions/CCBReader/CCBRelativePositioning.js b/extensions/CCBReader/CCBRelativePositioning.js
index 67948ff407..c23351eadd 100644
--- a/extensions/CCBReader/CCBRelativePositioning.js
+++ b/extensions/CCBReader/CCBRelativePositioning.js
@@ -26,21 +26,21 @@
cc.getAbsolutePosition = function(pt, type, containerSize, propName){
var absPt = cc.p(0,0);
- if(type == CCB_POSITIONTYPE_RELATIVE_BOTTOM_LEFT)
+ if(type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_LEFT)
absPt = pt;
- else if(type == CCB_POSITIONTYPE_RELATIVE_TOP_LEFT){
+ 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){
+ } 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) {
+ } else if (type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_RIGHT) {
absPt.x = containerSize.width - pt.x;
absPt.y = pt.y;
- } else if (type == CCB_POSITIONTYPE_PERCENT) {
+ } 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) {
+ } else if (type === CCB_POSITIONTYPE_MULTIPLY_RESOLUTION) {
var resolutionScale = cc.BuilderReader.getResolutionScale();
absPt.x = pt.x * resolutionScale;
absPt.y = pt.y * resolutionScale;
@@ -49,10 +49,35 @@ cc.getAbsolutePosition = function(pt, type, containerSize, propName){
return absPt;
};
+cc._getAbsolutePosition = function(x, y, type, containerSize, propName){
+ var absPt = 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){
+ absPt.x = x;
+ absPt.y = containerSize.height - y;
+ } 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) {
+ absPt.x = containerSize.width - x;
+ absPt.y = y;
+ } else if (type === CCB_POSITIONTYPE_PERCENT) {
+ absPt.x = (containerSize.width * x / 100.0);
+ absPt.y = (containerSize.height * y / 100.0);
+ } else if (type === CCB_POSITIONTYPE_MULTIPLY_RESOLUTION) {
+ var resolutionScale = cc.BuilderReader.getResolutionScale();
+ absPt.x = x * resolutionScale;
+ absPt.y = y * resolutionScale;
+ }
+ return absPt;
+};
+
cc.setRelativeScale = function(node,scaleX, scaleY, type, propName){
cc.Assert(node, "pNode should not be null");
- if (type == CCB_POSITIONTYPE_MULTIPLY_RESOLUTION) {
+ if (type === CCB_POSITIONTYPE_MULTIPLY_RESOLUTION) {
var resolutionScale = cc.BuilderReader.getResolutionScale();
scaleX *= resolutionScale;
diff --git a/extensions/CCBReader/CCBSequence.js b/extensions/CCBReader/CCBSequence.js
index 4980801bf1..b991c48e4b 100644
--- a/extensions/CCBReader/CCBSequence.js
+++ b/extensions/CCBReader/CCBSequence.js
@@ -77,7 +77,6 @@ cc.BuilderSequence = cc.Class.extend({
setSoundChannel:function(channel) {
this._soundChannel = channel;
}
-
});
cc.BuilderSequenceProperty = cc.Class.extend({
diff --git a/extensions/CCBReader/CCNodeLoader.js b/extensions/CCBReader/CCNodeLoader.js
index 8e879cf9d7..d13df20fe2 100644
--- a/extensions/CCBReader/CCNodeLoader.js
+++ b/extensions/CCBReader/CCNodeLoader.js
@@ -82,7 +82,7 @@ cc.NodeLoader = cc.Class.extend({
var setProp = false;
var platform = ccbReader.readByte();
- if ((platform == CCB_PLATFORM_ALL) ||(platform == CCB_PLATFORM_IOS) ||(platform == CCB_PLATFORM_MAC) )
+ if ((platform === CCB_PLATFORM_ALL) ||(platform === CCB_PLATFORM_IOS) ||(platform === CCB_PLATFORM_MAC) )
setProp = true;
//forward properties for sub ccb files
@@ -106,49 +106,43 @@ cc.NodeLoader = cc.Class.extend({
case CCB_PROPTYPE_POSITION:
{
var position = this.parsePropTypePosition(node, parent, ccbReader, propertyName);
- if (setProp) {
+ if (setProp)
this.onHandlePropTypePosition(node, parent, propertyName, position, ccbReader);
- }
break;
}
case CCB_PROPTYPE_POINT:
{
var point = this.parsePropTypePoint(node, parent, ccbReader);
- if (setProp) {
+ if (setProp)
this.onHandlePropTypePoint(node, parent, propertyName, point, ccbReader);
- }
break;
}
case CCB_PROPTYPE_POINTLOCK:
{
var pointLock = this.parsePropTypePointLock(node, parent, ccbReader);
- if (setProp) {
+ if (setProp)
this.onHandlePropTypePointLock(node, parent, propertyName, pointLock, ccbReader);
- }
break;
}
case CCB_PROPTYPE_SIZE:
{
var size = this.parsePropTypeSize(node, parent, ccbReader);
- if (setProp) {
+ if (setProp)
this.onHandlePropTypeSize(node, parent, propertyName, size, ccbReader);
- }
break;
}
case CCB_PROPTYPE_SCALELOCK:
{
var scaleLock = this.parsePropTypeScaleLock(node, parent, ccbReader, propertyName);
- if (setProp) {
+ if (setProp)
this.onHandlePropTypeScaleLock(node, parent, propertyName, scaleLock, ccbReader);
- }
break;
}
case CCB_PROPTYPE_FLOATXY:
{
var xy = this.parsePropTypeFloatXY(node, parent, ccbReader);
- if (setProp) {
+ if (setProp)
this.onHandlePropTypeFloatXY(node, parent, propertyName, xy, ccbReader);
- }
break;
}
@@ -350,7 +344,7 @@ cc.NodeLoader = cc.Class.extend({
var type = ccbReader.readInt(false);
var containerSize = ccbReader.getAnimationManager().getContainerSize(parent);
- var pt = cc.getAbsolutePosition(cc.p(x,y),type,containerSize,propertyName);
+ var pt = cc._getAbsolutePosition(x,y,type,containerSize,propertyName);
node.setPosition(cc.getAbsolutePosition(pt,type,containerSize,propertyName)); //different to -x node.setPosition(pt);
if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
@@ -620,12 +614,12 @@ cc.NodeLoader = cc.Class.extend({
var selectorName = ccbReader.readCachedString();
var selectorTarget = ccbReader.readInt(false);
- if (selectorTarget != CCB_TARGETTYPE_NONE) {
+ if (selectorTarget !== CCB_TARGETTYPE_NONE) {
var target = null;
if(!ccbReader.isJSControlled()) {
- if (selectorTarget == CCB_TARGETTYPE_DOCUMENTROOT) {
+ if (selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT) {
target = ccbReader.getAnimationManager().getRootNode();
- } else if (selectorTarget == CCB_TARGETTYPE_OWNER) {
+ } else if (selectorTarget === CCB_TARGETTYPE_OWNER) {
target = ccbReader.getOwner();
}
@@ -634,14 +628,13 @@ cc.NodeLoader = cc.Class.extend({
var selMenuHandler = 0;
//var targetAsCCBSelectorResolver = target;
- if (target != null && target.onResolveCCBCCMenuItemSelector) {
+ if (target != null && target.onResolveCCBCCMenuItemSelector)
selMenuHandler = target.onResolveCCBCCMenuItemSelector(target, selectorName);
- }
+
if (selMenuHandler == 0) {
var ccbSelectorResolver = ccbReader.getCCBSelectorResolver();
- if (ccbSelectorResolver != null) {
+ if (ccbSelectorResolver != null)
selMenuHandler = ccbSelectorResolver.onResolveCCBCCMenuItemSelector(target, selectorName);
- }
}
if (selMenuHandler == 0) {
@@ -656,7 +649,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);
@@ -674,7 +667,7 @@ cc.NodeLoader = cc.Class.extend({
var selectorTarget = ccbReader.readInt(false);
var controlEvents = ccbReader.readInt(false);
- if (selectorTarget != CCB_TARGETTYPE_NONE) {
+ if (selectorTarget !== CCB_TARGETTYPE_NONE) {
if(!ccbReader.isJSControlled()){
var target = null;
if (selectorTarget == CCB_TARGETTYPE_DOCUMENTROOT) {
@@ -730,11 +723,12 @@ cc.NodeLoader = cc.Class.extend({
ccbFileName = ccbFileWithoutPathExtension + ".ccbi";
//load sub file
- var path = cc.FileUtils.getInstance().fullPathFromRelativePath(ccbFileName);
+ var fileUtils = cc.FileUtils.getInstance();
+ var path = fileUtils.fullPathFromRelativePath(ccbFileName);
var myCCBReader = new cc.BuilderReader(ccbReader);
var size ;
- var bytes = cc.FileUtils.getInstance().getByteArrayFromFile(path,"rb", size);
+ var bytes = fileUtils.getByteArrayFromFile(path,"rb", size);
myCCBReader.initWithData(bytes,ccbReader.getOwner());
myCCBReader.getAnimationManager().setRootContainerSize(parent.getContentSize());
@@ -844,7 +838,7 @@ cc.NodeLoader = cc.Class.extend({
onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) {
if (propertyName === PROPERTY_VISIBLE) {
node.setVisible(check);
- } else if (propertyName == PROPERTY_IGNOREANCHORPOINTFORPOSITION) {
+ } else if (propertyName === PROPERTY_IGNOREANCHORPOINTFORPOSITION) {
node.ignoreAnchorPointForPosition(check);
} else {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
diff --git a/extensions/CCBReader/CCSpriteLoader.js b/extensions/CCBReader/CCSpriteLoader.js
index 85e841282f..cd08b83ad5 100644
--- a/extensions/CCBReader/CCSpriteLoader.js
+++ b/extensions/CCBReader/CCSpriteLoader.js
@@ -36,35 +36,38 @@ cc.SpriteLoader = cc.NodeLoader.extend({
},
onHandlePropTypeColor3:function (node, parent, propertyName, color3BValue, ccbReader) {
- if (propertyName == PROPERTY_COLOR) {
+ if (propertyName === PROPERTY_COLOR) {
node.setColor(color3BValue);
} else {
cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, color3BValue, ccbReader);
}
},
onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) {
- if (propertyName == PROPERTY_OPACITY) {
+ if (propertyName === PROPERTY_OPACITY) {
node.setOpacity(byteValue);
} else {
cc.NodeLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader);
}
},
onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccbBlendFunc, ccbReader) {
- if (propertyName == PROPERTY_BLENDFUNC) {
+ if (propertyName === PROPERTY_BLENDFUNC) {
node.setBlendFunc(ccbBlendFunc);
} else {
cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccbBlendFunc, ccbReader);
}
},
onHandlePropTypeSpriteFrame:function (node, parent, propertyName, ccSpriteFrame, ccbReader) {
- if (propertyName == PROPERTY_DISPLAYFRAME) {
- node.setDisplayFrame(ccSpriteFrame);
+ if (propertyName === PROPERTY_DISPLAYFRAME) {
+ if(ccSpriteFrame)
+ node.setDisplayFrame(ccSpriteFrame);
+ else
+ cc.log("ERROR: SpriteFrame is null");
} else {
cc.NodeLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, ccSpriteFrame, ccbReader);
}
},
onHandlePropTypeFlip:function (node, parent, propertyName, flip, ccbReader) {
- if (propertyName == PROPERTY_FLIP) {
+ if (propertyName === PROPERTY_FLIP) {
node.setFlipX(flip[0]);
node.setFlipY(flip[1]);
} else {
@@ -91,15 +94,15 @@ cc.LayerLoader = cc.NodeLoader.extend({
return cc.Layer.create();
},
onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) {
- if (propertyName == PROPERTY_TOUCH_ENABLED || propertyName == PROPERTY_IS_TOUCH_ENABLED) {
+ if (propertyName === PROPERTY_TOUCH_ENABLED || propertyName === PROPERTY_IS_TOUCH_ENABLED) {
node.setTouchEnabled(check);
- } else if (propertyName == PROPERTY_ACCELEROMETER_ENABLED || propertyName == PROPERTY_IS_ACCELEROMETER_ENABLED) {
+ } else if (propertyName === PROPERTY_ACCELEROMETER_ENABLED || propertyName === PROPERTY_IS_ACCELEROMETER_ENABLED) {
node.setAccelerometerEnabled(check);
- } else if (propertyName == PROPERTY_MOUSE_ENABLED || propertyName == PROPERTY_IS_MOUSE_ENABLED ) {
+ } else if (propertyName === PROPERTY_MOUSE_ENABLED || propertyName === PROPERTY_IS_MOUSE_ENABLED ) {
node.setMouseEnabled(check);
- } else if (propertyName == PROPERTY_KEYBOARD_ENABLED || propertyName == PROPERTY_IS_KEYBOARD_ENABLED) {
+ } else if (propertyName === PROPERTY_KEYBOARD_ENABLED || propertyName === PROPERTY_IS_KEYBOARD_ENABLED) {
// TODO XXX
- if(node.setKeyboardEnabled && sys.platform == "browser") {
+ if(node.setKeyboardEnabled && sys.platform === "browser") {
node.setKeyboardEnabled(check);
} else {
cc.log("The property '" + PROPERTY_IS_KEYBOARD_ENABLED + "' is not supported!");
@@ -122,21 +125,21 @@ cc.LayerColorLoader = cc.LayerLoader.extend({
},
onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
- if (propertyName == PROPERTY_COLOR) {
+ if (propertyName === PROPERTY_COLOR) {
node.setColor(ccColor3B);
} else {
cc.LayerLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader);
}
},
onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) {
- if (propertyName == PROPERTY_OPACITY) {
+ if (propertyName === PROPERTY_OPACITY) {
node.setOpacity(byteValue);
} else {
cc.LayerLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader);
}
},
onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) {
- if (propertyName == PROPERTY_BLENDFUNC) {
+ if (propertyName === PROPERTY_BLENDFUNC) {
node.setBlendFunc(ccBlendFunc);
} else {
cc.LayerLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader);
@@ -159,7 +162,7 @@ cc.LayerGradientLoader = cc.LayerLoader.extend({
return cc.LayerGradient.create();
},
onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
- if (propertyName == PROPERTY_STARTCOLOR) {
+ if (propertyName === PROPERTY_STARTCOLOR) {
node.setStartColor(ccColor3B);
} else if (propertyName == PROPERTY_ENDCOLOR) {
node.setEndColor(ccColor3B);
@@ -168,16 +171,16 @@ cc.LayerGradientLoader = cc.LayerLoader.extend({
}
},
onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) {
- if (propertyName == PROPERTY_STARTOPACITY) {
+ if (propertyName === PROPERTY_STARTOPACITY) {
node.setStartOpacity(byteValue);
- } else if (propertyName == PROPERTY_ENDOPACITY) {
+ } else if (propertyName === PROPERTY_ENDOPACITY) {
node.setEndOpacity(byteValue);
} else {
cc.LayerLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader);
}
},
onHandlePropTypePoint:function (node, parent, propertyName, point, ccbReader) {
- if (propertyName == PROPERTY_VECTOR) {
+ if (propertyName === PROPERTY_VECTOR) {
node.setVector(point);
// TODO Not passed along the ccbi file.
// node.setCompressedInterpolation(true);
@@ -186,7 +189,7 @@ cc.LayerGradientLoader = cc.LayerLoader.extend({
}
},
onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) {
- if (propertyName == PROPERTY_BLENDFUNC) {
+ if (propertyName === PROPERTY_BLENDFUNC) {
node.setBlendFunc(ccBlendFunc);
} else {
cc.LayerLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader);
@@ -217,7 +220,7 @@ cc.MenuItemLoader = cc.NodeLoader.extend({
},
onHandlePropTypeBlock:function (node, parent, propertyName, blockData, ccbReader) {
- if (propertyName == PROPERTY_BLOCK) {
+ if (propertyName === PROPERTY_BLOCK) {
if (null != blockData) { // Add this condition to allow CCMenuItemImage without target/selector predefined
node.setTarget(blockData.selMenuHander, blockData.target);
}
@@ -226,7 +229,7 @@ cc.MenuItemLoader = cc.NodeLoader.extend({
}
},
onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) {
- if (propertyName == PROPERTY_ISENABLED) {
+ if (propertyName === PROPERTY_ISENABLED) {
node.setEnabled(check);
} else {
cc.NodeLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader);
@@ -244,15 +247,15 @@ cc.MenuItemImageLoader = cc.MenuItemLoader.extend({
},
onHandlePropTypeSpriteFrame:function (node, parent, propertyName, spriteFrame, ccbReader) {
- if (propertyName == PROPERTY_NORMALDISPLAYFRAME) {
+ if (propertyName === PROPERTY_NORMALDISPLAYFRAME) {
if (spriteFrame != null) {
node.setNormalSpriteFrame(spriteFrame);
}
- } else if (propertyName == PROPERTY_SELECTEDDISPLAYFRAME) {
+ } else if (propertyName === PROPERTY_SELECTEDDISPLAYFRAME) {
if (spriteFrame != null) {
node.setSelectedSpriteFrame(spriteFrame);
}
- } else if (propertyName == PROPERTY_DISABLEDDISPLAYFRAME) {
+ } else if (propertyName === PROPERTY_DISABLEDDISPLAYFRAME) {
if (spriteFrame != null) {
node.setDisabledSpriteFrame(spriteFrame);
}
@@ -278,58 +281,58 @@ cc.LabelTTFLoader = cc.NodeLoader.extend({
return cc.LabelTTF.create();
},
onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
- if (propertyName == PROPERTY_COLOR) {
+ if (propertyName === PROPERTY_COLOR) {
node.setColor(ccColor3B);
} else {
cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader);
}
},
onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) {
- if (propertyName == PROPERTY_OPACITY) {
+ if (propertyName === PROPERTY_OPACITY) {
node.setOpacity(byteValue);
} else {
cc.NodeLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader);
}
},
onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) {
- if (propertyName == PROPERTY_BLENDFUNC) {
+ if (propertyName === PROPERTY_BLENDFUNC) {
node.setBlendFunc(ccBlendFunc);
} else {
cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader);
}
},
onHandlePropTypeFontTTF:function (node, parent, propertyName, fontTTF, ccbReader) {
- if (propertyName == PROPERTY_FONTNAME) {
+ if (propertyName === PROPERTY_FONTNAME) {
node.setFontName(fontTTF);
} else {
cc.NodeLoader.prototype.onHandlePropTypeFontTTF.call(this, node, parent, propertyName, fontTTF, ccbReader);
}
},
onHandlePropTypeText:function (node, parent, propertyName, textValue, ccbReader) {
- if (propertyName == PROPERTY_STRING) {
+ if (propertyName === PROPERTY_STRING) {
node.setString(textValue);
} else {
cc.NodeLoader.prototype.onHandlePropTypeText.call(this, node, parent, propertyName, textValue, ccbReader);
}
},
onHandlePropTypeFloatScale:function (node, parent, propertyName, floatScale, ccbReader) {
- if (propertyName == PROPERTY_FONTSIZE) {
+ if (propertyName === PROPERTY_FONTSIZE) {
node.setFontSize(floatScale);
} else {
cc.NodeLoader.prototype.onHandlePropTypeFloatScale.call(this, node, parent, propertyName, floatScale, ccbReader);
}
},
onHandlePropTypeIntegerLabeled:function (node, parent, propertyName, integerLabeled, ccbReader) {
- if (propertyName == PROPERTY_HORIZONTALALIGNMENT) {
+ if (propertyName === PROPERTY_HORIZONTALALIGNMENT) {
node.setHorizontalAlignment(integerLabeled);
- } else if (propertyName == PROPERTY_VERTICALALIGNMENT) {
+ } else if (propertyName === PROPERTY_VERTICALALIGNMENT) {
node.setVerticalAlignment(integerLabeled);
} else {
cc.NodeLoader.prototype.onHandlePropTypeIntegerLabeled.call(this, node, parent, propertyName, integerLabeled, ccbReader);
}
},
onHandlePropTypeSize:function (node, parent, propertyName, size, ccbReader) {
- if (propertyName == PROPERTY_DIMENSIONS) {
+ if (propertyName === PROPERTY_DIMENSIONS) {
node.setDimensions(size);
} else {
cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size, ccbReader);
@@ -349,35 +352,35 @@ cc.LabelBMFontLoader = cc.NodeLoader.extend({
},
onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
- if (propertyName == PROPERTY_COLOR) {
+ if (propertyName === PROPERTY_COLOR) {
node.setColor(ccColor3B);
} else {
cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader);
}
},
onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) {
- if (propertyName == PROPERTY_OPACITY) {
+ if (propertyName === PROPERTY_OPACITY) {
node.setOpacity(byteValue);
} else {
cc.NodeLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader);
}
},
onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) {
- if (propertyName == PROPERTY_BLENDFUNC) {
+ if (propertyName === PROPERTY_BLENDFUNC) {
node.setBlendFunc(ccBlendFunc);
} else {
cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader);
}
},
onHandlePropTypeFntFile:function (node, parent, propertyName, fntFile, ccbReader) {
- if (propertyName == PROPERTY_FNTFILE) {
+ if (propertyName === PROPERTY_FNTFILE) {
node.setFntFile(fntFile);
} else {
cc.NodeLoader.prototype.onHandlePropTypeFntFile.call(this, node, parent, propertyName, fntFile, ccbReader);
}
},
onHandlePropTypeText:function (node, parent, propertyName, textValue, ccbReader) {
- if (propertyName == PROPERTY_STRING) {
+ if (propertyName === PROPERTY_STRING) {
node.setString(textValue);
} else {
cc.NodeLoader.prototype.onHandlePropTypeText.call(this, node, parent, propertyName, textValue, ccbReader);
@@ -415,72 +418,72 @@ cc.ParticleSystemQuadLoader = cc.NodeLoader.extend({
},
onHandlePropTypeIntegerLabeled:function (node, parent, propertyName, integerLabeled, ccbReader) {
- if (propertyName == PROPERTY_EMITERMODE) {
+ if (propertyName === PROPERTY_EMITERMODE) {
node.setEmitterMode(integerLabeled);
} else {
cc.NodeLoader.prototype.onHandlePropTypeIntegerLabeled.call(this, node, parent, propertyName, integerLabeled, ccbReader);
}
},
onHandlePropTypePoint:function (node, parent, propertyName, point, ccbReader) {
- if (propertyName == PROPERTY_POSVAR) {
+ if (propertyName === PROPERTY_POSVAR) {
node.setPosVar(point);
- } else if (propertyName == PROPERTY_GRAVITY) {
+ } else if (propertyName === PROPERTY_GRAVITY) {
node.setGravity(point);
} else {
cc.NodeLoader.prototype.onHandlePropTypePoint.call(this, node, parent, propertyName, point, ccbReader);
}
},
onHandlePropTypeFloat:function (node, parent, propertyName, floatValue, ccbReader) {
- if (propertyName == PROPERTY_EMISSIONRATE) {
+ if (propertyName === PROPERTY_EMISSIONRATE) {
node.setEmissionRate(floatValue);
- } else if (propertyName == PROPERTY_DURATION) {
+ } else if (propertyName === PROPERTY_DURATION) {
node.setDuration(floatValue);
} else {
cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue, ccbReader);
}
},
onHandlePropTypeInteger:function (node, parent, propertyName, integerValue, ccbReader) {
- if (propertyName == PROPERTY_TOTALPARTICLES) {
+ if (propertyName === PROPERTY_TOTALPARTICLES) {
node.setTotalParticles(integerValue);
} else {
cc.NodeLoader.prototype.onHandlePropTypeInteger.call(this, node, parent, propertyName, integerValue, ccbReader);
}
},
onHandlePropTypeFloatVar:function (node, parent, propertyName, floatVar, ccbReader) {
- if (propertyName == PROPERTY_LIFE) {
+ if (propertyName === PROPERTY_LIFE) {
node.setLife(floatVar[0]);
node.setLifeVar(floatVar[1]);
- } else if (propertyName == PROPERTY_STARTSIZE) {
+ } else if (propertyName === PROPERTY_STARTSIZE) {
node.setStartSize(floatVar[0]);
node.setStartSizeVar(floatVar[1]);
- } else if (propertyName == PROPERTY_ENDSIZE) {
+ } else if (propertyName === PROPERTY_ENDSIZE) {
node.setEndSize(floatVar[0]);
node.setEndSizeVar(floatVar[1]);
- } else if (propertyName == PROPERTY_STARTSPIN) {
+ } else if (propertyName === PROPERTY_STARTSPIN) {
node.setStartSpin(floatVar[0]);
node.setStartSpinVar(floatVar[1]);
- } else if (propertyName == PROPERTY_ENDSPIN) {
+ } else if (propertyName === PROPERTY_ENDSPIN) {
node.setEndSpin(floatVar[0]);
node.setEndSpinVar(floatVar[1]);
- } else if (propertyName == PROPERTY_ANGLE) {
+ } else if (propertyName === PROPERTY_ANGLE) {
node.setAngle(floatVar[0]);
node.setAngleVar(floatVar[1]);
- } else if (propertyName == PROPERTY_SPEED) {
+ } else if (propertyName === PROPERTY_SPEED) {
node.setSpeed(floatVar[0]);
node.setSpeedVar(floatVar[1]);
- } else if (propertyName == PROPERTY_TANGENTIALACCEL) {
+ } else if (propertyName === PROPERTY_TANGENTIALACCEL) {
node.setTangentialAccel(floatVar[0]);
node.setTangentialAccelVar(floatVar[1]);
- } else if (propertyName == PROPERTY_RADIALACCEL) {
+ } else if (propertyName === PROPERTY_RADIALACCEL) {
node.setRadialAccel(floatVar[0]);
node.setRadialAccelVar(floatVar[1]);
- } else if (propertyName == PROPERTY_STARTRADIUS) {
+ } else if (propertyName === PROPERTY_STARTRADIUS) {
node.setStartRadius(floatVar[0]);
node.setStartRadiusVar(floatVar[1]);
- } else if (propertyName == PROPERTY_ENDRADIUS) {
+ } else if (propertyName === PROPERTY_ENDRADIUS) {
node.setEndRadius(floatVar[0]);
node.setEndRadiusVar(floatVar[1]);
- } else if (propertyName == PROPERTY_ROTATEPERSECOND) {
+ } else if (propertyName === PROPERTY_ROTATEPERSECOND) {
node.setRotatePerSecond(floatVar[0]);
node.setRotatePerSecondVar(floatVar[1]);
} else {
@@ -488,10 +491,10 @@ cc.ParticleSystemQuadLoader = cc.NodeLoader.extend({
}
},
onHandlePropTypeColor4FVar:function (node, parent, propertyName, ccColor4FVar, ccbReader) {
- if (propertyName == PROPERTY_STARTCOLOR) {
+ if (propertyName === PROPERTY_STARTCOLOR) {
node.setStartColor(ccColor4FVar[0]);
node.setStartColorVar(ccColor4FVar[1]);
- } else if (propertyName == PROPERTY_ENDCOLOR) {
+ } else if (propertyName === PROPERTY_ENDCOLOR) {
node.setEndColor(ccColor4FVar[0]);
node.setEndColorVar(ccColor4FVar[1]);
} else {
@@ -499,14 +502,14 @@ cc.ParticleSystemQuadLoader = cc.NodeLoader.extend({
}
},
onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) {
- if (propertyName == PROPERTY_BLENDFUNC) {
+ if (propertyName === PROPERTY_BLENDFUNC) {
node.setBlendFunc(ccBlendFunc);
} else {
cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader);
}
},
onHandlePropTypeTexture:function (node, parent, propertyName, ccTexture2D, ccbReader) {
- if (propertyName == PROPERTY_TEXTURE) {
+ if (propertyName === PROPERTY_TEXTURE) {
node.setTexture(ccTexture2D);
} else {
cc.NodeLoader.prototype.onHandlePropTypeTexture.call(this, node, parent, propertyName, ccTexture2D, ccbReader);
From 2bf826fcb9f5f6af151805253bc96d6a9eaa384a Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Tue, 3 Sep 2013 14:32:03 +0800
Subject: [PATCH 077/141] Closed #2762: Refactor CCSimpleAudioEngine.js for
code maintainability
---
CocosDenshion/SimpleAudioEngine.js | 238 ++++++++++++++---------------
1 file changed, 114 insertions(+), 124 deletions(-)
diff --git a/CocosDenshion/SimpleAudioEngine.js b/CocosDenshion/SimpleAudioEngine.js
index 0cafb66c9c..76acc46b61 100644
--- a/CocosDenshion/SimpleAudioEngine.js
+++ b/CocosDenshion/SimpleAudioEngine.js
@@ -69,16 +69,16 @@ cc.AudioEngine = cc.Class.extend(/** @lends cc.AudioEngine# */{
/**
* Helper function for cutting out the extension from the path
* @param {String} fullpath
+ * @return {String|null} path without ext name
* @protected
*/
_getPathWithoutExt: function (fullpath) {
if (typeof(fullpath) != "string") {
- return;
+ return null;
}
var endPos = fullpath.lastIndexOf(".");
- if (endPos != -1) {
+ if (endPos !== -1)
return fullpath.substring(0, endPos);
- }
return fullpath;
},
@@ -89,7 +89,7 @@ cc.AudioEngine = cc.Class.extend(/** @lends cc.AudioEngine# */{
*/
_getExtFromFullPath: function (fullpath) {
var startPos = fullpath.lastIndexOf(".");
- if (startPos != -1) {
+ if (startPos !== -1) {
return fullpath.substring(startPos + 1, fullpath.length);
}
return -1;
@@ -113,21 +113,15 @@ cc.SimpleSFX = function (audio, ext) {
* @extends cc.AudioEngine
*/
cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */{
- _supportedFormat:[],
- _soundEnable:false,
+ _supportedFormat:null,
_effectList:{},
_soundList:{},
_playingMusic:null,
_effectsVolume:1,
_maxAudioInstance:10,
+ _capabilities:null,
+ _soundSupported:false,
_canPlay:true,
- _capabilities:{
- mp3:false,
- ogg:false,
- wav:false,
- mp4:false,
- m4a:false
- },
/**
* Constructor
@@ -136,12 +130,17 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
cc.AudioEngine.prototype.ctor.call(this);
this._supportedFormat = [];
- this._checkCanPlay(this._capabilities);
+ this._effectList = {};
+ this._soundList = {};
+
+ this._capabilities = { mp3: false, ogg: false, wav: false, mp4: false, m4a: false};
+ var locCapabilities = this._capabilities;
+ this._checkCanPlay(locCapabilities);
// enable sound if any of the audio format is supported
- this._soundEnable = this._capabilities.mp3 || this._capabilities.mp4
- || this._capabilities.m4a || this._capabilities.ogg
- || this._capabilities.wav;
+ this._soundSupported = locCapabilities.mp3 || locCapabilities.mp4
+ || locCapabilities.m4a || locCapabilities.ogg
+ || locCapabilities.wav;
var ua = navigator.userAgent;
if(/Mobile/.test(ua) && (/iPhone OS/.test(ua)||/iPad/.test(ua)||/Firefox/.test(ua)) || /MSIE/.test(ua)){
@@ -156,7 +155,7 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
init:function () {
// detect the prefered audio format
this._getSupportedAudioFormat();
- return this._soundEnable;
+ return this._soundSupported;
},
/**
@@ -165,7 +164,7 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
* @param {String} path The path of the music file with filename extension.
*/
preloadSound:function (path) {
- if (this._soundEnable) {
+ if (this._soundSupported) {
var extName = this._getExtFromFullPath(path);
var keyname = this._getPathWithoutExt(path);
if (this.isFormatSupported(extName) && !this._soundList.hasOwnProperty(keyname)) {
@@ -174,31 +173,26 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
sfxCache.ext = extName;
sfxCache.audio = new Audio(path);
sfxCache.audio.preload = 'auto';
- sfxCache.audio.addEventListener('canplaythrough', function (e) {
+ var soundPreloadCanplayHandler = function (e) {
cc.Loader.getInstance().onResLoaded();
- this.removeEventListener('canplaythrough', arguments.callee, false);
- this.removeEventListener('error', arguments.callee, false);
- }, false);
-
- sfxCache.audio.addEventListener("error", function (e) {
+ this.removeEventListener('canplaythrough', soundPreloadCanplayHandler, false);
+ this.removeEventListener('error', soundPreloadErrorHandler, false);
+ };
+ var soundPreloadErrorHandler = function (e) {
cc.Loader.getInstance().onResLoadingErr(e.srcElement.src);
- this.removeEventListener('error', arguments.callee, false);
- }, false);
+ this.removeEventListener('canplaythrough', soundPreloadCanplayHandler, false);
+ this.removeEventListener('error', soundPreloadErrorHandler, false);
+ };
+ sfxCache.audio.addEventListener('canplaythrough', soundPreloadCanplayHandler, false);
+ sfxCache.audio.addEventListener("error", soundPreloadErrorHandler, false);
this._soundList[keyname] = sfxCache;
sfxCache.audio.load();
- }
- else{
- cc.Loader.getInstance().onResLoaded();
+ return;
}
}
- else {
- cc.Loader.getInstance().onResLoaded();
- }
- }
- else {
- cc.Loader.getInstance().onResLoaded();
}
+ cc.Loader.getInstance().onResLoaded();
},
/**
@@ -210,27 +204,27 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
* cc.AudioEngine.getInstance().playMusic(path, false);
*/
playMusic:function (path, loop) {
- if (!this._soundEnable)
+ if (!this._soundSupported)
return;
var keyname = this._getPathWithoutExt(path);
var extName = this._getExtFromFullPath(path);
var au;
- if (this._soundList.hasOwnProperty(this._playingMusic)) {
- this._soundList[this._playingMusic].audio.pause();
+ var locSoundList = this._soundList;
+ if (locSoundList.hasOwnProperty(this._playingMusic)) {
+ locSoundList[this._playingMusic].audio.pause();
}
this._playingMusic = keyname;
- if (this._soundList.hasOwnProperty(this._playingMusic)) {
- au = this._soundList[this._playingMusic].audio;
- }
- else {
+ if (locSoundList.hasOwnProperty(this._playingMusic)) {
+ au = locSoundList[this._playingMusic].audio;
+ } else {
var sfxCache = new cc.SimpleSFX();
sfxCache.ext = extName;
au = sfxCache.audio = new Audio(path);
sfxCache.audio.preload = 'auto';
- this._soundList[keyname] = sfxCache;
+ locSoundList[keyname] = sfxCache;
sfxCache.audio.load();
}
@@ -254,12 +248,13 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
* cc.AudioEngine.getInstance().stopMusic();
*/
stopMusic:function (releaseData) {
- if (this._soundList.hasOwnProperty(this._playingMusic)) {
- var au = this._soundList[this._playingMusic].audio;
+ var locSoundList = this._soundList, locPlayingMusic = this._playingMusic;
+ if (locSoundList.hasOwnProperty(locPlayingMusic)) {
+ var au = locSoundList[locPlayingMusic].audio;
au.pause();
au.currentTime = au.duration;
if (releaseData) {
- delete this._soundList[this._playingMusic];
+ delete locSoundList[locPlayingMusic];
}
cc.AudioEngine.isMusicPlaying = false;
}
@@ -340,11 +335,9 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
var music = this._soundList[this._playingMusic].audio;
if (volume > 1) {
music.volume = 1;
- }
- else if (volume < 0) {
+ } else if (volume < 0) {
music.volume = 0;
- }
- else {
+ } else {
music.volume = volume;
}
}
@@ -370,19 +363,19 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
* Play sound effect.
* @param {String} path The path of the sound effect with filename extension.
* @param {Boolean} loop Whether to loop the effect playing, default value is false
+ * @return {Number|null} the audio id
* @example
* //example
* var soundId = cc.AudioEngine.getInstance().playEffect(path);
*/
- playEffect:function (path, loop) {
- if (!this._soundEnable)
- return;
+ playEffect: function (path, loop) {
+ if (!this._soundSupported)
+ return null;
var keyname = this._getPathWithoutExt(path), actExt;
if (this._soundList.hasOwnProperty(keyname)) {
actExt = this._soundList[keyname].ext;
- }
- else {
+ } else {
actExt = this._getExtFromFullPath(path);
}
@@ -393,9 +386,8 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
if (reclaim[i].ended) {
au = reclaim[i];
au.currentTime = 0;
- if (window.chrome){
+ if (window.chrome)
au.load();
- }
break;
}
}
@@ -411,13 +403,11 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
reclaim.push(au);
}
- if (loop) {
+ if (loop)
au.loop = loop;
- }
au.play();
var audioID = this._audioID++;
this._audioIDList[audioID] = au;
-
return audioID;
},
@@ -440,19 +430,16 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
* cc.AudioEngine.getInstance().setEffectsVolume(0.5);
*/
setEffectsVolume:function (volume) {
- if (volume > 1) {
+ if (volume > 1)
this._effectsVolume = 1;
- }
- else if (volume < 0) {
+ else if (volume < 0)
this._effectsVolume = 0;
- }
- else {
+ else
this._effectsVolume = volume;
- }
- var tmpArr, au;
- for (var i in this._effectList) {
- tmpArr = this._effectList[i];
+ var tmpArr, au, locEffectList = this._effectList;
+ for (var i in locEffectList) {
+ tmpArr = locEffectList[i];
if (tmpArr.length > 0) {
for (var j = 0; j < tmpArr.length; j++) {
au = tmpArr[j];
@@ -488,13 +475,13 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
*/
pauseAllEffects:function () {
var tmpArr, au;
- for (var i in this._effectList) {
- tmpArr = this._effectList[i];
+ var locEffectList = this._effectList;
+ for (var i in locEffectList) {
+ tmpArr = locEffectList[i];
for (var j = 0; j < tmpArr.length; j++) {
au = tmpArr[j];
- if (!au.ended) {
+ if (!au.ended)
au.pause();
- }
}
}
},
@@ -511,9 +498,8 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
if (this._audioIDList.hasOwnProperty(audioID)) {
var au = this._audioIDList[audioID];
- if (!au.ended) {
+ if (!au.ended)
au.play();
- }
}
},
@@ -525,14 +511,14 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
*/
resumeAllEffects:function () {
var tmpArr, au;
- for (var i in this._effectList) {
- tmpArr = this._effectList[i];
+ var locEffectList = this._effectList;
+ for (var i in locEffectList) {
+ tmpArr = locEffectList[i];
if (tmpArr.length > 0) {
for (var j = 0; j < tmpArr.length; j++) {
au = tmpArr[j];
- if (!au.ended) {
+ if (!au.ended)
au.play();
- }
}
}
}
@@ -564,9 +550,9 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
* cc.AudioEngine.getInstance().stopAllEffects();
*/
stopAllEffects:function () {
- var tmpArr, au;
- for (var i in this._effectList) {
- tmpArr = this._effectList[i];
+ var tmpArr, au, locEffectList = this._effectList;
+ for (var i in locEffectList) {
+ tmpArr = locEffectList[i];
for (var j = 0; j < tmpArr.length; j++) {
au = tmpArr[j];
if (!au.ended) {
@@ -591,24 +577,24 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
delete this._effectList[keyname];
}
- var au,pathName;
- for (var k in this._audioIDList) {
- au = this._audioIDList[k];
+ var au, pathName, locAudioIDList = this._audioIDList;
+ for (var k in locAudioIDList) {
+ au = locAudioIDList[k];
pathName = this._getPathWithoutExt(au.src);
if(pathName.indexOf(keyname) > -1){
this.stopEffect(k);
- delete this._audioIDList[k];
+ delete locAudioIDList[k];
}
}
},
_getEffectList:function (elt) {
- if (this._effectList.hasOwnProperty(elt)) {
- return this._effectList[elt];
- }
- else {
- this._effectList[elt] = [];
- return this._effectList[elt];
+ var locEffectList = this._effectList;
+ if (locEffectList.hasOwnProperty(elt)) {
+ return locEffectList[elt];
+ } else {
+ locEffectList[elt] = [];
+ return locEffectList[elt];
}
},
@@ -617,20 +603,19 @@ cc.SimpleAudioEngine = cc.AudioEngine.extend(/** @lends cc.SimpleAudioEngine# */
* @param {String} ext
* @returns {Boolean}
*/
- isFormatSupported:function (ext) {
- var tmpExt;
- for (var i = 0; i < this._supportedFormat.length; i++) {
- tmpExt = this._supportedFormat[i];
- if (tmpExt == ext) {
+ isFormatSupported: function (ext) {
+ var tmpExt, locSupportedFormat = this._supportedFormat;
+ for (var i = 0; i < locSupportedFormat.length; i++) {
+ tmpExt = locSupportedFormat[i];
+ if (tmpExt == ext)
return true;
- }
}
return false;
},
_getSupportedAudioFormat:function () {
// check for sound support by the browser
- if (!this._soundEnable) {
+ if (!this._soundSupported) {
return;
}
@@ -675,11 +660,11 @@ cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{
// the Web Audio Context
_ctx: null,
// may be: mp3, ogg, wav, mp4, m4a
- _supportedFormat: [],
+ _supportedFormat: null,
// if sound is not enabled, this engine's init() will return false
- _soundEnable: false,
+ _soundSupported: false,
// containing all binary buffers of loaded audio resources
- _audioData: {},
+ _audioData: null,
/*
* Issue: When loading two resources with different suffixes asynchronously, the second one might start loading
* when the first one is already loading!
@@ -687,13 +672,13 @@ cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{
* exception "DOM exception 12", it should be a bug of the browser.
* So just add something to mark some audios as LOADING so as to avoid duplication.
*/
- _audiosLoading: {},
+ _audiosLoading: null,
// the music being played, cc.WebAudioSFX, when null, no music is being played; when not null, it may be playing or paused
_music: null,
// the volume applied to the music
_musicVolume: 1,
// the effects being played: { key => [cc.WebAudioSFX] }, many effects of the same resource may be played simultaneously
- _effects: {},
+ _effects: null,
// the volume applied to all effects
_effectsVolume: 1,
@@ -713,6 +698,10 @@ cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{
*/
ctor: function() {
cc.AudioEngine.prototype.ctor.call(this);
+ this._supportedFormat = [];
+ this._audioData = {};
+ this._audiosLoading = {};
+ this._effects = {};
},
/**
@@ -730,16 +719,14 @@ cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{
var capabilities = {};
this._checkCanPlay(capabilities);
- var formats = ['ogg', 'mp3', 'wav', 'mp4', 'm4a'];
+ var formats = ['ogg', 'mp3', 'wav', 'mp4', 'm4a'], locSupportedFormat = this._supportedFormat;
for (var idx in formats) {
var name = formats[idx];
- if (capabilities[name]) {
- this._supportedFormat.push(name);
- }
+ if (capabilities[name])
+ locSupportedFormat.push(name);
}
- this._soundEnable = this._supportedFormat.length > 0;
-
- return this._soundEnable;
+ this._soundSupported = locSupportedFormat.length > 0;
+ return this._soundSupported;
},
/**
@@ -748,10 +735,10 @@ cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{
* @returns {Boolean}
*/
isFormatSupported: function(ext) {
- for (var idx in this._supportedFormat) {
- if (ext === this._supportedFormat[idx]) {
+ var locSupportedFormat = this._supportedFormat;
+ for (var idx in locSupportedFormat) {
+ if (ext === locSupportedFormat[idx])
return true;
- }
}
return false;
},
@@ -785,7 +772,7 @@ cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{
* @param {String} path The path of the music file with filename extension.
*/
preloadSound: function(path) {
- if (!this._soundEnable) {
+ if (!this._soundSupported) {
return;
}
@@ -1146,11 +1133,12 @@ cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{
if (keyName in this._audioData) {
// the resource has been loaded, just play it
- if (!(keyName in this._effects)) {
- this._effects[keyName] = [];
+ var locEffects = this._effects;
+ if (!(keyName in locEffects)) {
+ locEffects[keyName] = [];
}
// a list of sound objects from the same resource
- var effectList = this._effects[keyName];
+ var effectList = locEffects[keyName];
for (var idx in effectList) {
var sfxCache = effectList[idx];
if (!this._isSoundPlaying(sfxCache) && !this._isSoundPaused(sfxCache)) {
@@ -1217,8 +1205,9 @@ cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{
}
this._effectsVolume = volume;
- for (var key in this._effects) {
- var effectList = this._effects[key];
+ var locEffects = this._effects;
+ for (var key in locEffects) {
+ var effectList = locEffects[key];
for (var idx in effectList) {
this._setSoundVolume(effectList[idx], volume);
}
@@ -1336,8 +1325,9 @@ cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{
* cc.AudioEngine.getInstance().stopAllEffects();
*/
stopAllEffects: function() {
- for (var key in this._effects) {
- var effectList = this._effects[key];
+ var locEffects = this._effects;
+ for (var key in locEffects) {
+ var effectList = locEffects[key];
for (var idx in effectList) {
this._endSound(effectList[idx]);
}
@@ -1347,7 +1337,7 @@ cc.WebAudioEngine = cc.AudioEngine.extend(/** @lends cc.WebAudioEngine# */{
* If I reassign a new {} to it, that will be appear in the instance.
* In other words, the dict in prototype won't release its children.
*/
- delete this._effects[key];
+ delete locEffects[key];
}
},
From b7395319a6de84a098183404a5772da3facfc180 Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Tue, 3 Sep 2013 15:13:16 +0800
Subject: [PATCH 078/141] fixed #880 add msPointerEnabled support
---
cocos2d/platform/Sys.js | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/cocos2d/platform/Sys.js b/cocos2d/platform/Sys.js
index 285a7dfc63..e3bc7431de 100644
--- a/cocos2d/platform/Sys.js
+++ b/cocos2d/platform/Sys.js
@@ -51,7 +51,7 @@ Object.defineProperties(sys,
if(cc.Browser.supportWebGL)
capabilities["opengl"] = true;
- if( 'ontouchstart' in document.documentElement )
+ if( 'ontouchstart' in document.documentElement || window.navigator.msPointerEnabled)
capabilities["touches"] = true;
else if( 'onmouseup' in document.documentElement )
From 832f5f14143dd31f9f4e6e37dad9940dc8586d5a Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Tue, 3 Sep 2013 15:32:17 +0800
Subject: [PATCH 079/141] Closed #2748: Fix a bug of cc.Sprite that its
children also follow fliped when it fliped
---
cocos2d/sprite_nodes/CCSprite.js | 23 ++++++++++++++++-------
1 file changed, 16 insertions(+), 7 deletions(-)
diff --git a/cocos2d/sprite_nodes/CCSprite.js b/cocos2d/sprite_nodes/CCSprite.js
index 78b022bab7..a838b2b47b 100644
--- a/cocos2d/sprite_nodes/CCSprite.js
+++ b/cocos2d/sprite_nodes/CCSprite.js
@@ -1323,14 +1323,19 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
context.globalAlpha = this._displayedOpacity / 255;
var locRect = this._rect, locContentSize = this._contentSize, locOffsetPosition = this._offsetPosition;
var flipXOffset = 0 | (locOffsetPosition.x), flipYOffset = -locOffsetPosition.y - locRect.height;
- if (this._flipX) {
- flipXOffset = -locOffsetPosition.x - locRect.width;
- context.scale(-1, 1);
- }
- if (this._flipY) {
- flipYOffset = locOffsetPosition.y;
- context.scale(1, -1);
+
+ if (this._flipX || this._flipY) {
+ context.save();
+ if (this._flipX) {
+ flipXOffset = -locOffsetPosition.x - locRect.width;
+ context.scale(-1, 1);
+ }
+ if (this._flipY) {
+ flipYOffset = locOffsetPosition.y;
+ context.scale(1, -1);
+ }
}
+
if (this._texture && locRect.width > 0) {
var image = this._texture.getHtmlElementObj();
if (this._colorized) {
@@ -1364,6 +1369,10 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
cc.p(flipXOffset + drawSize.width, flipYOffset - drawSize.height), cc.p(flipXOffset, flipYOffset - drawSize.height)];
cc.drawingUtil.drawPoly(vertices2, 4, true);
}
+
+ if (this._flipX || this._flipY)
+ context.restore();
+
cc.g_NumberOfDraws++;
}
});
From a1c8d296169f7b609de10ed3552400f38ee0156e Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Tue, 3 Sep 2013 15:41:41 +0800
Subject: [PATCH 080/141] Closed #2748: Fixed a bug of LabelAtlasCanvas, that
_opacity is wrong used.
---
cocos2d/label_nodes/CCLabelAtlas.js | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/cocos2d/label_nodes/CCLabelAtlas.js b/cocos2d/label_nodes/CCLabelAtlas.js
index 12dd596cdc..733e334b01 100644
--- a/cocos2d/label_nodes/CCLabelAtlas.js
+++ b/cocos2d/label_nodes/CCLabelAtlas.js
@@ -145,7 +145,7 @@ cc.LabelAtlasCanvas = cc.AtlasNode.extend(/** @lends cc.LabelAtlasCanvas# */{
fontChar.initWithTexture(texture, rect);
// restore to default in case they were modified
fontChar.setVisible(true);
- fontChar.setOpacity(this._opacity);
+ fontChar.setOpacity(this._displayedOpacity);
}
}
fontChar.setPosition(i * locItemWidth + locItemWidth / 2, locItemHeight / 2);
@@ -175,7 +175,7 @@ cc.LabelAtlasCanvas = cc.AtlasNode.extend(/** @lends cc.LabelAtlasCanvas# */{
},
setOpacity:function (opacity) {
- if (this._opacity != opacity) {
+ if (this._displayedOpacity != opacity) {
cc.AtlasNode.prototype.setOpacity.call(this, opacity);
var locChildren = this._children;
for (var i = 0, len = locChildren.length; i < len; i++) {
@@ -365,7 +365,7 @@ cc.LabelAtlasWebGL = cc.AtlasNode.extend(/** @lends cc.LabelAtlasWebGL# */{
},
setOpacity:function (opacity) {
- if (this._opacity !== opacity) {
+ if (this._displayedOpacity !== opacity) {
cc.AtlasNode.prototype.setOpacity.call(this, opacity);
}
}
From 3d5bbe68d8a687b955b9b3c9a805bd60d7f4fd69 Mon Sep 17 00:00:00 2001
From: NeroChan
Date: Tue, 3 Sep 2013 15:45:37 +0800
Subject: [PATCH 081/141] fixed #2763:fixed ccb parser bug
---
cocos2d/platform/CCSAXParser.js | 94 +++++++++----------
extensions/CCBReader/CCBAnimationManager.js | 5 +-
extensions/CCBReader/CCControlLoader.js | 4 +-
extensions/CCBReader/CCSpriteLoader.js | 12 ++-
extensions/CCEditBox.js | 1 -
.../GUI/CCControlExtension/CCControlButton.js | 1 -
.../GUI/CCControlExtension/CCScale9Sprite.js | 4 +-
7 files changed, 66 insertions(+), 55 deletions(-)
diff --git a/cocos2d/platform/CCSAXParser.js b/cocos2d/platform/CCSAXParser.js
index 58f729bd32..19392b9158 100644
--- a/cocos2d/platform/CCSAXParser.js
+++ b/cocos2d/platform/CCSAXParser.js
@@ -30,14 +30,20 @@
* @extends cc.Class
*/
cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{
- xmlDoc:null,
- parser:null,
- _xmlDict:null,
- plist:null,
+ xmlDoc: null,
+ _parser: null,
+ _xmlDict: null,
+ _isSupportDOMParser: null,
- ctor:function () {
+ ctor: function () {
this._xmlDict = {};
- this.plist = {};
+
+ if (window.DOMParser) {
+ this._isSupportDOMParser = true;
+ this._parser = new DOMParser();
+ } else {
+ this._isSupportDOMParser = false;
+ }
},
/**
@@ -45,22 +51,13 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{
* @param {String} textxml plist xml contents
* @return {Array} plist object array
*/
- parse:function (textxml) {
+ parse: function (textxml) {
var path = textxml;
textxml = this.getList(textxml);
- // get a reference to the requested corresponding xml file
- if (window.DOMParser) {
- this.parser = new DOMParser();
- this.xmlDoc = this.parser.parseFromString(textxml, "text/xml");
- } else {// Internet Explorer (untested!)
- this.xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
- this.xmlDoc.async = "false";
- this.xmlDoc.loadXML(textxml);
- }
- if (this.xmlDoc == null)
- cc.log("cocos2d:xml " + this.xmlDoc + " not found!");
- var plist = this.xmlDoc.documentElement;
+ var xmlDoc = this._parserXML(textxml, path);
+
+ var plist = xmlDoc.documentElement;
if (plist.tagName != 'plist')
throw "cocos2d: " + path + " is not a plist file";
@@ -71,8 +68,9 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{
if (node.nodeType == 1)
break
}
- this.plist = this._parseNode(node);
- return this.plist;
+ xmlDoc = null;
+
+ return this._parseNode(node);
},
/**
@@ -80,26 +78,32 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{
* @param {String} textxml tilemap xml content
* @return {Document} xml document
*/
- tmxParse:function (textxml, isXMLString) {
- if((isXMLString == null) || (isXMLString === false))
+ tmxParse: function (textxml, isXMLString) {
+ if ((isXMLString == null) || (isXMLString === false))
textxml = this.getList(textxml);
+ return this._parserXML(textxml);
+ },
+
+ _parserXML: function (textxml, path) {
// get a reference to the requested corresponding xml file
- if (window.DOMParser) {
- this.parser = new DOMParser();
- this.xmlDoc = this.parser.parseFromString(textxml, "text/xml");
- } else { // Internet Explorer (untested!)
- this.xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
- this.xmlDoc.async = "false";
- this.xmlDoc.loadXML(textxml);
+ var xmlDoc;
+ if (this._isSupportDOMParser) {
+ xmlDoc = this._parser.parseFromString(textxml, "text/xml");
+ } else {
+ // Internet Explorer (untested!)
+ xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
+ xmlDoc.async = "false";
+ xmlDoc.loadXML(textxml);
}
- if (this.xmlDoc == null)
- cc.log("cocos2d:xml " + this.xmlDoc + " not found!");
- return this.xmlDoc;
+ if (xmlDoc == null)
+ cc.log("cocos2d:xml " + path + " not found!");
+
+ return xmlDoc;
},
- _parseNode:function (node) {
+ _parseNode: function (node) {
var data = null;
switch (node.tagName) {
case 'dict':
@@ -135,7 +139,7 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{
return data;
},
- _parseArray:function (node) {
+ _parseArray: function (node) {
var data = [];
for (var i = 0, len = node.childNodes.length; i < len; i++) {
var child = node.childNodes[i];
@@ -146,7 +150,7 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{
return data;
},
- _parseDict:function (node) {
+ _parseDict: function (node) {
var data = {};
var key = null;
@@ -168,19 +172,15 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{
* Preload plist file
* @param {String} filePath
*/
- preloadPlist:function (filePath) {
+ preloadPlist: function (filePath) {
filePath = cc.FileUtils.getInstance().fullPathForFilename(filePath);
if (window.XMLHttpRequest) {
- // for IE7+, Firefox, Chrome, Opera, Safari brower
var xmlhttp = new XMLHttpRequest();
- // is xml file?
if (xmlhttp.overrideMimeType)
xmlhttp.overrideMimeType('text/xml');
- } else {
- // for IE6, IE5 brower
- xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
+
if (xmlhttp != null) {
var that = this;
xmlhttp.onreadystatechange = function () {
@@ -204,7 +204,7 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{
* Unload the preloaded plist from xmlList
* @param {String} filePath
*/
- unloadPlist:function(filePath){
+ unloadPlist: function (filePath) {
if (this._xmlDict.hasOwnProperty(filePath))
delete this._xmlDict[filePath];
},
@@ -214,7 +214,7 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{
* @param {String} filePath
* @return {String}
*/
- getName:function (filePath) {
+ getName: function (filePath) {
var startPos = filePath.lastIndexOf("/", filePath.length) + 1;
var endPos = filePath.lastIndexOf(".", filePath.length);
return filePath.substring(startPos, endPos);
@@ -225,7 +225,7 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{
* @param {String} filePath
* @return {String}
*/
- getExt:function (filePath) {
+ getExt: function (filePath) {
var startPos = filePath.lastIndexOf(".", filePath.length) + 1;
return filePath.substring(startPos, filePath.length);
},
@@ -235,7 +235,7 @@ cc.SAXParser = cc.Class.extend(/** @lends cc.SAXParser# */{
* @param {String} key
* @return {String} xml content
*/
- getList:function (key) {
+ getList: function (key) {
if (this._xmlDict != null) {
return this._xmlDict[key];
}
@@ -255,4 +255,4 @@ cc.SAXParser.getInstance = function () {
return this._instance;
};
-cc.SAXParser._instance = null;
+cc.SAXParser._instance = null;
\ No newline at end of file
diff --git a/extensions/CCBReader/CCBAnimationManager.js b/extensions/CCBReader/CCBAnimationManager.js
index 0f67fb02ce..c730a5c984 100644
--- a/extensions/CCBReader/CCBAnimationManager.js
+++ b/extensions/CCBReader/CCBAnimationManager.js
@@ -522,7 +522,10 @@ cc.BuilderAnimationManager = cc.Class.extend({
} else if(propName === "displayFrame"){
node.setDisplayFrame(value);
} else if(propName === "color"){
- node.setColor(value.getColor());
+ var ccColor3B = value.getColor();
+ if(!(ccColor3B.r == 255 && ccColor3B.g == 255 && ccColor3B.b == 255)){
+ node.setColor(ccColor3B);
+ }
} else if( propName === "visible"){
value = value || false;
node.setVisible(value);
diff --git a/extensions/CCBReader/CCControlLoader.js b/extensions/CCBReader/CCControlLoader.js
index c1c4a56e31..8f39c18974 100644
--- a/extensions/CCBReader/CCControlLoader.js
+++ b/extensions/CCBReader/CCControlLoader.js
@@ -253,7 +253,9 @@ cc.Scale9SpriteLoader = cc.NodeLoader.extend({
onHandlePropTypeColor3:function(node, parent, propertyName, ccColor3B,ccbReader){
if(propertyName == PROPERTY_COLOR) {
- node.setColor(ccColor3B);
+ 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);
}
diff --git a/extensions/CCBReader/CCSpriteLoader.js b/extensions/CCBReader/CCSpriteLoader.js
index 85e841282f..1bf82fe10e 100644
--- a/extensions/CCBReader/CCSpriteLoader.js
+++ b/extensions/CCBReader/CCSpriteLoader.js
@@ -37,7 +37,9 @@ cc.SpriteLoader = cc.NodeLoader.extend({
onHandlePropTypeColor3:function (node, parent, propertyName, color3BValue, ccbReader) {
if (propertyName == PROPERTY_COLOR) {
- node.setColor(color3BValue);
+ if(!(color3BValue.r == 255 && color3BValue.g == 255 && color3BValue.b == 255)){
+ node.setColor(color3BValue);
+ }
} else {
cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, color3BValue, ccbReader);
}
@@ -279,7 +281,9 @@ cc.LabelTTFLoader = cc.NodeLoader.extend({
},
onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
if (propertyName == PROPERTY_COLOR) {
- node.setColor(ccColor3B);
+ 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);
}
@@ -350,7 +354,9 @@ cc.LabelBMFontLoader = cc.NodeLoader.extend({
onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
if (propertyName == PROPERTY_COLOR) {
- node.setColor(ccColor3B);
+ 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);
}
diff --git a/extensions/CCEditBox.js b/extensions/CCEditBox.js
index 176181e246..1bb6a3ba3c 100644
--- a/extensions/CCEditBox.js
+++ b/extensions/CCEditBox.js
@@ -215,7 +215,6 @@ cc.EditBox = cc.ControlButton.extend({
this._placeholderColor = cc.GRAY;
this.setContentSize(boxSize);
this._domInputSprite = new cc.Sprite();
- this._domInputSprite.setColor(cc.BLUE);
this._domInputSprite.draw = function(){ }; //redefine draw function
this.addChild(this._domInputSprite);
var selfPointer = this;
diff --git a/extensions/GUI/CCControlExtension/CCControlButton.js b/extensions/GUI/CCControlExtension/CCControlButton.js
index ee479f8240..e57fcf0ec4 100644
--- a/extensions/GUI/CCControlExtension/CCControlButton.js
+++ b/extensions/GUI/CCControlExtension/CCControlButton.js
@@ -173,7 +173,6 @@ cc.ControlButton = cc.Control.extend({
this._backgroundSprite = backgroundSprite;
// Set the default color and opacity
- this.setColor(cc.c3(255, 255, 255));
this.setOpacity(255);
this.setOpacityModifyRGB(true);
diff --git a/extensions/GUI/CCControlExtension/CCScale9Sprite.js b/extensions/GUI/CCControlExtension/CCScale9Sprite.js
index 352fc6d010..cb5559834b 100644
--- a/extensions/GUI/CCControlExtension/CCScale9Sprite.js
+++ b/extensions/GUI/CCControlExtension/CCScale9Sprite.js
@@ -726,7 +726,9 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
if (this._spritesGenerated) {
// Restore color and opacity
this.setOpacity(opacity);
- this.setColor(color);
+ if(!(color.r == 255 && color.g == 255 && color.b == 255)){
+ this.setColor(color);
+ }
}
this._spritesGenerated = true;
return true;
From 64637fbf910cfc31b41476c5fd48fdbd0291bc28 Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Tue, 3 Sep 2013 15:49:00 +0800
Subject: [PATCH 082/141] Closed #2748: Fixed a bug of cc.ProgressTimerCanvas
that it is error display when it flip.
---
cocos2d/misc_nodes/CCProgressTimer.js | 210 ++++++++++++++------------
1 file changed, 110 insertions(+), 100 deletions(-)
diff --git a/cocos2d/misc_nodes/CCProgressTimer.js b/cocos2d/misc_nodes/CCProgressTimer.js
index 2d14f6ef45..57d78673e8 100644
--- a/cocos2d/misc_nodes/CCProgressTimer.js
+++ b/cocos2d/misc_nodes/CCProgressTimer.js
@@ -166,13 +166,11 @@ cc.ProgressTimerCanvas = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerCanvas# *
/// ---- common properties end ----
_origin:null,
- _originSize:null,
- _drawSize:null,
- _drawPosition:null,
_startAngle:270,
_endAngle:270,
_radius:0,
-
+ _counterClockWise:false,
+ _barRect:null,
ctor:function () {
cc.NodeRGBA.prototype.ctor.call(this);
@@ -185,12 +183,11 @@ cc.ProgressTimerCanvas = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerCanvas# *
this._sprite = null;
this._origin = cc.PointZero();
- this._originSize = cc.SizeZero();
- this._drawSize = cc.SizeZero();
- this._drawPosition = cc.PointZero();
this._startAngle = 270;
this._endAngle = 270;
this._radius = 0;
+ this._counterClockWise = false;
+ this._barRect = cc.RectZero();
},
/**
@@ -288,127 +285,140 @@ cc.ProgressTimerCanvas = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerCanvas# *
*/
draw:function (ctx) {
var context = ctx || cc.renderContext;
- var locSprite = this._sprite;
- context.globalAlpha = locSprite._opacity / 255;
- var centerPoint, mpX = 0, mpY = 0;
- var spriteContentSize = locSprite._contentSize;
- var spriteAnchorPoint = locSprite._anchorPointInPoints;
- if (locSprite._flipX) {
- centerPoint = cc.p(spriteContentSize.width * 0.5, spriteContentSize.height * 0.5);
- mpX = 0 | (centerPoint.x - spriteAnchorPoint.x);
- context.translate(mpX, 0);
- context.scale(-1, 1);
- }
- if (locSprite._flipY) {
- centerPoint = cc.p(spriteContentSize.width * 0.5, spriteContentSize.height * 0.5);
- mpY = -(0 | (centerPoint.y - spriteAnchorPoint.y));
- context.translate(0, mpY);
- context.scale(1, -1);
+ var locSprite = this._sprite;
+ context.globalAlpha = locSprite._displayedOpacity / 255;
+ var locRect = locSprite._rect, locOffsetPosition = locSprite._offsetPosition;
+ var flipXOffset = 0 | (locOffsetPosition.x), flipYOffset = -locOffsetPosition.y - locRect.height;
+
+ if (locSprite._flipX || locSprite._flipY) {
+ context.save();
+ if (locSprite._flipX) {
+ flipXOffset = -locOffsetPosition.x - locRect.width;
+ context.scale(-1, 1);
+ }
+ if (locSprite._flipY) {
+ flipYOffset = locOffsetPosition.y;
+ context.scale(1, -1);
+ }
}
- context.translate(spriteAnchorPoint.x, -spriteAnchorPoint.y);
- var pos;
- var offsetPixels = locSprite._offsetPosition, locSpriteTexture = locSprite._texture, locSpriteRect = locSprite._rect;
- var locOrigin = this._origin;
- var locElement = locSpriteTexture.getHtmlElementObj();
+ //clip
if (this._type == cc.PROGRESS_TIMER_TYPE_BAR) {
- pos = cc.p(( -spriteAnchorPoint.x + offsetPixels.x + this._drawPosition.x),
- ( -spriteAnchorPoint.y + offsetPixels.y + this._drawPosition.y));
- var locOriginSize = this._originSize;
- if (locElement instanceof HTMLImageElement) {
- if ((locOriginSize.width != 0) && (locOriginSize.height != 0)) {
- context.drawImage(locElement,
- locSpriteRect.x + locOrigin.x, locSpriteRect.y + locOrigin.y,
- locOriginSize.width, locOriginSize.height,
- pos.x, -(pos.y + this._drawSize.height),
- locOriginSize.width, locOriginSize.height);
- }
- } else if (locElement instanceof HTMLCanvasElement) {
- if ((locOriginSize.width != 0) && (locOriginSize.height != 0)) {
- context.drawImage(locElement,
- locOrigin.x, locOrigin.y,
- locOriginSize.width, locOriginSize.height,
- pos.x, -(pos.y + this._drawSize.height),
- locOriginSize.width, locOriginSize.height);
- }
- }
- } else {
+ var locBarRect = this._barRect;
context.beginPath();
- context.arc(locOrigin.x, locOrigin.y, this._radius, (Math.PI / 180) * this._startAngle, (Math.PI / 180) * this._endAngle, false);
+ context.rect(locBarRect.x,locBarRect.y,locBarRect.width,locBarRect.height);
+ context.clip();
+ context.closePath();
+ }else if(this._type == cc.PROGRESS_TIMER_TYPE_RADIAL){
+ var locOrigin = this._origin;
+ context.beginPath();
+ context.arc(locOrigin.x, locOrigin.y, this._radius, (Math.PI / 180) * this._startAngle, (Math.PI / 180) * this._endAngle, this._counterClockWise);
context.lineTo(locOrigin.x, locOrigin.y);
context.clip();
context.closePath();
+ }
- pos = cc.p(0 | ( -spriteAnchorPoint.x + offsetPixels.x),
- 0 | ( -spriteAnchorPoint.y + offsetPixels.y));
-
- if (locElement instanceof HTMLImageElement) {
- context.drawImage(locElement,
- locSpriteRect.x, locSpriteRect.y,
- locSpriteRect.width, locSpriteRect.height,
- pos.x, -(pos.y + locSpriteRect.height),
- locSpriteRect.width, locSpriteRect.height);
- } else if (locElement instanceof HTMLCanvasElement) {
- context.drawImage(locElement,
- 0, 0,
- locSpriteRect.width, locSpriteRect.height,
- pos.x, -(pos.y + locSpriteRect.height),
- locSpriteRect.width, locSpriteRect.height);
+ //draw sprite
+ if (locSprite._texture && locRect.width > 0) {
+ var image = locSprite._texture.getHtmlElementObj();
+ if (locSprite._colorized) {
+ context.drawImage(image,
+ 0, 0, locRect.width, locRect.height,
+ flipXOffset, flipYOffset, locRect.width, locRect.height);
+ } else {
+ context.drawImage(image,
+ locRect.x, locRect.y, locRect.width, locRect.height,
+ flipXOffset, flipYOffset, locRect.width, locRect.height);
}
}
+
+ if (locSprite._flipX || locSprite._flipY)
+ context.restore();
+
cc.INCREMENT_GL_DRAWS(1);
},
_updateProgress:function () {
- var size = this._sprite.getContentSize();
- var textureSize = this._sprite.getTextureRect().size;
+ var locSprite = this._sprite;
+ var spriteSize = locSprite.getContentSize();
var locMidPoint = this._midPoint;
+
if (this._type == cc.PROGRESS_TIMER_TYPE_RADIAL) {
- this._origin = cc.p(-(size.width * (0.5 - locMidPoint.x)), -(size.height * (locMidPoint.y - 0.5)));
- this._radius = Math.round(Math.sqrt(size.width * size.width + size.height * size.height));
+ this._radius = Math.round(Math.sqrt(spriteSize.width * spriteSize.width + spriteSize.height * spriteSize.height));
+ var locStartAngle = 270;
+ var locEndAngle = 270;
+ var locCounterClockWise = false;
+ var locOrigin = this._origin;
+
+ locOrigin.x = spriteSize.width * locMidPoint.x;
+ locOrigin.y = -spriteSize.height * locMidPoint.y;
+
if (this._reverseDirection) {
- this._startAngle = 270 - 3.6 * this._percentage;
+ locStartAngle = 270 - 3.6 * this._percentage;
} else {
- this._endAngle = 270 + 3.6 * this._percentage;
+ locEndAngle = 270 + 3.6 * this._percentage;
}
- } else {
- this._origin = cc.p(0, 0);
- this._drawPosition = cc.p(0, 0);
- var locBarChangeRate = this._barChangeRate;
- var percentageF = this._percentage / 100;
- var startPoint = cc.p(size.width * locMidPoint.x, size.height * locMidPoint.y);
- var startPointTx = cc.p(textureSize.width * locMidPoint.x, textureSize.height * locMidPoint.y);
-
- var drawedSize = cc.size((size.width * (1 - locBarChangeRate.x)), (size.height * (1 - locBarChangeRate.y)));
- var drawingSize = cc.size((size.width - drawedSize.width) * percentageF, (size.height - drawedSize.height) * percentageF);
- this._drawSize = cc.size(drawedSize.width + drawingSize.width, drawedSize.height + drawingSize.height);
+ if (locSprite._flipX) {
+ locOrigin.x -= spriteSize.width * (this._midPoint.x * 2);
+ locStartAngle= -locStartAngle;
+ locEndAngle= -locEndAngle;
+ locStartAngle -= 180;
+ locEndAngle -= 180;
+ locCounterClockWise = !locCounterClockWise;
+ }
+ if (locSprite._flipY) {
+ locOrigin.y+=spriteSize.height*(this._midPoint.y*2);
+ locCounterClockWise = !locCounterClockWise;
+ locStartAngle= -locStartAngle;
+ locEndAngle= -locEndAngle;
+ }
- var txDrawedSize = cc.size((textureSize.width * (1 - locBarChangeRate.x)), (textureSize.height * (1 - locBarChangeRate.y)));
- var txDrawingSize = cc.size((textureSize.width - txDrawedSize.width) * percentageF, (textureSize.height - txDrawedSize.height) * percentageF);
- this._originSize = cc.size(txDrawedSize.width + txDrawingSize.width, txDrawedSize.height + txDrawingSize.height);
+ this._startAngle = locStartAngle;
+ this._endAngle = locEndAngle;
+ this._counterClockWise = locCounterClockWise;
- var needToLeft = startPoint.x * percentageF;
- var needToLeftTx = startPointTx.x * percentageF;
+ } else {
+ var locBarChangeRate = this._barChangeRate;
+ var percentageF = this._percentage / 100;
+ var locBarRect = this._barRect;
+
+ var drawedSize = cc.size((spriteSize.width * (1 - locBarChangeRate.x)), (spriteSize.height * (1 - locBarChangeRate.y)));
+ var drawingSize = cc.size((spriteSize.width - drawedSize.width) * percentageF, (spriteSize.height - drawedSize.height) * percentageF);
+ var currentDrawSize = cc.size(drawedSize.width + drawingSize.width, drawedSize.height + drawingSize.height);
+
+ var startPoint = cc.p(spriteSize.width * locMidPoint.x, spriteSize.height * locMidPoint.y);
+ var needToLeft = startPoint.x - currentDrawSize.width / 2;
+ var needToTop = startPoint.y - currentDrawSize.height / 2;
+
+ //left pos
+ locBarRect.x = 0;
+ var flipXNeed = 1;
+ if (locSprite._flipX) {
+ locBarRect.x -= currentDrawSize.width;
+ flipXNeed = -1;
+ }
- if (size.width == this._drawSize.width) {
- this._origin.x = 0;
- this._drawPosition.x = 0;
- } else {
- this._origin.x = (startPointTx.x - needToLeftTx);
- this._drawPosition.x = (startPoint.x - needToLeft);
+ if (needToLeft > 0) {
+ locBarRect.x += needToLeft * flipXNeed;
}
- var needToTop = (textureSize.height - startPointTx.y) * percentageF;
+ //right pos
+ locBarRect.y = 0;
+ var flipYNeed = 1;
+ if (locSprite._flipY) {
+ locBarRect.y += currentDrawSize.height;
+ flipYNeed = -1;
+ }
- if (size.height == this._drawSize.height) {
- this._origin.y = 0;
- this._drawPosition.y = 0;
- } else {
- this._origin.y = (textureSize.height - startPointTx.y - needToTop);
- this._drawPosition.y = (startPoint.y - (startPoint.y * percentageF));
+ if (needToTop > 0) {
+ locBarRect.y -= needToTop * flipYNeed;
}
+
+ //clip width and clip height
+ locBarRect.width = currentDrawSize.width;
+ locBarRect.height = -currentDrawSize.height;
}
}
});
From b03882025cc8420811fe306f7539f2cdce041f86 Mon Sep 17 00:00:00 2001
From: NeroChan
Date: Tue, 3 Sep 2013 16:10:07 +0800
Subject: [PATCH 083/141] fixed #2763:fixed ccb parser bug
---
extensions/CCBReader/CCBAnimationManager.js | 2 +-
extensions/CCBReader/CCControlLoader.js | 2 +-
extensions/CCBReader/CCSpriteLoader.js | 12 ++++++------
extensions/GUI/CCControlExtension/CCScale9Sprite.js | 2 +-
4 files changed, 9 insertions(+), 9 deletions(-)
diff --git a/extensions/CCBReader/CCBAnimationManager.js b/extensions/CCBReader/CCBAnimationManager.js
index c730a5c984..6d1effdea1 100644
--- a/extensions/CCBReader/CCBAnimationManager.js
+++ b/extensions/CCBReader/CCBAnimationManager.js
@@ -523,7 +523,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
node.setDisplayFrame(value);
} else if(propName === "color"){
var ccColor3B = value.getColor();
- if(!(ccColor3B.r == 255 && ccColor3B.g == 255 && ccColor3B.b == 255)){
+ if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){
node.setColor(ccColor3B);
}
} else if( propName === "visible"){
diff --git a/extensions/CCBReader/CCControlLoader.js b/extensions/CCBReader/CCControlLoader.js
index 8f39c18974..3b3cd8283d 100644
--- a/extensions/CCBReader/CCControlLoader.js
+++ b/extensions/CCBReader/CCControlLoader.js
@@ -253,7 +253,7 @@ cc.Scale9SpriteLoader = cc.NodeLoader.extend({
onHandlePropTypeColor3:function(node, parent, propertyName, ccColor3B,ccbReader){
if(propertyName == PROPERTY_COLOR) {
- if(!(ccColor3B.r == 255 && ccColor3B.g == 255 && ccColor3B.b == 255)){
+ if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){
node.setColor(ccColor3B);
}
} else {
diff --git a/extensions/CCBReader/CCSpriteLoader.js b/extensions/CCBReader/CCSpriteLoader.js
index 1bf82fe10e..08ad71d13c 100644
--- a/extensions/CCBReader/CCSpriteLoader.js
+++ b/extensions/CCBReader/CCSpriteLoader.js
@@ -35,13 +35,13 @@ cc.SpriteLoader = cc.NodeLoader.extend({
return cc.Sprite.create();
},
- onHandlePropTypeColor3:function (node, parent, propertyName, color3BValue, ccbReader) {
+ onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
if (propertyName == PROPERTY_COLOR) {
- if(!(color3BValue.r == 255 && color3BValue.g == 255 && color3BValue.b == 255)){
- node.setColor(color3BValue);
+ if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){
+ node.setColor(ccColor3B);
}
} else {
- cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, color3BValue, ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader);
}
},
onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) {
@@ -281,7 +281,7 @@ cc.LabelTTFLoader = cc.NodeLoader.extend({
},
onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
if (propertyName == PROPERTY_COLOR) {
- if(!(ccColor3B.r == 255 && ccColor3B.g == 255 && ccColor3B.b == 255)){
+ if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){
node.setColor(ccColor3B);
}
} else {
@@ -354,7 +354,7 @@ cc.LabelBMFontLoader = cc.NodeLoader.extend({
onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
if (propertyName == PROPERTY_COLOR) {
- if(!(ccColor3B.r == 255 && ccColor3B.g == 255 && ccColor3B.b == 255)){
+ if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){
node.setColor(ccColor3B);
}
} else {
diff --git a/extensions/GUI/CCControlExtension/CCScale9Sprite.js b/extensions/GUI/CCControlExtension/CCScale9Sprite.js
index cb5559834b..5dc3b2ed72 100644
--- a/extensions/GUI/CCControlExtension/CCScale9Sprite.js
+++ b/extensions/GUI/CCControlExtension/CCScale9Sprite.js
@@ -726,7 +726,7 @@ cc.Scale9Sprite = cc.Node.extend(/** @lends cc.Scale9Sprite# */{
if (this._spritesGenerated) {
// Restore color and opacity
this.setOpacity(opacity);
- if(!(color.r == 255 && color.g == 255 && color.b == 255)){
+ if(color.r !== 255 || color.g !== 255 || color.b !== 255){
this.setColor(color);
}
}
From 56b9b7ee15826d01830950d19c09b8cacd6c6372 Mon Sep 17 00:00:00 2001
From: xingsenma
Date: Tue, 3 Sep 2013 16:35:19 +0800
Subject: [PATCH 084/141] closed #2748: clipping region also must use save
and restore
---
cocos2d/misc_nodes/CCProgressTimer.js | 22 +++++++++-------------
1 file changed, 9 insertions(+), 13 deletions(-)
diff --git a/cocos2d/misc_nodes/CCProgressTimer.js b/cocos2d/misc_nodes/CCProgressTimer.js
index 57d78673e8..c8722c85cf 100644
--- a/cocos2d/misc_nodes/CCProgressTimer.js
+++ b/cocos2d/misc_nodes/CCProgressTimer.js
@@ -291,16 +291,14 @@ cc.ProgressTimerCanvas = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerCanvas# *
var locRect = locSprite._rect, locOffsetPosition = locSprite._offsetPosition;
var flipXOffset = 0 | (locOffsetPosition.x), flipYOffset = -locOffsetPosition.y - locRect.height;
- if (locSprite._flipX || locSprite._flipY) {
- context.save();
- if (locSprite._flipX) {
- flipXOffset = -locOffsetPosition.x - locRect.width;
- context.scale(-1, 1);
- }
- if (locSprite._flipY) {
- flipYOffset = locOffsetPosition.y;
- context.scale(1, -1);
- }
+ context.save();
+ if (locSprite._flipX) {
+ flipXOffset = -locOffsetPosition.x - locRect.width;
+ context.scale(-1, 1);
+ }
+ if (locSprite._flipY) {
+ flipYOffset = locOffsetPosition.y;
+ context.scale(1, -1);
}
//clip
@@ -333,9 +331,7 @@ cc.ProgressTimerCanvas = cc.NodeRGBA.extend(/** @lends cc.ProgressTimerCanvas# *
}
}
- if (locSprite._flipX || locSprite._flipY)
- context.restore();
-
+ context.restore();
cc.INCREMENT_GL_DRAWS(1);
},
From 97508b054efcdbde97fba6f8e49f19998ef0691c Mon Sep 17 00:00:00 2001
From: dingpinglv
Date: Thu, 5 Sep 2013 13:56:46 +0800
Subject: [PATCH 085/141] Issue #2226: Improve Sprite, Node, LabelTTF class
define for maintainability and performance
---
cocos2d/CCDirector.js | 57 +-
cocos2d/CCDrawingPrimitives.js | 36 +-
cocos2d/base_nodes/CCAtlasNode.js | 352 ++---
cocos2d/base_nodes/CCNode.js | 1989 +++------------------------
cocos2d/label_nodes/CCLabelAtlas.js | 3 +-
cocos2d/label_nodes/CCLabelTTF.js | 898 ++----------
cocos2d/platform/CCApplication.js | 8 -
cocos2d/platform/CCClass.js | 26 +-
cocos2d/sprite_nodes/CCSprite.js | 1919 +++++++++-----------------
9 files changed, 1162 insertions(+), 4126 deletions(-)
diff --git a/cocos2d/CCDirector.js b/cocos2d/CCDirector.js
index d3d6ecdb72..399213422e 100644
--- a/cocos2d/CCDirector.js
+++ b/cocos2d/CCDirector.js
@@ -282,7 +282,7 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
* converts a UIKit coordinate to an OpenGL coordinate
* Useful to convert (multi) touches coordinates to the current layout (portrait or landscape)
*
- * @param {cc.Point} point
+ * @param {cc.Point} uiPoint
* @return {cc.Point}
*/
convertToGL:function (uiPoint) {
@@ -326,7 +326,9 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
/**
* Draw the scene. This method is called every frame. Don't call it manually.
*/
- drawScene:function () {
+ drawScene: null,
+
+ _drawSceneForCanvas: function () {
// calculate "global" dt
this.calculateDeltaTime();
@@ -334,23 +336,6 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
if (!this._paused)
this._scheduler.update(this._deltaTime);
- if (cc.renderContextType === cc.CANVAS)
- this._drawSceneForCanvas();
- else
- this._drawSceneForWebGL();
-
- this._totalFrames++;
-
- // swap buffers
- /* if (this._openGLView) {
- this._openGLView.swapBuffers();
- }*/
-
- if (this._displayStats)
- this._calculateMPF();
- },
-
- _drawSceneForCanvas:function () {
cc.renderContext.clearRect(0, 0, cc.canvas.width, -cc.canvas.height);
/* to avoid flickr, nextScene MUST be here: after tick and before draw.
@@ -368,9 +353,21 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
if (this._displayStats)
this._showStats();
+
+ this._totalFrames++;
+
+ if (this._displayStats)
+ this._calculateMPF();
},
- _drawSceneForWebGL:function () {
+ _drawSceneForWebGL: function () {
+ // calculate "global" dt
+ this.calculateDeltaTime();
+
+ //tick before glClear: issue #533
+ if (!this._paused)
+ this._scheduler.update(this._deltaTime);
+
var gl = cc.renderContext;
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
@@ -393,6 +390,11 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
this._showStats();
cc.kmGLPopMatrix();
+
+ this._totalFrames++;
+
+ if (this._displayStats)
+ this._calculateMPF();
},
/**
@@ -1089,12 +1091,7 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
this._mouseDispatcher = mouseDispatcher;
},
- _createStatsLabel:function () {
- if(cc.renderContextType === cc.CANVAS)
- this._createStatsLabelForCanvas();
- else
- this._createStatsLabelForWebGL();
- },
+ _createStatsLabel: null,
_createStatsLabelForWebGL:function(){
if((cc.Director._fpsImageLoaded == null) || (cc.Director._fpsImageLoaded == false))
@@ -1171,6 +1168,14 @@ cc.Director = cc.Class.extend(/** @lends cc.Director# */{
}
});
+if (cc.Browser.supportWebGL) {
+ cc.Director.prototype.drawScene = cc.Director.prototype._drawSceneForWebGL;
+ cc.Director.prototype._createStatsLabel = cc.Director.prototype._createStatsLabelForWebGL;
+} else {
+ cc.Director.prototype.drawScene = cc.Director.prototype._drawSceneForCanvas;
+ cc.Director.prototype._createStatsLabel = cc.Director.prototype._createStatsLabelForCanvas;
+}
+
/***************************************************
* implementation of DisplayLinkDirector
**************************************************/
diff --git a/cocos2d/CCDrawingPrimitives.js b/cocos2d/CCDrawingPrimitives.js
index 2851e42c54..d6f86e2f3e 100644
--- a/cocos2d/CCDrawingPrimitives.js
+++ b/cocos2d/CCDrawingPrimitives.js
@@ -55,7 +55,7 @@ cc.DrawingPrimitive = cc.Class.extend(/** @lends cc.DrawingPrimitive# */{
/**
* returns render context of drawing primitive
- * @return {CanvasContext}
+ * @return {CanvasRenderingContext2D}
*/
getRenderContext:function () {
return this._renderContext;
@@ -63,7 +63,7 @@ cc.DrawingPrimitive = cc.Class.extend(/** @lends cc.DrawingPrimitive# */{
/**
* Constructor
- * @param {CanvasContext} renderContext
+ * @param {CanvasRenderingContext2D} renderContext
*/
ctor:function (renderContext) {
this._renderContext = renderContext;
@@ -172,7 +172,7 @@ cc.DrawingPrimitive = cc.Class.extend(/** @lends cc.DrawingPrimitive# */{
/**
* draw a catmull rom line
- * @param {cc.PointArray} points
+ * @param {Array} points
* @param {Number} segments
*/
drawCatmullRom:function (points, segments) {
@@ -181,7 +181,7 @@ cc.DrawingPrimitive = cc.Class.extend(/** @lends cc.DrawingPrimitive# */{
/**
* draw a cardinal spline path
- * @param {cc.PointArray} config
+ * @param {Array} config
* @param {Number} tension
* @param {Number} segments
*/
@@ -200,6 +200,7 @@ cc.DrawingPrimitiveCanvas = cc.DrawingPrimitive.extend(/** @lends cc.DrawingPrim
* draws a point given x and y coordinate measured in points
* @override
* @param {cc.Point} point
+ * @param {Number} size
*/
drawPoint:function (point, size) {
if (!size) {
@@ -217,6 +218,7 @@ cc.DrawingPrimitiveCanvas = cc.DrawingPrimitive.extend(/** @lends cc.DrawingPrim
* @override
* @param {Array} points point of array
* @param {Number} numberOfPoints
+ * @param {Number} size
*/
drawPoints:function (points, numberOfPoints, size) {
if (points == null) {
@@ -397,7 +399,7 @@ cc.DrawingPrimitiveCanvas = cc.DrawingPrimitive.extend(/** @lends cc.DrawingPrim
/**
* draw a CatmullRom curve
* @override
- * @param {cc.PointArray} points
+ * @param {Array} points
* @param {Number} segments
*/
drawCatmullRom:function (points, segments) {
@@ -407,7 +409,7 @@ cc.DrawingPrimitiveCanvas = cc.DrawingPrimitive.extend(/** @lends cc.DrawingPrim
/**
* draw a cardinal spline path
* @override
- * @param {cc.PointArray} config
+ * @param {Array} config
* @param {Number} tension
* @param {Number} segments
*/
@@ -473,7 +475,7 @@ cc.DrawingPrimitiveCanvas = cc.DrawingPrimitive.extend(/** @lends cc.DrawingPrim
/**
* draw a star
- * @param {CanvasContext} ctx canvas context
+ * @param {CanvasRenderingContext2D} ctx canvas context
* @param {Number} radius
* @param {cc.Color3B|cc.Color4B|cc.Color4F} color
*/
@@ -513,7 +515,7 @@ cc.DrawingPrimitiveCanvas = cc.DrawingPrimitive.extend(/** @lends cc.DrawingPrim
/**
* draw a color ball
- * @param {CanvasContext} ctx canvas context
+ * @param {CanvasRenderingContext2D} ctx canvas context
* @param {Number} radius
* @param {cc.Color3B|cc.Color4B|cc.Color4F} color
*/
@@ -551,8 +553,8 @@ cc.DrawingPrimitiveCanvas = cc.DrawingPrimitive.extend(/** @lends cc.DrawingPrim
/**
* set the drawing color with 4 unsigned bytes
* @param {Number} r red value (0 to 255)
- * @param {Number} r green value (0 to 255)
- * @param {Number} r blue value (0 to 255)
+ * @param {Number} g green value (0 to 255)
+ * @param {Number} b blue value (0 to 255)
* @param {Number} a Alpha value (0 to 255)
*/
setDrawColor4B:function (r, g, b, a) {
@@ -563,8 +565,8 @@ cc.DrawingPrimitiveCanvas = cc.DrawingPrimitive.extend(/** @lends cc.DrawingPrim
/**
* set the drawing color with 4 floats
* @param {Number} r red value (0 to 1)
- * @param {Number} r green value (0 to 1)
- * @param {Number} r blue value (0 to 1)
+ * @param {Number} g green value (0 to 1)
+ * @param {Number} b blue value (0 to 1)
* @param {Number} a Alpha value (0 to 1)
*/
setDrawColor4F:function (r, g, b, a) {
@@ -751,7 +753,7 @@ cc.DrawingPrimitiveWebGL = cc.DrawingPrimitive.extend({
},
/**
- * draws a poligon given a pointer to cc.Point coordiantes and the number of vertices measured in points.
+ * draws a polygon given a pointer to cc.Point coordiantes and the number of vertices measured in points.
* @param {Array} vertices a pointer to cc.Point coordiantes
* @param {Number} numOfVertices the number of vertices measured in points
* @param {Boolean} closePolygon The polygon can be closed or open
@@ -994,8 +996,8 @@ cc.DrawingPrimitiveWebGL = cc.DrawingPrimitive.extend({
/**
* set the drawing color with 4 unsigned bytes
* @param {Number} r red value (0 to 255)
- * @param {Number} r green value (0 to 255)
- * @param {Number} r blue value (0 to 255)
+ * @param {Number} g green value (0 to 255)
+ * @param {Number} b blue value (0 to 255)
* @param {Number} a Alpha value (0 to 255)
*/
setDrawColor4B:function (r, g, b, a) {
@@ -1008,8 +1010,8 @@ cc.DrawingPrimitiveWebGL = cc.DrawingPrimitive.extend({
/**
* set the drawing color with 4 floats
* @param {Number} r red value (0 to 1)
- * @param {Number} r green value (0 to 1)
- * @param {Number} r blue value (0 to 1)
+ * @param {Number} g green value (0 to 1)
+ * @param {Number} b blue value (0 to 1)
* @param {Number} a Alpha value (0 to 1)
*/
setDrawColor4F:function (r, g, b, a) {
diff --git a/cocos2d/base_nodes/CCAtlasNode.js b/cocos2d/base_nodes/CCAtlasNode.js
index 1c1f4e042f..d122b3218a 100644
--- a/cocos2d/base_nodes/CCAtlasNode.js
+++ b/cocos2d/base_nodes/CCAtlasNode.js
@@ -25,7 +25,7 @@
****************************************************************************/
/**
cc.AtlasNode is a subclass of cc.Node that implements the cc.RGBAProtocol and
- * cc.TextureProtocol protocol (Canvas implement)
+ * cc.TextureProtocol protocol
*
*
It knows how to render a TextureAtlas object.
* If you are going to render a TextureAtlas consider subclassing cc.AtlasNode (or a subclass of cc.AtlasNode)
@@ -35,8 +35,7 @@
* @class
* @extends cc.NodeRGBA
*/
-cc.AtlasNodeCanvas = cc.NodeRGBA.extend(/** @lends cc.AtlasNode# */{
- /// ---- common properties start ----
+cc.AtlasNode = cc.NodeRGBA.extend(/** @lends cc.AtlasNode# */{
RGBAProtocol:true,
//! chars per row
_itemsPerRow:0,
@@ -144,10 +143,12 @@ cc.AtlasNodeCanvas = cc.NodeRGBA.extend(/** @lends cc.AtlasNode# */{
this._quadsToDraw = quadsToDraw;
},
- /// ---- common properties end ----
_textureForCanvas:null,
_originalTexture:null,
+ _uniformColor:null,
+ _colorF32Array:null,
+
/** initializes an cc.AtlasNode with an Atlas file the width and height of each item and the quantity of items to render
* @param {String} tile
* @param {Number} tileWidth
@@ -163,13 +164,15 @@ cc.AtlasNodeCanvas = cc.NodeRGBA.extend(/** @lends cc.AtlasNode# */{
/**
* initializes an CCAtlasNode with a texture the width and height of each item measured in points and the quantity of items to render
- * @param {HTMLImageElement|HTMLCanvasElement} texture
+ * @param {cc.Texture2D} texture
* @param {Number} tileWidth
* @param {Number} tileHeight
* @param {Number} itemsToRender
- * @returen {Boolean}
+ * @return {Boolean}
*/
- initWithTexture:function(texture, tileWidth, tileHeight, itemsToRender){
+ initWithTexture:null,
+
+ _initWithTextureForCanvas:function(texture, tileWidth, tileHeight, itemsToRender){
this._itemWidth = tileWidth;
this._itemHeight = tileHeight;
@@ -186,224 +189,7 @@ cc.AtlasNodeCanvas = cc.NodeRGBA.extend(/** @lends cc.AtlasNode# */{
return true;
},
- /**
- * @param {cc.Color3B} color3
- */
- setColor:function (color3) {
- if ((this._realColor.r == color3.r) && (this._realColor.g == color3.g) && (this._realColor.b == color3.b))
- return;
- var temp = new cc.Color3B(color3.r,color3.g,color3.b);
- this._colorUnmodified = color3;
-
- if (this._opacityModifyRGB) {
- temp.r = temp.r * this._displayedOpacity / 255;
- temp.g = temp.g * this._displayedOpacity / 255;
- temp.b = temp.b * this._displayedOpacity / 255;
- }
- cc.NodeRGBA.prototype.setColor.call(this, color3);
-
- if (this.getTexture()) {
- var element = this._originalTexture.getHtmlElementObj();
- if(!element)
- return;
- var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(element);
- if (cacheTextureForColor) {
- var textureRect = cc.rect(0, 0, element.width, element.height);
- element = cc.generateTintImage(element, cacheTextureForColor, this._realColor, textureRect);
- var locTexture = new cc.Texture2D();
- locTexture.initWithElement(element);
- locTexture.handleLoadedTexture();
- this.setTexture(locTexture);
- }
- }
- },
-
- /**
- * @param {Number} opacity
- */
- setOpacity:function (opacity) {
- cc.NodeRGBA.prototype.setOpacity.call(this, opacity);
-
- // special opacity for premultiplied textures
- if (this._opacityModifyRGB) {
- this.setColor(this._colorUnmodified);
- }
- },
-
- // cc.Texture protocol
- /**
- * returns the used texture
- * @return {cc.Texture2D}
- */
- getTexture:function () {
- return this._textureForCanvas;
- },
-
- /** sets a new texture. it will be retained
- * @param {cc.Texture2D} texture
- */
- setTexture:function (texture) {
- this._textureForCanvas = texture;
- },
-
- _calculateMaxItems:function () {
- var selTexture = this.getTexture();
- var size = selTexture.getContentSize();
-
- this._itemsPerColumn = 0 | (size.height / this._itemHeight);
- this._itemsPerRow = 0 | (size.width / this._itemWidth);
- },
-
- _setIgnoreContentScaleFactor:function(ignoreContentScaleFactor){
- this._ignoreContentScaleFactor = ignoreContentScaleFactor;
- }
-});
-
-/**
cc.AtlasNode is a subclass of cc.Node that implements the cc.RGBAProtocol and
- * cc.TextureProtocol protocol (WebGL implement)
- *
- *
It knows how to render a TextureAtlas object.
- * If you are going to render a TextureAtlas consider subclassing cc.AtlasNode (or a subclass of cc.AtlasNode)
- *
- *
All features from cc.Node are valid, plus the following features:
- * - opacity and RGB colors
cc.Node is the main element. Anything thats gets drawn or contains things that get drawn is a cc.Node.
- The most popular cc.Nodes are: cc.Scene, cc.Layer, cc.Sprite, cc.Menu. (WebGL implement)
+ The most popular cc.Nodes are: cc.Scene, cc.Layer, cc.Sprite, cc.Menu.
The main features of a cc.Node are:
- They can contain other cc.Node nodes (addChild, getChildByTag, removeChild, etc)
@@ -67,8 +66,6 @@ cc.s_globalOrderOfArrival = 1;
- position
- scale (x, y)
- rotation (in degrees, clockwise)
- - cc.Camera (an interface to gluLookAt )
- - cc.GridBase (to do mesh transformations)
- anchor point
- size
- visible
@@ -89,7 +86,6 @@ cc.s_globalOrderOfArrival = 1;
-# The node will be translated (position)
-# The node will be rotated (rotation)
-# The node will be scaled (scale)
- -# The node will be moved according to the camera values (camera)
Order in transformations with grid enabled
-# The node will be translated (position)
@@ -98,9 +94,6 @@ cc.s_globalOrderOfArrival = 1;
-# The grid will capture the screen
-# The node will be moved according to the camera values (camera)
-# The grid will render the captured screen
-
-
Camera:
- - Each node has a camera. By default it points to the center of the cc.Node.
Position (x,y) of the node in OpenGL coordinates. (0,0) is the left-bottom corner.
* @const
- * @return {cc.Point}
+ * @return {cc.Point} The position (x,y) of the node in OpenGL coordinates
*/
getPosition:function () {
return cc.p(this._position.x, this._position.y);
@@ -631,7 +629,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
* But you can use values higher than (1,1) and lower than (0,0) too.
* The default anchorPoint is (0.5,0.5), so it starts in the center of the node.
* @const
- * @return {cc.Point} The anchor point of node.
+ * @return {cc.Point} The anchor point of node.
*/
getAnchorPoint:function () {
return cc.p(this._anchorPoint.x, this._anchorPoint.y);
@@ -927,7 +925,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
*/
getBoundingBox:function () {
var rect = cc.rect(0, 0, this._contentSize.width, this._contentSize.height);
- return cc.RectApplyAffineTransform(rect, this.nodeToParentTransform());
+ return cc._RectApplyAffineTransformIn(rect, this.nodeToParentTransform());
},
/**
@@ -942,7 +940,8 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.cleanup);
},
- /** Node description
+ /**
+ * Gets the description string. It makes debugging easier.
* @return {String}
*/
description:function () {
@@ -1023,7 +1022,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
* Removes this node itself from its parent node.
* If the node orphan, then nothing happens.
* @deprecated
- * @param {Boolean} cleanup true if all actions and callbacks on this node should be removed, false otherwise.
+ * @param {Boolean} cleanup true if all actions and callbacks on this node should be removed, false otherwise.
*/
removeFromParentAndCleanup:function (cleanup) {
cc.log("removeFromParentAndCleanup is deprecated. Use removeFromParent instead");
@@ -1037,7 +1036,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
* to override this method
*
* @param {cc.Node} child The child node which will be removed.
- * @param {Boolean} cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise.
+ * @param {Boolean|null} [cleanup=null] true if all running actions and callbacks on the child node will be cleanup, false otherwise.
*/
removeChild:function (child, cleanup) {
// explicit nil handling
@@ -1046,9 +1045,8 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
if (cleanup == null)
cleanup = true;
- if (this._children.indexOf(child) > -1) {
+ if (this._children.indexOf(child) > -1)
this._detachChild(child, cleanup);
- }
this.setNodeDirty();
},
@@ -1073,7 +1071,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
/**
* Removes all children from the container and do a cleanup all running actions depending on the cleanup parameter.
* @deprecated
- * @param {Boolean | null} cleanup
+ * @param {Boolean | null } cleanup
*/
removeAllChildrenWithCleanup:function (cleanup) {
cc.log("removeAllChildrenWithCleanup is deprecated. Use removeAllChildren instead");
@@ -1149,8 +1147,8 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
/** Reorders a child according to a new z value.
* The child MUST be already added.
- * @param {cc.Node} child
- * @param {Number} zOrder
+ * @param {cc.Node} child An already added child node. It MUST be already added.
+ * @param {Number} zOrder Z order for drawing priority. Please refer to setZOrder(int)
*/
reorderChild:function (child, zOrder) {
cc.Assert(child != null, "Child must be non-nil");
@@ -1371,7 +1369,7 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
* Schedules a custom selector.
* If the selector is already scheduled, then the interval parameter will be updated without scheduling it again.
*
- * @param {function} callback_fn
+ * @param {function} callback_fn A function wrapped as a selector
* @param {Number} interval Tick interval in seconds. 0 means tick every frame. If interval = 0, it's recommended to use scheduleUpdate() instead.
* @param {Number} repeat The selector will be excuted (repeat + 1) times, you can use kCCRepeatForever for tick infinitely.
* @param {Number} delay The amount of time that the first tick will wait before execution.
@@ -1653,7 +1651,6 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
removeAllComponents:function(){
this._componentContainer.removeAll();
},
- /// ---- common properties end ----
_transform4x4:null,
_stackMatrix:null,
@@ -1661,8 +1658,19 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
_camera:null,
_grid:null,
- ctor:function () {
+ /**
+ * Constructor
+ */
+ ctor: null,
+
+ _ctorForCanvas: function () {
+ this._initNode();
+ },
+
+ _ctorForWebGL: function () {
this._initNode();
+
+ //WebGL
var mat4 = new cc.kmMat4();
mat4.mat[2] = mat4.mat[3] = mat4.mat[6] = mat4.mat[7] = mat4.mat[8] = mat4.mat[9] = mat4.mat[11] = mat4.mat[14] = 0.0;
mat4.mat[10] = mat4.mat[15] = 1.0;
@@ -1673,8 +1681,43 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
/**
* recursive method that visit its children and draw them
+ * @param {CanvasRenderingContext2D|WebGLRenderingContext} ctx
*/
- visit: function () {
+ visit:null,
+
+ _visitForCanvas:function (ctx) {
+ // quick return if not visible
+ if (!this._visible)
+ return;
+
+ //visit for canvas
+ var context = ctx || cc.renderContext, i;
+ var children = this._children,child;
+ context.save();
+ this.transform(context);
+ var len = children.length;
+ if (len > 0) {
+ this.sortAllChildren();
+ // draw children zOrder < 0
+ for (i = 0; i < len; i++) {
+ child = children[i];
+ if (child._zOrder < 0)
+ child.visit(context);
+ else
+ break;
+ }
+ this.draw(context);
+ for (; i < len; i++) {
+ children[i].visit(context);
+ }
+ } else
+ this.draw(context);
+
+ this._orderOfArrival = 0;
+ context.restore();
+ },
+
+ _visitForWebGL: function(){
// quick return if not visible
if (!this._visible)
return;
@@ -1725,7 +1768,16 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
/**
* Performs OpenGL view-matrix transformation based on position, scale, rotation and other attributes.
*/
- transform:function () {
+ transform:null,
+
+ _transformForCanvas: function (ctx) {
+ // transform for canvas
+ var context = ctx || cc.renderContext;
+ var t = this.nodeToParentTransform();
+ context.transform(t.a, t.b, t.c, t.d, t.tx, -t.ty);
+ },
+
+ _transformForWebGL: function () {
//optimize performance for javascript
var t4x4 = this._transform4x4, topMat4 = cc.current_stack.top;
@@ -1765,7 +1817,87 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
* The matrix is in Pixels.
* @return {cc.AffineTransform}
*/
- nodeToParentTransform:function () {
+ nodeToParentTransform: null,
+
+ _nodeToParentTransformForCanvas:function () {
+ if (!this._transform)
+ this._transform = {a:1, b:0, c:0, d:1, tx:0, ty:0};
+ if (this._transformDirty) {
+ var t = this._transform;// quick reference
+ // base position
+ t.tx = this._position.x;
+ t.ty = this._position.y;
+
+ // rotation Cos and Sin
+ var Cos = 1, Sin = 0;
+ if (this._rotationX) {
+ Cos = Math.cos(this._rotationRadiansX);
+ Sin = Math.sin(this._rotationRadiansX);
+ }
+
+ // base abcd
+ t.a = t.d = Cos;
+ t.c = -Sin;
+ t.b = Sin;
+
+ var lScaleX = this._scaleX, lScaleY = this._scaleY;
+ var appX = this._anchorPointInPoints.x, appY = this._anchorPointInPoints.y;
+
+ // Firefox on Vista and XP crashes
+ // GPU thread in case of scale(0.0, 0.0)
+ var sx = (lScaleX < 0.000001 && lScaleX > -0.000001)? 0.000001 : lScaleX,
+ sy = (lScaleY < 0.000001 && lScaleY > -0.000001)? 0.000001 : lScaleY;
+
+ // skew
+ if (this._skewX || this._skewY) {
+ // offset the anchorpoint
+ var skx = Math.tan(-this._skewX * Math.PI / 180);
+ var sky = Math.tan(-this._skewY * Math.PI / 180);
+ var xx = appY * skx * sx;
+ var yy = appX * sky * sy;
+ t.a = Cos + -Sin * sky;
+ t.c = Cos * skx + -Sin;
+ t.b = Sin + Cos * sky;
+ t.d = Sin * skx + Cos;
+ t.tx += Cos * xx + -Sin * yy;
+ t.ty += Sin * xx + Cos * yy;
+ }
+
+ // scale
+ if (lScaleX !== 1 || lScaleY !== 1) {
+ t.a *= sx;
+ t.b *= sx;
+ t.c *= sy;
+ t.d *= sy;
+ }
+
+ // adjust anchorPoint
+ t.tx += Cos * -appX * sx + -Sin * appY * sy;
+ t.ty -= Sin * -appX * sx + Cos * appY * sy;
+
+ // if ignore anchorPoint
+ if (this._ignoreAnchorPointForPosition) {
+ t.tx += appX
+ t.ty += appY;
+ }
+
+ if (this._additionalTransformDirty) {
+ this._transform = cc.AffineTransformConcat(this._transform, this._additionalTransform);
+ //Because the cartesian coordination is inverted in html5 canvas, these needs to be inverted as well
+ this._transform.b *= -1;
+ this._transform.c *= -1;
+
+ this._additionalTransformDirty = false;
+ }
+
+ t.tx = t.tx | 0;
+ t.ty = t.ty | 0;
+ this._transformDirty = false;
+ }
+ return this._transform;
+ },
+
+ _nodeToParentTransformForWebGL:function () {
if (this._transformDirty) {
// Translate values
var x = this._position.x;
@@ -1824,6 +1956,13 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
return this._transform;
},
+ _setNodeDirtyForCache:function () {
+ this._cacheDirty = true;
+ if (this._parent) {
+ this._parent._setNodeDirtyForCache();
+ }
+ },
+
/**
* Returns a camera object that lets you move the node using a gluLookAt
* @return {cc.Camera} A CCCamera object that lets you move the node using a gluLookAt
@@ -1892,1749 +2031,6 @@ cc.NodeWebGL = cc.Class.extend(/** @lends cc.NodeWebGL# */{
*/
setGLServerState:function (state) {
this._glServerState = state;
- }
-});
-
-/**
cc.Node is the main element. Anything thats gets drawn or contains things that get drawn is a cc.Node.
- The most popular cc.Nodes are: cc.Scene, cc.Layer, cc.Sprite, cc.Menu. (Canvas implement)
-
-
The main features of a cc.Node are:
- - They can contain other cc.Node nodes (addChild, getChildByTag, removeChild, etc)
- - They can schedule periodic callback (schedule, unschedule, etc)
- - They can execute actions (runAction, stopAction, etc)
-
-
Some cc.Node nodes provide extra functionality for them or their children.
-
-
Subclassing a cc.Node usually means (one/all) of:
- - overriding init to initialize resources and schedule callbacks
- - create callbacks to handle the advancement of time
- - overriding draw to render the node
-
-
Features of cc.Node:
- - position
- - scale (x, y)
- - rotation (in degrees, clockwise)
- - anchor point
- - size
- - visible
- - z-order
- - openGL z position
Limitations:
- - A cc.Node is a "void" object. It doesn't have a texture
-
-
Order in transformations with grid disabled
- -# The node will be translated (position)
- -# The node will be rotated (rotation)
- -# The node will be scaled (scale)
-
-
Order in transformations with grid enabled
- -# The node will be translated (position)
- -# The node will be rotated (rotation)
- -# The node will be scaled (scale)
- -# The grid will capture the screen
- -# The node will be moved according to the camera values (camera)
- -# The grid will render the captured screen
- * @class
- * @extends cc.Class
- * @example
- * // example
- * cc.Sprite = cc.Node.extend({});
- * cc.Sprite.initWithImage = function(){
- * };
- */
-cc.NodeCanvas = cc.Class.extend(/** @lends cc.NodeCanvas# */{
- /// ---- common properties start ----
- _zOrder:0,
- _vertexZ:0.0,
-
- _rotationX:0,
- _rotationY:0.0,
- _scaleX:1.0,
- _scaleY:1.0,
- _position:null,
- _skewX:0.0,
- _skewY:0.0,
- // children (lazy allocs),
- _children:null,
- // lazy alloc,
- _visible:true,
- _anchorPoint:null,
- _anchorPointInPoints:null,
- _contentSize:null,
- _running:false,
- _parent:null,
- // "whole screen" objects. like Scenes and Layers, should set _ignoreAnchorPointForPosition to true
- _ignoreAnchorPointForPosition:false,
- _tag:cc.NODE_TAG_INVALID,
- // userData is always inited as nil
- _userData:null,
- _userObject:null,
- _transformDirty:true,
- _inverseDirty:true,
- _cacheDirty:true,
- _transformGLDirty:null,
- _transform:null,
- _inverse:null,
-
- //since 2.0 api
- _reorderChildDirty:false,
- _shaderProgram:null,
- _orderOfArrival:0,
-
- _actionManager:null,
- _scheduler:null,
-
- _initializedNode:false,
- _additionalTransformDirty:false,
- _additionalTransform:null,
- _componentContainer:null,
- _isTransitionFinished:false,
-
- _rotationRadiansX:0,
- _rotationRadiansY:0,
-
- _initNode:function () {
- this._anchorPoint = cc.p(0, 0);
- this._anchorPointInPoints = cc.p(0, 0);
- this._contentSize = cc.size(0, 0);
- this._position = cc.p(0, 0);
- this._children = [];
-
- var director = cc.Director.getInstance();
- this._actionManager = director.getActionManager();
- this._scheduler = director.getScheduler();
- this._initializedNode = true;
- this._additionalTransform = cc.AffineTransformMakeIdentity();
- this._componentContainer = new cc.ComponentContainer(this);
- },
-
- /**
- * Initializes the instance of cc.Node
- * @returns {boolean} Whether the initialization was successful.
- */
- init:function () {
- if (this._initializedNode === false)
- this._initNode();
- return true;
- },
-
- /**
- * @param {Array} array
- * @param {cc.Node.StateCallbackType} callbackType
- * @private
- */
- _arrayMakeObjectsPerformSelector:function (array, callbackType) {
- if (!array || array.length === 0)
- return;
-
- var i, len = array.length,node;
- var nodeCallbackType = cc.Node.StateCallbackType;
- switch (callbackType) {
- case nodeCallbackType.onEnter:
- for (i = 0; i < len; i++) {
- node = array[i];
- if (node)
- node.onEnter();
- }
- break;
- case nodeCallbackType.onExit:
- for (i = 0; i < len; i++) {
- node = array[i];
- if (node)
- node.onExit();
- }
- break;
- case nodeCallbackType.onEnterTransitionDidFinish:
- for (i = 0; i < len; i++) {
- node = array[i];
- if (node)
- node.onEnterTransitionDidFinish();
- }
- break;
- case nodeCallbackType.cleanup:
- for (i = 0; i < len; i++) {
- node = array[i];
- if (node)
- node.cleanup();
- }
- break;
- case nodeCallbackType.updateTransform:
- for (i = 0; i < len; i++) {
- node = array[i];
- if (node)
- node.updateTransform();
- }
- break;
- case nodeCallbackType.onExitTransitionDidStart:
- for (i = 0; i < len; i++) {
- node = array[i];
- if (node)
- node.onExitTransitionDidStart();
- }
- break;
- case nodeCallbackType.sortAllChildren:
- for (i = 0; i < len; i++) {
- node = array[i];
- if (node)
- node.sortAllChildren();
- }
- break;
- default :
- throw "Unknown callback function";
- break;
- }
- },
-
- /**
- *
get the skew degrees in X
- * The X skew angle of the node in degrees.
- * This angle describes the shear distortion in the X direction.
- * Thus, it is the angle between the Y axis and the left edge of the shape
- * The default skewX angle is 0. Positive values distort the node in a CW direction.
- *
- * @return {Number} The X skew angle of the node in degrees.
- */
- getSkewX:function () {
- return this._skewX;
- },
-
- /**
- *
- * Changes the X skew angle of the node in degrees.
- *
- * This angle describes the shear distortion in the X direction.
- * Thus, it is the angle between the Y axis and the left edge of the shape
- * The default skewX angle is 0. Positive values distort the node in a CW direction.
- *
- * @param {Number} newSkewX The X skew angle of the node in degrees.
- */
- setSkewX:function (newSkewX) {
- this._skewX = newSkewX;
- this.setNodeDirty();
- },
-
- /**
- *
get the skew degrees in Y
- * The Y skew angle of the node in degrees.
- * This angle describes the shear distortion in the Y direction.
- * Thus, it is the angle between the X axis and the bottom edge of the shape
- * The default skewY angle is 0. Positive values distort the node in a CCW direction.
- *
- * @return {Number} The Y skew angle of the node in degrees.
- */
- getSkewY:function () {
- return this._skewY;
- },
-
- /**
- *
- * Changes the Y skew angle of the node in degrees.
- *
- * This angle describes the shear distortion in the Y direction.
- * Thus, it is the angle between the X axis and the bottom edge of the shape
- * The default skewY angle is 0. Positive values distort the node in a CCW direction.
- *
- * Sets the z order which stands for the drawing order
- *
- * This is an internal method. Don't call it outside the framework.
- * The difference between setZOrder(int) and _setOrder(int) is:
- * - _setZOrder(int) is a pure setter for m_nZOrder memeber variable
- * - setZOrder(int) firstly changes m_nZOrder, then recorder this node in its parent's chilren array.
- *
- * Sets the Z order which stands for the drawing order, and reorder this node in its parent's children array.
- *
- * The Z order of node is relative to its "brothers": children of the same parent.
- * It's nothing to do with OpenGL's z vertex. This one only affects the draw order of nodes in cocos2d.
- * The larger number it is, the later this node will be drawn in each message loop.
- * Please refer to setVertexZ(float) for the difference.
- *
- * @param {Number} z Z order of this node.
- */
- setZOrder:function (z) {
- this._setZOrder(z);
- if (this._parent)
- this._parent.reorderChild(this, z);
- },
-
- /**
- * Gets WebGL Z vertex of this node.
- * @return {Number} WebGL Z vertex of this node
- */
- getVertexZ:function () {
- return this._vertexZ;
- },
-
- /**
- *
- * Sets the real WebGL Z vertex.
- *
- * Differences between openGL Z vertex and cocos2d Z order:
- * - OpenGL Z modifies the Z vertex, and not the Z order in the relation between parent-children
- * - OpenGL Z might require to set 2D projection
- * - cocos2d Z order works OK if all the nodes uses the same openGL Z vertex. eg: vertexZ = 0
- *
- * @warning Use it at your own risk since it might break the cocos2d parent-children z order
- *
- * @param {Number} Var
- */
- setVertexZ:function (Var) {
- this._vertexZ = Var;
- },
-
- /**
- * The rotation (angle) of the node in degrees. 0 is the default rotation angle. Positive values rotate node CW.
- * @return {Number} The rotation of the node in degrees.
- */
- getRotation:function () {
- cc.Assert(this._rotationX == this._rotationY, "CCNode#rotation. RotationX != RotationY. Don't know which one to return");
- return this._rotationX;
- },
-
- /**
- *
- * Sets the rotation (angle) of the node in degrees.
- *
- * 0 is the default rotation angle.
- * Positive values rotate node clockwise, and negative values for anti-clockwise.
- *
- * @param {Number} newRotation The rotation of the node in degrees.
- */
- setRotation:function (newRotation) {
- this._rotationX = this._rotationY = newRotation;
- this._rotationRadiansX = this._rotationX * 0.017453292519943295; //(Math.PI / 180);
- this._rotationRadiansY = this._rotationY * 0.017453292519943295; //(Math.PI / 180);
-
- this.setNodeDirty();
- },
-
- /**
- * The rotation (angle) of the node in degrees. 0 is the default rotation angle.
- * Positive values rotate node CW. It only modifies the X rotation performing a horizontal rotational skew .
- * (support only in WebGl rendering mode)
- * @return {Number} The X rotation in degrees.
- */
- getRotationX:function () {
- return this._rotationX;
- },
-
- /**
- *
- * Sets the X rotation (angle) of the node in degrees which performs a horizontal rotational skew.
- *
- * 0 is the default rotation angle.
- * Positive values rotate node clockwise, and negative values for anti-clockwise.
- *
- * @param {Number} rotationX The X rotation in degrees which performs a horizontal rotational skew.
- */
- setRotationX:function (rotationX) {
- this._rotationX = rotationX;
- this._rotationRadiansX = this._rotationX * 0.017453292519943295; //(Math.PI / 180);
- this.setNodeDirty();
- },
-
- /**
- * The rotation (angle) of the node in degrees. 0 is the default rotation angle.
- * Positive values rotate node CW. It only modifies the Y rotation performing a vertical rotational skew .
- * @return {Number} The Y rotation in degrees.
- */
- getRotationY:function () {
- return this._rotationY;
- },
-
- /**
- *
- * Sets the Y rotation (angle) of the node in degrees which performs a vertical rotational skew.
- *
- * 0 is the default rotation angle.
- * Positive values rotate node clockwise, and negative values for anti-clockwise.
- *
- * @param rotationY The Y rotation in degrees.
- */
- setRotationY:function (rotationY) {
- this._rotationY = rotationY;
- this._rotationRadiansY = this._rotationY * 0.017453292519943295; //(Math.PI / 180);
- this.setNodeDirty();
- },
-
- /** Get the scale factor of the node.
- * @warning: Assert when _scaleX != _scaleY.
- * @return {Number}
- */
- getScale:function () {
- cc.Assert(this._scaleX == this._scaleY, "cc.Node#scale. ScaleX != ScaleY. Don't know which one to return");
- return this._scaleX;
- },
-
- /**
- * The scale factor of the node. 1.0 is the default scale factor. It modifies the X and Y scale at the same time.
- * @param {Number} scale or scaleX value
- * @param {Number} scaleY
- */
- setScale:function (scale, scaleY) {
- this._scaleX = scale;
- this._scaleY = scaleY === undefined ? scale : scaleY;
- this.setNodeDirty();
- },
-
- /**
- * Returns the scale factor on X axis of this node
- * @return {Number} The scale factor on X axis.
- */
- getScaleX:function () {
- return this._scaleX;
- },
-
- /**
- *
- * Changes the scale factor on X axis of this node
- * The deafult value is 1.0 if you haven't changed it before
- *
- * @param {Number} newScaleX The scale factor on X axis.
- */
- setScaleX:function (newScaleX) {
- this._scaleX = newScaleX;
- this.setNodeDirty();
- },
-
- /**
- * Returns the scale factor on Y axis of this node
- * @return {Number} The scale factor on Y axis.
- */
- getScaleY:function () {
- return this._scaleY;
- },
-
- /**
- *
- * Changes the scale factor on Y axis of this node
- * The Default value is 1.0 if you haven't changed it before.
- *
- * @param {Number} newScaleY The scale factor on Y axis.
- */
- setScaleY:function (newScaleY) {
- this._scaleY = newScaleY;
- this.setNodeDirty();
- },
-
- /**
- *
- * Changes the position (x,y) of the node in OpenGL coordinates
- * Usually we use ccp(x,y) to compose CCPoint object.
- * The original point (0,0) is at the left-bottom corner of screen.
- * and Passing two numbers (x,y) is much efficient than passing CCPoint object.
- *
- * @param {cc.Point|Number} newPosOrxValue The position (x,y) of the node in coordinates or X coordinate for position
- * @param {Number} yValue Y coordinate for position
- * @example
- * var size = cc.Director.getInstance().getWinSize();
- * node.setPosition( cc.p(size.width/2, size.height/2) )
- */
- setPosition:function (newPosOrxValue, yValue) {
- var locPosition = this._position;
- if (arguments.length == 2) {
- locPosition.x = newPosOrxValue;
- locPosition.y = yValue;
- } else if (arguments.length == 1) {
- locPosition.x = newPosOrxValue.x;
- locPosition.y = newPosOrxValue.y;
- }
- this.setNodeDirty();
- },
-
- /**
- *
Position (x,y) of the node in OpenGL coordinates. (0,0) is the left-bottom corner.
- * @const
- * @return {cc.Point} The position (x,y) of the node in OpenGL coordinates
- */
- getPosition:function () {
- return cc.p(this._position.x, this._position.y);
- },
-
- /**
- * @return {Number}
- */
- getPositionX:function () {
- return this._position.x;
- },
-
- /**
- * @param {Number} x
- */
- setPositionX:function (x) {
- this._position.x = x;
- this.setNodeDirty();
- },
-
- /**
- * @return {Number}
- */
- getPositionY:function () {
- return this._position.y;
- },
-
- /**
- * @param {Number} y
- */
- setPositionY:function (y) {
- this._position.y = y;
- this.setNodeDirty();
- },
-
- /**
- * Get the amount of children.
- * @return {Number} The amount of children.
- */
- getChildrenCount:function () {
- return this._children.length;
- },
-
- /**
- * Return an array of children
- * Composing a "tree" structure is a very important feature of CCNode
- * @return {Array} An array of children
- * @example
- * //This sample code traverses all children nodes, and set theie position to (0,0)
- * var allChildren = parent.getChildren();
- * for(var i = 0; i< allChildren.length; i++) {
- * allChildren[i].setPosition(0,0);
- * }
- */
- getChildren:function () {
- return this._children;
- },
-
- /**
- * Determines if the node is visible
- * @see setVisible(bool)
- * @return {Boolean} true if the node is visible, false if the node is hidden.
- */
- isVisible:function () {
- return this._visible;
- },
-
- /**
- * Sets whether the node is visible
- * The default value is true, a node is default to visible
- * @param {Boolean} Var true if the node is visible, false if the node is hidden.
- */
- setVisible:function (Var) {
- this._visible = Var;
- this.setNodeDirty();
- },
-
- /**
- *
anchorPoint is the point around which all transformations and positioning manipulations take place.
- * It's like a pin in the node where it is "attached" to its parent.
- * The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner.
- * But you can use values higher than (1,1) and lower than (0,0) too.
- * The default anchorPoint is (0.5,0.5), so it starts in the center of the node.
- * @const
- * @return {cc.Point} The anchor point of node.
- */
- getAnchorPoint:function () {
- return cc.p(this._anchorPoint.x, this._anchorPoint.y);
- },
-
- /**
- *
- * Sets the anchor point in percent.
- *
- * anchorPoint is the point around which all transformations and positioning manipulations take place.
- * It's like a pin in the node where it is "attached" to its parent.
- * The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner.
- * But you can use values higher than (1,1) and lower than (0,0) too.
- * The default anchorPoint is (0.5,0.5), so it starts in the center of the node.
- *
- * @param {cc.Point} point The anchor point of node.
- */
- setAnchorPoint:function (point) {
- var locAnchorPoint = this._anchorPoint;
- if (!cc.pointEqualToPoint(point, locAnchorPoint)) {
- locAnchorPoint.x = point.x;
- locAnchorPoint.y = point.y;
- var locAPP = this._anchorPointInPoints, locSize = this._contentSize;
- locAPP.x = locSize.width * point.x;
- locAPP.y = locSize.height * point.y;
- this.setNodeDirty();
- }
- },
-
- /**
- * The anchorPoint in absolute pixels.
- * you can only read it. If you wish to modify it, use anchorPoint instead
- * @see getAnchorPoint()
- * @const
- * @return {cc.Point} The anchor point in absolute pixels.
- */
- getAnchorPointInPoints:function () {
- return cc.p(this._anchorPointInPoints.x, this._anchorPointInPoints.y);
- },
-
- /**
- *
The untransformed size of the node.
- * The contentSize remains the same no matter the node is scaled or rotated.
- * All nodes has a size. Layer and Scene has the same size of the screen.
- * @const
- * @return {cc.Size} The untransformed size of the node.
- */
- getContentSize:function () {
- return cc.size(this._contentSize.width, this._contentSize.height);
- },
-
- /**
- *
- * Sets the untransformed size of the node.
- *
- * The contentSize remains the same no matter the node is scaled or rotated.
- * All nodes has a size. Layer and Scene has the same size of the screen.
- *
- * Returns whether or not the node accepts event callbacks.
- * Running means the node accept event callbacks like onEnter(), onExit(), update()
- *
- * @return {Boolean} Whether or not the node is running.
- */
- isRunning:function () {
- return this._running;
- },
-
- /**
- * Returns a pointer to the parent node
- * @return {cc.Node} A pointer to the parnet node
- */
- getParent:function () {
- return this._parent;
- },
-
- /**
- * Sets the parent node
- * @param {cc.Node} Var A pointer to the parnet node
- */
- setParent:function (Var) {
- this._parent = Var;
- },
-
- /**
- * Gets whether the anchor point will be (0,0) when you position this node.
- * @see ignoreAnchorPointForPosition(bool)
- * @return {Boolean} true if the anchor point will be (0,0) when you position this node.
- */
- isIgnoreAnchorPointForPosition:function () {
- return this._ignoreAnchorPointForPosition;
- },
-
- /**
- *
- * Sets whether the anchor point will be (0,0) when you position this node.
- *
- * This is an internal method, only used by CCLayer and CCScene. Don't call it outside framework.
- * The default value is false, while in CCLayer and CCScene are true
- *
- * @param {Boolean} newValue true if anchor point will be (0,0) when you position this node
- */
- ignoreAnchorPointForPosition:function (newValue) {
- if (newValue != this._ignoreAnchorPointForPosition) {
- this._ignoreAnchorPointForPosition = newValue;
- this.setNodeDirty();
- }
- },
-
- /**
- * Returns a tag that is used to identify the node easily.
- *
- * @return {Number} A interger that identifies the node.
- * @example
- * //You can set tags to node then identify them easily.
- * // set tags
- * node1.setTag(TAG_PLAYER);
- * node2.setTag(TAG_MONSTER);
- * node3.setTag(TAG_BOSS);
- * parent.addChild(node1);
- * parent.addChild(node2);
- * parent.addChild(node3);
- * // identify by tags
- * var allChildren = parent.getChildren();
- * for(var i = 0; i < allChildren.length; i++){
- * switch(node.getTag()) {
- * case TAG_PLAYER:
- * break;
- * case TAG_MONSTER:
- * break;
- * case TAG_BOSS:
- * break;
- * }
- * }
- */
- getTag:function () {
- return this._tag;
- },
-
- /**
- * Changes the tag that is used to identify the node easily.
- * Please refer to getTag for the sample code.
- * @param {Number} Var A interger that indentifies the node.
- */
- setTag:function (Var) {
- this._tag = Var;
- },
-
- /**
- *
- * Returns a custom user data pointer
- * You can set everything in UserData pointer, a data block, a structure or an object.
- *
- * @return {object} A custom user data pointer
- */
- getUserData:function () {
- return this._userData;
- },
-
- /**
- *
- * Sets a custom user data pointer
- * You can set everything in UserData pointer, a data block, a structure or an object, etc.
- *
- * @warning Don't forget to relfease the memroy manually,especially before you change this data pointer, and before this node is autoreleased.
- * @param {object} Var A custom user data
- */
- setUserData:function (Var) {
- this._userData = Var;
- },
-
- /**
- * Returns a user assigned CCObject.
- * Similar to userData, but instead of holding a void* it holds an id
- * @return {object} A user assigned CCObject
- */
- getUserObject:function () {
- return this._userObject;
- },
-
- /**
- *
- * Returns a user assigned CCObject
- * Similar to UserData, but instead of holding a void* it holds an object.
- * The UserObject will be retained once in this method, and the previous UserObject (if existed) will be relese.
- * The UserObject will be released in CCNode's destructure.
- *
- * @param {object} newValue A user assigned CCObject
- */
- setUserObject:function (newValue) {
- if (this._userObject != newValue) {
- this._userObject = newValue;
- }
- },
-
-
- /**
- * Returns the arrival order, indecates which children is added previously.
- * @return {Number} The arrival order.
- */
- getOrderOfArrival:function () {
- return this._orderOfArrival;
- },
-
- /**
- *
- * Sets the arrival order when this node has a same ZOrder with other children.
- *
- * A node which called addChild subsequently will take a larger arrival order,
- * If two children have the same Z order, the child with larger arrival order will be drawn later.
- *
- * @warning This method is used internally for zOrder sorting, don't change this manually
- * @param {Number} Var The arrival order.
- */
- setOrderOfArrival:function (Var) {
- this._orderOfArrival = Var;
- },
-
- /**
- *
Gets the CCActionManager object that is used by all actions.
- * (IMPORTANT: If you set a new cc.ActionManager, then previously created actions are going to be removed.)
Sets the cc.ActionManager object that is used by all actions.
- * @warning If you set a new CCActionManager, then previously created actions will be removed.
- * @param {cc.ActionManager} actionManager A CCActionManager object that is used by all actions.
- */
- setActionManager:function (actionManager) {
- if (this._actionManager != actionManager) {
- this.stopAllActions();
- this._actionManager = actionManager;
- }
- },
-
- /**
- *
- * cc.Scheduler used to schedule all "updates" and timers.
- * IMPORTANT: If you set a new cc.Scheduler, then previously created timers/update are going to be removed.
- *
- * Sets a CCScheduler object that is used to schedule all "updates" and timers.
- *
- * @warning If you set a new CCScheduler, then previously created timers/update are going to be removed.
- * @param scheduler A cc.Shdeduler object that is used to schedule all "update" and timers.
- */
- setScheduler:function (scheduler) {
- if (this._scheduler != scheduler) {
- this.unscheduleAllCallbacks();
- this._scheduler = scheduler;
- }
- },
-
- /**
- * Returns a "local" axis aligned bounding box of the node.
- * The returned box is relative only to its parent.
- * @note This method returns a temporaty variable, so it can't returns const CCRect&
- * @return {cc.Rect}
- */
- getBoundingBox:function () {
- var rect = cc.rect(0, 0, this._contentSize.width, this._contentSize.height);
- return cc._RectApplyAffineTransformIn(rect, this.nodeToParentTransform());
- },
-
- /**
- * Stops all running actions and schedulers
- */
- cleanup:function () {
- // actions
- this.stopAllActions();
- this.unscheduleAllCallbacks();
-
- // timers
- this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.cleanup);
- },
-
- /**
- * Gets the description string. It makes debugging easier.
- * @return {String}
- */
- description:function () {
- return "";
- },
-
- // composition: GET
- /**
- * Gets a child from the container given its tag
- * @param {Number} aTag An identifier to find the child node.
- * @return {cc.Node} a CCNode object whose tag equals to the input parameter
- */
- getChildByTag:function (aTag) {
- //cc.Assert(aTag != cc.NODE_TAG_INVALID, "Invalid tag");
- var __children = this._children;
- if (__children != null) {
- for (var i = 0; i < __children.length; i++) {
- var node = __children[i];
- if (node && node._tag == aTag)
- return node;
- }
- }
- //throw "not found";
- return null;
- },
- // composition: ADD
-
- /**
"add" logic MUST only be on this method
- *
- *
If the child is added to a 'running' node, then 'onEnter' and 'onEnterTransitionDidFinish' will be called immediately.
- *
- * @param {cc.Node} child A child node
- * @param {Number} zOrder Z order for drawing priority. Please refer to setZOrder(int)
- * @param {Number} tag A interger to identify the node easily. Please refer to setTag(int)
- */
- addChild:function (child, zOrder, tag) {
- if (child === this) {
- console.warn('cc.Node.addChild: An Node can\'t be added as a child of itself.');
- return;
- }
-
- cc.Assert(child != null, "Argument must be non-nil");
- if (child._parent !== null) {
- cc.Assert(child._parent === null, "child already added. It can't be added again");
- return;
- }
-
- var tmpzOrder = (zOrder != null) ? zOrder : child._zOrder;
- child._tag = (tag != null) ? tag : child._tag;
- this._insertChild(child, tmpzOrder);
- child._parent = this;
-
- if (this._running) {
- child.onEnter();
- // prevent onEnterTransitionDidFinish to be called twice when a node is added in onEnter
- if(this._isTransitionFinished)
- child.onEnterTransitionDidFinish();
- }
- },
-
- // composition: REMOVE
- /**
- * Remove itself from its parent node. If cleanup is true, then also remove all actions and callbacks.
- * If the cleanup parameter is not passed, it will force a cleanup.
- * If the node orphan, then nothing happens.
- * @param {Boolean} cleanup
- * @see removeFromParentAndCleanup(bool)
- */
- removeFromParent:function (cleanup) {
- if (this._parent) {
- if (cleanup == null)
- cleanup = true;
- this._parent.removeChild(this, cleanup);
- }
- },
-
- /**
- * Remove itself from its parent node.
- * @deprecated
- * @param {Boolean} cleanup
- */
- removeFromParentAndCleanup:function (cleanup) {
- cc.log("removeFromParentAndCleanup is deprecated. Use removeFromParent instead");
- this.removeFromParent(cleanup);
- },
-
- /**
Removes a child from the container. It will also cleanup all running actions depending on the cleanup parameter.
- * If the cleanup parameter is not passed, it will force a cleanup.
- *
"remove" logic MUST only be on this method
- * If a class wants to extend the 'removeChild' behavior it only needs
- * to override this method
- *
- * @param {cc.Node} child The child node which will be removed.
- * @param {Boolean} cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise.
- */
- removeChild:function (child, cleanup) {
- // explicit nil handling
- if (this._children.length === 0)
- return;
-
- if (cleanup == null)
- cleanup = true;
- if (this._children.indexOf(child) > -1) {
- this._detachChild(child, cleanup);
- }
-
- this.setNodeDirty();
- },
-
- /**
- * Removes a child from the container by tag value. It will also cleanup all running actions depending on the cleanup parameter.
- * If the cleanup parameter is not passed, it will force a cleanup.
- * @param {Number} tag An integer number that identifies a child node
- * @param {Boolean} cleanup true if all running actions and callbacks on the child node will be cleanup, false otherwise.
- * @see removeChildByTag(int, bool)
- */
- removeChildByTag:function (tag, cleanup) {
- cc.Assert(tag != cc.NODE_TAG_INVALID, "Invalid tag");
-
- var child = this.getChildByTag(tag);
- if (child == null)
- cc.log("cocos2d: removeChildByTag: child not found!");
- else
- this.removeChild(child, cleanup);
- },
-
- /**
- * Removes all children from the container and do a cleanup all running actions depending on the cleanup parameter.
- * @deprecated
- * @param {Boolean | null } cleanup
- */
- removeAllChildrenWithCleanup:function (cleanup) {
- cc.log("removeAllChildrenWithCleanup is deprecated. Use removeAllChildren instead");
- this.removeAllChildren(cleanup);
- },
-
- /**
- * Removes all children from the container and do a cleanup all running actions depending on the cleanup parameter.
- * If the cleanup parameter is not passed, it will force a cleanup.
- * @param {Boolean | null } cleanup true if all running actions on all children nodes should be cleanup, false oterwise.
- */
- removeAllChildren:function (cleanup) {
- // not using detachChild improves speed here
- var __children = this._children;
- if (__children != null) {
- if (cleanup == null)
- cleanup = true;
- for (var i = 0; i < __children.length; i++) {
- var node = __children[i];
- if (node) {
- // IMPORTANT:
- // -1st do onExit
- // -2nd cleanup
- if (this._running) {
- node.onExitTransitionDidStart();
- node.onExit();
- }
- if (cleanup)
- node.cleanup();
- // set parent nil at the end
- node.setParent(null);
- }
- }
- this._children.length = 0;
- }
- },
-
- /**
- * @param {cc.Node} child
- * @param {Boolean} doCleanup
- * @private
- */
- _detachChild:function (child, doCleanup) {
- // IMPORTANT:
- // -1st do onExit
- // -2nd cleanup
- if (this._running) {
- child.onExitTransitionDidStart();
- child.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 (doCleanup)
- child.cleanup();
-
- // set parent nil at the end
- child._parent = null;
-
- cc.ArrayRemoveObject(this._children, child);
- },
-
- /** helper used by reorderChild & add
- * @param {cc.Node} child
- * @param {Number} z
- * @private
- */
- _insertChild:function (child, z) {
- this._reorderChildDirty = true;
- this._children.push(child);
- child._setZOrder(z);
- },
-
- /** Reorders a child according to a new z value.
- * The child MUST be already added.
- * @param {cc.Node} child An already added child node. It MUST be already added.
- * @param {Number} zOrder Z order for drawing priority. Please refer to setZOrder(int)
- */
- reorderChild:function (child, zOrder) {
- cc.Assert(child != null, "Child must be non-nil");
- this._reorderChildDirty = true;
- child.setOrderOfArrival(cc.s_globalOrderOfArrival++);
- child._setZOrder(zOrder);
- this.setNodeDirty();
- },
-
- /**
- *
- * Sorts the children array once before drawing, instead of every time when a child is added or reordered.
- * This appraoch can improves the performance massively.
- *
- * @note Don't call this manually unless a child added needs to be removed in the same frame
- */
- sortAllChildren:function () {
- if (this._reorderChildDirty) {
- var _children = this._children;
- var i, j, length = _children.length,tempChild;
-
- // insertion sort
- for (i = 0; i < length; i++) {
- var tempItem = _children[i];
- j = i - 1;
- tempChild = _children[j];
-
- //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
- while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
- ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
- _children[j + 1] = tempChild;
- j = j - 1;
- tempChild = _children[j];
- }
- _children[j + 1] = tempItem;
- }
-
- //don't need to check children recursively, that's done in visit of each child
- this._reorderChildDirty = false;
- }
- },
-
- // draw
- /**
Override this method to draw your own node.
- * The following GL states will be enabled by default:
- - glEnableClientState(GL_VERTEX_ARRAY);
- - glEnableClientState(GL_COLOR_ARRAY);
- - glEnableClientState(GL_TEXTURE_COORD_ARRAY);
- - glEnable(GL_TEXTURE_2D);
-
-
AND YOU SHOULD NOT DISABLE THEM AFTER DRAWING YOUR NODE
-
-
But if you enable any other GL state, you should disable it after drawing your node.
- * @param {CanvasContext} ctx
- */
- draw:function (ctx) {
- //cc.Assert(0);
- // override me
- // Only use- this function to draw your staff.
- // DON'T draw your stuff outside this method
- },
-
- /** performs OpenGL view-matrix transformation of it's ancestors.
- * Generally the ancestors are already transformed, but in certain cases (eg: attaching a FBO)
- * it's necessary to transform the ancestors again.
- */
- transformAncestors:function () {
- if (this._parent != null) {
- this._parent.transformAncestors();
- this._parent.transform();
- }
- },
-
- //scene managment
- /**
- *
- * Event callback that is invoked every time when CCNode enters the 'stage'.
- * If the CCNode enters the 'stage' with a transition, this event is called when the transition starts.
- * During onEnter you can't access a "sister/brother" node.
- * If you override onEnter, you shall call its parent's one, e.g., CCNode::onEnter().
- *
- * Event callback that is invoked when the CCNode enters in the 'stage'.
- * If the CCNode 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. CCNode::onEnterTransitionDidFinish()
- *
callback that is called every time the cc.Node leaves the 'stage'.
- * If the cc.Node leaves the 'stage' with a transition, this callback is called when the transition starts.
- * callback that is called every time the cc.Node leaves the 'stage'.
- * If the cc.Node leaves the 'stage' with a transition, this callback is called when the transition finishes.
- * During onExit you can't access a sibling node.
- * If you override onExit, you shall call its parent's one, e.g., CCNode::onExit().
- *
- */
- onExit:function () {
- this._running = false;
- this.pauseSchedulerAndActions();
- this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.onExit);
- this._componentContainer.removeAll();
- },
-
- // actions
- /**
- * Executes an action, and returns the action that is executed.
- * The node becomes the action's target. Refer to CCAction::getTarget()
- * @warning Starting from v0.8 actions don't retain their target anymore.
- * @param {cc.Action} action
- * @return {cc.Action} An Action pointer
- */
- runAction:function (action) {
- cc.Assert(action != null, "Argument must be non-nil");
- this.getActionManager().addAction(action, this, !this._running);
- return action;
- },
-
- /**
- * Stops and removes all actions from the running action list .
- */
- stopAllActions:function () {
- this.getActionManager().removeAllActionsFromTarget(this);
- },
-
- /**
- * Stops and removes an action from the running action list.
- * @param {cc.Action} action An action object to be removed.
- */
- stopAction:function (action) {
- this.getActionManager().removeAction(action);
- },
-
- /**
- * Removes an action from the running action list by its tag.
- * @param {Number} tag A tag that indicates the action to be removed.
- */
- stopActionByTag:function (tag) {
- cc.Assert(tag != cc.ACTION_TAG_INVALID, "Invalid tag");
- this.getActionManager().removeActionByTag(tag, this);
- },
-
- /**
- * Gets an action from the running action list by its tag.
- * @see setTag(int), getTag().
- * @param {Number} tag
- * @return {cc.Action} The action object with the given tag.
- */
- getActionByTag:function (tag) {
- cc.Assert(tag != cc.ACTION_TAG_INVALID, "Invalid tag");
- return this.getActionManager().getActionByTag(tag, this);
- },
-
- /** Returns the numbers of actions that are running plus the ones that are schedule to run (actions in actionsToAdd and actions arrays).
- * Composable actions are counted as 1 action. Example:
- * If you are running 1 Sequence of 7 actions, it will return 1.
- * If you are running 7 Sequences of 2 actions, it will return 7.
- * @return {Number} The number of actions that are running plus the ones that are schedule to run
- */
- numberOfRunningActions:function () {
- return this.getActionManager().numberOfRunningActionsInTarget(this);
- },
-
- // cc.Node - Callbacks
- // timers
- /**
- * schedules the "update" method.
- * It will use the order number 0. This method will be called every frame.
- * Scheduled methods with a lower order value will be called before the ones that have a higher order value.
- * Only one "update" method could be scheduled per node.
- */
- scheduleUpdate:function () {
- this.scheduleUpdateWithPriority(0);
- },
-
- /**
- *
- * schedules the "update" callback function with a custom priority.
- * This callback function will be called every frame.
- * Scheduled callback functions with a lower priority will be called before the ones that have a higher value.
- * Only one "update" callback function could be scheduled per node (You can't have 2 'update' callback functions).
- *
- * @param {Number} priority
- */
- scheduleUpdateWithPriority:function (priority) {
- this.getScheduler().scheduleUpdateForTarget(this, priority, !this._running);
- },
-
- /**
- * unschedules the "update" method.
- * @see scheduleUpdate();
- */
- unscheduleUpdate:function () {
- this.getScheduler().unscheduleUpdateForTarget(this);
- },
-
- /**
- * Schedules a custom selector.
- * If the selector is already scheduled, then the interval parameter will be updated without scheduling it again.
- *
- * @param {function} callback_fn A function wrapped as a selector
- * @param {Number} interval Tick interval in seconds. 0 means tick every frame. If interval = 0, it's recommended to use scheduleUpdate() instead.
- * @param {Number} repeat The selector will be excuted (repeat + 1) times, you can use kCCRepeatForever for tick infinitely.
- * @param {Number} delay The amount of time that the first tick will wait before execution.
- */
- schedule:function (callback_fn, interval, repeat, delay) {
- interval = interval || 0;
-
- cc.Assert(callback_fn, "Argument must be non-nil");
- cc.Assert(interval >= 0, "Argument must be positive");
-
- repeat = (repeat == null) ? cc.REPEAT_FOREVER : repeat;
- delay = delay || 0;
-
- this.getScheduler().scheduleCallbackForTarget(this, callback_fn, interval, repeat, delay, !this._running);
- },
-
- /**
- * Schedules a callback function that runs only once, with a delay of 0 or larger
- * @see schedule(SEL_SCHEDULE, float, unsigned int, float)
- * @param {function} callback_fn A function wrapped as a selector
- * @param {Number} delay The amount of time that the first tick will wait before execution.
- */
- scheduleOnce:function (callback_fn, delay) {
- this.schedule(callback_fn, 0.0, 0, delay);
- },
-
- /**
- * unschedules a custom callback function.
- * @see schedule(SEL_SCHEDULE, float, unsigned int, float)
- * @param {function} callback_fn A function wrapped as a selector
- */
- unschedule:function (callback_fn) {
- // explicit nil handling
- if (!callback_fn)
- return;
-
- this.getScheduler().unscheduleCallbackForTarget(this, callback_fn);
- },
-
- /**
- * unschedule all scheduled callback functions: custom callback functions, and the 'update' callback function.
- * Actions are not affected by this method.
- */
- unscheduleAllCallbacks:function () {
- this.getScheduler().unscheduleAllCallbacksForTarget(this);
- },
-
- /**
- * Resumes all scheduled selectors and actions.
- * This method is called internally by onEnter
- */
- resumeSchedulerAndActions:function () {
- this.getScheduler().resumeTarget(this);
- this.getActionManager().resumeTarget(this);
- },
-
- /**
- * Pauses all scheduled selectors and actions.
- * This method is called internally by onExit
- */
- pauseSchedulerAndActions:function () {
- this.getScheduler().pauseTarget(this);
- this.getActionManager().pauseTarget(this);
- },
-
- /**
- *
Sets the additional transform.
- * The additional transform will be concatenated at the end of nodeToParentTransform.
- * It could be used to simulate `parent-child` relationship between two nodes (e.g. one is in BatchNode, another isn't).
- *
- * @example
- * // create a batchNode
- * var batch= cc.SpriteBatchNode.create("Icon-114.png");
- * this.addChild(batch);
- *
- * // create two sprites, spriteA will be added to batchNode, they are using different textures.
- * var spriteA = cc.Sprite.createWithTexture(batch->getTexture());
- * var spriteB = cc.Sprite.create("Icon-72.png");
- *
- * batch.addChild(spriteA);
- *
- * // We can't make spriteB as spriteA's child since they use different textures. So just add it to layer.
- * // But we want to simulate `parent-child` relationship for these two node.
- * this.addChild(spriteB);
- *
- * //position
- * spriteA.setPosition(ccp(200, 200));
- *
- * // Gets the spriteA's transform.
- * var t = spriteA.nodeToParentTransform();
- *
- * // Sets the additional transform to spriteB, spriteB's postion will based on its pseudo parent i.e. spriteA.
- * spriteB.setAdditionalTransform(t);
- *
- * //scale
- * spriteA.setScale(2);
- *
- * // Gets the spriteA's transform.
- * t = spriteA.nodeToParentTransform();
- *
- * // Sets the additional transform to spriteB, spriteB's scale will based on its pseudo parent i.e. spriteA.
- * spriteB.setAdditionalTransform(t);
- *
- * //rotation
- * spriteA.setRotation(20);
- *
- * // Gets the spriteA's transform.
- * t = spriteA.nodeToParentTransform();
- *
- * // Sets the additional transform to spriteB, spriteB's rotation will based on its pseudo parent i.e. spriteA.
- * spriteB.setAdditionalTransform(t);
- */
- setAdditionalTransform:function (additionalTransform) {
- this._additionalTransform = additionalTransform;
- this._transformDirty = true;
- this._additionalTransformDirty = true;
- },
-
- /**
- * Returns the matrix that transform parent's space coordinates to the node's (local) space coordinates.
- * The matrix is in Pixels.
- * @return {cc.AffineTransform}
- */
- parentToNodeTransform:function () {
- if (this._inverseDirty) {
- this._inverse = cc.AffineTransformInvert(this.nodeToParentTransform());
- this._inverseDirty = false;
- }
- return this._inverse;
- },
-
- /**
- * Retrusn the world affine transform matrix. The matrix is in Pixels.
- * @return {cc.AffineTransform}
- */
- nodeToWorldTransform:function () {
- var t = this.nodeToParentTransform();
- for (var p = this._parent; p != null; p = p.getParent())
- t = cc.AffineTransformConcat(t, p.nodeToParentTransform());
- return t;
- },
-
- /**
- * Returns the inverse world affine transform matrix. The matrix is in Pixels.
- * @return {cc.AffineTransform}
- */
- worldToNodeTransform:function () {
- return cc.AffineTransformInvert(this.nodeToWorldTransform());
- },
-
- /**
- * Converts a Point to node (local) space coordinates. The result is in Points.
- * @param {cc.Point} worldPoint
- * @return {cc.Point}
- */
- convertToNodeSpace:function (worldPoint) {
- return cc.PointApplyAffineTransform(worldPoint, this.worldToNodeTransform());
- },
-
- /**
- * Converts a Point to world space coordinates. The result is in Points.
- * @param {cc.Point} nodePoint
- * @return {cc.Point}
- */
- convertToWorldSpace:function (nodePoint) {
- return cc.PointApplyAffineTransform(nodePoint, this.nodeToWorldTransform());
- },
-
- /**
- * Converts a Point to node (local) space coordinates. The result is in Points.
- * treating the returned/received node point as anchor relative.
- * @param {cc.Point} worldPoint
- * @return {cc.Point}
- */
- convertToNodeSpaceAR:function (worldPoint) {
- return cc.pSub(this.convertToNodeSpace(worldPoint), this._anchorPointInPoints);
- },
-
- /**
- * Converts a local Point to world space coordinates.The result is in Points.
- * treating the returned/received node point as anchor relative.
- * @param {cc.Point} nodePoint
- * @return {cc.Point}
- */
- convertToWorldSpaceAR:function (nodePoint) {
- var pt = cc.pAdd(nodePoint, this._anchorPointInPoints);
- return this.convertToWorldSpace(pt);
- },
-
- _convertToWindowSpace:function (nodePoint) {
- var worldPoint = this.convertToWorldSpace(nodePoint);
- return cc.Director.getInstance().convertToUI(worldPoint);
- },
-
- /** convenience methods which take a cc.Touch instead of cc.Point
- * @param {cc.Touch} touch
- * @return {cc.Point}
- */
- convertTouchToNodeSpace:function (touch) {
- var point = touch.getLocation();
- //TODO This point needn't convert to GL in HTML5
- //point = cc.Director.getInstance().convertToGL(point);
- return this.convertToNodeSpace(point);
- },
-
- /**
- * converts a cc.Touch (world coordinates) into a local coordiante. This method is AR (Anchor Relative).
- * @param {cc.Touch}touch
- * @return {cc.Point}
- */
- convertTouchToNodeSpaceAR:function (touch) {
- var point = touch.getLocation();
- point = cc.Director.getInstance().convertToGL(point);
- return this.convertToNodeSpaceAR(point);
- },
-
- /**
- * Update will be called automatically every frame if "scheduleUpdate" is called, and the node is "live"
- * (override me)
- * @param {Number} dt
- */
- update:function (dt) {
- if(this._componentContainer && !this._componentContainer.isEmpty())
- this._componentContainer.visit(dt);
- },
-
- /**
- *
- * Calls children's updateTransform() method recursively.
- *
- * This method is moved from CCSprite, so it's no longer specific to CCSprite.
- * As the result, you apply CCSpriteBatchNode's optimization on your customed CCNode.
- * e.g., batchNode->addChild(myCustomNode), while you can only addChild(sprite) before.
- *
cc.Sprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_graphics) ) (Canvas implement)
+ *
cc.Sprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_graphics) )
*
* cc.Sprite can be created with an image, or with a sub-rectangle of an image.
*
@@ -292,8 +292,7 @@ if (cc.SPRITEBATCHNODE_RENDER_SUBPIXEL) {
* var aSprite = new cc.Sprite();
* aSprite.initWithFile("HelloHTML5World.png",cc.rect(0,0,480,320));
*/
-cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
- /// ---- common properties start ----
+cc.Sprite = cc.NodeRGBA.extend(/** @lends cc.Sprite# */{
RGBAProtocol:true,
//
// Data used when the sprite is rendered using a CCSpriteSheet
@@ -331,7 +330,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
_flipX:false, //Whether the sprite is flipped horizontally or not.
_flipY:false, //Whether the sprite is flipped vertically or not.
- _textureLoaded: false,
+ _textureLoaded:false,
_loadedEventListeners: null,
_newTextureWhenChangeColor: null, //hack property for LabelBMFont
@@ -369,15 +368,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
},
/**
- * Returns the quad (tex coords, vertex coords and color) information. (Use in WebGL model only)
- * @return {null}
- */
- getQuad:function () {
- return null;
- },
-
- /**
- * returns whether or not the texture rectangle is rotated
+ * Returns whether or not the texture rectangle is rotated.
* @return {Boolean}
*/
isTextureRectRotated:function () {
@@ -425,6 +416,22 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
this._textureAtlas = textureAtlas;
},
+ /**
+ * return the SpriteBatchNode of the cc.Sprite
+ * @return {cc.SpriteBatchNode}
+ */
+ getSpriteBatchNode:function () {
+ return this._batchNode;
+ },
+
+ /**
+ * set the SpriteBatchNode of the cc.Sprite
+ * @param {cc.SpriteBatchNode} spriteBatchNode
+ */
+ setSpriteBatchNode:function (spriteBatchNode) {
+ this._batchNode = spriteBatchNode;
+ },
+
/**
* Gets the offset position of the sprite. Calculated automatically by editors like Zwoptex.
* @return {cc.Point}
@@ -463,7 +470,15 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
return ret;
},
- _spriteFrameLoadedCallback:function(spriteFrame){
+ _spriteFrameLoadedCallback:null,
+
+ _spriteFrameLoadedCallbackForWebGL:function(spriteFrame){
+ this.setNodeDirty();
+ this.setTextureRect(spriteFrame.getRect(), spriteFrame.isRotated(), spriteFrame.getOriginalSize());
+ this._callLoadedEventCallbacks();
+ },
+
+ _spriteFrameLoadedCallbackForCanvas:function(spriteFrame){
this.setNodeDirty();
this.setTextureRect(spriteFrame.getRect(), spriteFrame.isRotated(), spriteFrame.getOriginalSize());
var curColor = this.getColor();
@@ -600,8 +615,10 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
// recursively set dirty
var locChildren = this._children;
if (locChildren != null) {
- for (var i = 0; i < locChildren.length; i++)
- locChildren[i].setDirtyRecursively(true);
+ for (var i = 0; i < locChildren.length; i++) {
+ if (locChildren[i] instanceof cc.Sprite)
+ locChildren[i].setDirtyRecursively(true);
+ }
}
},
@@ -694,7 +711,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
*
The scale factor of the node. 1.0 is the default scale factor.
* It modifies the X and Y scale at the same time. (override cc.Node )
* @param {Number} scale
- * @param {Number} [scaleY=]
+ * @param {Number|null} [scaleY=]
* @override
*/
setScale:function (scale, scaleY) {
@@ -797,13 +814,20 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
//
// RGBA protocol
//
-
- // RGBAProtocol
/**
- * opacity: conforms to cc.RGBAProtocol protocol
+ * opacity: conforms to CCRGBAProtocol protocol
* @param {Boolean} modify
*/
- setOpacityModifyRGB:function (modify) {
+ setOpacityModifyRGB:null,
+
+ _setOpacityModifyRGBForWebGL: function (modify) {
+ if (this._opacityModifyRGB !== modify) {
+ this._opacityModifyRGB = modify;
+ this.updateColor();
+ }
+ },
+
+ _setOpacityModifyRGBForCanvas: function (modify) {
if (this._opacityModifyRGB !== modify) {
this._opacityModifyRGB = modify;
this.setNodeDirty();
@@ -818,7 +842,13 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
return this._opacityModifyRGB;
},
- updateDisplayedOpacity:function (parentOpacity) {
+ updateDisplayedOpacity: null,
+ _updateDisplayedOpacityForWebGL:function (parentOpacity) {
+ cc.NodeRGBA.prototype.updateDisplayedOpacity.call(this, parentOpacity);
+ this.updateColor();
+ },
+
+ _updateDisplayedOpacityForCanvas:function (parentOpacity) {
cc.NodeRGBA.prototype.updateDisplayedOpacity.call(this, parentOpacity);
this._changeTextureColor();
this.setNodeDirty();
@@ -865,28 +895,66 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
getTexture:function () {
return this._texture;
},
- /// ---- common properties end ----
+ _quad:null, // vertex coords, texture coords and color info
+ _quadWebBuffer:null,
+ _quadDirty:false,
_colorized:false,
_isLighterMode:false,
_originalTexture:null,
/**
* Constructor
- * @param {String|cc.SpriteFrame|cc.SpriteBatchNode|HTMLImageElement} fileName sprite construct parameter
+ * @param {String|cc.SpriteFrame|cc.SpriteBatchNode|HTMLImageElement|cc.Texture2D} fileName sprite construct parameter
*/
- ctor:function (fileName) {
+ ctor: null,
+
+ _ctorForWebGL: function (fileName) {
cc.NodeRGBA.prototype.ctor.call(this);
this._shouldBeHidden = false;
this._offsetPosition = cc.p(0, 0);
this._unflippedOffsetPositionFromCenter = cc.p(0, 0);
- this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST};
+ this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST};
+
+ this._quad = new cc.V3F_C4B_T2F_Quad();
+ this._quadWebBuffer = cc.renderContext.createBuffer();
+ this._quadDirty = true;
+
this._textureLoaded = true;
this._loadedEventListeners = [];
+
+ if (fileName) {
+ if (typeof(fileName) === "string") {
+ var frame = cc.SpriteFrameCache.getInstance().getSpriteFrame(fileName);
+ this.initWithSpriteFrame(frame);
+ } else if (typeof(fileName) === "object") {
+ if (fileName instanceof cc.SpriteFrame) {
+ this.initWithSpriteFrame(fileName);
+ } else if ((fileName instanceof HTMLImageElement) || (fileName instanceof HTMLCanvasElement)) {
+ var texture2d = new cc.Texture2D();
+ texture2d.initWithElement(fileName);
+ texture2d.handleLoadedTexture();
+ this.initWithTexture(texture2d);
+ } else if (fileName instanceof cc.Texture2D) {
+ this.initWithTexture(fileName);
+ }
+ }
+ }
+ },
+
+ _ctorForCanvas: function (fileName) {
+ cc.NodeRGBA.prototype.ctor.call(this);
+ this._shouldBeHidden = false;
+ this._offsetPosition = cc.p(0, 0);
+ this._unflippedOffsetPositionFromCenter = cc.p(0, 0);
+ this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST};
+
this._newTextureWhenChangeColor = false;
+ this._textureLoaded = true;
+ this._loadedEventListeners = [];
if (fileName) {
- if (typeof(fileName) == "string") {
+ if (typeof(fileName) === "string") {
var frame = cc.SpriteFrameCache.getInstance().getSpriteFrame(fileName);
this.initWithSpriteFrame(frame);
} else if (typeof(fileName) === "object") {
@@ -896,24 +964,41 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
var texture2d = new cc.Texture2D();
texture2d.initWithElement(fileName);
texture2d.handleLoadedTexture();
- this.initWithTexture(texture2d)
+ this.initWithTexture(texture2d);
} else if (fileName instanceof cc.Texture2D) {
- this.initWithTexture(fileName)
+ this.initWithTexture(fileName);
}
}
}
},
+ /**
+ * Returns the quad (tex coords, vertex coords and color) information.
+ * @return {cc.V3F_C4B_T2F_Quad}
+ */
+ getQuad:function () {
+ return this._quad;
+ },
+
/**
* conforms to cc.TextureProtocol protocol
* @param {Number|cc.BlendFunc} src
* @param {Number} dst
*/
- setBlendFunc:function (src, dst) {
+ setBlendFunc: null,
+
+ _setBlendFuncForWebGL: function (src, dst) {
+ if (arguments.length == 1)
+ this._blendFunc = src;
+ else
+ this._blendFunc = {src: src, dst: dst};
+ },
+
+ _setBlendFuncForCanvas: function (src, dst) {
if (arguments.length == 1)
this._blendFunc = src;
else
- this._blendFunc = {src:src, dst:dst};
+ this._blendFunc = {src: src, dst: dst};
this._isLighterMode = (this._blendFunc && (this._blendFunc.src === gl.SRC_ALPHA) && (this._blendFunc.dst === gl.ONE));
},
@@ -921,7 +1006,46 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
* Initializes an empty sprite with nothing init.
* @return {Boolean}
*/
- init:function () {
+ init:null,
+
+ _initForWebGL: function () {
+ if (arguments.length > 0)
+ return this.initWithFile(arguments[0], arguments[1]);
+
+ cc.NodeRGBA.prototype.init.call(this);
+ this._dirty = this._recursiveDirty = false;
+ this._opacityModifyRGB = true;
+
+ this._blendFunc.src = cc.BLEND_SRC;
+ this._blendFunc.dst = cc.BLEND_DST;
+
+ // update texture (calls _updateBlendFunc)
+ this.setTexture(null);
+ this._textureLoaded = true;
+ this._flipX = this._flipY = false;
+
+ // default transform anchor: center
+ this.setAnchorPoint(cc.p(0.5, 0.5));
+
+ // zwoptex default values
+ this._offsetPosition = cc.PointZero();
+ this._hasChildren = false;
+
+ // Atlas: Color
+ var tempColor = {r: 255, g: 255, b: 255, a: 255};
+ this._quad.bl.colors = tempColor;
+ this._quad.br.colors = tempColor;
+ this._quad.tl.colors = tempColor;
+ this._quad.tr.colors = tempColor;
+ this._quadDirty = true;
+
+ // updated in "useSelfRender"
+ // Atlas: TexCoords
+ this.setTextureRect(cc.RectZero(), false, cc.SizeZero());
+ return true;
+ },
+
+ _initForCanvas: function () {
if (arguments.length > 0)
return this.initWithFile(arguments[0], arguments[1]);
@@ -981,18 +1105,79 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
},
/**
- * Initializes a sprite with a texture and a rect in points, optionally rotated.
+ * Initializes a sprite with a texture and a rect in points, optionally rotated.
* After initialization, the rect used will be the size of the texture, and the offset will be (0,0).
* @param {cc.Texture2D|HTMLImageElement|HTMLCanvasElement} texture A pointer to an existing CCTexture2D object. You can use a CCTexture2D object for many sprites.
* @param {cc.Rect} rect Only the contents inside rect of this texture will be applied for this sprite.
- * @param {Boolean} rotated Whether or not the texture rectangle is rotated.
+ * @param {Boolean} [rotated] Whether or not the texture rectangle is rotated.
* @return {Boolean} true if the sprite is initialized properly, false otherwise.
* @example
* var img =cc.TextureCache.getInstance().addImage("HelloHTML5World.png");
* var mySprite = new cc.Sprite();
* mySprite.initWithTexture(img,cc.rect(0,0,480,320));
*/
- initWithTexture:function (texture, rect, rotated) {
+ initWithTexture: null,
+
+ _initWithTextureForWebGL: function (texture, rect, rotated) {
+ var argnum = arguments.length;
+ if (argnum == 0)
+ throw "Sprite.initWithTexture(): Argument must be non-nil ";
+
+ rotated = rotated || false;
+
+ if (!cc.NodeRGBA.prototype.init.call(this))
+ return false;
+
+ this._batchNode = null;
+ this._recursiveDirty = false;
+ this._dirty = false;
+ this._opacityModifyRGB = true;
+
+ this._blendFunc.src = cc.BLEND_SRC;
+ this._blendFunc.dst = cc.BLEND_DST;
+
+ this._flipX = this._flipY = false;
+
+ // default transform anchor: center
+ this.setAnchorPoint(cc.p(0.5, 0.5));
+
+ // zwoptex default values
+ this._offsetPosition = cc.p(0, 0);
+ this._hasChildren = false;
+
+ // Atlas: Color
+ var tmpColor = new cc.Color4B(255, 255, 255, 255);
+ var locQuad = this._quad;
+ locQuad.bl.colors = tmpColor;
+ locQuad.br.colors = tmpColor;
+ locQuad.tl.colors = tmpColor;
+ locQuad.tr.colors = tmpColor;
+
+ var locTextureLoaded = texture.isLoaded();
+ this._textureLoaded = locTextureLoaded;
+
+ if (!locTextureLoaded) {
+ this._rectRotated = rotated || false;
+ this._rect = rect;
+ texture.addLoadedEventListener(this._textureLoadedCallback, this);
+ return true;
+ }
+
+ if (!rect) {
+ rect = cc.rect(0, 0, 0, 0);
+ rect.size = texture.getContentSize();
+ }
+ this.setTexture(texture);
+ this.setTextureRect(rect, rotated, rect.size);
+
+ // by default use "Self Render".
+ // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render"
+ this.setBatchNode(null);
+ this._quadDirty = true;
+ return true;
+ },
+
+ _initWithTextureForCanvas: function (texture, rect, rotated) {
var argnum = arguments.length;
if (argnum == 0)
throw "Sprite.initWithTexture(): Argument must be non-nil ";
@@ -1023,7 +1208,7 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
var locTextureLoaded = texture.isLoaded();
this._textureLoaded = locTextureLoaded;
- if(!locTextureLoaded){
+ if (!locTextureLoaded) {
this._rectRotated = rotated || false;
this._rect = rect;
texture.addLoadedEventListener(this._textureLoadedCallback, this);
@@ -1045,16 +1230,17 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
return true;
},
- _textureLoadedCallback:function(sender){
+ _textureLoadedCallback: null,
+
+ _textureLoadedCallbackForWebGL: function (sender) {
this._textureLoaded = true;
var locRect = this._rect;
if (!locRect) {
locRect = cc.rect(0, 0, 0, 0);
locRect.size = sender.getContentSize();
- } else if(cc._rectEqualToZero(locRect)){
+ } else if (cc._rectEqualToZero(locRect)) {
locRect.size = sender.getContentSize();
}
- this._originalTexture = sender;
this.setTexture(sender);
this.setTextureRect(locRect, this._rectRotated, locRect.size);
@@ -1062,7 +1248,27 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
// by default use "Self Render".
// if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render"
this.setBatchNode(null);
+ this._quadDirty = true;
+ this._callLoadedEventCallbacks();
+ },
+
+ _textureLoadedCallbackForCanvas: function (sender) {
+ this._textureLoaded = true;
+ var locRect = this._rect;
+ if (!locRect) {
+ locRect = cc.rect(0, 0, 0, 0);
+ locRect.size = sender.getContentSize();
+ } else if (cc._rectEqualToZero(locRect)) {
+ locRect.size = sender.getContentSize();
+ }
+ this._originalTexture = sender;
+
+ this.setTexture(sender);
+ this.setTextureRect(locRect, this._rectRotated, locRect.size);
+ // by default use "Self Render".
+ // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render"
+ this.setBatchNode(null);
this._callLoadedEventCallbacks();
},
@@ -1072,7 +1278,51 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
* @param {Boolean} rotated
* @param {cc.Size} untrimmedSize
*/
- setTextureRect:function (rect, rotated, untrimmedSize) {
+ setTextureRect:null,
+
+ _setTextureRectForWebGL:function (rect, rotated, untrimmedSize) {
+ this._rectRotated = rotated || false;
+ untrimmedSize = untrimmedSize || rect.size;
+
+ this.setContentSize(untrimmedSize);
+ this.setVertexRect(rect);
+ this._setTextureCoords(rect);
+
+ var relativeOffset = this._unflippedOffsetPositionFromCenter;
+ if (this._flipX)
+ relativeOffset.x = -relativeOffset.x;
+ if (this._flipY)
+ relativeOffset.y = -relativeOffset.y;
+
+ var locRect = this._rect;
+ this._offsetPosition.x = relativeOffset.x + (this._contentSize.width - locRect.width) / 2;
+ this._offsetPosition.y = relativeOffset.y + (this._contentSize.height - locRect.height) / 2;
+
+ // rendering using batch node
+ if (this._batchNode) {
+ // update dirty_, don't update recursiveDirty_
+ //this.setDirty(true);
+ this._dirty = true;
+ } else {
+ // self rendering
+ // Atlas: Vertex
+ var x1 = 0 + this._offsetPosition.x;
+ var y1 = 0 + this._offsetPosition.y;
+ var x2 = x1 + locRect.width;
+ var y2 = y1 + locRect.height;
+
+ // Don't update Z.
+ var locQuad = this._quad;
+ locQuad.bl.vertices = {x:x1, y:y1, z:0};
+ locQuad.br.vertices = {x:x2, y:y1, z:0};
+ locQuad.tl.vertices = {x:x1, y:y2, z:0};
+ locQuad.tr.vertices = {x:x2, y:y2, z:0};
+
+ this._quadDirty = true;
+ }
+ },
+
+ _setTextureRectForCanvas: function (rect, rotated, untrimmedSize) {
this._rectRotated = rotated || false;
untrimmedSize = untrimmedSize || rect.size;
@@ -1099,14 +1349,20 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
/**
* updates the quad according the the rotation, position, scale values.
*/
- updateTransform:function () {
+ updateTransform: null,
+
+ _updateTransformForWebGL: function () {
//cc.Assert(this._batchNode, "updateTransform is only valid when cc.Sprite is being rendered using an cc.SpriteBatchNode");
// recaculate matrix only if it is dirty
- if (this._dirty) {
+ if (this.isDirty()) {
+ var locQuad = this._quad, locParent = this._parent;
// If it is not visible, or one of its ancestors is not visible, then do nothing:
- var locParent = this._parent;
if (!this._visible || ( locParent && locParent != this._batchNode && locParent._shouldBeHidden)) {
+ locQuad.br.vertices = {x: 0, y: 0, z: 0};
+ locQuad.tl.vertices = {x: 0, y: 0, z: 0};
+ locQuad.tr.vertices = {x: 0, y: 0, z: 0};
+ locQuad.bl.vertices = {x: 0, y: 0, z: 0};
this._shouldBeHidden = true;
} else {
this._shouldBeHidden = false;
@@ -1117,1170 +1373,24 @@ cc.SpriteCanvas = cc.NodeRGBA.extend(/** @lends cc.SpriteCanvas# */{
//cc.Assert(this._parent instanceof cc.Sprite, "Logic error in CCSprite. Parent must be a CCSprite");
this._transformToBatch = cc.AffineTransformConcat(this.nodeToParentTransform(), locParent._transformToBatch);
}
- }
- this._recursiveDirty = false;
- this._dirty = false;
- }
-
- // recursively iterate over children
- if (this._hasChildren)
- this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.updateTransform);
- },
-
- /**
- * Add child to sprite (override cc.Node )
- * @param {cc.Sprite} child
- * @param {Number} zOrder child's zOrder
- * @param {String} tag child's tag
- * @override
- */
- addChild:function (child, zOrder, tag) {
- cc.Assert(child != null, "Argument must be non-NULL");
- if (zOrder == null)
- zOrder = child._zOrder;
- if (tag == null)
- tag = child._tag;
-
- //cc.Node already sets isReorderChildDirty_ so this needs to be after batchNode check
- cc.Node.prototype.addChild.call(this, child, zOrder, tag);
- this._hasChildren = true;
- },
-
- /**
- * opacity setter
- * @param {Number} opacity
- */
- setOpacity:function (opacity) {
- cc.NodeRGBA.prototype.setOpacity.call(this, opacity);
- this.setNodeDirty();
- },
-
- /**
- * color setter
- * @param {cc.Color3B} color3
- */
- setColor:function (color3) {
- var curColor = this.getColor();
- if ((curColor.r === color3.r) && (curColor.g === color3.g) && (curColor.b === color3.b))
- return;
-
- cc.NodeRGBA.prototype.setColor.call(this, color3);
- this._changeTextureColor();
- this.setNodeDirty();
- },
-
- updateDisplayedColor:function (parentColor) {
- cc.NodeRGBA.prototype.updateDisplayedColor.call(this, parentColor);
- this._changeTextureColor();
- this.setNodeDirty();
- },
-
- // Frames
- /**
- * Sets a new display frame to the cc.Sprite.
- * @param {cc.SpriteFrame} newFrame
- */
- setDisplayFrame:function (newFrame) {
- this.setNodeDirty();
-
- var frameOffset = newFrame.getOffset();
- this._unflippedOffsetPositionFromCenter.x = frameOffset.x;
- this._unflippedOffsetPositionFromCenter.y = frameOffset.y;
-
- // update rect
- this._rectRotated = newFrame.isRotated();
-
- var pNewTexture = newFrame.getTexture();
- var locTextureLoaded = newFrame.textureLoaded();
- if(!locTextureLoaded){
- this._textureLoaded = false;
- newFrame.addLoadedEventListener(function(sender){
- this._textureLoaded = true;
- var locNewTexture = sender.getTexture();
- if (locNewTexture != this._texture)
- this.setTexture(locNewTexture);
- this.setTextureRect(sender.getRect(), this._rectRotated, sender.getOriginalSize());
- this._callLoadedEventCallbacks();
- },this);
- }
- // update texture before updating texture rect
- if (pNewTexture != this._texture)
- this.setTexture(pNewTexture);
-
- if (this._rectRotated)
- this._originalTexture = pNewTexture;
-
- this.setTextureRect(newFrame.getRect(), this._rectRotated, newFrame.getOriginalSize());
- this._colorized = false;
- if (locTextureLoaded) {
- var curColor = this.getColor();
- if (curColor.r !== 255 || curColor.g !== 255 || curColor.b !== 255)
- this._changeTextureColor();
- }
- },
-
- /**
- * Returns whether or not a cc.SpriteFrame is being displayed
- * @param {cc.SpriteFrame} frame
- * @return {Boolean}
- */
- isFrameDisplayed:function (frame) {
- if (frame.getTexture() != this._texture)
- return false;
- return cc.rectEqualToRect(frame.getRect(), this._rect);
- },
-
- /**
- * Returns the current displayed frame.
- * @return {cc.SpriteFrame}
- */
- displayFrame:function () {
- return cc.SpriteFrame._frameWithTextureForCanvas(this._texture,
- cc.RECT_POINTS_TO_PIXELS(this._rect),
- this._rectRotated,
- cc.POINT_POINTS_TO_PIXELS(this._unflippedOffsetPositionFromCenter),
- cc.SIZE_POINTS_TO_PIXELS(this._contentSize));
- },
-
- /**
- * Sets the batch node to sprite
- * @param {cc.SpriteBatchNode|null} spriteBatchNode
- * @example
- * var batch = cc.SpriteBatchNode.create("Images/grossini_dance_atlas.png", 15);
- * var sprite = cc.Sprite.createWithTexture(batch.getTexture(), cc.RectMake(0, 0, 57, 57));
- * batch.addChild(sprite);
- * layer.addChild(batch);
- */
- setBatchNode:function (spriteBatchNode) {
- this._batchNode = spriteBatchNode; // weak reference
-
- // self render
- if (!this._batchNode) {
- this._atlasIndex = cc.SPRITE_INDEX_NOT_INITIALIZED;
- this.setTextureAtlas(null);
- this._recursiveDirty = false;
- this.setDirty(false);
- } else {
- // using batch
- this._transformToBatch = cc.AffineTransformIdentity();
- this.setTextureAtlas(this._batchNode.getTextureAtlas()); // weak ref
- }
- },
-
- // CCTextureProtocol
- /**
- * Texture of sprite setter
- * @param {HTMLImageElement|HTMLCanvasElement|cc.Texture2D} texture
- */
- setTexture:function (texture) {
- // CCSprite: setTexture doesn't work when the sprite is rendered using a CCSpriteSheet
- cc.Assert(!texture || texture instanceof cc.Texture2D, "setTexture expects a CCTexture2D. Invalid argument");
- if (this._texture != texture) {
- if(texture && texture.getHtmlElementObj() instanceof HTMLImageElement){
- this._originalTexture = texture;
- }
- this._texture = texture;
- }
- },
-
- _changeTextureColor: function () {
- var locElement, locTexture = this._texture, locRect = this.getTextureRect();
- if (locTexture && locRect.width > 0) {
- locElement = locTexture.getHtmlElementObj();
- if (!locElement)
- return;
-
- var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(this._originalTexture.getHtmlElementObj());
- if (cacheTextureForColor) {
- this._colorized = true;
- //generate color texture cache
- if (locElement instanceof HTMLCanvasElement && !this._rectRotated && !this._newTextureWhenChangeColor)
- cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, locRect, locElement);
- else {
- locElement = cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, locRect);
- locTexture = new cc.Texture2D();
- locTexture.initWithElement(locElement);
- locTexture.handleLoadedTexture();
- this.setTexture(locTexture);
- }
- }
- }
- },
-
- /**
- * draw sprite to canvas
- * @param {CanvasRenderingContext2D} ctx 2d context of canvas
- */
- draw:function (ctx) {
- if(!this._textureLoaded)
- return;
-
- var context = ctx || cc.renderContext;
- if (this._isLighterMode)
- context.globalCompositeOperation = 'lighter';
-
- context.globalAlpha = this._displayedOpacity / 255;
- var locRect = this._rect, locContentSize = this._contentSize, locOffsetPosition = this._offsetPosition;
- var flipXOffset = 0 | (locOffsetPosition.x), flipYOffset = -locOffsetPosition.y - locRect.height;
- if (this._flipX) {
- flipXOffset = -locOffsetPosition.x - locRect.width;
- context.scale(-1, 1);
- }
- if (this._flipY) {
- flipYOffset = locOffsetPosition.y;
- context.scale(1, -1);
- }
- if (this._texture && locRect.width > 0) {
- var image = this._texture.getHtmlElementObj();
- if (this._colorized) {
- context.drawImage(image,
- 0, 0, 0 | locRect.width, 0 | locRect.height,
- flipXOffset, flipYOffset, locRect.width, locRect.height);
- } else {
- context.drawImage(image,
- 0 | locRect.x, 0 | locRect.y, 0 | locRect.width, 0 | locRect.height,
- flipXOffset, flipYOffset, locRect.width, locRect.height);
- }
- } else if (locContentSize.width !== 0) {
- var curColor = this.getColor();
- context.fillStyle = "rgba(" + curColor.r + "," + curColor.g + "," + curColor.b + ",1)";
- context.fillRect(flipXOffset, flipYOffset, locContentSize.width, locContentSize.height);
- }
-
- if (cc.SPRITE_DEBUG_DRAW === 1) {
- // draw bounding box
- context.strokeStyle = "rgba(0,255,0,1)";
- flipYOffset = -flipYOffset;
- var vertices1 = [cc.p(flipXOffset, flipYOffset), cc.p(flipXOffset + locRect.width, flipYOffset), cc.p(flipXOffset + locRect.width, flipYOffset - locRect.height),
- cc.p(flipXOffset, flipYOffset - locRect.height)];
- cc.drawingUtil.drawPoly(vertices1, 4, true);
- } else if (cc.SPRITE_DEBUG_DRAW === 2) {
- // draw texture box
- context.strokeStyle = "rgba(0,255,0,1)";
- var drawSize = this._rect.size;
- flipYOffset = -flipYOffset;
- var vertices2 = [cc.p(flipXOffset, flipYOffset), cc.p(flipXOffset + drawSize.width, flipYOffset),
- cc.p(flipXOffset + drawSize.width, flipYOffset - drawSize.height), cc.p(flipXOffset, flipYOffset - drawSize.height)];
- cc.drawingUtil.drawPoly(vertices2, 4, true);
- }
- cc.g_NumberOfDraws++;
- }
-});
-
-/**
- *
cc.Sprite is a 2d image ( http://en.wikipedia.org/wiki/Sprite_(computer_graphics) ) (WebGL implement)
- *
- * cc.Sprite can be created with an image, or with a sub-rectangle of an image.
- *
- * If the parent or any of its ancestors is a cc.SpriteBatchNode then the following features/limitations are valid
- * - Features when the parent is a cc.BatchNode:
- * - MUCH faster rendering, specially if the cc.SpriteBatchNode has many children. All the children will be drawn in a single batch.
- *
- * - Limitations
- * - Camera is not supported yet (eg: CCOrbitCamera action doesn't work)
- * - GridBase actions are not supported (eg: CCLens, CCRipple, CCTwirl)
- * - The Alias/Antialias property belongs to CCSpriteBatchNode, so you can't individually set the aliased property.
- * - The Blending function property belongs to CCSpriteBatchNode, so you can't individually set the blending function property.
- * - Parallax scroller is not supported, but can be simulated with a "proxy" sprite.
- *
- * If the parent is an standard cc.Node, then cc.Sprite behaves like any other cc.Node:
- * - It supports blending functions
- * - It supports aliasing / antialiasing
- * - But the rendering will be slower: 1 draw per children.
- *
- * The default anchorPoint in cc.Sprite is (0.5, 0.5).
- * @class
- * @extends cc.NodeRGBA
- *
- * @example
- * var aSprite = new cc.Sprite();
- * aSprite.initWithFile("HelloHTML5World.png",cc.rect(0,0,480,320));
- */
-cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
- /// ---- common properties start ----
- RGBAProtocol:true,
- //
- // Data used when the sprite is rendered using a CCSpriteSheet
- //
- _textureAtlas:null, //cc.SpriteBatchNode texture atlas
-
- _atlasIndex:0,
- _batchNode:null,
- _dirty:false, //Whether the sprite needs to be updated
- _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
-
- //
- // Shared data
- //
- // texture
- _rect:cc.rect(0, 0, 0, 0), //Retangle of cc.Texture2D
- _rectRotated:false, //Whether the texture is rotated
-
- // Offset Position (used by Zwoptex)
- _offsetPosition:null, // absolute
- _unflippedOffsetPositionFromCenter:null,
-
- // opacity and RGB protocol
- _opacityModifyRGB:false,
-
- // image is flipped
- _flipX:false, //Whether the sprite is flipped horizontally or not.
- _flipY:false, //Whether the sprite is flipped vertically or not.
-
- _textureLoaded:false,
-
- textureLoaded:function(){
- return this._textureLoaded;
- },
-
- addLoadedEventListener:function(callback, target){
- this._loadedEventListeners.push({eventCallback:callback, eventTarget:target});
- },
-
- _callLoadedEventCallbacks:function(){
- var locListeners = this._loadedEventListeners;
- for(var i = 0, len = locListeners.length; i < len; i++){
- var selCallback = locListeners[i];
- selCallback.eventCallback.call(selCallback.eventTarget, this);
- }
- locListeners.length = 0;
- },
-
- /**
- * 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 () {
- return this._dirty;
- },
-
- /**
- * Makes the Sprite to be updated in the Atlas.
- * @param {Boolean} bDirty
- */
- setDirty:function (bDirty) {
- this._dirty = bDirty;
- },
-
- /**
- * Returns whether or not the texture rectangle is rotated.
- * @return {Boolean}
- */
- isTextureRectRotated:function () {
- return this._rectRotated;
- },
-
- /**
- * Returns the index used on the TextureAtlas.
- * @return {Number}
- */
- getAtlasIndex:function () {
- return this._atlasIndex;
- },
-
- /**
- * Set the index used on the TextureAtlas.
- * @warning Don't modify this value unless you know what you are doing
- * @param {Number} atlasIndex
- */
- setAtlasIndex:function (atlasIndex) {
- this._atlasIndex = atlasIndex;
- },
-
- /**
- * returns the rect of the cc.Sprite in points
- * @return {cc.Rect}
- */
- getTextureRect:function () {
- return cc.rect(this._rect.x, this._rect.y, this._rect.width, this._rect.height);
- },
-
- /**
- * Gets the weak reference of the cc.TextureAtlas when the sprite is rendered using via cc.SpriteBatchNode
- * @return {cc.TextureAtlas}
- */
- getTextureAtlas:function () {
- return this._textureAtlas;
- },
-
- /**
- * Sets the weak reference of the cc.TextureAtlas when the sprite is rendered using via cc.SpriteBatchNode
- * @param {cc.TextureAtlas} textureAtlas
- */
- setTextureAtlas:function (textureAtlas) {
- this._textureAtlas = textureAtlas;
- },
-
- /**
- * return the SpriteBatchNode of the cc.Sprite
- * @return {cc.SpriteBatchNode}
- */
- getSpriteBatchNode:function () {
- return this._batchNode;
- },
-
- /**
- * set the SpriteBatchNode of the cc.Sprite
- * @param {cc.SpriteBatchNode} spriteBatchNode
- */
- setSpriteBatchNode:function (spriteBatchNode) {
- this._batchNode = spriteBatchNode;
- },
-
- /**
- * Gets the offset position of the sprite. Calculated automatically by editors like Zwoptex.
- * @return {cc.Point}
- */
- getOffsetPosition:function () {
- return cc.p(this._offsetPosition.x, this._offsetPosition.y);
- },
-
- /**
- * conforms to cc.TextureProtocol protocol
- * @return {cc.BlendFunc}
- */
- getBlendFunc:function () {
- return this._blendFunc;
- },
-
- /**
- * Initializes a sprite with an SpriteFrame. The texture and rect in SpriteFrame will be applied on this 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.
- * @example
- * var spriteFrame = cc.SpriteFrameCache.getInstance().getSpriteFrame("grossini_dance_01.png");
- * var sprite = new cc.Sprite();
- * sprite.initWithSpriteFrame(spriteFrame);
- */
- initWithSpriteFrame:function (spriteFrame) {
- cc.Assert(spriteFrame != null, "");
- if(!spriteFrame.textureLoaded()){
- //add event listener
- this._textureLoaded = false;
- spriteFrame.addLoadedEventListener(this._spriteFrameLoadedCallback, this);
- }
- var ret = this.initWithTexture(spriteFrame.getTexture(), spriteFrame.getRect());
- this.setDisplayFrame(spriteFrame);
-
- return ret;
- },
-
- _spriteFrameLoadedCallback:function(spriteFrame){
- this.setNodeDirty();
- this.setTextureRect(spriteFrame.getRect(), spriteFrame.isRotated(), spriteFrame.getOriginalSize());
- this._callLoadedEventCallbacks();
- },
-
- /**
- * Initializes a sprite with a sprite frame name.
- * A cc.SpriteFrame will be fetched from the cc.SpriteFrameCache by name.
- * If the cc.SpriteFrame doesn't exist it will raise an exception.
- * @param {String} spriteFrameName A key string that can fected a volid CCSpriteFrame from CCSpriteFrameCache
- * @return {Boolean} true if the sprite is initialized properly, false otherwise.
- * @example
- * var sprite = new cc.Sprite();
- * sprite.initWithSpriteFrameName("grossini_dance_01.png");
- */
- initWithSpriteFrameName:function (spriteFrameName) {
- cc.Assert(spriteFrameName != null, "");
- var frame = cc.SpriteFrameCache.getInstance().getSpriteFrame(spriteFrameName);
- return this.initWithSpriteFrame(frame);
- },
-
- /**
- * tell the sprite to use batch node render.
- * @param {cc.SpriteBatchNode} batchNode
- */
- useBatchNode:function (batchNode) {
- this._textureAtlas = batchNode.getTextureAtlas(); // weak ref
- this._batchNode = batchNode;
- },
-
- /**
- *
- * set the vertex rect.
- * It will be called internally by setTextureRect.
- * Useful if you want to create 2x images from SD images in Retina Display.
- * Do not call it manually. Use setTextureRect instead.
- * (override this method to generate "double scale" sprites)
- *
- * @param rect
- */
- setVertexRect:function (rect) {
- this._rect = rect;
- },
-
- sortAllChildren:function () {
- if (this._reorderChildDirty) {
- var j, tempItem, locChildren = this._children, tempChild;
- for (var i = 1; i < locChildren.length; i++) {
- tempItem = locChildren[i];
- j = i - 1;
- tempChild = locChildren[j];
-
- //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
- while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
- ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
- locChildren[j + 1] = tempChild;
- j = j - 1;
- tempChild = locChildren[j];
- }
- locChildren[j + 1] = tempItem;
- }
-
- if (this._batchNode) {
- this._arrayMakeObjectsPerformSelector(locChildren, cc.Node.StateCallbackType.sortAllChildren);
- }
- this._reorderChildDirty = false;
- }
- },
-
- /**
- * Reorders a child according to a new z value. (override cc.Node )
- * @param {cc.Node} child
- * @param {Number} zOrder
- * @override
- */
- reorderChild:function (child, zOrder) {
- cc.Assert(child != null, "child is null");
- cc.Assert(this._children.indexOf(child) > -1, "this child is not in children list");
-
- if (zOrder === child.getZOrder())
- return;
-
- if (this._batchNode && !this._reorderChildDirty) {
- this._setReorderChildDirtyRecursively();
- this._batchNode.reorderBatch(true);
- }
- cc.Node.prototype.reorderChild.call(this, child, zOrder);
- },
-
- /**
- * Removes a child from the sprite. (override cc.Node )
- * @param child
- * @param cleanup whether or not cleanup all running actions
- * @override
- */
- removeChild:function (child, cleanup) {
- if (this._batchNode)
- this._batchNode.removeSpriteFromAtlas(child);
- cc.Node.prototype.removeChild.call(this, child, cleanup);
- },
-
- /**
- * Removes all children from the container (override cc.Node )
- * @param cleanup whether or not cleanup all running actions
- * @override
- */
- removeAllChildren:function (cleanup) {
- var locChildren = this._children, locBatchNode = this._batchNode;
- if (locBatchNode && locChildren != null) {
- for (var i = 0, len = locChildren.length; i < len; i++)
- locBatchNode.removeSpriteFromAtlas(locChildren[i]);
- }
-
- cc.Node.prototype.removeAllChildren.call(this, cleanup);
- this._hasChildren = false;
- },
-
- //
- // cc.Node property overloads
- //
-
- /**
- * set Recursively is or isn't Dirty
- * used only when parent is CCSpriteBatchNode
- * @param {Boolean} value
- */
- setDirtyRecursively:function (value) {
- this._recursiveDirty = value;
- this.setDirty(value);
- // recursively set dirty
- var locChildren = this._children;
- if (locChildren != null) {
- for (var i = 0; i < locChildren.length; i++) {
- if (locChildren[i] instanceof cc.Sprite)
- locChildren[i].setDirtyRecursively(true);
- }
- }
- },
-
- /**
- * HACK: optimization
- */
- SET_DIRTY_RECURSIVELY:function () {
- if (this._batchNode && !this._recursiveDirty) {
- this._recursiveDirty = true;
- this._dirty = true;
- if (this._hasChildren)
- this.setDirtyRecursively(true);
- }
- },
-
- /**
- * position setter (override cc.Node )
- * @param {cc.Point} pos
- * @override
- */
- setPosition:function (pos) {
- if (arguments.length >= 2)
- cc.Node.prototype.setPosition.call(this, pos, arguments[1]);
- else
- cc.Node.prototype.setPosition.call(this, pos);
- this.SET_DIRTY_RECURSIVELY();
- },
-
- /**
- * Rotation setter (override cc.Node )
- * @param {Number} rotation
- * @override
- */
- setRotation:function (rotation) {
- cc.Node.prototype.setRotation.call(this, rotation);
- this.SET_DIRTY_RECURSIVELY();
- },
-
- setRotationX:function (rotationX) {
- cc.Node.prototype.setRotationX.call(this, rotationX);
- this.SET_DIRTY_RECURSIVELY();
- },
-
- setRotationY:function (rotationY) {
- cc.Node.prototype.setRotationY.call(this, rotationY);
- this.SET_DIRTY_RECURSIVELY();
- },
-
- /**
- * SkewX setter (override cc.Node )
- * @param {Number} sx SkewX value
- * @override
- */
- setSkewX:function (sx) {
- cc.Node.prototype.setSkewX.call(this, sx);
- this.SET_DIRTY_RECURSIVELY();
- },
-
- /**
- * SkewY setter (override cc.Node )
- * @param {Number} sy SkewY value
- * @override
- */
- setSkewY:function (sy) {
- cc.Node.prototype.setSkewY.call(this, sy);
- this.SET_DIRTY_RECURSIVELY();
- },
-
- /**
- * ScaleX setter (override cc.Node )
- * @param {Number} scaleX
- * @override
- */
- setScaleX:function (scaleX) {
- cc.Node.prototype.setScaleX.call(this, scaleX);
- this.SET_DIRTY_RECURSIVELY();
- },
-
- /**
- * ScaleY setter (override cc.Node )
- * @param {Number} scaleY
- * @override
- */
- setScaleY:function (scaleY) {
- cc.Node.prototype.setScaleY.call(this, scaleY);
- this.SET_DIRTY_RECURSIVELY();
- },
-
- /**
- *
The scale factor of the node. 1.0 is the default scale factor.
- * It modifies the X and Y scale at the same time. (override cc.Node )
- * Returns the flag which indicates whether the sprite is flipped horizontally or not.
- *
- * It only flips the texture of the sprite, and not the texture of the sprite'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:
- * sprite->setScaleX(sprite->getScaleX() * -1);
- * @return {Boolean} true if the sprite is flipped horizaontally, false otherwise.
- */
- isFlippedX:function () {
- return this._flipX;
- },
-
- /**
- *
- * Return the flag which indicates whether the sprite is flipped vertically or not.
- *
- * It only flips the texture of the sprite, and not the texture of the sprite'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:
- * sprite->setScaleY(sprite->getScaleY() * -1);
- * @return {Boolean} true if the sprite is flipped vertically, flase otherwise.
- */
- isFlippedY:function () {
- return this._flipY;
- },
-
- //
- // RGBA protocol
- //
-
- // RGBAProtocol
- /**
- * opacity: conforms to CCRGBAProtocol protocol
- * @param {Boolean} modify
- */
- setOpacityModifyRGB:function (modify) {
- if (this._opacityModifyRGB !== modify) {
- this._opacityModifyRGB = modify;
- this.updateColor();
- }
- },
-
- /**
- * return IsOpacityModifyRGB value
- * @return {Boolean}
- */
- isOpacityModifyRGB:function () {
- return this._opacityModifyRGB;
- },
-
- updateDisplayedOpacity:function (parentOpacity) {
- cc.NodeRGBA.prototype.updateDisplayedOpacity.call(this, parentOpacity);
- this.updateColor();
- },
-
- // Animation
-
- /**
- * changes the display frame with animation name and index.
- * The animation name will be get from the CCAnimationCache
- * @param animationName
- * @param frameIndex
- */
- setDisplayFrameWithAnimationName:function (animationName, frameIndex) {
- cc.Assert(animationName, "cc.Sprite#setDisplayFrameWithAnimationName. animationName must not be null");
- var cache = cc.AnimationCache.getInstance().getAnimation(animationName);
- cc.Assert(cache, "cc.Sprite#setDisplayFrameWithAnimationName: Frame not found");
- var animFrame = cache.getFrames()[frameIndex];
- cc.Assert(animFrame, "cc.Sprite#setDisplayFrame. Invalid frame");
- this.setDisplayFrame(animFrame.getSpriteFrame());
- },
-
- /**
- * 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 () {
- return this._batchNode;
- },
-
- _setReorderChildDirtyRecursively:function () {
- //only set parents flag the first time
- if (!this._reorderChildDirty) {
- this._reorderChildDirty = true;
- var pNode = this._parent;
- while (pNode && pNode != this._batchNode) {
- pNode._setReorderChildDirtyRecursively();
- pNode = pNode.getParent();
- }
- }
- },
-
- // CCTextureProtocol
- getTexture:function () {
- return this._texture;
- },
- /// ---- common properties end ----
-
- _quad:null, // vertex coords, texture coords and color info
- _quadWebBuffer:null,
- _quadDirty:false,
-
- /**
- * Constructor
- * @param {String|cc.SpriteFrame|cc.SpriteBatchNode|HTMLImageElement|cc.Texture2D} fileName sprite construct parameter
- */
- ctor:function (fileName) {
- cc.NodeRGBA.prototype.ctor.call(this);
- this._shouldBeHidden = false;
- this._offsetPosition = cc.p(0, 0);
- this._unflippedOffsetPositionFromCenter = cc.p(0, 0);
- this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST};
-
- this._quad = new cc.V3F_C4B_T2F_Quad();
- this._quadWebBuffer = cc.renderContext.createBuffer();
- this._quadDirty = true;
- this._textureLoaded = true;
- this._loadedEventListeners = [];
-
- if (fileName) {
- if (typeof(fileName) == "string") {
- var frame = cc.SpriteFrameCache.getInstance().getSpriteFrame(fileName);
- this.initWithSpriteFrame(frame);
- } else if (typeof(fileName) == "object") {
- if (fileName instanceof cc.SpriteFrame) {
- this.initWithSpriteFrame(fileName);
- } else if ((fileName instanceof HTMLImageElement) || (fileName instanceof HTMLCanvasElement)) {
- var texture2d = new cc.Texture2D();
- texture2d.initWithElement(fileName);
- texture2d.handleLoadedTexture();
- this.initWithTexture(texture2d);
- } else if (fileName instanceof cc.Texture2D) {
- this.initWithTexture(fileName);
- }
- }
- }
- },
-
- /**
- * Returns the quad (tex coords, vertex coords and color) information.
- * @return {cc.V3F_C4B_T2F_Quad}
- */
- getQuad:function () {
- return this._quad;
- },
-
- /**
- * conforms to cc.TextureProtocol protocol
- * @param {Number|cc.BlendFunc} src
- * @param {Number} dst
- */
- setBlendFunc:function (src, dst) {
- if (arguments.length == 1)
- this._blendFunc = src;
- else
- this._blendFunc = {src:src, dst:dst};
- },
-
- /**
- * Initializes an empty sprite with nothing init.
- * @return {Boolean}
- */
- init:function () {
- if (arguments.length > 0)
- return this.initWithFile(arguments[0], arguments[1]);
-
- cc.NodeRGBA.prototype.init.call(this);
- this._dirty = this._recursiveDirty = false;
- this._opacityModifyRGB = true;
-
- this._blendFunc.src = cc.BLEND_SRC;
- this._blendFunc.dst = cc.BLEND_DST;
-
- // update texture (calls _updateBlendFunc)
- this.setTexture(null);
- this._textureLoaded = true;
- this._flipX = this._flipY = false;
-
- // default transform anchor: center
- this.setAnchorPoint(cc.p(0.5, 0.5));
-
- // zwoptex default values
- this._offsetPosition = cc.PointZero();
- this._hasChildren = false;
-
- // Atlas: Color
- var tempColor = {r:255, g:255, b:255, a:255};
- this._quad.bl.colors = tempColor;
- this._quad.br.colors = tempColor;
- this._quad.tl.colors = tempColor;
- this._quad.tr.colors = tempColor;
- this._quadDirty = true;
-
- // updated in "useSelfRender"
- // Atlas: TexCoords
- this.setTextureRect(cc.RectZero(), false, cc.SizeZero());
- return true;
- },
- /**
- *
- * Initializes a sprite with an image filename.
- *
- * This method will find pszFilename from local file system, load its content to CCTexture2D,
- * then use CCTexture2D to create a sprite.
- * After initialization, the rect used will be the size of the image. The offset will be (0,0).
- *
- * @param {String} filename The path to an image file in local file system
- * @param {cc.Rect} rect The rectangle assigned the content area from texture.
- * @return {Boolean} true if the sprite is initialized properly, false otherwise.
- * @example
- * var mySprite = new cc.Sprite();
- * mySprite.initWithFile("HelloHTML5World.png",cc.rect(0,0,480,320));
- */
- initWithFile:function (filename, rect) {
- cc.Assert(filename != null, "Sprite#initWithFile():Invalid filename for sprite");
- var texture = cc.TextureCache.getInstance().textureForKey(filename);
- if (!texture) {
- texture = cc.TextureCache.getInstance().addImage(filename);
- return this.initWithTexture(texture, rect);
- } else {
- if (!rect) {
- var size = texture.getContentSize();
- rect = cc.rect(0, 0, size.width, size.height);
- }
- return this.initWithTexture(texture, rect);
- }
- },
-
- /**
- * Initializes a sprite with a texture.
- * After initialization, the rect used will be the size of the texture, and the offset will be (0,0).
- * @param {cc.Texture2D|HTMLImageElement|HTMLCanvasElement} texture A pointer to an existing CCTexture2D object. You can use a CCTexture2D object for many sprites.
- * @param {cc.Rect} rect Only the contents inside rect of this texture will be applied for this sprite.
- * @param {Boolean} rotated Whether or not the texture rectangle is rotated.
- * @return {Boolean} true if the sprite is initialized properly, false otherwise.
- * @example
- * var img =cc.TextureCache.getInstance().addImage("HelloHTML5World.png");
- * var mySprite = new cc.Sprite();
- * mySprite.initWithTexture(img,cc.rect(0,0,480,320));
- */
- initWithTexture:function (texture, rect, rotated) {
- var argnum = arguments.length;
- if (argnum == 0)
- throw "Sprite.initWithTexture(): Argument must be non-nil ";
-
- rotated = rotated || false;
-
- if (!cc.NodeRGBA.prototype.init.call(this))
- return false;
-
- this._batchNode = null;
- this._recursiveDirty = false;
- this._dirty = false;
- this._opacityModifyRGB = true;
-
- this._blendFunc.src = cc.BLEND_SRC;
- this._blendFunc.dst = cc.BLEND_DST;
-
- this._flipX = this._flipY = false;
-
- // default transform anchor: center
- this.setAnchorPoint(cc.p(0.5, 0.5));
-
- // zwoptex default values
- this._offsetPosition = cc.p(0, 0);
- this._hasChildren = false;
-
- // Atlas: Color
- var tmpColor = new cc.Color4B(255, 255, 255, 255);
- this._quad.bl.colors = tmpColor;
- this._quad.br.colors = tmpColor;
- this._quad.tl.colors = tmpColor;
- this._quad.tr.colors = tmpColor;
-
- var locTextureLoaded = texture.isLoaded();
- this._textureLoaded = locTextureLoaded;
-
- if(!locTextureLoaded){
- this._rectRotated = rotated || false;
- this._rect = rect;
- texture.addLoadedEventListener(this._textureLoadedCallback, this);
- return true;
- }
-
- if (!rect) {
- rect = cc.rect(0, 0, 0, 0);
- rect.size = texture.getContentSize();
- }
- this.setTexture(texture);
- this.setTextureRect(rect, rotated, rect.size);
-
- // by default use "Self Render".
- // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render"
- this.setBatchNode(null);
- this._quadDirty = true;
- return true;
- },
-
- _textureLoadedCallback:function(sender){
- this._textureLoaded = true;
- var locRect = this._rect;
- if (!locRect) {
- locRect = cc.rect(0, 0, 0, 0);
- locRect.size = sender.getContentSize();
- } else if(cc._rectEqualToZero(locRect)){
- locRect.size = sender.getContentSize();
- }
-
- this.setTexture(sender);
- this.setTextureRect(locRect, this._rectRotated, locRect.size);
-
- // by default use "Self Render".
- // if the sprite is added to a batchnode, then it will automatically switch to "batchnode Render"
- this.setBatchNode(null);
- this._quadDirty = true;
- },
- /**
- * updates the texture rect of the CCSprite in points.
- * @param {cc.Rect} rect a rect of texture
- * @param {Boolean} rotated
- * @param {cc.Size} untrimmedSize
- */
- setTextureRect:function (rect, rotated, untrimmedSize) {
- this._rectRotated = rotated || false;
- untrimmedSize = untrimmedSize || rect.size;
-
- this.setContentSize(untrimmedSize);
- this.setVertexRect(rect);
- this._setTextureCoords(rect);
-
- var relativeOffset = this._unflippedOffsetPositionFromCenter;
- if (this._flipX)
- relativeOffset.x = -relativeOffset.x;
- if (this._flipY)
- relativeOffset.y = -relativeOffset.y;
-
- this._offsetPosition.x = relativeOffset.x + (this._contentSize.width - this._rect.width) / 2;
- this._offsetPosition.y = relativeOffset.y + (this._contentSize.height - this._rect.height) / 2;
-
- // rendering using batch node
- if (this._batchNode) {
- // update dirty_, don't update recursiveDirty_
- //this.setDirty(true);
- this._dirty = true;
- } else {
- // self rendering
- // Atlas: Vertex
- var x1 = 0 + this._offsetPosition.x;
- var y1 = 0 + this._offsetPosition.y;
- var x2 = x1 + this._rect.width;
- var y2 = y1 + this._rect.height;
-
- // Don't update Z.
- this._quad.bl.vertices = {x:x1, y:y1, z:0};
- this._quad.br.vertices = {x:x2, y:y1, z:0};
- this._quad.tl.vertices = {x:x1, y:y2, z:0};
- this._quad.tr.vertices = {x:x2, y:y2, z:0};
-
- this._quadDirty = true;
- }
- },
-
- // BatchNode methods
- /**
- * updates the quad according the the rotation, position, scale values.
- */
- updateTransform:function () {
- //cc.Assert(this._batchNode, "updateTransform is only valid when cc.Sprite is being rendered using an cc.SpriteBatchNode");
-
- // recaculate matrix only if it is dirty
- if (this.isDirty()) {
- // If it is not visible, or one of its ancestors is not visible, then do nothing:
- if (!this._visible || ( this._parent && this._parent != this._batchNode && this._parent._shouldBeHidden)) {
- this._quad.br.vertices = {x:0, y:0, z:0};
- this._quad.tl.vertices = {x:0, y:0, z:0};
- this._quad.tr.vertices = {x:0, y:0, z:0};
- this._quad.bl.vertices = {x:0, y:0, z:0};
- this._shouldBeHidden = true;
- } else {
- this._shouldBeHidden = false;
-
- if (!this._parent || this._parent == this._batchNode) {
- this._transformToBatch = this.nodeToParentTransform();
- } else {
- //cc.Assert(this._parent instanceof cc.Sprite, "Logic error in CCSprite. Parent must be a CCSprite");
- this._transformToBatch = cc.AffineTransformConcat(this.nodeToParentTransform(), this._parent._transformToBatch);
- }
//
// calculate the Quad based on the Affine Matrix
//
+ var locTransformToBatch = this._transformToBatch;
var size = this._rect.size;
var x1 = this._offsetPosition.x;
var y1 = this._offsetPosition.y;
var x2 = x1 + size.width;
var y2 = y1 + size.height;
- var x = this._transformToBatch.tx;
- var y = this._transformToBatch.ty;
+ var x = locTransformToBatch.tx;
+ var y = locTransformToBatch.ty;
- var cr = this._transformToBatch.a;
- var sr = this._transformToBatch.b;
- var cr2 = this._transformToBatch.d;
- var sr2 = -this._transformToBatch.c;
+ var cr = locTransformToBatch.a;
+ var sr = locTransformToBatch.b;
+ var cr2 = locTransformToBatch.d;
+ var sr2 = -locTransformToBatch.c;
var ax = x1 * cr - y1 * sr2 + x;
var ay = x1 * sr + y1 * cr2 + y;
@@ -2293,13 +1403,13 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
var dx = x1 * cr - y2 * sr2 + x;
var dy = x1 * sr + y2 * cr2 + y;
- this._quad.bl.vertices = {x:cc.RENDER_IN_SUBPIXEL(ax), y:cc.RENDER_IN_SUBPIXEL(ay), z:this._vertexZ};
- this._quad.br.vertices = {x:cc.RENDER_IN_SUBPIXEL(bx), y:cc.RENDER_IN_SUBPIXEL(by), z:this._vertexZ};
- this._quad.tl.vertices = {x:cc.RENDER_IN_SUBPIXEL(dx), y:cc.RENDER_IN_SUBPIXEL(dy), z:this._vertexZ};
- this._quad.tr.vertices = {x:cc.RENDER_IN_SUBPIXEL(cx), y:cc.RENDER_IN_SUBPIXEL(cy), z:this._vertexZ};
+ var locVertexZ = this._vertexZ;
+ locQuad.bl.vertices = {x: cc.RENDER_IN_SUBPIXEL(ax), y: cc.RENDER_IN_SUBPIXEL(ay), z: locVertexZ};
+ locQuad.br.vertices = {x: cc.RENDER_IN_SUBPIXEL(bx), y: cc.RENDER_IN_SUBPIXEL(by), z: locVertexZ};
+ locQuad.tl.vertices = {x: cc.RENDER_IN_SUBPIXEL(dx), y: cc.RENDER_IN_SUBPIXEL(dy), z: locVertexZ};
+ locQuad.tr.vertices = {x: cc.RENDER_IN_SUBPIXEL(cx), y: cc.RENDER_IN_SUBPIXEL(cy), z: locVertexZ};
}
- if (cc.renderContextType === cc.WEBGL)
- this._textureAtlas.updateQuad(this._quad, this._atlasIndex);
+ this._textureAtlas.updateQuad(locQuad, this._atlasIndex);
this._recursiveDirty = false;
this.setDirty(false);
}
@@ -2320,6 +1430,34 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
}
},
+ _updateTransformForCanvas: function () {
+ //cc.Assert(this._batchNode, "updateTransform is only valid when cc.Sprite is being rendered using an cc.SpriteBatchNode");
+
+ // recaculate matrix only if it is dirty
+ if (this._dirty) {
+ // If it is not visible, or one of its ancestors is not visible, then do nothing:
+ var locParent = this._parent;
+ if (!this._visible || ( locParent && locParent != this._batchNode && locParent._shouldBeHidden)) {
+ this._shouldBeHidden = true;
+ } else {
+ this._shouldBeHidden = false;
+
+ if (!locParent || locParent == this._batchNode) {
+ this._transformToBatch = this.nodeToParentTransform();
+ } else {
+ //cc.Assert(this._parent instanceof cc.Sprite, "Logic error in CCSprite. Parent must be a CCSprite");
+ this._transformToBatch = cc.AffineTransformConcat(this.nodeToParentTransform(), locParent._transformToBatch);
+ }
+ }
+ this._recursiveDirty = false;
+ this._dirty = false;
+ }
+
+ // recursively iterate over children
+ if (this._hasChildren)
+ this._arrayMakeObjectsPerformSelector(this._children, cc.Node.StateCallbackType.updateTransform);
+ },
+
/**
* Add child to sprite (override cc.Node )
* @param {cc.Sprite} child
@@ -2327,7 +1465,9 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
* @param {String} tag child's tag
* @override
*/
- addChild:function (child, zOrder, tag) {
+ addChild: null,
+
+ _addChildForWebGL:function (child, zOrder, tag) {
cc.Assert(child != null, "Argument must be non-NULL");
if (zOrder == null)
zOrder = child._zOrder;
@@ -2348,26 +1488,41 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
cc.Node.prototype.addChild.call(this, child, zOrder, tag);
this._hasChildren = true;
},
+
+ _addChildForCanvas: function (child, zOrder, tag) {
+ cc.Assert(child != null, "Argument must be non-NULL");
+ if (zOrder == null)
+ zOrder = child._zOrder;
+ if (tag == null)
+ tag = child._tag;
+
+ //cc.Node already sets isReorderChildDirty_ so this needs to be after batchNode check
+ cc.Node.prototype.addChild.call(this, child, zOrder, tag);
+ this._hasChildren = true;
+ },
+
/**
* Update sprite's color
*/
updateColor:function () {
- var color4 = {r:this._displayedColor.r, g:this._displayedColor.g, b:this._displayedColor.b, a:this._displayedOpacity};
+ var locDisplayedColor = this._displayedColor, locDisplayedOpacity = this._displayedOpacity;
+ var color4 = {r: locDisplayedColor.r, g: locDisplayedColor.g, b: locDisplayedColor.b, a: locDisplayedOpacity};
// special opacity for premultiplied textures
if (this._opacityModifyRGB) {
- color4.r *= this._displayedOpacity / 255.0;
- color4.g *= this._displayedOpacity / 255.0;
- color4.b *= this._displayedOpacity / 255.0;
+ color4.r *= locDisplayedOpacity / 255.0;
+ color4.g *= locDisplayedOpacity / 255.0;
+ color4.b *= locDisplayedOpacity / 255.0;
}
- this._quad.bl.colors = color4;
- this._quad.br.colors = color4;
- this._quad.tl.colors = color4;
- this._quad.tr.colors = color4;
+ var locQuad = this._quad;
+ locQuad.bl.colors = color4;
+ locQuad.br.colors = color4;
+ locQuad.tl.colors = color4;
+ locQuad.tr.colors = color4;
// renders using Sprite Manager
if (this._batchNode) {
if (this._atlasIndex != cc.SPRITE_INDEX_NOT_INITIALIZED) {
- this._textureAtlas.updateQuad(this._quad, this._atlasIndex)
+ this._textureAtlas.updateQuad(locQuad, this._atlasIndex)
} else {
// no need to set it recursively
// update dirty_, don't update recursiveDirty_
@@ -2384,31 +1539,60 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
* opacity setter
* @param {Number} opacity
*/
- setOpacity:function (opacity) {
+ setOpacity:null,
+
+ _setOpacityForWebGL: function (opacity) {
cc.NodeRGBA.prototype.setOpacity.call(this, opacity);
this.updateColor();
},
+ _setOpacityForCanvas: function (opacity) {
+ cc.NodeRGBA.prototype.setOpacity.call(this, opacity);
+ this.setNodeDirty();
+ },
+
/**
* color setter
* @param {cc.Color3B} color3
*/
- setColor:function (color3) {
+ setColor: null,
+
+ _setColorForWebGL: function (color3) {
cc.NodeRGBA.prototype.setColor.call(this, color3);
this.updateColor();
},
- updateDisplayedColor:function (parentColor) {
+ _setColorForCanvas: function (color3) {
+ var curColor = this.getColor();
+ if ((curColor.r === color3.r) && (curColor.g === color3.g) && (curColor.b === color3.b))
+ return;
+
+ cc.NodeRGBA.prototype.setColor.call(this, color3);
+ this._changeTextureColor();
+ this.setNodeDirty();
+ },
+
+ updateDisplayedColor: null,
+
+ _updateDisplayedColorForWebGL: function (parentColor) {
cc.NodeRGBA.prototype.updateDisplayedColor.call(this, parentColor);
this.updateColor();
},
+ _updateDisplayedColorForCanvas: function (parentColor) {
+ cc.NodeRGBA.prototype.updateDisplayedColor.call(this, parentColor);
+ this._changeTextureColor();
+ this.setNodeDirty();
+ },
+
// Frames
/**
* Sets a new display frame to the cc.Sprite.
* @param {cc.SpriteFrame} newFrame
*/
- setDisplayFrame:function (newFrame) {
+ setDisplayFrame: null,
+
+ _setDisplayFrameForWebGL: function (newFrame) {
this.setNodeDirty();
var frameOffset = newFrame.getOffset();
this._unflippedOffsetPositionFromCenter.x = frameOffset.x;
@@ -2416,16 +1600,16 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
var pNewTexture = newFrame.getTexture();
var locTextureLoaded = newFrame.textureLoaded();
- if(!locTextureLoaded){
+ if (!locTextureLoaded) {
this._textureLoaded = false;
- newFrame.addLoadedEventListener(function(sender){
+ newFrame.addLoadedEventListener(function (sender) {
this._textureLoaded = true;
var locNewTexture = sender.getTexture();
if (locNewTexture != this._texture)
this.setTexture(locNewTexture);
this.setTextureRect(sender.getRect(), sender._rectRotated, sender.getOriginalSize());
this._callLoadedEventCallbacks();
- },this);
+ }, this);
}
// update texture before updating texture rect
if (pNewTexture != this._texture)
@@ -2436,21 +1620,70 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
this.setTextureRect(newFrame.getRect(), this._rectRotated, newFrame.getOriginalSize());
},
+ _setDisplayFrameForCanvas: function (newFrame) {
+ this.setNodeDirty();
+
+ var frameOffset = newFrame.getOffset();
+ this._unflippedOffsetPositionFromCenter.x = frameOffset.x;
+ this._unflippedOffsetPositionFromCenter.y = frameOffset.y;
+
+ // update rect
+ this._rectRotated = newFrame.isRotated();
+
+ var pNewTexture = newFrame.getTexture();
+ var locTextureLoaded = newFrame.textureLoaded();
+ if (!locTextureLoaded) {
+ this._textureLoaded = false;
+ newFrame.addLoadedEventListener(function (sender) {
+ this._textureLoaded = true;
+ var locNewTexture = sender.getTexture();
+ if (locNewTexture != this._texture)
+ this.setTexture(locNewTexture);
+ this.setTextureRect(sender.getRect(), this._rectRotated, sender.getOriginalSize());
+ this._callLoadedEventCallbacks();
+ }, this);
+ }
+ // update texture before updating texture rect
+ if (pNewTexture != this._texture)
+ this.setTexture(pNewTexture);
+
+ if (this._rectRotated)
+ this._originalTexture = pNewTexture;
+
+ this.setTextureRect(newFrame.getRect(), this._rectRotated, newFrame.getOriginalSize());
+ this._colorized = false;
+ if (locTextureLoaded) {
+ var curColor = this.getColor();
+ if (curColor.r !== 255 || curColor.g !== 255 || curColor.b !== 255)
+ this._changeTextureColor();
+ }
+ },
+
/**
* Returns whether or not a cc.SpriteFrame is being displayed
* @param {cc.SpriteFrame} frame
* @return {Boolean}
*/
- isFrameDisplayed:function (frame) {
+ isFrameDisplayed: null,
+
+ _isFrameDisplayedForWebGL: function (frame) {
return (cc.rectEqualToRect(frame.getRect(), this._rect) && frame.getTexture().getName() == this._texture.getName()
&& cc.pointEqualToPoint(frame.getOffset(), this._unflippedOffsetPositionFromCenter));
},
+ _isFrameDisplayedForCanvas: function (frame) {
+ if (frame.getTexture() != this._texture)
+ return false;
+ return cc.rectEqualToRect(frame.getRect(), this._rect);
+ },
+
/**
* Returns the current displayed frame.
* @return {cc.SpriteFrame}
*/
- displayFrame:function () {
+ displayFrame: null,
+
+ _displayFrameForWebGL: function () {
return cc.SpriteFrame.createWithTexture(this._texture,
cc.RECT_POINTS_TO_PIXELS(this._rect),
this._rectRotated,
@@ -2458,6 +1691,14 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
cc.SIZE_POINTS_TO_PIXELS(this._contentSize));
},
+ _displayFrameForCanvas: function () {
+ return cc.SpriteFrame._frameWithTextureForCanvas(this._texture,
+ cc.RECT_POINTS_TO_PIXELS(this._rect),
+ this._rectRotated,
+ cc.POINT_POINTS_TO_PIXELS(this._unflippedOffsetPositionFromCenter),
+ cc.SIZE_POINTS_TO_PIXELS(this._contentSize));
+ },
+
/**
* Sets the batch node to sprite
* @param {cc.SpriteBatchNode|null} spriteBatchNode
@@ -2467,7 +1708,9 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
* batch.addChild(sprite);
* layer.addChild(batch);
*/
- setBatchNode:function (spriteBatchNode) {
+ setBatchNode:null,
+
+ _setBatchNodeForWebGL:function (spriteBatchNode) {
this._batchNode = spriteBatchNode; // weak reference
// self render
@@ -2481,10 +1724,11 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
var y1 = this._offsetPosition.y;
var x2 = x1 + this._rect.width;
var y2 = y1 + this._rect.height;
- this._quad.bl.vertices = {x:x1, y:y1, z:0};
- this._quad.br.vertices = {x:x2, y:y1, z:0};
- this._quad.tl.vertices = {x:x1, y:y2, z:0};
- this._quad.tr.vertices = {x:x2, y:y2, z:0};
+ var locQuad = this._quad;
+ locQuad.bl.vertices = {x:x1, y:y1, z:0};
+ locQuad.br.vertices = {x:x2, y:y1, z:0};
+ locQuad.tl.vertices = {x:x1, y:y2, z:0};
+ locQuad.tr.vertices = {x:x2, y:y2, z:0};
this._quadDirty = true;
} else {
@@ -2494,12 +1738,30 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
}
},
+ _setBatchNodeForCanvas:function (spriteBatchNode) {
+ this._batchNode = spriteBatchNode; // weak reference
+
+ // self render
+ if (!this._batchNode) {
+ this._atlasIndex = cc.SPRITE_INDEX_NOT_INITIALIZED;
+ this.setTextureAtlas(null);
+ this._recursiveDirty = false;
+ this.setDirty(false);
+ } else {
+ // using batch
+ this._transformToBatch = cc.AffineTransformIdentity();
+ this.setTextureAtlas(this._batchNode.getTextureAtlas()); // weak ref
+ }
+ },
+
// CCTextureProtocol
/**
* Texture of sprite setter
* @param {HTMLImageElement|HTMLCanvasElement|cc.Texture2D} texture
*/
- setTexture:function (texture) {
+ setTexture: null,
+
+ _setTextureForWebGL: function (texture) {
// CCSprite: setTexture doesn't work when the sprite is rendered using a CCSpriteSheet
cc.Assert(!texture || texture instanceof cc.Texture2D, "setTexture expects a CCTexture2D. Invalid argument");
@@ -2517,6 +1779,17 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
}
},
+ _setTextureForCanvas: function (texture) {
+ // CCSprite: setTexture doesn't work when the sprite is rendered using a CCSpriteSheet
+ cc.Assert(!texture || texture instanceof cc.Texture2D, "setTexture expects a CCTexture2D. Invalid argument");
+ if (this._texture != texture) {
+ if (texture && texture.getHtmlElementObj() instanceof HTMLImageElement) {
+ this._originalTexture = texture;
+ }
+ this._texture = texture;
+ }
+ },
+
// Texture protocol
_updateBlendFunc:function () {
cc.Assert(!this._batchNode, "cc.Sprite: _updateBlendFunc doesn't work when the sprite is rendered using a cc.CCSpriteBatchNode");
@@ -2532,6 +1805,30 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
}
},
+ _changeTextureColor: function () {
+ var locElement, locTexture = this._texture, locRect = this.getTextureRect();
+ if (locTexture && locRect.width > 0) {
+ locElement = locTexture.getHtmlElementObj();
+ if (!locElement)
+ return;
+
+ var cacheTextureForColor = cc.TextureCache.getInstance().getTextureColors(this._originalTexture.getHtmlElementObj());
+ if (cacheTextureForColor) {
+ this._colorized = true;
+ //generate color texture cache
+ if (locElement instanceof HTMLCanvasElement && !this._rectRotated && !this._newTextureWhenChangeColor)
+ cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, locRect, locElement);
+ else {
+ locElement = cc.generateTintImage(locElement, cacheTextureForColor, this._displayedColor, locRect);
+ locTexture = new cc.Texture2D();
+ locTexture.initWithElement(locElement);
+ locTexture.handleLoadedTexture();
+ this.setTexture(locTexture);
+ }
+ }
+ }
+ },
+
_setTextureCoords:function (rect) {
rect = cc.RECT_POINTS_TO_PIXELS(rect);
@@ -2542,7 +1839,7 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
var atlasWidth = tex.getPixelsWide();
var atlasHeight = tex.getPixelsHigh();
- var left, right, top, bottom, tempSwap;
+ var left, right, top, bottom, tempSwap, locQuad = this._quad;
if (this._rectRotated) {
if (cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL) {
left = (2 * rect.x + 1) / (2 * atlasWidth);
@@ -2568,14 +1865,14 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
right = tempSwap;
}
- this._quad.bl.texCoords.u = left;
- this._quad.bl.texCoords.v = top;
- this._quad.br.texCoords.u = left;
- this._quad.br.texCoords.v = bottom;
- this._quad.tl.texCoords.u = right;
- this._quad.tl.texCoords.v = top;
- this._quad.tr.texCoords.u = right;
- this._quad.tr.texCoords.v = bottom;
+ locQuad.bl.texCoords.u = left;
+ locQuad.bl.texCoords.v = top;
+ locQuad.br.texCoords.u = left;
+ locQuad.br.texCoords.v = bottom;
+ locQuad.tl.texCoords.u = right;
+ locQuad.tl.texCoords.v = top;
+ locQuad.tr.texCoords.u = right;
+ locQuad.tr.texCoords.v = bottom;
} else {
if (cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL) {
left = (2 * rect.x + 1) / (2 * atlasWidth);
@@ -2601,22 +1898,24 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
bottom = tempSwap;
}
- this._quad.bl.texCoords.u = left;
- this._quad.bl.texCoords.v = bottom;
- this._quad.br.texCoords.u = right;
- this._quad.br.texCoords.v = bottom;
- this._quad.tl.texCoords.u = left;
- this._quad.tl.texCoords.v = top;
- this._quad.tr.texCoords.u = right;
- this._quad.tr.texCoords.v = top;
+ locQuad.bl.texCoords.u = left;
+ locQuad.bl.texCoords.v = bottom;
+ locQuad.br.texCoords.u = right;
+ locQuad.br.texCoords.v = bottom;
+ locQuad.tl.texCoords.u = left;
+ locQuad.tl.texCoords.v = top;
+ locQuad.tr.texCoords.u = right;
+ locQuad.tr.texCoords.v = top;
}
this._quadDirty = true;
},
/**
* draw sprite to canvas
*/
- draw:function () {
- if(!this._textureLoaded)
+ draw: null,
+
+ _drawForWebGL: function () {
+ if (!this._textureLoaded)
return;
var gl = cc.renderContext, locTexture = this._texture;
@@ -2667,11 +1966,12 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
if (cc.SPRITE_DEBUG_DRAW === 1) {
// draw bounding box
+ var locQuad = this._quad;
var verticesG1 = [
- cc.p(this._quad.tl.vertices.x, this._quad.tl.vertices.y),
- cc.p(this._quad.bl.vertices.x, this._quad.bl.vertices.y),
- cc.p(this._quad.br.vertices.x, this._quad.br.vertices.y),
- cc.p(this._quad.tr.vertices.x, this._quad.tr.vertices.y)
+ cc.p(locQuad.tl.vertices.x, locQuad.tl.vertices.y),
+ cc.p(locQuad.bl.vertices.x, locQuad.bl.vertices.y),
+ cc.p(locQuad.br.vertices.x, locQuad.br.vertices.y),
+ cc.p(locQuad.tr.vertices.x, locQuad.tr.vertices.y)
];
cc.drawingUtil.drawPoly(verticesG1, 4, true);
} else if (cc.SPRITE_DEBUG_DRAW === 2) {
@@ -2682,10 +1982,107 @@ cc.SpriteWebGL = cc.NodeRGBA.extend(/** @lends cc.SpriteWebGL# */{
cc.p(offsetPixG2.x + drawSizeG2.width, offsetPixG2.y + drawSizeG2.height), cc.p(offsetPixG2.x, offsetPixG2.y + drawSizeG2.height)];
cc.drawingUtil.drawPoly(verticesG2, 4, true);
} // CC_SPRITE_DEBUG_DRAW
+ },
+
+ _drawForCanvas: function (ctx) {
+ if (!this._textureLoaded)
+ return;
+
+ var context = ctx || cc.renderContext;
+ if (this._isLighterMode)
+ context.globalCompositeOperation = 'lighter';
+
+ context.globalAlpha = this._displayedOpacity / 255;
+ var locRect = this._rect, locContentSize = this._contentSize, locOffsetPosition = this._offsetPosition;
+ var flipXOffset = 0 | (locOffsetPosition.x), flipYOffset = -locOffsetPosition.y - locRect.height;
+ if (this._flipX) {
+ flipXOffset = -locOffsetPosition.x - locRect.width;
+ context.scale(-1, 1);
+ }
+ if (this._flipY) {
+ flipYOffset = locOffsetPosition.y;
+ context.scale(1, -1);
+ }
+ if (this._texture && locRect.width > 0) {
+ var image = this._texture.getHtmlElementObj();
+ if (this._colorized) {
+ context.drawImage(image,
+ 0, 0, 0 | locRect.width, 0 | locRect.height,
+ flipXOffset, flipYOffset, locRect.width, locRect.height);
+ } else {
+ context.drawImage(image,
+ 0 | locRect.x, 0 | locRect.y, 0 | locRect.width, 0 | locRect.height,
+ flipXOffset, flipYOffset, locRect.width, locRect.height);
+ }
+ } else if (locContentSize.width !== 0) {
+ var curColor = this.getColor();
+ context.fillStyle = "rgba(" + curColor.r + "," + curColor.g + "," + curColor.b + ",1)";
+ context.fillRect(flipXOffset, flipYOffset, locContentSize.width, locContentSize.height);
+ }
+
+ if (cc.SPRITE_DEBUG_DRAW === 1) {
+ // draw bounding box
+ context.strokeStyle = "rgba(0,255,0,1)";
+ flipYOffset = -flipYOffset;
+ var vertices1 = [cc.p(flipXOffset, flipYOffset), cc.p(flipXOffset + locRect.width, flipYOffset), cc.p(flipXOffset + locRect.width, flipYOffset - locRect.height),
+ cc.p(flipXOffset, flipYOffset - locRect.height)];
+ cc.drawingUtil.drawPoly(vertices1, 4, true);
+ } else if (cc.SPRITE_DEBUG_DRAW === 2) {
+ // draw texture box
+ context.strokeStyle = "rgba(0,255,0,1)";
+ var drawSize = this._rect.size;
+ flipYOffset = -flipYOffset;
+ var vertices2 = [cc.p(flipXOffset, flipYOffset), cc.p(flipXOffset + drawSize.width, flipYOffset),
+ cc.p(flipXOffset + drawSize.width, flipYOffset - drawSize.height), cc.p(flipXOffset, flipYOffset - drawSize.height)];
+ cc.drawingUtil.drawPoly(vertices2, 4, true);
+ }
+ cc.g_NumberOfDraws++;
}
});
-cc.Sprite = cc.Browser.supportWebGL ? cc.SpriteWebGL : cc.SpriteCanvas;
+if(cc.Browser.supportWebGL){
+ cc.Sprite.prototype._spriteFrameLoadedCallback = cc.Sprite.prototype._spriteFrameLoadedCallbackForWebGL;
+ cc.Sprite.prototype.setOpacityModifyRGB = cc.Sprite.prototype._setOpacityModifyRGBForWebGL;
+ cc.Sprite.prototype.updateDisplayedOpacity = cc.Sprite.prototype._updateDisplayedOpacityForWebGL;
+ cc.Sprite.prototype.ctor = cc.Sprite.prototype._ctorForWebGL;
+ cc.Sprite.prototype.setBlendFunc = cc.Sprite.prototype._setBlendFuncForWebGL;
+ cc.Sprite.prototype.init = cc.Sprite.prototype._initForWebGL;
+ cc.Sprite.prototype.initWithTexture = cc.Sprite.prototype._initWithTextureForWebGL;
+ cc.Sprite.prototype._textureLoadedCallback = cc.Sprite.prototype._textureLoadedCallbackForWebGL;
+ cc.Sprite.prototype.setTextureRect = cc.Sprite.prototype._setTextureRectForWebGL;
+ cc.Sprite.prototype.updateTransform = cc.Sprite.prototype._updateTransformForWebGL;
+ cc.Sprite.prototype.addChild = cc.Sprite.prototype._addChildForWebGL;
+ cc.Sprite.prototype.setOpacity = cc.Sprite.prototype._setOpacityForWebGL;
+ cc.Sprite.prototype.setColor = cc.Sprite.prototype._setColorForWebGL;
+ cc.Sprite.prototype.updateDisplayedColor = cc.Sprite.prototype._updateDisplayedColorForWebGL;
+ cc.Sprite.prototype.setDisplayFrame = cc.Sprite.prototype._setDisplayFrameForWebGL;
+ cc.Sprite.prototype.isFrameDisplayed = cc.Sprite.prototype._isFrameDisplayedForWebGL;
+ cc.Sprite.prototype.displayFrame = cc.Sprite.prototype._displayFrameForWebGL;
+ cc.Sprite.prototype.setBatchNode = cc.Sprite.prototype._setBatchNodeForWebGL;
+ cc.Sprite.prototype.setTexture = cc.Sprite.prototype._setTextureForWebGL;
+ cc.Sprite.prototype.draw = cc.Sprite.prototype._drawForWebGL;
+}else{
+ cc.Sprite.prototype._spriteFrameLoadedCallback = cc.Sprite.prototype._spriteFrameLoadedCallbackForCanvas;
+ cc.Sprite.prototype.setOpacityModifyRGB = cc.Sprite.prototype._setOpacityModifyRGBForCanvas;
+ cc.Sprite.prototype.updateDisplayedOpacity = cc.Sprite.prototype._updateDisplayedOpacityForCanvas;
+ cc.Sprite.prototype.ctor = cc.Sprite.prototype._ctorForCanvas;
+ cc.Sprite.prototype.setBlendFunc = cc.Sprite.prototype._setBlendFuncForCanvas;
+ cc.Sprite.prototype.init = cc.Sprite.prototype._initForCanvas;
+ cc.Sprite.prototype.initWithTexture = cc.Sprite.prototype._initWithTextureForCanvas;
+ cc.Sprite.prototype._textureLoadedCallback = cc.Sprite.prototype._textureLoadedCallbackForCanvas;
+ cc.Sprite.prototype.setTextureRect = cc.Sprite.prototype._setTextureRectForCanvas;
+ cc.Sprite.prototype.updateTransform = cc.Sprite.prototype._updateTransformForCanvas;
+ cc.Sprite.prototype.addChild = cc.Sprite.prototype._addChildForCanvas;
+ cc.Sprite.prototype.setOpacity = cc.Sprite.prototype._setOpacityForCanvas;
+ cc.Sprite.prototype.setColor = cc.Sprite.prototype._setColorForCanvas;
+ cc.Sprite.prototype.updateDisplayedColor = cc.Sprite.prototype._updateDisplayedColorForCanvas;
+ cc.Sprite.prototype.setDisplayFrame = cc.Sprite.prototype._setDisplayFrameForCanvas;
+ cc.Sprite.prototype.isFrameDisplayed = cc.Sprite.prototype._isFrameDisplayedForCanvas;
+ cc.Sprite.prototype.displayFrame = cc.Sprite.prototype._displayFrameForCanvas;
+ cc.Sprite.prototype.setBatchNode = cc.Sprite.prototype._setBatchNodeForCanvas;
+ cc.Sprite.prototype.setTexture = cc.Sprite.prototype._setTextureForCanvas;
+ cc.Sprite.prototype.draw = cc.Sprite.prototype._drawForCanvas;
+}
/**
*
+ * initializes the cc.LabelAtlas with a string, a char map file(the atlas),
+ * the width and height of each element and the starting char of the atlas
+ * It accepts two groups of parameters:
+ * a) string, fntFile
+ * b) label, textureFilename, width, height, startChar
+ *
* @param {String} strText
* @param {String|cc.Texture2D} charMapFile charMapFile or fntFile or texture file
- * @param {Number} itemWidth
- * @param {Number} itemHeight
- * @param {Number} startCharMap
+ * @param {Number} [itemWidth=0]
+ * @param {Number} [itemHeight=0]
+ * @param {Number} [startCharMap=""]
* @return {Boolean} returns true on success
*/
initWithString:function (strText, charMapFile, itemWidth, itemHeight, startCharMap) {
@@ -60,8 +62,9 @@ cc.LabelAtlasCanvas = cc.AtlasNode.extend(/** @lends cc.LabelAtlasCanvas# */{
cc.Assert(parseInt(dict["version"], 10) == 1, "Unsupported version. Upgrade cocos2d version");
textureFilename = relPathStr + dict["textureFilename"];
- width = parseInt(dict["itemWidth"], 10) / cc.CONTENT_SCALE_FACTOR();
- height = parseInt(dict["itemHeight"], 10) / cc.CONTENT_SCALE_FACTOR();
+ var locScaleFactor = cc.CONTENT_SCALE_FACTOR();
+ width = parseInt(dict["itemWidth"], 10) / locScaleFactor;
+ height = parseInt(dict["itemHeight"], 10) / locScaleFactor;
startChar = String.fromCharCode(parseInt(dict["firstChar"], 10));
} else {
textureFilename = charMapFile;
@@ -102,8 +105,8 @@ cc.LabelAtlasCanvas = cc.AtlasNode.extend(/** @lends cc.LabelAtlasCanvas# */{
/**
* draw the label
*/
- draw:function () {
- cc.AtlasNode.prototype.draw.call(this);
+ draw:function (ctx) {
+ cc.AtlasNode.prototype.draw.call(this,ctx);
if (cc.LABELATLAS_DEBUG_DRAW) {
var s = this.getContentSize();
var vertices = [cc.p(0, 0), cc.p(s.width, 0),
@@ -111,21 +114,25 @@ cc.LabelAtlasCanvas = cc.AtlasNode.extend(/** @lends cc.LabelAtlasCanvas# */{
cc.drawingUtil.drawPoly(vertices, 4, true);
}
},
- // ---- common properties end ----
/**
* Atlas generation
*/
- updateAtlasValues:function () {
+ updateAtlasValues: null,
+
+ _updateAtlasValuesForCanvas: function () {
+ var locString = this._string;
+ var n = locString.length;
var texture = this.getTexture();
var locItemWidth = this._itemWidth, locItemHeight = this._itemHeight;
- for (var i = 0; i < this._string.length; i++) {
- var a = this._string.charCodeAt(i) - this._mapStartChar.charCodeAt(0);
- var row = parseInt(a % this._itemsPerRow, 10) * cc.CONTENT_SCALE_FACTOR();
- var col = parseInt(a / this._itemsPerRow, 10) * cc.CONTENT_SCALE_FACTOR();
+ var locScaleFactor = cc.CONTENT_SCALE_FACTOR();
+ for (var i = 0; i < n; i++) {
+ var a = locString.charCodeAt(i) - this._mapStartChar.charCodeAt(0);
+ var row = parseInt(a % this._itemsPerRow, 10) * locScaleFactor;
+ var col = parseInt(a / this._itemsPerRow, 10) * locScaleFactor;
var rect = cc.rect(row * locItemWidth, col * locItemHeight, locItemWidth, locItemHeight);
- var c = this._string.charCodeAt(i);
+ var c = locString.charCodeAt(i);
var fontChar = this.getChildByTag(i);
if (!fontChar) {
fontChar = new cc.Sprite();
@@ -152,151 +159,27 @@ cc.LabelAtlasCanvas = cc.AtlasNode.extend(/** @lends cc.LabelAtlasCanvas# */{
}
},
- /**
- * set the display string
- * @param {String} label
- */
- setString:function (label) {
- label = String(label);
- var len = label.length;
- this._string = label;
- this.setContentSize(cc.size(len * this._itemWidth, this._itemHeight));
- if (this._children) {
- var locChildren = this._children;
- len = locChildren.length;
- for (var i = 0; i < len; i++) {
- var node = locChildren[i];
- if (node)
- node.setVisible(false);
- }
- }
-
- this.updateAtlasValues();
- this._quadsToDraw = len;
- },
-
- setOpacity:function (opacity) {
- if (this._displayedOpacity != opacity) {
- cc.AtlasNode.prototype.setOpacity.call(this, opacity);
- var locChildren = this._children;
- for (var i = 0, len = locChildren.length; i < len; i++) {
- if (locChildren[i])
- locChildren[i].setOpacity(opacity);
- }
- }
- }
-});
-
-/**
- * using image file to print text label on the screen, might be a bit slower than cc.Label, similar to cc.LabelBMFont (WebGL version)
- * @class
- * @extends cc.AtlasNode
- */
-cc.LabelAtlasWebGL = cc.AtlasNode.extend(/** @lends cc.LabelAtlasWebGL# */{
- // ---- common properties start ----
- // string to render
- _string:null,
- // the first char in the charmap
- _mapStartChar:null,
-
- /**
- * initializes the cc.LabelAtlas with a string, a char map file(the atlas), the width and height of each element and the starting char of the atlas
- * It accepts two groups of parameters:
- * a) string, fntFile
- * b) label, textureFilename, width, height, startChar
- * @param {String} strText
- * @param {String | cc.Texture2D} charMapFile charMapFile or fntFile
- * @param {Number} itemWidth
- * @param {Number} itemHeight
- * @param {Number} startCharMap
- * @return {Boolean} returns true on success
- */
- initWithString:function (strText, charMapFile, itemWidth, itemHeight, startCharMap) {
- var label = strText + "", textureFilename, width, height, startChar;
- cc.Assert(label !== null, "Label must be non-nil");
- if (arguments.length === 2) {
- var fileUtils = cc.FileUtils.getInstance();
- var pathStr = fileUtils.fullPathForFilename(charMapFile);
- var relPathStr = pathStr.substr(0, pathStr.lastIndexOf('/')) + '/';
-
- var dict = fileUtils.dictionaryWithContentsOfFileThreadSafe(pathStr);
- cc.Assert(parseInt(dict["version"], 10) == 1, "Unsupported version. Upgrade cocos2d version");
-
- textureFilename = relPathStr + dict["textureFilename"];
- width = parseInt(dict["itemWidth"], 10) / cc.CONTENT_SCALE_FACTOR();
- height = parseInt(dict["itemHeight"], 10) / cc.CONTENT_SCALE_FACTOR();
- startChar = String.fromCharCode(parseInt(dict["firstChar"], 10));
- } else {
- textureFilename = charMapFile;
- width = itemWidth || 0;
- height = itemHeight || 0;
- startChar = startCharMap || " ";
- }
-
- var texture = null;
- if(textureFilename instanceof cc.Texture2D)
- texture = textureFilename;
- else
- texture = cc.TextureCache.getInstance().addImage(textureFilename);
-
- if (this.initWithTexture(texture, width, height, label.length)) {
- this._mapStartChar = startChar;
- this.setString(label);
- return true;
- }
- return false;
- },
-
- /**
- * @param {cc.Color3B} color3
- */
- setColor:function (color3) {
- cc.AtlasNode.prototype.setColor.call(this, color3);
- this.updateAtlasValues();
- },
- /**
- * return the text of this label
- * @return {String}
- */
- getString:function () {
- return this._string;
- },
-
- /**
- * draw the label
- */
- draw:function () {
- cc.AtlasNode.prototype.draw.call(this);
- if (cc.LABELATLAS_DEBUG_DRAW) {
- var s = this.getContentSize();
- var vertices = [cc.p(0, 0), cc.p(s.width, 0),
- cc.p(s.width, s.height), cc.p(0, s.height)];
- cc.drawingUtil.drawPoly(vertices, 4, true);
- }
- },
- // ---- common properties end ----
-
- /**
- * Atlas generation
- */
- updateAtlasValues:function () {
- var n = this._string.length;
+ _updateAtlasValuesForWebGL: function () {
+ var locString = this._string;
+ var n = locString.length;
var locTextureAtlas = this._textureAtlas;
var texture = locTextureAtlas.getTexture();
var textureWide = texture.getPixelsWide();
var textureHigh = texture.getPixelsHigh();
- var itemWidthInPixels = this._itemWidth ;
+ var itemWidthInPixels = this._itemWidth;
var itemHeightInPixels = this._itemHeight;
- if(!this._ignoreContentScaleFactor){
+ if (!this._ignoreContentScaleFactor) {
itemWidthInPixels = this._itemWidth * cc.CONTENT_SCALE_FACTOR();
itemHeightInPixels = this._itemHeight * cc.CONTENT_SCALE_FACTOR();
}
- cc.Assert( n <= locTextureAtlas.getCapacity(), "updateAtlasValues: Invalid String length");
+ cc.Assert(n <= locTextureAtlas.getCapacity(), "updateAtlasValues: Invalid String length");
var quads = locTextureAtlas.getQuads();
- var curColor = {r: this._displayedColor.r, g:this._displayedColor.g, b:this._displayedColor.b, a:this._displayedOpacity};
+ var locDisplayedColor = this._displayedColor;
+ var curColor = {r: locDisplayedColor.r, g: locDisplayedColor.g, b: locDisplayedColor.b, a: this._displayedOpacity};
+ var locItemWidth = this._itemWidth;
for (var i = 0; i < n; i++) {
- var a = this._string.charCodeAt(i) - this._mapStartChar.charCodeAt(0);
+ var a = locString.charCodeAt(i) - this._mapStartChar.charCodeAt(0);
var row = a % this._itemsPerRow;
var col = 0 | (a / this._itemsPerRow);
@@ -314,33 +197,34 @@ cc.LabelAtlasWebGL = cc.AtlasNode.extend(/** @lends cc.LabelAtlasWebGL# */{
bottom = top + itemHeightInPixels / textureHigh;
}
var quad = quads[i];
- quad.tl.texCoords.u = left;
- quad.tl.texCoords.v = top;
- quad.tr.texCoords.u = right;
- quad.tr.texCoords.v = top;
- quad.bl.texCoords.u = left;
- quad.bl.texCoords.v = bottom;
- quad.br.texCoords.u = right;
- quad.br.texCoords.v = bottom;
-
- quad.bl.vertices.x = (i * this._itemWidth);
- quad.bl.vertices.y = 0;
- quad.bl.vertices.z = 0.0;
- quad.br.vertices.x = (i * this._itemWidth + this._itemWidth);
- quad.br.vertices.y = 0;
- quad.br.vertices.z = 0.0;
- quad.tl.vertices.x = i * this._itemWidth;
- quad.tl.vertices.y = this._itemHeight;
- quad.tl.vertices.z = 0.0;
- quad.tr.vertices.x = i * this._itemWidth + this._itemWidth;
- quad.tr.vertices.y = this._itemHeight;
- quad.tr.vertices.z = 0.0;
- quad.tl.colors = curColor;
- quad.tr.colors = curColor;
- quad.bl.colors = curColor;
- quad.br.colors = curColor;
+ var locQuadTL = quad.tl, locQuadTR = quad.tr, locQuadBL = quad.bl, locQuadBR = quad.br;
+ locQuadTL.texCoords.u = left;
+ locQuadTL.texCoords.v = top;
+ locQuadTR.texCoords.u = right;
+ locQuadTR.texCoords.v = top;
+ locQuadBL.texCoords.u = left;
+ locQuadBL.texCoords.v = bottom;
+ locQuadBR.texCoords.u = right;
+ locQuadBR.texCoords.v = bottom;
+
+ locQuadBL.vertices.x = (i * locItemWidth);
+ locQuadBL.vertices.y = 0;
+ locQuadBL.vertices.z = 0.0;
+ locQuadBR.vertices.x = (i * locItemWidth + locItemWidth);
+ locQuadBR.vertices.y = 0;
+ locQuadBR.vertices.z = 0.0;
+ locQuadTL.vertices.x = i * locItemWidth;
+ locQuadTL.vertices.y = this._itemHeight;
+ locQuadTL.vertices.z = 0.0;
+ locQuadTR.vertices.x = i * locItemWidth + locItemWidth;
+ locQuadTR.vertices.y = this._itemHeight;
+ locQuadTR.vertices.z = 0.0;
+ locQuadTL.colors = curColor;
+ locQuadTR.colors = curColor;
+ locQuadBL.colors = curColor;
+ locQuadBR.colors = curColor;
}
- if (n > 0 ){
+ if (n > 0) {
locTextureAtlas.setDirty(true);
var totalQuads = locTextureAtlas.getTotalQuads();
if (n > totalQuads)
@@ -352,7 +236,28 @@ cc.LabelAtlasWebGL = cc.AtlasNode.extend(/** @lends cc.LabelAtlasWebGL# */{
* set the display string
* @param {String} label
*/
- setString:function (label) {
+ setString: null,
+
+ _setStringForCanvas: function (label) {
+ label = String(label);
+ var len = label.length;
+ this._string = label;
+ this.setContentSize(cc.size(len * this._itemWidth, this._itemHeight));
+ if (this._children) {
+ var locChildren = this._children;
+ len = locChildren.length;
+ for (var i = 0; i < len; i++) {
+ var node = locChildren[i];
+ if (node)
+ node.setVisible(false);
+ }
+ }
+
+ this.updateAtlasValues();
+ this._quadsToDraw = len;
+ },
+
+ _setStringForWebGL: function (label) {
label = String(label);
var len = label.length;
if (len > this._textureAtlas.getTotalQuads())
@@ -365,24 +270,46 @@ cc.LabelAtlasWebGL = cc.AtlasNode.extend(/** @lends cc.LabelAtlasWebGL# */{
this._quadsToDraw = len;
},
- setOpacity:function (opacity) {
+ setOpacity: null,
+
+ _setOpacityForCanvas: function (opacity) {
if (this._displayedOpacity !== opacity) {
cc.AtlasNode.prototype.setOpacity.call(this, opacity);
+ var locChildren = this._children;
+ for (var i = 0, len = locChildren.length; i < len; i++) {
+ if (locChildren[i])
+ locChildren[i].setOpacity(opacity);
+ }
}
+ },
+
+ _setOpacityForWebGL: function (opacity) {
+ if (this._opacity !== opacity)
+ cc.AtlasNode.prototype.setOpacity.call(this, opacity);
}
});
-cc.LabelAtlas = cc.Browser.supportWebGL ? cc.LabelAtlasWebGL : cc.LabelAtlasCanvas;
+if(cc.Browser.supportWebGL){
+ cc.LabelAtlas.prototype.updateAtlasValues = cc.LabelAtlas.prototype._updateAtlasValuesForWebGL;
+ cc.LabelAtlas.prototype.setString = cc.LabelAtlas.prototype._setStringForWebGL;
+ cc.LabelAtlas.prototype.setOpacity = cc.LabelAtlas.prototype._setOpacityForWebGL;
+} else {
+ cc.LabelAtlas.prototype.updateAtlasValues = cc.LabelAtlas.prototype._updateAtlasValuesForCanvas;
+ cc.LabelAtlas.prototype.setString = cc.LabelAtlas.prototype._setStringForCanvas;
+ cc.LabelAtlas.prototype.setOpacity = cc.LabelAtlas.prototype._setOpacityForCanvas;
+}
/**
- * It accepts two groups of parameters:
- * a) string, fntFile
- * b) label, textureFilename, width, height, startChar
+ *
+ * It accepts two groups of parameters:
+ * a) string, fntFile
+ * b) label, textureFilename, width, height, startChar
+ *
+ * CCLayerColor is a subclass of CCLayer that implements the CCRGBAProtocol protocol.
+ * All features from CCLayer are valid, plus the following new features:
+ *
* In Canvas render mode ,cc.SpriteBatchNodeCanvas is like a normal node: if it contains children.
- * If its _useCache is set to true, it can cache the result that all children of SpriteBatchNodeCanvas to a canvas
+ * If its _useCache is set to true, it can cache the result that all children of SpriteBatchNode to a canvas
* (often known as "batch draw").
*
* A cc.SpriteBatchNode can reference one and only one texture (one image file, one texture atlas).
@@ -51,593 +51,9 @@ cc.DEFAULT_SPRITE_BATCH_CAPACITY = 29;
* @extends cc.Node
* @example
* //create a SpriteBatchNode
- * var parent2 = cc.SpriteBatchNodeCanvas.create("res/animations/grossini.png", 50);
- */
-cc.SpriteBatchNodeCanvas = cc.Node.extend(/** @lends cc.SpriteBatchNodeCanvas# */{
- /// ---- common properties start ----
- _textureAtlas:null,
- _blendFunc:null,
- // all descendants: chlidren, gran children, etc...
- _descendants:null,
-
- /**
- *
- * This is the opposite of "addQuadFromSprite.
- * It add the sprite to the children and descendants array, but it doesn't update add it to the texture atlas
- *
- * @param {cc.Sprite} child
- * @param {Number} z zOrder
- * @param {Number} aTag
- * @return {cc.SpriteBatchNode}
- */
- addSpriteWithoutQuad:function (child, z, aTag) {
- cc.Assert(child != null, "SpriteBatchNode.addQuadFromSprite():Argument must be non-nil");
- cc.Assert((child instanceof cc.Sprite), "cc.SpriteBatchNode only supports cc.Sprites as children");
-
- // quad index is Z
- child.setAtlasIndex(z);
-
- // XXX: optimize with a binary search
- var i = 0, locDescendants = this._descendants;
- if (locDescendants && locDescendants.length > 0) {
- for (var index = 0; index < locDescendants.length; index++) {
- var obj = locDescendants[index];
- if (obj && (obj.getAtlasIndex() >= z))
- ++i;
- }
- }
- this._descendants = cc.ArrayAppendObjectToIndex(locDescendants, child, i);
-
- // IMPORTANT: Call super, and not self. Avoid adding it to the texture atlas array
- cc.Node.prototype.addChild.call(this, child, z, aTag);
-
- //#issue 1262 don't use lazy sorting, tiles are added as quads not as sprites, so sprites need to be added in order
- this.reorderBatch(false);
- return this;
- },
-
- // property
- /**
- * Return TextureAtlas of cc.SpriteBatchNode
- * @return {cc.TextureAtlas}
- */
- getTextureAtlas:function () {
- return this._textureAtlas;
- },
-
- /**
- * TextureAtlas of cc.SpriteBatchNode setter
- * @param {cc.TextureAtlas} textureAtlas
- */
- setTextureAtlas:function (textureAtlas) {
- if (textureAtlas != this._textureAtlas) {
- this._textureAtlas = textureAtlas;
- }
- },
-
- /**
- * Return Descendants of cc.SpriteBatchNode
- * @return {Array}
- */
- getDescendants:function () {
- return this._descendants;
- },
-
- /**
- *
- * initializes a cc.SpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and a capacity of children.
- * The capacity will be increased in 33% in runtime if it run out of space.
- * The file will be loaded using the TextureMgr.
- *
- * initializes a cc.SpriteBatchNode with a file image (.png, .jpeg, .pvr, etc) and a capacity of children.
- * The capacity will be increased in 33% in runtime if it run out of space.
- * The file will be loaded using the TextureMgr.
- *
- * @param {String} fileImage
- * @param {Number} capacity
- * @return {Boolean}
- */
- init:function (fileImage, capacity) {
- var texture2D = cc.TextureCache.getInstance().textureForKey(fileImage);
- if (!texture2D)
- texture2D = cc.TextureCache.getInstance().addImage(fileImage);
- return this.initWithTexture(texture2D, capacity);
- },
-
- /**
- * increase Atlas Capacity
- */
- increaseAtlasCapacity:function () {
- // if we're going beyond the current TextureAtlas's capacity,
- // all the previously initialized sprites will need to redo their texture coords
- // this is likely computationally expensive
- var quantity = Math.floor((this._textureAtlas.getCapacity() + 1) * 4 / 3);
-
- cc.log("cocos2d: CCSpriteBatchNode: resizing TextureAtlas capacity from " + this._textureAtlas.getCapacity() + " to " + quantity + ".");
-
- if (!this._textureAtlas.resizeCapacity(quantity)) {
- // serious problems
- cc.log("cocos2d: WARNING: Not enough memory to resize the atlas");
- cc.Assert(false, "Not enough memory to resize the atla");
- }
- },
-
- /**
- * removes a child given a certain index. It will also cleanup the running actions depending on the cleanup parameter.
- * @warning Removing a child from a cc.SpriteBatchNode is very slow
- * @param {Number} index
- * @param {Boolean} doCleanup
- */
- removeChildAtIndex:function (index, doCleanup) {
- this.removeChild(this._children[index], doCleanup);
- },
-
- /**
- * rebuild index in order for child
- * @param {cc.Sprite} pobParent
- * @param {Number} index
- * @return {Number}
- */
- rebuildIndexInOrder:function (pobParent, index) {
- var children = pobParent.getChildren();
- if (children && children.length > 0) {
- for (var i = 0; i < children.length; i++) {
- var obj = children[i];
- if (obj && (obj.getZOrder() < 0)) {
- index = this.rebuildIndexInOrder(obj, index);
- }
- }
- }
- // ignore self (batch node)
- if (!pobParent == this) {
- pobParent.setAtlasIndex(index);
- index++;
- }
- if (children && children.length > 0) {
- for (i = 0; i < children.length; i++) {
- obj = children[i];
- if (obj && (obj.getZOrder() >= 0)) {
- index = this.rebuildIndexInOrder(obj, index);
- }
- }
- }
- return index;
- },
-
- /**
- * get highest atlas index in child
- * @param {cc.Sprite} sprite
- * @return {Number}
- */
- highestAtlasIndexInChild:function (sprite) {
- var children = sprite.getChildren();
-
- if (!children || children.length == 0)
- return sprite.getAtlasIndex();
- else
- return this.highestAtlasIndexInChild(children[children.length - 1]);
- },
-
- /**
- * get lowest atlas index in child
- * @param {cc.Sprite} sprite
- * @return {Number}
- */
- lowestAtlasIndexInChild:function (sprite) {
- var children = sprite.getChildren();
-
- if (!children || children.length == 0)
- return sprite.getAtlasIndex();
- else
- return this.lowestAtlasIndexInChild(children[children.length - 1]);
- },
-
- /**
- * get atlas index for child
- * @param {cc.Sprite} sprite
- * @param {Number} nZ
- * @return {Number}
- */
- atlasIndexForChild:function (sprite, nZ) {
- var brothers = sprite.getParent().getChildren();
- var childIndex = cc.ArrayGetIndexOfObject(brothers, sprite);
-
- // ignore parent Z if parent is spriteSheet
- var ignoreParent = sprite.getParent() == this;
- var previous = null;
- if (childIndex > 0 && childIndex < cc.UINT_MAX)
- previous = brothers[childIndex - 1];
-
- // first child of the sprite sheet
- if (ignoreParent) {
- if (childIndex == 0)
- return 0;
- return this.highestAtlasIndexInChild(previous) + 1;
- }
-
- // parent is a cc.Sprite, so, it must be taken into account
- // first child of an cc.Sprite ?
- var selParent;
- if (childIndex == 0) {
- selParent = sprite.getParent();
-
- // less than parent and brothers
- if (nZ < 0)
- return selParent.getAtlasIndex();
- else
- return selParent.getAtlasIndex() + 1;
- } else {
- // previous & sprite belong to the same branch
- if ((previous.getZOrder() < 0 && nZ < 0) || (previous.getZOrder() >= 0 && nZ >= 0))
- return this.highestAtlasIndexInChild(previous) + 1;
-
- // else (previous < 0 and sprite >= 0 )
- selParent = sprite.getParent();
- return selParent.getAtlasIndex() + 1;
- }
- },
-
- /**
- * Sprites use this to start sortChildren, don't call this manually
- * @param {Boolean} reorder
- */
- reorderBatch:function (reorder) {
- this._reorderChildDirty = reorder;
- },
-
- /**
- * set the source blending function for the texture
- * @param {Number | cc.BlendFunc} src
- * @param {Number} dst
- */
- setBlendFunc:function (src, dst) {
- if (arguments.length == 1)
- this._blendFunc = src;
- else
- this._blendFunc = {src:src, dst:dst};
- },
-
- /**
- * returns the blending function used for the texture
- * @return {cc.BlendFunc}
- */
- getBlendFunc:function () {
- return this._blendFunc;
- },
-
- /**
- * (override reorderChild of cc.Node)
- * @override
- * @param {cc.Sprite} child
- * @param {Number} zOrder
- */
- reorderChild:function (child, zOrder) {
- cc.Assert(child != null, "SpriteBatchNode.addChild():the child should not be null");
- cc.Assert(this._children.indexOf(child) > -1, "SpriteBatchNode.addChild():Child doesn't belong to Sprite");
-
- if (zOrder === child.getZOrder())
- return;
-
- //set the z-order and sort later
- cc.Node.prototype.reorderChild.call(this, child, zOrder);
- this.setNodeDirty();
- },
-
- /**
- * remove child from cc.SpriteBatchNode (override removeChild of cc.Node)
- * @param {cc.Sprite} child
- * @param cleanup
- */
- removeChild:function (child, cleanup) {
- // explicit null handling
- if (child == null)
- return;
-
- cc.Assert(this._children.indexOf(child) > -1, "SpriteBatchNode.addChild():sprite batch node should contain the child");
-
- // cleanup before removing
- this.removeSpriteFromAtlas(child);
- cc.Node.prototype.removeChild.call(this, child, cleanup);
- },
- /// ---- common properties end ----
-
- _textureForCanvas:null,
- _useCache:false,
- _originalTexture:null,
-
- /**
- * Constructor
- * @param {String} fileImage
- */
- ctor:function (fileImage) {
- cc.Node.prototype.ctor.call(this);
- if (fileImage)
- this.init(fileImage, cc.DEFAULT_SPRITE_BATCH_CAPACITY);
- },
-
- /**
- *
- * Updates a quad at a certain index into the texture atlas. The CCSprite won't be added into the children array.
- * This method should be called only when you are dealing with very big AtlasSrite and when most of the cc.Sprite won't be updated.
- * For example: a tile map (cc.TMXMap) or a label with lots of characters (BitmapFontAtlas)
- *
- * @param {cc.Sprite} sprite
- * @param {Number} index
- */
- updateQuadFromSprite:function (sprite, index) {
- cc.Assert(sprite != null, "SpriteBatchNode.addQuadFromSprite():Argument must be non-nil");
- cc.Assert((sprite instanceof cc.Sprite), "cc.SpriteBatchNode only supports cc.Sprites as children");
-
- //
- // update the quad directly. Don't add the sprite to the scene graph
- //
- sprite.setBatchNode(this);
- sprite.setAtlasIndex(index);
-
- sprite.setDirty(true);
- // UpdateTransform updates the textureAtlas quad
- sprite.updateTransform();
- },
-
- /**
- *
- * Inserts a quad at a certain index into the texture atlas. The cc.Sprite won't be added into the children array.
- * This method should be called only when you are dealing with very big AtlasSprite and when most of the cc.Sprite won't be updated.
- * For example: a tile map (cc.TMXMap) or a label with lots of characters (cc.LabelBMFont)
- *
- * @param {cc.Sprite} sprite
- * @param {Number} index
- */
- insertQuadFromSprite:function (sprite, index) {
- cc.Assert(sprite != null, "Argument must be non-NULL");
- cc.Assert(sprite instanceof cc.Sprite, "cc.SpriteBatchNode only supports cc.Sprites as children");
-
- //
- // update the quad directly. Don't add the sprite to the scene graph
- //
- sprite.setBatchNode(this);
- sprite.setAtlasIndex(index);
-
- // XXX: updateTransform will update the textureAtlas too, using updateQuad.
- // XXX: so, it should be AFTER the insertQuad
- sprite.setDirty(true);
- sprite.updateTransform();
- this._children = cc.ArrayAppendObjectToIndex(this._children, sprite, index);
- },
-
- /**
- *
- * initializes a CCSpriteBatchNode with a texture2d and capacity of children.
- * The capacity will be increased in 33% in runtime if it run out of space.
- *
- * @param {cc.Texture2D} tex
- * @param {Number} capacity
- * @return {Boolean}
- */
- initWithTexture:function (tex, capacity) {
- this._children = [];
- this._descendants = [];
-
- this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST);
-
- this._originalTexture = tex;
- this._textureForCanvas = tex;
- return true;
- },
-
- /**
- * addChild helper, faster than insertChild
- * @param {cc.Sprite} sprite
- */
- appendChild:function (sprite) {
- this._reorderChildDirty = true;
- sprite.setBatchNode(this);
- sprite.setDirty(true);
-
- this._descendants.push(sprite);
- var index = this._descendants.length - 1;
- sprite.setAtlasIndex(index);
-
- // add children recursively
- var children = sprite.getChildren();
- for (var i = 0; i < children.length; i++)
- this.appendChild(children[i]);
- },
-
- /**
- * remove sprite from TextureAtlas
- * @param {cc.Sprite} sprite
- */
- removeSpriteFromAtlas:function (sprite) {
- // Cleanup sprite. It might be reused (issue #569)
- sprite.setBatchNode(null);
- var locDescendants = this._descendants;
- var index = cc.ArrayGetIndexOfObject(locDescendants, sprite);
- if (index != -1) {
- cc.ArrayRemoveObjectAtIndex(locDescendants, index);
-
- // update all sprites beyond this one
- var len = locDescendants.length;
- for (; index < len; ++index) {
- var s = locDescendants[index];
- s.setAtlasIndex(s.getAtlasIndex() - 1);
- }
- }
-
- // remove children recursively
- var children = sprite.getChildren();
- if (children && children.length > 0) {
- for (var i = 0; i < children.length; i++)
- if (children[i])
- this.removeSpriteFromAtlas(children[i]);
- }
- },
- // CCTextureProtocol
- /**
- * Return texture of cc.SpriteBatchNode
- * @return {cc.Texture2D|HTMLImageElement|HTMLCanvasElement}
- */
- getTexture:function () {
- return this._textureForCanvas;
- },
-
- /**
- * texture of cc.SpriteBatchNode setter
- * @param {cc.Texture2D} texture
- */
- setTexture:function (texture) {
- this._textureForCanvas = texture;
- var locChildren = this._children;
- for (var i = 0; i < locChildren.length; i++)
- locChildren[i].setTexture(texture);
- },
-
- /**
- * don't call visit on it's children ( override visit of cc.Node )
- * @override
- * @param {CanvasRenderingContext2D} ctx
- */
- visit:function (ctx) {
- var context = ctx || cc.renderContext;
- // quick return if not visible
- if (!this._visible)
- return;
-
- context.save();
- this.transform(ctx);
- var i, locChildren = this._children;
-
- if (locChildren) {
- this.sortAllChildren();
- for (i = 0; i < locChildren.length; i++) {
- if (locChildren[i])
- locChildren[i].visit(context);
- }
- }
-
- context.restore();
- },
-
- /**
- * add child to cc.SpriteBatchNode (override addChild of cc.Node)
- * @override
- * @param {cc.Sprite} child
- * @param {Number} zOrder
- * @param {Number} tag
- */
- addChild:function (child, zOrder, tag) {
- if (child == null)
- return;
-
- if (arguments.length === 4)
- if (arguments[3] == true) {
- cc.Node.prototype.addChild.call(this, child, zOrder, tag);
- this.setNodeDirty();
- return;
- }
-
- zOrder = (zOrder == null) ? child.getZOrder() : zOrder;
- tag = (tag == null) ? child.getTag() : tag;
-
- cc.Assert(child != null, "SpriteBatchNode.addChild():child should not be null");
- cc.Assert((child instanceof cc.Sprite), "cc.SpriteBatchNode only supports cc.Sprites as children");
-
- cc.Node.prototype.addChild.call(this, child, zOrder, tag);
- this.appendChild(child);
- this.setNodeDirty();
- },
-
- /**
- *
Removes all children from the container and do a cleanup all running actions depending on the cleanup parameter.
- * (override removeAllChildren of cc.Node)
- * @param {Boolean} cleanup
- */
- removeAllChildren:function (cleanup) {
- // Invalidate atlas index. issue #569
- // useSelfRender should be performed on all descendants. issue #1216
- var locDescendants = this._descendants;
- if (locDescendants && locDescendants.length > 0) {
- for (var i = 0; i < locDescendants.length; i++) {
- if (locDescendants[i])
- locDescendants[i].setBatchNode(null);
- }
- }
-
- cc.Node.prototype.removeAllChildren.call(this, cleanup);
- this._descendants = [];
- },
-
- sortAllChildren:function () {
- if (this._reorderChildDirty) {
- var i, j = 0, locChildren = this._children;
- var length = locChildren.length, tempChild;
- //insertion sort
- for (i = 1; i < length; i++) {
- var tempItem = locChildren[i];
- j = i - 1;
- tempChild = locChildren[j];
-
- //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
- while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
- ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
- locChildren[j + 1] = tempChild;
- j = j - 1;
- tempChild = locChildren[j];
- }
- locChildren[j + 1] = tempItem;
- }
-
- //sorted now check all children
- if (locChildren.length > 0) {
- //first sort all children recursively based on zOrder
- this._arrayMakeObjectsPerformSelector(locChildren, cc.Node.StateCallbackType.sortAllChildren);
- }
- this._reorderChildDirty = false;
- }
- }
-});
-
-/**
- *
- * In WebGL render mode ,cc.SpriteBatchNode is like a batch node: if it contains children, it will draw them in 1 single OpenGL call
- * (often known as "batch draw").
- *
- * A cc.SpriteBatchNode can reference one and only one texture (one image file, one texture atlas).
- * Only the cc.Sprites that are contained in that texture can be added to the cc.SpriteBatchNode.
- * All cc.Sprites added to a cc.SpriteBatchNode are drawn in one WebGL draw call.
- * If the cc.Sprites are not added to a cc.SpriteBatchNode then an WebGL draw call will be needed for each one, which is less efficient.
- *
- * Limitations:
- * - The only object that is accepted as child (or grandchild, grand-grandchild, etc...) is cc.Sprite or any subclass of cc.Sprite.
- * eg: particles, labels and layer can't be added to a cc.SpriteBatchNode.
- * - Either all its children are Aliased or Antialiased. It can't be a mix.
- * This is because "alias" is a property of the texture, and all the sprites share the same texture.
- *
- * @class
- * @extends cc.Node
- * @example
- * //create a SpriteBatchNodeWebGL
- * var parent2 = cc.SpriteBatchNodeWebGL.create("res/animations/grossini.png", 50);
+ * var parent2 = cc.SpriteBatchNode.create("res/animations/grossini.png", 50);
*/
-cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
- /// ---- common properties start ----
+cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{
_textureAtlas:null,
_blendFunc:null,
// all descendants: chlidren, gran children, etc...
@@ -661,15 +77,15 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
child.setAtlasIndex(z);
// XXX: optimize with a binary search
- var i = 0;
- if (this._descendants && this._descendants.length > 0) {
- for (var index = 0; index < this._descendants.length; index++) {
- var obj = this._descendants[index];
+ var i = 0, locDescendants = this._descendants;
+ if (locDescendants && locDescendants.length > 0) {
+ for (var index = 0; index < locDescendants.length; index++) {
+ var obj = locDescendants[index];
if (obj && (obj.getAtlasIndex() >= z))
++i;
}
}
- this._descendants = cc.ArrayAppendObjectToIndex(this._descendants, child, i);
+ this._descendants = cc.ArrayAppendObjectToIndex(locDescendants, child, i);
// IMPORTANT: Call super, and not self. Avoid adding it to the texture atlas array
cc.Node.prototype.addChild.call(this, child, z, aTag);
@@ -751,9 +167,10 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
// if we're going beyond the current TextureAtlas's capacity,
// all the previously initialized sprites will need to redo their texture coords
// this is likely computationally expensive
- var quantity = 0 | ((this._textureAtlas.getCapacity() + 1) * 4 / 3);
+ var locCapacity = this._textureAtlas.getCapacity();
+ var quantity = Math.floor((locCapacity + 1) * 4 / 3);
- cc.log("cocos2d: CCSpriteBatchNode: resizing TextureAtlas capacity from " + this._textureAtlas.getCapacity() + " to [" + quantity + "].");
+ cc.log("cocos2d: CCSpriteBatchNode: resizing TextureAtlas capacity from " + locCapacity + " to " + quantity + ".");
if (!this._textureAtlas.resizeCapacity(quantity)) {
// serious problems
@@ -937,22 +354,34 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
// cleanup before removing
this.removeSpriteFromAtlas(child);
-
cc.Node.prototype.removeChild.call(this, child, cleanup);
},
- /// ---- common properties end ----
+
_mvpMatrix:null,
+ _textureForCanvas:null,
+ _useCache:false,
+ _originalTexture:null,
+
/**
* Constructor
* @param {String} fileImage
*/
- ctor:function (fileImage) {
+ ctor: null,
+
+ _ctorForCanvas: function (fileImage) {
+ cc.Node.prototype.ctor.call(this);
+ if (fileImage)
+ this.init(fileImage, cc.DEFAULT_SPRITE_BATCH_CAPACITY);
+ },
+
+ _ctorForWebGL: function (fileImage) {
cc.Node.prototype.ctor.call(this);
this._mvpMatrix = new cc.kmMat4();
if (fileImage)
this.init(fileImage, cc.DEFAULT_SPRITE_BATCH_CAPACITY);
},
+
/**
*
* Updates a quad at a certain index into the texture atlas. The CCSprite won't be added into the children array.
@@ -962,12 +391,30 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
* @param {cc.Sprite} sprite
* @param {Number} index
*/
- updateQuadFromSprite:function (sprite, index) {
+ updateQuadFromSprite:null,
+
+ _updateQuadFromSpriteForCanvas:function (sprite, index) {
+ cc.Assert(sprite != null, "SpriteBatchNode.addQuadFromSprite():Argument must be non-nil");
+ cc.Assert((sprite instanceof cc.Sprite), "cc.SpriteBatchNode only supports cc.Sprites as children");
+
+ //
+ // update the quad directly. Don't add the sprite to the scene graph
+ //
+ sprite.setBatchNode(this);
+ sprite.setAtlasIndex(index);
+
+ sprite.setDirty(true);
+ // UpdateTransform updates the textureAtlas quad
+ sprite.updateTransform();
+ },
+
+ _updateQuadFromSpriteForWebGL:function (sprite, index) {
cc.Assert(sprite != null, "SpriteBatchNode.addQuadFromSprite():Argument must be non-nil");
cc.Assert((sprite instanceof cc.Sprite), "cc.SpriteBatchNode only supports cc.Sprites as children");
// make needed room
- while (index >= this._textureAtlas.getCapacity() || this._textureAtlas.getCapacity() == this._textureAtlas.getTotalQuads()) {
+ var locCapacity = this._textureAtlas.getCapacity();
+ while (index >= locCapacity || locCapacity == this._textureAtlas.getTotalQuads()) {
this.increaseAtlasCapacity();
}
@@ -983,17 +430,19 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
},
_swap:function (oldIndex, newIndex) {
- var quads = this._textureAtlas.getQuads();
- var tempItem = this._descendants[oldIndex];
+ var locDescendants = this._descendants;
+ var locTextureAtlas = this._textureAtlas;
+ var quads = locTextureAtlas.getQuads();
+ var tempItem = locDescendants[oldIndex];
var tempIteQuad = cc.V3F_C4B_T2F_QuadCopy(quads[oldIndex]);
//update the index of other swapped item
- this._descendants[newIndex].setAtlasIndex(oldIndex);
- this._descendants[oldIndex] = this._descendants[newIndex];
+ locDescendants[newIndex].setAtlasIndex(oldIndex);
+ locDescendants[oldIndex] = locDescendants[newIndex];
- this._textureAtlas.updateQuad(quads[newIndex], oldIndex);
- this._descendants[newIndex] = tempItem;
- this._textureAtlas.updateQuad(tempIteQuad, newIndex);
+ locTextureAtlas.updateQuad(quads[newIndex], oldIndex);
+ locDescendants[newIndex] = tempItem;
+ locTextureAtlas.updateQuad(tempIteQuad, newIndex);
},
/**
@@ -1005,12 +454,33 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
* @param {cc.Sprite} sprite
* @param {Number} index
*/
- insertQuadFromSprite:function (sprite, index) {
+ insertQuadFromSprite:null,
+
+ _insertQuadFromSpriteForCanvas:function (sprite, index) {
+ cc.Assert(sprite != null, "Argument must be non-NULL");
+ cc.Assert(sprite instanceof cc.Sprite, "cc.SpriteBatchNode only supports cc.Sprites as children");
+
+ //
+ // update the quad directly. Don't add the sprite to the scene graph
+ //
+ sprite.setBatchNode(this);
+ sprite.setAtlasIndex(index);
+
+ // XXX: updateTransform will update the textureAtlas too, using updateQuad.
+ // XXX: so, it should be AFTER the insertQuad
+ sprite.setDirty(true);
+ sprite.updateTransform();
+ this._children = cc.ArrayAppendObjectToIndex(this._children, sprite, index);
+ },
+
+ _insertQuadFromSpriteForWebGL:function (sprite, index) {
cc.Assert(sprite != null, "Argument must be non-NULL");
cc.Assert(sprite instanceof cc.Sprite, "cc.SpriteBatchNode only supports cc.Sprites as children");
// make needed room
- while (index >= this._textureAtlas.getCapacity() || this._textureAtlas.getCapacity() === this._textureAtlas.getTotalQuads())
+ var locTextureAtlas = this._textureAtlas;
+ var locCapacity = locTextureAtlas.getCapacity();
+ while (index >= locCapacity || locCapacity === locTextureAtlas.getTotalQuads())
this.increaseAtlasCapacity();
//
@@ -1018,7 +488,7 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
//
sprite.setBatchNode(this);
sprite.setAtlasIndex(index);
- this._textureAtlas.insertQuad(sprite.getQuad(), index);
+ locTextureAtlas.insertQuad(sprite.getQuad(), index);
// XXX: updateTransform will update the textureAtlas too, using updateQuad.
// XXX: so, it should be AFTER the insertQuad
@@ -1095,10 +565,23 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
* The capacity will be increased in 33% in runtime if it run out of space.
*
* @param {cc.Texture2D} tex
- * @param {Number} capacity
+ * @param {Number} [capacity]
* @return {Boolean}
*/
- initWithTexture:function (tex, capacity) {
+ initWithTexture:null,
+
+ _initWithTextureForCanvas:function (tex, capacity) {
+ this._children = [];
+ this._descendants = [];
+
+ this._blendFunc = new cc.BlendFunc(cc.BLEND_SRC, cc.BLEND_DST);
+
+ this._originalTexture = tex;
+ this._textureForCanvas = tex;
+ return true;
+ },
+
+ _initWithTextureForWebGL:function (tex, capacity) {
this._children = [];
this._descendants = [];
@@ -1110,6 +593,7 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
this.setShaderProgram(cc.ShaderCache.getInstance().programForKey(cc.SHADER_POSITION_TEXTURECOLOR));
return true;
},
+
/**
* add child helper
* @param {cc.Sprite} sprite
@@ -1120,26 +604,27 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
sprite.setAtlasIndex(index);
sprite.setDirty(true);
- if (this._textureAtlas.getTotalQuads() == this._textureAtlas.getCapacity())
+ var locTextureAtlas = this._textureAtlas;
+ if (locTextureAtlas.getTotalQuads() >= locTextureAtlas.getCapacity())
this.increaseAtlasCapacity();
- this._textureAtlas.insertQuad(sprite.getQuad(), index);
+ locTextureAtlas.insertQuad(sprite.getQuad(), index);
this._descendants = cc.ArrayAppendObjectToIndex(this._descendants, sprite, index);
// update indices
- var i = index + 1;
- if (this._descendants && this._descendants.length > 0) {
- for (; i < this._descendants.length; i++)
- this._descendants[i].setAtlasIndex(this._descendants[i].getAtlasIndex() + 1);
+ var i = index + 1, locDescendant = this._descendants;
+ if (locDescendant && locDescendant.length > 0) {
+ for (; i < locDescendant.length; i++)
+ locDescendant[i].setAtlasIndex(locDescendant[i].getAtlasIndex() + 1);
}
// add children recursively
- var children = sprite.getChildren();
- if (children && children.length > 0) {
- for (i = 0; i < children.length; i++) {
- if (children[i]) {
- var getIndex = this.atlasIndexForChild(children[i], children[i].getZOrder());
- this.insertChild(children[i], getIndex);
+ var locChildren = sprite.getChildren();
+ if (locChildren && locChildren.length > 0) {
+ for (i = 0; i < locChildren.length; i++) {
+ if (locChildren[i]) {
+ var getIndex = this.atlasIndexForChild(locChildren[i], locChildren[i].getZOrder());
+ this.insertChild(locChildren[i], getIndex);
}
}
}
@@ -1149,18 +634,36 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
* addChild helper, faster than insertChild
* @param {cc.Sprite} sprite
*/
- appendChild:function (sprite) {
+ appendChild:null,
+
+ _appendChildForCanvas:function (sprite) {
+ this._reorderChildDirty = true;
+ sprite.setBatchNode(this);
+ sprite.setDirty(true);
+
+ this._descendants.push(sprite);
+ var index = this._descendants.length - 1;
+ sprite.setAtlasIndex(index);
+
+ // add children recursively
+ var children = sprite.getChildren();
+ for (var i = 0; i < children.length; i++)
+ this.appendChild(children[i]);
+ },
+
+ _appendChildForWebGL:function (sprite) {
this._reorderChildDirty = true;
sprite.setBatchNode(this);
sprite.setDirty(true);
- cc.ArrayAppendObject(this._descendants, sprite);
+ this._descendants.push(sprite);
var index = this._descendants.length - 1;
sprite.setAtlasIndex(index);
- if (this._textureAtlas.getTotalQuads() == this._textureAtlas.getCapacity())
+ var locTextureAtlas = this._textureAtlas;
+ if (locTextureAtlas.getTotalQuads() == locTextureAtlas.getCapacity())
this.increaseAtlasCapacity();
- this._textureAtlas.insertQuad(sprite.getQuad(), index);
+ locTextureAtlas.insertQuad(sprite.getQuad(), index);
// add children recursively
var children = sprite.getChildren();
@@ -1172,20 +675,49 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
* remove sprite from TextureAtlas
* @param {cc.Sprite} sprite
*/
- removeSpriteFromAtlas:function (sprite) {
+ removeSpriteFromAtlas:null,
+
+ _removeSpriteFromAtlasForCanvas:function (sprite) {
+ // Cleanup sprite. It might be reused (issue #569)
+ sprite.setBatchNode(null);
+ var locDescendants = this._descendants;
+ var index = cc.ArrayGetIndexOfObject(locDescendants, sprite);
+ if (index != -1) {
+ cc.ArrayRemoveObjectAtIndex(locDescendants, index);
+
+ // update all sprites beyond this one
+ var len = locDescendants.length;
+ for (; index < len; ++index) {
+ var s = locDescendants[index];
+ s.setAtlasIndex(s.getAtlasIndex() - 1);
+ }
+ }
+
+ // remove children recursively
+ var children = sprite.getChildren();
+ if (children && children.length > 0) {
+ for (var i = 0; i < children.length; i++)
+ if (children[i])
+ this.removeSpriteFromAtlas(children[i]);
+ }
+ },
+
+ _removeSpriteFromAtlasForWebGL:function (sprite) {
this._textureAtlas.removeQuadAtIndex(sprite.getAtlasIndex()); // remove from TextureAtlas
// Cleanup sprite. It might be reused (issue #569)
sprite.setBatchNode(null);
- var index = cc.ArrayGetIndexOfObject(this._descendants, sprite);
+ var locDescendants = this._descendants;
+ var index = cc.ArrayGetIndexOfObject(locDescendants, sprite);
if (index != -1) {
- cc.ArrayRemoveObjectAtIndex(this._descendants, index);
+ cc.ArrayRemoveObjectAtIndex(locDescendants, index);
// update all sprites beyond this one
- var len = this._descendants.length;
+
+ var len = locDescendants.length;
for (; index < len; ++index) {
- var s = this._descendants[index];
+ var s = locDescendants[index];
s.setAtlasIndex(s.getAtlasIndex() - 1);
}
}
@@ -1198,13 +730,18 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
this.removeSpriteFromAtlas(children[i]);
}
},
-
// CCTextureProtocol
/**
* Return texture of cc.SpriteBatchNode
* @return {cc.Texture2D|HTMLImageElement|HTMLCanvasElement}
*/
- getTexture:function () {
+ getTexture:null,
+
+ _getTextureForCanvas:function () {
+ return this._textureForCanvas;
+ },
+
+ _getTextureForWebGL:function () {
return this._textureAtlas.getTexture();
},
@@ -1212,7 +749,16 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
* texture of cc.SpriteBatchNode setter
* @param {cc.Texture2D} texture
*/
- setTexture:function (texture) {
+ setTexture:null,
+
+ _setTextureForCanvas:function (texture) {
+ this._textureForCanvas = texture;
+ var locChildren = this._children;
+ for (var i = 0; i < locChildren.length; i++)
+ locChildren[i].setTexture(texture);
+ },
+
+ _setTextureForWebGL:function (texture) {
this._textureAtlas.setTexture(texture);
this._updateBlendFunc();
},
@@ -1220,9 +766,32 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
/**
* don't call visit on it's children ( override visit of cc.Node )
* @override
- * @param {WebGLRenderingContext} ctx
+ * @param {CanvasRenderingContext2D} ctx
*/
- visit:function (ctx) {
+ visit:null,
+
+ _visitForCanvas:function (ctx) {
+ var context = ctx || cc.renderContext;
+ // quick return if not visible
+ if (!this._visible)
+ return;
+
+ context.save();
+ this.transform(ctx);
+ var i, locChildren = this._children;
+
+ if (locChildren) {
+ this.sortAllChildren();
+ for (i = 0; i < locChildren.length; i++) {
+ if (locChildren[i])
+ locChildren[i].visit(context);
+ }
+ }
+
+ context.restore();
+ },
+
+ _visitForWebGL:function (ctx) {
var gl = ctx || cc.renderContext;
// CAREFUL:
@@ -1235,15 +804,16 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
if (!this._visible)
return;
cc.kmGLPushMatrix();
- if (this._grid && this._grid.isActive()) {
- this._grid.beforeDraw();
+ var locGrid = this._grid;
+ if (locGrid && locGrid.isActive()) {
+ locGrid.beforeDraw();
this.transformAncestors();
}
this.sortAllChildren();
this.transform(gl);
this.draw(gl);
- if (this._grid && this._grid.isActive())
- this._grid.afterDraw(this);
+ if (locGrid && locGrid.isActive())
+ locGrid.afterDraw(this);
cc.kmGLPopMatrix();
this.setOrderOfArrival(0);
},
@@ -1252,19 +822,29 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
* add child to cc.SpriteBatchNode (override addChild of cc.Node)
* @override
* @param {cc.Sprite} child
- * @param {Number} zOrder
- * @param {Number} tag
+ * @param {Number} [zOrder]
+ * @param {Number} [tag]
*/
- addChild:function (child, zOrder, tag) {
+ addChild: null,
+
+ _addChildForCanvas: function (child, zOrder, tag) {
if (child == null)
return;
- if (arguments.length === 4)
- if (arguments[3] == true) {
- cc.Node.prototype.addChild.call(this, child, zOrder, tag);
- this.setNodeDirty();
- return;
- }
+ zOrder = (zOrder == null) ? child.getZOrder() : zOrder;
+ tag = (tag == null) ? child.getTag() : tag;
+
+ cc.Assert(child != null, "SpriteBatchNode.addChild():child should not be null");
+ cc.Assert((child instanceof cc.Sprite), "cc.SpriteBatchNode only supports cc.Sprites as children");
+
+ cc.Node.prototype.addChild.call(this, child, zOrder, tag);
+ this.appendChild(child);
+ this.setNodeDirty();
+ },
+
+ _addChildForWebGL: function (child, zOrder, tag) {
+ if (child == null)
+ return;
zOrder = (zOrder == null) ? child.getZOrder() : zOrder;
tag = (tag == null) ? child.getTag() : tag;
@@ -1285,13 +865,31 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
* (override removeAllChildren of cc.Node)
* @param {Boolean} cleanup
*/
- removeAllChildren:function (cleanup) {
+ removeAllChildren:null,
+
+ _removeAllChildrenForCanvas:function (cleanup) {
+ // Invalidate atlas index. issue #569
+ // useSelfRender should be performed on all descendants. issue #1216
+ var locDescendants = this._descendants;
+ if (locDescendants && locDescendants.length > 0) {
+ for (var i = 0, len = locDescendants.length; i < len; i++) {
+ if (locDescendants[i])
+ locDescendants[i].setBatchNode(null);
+ }
+ }
+
+ cc.Node.prototype.removeAllChildren.call(this, cleanup);
+ this._descendants = [];
+ },
+
+ _removeAllChildrenForWebGL:function (cleanup) {
// Invalidate atlas index. issue #569
// useSelfRender should be performed on all descendants. issue #1216
- if (this._descendants && this._descendants.length > 0) {
- for (var i = 0; i < this._descendants.length; i++) {
- if (this._descendants[i])
- this._descendants[i].setBatchNode(null);
+ var locDescendants = this._descendants;
+ if (locDescendants && locDescendants.length > 0) {
+ for (var i = 0, len = locDescendants.length; i < len; i++) {
+ if (locDescendants[i])
+ locDescendants[i].setBatchNode(null);
}
}
cc.Node.prototype.removeAllChildren.call(this, cleanup);
@@ -1299,7 +897,38 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
this._textureAtlas.removeAllQuads();
},
- sortAllChildren:function () {
+ sortAllChildren:null,
+
+ _sortAllChildrenForCanvas:function () {
+ if (this._reorderChildDirty) {
+ var i, j = 0, locChildren = this._children;
+ var length = locChildren.length, tempChild;
+ //insertion sort
+ for (i = 1; i < length; i++) {
+ var tempItem = locChildren[i];
+ j = i - 1;
+ tempChild = locChildren[j];
+
+ //continue moving element downwards while zOrder is smaller or when zOrder is the same but mutatedIndex is smaller
+ while (j >= 0 && ( tempItem._zOrder < tempChild._zOrder ||
+ ( tempItem._zOrder == tempChild._zOrder && tempItem._orderOfArrival < tempChild._orderOfArrival ))) {
+ locChildren[j + 1] = tempChild;
+ j = j - 1;
+ tempChild = locChildren[j];
+ }
+ locChildren[j + 1] = tempItem;
+ }
+
+ //sorted now check all children
+ if (locChildren.length > 0) {
+ //first sort all children recursively based on zOrder
+ this._arrayMakeObjectsPerformSelector(locChildren, cc.Node.StateCallbackType.sortAllChildren);
+ }
+ this._reorderChildDirty = false;
+ }
+ },
+
+ _sortAllChildrenForWebGL:function () {
if (this._reorderChildDirty) {
var childrenArr = this._children;
var i, j = 0, length = childrenArr.length, tempChild;
@@ -1336,7 +965,9 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
/**
* draw cc.SpriteBatchNode (override draw of cc.Node)
*/
- draw:function () {
+ draw:null,
+
+ _drawForWebGL:function () {
// Optimization: Fast Dispatch
if (this._textureAtlas.getTotalQuads() === 0)
return;
@@ -1351,7 +982,35 @@ cc.SpriteBatchNodeWebGL = cc.Node.extend(/** @lends cc.SpriteBatchNodeWebGL# */{
}
});
-cc.SpriteBatchNode = (cc.Browser.supportWebGL)?cc.SpriteBatchNodeWebGL:cc.SpriteBatchNodeCanvas;
+if(cc.Browser.supportWebGL){
+ cc.SpriteBatchNode.prototype.ctor = cc.SpriteBatchNode.prototype._ctorForWebGL;
+ cc.SpriteBatchNode.prototype.updateQuadFromSprite = cc.SpriteBatchNode.prototype._updateQuadFromSpriteForWebGL;
+ cc.SpriteBatchNode.prototype.insertQuadFromSprite = cc.SpriteBatchNode.prototype._insertQuadFromSpriteForWebGL;
+ cc.SpriteBatchNode.prototype.initWithTexture = cc.SpriteBatchNode.prototype._initWithTextureForWebGL;
+ cc.SpriteBatchNode.prototype.appendChild = cc.SpriteBatchNode.prototype._appendChildForWebGL;
+ cc.SpriteBatchNode.prototype.removeSpriteFromAtlas = cc.SpriteBatchNode.prototype._removeSpriteFromAtlasForWebGL;
+ cc.SpriteBatchNode.prototype.getTexture = cc.SpriteBatchNode.prototype._getTextureForWebGL;
+ cc.SpriteBatchNode.prototype.setTexture = cc.SpriteBatchNode.prototype._setTextureForWebGL;
+ cc.SpriteBatchNode.prototype.visit = cc.SpriteBatchNode.prototype._visitForWebGL;
+ cc.SpriteBatchNode.prototype.addChild = cc.SpriteBatchNode.prototype._addChildForWebGL;
+ cc.SpriteBatchNode.prototype.removeAllChildren = cc.SpriteBatchNode.prototype._removeAllChildrenForWebGL;
+ cc.SpriteBatchNode.prototype.sortAllChildren = cc.SpriteBatchNode.prototype._sortAllChildrenForWebGL;
+ cc.SpriteBatchNode.prototype.draw = cc.SpriteBatchNode.prototype._drawForWebGL;
+} else {
+ cc.SpriteBatchNode.prototype.ctor = cc.SpriteBatchNode.prototype._ctorForCanvas;
+ cc.SpriteBatchNode.prototype.updateQuadFromSprite = cc.SpriteBatchNode.prototype._updateQuadFromSpriteForCanvas;
+ cc.SpriteBatchNode.prototype.insertQuadFromSprite = cc.SpriteBatchNode.prototype._insertQuadFromSpriteForCanvas;
+ cc.SpriteBatchNode.prototype.initWithTexture = cc.SpriteBatchNode.prototype._initWithTextureForCanvas;
+ cc.SpriteBatchNode.prototype.appendChild = cc.SpriteBatchNode.prototype._appendChildForCanvas;
+ cc.SpriteBatchNode.prototype.removeSpriteFromAtlas = cc.SpriteBatchNode.prototype._removeSpriteFromAtlasForCanvas;
+ cc.SpriteBatchNode.prototype.getTexture = cc.SpriteBatchNode.prototype._getTextureForCanvas;
+ cc.SpriteBatchNode.prototype.setTexture = cc.SpriteBatchNode.prototype._setTextureForCanvas;
+ cc.SpriteBatchNode.prototype.visit = cc.SpriteBatchNode.prototype._visitForCanvas;
+ cc.SpriteBatchNode.prototype.removeAllChildren = cc.SpriteBatchNode.prototype._removeAllChildrenForCanvas;
+ cc.SpriteBatchNode.prototype.addChild = cc.SpriteBatchNode.prototype._addChildForCanvas;
+ cc.SpriteBatchNode.prototype.sortAllChildren = cc.SpriteBatchNode.prototype._sortAllChildrenForCanvas;
+ cc.SpriteBatchNode.prototype.draw = cc.Node.prototype.draw;
+}
/**
*
- * Returns a Texture2D object given an PVR filename
- * If the file image was not previously loaded, it will create a new CCTexture2D
- * object and it will return it. Otherwise it will return a reference of a previously loaded image
- * note: AddPVRTCImage does not support on HTML5
- *
- * @param {String} filename
- * @return {cc.Texture2D}
- */
- addPVRTCImage:function (filename) {
- cc.Assert(0, "TextureCache:addPVRTCImage does not support on HTML5");
- },
-
-
- /**
- *
- * Returns a Texture2D object given an ETC filename
- * If the file image was not previously loaded, it will create a new CCTexture2D
- * object and it will return it. Otherwise it will return a reference of a previously loaded image
- * note:addETCImage does not support on HTML5
- *
Returns a Texture2D object given an PVR filename
- * If the file image was not previously loaded, it will create a new Texture2D
- * object and it will return it. Otherwise it will return a reference of a previously loaded image
- * @param {String} path
- * @return {cc.Texture2D}
- */
- addPVRImage:function (path) {
- cc.Assert(path != null, "TextureCache: file image MUST not be null");
-
- path = cc.FileUtils.getInstance().fullPathForFilename(path);
-
- var key = path;
-
- if (this._textures[key] != null) {
- return this._textures[key];
- }
-
- // Split up directory and filename
- var tex = new cc.Texture2D();
- if (tex.initWithPVRFile(key)) {
- this._textures[key] = tex;
- } else {
- cc.log("cocos2d: Couldn't add PVRImage:" + key + " in TextureCache");
- }
- return tex;
- },
- /// ---- common properties end ----
- /**
- *
Purges the dictionary of loaded textures.
- * Call this method if you receive the "Memory Warning"
- * In the short term: it will free some resources preventing your app from being killed
- * In the medium term: it will allocate more resources
- * In the long term: it will be the same
- * @example
- * //example
- * cc.TextureCache.getInstance().removeAllTextures();
- */
- removeAllTextures:function () {
- this._textures = {};
- },
-
- /**
- * Deletes a texture from the cache given a texture
- * @param {Image} texture
- * @example
- * //example
- * cc.TextureCache.getInstance().removeTexture(texture);
- */
- removeTexture:function (texture) {
- if (!texture)
- return;
-
- for (var selKey in this._textures) {
- if (this._textures[selKey] == texture) {
- delete(this._textures[selKey]);
- }
- }
- },
-
- /**
- * Deletes a texture from the cache given a its key name
- * @param {String} textureKeyName
- * @example
- * //example
- * cc.TextureCache.getInstance().removeTexture("hello.png");
- */
- removeTextureForKey:function (textureKeyName) {
- if (textureKeyName == null)
- return;
- var fullPath = cc.FileUtils.getInstance().fullPathForFilename(textureKeyName);
- if (this._textures[fullPath])
- delete(this._textures[fullPath]);
- },
-
- /**
- * Loading the images asynchronously
- * @param {String} path
- * @param {cc.Node} target
- * @param {Function} selector
- * @return {HTMLImageElement|cc.Texture2D}
- * @example
- * //example
- * cc.TextureCache.getInstance().addImageAsync("hello.png", this, this.loadingCallBack);
- */
- addImageAsync:function (path, target, selector) {
- cc.Assert(path != null, "TextureCache: path MUST not be null");
- path = cc.FileUtils.getInstance().fullPathForFilename(path);
- var texture = this._textures[path];
- var image,that;
- if (texture) {
- if(texture.isLoaded()){
- this._addImageAsyncCallBack(target, selector);
- }else{
- that = this;
- image = texture.getHtmlElementObj();
- image.addEventListener("load", function () {
- texture.handleLoadedTexture();
- that._addImageAsyncCallBack(target, selector);
- this.removeEventListener('load', arguments.callee, false);
- });
- }
- } else {
- image = new Image();
- image.crossOrigin = "Anonymous";
-
- that = this;
- image.addEventListener("load", function () {
- if (that._textures.hasOwnProperty(path))
- that._textures[path].handleLoadedTexture();
- that._addImageAsyncCallBack(target, selector);
- this.removeEventListener('load', arguments.callee, false);
- this.removeEventListener('error', arguments.callee, false);
- });
- image.addEventListener("error", function () {
- cc.Loader.getInstance().onResLoadingErr(path);
- //remove from cache
- if (that._textures.hasOwnProperty(path))
- delete that._textures[path];
-
- this.removeEventListener('error', arguments.callee, false);
- });
- image.src = path;
- var texture2d = new cc.Texture2D();
- texture2d.initWithElement(image);
- this._textures[path] = texture2d;
- }
- return this._textures[path];
- },
-
- /**
- *
Returns a Texture2D object given an file image
- * If the file image was not previously loaded, it will create a new Texture2D
- * object and it will return it. It will use the filename as a key.
- * Otherwise it will return a reference of a previously loaded image.
- * Supported image extensions: .png, .jpg, .gif
Returns a Texture2D object given an UIImage image
- * If the image was not previously loaded, it will create a new Texture2D object and it will return it.
- * Otherwise it will return a reference of a previously loaded image
- * The "key" parameter will be used as the "key" for the cache.
- * If "key" is null, then a new texture will be created each time.
- * @param {HTMLImageElement|HTMLCanvasElement} image
- * @param {String} key
- * @return {HTMLImageElement|HTMLCanvasElement}
- */
- addUIImage:function (image, key) {
- cc.Assert(image != null, "TextureCache: image MUST not be nulll");
-
- if (key) {
- if (this._textures.hasOwnProperty(key) && this._textures[key])
- return this._textures[key];
- }
-
- // prevents overloading the autorelease pool
- var texture = new cc.Texture2D();
- texture.initWithImage(image);
- if ((key != null) && (texture != null))
- this._textures[key] = texture;
- else
- cc.log("cocos2d: Couldn't add UIImage in TextureCache");
- return texture;
- },
-
- /**
- *
Output to cc.log the current contents of this TextureCache
- * This will attempt to calculate the size of each texture, and the total texture memory in use.