* @function
- *
+ *
* @return {cc.AffineTransform}
* @deprecated since v3.0, please use cc.affineTransformMakeIdentity() instead
* @see cc.affineTransformMakeIdentity
@@ -129,7 +129,7 @@ cc.affineTransformIdentity = function () {
/**
* Apply the affine transformation on a rect.
* @function
- *
+ *
* @param {cc.Rect} rect
* @param {cc.AffineTransform} anAffineTransform
* @return {cc.Rect}
@@ -153,7 +153,7 @@ cc.rectApplyAffineTransform = function (rect, anAffineTransform) {
return cc.rect(minX, minY, (maxX - minX), (maxY - minY));
};
-cc._rectApplyAffineTransformIn = function(rect, anAffineTransform){
+cc._rectApplyAffineTransformIn = function (rect, anAffineTransform) {
var top = cc.rectGetMinY(rect);
var left = cc.rectGetMinX(rect);
var right = cc.rectGetMaxX(rect);
@@ -179,7 +179,7 @@ cc._rectApplyAffineTransformIn = function(rect, anAffineTransform){
/**
* Create a new affine transformation with a base transformation matrix and a translation based on it.
* @function
- *
+ *
* @param {cc.AffineTransform} t The base affine transform object
* @param {Number} tx The translation on x axis
* @param {Number} ty The translation on y axis
@@ -219,12 +219,14 @@ cc.affineTransformRotate = function (aTransform, anAngle) {
var fSin = Math.sin(anAngle);
var fCos = Math.cos(anAngle);
- return {a: aTransform.a * fCos + aTransform.c * fSin,
+ return {
+ a: aTransform.a * fCos + aTransform.c * fSin,
b: aTransform.b * fCos + aTransform.d * fSin,
c: aTransform.c * fCos - aTransform.a * fSin,
d: aTransform.d * fCos - aTransform.b * fSin,
tx: aTransform.tx,
- ty: aTransform.ty};
+ ty: aTransform.ty
+ };
};
/**
@@ -236,12 +238,14 @@ cc.affineTransformRotate = function (aTransform, anAngle) {
* @return {cc.AffineTransform} The result of concatenation
*/
cc.affineTransformConcat = function (t1, t2) {
- return {a: t1.a * t2.a + t1.b * t2.c, //a
+ return {
+ a: t1.a * t2.a + t1.b * t2.c, //a
b: t1.a * t2.b + t1.b * t2.d, //b
c: t1.c * t2.a + t1.d * t2.c, //c
d: t1.c * t2.b + t1.d * t2.d, //d
tx: t1.tx * t2.a + t1.ty * t2.c + t2.tx, //tx
- ty: t1.tx * t2.b + t1.ty * t2.d + t2.ty}; //ty
+ ty: t1.tx * t2.b + t1.ty * t2.d + t2.ty
+ }; //ty
};
/**
@@ -283,6 +287,19 @@ cc.affineTransformEqualToTransform = function (t1, t2) {
*/
cc.affineTransformInvert = function (t) {
var determinant = 1 / (t.a * t.d - t.b * t.c);
- return {a: determinant * t.d, b: -determinant * t.b, c: -determinant * t.c, d: determinant * t.a,
- tx: determinant * (t.c * t.ty - t.d * t.tx), ty: determinant * (t.b * t.tx - t.a * t.ty)};
+ return {
+ a: determinant * t.d, b: -determinant * t.b, c: -determinant * t.c, d: determinant * t.a,
+ tx: determinant * (t.c * t.ty - t.d * t.tx), ty: determinant * (t.b * t.tx - t.a * t.ty)
+ };
+};
+
+cc.affineTransformInvertOut = function (t, out) {
+ var a = t.a, b = t.b, c = t.c, d = t.d;
+ var determinant = 1 / (a * d - b * c);
+ out.a = determinant * d;
+ out.b = -determinant * b;
+ out.c = -determinant * c;
+ out.d = determinant * a;
+ out.tx = determinant * (c * t.ty - d * t.tx);
+ out.ty = determinant * (b * t.tx - a * t.ty);
};
diff --git a/cocos2d/core/event-manager/CCEventHelper.js b/cocos2d/core/event-manager/CCEventHelper.js
index bd4198f23a..b005e71c59 100644
--- a/cocos2d/core/event-manager/CCEventHelper.js
+++ b/cocos2d/core/event-manager/CCEventHelper.js
@@ -24,111 +24,112 @@
****************************************************************************/
// The event helper
-cc.EventHelper = function(){};
+cc.EventHelper = function () {
+};
cc.EventHelper.prototype = {
constructor: cc.EventHelper,
- apply: function ( object ) {
+ apply: function (object) {
object.addEventListener = cc.EventHelper.prototype.addEventListener;
object.hasEventListener = cc.EventHelper.prototype.hasEventListener;
object.removeEventListener = cc.EventHelper.prototype.removeEventListener;
object.dispatchEvent = cc.EventHelper.prototype.dispatchEvent;
},
- addEventListener: function ( type, listener, target ) {
+ addEventListener: function (type, listener, target) {
//check 'type' status, if the status is ready, dispatch event next frame
- if(type === "load" && this._textureLoaded){ //only load event checked.
- setTimeout(function(){
+ if (type === "load" && this._textureLoaded) { //only load event checked.
+ setTimeout(function () {
listener.call(target);
}, 0);
return;
}
- if ( this._listeners === undefined )
+ if (this._listeners === undefined)
this._listeners = {};
var listeners = this._listeners;
- if ( listeners[ type ] === undefined )
- listeners[ type ] = [];
+ if (listeners[type] === undefined)
+ listeners[type] = [];
- if ( !this.hasEventListener(type, listener, target))
- listeners[ type ].push( {callback:listener, eventTarget: target} );
+ if (!this.hasEventListener(type, listener, target))
+ listeners[type].push({callback: listener, eventTarget: target});
},
- hasEventListener: function ( type, listener, target ) {
- if ( this._listeners === undefined )
+ hasEventListener: function (type, listener, target) {
+ if (this._listeners === undefined)
return false;
var listeners = this._listeners;
- if ( listeners[ type ] !== undefined ) {
- for(var i = 0, len = listeners.length; i < len ; i++){
+ if (listeners[type] !== undefined) {
+ for (var i = 0, len = listeners.length; i < len; i++) {
var selListener = listeners[i];
- if(selListener.callback === listener && selListener.eventTarget === target)
+ if (selListener.callback === listener && selListener.eventTarget === target)
return true;
}
}
return false;
},
- removeEventListener: function( type, listener, target){
- if ( this._listeners === undefined )
+ removeEventListener: function (type, listener, target) {
+ if (this._listeners === undefined)
return;
var listeners = this._listeners;
- var listenerArray = listeners[ type ];
+ var listenerArray = listeners[type];
- if ( listenerArray !== undefined ) {
- for(var i = 0; i < listenerArray.length ; ){
+ if (listenerArray !== undefined) {
+ for (var i = 0; i < listenerArray.length;) {
var selListener = listenerArray[i];
- if(selListener.eventTarget === target && selListener.callback === listener)
- listenerArray.splice( i, 1 );
+ if (selListener.eventTarget === target && selListener.callback === listener)
+ listenerArray.splice(i, 1);
else
i++
}
}
},
- removeEventTarget: function( type, listener, target){
- if ( this._listeners === undefined )
+ removeEventTarget: function (type, listener, target) {
+ if (this._listeners === undefined)
return;
var listeners = this._listeners;
- var listenerArray = listeners[ type ];
+ var listenerArray = listeners[type];
- if ( listenerArray !== undefined ) {
- for(var i = 0; i < listenerArray.length ; ){
+ if (listenerArray !== undefined) {
+ for (var i = 0; i < listenerArray.length;) {
var selListener = listenerArray[i];
- if(selListener.eventTarget === target)
- listenerArray.splice( i, 1 );
+ if (selListener.eventTarget === target)
+ listenerArray.splice(i, 1);
else
i++
}
}
},
- dispatchEvent: function ( event, clearAfterDispatch ) {
- if ( this._listeners === undefined )
+ dispatchEvent: function (event, clearAfterDispatch) {
+ if (this._listeners === undefined)
return;
- if(clearAfterDispatch == null)
+ if (clearAfterDispatch == null)
clearAfterDispatch = true;
var listeners = this._listeners;
- var listenerArray = listeners[ event];
+ var listenerArray = listeners[event];
- if ( listenerArray !== undefined ) {
+ if (listenerArray !== undefined) {
var array = [];
var length = listenerArray.length;
- for ( var i = 0; i < length; i ++ ) {
- array[ i ] = listenerArray[ i ];
+ for (var i = 0; i < length; i++) {
+ array[i] = listenerArray[i];
}
- for ( i = 0; i < length; i ++ ) {
- array[ i ].callback.call( array[i].eventTarget, this );
+ for (i = 0; i < length; i++) {
+ array[i].callback.call(array[i].eventTarget, this);
}
- if(clearAfterDispatch)
+ if (clearAfterDispatch)
listenerArray.length = 0;
}
}
diff --git a/cocos2d/core/event-manager/CCEventListener.js b/cocos2d/core/event-manager/CCEventListener.js
index 06e5bd4eee..c970c43fdf 100644
--- a/cocos2d/core/event-manager/CCEventListener.js
+++ b/cocos2d/core/event-manager/CCEventListener.js
@@ -277,15 +277,16 @@ cc.EventListener.CUSTOM = 8;
cc._EventListenerCustom = cc.EventListener.extend({
_onCustomEvent: null,
- ctor: function (listenerId, callback) {
+ ctor: function (listenerId, callback, target) {
this._onCustomEvent = callback;
- var selfPointer = this;
- var listener = function (event) {
- if (selfPointer._onCustomEvent !== null)
- selfPointer._onCustomEvent(event);
- };
+ this._target = target;
- cc.EventListener.prototype.ctor.call(this, cc.EventListener.CUSTOM, listenerId, listener);
+ cc.EventListener.prototype.ctor.call(this, cc.EventListener.CUSTOM, listenerId, this._callback);
+ },
+
+ _callback: function (event) {
+ if (this._onCustomEvent !== null)
+ this._onCustomEvent.call(this._target, event);
},
checkAvailable: function () {
@@ -308,31 +309,31 @@ cc._EventListenerMouse = cc.EventListener.extend({
onMouseScroll: null,
ctor: function () {
- var selfPointer = this;
- var listener = function (event) {
- var eventType = cc.EventMouse;
- switch (event._eventType) {
- case eventType.DOWN:
- if (selfPointer.onMouseDown)
- selfPointer.onMouseDown(event);
- break;
- case eventType.UP:
- if (selfPointer.onMouseUp)
- selfPointer.onMouseUp(event);
- break;
- case eventType.MOVE:
- if (selfPointer.onMouseMove)
- selfPointer.onMouseMove(event);
- break;
- case eventType.SCROLL:
- if (selfPointer.onMouseScroll)
- selfPointer.onMouseScroll(event);
- break;
- default:
- break;
- }
- };
- cc.EventListener.prototype.ctor.call(this, cc.EventListener.MOUSE, cc._EventListenerMouse.LISTENER_ID, listener);
+ cc.EventListener.prototype.ctor.call(this, cc.EventListener.MOUSE, cc._EventListenerMouse.LISTENER_ID, this._callback);
+ },
+
+ _callback: function (event) {
+ var eventType = cc.EventMouse;
+ switch (event._eventType) {
+ case eventType.DOWN:
+ if (this.onMouseDown)
+ this.onMouseDown(event);
+ break;
+ case eventType.UP:
+ if (this.onMouseUp)
+ this.onMouseUp(event);
+ break;
+ case eventType.MOVE:
+ if (this.onMouseMove)
+ this.onMouseMove(event);
+ break;
+ case eventType.SCROLL:
+ if (this.onMouseScroll)
+ this.onMouseScroll(event);
+ break;
+ default:
+ break;
+ }
},
clone: function () {
@@ -501,11 +502,12 @@ cc._EventListenerFocus = cc.EventListener.extend({
},
onFocusChanged: null,
ctor: function(){
- var listener = function(event){
- if(this.onFocusChanged)
- this.onFocusChanged(event._widgetLoseFocus, event._widgetGetFocus);
- };
- cc.EventListener.prototype.ctor.call(this, cc.EventListener.FOCUS, cc._EventListenerFocus.LISTENER_ID, listener);
+ cc.EventListener.prototype.ctor.call(this, cc.EventListener.FOCUS, cc._EventListenerFocus.LISTENER_ID, this._callback);
+ },
+ _callback: function (event) {
+ if (this.onFocusChanged) {
+ this.onFocusChanged(event._widgetLoseFocus, event._widgetGetFocus);
+ }
}
});
diff --git a/cocos2d/core/event-manager/CCEventManager.js b/cocos2d/core/event-manager/CCEventManager.js
index 6afe2e6e13..7f54f03939 100644
--- a/cocos2d/core/event-manager/CCEventManager.js
+++ b/cocos2d/core/event-manager/CCEventManager.js
@@ -23,6 +23,8 @@
THE SOFTWARE.
****************************************************************************/
+(function () {
+
/**
* @ignore
*/
@@ -73,25 +75,25 @@ cc._EventListenerVector = cc.Class.extend({
}
});
-cc.__getListenerID = function (event) {
- var eventType = cc.Event, getType = event.getType();
- if(getType === eventType.ACCELERATION)
+function __getListenerID (event) {
+ var eventType = cc.Event, getType = event._type;
+ if (getType === eventType.ACCELERATION)
return cc._EventListenerAcceleration.LISTENER_ID;
- if(getType === eventType.CUSTOM)
- return event.getEventName();
- if(getType === eventType.KEYBOARD)
+ if (getType === eventType.CUSTOM)
+ return event._eventName;
+ if (getType === eventType.KEYBOARD)
return cc._EventListenerKeyboard.LISTENER_ID;
- if(getType === eventType.MOUSE)
+ if (getType === eventType.MOUSE)
return cc._EventListenerMouse.LISTENER_ID;
- if(getType === eventType.FOCUS)
+ if (getType === eventType.FOCUS)
return cc._EventListenerFocus.LISTENER_ID;
- if(getType === eventType.TOUCH){
+ if (getType === eventType.TOUCH) {
// Touch listener is very special, it contains two kinds of listeners, EventListenerTouchOneByOne and EventListenerTouchAllAtOnce.
// return UNKNOWN instead.
cc.log(cc._LogInfos.__getListenerID);
}
return "";
-};
+}
/**
*
@@ -105,9 +107,9 @@ cc.__getListenerID = function (event) {
*/
cc.eventManager = /** @lends cc.eventManager# */{
//Priority dirty flag
- DIRTY_NONE:0,
- DIRTY_FIXED_PRIORITY:1 <<0,
- DIRTY_SCENE_GRAPH_PRIORITY : 1<< 1,
+ DIRTY_NONE: 0,
+ DIRTY_FIXED_PRIORITY: 1 << 0,
+ DIRTY_SCENE_GRAPH_PRIORITY: 1 << 1,
DIRTY_ALL: 3,
_listenersMap: {},
@@ -122,7 +124,7 @@ cc.eventManager = /** @lends cc.eventManager# */{
_isEnabled: false,
_nodePriorityIndex: 0,
- _internalCustomListenerIDs:[cc.game.EVENT_HIDE, cc.game.EVENT_SHOW],
+ _internalCustomListenerIDs: [cc.game.EVENT_HIDE, cc.game.EVENT_SHOW],
_setDirtyForNode: function (node) {
// Mark the node dirty only when there is an event listener associated with it.
@@ -141,12 +143,12 @@ cc.eventManager = /** @lends cc.eventManager# */{
pauseTarget: function (node, recursive) {
var listeners = this._nodeListenersMap[node.__instanceId], i, len;
if (listeners) {
- for ( i = 0, len = listeners.length; i < len; i++)
+ for (i = 0, len = listeners.length; i < len; i++)
listeners[i]._setPaused(true);
}
if (recursive === true) {
var locChildren = node.getChildren();
- for ( i = 0, len = locChildren.length; i< len; i++)
+ for (i = 0, len = locChildren.length; i < len; i++)
this.pauseTarget(locChildren[i], true);
}
},
@@ -158,14 +160,14 @@ cc.eventManager = /** @lends cc.eventManager# */{
*/
resumeTarget: function (node, recursive) {
var listeners = this._nodeListenersMap[node.__instanceId], i, len;
- if (listeners){
- for ( i = 0, len = listeners.length; i < len; i++)
+ if (listeners) {
+ for (i = 0, len = listeners.length; i < len; i++)
listeners[i]._setPaused(false);
}
this._setDirtyForNode(node);
if (recursive === true) {
var locChildren = node.getChildren();
- for ( i = 0, len = locChildren.length; i< len; i++)
+ for (i = 0, len = locChildren.length; i< len; i++)
this.resumeTarget(locChildren[i], true);
}
},
@@ -229,7 +231,7 @@ cc.eventManager = /** @lends cc.eventManager# */{
for (var i = 0; i < listenerVector.length;) {
selListener = listenerVector[i];
selListener._setRegistered(false);
- if (selListener._getSceneGraphPriority() != null){
+ if (selListener._getSceneGraphPriority() != null) {
this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener);
selListener._setSceneGraphPriority(null); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes.
}
@@ -256,8 +258,8 @@ cc.eventManager = /** @lends cc.eventManager# */{
if (!this._inDispatch) {
listeners.clear();
- delete this._listenersMap[listenerID];
}
+ delete this._listenersMap[listenerID];
}
var locToAddedListeners = this._toAddedListeners, listener;
@@ -271,7 +273,7 @@ cc.eventManager = /** @lends cc.eventManager# */{
},
_sortEventListeners: function (listenerID) {
- var dirtyFlag = this.DIRTY_NONE, locFlagMap = this._priorityDirtyFlagMap;
+ var dirtyFlag = this.DIRTY_NONE, locFlagMap = this._priorityDirtyFlagMap;
if (locFlagMap[listenerID])
dirtyFlag = locFlagMap[listenerID];
@@ -282,9 +284,9 @@ cc.eventManager = /** @lends cc.eventManager# */{
if (dirtyFlag & this.DIRTY_FIXED_PRIORITY)
this._sortListenersOfFixedPriority(listenerID);
- if (dirtyFlag & this.DIRTY_SCENE_GRAPH_PRIORITY){
+ if (dirtyFlag & this.DIRTY_SCENE_GRAPH_PRIORITY) {
var rootNode = cc.director.getRunningScene();
- if(rootNode)
+ if (rootNode)
this._sortListenersOfSceneGraphPriority(listenerID, rootNode);
else
locFlagMap[listenerID] = this.DIRTY_SCENE_GRAPH_PRIORITY;
@@ -298,7 +300,7 @@ cc.eventManager = /** @lends cc.eventManager# */{
return;
var sceneGraphListener = listeners.getSceneGraphPriorityListeners();
- if(!sceneGraphListener || sceneGraphListener.length === 0)
+ if (!sceneGraphListener || sceneGraphListener.length === 0)
return;
// Reset priority index
@@ -311,12 +313,12 @@ cc.eventManager = /** @lends cc.eventManager# */{
listeners.getSceneGraphPriorityListeners().sort(this._sortEventListenersOfSceneGraphPriorityDes);
},
- _sortEventListenersOfSceneGraphPriorityDes : function(l1, l2){
+ _sortEventListenersOfSceneGraphPriorityDes: function (l1, l2) {
var locNodePriorityMap = cc.eventManager._nodePriorityMap, node1 = l1._getSceneGraphPriority(),
node2 = l2._getSceneGraphPriority();
- if( !l2 || !node2 || !locNodePriorityMap[node2.__instanceId] )
+ if (!l2 || !node2 || !locNodePriorityMap[node2.__instanceId])
return -1;
- else if( !l1 || !node1 || !locNodePriorityMap[node1.__instanceId] )
+ else if (!l1 || !node1 || !locNodePriorityMap[node1.__instanceId])
return 1;
return locNodePriorityMap[l2._getSceneGraphPriority().__instanceId] - locNodePriorityMap[l1._getSceneGraphPriority().__instanceId];
},
@@ -327,7 +329,7 @@ cc.eventManager = /** @lends cc.eventManager# */{
return;
var fixedListeners = listeners.getFixedPriorityListeners();
- if(!fixedListeners || fixedListeners.length === 0)
+ if (!fixedListeners || fixedListeners.length === 0)
return;
// After sort: priority < 0, > 0
fixedListeners.sort(this._sortListenersOfFixedPriorityAsc);
@@ -346,11 +348,7 @@ cc.eventManager = /** @lends cc.eventManager# */{
return l1._getFixedPriority() - l2._getFixedPriority();
},
- _onUpdateListeners: function (listenerID) {
- var listeners = this._listenersMap[listenerID];
- if (!listeners)
- return;
-
+ _onUpdateListeners: function (listeners) {
var fixedPriorityListeners = listeners.getFixedPriorityListeners();
var sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners();
var i, selListener, idx, toRemovedListeners = this._toRemovedListeners;
@@ -390,20 +388,7 @@ cc.eventManager = /** @lends cc.eventManager# */{
listeners.clearFixedListeners();
},
- _updateListeners: function (event) {
- var locInDispatch = this._inDispatch;
- cc.assert(locInDispatch > 0, cc._LogInfos.EventManager__updateListeners);
-
- if(locInDispatch > 1)
- return;
-
- if (event.getType() === cc.Event.TOUCH) {
- this._onUpdateListeners(cc._EventListenerTouchOneByOne.LISTENER_ID);
- this._onUpdateListeners(cc._EventListenerTouchAllAtOnce.LISTENER_ID);
- } else
- this._onUpdateListeners(cc.__getListenerID(event));
-
- cc.assert(locInDispatch === 1, cc._LogInfos.EventManager__updateListeners_2);
+ frameUpdateListeners: function () {
var locListenersMap = this._listenersMap, locPriorityDirtyFlagMap = this._priorityDirtyFlagMap;
for (var selKey in locListenersMap) {
if (locListenersMap[selKey].empty()) {
@@ -416,31 +401,62 @@ cc.eventManager = /** @lends cc.eventManager# */{
if (locToAddedListeners.length !== 0) {
for (var i = 0, len = locToAddedListeners.length; i < len; i++)
this._forceAddEventListener(locToAddedListeners[i]);
- this._toAddedListeners.length = 0;
+ locToAddedListeners.length = 0;
+ }
+ if (this._toRemovedListeners.length !== 0) {
+ this._cleanToRemovedListeners();
+ }
+ },
+
+ _updateTouchListeners: function (event) {
+ var locInDispatch = this._inDispatch;
+ cc.assert(locInDispatch > 0, cc._LogInfos.EventManager__updateListeners);
+
+ if (locInDispatch > 1)
+ return;
+
+ var listeners;
+ listeners = this._listenersMap[cc._EventListenerTouchOneByOne.LISTENER_ID];
+ if (listeners) {
+ this._onUpdateListeners(listeners);
+ }
+ listeners = this._listenersMap[cc._EventListenerTouchAllAtOnce.LISTENER_ID];
+ if (listeners) {
+ this._onUpdateListeners(listeners);
+ }
+
+ cc.assert(locInDispatch === 1, cc._LogInfos.EventManager__updateListeners_2);
+
+ var locToAddedListeners = this._toAddedListeners;
+ if (locToAddedListeners.length !== 0) {
+ for (var i = 0, len = locToAddedListeners.length; i < len; i++)
+ this._forceAddEventListener(locToAddedListeners[i]);
+ locToAddedListeners.length = 0;
}
- if(this._toRemovedListeners.length !== 0)
+ if (this._toRemovedListeners.length !== 0) {
this._cleanToRemovedListeners();
+ }
},
//Remove all listeners in _toRemoveListeners list and cleanup
- _cleanToRemovedListeners: function(){
+ _cleanToRemovedListeners: function () {
var toRemovedListeners = this._toRemovedListeners;
- for(var i = 0; i< toRemovedListeners.length; i++){
+ for (var i = 0; i < toRemovedListeners.length; i++) {
var selListener = toRemovedListeners[i];
var listeners = this._listenersMap[selListener._getListenerID()];
- if(!listeners)
+ if (!listeners)
continue;
var idx, fixedPriorityListeners = listeners.getFixedPriorityListeners(),
sceneGraphPriorityListeners = listeners.getSceneGraphPriorityListeners();
- if(sceneGraphPriorityListeners){
+ if (sceneGraphPriorityListeners) {
idx = sceneGraphPriorityListeners.indexOf(selListener);
if (idx !== -1) {
sceneGraphPriorityListeners.splice(idx, 1);
}
}
- if(fixedPriorityListeners){
+ if (fixedPriorityListeners) {
idx = fixedPriorityListeners.indexOf(selListener);
if (idx !== -1) {
fixedPriorityListeners.splice(idx, 1);
@@ -450,7 +466,7 @@ cc.eventManager = /** @lends cc.eventManager# */{
toRemovedListeners.length = 0;
},
- _onTouchEventCallback: function(listener, argsObj){
+ _onTouchEventCallback: function (listener, argsObj) {
// Skip if the listener was removed.
if (!listener._isRegistered)
return false;
@@ -469,14 +485,14 @@ cc.eventManager = /** @lends cc.eventManager# */{
} else if (listener._claimedTouches.length > 0
&& ((removedIdx = listener._claimedTouches.indexOf(selTouch)) !== -1)) {
isClaimed = true;
- if(getCode === eventCode.MOVED && listener.onTouchMoved){
+ if (getCode === eventCode.MOVED && listener.onTouchMoved) {
listener.onTouchMoved(selTouch, event);
- } else if(getCode === eventCode.ENDED){
+ } else if (getCode === eventCode.ENDED) {
if (listener.onTouchEnded)
listener.onTouchEnded(selTouch, event);
if (listener._registered)
listener._claimedTouches.splice(removedIdx, 1);
- } else if(getCode === eventCode.CANCELLED){
+ } else if (getCode === eventCode.CANCELLED) {
if (listener.onTouchCancelled)
listener.onTouchCancelled(selTouch, event);
if (listener._registered)
@@ -486,7 +502,7 @@ cc.eventManager = /** @lends cc.eventManager# */{
// If the event was stopped, return directly.
if (event.isStopped()) {
- cc.eventManager._updateListeners(event);
+ cc.eventManager._updateTouchListeners(event);
return true;
}
@@ -532,7 +548,7 @@ cc.eventManager = /** @lends cc.eventManager# */{
if (event.isStopped())
return;
}
- this._updateListeners(event);
+ this._updateTouchListeners(event);
},
_onTouchesEventCallback: function (listener, callbackParams) {
@@ -542,18 +558,18 @@ cc.eventManager = /** @lends cc.eventManager# */{
var eventCode = cc.EventTouch.EventCode, event = callbackParams.event, touches = callbackParams.touches, getCode = event.getEventCode();
event._setCurrentTarget(listener._node);
- if(getCode === eventCode.BEGAN && listener.onTouchesBegan)
+ if (getCode === eventCode.BEGAN && listener.onTouchesBegan)
listener.onTouchesBegan(touches, event);
- else if(getCode === eventCode.MOVED && listener.onTouchesMoved)
+ else if (getCode === eventCode.MOVED && listener.onTouchesMoved)
listener.onTouchesMoved(touches, event);
- else if(getCode === eventCode.ENDED && listener.onTouchesEnded)
+ else if (getCode === eventCode.ENDED && listener.onTouchesEnded)
listener.onTouchesEnded(touches, event);
- else if(getCode === eventCode.CANCELLED && listener.onTouchesCancelled)
+ else if (getCode === eventCode.CANCELLED && listener.onTouchesCancelled)
listener.onTouchesCancelled(touches, event);
// If the event was stopped, return directly.
if (event.isStopped()) {
- cc.eventManager._updateListeners(event);
+ cc.eventManager._updateTouchListeners(event);
return true;
}
return false;
@@ -675,7 +691,7 @@ cc.eventManager = /** @lends cc.eventManager# */{
}
},
- _sortNumberAsc : function (a, b) {
+ _sortNumberAsc: function (a, b) {
return a - b;
},
@@ -695,11 +711,11 @@ cc.eventManager = /** @lends cc.eventManager# */{
*/
addListener: function (listener, nodeOrPriority) {
cc.assert(listener && nodeOrPriority, cc._LogInfos.eventManager_addListener_2);
- if(!(listener instanceof cc.EventListener)){
+ if (!(listener instanceof cc.EventListener)) {
cc.assert(!cc.isNumber(nodeOrPriority), cc._LogInfos.eventManager_addListener_3);
listener = cc.EventListener.create(listener);
} else {
- if(listener._isRegistered()){
+ if (listener._isRegistered()) {
cc.log(cc._LogInfos.eventManager_addListener_4);
return;
}
@@ -735,8 +751,8 @@ cc.eventManager = /** @lends cc.eventManager# */{
* @param {function} callback
* @return {cc.EventListener} the generated event. Needed in order to remove the event from the dispatcher
*/
- addCustomListener: function (eventName, callback) {
- var listener = new cc._EventListenerCustom(eventName, callback);
+ addCustomListener: function (eventName, callback, target) {
+ var listener = new cc._EventListenerCustom(eventName, callback, target);
this.addListener(listener, 1);
return listener;
},
@@ -786,7 +802,7 @@ cc.eventManager = /** @lends cc.eventManager# */{
}
},
- _removeListenerInCallback: function(listeners, callback){
+ _removeListenerInCallback: function (listeners, callback) {
if (listeners == null)
return false;
@@ -794,7 +810,7 @@ cc.eventManager = /** @lends cc.eventManager# */{
var selListener = listeners[i];
if (selListener._onCustomEvent === callback || selListener._onEvent === callback) {
selListener._setRegistered(false);
- if (selListener._getSceneGraphPriority() != null){
+ if (selListener._getSceneGraphPriority() != null) {
this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener);
selListener._setSceneGraphPriority(null); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes.
}
@@ -807,7 +823,7 @@ cc.eventManager = /** @lends cc.eventManager# */{
return false;
},
- _removeListenerInVector : function(listeners, listener){
+ _removeListenerInVector: function (listeners, listener) {
if (listeners == null)
return false;
@@ -815,7 +831,7 @@ cc.eventManager = /** @lends cc.eventManager# */{
var selListener = listeners[i];
if (selListener === listener) {
selListener._setRegistered(false);
- if (selListener._getSceneGraphPriority() != null){
+ if (selListener._getSceneGraphPriority() != null) {
this._dissociateNodeAndEventListener(selListener._getSceneGraphPriority(), selListener);
selListener._setSceneGraphPriority(null); // NULL out the node pointer so we don't have any dangling pointers to destroyed nodes.
}
@@ -900,8 +916,8 @@ cc.eventManager = /** @lends cc.eventManager# */{
*/
removeAllListeners: function () {
var locListeners = this._listenersMap, locInternalCustomEventIDs = this._internalCustomListenerIDs;
- for (var selKey in locListeners){
- if(locInternalCustomEventIDs.indexOf(selKey) === -1)
+ for (var selKey in locListeners) {
+ if (locInternalCustomEventIDs.indexOf(selKey) === -1)
this._removeListenersForListenerID(selKey);
}
},
@@ -922,7 +938,7 @@ cc.eventManager = /** @lends cc.eventManager# */{
if (fixedPriorityListeners) {
var found = fixedPriorityListeners.indexOf(listener);
if (found !== -1) {
- if(listener._getSceneGraphPriority() != null)
+ if (listener._getSceneGraphPriority() != null)
cc.log(cc._LogInfos.eventManager_setPriority);
if (listener._getFixedPriority() !== fixedPriority) {
listener._setFixedPriority(fixedPriority);
@@ -960,25 +976,26 @@ cc.eventManager = /** @lends cc.eventManager# */{
this._updateDirtyFlagForSceneGraph();
this._inDispatch++;
- if(!event || !event.getType)
+ if (!event || !event.getType)
throw new Error("event is undefined");
- if (event.getType() === cc.Event.TOUCH) {
+ if (event._type === cc.Event.TOUCH) {
this._dispatchTouchEvent(event);
this._inDispatch--;
return;
}
- var listenerID = cc.__getListenerID(event);
+ var listenerID = __getListenerID(event);
this._sortEventListeners(listenerID);
var selListeners = this._listenersMap[listenerID];
- if (selListeners != null)
+ if (selListeners) {
this._dispatchEventToListeners(selListeners, this._onListenerCallback, event);
-
- this._updateListeners(event);
+ this._onUpdateListeners(selListeners);
+ }
+
this._inDispatch--;
},
- _onListenerCallback: function(listener, event){
+ _onListenerCallback: function (listener, event) {
event._setCurrentTarget(listener._getSceneGraphPriority());
listener._onEvent(event);
return event.isStopped();
@@ -995,3 +1012,5 @@ cc.eventManager = /** @lends cc.eventManager# */{
this.dispatchEvent(ev);
}
};
+
+})();
diff --git a/cocos2d/core/event-manager/CCTouch.js b/cocos2d/core/event-manager/CCTouch.js
index c36cea14dc..3c8ea79fb9 100644
--- a/cocos2d/core/event-manager/CCTouch.js
+++ b/cocos2d/core/event-manager/CCTouch.js
@@ -33,6 +33,7 @@
* @param {Number} id
*/
cc.Touch = cc.Class.extend(/** @lends cc.Touch# */{
+ _lastModified: 0,
_point:null,
_prevPoint:null,
_id:0,
diff --git a/cocos2d/core/labelttf/CCLabelTTF.js b/cocos2d/core/labelttf/CCLabelTTF.js
index 42803f2a2a..ac988109b9 100644
--- a/cocos2d/core/labelttf/CCLabelTTF.js
+++ b/cocos2d/core/labelttf/CCLabelTTF.js
@@ -512,8 +512,8 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{
this._fontName = textDefinition.fontName;
this._fontSize = textDefinition.fontSize || 12;
- if(textDefinition.lineHeight)
- this._lineHeight = textDefinition.lineHeight
+ if (textDefinition.lineHeight)
+ this._lineHeight = textDefinition.lineHeight;
else
this._lineHeight = this._fontSize;
@@ -537,7 +537,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{
if (mustUpdateTexture)
this._renderCmd._updateTexture();
var flags = cc.Node._dirtyFlags;
- this._renderCmd.setDirtyFlag(flags.colorDirty|flags.opacityDirty|flags.textDirty);
+ this._renderCmd.setDirtyFlag(flags.colorDirty | flags.opacityDirty | flags.textDirty);
},
_prepareTextDefinition: function (adjustForResolution) {
@@ -610,9 +610,9 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{
* @param {Number} [scaleY=]
*/
setScale: function (scale, scaleY) {
- this._scaleX = scale / cc.view.getDevicePixelRatio();
- this._scaleY = ((scaleY || scaleY === 0) ? scaleY : scale) /
- cc.view.getDevicePixelRatio();
+ var ratio = cc.view.getDevicePixelRatio();
+ this._scaleX = scale / ratio;
+ this._scaleY = ((scaleY || scaleY === 0) ? scaleY : scale) / ratio;
this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
},
@@ -806,23 +806,40 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{
getContentSize: function () {
if (this._needUpdateTexture)
this._renderCmd._updateTTF();
- return cc.size(this._contentSize);
+ var ratio = cc.view.getDevicePixelRatio();
+ return cc.size( this._contentSize.width / ratio, this._contentSize.height / ratio );
},
_getWidth: function () {
if (this._needUpdateTexture)
this._renderCmd._updateTTF();
- return this._contentSize.width;
+ return this._contentSize.width / cc.view.getDevicePixelRatio();
},
_getHeight: function () {
if (this._needUpdateTexture)
this._renderCmd._updateTTF();
- return this._contentSize.height;
+ return this._contentSize.height / cc.view.getDevicePixelRatio();
},
setTextureRect: function (rect, rotated, untrimmedSize) {
- //set needConvert to false
- cc.Sprite.prototype.setTextureRect.call(this, rect, rotated, untrimmedSize, false);
+ var _t = this;
+ _t._rectRotated = rotated || false;
+ _t.setContentSize(untrimmedSize || rect);
+
+ var locRect = _t._rect;
+ locRect.x = rect.x;
+ locRect.y = rect.y;
+ locRect.width = rect.width;
+ locRect.height = rect.height;
+ _t._renderCmd._setTextureCoords(rect, false);
+
+ var relativeOffsetX = _t._unflippedOffsetPositionFromCenter.x, relativeOffsetY = _t._unflippedOffsetPositionFromCenter.y;
+ if (_t._flippedX)
+ relativeOffsetX = -relativeOffsetX;
+ if (_t._flippedY)
+ relativeOffsetY = -relativeOffsetY;
+ _t._offsetPosition.x = relativeOffsetX + (rect.width - locRect.width) / 2;
+ _t._offsetPosition.y = relativeOffsetY + (rect.height - locRect.height) / 2;
},
/**
@@ -843,7 +860,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{
},
//For web only
- _setFontStyle: function(fontStyle){
+ _setFontStyle: function (fontStyle) {
if (this._fontStyle !== fontStyle) {
this._fontStyle = fontStyle;
this._renderCmd._setFontStyle(this._fontName, this._fontSize, this._fontStyle, this._fontWeight);
@@ -851,11 +868,11 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{
}
},
- _getFontStyle: function(){
+ _getFontStyle: function () {
return this._fontStyle;
},
- _setFontWeight: function(fontWeight){
+ _setFontWeight: function (fontWeight) {
if (this._fontWeight !== fontWeight) {
this._fontWeight = fontWeight;
this._renderCmd._setFontStyle(this._fontName, this._fontSize, this._fontStyle, this._fontWeight);
@@ -863,7 +880,7 @@ cc.LabelTTF = cc.Sprite.extend(/** @lends cc.LabelTTF# */{
}
},
- _getFontWeight: function(){
+ _getFontWeight: function () {
return this._fontWeight;
}
});
diff --git a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js
index 31109f2f9b..44c8f1866f 100644
--- a/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js
+++ b/cocos2d/core/labelttf/CCLabelTTFCanvasRenderCmd.js
@@ -24,15 +24,27 @@ cc.LabelTTF._textBaseline = ["top", "middle", "bottom"];
//check the first character
cc.LabelTTF.wrapInspection = true;
-//Support: English French German
-//Other as Oriental Language
-cc.LabelTTF._wordRex = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]+|\S)/;
-cc.LabelTTF._symbolRex = /^[!,.:;}\]%\?>、‘“》?。,!]/;
-cc.LabelTTF._lastWordRex = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]+|\S)$/;
-cc.LabelTTF._lastEnglish = /[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]+$/;
-cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/;
-
-(function() {
+// These regular expressions consider a word any sequence of characters
+// from these Unicode (sub)blocks:
+// - Basic Latin (letters and numbers, plus the hypen-minus '-')
+// - Latin-1 Supplement (accentuated letters and ¿¡ only)
+// - Latin Extended-A (complete)
+// - Latin Extended-B (complete)
+// - IPA Extensions (complete)
+// - Spacing Modifier Letters (complete)
+// - Combining Diacritical Marks (Combining Grapheme Joiner excluded)
+// - Greek and Coptic (complete, including reserved code points)
+// - Cyrillic (complete)
+// - Cyrillic Supplement (complete)
+// - General Punctuation (Non-Breaking Hyphen* [U+2011] and quotation marks)
+// * Note that Hyphen [U+2010] is considered a word boundary.
+cc.LabelTTF._wordRex = /([a-zA-Z0-9\-¿¡«À-ÖØ-öø-ʯ\u0300-\u034e\u0350-\u036FͰ-ԯ\u2011‵-‷‹⁅]+|\S)/;
+cc.LabelTTF._symbolRex = /^[!,.:;}\]%\?>、‘“》»?。,!\u2010′-‴›‼⁆⁇-⁉]/;
+cc.LabelTTF._lastWordRex = /([a-zA-Z0-9\-¿¡«À-ÖØ-öø-ʯ\u0300-\u034e\u0350-\u036FͰ-ԯ\u2011‵-‷‹⁅]+|\S)$/;
+cc.LabelTTF._lastEnglish = /[a-zA-Z0-9\-¿¡«À-ÖØ-öø-ʯ\u0300-\u034e\u0350-\u036FͰ-ԯ\u2011‵-‷‹⁅]+$/;
+cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9\-¿¡«À-ÖØ-öø-ʯ\u0300-\u034e\u0350-\u036FͰ-ԯ\u2011‵-‷‹⁅]/;
+
+(function () {
cc.LabelTTF.RenderCmd = function () {
this._fontClientHeight = 18;
this._fontStyleStr = "";
@@ -48,17 +60,17 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/;
this._status = [];
this._renderingIndex = 0;
- this._texRect = cc.rect();
this._canUseDirtyRegion = true;
};
var proto = cc.LabelTTF.RenderCmd.prototype;
proto.constructor = cc.LabelTTF.RenderCmd;
+ proto._labelCmdCtor = cc.LabelTTF.RenderCmd;
proto._setFontStyle = function (fontNameOrFontDef, fontSize, fontStyle, fontWeight) {
- if(fontNameOrFontDef instanceof cc.FontDefinition){
+ if (fontNameOrFontDef instanceof cc.FontDefinition) {
this._fontStyleStr = fontNameOrFontDef._getCanvasFontStr();
this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(fontNameOrFontDef);
- }else {
+ } else {
var deviceFontSize = fontSize * cc.view.getDevicePixelRatio();
this._fontStyleStr = fontStyle + " " + fontWeight + " " + deviceFontSize + "px '" + fontNameOrFontDef + "'";
this._fontClientHeight = cc.LabelTTF.__getFontHeightByDiv(fontNameOrFontDef, fontSize);
@@ -73,7 +85,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/;
return this._fontClientHeight;
};
- proto._updateColor = function(){
+ proto._updateColor = function () {
this._setColorsString();
this._updateTexture();
};
@@ -111,6 +123,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/;
this._isMultiLine = false;
this._measureConfig();
+ var textWidthCache = {};
if (locDimensionsWidth !== 0) {
// Content processing
this._strings = node._string.split('\n');
@@ -121,7 +134,13 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/;
} else {
this._strings = node._string.split('\n');
for (i = 0, strLength = this._strings.length; i < strLength; i++) {
- locLineWidth.push(this._measure(this._strings[i]));
+ if(this._strings[i]) {
+ var measuredWidth = this._measure(this._strings[i]);
+ locLineWidth.push(measuredWidth);
+ textWidthCache[this._strings[i]] = measuredWidth;
+ } else {
+ locLineWidth.push(0);
+ }
}
}
@@ -139,14 +158,18 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/;
//get offset for stroke and shadow
if (locDimensionsWidth === 0) {
- if (this._isMultiLine)
- locSize = cc.size(
- Math.ceil(Math.max.apply(Math, locLineWidth) + locStrokeShadowOffsetX),
- Math.ceil((this._fontClientHeight * pixelRatio * this._strings.length) + locStrokeShadowOffsetY));
- else
- locSize = cc.size(
- Math.ceil(this._measure(node._string) + locStrokeShadowOffsetX),
- Math.ceil(this._fontClientHeight * pixelRatio + locStrokeShadowOffsetY));
+ if (this._isMultiLine) {
+ locSize = cc.size(Math.ceil(Math.max.apply(Math, locLineWidth) + locStrokeShadowOffsetX),
+ Math.ceil((this._fontClientHeight * pixelRatio * this._strings.length) + locStrokeShadowOffsetY));
+ }
+ else {
+ var measuredWidth = textWidthCache[node._string];
+ if(!measuredWidth && node._string) {
+ measuredWidth = this._measure(node._string);
+ }
+ locSize = cc.size(Math.ceil((measuredWidth ? measuredWidth : 0) + locStrokeShadowOffsetX),
+ Math.ceil(this._fontClientHeight * pixelRatio + locStrokeShadowOffsetY));
+ }
} else {
if (node._dimensions.height === 0) {
if (this._isMultiLine)
@@ -167,16 +190,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/;
if (node._getFontStyle() !== "normal") { //add width for 'italic' and 'oblique'
locSize.width = Math.ceil(locSize.width + node._fontSize * 0.3);
}
- if (this._strings.length === 0) {
- this._texRect.width = 1;
- this._texRect.height = locSize.height || 1;
- }
- else {
- this._texRect.width = locSize.width;
- this._texRect.height = locSize.height;
- }
- var nodeW = locSize.width / pixelRatio, nodeH = locSize.height / pixelRatio;
- node.setContentSize(nodeW, nodeH);
+ node.setContentSize(locSize);
node._strokeShadowOffsetX = locStrokeShadowOffsetX;
node._strokeShadowOffsetY = locStrokeShadowOffsetY;
@@ -190,12 +204,12 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/;
var node = this._node;
var scale = cc.view.getDevicePixelRatio();
var locStrokeShadowOffsetX = node._strokeShadowOffsetX, locStrokeShadowOffsetY = node._strokeShadowOffsetY;
- var locContentSizeHeight = node._contentSize.height * scale - locStrokeShadowOffsetY, locVAlignment = node._vAlignment,
+ var locContentSizeHeight = node._contentSize.height - locStrokeShadowOffsetY, locVAlignment = node._vAlignment,
locHAlignment = node._hAlignment;
var dx = locStrokeShadowOffsetX * 0.5,
dy = locContentSizeHeight + locStrokeShadowOffsetY * 0.5;
var xOffset = 0, yOffset = 0, OffsetYArray = [];
- var locContentWidth = node._contentSize.width * scale - locStrokeShadowOffsetX;
+ var locContentWidth = node._contentSize.width - locStrokeShadowOffsetX;
//lineHeight
var lineHeight = node.getLineHeight() * scale;
@@ -230,9 +244,9 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/;
OffsetYArray.push(yOffset);
}
var tmpStatus = {
- contextTransform:cc.p(dx,dy),
- xOffset:xOffset,
- OffsetYArray:OffsetYArray
+ contextTransform: cc.p(dx, dy),
+ xOffset: xOffset,
+ OffsetYArray: OffsetYArray
};
this._status.push(tmpStatus);
};
@@ -321,16 +335,11 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/;
proto.updateStatus = function () {
var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
-
+
if (locFlag & flags.textDirty)
this._updateTexture();
- cc.Node.RenderCmd.prototype.updateStatus.call(this);
-
- if (this._dirtyFlag & flags.transformDirty){
- this.transform(this.getParentRenderCmd(), true);
- this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.transformDirty ^ this._dirtyFlag;
- }
+ this.originUpdateStatus();
};
proto._syncStatus = function (parentCmd) {
@@ -339,7 +348,7 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/;
if (locFlag & flags.textDirty)
this._updateTexture();
- cc.Node.RenderCmd.prototype._syncStatus.call(this, parentCmd);
+ this._originSyncStatus(parentCmd);
if (cc._renderType === cc.game.RENDER_TYPE_WEBGL || locFlag & flags.transformDirty)
this.transform(parentCmd);
@@ -378,49 +387,56 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/;
var locStrLen = this._strings.length;
for (var i = 0; i < locStrLen; i++) {
var line = this._strings[i];
- if (locStrokeEnabled)
+ if (locStrokeEnabled) {
+ context.lineJoin = 'round';
context.strokeText(line, xOffset, yOffsetArray[i]);
+ }
context.fillText(line, xOffset, yOffsetArray[i]);
}
cc.g_NumberOfDraws++;
};
})();
-(function(){
- cc.LabelTTF.CacheRenderCmd = function (renderable) {
- cc.LabelTTF.RenderCmd.call(this,renderable);
+(function () {
+ cc.LabelTTF.CacheRenderCmd = function () {
+ this._labelCmdCtor();
var locCanvas = this._labelCanvas = document.createElement("canvas");
locCanvas.width = 1;
locCanvas.height = 1;
this._labelContext = locCanvas.getContext("2d");
- this._texRect = cc.rect();
};
- cc.LabelTTF.CacheRenderCmd.prototype = Object.create( cc.LabelTTF.RenderCmd.prototype);
+ cc.LabelTTF.CacheRenderCmd.prototype = Object.create(cc.LabelTTF.RenderCmd.prototype);
cc.inject(cc.LabelTTF.RenderCmd.prototype, cc.LabelTTF.CacheRenderCmd.prototype);
var proto = cc.LabelTTF.CacheRenderCmd.prototype;
proto.constructor = cc.LabelTTF.CacheRenderCmd;
+ proto._cacheCmdCtor = cc.LabelTTF.CacheRenderCmd;
proto._updateTexture = function () {
this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.textDirty ^ this._dirtyFlag;
var node = this._node;
+ node._needUpdateTexture = false;
+ var locContentSize = node._contentSize;
this._updateTTF();
- var width = this._texRect.width, height = this._texRect.height;
+ var width = locContentSize.width, height = locContentSize.height;
var locContext = this._labelContext, locLabelCanvas = this._labelCanvas;
- if(!node._texture){
+ if (!node._texture) {
var labelTexture = new cc.Texture2D();
labelTexture.initWithElement(this._labelCanvas);
node.setTexture(labelTexture);
}
if (node._string.length === 0) {
- locLabelCanvas.width = width;
- locLabelCanvas.height = height;
- node._texture && node._texture.handleLoadedTexture();
- node.setTextureRect(this._texRect);
+ locLabelCanvas.width = 1;
+ locLabelCanvas.height = locContentSize.height || 1;
+ if (node._texture) {
+ node._texture._htmlElementObj = this._labelCanvas;
+ node._texture.handleLoadedTexture();
+ }
+ node.setTextureRect(cc.rect(0, 0, 1, locContentSize.height));
return true;
}
@@ -428,13 +444,16 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/;
locContext.font = this._fontStyleStr;
var flag = locLabelCanvas.width === width && locLabelCanvas.height === height;
- locLabelCanvas.width = this._texRect.width;
- locLabelCanvas.height = this._texRect.height;
+ locLabelCanvas.width = width;
+ locLabelCanvas.height = height;
if (flag) locContext.clearRect(0, 0, width, height);
this._saveStatus();
this._drawTTFInCanvas(locContext);
- node._texture && node._texture.handleLoadedTexture();
- node.setTextureRect(this._texRect);
+ if (node._texture) {
+ node._texture._htmlElementObj = this._labelCanvas;
+ node._texture.handleLoadedTexture();
+ }
+ node.setTextureRect(cc.rect(0, 0, width, height));
return true;
};
@@ -443,15 +462,19 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/;
};
proto._measure = function (text) {
- return this._labelContext.measureText(text).width;
+ if (text) {
+ return this._labelContext.measureText(text).width;
+ } else {
+ return 0;
+ }
};
})();
-(function(){
+(function () {
cc.LabelTTF.CacheCanvasRenderCmd = function (renderable) {
- cc.Sprite.CanvasRenderCmd.call(this, renderable);
- cc.LabelTTF.CacheRenderCmd.call(this);
+ this._spriteCmdCtor(renderable);
+ this._cacheCmdCtor();
};
var proto = cc.LabelTTF.CacheCanvasRenderCmd.prototype = Object.create(cc.Sprite.CanvasRenderCmd.prototype);
@@ -459,10 +482,10 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/;
proto.constructor = cc.LabelTTF.CacheCanvasRenderCmd;
})();
-(function(){
+(function () {
cc.LabelTTF.CanvasRenderCmd = function (renderable) {
- cc.Sprite.CanvasRenderCmd.call(this, renderable);
- cc.LabelTTF.RenderCmd.call(this);
+ this._spriteCmdCtor(renderable);
+ this._labelCmdCtor();
};
cc.LabelTTF.CanvasRenderCmd.prototype = Object.create(cc.Sprite.CanvasRenderCmd.prototype);
@@ -471,29 +494,35 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/;
var proto = cc.LabelTTF.CanvasRenderCmd.prototype;
proto.constructor = cc.LabelTTF.CanvasRenderCmd;
- proto._measureConfig = function () {};
+ proto._measureConfig = function () {
+ };
proto._measure = function (text) {
- var context = cc._renderContext.getContext();
- context.font = this._fontStyleStr;
- return context.measureText(text).width;
+ if(text) {
+ var context = cc._renderContext.getContext();
+ context.font = this._fontStyleStr;
+ return context.measureText(text).width;
+ } else {
+ return 0;
+ }
};
proto._updateTexture = function () {
this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.textDirty ^ this._dirtyFlag;
var node = this._node;
- var scale = cc.view.getDevicePixelRatio();
+ var locContentSize = node._contentSize;
this._updateTTF();
+ var width = locContentSize.width, height = locContentSize.height;
if (node._string.length === 0) {
- node.setTextureRect(this._texRect);
+ node.setTextureRect(cc.rect(0, 0, 1, locContentSize.height));
return true;
}
this._saveStatus();
- node.setTextureRect(this._texRect);
+ node.setTextureRect(cc.rect(0, 0, width, height));
return true;
};
- proto.rendering = function(ctx) {
+ proto.rendering = function (ctx) {
var scaleX = cc.view.getScaleX(),
scaleY = cc.view.getScaleY();
var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
@@ -501,11 +530,11 @@ cc.LabelTTF._firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/;
return;
var node = this._node;
wrapper.computeRealOffsetY();
- if(this._status.length <= 0)
+ if (this._status.length <= 0)
return;
- var locIndex = (this._renderingIndex >= this._status.length)? this._renderingIndex-this._status.length:this._renderingIndex;
+ var locIndex = (this._renderingIndex >= this._status.length) ? this._renderingIndex - this._status.length : this._renderingIndex;
var status = this._status[locIndex];
- this._renderingIndex = locIndex+1;
+ this._renderingIndex = locIndex + 1;
var locHeight = node._rect.height,
locX = node._offsetPosition.x,
diff --git a/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js b/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js
index 6b7e25f8b6..e1e8411e58 100644
--- a/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js
+++ b/cocos2d/core/labelttf/CCLabelTTFWebGLRenderCmd.js
@@ -23,14 +23,15 @@
****************************************************************************/
// ----------------------------------- LabelTTF WebGL render cmd ----------------------------
-(function() {
+(function () {
cc.LabelTTF.WebGLRenderCmd = function (renderable) {
- cc.Sprite.WebGLRenderCmd.call(this, renderable);
- cc.LabelTTF.CacheRenderCmd.call(this);
+ this._spriteCmdCtor(renderable);
+ this._cacheCmdCtor();
};
var proto = cc.LabelTTF.WebGLRenderCmd.prototype = Object.create(cc.Sprite.WebGLRenderCmd.prototype);
cc.inject(cc.LabelTTF.CacheRenderCmd.prototype, proto);
proto.constructor = cc.LabelTTF.WebGLRenderCmd;
- proto._updateColor = function () {};
-})();
\ No newline at end of file
+ proto._updateColor = function () {
+ };
+})();
diff --git a/cocos2d/core/layers/CCLayer.js b/cocos2d/core/layers/CCLayer.js
index fc085fa19f..c752ad814f 100644
--- a/cocos2d/core/layers/CCLayer.js
+++ b/cocos2d/core/layers/CCLayer.js
@@ -40,19 +40,8 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{
this._ignoreAnchorPointForPosition = true;
this.setAnchorPoint(0.5, 0.5);
this.setContentSize(cc.winSize);
- },
-
- /**
- * Initialization of the layer, please do not call this function by yourself, you should pass the parameters to constructor to initialize a layer
- */
- init: function(){
- var _t = this;
- _t._ignoreAnchorPointForPosition = true;
- _t.setAnchorPoint(0.5, 0.5);
- _t.setContentSize(cc.winSize);
- _t._cascadeColorEnabled = false;
- _t._cascadeOpacityEnabled = false;
- return true;
+ this._cascadeColorEnabled = false;
+ this._cascadeOpacityEnabled = false;
},
/**
@@ -61,7 +50,7 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{
* @function
* @see cc.Layer#unbake
*/
- bake: function(){
+ bake: function () {
this._renderCmd.bake();
},
@@ -71,7 +60,7 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{
* @function
* @see cc.Layer#bake
*/
- unbake: function(){
+ unbake: function () {
this._renderCmd.unbake();
},
@@ -81,16 +70,60 @@ cc.Layer = cc.Node.extend(/** @lends cc.Layer# */{
* @returns {boolean}
* @see cc.Layer#bake and cc.Layer#unbake
*/
- isBaked: function(){
+ isBaked: function () {
return this._renderCmd._isBaked;
},
- addChild: function(child, localZOrder, tag){
+ visit: function (parent) {
+ var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null;
+
+ // quick return if not visible
+ if (!this._visible) {
+ cmd._propagateFlagsDown(parentCmd);
+ return;
+ }
+
+ var renderer = cc.renderer;
+ cmd.visit(parentCmd);
+
+ if (cmd._isBaked) {
+ renderer.pushRenderCommand(cmd);
+ cmd._bakeSprite.visit(this);
+ }
+ else {
+ var i, children = this._children, len = children.length, child;
+ if (len > 0) {
+ if (this._reorderChildDirty) {
+ this.sortAllChildren();
+ }
+ // draw children zOrder < 0
+ for (i = 0; i < len; i++) {
+ child = children[i];
+ if (child._localZOrder < 0) {
+ child.visit(this);
+ }
+ else {
+ break;
+ }
+ }
+
+ renderer.pushRenderCommand(cmd);
+ for (; i < len; i++) {
+ children[i].visit(this);
+ }
+ } else {
+ renderer.pushRenderCommand(cmd);
+ }
+ }
+ cmd._dirtyFlag = 0;
+ },
+
+ addChild: function (child, localZOrder, tag) {
cc.Node.prototype.addChild.call(this, child, localZOrder, tag);
this._renderCmd._bakeForAddChild(child);
},
- _createRenderCmd: function(){
+ _createRenderCmd: function () {
if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return new cc.Layer.CanvasRenderCmd(this);
else
@@ -188,7 +221,7 @@ cc.LayerColor = cc.Layer.extend(/** @lends cc.LayerColor# */{
* @param {Number} [width=]
* @param {Number} [height=]
*/
- ctor: function(color, width, height){
+ ctor: function (color, width, height) {
cc.Layer.prototype.ctor.call(this);
this._blendFunc = cc.BlendFunc._alphaNonPremultiplied();
cc.LayerColor.prototype.init.call(this, color, width, height);
@@ -212,12 +245,59 @@ cc.LayerColor = cc.Layer.extend(/** @lends cc.LayerColor# */{
locRealColor.g = color.g;
locRealColor.b = color.b;
this._realOpacity = color.a;
- this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty|cc.Node._dirtyFlags.opacityDirty);
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty | cc.Node._dirtyFlags.opacityDirty);
cc.LayerColor.prototype.setContentSize.call(this, width, height);
return true;
},
+ visit: function (parent) {
+ var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null;
+
+ // quick return if not visible
+ if (!this._visible) {
+ cmd._propagateFlagsDown(parentCmd);
+ return;
+ }
+
+ var renderer = cc.renderer;
+ cmd.visit(parentCmd);
+
+ if (cmd._isBaked) {
+ renderer.pushRenderCommand(cmd._bakeRenderCmd);
+ //the bakeSprite is drawing
+ cmd._bakeSprite._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
+ cmd._bakeSprite.visit(this);
+ }
+ else {
+ var i, children = this._children, len = children.length;
+ if (len > 0) {
+ if (this._reorderChildDirty) {
+ this.sortAllChildren();
+ }
+ // draw children zOrder < 0
+ for (i = 0; i < len; i++) {
+ child = children[i];
+ if (child._localZOrder < 0) {
+ child.visit(this);
+ }
+ else {
+ break;
+ }
+ }
+
+ renderer.pushRenderCommand(cmd);
+ for (; i < len; i++) {
+ children[i].visit(this);
+ }
+ } else {
+ renderer.pushRenderCommand(cmd);
+ }
+ }
+
+ cmd._dirtyFlag = 0;
+ },
+
/**
* Sets the blend func, you can pass either a cc.BlendFunc object or source and destination value separately
* @param {Number|cc.BlendFunc} src
@@ -235,7 +315,7 @@ cc.LayerColor = cc.Layer.extend(/** @lends cc.LayerColor# */{
this._renderCmd.updateBlendFunc(locBlendFunc);
},
- _createRenderCmd: function(){
+ _createRenderCmd: function () {
if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return new cc.LayerColor.CanvasRenderCmd(this);
else
@@ -257,7 +337,7 @@ cc.LayerColor.create = function (color, width, height) {
};
//LayerColor - Getter Setter
-(function(){
+(function () {
var proto = cc.LayerColor.prototype;
cc.defineGetterSetter(proto, "width", proto._getWidth, proto._setWidth);
cc.defineGetterSetter(proto, "height", proto._getHeight, proto._setHeight);
@@ -328,12 +408,12 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{
this._startOpacity = 255;
this._endOpacity = 255;
- if(stops && stops instanceof Array){
+ if (stops && stops instanceof Array) {
this._colorStops = stops;
- stops.splice(0, 0, {p:0, color: start || cc.color.BLACK});
- stops.push({p:1, color: end || cc.color.BLACK});
+ stops.splice(0, 0, {p: 0, color: start || cc.color.BLACK});
+ stops.push({p: 1, color: end || cc.color.BLACK});
} else
- this._colorStops = [{p:0, color: start || cc.color.BLACK}, {p:1, color: end || cc.color.BLACK}];
+ this._colorStops = [{p: 0, color: start || cc.color.BLACK}, {p: 1, color: end || cc.color.BLACK}];
cc.LayerGradient.prototype.init.call(this, start, end, v, stops);
},
@@ -365,7 +445,7 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{
_t._compressedInterpolation = true;
cc.LayerColor.prototype.init.call(_t, cc.color(start.r, start.g, start.b, 255));
- this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty|cc.Node._dirtyFlags.opacityDirty|cc.Node._dirtyFlags.gradientDirty);
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty | cc.Node._dirtyFlags.opacityDirty | cc.Node._dirtyFlags.gradientDirty);
return true;
},
@@ -408,7 +488,7 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{
this.color = color;
//update the color stops
var stops = this._colorStops;
- if(stops && stops.length > 0){
+ if (stops && stops.length > 0) {
var selColor = stops[0].color;
selColor.r = color.r;
selColor.g = color.g;
@@ -431,8 +511,8 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{
locColor.b = color.b;
//update the color stops
var stops = this._colorStops;
- if(stops && stops.length > 0){
- var selColor = stops[stops.length -1].color;
+ if (stops && stops.length > 0) {
+ var selColor = stops[stops.length - 1].color;
selColor.r = color.r;
selColor.g = color.g;
selColor.b = color.b;
@@ -456,7 +536,7 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{
this._startOpacity = o;
//update the color stops
var stops = this._colorStops;
- if(stops && stops.length > 0)
+ if (stops && stops.length > 0)
stops[0].color.a = o;
this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.opacityDirty);
},
@@ -476,8 +556,8 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{
setEndOpacity: function (o) {
this._endOpacity = o;
var stops = this._colorStops;
- if(stops && stops.length > 0)
- stops[stops.length -1].color.a = o;
+ if (stops && stops.length > 0)
+ stops[stops.length - 1].color.a = o;
this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.opacityDirty);
},
@@ -531,7 +611,7 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{
* [{p: 0, color: cc.color.RED},{p: 1, color: cc.color.RED},...]
* @returns {Array}
*/
- getColorStops: function(){
+ getColorStops: function () {
return this._colorStops;
},
/**
@@ -548,13 +628,13 @@ cc.LayerGradient = cc.LayerColor.extend(/** @lends cc.LayerGradient# */{
* //where p = A value between 0.0 and 1.0 that represents the position between start and end in a gradient
*
*/
- setColorStops: function(colorStops){
+ setColorStops: function (colorStops) {
this._colorStops = colorStops;
//todo need update the start color and end color
- this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty|cc.Node._dirtyFlags.opacityDirty|cc.Node._dirtyFlags.gradientDirty);
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty | cc.Node._dirtyFlags.opacityDirty | cc.Node._dirtyFlags.gradientDirty);
},
- _createRenderCmd: function(){
+ _createRenderCmd: function () {
if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return new cc.LayerGradient.CanvasRenderCmd(this);
else
@@ -576,7 +656,7 @@ cc.LayerGradient.create = function (start, end, v, stops) {
return new cc.LayerGradient(start, end, v, stops);
};
//LayerGradient - Getter Setter
-(function(){
+(function () {
var proto = cc.LayerGradient.prototype;
// Extended properties
/** @expose */
@@ -699,4 +779,4 @@ cc.LayerMultiplex = cc.Layer.extend(/** @lends cc.LayerMultiplex# */{
*/
cc.LayerMultiplex.create = function (/*Multiple Arguments*/) {
return new cc.LayerMultiplex(Array.prototype.slice.call(arguments));
-};
\ No newline at end of file
+};
diff --git a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js
index 84ba03eb9f..3149895ee3 100644
--- a/cocos2d/core/layers/CCLayerCanvasRenderCmd.js
+++ b/cocos2d/core/layers/CCLayerCanvasRenderCmd.js
@@ -31,10 +31,10 @@
/**
* cc.Layer's rendering objects of Canvas
*/
-(function(){
+(function () {
//Layer's canvas render command
- cc.Layer.CanvasRenderCmd = function(renderable){
- cc.Node.CanvasRenderCmd.call(this, renderable);
+ cc.Layer.CanvasRenderCmd = function (renderable) {
+ this._rootCtor(renderable);
this._isBaked = false;
this._bakeSprite = null;
this._canUseDirtyRegion = true;
@@ -43,9 +43,10 @@
var proto = cc.Layer.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
proto.constructor = cc.Layer.CanvasRenderCmd;
+ proto._layerCmdCtor = cc.Layer.CanvasRenderCmd;
- proto._setCacheDirty = function(child){
- if(child && this._updateCache === 0)
+ proto._setCacheDirty = function (child) {
+ if (child && this._updateCache === 0)
this._updateCache = 2;
if (this._cacheDirty === false) {
this._cacheDirty = true;
@@ -58,74 +59,78 @@
var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
if (locFlag & flags.orderDirty) {
this._cacheDirty = true;
- if(this._updateCache === 0)
+ if (this._updateCache === 0)
this._updateCache = 2;
- this._dirtyFlag = locFlag & flags.orderDirty ^ locFlag;
+ this._dirtyFlag &= ~flags.orderDirty;
}
- cc.Node.RenderCmd.prototype.updateStatus.call(this);
+ this.originUpdateStatus();
};
proto._syncStatus = function (parentCmd) {
var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
- if (locFlag & flags.orderDirty) {
+ // if (locFlag & flags.orderDirty) {
+ if (this._isBaked || locFlag & flags.orderDirty) {
this._cacheDirty = true;
- if(this._updateCache === 0)
+ if (this._updateCache === 0)
this._updateCache = 2;
- this._dirtyFlag = locFlag & flags.orderDirty ^ locFlag;
+ this._dirtyFlag &= ~flags.orderDirty;
}
- cc.Node.RenderCmd.prototype._syncStatus.call(this, parentCmd);
+ this._originSyncStatus(parentCmd);
};
proto.transform = function (parentCmd, recursive) {
+ if (!this._worldTransform) {
+ this._worldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0};
+ }
var wt = this._worldTransform;
var a = wt.a, b = wt.b, c = wt.c, d = wt.d, tx = wt.tx, ty = wt.ty;
- cc.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd, recursive);
- if(( wt.a !== a || wt.b !== b || wt.c !== c || wt.d !== d ) && this._updateCache === 0)
+ this.originTransform(parentCmd, recursive);
+ if (( wt.a !== a || wt.b !== b || wt.c !== c || wt.d !== d ) && this._updateCache === 0)
this._updateCache = 2;
};
- proto.bake = function(){
+ proto.bake = function () {
if (!this._isBaked) {
this._needDraw = true;
cc.renderer.childrenOrderDirty = true;
//limit: 1. its children's blendfunc are invalid.
this._isBaked = this._cacheDirty = true;
- if(this._updateCache === 0)
+ if (this._updateCache === 0)
this._updateCache = 2;
var children = this._node._children;
- for(var i = 0, len = children.length; i < len; i++)
+ for (var i = 0, len = children.length; i < len; i++)
children[i]._renderCmd._setCachedParent(this);
if (!this._bakeSprite) {
this._bakeSprite = new cc.BakeSprite();
- this._bakeSprite.setAnchorPoint(0,0);
+ this._bakeSprite.setAnchorPoint(0, 0);
}
}
};
- proto.unbake = function(){
+ proto.unbake = function () {
if (this._isBaked) {
cc.renderer.childrenOrderDirty = true;
this._needDraw = false;
this._isBaked = false;
this._cacheDirty = true;
- if(this._updateCache === 0)
+ if (this._updateCache === 0)
this._updateCache = 2;
var children = this._node._children;
- for(var i = 0, len = children.length; i < len; i++)
+ for (var i = 0, len = children.length; i < len; i++)
children[i]._renderCmd._setCachedParent(null);
}
};
- proto.isBaked = function(){
+ proto.isBaked = function () {
return this._isBaked;
};
- proto.rendering = function(){
- if(this._cacheDirty){
+ proto.rendering = function () {
+ if (this._cacheDirty) {
var node = this._node;
var children = node._children, locBakeSprite = this._bakeSprite;
@@ -133,17 +138,17 @@
this.transform(this.getParentRenderCmd(), true);
var boundingBox = this._getBoundingBoxForBake();
- boundingBox.width = 0|(boundingBox.width+0.5);
- boundingBox.height = 0|(boundingBox.height+0.5);
+ boundingBox.width = 0 | (boundingBox.width + 0.5);
+ boundingBox.height = 0 | (boundingBox.height + 0.5);
var bakeContext = locBakeSprite.getCacheContext();
var ctx = bakeContext.getContext();
locBakeSprite.setPosition(boundingBox.x, boundingBox.y);
- if(this._updateCache > 0){
+ if (this._updateCache > 0) {
locBakeSprite.resetCanvasSize(boundingBox.width, boundingBox.height);
- bakeContext.setOffset(0 - boundingBox.x, ctx.canvas.height - boundingBox.height + boundingBox.y );
+ bakeContext.setOffset(0 - boundingBox.x, ctx.canvas.height - boundingBox.height + boundingBox.y);
//visit for canvas
node.sortAllChildren();
cc.renderer._turnToCacheMode(this.__instanceId);
@@ -159,32 +164,12 @@
}
};
- proto.visit = function(parentCmd){
- if(!this._isBaked){
- this.originVisit(parentCmd);
- return;
- }
-
- var node = this._node, children = node._children;
- var len = children.length;
- // quick return if not visible
- if (!node._visible || len === 0)
- return;
-
- this._syncStatus(parentCmd);
- cc.renderer.pushRenderCommand(this);
-
- //the bakeSprite is drawing
- this._bakeSprite.visit(this);
- this._dirtyFlag = 0;
- };
-
- proto._bakeForAddChild = function(child){
- if(child._parent === this._node && this._isBaked)
+ proto._bakeForAddChild = function (child) {
+ if (child._parent === this._node && this._isBaked)
child._renderCmd._setCachedParent(this);
};
- proto._getBoundingBoxForBake = function(){
+ proto._getBoundingBoxForBake = function () {
var rect = null, node = this._node;
//query child's BoundingBox
@@ -196,11 +181,11 @@
for (var i = 0, len = locChildren.length; i < len; i++) {
var child = locChildren[i];
if (child && child._visible) {
- if(rect){
+ if (rect) {
var childRect = child._getBoundingBoxToCurrentNode(trans);
if (childRect)
rect = cc.rectUnion(rect, childRect);
- }else{
+ } else {
rect = child._getBoundingBoxToCurrentNode(trans);
}
}
@@ -212,10 +197,10 @@
/**
* cc.LayerColor's rendering objects of Canvas
*/
-(function(){
+(function () {
//LayerColor's canvas render command
- cc.LayerColor.CanvasRenderCmd = function(renderable){
- cc.Layer.CanvasRenderCmd.call(this, renderable);
+ cc.LayerColor.CanvasRenderCmd = function (renderable) {
+ this._layerCmdCtor(renderable);
this._needDraw = true;
this._blendFuncStr = "source-over";
this._bakeRenderCmd = new cc.CustomRenderCmd(this, this._bakeRendering);
@@ -223,7 +208,7 @@
var proto = cc.LayerColor.CanvasRenderCmd.prototype = Object.create(cc.Layer.CanvasRenderCmd.prototype);
proto.constructor = cc.LayerColor.CanvasRenderCmd;
- proto.unbake = function(){
+ proto.unbake = function () {
cc.Layer.CanvasRenderCmd.prototype.unbake.call(this);
this._needDraw = true;
};
@@ -245,41 +230,41 @@
+ (0 | curColor.b) + ", 1)"); //TODO: need cache the color string
wrapper.setTransform(this._worldTransform, scaleX, scaleY);
- context.fillRect(0, 0, locWidth , -locHeight );
+ context.fillRect(0, 0, locWidth, -locHeight);
cc.g_NumberOfDraws++;
};
- proto.updateBlendFunc = function(blendFunc){
+ proto.updateBlendFunc = function (blendFunc) {
this._blendFuncStr = cc.Node.CanvasRenderCmd._getCompositeOperationByBlendFunc(blendFunc);
};
proto._updateSquareVertices =
proto._updateSquareVerticesWidth =
- proto._updateSquareVerticesHeight = function(){};
+ proto._updateSquareVerticesHeight = function () {};
- proto._bakeRendering = function(){
- if(this._cacheDirty){
+ proto._bakeRendering = function () {
+ if (this._cacheDirty) {
var node = this._node;
var locBakeSprite = this._bakeSprite, children = node._children;
- var len = children.length, i;
+ var i, len = children.length;
//compute the bounding box of the bake layer.
this.transform(this.getParentRenderCmd(), true);
//compute the bounding box of the bake layer.
var boundingBox = this._getBoundingBoxForBake();
- boundingBox.width = 0|(boundingBox.width+0.5);
- boundingBox.height = 0|(boundingBox.height+0.5);
+ boundingBox.width = 0 | (boundingBox.width + 0.5);
+ boundingBox.height = 0 | (boundingBox.height + 0.5);
var bakeContext = locBakeSprite.getCacheContext();
var ctx = bakeContext.getContext();
locBakeSprite.setPosition(boundingBox.x, boundingBox.y);
- if(this._updateCache > 0) {
+ if (this._updateCache > 0) {
ctx.fillStyle = bakeContext._currentFillStyle;
locBakeSprite.resetCanvasSize(boundingBox.width, boundingBox.height);
- bakeContext.setOffset(0 - boundingBox.x, ctx.canvas.height - boundingBox.height + boundingBox.y );
+ bakeContext.setOffset(0 - boundingBox.x, ctx.canvas.height - boundingBox.height + boundingBox.y);
var child;
cc.renderer._turnToCacheMode(this.__instanceId);
@@ -290,13 +275,13 @@
for (i = 0; i < len; i++) {
child = children[i];
if (child._localZOrder < 0)
- child._renderCmd.visit(this);
+ child.visit(node);
else
break;
}
cc.renderer.pushRenderCommand(this);
for (; i < len; i++) {
- children[i]._renderCmd.visit(this);
+ children[i].visit(node);
}
} else
cc.renderer.pushRenderCommand(this);
@@ -308,28 +293,7 @@
}
};
- proto.visit = function(parentCmd){
- if(!this._isBaked){
- this.originVisit();
- return;
- }
-
- var node = this._node;
- // quick return if not visible
- if (!node._visible)
- return;
-
- this._syncStatus(parentCmd);
-
- cc.renderer.pushRenderCommand(this._bakeRenderCmd);
-
- //the bakeSprite is drawing
- this._bakeSprite._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
- this._bakeSprite.visit(this);
- this._dirtyFlag = 0;
- };
-
- proto._getBoundingBoxForBake = function(){
+ proto._getBoundingBoxForBake = function () {
var node = this._node;
//default size
var rect = cc.rect(0, 0, node._contentSize.width, node._contentSize.height);
@@ -355,8 +319,8 @@
/**
* cc.LayerGradient's rendering objects of Canvas
*/
-(function(){
- cc.LayerGradient.CanvasRenderCmd = function(renderable){
+(function () {
+ cc.LayerGradient.CanvasRenderCmd = function (renderable) {
cc.LayerColor.CanvasRenderCmd.call(this, renderable);
this._needDraw = true;
this._startPoint = cc.p(0, 0);
@@ -380,12 +344,12 @@
wrapper.setGlobalAlpha(opacity);
var gradient = context.createLinearGradient(this._startPoint.x, this._startPoint.y, this._endPoint.x, this._endPoint.y);
- if(node._colorStops){ //Should always fall here now
- for(var i=0; i < node._colorStops.length; i++) {
- var stop = node._colorStops[i];
- gradient.addColorStop(stop.p, this._colorStopsStr[i]);
- }
- }else{
+ if (node._colorStops) { //Should always fall here now
+ for (var i = 0; i < node._colorStops.length; i++) {
+ var stop = node._colorStops[i];
+ gradient.addColorStop(stop.p, this._colorStopsStr[i]);
+ }
+ } else {
gradient.addColorStop(0, this._startStopStr);
gradient.addColorStop(1, this._endStopStr);
}
@@ -393,7 +357,7 @@
wrapper.setFillStyle(gradient);
wrapper.setTransform(this._worldTransform, scaleX, scaleY);
- context.fillRect(0, 0, locWidth , -locHeight );
+ context.fillRect(0, 0, locWidth, -locHeight);
cc.g_NumberOfDraws++;
};
@@ -401,31 +365,31 @@
var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
if (locFlag & flags.gradientDirty) {
this._dirtyFlag |= flags.colorDirty;
- this._dirtyFlag = locFlag & flags.gradientDirty ^ locFlag;
+ this._dirtyFlag &= ~flags.gradientDirty;
}
- cc.Node.RenderCmd.prototype.updateStatus.call(this);
+ this.originUpdateStatus();
};
proto._syncStatus = function (parentCmd) {
var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
if (locFlag & flags.gradientDirty) {
this._dirtyFlag |= flags.colorDirty;
- this._dirtyFlag = locFlag & flags.gradientDirty ^ locFlag;
+ this._dirtyFlag &= ~flags.gradientDirty;
}
- cc.Node.RenderCmd.prototype._syncStatus.call(this, parentCmd);
+ this._originSyncStatus(parentCmd);
};
- proto._updateColor = function() {
+ proto._updateColor = function () {
var node = this._node;
var contentSize = node._contentSize;
var tWidth = contentSize.width * 0.5, tHeight = contentSize.height * 0.5;
//fix the bug of gradient layer
var angle = cc.pAngleSigned(cc.p(0, -1), node._alongVector);
- var p1 = cc.pRotateByAngle(cc.p(0, -1), cc.p(0,0), angle);
- var factor = Math.min(Math.abs(1 / p1.x), Math.abs(1/ p1.y));
+ var p1 = cc.pRotateByAngle(cc.p(0, -1), cc.p(0, 0), angle);
+ var factor = Math.min(Math.abs(1 / p1.x), Math.abs(1 / p1.y));
this._startPoint.x = tWidth * (-p1.x * factor) + tWidth;
this._startPoint.y = tHeight * (p1.y * factor) - tHeight;
@@ -433,18 +397,18 @@
this._endPoint.y = tHeight * (-p1.y * factor) - tHeight;
var locStartColor = this._displayedColor, locEndColor = node._endColor;
- var startOpacity = node._startOpacity/255, endOpacity = node._endOpacity/255;
+ var startOpacity = node._startOpacity / 255, endOpacity = node._endOpacity / 255;
this._startStopStr = "rgba(" + Math.round(locStartColor.r) + "," + Math.round(locStartColor.g) + ","
+ Math.round(locStartColor.b) + "," + startOpacity.toFixed(4) + ")";
this._endStopStr = "rgba(" + Math.round(locEndColor.r) + "," + Math.round(locEndColor.g) + ","
+ Math.round(locEndColor.b) + "," + endOpacity.toFixed(4) + ")";
- if( node._colorStops){
+ if (node._colorStops) {
this._startOpacity = 0;
this._endOpacity = 0;
this._colorStopsStr = [];
- for(var i =0; i < node._colorStops.length; i++){
+ for (var i = 0; i < node._colorStops.length; i++) {
var stopColor = node._colorStops[i].color;
var stopOpacity = stopColor.a == null ? 1 : stopColor.a / 255;
this._colorStopsStr.push("rgba(" + Math.round(stopColor.r) + "," + Math.round(stopColor.g) + ","
@@ -452,4 +416,4 @@
}
}
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js
index 8051a50abe..4acf7f22d6 100644
--- a/cocos2d/core/layers/CCLayerWebGLRenderCmd.js
+++ b/cocos2d/core/layers/CCLayerWebGLRenderCmd.js
@@ -31,83 +31,52 @@
/**
* cc.Layer's rendering objects of WebGL
*/
-(function(){
- cc.Layer.WebGLRenderCmd = function(renderable){
- cc.Node.WebGLRenderCmd.call(this, renderable);
+(function () {
+ cc.Layer.WebGLRenderCmd = function (renderable) {
+ this._rootCtor(renderable);
+ this._isBaked = false;
};
var proto = cc.Layer.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
proto.constructor = cc.Layer.WebGLRenderCmd;
+ proto._layerCmdCtor = cc.Layer.WebGLRenderCmd;
- proto.bake = function(){};
+ proto.bake = function () {
+ };
- proto.unbake = function(){};
+ proto.unbake = function () {
+ };
- proto._bakeForAddChild = function(){};
+ proto._bakeForAddChild = function () {
+ };
})();
/**
* cc.LayerColor's rendering objects of WebGL
*/
-(function(){
- cc.LayerColor.WebGLRenderCmd = function(renderable){
- cc.Layer.WebGLRenderCmd.call(this, renderable);
+(function () {
+ var FLOAT_PER_VERTEX = 4;
+
+ cc.LayerColor.WebGLRenderCmd = function (renderable) {
+ this._layerCmdCtor(renderable);
this._needDraw = true;
- this._matrix = new cc.math.Matrix4();
- this._matrix.identity();
-
- //
- var _t = this;
- _t._squareVerticesAB = new ArrayBuffer(48);
- _t._squareColorsAB = new ArrayBuffer(16);
-
- var locSquareVerticesAB = _t._squareVerticesAB, locSquareColorsAB = _t._squareColorsAB;
- var locVertex3FLen = cc.Vertex3F.BYTES_PER_ELEMENT, locColorLen = cc.Color.BYTES_PER_ELEMENT;
- _t._squareVertices = [new cc.Vertex3F(0, 0, 0, locSquareVerticesAB, 0),
- new cc.Vertex3F(0, 0, 0, locSquareVerticesAB, locVertex3FLen),
- new cc.Vertex3F(0, 0, 0, locSquareVerticesAB, locVertex3FLen * 2),
- new cc.Vertex3F(0, 0, 0, locSquareVerticesAB, locVertex3FLen * 3)];
- _t._squareColors = [cc.color(0, 0, 0, 255, locSquareColorsAB, 0),
- cc.color(0, 0, 0, 255, locSquareColorsAB, locColorLen),
- cc.color(0, 0, 0, 255, locSquareColorsAB, locColorLen * 2),
- cc.color(0, 0, 0, 255, locSquareColorsAB, locColorLen * 3)];
- _t._verticesFloat32Buffer = cc._renderContext.createBuffer();
- _t._colorsUint8Buffer = cc._renderContext.createBuffer();
+ this._matrix = null;
+
+ this.initData(4);
+ this._color = new Uint32Array(1);
+ this._vertexBuffer = null;
this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_COLOR);
};
var proto = cc.LayerColor.WebGLRenderCmd.prototype = Object.create(cc.Layer.WebGLRenderCmd.prototype);
proto.constructor = cc.LayerColor.WebGLRenderCmd;
- proto.rendering = function (ctx) {
- var context = ctx || cc._renderContext;
- var node = this._node;
-
- var wt = this._worldTransform;
- this._matrix.mat[0] = wt.a;
- this._matrix.mat[4] = wt.c;
- this._matrix.mat[12] = wt.tx;
- this._matrix.mat[1] = wt.b;
- this._matrix.mat[5] = wt.d;
- this._matrix.mat[13] = wt.ty;
-
- this._shaderProgram.use();
- this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix);
- context.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION);
- context.enableVertexAttribArray(cc.VERTEX_ATTRIB_COLOR);
- cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst);
-
- //
- // Attributes
- //
- context.bindBuffer(context.ARRAY_BUFFER, this._verticesFloat32Buffer);
- context.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, context.FLOAT, false, 0, 0);
-
- context.bindBuffer(context.ARRAY_BUFFER, this._colorsUint8Buffer);
- context.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, context.UNSIGNED_BYTE, true, 0, 0);
-
- context.drawArrays(context.TRIANGLE_STRIP, 0, this._squareVertices.length);
+ proto.initData = function (vertexCount) {
+ this._data = new ArrayBuffer(16 * vertexCount);
+ this._positionView = new Float32Array(this._data);
+ this._colorView = new Uint32Array(this._data);
+ this._dataDirty = true;
};
proto.transform = function (parentCmd, recursive) {
@@ -117,51 +86,80 @@
width = node._contentSize.width,
height = node._contentSize.height;
- var locSquareVertices = this._squareVertices;
- locSquareVertices[1].x = width;
- locSquareVertices[2].y = height;
- locSquareVertices[3].x = width;
- locSquareVertices[3].y = height;
- locSquareVertices[0].z =
- locSquareVertices[1].z =
- locSquareVertices[2].z =
- locSquareVertices[3].z = node._vertexZ;
-
- this._bindLayerVerticesBufferData();
+ var pos = this._positionView;
+ pos[FLOAT_PER_VERTEX] = width; // br.x
+ pos[FLOAT_PER_VERTEX * 2 + 1] = height; // tl.y
+ pos[FLOAT_PER_VERTEX * 3] = width; // tr.x
+ pos[FLOAT_PER_VERTEX * 3 + 1] = height; // tr.y
+ pos[2].z =
+ pos[FLOAT_PER_VERTEX + 2] =
+ pos[FLOAT_PER_VERTEX * 2 + 2] =
+ pos[FLOAT_PER_VERTEX * 3 + 2] = node._vertexZ;
+
+ this._dataDirty = true;
};
- proto._updateColor = function(){
- var locDisplayedColor = this._displayedColor, locDisplayedOpacity = this._displayedOpacity,
- locSquareColors = this._squareColors;
+ proto._updateColor = function () {
+ var color = this._displayedColor;
+ this._color[0] = ((this._displayedOpacity << 24) | (color.b << 16) | (color.g << 8) | color.r);
+
+ var colors = this._colorView;
for (var i = 0; i < 4; i++) {
- locSquareColors[i].r = locDisplayedColor.r;
- locSquareColors[i].g = locDisplayedColor.g;
- locSquareColors[i].b = locDisplayedColor.b;
- locSquareColors[i].a = locDisplayedOpacity;
+ colors[i * FLOAT_PER_VERTEX + 3] = this._color[0];
}
- this._bindLayerColorsBufferData();
+ this._dataDirty = true;
};
- proto._bindLayerVerticesBufferData = function(){
- var glContext = cc._renderContext;
- glContext.bindBuffer(glContext.ARRAY_BUFFER, this._verticesFloat32Buffer);
- glContext.bufferData(glContext.ARRAY_BUFFER, this._squareVerticesAB, glContext.DYNAMIC_DRAW);
- };
+ proto.rendering = function (ctx) {
+ var gl = ctx || cc._renderContext;
+ var node = this._node;
+
+ if (!this._matrix) {
+ this._matrix = new cc.math.Matrix4();
+ this._matrix.identity();
+ }
- proto._bindLayerColorsBufferData = function(){
- var glContext = cc._renderContext;
- glContext.bindBuffer(glContext.ARRAY_BUFFER, this._colorsUint8Buffer);
- glContext.bufferData(glContext.ARRAY_BUFFER, this._squareColorsAB, glContext.STATIC_DRAW);
+ var wt = this._worldTransform;
+ this._matrix.mat[0] = wt.a;
+ this._matrix.mat[4] = wt.c;
+ this._matrix.mat[12] = wt.tx;
+ this._matrix.mat[1] = wt.b;
+ this._matrix.mat[5] = wt.d;
+ this._matrix.mat[13] = wt.ty;
+
+ if (this._dataDirty) {
+ if (!this._vertexBuffer) {
+ this._vertexBuffer = gl.createBuffer();
+ }
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, this._data, gl.DYNAMIC_DRAW);
+ this._dataDirty = false;
+ }
+
+ this._glProgramState.apply(this._matrix);
+ cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst);
+
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
+ gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION);
+ gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_COLOR);
+
+ gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 16, 0);
+ gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 16, 12);
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
};
- proto.updateBlendFunc = function(blendFunc){};
+ proto.updateBlendFunc = function (blendFunc) {
+ };
})();
/**
* cc.LayerGradient's rendering objects of WebGL
*/
-(function(){
- cc.LayerGradient.WebGLRenderCmd = function(renderable){
+(function () {
+ var FLOAT_PER_VERTEX = 4;
+
+ cc.LayerGradient.WebGLRenderCmd = function (renderable) {
cc.LayerColor.WebGLRenderCmd.call(this, renderable);
this._needDraw = true;
this._clipRect = new cc.Rect();
@@ -175,10 +173,10 @@
if (locFlag & flags.gradientDirty) {
this._dirtyFlag |= flags.colorDirty;
this._updateVertex();
- this._dirtyFlag = locFlag & flags.gradientDirty ^ locFlag;
+ this._dirtyFlag &= ~flags.gradientDirty;
}
- cc.Node.RenderCmd.prototype.updateStatus.call(this);
+ this.originUpdateStatus();
};
proto._syncStatus = function (parentCmd) {
@@ -186,10 +184,10 @@
if (locFlag & flags.gradientDirty) {
this._dirtyFlag |= flags.colorDirty;
this._updateVertex();
- this._dirtyFlag = locFlag & flags.gradientDirty ^ locFlag;
+ this._dirtyFlag &= ~flags.gradientDirty;
}
- cc.Node.RenderCmd.prototype._syncStatus.call(this, parentCmd);
+ this._originSyncStatus(parentCmd);
};
proto.transform = function (parentCmd, recursive) {
@@ -199,35 +197,28 @@
proto._updateVertex = function () {
var node = this._node, stops = node._colorStops;
- if(!stops || stops.length < 2)
+ if (!stops || stops.length < 2)
return;
this._clippingRectDirty = true;
- var stopsLen = stops.length, verticesLen = stopsLen * 2, i, contentSize = node._contentSize;
- var locVertices = this._squareVertices;
- if (locVertices.length < verticesLen) {
- this._squareVerticesAB = new ArrayBuffer(verticesLen * 12);
- locVertices.length = 0;
- var locSquareVerticesAB = this._squareVerticesAB;
- var locVertex3FLen = cc.Vertex3F.BYTES_PER_ELEMENT;
- for(i = 0; i < verticesLen; i++){
- locVertices.push(new cc.Vertex3F(0, 0, 0, locSquareVerticesAB, locVertex3FLen * i));
- }
+ var i, stopsLen = stops.length, verticesLen = stopsLen * 2, contentSize = node._contentSize;
+ if (this._positionView.length / FLOAT_PER_VERTEX < verticesLen) {
+ this.initData(verticesLen);
}
//init vertex
- var angle = Math.PI + cc.pAngleSigned(cc.p(0, -1), node._alongVector), locAnchor = cc.p(contentSize.width/2, contentSize.height /2);
+ var angle = Math.PI + cc.pAngleSigned(cc.p(0, -1), node._alongVector), locAnchor = cc.p(contentSize.width / 2, contentSize.height / 2);
var degrees = Math.round(cc.radiansToDegrees(angle));
var transMat = cc.affineTransformMake(1, 0, 0, 1, locAnchor.x, locAnchor.y);
transMat = cc.affineTransformRotate(transMat, angle);
var a, b;
- if(degrees < 90) {
+ if (degrees < 90) {
a = cc.p(-locAnchor.x, locAnchor.y);
b = cc.p(locAnchor.x, locAnchor.y);
- } else if(degrees < 180) {
+ } else if (degrees < 180) {
a = cc.p(locAnchor.x, locAnchor.y);
b = cc.p(locAnchor.x, -locAnchor.y);
- } else if(degrees < 270) {
+ } else if (degrees < 270) {
a = cc.p(locAnchor.x, -locAnchor.y);
b = cc.p(-locAnchor.x, -locAnchor.y);
} else {
@@ -236,60 +227,56 @@
}
var sin = Math.sin(angle), cos = Math.cos(angle);
- var tx = Math.abs((a.x * cos - a.y * sin)/locAnchor.x), ty = Math.abs((b.x * sin + b.y * cos)/locAnchor.y);
+ var tx = Math.abs((a.x * cos - a.y * sin) / locAnchor.x), ty = Math.abs((b.x * sin + b.y * cos) / locAnchor.y);
transMat = cc.affineTransformScale(transMat, tx, ty);
+ var pos = this._positionView;
for (i = 0; i < stopsLen; i++) {
- var stop = stops[i], y = stop.p * contentSize.height ;
- var p0 = cc.pointApplyAffineTransform(- locAnchor.x , y - locAnchor.y, transMat);
- locVertices[i * 2].x = p0.x;
- locVertices[i * 2].y = p0.y;
- locVertices[i * 2].z = node._vertexZ;
+ var stop = stops[i], y = stop.p * contentSize.height;
+ var p0 = cc.pointApplyAffineTransform(-locAnchor.x, y - locAnchor.y, transMat);
+ var offset = i * 2 * FLOAT_PER_VERTEX;
+ pos[offset] = p0.x;
+ pos[offset + 1] = p0.y;
+ pos[offset + 2] = node._vertexZ;
var p1 = cc.pointApplyAffineTransform(contentSize.width - locAnchor.x, y - locAnchor.y, transMat);
- locVertices[i * 2 + 1].x = p1.x;
- locVertices[i * 2 + 1].y = p1.y;
- locVertices[i * 2 + 1].z = node._vertexZ;
+ offset += FLOAT_PER_VERTEX;
+ pos[offset] = p1.x;
+ pos[offset + 1] = p1.y;
+ pos[offset + 2] = node._vertexZ;
}
- this._bindLayerVerticesBufferData();
+ this._dataDirty = true;
};
- proto._updateColor = function() {
+ proto._updateColor = function () {
var node = this._node, stops = node._colorStops;
- if(!stops || stops.length < 2)
+ if (!stops || stops.length < 2)
return;
- //init color
- var stopsLen = stops.length;
- var locColors = this._squareColors, verticesLen = stopsLen * 2;
- if (locColors.length < verticesLen) {
- this._squareColorsAB = new ArrayBuffer(verticesLen * 4);
- locColors.length = 0;
- var locSquareColorsAB = this._squareColorsAB;
- var locColorLen = cc.Color.BYTES_PER_ELEMENT;
- for(i = 0; i < verticesLen; i++){
- locColors.push(cc.color(0, 0, 0, 255, locSquareColorsAB, locColorLen * i));
- }
- }
-
- var opacityf = this._displayedOpacity / 255.0; //, displayColor = this._displayedColor;
- for(i = 0; i < stopsLen; i++){
- var stopColor = stops[i].color, locSquareColor0 = locColors[i * 2], locSquareColor1 = locColors[i * 2 + 1];
- locSquareColor0.r = stopColor.r;
- locSquareColor0.g = stopColor.g;
- locSquareColor0.b = stopColor.b;
- locSquareColor0.a = stopColor.a * opacityf;
-
- locSquareColor1.r = stopColor.r;
- locSquareColor1.g = stopColor.g;
- locSquareColor1.b = stopColor.b;
- locSquareColor1.a = stopColor.a * opacityf;
+ var stopsLen = stops.length,
+ stopColor,
+ offset,
+ colors = this._colorView,
+ opacityf = this._displayedOpacity / 255;
+ for (i = 0; i < stopsLen; i++) {
+ stopColor = stops[i].color;
+ this._color[0] = ((stopColor.a*opacityf) << 24) | (stopColor.b << 16) | (stopColor.g << 8) | stopColor.r;
+
+ offset = i * 2 * FLOAT_PER_VERTEX;
+ colors[offset + 3] = this._color[0];
+ offset += FLOAT_PER_VERTEX;
+ colors[offset + 3] = this._color[0];
}
- this._bindLayerColorsBufferData();
+ this._dataDirty = true;
};
proto.rendering = function (ctx) {
var context = ctx || cc._renderContext, node = this._node;
+ if (!this._matrix) {
+ this._matrix = new cc.math.Matrix4();
+ this._matrix.identity();
+ }
+
//it is too expensive to use stencil to clip, so it use Scissor,
//but it has a bug when layer rotated and layer's content size less than canvas's size.
var clippingRect = this._getClippingRect();
@@ -304,26 +291,33 @@
this._matrix.mat[5] = wt.d;
this._matrix.mat[13] = wt.ty;
+ if (this._dataDirty) {
+ if (!this._vertexBuffer) {
+ this._vertexBuffer = gl.createBuffer();
+ }
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, this._data, gl.DYNAMIC_DRAW);
+ this._dataDirty = false;
+ }
+
//draw gradient layer
- this._shaderProgram.use();
- this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix);
- context.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION);
- context.enableVertexAttribArray(cc.VERTEX_ATTRIB_COLOR);
+ this._glProgramState.apply(this._matrix);
cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst);
- //
- // Attributes
- //
- context.bindBuffer(context.ARRAY_BUFFER, this._verticesFloat32Buffer);
- context.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, context.FLOAT, false, 0, 0);
- context.bindBuffer(context.ARRAY_BUFFER, this._colorsUint8Buffer);
- context.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, context.UNSIGNED_BYTE, true, 0, 0);
- context.drawArrays(context.TRIANGLE_STRIP, 0, this._squareVertices.length);
+
+ gl.bindBuffer(gl.ARRAY_BUFFER, this._vertexBuffer);
+ gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_POSITION);
+ gl.enableVertexAttribArray(cc.VERTEX_ATTRIB_COLOR);
+
+ gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 16, 0);
+ gl.vertexAttribPointer(cc.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 16, 12);
+
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
context.disable(context.SCISSOR_TEST);
};
- proto._getClippingRect = function(){
- if(this._clippingRectDirty){
+ proto._getClippingRect = function () {
+ if (this._clippingRectDirty) {
var node = this._node;
var rect = cc.rect(0, 0, node._contentSize.width, node._contentSize.height);
var trans = node.getNodeToWorldTransform();
@@ -331,4 +325,4 @@
}
return this._clipRect;
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/core/platform/CCClass.js b/cocos2d/core/platform/CCClass.js
index e5d5ca1b81..be34ad92eb 100644
--- a/cocos2d/core/platform/CCClass.js
+++ b/cocos2d/core/platform/CCClass.js
@@ -27,23 +27,133 @@
var cc = cc || {};
/**
- * @namespace
- * @name ClassManager
+ * Common getter setter configuration function
+ * @function
+ * @param {Object} proto A class prototype or an object to config
+ * @param {String} prop Property name
+ * @param {function} getter Getter function for the property
+ * @param {function} setter Setter function for the property
+ * @param {String} getterName Name of getter function for the property
+ * @param {String} setterName Name of setter function for the property
*/
-var ClassManager = {
- id : (0|(Math.random()*998)),
+cc.defineGetterSetter = function (proto, prop, getter, setter, getterName, setterName) {
+ if (proto.__defineGetter__) {
+ getter && proto.__defineGetter__(prop, getter);
+ setter && proto.__defineSetter__(prop, setter);
+ } else if (Object.defineProperty) {
+ var desc = {enumerable: false, configurable: true};
+ getter && (desc.get = getter);
+ setter && (desc.set = setter);
+ Object.defineProperty(proto, prop, desc);
+ } else {
+ throw new Error("browser does not support getters");
+ }
+
+ if (!getterName && !setterName) {
+ // Lookup getter/setter function
+ var hasGetter = (getter != null), hasSetter = (setter != undefined), props = Object.getOwnPropertyNames(proto);
+ for (var i = 0; i < props.length; i++) {
+ var name = props[i];
+
+ if ((proto.__lookupGetter__ ? proto.__lookupGetter__(name)
+ : Object.getOwnPropertyDescriptor(proto, name))
+ || typeof proto[name] !== "function")
+ continue;
- instanceId : (0|(Math.random()*998)),
+ var func = proto[name];
+ if (hasGetter && func === getter) {
+ getterName = name;
+ if (!hasSetter || setterName) break;
+ }
+ if (hasSetter && func === setter) {
+ setterName = name;
+ if (!hasGetter || getterName) break;
+ }
+ }
+ }
+
+ // Found getter/setter
+ var ctor = proto.constructor;
+ if (getterName) {
+ if (!ctor.__getters__) {
+ ctor.__getters__ = {};
+ }
+ ctor.__getters__[getterName] = prop;
+ }
+ if (setterName) {
+ if (!ctor.__setters__) {
+ ctor.__setters__ = {};
+ }
+ ctor.__setters__[setterName] = prop;
+ }
+};
- getNewID : function(){
- return this.id++;
- },
+/**
+ * Create a new object and copy all properties in an exist object to the new object
+ * @function
+ * @param {object|Array} obj The source object
+ * @return {Array|object} The created object
+ */
+cc.clone = function (obj) {
+ // Cloning is better if the new object is having the same prototype chain
+ // as the copied obj (or otherwise, the cloned object is certainly going to
+ // have a different hidden class). Play with C1/C2 of the
+ // PerformanceVirtualMachineTests suite to see how this makes an impact
+ // under extreme conditions.
+ //
+ // Object.create(Object.getPrototypeOf(obj)) doesn't work well because the
+ // prototype lacks a link to the constructor (Carakan, V8) so the new
+ // object wouldn't have the hidden class that's associated with the
+ // constructor (also, for whatever reasons, utilizing
+ // Object.create(Object.getPrototypeOf(obj)) + Object.defineProperty is even
+ // slower than the original in V8). Therefore, we call the constructor, but
+ // there is a big caveat - it is possible that the this.init() in the
+ // constructor would throw with no argument. It is also possible that a
+ // derived class forgets to set "constructor" on the prototype. We ignore
+ // these possibities for and the ultimate solution is a standardized
+ // Object.clone(
* @param {cc.Rect} rect
*/
- setVertexRect:function (rect) {
+ setVertexRect: function (rect) {
var locRect = this._rect;
locRect.x = rect.x;
locRect.y = rect.y;
@@ -299,109 +297,15 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
},
- /**
- * Sort all children of this sprite node.
- * @override
- */
- sortAllChildren:function () {
- if (this._reorderChildDirty) {
- var _children = this._children;
-
- cc.Node.prototype.sortAllChildren.call(this);
-
- if (this._batchNode) {
- this._arrayMakeObjectsPerformSelector(_children, cc.Node._stateCallbackType.sortAllChildren);
- }
-
- //don't need to check children recursively, that's done in visit of each child
- 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, cc._LogInfos.Sprite_reorderChild_2);
- if(this._children.indexOf(child) === -1){
- cc.log(cc._LogInfos.Sprite_reorderChild);
- return;
- }
-
- if (zOrder === child.zIndex)
- 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.
- * @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);
- },
-
- /**
- * Sets whether the sprite is visible or not.
- * @param {Boolean} visible
- * @override
- */
- setVisible:function (visible) {
- cc.Node.prototype.setVisible.call(this, visible);
- this._renderCmd.setDirtyRecursively(true);
- },
-
- /**
- * Removes all children from the container.
- * @param cleanup whether or not cleanup all running actions
- * @override
- */
- removeAllChildren:function (cleanup) {
- 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
//
- /**
- * Sets whether ignore anchor point for positioning
- * @param {Boolean} relative
- * @override
- */
- ignoreAnchorPointForPosition:function (relative) {
- if(this._batchNode){
- cc.log(cc._LogInfos.Sprite_ignoreAnchorPointForPosition);
- return;
- }
- cc.Node.prototype.ignoreAnchorPointForPosition.call(this, relative);
- },
-
/**
* Sets whether the sprite should be flipped horizontally or not.
* @param {Boolean} flippedX true if the sprite should be flipped horizontally, false otherwise.
*/
- setFlippedX:function (flippedX) {
+ setFlippedX: function (flippedX) {
if (this._flippedX !== flippedX) {
this._flippedX = flippedX;
this.setTextureRect(this._rect, this._rectRotated, this._contentSize);
@@ -413,7 +317,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Sets whether the sprite should be flipped vertically or not.
* @param {Boolean} flippedY true if the sprite should be flipped vertically, false otherwise.
*/
- setFlippedY:function (flippedY) {
+ setFlippedY: function (flippedY) {
if (this._flippedY !== flippedY) {
this._flippedY = flippedY;
this.setTextureRect(this._rect, this._rectRotated, this._contentSize);
@@ -431,7 +335,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* sprite.setScaleX(sprite.getScaleX() * -1);
* @return {Boolean} true if the sprite is flipped horizontally, false otherwise.
*/
- isFlippedX:function () {
+ isFlippedX: function () {
return this._flippedX;
},
@@ -445,7 +349,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* sprite.setScaleY(sprite.getScaleY() * -1);
* @return {Boolean} true if the sprite is flipped vertically, false otherwise.
*/
- isFlippedY:function () {
+ isFlippedY: function () {
return this._flippedY;
},
@@ -468,7 +372,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Returns whether opacity modify color or not.
* @return {Boolean}
*/
- isOpacityModifyRGB:function () {
+ isOpacityModifyRGB: function () {
return this._opacityModifyRGB;
},
@@ -480,16 +384,16 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* @param {String} animationName
* @param {Number} frameIndex
*/
- setDisplayFrameWithAnimationName:function (animationName, frameIndex) {
+ setDisplayFrameWithAnimationName: function (animationName, frameIndex) {
cc.assert(animationName, cc._LogInfos.Sprite_setDisplayFrameWithAnimationName_3);
var cache = cc.animationCache.getAnimation(animationName);
- if(!cache){
+ if (!cache) {
cc.log(cc._LogInfos.Sprite_setDisplayFrameWithAnimationName);
return;
}
var animFrame = cache.getFrames()[frameIndex];
- if(!animFrame){
+ if (!animFrame) {
cc.log(cc._LogInfos.Sprite_setDisplayFrameWithAnimationName_2);
return;
}
@@ -500,35 +404,23 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Returns the batch node object if this sprite is rendered by cc.SpriteBatchNode
* @returns {cc.SpriteBatchNode|null} The cc.SpriteBatchNode object if this sprite is rendered by cc.SpriteBatchNode, null if the sprite isn't used batch node.
*/
- getBatchNode:function () {
+ getBatchNode: function () {
return this._batchNode;
},
- _setReorderChildDirtyRecursively:function () {
- //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.parent;
- }
- }
- },
-
// CCTextureProtocol
/**
* Returns the texture of the sprite node
* @returns {cc.Texture2D}
*/
- getTexture:function () {
+ getTexture: function () {
return this._texture;
},
_softInit: function (fileName, rect, rotated) {
if (fileName === undefined)
cc.Sprite.prototype.init.call(this);
- else if (cc.isString(fileName)) {
+ else if (typeof fileName === 'string') {
if (fileName[0] === "#") {
// Init with a sprite frame name
var frameName = fileName.substr(1, fileName.length - 1);
@@ -562,7 +454,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* Returns the quad (tex coords, vertex coords and color) information.
* @return {cc.V3F_C4B_T2F_Quad|null} Returns a cc.V3F_C4B_T2F_Quad object when render mode is WebGL, returns null when render mode is Canvas.
*/
- getQuad:function () {
+ getQuad: function () {
return null;
},
@@ -632,7 +524,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* @param {cc.Rect} rect The rectangle assigned the content area from texture.
* @return {Boolean} true if the sprite is initialized properly, false otherwise.
*/
- initWithFile:function (filename, rect) {
+ initWithFile: function (filename, rect) {
cc.assert(filename, cc._LogInfos.Sprite_initWithFile);
var tex = cc.textureCache.getTextureForKey(filename);
@@ -768,7 +660,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
if (tag == null)
tag = child.tag;
- if(this._renderCmd._setBatchNodeForAddChild(child)){
+ if (this._renderCmd._setBatchNodeForAddChild(child)) {
//cc.Node already sets isReorderChildDirty_ so this needs to be after batchNode check
cc.Node.prototype.addChild.call(this, child, localZOrder, tag);
this._hasChildren = true;
@@ -783,9 +675,9 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
*/
setSpriteFrame: function (newFrame) {
var _t = this;
- if(cc.isString(newFrame)){
+ if (typeof newFrame === 'string') {
newFrame = cc.spriteFrameCache.getSpriteFrame(newFrame);
- cc.assert(newFrame, cc._LogInfos.Sprite_setSpriteFrame)
+ cc.assert(newFrame, cc._LogInfos.Sprite_setSpriteFrame);
}
this._loader.clear();
@@ -819,7 +711,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* @param {cc.SpriteFrame|String} newFrame
* @deprecated
*/
- setDisplayFrame: function(newFrame){
+ setDisplayFrame: function (newFrame) {
cc.log(cc._LogInfos.Sprite_setDisplayFrame);
this.setSpriteFrame(newFrame);
},
@@ -830,7 +722,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* @param {cc.SpriteFrame} frame
* @return {Boolean}
*/
- isFrameDisplayed: function(frame){
+ isFrameDisplayed: function (frame) {
return this._renderCmd.isFrameDisplayed(frame);
},
@@ -865,21 +757,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* batch.addChild(sprite);
* layer.addChild(batch);
*/
- setBatchNode:function (spriteBatchNode) {
- var _t = this;
- _t._batchNode = spriteBatchNode; // weak reference
-
- // self render
- if (!_t._batchNode) {
- _t.atlasIndex = cc.Sprite.INDEX_NOT_INITIALIZED;
- _t.textureAtlas = null;
- _t._recursiveDirty = false;
- _t.dirty = false;
- } else {
- // using batch
- _t._transformToBatch = cc.affineTransformIdentity();
- _t.textureAtlas = _t._batchNode.getTextureAtlas(); // weak ref
- }
+ setBatchNode: function (spriteBatchNode) {
},
// CCTextureProtocol
@@ -889,13 +767,13 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
* @param {cc.Texture2D|String} texture
*/
setTexture: function (texture) {
- if(!texture)
+ if (!texture)
return this._renderCmd._setTexture(null);
//CCSprite.cpp 327 and 338
- var isFileName = cc.isString(texture);
+ var isFileName = (typeof texture === 'string');
- if(isFileName)
+ if (isFileName)
texture = cc.textureCache.addImage(texture);
this._loader.clear();
@@ -915,7 +793,7 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
this._textureLoaded = true;
},
- _changeRectWithTexture: function(texture){
+ _changeRectWithTexture: function (texture) {
var contentSize = texture._contentSize;
var rect = cc.rect(
0, 0,
@@ -924,8 +802,8 @@ cc.Sprite = cc.Node.extend(/** @lends cc.Sprite# */{
this.setTextureRect(rect);
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return new cc.Sprite.CanvasRenderCmd(this);
else
return new cc.Sprite.WebGLRenderCmd(this);
@@ -1011,4 +889,4 @@ delete cc._tmp.PrototypeSprite;
item.source.removeEventListener('load', item.listener, item.target);
}
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/core/sprites/CCSpriteBatchNode.js b/cocos2d/core/sprites/CCSpriteBatchNode.js
index d8044af074..3abd61fb4c 100644
--- a/cocos2d/core/sprites/CCSpriteBatchNode.js
+++ b/cocos2d/core/sprites/CCSpriteBatchNode.js
@@ -69,7 +69,7 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{
texture2D = cc.textureCache.getTextureForKey(fileImage);
if (!texture2D)
texture2D = cc.textureCache.addImage(fileImage);
- }else if (fileImage instanceof cc.Texture2D)
+ } else if (fileImage instanceof cc.Texture2D)
texture2D = fileImage;
texture2D && this.initWithTexture(texture2D);
@@ -105,7 +105,8 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{
* @param {cc.TextureAtlas} textureAtlas
* @deprecated since v3.12
*/
- setTextureAtlas: function (textureAtlas) {},
+ setTextureAtlas: function (textureAtlas) {
+ },
/**
* Return Descendants of cc.SpriteBatchNode
@@ -156,7 +157,8 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{
* Do nothing
* @deprecated since v3.12
*/
- increaseAtlasCapacity: function () {},
+ increaseAtlasCapacity: function () {
+ },
/**
* Removes a child given a certain index. It will also cleanup the running actions depending on the cleanup parameter.
@@ -243,7 +245,7 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{
* @return {cc.BlendFunc}
*/
getBlendFunc: function () {
- return new cc.BlendFunc(this._blendFunc.src,this._blendFunc.dst);
+ return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst);
},
/**
@@ -301,8 +303,8 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{
*/
appendChild: function (sprite) {
this.sortAllChildren();
- var lastLocalZOrder = this._children[this._children.length-1]._localZOrder;
- this.addChild(sprite. lastLocalZOrder + 1);
+ var lastLocalZOrder = this._children[this._children.length - 1]._localZOrder;
+ this.addChild(sprite.lastLocalZOrder + 1);
},
/**
@@ -342,18 +344,18 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{
* @function
* @param {cc.Texture2D} texture
*/
- setTexture: function(texture){
+ setTexture: function (texture) {
this._texture = texture;
if (texture._textureLoaded) {
- var children = this._children, i, len = children.length;
+ var i, children = this._children, len = children.length;
for (i = 0; i < len; ++i) {
children[i].setTexture(texture);
}
}
else {
- texture.addEventListener("load", function(){
- var children = this._children, i, len = children.length;
+ texture.addEventListener("load", function () {
+ var i, children = this._children, len = children.length;
for (i = 0; i < len; ++i) {
children[i].setTexture(texture);
}
@@ -363,7 +365,7 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{
setShaderProgram: function (newShaderProgram) {
this._renderCmd.setShaderProgram(newShaderProgram);
- var children = this._children, i, len = children.length;
+ var i, children = this._children, len = children.length;
for (i = 0; i < len; ++i) {
children[i].setShaderProgram(newShaderProgram);
}
@@ -380,7 +382,7 @@ cc.SpriteBatchNode = cc.Node.extend(/** @lends cc.SpriteBatchNode# */{
addChild: function (child, zOrder, tag) {
cc.assert(child !== undefined, cc._LogInfos.CCSpriteBatchNode_addChild_3);
- if(!this._isValidChild(child))
+ if (!this._isValidChild(child))
return;
zOrder = (zOrder === undefined) ? child.zIndex : zOrder;
diff --git a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js
index ba289bfcf1..87da2606e5 100644
--- a/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js
+++ b/cocos2d/core/sprites/CCSpriteCanvasRenderCmd.js
@@ -22,9 +22,9 @@
THE SOFTWARE.
****************************************************************************/
-(function() {
+(function () {
cc.Sprite.CanvasRenderCmd = function (renderable) {
- cc.Node.CanvasRenderCmd.call(this, renderable);
+ this._rootCtor(renderable);
this._needDraw = true;
this._textureCoord = {
renderX: 0, //the x of texture coordinate for render, when texture tinted, its value doesn't equal x.
@@ -43,18 +43,20 @@
var proto = cc.Sprite.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
proto.constructor = cc.Sprite.CanvasRenderCmd;
+ proto._spriteCmdCtor = cc.Sprite.CanvasRenderCmd;
- proto.setDirtyRecursively = function (value) {};
+ proto.setDirtyRecursively = function (value) {
+ };
proto._setTexture = function (texture) {
var node = this._node;
if (node._texture !== texture) {
- if (texture) {
- node._textureLoaded = texture._textureLoaded;
- }else{
- node._textureLoaded = false;
- }
+ node._textureLoaded = texture ? texture._textureLoaded : false;
node._texture = texture;
+
+ var texSize = texture._contentSize;
+ var rect = cc.rect(0, 0, texSize.width, texSize.height);
+ node.setTextureRect(rect);
this._updateColor();
}
};
@@ -107,7 +109,7 @@
var locTextureCoord = this._textureCoord, alpha = (this._displayedOpacity / 255);
var texture = this._textureToRender || node._texture;
- if ((texture && (locTextureCoord.width === 0 || locTextureCoord.height === 0|| !texture._textureLoaded)) || alpha === 0)
+ if ((texture && (locTextureCoord.width === 0 || locTextureCoord.height === 0 || !texture._textureLoaded)) || alpha === 0)
return;
var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
@@ -118,7 +120,7 @@
wrapper.setCompositeOperation(this._blendFuncStr);
wrapper.setGlobalAlpha(alpha);
- if(node._flippedX || node._flippedY)
+ if (node._flippedX || node._flippedY)
wrapper.save();
if (node._flippedX) {
locX = -locX - locWidth;
@@ -133,7 +135,7 @@
if (this._colorized) {
sx = 0;
sy = 0;
- }else{
+ } else {
sx = locTextureCoord.renderX;
sy = locTextureCoord.renderY;
}
@@ -163,22 +165,22 @@
context.fillRect(x, y, contentSize.width * scaleX, contentSize.height * scaleY);
}
}
- if(node._flippedX || node._flippedY)
+ if (node._flippedX || node._flippedY)
wrapper.restore();
cc.g_NumberOfDraws++;
};
- proto._updateColor = function(){
+ proto._updateColor = function () {
var node = this._node;
var texture = node._texture, rect = this._textureCoord;
var dColor = this._displayedColor;
- if(texture){
- if(dColor.r !== 255 || dColor.g !== 255 || dColor.b !== 255){
+ if (texture) {
+ if (dColor.r !== 255 || dColor.g !== 255 || dColor.b !== 255) {
this._textureToRender = texture._generateColorTexture(dColor.r, dColor.g, dColor.b, rect);
this._colorized = true;
- }else if(texture){
+ } else if (texture) {
this._textureToRender = texture;
this._colorized = false;
}
@@ -232,14 +234,14 @@
if (!rect)
return texture;
- counterclockwise = counterclockwise == null? true: counterclockwise; // texture package is counterclockwise, spine is clockwise
+ counterclockwise = counterclockwise == null ? true : counterclockwise; // texture package is counterclockwise, spine is clockwise
var nCanvas = document.createElement("canvas");
nCanvas.width = rect.width;
nCanvas.height = rect.height;
var ctx = nCanvas.getContext("2d");
ctx.translate(nCanvas.width / 2, nCanvas.height / 2);
- if(counterclockwise)
+ if (counterclockwise)
ctx.rotate(-1.5707963267948966);
else
ctx.rotate(1.5707963267948966);
diff --git a/cocos2d/core/sprites/CCSpriteFrame.js b/cocos2d/core/sprites/CCSpriteFrame.js
index ccb7f9a86e..4879225a53 100644
--- a/cocos2d/core/sprites/CCSpriteFrame.js
+++ b/cocos2d/core/sprites/CCSpriteFrame.js
@@ -52,18 +52,18 @@
* var frame2 = new cc.SpriteFrame(texture, cc.rect(0,0,90,128),false,0,cc.size(90,128));
*/
cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
- _offset:null,
- _originalSize:null,
- _rectInPixels:null,
- _rotated:false,
- _rect:null,
- _offsetInPixels:null,
- _originalSizeInPixels:null,
- _texture:null,
- _textureFilename:"",
- _textureLoaded:false,
-
- ctor:function (filename, rect, rotated, offset, originalSize) {
+ _offset: null,
+ _originalSize: null,
+ _rectInPixels: null,
+ _rotated: false,
+ _rect: null,
+ _offsetInPixels: null,
+ _originalSizeInPixels: null,
+ _texture: null,
+ _textureFilename: "",
+ _textureLoaded: false,
+
+ ctor: function (filename, rect, rotated, offset, originalSize) {
this._offset = cc.p(0, 0);
this._offsetInPixels = cc.p(0, 0);
this._originalSize = cc.size(0, 0);
@@ -73,11 +73,11 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
this._texture = null;
this._textureLoaded = false;
- if(filename !== undefined && rect !== undefined ){
- if(rotated === undefined || offset === undefined || originalSize === undefined)
+ if (filename !== undefined && rect !== undefined) {
+ if (rotated === undefined || offset === undefined || originalSize === undefined)
this.initWithTexture(filename, rect);
else
- this.initWithTexture(filename, rect, rotated, offset, originalSize)
+ this.initWithTexture(filename, rect, rotated, offset, originalSize);
}
},
@@ -85,7 +85,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Returns whether the texture have been loaded
* @returns {boolean}
*/
- textureLoaded:function(){
+ textureLoaded: function () {
return this._textureLoaded;
},
@@ -95,7 +95,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* @param {Object} target
* @deprecated since 3.1, please use addEventListener instead
*/
- addLoadedEventListener:function(callback, target){
+ addLoadedEventListener: function (callback, target) {
this.addEventListener("load", callback, target);
},
@@ -103,7 +103,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Gets the rect of the frame in the texture
* @return {cc.Rect}
*/
- getRectInPixels:function () {
+ getRectInPixels: function () {
var locRectInPixels = this._rectInPixels;
return cc.rect(locRectInPixels.x, locRectInPixels.y, locRectInPixels.width, locRectInPixels.height);
},
@@ -112,9 +112,9 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Sets the rect of the frame in the texture
* @param {cc.Rect} rectInPixels
*/
- setRectInPixels:function (rectInPixels) {
- if (!this._rectInPixels){
- this._rectInPixels = cc.rect(0,0,0,0);
+ setRectInPixels: function (rectInPixels) {
+ if (!this._rectInPixels) {
+ this._rectInPixels = cc.rect(0, 0, 0, 0);
}
this._rectInPixels.x = rectInPixels.x;
this._rectInPixels.y = rectInPixels.y;
@@ -127,7 +127,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Returns whether the sprite frame is rotated in the texture.
* @return {Boolean}
*/
- isRotated:function () {
+ isRotated: function () {
return this._rotated;
},
@@ -135,7 +135,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Set whether the sprite frame is rotated in the texture.
* @param {Boolean} bRotated
*/
- setRotated:function (bRotated) {
+ setRotated: function (bRotated) {
this._rotated = bRotated;
},
@@ -143,7 +143,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Returns the rect of the sprite frame in the texture
* @return {cc.Rect}
*/
- getRect:function () {
+ getRect: function () {
var locRect = this._rect;
return cc.rect(locRect.x, locRect.y, locRect.width, locRect.height);
},
@@ -152,9 +152,9 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Sets the rect of the sprite frame in the texture
* @param {cc.Rect} rect
*/
- setRect:function (rect) {
- if (!this._rect){
- this._rect = cc.rect(0,0,0,0);
+ setRect: function (rect) {
+ if (!this._rect) {
+ this._rect = cc.rect(0, 0, 0, 0);
}
this._rect.x = rect.x;
this._rect.y = rect.y;
@@ -167,7 +167,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Returns the offset of the sprite frame in the texture in pixel
* @return {cc.Point}
*/
- getOffsetInPixels:function () {
+ getOffsetInPixels: function () {
return cc.p(this._offsetInPixels);
},
@@ -175,7 +175,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Sets the offset of the sprite frame in the texture in pixel
* @param {cc.Point} offsetInPixels
*/
- setOffsetInPixels:function (offsetInPixels) {
+ setOffsetInPixels: function (offsetInPixels) {
this._offsetInPixels.x = offsetInPixels.x;
this._offsetInPixels.y = offsetInPixels.y;
cc._pointPixelsToPointsOut(this._offsetInPixels, this._offset);
@@ -185,7 +185,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Returns the original size of the trimmed image
* @return {cc.Size}
*/
- getOriginalSizeInPixels:function () {
+ getOriginalSizeInPixels: function () {
return cc.size(this._originalSizeInPixels);
},
@@ -193,7 +193,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Sets the original size of the trimmed image
* @param {cc.Size} sizeInPixels
*/
- setOriginalSizeInPixels:function (sizeInPixels) {
+ setOriginalSizeInPixels: function (sizeInPixels) {
this._originalSizeInPixels.width = sizeInPixels.width;
this._originalSizeInPixels.height = sizeInPixels.height;
},
@@ -202,7 +202,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Returns the original size of the trimmed image
* @return {cc.Size}
*/
- getOriginalSize:function () {
+ getOriginalSize: function () {
return cc.size(this._originalSize);
},
@@ -210,7 +210,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Sets the original size of the trimmed image
* @param {cc.Size} sizeInPixels
*/
- setOriginalSize:function (sizeInPixels) {
+ setOriginalSize: function (sizeInPixels) {
this._originalSize.width = sizeInPixels.width;
this._originalSize.height = sizeInPixels.height;
},
@@ -219,7 +219,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Returns the texture of the frame
* @return {cc.Texture2D}
*/
- getTexture:function () {
+ getTexture: function () {
if (this._texture)
return this._texture;
if (this._textureFilename !== "") {
@@ -235,15 +235,15 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Sets the texture of the frame, the texture is retained automatically
* @param {cc.Texture2D} texture
*/
- setTexture:function (texture) {
+ setTexture: function (texture) {
if (this._texture !== texture) {
var locLoaded = texture.isLoaded();
this._textureLoaded = locLoaded;
this._texture = texture;
- if(!locLoaded){
- texture.addEventListener("load", function(sender){
+ if (!locLoaded) {
+ texture.addEventListener("load", function (sender) {
this._textureLoaded = true;
- if(this._rotated && cc._renderType === cc.game.RENDER_TYPE_CANVAS){
+ if (this._rotated && cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
var tempElement = sender.getHtmlElementObj();
tempElement = cc.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, this.getRect());
var tempTexture = new cc.Texture2D();
@@ -255,15 +255,15 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
this.setRect(cc.rect(0, 0, rect.width, rect.height));
}
var locRect = this._rect;
- if(locRect.width === 0 && locRect.height === 0){
+ if (locRect.width === 0 && locRect.height === 0) {
var w = sender.width, h = sender.height;
this._rect.width = w;
this._rect.height = h;
this._rectInPixels = cc.rectPointsToPixels(this._rect);
this._originalSizeInPixels.width = this._rectInPixels.width;
this._originalSizeInPixels.height = this._rectInPixels.height;
- this._originalSize.width = w;
- this._originalSize.height = h;
+ this._originalSize.width = w;
+ this._originalSize.height = h;
}
//dispatch 'load' event of cc.SpriteFrame
this.dispatchEvent("load");
@@ -276,7 +276,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Returns the offset of the frame in the texture
* @return {cc.Point}
*/
- getOffset:function () {
+ getOffset: function () {
return cc.p(this._offset);
},
@@ -284,7 +284,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Sets the offset of the frame in the texture
* @param {cc.Point} offsets
*/
- setOffset:function (offsets) {
+ setOffset: function (offsets) {
this._offset.x = offsets.x;
this._offset.y = offsets.y;
},
@@ -293,7 +293,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Clone the sprite frame
* @returns {SpriteFrame}
*/
- clone: function(){
+ clone: function () {
var frame = new cc.SpriteFrame();
frame.initWithTexture(this._textureFilename, this._rectInPixels, this._rotated, this._offsetInPixels, this._originalSizeInPixels);
frame.setTexture(this._texture);
@@ -304,7 +304,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Copy the sprite frame
* @return {cc.SpriteFrame}
*/
- copyWithZone:function () {
+ copyWithZone: function () {
var copy = new cc.SpriteFrame();
copy.initWithTexture(this._textureFilename, this._rectInPixels, this._rotated, this._offsetInPixels, this._originalSizeInPixels);
copy.setTexture(this._texture);
@@ -315,7 +315,7 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* Copy the sprite frame
* @returns {cc.SpriteFrame}
*/
- copy:function () {
+ copy: function () {
return this.copyWithZone();
},
@@ -329,18 +329,18 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
* @param {cc.Size} [originalSize=rect.size]
* @return {Boolean}
*/
- initWithTexture:function (texture, rect, rotated, offset, originalSize) {
- if(arguments.length === 2)
+ initWithTexture: function (texture, rect, rotated, offset, originalSize) {
+ if (arguments.length === 2)
rect = cc.rectPointsToPixels(rect);
offset = offset || cc.p(0, 0);
originalSize = originalSize || rect;
rotated = rotated || false;
- if (cc.isString(texture)){
+ if (typeof texture === 'string') {
this._texture = null;
this._textureFilename = texture;
- } else if (texture instanceof cc.Texture2D){
+ } else if (texture instanceof cc.Texture2D) {
this.setTexture(texture);
}
@@ -349,19 +349,19 @@ cc.SpriteFrame = cc.Class.extend(/** @lends cc.SpriteFrame# */{
this._rectInPixels = rect;
this._rect = cc.rectPixelsToPoints(rect);
- if(texture && texture.url && texture.isLoaded()) {
+ if (texture && texture.url && texture.isLoaded()) {
var _x, _y;
- if(rotated){
+ if (rotated) {
_x = rect.x + rect.height;
_y = rect.y + rect.width;
- }else{
+ } else {
_x = rect.x + rect.width;
_y = rect.y + rect.height;
}
- if(_x > texture.getPixelsWide()){
+ if (_x > texture.getPixelsWide()) {
cc.error(cc._LogInfos.RectWidth, texture.url);
}
- if(_y > texture.getPixelsHigh()){
+ if (_y > texture.getPixelsHigh()) {
cc.error(cc._LogInfos.RectHeight, texture.url);
}
}
@@ -394,7 +394,7 @@ cc.EventHelper.prototype.apply(cc.SpriteFrame.prototype);
* @return {cc.SpriteFrame}
*/
cc.SpriteFrame.create = function (filename, rect, rotated, offset, originalSize) {
- return new cc.SpriteFrame(filename,rect,rotated,offset,originalSize);
+ return new cc.SpriteFrame(filename, rect, rotated, offset, originalSize);
};
/**
diff --git a/cocos2d/core/sprites/CCSpriteFrameCache.js b/cocos2d/core/sprites/CCSpriteFrameCache.js
index d6955477c1..7d38e89a5b 100644
--- a/cocos2d/core/sprites/CCSpriteFrameCache.js
+++ b/cocos2d/core/sprites/CCSpriteFrameCache.js
@@ -36,38 +36,38 @@
* @name cc.spriteFrameCache
*/
cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
- _CCNS_REG1 : /^\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*$/,
- _CCNS_REG2 : /^\s*\{\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*,\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*\}\s*$/,
+ _CCNS_REG1: /^\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*$/,
+ _CCNS_REG2: /^\s*\{\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*,\s*\{\s*([\-]?\d+[.]?\d*)\s*,\s*([\-]?\d+[.]?\d*)\s*\}\s*\}\s*$/,
_spriteFrames: {},
_spriteFramesAliases: {},
- _frameConfigCache : {},
+ _frameConfigCache: {},
- _rectFromString : function (content) {
+ _rectFromString: function (content) {
var result = this._CCNS_REG2.exec(content);
- if(!result) return cc.rect(0, 0, 0, 0);
+ if (!result) return cc.rect(0, 0, 0, 0);
return cc.rect(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3]), parseFloat(result[4]));
},
- _pointFromString : function (content) {
+ _pointFromString: function (content) {
var result = this._CCNS_REG1.exec(content);
- if(!result) return cc.p(0,0);
+ if (!result) return cc.p(0, 0);
return cc.p(parseFloat(result[1]), parseFloat(result[2]));
},
- _sizeFromString : function (content) {
+ _sizeFromString: function (content) {
var result = this._CCNS_REG1.exec(content);
- if(!result) return cc.size(0, 0);
+ if (!result) return cc.size(0, 0);
return cc.size(parseFloat(result[1]), parseFloat(result[2]));
},
- _getFrameConfig : function(url){
+ _getFrameConfig: function (url) {
var dict = cc.loader.getRes(url);
cc.assert(dict, cc._LogInfos.spriteFrameCache__getFrameConfig_2, url);
cc.loader.release(url);//release it in loader
- if(dict._inited){
+ if (dict._inited) {
this._frameConfigCache[url] = dict;
return dict;
}
@@ -75,24 +75,24 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
return this._frameConfigCache[url];
},
- _getFrameConfigByJsonObject: function(url, jsonObject) {
+ _getFrameConfigByJsonObject: function (url, jsonObject) {
cc.assert(jsonObject, cc._LogInfos.spriteFrameCache__getFrameConfig_2, url);
this._frameConfigCache[url] = this._parseFrameConfig(jsonObject);
return this._frameConfigCache[url];
},
- _parseFrameConfig: function(dict) {
+ _parseFrameConfig: function (dict) {
var tempFrames = dict["frames"], tempMeta = dict["metadata"] || dict["meta"];
var frames = {}, meta = {};
var format = 0;
- if(tempMeta){//init meta
+ if (tempMeta) {//init meta
var tmpFormat = tempMeta["format"];
format = (tmpFormat.length <= 1) ? parseInt(tmpFormat) : tmpFormat;
meta.image = tempMeta["textureFileName"] || tempMeta["textureFileName"] || tempMeta["image"];
}
for (var key in tempFrames) {
var frameDict = tempFrames[key];
- if(!frameDict) continue;
+ if (!frameDict) continue;
var tempFrame = {};
if (format == 0) {
@@ -140,9 +140,9 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
},
// Adds multiple Sprite Frames from a json object. it uses for local web view app.
- _addSpriteFramesByObject: function(url, jsonObject, texture) {
+ _addSpriteFramesByObject: function (url, jsonObject, texture) {
cc.assert(url, cc._LogInfos.spriteFrameCache_addSpriteFrames_2);
- if(!jsonObject || !jsonObject["frames"])
+ if (!jsonObject || !jsonObject["frames"])
return;
var frameConfig = this._frameConfigCache[url] || this._getFrameConfigByJsonObject(url, jsonObject);
@@ -150,16 +150,16 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
this._createSpriteFrames(url, frameConfig, texture);
},
- _createSpriteFrames: function(url, frameConfig, texture) {
+ _createSpriteFrames: function (url, frameConfig, texture) {
var frames = frameConfig.frames, meta = frameConfig.meta;
- if(!texture){
+ if (!texture) {
var texturePath = cc.path.changeBasename(url, meta.image || ".png");
texture = cc.textureCache.addImage(texturePath);
- }else if(texture instanceof cc.Texture2D){
+ } else if (texture instanceof cc.Texture2D) {
//do nothing
- }else if(cc.isString(texture)){//string
+ } else if (cc.isString(texture)) {//string
texture = cc.textureCache.addImage(texture);
- }else{
+ } else {
cc.assert(0, cc._LogInfos.spriteFrameCache_addSpriteFrames_3);
}
@@ -169,10 +169,10 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
var frame = frames[key];
var spriteFrame = spriteFrames[key];
if (!spriteFrame) {
- spriteFrame = new cc.SpriteFrame(texture, frame.rect, frame.rotated, frame.offset, frame.size);
+ spriteFrame = new cc.SpriteFrame(texture, cc.rect(frame.rect), frame.rotated, frame.offset, frame.size);
var aliases = frame.aliases;
- if(aliases){//set aliases
- for(var i = 0, li = aliases.length; i < li; i++){
+ if (aliases) {//set aliases
+ for (var i = 0, li = aliases.length; i < li; i++) {
var alias = aliases[i];
if (spAliases[alias])
cc.log(cc._LogInfos.spriteFrameCache_addSpriteFrames, alias);
@@ -190,6 +190,7 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
tempTexture.initWithElement(tempElement);
tempTexture.handleLoadedTexture();
spriteFrame.setTexture(tempTexture);
+ spriteFrame.setRotated(false);
var rect = spriteFrame._rect;
spriteFrame.setRect(cc.rect(0, 0, rect.width, rect.height));
@@ -218,7 +219,7 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
//Is it a SpriteFrame plist?
var dict = this._frameConfigCache[url] || cc.loader.getRes(url);
- if(!dict || !dict["frames"])
+ if (!dict || !dict["frames"])
return;
var frameConfig = this._frameConfigCache[url] || this._getFrameConfig(url);
@@ -294,13 +295,13 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
removeSpriteFramesFromFile: function (url) {
var self = this, spriteFrames = self._spriteFrames,
aliases = self._spriteFramesAliases, cfg = self._frameConfigCache[url];
- if(!cfg) return;
+ if (!cfg) return;
var frames = cfg.frames;
for (var key in frames) {
if (spriteFrames[key]) {
delete(spriteFrames[key]);
for (var alias in aliases) {//remove alias
- if(aliases[alias] === key) delete aliases[alias];
+ if (aliases[alias] === key) delete aliases[alias];
}
}
}
@@ -320,7 +321,7 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
if (frame && (frame.getTexture() === texture)) {
delete(spriteFrames[key]);
for (var alias in aliases) {//remove alias
- if(aliases[alias] === key) delete aliases[alias];
+ if (aliases[alias] === key) delete aliases[alias];
}
}
}
@@ -345,15 +346,15 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
var key = self._spriteFramesAliases[name];
if (key) {
frame = self._spriteFrames[key.toString()];
- if(!frame) delete self._spriteFramesAliases[name];
+ if (!frame) delete self._spriteFramesAliases[name];
}
}
return frame;
},
- _clear: function () {
- this._spriteFrames = {};
- this._spriteFramesAliases = {};
- this._frameConfigCache = {};
- }
+ _clear: function () {
+ this._spriteFrames = {};
+ this._spriteFramesAliases = {};
+ this._frameConfigCache = {};
+ }
};
diff --git a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js
index 3d02a422ce..51ea5024cb 100644
--- a/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js
+++ b/cocos2d/core/sprites/CCSpriteWebGLRenderCmd.js
@@ -23,10 +23,10 @@
****************************************************************************/
//Sprite's WebGL render command
-(function() {
+(function () {
cc.Sprite.WebGLRenderCmd = function (renderable) {
- cc.Node.WebGLRenderCmd.call(this, renderable);
+ this._rootCtor(renderable);
this._needDraw = true;
this._vertices = [
@@ -39,15 +39,17 @@
this._dirty = false;
this._recursiveDirty = false;
- this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST);
+ this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLOR);
};
var proto = cc.Sprite.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
proto.constructor = cc.Sprite.WebGLRenderCmd;
+ proto._spriteCmdCtor = cc.Sprite.WebGLRenderCmd;
- proto.updateBlendFunc = function (blendFunc) {};
+ proto.updateBlendFunc = function (blendFunc) {
+ };
- proto.setDirtyFlag = function(dirtyFlag){
+ proto.setDirtyFlag = function (dirtyFlag) {
cc.Node.WebGLRenderCmd.prototype.setDirtyFlag.call(this, dirtyFlag);
this._dirty = true;
};
@@ -201,7 +203,8 @@
}
};
- proto._setColorDirty = function () {};
+ proto._setColorDirty = function () {
+ };
proto._updateBlendFunc = function () {
if (this._batchNode) {
@@ -227,22 +230,21 @@
proto._setTexture = function (texture) {
var node = this._node;
- // If batchnode, then texture id should be the same
- if (node._batchNode) {
- if(node._batchNode.texture !== texture){
- cc.log(cc._LogInfos.Sprite_setTexture);
- return;
- }
- } else {
- if(node._texture !== texture){
- node._textureLoaded = texture ? texture._textureLoaded : false;
- node._texture = texture;
+ if (node._texture !== texture) {
+ node._textureLoaded = texture ? texture._textureLoaded : false;
+ node._texture = texture;
+
+ // Update texture rect and blend func
+ if (texture) {
+ var texSize = texture._contentSize;
+ var rect = cc.rect(0, 0, texSize.width, texSize.height);
+ node.setTextureRect(rect);
this._updateBlendFunc();
+ }
- if (node._textureLoaded) {
- // Force refresh the render command list
- cc.renderer.childrenOrderDirty = true;
- }
+ if (node._textureLoaded) {
+ // Force refresh the render command list
+ cc.renderer.childrenOrderDirty = true;
}
}
};
@@ -272,17 +274,20 @@
var node = this._node,
lx = node._offsetPosition.x, rx = lx + node._rect.width,
by = node._offsetPosition.y, ty = by + node._rect.height,
- wt = this._worldTransform;
+ wt = this._worldTransform,
+ wtx = wt.tx, wty = wt.ty,
+ lxa = lx * wt.a, lxb = lx * wt.b, rxa = rx * wt.a, rxb = rx * wt.b,
+ tyc = ty * wt.c, tyd = ty * wt.d, byc = by * wt.c, byd = by * wt.d;
var vertices = this._vertices;
- vertices[0].x = lx * wt.a + ty * wt.c + wt.tx; // tl
- vertices[0].y = lx * wt.b + ty * wt.d + wt.ty;
- vertices[1].x = lx * wt.a + by * wt.c + wt.tx; // bl
- vertices[1].y = lx * wt.b + by * wt.d + wt.ty;
- vertices[2].x = rx * wt.a + ty * wt.c + wt.tx; // tr
- vertices[2].y = rx * wt.b + ty * wt.d + wt.ty;
- vertices[3].x = rx * wt.a + by * wt.c + wt.tx; // br
- vertices[3].y = rx * wt.b + by * wt.d + wt.ty;
+ vertices[0].x = lxa + tyc + wtx; // tl
+ vertices[0].y = lxb + tyd + wty;
+ vertices[1].x = lxa + byc + wtx; // bl
+ vertices[1].y = lxb + byd + wty;
+ vertices[2].x = rxa + tyc + wtx; // tr
+ vertices[2].y = rxb + tyd + wty;
+ vertices[3].x = rxa + byc + wtx; // br
+ vertices[3].y = rxb + byd + wty;
};
proto.needDraw = function () {
@@ -293,7 +298,7 @@
proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset) {
var node = this._node, locTexture = node._texture;
if (!(locTexture && locTexture._textureLoaded && node._rect.width && node._rect.height) || !this._displayedOpacity)
- return false;
+ return 0;
// Fill in vertex data with quad information (4 vertices for sprite)
var opacity = this._displayedOpacity;
@@ -306,7 +311,7 @@
g *= a;
b *= a;
}
- this._color[0] = ((opacity<<24) | (b<<16) | (g<<8) | r);
+ this._color[0] = ((opacity << 24) | (b << 16) | (g << 8) | r);
var z = node._vertexZ;
var vertices = this._vertices;
@@ -324,4 +329,4 @@
return len;
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/core/support/CCPointExtension.js b/cocos2d/core/support/CCPointExtension.js
index d2ea212435..3171a5f7ea 100644
--- a/cocos2d/core/support/CCPointExtension.js
+++ b/cocos2d/core/support/CCPointExtension.js
@@ -510,5 +510,7 @@ cc.pAddIn = function(v1, v2) {
* @param {cc.Point} v
*/
cc.pNormalizeIn = function(v) {
- cc.pMultIn(v, 1.0 / Math.sqrt(v.x * v.x + v.y * v.y));
+ var n = Math.sqrt(v.x * v.x + v.y * v.y);
+ if (n !== 0)
+ cc.pMultIn(v, 1.0 / n);
};
diff --git a/cocos2d/core/textures/CCTexture2D.js b/cocos2d/core/textures/CCTexture2D.js
index b772532ae1..b69d83cfd9 100644
--- a/cocos2d/core/textures/CCTexture2D.js
+++ b/cocos2d/core/textures/CCTexture2D.js
@@ -98,7 +98,7 @@ cc.PVRHaveAlphaPremultiplied_ = false;
cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
- if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
var proto = {
_contentSize: null,
@@ -112,6 +112,8 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
this._textureLoaded = false;
this._htmlElementObj = null;
this._pattern = "";
+ this._pixelsWide = 0;
+ this._pixelsHigh = 0;
},
/**
@@ -119,7 +121,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
* @return {Number}
*/
getPixelsWide: function () {
- return this._contentSize.width;
+ return this._pixelsWide;
},
/**
@@ -127,7 +129,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
* @return {Number}
*/
getPixelsHigh: function () {
- return this._contentSize.height;
+ return this._pixelsHigh;
},
/**
@@ -162,8 +164,8 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
if (!element)
return;
this._htmlElementObj = element;
- this._contentSize.width = element.width;
- this._contentSize.height = element.height;
+ this._pixelsWide = this._contentSize.width = element.width;
+ this._pixelsHigh = this._contentSize.height = element.height;
this._textureLoaded = true;
},
@@ -188,16 +190,13 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
*/
handleLoadedTexture: function () {
var self = this;
- if (self._textureLoaded) return;
if (!self._htmlElementObj) {
- var img = cc.loader.getRes(self.url);
- if (!img) return;
- self.initWithElement(img);
+ return;
}
var locElement = self._htmlElementObj;
- self._contentSize.width = locElement.width;
- self._contentSize.height = locElement.height;
+ self._pixelsWide = self._contentSize.width = locElement.width;
+ self._pixelsHigh = self._contentSize.height = locElement.height;
//dispatch load event to listener.
self.dispatchEvent("load");
@@ -227,6 +226,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
},
releaseTexture: function () {
+ this._htmlElementObj = null;
cc.loader.release(this.url);
},
@@ -322,20 +322,20 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
},
setTexParameters: function (texParams, magFilter, wrapS, wrapT) {
- if(magFilter !== undefined)
+ if (magFilter !== undefined)
texParams = {minFilter: texParams, magFilter: magFilter, wrapS: wrapS, wrapT: wrapT};
- if(texParams.wrapS === cc.REPEAT && texParams.wrapT === cc.REPEAT){
+ if (texParams.wrapS === cc.REPEAT && texParams.wrapT === cc.REPEAT) {
this._pattern = "repeat";
return;
}
- if(texParams.wrapS === cc.REPEAT ){
+ if (texParams.wrapS === cc.REPEAT) {
this._pattern = "repeat-x";
return;
}
- if(texParams.wrapT === cc.REPEAT){
+ if (texParams.wrapT === cc.REPEAT) {
this._pattern = "repeat-y";
return;
}
@@ -383,8 +383,9 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
this.removeEventTarget("load", target);
},
- _generateColorTexture: function(){/*overide*/},
- _generateTextureCacheForColor: function(){
+ _generateColorTexture: function () {/*overide*/
+ },
+ _generateTextureCacheForColor: function () {
if (this.channelCache)
return this.channelCache;
@@ -403,23 +404,33 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
_grayElementObj: null,
_backupElement: null,
_isGray: false,
- _switchToGray: function(toGray){
- if(!this._textureLoaded || this._isGray === toGray)
+ _switchToGray: function (toGray) {
+ if (!this._textureLoaded || this._isGray === toGray)
return;
this._isGray = toGray;
- if(this._isGray){
+ if (this._isGray) {
this._backupElement = this._htmlElementObj;
- if(!this._grayElementObj)
+ if (!this._grayElementObj)
this._grayElementObj = cc.Texture2D._generateGrayTexture(this._htmlElementObj);
this._htmlElementObj = this._grayElementObj;
} else {
- if(this._backupElement !== null)
+ if (this._backupElement !== null)
this._htmlElementObj = this._backupElement;
}
- }
+ },
+
+ _generateGrayTexture: function() {
+ if(!this._textureLoaded)
+ return null;
+ var grayElement = cc.Texture2D._generateGrayTexture(this._htmlElementObj);
+ var newTexture = new cc.Texture2D();
+ newTexture.initWithElement(grayElement);
+ newTexture.handleLoadedTexture();
+ return newTexture;
+ },
};
- var renderToCache = function(image, cache){
+ var renderToCache = function (image, cache) {
var w = image.width;
var h = image.height;
@@ -443,7 +454,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
var to = ctx.getImageData(0, 0, w, h);
var data = to.data;
for (var i = 0; i < pixels.length; i += 4) {
- data[i ] = (rgbI === 0) ? pixels[i ] : 0;
+ data[i] = (rgbI === 0) ? pixels[i] : 0;
data[i + 1] = (rgbI === 1) ? pixels[i + 1] : 0;
data[i + 2] = (rgbI === 2) ? pixels[i + 2] : 0;
data[i + 3] = pixels[i + 3];
@@ -454,17 +465,17 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
};
//change color function
- if(cc.sys._supportCanvasNewBlendModes){
+ if (cc.sys._supportCanvasNewBlendModes) {
//multiply mode
//Primary afferent, Draw a new texture based on rect
- proto._generateColorTexture = function(r, g, b, rect, canvas){
+ proto._generateColorTexture = function (r, g, b, rect, canvas) {
var onlyCanvas = false;
- if(canvas)
+ if (canvas)
onlyCanvas = true;
else
canvas = document.createElement("canvas");
var textureImage = this._htmlElementObj;
- if(!rect)
+ if (!rect)
rect = cc.rect(0, 0, textureImage.width, textureImage.height);
canvas.width = rect.width;
@@ -472,7 +483,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
var context = canvas.getContext("2d");
context.globalCompositeOperation = "source-over";
- context.fillStyle = "rgb(" + (r|0) + "," + (g|0) + "," + (b|0) + ")";
+ context.fillStyle = "rgb(" + (r | 0) + "," + (g | 0) + "," + (b | 0) + ")";
context.fillRect(0, 0, rect.width, rect.height);
context.globalCompositeOperation = "multiply";
context.drawImage(
@@ -486,28 +497,28 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
rect.x, rect.y, rect.width, rect.height,
0, 0, rect.width, rect.height
);
- if(onlyCanvas)
+ if (onlyCanvas)
return canvas;
var newTexture = new cc.Texture2D();
newTexture.initWithElement(canvas);
newTexture.handleLoadedTexture();
return newTexture;
};
- }else{
+ } else {
//Four color map overlay
- proto._generateColorTexture = function(r, g, b, rect, canvas){
+ proto._generateColorTexture = function (r, g, b, rect, canvas) {
var onlyCanvas = false;
- if(canvas)
+ if (canvas)
onlyCanvas = true;
else
canvas = document.createElement("canvas");
var textureImage = this._htmlElementObj;
- if(!rect)
+ if (!rect)
rect = cc.rect(0, 0, textureImage.width, textureImage.height);
var x, y, w, h;
x = rect.x; y = rect.y; w = rect.width; h = rect.height;
- if(!w || !h)
+ if (!w || !h)
return;
canvas.width = w;
@@ -545,7 +556,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
0, 0, w, h
);
}
- if(onlyCanvas)
+ if (onlyCanvas)
return canvas;
var newTexture = new cc.Texture2D();
@@ -578,7 +589,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
*/
cc.Texture2D = cc.Class.extend(/** @lends cc.Texture2D# */proto);
- cc.Texture2D._generateGrayTexture = function(texture, rect, renderCanvas){
+ cc.Texture2D._generateGrayTexture = function (texture, rect, renderCanvas) {
if (texture === null)
return null;
renderCanvas = renderCanvas || document.createElement("canvas");
diff --git a/cocos2d/core/textures/CCTextureCache.js b/cocos2d/core/textures/CCTextureCache.js
index dcef25dc39..5e59c2f83c 100644
--- a/cocos2d/core/textures/CCTextureCache.js
+++ b/cocos2d/core/textures/CCTextureCache.js
@@ -108,7 +108,7 @@ cc.textureCache = /** @lends cc.textureCache# */{
* //example
* var key = cc.textureCache.getTextureForKey("hello.png");
*/
- getTextureForKey: function(textureKeyName){
+ getTextureForKey: function (textureKeyName) {
return this._textures[textureKeyName] || this._textures[cc.loader._getAliase(textureKeyName)];
},
@@ -214,8 +214,11 @@ cc.textureCache = /** @lends cc.textureCache# */{
removeTextureForKey: function (textureKeyName) {
if (textureKeyName == null)
return;
- if (this._textures[textureKeyName])
+ var tex = this._textures[textureKeyName];
+ if (tex) {
+ tex.releaseTexture();
delete(this._textures[textureKeyName]);
+ }
},
//addImage move to Canvas/WebGL
@@ -276,11 +279,11 @@ cc.textureCache = /** @lends cc.textureCache# */{
var selTexture = locTextures[key];
count++;
if (selTexture.getHtmlElementObj() instanceof HTMLImageElement)
- cc.log(cc._LogInfos.textureCache_dumpCachedTextureInfo, key, selTexture.getHtmlElementObj().src, selTexture.pixelsWidth, selTexture.pixelsHeight);
+ cc.log(cc._LogInfos.textureCache_dumpCachedTextureInfo, key, selTexture.getHtmlElementObj().src, selTexture.getPixelsWide(), selTexture.getPixelsHigh());
else {
- cc.log(cc._LogInfos.textureCache_dumpCachedTextureInfo_2, key, selTexture.pixelsWidth, selTexture.pixelsHeight);
+ cc.log(cc._LogInfos.textureCache_dumpCachedTextureInfo_2, key, selTexture.getPixelsWide(), selTexture.getPixelsHigh());
}
- totalBytes += selTexture.pixelsWidth * selTexture.pixelsHeight * 4;
+ totalBytes += selTexture.getPixelsWide() * selTexture.getPixelsHigh() * 4;
}
var locTextureColorsCache = this._textureColorsCache;
@@ -310,7 +313,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
var _p = cc.textureCache;
- _p.handleLoadedTexture = function (url) {
+ _p.handleLoadedTexture = function (url, img) {
var locTexs = this._textures;
//remove judge
var tex = locTexs[url];
@@ -318,7 +321,9 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
tex = locTexs[url] = new cc.Texture2D();
tex.url = url;
}
+ tex.initWithElement(img);
tex.handleLoadedTexture();
+ return tex;
};
/**
@@ -343,13 +348,12 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
//remove judge
var tex = locTexs[url] || locTexs[cc.loader._getAliase(url)];
if (tex) {
- if(tex.isLoaded()) {
+ if (tex.isLoaded()) {
cb && cb.call(target, tex);
return tex;
}
- else
- {
- tex.addEventListener("load", function(){
+ else {
+ tex.addEventListener("load", function () {
cb && cb.call(target, tex);
}, target);
return tex;
@@ -363,12 +367,7 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
if (err)
return cb && cb.call(target, err);
- if (!cc.loader.cache[url]) {
- cc.loader.cache[url] = img;
- }
- cc.textureCache.handleLoadedTexture(url);
-
- var texResult = locTexs[url];
+ var texResult = cc.textureCache.handleLoadedTexture(url, img);
cb && cb.call(target, texResult);
});
diff --git a/cocos2d/core/textures/TexturesWebGL.js b/cocos2d/core/textures/TexturesWebGL.js
index cf6a2555de..2dfe145e56 100644
--- a/cocos2d/core/textures/TexturesWebGL.js
+++ b/cocos2d/core/textures/TexturesWebGL.js
@@ -83,6 +83,7 @@ cc._tmp.WebGLTexture2D = function () {
releaseTexture: function () {
if (this._webTextureObj)
cc._renderContext.deleteTexture(this._webTextureObj);
+ this._htmlElementObj = null;
cc.loader.release(this.url);
},
@@ -324,10 +325,10 @@ cc._tmp.WebGLTexture2D = function () {
drawAtPoint: function (point) {
var self = this;
var coordinates = [
- 0.0, self.maxT,
- self.maxS, self.maxT,
- 0.0, 0.0,
- self.maxS, 0.0 ],
+ 0.0, self.maxT,
+ self.maxS, self.maxT,
+ 0.0, 0.0,
+ self.maxS, 0.0],
gl = cc._renderContext;
var width = self._pixelsWide * self.maxS,
@@ -337,10 +338,10 @@ cc._tmp.WebGLTexture2D = function () {
point.x, point.y, 0.0,
width + point.x, point.y, 0.0,
point.x, height + point.y, 0.0,
- width + point.x, height + point.y, 0.0 ];
+ width + point.x, height + point.y, 0.0];
- self._shaderProgram.use();
- self._shaderProgram.setUniformsForBuiltins();
+ self._glProgramState.apply();
+ self._glProgramState._glprogram.setUniformsForBuiltins();
cc.glBindTexture2D(self);
@@ -364,13 +365,13 @@ cc._tmp.WebGLTexture2D = function () {
0.0, 0.0,
self.maxS, 0.0];
- var vertices = [ rect.x, rect.y, /*0.0,*/
+ var vertices = [rect.x, rect.y, /*0.0,*/
rect.x + rect.width, rect.y, /*0.0,*/
rect.x, rect.y + rect.height, /*0.0,*/
- rect.x + rect.width, rect.y + rect.height /*0.0*/ ];
+ rect.x + rect.width, rect.y + rect.height /*0.0*/];
- self._shaderProgram.use();
- self._shaderProgram.setUniformsForBuiltins();
+ self._glProgramState.apply();
+ self._glProgramState._glprogram.setUniformsForBuiltins();
cc.glBindTexture2D(self);
@@ -451,17 +452,14 @@ cc._tmp.WebGLTexture2D = function () {
handleLoadedTexture: function (premultiplied) {
var self = this;
premultiplied =
- (premultiplied !== undefined)
- ? premultiplied
- : self._hasPremultipliedAlpha;
+ (premultiplied !== undefined)
+ ? premultiplied
+ : self._hasPremultipliedAlpha;
// Not sure about this ! Some texture need to be updated even after loaded
if (!cc.game._rendererInitialized)
return;
- if (!self._htmlElementObj) {
- var img = cc.loader.getRes(self.url);
- if (!img) return;
- self.initWithElement(img);
- }
+ if (!self._htmlElementObj)
+ return;
if (!self._htmlElementObj.width || !self._htmlElementObj.height)
return;
@@ -471,7 +469,7 @@ cc._tmp.WebGLTexture2D = function () {
cc.glBindTexture2D(self);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
- if(premultiplied)
+ if (premultiplied)
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
// Specify OpenGL texture image
@@ -484,7 +482,7 @@ cc._tmp.WebGLTexture2D = function () {
self.shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE);
cc.glBindTexture2D(null);
- if(premultiplied)
+ if (premultiplied)
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
var pixelsWide = self._htmlElementObj.width;
@@ -498,6 +496,9 @@ cc._tmp.WebGLTexture2D = function () {
self._hasPremultipliedAlpha = premultiplied;
self._hasMipmaps = false;
+ if (window.ENABLE_IMAEG_POOL) {
+ self._htmlElementObj = null;
+ }
//dispatch load event to listener.
self.dispatchEvent("load");
@@ -575,7 +576,7 @@ cc._tmp.WebGLTexture2D = function () {
var _t = this;
var gl = cc._renderContext;
- if(magFilter !== undefined)
+ if (magFilter !== undefined)
texParams = {minFilter: texParams, magFilter: magFilter, wrapS: wrapS, wrapT: wrapT};
cc.assert((_t._pixelsWide === cc.NextPOT(_t._pixelsWide) && _t._pixelsHigh === cc.NextPOT(_t._pixelsHigh)) ||
@@ -664,7 +665,6 @@ cc._tmp.WebGLTexture2D = function () {
var imageSize = cc.size(uiImage.getWidth(), uiImage.getHeight());
var pixelFormat = tex2d.defaultPixelFormat;
var bpp = uiImage.getBitsPerComponent();
- var i;
// compute pixel format
if (!hasAlpha) {
@@ -677,7 +677,7 @@ cc._tmp.WebGLTexture2D = function () {
}
// Repack the pixel data into the right format
- var length = width * height;
+ var i, length = width * height;
if (pixelFormat === tex2d.PIXEL_FORMAT_RGB565) {
if (hasAlpha) {
@@ -688,8 +688,8 @@ cc._tmp.WebGLTexture2D = function () {
for (i = 0; i < length; ++i) {
tempData[i] =
((((inPixel32[i] >> 0) & 0xFF) >> 3) << 11) | // R
- ((((inPixel32[i] >> 8) & 0xFF) >> 2) << 5) | // G
- ((((inPixel32[i] >> 16) & 0xFF) >> 3) << 0); // B
+ ((((inPixel32[i] >> 8) & 0xFF) >> 2) << 5) | // G
+ ((((inPixel32[i] >> 16) & 0xFF) >> 3) << 0); // B
}
} else {
// Convert "RRRRRRRRRGGGGGGGGBBBBBBBB" to "RRRRRGGGGGGBBBBB"
@@ -699,8 +699,8 @@ cc._tmp.WebGLTexture2D = function () {
for (i = 0; i < length; ++i) {
tempData[i] =
(((inPixel8[i] & 0xFF) >> 3) << 11) | // R
- (((inPixel8[i] & 0xFF) >> 2) << 5) | // G
- (((inPixel8[i] & 0xFF) >> 3) << 0); // B
+ (((inPixel8[i] & 0xFF) >> 2) << 5) | // G
+ (((inPixel8[i] & 0xFF) >> 3) << 0); // B
}
}
} else if (pixelFormat === tex2d.PIXEL_FORMAT_RGBA4444) {
@@ -711,9 +711,9 @@ cc._tmp.WebGLTexture2D = function () {
for (i = 0; i < length; ++i) {
tempData[i] =
((((inPixel32[i] >> 0) & 0xFF) >> 4) << 12) | // R
- ((((inPixel32[i] >> 8) & 0xFF) >> 4) << 8) | // G
- ((((inPixel32[i] >> 16) & 0xFF) >> 4) << 4) | // B
- ((((inPixel32[i] >> 24) & 0xFF) >> 4) << 0); // A
+ ((((inPixel32[i] >> 8) & 0xFF) >> 4) << 8) | // G
+ ((((inPixel32[i] >> 16) & 0xFF) >> 4) << 4) | // B
+ ((((inPixel32[i] >> 24) & 0xFF) >> 4) << 0); // A
}
} else if (pixelFormat === tex2d.PIXEL_FORMAT_RGB5A1) {
// Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGBBBBBA"
@@ -723,9 +723,9 @@ cc._tmp.WebGLTexture2D = function () {
for (i = 0; i < length; ++i) {
tempData[i] =
((((inPixel32[i] >> 0) & 0xFF) >> 3) << 11) | // R
- ((((inPixel32[i] >> 8) & 0xFF) >> 3) << 6) | // G
- ((((inPixel32[i] >> 16) & 0xFF) >> 3) << 1) | // B
- ((((inPixel32[i] >> 24) & 0xFF) >> 7) << 0); // A
+ ((((inPixel32[i] >> 8) & 0xFF) >> 3) << 6) | // G
+ ((((inPixel32[i] >> 16) & 0xFF) >> 3) << 1) | // B
+ ((((inPixel32[i] >> 24) & 0xFF) >> 7) << 0); // A
}
} else if (pixelFormat === tex2d.PIXEL_FORMAT_A8) {
// Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "AAAAAAAA"
@@ -827,7 +827,7 @@ cc._tmp.WebGLTextureAtlas = function () {
// XXX: update is done in draw... perhaps it should be done in a timer
gl.bindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer);
- if (_t.dirty){
+ if (_t.dirty) {
gl.bufferData(gl.ARRAY_BUFFER, _t._quadsArrayBuffer, gl.DYNAMIC_DRAW);
_t.dirty = false;
}
@@ -855,7 +855,7 @@ cc._tmp.WebGLTextureAtlas = function () {
cc._tmp.WebGLTextureCache = function () {
var _p = cc.textureCache;
- _p.handleLoadedTexture = function (url) {
+ _p.handleLoadedTexture = function (url, img) {
var locTexs = this._textures, tex, ext;
//remove judge(webgl)
if (!cc.game._rendererInitialized) {
@@ -866,6 +866,7 @@ cc._tmp.WebGLTextureCache = function () {
tex = locTexs[url] = new cc.Texture2D();
tex.url = url;
}
+ tex.initWithElement(img);
ext = cc.path.extname(url);
if (ext === ".png") {
tex.handleLoadedTexture(true);
@@ -873,6 +874,7 @@ cc._tmp.WebGLTextureCache = function () {
else {
tex.handleLoadedTexture();
}
+ return tex;
};
/**
@@ -899,14 +901,13 @@ cc._tmp.WebGLTextureCache = function () {
}
var tex = locTexs[url] || locTexs[cc.loader._getAliase(url)];
if (tex) {
- if(tex.isLoaded()) {
+ if (tex.isLoaded()) {
cb && cb.call(target, tex);
return tex;
}
- else
- {
- tex.addEventListener("load", function(){
- cb && cb.call(target, tex);
+ else {
+ tex.addEventListener("load", function () {
+ cb && cb.call(target, tex);
}, target);
return tex;
}
@@ -919,12 +920,7 @@ cc._tmp.WebGLTextureCache = function () {
if (err)
return cb && cb.call(target, err);
- if (!cc.loader.cache[url]) {
- cc.loader.cache[url] = img;
- }
- cc.textureCache.handleLoadedTexture(url);
-
- var texResult = locTexs[url];
+ var texResult = cc.textureCache.handleLoadedTexture(url, img);
cb && cb.call(target, texResult);
});
diff --git a/cocos2d/core/utils/BinaryLoader.js b/cocos2d/core/utils/BinaryLoader.js
index b95b93e799..46b82b65cf 100644
--- a/cocos2d/core/utils/BinaryLoader.js
+++ b/cocos2d/core/utils/BinaryLoader.js
@@ -37,6 +37,7 @@ cc.loader.loadBinary = function (url, cb) {
var xhr = this.getXMLHttpRequest(),
errInfo = "load " + url + " failed!";
xhr.open("GET", url, true);
+ xhr.responseType = 'arraybuffer';
if (cc.loader.loadBinary._IEFilter) {
// IE-specific logic here
xhr.setRequestHeader("Accept-Charset", "x-user-defined");
@@ -49,7 +50,7 @@ cc.loader.loadBinary = function (url, cb) {
} else {
if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=x-user-defined");
xhr.onload = function () {
- xhr.readyState === 4 && xhr.status === 200 ? cb(null, self._str2Uint8Array(xhr.responseText)) : cb(errInfo);
+ xhr.readyState === 4 && xhr.status === 200 ? cb(null, new Uint8Array(xhr.response)) : cb(errInfo);
};
}
xhr.send(null);
@@ -77,6 +78,7 @@ cc.loader._str2Uint8Array = function (strData) {
cc.loader.loadBinarySync = function (url) {
var self = this;
var req = this.getXMLHttpRequest();
+ req.timeout = 0;
var errInfo = "load " + url + " failed!";
req.open('GET', url, false);
var arrayInfo = null;
@@ -101,7 +103,7 @@ cc.loader.loadBinarySync = function (url) {
return null;
}
- arrayInfo = this._str2Uint8Array(req.responseText);
+ arrayInfo = self._str2Uint8Array(req.responseText);
}
return arrayInfo;
};
@@ -150,4 +152,4 @@ if (cc.loader.loadBinary._IEFilter) {
return byteMapping[match];
}) + lastChr;
};
-}
\ No newline at end of file
+}
diff --git a/cocos2d/core/utils/CCProfiler.js b/cocos2d/core/utils/CCProfiler.js
index 704f8697eb..94d0c41eb4 100644
--- a/cocos2d/core/utils/CCProfiler.js
+++ b/cocos2d/core/utils/CCProfiler.js
@@ -2,9 +2,9 @@ cc.profiler = (function () {
var _showFPS = false;
var _inited = false;
var _frames = 0, _frameRate = 0, _lastSPF = 0, _accumDt = 0;
- var _afterVisitListener = null,
- _FPSLabel = document.createElement('div'),
- _SPFLabel = document.createElement('div'),
+ var _afterVisitListener = null,
+ _FPSLabel = document.createElement('div'),
+ _SPFLabel = document.createElement('div'),
_drawsLabel = document.createElement('div'),
_fps = document.createElement('div');
@@ -21,7 +21,7 @@ cc.profiler = (function () {
_fps.style.bottom = cc.DIRECTOR_STATS_POSITION.y + '0px';
_fps.style.left = cc.DIRECTOR_STATS_POSITION.x + 'px';
_fps.style.width = '45px';
- _fps.style.height = '60px';
+ _fps.style.height = '80px';
var labels = [_drawsLabel, _SPFLabel, _FPSLabel];
for (var i = 0; i < 3; ++i) {
@@ -47,7 +47,7 @@ cc.profiler = (function () {
if (_analyseCount >= _levelDetCycle) {
average = _totalFPS / _levelDetCycle;
- for (i = lastId; i >0; i--) {
+ for (i = lastId; i > 0; i--) {
ratio = _fpsCount[i] / _levelDetCycle;
// Determined level
if (ratio >= LEVEL_DET_FACTOR && average >= LEVELS[i]) {
@@ -85,9 +85,10 @@ cc.profiler = (function () {
}
if (_showFPS) {
- _SPFLabel.innerText = _lastSPF.toFixed(3);
- _FPSLabel.innerText = _frameRate.toFixed(1);
- _drawsLabel.innerText = (0 | cc.g_NumberOfDraws).toString();
+ var mode = cc._renderType === cc.game.RENDER_TYPE_CANVAS ? "\n canvas" : "\n webgl";
+ _SPFLabel.innerHTML = _lastSPF.toFixed(3);
+ _FPSLabel.innerHTML = _frameRate.toFixed(1).toString() + mode;
+ _drawsLabel.innerHTML = (0 | cc.g_NumberOfDraws).toString();
}
}
};
@@ -147,4 +148,4 @@ cc.profiler = (function () {
};
return profiler;
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/effects/CCGrid.js b/cocos2d/effects/CCGrid.js
index 8c5cd08a22..361cba84b3 100644
--- a/cocos2d/effects/CCGrid.js
+++ b/cocos2d/effects/CCGrid.js
@@ -31,18 +31,18 @@
* @extends cc.Class
*/
cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
- _active:false,
- _reuseGrid:0,
- _gridSize:null,
- _gridRect:null,
- _texture:null,
- _step:null,
- _grabber:null,
- _isTextureFlipped:false,
- _shaderProgram:null,
- _directorProjection:0,
-
- _dirty:false,
+ _active: false,
+ _reuseGrid: 0,
+ _gridSize: null,
+ _gridRect: null,
+ _texture: null,
+ _step: null,
+ _grabber: null,
+ _isTextureFlipped: false,
+ _glProgramState: null,
+ _directorProjection: 0,
+
+ _dirty: false,
/**
* create one cc.GridBase Object
@@ -52,21 +52,21 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* @param {Boolean} [flipped=]
* @param {cc.Rect} rect
*/
- ctor:function (gridSize, texture, flipped, rect) {
+ ctor: function (gridSize, texture, flipped, rect) {
cc.sys._checkWebGLRenderMode();
- this._active=false;
- this._reuseGrid=0;
- this._gridSize=null;
- this._gridRect=new cc.rect();
- this._texture=null;
+ this._active = false;
+ this._reuseGrid = 0;
+ this._gridSize = null;
+ this._gridRect = new cc.rect();
+ this._texture = null;
this._step = cc.p(0, 0);
- this._grabber=null;
- this._isTextureFlipped=false;
- this._shaderProgram=null;
- this._directorProjection=0;
- this._dirty=false;
+ this._grabber = null;
+ this._isTextureFlipped = false;
+ this._glProgramState = null;
+ this._directorProjection = 0;
+ this._dirty = false;
- if(gridSize !== undefined)
+ if (gridSize !== undefined)
this.initWithSize(gridSize, texture, flipped, rect);
},
@@ -74,7 +74,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* whether or not the grid is active
* @return {Boolean}
*/
- isActive:function () {
+ isActive: function () {
return this._active;
},
@@ -82,7 +82,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* whether or not the grid is active
* @param {Number} active
*/
- setActive:function (active) {
+ setActive: function (active) {
this._active = active;
if (!active) {
var director = cc.director;
@@ -95,14 +95,14 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* get number of times that the grid will be reused
* @return {Number}
*/
- getReuseGrid:function () {
+ getReuseGrid: function () {
return this._reuseGrid;
},
/**
* set number of times that the grid will be reused
* @param reuseGrid
*/
- setReuseGrid:function (reuseGrid) {
+ setReuseGrid: function (reuseGrid) {
this._reuseGrid = reuseGrid;
},
@@ -110,7 +110,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* get size of the grid
* @return {cc.Size}
*/
- getGridSize:function () {
+ getGridSize: function () {
return cc.size(this._gridSize.width, this._gridSize.height);
},
@@ -118,7 +118,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* set size of the grid
* @param {cc.Size} gridSize
*/
- setGridSize:function (gridSize) {
+ setGridSize: function (gridSize) {
this._gridSize.width = parseInt(gridSize.width);
this._gridSize.height = parseInt(gridSize.height);
},
@@ -127,7 +127,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* set rect of the grid
* @param {cc.Rect} rect
*/
- setGridRect:function (rect) {
+ setGridRect: function (rect) {
this._gridRect = rect;
},
@@ -135,7 +135,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* get rect of the grid
* @return {cc.Rect} rect
*/
- getGridRect:function () {
+ getGridRect: function () {
return this._gridRect;
},
@@ -143,7 +143,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* get pixels between the grids
* @return {cc.Point}
*/
- getStep:function () {
+ getStep: function () {
return cc.p(this._step.x, this._step.y);
},
@@ -151,7 +151,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* set pixels between the grids
* @param {cc.Point} step
*/
- setStep:function (step) {
+ setStep: function (step) {
this._step.x = step.x;
this._step.y = step.y;
},
@@ -160,7 +160,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* get whether or not the texture is flipped
* @return {Boolean}
*/
- isTextureFlipped:function () {
+ isTextureFlipped: function () {
return this._isTextureFlipped;
},
@@ -168,7 +168,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* set whether or not the texture is flipped
* @param {Boolean} flipped
*/
- setTextureFlipped:function (flipped) {
+ setTextureFlipped: function (flipped) {
if (this._isTextureFlipped !== flipped) {
this._isTextureFlipped = flipped;
this.calculateVertexPoints();
@@ -183,7 +183,7 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
* @param {cc.Rect} [rect=]
* @returns {boolean}
*/
- initWithSize:function (gridSize, texture, flipped, rect) {
+ initWithSize: function (gridSize, texture, flipped, rect) {
if (!texture) {
var director = cc.director;
var winSize = director.getWinSizeInPixels();
@@ -213,10 +213,9 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
this._gridSize = gridSize;
this._texture = texture;
this._isTextureFlipped = flipped;
- if(rect === undefined || cc._rectEqualToZero(rect))
- {
+ if (rect === undefined || cc._rectEqualToZero(rect)) {
var size = this._texture.getContentSize();
- rect = new cc.rect(0,0,size.width,size.height);
+ rect = new cc.rect(0, 0, size.width, size.height);
}
this._gridRect = rect;
@@ -228,22 +227,22 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
if (!this._grabber)
return false;
this._grabber.grab(this._texture);
- this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE);
+ this._glProgramState = cc.GLProgramState.getOrCreateWithGLProgram(cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURE));
this.calculateVertexPoints();
return true;
},
- beforeDraw:function () {
+ beforeDraw: function () {
// save projection
this._directorProjection = cc.director.getProjection();
//this.set2DProjection(); //TODO why?
var size = cc.director.getWinSizeInPixels();
- gl.viewport(0, 0, size.width , size.height);
+ gl.viewport(0, 0, size.width, size.height);
this._grabber.beforeRender(this._texture);
},
- afterDraw:function (target) {
+ afterDraw: function (target) {
this._grabber.afterRender(this._texture);
// restore projection
@@ -262,23 +261,23 @@ cc.GridBase = cc.Class.extend(/** @lends cc.GridBase# */{
afterBlit: function () {
},
- blit:function () {
+ blit: function () {
cc.log("cc.GridBase.blit(): Shall be overridden in subclass.");
},
- reuse:function () {
+ reuse: function () {
cc.log("cc.GridBase.reuse(): Shall be overridden in subclass.");
},
- calculateVertexPoints:function () {
+ calculateVertexPoints: function () {
cc.log("cc.GridBase.calculateVertexPoints(): Shall be overridden in subclass.");
},
- set2DProjection:function () {
+ set2DProjection: function () {
var winSize = cc.director.getWinSizeInPixels();
var gl = cc._renderContext;
- gl.viewport(0, 0, winSize.width , winSize.height);
+ gl.viewport(0, 0, winSize.width, winSize.height);
cc.kmGLMatrixMode(cc.KM_GL_PROJECTION);
cc.kmGLLoadIdentity();
@@ -310,14 +309,14 @@ cc.GridBase.create = function (gridSize, texture, flipped, rect) {
* @extends cc.GridBase
*/
cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
- _texCoordinates:null,
- _vertices:null,
- _originalVertices:null,
- _indices:null,
+ _texCoordinates: null,
+ _vertices: null,
+ _originalVertices: null,
+ _indices: null,
- _texCoordinateBuffer:null,
- _verticesBuffer:null,
- _indicesBuffer:null,
+ _texCoordinateBuffer: null,
+ _verticesBuffer: null,
+ _indicesBuffer: null,
_needDepthTestForBlit: false,
_oldDepthTestValue: false,
@@ -331,21 +330,21 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
* @param {Boolean} [flipped=]
* @param {cc.Rect} [rect=]
*/
- ctor:function (gridSize, texture, flipped, rect) {
+ ctor: function (gridSize, texture, flipped, rect) {
cc.GridBase.prototype.ctor.call(this);
- this._texCoordinates=null;
- this._vertices=null;
- this._originalVertices=null;
- this._indices=null;
+ this._texCoordinates = null;
+ this._vertices = null;
+ this._originalVertices = null;
+ this._indices = null;
- this._texCoordinateBuffer=null;
- this._verticesBuffer=null;
- this._indicesBuffer=null;
+ this._texCoordinateBuffer = null;
+ this._verticesBuffer = null;
+ this._indicesBuffer = null;
this._matrix = new cc.math.Matrix4();
this._matrix.identity();
- if(gridSize !== undefined)
+ if (gridSize !== undefined)
this.initWithSize(gridSize, texture, flipped, rect);
},
@@ -355,8 +354,8 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
* @param {cc.Point} pos
* @return {cc.Vertex3F}
*/
- vertex:function (pos) {
- return this.getVertex(pos);
+ vertex: function (pos) {
+ return this.getVertex(pos);
},
/**
@@ -364,8 +363,8 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
* @param {cc.Point} pos
* @return {cc.Vertex3F}
*/
- getVertex: function(pos){
- if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y))
+ getVertex: function (pos) {
+ if (pos.x !== (0 | pos.x) || pos.y !== (0 | pos.y))
cc.log("cc.Grid3D.vertex() : Numbers must be integers");
var index = 0 | ((pos.x * (this._gridSize.height + 1) + pos.y) * 3);
var locVertices = this._vertices;
@@ -378,7 +377,7 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
* @param {cc.Point} pos
* @return {cc.Vertex3F}
*/
- originalVertex:function (pos) {
+ originalVertex: function (pos) {
return this.getOriginalVertex(pos);
},
@@ -387,8 +386,8 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
* @param {cc.Point} pos
* @return {cc.Vertex3F}
*/
- getOriginalVertex: function(pos) {
- if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y))
+ getOriginalVertex: function (pos) {
+ if (pos.x !== (0 | pos.x) || pos.y !== (0 | pos.y))
cc.log("cc.Grid3D.originalVertex() : Numbers must be integers");
var index = 0 | ((pos.x * (this._gridSize.height + 1) + pos.y) * 3);
var locOriginalVertices = this._originalVertices;
@@ -400,8 +399,8 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
* @param {cc.Point} pos
* @param {cc.Vertex3F} vertex
*/
- setVertex:function (pos, vertex) {
- if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y))
+ setVertex: function (pos, vertex) {
+ if (pos.x !== (0 | pos.x) || pos.y !== (0 | pos.y))
cc.log("cc.Grid3D.setVertex() : Numbers must be integers");
var index = 0 | ((pos.x * (this._gridSize.height + 1) + pos.y) * 3);
var vertArray = this._vertices;
@@ -433,7 +432,7 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
}
},
- blit:function (target) {
+ blit: function (target) {
var n = this._gridSize.width * this._gridSize.height;
var wt = target._renderCmd._worldTransform;
@@ -444,9 +443,7 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
this._matrix.mat[5] = wt.d;
this._matrix.mat[13] = wt.ty;
- this._shaderProgram.use();
- //this._shaderProgram.setUniformsForBuiltins();
- this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix);
+ this._glProgramState.apply(this._matrix);
var gl = cc._renderContext, locDirty = this._dirty;
@@ -476,16 +473,16 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
cc.incrementGLDraws(1);
},
- reuse:function () {
+ reuse: function () {
if (this._reuseGrid > 0) {
var locOriginalVertices = this._originalVertices, locVertices = this._vertices;
- for (var i = 0, len = this._vertices.length; i < len; i++)
+ for (var i = 0, len = this._vertices.length; i < len; i++)
locOriginalVertices[i] = locVertices[i];
--this._reuseGrid;
}
},
- calculateVertexPoints:function () {
+ calculateVertexPoints: function () {
var gl = cc._renderContext;
var width = this._texture.pixelsWidth;
@@ -498,13 +495,13 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
this._texCoordinates = new Float32Array(numOfPoints * 2);
this._indices = new Uint16Array(locGridSize.width * locGridSize.height * 6);
- if(this._verticesBuffer)
+ if (this._verticesBuffer)
gl.deleteBuffer(this._verticesBuffer);
this._verticesBuffer = gl.createBuffer();
- if(this._texCoordinateBuffer)
+ if (this._texCoordinateBuffer)
gl.deleteBuffer(this._texCoordinateBuffer);
this._texCoordinateBuffer = gl.createBuffer();
- if(this._indicesBuffer)
+ if (this._indicesBuffer)
gl.deleteBuffer(this._indicesBuffer);
this._indicesBuffer = gl.createBuffer();
@@ -531,10 +528,10 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
locIndices[idx * 6 + 5] = d;
var l1 = [a * 3, b * 3, c * 3, d * 3];
- var e = {x:x1, y:y1, z:0}; //new cc.Vertex3F(x1, y1, 0);
- var f = {x:x2, y:y1, z:0}; //new cc.Vertex3F(x2, y1, 0);
- var g = {x:x2, y:y2, z:0}; // new cc.Vertex3F(x2, y2, 0);
- var h = {x:x1, y:y2, z:0}; //new cc.Vertex3F(x1, y2, 0);
+ var e = {x: x1, y: y1, z: 0}; //new cc.Vertex3F(x1, y1, 0);
+ var f = {x: x2, y: y1, z: 0}; //new cc.Vertex3F(x2, y1, 0);
+ var g = {x: x2, y: y2, z: 0}; // new cc.Vertex3F(x2, y2, 0);
+ var h = {x: x1, y: y2, z: 0}; //new cc.Vertex3F(x1, y2, 0);
var l2 = [e, f, g, h];
var tex1 = [a * 2, b * 2, c * 2, d * 2];
@@ -562,11 +559,11 @@ cc.Grid3D = cc.GridBase.extend(/** @lends cc.Grid3D# */{
this._dirty = true;
},
- setNeedDepthTestForBlit: function(needDepthTest){
+ setNeedDepthTestForBlit: function (needDepthTest) {
this._needDepthTestForBlit = needDepthTest;
},
- getNeedDepthTestForBlit: function(){
+ getNeedDepthTestForBlit: function () {
return this._needDepthTestForBlit;
}
});
@@ -590,14 +587,14 @@ cc.Grid3D.create = function (gridSize, texture, flipped) {
* @extends cc.GridBase
*/
cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
- _texCoordinates:null,
- _vertices:null,
- _originalVertices:null,
- _indices:null,
+ _texCoordinates: null,
+ _vertices: null,
+ _originalVertices: null,
+ _indices: null,
- _texCoordinateBuffer:null,
- _verticesBuffer:null,
- _indicesBuffer:null,
+ _texCoordinateBuffer: null,
+ _verticesBuffer: null,
+ _indicesBuffer: null,
/**
* create one TiledGrid3D object
@@ -606,21 +603,21 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
* @param {cc.Texture2D} [texture=]
* @param {Boolean} [flipped=]
*/
- ctor:function (gridSize, texture, flipped, rect) {
+ ctor: function (gridSize, texture, flipped, rect) {
cc.GridBase.prototype.ctor.call(this);
- this._texCoordinates=null;
- this._vertices=null;
- this._originalVertices=null;
- this._indices=null;
+ this._texCoordinates = null;
+ this._vertices = null;
+ this._originalVertices = null;
+ this._indices = null;
- this._texCoordinateBuffer=null;
- this._verticesBuffer=null;
- this._indicesBuffer=null;
+ this._texCoordinateBuffer = null;
+ this._verticesBuffer = null;
+ this._indicesBuffer = null;
this._matrix = new cc.math.Matrix4();
this._matrix.identity();
- if(gridSize !== undefined)
+ if (gridSize !== undefined)
this.initWithSize(gridSize, texture, flipped, rect);
},
@@ -630,7 +627,7 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
* @param {cc.Point} pos
* @return {cc.Quad3}
*/
- tile:function (pos) {
+ tile: function (pos) {
return this.getTile(pos);
},
@@ -639,15 +636,15 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
* @param {cc.Point} pos
* @return {cc.Quad3}
*/
- getTile: function(pos){
- if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y))
+ getTile: function (pos) {
+ if (pos.x !== (0 | pos.x) || pos.y !== (0 | pos.y))
cc.log("cc.TiledGrid3D.tile() : Numbers must be integers");
var idx = (this._gridSize.height * pos.x + pos.y) * 4 * 3;
var locVertices = this._vertices;
return new cc.Quad3(new cc.Vertex3F(locVertices[idx], locVertices[idx + 1], locVertices[idx + 2]),
new cc.Vertex3F(locVertices[idx + 3], locVertices[idx + 4], locVertices[idx + 5]),
- new cc.Vertex3F(locVertices[idx + 6 ], locVertices[idx + 7], locVertices[idx + 8]),
+ new cc.Vertex3F(locVertices[idx + 6], locVertices[idx + 7], locVertices[idx + 8]),
new cc.Vertex3F(locVertices[idx + 9], locVertices[idx + 10], locVertices[idx + 11]));
},
@@ -656,15 +653,15 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
* @param {cc.Point} pos
* @return {cc.Quad3}
*/
- getOriginalTile:function (pos) {
- if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y))
+ getOriginalTile: function (pos) {
+ if (pos.x !== (0 | pos.x) || pos.y !== (0 | pos.y))
cc.log("cc.TiledGrid3D.originalTile() : Numbers must be integers");
var idx = (this._gridSize.height * pos.x + pos.y) * 4 * 3;
var locOriginalVertices = this._originalVertices;
return new cc.Quad3(new cc.Vertex3F(locOriginalVertices[idx], locOriginalVertices[idx + 1], locOriginalVertices[idx + 2]),
new cc.Vertex3F(locOriginalVertices[idx + 3], locOriginalVertices[idx + 4], locOriginalVertices[idx + 5]),
- new cc.Vertex3F(locOriginalVertices[idx + 6 ], locOriginalVertices[idx + 7], locOriginalVertices[idx + 8]),
+ new cc.Vertex3F(locOriginalVertices[idx + 6], locOriginalVertices[idx + 7], locOriginalVertices[idx + 8]),
new cc.Vertex3F(locOriginalVertices[idx + 9], locOriginalVertices[idx + 10], locOriginalVertices[idx + 11]));
},
@@ -674,7 +671,7 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
* @param {cc.Point} pos
* @return {cc.Quad3}
*/
- originalTile: function(pos) {
+ originalTile: function (pos) {
return this.getOriginalTile(pos);
},
@@ -683,8 +680,8 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
* @param {cc.Point} pos
* @param {cc.Quad3} coords
*/
- setTile:function (pos, coords) {
- if(pos.x !== (0| pos.x) || pos.y !== (0| pos.y))
+ setTile: function (pos, coords) {
+ if (pos.x !== (0 | pos.x) || pos.y !== (0 | pos.y))
cc.log("cc.TiledGrid3D.setTile() : Numbers must be integers");
var idx = (this._gridSize.height * pos.x + pos.y) * 12;
@@ -715,9 +712,7 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
this._matrix.mat[5] = wt.d;
this._matrix.mat[13] = wt.ty;
- this._shaderProgram.use();
- this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix);
- //this._shaderProgram.setUniformsForBuiltins();
+ this._glProgramState.apply(this._matrix);
//
// Attributes
@@ -747,7 +742,7 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
cc.incrementGLDraws(1);
},
- reuse:function () {
+ reuse: function () {
if (this._reuseGrid > 0) {
var locVertices = this._vertices, locOriginalVertices = this._originalVertices;
for (var i = 0; i < locVertices.length; i++)
@@ -756,7 +751,7 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
}
},
- calculateVertexPoints:function () {
+ calculateVertexPoints: function () {
var width = this._texture.pixelsWidth;
var height = this._texture.pixelsHeight;
var imageH = this._texture.getContentSizeInPixels().height;
@@ -768,13 +763,13 @@ cc.TiledGrid3D = cc.GridBase.extend(/** @lends cc.TiledGrid3D# */{
this._indices = new Uint16Array(numQuads * 6);
var gl = cc._renderContext;
- if(this._verticesBuffer)
+ if (this._verticesBuffer)
gl.deleteBuffer(this._verticesBuffer);
this._verticesBuffer = gl.createBuffer();
- if(this._texCoordinateBuffer)
+ if (this._texCoordinateBuffer)
gl.deleteBuffer(this._texCoordinateBuffer);
this._texCoordinateBuffer = gl.createBuffer();
- if(this._indicesBuffer)
+ if (this._indicesBuffer)
gl.deleteBuffer(this._indicesBuffer);
this._indicesBuffer = gl.createBuffer();
diff --git a/cocos2d/kazmath/gl/mat4stack.js b/cocos2d/kazmath/gl/mat4stack.js
index ecd3aceba3..cd339423e2 100644
--- a/cocos2d/kazmath/gl/mat4stack.js
+++ b/cocos2d/kazmath/gl/mat4stack.js
@@ -26,54 +26,55 @@
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-(function(cc){
+(function (cc) {
/**
* The stack of cc.math.Matrix4
* @param {cc.math.Matrix4} [top]
* @param {Array} [stack]
* @constructor
*/
- cc.math.Matrix4Stack = function(top, stack) {
+ cc.math.Matrix4Stack = function (top, stack) {
this.top = top;
this.stack = stack || [];
+ this.lastUpdated = 0;
//this._matrixPool = []; // use pool in next version
};
cc.km_mat4_stack = cc.math.Matrix4Stack;
var proto = cc.math.Matrix4Stack.prototype;
- proto.initialize = function() { //cc.km_mat4_stack_initialize
+ proto.initialize = function () { //cc.km_mat4_stack_initialize
this.stack.length = 0;
this.top = null;
};
//for compatibility
- cc.km_mat4_stack_push = function(stack, item){
+ cc.km_mat4_stack_push = function (stack, item) {
stack.stack.push(stack.top);
stack.top = new cc.math.Matrix4(item);
};
- cc.km_mat4_stack_pop = function(stack, pOut){
+ cc.km_mat4_stack_pop = function (stack, pOut) {
stack.top = stack.stack.pop();
};
- cc.km_mat4_stack_release = function(stack){
+ cc.km_mat4_stack_release = function (stack) {
stack.stack = null;
stack.top = null;
};
- proto.push = function(item) {
+ proto.push = function (item) {
item = item || this.top;
this.stack.push(this.top);
this.top = new cc.math.Matrix4(item);
//this.top = this._getFromPool(item);
};
- proto.pop = function() {
+ proto.pop = function () {
//this._putInPool(this.top);
this.top = this.stack.pop();
};
- proto.release = function(){
+ proto.release = function () {
this.stack = null;
this.top = null;
this._matrixPool = null;
@@ -88,7 +89,7 @@
return ret;
};
- proto._putInPool = function(matrix){
+ proto._putInPool = function (matrix) {
this._matrixPool.push(matrix);
};
})(cc);
diff --git a/cocos2d/kazmath/gl/matrix.js b/cocos2d/kazmath/gl/matrix.js
index ae2605db06..13c9798125 100644
--- a/cocos2d/kazmath/gl/matrix.js
+++ b/cocos2d/kazmath/gl/matrix.js
@@ -26,7 +26,7 @@
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
-(function(cc) {
+(function (cc) {
cc.KM_GL_MODELVIEW = 0x1700;
cc.KM_GL_PROJECTION = 0x1701;
cc.KM_GL_TEXTURE = 0x1702;
@@ -106,6 +106,7 @@
throw new Error("Invalid matrix mode specified"); //TODO: Proper error handling
break;
}
+ cc.current_stack.lastUpdated = cc.director.getTotalFrames();
};
cc.kmGLLoadIdentity = function () {
diff --git a/cocos2d/labels/CCLabelAtlas.js b/cocos2d/labels/CCLabelAtlas.js
index 2b8c06178f..c5cd81669b 100644
--- a/cocos2d/labels/CCLabelAtlas.js
+++ b/cocos2d/labels/CCLabelAtlas.js
@@ -27,7 +27,7 @@
/**
* using image file to print text label on the screen, might be a bit slower than cc.Label, similar to cc.LabelBMFont
* @class
- * @extends cc.AtlasNode
+ * @extends cc.LabelBMFont
*
* @property {String} string - Content string of label
*
@@ -43,14 +43,7 @@
* //creates the cc.LabelAtlas with a string, a fnt file
* var myLabel = new cc.LabelAtlas('Text to display', 'CharMapFile.plist‘);
*/
-cc.LabelAtlas = cc.AtlasNode.extend(/** @lends cc.LabelAtlas# */{
- //property String is Getter and Setter
- // string to render
- _string: null,
- // the first char in the charmap
- _mapStartChar: null,
-
- _textureLoaded: false,
+cc.LabelAtlas = cc.LabelBMFont.extend(/** @lends cc.LabelBMFont# */{
_className: "LabelAtlas",
/**
@@ -68,35 +61,47 @@ cc.LabelAtlas = cc.AtlasNode.extend(/** @lends cc.LabelAtlas# */{
* @param {Number} [startCharMap=""]
*/
ctor: function (strText, charMapFile, itemWidth, itemHeight, startCharMap) {
- cc.AtlasNode.prototype.ctor.call(this);
+ cc.SpriteBatchNode.prototype.ctor.call(this);
+ this._imageOffset = cc.p(0, 0);
+ this._cascadeColorEnabled = true;
+ this._cascadeOpacityEnabled = true;
- this._renderCmd.setCascade();
charMapFile && cc.LabelAtlas.prototype.initWithString.call(this, strText, charMapFile, itemWidth, itemHeight, startCharMap);
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
- return new cc.LabelAtlas.WebGLRenderCmd(this);
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ return new cc.LabelBMFont.WebGLRenderCmd(this);
else
- return new cc.LabelAtlas.CanvasRenderCmd(this);
+ return new cc.LabelBMFont.CanvasRenderCmd(this);
},
- /**
- * Return texture is loaded.
- * @returns {boolean}
- */
- textureLoaded: function () {
- return this._textureLoaded;
- },
+ _createFntConfig: function (texture, itemWidth, itemHeight, startCharMap) {
+ var fnt = {};
+ fnt.commonHeight = itemHeight;
+
+ var fontDefDictionary = fnt.fontDefDictionary = {};
+
+ var textureWidth = texture.pixelsWidth;
+ var textureHeight = texture.pixelsHeight;
+
+ var startCharCode = startCharMap.charCodeAt(0);
+ var i = 0;
+ for (var col = itemHeight; col <= textureHeight; col += itemHeight) {
+ for (var row = 0; row < textureWidth; row += itemWidth) {
+ fontDefDictionary[startCharCode+i] = {
+ rect: {x: row, y: col - itemHeight, width:itemWidth, height: itemHeight },
+ xOffset: 0,
+ yOffset: 0,
+ xAdvance: itemWidth
+ };
+ ++i;
+ }
+ }
- /**
- * Add texture loaded event listener.
- * @param {Function} callback
- * @param {cc.Node} target
- * @deprecated since 3.1, please use addEventListener instead
- */
- addLoadedEventListener: function (callback, target) {
- this.addEventListener("load", callback, target);
+ fnt.kerningDict = {};
+
+ return fnt;
},
/**
@@ -116,6 +121,10 @@ cc.LabelAtlas = cc.AtlasNode.extend(/** @lends cc.LabelAtlas# */{
*/
initWithString: function (strText, charMapFile, itemWidth, itemHeight, startCharMap) {
var label = strText + "", textureFilename, width, height, startChar;
+ var self = this, theString = label || "";
+ this._initialString = theString;
+ self._string = theString;
+
if (itemWidth === undefined) {
var dict = cc.loader.getRes(charMapFile);
if (parseInt(dict["version"], 10) !== 1) {
@@ -135,88 +144,63 @@ cc.LabelAtlas = cc.AtlasNode.extend(/** @lends cc.LabelAtlas# */{
startChar = startCharMap || " ";
}
- var texture = null;
- if (textureFilename instanceof cc.Texture2D)
- texture = textureFilename;
- else
- texture = cc.textureCache.addImage(textureFilename);
- var locLoaded = texture.isLoaded();
- this._textureLoaded = locLoaded;
- if (!locLoaded) {
- this._string = label;
- texture.addEventListener("load", function (sender) {
- this.initWithTexture(texture, width, height, label.length);
- this.string = this._string;
- this.setColor(this._renderCmd._displayedColor);
- this.dispatchEvent("load");
- }, this);
- }
- if (this.initWithTexture(texture, width, height, label.length)) {
- this._mapStartChar = startChar;
- this.string = label;
- return true;
+ var texture;
+ if (charMapFile) {
+ self._fntFile = "dummy_fnt_file:" + textureFilename;
+ var spriteFrameBaseName = textureFilename;
+ var spriteFrame = cc.spriteFrameCache.getSpriteFrame(spriteFrameBaseName) || cc.spriteFrameCache.getSpriteFrame(cc.path.basename(spriteFrameBaseName));
+ if(spriteFrame) {
+ texture = spriteFrame.getTexture();
+ this._spriteFrame = spriteFrame;
+ } else {
+ texture = cc.textureCache.addImage(textureFilename);
+ }
+
+ var newConf = this._createFntConfig(texture, width, height, startChar);
+ newConf.atlasName = textureFilename;
+ self._config = newConf;
+
+ var locIsLoaded = texture.isLoaded();
+ self._textureLoaded = locIsLoaded;
+ if (!locIsLoaded) {
+ texture.addEventListener("load", function (sender) {
+ var self1 = this;
+ self1._textureLoaded = true;
+ //reset the LabelBMFont
+ self1.initWithTexture(sender, self1._initialString.length);
+ self1.setString(self1._initialString, true);
+ self1.dispatchEvent("load");
+ }, self);
+ }
+ } else {
+ texture = new cc.Texture2D();
+ var image = new Image();
+ texture.initWithElement(image);
+ self._textureLoaded = false;
}
- return false;
- },
- /**
- * Set the color.
- * @param {cc.Color} color3
- */
- setColor: function (color3) {
- cc.AtlasNode.prototype.setColor.call(this, color3);
- this._renderCmd.updateAtlasValues();
- },
+ if (self.initWithTexture(texture, theString.length)) {
+ self._alignment = cc.TEXT_ALIGNMENT_LEFT;
+ self._imageOffset = cc.p(0, 0);
+ self._width = -1;
- /**
- * return the text of this label
- * @return {String}
- */
- getString: function () {
- return this._string;
- },
+ self._realOpacity = 255;
+ self._realColor = cc.color(255, 255, 255, 255);
- addChild: function(child, localZOrder, tag){
- this._renderCmd._addChild(child);
- cc.Node.prototype.addChild.call(this, child, localZOrder, tag);
- },
+ self._contentSize.width = 0;
+ self._contentSize.height = 0;
- /**
- * Atlas generation
- * @function
- */
- updateAtlasValues: function(){
- this._renderCmd.updateAtlasValues();
+ self.setString(theString, true);
+ return true;
+ }
+ return false;
},
- /**
- * set the display string
- * @function
- * @param {String} label
- */
- setString: function(label){
- label = String(label);
- var len = label.length;
- this._string = label;
- this.setContentSize(len * this._itemWidth, this._itemHeight);
- this._renderCmd.setString(label);
-
- this._renderCmd.updateAtlasValues();
- this.quadsToDraw = len;
+ setFntFile: function () {
+ cc.warn("setFntFile doesn't support with LabelAtlas.");
}
-});
-(function(){
- var proto = cc.LabelAtlas.prototype;
- // Override properties
- cc.defineGetterSetter(proto, "opacity", proto.getOpacity, proto.setOpacity);
- cc.defineGetterSetter(proto, "color", proto.getColor, proto.setColor);
-
- // Extended properties
- /** @expose */
- proto.string;
- cc.defineGetterSetter(proto, "string", proto.getString, proto.setString);
-})();
+});
/**
*
diff --git a/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js b/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js
index 9a7484d1ba..5edf6c501b 100644
--- a/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js
+++ b/cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js
@@ -22,8 +22,8 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- cc.LabelAtlas.WebGLRenderCmd = function(renderable){
+(function () {
+ cc.LabelAtlas.WebGLRenderCmd = function (renderable) {
cc.AtlasNode.WebGLRenderCmd.call(this, renderable);
this._needDraw = true;
};
@@ -50,13 +50,13 @@
}
};
- proto.setCascade = function(){
+ proto.setCascade = function () {
var node = this._node;
node._cascadeOpacityEnabled = true;
node._cascadeColorEnabled = true;
};
- proto.rendering = function(ctx){
+ proto.rendering = function (ctx) {
cc.AtlasNode.WebGLRenderCmd.prototype.rendering.call(this, ctx);
if (cc.LABELATLAS_DEBUG_DRAW) {
var node = this._node;
@@ -64,15 +64,15 @@
var locRect = node.getBoundingBoxToWorld();
var posX = locRect.x,
posY = locRect.y;
- s.width = locRect.width;
- s.height = locRect.height;
- var vertices = [cc.p(posX, posY), cc.p(posX+ s.width, posY),
- cc.p(s.width+posX, s.height+posY), cc.p(posX, posY+s.height)];
+ s.width = locRect.width;
+ s.height = locRect.height;
+ var vertices = [cc.p(posX, posY), cc.p(posX + s.width, posY),
+ cc.p(s.width + posX, s.height + posY), cc.p(posX, posY + s.height)];
cc._drawingUtil.drawPoly(vertices, 4, true);
}
};
- proto.updateAtlasValues = function(){
+ proto.updateAtlasValues = function () {
var node = this._node;
var locString = node._string;
var n = locString.length;
@@ -96,9 +96,9 @@
var a = locString.charCodeAt(i) - node._mapStartChar.charCodeAt(0);
var row = a % node._itemsPerRow;
var col = 0 | (a / node._itemsPerRow);
- if(row < 0 || col < 0)
+ if (row < 0 || col < 0)
continue;
- if(row*locItemWidth + locItemWidth > textureWide || col*locItemHeight + locItemHeight > textureHigh)
+ if (row * locItemWidth + locItemWidth > textureWide || col * locItemHeight + locItemHeight > textureHigh)
continue;
cr++;
@@ -142,7 +142,7 @@
this._updateColor();
- this.updateContentSize(i, cr+1);
+ this.updateContentSize(i, cr + 1);
if (n > 0) {
locTextureAtlas.dirty = true;
var totalQuads = locTextureAtlas.totalQuads;
@@ -151,19 +151,20 @@
}
};
- proto.updateContentSize = function(i, cr){
+ proto.updateContentSize = function (i, cr) {
var node = this._node,
contentSize = node._contentSize;
- if(i !== cr && i*node._itemWidth === contentSize.width && node._itemHeight === contentSize.height){
+ if (i !== cr && i * node._itemWidth === contentSize.width && node._itemHeight === contentSize.height) {
node.setContentSize(cr * node._itemWidth, node._itemHeight);
}
};
- proto.setString = function(label){
+ proto.setString = function (label) {
var len = label.length;
if (len > this._textureAtlas.totalQuads)
this._textureAtlas.resizeCapacity(len);
};
- proto._addChild = function(){};
-})();
\ No newline at end of file
+ proto._addChild = function () {
+ };
+})();
diff --git a/cocos2d/labels/CCLabelBMFont.js b/cocos2d/labels/CCLabelBMFont.js
index 0dd628e128..388f0e858c 100644
--- a/cocos2d/labels/CCLabelBMFont.js
+++ b/cocos2d/labels/CCLabelBMFont.js
@@ -106,8 +106,8 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
_textureLoaded: false,
_className: "LabelBMFont",
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
return new cc.LabelBMFont.WebGLRenderCmd(this);
else
return new cc.LabelBMFont.CanvasRenderCmd(this);
@@ -119,6 +119,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
} else {
this._initialString = newString;
}
+
var locChildren = this._children;
if (locChildren) {
for (var i = 0; i < locChildren.length; i++) {
@@ -128,7 +129,9 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
}
}
if (this._textureLoaded) {
- this.createFontChars();
+ if(this._string && this._string.length > 0) {
+ this.createFontChars();
+ }
if (needUpdateLabel)
this.updateLabel();
}
@@ -224,13 +227,23 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
if (fntFile) {
var newConf = cc.loader.getRes(fntFile);
if (!newConf) {
- cc.log("cc.LabelBMFont.initWithString(): Impossible to create font. Please check file");
- return false;
+ newConf = cc.FntFrameCache[fntFile] || cc.FntFrameCache[cc.path.basename(fntFile)];
+ if(!newConf) {
+ cc.log("cc.LabelBMFont.initWithString(): Impossible to create font. Please check file");
+ return false;
+ }
}
self._config = newConf;
self._fntFile = fntFile;
- texture = cc.textureCache.addImage(newConf.atlasName);
+ var spriteFrameBaseName = newConf.atlasName;
+ var spriteFrame = cc.spriteFrameCache.getSpriteFrame(spriteFrameBaseName) || cc.spriteFrameCache.getSpriteFrame(cc.path.basename(spriteFrameBaseName));
+ if(spriteFrame) {
+ texture = spriteFrame.getTexture();
+ this._spriteFrame = spriteFrame;
+ } else {
+ texture = cc.textureCache.addImage(newConf.atlasName);
+ }
var locIsLoaded = texture.isLoaded();
self._textureLoaded = locIsLoaded;
if (!locIsLoaded) {
@@ -264,6 +277,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
self.setAnchorPoint(0.5, 0.5);
self.setString(theString, true);
+
return true;
}
return false;
@@ -273,6 +287,9 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
* updates the font chars based on the string to render
*/
createFontChars: function () {
+ var locStr = this._string;
+ var stringLen = locStr ? locStr.length : 0;
+
var self = this;
var cmd = this._renderCmd;
var locTexture = cmd._texture || this._texture;
@@ -285,11 +302,6 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
var quantityOfLines = 1;
- var locStr = self._string;
- var stringLen = locStr ? locStr.length : 0;
-
- if (stringLen === 0)
- return;
var i, locCfg = self._config, locKerningDict = locCfg.kerningDict,
locCommonH = locCfg.commonHeight, locFontDict = locCfg.fontDefDictionary;
@@ -336,15 +348,30 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
rect.x += self._imageOffset.x;
rect.y += self._imageOffset.y;
+ var isRotated = false;
+ if(this._spriteFrame) {
+ var textureWidth = locTexture.width;
+ var spriteFrameRect = this._spriteFrame._rect;
+ if(!this._spriteFrame._rotated) {
+ rect.x = rect.x + spriteFrameRect.x;
+ rect.y = rect.y + spriteFrameRect.y;
+ } else {
+ isRotated = true;
+ var originalX = rect.x;
+ rect.x = rect.y + spriteFrameRect.x;
+ rect.y = originalX + spriteFrameRect.y;
+ }
+ }
+
var fontChar = self.getChildByTag(i);
if (!fontChar) {
fontChar = new cc.Sprite();
- fontChar.initWithTexture(locTexture, rect, false);
+ fontChar.initWithTexture(locTexture, rect, isRotated);
fontChar._newTextureWhenChangeColor = true;
this.addChild(fontChar, 0, i);
} else {
- cmd._updateCharTexture(fontChar, rect, key);
+ cmd._updateCharTexture(fontChar, rect, key, isRotated);
}
// Apply label properties
@@ -366,7 +393,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
//If the last character processed has an xAdvance which is less that the width of the characters image, then we need
// to adjust the width of the string to take this into account, or the character will overlap the end of the bounding box
- if(fontDef && fontDef.xAdvance < fontDef.rect.width)
+ if (fontDef && fontDef.xAdvance < fontDef.rect.width)
tmpSize.width = longestLine - fontDef.xAdvance + fontDef.rect.width;
else
tmpSize.width = longestLine;
@@ -383,13 +410,17 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
var self = this;
var locChildren = self._children;
if (locChildren) {
- for (var i = 0, li = locChildren.length; i < li; i++) {
+ var length = locChildren.length;
+ for (var i = 0, li = length; i < li; i++) {
var node = locChildren[i];
if (node) node.visible = false;
}
}
- if (self._config)
- self.createFontChars();
+ if (self._config) {
+ if(self._string && self._string.length > 0) {
+ self.createFontChars();
+ }
+ }
if (!fromUpdate)
self.updateLabel();
@@ -410,9 +441,9 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
*/
setString: function (newString, needUpdateLabel) {
newString = String(newString);
- if (needUpdateLabel == null)
+ if (needUpdateLabel === undefined)
needUpdateLabel = true;
- if (newString == null || !cc.isString(newString))
+ if (newString === undefined || typeof newString !== 'string')
newString = newString + "";
this._initialString = newString;
@@ -434,9 +465,8 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
},
// calc the text all with in a line
- _getCharsWidth:function (startIndex, endIndex) {
- if (endIndex <= 0)
- {
+ _getCharsWidth: function (startIndex, endIndex) {
+ if (endIndex <= 0) {
return 0;
}
var curTextFirstSprite = this.getChildByTag(startIndex);
@@ -444,12 +474,11 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
return this._getLetterPosXLeft(curTextLastSprite) - this._getLetterPosXLeft(curTextFirstSprite);
},
- _checkWarp:function (strArr, i, maxWidth, initStringWrapNum) {
+ _checkWarp: function (strArr, i, maxWidth, initStringWrapNum) {
var self = this;
var text = strArr[i];
var curLength = 0;
- for (var strArrIndex = 0; strArrIndex < i; strArrIndex++)
- {
+ for (var strArrIndex = 0; strArrIndex < i; strArrIndex++) {
curLength += strArr[strArrIndex].length;
}
@@ -540,6 +569,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
updateLabel: function () {
var self = this;
self.string = self._initialString;
+
var i, j, characterSprite;
// process string
// Step 1: Make multiline
@@ -554,8 +584,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
if (oldArrLength < stringArr.length) {
newWrapNum++;
}
- if (i > 0)
- {
+ if (i > 0) {
wrapString += "\n";
}
wrapString += stringArr[i];
@@ -563,7 +592,6 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
wrapString = wrapString + String.fromCharCode(0);
self._setString(wrapString, false);
}
-
// Step 2: Make alignment
if (self._alignment !== cc.TEXT_ALIGNMENT_LEFT) {
i = 0;
@@ -718,7 +746,10 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
var self1 = this;
self1._textureLoaded = true;
self1.setTexture(sender);
- self1.createFontChars();
+ if(self1._string && self1._string.length > 0) {
+ self1.createFontChars();
+ }
+
self1._changeTextureColor();
self1.updateLabel();
@@ -726,7 +757,9 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
}, self);
} else {
self.setTexture(texture);
- self.createFontChars();
+ if(self._string && self._string.length > 0) {
+ self.createFontChars();
+ }
}
}
},
@@ -739,7 +772,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
return this._fntFile;
},
- setTexture: function(texture){
+ setTexture: function (texture) {
this._texture = texture;
this._renderCmd.setTexture(texture);
},
@@ -766,7 +799,8 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
this.updateLabel();
},
- _atlasNameFromFntFile: function (fntFile) {},
+ _atlasNameFromFntFile: function (fntFile) {
+ },
_kerningAmountForFirst: function (first, second) {
var ret = 0;
@@ -788,14 +822,14 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
},
//Checking whether the character is a whitespace
- _isspace_unicode: function(ch){
+ _isspace_unicode: function (ch) {
ch = ch.charCodeAt(0);
- return ((ch >= 9 && ch <= 13) || ch === 32 || ch === 133 || ch === 160 || ch === 5760
- || (ch >= 8192 && ch <= 8202) || ch === 8232 || ch === 8233 || ch === 8239
- || ch === 8287 || ch === 12288)
+ return ((ch >= 9 && ch <= 13) || ch === 32 || ch === 133 || ch === 160 || ch === 5760
+ || (ch >= 8192 && ch <= 8202) || ch === 8232 || ch === 8233 || ch === 8239
+ || ch === 8287 || ch === 12288);
},
- _utf8_trim_ws: function(str){
+ _utf8_trim_ws: function (str) {
var len = str.length;
if (len <= 0)
@@ -819,7 +853,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
//Trims str st str=[0, index) after the operation.
//Return value: the trimmed string.
- _utf8_trim_from: function(str, index){
+ _utf8_trim_from: function (str, index) {
var len = str.length;
if (index >= len || index < 0)
return;
@@ -827,7 +861,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
}
});
-(function(){
+(function () {
var p = cc.LabelBMFont.prototype;
cc.EventHelper.prototype.apply(p);
@@ -859,7 +893,11 @@ cc.LabelBMFont.create = function (str, fntFile, width, alignment, imageOffset) {
return new cc.LabelBMFont(str, fntFile, width, alignment, imageOffset);
};
+cc.FntFrameCache = {};
+
var _fntLoader = {
+ FNT_HEAD: /fntframes [^\n]*(\n|$)/gi,
+ FNT_FRAME_NAME: /fntframe [^\n]*(\n|$)/gi,
INFO_EXP: /info [^\n]*(\n|$)/gi,
COMMON_EXP: /common [^\n]*(\n|$)/gi,
PAGE_EXP: /page [^\n]*(\n|$)/gi,
@@ -885,24 +923,8 @@ var _fntLoader = {
return obj;
},
- /**
- * Parse Fnt string.
- * @param fntStr
- * @param url
- * @returns {{}}
- */
- parseFnt: function (fntStr, url) {
- var self = this, fnt = {};
- //padding
- var infoObj = self._parseStrToObj(fntStr.match(self.INFO_EXP)[0]);
- var paddingArr = infoObj["padding"].split(",");
- var padding = {
- left: parseInt(paddingArr[0]),
- top: parseInt(paddingArr[1]),
- right: parseInt(paddingArr[2]),
- bottom: parseInt(paddingArr[3])
- };
-
+ _parseFntContent: function (fnt, fntStr, url, useAtlas) {
+ var self = this;
//common
var commonObj = self._parseStrToObj(fntStr.match(self.COMMON_EXP)[0]);
fnt.commonHeight = commonObj["lineHeight"];
@@ -916,7 +938,11 @@ var _fntLoader = {
//page
var pageObj = self._parseStrToObj(fntStr.match(self.PAGE_EXP)[0]);
if (pageObj["id"] !== 0) cc.log("cc.LabelBMFont._parseImageFileName() : file could not be found");
- fnt.atlasName = cc.path.changeBasename(url, pageObj["file"]);
+ if(!useAtlas) {
+ fnt.atlasName = cc.path.changeBasename(url, pageObj["file"]);
+ } else {
+ fnt.atlasName = cc.path.join(cc.path.dirname(useAtlas.path) + pageObj["file"]);
+ }
//char
var charLines = fntStr.match(self.CHAR_EXP);
@@ -941,6 +967,40 @@ var _fntLoader = {
kerningDict[(kerningObj["first"] << 16) | (kerningObj["second"] & 0xffff)] = kerningObj["amount"];
}
}
+
+ return fnt;
+ },
+
+ /**
+ * Parse Fnt string.
+ * @param fntStr
+ * @param url
+ * @returns {{}}
+ */
+ parseFnt: function (fntStr, url) {
+ var self = this, fnt = {};
+ var headString = fntStr.match(self.FNT_HEAD);
+ if(headString) {
+ var headObj = self._parseStrToObj(headString[0]);
+ if(headObj && headObj.count) {
+ fntStr = fntStr.substr(headString[0].length);
+ var fntFrames = fntStr.split("----");
+ for(var i = 0; i < headObj.count; ++i) {
+ var contentString = fntFrames[i];
+ var frameNameStr = contentString.match(self.FNT_FRAME_NAME);
+ if(frameNameStr) {
+ var frameName = self._parseStrToObj(frameNameStr[0]);
+ if(frameName && frameName.name) {
+ fnt = {};
+ var realFntPathKey = cc.path.join(cc.path.dirname(url), frameName.name);
+ cc.FntFrameCache[realFntPathKey] = this._parseFntContent(fnt, contentString.substr(frameNameStr[0].length), url, {path: frameName.name});
+ }
+ }
+ }
+ }
+ } else {
+ fnt = this._parseFntContent(fnt, fntStr, url);
+ }
return fnt;
},
diff --git a/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js b/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js
index 1f34cd6cb4..5861daa30a 100644
--- a/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js
+++ b/cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js
@@ -30,15 +30,15 @@
http://www.angelcode.com/products/bmfont/ (Free, Windows only)
****************************************************************************/
-(function(){
- cc.LabelBMFont.CanvasRenderCmd = function(renderableObject){
- cc.Node.CanvasRenderCmd.call(this, renderableObject);
+(function () {
+ cc.LabelBMFont.CanvasRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
};
var proto = cc.LabelBMFont.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
proto.constructor = cc.LabelBMFont.CanvasRenderCmd;
- proto._updateCharTexture = function(fontChar, rect, key){
+ proto._updateCharTexture = function (fontChar, rect, key) {
if (key === 32) {
fontChar.setTextureRect(rect, false, cc.size(0, 0));
} else {
@@ -49,7 +49,7 @@
}
};
- proto._updateCharColorAndOpacity = function(fontChar){
+ proto._updateCharColorAndOpacity = function (fontChar) {
// Color MUST be set before opacity, since opacity might change color if OpacityModifyRGB is on
fontChar._displayedColor = this._displayedColor;
fontChar._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.colorDirty);
@@ -73,7 +73,7 @@
node._texture = texture;
};
- proto._changeTextureColor = function(){
+ proto._changeTextureColor = function () {
var node = this._node;
var texture = node._texture,
contentSize = texture.getContentSize();
@@ -83,19 +83,19 @@
var disColor = this._displayedColor;
var textureRect = cc.rect(0, 0, oElement.width, oElement.height);
if (texture && contentSize.width > 0) {
- if(!oElement)
+ if (!oElement)
return;
var textureToRender = oTexture._generateColorTexture(disColor.r, disColor.g, disColor.b, textureRect);
node.setTexture(textureToRender);
}
};
- proto._updateChildrenDisplayedOpacity = function(locChild){
+ proto._updateChildrenDisplayedOpacity = function (locChild) {
cc.Node.prototype.updateDisplayedOpacity.call(locChild, this._displayedOpacity);
};
- proto._updateChildrenDisplayedColor = function(locChild){
+ proto._updateChildrenDisplayedColor = function (locChild) {
cc.Node.prototype.updateDisplayedColor.call(locChild, this._displayedColor);
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js b/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js
index 68d5c374a7..09e18a5f6b 100644
--- a/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js
+++ b/cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js
@@ -30,9 +30,9 @@
http://www.angelcode.com/products/bmfont/ (Free, Windows only)
****************************************************************************/
-(function(){
- cc.LabelBMFont.WebGLRenderCmd = function(renderableObject){
- cc.Node.WebGLRenderCmd.call(this, renderableObject);
+(function () {
+ cc.LabelBMFont.WebGLRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
};
var proto = cc.LabelBMFont.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
@@ -42,14 +42,16 @@
this._node.setOpacityModifyRGB(this._node._texture.hasPremultipliedAlpha());
};
- proto._updateCharTexture = function(fontChar, rect, key){
+ proto._updateCharTexture = function(fontChar, rect, key, isRotated){
// updating previous sprite
- fontChar.setTextureRect(rect, false);
+ fontChar.setTextureRect(rect, isRotated);
// restore to default in case they were modified
fontChar.visible = true;
};
- proto._changeTextureColor = function(){};
+ proto._changeTextureColor = function () {
+ };
- proto._updateCharColorAndOpacity = function(){};
-})();
\ No newline at end of file
+ proto._updateCharColorAndOpacity = function () {
+ };
+})();
diff --git a/cocos2d/menus/CCMenu.js b/cocos2d/menus/CCMenu.js
index 6cf5703760..e3edd737ee 100644
--- a/cocos2d/menus/CCMenu.js
+++ b/cocos2d/menus/CCMenu.js
@@ -84,19 +84,14 @@ cc.Menu = cc.Layer.extend(/** @lends cc.Menu# */{
onTouchCancelled: this._onTouchCancelled
});
- if ((arguments.length > 0) && (arguments[arguments.length - 1] == null))
- cc.log("parameters should not be ending with null in Javascript");
-
var argc = arguments.length, items;
- if (argc === 0) {
+ if (menuItems instanceof Array) {
+ items = menuItems;
+ }
+ else if (argc === 0) {
items = [];
- } else if (argc === 1) {
- if (menuItems instanceof Array) {
- items = menuItems;
- }
- else items = [menuItems];
}
- else if (argc > 1) {
+ else if (argc > 0) {
items = [];
for (var i = 0; i < argc; i++) {
if (arguments[i])
@@ -281,8 +276,8 @@ cc.Menu = cc.Layer.extend(/** @lends cc.Menu# */{
if ((arguments.length > 0) && (arguments[arguments.length - 1] == null))
cc.log("parameters should not be ending with null in Javascript");
- var rows = [];
- for (var i = 0; i < arguments.length; i++) {
+ var i, rows = [];
+ for (i = 0; i < arguments.length; i++) {
rows.push(arguments[i]);
}
var height = -5;
@@ -363,7 +358,7 @@ cc.Menu = cc.Layer.extend(/** @lends cc.Menu# */{
alignItemsInRows: function (/*Multiple arguments*/) {
if ((arguments.length > 0) && (arguments[arguments.length - 1] == null))
cc.log("parameters should not be ending with null in Javascript");
- var columns = [], i;
+ var i, columns = [];
for (i = 0; i < arguments.length; i++) {
columns.push(arguments[i]);
}
@@ -558,7 +553,7 @@ cc.Menu = cc.Layer.extend(/** @lends cc.Menu# */{
},
/**
* only use for jsbinding
- * @returns {boolean}
+ * @returns {boolean}
*/
isOpacityModifyRGB: function () {
return false;
diff --git a/cocos2d/motion-streak/CCMotionStreak.js b/cocos2d/motion-streak/CCMotionStreak.js
index 1553aa4c2a..158393454a 100644
--- a/cocos2d/motion-streak/CCMotionStreak.js
+++ b/cocos2d/motion-streak/CCMotionStreak.js
@@ -44,33 +44,33 @@
* new cc.MotionStreak(2, 3, 32, cc.color.GREEN, s_streak);
*/
cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
- texture:null,
- fastMode:false,
- startingPositionInitialized:false,
+ texture: null,
+ fastMode: false,
+ startingPositionInitialized: false,
- _blendFunc:null,
+ _blendFunc: null,
- _stroke:0,
- _fadeDelta:0,
- _minSeg:0,
+ _stroke: 0,
+ _fadeDelta: 0,
+ _minSeg: 0,
- _maxPoints:0,
- _nuPoints:0,
- _previousNuPoints:0,
+ _maxPoints: 0,
+ _nuPoints: 0,
+ _previousNuPoints: 0,
/* Pointers */
- _pointVertexes:null,
- _pointState:null,
+ _pointVertexes: null,
+ _pointState: null,
// webgl
- _vertices:null,
- _colorPointer:null,
- _texCoords:null,
+ _vertices: null,
+ _colorPointer: null,
+ _texCoords: null,
- _verticesBuffer:null,
- _colorPointerBuffer:null,
- _texCoordsBuffer:null,
- _className:"MotionStreak",
+ _verticesBuffer: null,
+ _colorPointerBuffer: null,
+ _texCoordsBuffer: null,
+ _className: "MotionStreak",
/**
* creates and initializes a motion streak with fade in seconds, minimum segments, stroke's width, color, texture filename or texture
@@ -112,7 +112,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
this._colorPointerBuffer = null;
this._texCoordsBuffer = null;
- if(texture !== undefined)
+ if (texture !== undefined)
this.initWithFade(fade, minSeg, stroke, color, texture);
},
@@ -120,7 +120,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Gets the texture.
* @return {cc.Texture2D}
*/
- getTexture:function () {
+ getTexture: function () {
return this.texture;
},
@@ -128,7 +128,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Set the texture.
* @param {cc.Texture2D} texture
*/
- setTexture:function (texture) {
+ setTexture: function (texture) {
if (this.texture !== texture)
this.texture = texture;
},
@@ -137,7 +137,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Gets the blend func.
* @return {cc.BlendFunc}
*/
- getBlendFunc:function () {
+ getBlendFunc: function () {
return this._blendFunc;
},
@@ -146,7 +146,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* @param {Number} src
* @param {Number} dst
*/
- setBlendFunc:function (src, dst) {
+ setBlendFunc: function (src, dst) {
if (dst === undefined) {
this._blendFunc = src;
} else {
@@ -160,7 +160,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* @warning cc.MotionStreak.getOpacity has not been supported.
* @returns {number}
*/
- getOpacity:function () {
+ getOpacity: function () {
cc.log("cc.MotionStreak.getOpacity has not been supported.");
return 0;
},
@@ -170,7 +170,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* @warning cc.MotionStreak.setOpacity has not been supported.
* @param opacity
*/
- setOpacity:function (opacity) {
+ setOpacity: function (opacity) {
cc.log("cc.MotionStreak.setOpacity has not been supported.");
},
@@ -179,14 +179,14 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* @warning cc.MotionStreak.setOpacityModifyRGB has not been supported.
* @param value
*/
- setOpacityModifyRGB:function (value) {
+ setOpacityModifyRGB: function (value) {
},
/**
* Checking OpacityModifyRGB.
* @returns {boolean}
*/
- isOpacityModifyRGB:function () {
+ isOpacityModifyRGB: function () {
return false;
},
@@ -194,7 +194,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Checking fast mode.
* @returns {boolean}
*/
- isFastMode:function () {
+ isFastMode: function () {
return this.fastMode;
},
@@ -202,7 +202,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* set fast mode
* @param {Boolean} fastMode
*/
- setFastMode:function (fastMode) {
+ setFastMode: function (fastMode) {
this.fastMode = fastMode;
},
@@ -210,7 +210,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Checking starting position initialized.
* @returns {boolean}
*/
- isStartingPositionInitialized:function () {
+ isStartingPositionInitialized: function () {
return this.startingPositionInitialized;
},
@@ -218,7 +218,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Set Starting Position Initialized.
* @param {Boolean} startingPositionInitialized
*/
- setStartingPositionInitialized:function (startingPositionInitialized) {
+ setStartingPositionInitialized: function (startingPositionInitialized) {
this.startingPositionInitialized = startingPositionInitialized;
},
@@ -226,7 +226,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Get stroke.
* @returns {Number} stroke
*/
- getStroke:function () {
+ getStroke: function () {
return this._stroke;
},
@@ -234,7 +234,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Set stroke.
* @param {Number} stroke
*/
- setStroke:function (stroke) {
+ setStroke: function (stroke) {
this._stroke = stroke;
},
@@ -247,14 +247,14 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* @param {string|cc.Texture2D} texture texture filename or texture
* @return {Boolean}
*/
- initWithFade:function (fade, minSeg, stroke, color, texture) {
- if(!texture)
+ initWithFade: function (fade, minSeg, stroke, color, texture) {
+ if (!texture)
throw new Error("cc.MotionStreak.initWithFade(): Invalid filename or texture");
if (cc.isString(texture))
texture = cc.textureCache.addImage(texture);
- cc.Node.prototype.setPosition.call(this, cc.p(0,0));
+ cc.Node.prototype.setPosition.call(this, cc.p(0, 0));
this.anchorX = 0;
this.anchorY = 0;
this.ignoreAnchor = true;
@@ -304,7 +304,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* color used for the tint
* @param {cc.Color} color
*/
- tintWithColor:function (color) {
+ tintWithColor: function (color) {
this.color = color;
// Fast assignation
@@ -319,7 +319,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
/**
* Remove all living segments of the ribbon
*/
- reset:function () {
+ reset: function () {
this._nuPoints = 0;
},
@@ -329,9 +329,9 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* @param {cc.Point|Number} position
* @param {Number} [yValue=undefined] If not exists, the first parameter must be cc.Point.
*/
- setPosition:function (position, yValue) {
+ setPosition: function (position, yValue) {
this.startingPositionInitialized = true;
- if(yValue === undefined){
+ if (yValue === undefined) {
this._positionR.x = position.x;
this._positionR.y = position.y;
} else {
@@ -344,7 +344,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Gets the position.x
* @return {Number}
*/
- getPositionX:function () {
+ getPositionX: function () {
return this._positionR.x;
},
@@ -352,9 +352,9 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Set the position.x
* @param {Number} x
*/
- setPositionX:function (x) {
+ setPositionX: function (x) {
this._positionR.x = x;
- if(!this.startingPositionInitialized)
+ if (!this.startingPositionInitialized)
this.startingPositionInitialized = true;
},
@@ -362,17 +362,17 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Gets the position.y
* @return {Number}
*/
- getPositionY:function () {
- return this._positionR.y;
+ getPositionY: function () {
+ return this._positionR.y;
},
/**
* Set the position.y
* @param {Number} y
*/
- setPositionY:function (y) {
+ setPositionY: function (y) {
this._positionR.y = y;
- if(!this.startingPositionInitialized)
+ if (!this.startingPositionInitialized)
this.startingPositionInitialized = true;
},
@@ -383,7 +383,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
* Only one "update" method could be scheduled per node.
* @param {Number} delta
*/
- update:function (delta) {
+ update: function (delta) {
if (!this.startingPositionInitialized)
return;
@@ -392,7 +392,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
delta *= this._fadeDelta;
- var newIdx, newIdx2, i, i2;
+ var i, newIdx, newIdx2, i2;
var mov = 0;
// Update current points
@@ -447,7 +447,7 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
appendNewPoint = false;
else if (locNuPoints > 0) {
var a1 = cc.pDistanceSQ(cc.p(locPointVertexes[(locNuPoints - 1) * 2], locPointVertexes[(locNuPoints - 1) * 2 + 1]),
- this._positionR) < this._minSeg;
+ this._positionR) < this._minSeg;
var a2 = (locNuPoints === 1) ? false : (cc.pDistanceSQ(
cc.p(locPointVertexes[(locNuPoints - 2) * 2], locPointVertexes[(locNuPoints - 2) * 2 + 1]), this._positionR) < (this._minSeg * 2.0));
if (a1 || a2)
@@ -506,8 +506,8 @@ cc.MotionStreak = cc.Node.extend(/** @lends cc.MotionStreak# */{
this._nuPoints = locNuPoints;
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
return new cc.MotionStreak.WebGLRenderCmd(this);
else
return null; //MotionStreak doesn't support Canvas mode
diff --git a/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js b/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js
index 69f4f12f5f..a7d793a336 100644
--- a/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js
+++ b/cocos2d/motion-streak/CCMotionStreakWebGLRenderCmd.js
@@ -22,8 +22,8 @@
THE SOFTWARE.
****************************************************************************/
-cc.MotionStreak.WebGLRenderCmd = function(renderableObject){
- cc.Node.WebGLRenderCmd.call(this, renderableObject);
+cc.MotionStreak.WebGLRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
this._needDraw = true;
this._matrix = new cc.math.Matrix4();
this._matrix.identity();
@@ -33,7 +33,7 @@ cc.MotionStreak.WebGLRenderCmd = function(renderableObject){
cc.MotionStreak.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
cc.MotionStreak.WebGLRenderCmd.prototype.constructor = cc.Sprite.WebGLRenderCmd;
-cc.MotionStreak.WebGLRenderCmd.prototype.rendering = function(ctx){
+cc.MotionStreak.WebGLRenderCmd.prototype.rendering = function (ctx) {
var node = this._node;
if (node._nuPoints <= 1)
return;
@@ -49,8 +49,7 @@ cc.MotionStreak.WebGLRenderCmd.prototype.rendering = function(ctx){
this._matrix.mat[5] = wt.d;
this._matrix.mat[13] = wt.ty;
- this._shaderProgram.use();
- this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix);
+ this._glProgramState.apply(this._matrix);
cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst);
cc.glBindTexture2D(node.texture);
@@ -77,4 +76,4 @@ cc.MotionStreak.WebGLRenderCmd.prototype.rendering = function(ctx){
ctx.drawArrays(ctx.TRIANGLE_STRIP, 0, node._nuPoints * 2);
cc.g_NumberOfDraws++;
}
-};
\ No newline at end of file
+};
diff --git a/cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js b/cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js
index 8c45377dfe..9288a0fd69 100644
--- a/cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js
+++ b/cocos2d/node-grid/CCNodeGridWebGLRenderCmd.js
@@ -22,9 +22,9 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- cc.NodeGrid.WebGLRenderCmd = function(renderable){
- cc.Node.WebGLRenderCmd.call(this, renderable);
+(function () {
+ cc.NodeGrid.WebGLRenderCmd = function (renderable) {
+ this._rootCtor(renderable);
this._needDraw = false;
this._gridBeginCommand = new cc.CustomRenderCmd(this, this.onGridBeginDraw);
this._gridEndCommand = new cc.CustomRenderCmd(this, this.onGridEndDraw);
@@ -33,15 +33,15 @@
var proto = cc.NodeGrid.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
proto.constructor = cc.NodeGrid.WebGLRenderCmd;
- proto.visit = function(parentCmd) {
+ proto.visit = function (parentCmd) {
var node = this._node;
// quick return if not visible
if (!node._visible)
return;
parentCmd = parentCmd || this.getParentRenderCmd();
- if (node._parent && node._parent._renderCmd)
- this._curLevel = node._parent._renderCmd._curLevel + 1;
+ if (parentCmd)
+ this._curLevel = parentCmd._curLevel + 1;
var currentStack = cc.current_stack;
currentStack.stack.push(currentStack.top);
@@ -49,16 +49,16 @@
currentStack.top = this._stackMatrix;
/*var beforeProjectionType = cc.director.PROJECTION_DEFAULT;
- if (locGrid && locGrid._active) {
- //var backMatrix = new cc.kmMat4();
- //cc.kmMat4Assign(backMatrix, this._stackMatrix);
+ if (locGrid && locGrid._active) {
+ //var backMatrix = new cc.kmMat4();
+ //cc.kmMat4Assign(backMatrix, this._stackMatrix);
- beforeProjectionType = cc.director.getProjection();
- //locGrid.set2DProjection();
+ beforeProjectionType = cc.director.getProjection();
+ //locGrid.set2DProjection();
- //reset this._stackMatrix to current_stack.top
- //cc.kmMat4Assign(currentStack.top, backMatrix);
- }*/
+ //reset this._stackMatrix to current_stack.top
+ //cc.kmMat4Assign(currentStack.top, backMatrix);
+ }*/
cc.renderer.pushRenderCommand(this._gridBeginCommand);
if (node._target)
@@ -76,7 +76,7 @@
}
//if (locGrid && locGrid._active) {
- //cc.director.setProjection(beforeProjectionType);
+ //cc.director.setProjection(beforeProjectionType);
//}
cc.renderer.pushRenderCommand(this._gridEndCommand);
@@ -84,13 +84,13 @@
currentStack.top = currentStack.stack.pop();
};
- proto.onGridBeginDraw = function(){
+ proto.onGridBeginDraw = function () {
var locGrid = this._node.grid;
if (locGrid && locGrid._active)
locGrid.beforeDraw();
};
- proto.onGridEndDraw = function(){
+ proto.onGridEndDraw = function () {
var locGrid = this._node.grid;
if (locGrid && locGrid._active)
locGrid.afterDraw(this._node);
diff --git a/cocos2d/parallax/CCParallaxNodeRenderCmd.js b/cocos2d/parallax/CCParallaxNodeRenderCmd.js
index 572c10e3e1..2f5031c844 100644
--- a/cocos2d/parallax/CCParallaxNodeRenderCmd.js
+++ b/cocos2d/parallax/CCParallaxNodeRenderCmd.js
@@ -24,46 +24,46 @@
//TODO find a way to simple these code.
-(function(){
- cc.ParallaxNode.CanvasRenderCmd = function(renderable){
- cc.Node.CanvasRenderCmd.call(this, renderable);
+(function () {
+ cc.ParallaxNode.CanvasRenderCmd = function (renderable) {
+ this._rootCtor(renderable);
this._needDraw = false;
};
var proto = cc.ParallaxNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
proto.constructor = cc.ParallaxNode.CanvasRenderCmd;
- proto.updateStatus = function(){
+ proto.updateStatus = function () {
this._node._updateParallaxPosition();
- cc.Node.CanvasRenderCmd.prototype.updateStatus.call(this);
+ this.originUpdateStatus();
};
- proto._syncStatus = function(parentCmd){
+ proto._syncStatus = function (parentCmd) {
this._node._updateParallaxPosition();
- cc.Node.CanvasRenderCmd.prototype._syncStatus.call(this, parentCmd);
+ this._originSyncStatus(parentCmd);
};
})();
cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
- if(cc._renderType !== cc.game.RENDER_TYPE_WEBGL)
+ if (cc._renderType !== cc.game.RENDER_TYPE_WEBGL)
return;
- cc.ParallaxNode.WebGLRenderCmd = function(renderable){
- cc.Node.WebGLRenderCmd.call(this, renderable);
+ cc.ParallaxNode.WebGLRenderCmd = function (renderable) {
+ this._rootCtor(renderable);
this._needDraw = false;
};
var proto = cc.ParallaxNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
proto.constructor = cc.ParallaxNode.WebGLRenderCmd;
- proto.updateStatus = function(){
+ proto.updateStatus = function () {
this._node._updateParallaxPosition();
- cc.Node.WebGLRenderCmd.prototype.updateStatus.call(this);
+ this.originUpdateStatus();
};
- proto._syncStatus = function(parentCmd){
+ proto._syncStatus = function (parentCmd) {
this._node._updateParallaxPosition();
- cc.Node.WebGLRenderCmd.prototype._syncStatus.call(this, parentCmd);
+ this._originSyncStatus(parentCmd);
};
});
diff --git a/cocos2d/particle/CCParticleBatchNode.js b/cocos2d/particle/CCParticleBatchNode.js
index 1a2200f93e..53c381fc30 100644
--- a/cocos2d/particle/CCParticleBatchNode.js
+++ b/cocos2d/particle/CCParticleBatchNode.js
@@ -71,10 +71,10 @@ cc.PARTICLE_DEFAULT_CAPACITY = 500;
* var particleBatchNode = new cc.ParticleBatchNode(texture, 30);
*/
cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
- textureAtlas:null,
+ textureAtlas: null,
//the blend function used for drawing the quads
- _blendFunc:null,
- _className:"ParticleBatchNode",
+ _blendFunc: null,
+ _className: "ParticleBatchNode",
/**
* initializes the particle system with the name of a file on disk (for a list of supported formats look at the cc.Texture2D class), a capacity of particles
@@ -91,9 +91,9 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* var texture = cc.TextureCache.getInstance().addImage("res/grossini_dance.png");
* var particleBatchNode = new cc.ParticleBatchNode(texture, 30);
*/
- ctor:function (fileImage, capacity) {
+ ctor: function (fileImage, capacity) {
cc.Node.prototype.ctor.call(this);
- this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST};
+ this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST};
if (cc.isString(fileImage)) {
this.init(fileImage, capacity);
} else if (fileImage instanceof cc.Texture2D) {
@@ -101,8 +101,8 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
}
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return new cc.ParticleBatchNode.CanvasRenderCmd(this);
else
return new cc.ParticleBatchNode.WebGLRenderCmd(this);
@@ -114,7 +114,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* @param {Number} capacity
* @return {Boolean}
*/
- initWithTexture:function (texture, capacity) {
+ initWithTexture: function (texture, capacity) {
this.textureAtlas = new cc.TextureAtlas();
this.textureAtlas.initWithTexture(texture, capacity);
@@ -131,7 +131,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* @param {Number} capacity
* @return {Boolean}
*/
- initWithFile:function (fileImage, capacity) {
+ initWithFile: function (fileImage, capacity) {
var tex = cc.textureCache.addImage(fileImage);
return this.initWithTexture(tex, capacity);
},
@@ -142,34 +142,48 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* @param {Number} capacity
* @return {Boolean}
*/
- init:function (fileImage, capacity) {
+ init: function (fileImage, capacity) {
var tex = cc.textureCache.addImage(fileImage);
return this.initWithTexture(tex, capacity);
},
+ visit: function (parent) {
+ var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null;
+
+ // quick return if not visible
+ if (!this._visible) {
+ cmd._propagateFlagsDown(parentCmd);
+ return;
+ }
+
+ cmd.visit(parentCmd);
+ cc.renderer.pushRenderCommand(cmd);
+ cmd._dirtyFlag = 0;
+ },
+
/**
* Add a child into the cc.ParticleBatchNode
* @param {cc.ParticleSystem} child
* @param {Number} zOrder
* @param {Number} tag
*/
- addChild:function (child, zOrder, tag) {
- if(!child)
+ addChild: function (child, zOrder, tag) {
+ if (!child)
throw new Error("cc.ParticleBatchNode.addChild() : child should be non-null");
- if(!(child instanceof cc.ParticleSystem))
+ if (!(child instanceof cc.ParticleSystem))
throw new Error("cc.ParticleBatchNode.addChild() : only supports cc.ParticleSystem as children");
zOrder = (zOrder == null) ? child.zIndex : zOrder;
tag = (tag == null) ? child.tag : tag;
- if(child.getTexture() !== this.textureAtlas.texture)
+ if (child.getTexture() !== this.textureAtlas.texture)
throw new Error("cc.ParticleSystem.addChild() : the child is not using the same texture id");
// If this is the 1st children, then copy blending function
var childBlendFunc = child.getBlendFunc();
if (this._children.length === 0)
this.setBlendFunc(childBlendFunc);
- else{
- if((childBlendFunc.src !== this._blendFunc.src) || (childBlendFunc.dst !== this._blendFunc.dst)){
+ else {
+ if ((childBlendFunc.src !== this._blendFunc.src) || (childBlendFunc.dst !== this._blendFunc.dst)) {
cc.log("cc.ParticleSystem.addChild() : Can't add a ParticleSystem that uses a different blending function");
return;
}
@@ -198,7 +212,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* @param {cc.ParticleSystem} pSystem
* @param {Number} index
*/
- insertChild:function (pSystem, index) {
+ insertChild: function (pSystem, index) {
var totalParticles = pSystem.getTotalParticles();
var locTextureAtlas = this.textureAtlas;
var totalQuads = locTextureAtlas.totalQuads;
@@ -222,14 +236,14 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* @param {cc.ParticleSystem} child
* @param {Boolean} cleanup
*/
- removeChild:function (child, cleanup) {
+ removeChild: function (child, cleanup) {
// explicit nil handling
if (child == null)
return;
- if(!(child instanceof cc.ParticleSystem))
+ if (!(child instanceof cc.ParticleSystem))
throw new Error("cc.ParticleBatchNode.removeChild(): only supports cc.ParticleSystem as children");
- if(this._children.indexOf(child) === -1){
+ if (this._children.indexOf(child) === -1) {
cc.log("cc.ParticleBatchNode.removeChild(): doesn't contain the sprite. Can't remove it");
return;
}
@@ -254,19 +268,16 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* @param {cc.ParticleSystem} child
* @param {Number} zOrder
*/
- reorderChild:function (child, zOrder) {
- if(!child)
+ reorderChild: function (child, zOrder) {
+ if (!child)
throw new Error("cc.ParticleBatchNode.reorderChild(): child should be non-null");
- if(!(child instanceof cc.ParticleSystem))
+ if (!(child instanceof cc.ParticleSystem))
throw new Error("cc.ParticleBatchNode.reorderChild(): only supports cc.QuadParticleSystems as children");
- if(this._children.indexOf(child) === -1){
+ if (this._children.indexOf(child) === -1) {
cc.log("cc.ParticleBatchNode.reorderChild(): Child doesn't belong to batch");
return;
}
- if (zOrder === child.zIndex)
- return;
-
// no reordering if only 1 child
if (this._children.length > 1) {
var getIndexes = this._getCurrentIndex(child, zOrder);
@@ -306,14 +317,14 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* @param {Number} index
* @param {Boolean} doCleanup
*/
- removeChildAtIndex:function (index, doCleanup) {
+ removeChildAtIndex: function (index, doCleanup) {
this.removeChild(this._children[i], doCleanup);
},
/**
* @param {Boolean} [doCleanup=true]
*/
- removeAllChildren:function (doCleanup) {
+ removeAllChildren: function (doCleanup) {
var locChildren = this._children;
for (var i = 0; i < locChildren.length; i++) {
locChildren[i].setBatchNode(null);
@@ -326,7 +337,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* disables a particle by inserting a 0'd quad into the texture atlas
* @param {Number} particleIndex
*/
- disableParticle:function (particleIndex) {
+ disableParticle: function (particleIndex) {
var quad = this.textureAtlas.quads[particleIndex];
quad.br.vertices.x = quad.br.vertices.y = quad.tr.vertices.x = quad.tr.vertices.y =
quad.tl.vertices.x = quad.tl.vertices.y = quad.bl.vertices.x = quad.bl.vertices.y = 0.0;
@@ -337,7 +348,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* returns the used texture
* @return {cc.Texture2D}
*/
- getTexture:function () {
+ getTexture: function () {
return this.textureAtlas.texture;
},
@@ -345,7 +356,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* sets a new texture. it will be retained
* @param {cc.Texture2D} texture
*/
- setTexture:function (texture) {
+ setTexture: function (texture) {
this.textureAtlas.texture = texture;
// If the new texture has No premultiplied alpha, AND the blendFunc hasn't been changed, then update it
@@ -361,11 +372,11 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* @param {Number|Object} src
* @param {Number} dst
*/
- setBlendFunc:function (src, dst) {
- if (dst === undefined){
+ setBlendFunc: function (src, dst) {
+ if (dst === undefined) {
this._blendFunc.src = src.src;
this._blendFunc.dst = src.dst;
- } else{
+ } else {
this._blendFunc.src = src;
this._blendFunc.src = dst;
}
@@ -375,11 +386,11 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* returns the blending function used for the texture
* @return {cc.BlendFunc}
*/
- getBlendFunc:function () {
+ getBlendFunc: function () {
return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst);
},
- _updateAllAtlasIndexes:function () {
+ _updateAllAtlasIndexes: function () {
var index = 0;
var locChildren = this._children;
for (var i = 0; i < locChildren.length; i++) {
@@ -389,7 +400,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
}
},
- _increaseAtlasCapacityTo:function (quantity) {
+ _increaseAtlasCapacityTo: function (quantity) {
cc.log("cocos2d: cc.ParticleBatchNode: resizing TextureAtlas capacity from [" + this.textureAtlas.getCapacity()
+ "] to [" + quantity + "].");
@@ -399,7 +410,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
}
},
- _searchNewPositionInChildrenForZ:function (z) {
+ _searchNewPositionInChildrenForZ: function (z) {
var locChildren = this._children;
var count = locChildren.length;
for (var i = 0; i < count; i++) {
@@ -409,7 +420,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
return count;
},
- _getCurrentIndex:function (child, z) {
+ _getCurrentIndex: function (child, z) {
var foundCurrentIdx = false;
var foundNewIdx = false;
@@ -441,7 +452,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
if (!foundNewIdx)
newIndex = count;
newIndex += minusOne;
- return {newIndex:newIndex, oldIndex:oldIndex};
+ return {newIndex: newIndex, oldIndex: oldIndex};
},
//
@@ -457,10 +468,10 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
// @return {Number}
// @private
//
- _addChildHelper:function (child, z, aTag) {
- if(!child)
+ _addChildHelper: function (child, z, aTag) {
+ if (!child)
throw new Error("cc.ParticleBatchNode._addChildHelper(): child should be non-null");
- if(child.parent){
+ if (child.parent) {
cc.log("cc.ParticleBatchNode._addChildHelper(): child already added. It can't be added again");
return null;
}
@@ -477,13 +488,13 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
child._setLocalZOrder(z);
child.parent = this;
if (this._running) {
- child.onEnter();
- child.onEnterTransitionDidFinish();
+ child._performRecursive(cc.Node._stateCallbackType.onEnter);
+ child._performRecursive(cc.Node._stateCallbackType.onEnterTransitionDidFinish);
}
return pos;
},
- _updateBlendFunc:function () {
+ _updateBlendFunc: function () {
if (!this.textureAtlas.texture.hasPremultipliedAlpha()) {
this._blendFunc.src = cc.SRC_ALPHA;
this._blendFunc.dst = cc.ONE_MINUS_SRC_ALPHA;
@@ -494,7 +505,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* return the texture atlas used for drawing the quads
* @return {cc.TextureAtlas}
*/
- getTextureAtlas:function () {
+ getTextureAtlas: function () {
return this.textureAtlas;
},
@@ -502,7 +513,7 @@ cc.ParticleBatchNode = cc.Node.extend(/** @lends cc.ParticleBatchNode# */{
* set the texture atlas used for drawing the quads
* @param {cc.TextureAtlas} textureAtlas
*/
- setTextureAtlas:function (textureAtlas) {
+ setTextureAtlas: function (textureAtlas) {
this.textureAtlas = textureAtlas;
}
});
diff --git a/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js b/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js
index 36da185ecb..6e0990d140 100644
--- a/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js
+++ b/cocos2d/particle/CCParticleBatchNodeCanvasRenderCmd.js
@@ -22,17 +22,18 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
+(function () {
/**
* cc.ParticleBatchNode's rendering objects of Canvas
*/
- cc.ParticleBatchNode.CanvasRenderCmd = function(renderable){
- cc.Node.CanvasRenderCmd.call(this, renderable);
+ cc.ParticleBatchNode.CanvasRenderCmd = function (renderable) {
+ this._rootCtor(renderable);
this._needDraw = false;
};
var proto = cc.ParticleBatchNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
proto.constructor = cc.ParticleBatchNode.CanvasRenderCmd;
- proto._initWithTexture = function(){};
+ proto._initWithTexture = function () {
+ };
})();
diff --git a/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js b/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js
index 44cea2f052..765e7553ad 100644
--- a/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js
+++ b/cocos2d/particle/CCParticleBatchNodeWebGLRenderCmd.js
@@ -22,12 +22,12 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
+(function () {
/**
* cc.ParticleBatchNode's rendering objects of WebGL
*/
- cc.ParticleBatchNode.WebGLRenderCmd = function(renderable){
- cc.Node.WebGLRenderCmd.call(this, renderable);
+ cc.ParticleBatchNode.WebGLRenderCmd = function (renderable) {
+ this._rootCtor(renderable);
this._needDraw = true;
this._matrix = new cc.math.Matrix4();
this._matrix.identity();
@@ -49,35 +49,12 @@
this._matrix.mat[5] = wt.d;
this._matrix.mat[13] = wt.ty;
- this._shaderProgram.use();
- this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix);
+ this._glProgramState.apply(this._matrix);
cc.glBlendFuncForParticle(_t._blendFunc.src, _t._blendFunc.dst);
_t.textureAtlas.drawQuads();
};
- proto._initWithTexture = function(){
+ proto._initWithTexture = function () {
this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR);
};
-
- proto.visit = function(parentCmd){
- var node = this._node;
- // CAREFUL:
- // This visit is almost identical to cc.Node#visit
- // with the exception that it doesn't call visit on it's children
- //
- // The alternative is to have a void cc.Sprite#visit, but
- // although this is less mantainable, is faster
- //
- if (!node._visible)
- return;
-
- parentCmd = parentCmd || this.getParentRenderCmd();
- if (parentCmd)
- this._curLevel = parentCmd._curLevel + 1;
- this._syncStatus(parentCmd);
-
- cc.renderer.pushRenderCommand(this);
-
- this._dirtyFlag = 0;
- };
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/particle/CCParticleSystem.js b/cocos2d/particle/CCParticleSystem.js
index 3a0d3bdc8a..7a18fa4f32 100644
--- a/cocos2d/particle/CCParticleSystem.js
+++ b/cocos2d/particle/CCParticleSystem.js
@@ -64,10 +64,10 @@
* @param {cc.Particle.ModeA} [modeB=]
*/
cc.Particle = function (pos, startPos, color, deltaColor, size, deltaSize, rotation, deltaRotation, timeToLive, atlasIndex, modeA, modeB) {
- this.pos = pos ? pos : cc.p(0,0);
- this.startPos = startPos ? startPos : cc.p(0,0);
- this.color = color ? color : {r:0, g: 0, b:0, a:255};
- this.deltaColor = deltaColor ? deltaColor : {r:0, g: 0, b:0, a:255} ;
+ this.pos = pos ? pos : cc.p(0, 0);
+ this.startPos = startPos ? startPos : cc.p(0, 0);
+ this.color = color ? color : {r: 0, g: 0, b: 0, a: 255};
+ this.deltaColor = deltaColor ? deltaColor : {r: 0, g: 0, b: 0, a: 255};
this.size = size || 0;
this.deltaSize = deltaSize || 0;
this.rotation = rotation || 0;
@@ -89,7 +89,7 @@ cc.Particle = function (pos, startPos, color, deltaColor, size, deltaSize, rotat
* @param {Number} tangentialAccel
*/
cc.Particle.ModeA = function (dir, radialAccel, tangentialAccel) {
- this.dir = dir ? dir : cc.p(0,0);
+ this.dir = dir ? dir : cc.p(0, 0);
this.radialAccel = radialAccel || 0;
this.tangentialAccel = tangentialAccel || 0;
};
@@ -111,8 +111,8 @@ cc.Particle.ModeB = function (angle, degreesPerSecond, radius, deltaRadius) {
};
/**
- * Array of Point instances used to optimize particle updates
- */
+ * Array of Point instances used to optimize particle updates
+ */
cc.Particle.TemporaryPoints = [
cc.p(),
cc.p(),
@@ -211,7 +211,7 @@ cc.Particle.TemporaryPoints = [
* emitter.startSpin = 0;
*/
cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
- _className:"ParticleSystem",
+ _className: "ParticleSystem",
//***********variables*************
_plistFile: "",
//! time elapsed since the start of the system (in seconds)
@@ -285,12 +285,12 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Constructor of cc.ParticleSystem
* @param {String|Number} plistFile
*/
- ctor:function (plistFile) {
+ ctor: function (plistFile) {
cc.Node.prototype.ctor.call(this);
this.emitterMode = cc.ParticleSystem.MODE_GRAVITY;
this.modeA = new cc.ParticleSystem.ModeA();
this.modeB = new cc.ParticleSystem.ModeB();
- this._blendFunc = {src:cc.BLEND_SRC, dst:cc.BLEND_DST};
+ this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST};
this._particles = [];
this._sourcePosition = cc.p(0, 0);
@@ -348,8 +348,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
}
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return new cc.ParticleSystem.CanvasRenderCmd(this);
else
return new cc.ParticleSystem.WebGLRenderCmd(this);
@@ -360,8 +360,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* It's very expensive to change color on Canvas mode, so if set it to true, particle system will ignore the changing color operation.
* @param {boolean} ignore
*/
- ignoreColor: function(ignore){
- this._dontTint = ignore;
+ ignoreColor: function (ignore) {
+ this._dontTint = ignore;
},
/**
@@ -370,7 +370,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
*
* @param {cc.Rect} pointRect
*/
- initTexCoordsWithRect:function (pointRect) {
+ initTexCoordsWithRect: function (pointRect) {
this._renderCmd.initTexCoordsWithRect(pointRect);
},
@@ -378,7 +378,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* return weak reference to the cc.SpriteBatchNode that renders the cc.Sprite
* @return {cc.ParticleBatchNode}
*/
- getBatchNode:function () {
+ getBatchNode: function () {
return this._batchNode;
},
@@ -386,7 +386,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set weak reference to the cc.SpriteBatchNode that renders the cc.Sprite
* @param {cc.ParticleBatchNode} batchNode
*/
- setBatchNode:function (batchNode) {
+ setBatchNode: function (batchNode) {
this._renderCmd.setBatchNode(batchNode);
},
@@ -394,7 +394,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* return index of system in batch node array
* @return {Number}
*/
- getAtlasIndex:function () {
+ getAtlasIndex: function () {
return this.atlasIndex;
},
@@ -402,7 +402,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set index of system in batch node array
* @param {Number} atlasIndex
*/
- setAtlasIndex:function (atlasIndex) {
+ setAtlasIndex: function (atlasIndex) {
this.atlasIndex = atlasIndex;
},
@@ -410,7 +410,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return DrawMode of ParticleSystem (Canvas Mode only)
* @return {Number}
*/
- getDrawMode:function () {
+ getDrawMode: function () {
return this._renderCmd.getDrawMode();
},
@@ -418,7 +418,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* DrawMode of ParticleSystem setter (Canvas Mode only)
* @param {Number} drawMode
*/
- setDrawMode:function (drawMode) {
+ setDrawMode: function (drawMode) {
this._renderCmd.setDrawMode(drawMode);
},
@@ -426,7 +426,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return ShapeType of ParticleSystem (Canvas Mode only)
* @return {Number}
*/
- getShapeType:function () {
+ getShapeType: function () {
return this._renderCmd.getShapeType();
},
@@ -434,7 +434,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* ShapeType of ParticleSystem setter (Canvas Mode only)
* @param {Number} shapeType
*/
- setShapeType:function (shapeType) {
+ setShapeType: function (shapeType) {
this._renderCmd.setShapeType(shapeType);
},
@@ -442,7 +442,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return ParticleSystem is active
* @return {Boolean}
*/
- isActive:function () {
+ isActive: function () {
return this._isActive;
},
@@ -450,7 +450,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Quantity of particles that are being simulated at the moment
* @return {Number}
*/
- getParticleCount:function () {
+ getParticleCount: function () {
return this.particleCount;
},
@@ -458,7 +458,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Quantity of particles setter
* @param {Number} particleCount
*/
- setParticleCount:function (particleCount) {
+ setParticleCount: function (particleCount) {
this.particleCount = particleCount;
},
@@ -466,7 +466,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* How many seconds the emitter wil run. -1 means 'forever'
* @return {Number}
*/
- getDuration:function () {
+ getDuration: function () {
return this.duration;
},
@@ -474,7 +474,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set run seconds of the emitter
* @param {Number} duration
*/
- setDuration:function (duration) {
+ setDuration: function (duration) {
this.duration = duration;
},
@@ -482,7 +482,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return sourcePosition of the emitter
* @return {cc.Point | Object}
*/
- getSourcePosition:function () {
+ getSourcePosition: function () {
return {x: this._sourcePosition.x, y: this._sourcePosition.y};
},
@@ -490,15 +490,16 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* sourcePosition of the emitter setter
* @param sourcePosition
*/
- setSourcePosition:function (sourcePosition) {
- this._sourcePosition = sourcePosition;
+ setSourcePosition: function (sourcePosition) {
+ this._sourcePosition.x = sourcePosition.x;
+ this._sourcePosition.y = sourcePosition.y;
},
/**
* Return Position variance of the emitter
* @return {cc.Point | Object}
*/
- getPosVar:function () {
+ getPosVar: function () {
return {x: this._posVar.x, y: this._posVar.y};
},
@@ -506,15 +507,16 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Position variance of the emitter setter
* @param {cc.Point} posVar
*/
- setPosVar:function (posVar) {
- this._posVar = posVar;
+ setPosVar: function (posVar) {
+ this._posVar.x = posVar.x;
+ this._posVar.y = posVar.y;
},
/**
* Return life of each particle
* @return {Number}
*/
- getLife:function () {
+ getLife: function () {
return this.life;
},
@@ -522,7 +524,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* life of each particle setter
* @param {Number} life
*/
- setLife:function (life) {
+ setLife: function (life) {
this.life = life;
},
@@ -530,7 +532,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return life variance of each particle
* @return {Number}
*/
- getLifeVar:function () {
+ getLifeVar: function () {
return this.lifeVar;
},
@@ -538,7 +540,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* life variance of each particle setter
* @param {Number} lifeVar
*/
- setLifeVar:function (lifeVar) {
+ setLifeVar: function (lifeVar) {
this.lifeVar = lifeVar;
},
@@ -546,7 +548,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return angle of each particle
* @return {Number}
*/
- getAngle:function () {
+ getAngle: function () {
return this.angle;
},
@@ -554,7 +556,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* angle of each particle setter
* @param {Number} angle
*/
- setAngle:function (angle) {
+ setAngle: function (angle) {
this.angle = angle;
},
@@ -562,7 +564,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return angle variance of each particle
* @return {Number}
*/
- getAngleVar:function () {
+ getAngleVar: function () {
return this.angleVar;
},
@@ -570,7 +572,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* angle variance of each particle setter
* @param angleVar
*/
- setAngleVar:function (angleVar) {
+ setAngleVar: function (angleVar) {
this.angleVar = angleVar;
},
@@ -579,8 +581,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return Gravity of emitter
* @return {cc.Point}
*/
- getGravity:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ getGravity: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getGravity() : Particle Mode should be Gravity");
var locGravity = this.modeA.gravity;
return cc.p(locGravity.x, locGravity.y);
@@ -590,8 +592,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Gravity of emitter setter
* @param {cc.Point} gravity
*/
- setGravity:function (gravity) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ setGravity: function (gravity) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setGravity() : Particle Mode should be Gravity");
this.modeA.gravity = gravity;
},
@@ -600,8 +602,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return Speed of each particle
* @return {Number}
*/
- getSpeed:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ getSpeed: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getSpeed() : Particle Mode should be Gravity");
return this.modeA.speed;
},
@@ -610,8 +612,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Speed of each particle setter
* @param {Number} speed
*/
- setSpeed:function (speed) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ setSpeed: function (speed) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setSpeed() : Particle Mode should be Gravity");
this.modeA.speed = speed;
},
@@ -620,8 +622,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* return speed variance of each particle. Only available in 'Gravity' mode.
* @return {Number}
*/
- getSpeedVar:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ getSpeedVar: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getSpeedVar() : Particle Mode should be Gravity");
return this.modeA.speedVar;
},
@@ -630,8 +632,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* speed variance of each particle setter. Only available in 'Gravity' mode.
* @param {Number} speedVar
*/
- setSpeedVar:function (speedVar) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ setSpeedVar: function (speedVar) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setSpeedVar() : Particle Mode should be Gravity");
this.modeA.speedVar = speedVar;
},
@@ -640,8 +642,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return tangential acceleration of each particle. Only available in 'Gravity' mode.
* @return {Number}
*/
- getTangentialAccel:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ getTangentialAccel: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getTangentialAccel() : Particle Mode should be Gravity");
return this.modeA.tangentialAccel;
},
@@ -650,8 +652,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Tangential acceleration of each particle setter. Only available in 'Gravity' mode.
* @param {Number} tangentialAccel
*/
- setTangentialAccel:function (tangentialAccel) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ setTangentialAccel: function (tangentialAccel) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setTangentialAccel() : Particle Mode should be Gravity");
this.modeA.tangentialAccel = tangentialAccel;
},
@@ -660,8 +662,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return tangential acceleration variance of each particle. Only available in 'Gravity' mode.
* @return {Number}
*/
- getTangentialAccelVar:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ getTangentialAccelVar: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getTangentialAccelVar() : Particle Mode should be Gravity");
return this.modeA.tangentialAccelVar;
},
@@ -670,8 +672,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* tangential acceleration variance of each particle setter. Only available in 'Gravity' mode.
* @param {Number} tangentialAccelVar
*/
- setTangentialAccelVar:function (tangentialAccelVar) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ setTangentialAccelVar: function (tangentialAccelVar) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setTangentialAccelVar() : Particle Mode should be Gravity");
this.modeA.tangentialAccelVar = tangentialAccelVar;
},
@@ -680,8 +682,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return radial acceleration of each particle. Only available in 'Gravity' mode.
* @return {Number}
*/
- getRadialAccel:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ getRadialAccel: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getRadialAccel() : Particle Mode should be Gravity");
return this.modeA.radialAccel;
},
@@ -690,8 +692,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* radial acceleration of each particle setter. Only available in 'Gravity' mode.
* @param {Number} radialAccel
*/
- setRadialAccel:function (radialAccel) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ setRadialAccel: function (radialAccel) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setRadialAccel() : Particle Mode should be Gravity");
this.modeA.radialAccel = radialAccel;
},
@@ -700,8 +702,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return radial acceleration variance of each particle. Only available in 'Gravity' mode.
* @return {Number}
*/
- getRadialAccelVar:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ getRadialAccelVar: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getRadialAccelVar() : Particle Mode should be Gravity");
return this.modeA.radialAccelVar;
},
@@ -710,8 +712,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* radial acceleration variance of each particle setter. Only available in 'Gravity' mode.
* @param {Number} radialAccelVar
*/
- setRadialAccelVar:function (radialAccelVar) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ setRadialAccelVar: function (radialAccelVar) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setRadialAccelVar() : Particle Mode should be Gravity");
this.modeA.radialAccelVar = radialAccelVar;
},
@@ -720,8 +722,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get the rotation of each particle to its direction Only available in 'Gravity' mode.
* @returns {boolean}
*/
- getRotationIsDir: function(){
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ getRotationIsDir: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.getRotationIsDir() : Particle Mode should be Gravity");
return this.modeA.rotationIsDir;
},
@@ -730,8 +732,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set the rotation of each particle to its direction Only available in 'Gravity' mode.
* @param {boolean} t
*/
- setRotationIsDir: function(t){
- if(this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
+ setRotationIsDir: function (t) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_GRAVITY)
cc.log("cc.ParticleBatchNode.setRotationIsDir() : Particle Mode should be Gravity");
this.modeA.rotationIsDir = t;
},
@@ -741,8 +743,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return starting radius of the particles. Only available in 'Radius' mode.
* @return {Number}
*/
- getStartRadius:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ getStartRadius: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.getStartRadius() : Particle Mode should be Radius");
return this.modeB.startRadius;
},
@@ -751,8 +753,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* starting radius of the particles setter. Only available in 'Radius' mode.
* @param {Number} startRadius
*/
- setStartRadius:function (startRadius) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ setStartRadius: function (startRadius) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.setStartRadius() : Particle Mode should be Radius");
this.modeB.startRadius = startRadius;
},
@@ -761,8 +763,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return starting radius variance of the particles. Only available in 'Radius' mode.
* @return {Number}
*/
- getStartRadiusVar:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ getStartRadiusVar: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.getStartRadiusVar() : Particle Mode should be Radius");
return this.modeB.startRadiusVar;
},
@@ -771,8 +773,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* starting radius variance of the particles setter. Only available in 'Radius' mode.
* @param {Number} startRadiusVar
*/
- setStartRadiusVar:function (startRadiusVar) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ setStartRadiusVar: function (startRadiusVar) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.setStartRadiusVar() : Particle Mode should be Radius");
this.modeB.startRadiusVar = startRadiusVar;
},
@@ -781,8 +783,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return ending radius of the particles. Only available in 'Radius' mode.
* @return {Number}
*/
- getEndRadius:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ getEndRadius: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.getEndRadius() : Particle Mode should be Radius");
return this.modeB.endRadius;
},
@@ -791,8 +793,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* ending radius of the particles setter. Only available in 'Radius' mode.
* @param {Number} endRadius
*/
- setEndRadius:function (endRadius) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ setEndRadius: function (endRadius) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.setEndRadius() : Particle Mode should be Radius");
this.modeB.endRadius = endRadius;
},
@@ -801,8 +803,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return ending radius variance of the particles. Only available in 'Radius' mode.
* @return {Number}
*/
- getEndRadiusVar:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ getEndRadiusVar: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.getEndRadiusVar() : Particle Mode should be Radius");
return this.modeB.endRadiusVar;
},
@@ -811,8 +813,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* ending radius variance of the particles setter. Only available in 'Radius' mode.
* @param endRadiusVar
*/
- setEndRadiusVar:function (endRadiusVar) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ setEndRadiusVar: function (endRadiusVar) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.setEndRadiusVar() : Particle Mode should be Radius");
this.modeB.endRadiusVar = endRadiusVar;
},
@@ -821,8 +823,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode.
* @return {Number}
*/
- getRotatePerSecond:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ getRotatePerSecond: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.getRotatePerSecond() : Particle Mode should be Radius");
return this.modeB.rotatePerSecond;
},
@@ -831,8 +833,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode.
* @param {Number} degrees
*/
- setRotatePerSecond:function (degrees) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ setRotatePerSecond: function (degrees) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.setRotatePerSecond() : Particle Mode should be Radius");
this.modeB.rotatePerSecond = degrees;
},
@@ -841,8 +843,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Return Variance in degrees for rotatePerSecond. Only available in 'Radius' mode.
* @return {Number}
*/
- getRotatePerSecondVar:function () {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ getRotatePerSecondVar: function () {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.getRotatePerSecondVar() : Particle Mode should be Radius");
return this.modeB.rotatePerSecondVar;
},
@@ -851,30 +853,30 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Variance in degrees for rotatePerSecond setter. Only available in 'Radius' mode.
* @param degrees
*/
- setRotatePerSecondVar:function (degrees) {
- if(this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
+ setRotatePerSecondVar: function (degrees) {
+ if (this.emitterMode !== cc.ParticleSystem.MODE_RADIUS)
cc.log("cc.ParticleBatchNode.setRotatePerSecondVar() : Particle Mode should be Radius");
this.modeB.rotatePerSecondVar = degrees;
},
//////////////////////////////////////////////////////////////////////////
//don't use a transform matrix, this is faster
- setScale:function (scale, scaleY) {
+ setScale: function (scale, scaleY) {
this._transformSystemDirty = true;
cc.Node.prototype.setScale.call(this, scale, scaleY);
},
- setRotation:function (newRotation) {
+ setRotation: function (newRotation) {
this._transformSystemDirty = true;
cc.Node.prototype.setRotation.call(this, newRotation);
},
- setScaleX:function (newScaleX) {
+ setScaleX: function (newScaleX) {
this._transformSystemDirty = true;
cc.Node.prototype.setScaleX.call(this, newScaleX);
},
- setScaleY:function (newScaleY) {
+ setScaleY: function (newScaleY) {
this._transformSystemDirty = true;
cc.Node.prototype.setScaleY.call(this, newScaleY);
},
@@ -883,7 +885,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get start size in pixels of each particle
* @return {Number}
*/
- getStartSize:function () {
+ getStartSize: function () {
return this.startSize;
},
@@ -891,7 +893,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set start size in pixels of each particle
* @param {Number} startSize
*/
- setStartSize:function (startSize) {
+ setStartSize: function (startSize) {
this.startSize = startSize;
},
@@ -899,7 +901,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get size variance in pixels of each particle
* @return {Number}
*/
- getStartSizeVar:function () {
+ getStartSizeVar: function () {
return this.startSizeVar;
},
@@ -907,7 +909,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set size variance in pixels of each particle
* @param {Number} startSizeVar
*/
- setStartSizeVar:function (startSizeVar) {
+ setStartSizeVar: function (startSizeVar) {
this.startSizeVar = startSizeVar;
},
@@ -915,7 +917,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get end size in pixels of each particle
* @return {Number}
*/
- getEndSize:function () {
+ getEndSize: function () {
return this.endSize;
},
@@ -923,7 +925,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set end size in pixels of each particle
* @param endSize
*/
- setEndSize:function (endSize) {
+ setEndSize: function (endSize) {
this.endSize = endSize;
},
@@ -931,7 +933,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get end size variance in pixels of each particle
* @return {Number}
*/
- getEndSizeVar:function () {
+ getEndSizeVar: function () {
return this.endSizeVar;
},
@@ -939,7 +941,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set end size variance in pixels of each particle
* @param {Number} endSizeVar
*/
- setEndSizeVar:function (endSizeVar) {
+ setEndSizeVar: function (endSizeVar) {
this.endSizeVar = endSizeVar;
},
@@ -947,7 +949,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set start color of each particle
* @return {cc.Color}
*/
- getStartColor:function () {
+ getStartColor: function () {
return cc.color(this._startColor.r, this._startColor.g, this._startColor.b, this._startColor.a);
},
@@ -955,15 +957,18 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get start color of each particle
* @param {cc.Color} startColor
*/
- setStartColor:function (startColor) {
- this._startColor = cc.color(startColor);
+ setStartColor: function (startColor) {
+ this._startColor.r = startColor.r;
+ this._startColor.g = startColor.g;
+ this._startColor.b = startColor.b;
+ this._startColor.a = startColor.a;
},
/**
* get start color variance of each particle
* @return {cc.Color}
*/
- getStartColorVar:function () {
+ getStartColorVar: function () {
return cc.color(this._startColorVar.r, this._startColorVar.g, this._startColorVar.b, this._startColorVar.a);
},
@@ -971,15 +976,18 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set start color variance of each particle
* @param {cc.Color} startColorVar
*/
- setStartColorVar:function (startColorVar) {
- this._startColorVar = cc.color(startColorVar);
+ setStartColorVar: function (startColorVar) {
+ this._startColorVar.r = startColorVar.r;
+ this._startColorVar.g = startColorVar.g;
+ this._startColorVar.b = startColorVar.b;
+ this._startColorVar.a = startColorVar.a;
},
/**
* get end color and end color variation of each particle
* @return {cc.Color}
*/
- getEndColor:function () {
+ getEndColor: function () {
return cc.color(this._endColor.r, this._endColor.g, this._endColor.b, this._endColor.a);
},
@@ -987,15 +995,18 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set end color and end color variation of each particle
* @param {cc.Color} endColor
*/
- setEndColor:function (endColor) {
- this._endColor = cc.color(endColor);
+ setEndColor: function (endColor) {
+ this._endColor.r = endColor.r;
+ this._endColor.g = endColor.g;
+ this._endColor.b = endColor.b;
+ this._endColor.a = endColor.a;
},
/**
* get end color variance of each particle
* @return {cc.Color}
*/
- getEndColorVar:function () {
+ getEndColorVar: function () {
return cc.color(this._endColorVar.r, this._endColorVar.g, this._endColorVar.b, this._endColorVar.a);
},
@@ -1003,15 +1014,18 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set end color variance of each particle
* @param {cc.Color} endColorVar
*/
- setEndColorVar:function (endColorVar) {
- this._endColorVar = cc.color(endColorVar);
+ setEndColorVar: function (endColorVar) {
+ this._endColorVar.r = endColorVar.r;
+ this._endColorVar.g = endColorVar.g;
+ this._endColorVar.b = endColorVar.b;
+ this._endColorVar.a = endColorVar.a;
},
/**
* get initial angle of each particle
* @return {Number}
*/
- getStartSpin:function () {
+ getStartSpin: function () {
return this.startSpin;
},
@@ -1019,7 +1033,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set initial angle of each particle
* @param {Number} startSpin
*/
- setStartSpin:function (startSpin) {
+ setStartSpin: function (startSpin) {
this.startSpin = startSpin;
},
@@ -1027,7 +1041,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get initial angle variance of each particle
* @return {Number}
*/
- getStartSpinVar:function () {
+ getStartSpinVar: function () {
return this.startSpinVar;
},
@@ -1035,7 +1049,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set initial angle variance of each particle
* @param {Number} startSpinVar
*/
- setStartSpinVar:function (startSpinVar) {
+ setStartSpinVar: function (startSpinVar) {
this.startSpinVar = startSpinVar;
},
@@ -1043,7 +1057,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get end angle of each particle
* @return {Number}
*/
- getEndSpin:function () {
+ getEndSpin: function () {
return this.endSpin;
},
@@ -1051,7 +1065,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set end angle of each particle
* @param {Number} endSpin
*/
- setEndSpin:function (endSpin) {
+ setEndSpin: function (endSpin) {
this.endSpin = endSpin;
},
@@ -1059,7 +1073,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get end angle variance of each particle
* @return {Number}
*/
- getEndSpinVar:function () {
+ getEndSpinVar: function () {
return this.endSpinVar;
},
@@ -1067,7 +1081,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set end angle variance of each particle
* @param {Number} endSpinVar
*/
- setEndSpinVar:function (endSpinVar) {
+ setEndSpinVar: function (endSpinVar) {
this.endSpinVar = endSpinVar;
},
@@ -1075,7 +1089,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get emission rate of the particles
* @return {Number}
*/
- getEmissionRate:function () {
+ getEmissionRate: function () {
return this.emissionRate;
},
@@ -1083,7 +1097,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set emission rate of the particles
* @param {Number} emissionRate
*/
- setEmissionRate:function (emissionRate) {
+ setEmissionRate: function (emissionRate) {
this.emissionRate = emissionRate;
},
@@ -1091,7 +1105,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get maximum particles of the system
* @return {Number}
*/
- getTotalParticles:function () {
+ getTotalParticles: function () {
return this._totalParticles;
},
@@ -1099,7 +1113,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set maximum particles of the system
* @param {Number} tp totalParticles
*/
- setTotalParticles:function (tp) {
+ setTotalParticles: function (tp) {
this._renderCmd.setTotalParticles(tp);
},
@@ -1107,7 +1121,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get Texture of Particle System
* @return {cc.Texture2D}
*/
- getTexture:function () {
+ getTexture: function () {
return this._texture;
},
@@ -1115,15 +1129,15 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set Texture of Particle System
* @param {cc.Texture2D } texture
*/
- setTexture:function (texture) {
- if(!texture)
+ setTexture: function (texture) {
+ if (!texture)
return;
- if(texture.isLoaded()){
+ if (texture.isLoaded()) {
this.setTextureWithRect(texture, cc.rect(0, 0, texture.width, texture.height));
} else {
this._textureLoaded = false;
- texture.addEventListener("load", function(sender){
+ texture.addEventListener("load", function (sender) {
this._textureLoaded = true;
this.setTextureWithRect(sender, cc.rect(0, 0, sender.width, sender.height));
}, this);
@@ -1135,7 +1149,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get BlendFunc of Particle System
* @return {cc.BlendFunc}
*/
- getBlendFunc:function () {
+ getBlendFunc: function () {
return this._blendFunc;
},
@@ -1144,7 +1158,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* @param {Number} src
* @param {Number} dst
*/
- setBlendFunc:function (src, dst) {
+ setBlendFunc: function (src, dst) {
if (dst === undefined) {
if (this._blendFunc !== src) {
this._blendFunc = src;
@@ -1152,7 +1166,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
}
} else {
if (this._blendFunc.src !== src || this._blendFunc.dst !== dst) {
- this._blendFunc = {src:src, dst:dst};
+ this._blendFunc = {src: src, dst: dst};
this._updateBlendFunc();
}
}
@@ -1162,7 +1176,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* does the alpha value modify color getter
* @return {Boolean}
*/
- isOpacityModifyRGB:function () {
+ isOpacityModifyRGB: function () {
return this._opacityModifyRGB;
},
@@ -1170,7 +1184,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* does the alpha value modify color setter
* @param newValue
*/
- setOpacityModifyRGB:function (newValue) {
+ setOpacityModifyRGB: function (newValue) {
this._opacityModifyRGB = newValue;
},
@@ -1183,7 +1197,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* source blend function = GL_SRC_ALPHA;
* dest blend function = GL_ONE;
*/
- isBlendAdditive:function () {
+ isBlendAdditive: function () {
return (( this._blendFunc.src === cc.SRC_ALPHA && this._blendFunc.dst === cc.ONE) || (this._blendFunc.src === cc.ONE && this._blendFunc.dst === cc.ONE));
},
@@ -1193,7 +1207,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
*
* @param {Boolean} isBlendAdditive
*/
- setBlendAdditive:function (isBlendAdditive) {
+ setBlendAdditive: function (isBlendAdditive) {
var locBlendFunc = this._blendFunc;
if (isBlendAdditive) {
locBlendFunc.src = cc.SRC_ALPHA;
@@ -1207,7 +1221,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* get particles movement type: Free or Grouped
* @return {Number}
*/
- getPositionType:function () {
+ getPositionType: function () {
return this.positionType;
},
@@ -1215,7 +1229,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* set particles movement type: Free or Grouped
* @param {Number} positionType
*/
- setPositionType:function (positionType) {
+ setPositionType: function (positionType) {
this.positionType = positionType;
},
@@ -1225,7 +1239,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
*
* @return {Boolean}
*/
- isAutoRemoveOnFinish:function () {
+ isAutoRemoveOnFinish: function () {
return this.autoRemoveOnFinish;
},
@@ -1235,7 +1249,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
*
* @param {Boolean} isAutoRemoveOnFinish
*/
- setAutoRemoveOnFinish:function (isAutoRemoveOnFinish) {
+ setAutoRemoveOnFinish: function (isAutoRemoveOnFinish) {
this.autoRemoveOnFinish = isAutoRemoveOnFinish;
},
@@ -1243,7 +1257,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* return kind of emitter modes
* @return {Number}
*/
- getEmitterMode:function () {
+ getEmitterMode: function () {
return this.emitterMode;
},
@@ -1254,14 +1268,14 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
*
* @param {Number} emitterMode
*/
- setEmitterMode:function (emitterMode) {
+ setEmitterMode: function (emitterMode) {
this.emitterMode = emitterMode;
},
/**
* initializes a cc.ParticleSystem
*/
- init:function () {
+ init: function () {
return this.initWithTotalParticles(150);
},
@@ -1274,10 +1288,10 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* @param {String} plistFile
* @return {boolean}
*/
- initWithFile:function (plistFile) {
+ initWithFile: function (plistFile) {
this._plistFile = plistFile;
var dict = cc.loader.getRes(plistFile);
- if(!dict){
+ if (!dict) {
cc.log("cc.ParticleSystem.initWithFile(): Particles: file not found");
return false;
}
@@ -1290,7 +1304,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* return bounding box of particle system in world space
* @return {cc.Rect}
*/
- getBoundingBoxToWorld:function () {
+ getBoundingBoxToWorld: function () {
return cc.rect(0, 0, cc._canvas.width, cc._canvas.height);
},
@@ -1300,7 +1314,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* @param {String} dirname
* @return {Boolean}
*/
- initWithDictionary:function (dictionary, dirname) {
+ initWithDictionary: function (dictionary, dirname) {
var ret = false;
var buffer = null;
var image = null;
@@ -1353,7 +1367,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
// position
this.setPosition(parseFloat(locValueForKey("sourcePositionx", dictionary)),
- parseFloat(locValueForKey("sourcePositiony", dictionary)));
+ parseFloat(locValueForKey("sourcePositiony", dictionary)));
this._posVar.x = parseFloat(locValueForKey("sourcePositionVariancex", dictionary));
this._posVar.y = parseFloat(locValueForKey("sourcePositionVariancey", dictionary));
@@ -1391,8 +1405,14 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
locModeA.tangentialAccelVar = (pszTmp) ? parseFloat(pszTmp) : 0;
// rotation is dir
- var locRotationIsDir = locValueForKey("rotationIsDir", dictionary).toLowerCase();
- locModeA.rotationIsDir = (locRotationIsDir != null && (locRotationIsDir === "true" || locRotationIsDir === "1"));
+ var locRotationIsDir = locValueForKey("rotationIsDir", dictionary);
+ if (locRotationIsDir !== null) {
+ locRotationIsDir = locRotationIsDir.toString().toLowerCase();
+ locModeA.rotationIsDir = (locRotationIsDir === "true" || locRotationIsDir === "1");
+ }
+ else {
+ locModeA.rotationIsDir = false;
+ }
} else if (this.emitterMode === cc.ParticleSystem.MODE_RADIUS) {
// or Mode B: radius movement
var locModeB = this.modeB;
@@ -1444,24 +1464,24 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
var imageFormat = cc.getImageFormatByData(buffer);
- if(imageFormat !== cc.FMT_TIFF && imageFormat !== cc.FMT_PNG){
+ if (imageFormat !== cc.FMT_TIFF && imageFormat !== cc.FMT_PNG) {
cc.log("cc.ParticleSystem: unknown image format with Data");
return false;
}
var canvasObj = document.createElement("canvas");
- if(imageFormat === cc.FMT_PNG){
+ if (imageFormat === cc.FMT_PNG) {
var myPngObj = new cc.PNGReader(buffer);
myPngObj.render(canvasObj);
} else {
var myTIFFObj = cc.tiffReader;
- myTIFFObj.parseTIFF(buffer,canvasObj);
+ myTIFFObj.parseTIFF(buffer, canvasObj);
}
cc.textureCache.cacheImage(imgPath, canvasObj);
var addTexture = cc.textureCache.getTextureForKey(imgPath);
- if(!addTexture)
+ if (!addTexture)
cc.log("cc.ParticleSystem.initWithDictionary() : error loading the texture");
this.setTexture(addTexture);
}
@@ -1477,12 +1497,12 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* @param {Number} numberOfParticles
* @return {Boolean}
*/
- initWithTotalParticles:function (numberOfParticles) {
+ initWithTotalParticles: function (numberOfParticles) {
this._totalParticles = numberOfParticles;
var i, locParticles = this._particles;
locParticles.length = 0;
- for(i = 0; i< numberOfParticles; i++){
+ for (i = 0; i < numberOfParticles; i++) {
locParticles[i] = new cc.Particle();
}
@@ -1528,7 +1548,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* @function
* @see scheduleUpdate();
*/
- destroyParticleSystem:function () {
+ destroyParticleSystem: function () {
this.unscheduleUpdate();
},
@@ -1550,7 +1570,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* Initializes a particle
* @param {cc.Particle} particle
*/
- initParticle:function (particle) {
+ initParticle: function (particle) {
var locRandomMinus11 = cc.randomMinus1To1;
// timeToLive
// no negative life. prevent division by 0
@@ -1607,7 +1627,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
// position
if (this.positionType === cc.ParticleSystem.TYPE_FREE)
particle.startPos = this.convertToWorldSpace(this._pointZeroForParticle);
- else if (this.positionType === cc.ParticleSystem.TYPE_RELATIVE){
+ else if (this.positionType === cc.ParticleSystem.TYPE_RELATIVE) {
particle.startPos.x = this._position.x;
particle.startPos.y = this._position.y;
}
@@ -1632,7 +1652,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
locParticleModeA.tangentialAccel = locModeA.tangentialAccel + locModeA.tangentialAccelVar * locRandomMinus11();
// rotation is dir
- if(locModeA.rotationIsDir)
+ if (locModeA.rotationIsDir)
particle.rotation = -cc.radiansToDegrees(cc.pToAngle(locParticleModeA.dir));
} else {
// Mode Radius: B
@@ -1653,7 +1673,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
/**
* stop emitting particles. Running particles will continue to run until they die
*/
- stopSystem:function () {
+ stopSystem: function () {
this._isActive = false;
this._elapsed = this.duration;
this._emitCounter = 0;
@@ -1662,19 +1682,19 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
/**
* Kill all living particles.
*/
- resetSystem:function () {
+ resetSystem: function () {
this._isActive = true;
this._elapsed = 0;
var locParticles = this._particles;
for (this._particleIdx = 0; this._particleIdx < this.particleCount; ++this._particleIdx)
- locParticles[this._particleIdx].timeToLive = 0 ;
+ locParticles[this._particleIdx].timeToLive = 0;
},
/**
* whether or not the system is full
* @return {Boolean}
*/
- isFull:function () {
+ isFull: function () {
return (this.particleCount >= this._totalParticles);
},
@@ -1683,14 +1703,14 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* @param {cc.Particle} particle
* @param {cc.Point} newPosition
*/
- updateQuadWithParticle:function (particle, newPosition) {
+ updateQuadWithParticle: function (particle, newPosition) {
this._renderCmd.updateQuadWithParticle(particle, newPosition);
},
/**
* should be overridden by subclasses
*/
- postStep:function () {
+ postStep: function () {
this._renderCmd.postStep();
},
@@ -1827,10 +1847,10 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
} else {
// life < 0
var currentIndex = selParticle.atlasIndex;
- if(this._particleIdx !== this.particleCount -1){
- var deadParticle = locParticles[this._particleIdx];
- locParticles[this._particleIdx] = locParticles[this.particleCount -1];
- locParticles[this.particleCount -1] = deadParticle;
+ if (this._particleIdx !== this.particleCount - 1) {
+ var deadParticle = locParticles[this._particleIdx];
+ locParticles[this._particleIdx] = locParticles[this.particleCount - 1];
+ locParticles[this.particleCount - 1] = deadParticle;
}
if (this._batchNode) {
//disable the switched particle
@@ -1857,7 +1877,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
/**
* update emitter's status (dt = 0)
*/
- updateWithNoTime:function () {
+ updateWithNoTime: function () {
this.update(0);
},
@@ -1868,7 +1888,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
// @return {String} "" if not found; return the string if found.
// @private
//
- _valueForKey:function (key, dict) {
+ _valueForKey: function (key, dict) {
if (dict) {
var pString = dict[key];
return pString != null ? pString : "";
@@ -1876,8 +1896,8 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
return "";
},
- _updateBlendFunc:function () {
- if(this._batchNode){
+ _updateBlendFunc: function () {
+ if (this._batchNode) {
cc.log("Can't change blending functions when the particle is being batched");
return;
}
@@ -1903,7 +1923,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
*
* @return {cc.ParticleSystem}
*/
- clone:function () {
+ clone: function () {
var retParticle = new cc.ParticleSystem();
// self, not super
@@ -1917,7 +1937,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
// blend function
var blend = this.getBlendFunc();
- retParticle.setBlendFunc(blend.src,blend.dst);
+ retParticle.setBlendFunc(blend.src, blend.dst);
// color
retParticle.setStartColor(this.getStartColor());
@@ -1936,15 +1956,15 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
// position
retParticle.setPosition(cc.p(this.x, this.y));
- retParticle.setPosVar(cc.p(this.getPosVar().x,this.getPosVar().y));
+ retParticle.setPosVar(cc.p(this.getPosVar().x, this.getPosVar().y));
retParticle.setPositionType(this.getPositionType());
// Spinning
- retParticle.setStartSpin(this.getStartSpin()||0);
- retParticle.setStartSpinVar(this.getStartSpinVar()||0);
- retParticle.setEndSpin(this.getEndSpin()||0);
- retParticle.setEndSpinVar(this.getEndSpinVar()||0);
+ retParticle.setStartSpin(this.getStartSpin() || 0);
+ retParticle.setStartSpinVar(this.getStartSpinVar() || 0);
+ retParticle.setEndSpin(this.getEndSpin() || 0);
+ retParticle.setEndSpinVar(this.getEndSpinVar() || 0);
retParticle.setEmitterMode(this.getEmitterMode());
@@ -1952,7 +1972,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
if (this.getEmitterMode() === cc.ParticleSystem.MODE_GRAVITY) {
// gravity
var gra = this.getGravity();
- retParticle.setGravity(cc.p(gra.x,gra.y));
+ retParticle.setGravity(cc.p(gra.x, gra.y));
// speed
retParticle.setSpeed(this.getSpeed());
@@ -1990,7 +2010,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
retParticle.setOpacityModifyRGB(this.isOpacityModifyRGB());
// texture
var texture = this.getTexture();
- if(texture){
+ if (texture) {
var size = texture.getContentSize();
retParticle.setTextureWithRect(texture, cc.rect(0, 0, size.width, size.height));
}
@@ -2037,7 +2057,7 @@ cc.ParticleSystem = cc.Node.extend(/** @lends cc.ParticleSystem# */{
* listen the event that coming to foreground on Android (An empty function for native)
* @param {cc.Class} obj
*/
- listenBackToForeground:function (obj) {
+ listenBackToForeground: function (obj) {
//do nothing
}
});
@@ -2169,7 +2189,7 @@ cc.ParticleSystem.createWithTotalParticles = cc.ParticleSystem.create;
*/
cc.ParticleSystem.ModeA = function (gravity, speed, speedVar, tangentialAccel, tangentialAccelVar, radialAccel, radialAccelVar, rotationIsDir) {
/** Gravity value. Only available in 'Gravity' mode. */
- this.gravity = gravity ? gravity : cc.p(0,0);
+ this.gravity = gravity ? gravity : cc.p(0, 0);
/** speed of each particle. Only available in 'Gravity' mode. */
this.speed = speed || 0;
/** speed variance of each particle. Only available in 'Gravity' mode. */
diff --git a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js
index de78252346..5f602e99f2 100644
--- a/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js
+++ b/cocos2d/particle/CCParticleSystemCanvasRenderCmd.js
@@ -25,37 +25,37 @@
/**
* ParticleSystem's canvas render command
*/
-(function(){
- cc.ParticleSystem.CanvasRenderCmd = function(renderable){
- cc.Node.CanvasRenderCmd.call(this, renderable);
+(function () {
+ cc.ParticleSystem.CanvasRenderCmd = function (renderable) {
+ this._rootCtor(renderable);
this._needDraw = true;
this._drawMode = cc.ParticleSystem.TEXTURE_MODE;
this._shapeType = cc.ParticleSystem.BALL_SHAPE;
this._pointRect = cc.rect(0, 0, 0, 0);
- this._tintCache = document.createElement("canvas");
+ this._tintCache = null;
};
var proto = cc.ParticleSystem.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
proto.constructor = cc.ParticleSystem.CanvasRenderCmd;
- proto.getDrawMode = function(){
+ proto.getDrawMode = function () {
return this._drawMode;
};
- proto.setDrawMode = function(drawMode){
+ proto.setDrawMode = function (drawMode) {
this._drawMode = drawMode;
};
- proto.getShapeType = function(){
+ proto.getShapeType = function () {
return this._shapeType;
};
- proto.setShapeType = function(shapeType){
+ proto.setShapeType = function (shapeType) {
this._shapeType = shapeType;
};
- proto.setBatchNode = function(batchNode){
+ proto.setBatchNode = function (batchNode) {
if (this._batchNode !== batchNode) {
this._node._batchNode = batchNode;
}
@@ -65,7 +65,7 @@
//do nothing
};
- proto.updateParticlePosition = function(particle, position){
+ proto.updateParticlePosition = function (particle, position) {
cc.pIn(particle.drawPos, position);
};
@@ -143,7 +143,10 @@
cc.g_NumberOfDraws++;
};
- proto._changeTextureColor = function(texture, color, rect){
+ proto._changeTextureColor = function (texture, color, rect) {
+ if (!this._tintCache) {
+ this._tintCache = document.createElement("canvas");
+ }
var tintCache = this._tintCache;
var textureContentSize = texture.getContentSize();
tintCache.width = textureContentSize.width;
@@ -151,16 +154,16 @@
return texture._generateColorTexture(color.r, color.g, color.b, rect, tintCache);
};
- proto.initTexCoordsWithRect = function(pointRect){
+ proto.initTexCoordsWithRect = function (pointRect) {
this._pointRect = pointRect;
};
- proto.setTotalParticles = function(tp){
+ proto.setTotalParticles = function (tp) {
//cc.assert(tp <= this._allocatedParticles, "Particle: resizing particle array only supported for quads");
this._node._totalParticles = (tp < 200) ? tp : 200;
};
- proto.addParticle = function(){
+ proto.addParticle = function () {
var node = this._node,
particles = node._particles,
particle;
@@ -173,27 +176,31 @@
return particle;
};
- proto._setupVBO = function(){};
- proto._allocMemory = function(){
+ proto._setupVBO = function () {
+ };
+ proto._allocMemory = function () {
return true;
};
- proto.postStep = function(){};
+ proto.postStep = function () {
+ };
- proto._setBlendAdditive = function(){
+ proto._setBlendAdditive = function () {
var locBlendFunc = this._node._blendFunc;
locBlendFunc.src = cc.BLEND_SRC;
locBlendFunc.dst = cc.BLEND_DST;
};
- proto._initWithTotalParticles = function(totalParticles){};
- proto._updateDeltaColor = function(selParticle, dt){
+ proto._initWithTotalParticles = function (totalParticles) {
+ };
+ proto._updateDeltaColor = function (selParticle, dt) {
if (!this._node._dontTint) {
- selParticle.color.r += selParticle.deltaColor.r * dt;
- selParticle.color.g += selParticle.deltaColor.g * dt;
- selParticle.color.b += selParticle.deltaColor.b * dt;
- selParticle.color.a += selParticle.deltaColor.a * dt;
- selParticle.isChangeColor = true;
+ var deltaColor = selParticle.deltaColor;
+ selParticle.color.r += deltaColor.r * dt;
+ selParticle.color.g += deltaColor.g * dt;
+ selParticle.color.b += deltaColor.b * dt;
+ selParticle.color.a += deltaColor.a * dt;
+ selParticle.isChangeColor = deltaColor.r !== 0 || deltaColor.g !== 0 || deltaColor.b !== 0;
}
};
})();
diff --git a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js
index 8e684256d3..54b1236119 100644
--- a/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js
+++ b/cocos2d/particle/CCParticleSystemWebGLRenderCmd.js
@@ -22,16 +22,15 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
+(function () {
/**
* ParticleSystem's WebGL render command
*/
- cc.ParticleSystem.WebGLRenderCmd = function(renderable){
- cc.Node.WebGLRenderCmd.call(this, renderable);
+ cc.ParticleSystem.WebGLRenderCmd = function (renderable) {
+ this._rootCtor(renderable);
this._needDraw = true;
- this._matrix = new cc.math.Matrix4();
- this._matrix.identity();
+ this._matrix = null;
this._buffersVBO = [0, 0];
this._quads = [];
@@ -41,12 +40,16 @@
var proto = cc.ParticleSystem.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
proto.constructor = cc.ParticleSystem.WebGLRenderCmd;
- proto.getDrawMode = function(){};
- proto.setDrawMode = function(drawMode){};
- proto.getShapeType = function(){};
- proto.setShapeType = function(shapeType){};
+ proto.getDrawMode = function () {
+ };
+ proto.setDrawMode = function (drawMode) {
+ };
+ proto.getShapeType = function () {
+ };
+ proto.setShapeType = function (shapeType) {
+ };
- proto.setBatchNode = function(batchNode){
+ proto.setBatchNode = function (batchNode) {
var node = this._node;
if (node._batchNode !== batchNode) {
var oldBatch = node._batchNode;
@@ -91,11 +94,11 @@
}
};
- proto.isDifferentTexture = function(texture1, texture2){
- return (texture1 === texture2);
+ proto.isDifferentTexture = function (texture1, texture2) {
+ return (texture1 === texture2);
};
- proto.updateParticlePosition = function(particle, position){
+ proto.updateParticlePosition = function (particle, position) {
// IMPORTANT: newPos may not be used as a reference here! (as it is just the temporary tpa point)
// the implementation of updateQuadWithParticle must use
// the x and y values directly
@@ -113,9 +116,9 @@
var r, g, b, a;
if (node._opacityModifyRGB) {
- r = 0 | (particle.color.r * particle.color.a/255);
- g = 0 | (particle.color.g * particle.color.a/255);
- b = 0 | (particle.color.b * particle.color.a/255);
+ r = 0 | (particle.color.r * particle.color.a / 255);
+ g = 0 | (particle.color.g * particle.color.a / 255);
+ b = 0 | (particle.color.b * particle.color.a / 255);
} else {
r = 0 | (particle.color.r );
g = 0 | (particle.color.g );
@@ -189,6 +192,10 @@
var gl = ctx || cc._renderContext;
+ if (!this._matrix) {
+ this._matrix = new cc.math.Matrix4();
+ this._matrix.identity();
+ }
var wt = this._worldTransform;
this._matrix.mat[0] = wt.a;
this._matrix.mat[4] = wt.c;
@@ -197,8 +204,7 @@
this._matrix.mat[5] = wt.d;
this._matrix.mat[13] = wt.ty;
- this._shaderProgram.use();
- this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix); //;
+ this._glProgramState.apply(this._matrix);
cc.glBindTexture2D(node._texture);
cc.glBlendFuncForParticle(node._blendFunc.src, node._blendFunc.dst);
@@ -219,16 +225,16 @@
gl.drawElements(gl.TRIANGLES, node._particleIdx * 6, gl.UNSIGNED_SHORT, 0);
};
- proto.initTexCoordsWithRect = function(pointRect){
+ proto.initTexCoordsWithRect = function (pointRect) {
var node = this._node;
var texture = node.texture;
var scaleFactor = cc.contentScaleFactor();
// convert to pixels coords
var rect = cc.rect(
- pointRect.x * scaleFactor,
- pointRect.y * scaleFactor,
- pointRect.width * scaleFactor,
- pointRect.height * scaleFactor);
+ pointRect.x * scaleFactor,
+ pointRect.y * scaleFactor,
+ pointRect.width * scaleFactor,
+ pointRect.height * scaleFactor);
var wide = pointRect.width;
var high = pointRect.height;
@@ -288,7 +294,7 @@
}
};
- proto.setTotalParticles = function(tp){
+ proto.setTotalParticles = function (tp) {
var node = this._node;
// If we are setting the total numer of particles to a number higher
// than what is allocated, we need to allocate new arrays
@@ -321,7 +327,7 @@
this._setupVBO();
//set the texture coord
- if(node._texture){
+ if (node._texture) {
this.initTexCoordsWithRect(cc.rect(0, 0, node._texture.width, node._texture.height));
}
} else
@@ -329,13 +335,13 @@
node.resetSystem();
};
- proto.addParticle = function(){
+ proto.addParticle = function () {
var node = this._node,
particles = node._particles;
return particles[node.particleCount];
};
- proto._setupVBO = function(){
+ proto._setupVBO = function () {
var node = this;
var gl = cc._renderContext;
@@ -351,10 +357,10 @@
//cc.checkGLErrorDebug();
};
- proto._allocMemory = function(){
- var node = this._node;
+ proto._allocMemory = function () {
+ var node = this._node;
//cc.assert((!this._quads && !this._indices), "Memory already allocated");
- if(node._batchNode){
+ if (node._batchNode) {
cc.log("cc.ParticleSystem._allocMemory(): Memory should not be allocated when not using batchNode");
return false;
}
@@ -376,13 +382,13 @@
return true;
};
- proto.postStep = function(){
+ proto.postStep = function () {
var gl = cc._renderContext;
gl.bindBuffer(gl.ARRAY_BUFFER, this._buffersVBO[0]);
gl.bufferSubData(gl.ARRAY_BUFFER, 0, this._quadsArrayBuffer);
};
- proto._setBlendAdditive = function(){
+ proto._setBlendAdditive = function () {
var locBlendFunc = this._node._blendFunc;
if (this._texture && !this._texture.hasPremultipliedAlpha()) {
locBlendFunc.src = cc.SRC_ALPHA;
@@ -393,7 +399,7 @@
}
};
- proto._initWithTotalParticles = function(totalParticles){
+ proto._initWithTotalParticles = function (totalParticles) {
// allocating data space
if (!this._allocMemory())
return false;
@@ -411,4 +417,4 @@
selParticle.color.a += selParticle.deltaColor.a * dt;
selParticle.isChangeColor = true;
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js b/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js
index be1f6f14ba..1adf9a3f49 100644
--- a/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js
+++ b/cocos2d/physics/CCPhysicsDebugNodeCanvasRenderCmd.js
@@ -25,9 +25,9 @@
/**
* cc.PhysicsDebugNode's rendering objects of Canvas
*/
-(function(){
- cc.PhysicsDebugNode.CanvasRenderCmd = function(renderableObject){
- cc.Node.CanvasRenderCmd.call(this, renderableObject);
+(function () {
+ cc.PhysicsDebugNode.CanvasRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
this._buffer = renderableObject._buffer;
this._needDraw = true;
};
@@ -35,7 +35,7 @@
var proto = cc.PhysicsDebugNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
proto.constructor = cc.PhysicsDebugNode.CanvasRenderCmd;
- proto.rendering = function(ctx, scaleX, scaleY){
+ proto.rendering = function (ctx, scaleX, scaleY) {
var node = this._node;
if (!node._space)
return;
diff --git a/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js b/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js
index e2f16f8560..0b8a18504c 100644
--- a/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js
+++ b/cocos2d/physics/CCPhysicsDebugNodeWebGLRenderCmd.js
@@ -25,9 +25,9 @@
/**
* cc.PhysicsDebugNode's rendering objects of WebGL
*/
-(function(){
+(function () {
cc.PhysicsDebugNode.WebGLRenderCmd = function (renderableObject) {
- cc.Node.WebGLRenderCmd.call(this, renderableObject);
+ this._rootCtor(renderableObject);
this._needDraw = true;
this._matrix = new cc.math.Matrix4();
this._matrix.identity();
@@ -54,10 +54,9 @@
//cc.DrawNode.prototype.draw.call(node);
cc.glBlendFunc(node._blendFunc.src, node._blendFunc.dst);
- this._shaderProgram.use();
- this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix);
+ this._glProgramState.apply(this._matrix);
node._render();
node.clear();
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/physics/CCPhysicsSprite.js b/cocos2d/physics/CCPhysicsSprite.js
index 80df018400..dde3546318 100644
--- a/cocos2d/physics/CCPhysicsSprite.js
+++ b/cocos2d/physics/CCPhysicsSprite.js
@@ -37,10 +37,10 @@
*/
(function () {
var box2dAPI = {
- _ignoreBodyRotation:false,
- _body:null,
- _PTMRatio:32,
- _rotation:1,
+ _ignoreBodyRotation: false,
+ _body: null,
+ _PTMRatio: 32,
+ _rotation: 1,
/**
* Create a PhysicsSprite with filename and rect
* Constructor of cc.PhysicsSprite for Box2d
@@ -66,12 +66,12 @@
* var physicsSprite2 = new cc.PhysicsSprite(texture, cc.rect(0,0,480,320));
*
*/
- ctor:function(fileName, rect){
+ ctor: function (fileName, rect) {
cc.Sprite.prototype.ctor.call(this);
if (fileName === undefined) {
cc.PhysicsSprite.prototype.init.call(this);
- }else if (cc.isString(fileName)) {
+ } else if (cc.isString(fileName)) {
if (fileName[0] === "#") {
//init with a sprite frame name
var frameName = fileName.substr(1, fileName.length - 1);
@@ -81,7 +81,7 @@
//init with filename and rect
this.init(fileName, rect);
}
- }else if (cc.isObject(fileName)) {
+ } else if (cc.isObject(fileName)) {
if (fileName instanceof cc.Texture2D) {
//init with texture and rect
this.initWithTexture(fileName, rect);
@@ -103,7 +103,7 @@
* set body
* @param {Box2D.Dynamics.b2Body} body
*/
- setBody:function (body) {
+ setBody: function (body) {
this._body = body;
},
@@ -111,7 +111,7 @@
* get body
* @return {Box2D.Dynamics.b2Body}
*/
- getBody:function () {
+ getBody: function () {
return this._body;
},
@@ -119,7 +119,7 @@
* set PTM ratio
* @param {Number} r
*/
- setPTMRatio:function (r) {
+ setPTMRatio: function (r) {
this._PTMRatio = r;
},
@@ -127,7 +127,7 @@
* get PTM ration
* @return {Number}
*/
- getPTMRatio:function () {
+ getPTMRatio: function () {
return this._PTMRatio;
},
@@ -135,9 +135,9 @@
* get position
* @return {cc.Point}
*/
- getPosition:function () {
+ getPosition: function () {
var pos = this._body.GetPosition();
- var locPTMRatio =this._PTMRatio;
+ var locPTMRatio = this._PTMRatio;
return cc.p(pos.x * locPTMRatio, pos.y * locPTMRatio);
},
@@ -145,9 +145,9 @@
* set position
* @param {cc.Point} p
*/
- setPosition:function (p) {
+ setPosition: function (p) {
var angle = this._body.GetAngle();
- var locPTMRatio =this._PTMRatio;
+ var locPTMRatio = this._PTMRatio;
this._body.setTransform(Box2D.b2Vec2(p.x / locPTMRatio, p.y / locPTMRatio), angle);
this.setNodeDirty();
},
@@ -156,7 +156,7 @@
* get rotation
* @return {Number}
*/
- getRotation:function () {
+ getRotation: function () {
return (this._ignoreBodyRotation ? cc.radiansToDegrees(this._rotationRadians) : cc.radiansToDegrees(this._body.GetAngle()));
},
@@ -164,7 +164,7 @@
* set rotation
* @param {Number} r
*/
- setRotation:function (r) {
+ setRotation: function (r) {
if (this._ignoreBodyRotation) {
this._rotation = r;
} else {
@@ -175,7 +175,7 @@
this.setNodeDirty();
},
- _syncPosition:function () {
+ _syncPosition: function () {
var locPosition = this._position,
pos = this._body.GetPosition(),
x = pos.x * this._PTMRatio,
@@ -184,7 +184,7 @@
cc.Sprite.prototype.setPosition.call(this, x, y);
}
},
- _syncRotation:function () {
+ _syncRotation: function () {
this._rotationRadians = this._body.GetAngle();
var a = cc.radiansToDegrees(this._rotationRadians);
if (this._rotationX !== a) {
@@ -196,15 +196,15 @@
* set whether to ingore body's rotation
* @param {Boolean} b
*/
- setIgnoreBodyRotation: function(b) {
+ setIgnoreBodyRotation: function (b) {
this._ignoreBodyRotation = b;
}
};
var chipmunkAPI = {
- _ignoreBodyRotation:false,
- _body:null, //physics body
- _rotation:1,
+ _ignoreBodyRotation: false,
+ _body: null, //physics body
+ _rotation: 1,
/**
* Create a PhysicsSprite with filename and rect
@@ -231,12 +231,12 @@
* var physicsSprite2 = new cc.PhysicsSprite(texture, cc.rect(0,0,480,320));
*
*/
- ctor:function(fileName, rect){
+ ctor: function (fileName, rect) {
cc.Sprite.prototype.ctor.call(this);
if (fileName === undefined) {
cc.PhysicsSprite.prototype.init.call(this);
- }else if (cc.isString(fileName)) {
+ } else if (cc.isString(fileName)) {
if (fileName[0] === "#") {
//init with a sprite frame name
var frameName = fileName.substr(1, fileName.length - 1);
@@ -246,7 +246,7 @@
//init with filename and rect
this.init(fileName, rect);
}
- }else if (cc.isObject(fileName)) {
+ } else if (cc.isObject(fileName)) {
if (fileName instanceof cc.Texture2D) {
//init with texture and rect
this.initWithTexture(fileName, rect);
@@ -259,7 +259,7 @@
cc.renderer.pushRenderCommand(this._renderCmd);
},
- visit: function(){
+ visit: function () {
cc.renderer.pushRenderCommand(this._renderCmd);
cc.Sprite.prototype.visit.call(this);
},
@@ -268,7 +268,7 @@
* set body
* @param {cp.Body} body
*/
- setBody:function (body) {
+ setBody: function (body) {
this._body = body;
},
@@ -276,7 +276,7 @@
* get body
* @returns {cp.Body}
*/
- getBody:function () {
+ getBody: function () {
return this._body;
},
@@ -284,16 +284,16 @@
* get position
* @return {cc.Point}
*/
- getPosition:function () {
+ getPosition: function () {
var locBody = this._body;
- return {x:locBody.p.x, y:locBody.p.y};
+ return {x: locBody.p.x, y: locBody.p.y};
},
/**
* get position x
* @return {Number}
*/
- getPositionX:function () {
+ getPositionX: function () {
return this._body.p.x;
},
@@ -301,7 +301,7 @@
* get position y
* @return {Number}
*/
- getPositionY:function () {
+ getPositionY: function () {
return this._body.p.y;
},
@@ -310,7 +310,7 @@
* @param {cc.Point|Number}newPosOrxValue
* @param {Number}yValue
*/
- setPosition:function (newPosOrxValue, yValue) {
+ setPosition: function (newPosOrxValue, yValue) {
if (yValue === undefined) {
this._body.p.x = newPosOrxValue.x;
this._body.p.y = newPosOrxValue.y;
@@ -324,7 +324,7 @@
* set position x
* @param {Number} xValue
*/
- setPositionX:function (xValue) {
+ setPositionX: function (xValue) {
this._body.p.x = xValue;
},
@@ -332,11 +332,11 @@
* set position y
* @param {Number} yValue
*/
- setPositionY:function (yValue) {
+ setPositionY: function (yValue) {
this._body.p.y = yValue;
},
- _syncPosition:function () {
+ _syncPosition: function () {
var locPosition = this._position, locBody = this._body;
if (locPosition.x !== locBody.p.x || locPosition.y !== locBody.p.y) {
cc.Sprite.prototype.setPosition.call(this, locBody.p.x, locBody.p.y);
@@ -347,7 +347,7 @@
* get rotation
* @return {Number}
*/
- getRotation:function () {
+ getRotation: function () {
return this._ignoreBodyRotation ? this._rotationX : -cc.radiansToDegrees(this._body.a);
},
@@ -355,14 +355,14 @@
* set rotation
* @param {Number} r
*/
- setRotation:function (r) {
+ setRotation: function (r) {
if (this._ignoreBodyRotation) {
cc.Sprite.prototype.setRotation.call(this, r);
} else {
this._body.a = -cc.degreesToRadians(r);
}
},
- _syncRotation:function () {
+ _syncRotation: function () {
var a = -cc.radiansToDegrees(this._body.a);
if (this._rotationX !== a) {
cc.Sprite.prototype.setRotation.call(this, a);
@@ -373,7 +373,7 @@
* get the affine transform matrix of node to parent coordinate frame
* @return {cc.AffineTransform}
*/
- getNodeToParentTransform:function () {
+ getNodeToParentTransform: function () {
return this._renderCmd.getNodeToParentTransform();
},
@@ -381,21 +381,22 @@
* whether dirty
* @return {Boolean}
*/
- isDirty:function(){
- return !this._body.isSleeping();
+ isDirty: function () {
+ return !this._body.isSleeping();
+ },
+ setDirty: function () {
},
- setDirty: function(){ },
/**
* set whether to ignore rotation of body
* @param {Boolean} b
*/
- setIgnoreBodyRotation: function(b) {
+ setIgnoreBodyRotation: function (b) {
this._ignoreBodyRotation = b;
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return new cc.PhysicsSprite.CanvasRenderCmd(this);
else
return new cc.PhysicsSprite.WebGLRenderCmd(this);
diff --git a/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js b/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js
index 705749d259..09279e65ea 100644
--- a/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js
+++ b/cocos2d/physics/CCPhysicsSpriteCanvasRenderCmd.js
@@ -25,26 +25,26 @@
/**
* cc.PhysicsSprite's rendering objects of Canvas
*/
-(function(){
- cc.PhysicsSprite.CanvasRenderCmd = function(renderableObject){
- cc.Sprite.CanvasRenderCmd.call(this, renderableObject);
+(function () {
+ cc.PhysicsSprite.CanvasRenderCmd = function (renderableObject) {
+ this._spriteCmdCtor(renderableObject);
this._needDraw = true;
};
var proto = cc.PhysicsSprite.CanvasRenderCmd.prototype = Object.create(cc.Sprite.CanvasRenderCmd.prototype);
proto.constructor = cc.PhysicsSprite.CanvasRenderCmd;
- proto.rendering = function(ctx, scaleX, scaleY){
+ proto.rendering = function (ctx, scaleX, scaleY) {
// This is a special class
// Sprite can not obtain sign
// So here must to calculate of each frame
- var node = this._node;
+ var node = this._node;
node._syncPosition();
- if(!node._ignoreBodyRotation)
+ if (!node._ignoreBodyRotation)
node._syncRotation();
this.transform(this.getParentRenderCmd());
cc.Sprite.CanvasRenderCmd.prototype.rendering.call(this, ctx, scaleX, scaleY);
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js b/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js
index d2e6b25c25..25fc120601 100644
--- a/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js
+++ b/cocos2d/physics/CCPhysicsSpriteWebGLRenderCmd.js
@@ -25,9 +25,9 @@
/**
* cc.PhysicsSprite's rendering objects of WebGL
*/
-(function(){
- cc.PhysicsSprite.WebGLRenderCmd = function(renderableObject){
- cc.Sprite.WebGLRenderCmd.call(this, renderableObject);
+(function () {
+ cc.PhysicsSprite.WebGLRenderCmd = function (renderableObject) {
+ this._spriteCmdCtor(renderableObject);
this._needDraw = true;
};
@@ -40,12 +40,12 @@
// This is a special class
// Sprite can not obtain sign
// So here must to calculate of each frame
- var node = this._node;
+ var node = this._node;
node._syncPosition();
- if(!node._ignoreBodyRotation)
+ if (!node._ignoreBodyRotation)
node._syncRotation();
this.transform(this.getParentRenderCmd(), true);
return this.spUploadData(f32buffer, ui32buffer, vertexDataOffset);
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js
index 2a9c8682a4..4dc2a71b74 100644
--- a/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js
+++ b/cocos2d/progress-timer/CCProgressTimerCanvasRenderCmd.js
@@ -25,9 +25,9 @@
/**
* cc.ProgressTimer's rendering objects of Canvas
*/
-(function(){
- cc.ProgressTimer.CanvasRenderCmd = function(renderableObject){
- cc.Node.CanvasRenderCmd.call(this, renderableObject);
+(function () {
+ cc.ProgressTimer.CanvasRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
this._needDraw = true;
this._PI180 = Math.PI / 180;
@@ -44,7 +44,7 @@
proto.constructor = cc.ProgressTimer.CanvasRenderCmd;
proto.rendering = function (ctx, scaleX, scaleY) {
- var wrapper = ctx || cc._renderContext,context = wrapper.getContext(), node = this._node, locSprite = node._sprite;
+ var wrapper = ctx || cc._renderContext, context = wrapper.getContext(), node = this._node, locSprite = node._sprite;
var locTextureCoord = locSprite._renderCmd._textureCoord, alpha = locSprite._renderCmd._displayedOpacity / 255;
if (locTextureCoord.width === 0 || locTextureCoord.height === 0)
@@ -76,14 +76,14 @@
if (node._type === cc.ProgressTimer.TYPE_BAR) {
var locBarRect = this._barRect;
context.beginPath();
- context.rect(locBarRect.x , locBarRect.y , locBarRect.width , locBarRect.height );
+ context.rect(locBarRect.x, locBarRect.y, locBarRect.width, locBarRect.height);
context.clip();
context.closePath();
} else if (node._type === cc.ProgressTimer.TYPE_RADIAL) {
- var locOriginX = this._origin.x ;
- var locOriginY = this._origin.y ;
+ var locOriginX = this._origin.x;
+ var locOriginY = this._origin.y;
context.beginPath();
- context.arc(locOriginX, locOriginY, this._radius , this._PI180 * this._startAngle, this._PI180 * this._endAngle, this._counterClockWise);
+ context.arc(locOriginX, locOriginY, this._radius, this._PI180 * this._startAngle, this._PI180 * this._endAngle, this._counterClockWise);
context.lineTo(locOriginX, locOriginY);
context.clip();
context.closePath();
@@ -95,21 +95,23 @@
if (locSprite._renderCmd._colorized) {
context.drawImage(image,
0, 0, locTextureCoord.width, locTextureCoord.height,
- locX , locY , locWidth , locHeight );
+ locX, locY, locWidth, locHeight);
} else {
context.drawImage(image,
locTextureCoord.renderX, locTextureCoord.renderY, locTextureCoord.width, locTextureCoord.height,
- locX , locY , locWidth , locHeight );
+ locX, locY, locWidth, locHeight);
}
wrapper.restore();
cc.g_NumberOfDraws++;
};
- proto.releaseData = function(){};
+ proto.releaseData = function () {
+ };
- proto.resetVertexData = function(){};
+ proto.resetVertexData = function () {
+ };
- proto._updateProgress = function(){
+ proto._updateProgress = function () {
this.setDirtyFlag(cc.Node._dirtyFlags.contentDirty);
var node = this._node;
var locSprite = node._sprite;
@@ -197,18 +199,18 @@
proto._syncStatus = function (parentCmd) {
var node = this._node;
- if(!node._sprite)
+ if (!node._sprite)
return;
var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
var parentNode = parentCmd ? parentCmd._node : null;
- if(parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty))
+ if (parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty))
locFlag |= flags.colorDirty;
- if(parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty))
+ if (parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty))
locFlag |= flags.opacityDirty;
- if(parentCmd && (parentCmd._dirtyFlag & flags.transformDirty))
+ if (parentCmd && (parentCmd._dirtyFlag & flags.transformDirty))
locFlag |= flags.transformDirty;
this._dirtyFlag = locFlag;
@@ -219,19 +221,19 @@
var colorDirty = spriteFlag & flags.colorDirty,
opacityDirty = spriteFlag & flags.opacityDirty;
- if (colorDirty){
+ if (colorDirty) {
spriteCmd._syncDisplayColor();
- spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.colorDirty ^ spriteCmd._dirtyFlag;
- this._dirtyFlag = this._dirtyFlag & flags.colorDirty ^ this._dirtyFlag;
+ spriteCmd._dirtyFlag &= ~flags.colorDirty;
+ this._dirtyFlag &= ~flags.colorDirty;
}
- if (opacityDirty){
+ if (opacityDirty) {
spriteCmd._syncDisplayOpacity();
- spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.opacityDirty ^ spriteCmd._dirtyFlag;
- this._dirtyFlag = this._dirtyFlag & flags.opacityDirty ^ this._dirtyFlag;
+ spriteCmd._dirtyFlag &= ~flags.opacityDirty;
+ this._dirtyFlag &= ~flags.opacityDirty;
}
- if(colorDirty || opacityDirty){
+ if (colorDirty || opacityDirty) {
spriteCmd._updateColor();
}
@@ -241,13 +243,13 @@
}
if (locFlag & flags.orderDirty) {
- this._dirtyFlag = this._dirtyFlag & flags.orderDirty ^ this._dirtyFlag;
+ this._dirtyFlag &= ~flags.orderDirty;
}
};
proto.updateStatus = function () {
var node = this._node;
- if(!node._sprite)
+ if (!node._sprite)
return;
var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
var spriteCmd = node._sprite._renderCmd;
@@ -256,23 +258,23 @@
var colorDirty = spriteFlag & flags.colorDirty,
opacityDirty = spriteFlag & flags.opacityDirty;
- if(colorDirty){
+ if (colorDirty) {
spriteCmd._updateDisplayColor();
spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.colorDirty ^ spriteCmd._dirtyFlag;
this._dirtyFlag = this._dirtyFlag & flags.colorDirty ^ this._dirtyFlag;
}
- if(opacityDirty){
+ if (opacityDirty) {
spriteCmd._updateDisplayOpacity();
spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.opacityDirty ^ spriteCmd._dirtyFlag;
this._dirtyFlag = this._dirtyFlag & flags.opacityDirty ^ this._dirtyFlag;
}
- if(colorDirty || opacityDirty){
+ if (colorDirty || opacityDirty) {
spriteCmd._updateColor();
}
- if(locFlag & flags.transformDirty){
+ if (locFlag & flags.transformDirty) {
//update the transform
this.transform(this.getParentRenderCmd(), true);
}
@@ -281,4 +283,4 @@
}
this._dirtyFlag = 0;
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js
index e1be5255ae..8a89913eed 100644
--- a/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js
+++ b/cocos2d/progress-timer/CCProgressTimerWebGLRenderCmd.js
@@ -25,16 +25,17 @@
/**
* cc.ProgressTimer's rendering objects of WebGL
*/
-(function(){
+(function () {
var MAX_VERTEX_COUNT = 8;
- cc.ProgressTimer.WebGLRenderCmd = function(renderableObject){
- cc.Node.WebGLRenderCmd.call(this, renderableObject);
+ cc.ProgressTimer.WebGLRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
this._needDraw = true;
this._progressDirty = true;
this._bl = cc.p();
this._tr = cc.p();
+ this._transformUpdating = false;
this.initCmd();
};
@@ -55,7 +56,9 @@
this._tr.x = rx * wt.a + ty * wt.c + wt.tx;
this._tr.y = rx * wt.b + ty * wt.d + wt.ty;
+ this._transformUpdating = true;
this._updateProgressData();
+ this._transformUpdating = false;
};
proto.rendering = function (ctx) {
@@ -64,7 +67,7 @@
if (this._vertexDataCount === 0 || !node._sprite)
return;
- this._shaderProgram.use();
+ this._glProgramState.apply();
this._shaderProgram._updateProjectionUniform();
var blendFunc = node._sprite._blendFunc;
@@ -102,16 +105,16 @@
proto._syncStatus = function (parentCmd) {
var node = this._node;
- if(!node._sprite)
+ if (!node._sprite)
return;
var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
var parentNode = parentCmd ? parentCmd._node : null;
- if(parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty))
+ if (parentNode && parentNode._cascadeColorEnabled && (parentCmd._dirtyFlag & flags.colorDirty))
locFlag |= flags.colorDirty;
- if(parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty))
+ if (parentNode && parentNode._cascadeOpacityEnabled && (parentCmd._dirtyFlag & flags.opacityDirty))
locFlag |= flags.opacityDirty;
- if(parentCmd && (parentCmd._dirtyFlag & flags.transformDirty))
+ if (parentCmd && (parentCmd._dirtyFlag & flags.transformDirty))
locFlag |= flags.transformDirty;
this._dirtyFlag = locFlag;
@@ -121,19 +124,19 @@
var colorDirty = (locFlag | spriteFlag) & flags.colorDirty,
opacityDirty = (locFlag | spriteFlag) & flags.opacityDirty;
- if (colorDirty){
+ if (colorDirty) {
spriteCmd._syncDisplayColor();
- spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.colorDirty ^ spriteCmd._dirtyFlag;
- this._dirtyFlag = this._dirtyFlag & flags.colorDirty ^ this._dirtyFlag;
+ spriteCmd._dirtyFlag &= ~flags.colorDirty;
+ this._dirtyFlag &= ~flags.colorDirty;
}
- if (opacityDirty){
+ if (opacityDirty) {
spriteCmd._syncDisplayOpacity();
- spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.opacityDirty ^ spriteCmd._dirtyFlag;
- this._dirtyFlag = this._dirtyFlag & flags.opacityDirty ^ this._dirtyFlag;
+ spriteCmd._dirtyFlag &= ~flags.opacityDirty;
+ this._dirtyFlag &= ~flags.opacityDirty;
}
- if(colorDirty || opacityDirty){
+ if (colorDirty || opacityDirty) {
this._updateColor();
}
@@ -144,7 +147,7 @@
if (locFlag & flags.textureDirty) {
this._updateProgressData();
- this._dirtyFlag = this._dirtyFlag & flags.textureDirty ^ this._dirtyFlag;
+ this._dirtyFlag &= ~flags.textureDirty;
}
spriteCmd._dirtyFlag = 0;
@@ -152,7 +155,7 @@
proto.updateStatus = function () {
var node = this._node;
- if(!node._sprite)
+ if (!node._sprite)
return;
var flags = cc.Node._dirtyFlags, locFlag = this._dirtyFlag;
var spriteCmd = node._sprite._renderCmd;
@@ -161,23 +164,23 @@
var colorDirty = (locFlag | spriteFlag) & flags.colorDirty,
opacityDirty = (locFlag | spriteFlag) & flags.opacityDirty;
- if(colorDirty){
+ if (colorDirty) {
spriteCmd._updateDisplayColor();
spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.colorDirty ^ spriteCmd._dirtyFlag;
this._dirtyFlag = this._dirtyFlag & flags.colorDirty ^ this._dirtyFlag;
}
- if(opacityDirty){
+ if (opacityDirty) {
spriteCmd._updateDisplayOpacity();
spriteCmd._dirtyFlag = spriteCmd._dirtyFlag & flags.opacityDirty ^ spriteCmd._dirtyFlag;
this._dirtyFlag = this._dirtyFlag & flags.opacityDirty ^ this._dirtyFlag;
}
- if(colorDirty || opacityDirty){
+ if (colorDirty || opacityDirty) {
this._updateColor();
}
- if(locFlag & flags.transformDirty){
+ if (locFlag & flags.transformDirty) {
//update the transform
this.transform(this.getParentRenderCmd(), true);
}
@@ -192,7 +195,7 @@
}
};
- proto.releaseData = function(){
+ proto.releaseData = function () {
if (this._vertexData) {
//release all previous information
var webglBuffer = this._vertexWebGLBuffer;
@@ -238,9 +241,9 @@
proto._updateProgressData = function () {
var node = this._node;
var locType = node._type;
- if(locType === cc.ProgressTimer.TYPE_RADIAL)
+ if (locType === cc.ProgressTimer.TYPE_RADIAL)
this._updateRadial();
- else if(locType === cc.ProgressTimer.TYPE_BAR)
+ else if (locType === cc.ProgressTimer.TYPE_BAR)
this._updateBar();
this._vertexDataDirty = true;
};
@@ -260,7 +263,7 @@
*
* @private
*/
- proto._updateBar = function(){
+ proto._updateBar = function () {
var node = this._node;
if (!node._sprite)
return;
@@ -268,7 +271,7 @@
var i, alpha = node._percentage / 100.0;
var locBarChangeRate = node._barChangeRate;
var alphaOffset = cc.pMult(cc.p((1.0 - locBarChangeRate.x) + alpha * locBarChangeRate.x,
- (1.0 - locBarChangeRate.y) + alpha * locBarChangeRate.y), 0.5);
+ (1.0 - locBarChangeRate.y) + alpha * locBarChangeRate.y), 0.5);
var min = cc.pSub(node._midPoint, alphaOffset), max = cc.pAdd(node._midPoint, alphaOffset);
if (min.x < 0) {
@@ -449,7 +452,7 @@
this._updateColor();
var locVertexData = this._vertexData;
- if (!sameIndexCount) {
+ if (this._transformUpdating || !sameIndexCount) {
// First we populate the array with the m_tMidpoint, then all
// vertices/texcoords/colors of the 12 'o clock start and edges and the hitpoint
this._textureCoordFromAlphaPoint(locVertexData[0].texCoords, locMidPoint.x, locMidPoint.y);
@@ -478,7 +481,7 @@
else
return cc.p((locProTextCoords >> ((index << 1) + 1)) & 1, (locProTextCoords >> (index << 1)) & 1);
}
- return cc.p(0,0);
+ return cc.p(0, 0);
};
proto._textureCoordFromAlphaPoint = function (coords, ax, ay) {
@@ -510,7 +513,7 @@
vertex.z = this._node._vertexZ;
};
- proto._updateColor = function(){
+ proto._updateColor = function () {
var sp = this._node._sprite;
if (!this._vertexDataCount || !sp)
return;
@@ -536,4 +539,4 @@
}
this._vertexDataDirty = true;
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/render-texture/CCRenderTexture.js b/cocos2d/render-texture/CCRenderTexture.js
index d0e6950e51..5cc00ae45a 100644
--- a/cocos2d/render-texture/CCRenderTexture.js
+++ b/cocos2d/render-texture/CCRenderTexture.js
@@ -77,26 +77,26 @@ cc.NextPOT = function (x) {
* @property {cc.Color} clearColorVal - Clear color value, valid only when "autoDraw" is true.
*/
cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
- sprite:null,
+ sprite: null,
- //
- //
Code for "auto" update
- // Valid flags: GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
- // They can be OR'ed. Valid when "autoDraw is YES.
- // @public
- //
- clearFlags:0,
+ //
+ //
Code for "auto" update
+ // Valid flags: GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT.
+ // They can be OR'ed. Valid when "autoDraw is YES.
+ // @public
+ //
+ clearFlags: 0,
- clearDepthVal:0,
- autoDraw:false,
+ clearDepthVal: 0,
+ autoDraw: false,
- _texture:null,
- _pixelFormat:0,
+ _texture: null,
+ _pixelFormat: 0,
- clearStencilVal:0,
- _clearColor:null,
+ clearStencilVal: 0,
+ _clearColor: null,
- _className:"RenderTexture",
+ _className: "RenderTexture",
/**
* creates a RenderTexture object with width and height in Points and a pixel format, only RGB and RGBA formats are valid
@@ -110,33 +110,50 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* var rt = new cc.RenderTexture(width, height, format, depthStencilFormat)
* @function
*/
- ctor: function(width, height, format, depthStencilFormat){
+ ctor: function (width, height, format, depthStencilFormat) {
cc.Node.prototype.ctor.call(this);
this._cascadeColorEnabled = true;
this._cascadeOpacityEnabled = true;
this._pixelFormat = cc.Texture2D.PIXEL_FORMAT_RGBA8888;
- this._clearColor = new cc.Color(0,0,0,255);
+ this._clearColor = new cc.Color(0, 0, 0, 255);
- if(width !== undefined && height !== undefined) {
+ if (width !== undefined && height !== undefined) {
format = format || cc.Texture2D.PIXEL_FORMAT_RGBA8888;
depthStencilFormat = depthStencilFormat || 0;
this.initWithWidthAndHeight(width, height, format, depthStencilFormat);
}
- this.setAnchorPoint(0,0);
+ this.setAnchorPoint(0, 0);
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return new cc.RenderTexture.CanvasRenderCmd(this);
else
return new cc.RenderTexture.WebGLRenderCmd(this);
},
+ visit: function (parent) {
+ var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null;
+
+ // quick return if not visible
+ if (!this._visible) {
+ cmd._propagateFlagsDown(parentCmd);
+ return;
+ }
+
+ var renderer = cc.renderer;
+
+ cmd.visit(parentCmd);
+ renderer.pushRenderCommand(cmd);
+ this.sprite.visit(this);
+ cmd._dirtyFlag = 0;
+ },
+
/**
* Clear RenderTexture.
* @function
*/
- cleanup: function(){
+ cleanup: function () {
cc.Node.prototype.onExit.call(this);
this._renderCmd.cleanup();
},
@@ -145,7 +162,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Gets the sprite
* @return {cc.Sprite}
*/
- getSprite:function () {
+ getSprite: function () {
return this.sprite;
},
@@ -153,7 +170,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Set the sprite
* @param {cc.Sprite} sprite
*/
- setSprite:function (sprite) {
+ setSprite: function (sprite) {
this.sprite = sprite;
},
@@ -163,8 +180,8 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @param {cc.Rect} fullRect
* @param {cc.Rect} fullViewport
*/
- setVirtualViewport: function(rtBegin, fullRect, fullViewport){
- this._renderCmd.setVirtualViewport(rtBegin, fullRect, fullViewport);
+ setVirtualViewport: function (rtBegin, fullRect, fullViewport) {
+ this._renderCmd.setVirtualViewport(rtBegin, fullRect, fullViewport);
},
/**
@@ -176,7 +193,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @param {Number} [depthStencilFormat]
* @return {Boolean}
*/
- initWithWidthAndHeight: function(width, height, format, depthStencilFormat){
+ initWithWidthAndHeight: function (width, height, format, depthStencilFormat) {
return this._renderCmd.initWithWidthAndHeight(width, height, format, depthStencilFormat);
},
@@ -184,7 +201,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* starts grabbing
* @function
*/
- begin: function(){
+ begin: function () {
cc.renderer._turnToCacheMode(this.__instanceId);
this._renderCmd.begin();
},
@@ -198,16 +215,16 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @param {Number} [depthValue=]
* @param {Number} [stencilValue=]
*/
- beginWithClear:function (r, g, b, a, depthValue, stencilValue) {
+ beginWithClear: function (r, g, b, a, depthValue, stencilValue) {
//todo: only for WebGL?
var gl = cc._renderContext;
depthValue = depthValue || gl.COLOR_BUFFER_BIT;
stencilValue = stencilValue || (gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
- this._beginWithClear(r , g , b , a , depthValue, stencilValue, (gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT));
+ this._beginWithClear(r, g, b, a, depthValue, stencilValue, (gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT));
},
- _beginWithClear: function(r, g, b, a, depthValue, stencilValue, flags){
+ _beginWithClear: function (r, g, b, a, depthValue, stencilValue, flags) {
this.begin();
this._renderCmd._beginWithClear(r, g, b, a, depthValue, stencilValue, flags);
},
@@ -216,18 +233,18 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* ends grabbing
* @function
*/
- end: function(){
+ end: function () {
this._renderCmd.end();
},
/**
* 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
+ * @param {Number|cc.Rect} r red 0-255
+ * @param {Number} g green 0-255
+ * @param {Number} b blue 0-255
+ * @param {Number} a alpha 0-255
*/
- clear:function (r, g, b, a) {
+ clear: function (r, g, b, a) {
this.beginWithClear(r, g, b, a);
this.end();
},
@@ -240,7 +257,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @param {number} width
* @param {number} height
*/
- clearRect: function(x, y, width, height){
+ clearRect: function (x, y, width, height) {
this._renderCmd.clearRect(x, y, width, height);
},
@@ -249,7 +266,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @function
* @param {Number} depthValue
*/
- clearDepth: function(depthValue){
+ clearDepth: function (depthValue) {
this._renderCmd.clearDepth(depthValue);
},
@@ -258,7 +275,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @function
* @param {Number} stencilValue
*/
- clearStencil: function(stencilValue) {
+ clearStencil: function (stencilValue) {
this._renderCmd.clearStencil(stencilValue);
},
@@ -266,7 +283,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Valid flags: GL_COLOR_BUFFER_BIT, GL_DEPTH_BUFFER_BIT, GL_STENCIL_BUFFER_BIT. They can be OR'ed. Valid when "autoDraw is YES.
* @return {Number}
*/
- getClearFlags:function () {
+ getClearFlags: function () {
return this.clearFlags;
},
@@ -274,7 +291,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Set the clearFlags
* @param {Number} clearFlags
*/
- setClearFlags:function (clearFlags) {
+ setClearFlags: function (clearFlags) {
this.clearFlags = clearFlags;
},
@@ -283,16 +300,16 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @function
* @return {cc.Color}
*/
- getClearColor:function () {
+ getClearColor: function () {
return this._clearColor;
},
- /**
- * Set the clear color value. Valid only when "autoDraw" is true.
- * @function
- * @param {cc.Color} clearColor The clear color
- */
- setClearColor: function(clearColor){
+ /**
+ * Set the clear color value. Valid only when "autoDraw" is true.
+ * @function
+ * @param {cc.Color} clearColor The clear color
+ */
+ setClearColor: function (clearColor) {
var locClearColor = this._clearColor;
locClearColor.r = clearColor.r;
locClearColor.g = clearColor.g;
@@ -305,7 +322,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Value for clearDepth. Valid only when autoDraw is true.
* @return {Number}
*/
- getClearDepth:function () {
+ getClearDepth: function () {
return this.clearDepthVal;
},
@@ -313,7 +330,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Set value for clearDepth. Valid only when autoDraw is true.
* @param {Number} clearDepth
*/
- setClearDepth:function (clearDepth) {
+ setClearDepth: function (clearDepth) {
this.clearDepthVal = clearDepth;
},
@@ -321,7 +338,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Value for clear Stencil. Valid only when autoDraw is true
* @return {Number}
*/
- getClearStencil:function () {
+ getClearStencil: function () {
return this.clearStencilVal;
},
@@ -329,7 +346,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Set value for clear Stencil. Valid only when autoDraw is true
* @return {Number}
*/
- setClearStencil:function (clearStencil) {
+ setClearStencil: function (clearStencil) {
this.clearStencilVal = clearStencil;
},
@@ -338,7 +355,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Will be enabled in the future.
* @return {Boolean}
*/
- isAutoDraw:function () {
+ isAutoDraw: function () {
return this.autoDraw;
},
@@ -347,7 +364,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Will be enabled in the future.
* @return {Boolean}
*/
- setAutoDraw:function (autoDraw) {
+ setAutoDraw: function (autoDraw) {
this.autoDraw = autoDraw;
},
@@ -359,7 +376,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* @param {Number} filePath
* @param {Number} format
*/
- saveToFile:function (filePath, format) {
+ saveToFile: function (filePath, format) {
cc.log("saveToFile isn't supported on Cocos2d-Html5");
},
@@ -367,7 +384,7 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* creates a new CCImage from with the texture's data. Caller is responsible for releasing it by calling delete.
* @return {*}
*/
- newCCImage:function(flipImage){
+ newCCImage: function (flipImage) {
cc.log("saveToFile isn't supported on cocos2d-html5");
return null;
},
@@ -376,13 +393,15 @@ cc.RenderTexture = cc.Node.extend(/** @lends cc.RenderTexture# */{
* Listen "come to background" message, and save render texture. It only has effect on Android.
* @param {cc.Class} obj
*/
- listenToBackground:function (obj) { },
+ listenToBackground: function (obj) {
+ },
/**
* Listen "come to foreground" message and restore the frame buffer object. It only has effect on Android.
* @param {cc.Class} obj
*/
- listenToForeground:function (obj) { }
+ listenToForeground: function (obj) {
+ }
});
var _p = cc.RenderTexture.prototype;
diff --git a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js
index c79b36f34d..c55f9e7ad1 100644
--- a/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js
+++ b/cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js
@@ -22,10 +22,10 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- cc.RenderTexture.CanvasRenderCmd = function(renderableObject){
- cc.Node.CanvasRenderCmd.call(this, renderableObject);
- this._needDraw = true;
+(function () {
+ cc.RenderTexture.CanvasRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
+ this._needDraw = false;
this._clearColorStr = "rgba(255,255,255,1)";
this._cacheCanvas = document.createElement('canvas');
@@ -35,20 +35,22 @@
var proto = cc.RenderTexture.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
proto.constructor = cc.RenderTexture.CanvasRenderCmd;
- proto.cleanup = function(){
+ proto.cleanup = function () {
this._cacheContext = null;
this._cacheCanvas = null;
};
- proto.clearStencil = function (stencilValue) { };
+ proto.clearStencil = function (stencilValue) {
+ };
- proto.setVirtualViewport = function(rtBegin, fullRect, fullViewport) {};
+ proto.setVirtualViewport = function (rtBegin, fullRect, fullViewport) {
+ };
- proto.updateClearColor = function(clearColor){
+ proto.updateClearColor = function (clearColor) {
this._clearColorStr = "rgba(" + (0 | clearColor.r) + "," + (0 | clearColor.g) + "," + (0 | clearColor.b) + "," + clearColor.a / 255 + ")";
};
- proto.initWithWidthAndHeight = function(width, height, format, depthStencilFormat){
+ proto.initWithWidthAndHeight = function (width, height, format, depthStencilFormat) {
var node = this._node;
var locCacheCanvas = this._cacheCanvas, locScaleFactor = cc.contentScaleFactor();
locCacheCanvas.width = 0 | (width * locScaleFactor);
@@ -67,9 +69,10 @@
return true;
};
- proto.begin = function(){};
+ proto.begin = function () {
+ };
- proto._beginWithClear = function(r, g, b, a, depthValue, stencilValue, flags){
+ proto._beginWithClear = function (r, g, b, a, depthValue, stencilValue, flags) {
r = r || 0;
g = g || 0;
b = b || 0;
@@ -77,13 +80,13 @@
var context = this._cacheContext.getContext();
var locCanvas = this._cacheCanvas;
- context.setTransform(1,0,0,1,0,0);
+ context.setTransform(1, 0, 0, 1, 0, 0);
this._cacheContext.setFillStyle("rgba(" + (0 | r) + "," + (0 | g) + "," + (0 | b) + "," + a / 255 + ")");
context.clearRect(0, 0, locCanvas.width, locCanvas.height);
context.fillRect(0, 0, locCanvas.width, locCanvas.height);
};
- proto.end = function(){
+ proto.end = function () {
var node = this._node;
var scale = cc.contentScaleFactor();
@@ -92,18 +95,11 @@
spriteRenderCmd._notifyRegionStatus && spriteRenderCmd._notifyRegionStatus(cc.Node.CanvasRenderCmd.RegionStatus.Dirty);
};
- proto.clearRect = function(x, y, width, height){
+ proto.clearRect = function (x, y, width, height) {
this._cacheContext.clearRect(x, y, width, -height);
};
- proto.clearDepth = function(depthValue){
+ proto.clearDepth = function (depthValue) {
cc.log("clearDepth isn't supported on Cocos2d-Html5");
};
-
- proto.visit = function(parentCmd){
- var node = this._node;
- this._syncStatus(parentCmd);
- node.sprite.visit(this);
- this._dirtyFlag = 0;
- };
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js
index dd25b8bf73..9abe91feaf 100644
--- a/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js
+++ b/cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js
@@ -22,9 +22,9 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- cc.RenderTexture.WebGLRenderCmd = function(renderableObject){
- cc.Node.WebGLRenderCmd.call(this, renderableObject);
+(function () {
+ cc.RenderTexture.WebGLRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
this._needDraw = true;
this._fBO = null;
@@ -40,7 +40,7 @@
var proto = cc.RenderTexture.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
proto.constructor = cc.RenderTexture.WebGLRenderCmd;
- proto.setVirtualViewport = function(rtBegin, fullRect, fullViewport) {
+ proto.setVirtualViewport = function (rtBegin, fullRect, fullViewport) {
this._rtTextureRect.x = rtBegin.x;
this._rtTextureRect.y = rtBegin.y;
@@ -99,15 +99,15 @@
var locChildren = node._children;
for (var i = 0; i < locChildren.length; i++) {
var getChild = locChildren[i];
- if (getChild !== node.sprite){
- getChild._renderCmd.visit(node.sprite._renderCmd); //TODO it's very Strange
+ if (getChild !== node.sprite) {
+ getChild.visit(node.sprite); //TODO it's very Strange
}
}
node.end();
}
};
- proto.clearStencil = function(stencilValue) {
+ proto.clearStencil = function (stencilValue) {
var gl = cc._renderContext;
// save old stencil value
var stencilClearValue = gl.getParameter(gl.STENCIL_CLEAR_VALUE);
@@ -119,7 +119,7 @@
gl.clearStencil(stencilClearValue);
};
- proto.cleanup = function(){
+ proto.cleanup = function () {
var node = this._node;
//node.sprite = null;
this._textureCopy = null;
@@ -130,16 +130,17 @@
gl.deleteRenderbuffer(this._depthRenderBuffer);
};
- proto.updateClearColor = function(clearColor){ };
+ proto.updateClearColor = function (clearColor) {
+ };
- proto.initWithWidthAndHeight = function(width, height, format, depthStencilFormat){
+ proto.initWithWidthAndHeight = function (width, height, format, depthStencilFormat) {
var node = this._node;
- if(format === cc.Texture2D.PIXEL_FORMAT_A8)
- cc.log( "cc.RenderTexture._initWithWidthAndHeightForWebGL() : only RGB and RGBA formats are valid for a render texture;");
+ if (format === cc.Texture2D.PIXEL_FORMAT_A8)
+ cc.log("cc.RenderTexture._initWithWidthAndHeightForWebGL() : only RGB and RGBA formats are valid for a render texture;");
var gl = cc._renderContext, locScaleFactor = cc.contentScaleFactor();
- this._fullRect = new cc.Rect(0,0, width, height);
- this._fullViewport = new cc.Rect(0,0, width, height);
+ this._fullRect = new cc.Rect(0, 0, width, height);
+ this._fullViewport = new cc.Rect(0, 0, width, height);
width = 0 | (width * locScaleFactor);
height = 0 | (height * locScaleFactor);
@@ -147,7 +148,7 @@
this._oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING);
// textures must be power of two squared
- var powW , powH;
+ var powW, powH;
if (cc.configuration.supportsNPOT()) {
powW = width;
@@ -194,16 +195,16 @@
this._depthRenderBuffer = gl.createRenderbuffer();
gl.bindRenderbuffer(gl.RENDERBUFFER, this._depthRenderBuffer);
gl.renderbufferStorage(gl.RENDERBUFFER, depthStencilFormat, powW, powH);
- if(depthStencilFormat === gl.DEPTH_STENCIL)
+ if (depthStencilFormat === gl.DEPTH_STENCIL)
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer);
- else if(depthStencilFormat === gl.STENCIL_INDEX || depthStencilFormat === gl.STENCIL_INDEX8)
+ else if (depthStencilFormat === gl.STENCIL_INDEX || depthStencilFormat === gl.STENCIL_INDEX8)
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.STENCIL_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer);
- else if(depthStencilFormat === gl.DEPTH_COMPONENT16)
+ else if (depthStencilFormat === gl.DEPTH_COMPONENT16)
gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, this._depthRenderBuffer);
}
// check if it worked (probably worth doing :) )
- if(gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE)
+ if (gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE)
cc.log("Could not attach texture to the framebuffer");
locTexture.setAliasTexParameters();
@@ -223,7 +224,7 @@
return true;
};
- proto.begin = function(){
+ proto.begin = function () {
var node = this._node;
// Save the current matrix
cc.kmGLMatrixMode(cc.KM_GL_PROJECTION);
@@ -274,7 +275,7 @@
}
};
- proto._beginWithClear = function(r, g, b, a, depthValue, stencilValue, flags){
+ proto._beginWithClear = function (r, g, b, a, depthValue, stencilValue, flags) {
r = r / 255;
g = g / 255;
b = b / 255;
@@ -315,7 +316,7 @@
gl.clearStencil(stencilClearValue);
};
- proto.end = function(){
+ proto.end = function () {
var node = this._node;
cc.renderer._renderingToBuffer(node.__instanceId);
@@ -343,11 +344,11 @@
director.setProjection(director.getProjection());*/
};
- proto.clearRect = function(x, y, width, height){
+ proto.clearRect = function (x, y, width, height) {
//TODO need to implement
};
- proto.clearDepth = function(depthValue){
+ proto.clearDepth = function (depthValue) {
var node = this._node;
node.begin();
@@ -362,30 +363,4 @@
gl.clearDepth(depthClearValue);
node.end();
};
-
- proto.visit = function(parentCmd){
- var node = this._node;
- if (!node._visible)
- return;
- cc.kmGLPushMatrix();
-
- //TODO using GridNode
- /* var locGrid = this.grid;
- if (locGrid && locGrid.isActive()) {
- locGrid.beforeDraw();
- this.transformAncestors();
- }*/
-
- this._syncStatus(parentCmd);
- //this.toRenderer();
- cc.renderer.pushRenderCommand(this);
- node.sprite.visit(this);
-
- //TODO GridNode
- /* if (locGrid && locGrid.isActive())
- locGrid.afterDraw(this);*/
-
- this._dirtyFlag = 0;
- cc.kmGLPopMatrix();
- };
})();
diff --git a/cocos2d/shaders/CCGLProgram.js b/cocos2d/shaders/CCGLProgram.js
index 829584886f..0cf9f4702d 100644
--- a/cocos2d/shaders/CCGLProgram.js
+++ b/cocos2d/shaders/CCGLProgram.js
@@ -39,30 +39,33 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
_uniforms: null,
_hashForUniforms: null,
_usesTime: false,
+ _projectionUpdated: -1,
// Uniform cache
- _updateUniformLocation: function (location) {
- if (!location)
+ _updateUniform: function (name) {
+ if (!name)
return false;
- var updated;
- var element = this._hashForUniforms[location];
-
- if (!element) {
- element = [
- arguments[1],
- arguments[2],
- arguments[3],
- arguments[4]
- ];
- this._hashForUniforms[location] = element;
+ var updated = false;
+ var element = this._hashForUniforms[name];
+ var args;
+ if (Array.isArray(arguments[1])) {
+ args = arguments[1];
+ } else {
+ args = new Array(arguments.length - 1);
+ for (var i = 1; i < arguments.length; i += 1) {
+ args[i - 1] = arguments[i];
+ }
+ }
+
+ if (!element || element.length !== args.length) {
+ this._hashForUniforms[name] = [].concat(args);
updated = true;
} else {
- updated = false;
- var count = arguments.length-1;
- for (var i = 0; i < count; ++i) {
- if (arguments[i+1] !== element[i]) {
- element[i] = arguments[i+1];
+ for (var i = 0; i < args.length; i += 1) {
+ // Array and Typed Array inner values could be changed, so we must update them
+ if (args[i] !== element[i] || typeof args[i] === 'object') {
+ element[i] = args[i];
updated = true;
}
}
@@ -106,18 +109,18 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
return ( status === true );
},
- /**
- * Create a cc.GLProgram object
- * @param {String} vShaderFileName
- * @param {String} fShaderFileName
- * @returns {cc.GLProgram}
- */
+ /**
+ * Create a cc.GLProgram object
+ * @param {String} vShaderFileName
+ * @param {String} fShaderFileName
+ * @returns {cc.GLProgram}
+ */
ctor: function (vShaderFileName, fShaderFileName, glContext) {
this._uniforms = {};
this._hashForUniforms = {};
this._glContext = glContext || cc._renderContext;
- vShaderFileName && fShaderFileName && this.init(vShaderFileName, fShaderFileName);
+ vShaderFileName && fShaderFileName && this.init(vShaderFileName, fShaderFileName);
},
/**
@@ -168,9 +171,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
if (this._fragShader)
locGL.attachShader(this._programObj, this._fragShader);
- for (var key in this._hashForUniforms) {
- delete this._hashForUniforms[key];
- }
+ if (Object.keys(this._hashForUniforms).length > 0) this._hashForUniforms = {};
cc.checkGLErrorDebug();
return true;
@@ -194,9 +195,9 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
*/
initWithVertexShaderFilename: function (vShaderFilename, fShaderFileName) {
var vertexSource = cc.loader.getRes(vShaderFilename);
- if(!vertexSource) throw new Error("Please load the resource firset : " + vShaderFilename);
+ if (!vertexSource) throw new Error("Please load the resource firset : " + vShaderFilename);
var fragmentSource = cc.loader.getRes(fShaderFileName);
- if(!fragmentSource) throw new Error("Please load the resource firset : " + fShaderFileName);
+ if (!fragmentSource) throw new Error("Please load the resource firset : " + fShaderFileName);
return this.initWithVertexShaderByteArray(vertexSource, fragmentSource);
},
@@ -224,7 +225,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* @return {Boolean}
*/
link: function () {
- if(!this._programObj) {
+ if (!this._programObj) {
cc.log("cc.GLProgram.link(): Cannot link invalid program");
return false;
}
@@ -267,18 +268,16 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* cc.UNIFORM_SAMPLER
*/
updateUniforms: function () {
- this._uniforms[cc.UNIFORM_PMATRIX_S] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_PMATRIX_S);
- this._uniforms[cc.UNIFORM_MVMATRIX_S] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_MVMATRIX_S);
- this._uniforms[cc.UNIFORM_MVPMATRIX_S] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_MVPMATRIX_S);
- this._uniforms[cc.UNIFORM_TIME_S] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_TIME_S);
- this._uniforms[cc.UNIFORM_SINTIME_S] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_SINTIME_S);
- this._uniforms[cc.UNIFORM_COSTIME_S] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_COSTIME_S);
-
+ this._addUniformLocation(cc.UNIFORM_PMATRIX_S);
+ this._addUniformLocation(cc.UNIFORM_MVMATRIX_S);
+ this._addUniformLocation(cc.UNIFORM_MVPMATRIX_S);
+ this._addUniformLocation(cc.UNIFORM_TIME_S);
+ this._addUniformLocation(cc.UNIFORM_SINTIME_S);
+ this._addUniformLocation(cc.UNIFORM_COSTIME_S);
+ this._addUniformLocation(cc.UNIFORM_RANDOM01_S);
+ this._addUniformLocation(cc.UNIFORM_SAMPLER_S);
this._usesTime = (this._uniforms[cc.UNIFORM_TIME_S] != null || this._uniforms[cc.UNIFORM_SINTIME_S] != null || this._uniforms[cc.UNIFORM_COSTIME_S] != null);
- this._uniforms[cc.UNIFORM_RANDOM01_S] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_RANDOM01_S);
- this._uniforms[cc.UNIFORM_SAMPLER_S] = this._glContext.getUniformLocation(this._programObj, cc.UNIFORM_SAMPLER_S);
-
this.use();
// Since sample most probably won't change, set it to 0 now.
this.setUniformLocationWith1i(this._uniforms[cc.UNIFORM_SAMPLER_S], 0);
@@ -286,7 +285,9 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
_addUniformLocation: function (name) {
var location = this._glContext.getUniformLocation(this._programObj, name);
+ if (location) location._name = name;
this._uniforms[name] = location;
+ return location;
},
/**
@@ -300,7 +301,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
if (!this._programObj)
throw new Error("cc.GLProgram.getUniformLocationForName(): Invalid operation. Cannot get uniform location when program is not initialized");
- var location = this._uniforms[name] || this._glContext.getUniformLocation(this._programObj, name);
+ var location = this._uniforms[name] || this._addUniformLocation(name);
return location;
},
@@ -326,16 +327,15 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* @param {Number} i1
*/
setUniformLocationWith1i: function (location, i1) {
- var gl = this._glContext;
- if (typeof location === 'string') {
- var updated = this._updateUniformLocation(location, i1);
- if (updated) {
- var locObj = this.getUniformLocationForName(location);
- gl.uniform1i(locObj, i1);
+ var isString = typeof location === 'string';
+ var name = isString ? location : location && location._name;
+ if (name) {
+ if (this._updateUniform(name, i1)) {
+ if (isString) location = this.getUniformLocationForName(name);
+ this._glContext.uniform1i(location, i1);
}
- }
- else {
- gl.uniform1i(location, i1);
+ } else {
+ this._glContext.uniform1i(location, i1);
}
},
@@ -346,16 +346,15 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* @param {Number} i2
*/
setUniformLocationWith2i: function (location, i1, i2) {
- var gl = this._glContext;
- if (typeof location === 'string') {
- var updated = this._updateUniformLocation(location, i1, i2);
- if (updated) {
- var locObj = this.getUniformLocationForName(location);
- gl.uniform2i(locObj, i1, i2);
+ var isString = typeof location === 'string';
+ var name = isString ? location : location && location._name;
+ if (name) {
+ if (this._updateUniform(name, i1, i2)) {
+ if (isString) location = this.getUniformLocationForName(name);
+ this._glContext.uniform2i(location, i1, i2);
}
- }
- else {
- gl.uniform2i(location, i1, i2);
+ } else {
+ this._glContext.uniform2i(location, i1, i2);
}
},
@@ -367,16 +366,15 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* @param {Number} i3
*/
setUniformLocationWith3i: function (location, i1, i2, i3) {
- var gl = this._glContext;
- if (typeof location === 'string') {
- var updated = this._updateUniformLocation(location, i1, i2, i3);
- if (updated) {
- var locObj = this.getUniformLocationForName(location);
- gl.uniform3i(locObj, i1, i2, i3);
+ var isString = typeof location === 'string';
+ var name = isString ? location : location && location._name;
+ if (name) {
+ if (this._updateUniform(name, i1, i2, i3)) {
+ if (isString) location = this.getUniformLocationForName(name);
+ this._glContext.uniform3i(location, i1, i2, i3);
}
- }
- else {
- gl.uniform3i(location, i1, i2, i3);
+ } else {
+ this._glContext.uniform3i(location, i1, i2, i3);
}
},
@@ -389,16 +387,15 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* @param {Number} i4
*/
setUniformLocationWith4i: function (location, i1, i2, i3, i4) {
- var gl = this._glContext;
- if (typeof location === 'string') {
- var updated = this._updateUniformLocation(location, i1, i2, i3, i4);
- if (updated) {
- var locObj = this.getUniformLocationForName(location);
- gl.uniform4i(locObj, i1, i2, i3, i4);
+ var isString = typeof location === 'string';
+ var name = isString ? location : location && location._name;
+ if (name) {
+ if (this._updateUniform(name, i1, i2, i3, i4)) {
+ if (isString) location = this.getUniformLocationForName(name);
+ this._glContext.uniform4i(location, i1, i2, i3, i4);
}
- }
- else {
- gl.uniform4i(location, i1, i2, i3, i4);
+ } else {
+ this._glContext.uniform4i(location, i1, i2, i3, i4);
}
},
@@ -409,8 +406,16 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* @param {Number} numberOfArrays
*/
setUniformLocationWith2iv: function (location, intArray) {
- var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location;
- this._glContext.uniform2iv(locObj, intArray);
+ var isString = typeof location === 'string';
+ var name = isString ? location : location && location._name;
+ if (name) {
+ if (this._updateUniform(name, intArray)) {
+ if (isString) location = this.getUniformLocationForName(name);
+ this._glContext.uniform2iv(location, intArray);
+ }
+ } else {
+ this._glContext.uniform2iv(location, intArray);
+ }
},
/**
@@ -418,9 +423,17 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* @param {WebGLUniformLocation|String} location
* @param {Int32Array} intArray
*/
- setUniformLocationWith3iv:function(location, intArray){
- var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location;
- this._glContext.uniform3iv(locObj, intArray);
+ setUniformLocationWith3iv: function (location, intArray) {
+ var isString = typeof location === 'string';
+ var name = isString ? location : location && location._name;
+ if (name) {
+ if (this._updateUniform(name, intArray)) {
+ if (isString) location = this.getUniformLocationForName(name);
+ this._glContext.uniform3iv(location, intArray);
+ }
+ } else {
+ this._glContext.uniform3iv(location, intArray);
+ }
},
/**
@@ -428,9 +441,17 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* @param {WebGLUniformLocation|String} location
* @param {Int32Array} intArray
*/
- setUniformLocationWith4iv:function(location, intArray){
- var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location;
- this._glContext.uniform4iv(locObj, intArray);
+ setUniformLocationWith4iv: function (location, intArray) {
+ var isString = typeof location === 'string';
+ var name = isString ? location : location && location._name;
+ if (name) {
+ if (this._updateUniform(name, intArray)) {
+ if (isString) location = this.getUniformLocationForName(name);
+ this._glContext.uniform4iv(location, intArray);
+ }
+ } else {
+ this._glContext.uniform4iv(location, intArray);
+ }
},
/**
@@ -448,16 +469,15 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* @param {Number} f1
*/
setUniformLocationWith1f: function (location, f1) {
- var gl = this._glContext;
- if (typeof location === 'string') {
- var updated = this._updateUniformLocation(location, f1);
- if (updated) {
- var locObj = this.getUniformLocationForName(location);
- gl.uniform1f(locObj, f1);
+ var isString = typeof location === 'string';
+ var name = isString ? location : location && location._name;
+ if (name) {
+ if (this._updateUniform(name, f1)) {
+ if (isString) location = this.getUniformLocationForName(name);
+ this._glContext.uniform1f(location, f1);
}
- }
- else {
- gl.uniform1f(location, f1);
+ } else {
+ this._glContext.uniform1f(location, f1);
}
},
@@ -468,16 +488,15 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* @param {Number} f2
*/
setUniformLocationWith2f: function (location, f1, f2) {
- var gl = this._glContext;
- if (typeof location === 'string') {
- var updated = this._updateUniformLocation(location, f1, f2);
- if (updated) {
- var locObj = this.getUniformLocationForName(location);
- gl.uniform2f(locObj, f1, f2);
+ var isString = typeof location === 'string';
+ var name = isString ? location : location && location._name;
+ if (name) {
+ if (this._updateUniform(name, f1, f2)) {
+ if (isString) location = this.getUniformLocationForName(name);
+ this._glContext.uniform2f(location, f1, f2);
}
- }
- else {
- gl.uniform2f(location, f1, f2);
+ } else {
+ this._glContext.uniform2f(location, f1, f2);
}
},
@@ -489,16 +508,15 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* @param {Number} f3
*/
setUniformLocationWith3f: function (location, f1, f2, f3) {
- var gl = this._glContext;
- if (typeof location === 'string') {
- var updated = this._updateUniformLocation(location, f1, f2, f3);
- if (updated) {
- var locObj = this.getUniformLocationForName(location);
- gl.uniform3f(locObj, f1, f2, f3);
+ var isString = typeof location === 'string';
+ var name = isString ? location : location && location._name;
+ if (name) {
+ if (this._updateUniform(name, f1, f2, f3)) {
+ if (isString) location = this.getUniformLocationForName(name);
+ this._glContext.uniform3f(location, f1, f2, f3);
}
- }
- else {
- gl.uniform3f(location, f1, f2, f3);
+ } else {
+ this._glContext.uniform3f(location, f1, f2, f3);
}
},
@@ -511,16 +529,16 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* @param {Number} f4
*/
setUniformLocationWith4f: function (location, f1, f2, f3, f4) {
- var gl = this._glContext;
- if (typeof location === 'string') {
- var updated = this._updateUniformLocation(location, f1, f2, f3, f4);
- if (updated) {
- var locObj = this.getUniformLocationForName(location);
- gl.uniform4f(locObj, f1, f2, f3, f4);
+ var isString = typeof location === 'string';
+ var name = isString ? location : location && location._name;
+ if (name) {
+ if (this._updateUniform(name, f1, f2, f3, f4)) {
+ if (isString) location = this.getUniformLocationForName(name);
+ this._glContext.uniform4f(location, f1, f2, f3, f4);
}
- }
- else {
- gl.uniform4f(location, f1, f2, f3, f4);
+ } else {
+ this._glContext.uniform4f(location, f1, f2, f3, f4);
+ cc.log('uniform4f', f1, f2, f3, f4);
}
},
@@ -530,8 +548,16 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* @param {Float32Array} floatArray
*/
setUniformLocationWith2fv: function (location, floatArray) {
- var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location;
- this._glContext.uniform2fv(locObj, floatArray);
+ var isString = typeof location === 'string';
+ var name = isString ? location : location && location._name;
+ if (name) {
+ if (this._updateUniform(name, floatArray)) {
+ if (isString) location = this.getUniformLocationForName(name);
+ this._glContext.uniform2fv(location, floatArray);
+ }
+ } else {
+ this._glContext.uniform2fv(location, floatArray);
+ }
},
/**
@@ -540,8 +566,16 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* @param {Float32Array} floatArray
*/
setUniformLocationWith3fv: function (location, floatArray) {
- var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location;
- this._glContext.uniform3fv(locObj, floatArray);
+ var isString = typeof location === 'string';
+ var name = isString ? location : location && location._name;
+ if (name) {
+ if (this._updateUniform(name, floatArray)) {
+ if (isString) location = this.getUniformLocationForName(name);
+ this._glContext.uniform3fv(location, floatArray);
+ }
+ } else {
+ this._glContext.uniform3fv(location, floatArray);
+ }
},
/**
@@ -550,17 +584,53 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* @param {Float32Array} floatArray
*/
setUniformLocationWith4fv: function (location, floatArray) {
- var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location;
- this._glContext.uniform4fv(locObj, floatArray);
+ var isString = typeof location === 'string';
+ var name = isString ? location : location && location._name;
+ if (name) {
+ if (this._updateUniform(name, floatArray)) {
+ if (isString) location = this.getUniformLocationForName(name);
+ this._glContext.uniform4fv(location, floatArray);
+ }
+ } else {
+ this._glContext.uniform4fv(location, floatArray);
+ cc.log('uniform4fv', floatArray);
+ }
+ },
+
+ /**
+ * calls glUniformMatrix2fv
+ * @param {WebGLUniformLocation|String} location
+ * @param {Float32Array} matrixArray
+ */
+ setUniformLocationWithMatrix2fv: function (location, matrixArray) {
+ var isString = typeof location === 'string';
+ var name = isString ? location : location && location._name;
+ if (name) {
+ if (this._updateUniform(name, matrixArray)) {
+ if (isString) location = this.getUniformLocationForName(name);
+ this._glContext.uniformMatrix2fv(location, false, matrixArray);
+ }
+ } else {
+ this._glContext.uniformMatrix2fv(location, false, matrixArray);
+ }
},
+
/**
* calls glUniformMatrix3fv
* @param {WebGLUniformLocation|String} location
* @param {Float32Array} matrixArray
*/
setUniformLocationWithMatrix3fv: function (location, matrixArray) {
- var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location;
- this._glContext.uniformMatrix3fv(locObj, false, matrixArray);
+ var isString = typeof location === 'string';
+ var name = isString ? location : location && location._name;
+ if (name) {
+ if (this._updateUniform(name, matrixArray)) {
+ if (isString) location = this.getUniformLocationForName(name);
+ this._glContext.uniformMatrix3fv(location, false, matrixArray);
+ }
+ } else {
+ this._glContext.uniformMatrix3fv(location, false, matrixArray);
+ }
},
/**
@@ -569,8 +639,16 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* @param {Float32Array} matrixArray
*/
setUniformLocationWithMatrix4fv: function (location, matrixArray) {
- var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location;
- this._glContext.uniformMatrix4fv(locObj, false, matrixArray);
+ var isString = typeof location === 'string';
+ var name = isString ? location : location && location._name;
+ if (name) {
+ if (this._updateUniform(name, matrixArray)) {
+ if (isString) location = this.getUniformLocationForName(name);
+ this._glContext.uniformMatrix4fv(location, false, matrixArray);
+ }
+ } else {
+ this._glContext.uniformMatrix4fv(location, false, matrixArray);
+ }
},
setUniformLocationF32: function () {
@@ -627,7 +705,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
},
_setUniformsForBuiltinsForRenderer: function (node) {
- if(!node || !node._renderCmd)
+ if (!node || !node._renderCmd)
return;
var matrixP = new cc.math.Matrix4();
@@ -663,29 +741,33 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
* will update the MVP matrix on the MVP uniform if it is different than the previous call for this same shader program.
*/
setUniformForModelViewProjectionMatrix: function () {
- this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_MVPMATRIX_S], false,
- cc.getMat4MultiplyValue(cc.projection_matrix_stack.top, cc.modelview_matrix_stack.top));
+ this.setUniformLocationWithMatrix4fv(this._uniforms[cc.UNIFORM_MVPMATRIX_S],
+ cc.getMat4MultiplyValue(cc.projection_matrix_stack.top, cc.modelview_matrix_stack.top));
},
setUniformForModelViewProjectionMatrixWithMat4: function (swapMat4) {
cc.kmMat4Multiply(swapMat4, cc.projection_matrix_stack.top, cc.modelview_matrix_stack.top);
- this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_MVPMATRIX_S], false, swapMat4.mat);
+ this.setUniformLocationWithMatrix4fv(this._uniforms[cc.UNIFORM_MVPMATRIX_S], swapMat4.mat);
},
setUniformForModelViewAndProjectionMatrixWithMat4: function () {
- this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_MVMATRIX_S], false, cc.modelview_matrix_stack.top.mat);
- this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX_S], false, cc.projection_matrix_stack.top.mat);
+ this.setUniformLocationWithMatrix4fv(this._uniforms[cc.UNIFORM_MVMATRIX_S], cc.modelview_matrix_stack.top.mat);
+ this.setUniformLocationWithMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX_S], cc.projection_matrix_stack.top.mat);
},
- _setUniformForMVPMatrixWithMat4: function(modelViewMatrix){
- if(!modelViewMatrix)
+ _setUniformForMVPMatrixWithMat4: function (modelViewMatrix) {
+ if (!modelViewMatrix)
throw new Error("modelView matrix is undefined.");
- this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_MVMATRIX_S], false, modelViewMatrix.mat);
- this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX_S], false, cc.projection_matrix_stack.top.mat);
+ this.setUniformLocationWithMatrix4fv(this._uniforms[cc.UNIFORM_MVMATRIX_S], modelViewMatrix.mat);
+ this.setUniformLocationWithMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX_S], cc.projection_matrix_stack.top.mat);
},
- _updateProjectionUniform: function(){
- this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX_S], false, cc.projection_matrix_stack.top.mat);
+ _updateProjectionUniform: function () {
+ var stack = cc.projection_matrix_stack;
+ if (stack.lastUpdated !== this._projectionUpdated) {
+ this._glContext.uniformMatrix4fv(this._uniforms[cc.UNIFORM_PMATRIX_S], false, stack.top.mat);
+ this._projectionUpdated = stack.lastUpdated;
+ }
},
/**
@@ -743,7 +825,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
reset: function () {
this._vertShader = null;
this._fragShader = null;
- this._uniforms.length = 0;
+ if (Object.keys(this._uniforms).length > 0) this._uniforms = {};
// it is already deallocated by android
//ccGLDeleteProgram(m_uProgram);
@@ -751,10 +833,7 @@ cc.GLProgram = cc.Class.extend(/** @lends cc.GLProgram# */{
this._programObj = null;
// Purge uniform hash
- for (var key in this._hashForUniforms) {
- this._hashForUniforms[key].length = 0;
- delete this._hashForUniforms[key];
- }
+ if (Object.keys(this._hashForUniforms).length > 0) this._hashForUniforms = {};
},
/**
@@ -789,9 +868,9 @@ cc.GLProgram.create = function (vShaderFileName, fShaderFileName) {
cc.GLProgram._highpSupported = null;
-cc.GLProgram._isHighpSupported = function(){
- if(cc.GLProgram._highpSupported == null){
- var ctx = cc._renderContext;
+cc.GLProgram._isHighpSupported = function () {
+ var ctx = cc._renderContext;
+ if (ctx.getShaderPrecisionFormat && cc.GLProgram._highpSupported == null) {
var highp = ctx.getShaderPrecisionFormat(ctx.FRAGMENT_SHADER, ctx.HIGH_FLOAT);
cc.GLProgram._highpSupported = highp.precision !== 0;
}
diff --git a/cocos2d/shaders/CCGLProgramState.js b/cocos2d/shaders/CCGLProgramState.js
new file mode 100644
index 0000000000..c5bc2fd428
--- /dev/null
+++ b/cocos2d/shaders/CCGLProgramState.js
@@ -0,0 +1,303 @@
+/****************************************************************************
+ Copyright (c) 2008-2010 Ricardo Quesada
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2013-2014 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+var types =
+ {
+ GL_FLOAT: 0,
+ GL_INT: 1,
+ GL_FLOAT_VEC2: 2,
+ GL_FLOAT_VEC3: 3,
+ GL_FLOAT_VEC4: 4,
+ GL_FLOAT_MAT4: 5,
+ GL_CALLBACK: 6,
+ GL_TEXTURE: 7
+ };
+
+
+
+cc.UniformValue = function (uniform, glprogram) {
+ this._uniform = uniform;
+ this._glprogram = glprogram;
+
+ this._value = null;
+ this._type = -1;
+};
+
+cc.UniformValue.prototype = {
+ setFloat: function setFloat(value) {
+ this._value = value;
+ this._type = types.GL_FLOAT;
+ },
+
+ setInt: function setInt(value) {
+ this._value = value;
+ this._type = types.GL_INT;
+ },
+
+ setVec2: function setVec2(v1, v2) {
+ this._value = [v1, v2];
+ this._type = types.GL_FLOAT_VEC2;
+ },
+
+ setVec2v: function setVec2v(value) {
+ this._value = value.slice(0);
+ this._type = types.GL_FLOAT_VEC2;
+ },
+
+ setVec3: function setVec3(v1, v2, v3) {
+ this._value = [v1, v2, v3];
+ this._type = types.GL_FLOAT_VEC3;
+ },
+
+ setVec3v: function setVec3v(value) {
+ this._value = value.slice(0);
+ this._type = types.GL_FLOAT_VEC3;
+ },
+
+ setVec4: function setVec4(v1, v2, v3, v4) {
+ this._value = [v1, v2, v3, v4];
+ this._type = types.GL_FLOAT_VEC4;
+ },
+
+ setVec4v: function setVec4v(value) {
+ this._value = value.slice(0);
+ this._type = types.GL_FLOAT_VEC4;
+ },
+
+ setMat4: function setMat4(value) {
+ this._value = value.slice(0);
+ this._type = types.GL_FLOAT_MAT4;
+ },
+
+ setCallback: function setCallback(fn) {
+ this._value = fn;
+ this._type = types.GL_CALLBACK;
+ },
+
+ setTexture: function setTexture(textureId, textureUnit) {
+ this._value = textureUnit;
+ this._textureId = textureId;
+ this._type = types.GL_TEXTURE;
+ },
+
+ apply: function apply() {
+ switch (this._type) {
+ case types.GL_INT:
+ this._glprogram.setUniformLocationWith1i(this._uniform._location, this._value);
+ break;
+ case types.GL_FLOAT:
+ this._glprogram.setUniformLocationWith1f(this._uniform._location, this._value);
+ break;
+ case types.GL_FLOAT_VEC2:
+ this._glprogram.setUniformLocationWith2fv(this._uniform._location, this._value);
+ break;
+ case types.GL_FLOAT_VEC3:
+ this._glprogram.setUniformLocationWith3fv(this._uniform._location, this._value);
+ break;
+ case types.GL_FLOAT_VEC4:
+ this._glprogram.setUniformLocationWith4fv(this._uniform._location, this._value);
+ break;
+ case types.GL_FLOAT_MAT4:
+ this._glprogram.setUniformLocationWithMatrix4fv(this._uniform._location, this._value);
+ break;
+ case types.GL_CALLBACK:
+ this._value(this._glprogram, this._uniform);
+ break;
+ case types.GL_TEXTURE:
+ this._glprogram.setUniformLocationWith1i(this._uniform._location, this._value);
+ cc.glBindTexture2DN(this._value, this._textureId);
+ break;
+ default:
+ ;
+ }
+ },
+};
+
+cc.GLProgramState = function (glprogram) {
+ this._glprogram = glprogram;
+ this._uniforms = {};
+ this._boundTextureUnits = {};
+ this._textureUnitIndex = 1; // Start at 1, as CC_Texture0 is bound to 0
+
+ var activeUniforms = glprogram._glContext.getProgramParameter(glprogram._programObj,
+ glprogram._glContext.ACTIVE_UNIFORMS);
+
+ for (var i = 0; i < activeUniforms; i += 1) {
+ var uniform = glprogram._glContext.getActiveUniform(glprogram._programObj, i);
+ if (uniform.name.indexOf("CC_") !== 0) {
+ uniform._location = glprogram._glContext.getUniformLocation(glprogram._programObj, uniform.name);
+ uniform._location._name = uniform.name;
+ var uniformValue = new cc.UniformValue(uniform, glprogram);
+ this._uniforms[uniform.name] = uniformValue;
+ }
+ }
+};
+
+cc.GLProgramState.prototype = {
+ apply: function apply(modelView) {
+ this._glprogram.use();
+ if (modelView) {
+ this._glprogram._setUniformForMVPMatrixWithMat4(modelView);
+ }
+
+ for (var name in this._uniforms) {
+ this._uniforms[name].apply();
+ };
+ },
+
+ setGLProgram: function setGLProgram(glprogram) {
+ this._glprogram = glprogram;
+ },
+
+ getGLProgram: function getGLProgram() {
+ return this._glprogram;
+ },
+
+ getUniformCount: function getUniformCount() {
+ return this._uniforms.length;
+ },
+
+ getUniformValue: function getUniformValue(uniform) {
+ return this._uniforms[uniform];
+ },
+
+ setUniformInt: function setUniformInt(uniform, value) {
+ var v = this.getUniformValue(uniform);
+ if (v) {
+ v.setInt(value);
+ } else {
+ cc.log("cocos2d: warning: Uniform not found: " + uniform);
+ }
+ },
+
+ setUniformFloat: function setUniformFloat(uniform, value) {
+ var v = this.getUniformValue(uniform);
+ if (v) {
+ v.setFloat(value);
+ } else {
+ cc.log("cocos2d: warning: Uniform not found: " + uniform);
+ }
+ },
+
+ setUniformVec2: function setUniformVec2(uniform, v1, v2) {
+ var v = this.getUniformValue(uniform);
+ if (v) {
+ v.setVec2(v1, v2);
+ } else {
+ cc.log("cocos2d: warning: Uniform not found: " + uniform);
+ }
+ },
+
+ setUniformVec2v: function setUniformVec2v(uniform, value) {
+ var v = this.getUniformValue(uniform);
+ if (v) {
+ v.setVec2v(value);
+ } else {
+ cc.log("cocos2d: warning: Uniform not found: " + uniform);
+ }
+ },
+
+ setUniformVec3: function setUniformVec3(uniform, v1, v2, v3) {
+ var v = this.getUniformValue(uniform);
+ if (v) {
+ v.setVec3(v1, v2, v3);
+ } else {
+ cc.log("cocos2d: warning: Uniform not found: " + uniform);
+ }
+ },
+
+ setUniformVec3v: function setUniformVec3v(uniform, value) {
+ var v = this.getUniformValue(uniform);
+ if (v) {
+ v.setVec3v(value);
+ } else {
+ cc.log("cocos2d: warning: Uniform not found: " + uniform);
+ }
+ },
+
+ setUniformVec4: function setUniformVec4(uniform, v1, v2, v3, v4) {
+ var v = this.getUniformValue(uniform);
+ if (v) {
+ v.setVec4(v1, v2, v3, v4);
+ } else {
+ cc.log("cocos2d: warning: Uniform not found: " + uniform);
+ }
+ },
+
+ setUniformVec4v: function setUniformVec4v(uniform, value) {
+ var v = this.getUniformValue(uniform);
+ if (v) {
+ v.setVec4v(value);
+ } else {
+ cc.log("cocos2d: warning: Uniform not found: " + uniform);
+ }
+ },
+
+
+ setUniformMat4: function setUniformMat4(uniform, value) {
+ var v = this.getUniformValue(uniform);
+ if (v) {
+ v.setMat4(value);
+ } else {
+ cc.log("cocos2d: warning: Uniform not found: " + uniform);
+ }
+
+ },
+
+ setUniformCallback: function setUniformCallback(uniform, callback) {
+ var v = this.getUniformValue(uniform);
+ if (v) {
+ v.setCallback(callback);
+ } else {
+ cc.log("cocos2d: warning: Uniform not found: " + uniform);
+ }
+
+ },
+
+ setUniformTexture: function setUniformTexture(uniform, texture) {
+ var uniformValue = this.getUniformValue(uniform);
+ if (uniformValue) {
+ var textureUnit = this._boundTextureUnits[uniform];
+ if (textureUnit) {
+ uniformValue.setTexture(texture, textureUnit);
+ } else {
+ uniformValue.setTexture(texture, this._textureUnitIndex);
+ this._boundTextureUnits[uniform] = this._textureUnitIndex++;
+ }
+ }
+ }
+};
+
+cc.GLProgramState._cache = {};
+cc.GLProgramState.getOrCreateWithGLProgram = function (glprogram) {
+ var programState = cc.GLProgramState._cache[glprogram.__instanceId];
+ if (!programState) {
+ programState = new cc.GLProgramState(glprogram);
+ cc.GLProgramState._cache[glprogram.__instanceId] = programState;
+ }
+
+ return programState;
+};
diff --git a/cocos2d/shaders/CCGLStateCache.js b/cocos2d/shaders/CCGLStateCache.js
index 127bc2d711..626c587a9c 100644
--- a/cocos2d/shaders/CCGLStateCache.js
+++ b/cocos2d/shaders/CCGLStateCache.js
@@ -36,64 +36,6 @@ if (cc.ENABLE_GL_STATE_CACHE) {
cc._GLServerState = 0;
if(cc.TEXTURE_ATLAS_USE_VAO)
cc._uVAO = 0;
-
- var _currBuffers = {};
-
- WebGLRenderingContext.prototype.glBindBuffer = WebGLRenderingContext.prototype.bindBuffer;
- WebGLRenderingContext.prototype.bindBuffer = function (target, buffer) {
- if (_currBuffers[target] !== buffer) {
- this.glBindBuffer(target, buffer);
- _currBuffers[target] = buffer;
- return false;
- }
- else {
- return true;
- }
- };
-
- WebGLRenderingContext.prototype.glEnableVertexAttribArray = WebGLRenderingContext.prototype.enableVertexAttribArray;
- WebGLRenderingContext.prototype.enableVertexAttribArray = function (index) {
- if (index === cc.VERTEX_ATTRIB_FLAG_POSITION) {
- if (!this._vertexAttribPosition) {
- this.glEnableVertexAttribArray(index);
- this._vertexAttribPosition = true;
- }
- }
- else if (index === cc.VERTEX_ATTRIB_FLAG_COLOR) {
- if (!this._vertexAttribColor) {
- this.glEnableVertexAttribArray(index);
- this._vertexAttribColor = true;
- }
- }
- else if (index === cc.VERTEX_ATTRIB_FLAG_TEX_COORDS) {
- if (!this._vertexAttribTexCoords) {
- this.glEnableVertexAttribArray(index);
- this._vertexAttribTexCoords = true;
- }
- }
- else {
- this.glEnableVertexAttribArray(index);
- }
- };
-
- WebGLRenderingContext.prototype.glDisableVertexAttribArray = WebGLRenderingContext.prototype.disableVertexAttribArray;
- WebGLRenderingContext.prototype.disableVertexAttribArray = function (index) {
- if (index === cc.VERTEX_ATTRIB_FLAG_COLOR) {
- if (this._vertexAttribColor) {
- this.glDisableVertexAttribArray(index);
- this._vertexAttribColor = false;
- }
- }
- else if (index === cc.VERTEX_ATTRIB_FLAG_TEX_COORDS) {
- if (this._vertexAttribTexCoords) {
- this.glDisableVertexAttribArray(index);
- this._vertexAttribTexCoords = false;
- }
- }
- else if (index !== 0) {
- this.glDisableVertexAttribArray(index);
- }
- };
}
// GL State Cache functions
diff --git a/cocos2d/shaders/CCShaderCache.js b/cocos2d/shaders/CCShaderCache.js
index be23a9cc93..462f208d21 100644
--- a/cocos2d/shaders/CCShaderCache.js
+++ b/cocos2d/shaders/CCShaderCache.js
@@ -102,7 +102,28 @@ cc.shaderCache = /** @lends cc.shaderCache# */{
* @constant
* @type {Number}
*/
- TYPE_MAX: 10,
+ TYPE_SPRITE_POSITION_TEXTURECOLOR_GRAY: 11,
+ /**
+ * @public
+ * @constant
+ * @type {Number}
+ */
+ TYPE_MAX: 11,
+
+ _keyMap: [
+ cc.SHADER_POSITION_TEXTURECOLOR,
+ cc.SHADER_POSITION_TEXTURECOLORALPHATEST,
+ cc.SHADER_POSITION_COLOR,
+ cc.SHADER_POSITION_TEXTURE,
+ cc.SHADER_POSITION_TEXTURE_UCOLOR,
+ cc.SHADER_POSITION_TEXTUREA8COLOR,
+ cc.SHADER_POSITION_UCOLOR,
+ cc.SHADER_POSITION_LENGTHTEXTURECOLOR,
+ cc.SHADER_SPRITE_POSITION_TEXTURECOLOR,
+ cc.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST,
+ cc.SHADER_SPRITE_POSITION_COLOR,
+ cc.SHADER_SPRITE_POSITION_TEXTURECOLOR_GRAY
+ ],
_programs: {},
@@ -113,61 +134,67 @@ cc.shaderCache = /** @lends cc.shaderCache# */{
_loadDefaultShader: function (program, type) {
switch (type) {
- case this.TYPE_POSITION_TEXTURECOLOR:
+ case cc.SHADER_POSITION_TEXTURECOLOR:
program.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_COLOR_VERT, cc.SHADER_POSITION_TEXTURE_COLOR_FRAG);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
break;
- case this.TYPE_SPRITE_POSITION_TEXTURECOLOR:
+ case cc.SHADER_SPRITE_POSITION_TEXTURECOLOR:
program.initWithVertexShaderByteArray(cc.SHADER_SPRITE_POSITION_TEXTURE_COLOR_VERT, cc.SHADER_POSITION_TEXTURE_COLOR_FRAG);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
- break;
- case this.TYPE_POSITION_TEXTURECOLOR_ALPHATEST:
+ break;
+ case cc.SHADER_SPRITE_POSITION_TEXTURECOLOR_GRAY:
+ program.initWithVertexShaderByteArray(cc.SHADER_SPRITE_POSITION_TEXTURE_COLOR_VERT, cc.SHADER_SPRITE_POSITION_TEXTURE_COLOR_GRAY_FRAG);
+ program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
+ program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
+ program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
+ break;
+ case cc.SHADER_POSITION_TEXTURECOLORALPHATEST:
program.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_COLOR_VERT, cc.SHADER_POSITION_TEXTURE_COLOR_ALPHATEST_FRAG);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
break;
- case this.TYPE_SPRITE_POSITION_TEXTURECOLOR_ALPHATEST:
+ case cc.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST:
program.initWithVertexShaderByteArray(cc.SHADER_SPRITE_POSITION_TEXTURE_COLOR_VERT, cc.SHADER_POSITION_TEXTURE_COLOR_ALPHATEST_FRAG);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
break;
- case this.TYPE_POSITION_COLOR:
+ case cc.SHADER_POSITION_COLOR:
program.initWithVertexShaderByteArray(cc.SHADER_POSITION_COLOR_VERT, cc.SHADER_POSITION_COLOR_FRAG);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
break;
- case this.TYPE_SPRITE_POSITION_COLOR:
+ case cc.SHADER_SPRITE_POSITION_COLOR:
program.initWithVertexShaderByteArray(cc.SHADER_SPRITE_POSITION_COLOR_VERT, cc.SHADER_POSITION_COLOR_FRAG);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
break;
- case this.TYPE_POSITION_TEXTURE:
+ case cc.SHADER_POSITION_TEXTURE:
program.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_VERT, cc.SHADER_POSITION_TEXTURE_FRAG);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
break;
- case this.TYPE_POSITION_TEXTURE_UCOLOR:
+ case cc.SHADER_POSITION_TEXTURE_UCOLOR:
program.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_UCOLOR_VERT, cc.SHADER_POSITION_TEXTURE_UCOLOR_FRAG);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
break;
- case this.TYPE_POSITION_TEXTURE_A8COLOR:
+ case cc.SHADER_POSITION_TEXTUREA8COLOR:
program.initWithVertexShaderByteArray(cc.SHADER_POSITION_TEXTURE_A8COLOR_VERT, cc.SHADER_POSITION_TEXTURE_A8COLOR_FRAG);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_COLOR, cc.VERTEX_ATTRIB_COLOR);
program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
break;
- case this.TYPE_POSITION_UCOLOR:
+ case cc.SHADER_POSITION_UCOLOR:
program.initWithVertexShaderByteArray(cc.SHADER_POSITION_UCOLOR_VERT, cc.SHADER_POSITION_UCOLOR_FRAG);
program.addAttribute("aVertex", cc.VERTEX_ATTRIB_POSITION);
break;
- case this.TYPE_POSITION_LENGTH_TEXTURECOLOR:
+ case cc.SHADER_POSITION_LENGTHTEXTURECOLOR:
program.initWithVertexShaderByteArray(cc.SHADER_POSITION_COLOR_LENGTH_TEXTURE_VERT, cc.SHADER_POSITION_COLOR_LENGTH_TEXTURE_FRAG);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
@@ -188,85 +215,10 @@ cc.shaderCache = /** @lends cc.shaderCache# */{
* loads the default shaders
*/
loadDefaultShaders: function () {
- // Position Texture Color shader
- var program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURECOLOR);
- this._programs[cc.SHADER_POSITION_TEXTURECOLOR] = program;
- this._programs["ShaderPositionTextureColor"] = program;
-
- // Position Texture Color shader with position precalculated
- program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_SPRITE_POSITION_TEXTURECOLOR);
- this._programs[cc.SHADER_SPRITE_POSITION_TEXTURECOLOR] = program;
- this._programs["ShaderSpritePositionTextureColor"] = program;
-
- // Position Texture Color alpha test
- program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURECOLOR_ALPHATEST);
- this._programs[cc.SHADER_POSITION_TEXTURECOLORALPHATEST] = program;
- this._programs["ShaderPositionTextureColorAlphaTest"] = program;
-
- // Position Texture Color alpha with position precalculated
- program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_SPRITE_POSITION_TEXTURECOLOR_ALPHATEST);
- this._programs[cc.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST] = program;
- this._programs["ShaderSpritePositionTextureColorAlphaTest"] = program;
-
- //
- // Position, Color shader
- //
- program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_POSITION_COLOR);
- this._programs[cc.SHADER_POSITION_COLOR] = program;
- this._programs["ShaderPositionColor"] = program;
-
- //
- // Position, Color shader with position precalculated
- //
- program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_SPRITE_POSITION_COLOR);
- this._programs[cc.SHADER_SPRITE_POSITION_COLOR] = program;
- this._programs["ShaderSpritePositionColor"] = program;
-
- //
- // Position Texture shader
- //
- program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE);
- this._programs[cc.SHADER_POSITION_TEXTURE] = program;
- this._programs["ShaderPositionTexture"] = program;
-
- //
- // Position, Texture attribs, 1 Color as uniform shader
- //
- program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE_UCOLOR);
- this._programs[cc.SHADER_POSITION_TEXTURE_UCOLOR] = program;
- this._programs["ShaderPositionTextureUColor"] = program;
-
- //
- // Position Texture A8 Color shader
- //
- program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE_A8COLOR);
- this._programs[cc.SHADER_POSITION_TEXTUREA8COLOR] = program;
- this._programs["ShaderPositionTextureA8Color"] = program;
-
- //
- // Position and 1 color passed as a uniform (to similate glColor4ub )
- //
- program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_POSITION_UCOLOR);
- this._programs[cc.SHADER_POSITION_UCOLOR] = program;
- this._programs["ShaderPositionUColor"] = program;
-
- //
- // Position, Legth(TexCoords, Color (used by Draw Node basically )
- //
- program = new cc.GLProgram();
- this._loadDefaultShader(program, this.TYPE_POSITION_LENGTH_TEXTURECOLOR);
- this._programs[cc.SHADER_POSITION_LENGTHTEXTURECOLOR] = program;
- this._programs["ShaderPositionLengthTextureColor"] = program;
+ for (var i = 0; i < this.TYPE_MAX; ++i) {
+ var key = this._keyMap[i];
+ this.programForKey(key);
+ }
},
/**
@@ -278,57 +230,62 @@ cc.shaderCache = /** @lends cc.shaderCache# */{
// Position Texture Color shader
var program = this.programForKey(cc.SHADER_POSITION_TEXTURECOLOR);
program.reset();
- this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURECOLOR);
+ this._loadDefaultShader(program, cc.SHADER_POSITION_TEXTURECOLOR);
// Sprite Position Texture Color shader
program = this.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLOR);
program.reset();
- this._loadDefaultShader(program, this.TYPE_SPRITE_POSITION_TEXTURECOLOR);
+ this._loadDefaultShader(program, cc.SHADER_SPRITE_POSITION_TEXTURECOLOR);
// Position Texture Color alpha test
program = this.programForKey(cc.SHADER_POSITION_TEXTURECOLORALPHATEST);
program.reset();
- this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURECOLOR_ALPHATEST);
+ this._loadDefaultShader(program, cc.SHADER_POSITION_TEXTURECOLORALPHATEST);
// Sprite Position Texture Color alpha shader
program = this.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST);
program.reset();
- this._loadDefaultShader(program, this.TYPE_SPRITE_POSITION_TEXTURECOLOR_ALPHATEST);
+ this._loadDefaultShader(program, cc.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST);
//
// Position, Color shader
//
program = this.programForKey(cc.SHADER_POSITION_COLOR);
program.reset();
- this._loadDefaultShader(program, this.TYPE_POSITION_COLOR);
+ this._loadDefaultShader(program, cc.SHADER_POSITION_COLOR);
//
// Position Texture shader
//
program = this.programForKey(cc.SHADER_POSITION_TEXTURE);
program.reset();
- this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE);
+ this._loadDefaultShader(program, cc.SHADER_POSITION_TEXTURE);
+
+ //Position Texture Gray shader
+ program = this.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURE_COLOR_GRAY_FRAG);
+ program.reset();
+ this._loadDefaultShader(program, cc.SHADER_SPRITE_POSITION_TEXTURE_COLOR_GRAY_FRAG);
//
// Position, Texture attribs, 1 Color as uniform shader
//
program = this.programForKey(cc.SHADER_POSITION_TEXTURE_UCOLOR);
program.reset();
- this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE_UCOLOR);
+ this._loadDefaultShader(program, cc.SHADER_POSITION_TEXTURE_UCOLOR);
//
// Position Texture A8 Color shader
//
program = this.programForKey(cc.SHADER_POSITION_TEXTUREA8COLOR);
program.reset();
- this._loadDefaultShader(program, this.TYPE_POSITION_TEXTURE_A8COLOR);
+ this._loadDefaultShader(program, cc.SHADER_POSITION_TEXTUREA8COLOR);
//
// Position and 1 color passed as a uniform (to similate glColor4ub )
//
program = this.programForKey(cc.SHADER_POSITION_UCOLOR);
program.reset();
- this._loadDefaultShader(program, this.TYPE_POSITION_UCOLOR);
+ this._loadDefaultShader(program, cc.SHADER_POSITION_UCOLOR);
},
/**
@@ -336,6 +293,12 @@ cc.shaderCache = /** @lends cc.shaderCache# */{
* @param {String} key
*/
programForKey: function (key) {
+ if (!this._programs[key]) {
+ var program = new cc.GLProgram();
+ this._loadDefaultShader(program, key);
+ this._programs[key] = program;
+ }
+
return this._programs[key];
},
@@ -345,7 +308,7 @@ cc.shaderCache = /** @lends cc.shaderCache# */{
* @return {cc.GLProgram}
*/
getProgram: function (shaderName) {
- return this._programs[shaderName];
+ return this.programForKey(shaderName);
},
/**
@@ -356,4 +319,4 @@ cc.shaderCache = /** @lends cc.shaderCache# */{
addProgram: function (program, key) {
this._programs[key] = program;
}
-};
\ No newline at end of file
+};
diff --git a/cocos2d/shaders/CCShaders.js b/cocos2d/shaders/CCShaders.js
index c092340059..eb656c55ba 100644
--- a/cocos2d/shaders/CCShaders.js
+++ b/cocos2d/shaders/CCShaders.js
@@ -262,8 +262,18 @@ cc.SHADER_SPRITE_POSITION_TEXTURE_COLOR_VERT =
+ " gl_Position = CC_PMatrix * a_position; \n"
+ " v_fragmentColor = a_color; \n"
+ " v_texCoord = a_texCoord; \n"
- + "}";
+ + "}";
+cc.SHADER_SPRITE_POSITION_TEXTURE_COLOR_GRAY_FRAG =
+ "precision lowp float;\n"
+ + "varying vec4 v_fragmentColor; \n"
+ + "varying vec2 v_texCoord; \n"
+ + "void main() \n"
+ + "{ \n"
+ + " vec4 c = texture2D(CC_Texture0, v_texCoord); \n"
+ + " gl_FragColor.xyz = vec3(0.2126*c.r + 0.7152*c.g + 0.0722*c.b); \n"
+ +" gl_FragColor.w = c.w ; \n"
+ + "}";
//-----------------------Shader_PositionTextureColorAlphaTest_frag Shader Source----------------------------
/**
* @constant
@@ -301,4 +311,4 @@ cc.SHADEREX_SWITCHMASK_FRAG =
+ " vec4 maskColor = texture2D(u_mask, v_texCoord); \n"
+ " vec4 finalColor = vec4(texColor.r, texColor.g, texColor.b, maskColor.a * texColor.a); \n"
+ " gl_FragColor = v_fragmentColor * finalColor; \n"
- + "}";
\ No newline at end of file
+ + "}";
diff --git a/cocos2d/shape-nodes/CCDrawNode.js b/cocos2d/shape-nodes/CCDrawNode.js
index 48cdf4cccc..48caafa13f 100644
--- a/cocos2d/shape-nodes/CCDrawNode.js
+++ b/cocos2d/shape-nodes/CCDrawNode.js
@@ -25,61 +25,6 @@
THE SOFTWARE.
****************************************************************************/
-/**
- * Code copied & pasted from SpacePatrol game https://github.com/slembcke/SpacePatrol
- *
- * Renamed and added some changes for cocos2d
- *
- */
-cc.v2fzero = function () {
- return {x: 0, y: 0};
-};
-
-cc.v2f = function (x, y) {
- return {x: x, y: y};
-};
-
-cc.v2fadd = function (v0, v1) {
- return cc.v2f(v0.x + v1.x, v0.y + v1.y);
-};
-
-cc.v2fsub = function (v0, v1) {
- return cc.v2f(v0.x - v1.x, v0.y - v1.y);
-};
-
-cc.v2fmult = function (v, s) {
- return cc.v2f(v.x * s, v.y * s);
-};
-
-cc.v2fperp = function (p0) {
- return cc.v2f(-p0.y, p0.x);
-};
-
-cc.v2fneg = function (p0) {
- return cc.v2f(-p0.x, -p0.y);
-};
-
-cc.v2fdot = function (p0, p1) {
- return p0.x * p1.x + p0.y * p1.y;
-};
-
-cc.v2fforangle = function (_a_) {
- return cc.v2f(Math.cos(_a_), Math.sin(_a_));
-};
-
-cc.v2fnormalize = function (p) {
- var r = cc.pNormalize(cc.p(p.x, p.y));
- return cc.v2f(r.x, r.y);
-};
-
-cc.__v2f = function (v) {
- return cc.v2f(v.x, v.y);
-};
-
-cc.__t = function (v) {
- return {u: v.x, v: v.y};
-};
-
/**
*
The cc.BinaryStreamReader's constructor.
@@ -302,7 +302,7 @@ cc.BinaryStreamReader = cc.Class.extend({
* Override it to extend its behavior, remember to call "this._super()" in the extended "ctor" function.
* @param binaryData
*/
- ctor:function (binaryData) {
+ ctor: function (binaryData) {
this._binaryData = binaryData;
},
@@ -310,7 +310,7 @@ cc.BinaryStreamReader = cc.Class.extend({
* Set the binaryData.
* @param binaryData
*/
- setBinaryData:function (binaryData) {
+ setBinaryData: function (binaryData) {
this._binaryData = binaryData;
this._offset = 0;
},
@@ -319,16 +319,16 @@ cc.BinaryStreamReader = cc.Class.extend({
* Gets the binaryData.
* @returns {Object}
*/
- getBinaryData:function () {
+ getBinaryData: function () {
return this._binaryData;
},
- _checkSize:function (neededBits) {
+ _checkSize: function (neededBits) {
if (!(this._offset + Math.ceil(neededBits / 8) < this._data.length))
throw new Error("Index out of bound");
},
- _decodeFloat:function (precisionBits, exponentBits) {
+ _decodeFloat: function (precisionBits, exponentBits) {
var length = precisionBits + exponentBits + 1;
var size = length >> 3;
this._checkSize(length);
@@ -357,11 +357,11 @@ cc.BinaryStreamReader = cc.Class.extend({
: Math.pow(2, exponent - bias) * (1 + significand) : 0);
},
- _readByte:function (i, size) {
+ _readByte: function (i, size) {
return this._data[this._offset + size - i - 1];
},
- _decodeInt:function (bits, signed) {
+ _decodeInt: function (bits, signed) {
var x = this._readBits(0, bits, bits / 8), max = Math.pow(2, bits);
var result = signed && x >= max / 2 ? x - max : x;
@@ -369,12 +369,13 @@ cc.BinaryStreamReader = cc.Class.extend({
return result;
},
- _shl:function (a, b) {
- for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) === 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1){};
+ _shl: function (a, b) {
+ for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) === 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1) {
+ }
return a;
},
- _readBits:function (start, length, size) {
+ _readBits: function (start, length, size) {
var offsetLeft = (start + length) % 8;
var offsetRight = start % 8;
var curByte = size - (start >> 3) - 1;
@@ -392,33 +393,33 @@ cc.BinaryStreamReader = cc.Class.extend({
return sum;
},
- readInteger:function () {
+ readInteger: function () {
return this._decodeInt(32, true);
},
- readUnsignedInteger:function () {
+ readUnsignedInteger: function () {
return this._decodeInt(32, false);
},
- readSingle:function () {
+ readSingle: function () {
return this._decodeFloat(23, 8);
},
- readShort:function () {
+ readShort: function () {
return this._decodeInt(16, true);
},
- readUnsignedShort:function () {
+ readUnsignedShort: function () {
return this._decodeInt(16, false);
},
- readByte:function () {
+ readByte: function () {
var readByte = this._data[this._offset];
this._offset += 1;
return readByte;
},
- readData:function (start, end) {
+ readData: function (start, end) {
if (this._binaryData instanceof Array) {
return this._binaryData.slice(start, end);
} else {
@@ -427,11 +428,11 @@ cc.BinaryStreamReader = cc.Class.extend({
}
},
- setOffset:function (offset) {
+ setOffset: function (offset) {
this._offset = offset;
},
- getOffset:function () {
+ getOffset: function () {
return this._offset;
}
});
diff --git a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js
index d28a3cde6b..f354284de2 100644
--- a/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js
+++ b/cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js
@@ -22,9 +22,9 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- cc.TMXLayer.CanvasRenderCmd = function(renderable){
- cc.Node.CanvasRenderCmd.call(this, renderable);
+(function () {
+ cc.TMXLayer.CanvasRenderCmd = function (renderable) {
+ this._rootCtor(renderable);
this._needDraw = true;
};
@@ -132,10 +132,10 @@
if (maxRow > rows) maxRow = rows;
}
- var i, row, col, colOffset = startRow * cols, z,
+ var i, row, col, colOffset = startRow * cols, z,
gid, grid, tex, cmd,
mask = cc.TMX_TILE_FLIPPED_MASK,
- top, left, bottom, right, dw = tilew, dh = tileh ,
+ top, left, bottom, right, dw = tilew, dh = tileh,
w = tilew * a, h = tileh * d, gt, gl, gb, gr,
flippedX = false, flippedY = false;
@@ -198,18 +198,18 @@
top = bottom - tileh;
// TMX_ORIENTATION_ISO trim
if (!hasRotation && layerOrientation === cc.TMX_ORIENTATION_ISO) {
- gb = -mapy + bottom*d;
- if (gb < -winh-h) {
- col += Math.floor((-winh - gb)*2/h) - 1;
+ gb = -mapy + bottom * d;
+ if (gb < -winh - h) {
+ col += Math.floor((-winh - gb) * 2 / h) - 1;
continue;
}
- gr = mapx + right*a;
+ gr = mapx + right * a;
if (gr < -w) {
- col += Math.floor((-gr)*2/w) - 1;
+ col += Math.floor((-gr) * 2 / w) - 1;
continue;
}
- gl = mapx + left*a;
- gt = -mapy + top*d;
+ gl = mapx + left * a;
+ gt = -mapy + top * d;
if (gl > winw || gt > 0) {
col = maxCol;
continue;
@@ -256,4 +256,4 @@
}
}
};
-})();
\ No newline at end of file
+})();
diff --git a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js
index 36103af82b..d0e90bebc9 100644
--- a/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js
+++ b/cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js
@@ -22,15 +22,15 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- cc.TMXLayer.WebGLRenderCmd = function(renderableObject){
- cc.Node.WebGLRenderCmd.call(this, renderableObject);
+(function () {
+ cc.TMXLayer.WebGLRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
this._needDraw = true;
this._vertices = [
- {x:0, y:0},
- {x:0, y:0},
- {x:0, y:0},
- {x:0, y:0}
+ {x: 0, y: 0},
+ {x: 0, y: 0},
+ {x: 0, y: 0},
+ {x: 0, y: 0}
];
this._color = new Uint32Array(1);
this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST);
@@ -86,7 +86,7 @@
cg *= ca;
cb *= ca;
}
- this._color[0] = ((opacity<<24) | (cb<<16) | (cg<<8) | cr);
+ this._color[0] = ((opacity << 24) | (cb << 16) | (cg << 8) | cr);
// Culling
var startCol = 0, startRow = 0,
@@ -107,7 +107,7 @@
offset = vertexDataOffset,
colOffset = startRow * cols, z, gid, grid,
mask = cc.TMX_TILE_FLIPPED_MASK,
- i, top, left, bottom, right,
+ i, top, left, bottom, right,
w = tilew * a, h = tileh * d, gt, gl, gb, gr,
wa = a, wb = b, wc = c, wd = d, wtx = tx, wty = ty, // world
flagged = false, flippedX = false, flippedY = false,
@@ -156,18 +156,18 @@
top = bottom + tileh;
// TMX_ORIENTATION_ISO trim
if (!hasRotation && layerOrientation === cc.TMX_ORIENTATION_ISO) {
- gb = mapy + bottom*d;
- if (gb > winh+h) {
- col += Math.floor((gb-winh)*2/h) - 1;
+ gb = mapy + bottom * d;
+ if (gb > winh + h) {
+ col += Math.floor((gb - winh) * 2 / h) - 1;
continue;
}
- gr = mapx + right*a;
+ gr = mapx + right * a;
if (gr < -w) {
- col += Math.floor((-gr)*2/w) - 1;
+ col += Math.floor((-gr) * 2 / w) - 1;
continue;
}
- gl = mapx + left*a;
- gt = mapy + top*d;
+ gl = mapx + left * a;
+ gt = mapy + top * d;
if (gl > winw || gt < 0) {
col = maxCol;
continue;
@@ -221,21 +221,21 @@
ui32buffer[offset + 3] = this._color[0];
switch (i) {
case 0: // tl
- f32buffer[offset + 4] = flippedX ? grid.r : grid.l;
- f32buffer[offset + 5] = flippedY ? grid.b : grid.t;
- break;
+ f32buffer[offset + 4] = flippedX ? grid.r : grid.l;
+ f32buffer[offset + 5] = flippedY ? grid.b : grid.t;
+ break;
case 1: // bl
- f32buffer[offset + 4] = flippedX ? grid.r : grid.l;
- f32buffer[offset + 5] = flippedY ? grid.t : grid.b;
- break;
+ f32buffer[offset + 4] = flippedX ? grid.r : grid.l;
+ f32buffer[offset + 5] = flippedY ? grid.t : grid.b;
+ break;
case 2: // tr
- f32buffer[offset + 4] = flippedX ? grid.l : grid.r;
- f32buffer[offset + 5] = flippedY ? grid.b : grid.t;
- break;
+ f32buffer[offset + 4] = flippedX ? grid.l : grid.r;
+ f32buffer[offset + 5] = flippedY ? grid.b : grid.t;
+ break;
case 3: // br
- f32buffer[offset + 4] = flippedX ? grid.l : grid.r;
- f32buffer[offset + 5] = flippedY ? grid.t : grid.b;
- break;
+ f32buffer[offset + 4] = flippedX ? grid.l : grid.r;
+ f32buffer[offset + 5] = flippedY ? grid.t : grid.b;
+ break;
}
offset += 6;
diff --git a/cocos2d/transitions/CCTransition.js b/cocos2d/transitions/CCTransition.js
index 6796074555..09b18228e6 100644
--- a/cocos2d/transitions/CCTransition.js
+++ b/cocos2d/transitions/CCTransition.js
@@ -64,12 +64,12 @@ cc.TRANSITION_ORIENTATION_DOWN_OVER = 1;
* var trans = new TransitionScene(time,scene);
*/
cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
- _inScene:null,
- _outScene:null,
- _duration:null,
- _isInSceneOnTop:false,
- _isSendCleanupToScene:false,
- _className:"TransitionScene",
+ _inScene: null,
+ _outScene: null,
+ _duration: null,
+ _isInSceneOnTop: false,
+ _isSendCleanupToScene: false,
+ _className: "TransitionScene",
/**
* creates a base transition with duration and incoming scene
@@ -77,14 +77,14 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
* @param {Number} t time in seconds
* @param {cc.Scene} scene the scene to transit with
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.Scene.prototype.ctor.call(this);
- if(t !== undefined && scene !== undefined)
+ if (t !== undefined && scene !== undefined)
this.initWithDuration(t, scene);
},
//private
- _setNewScene:function (dt) {
+ _setNewScene: function (dt) {
this.unschedule(this._setNewScene);
// Before replacing, save the "send cleanup to scene"
var director = cc.director;
@@ -99,14 +99,14 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
},
//protected
- _sceneOrder:function () {
+ _sceneOrder: function () {
this._isInSceneOnTop = true;
},
/**
* stuff gets drawn here
*/
- visit:function () {
+ visit: function () {
if (this._isInSceneOnTop) {
this._outScene.visit();
this._inScene.visit();
@@ -125,7 +125,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
* If you override onEnter, you must call its parent's onEnter function with this._super().
*
*/
- onEnter:function () {
+ onEnter: function () {
cc.Node.prototype.onEnter.call(this);
// disable events while transitions
@@ -133,9 +133,9 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
// outScene should not receive the onEnter callback
// only the onExitTransitionDidStart
- this._outScene.onExitTransitionDidStart();
+ this._outScene._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart);
- this._inScene.onEnter();
+ this._inScene._performRecursive(cc.Node._stateCallbackType.onEnter);
},
/**
@@ -146,27 +146,27 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
* If you override onExit, you shall call its parent's onExit with this._super().
*
*/
- onExit:function () {
+ onExit: function () {
cc.Node.prototype.onExit.call(this);
// enable events while transitions
cc.eventManager.setEnabled(true);
- this._outScene.onExit();
+ this._outScene._performRecursive(cc.Node._stateCallbackType.onExit);
// _inScene should not receive the onEnter callback
// only the onEnterTransitionDidFinish
- this._inScene.onEnterTransitionDidFinish();
+ this._inScene._performRecursive(cc.Node._stateCallbackType.onEnterTransitionDidFinish);
},
/**
* custom cleanup
*/
- cleanup:function () {
+ cleanup: function () {
cc.Node.prototype.cleanup.call(this);
if (this._isSendCleanupToScene)
- this._outScene.cleanup();
+ this._outScene._performRecursive(cc.Node._stateCallbackType.cleanup);
},
/**
@@ -175,17 +175,17 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
* @param {cc.Scene} scene a scene to transit to
* @return {Boolean} return false if error
*/
- initWithDuration:function (t, scene) {
- if(!scene)
+ initWithDuration: function (t, scene) {
+ if (!scene)
throw new Error("cc.TransitionScene.initWithDuration(): Argument scene must be non-nil");
if (this.init()) {
this._duration = t;
this.attr({
- x: 0,
- y: 0,
- anchorX: 0,
- anchorY: 0
+ x: 0,
+ y: 0,
+ anchorX: 0,
+ anchorY: 0
});
// retain
this._inScene = scene;
@@ -195,7 +195,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
this._outScene.init();
}
- if(this._inScene === this._outScene)
+ if (this._inScene === this._outScene)
throw new Error("cc.TransitionScene.initWithDuration(): Incoming scene must be different from the outgoing scene");
this._sceneOrder();
@@ -208,22 +208,22 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
/**
* called after the transition finishes
*/
- finish:function () {
+ finish: function () {
// clean up
this._inScene.attr({
- visible: true,
- x: 0,
- y: 0,
- scale: 1.0,
- rotation: 0.0
+ visible: true,
+ x: 0,
+ y: 0,
+ scale: 1.0,
+ rotation: 0.0
});
this._outScene.attr({
- visible: false,
- x: 0,
- y: 0,
- scale: 1.0,
- rotation: 0.0
+ visible: false,
+ x: 0,
+ y: 0,
+ scale: 1.0,
+ rotation: 0.0
});
//[self schedule:@selector(setNewScene:) interval:0];
@@ -233,7 +233,7 @@ cc.TransitionScene = cc.Scene.extend(/** @lends cc.TransitionScene# */{
/**
* set hide the out scene and show in scene
*/
- hideOutShowIn:function () {
+ hideOutShowIn: function () {
this._inScene.visible = true;
this._outScene.visible = false;
}
@@ -262,7 +262,7 @@ cc.TransitionScene.create = function (t, scene) {
* var trans = new cc.TransitionSceneOriented(time,scene,orientation);
*/
cc.TransitionSceneOriented = cc.TransitionScene.extend(/** @lends cc.TransitionSceneOriented# */{
- _orientation:0,
+ _orientation: 0,
/**
* Constructor of TransitionSceneOriented
@@ -270,7 +270,7 @@ cc.TransitionSceneOriented = cc.TransitionScene.extend(/** @lends cc.TransitionS
* @param {cc.Scene} scene
* @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} orientation
*/
- ctor:function (t, scene, orientation) {
+ ctor: function (t, scene, orientation) {
cc.TransitionScene.prototype.ctor.call(this);
orientation != undefined && this.initWithDuration(t, scene, orientation);
},
@@ -281,7 +281,7 @@ cc.TransitionSceneOriented = cc.TransitionScene.extend(/** @lends cc.TransitionS
* @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} orientation
* @return {Boolean}
*/
- initWithDuration:function (t, scene, orientation) {
+ initWithDuration: function (t, scene, orientation) {
if (cc.TransitionScene.prototype.initWithDuration.call(this, t, scene)) {
this._orientation = orientation;
}
@@ -318,7 +318,7 @@ cc.TransitionRotoZoom = cc.TransitionScene.extend(/** @lends cc.TransitionRotoZo
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionScene.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
@@ -326,19 +326,19 @@ cc.TransitionRotoZoom = cc.TransitionScene.extend(/** @lends cc.TransitionRotoZo
* Custom On Enter callback
* @override
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
- this._inScene.attr({
- scale: 0.001,
- anchorX: 0.5,
- anchorY: 0.5
- });
- this._outScene.attr({
- scale: 1.0,
- anchorX: 0.5,
- anchorY: 0.5
- });
+ this._inScene.attr({
+ scale: 0.001,
+ anchorX: 0.5,
+ anchorY: 0.5
+ });
+ this._outScene.attr({
+ scale: 1.0,
+ anchorX: 0.5,
+ anchorY: 0.5
+ });
var rotoZoom = cc.sequence(
cc.spawn(cc.scaleBy(this._duration / 2, 0.001),
@@ -378,26 +378,26 @@ cc.TransitionJumpZoom = cc.TransitionScene.extend(/** @lends cc.TransitionJumpZo
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionScene.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
/**
* Custom on enter
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
var winSize = cc.director.getWinSize();
- this._inScene.attr({
- scale: 0.5,
- x: winSize.width,
- y: 0,
- anchorX: 0.5,
- anchorY: 0.5
- });
+ this._inScene.attr({
+ scale: 0.5,
+ x: winSize.width,
+ y: 0,
+ anchorX: 0.5,
+ anchorY: 0.5
+ });
this._outScene.anchorX = 0.5;
- this._outScene.anchorY = 0.5;
+ this._outScene.anchorY = 0.5;
var jump = cc.jumpBy(this._duration / 4, cc.p(-winSize.width, 0), winSize.width / 4, 2);
var scaleIn = cc.scaleTo(this._duration / 4, 1.0);
@@ -438,14 +438,14 @@ cc.TransitionMoveInL = cc.TransitionScene.extend(/** @lends cc.TransitionMoveInL
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionScene.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
/**
* Custom on enter
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
this.initScenes();
@@ -458,14 +458,14 @@ cc.TransitionMoveInL = cc.TransitionScene.extend(/** @lends cc.TransitionMoveInL
/**
* initializes the scenes
*/
- initScenes:function () {
+ initScenes: function () {
this._inScene.setPosition(-cc.director.getWinSize().width, 0);
},
/**
* returns the action that will be performed
*/
- action:function () {
+ action: function () {
return cc.moveTo(this._duration, cc.p(0, 0));
},
@@ -474,7 +474,7 @@ cc.TransitionMoveInL = cc.TransitionScene.extend(/** @lends cc.TransitionMoveInL
* @param {cc.ActionInterval} action
* @return {cc.EaseOut}
*/
- easeActionWithAction:function (action) {
+ easeActionWithAction: function (action) {
return new cc.EaseOut(action, 2.0);
}
});
@@ -505,14 +505,14 @@ cc.TransitionMoveInR = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveI
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionMoveInL.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
/**
* Init function
*/
- initScenes:function () {
+ initScenes: function () {
this._inScene.setPosition(cc.director.getWinSize().width, 0);
}
});
@@ -543,14 +543,14 @@ cc.TransitionMoveInT = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveI
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionMoveInL.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
/**
* init function
*/
- initScenes:function () {
+ initScenes: function () {
this._inScene.setPosition(0, cc.director.getWinSize().height);
}
});
@@ -581,7 +581,7 @@ cc.TransitionMoveInB = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveI
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionMoveInL.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
@@ -589,7 +589,7 @@ cc.TransitionMoveInB = cc.TransitionMoveInL.extend(/** @lends cc.TransitionMoveI
/**
* init function
*/
- initScenes:function () {
+ initScenes: function () {
this._inScene.setPosition(0, -cc.director.getWinSize().height);
}
});
@@ -630,18 +630,18 @@ cc.TransitionSlideInL = cc.TransitionScene.extend(/** @lends cc.TransitionSlideI
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionScene.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
- _sceneOrder:function () {
+ _sceneOrder: function () {
this._isInSceneOnTop = false;
},
/**
* custom on enter
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
this.initScenes();
@@ -657,14 +657,14 @@ cc.TransitionSlideInL = cc.TransitionScene.extend(/** @lends cc.TransitionSlideI
/**
* initializes the scenes
*/
- initScenes:function () {
+ initScenes: function () {
this._inScene.setPosition(-cc.director.getWinSize().width + cc.ADJUST_FACTOR, 0);
},
/**
* returns the action that will be performed by the incoming and outgoing scene
* @return {cc.MoveBy}
*/
- action:function () {
+ action: function () {
return cc.moveBy(this._duration, cc.p(cc.director.getWinSize().width - cc.ADJUST_FACTOR, 0));
},
@@ -672,7 +672,7 @@ cc.TransitionSlideInL = cc.TransitionScene.extend(/** @lends cc.TransitionSlideI
* @param {cc.ActionInterval} action
* @return {*}
*/
- easeActionWithAction:function (action) {
+ easeActionWithAction: function (action) {
return new cc.EaseInOut(action, 2.0);
}
});
@@ -703,24 +703,24 @@ cc.TransitionSlideInR = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionSlideInL.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
- _sceneOrder:function () {
+ _sceneOrder: function () {
this._isInSceneOnTop = true;
},
/**
* initializes the scenes
*/
- initScenes:function () {
+ initScenes: function () {
this._inScene.setPosition(cc.director.getWinSize().width - cc.ADJUST_FACTOR, 0);
},
/**
* returns the action that will be performed by the incoming and outgoing scene
* @return {cc.MoveBy}
*/
- action:function () {
+ action: function () {
return cc.moveBy(this._duration, cc.p(-(cc.director.getWinSize().width - cc.ADJUST_FACTOR), 0));
}
});
@@ -751,18 +751,18 @@ cc.TransitionSlideInB = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionSlideInL.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
- _sceneOrder:function () {
+ _sceneOrder: function () {
this._isInSceneOnTop = false;
},
/**
* initializes the scenes
*/
- initScenes:function () {
+ initScenes: function () {
this._inScene.setPosition(0, -(cc.director.getWinSize().height - cc.ADJUST_FACTOR));
},
@@ -770,7 +770,7 @@ cc.TransitionSlideInB = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli
* returns the action that will be performed by the incoming and outgoing scene
* @return {cc.MoveBy}
*/
- action:function () {
+ action: function () {
return cc.moveBy(this._duration, cc.p(0, cc.director.getWinSize().height - cc.ADJUST_FACTOR));
}
});
@@ -801,18 +801,18 @@ cc.TransitionSlideInT = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionSlideInL.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
- _sceneOrder:function () {
+ _sceneOrder: function () {
this._isInSceneOnTop = true;
},
/**
* initializes the scenes
*/
- initScenes:function () {
+ initScenes: function () {
this._inScene.setPosition(0, cc.director.getWinSize().height - cc.ADJUST_FACTOR);
},
@@ -820,7 +820,7 @@ cc.TransitionSlideInT = cc.TransitionSlideInL.extend(/** @lends cc.TransitionSli
* returns the action that will be performed by the incoming and outgoing scene
* @return {cc.MoveBy}
*/
- action:function () {
+ action: function () {
return cc.moveBy(this._duration, cc.p(0, -(cc.director.getWinSize().height - cc.ADJUST_FACTOR)));
}
});
@@ -851,26 +851,26 @@ cc.TransitionShrinkGrow = cc.TransitionScene.extend(/** @lends cc.TransitionShri
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionScene.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
/**
* Custom on enter
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
- this._inScene.attr({
- scale: 0.001,
- anchorX: 2 / 3.0,
- anchorY: 0.5
- });
- this._outScene.attr({
- scale: 1.0,
- anchorX: 1 / 3.0,
- anchorY: 0.5
- });
+ this._inScene.attr({
+ scale: 0.001,
+ anchorX: 2 / 3.0,
+ anchorY: 0.5
+ });
+ this._outScene.attr({
+ scale: 1.0,
+ anchorX: 1 / 3.0,
+ anchorY: 0.5
+ });
var scaleOut = cc.scaleTo(this._duration, 0.01);
var scaleIn = cc.scaleTo(this._duration, 1.0);
@@ -883,7 +883,7 @@ cc.TransitionShrinkGrow = cc.TransitionScene.extend(/** @lends cc.TransitionShri
* @param action
* @return {cc.EaseOut}
*/
- easeActionWithAction:function (action) {
+ easeActionWithAction: function (action) {
return new cc.EaseOut(action, 2.0);
}
});
@@ -910,7 +910,7 @@ cc.TransitionShrinkGrow.create = function (t, scene) {
* var trans = new cc.TransitionFade(time,scene,color)
*/
cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{
- _color:null,
+ _color: null,
/**
* Constructor of TransitionFade
@@ -918,7 +918,7 @@ cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{
* @param {cc.Scene} scene
* @param {cc.TRANSITION_ORIENTATION_LEFT_OVER|cc.TRANSITION_ORIENTATION_RIGHT_OVER|cc.TRANSITION_ORIENTATION_UP_OVER|cc.TRANSITION_ORIENTATION_DOWN_OVER} o
*/
- ctor:function (t, scene, color) {
+ ctor: function (t, scene, color) {
cc.TransitionScene.prototype.ctor.call(this);
this._color = cc.color();
scene && this.initWithDuration(t, scene, color);
@@ -927,7 +927,7 @@ cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{
/**
* custom on enter
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
var l = new cc.LayerColor(this._color);
@@ -948,7 +948,7 @@ cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{
/**
* custom on exit
*/
- onExit:function () {
+ onExit: function () {
cc.TransitionScene.prototype.onExit.call(this);
this.removeChildByTag(cc.SCENE_FADE, false);
},
@@ -960,7 +960,7 @@ cc.TransitionFade = cc.TransitionScene.extend(/** @lends cc.TransitionFade# */{
* @param {cc.Color} color
* @return {Boolean}
*/
- initWithDuration:function (t, scene, color) {
+ initWithDuration: function (t, scene, color) {
color = color || cc.color.BLACK;
if (cc.TransitionScene.prototype.initWithDuration.call(this, t, scene)) {
this._color.r = color.r;
@@ -1000,14 +1000,14 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionScene.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
/**
* custom on enter
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
// create a transparent color layer
@@ -1020,12 +1020,12 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross
var inTexture = new cc.RenderTexture(winSize.width, winSize.height);
inTexture.sprite.anchorX = 0.5;
- inTexture.sprite.anchorY = 0.5;
+ inTexture.sprite.anchorY = 0.5;
inTexture.attr({
- x: winSize.width / 2,
- y: winSize.height / 2,
- anchorX: 0.5,
- anchorY: 0.5
+ x: winSize.width / 2,
+ y: winSize.height / 2,
+ anchorX: 0.5,
+ anchorY: 0.5
});
// render inScene to its texturebuffer
@@ -1036,8 +1036,8 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross
// create the second render texture for outScene
var outTexture = new cc.RenderTexture(winSize.width, winSize.height);
outTexture.setPosition(winSize.width / 2, winSize.height / 2);
- outTexture.sprite.anchorX = outTexture.anchorX = 0.5;
- outTexture.sprite.anchorY = outTexture.anchorY = 0.5;
+ outTexture.sprite.anchorX = outTexture.anchorX = 0.5;
+ outTexture.sprite.anchorY = outTexture.anchorY = 0.5;
// render outScene to its texturebuffer
outTexture.begin();
@@ -1071,24 +1071,10 @@ cc.TransitionCrossFade = cc.TransitionScene.extend(/** @lends cc.TransitionCross
/**
* custom on exit
*/
- onExit:function () {
+ onExit: function () {
this.removeChildByTag(cc.SCENE_FADE, false);
cc.TransitionScene.prototype.onExit.call(this);
},
-
- /**
- * stuff gets drawn here
- */
- visit:function () {
- cc.Node.prototype.visit.call(this);
- },
-
- /**
- * overide draw
- */
- draw:function () {
- // override draw since both scenes (textures) are rendered in 1 scene
- }
});
/**
@@ -1118,23 +1104,23 @@ cc.TransitionTurnOffTiles = cc.TransitionScene.extend(/** @lends cc.TransitionTu
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionScene.prototype.ctor.call(this);
this._gridProxy = new cc.NodeGrid();
scene && this.initWithDuration(t, scene);
},
- _sceneOrder:function () {
+ _sceneOrder: function () {
this._isInSceneOnTop = false;
},
/**
* custom on enter
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
this._gridProxy.setTarget(this._outScene);
- this._gridProxy.onEnter();
+ this._gridProxy._performRecursive(cc.Node._stateCallbackType.onEnter);
var winSize = cc.director.getWinSize();
var aspect = winSize.width / winSize.height;
@@ -1145,7 +1131,7 @@ cc.TransitionTurnOffTiles = cc.TransitionScene.extend(/** @lends cc.TransitionTu
this._gridProxy.runAction(cc.sequence(action, cc.callFunc(this.finish, this), cc.stopGrid()));
},
- visit: function(){
+ visit: function () {
this._inScene.visit();
this._gridProxy.visit();
},
@@ -1154,7 +1140,7 @@ cc.TransitionTurnOffTiles = cc.TransitionScene.extend(/** @lends cc.TransitionTu
* @param {cc.ActionInterval} action
* @return {cc.ActionInterval}
*/
- easeActionWithAction:function (action) {
+ easeActionWithAction: function (action) {
return action;
}
});
@@ -1182,7 +1168,7 @@ cc.TransitionTurnOffTiles.create = function (t, scene) {
cc.TransitionSplitCols = cc.TransitionScene.extend(/** @lends cc.TransitionSplitCols# */{
_gridProxy: null,
- _switchTargetToInscene: function(){
+ _switchTargetToInscene: function () {
this._gridProxy.setTarget(this._inScene);
},
@@ -1191,7 +1177,7 @@ cc.TransitionSplitCols = cc.TransitionScene.extend(/** @lends cc.TransitionSplit
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionScene.prototype.ctor.call(this);
this._gridProxy = new cc.NodeGrid();
scene && this.initWithDuration(t, scene);
@@ -1199,11 +1185,11 @@ cc.TransitionSplitCols = cc.TransitionScene.extend(/** @lends cc.TransitionSplit
/**
* custom on enter
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
//this._inScene.visible = false;
this._gridProxy.setTarget(this._outScene);
- this._gridProxy.onEnter();
+ this._gridProxy._performRecursive(cc.Node._stateCallbackType.onEnter);
var split = this.action();
var seq = cc.sequence(
@@ -1214,13 +1200,13 @@ cc.TransitionSplitCols = cc.TransitionScene.extend(/** @lends cc.TransitionSplit
);
},
- onExit: function(){
+ onExit: function () {
this._gridProxy.setTarget(null);
- this._gridProxy.onExit();
+ this._gridProxy._performRecursive(cc.Node._stateCallbackType.onExit);
cc.TransitionScene.prototype.onExit.call(this);
},
- visit: function(){
+ visit: function () {
this._gridProxy.visit();
},
@@ -1228,14 +1214,14 @@ cc.TransitionSplitCols = cc.TransitionScene.extend(/** @lends cc.TransitionSplit
* @param {cc.ActionInterval} action
* @return {cc.EaseInOut}
*/
- easeActionWithAction:function (action) {
+ easeActionWithAction: function (action) {
return new cc.EaseInOut(action, 3.0);
},
/**
* @return {*}
*/
- action:function () {
+ action: function () {
return cc.splitCols(this._duration / 2.0, 3);
}
});
@@ -1267,14 +1253,14 @@ cc.TransitionSplitRows = cc.TransitionSplitCols.extend(/** @lends cc.TransitionS
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionSplitCols.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
/**
* @return {*}
*/
- action:function () {
+ action: function () {
return cc.splitRows(this._duration / 2.0, 3);
}
});
@@ -1306,23 +1292,23 @@ cc.TransitionFadeTR = cc.TransitionScene.extend(/** @lends cc.TransitionFadeTR#
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionScene.prototype.ctor.call(this);
this._gridProxy = new cc.NodeGrid();
scene && this.initWithDuration(t, scene);
},
- _sceneOrder:function () {
+ _sceneOrder: function () {
this._isInSceneOnTop = false;
},
/**
* Custom on enter
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
this._gridProxy.setTarget(this._outScene);
- this._gridProxy.onEnter();
+ this._gridProxy._performRecursive(cc.Node._stateCallbackType.onEnter);
var winSize = cc.director.getWinSize();
var aspect = winSize.width / winSize.height;
@@ -1335,7 +1321,7 @@ cc.TransitionFadeTR = cc.TransitionScene.extend(/** @lends cc.TransitionFadeTR#
);
},
- visit: function(){
+ visit: function () {
this._inScene.visit();
this._gridProxy.visit();
},
@@ -1344,7 +1330,7 @@ cc.TransitionFadeTR = cc.TransitionScene.extend(/** @lends cc.TransitionFadeTR#
* @param {cc.ActionInterval} action
* @return {cc.ActionInterval}
*/
- easeActionWithAction:function (action) {
+ easeActionWithAction: function (action) {
return action;
},
@@ -1352,7 +1338,7 @@ cc.TransitionFadeTR = cc.TransitionScene.extend(/** @lends cc.TransitionFadeTR#
* @param {cc.Size} size
* @return {*}
*/
- actionWithSize:function (size) {
+ actionWithSize: function (size) {
return cc.fadeOutTRTiles(this._duration, size);
}
});
@@ -1383,7 +1369,7 @@ cc.TransitionFadeBL = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeBL#
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionFadeTR.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
@@ -1392,7 +1378,7 @@ cc.TransitionFadeBL = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeBL#
* @param {cc.Size} size
* @return {*}
*/
- actionWithSize:function (size) {
+ actionWithSize: function (size) {
return cc.fadeOutBLTiles(this._duration, size);
}
});
@@ -1425,7 +1411,7 @@ cc.TransitionFadeUp = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeUp#
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionFadeTR.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
@@ -1434,7 +1420,7 @@ cc.TransitionFadeUp = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeUp#
* @param {cc.Size} size
* @return {cc.FadeOutUpTiles}
*/
- actionWithSize:function (size) {
+ actionWithSize: function (size) {
return new cc.FadeOutUpTiles(this._duration, size);
}
});
@@ -1466,7 +1452,7 @@ cc.TransitionFadeDown = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeD
* @param {Number} t time in seconds
* @param {cc.Scene} scene
*/
- ctor:function (t, scene) {
+ ctor: function (t, scene) {
cc.TransitionFadeTR.prototype.ctor.call(this);
scene && this.initWithDuration(t, scene);
},
@@ -1475,8 +1461,8 @@ cc.TransitionFadeDown = cc.TransitionFadeTR.extend(/** @lends cc.TransitionFadeD
* @param {cc.Size} size
* @return {*}
*/
- actionWithSize:function (size) {
- return cc.fadeOutDownTiles( this._duration, size);
+ actionWithSize: function (size) {
+ return cc.fadeOutDownTiles(this._duration, size);
}
});
diff --git a/cocos2d/transitions/CCTransitionPageTurn.js b/cocos2d/transitions/CCTransitionPageTurn.js
index 6b71fd848b..44a6bedd28 100644
--- a/cocos2d/transitions/CCTransitionPageTurn.js
+++ b/cocos2d/transitions/CCTransitionPageTurn.js
@@ -47,7 +47,7 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu
* @param {cc.Scene} scene
* @param {Boolean} backwards
*/
- ctor:function (t, scene, backwards) {
+ ctor: function (t, scene, backwards) {
cc.TransitionScene.prototype.ctor.call(this);
this._gridProxy = new cc.NodeGrid();
this.initWithDuration(t, scene, backwards);
@@ -56,9 +56,9 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu
/**
* @type Boolean
*/
- _back:true,
+ _back: true,
_gridProxy: null,
- _className:"TransitionPageTurn",
+ _className: "TransitionPageTurn",
/**
* Creates a base transition with duration and incoming scene.
@@ -69,7 +69,7 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu
* @param {Boolean} backwards
* @return {Boolean}
*/
- initWithDuration:function (t, scene, backwards) {
+ initWithDuration: function (t, scene, backwards) {
// XXX: needed before [super init]
this._back = backwards;
@@ -83,7 +83,7 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu
* @param {cc.Size} vector
* @return {cc.ReverseTime|cc.TransitionScene}
*/
- actionWithSize:function (vector) {
+ actionWithSize: function (vector) {
if (this._back)
return cc.reverseTime(cc.pageTurn3D(this._duration, vector)); // Get hold of the PageTurn3DAction
else
@@ -93,7 +93,7 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu
/**
* custom on enter
*/
- onEnter:function () {
+ onEnter: function () {
cc.TransitionScene.prototype.onEnter.call(this);
var winSize = cc.director.getWinSize();
var x, y;
@@ -109,11 +109,11 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu
if (!this._back) {
gridProxy.setTarget(this._outScene);
- gridProxy.onEnter();
- gridProxy.runAction( cc.sequence(action,cc.callFunc(this.finish, this),cc.stopGrid()));
+ gridProxy._performRecursive(cc.Node._stateCallbackType.onEnter);
+ gridProxy.runAction(cc.sequence(action, cc.callFunc(this.finish, this), cc.stopGrid()));
} else {
gridProxy.setTarget(this._inScene);
- gridProxy.onEnter();
+ gridProxy._performRecursive(cc.Node._stateCallbackType.onEnter);
// to prevent initial flicker
this._inScene.visible = false;
gridProxy.runAction(
@@ -123,16 +123,16 @@ cc.TransitionPageTurn = cc.TransitionScene.extend(/** @lends cc.TransitionPageTu
}
},
- visit: function(){
+ visit: function () {
//cc.TransitionScene.prototype.visit.call(this);
- if(this._back)
+ if (this._back)
this._outScene.visit();
else
this._inScene.visit();
this._gridProxy.visit();
},
- _sceneOrder:function () {
+ _sceneOrder: function () {
this._isInSceneOnTop = this._back;
}
});
diff --git a/extensions/ccb-reader/CCBAnimationManager.js b/extensions/ccb-reader/CCBAnimationManager.js
index b341ea4bbd..54ab341f0c 100644
--- a/extensions/ccb-reader/CCBAnimationManager.js
+++ b/extensions/ccb-reader/CCBAnimationManager.js
@@ -24,43 +24,48 @@
THE SOFTWARE.
****************************************************************************/
+(function () {
+
+var _pos = cc.p();
+
cc.BuilderAnimationManagerDelegate = cc.Class.extend({
- completedAnimationSequenceNamed:function (name) {}
+ completedAnimationSequenceNamed: function (name) {
+ }
});
cc.BuilderAnimationManager = cc.Class.extend({
- _sequences:null,
- _nodeSequences:null,
- _baseValues:null,
- _autoPlaySequenceId:0,
-
- _rootNode:null,
- _owner:null,
- _rootContainerSize:null,
-
- _delegate:null,
- _runningSequence:null,
-
- _documentOutletNames:null,
- _documentOutletNodes:null,
- _documentCallbackNames:null,
- _documentCallbackNodes:null,
- _documentCallbackControlEvents:null,
- _documentControllerName:"",
- _lastCompletedSequenceName:"",
- _keyframeCallbacks:null,
- _keyframeCallFuncs:null,
-
- _animationCompleteCallbackFunc:null,
- _target:null,
- _jsControlled:false,
-
- ctor:function () {
+ _sequences: null,
+ _nodeSequences: null,
+ _baseValues: null,
+ _autoPlaySequenceId: 0,
+
+ _rootNode: null,
+ _owner: null,
+ _rootContainerSize: null,
+
+ _delegate: null,
+ _runningSequence: null,
+
+ _documentOutletNames: null,
+ _documentOutletNodes: null,
+ _documentCallbackNames: null,
+ _documentCallbackNodes: null,
+ _documentCallbackControlEvents: null,
+ _documentControllerName: "",
+ _lastCompletedSequenceName: "",
+ _keyframeCallbacks: null,
+ _keyframeCallFuncs: null,
+
+ _animationCompleteCallbackFunc: null,
+ _target: null,
+ _jsControlled: false,
+
+ ctor: function () {
this._rootContainerSize = cc.size(0, 0);
this.init();
},
- init:function () {
+ init: function () {
this._sequences = [];
this._nodeSequences = new cc._Dictionary();
this._baseValues = new cc._Dictionary();
@@ -77,122 +82,122 @@ cc.BuilderAnimationManager = cc.Class.extend({
return true;
},
- getSequences:function () {
+ getSequences: function () {
return this._sequences;
},
- setSequences:function(seqs){
+ setSequences: function (seqs) {
this._sequences = seqs;
},
- getAutoPlaySequenceId:function () {
+ getAutoPlaySequenceId: function () {
return this._autoPlaySequenceId;
},
- setAutoPlaySequenceId:function (autoPlaySequenceId) {
+ setAutoPlaySequenceId: function (autoPlaySequenceId) {
this._autoPlaySequenceId = autoPlaySequenceId;
},
- getRootNode:function () {
+ getRootNode: function () {
return this._rootNode;
},
- setRootNode:function (rootNode) {
+ setRootNode: function (rootNode) {
this._rootNode = rootNode;
},
- getOwner:function () {
+ getOwner: function () {
return this._owner;
},
- setOwner:function (owner) {
+ setOwner: function (owner) {
this._owner = owner;
},
- addDocumentCallbackNode:function(node){
+ addDocumentCallbackNode: function (node) {
this._documentCallbackNodes.push(node);
},
- addDocumentCallbackName:function(name){
+ addDocumentCallbackName: function (name) {
this._documentCallbackNames.push(name);
},
- addDocumentCallbackControlEvents:function(controlEvents){
+ addDocumentCallbackControlEvents: function (controlEvents) {
this._documentCallbackControlEvents.push(controlEvents);
},
- addDocumentOutletNode:function(node){
+ addDocumentOutletNode: function (node) {
this._documentOutletNodes.push(node);
},
- addDocumentOutletName:function(name){
+ addDocumentOutletName: function (name) {
this._documentOutletNames.push(name);
},
- setDocumentControllerName:function(name){
+ setDocumentControllerName: function (name) {
this._documentControllerName = name;
},
- getDocumentControllerName:function(){
+ getDocumentControllerName: function () {
return this._documentControllerName;
},
- getDocumentCallbackNames:function(){
+ getDocumentCallbackNames: function () {
return this._documentCallbackNames;
},
- getDocumentCallbackNodes:function(){
+ getDocumentCallbackNodes: function () {
return this._documentCallbackNodes;
},
- getDocumentCallbackControlEvents:function(){
+ getDocumentCallbackControlEvents: function () {
return this._documentCallbackControlEvents;
},
- getDocumentOutletNames:function(){
+ getDocumentOutletNames: function () {
return this._documentOutletNames;
},
- getDocumentOutletNodes:function(){
+ getDocumentOutletNodes: function () {
return this._documentOutletNodes;
},
- getLastCompletedSequenceName:function(){
+ getLastCompletedSequenceName: function () {
return this._lastCompletedSequenceName;
},
- getKeyframeCallbacks:function(){
+ getKeyframeCallbacks: function () {
return this._keyframeCallbacks;
},
- getRootContainerSize:function () {
+ getRootContainerSize: function () {
return this._rootContainerSize;
},
- setRootContainerSize:function (rootContainerSize) {
+ setRootContainerSize: function (rootContainerSize) {
this._rootContainerSize = cc.size(rootContainerSize.width, rootContainerSize.height);
},
- getDelegate:function () {
+ getDelegate: function () {
return this._delegate;
},
- setDelegate:function (delegate) {
+ setDelegate: function (delegate) {
this._delegate = delegate;
},
- getRunningSequenceName:function () {
- if(this._runningSequence)
+ getRunningSequenceName: function () {
+ if (this._runningSequence)
return this._runningSequence.getName();
return null;
},
- getContainerSize:function (node) {
+ getContainerSize: function (node) {
if (node)
return node.getContentSize();
else
return this._rootContainerSize;
},
- addNode:function (node, seq) {
+ addNode: function (node, seq) {
this._nodeSequences.setObject(seq, node);
},
- setBaseValue:function (value, node, propName) {
+ setBaseValue: function (value, node, propName) {
var props = this._baseValues.objectForKey(node);
if (!props) {
props = new cc._Dictionary();
@@ -201,11 +206,11 @@ cc.BuilderAnimationManager = cc.Class.extend({
props.setObject(value, propName);
},
- moveAnimationsFromNode:function(fromNode,toNode){
+ moveAnimationsFromNode: function (fromNode, toNode) {
// Move base values
var locBaseValues = this._baseValues;
var baseValue = locBaseValues.objectForKey(fromNode);
- if(baseValue !== null) {
+ if (baseValue !== null) {
locBaseValues.setObject(baseValue, toNode);
locBaseValues.removeObjectForKey(fromNode);
}
@@ -213,13 +218,13 @@ cc.BuilderAnimationManager = cc.Class.extend({
// Move seqs
var locNodeSequences = this._nodeSequences;
var seqs = locNodeSequences.objectForKey(fromNode);
- if(seqs != null) {
+ if (seqs != null) {
locNodeSequences.setObject(seqs, toNode);
locNodeSequences.removeObjectForKey(fromNode);
}
},
- getActionForCallbackChannel:function(channel) {
+ getActionForCallbackChannel: function (channel) {
var lastKeyframeTime = 0;
var actions = [];
@@ -230,7 +235,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
var keyframe = keyframes[i];
var timeSinceLastKeyframe = keyframe.getTime() - lastKeyframeTime;
lastKeyframeTime = keyframe.getTime();
- if(timeSinceLastKeyframe > 0) {
+ if (timeSinceLastKeyframe > 0) {
actions.push(cc.delayTime(timeSinceLastKeyframe));
}
@@ -238,41 +243,41 @@ cc.BuilderAnimationManager = cc.Class.extend({
var selectorName = keyVal[0];
var selectorTarget = keyVal[1];
- if(this._jsControlled) {
+ if (this._jsControlled) {
var callbackName = selectorTarget + ":" + selectorName; //add number to the stream
var callback = this._keyframeCallFuncs[callbackName];
- if(callback != null)
+ if (callback != null)
actions.push(callback);
} else {
var target;
- if(selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT)
+ if (selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT)
target = this._rootNode;
else if (selectorTarget === CCB_TARGETTYPE_OWNER)
target = this._owner;
- if(target != null) {
- if(selectorName.length > 0) {
+ if (target != null) {
+ if (selectorName.length > 0) {
var selCallFunc = 0;
- if(target.onResolveCCBCCCallFuncSelector != null)
+ if (target.onResolveCCBCCCallFuncSelector != null)
selCallFunc = target.onResolveCCBCCCallFuncSelector(target, selectorName);
- if(selCallFunc === 0)
+ if (selCallFunc === 0)
cc.log("Skipping selector '" + selectorName + "' since no CCBSelectorResolver is present.");
else
- actions.push(cc.callFunc(selCallFunc,target));
+ actions.push(cc.callFunc(selCallFunc, target));
} else {
cc.log("Unexpected empty selector.");
}
}
}
}
- if(actions.length < 1)
+ if (actions.length < 1)
return null;
return cc.sequence(actions);
},
- getActionForSoundChannel:function(channel) {
+ getActionForSoundChannel: function (channel) {
var lastKeyframeTime = 0;
var actions = [];
@@ -283,7 +288,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
var keyframe = keyframes[i];
var timeSinceLastKeyframe = keyframe.getTime() - lastKeyframeTime;
lastKeyframeTime = keyframe.getTime();
- if(timeSinceLastKeyframe > 0) {
+ if (timeSinceLastKeyframe > 0) {
actions.push(cc.delayTime(timeSinceLastKeyframe));
}
@@ -293,29 +298,29 @@ cc.BuilderAnimationManager = cc.Class.extend({
actions.push(cc.BuilderSoundEffect.create(soundFile, pitch, pan, gain));
}
- if(actions.length < 1)
+ if (actions.length < 1)
return null;
return cc.sequence(actions);
},
- runAnimationsForSequenceNamed:function(name){
+ runAnimationsForSequenceNamed: function (name) {
this.runAnimationsForSequenceIdTweenDuration(this._getSequenceId(name), 0);
},
- runAnimationsForSequenceNamedTweenDuration:function(name, tweenDuration){
- this.runAnimationsForSequenceIdTweenDuration(this._getSequenceId(name), tweenDuration);
+ runAnimationsForSequenceNamedTweenDuration: function (name, tweenDuration) {
+ this.runAnimationsForSequenceIdTweenDuration(this._getSequenceId(name), tweenDuration);
},
- runAnimationsForSequenceIdTweenDuration:function(nSeqId, tweenDuration){
- if(nSeqId === -1)
+ runAnimationsForSequenceIdTweenDuration: function (nSeqId, tweenDuration) {
+ if (nSeqId === -1)
throw new Error("cc.BuilderAnimationManager.runAnimationsForSequenceIdTweenDuration(): Sequence id should not be -1");
tweenDuration = tweenDuration || 0;
this._rootNode.stopAllActions();
var allKeys = this._nodeSequences.allKeys();
- for(var i = 0,len = allKeys.length ; i< len;i++){
+ for (var i = 0, len = allKeys.length; i < len; i++) {
var node = allKeys[i];
node.stopAllActions();
@@ -323,27 +328,27 @@ cc.BuilderAnimationManager = cc.Class.extend({
var seqNodeProps = seqs.objectForKey(nSeqId);
var j;
var seqNodePropNames = [];
- if(seqNodeProps){
+ if (seqNodeProps) {
var propKeys = seqNodeProps.allKeys();
- for(j = 0; j < propKeys.length; j++){
+ for (j = 0; j < propKeys.length; j++) {
var propName = propKeys[j];
var seqProp = seqNodeProps.objectForKey(propName);
seqNodePropNames.push(propName);
- this._setFirstFrame(node, seqProp,tweenDuration);
- this._runAction(node,seqProp,tweenDuration);
+ this._setFirstFrame(node, seqProp, tweenDuration);
+ this._runAction(node, seqProp, tweenDuration);
}
}
var nodeBaseValues = this._baseValues.objectForKey(node);
- if(nodeBaseValues){
+ if (nodeBaseValues) {
var baseKeys = nodeBaseValues.allKeys();
- for(j = 0; j < baseKeys.length;j++){
- var selBaseKey = baseKeys[j];
- if(seqNodePropNames.indexOf(selBaseKey) === -1){
+ for (j = 0; j < baseKeys.length; j++) {
+ var selBaseKey = baseKeys[j];
+ if (seqNodePropNames.indexOf(selBaseKey) === -1) {
var value = nodeBaseValues.objectForKey(selBaseKey);
- if(value != null)
- this._setAnimatedProperty(selBaseKey,node, value, tweenDuration);
+ if (value != null)
+ this._setAnimatedProperty(selBaseKey, node, value, tweenDuration);
}
}
}
@@ -352,7 +357,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
// Make callback at end of sequence
var seq = this._getSequence(nSeqId);
var completeAction = cc.sequence(cc.delayTime(seq.getDuration() + tweenDuration),
- cc.callFunc(this._sequenceCompleted,this));
+ cc.callFunc(this._sequenceCompleted, this));
this._rootNode.runAction(completeAction);
// Playback callbacks and sounds
@@ -376,10 +381,10 @@ cc.BuilderAnimationManager = cc.Class.extend({
this._runningSequence = this._getSequence(nSeqId);
},
- runAnimations:function (name, tweenDuration) {
+ runAnimations: function (name, tweenDuration) {
tweenDuration = tweenDuration || 0;
var nSeqId;
- if(cc.isString(name))
+ if (cc.isString(name))
nSeqId = this._getSequenceId(name);
else
nSeqId = name;
@@ -387,29 +392,29 @@ cc.BuilderAnimationManager = cc.Class.extend({
this.runAnimationsForSequenceIdTweenDuration(nSeqId, tweenDuration);
},
- setAnimationCompletedCallback:function(target,callbackFunc){
+ setAnimationCompletedCallback: function (target, callbackFunc) {
this._target = target;
this._animationCompleteCallbackFunc = callbackFunc;
},
- setCompletedAnimationCallback:function(target,callbackFunc){
- this.setAnimationCompletedCallback(target,callbackFunc);
+ setCompletedAnimationCallback: function (target, callbackFunc) {
+ this.setAnimationCompletedCallback(target, callbackFunc);
},
- setCallFunc:function(callFunc, callbackNamed) {
+ setCallFunc: function (callFunc, callbackNamed) {
this._keyframeCallFuncs[callbackNamed] = callFunc;
},
- debug:function () {
+ debug: function () {
},
- _getBaseValue:function (node, propName) {
+ _getBaseValue: function (node, propName) {
var props = this._baseValues.objectForKey(node);
if (props)
return props.objectForKey(propName);
return null;
},
- _getSequenceId:function (sequenceName) {
+ _getSequenceId: function (sequenceName) {
var element = null;
var locSequences = this._sequences;
for (var i = 0, len = locSequences.length; i < len; i++) {
@@ -420,7 +425,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
return -1;
},
- _getSequence:function (sequenceId) {
+ _getSequence: function (sequenceId) {
var element = null;
var locSequences = this._sequences;
for (var i = 0, len = locSequences.length; i < len; i++) {
@@ -431,9 +436,9 @@ cc.BuilderAnimationManager = cc.Class.extend({
return null;
},
- _getAction:function (keyframe0, keyframe1, propName, node) {
+ _getAction: function (keyframe0, keyframe1, propName, node) {
var duration = keyframe1.getTime() - (keyframe0 ? keyframe0.getTime() : 0);
- var getArr,type,getValueArr, x, y;
+ var getArr, type, getValueArr, x, y;
if (propName === "rotation") {
return cc.BuilderRotateTo.create(duration, keyframe1.getValue());
@@ -444,7 +449,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
} else if (propName === "opacity") {
return cc.fadeTo(duration, keyframe1.getValue());
} else if (propName === "color") {
- var selColor = keyframe1.getValue().getColor();
+ var selColor = keyframe1.getValue();
return cc.tintTo(duration, selColor.r, selColor.g, selColor.b);
} else if (propName === "visible") {
var isVisible = keyframe1.getValue();
@@ -455,8 +460,8 @@ cc.BuilderAnimationManager = cc.Class.extend({
}
} else if (propName === "displayFrame") {
return cc.sequence(cc.delayTime(duration), cc.BuilderSetSpriteFrame.create(keyframe1.getValue()));
- } else if(propName === "position"){
- getArr = this._getBaseValue(node,propName);
+ } else if (propName === "position") {
+ getArr = this._getBaseValue(node, propName);
type = getArr[2];
//get relative position
@@ -466,11 +471,11 @@ cc.BuilderAnimationManager = cc.Class.extend({
var containerSize = this.getContainerSize(node.getParent());
- var absPos = cc._getAbsolutePosition(x,y, type,containerSize,propName);
+ var absPos = cc.getAbsolutePosition(x, y, type, containerSize, propName);
- return cc.moveTo(duration,absPos);
- } else if( propName === "scale"){
- getArr = this._getBaseValue(node,propName);
+ return cc.moveTo(duration, absPos);
+ } else if (propName === "scale") {
+ getArr = this._getBaseValue(node, propName);
type = getArr[2];
//get relative position
@@ -478,28 +483,28 @@ cc.BuilderAnimationManager = cc.Class.extend({
x = getValueArr[0];
y = getValueArr[1];
- if(type === CCB_SCALETYPE_MULTIPLY_RESOLUTION){
+ if (type === CCB_SCALETYPE_MULTIPLY_RESOLUTION) {
//TODO need to test
var resolutionScale = cc.BuilderReader.getResolutionScale();
x *= resolutionScale;
y *= resolutionScale;
}
- return cc.scaleTo(duration,x,y);
- } else if( propName === "skew") {
+ return cc.scaleTo(duration, x, y);
+ } else if (propName === "skew") {
//get relative position
getValueArr = keyframe1.getValue();
x = getValueArr[0];
y = getValueArr[1];
- return cc.skewTo(duration,x,y);
+ return cc.skewTo(duration, x, y);
} else {
cc.log("BuilderReader: Failed to create animation for property: " + propName);
}
return null;
},
- _setAnimatedProperty:function (propName, node, value, tweenDuration) {
- if(tweenDuration > 0){
+ _setAnimatedProperty: function (propName, node, value, tweenDuration) {
+ if (tweenDuration > 0) {
// Create a fake keyframe to generate the action from
var kf1 = new cc.BuilderKeyframe();
kf1.setValue(value);
@@ -511,64 +516,65 @@ cc.BuilderAnimationManager = cc.Class.extend({
node.runAction(tweenAction);
} else {
// Just set the value
- var getArr, nType, x,y;
- if(propName === "position"){
- getArr = this._getBaseValue(node,propName);
+ var getArr, nType, x, y;
+ if (propName === "position") {
+ getArr = this._getBaseValue(node, propName);
nType = getArr[2];
x = value[0];
y = value[1];
- node.setPosition(cc._getAbsolutePosition(x,y,nType, this.getContainerSize(node.getParent()),propName));
- }else if(propName === "scale"){
- getArr = this._getBaseValue(node,propName);
+ cc.getAbsolutePosition(x, y, nType, this.getContainerSize(node.getParent()), propName, _pos);
+ node._position.x = _pos.x;
+ node._position.y = _pos.y;
+ } else if (propName === "scale") {
+ getArr = this._getBaseValue(node, propName);
nType = getArr[2];
x = value[0];
y = value[1];
- cc.setRelativeScale(node,x,y,nType,propName);
- } else if( propName === "skew") {
+ cc.setRelativeScale(node, x, y, nType, propName);
+ } else if (propName === "skew") {
x = value[0];
y = value[1];
- node.setSkewX(x);
- node.setSkewY(y);
- }else {
+ node._skewX = x;
+ node._skewY = y;
+ } else {
// [node setValue:value forKey:name];
// TODO only handle rotation, opacity, displayFrame, color
- if(propName === "rotation"){
+ if (propName === "rotation") {
node.setRotation(value);
- } else if(propName === "rotationX")
- {
- node.setRotationSkewX(value);
- }else if(propName === "rotationY")
- {
- node.setRotationSkewY(value);
- }else if(propName === "opacity"){
- node.setOpacity(value);
- } else if(propName === "displayFrame"){
+ } else if (propName === "rotationX") {
+ node._rotationX = value;
+ } else if (propName === "rotationY") {
+ node._rotationY = value;
+ } else if (propName === "opacity") {
+ node._realOpacity = value;
+ } else if (propName === "displayFrame") {
node.setSpriteFrame(value);
- } else if(propName === "color"){
- var ccColor3B = value.getColor();
- if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){
- node.setColor(ccColor3B);
+ } else if (propName === "color") {
+ if (value.r !== 255 || value.g !== 255 || value.b !== 255) {
+ node.setColor(value);
}
- } else if( propName === "visible"){
+ } else if (propName === "visible") {
value = value || false;
node.setVisible(value);
} else {
- cc.log("unsupported property name is "+ propName);
+ cc.log("unsupported property name is " + propName);
+ return;
}
}
+ node.setNodeDirty();
}
},
- _setFirstFrame:function (node, seqProp, tweenDuration) {
+ _setFirstFrame: function (node, seqProp, tweenDuration) {
var keyframes = seqProp.getKeyframes();
if (keyframes.length === 0) {
// Use base value (no animation)
var baseValue = this._getBaseValue(node, seqProp.getName());
- if(!baseValue)
+ if (!baseValue)
cc.log("cc.BuilderAnimationManager._setFirstFrame(): No baseValue found for property");
this._setAnimatedProperty(seqProp.getName(), node, baseValue, tweenDuration);
} else {
@@ -578,8 +584,8 @@ cc.BuilderAnimationManager = cc.Class.extend({
}
},
- _getEaseAction:function (action, easingType, easingOpt) {
- if (easingType === CCB_KEYFRAME_EASING_LINEAR || easingType === CCB_KEYFRAME_EASING_INSTANT ) {
+ _getEaseAction: function (action, easingType, easingOpt) {
+ if (easingType === CCB_KEYFRAME_EASING_LINEAR || easingType === CCB_KEYFRAME_EASING_INSTANT) {
return action;
} else if (easingType === CCB_KEYFRAME_EASING_CUBIC_IN) {
return action.easing(cc.easeIn(easingOpt));
@@ -611,7 +617,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
}
},
- _runAction:function (node, seqProp, tweenDuration) {
+ _runAction: function (node, seqProp, tweenDuration) {
var keyframes = seqProp.getKeyframes();
var numKeyframes = keyframes.length;
@@ -628,7 +634,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
for (var i = 0; i < numKeyframes - 1; ++i) {
var kf0 = keyframes[i];
- var kf1 = keyframes[(i+1)];
+ var kf1 = keyframes[(i + 1)];
var action = this._getAction(kf0, kf1, seqProp.getName(), node);
if (action) {
@@ -642,12 +648,12 @@ cc.BuilderAnimationManager = cc.Class.extend({
}
},
- _sequenceCompleted:function () {
+ _sequenceCompleted: function () {
var locRunningSequence = this._runningSequence;
var locRunningName = locRunningSequence.getName();
- if(this._lastCompletedSequenceName != locRunningSequence.getName()){
+ if (this._lastCompletedSequenceName != locRunningSequence.getName()) {
this._lastCompletedSequenceName = locRunningSequence.getName();
}
@@ -660,7 +666,7 @@ cc.BuilderAnimationManager = cc.Class.extend({
if (this._delegate)
this._delegate.completedAnimationSequenceNamed(locRunningName);
- if(this._target && this._animationCompleteCallbackFunc){
+ if (this._target && this._animationCompleteCallbackFunc) {
this._animationCompleteCallbackFunc.call(this._target);
}
}
@@ -668,13 +674,13 @@ cc.BuilderAnimationManager = cc.Class.extend({
cc.BuilderSetSpriteFrame = cc.ActionInstant.extend({
- _spriteFrame:null,
+ _spriteFrame: null,
- initWithSpriteFrame:function (spriteFrame) {
+ initWithSpriteFrame: function (spriteFrame) {
this._spriteFrame = spriteFrame;
return true;
},
- update:function (time) {
+ update: function (time) {
this.target.setSpriteFrame(this._spriteFrame);
}
});
@@ -692,11 +698,11 @@ cc.BuilderSetSpriteFrame.create = function (spriteFrame) {
// cc.BuilderRotateTo
//
cc.BuilderRotateTo = cc.ActionInterval.extend({
- _startAngle:0,
- _dstAngle:0,
- _diffAngle:0,
+ _startAngle: 0,
+ _dstAngle: 0,
+ _diffAngle: 0,
- initWithDuration:function (duration, angle) {
+ initWithDuration: function (duration, angle) {
if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
this._dstAngle = angle;
return true;
@@ -704,11 +710,11 @@ cc.BuilderRotateTo = cc.ActionInterval.extend({
return false;
}
},
- update:function (time) {
+ update: function (time) {
this.target.setRotation(this._startAngle + (this._diffAngle * time));
},
- startWithTarget:function (node) {
+ startWithTarget: function (node) {
cc.ActionInterval.prototype.startWithTarget.call(this, node);
this._startAngle = this.target.getRotation();
this._diffAngle = this._dstAngle - this._startAngle;
@@ -750,19 +756,19 @@ cc.BuilderRotateYTo.create = function (duration, angle) {
// cc.BuilderSoundEffect
//
cc.BuilderSoundEffect = cc.ActionInstant.extend({
- init:function(file) {
+ init: function (file) {
this._file = file;
return true;
},
- update:function(dt) {
+ update: function (dt) {
cc.audioEngine.playEffect(this._file);
}
});
cc.BuilderSoundEffect.create = function (file, pitch, pan, gain) {
var ret = new cc.BuilderSoundEffect();
if (ret && ret.init(file)) {
- return ret;
+ return ret;
}
return null;
};
-
+})();
diff --git a/extensions/ccb-reader/CCBReader.js b/extensions/ccb-reader/CCBReader.js
index d613575d0d..0baa27b4ca 100644
--- a/extensions/ccb-reader/CCBReader.js
+++ b/extensions/ccb-reader/CCBReader.js
@@ -102,58 +102,43 @@ var CCB_SIZETYPE_MULTIPLY_RESOLUTION = 5;
var CCB_SCALETYPE_ABSOLUTE = 0;
var CCB_SCALETYPE_MULTIPLY_RESOLUTION = 1;
-cc.BuilderFile = cc.Node.extend({
- _ccbFileNode:null,
-
- getCCBFileNode:function () {
- return this._ccbFileNode;
- },
- setCCBFileNode:function (node) {
- this._ccbFileNode = node;
- }
-});
-
-cc.BuilderFile.create = function () {
- return new cc.BuilderFile();
-};
-
/**
* Parse CCBI file which is generated by CocosBuilder
*/
cc.BuilderReader = cc.Class.extend({
- _jsControlled:false,
- _data:null,
- _ccbRootPath:"",
+ _jsControlled: false,
+ _data: null,
+ _ccbRootPath: "",
- _bytes:0,
- _currentByte:0,
- _currentBit:0,
+ _bytes: 0,
+ _currentByte: 0,
+ _currentBit: 0,
- _stringCache:null,
- _loadedSpriteSheets:null,
+ _stringCache: null,
+ _loadedSpriteSheets: null,
- _owner:null,
- _animationManager:null,
- _animationManagers:null,
- _animatedProps:null,
+ _owner: null,
+ _animationManager: null,
+ _animationManagers: null,
+ _animatedProps: null,
- _ccNodeLoaderLibrary:null,
- _ccNodeLoaderListener:null,
- _ccbMemberVariableAssigner:null,
- _ccbSelectorResolver:null,
+ _ccNodeLoaderLibrary: null,
+ _ccNodeLoaderListener: null,
+ _ccbMemberVariableAssigner: null,
+ _ccbSelectorResolver: null,
- _ownerOutletNames:null,
- _ownerOutletNodes:null,
- _nodesWithAnimationManagers:null,
- _animationManagerForNodes:null,
+ _ownerOutletNames: null,
+ _ownerOutletNodes: null,
+ _nodesWithAnimationManagers: null,
+ _animationManagerForNodes: null,
- _ownerCallbackNames:null,
- _ownerCallbackNodes:null,
- _ownerCallbackEvents:null,
+ _ownerCallbackNames: null,
+ _ownerCallbackNodes: null,
+ _ownerCallbackEvents: null,
- _readNodeGraphFromData:false,
+ _readNodeGraphFromData: false,
- ctor:function (ccNodeLoaderLibrary, ccbMemberVariableAssigner, ccbSelectorResolver, ccNodeLoaderListener) {
+ ctor: function (ccNodeLoaderLibrary, ccbMemberVariableAssigner, ccbSelectorResolver, ccNodeLoaderListener) {
this._stringCache = [];
this._loadedSpriteSheets = [];
this._currentBit = -1;
@@ -186,15 +171,15 @@ cc.BuilderReader = cc.Class.extend({
}
},
- getCCBRootPath:function () {
+ getCCBRootPath: function () {
return this._ccbRootPath;
},
- setCCBRootPath:function (rootPath) {
+ setCCBRootPath: function (rootPath) {
this._ccbRootPath = rootPath;
},
- initWithData:function (data, owner) {
+ initWithData: function (data, owner) {
//setup action manager
this._animationManager = new cc.BuilderAnimationManager();
@@ -213,7 +198,7 @@ cc.BuilderReader = cc.Class.extend({
return true;
},
- _loadBinarySync : function(url){
+ _loadBinarySync: function (url) {
var self = this;
var req = this.getXMLHttpRequest();
var errInfo = "load " + url + " failed!";
@@ -247,7 +232,7 @@ cc.BuilderReader = cc.Class.extend({
return arrayInfo;
},
- readNodeGraphFromFile:function (ccbFileName, owner, parentSize, animationManager) {
+ readNodeGraphFromFile: function (ccbFileName, owner, parentSize, animationManager) {
if (parentSize == null) {
parentSize = cc.director.getWinSize();
} else if (parentSize instanceof cc.BuilderAnimationManager) {
@@ -256,7 +241,7 @@ cc.BuilderReader = cc.Class.extend({
}
var data = cc.loader.getRes(ccbFileName);
- if(!data){
+ if (!data) {
var realUrl = cc.loader.getUrl(ccbFileName);
data = cc.loader.loadBinarySync(realUrl);
cc.loader.cache[ccbFileName] = data;
@@ -265,7 +250,7 @@ cc.BuilderReader = cc.Class.extend({
return this.readNodeGraphFromData(data, owner, parentSize, animationManager);
},
- readNodeGraphFromData:function (data, owner, parentSize) {
+ readNodeGraphFromData: function (data, owner, parentSize) {
this.initWithData(data, owner);
var locAnimationManager = this._animationManager;
locAnimationManager.setRootContainerSize(parentSize);
@@ -303,50 +288,68 @@ cc.BuilderReader = cc.Class.extend({
return nodeGraph;
},
- createSceneWithNodeGraphFromFile:function (ccbFileName, owner, parentSize, animationManager) {
+ createSceneWithNodeGraphFromFile: function (ccbFileName, owner, parentSize, animationManager) {
var node = this.readNodeGraphFromFile(ccbFileName, owner, parentSize, animationManager);
var scene = new cc.Scene();
scene.addChild(node);
return scene;
},
- getCCBMemberVariableAssigner:function () {
+ getCCBMemberVariableAssigner: function () {
return this._ccbMemberVariableAssigner;
},
- getCCBSelectorResolver:function () {
+ getCCBSelectorResolver: function () {
return this._ccbSelectorResolver;
},
- getAnimationManager:function () {
+ getAnimationManager: function () {
return this._animationManager;
},
- setAnimationManager:function (animationManager) {
+ setAnimationManager: function (animationManager) {
this._animationManager = animationManager;
},
- getAnimatedProperties:function () {
+ getAnimatedProperties: function () {
return this._animatedProps;
},
- getLoadedSpriteSheet:function () {
+ getLoadedSpriteSheet: function () {
return this._loadedSpriteSheets;
},
- getOwner:function () {
+ getOwner: function () {
return this._owner;
},
- readInt:function (signed) {
+ readInt: function (signed) {
var numBits = 0;
- while (!this._getBit()) {
+ var data = this._data[this._currentByte];
+ var bit = !!(data & (1 << this._currentBit++));
+ while (!bit) {
numBits++;
+ bit = !!(data & (1 << this._currentBit++));
+ if (this._currentBit >= 8) {
+ this._currentBit = 0;
+ this._currentByte++;
+ data = this._data[this._currentByte];
+ if (this._currentByte > this._data.length)
+ throw new Error("out of the data bound");
+ }
}
var current = 0;
for (var a = numBits - 1; a >= 0; a--) {
- if (this._getBit()) {
+ bit = !!(data & (1 << this._currentBit++));
+ if (this._currentBit >= 8) {
+ this._currentBit = 0;
+ this._currentByte++;
+ data = this._data[this._currentByte];
+ if (this._currentByte > this._data.length)
+ throw new Error("out of the data bound");
+ }
+ if (bit) {
current |= 1 << a;
}
}
@@ -364,23 +367,26 @@ cc.BuilderReader = cc.Class.extend({
num = current - 1;
}
- this._alignBits();
+ if (this._currentBit) {
+ this._currentBit = 0;
+ this._currentByte++;
+ }
return num;
},
- readByte:function () {
+ readByte: function () {
var byteValue = this._data[this._currentByte];
this._currentByte++;
return byteValue;
},
- readBool:function () {
- return (0 !== this.readByte());
+ readBool: function () {
+ return !!this._data[this._currentByte++];
},
- readFloat:function () {
- var type = this.readByte();
+ readFloat: function () {
+ var type = this._data[this._currentByte++];
switch (type) {
case CCB_FLOAT0:
@@ -403,10 +409,12 @@ cc.BuilderReader = cc.Class.extend({
}
},
- _decodeFloat:function (precisionBits, exponentBits) {
+ _decodeFloat: function (precisionBits, exponentBits) {
var length = precisionBits + exponentBits + 1;
var size = length >> 3;
- this._checkSize(length);
+ if (this._currentByte + size >= this._data.length) {
+ throw new Error("Index out of bound");
+ }
var bias = Math.pow(2, exponentBits - 1) - 1;
var signal = this._readBitsOnly(precisionBits + exponentBits, 1, size);
@@ -415,7 +423,7 @@ cc.BuilderReader = cc.Class.extend({
var divisor = 2;
var curByte = 0; //length + (-precisionBits >> 3) - 1;
do {
- var byteValue = this._readByteOnly(++curByte, size);
+ var byteValue = this._data[this._currentByte + size - (++curByte) - 1];
var startBit = precisionBits % 8 || 8;
var mask = 1 << startBit;
while (mask >>= 1) {
@@ -433,110 +441,102 @@ cc.BuilderReader = cc.Class.extend({
: Math.pow(2, exponent - bias) * (1 + significand) : 0);
},
- _readBitsOnly:function (start, length, size) {
+ _readBitsOnly: function (start, length, size) {
var offsetLeft = (start + length) % 8;
var offsetRight = start % 8;
var curByte = size - (start >> 3) - 1;
var lastByte = size + (-(start + length) >> 3);
var diff = curByte - lastByte;
- var sum = (this._readByteOnly(curByte, size) >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1);
+ var sum = (this._data[this._currentByte + size - curByte - 1] >> offsetRight) & ((1 << (diff ? 8 - offsetRight : length)) - 1);
if (diff && offsetLeft) {
- sum += (this._readByteOnly(lastByte++, size) & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight;
+ sum += (this._data[this._currentByte + size - lastByte - 1] & ((1 << offsetLeft) - 1)) << (diff-- << 3) - offsetRight;
+ lastByte++;
}
while (diff) {
- sum += this._shl(this._readByteOnly(lastByte++, size), (diff-- << 3) - offsetRight);
+ sum += this._shl(this._data[this._currentByte + size - lastByte - 1], (diff-- << 3) - offsetRight);
+ lastByte++;
}
return sum;
},
- _readByteOnly:function (i, size) {
- return this._data[this._currentByte + size - i - 1];
- },
-
- _shl:function (a, b) {
+ _shl: function (a, b) {
for (++b; --b; a = ((a %= 0x7fffffff + 1) & 0x40000000) === 0x40000000 ? a * 2 : (a - 0x40000000) * 2 + 0x7fffffff + 1);
return a;
},
- _checkSize:function (neededBits) {
- if (!(this._currentByte + Math.ceil(neededBits / 8) < this._data.length)) {
- throw new Error("Index out of bound");
- }
- },
-
- readCachedString:function () {
+ readCachedString: function () {
return this._stringCache[this.readInt(false)];
},
- isJSControlled:function () {
+ isJSControlled: function () {
return this._jsControlled;
},
- getOwnerCallbackNames:function () {
+ getOwnerCallbackNames: function () {
return this._ownerCallbackNames;
},
- getOwnerCallbackNodes:function () {
+ getOwnerCallbackNodes: function () {
return this._ownerCallbackNodes;
},
- getOwnerCallbackControlEvents:function(){
+ getOwnerCallbackControlEvents: function () {
return this._ownerCallbackEvents;
},
- getOwnerOutletNames:function () {
+ getOwnerOutletNames: function () {
return this._ownerOutletNames;
},
- getOwnerOutletNodes:function () {
+ getOwnerOutletNodes: function () {
return this._ownerOutletNodes;
},
- getNodesWithAnimationManagers:function () {
+ getNodesWithAnimationManagers: function () {
return this._nodesWithAnimationManagers;
},
- getAnimationManagersForNodes:function () {
+ getAnimationManagersForNodes: function () {
return this._animationManagerForNodes;
},
- getAnimationManagers:function () {
+ getAnimationManagers: function () {
return this._animationManagers;
},
- setAnimationManagers:function (animationManagers) {
+ setAnimationManagers: function (animationManagers) {
this._animationManagers = animationManagers;
},
- addOwnerCallbackName:function (name) {
- this._ownerCallbackNames.push(name)
+ addOwnerCallbackName: function (name) {
+ this._ownerCallbackNames.push(name);
},
- addOwnerCallbackNode:function (node) {
+ addOwnerCallbackNode: function (node) {
this._ownerCallbackNodes.push(node);
},
- addOwnerCallbackControlEvents:function(event){
+ addOwnerCallbackControlEvents: function (event) {
this._ownerCallbackEvents.push(event);
},
- addDocumentCallbackName:function (name) {
+ addDocumentCallbackName: function (name) {
this._animationManager.addDocumentCallbackName(name);
},
- addDocumentCallbackNode:function (node) {
+ addDocumentCallbackNode: function (node) {
this._animationManager.addDocumentCallbackNode(node);
},
- addDocumentCallbackControlEvents:function(controlEvents){
+ addDocumentCallbackControlEvents: function (controlEvents) {
this._animationManager.addDocumentCallbackControlEvents(controlEvents);
},
- readFileWithCleanUp:function (cleanUp) {
+ readFileWithCleanUp: function (cleanUp) {
if (!this._readHeader())
return null;
if (!this._readStringCache())
@@ -552,18 +552,18 @@ cc.BuilderReader = cc.Class.extend({
return node;
},
- addOwnerOutletName: function(name){
- this._ownerOutletNames.push(name);
+ addOwnerOutletName: function (name) {
+ this._ownerOutletNames.push(name);
},
- addOwnerOutletNode: function(node){
- if(node == null)
+ addOwnerOutletNode: function (node) {
+ if (node == null)
return;
this._ownerOutletNodes.push(node);
},
- _cleanUpNodeGraph:function (node) {
+ _cleanUpNodeGraph: function (node) {
node.userObject = null;
var getChildren = node.getChildren();
for (var i = 0, len = getChildren.length; i < len; i++) {
@@ -571,7 +571,7 @@ cc.BuilderReader = cc.Class.extend({
}
},
- _readCallbackKeyframesForSeq:function(seq) {
+ _readCallbackKeyframesForSeq: function (seq) {
var numKeyframes = this.readInt(false);
if (!numKeyframes)
@@ -584,14 +584,14 @@ cc.BuilderReader = cc.Class.extend({
var callbackName = this.readCachedString();
var callbackType = this.readInt(false);
- var value = [ callbackName, callbackType];
+ var value = [callbackName, callbackType];
var keyframe = new cc.BuilderKeyframe();
keyframe.setTime(time);
keyframe.setValue(value);
- if(locJsControlled)
- locAnimationManager.getKeyframeCallbacks().push(callbackType+":"+callbackName);
+ if (locJsControlled)
+ locAnimationManager.getKeyframeCallbacks().push(callbackType + ":" + callbackName);
locKeyframes.push(keyframe);
}
@@ -602,7 +602,7 @@ cc.BuilderReader = cc.Class.extend({
return true;
},
- _readSoundKeyframesForSeq:function(seq) {
+ _readSoundKeyframesForSeq: function (seq) {
var numKeyframes = this.readInt(false);
if (!numKeyframes)
@@ -617,7 +617,7 @@ cc.BuilderReader = cc.Class.extend({
var pan = this.readFloat();
var gain = this.readFloat();
- var value = [soundFile, pitch, pan, gain];
+ var value = [soundFile, pitch, pan, gain];
var keyframe = new cc.BuilderKeyframe();
keyframe.setTime(time);
keyframe.setValue(value);
@@ -629,7 +629,7 @@ cc.BuilderReader = cc.Class.extend({
seq.setSoundChannel(channel);
return true;
},
- _readSequences:function () {
+ _readSequences: function () {
var sequences = this._animationManager.getSequences();
var numSeqs = this.readInt(false);
for (var i = 0; i < numSeqs; i++) {
@@ -650,7 +650,7 @@ cc.BuilderReader = cc.Class.extend({
return true;
},
- readKeyframe:function (type) {
+ readKeyframe: function (type) {
var keyframe = new cc.BuilderKeyframe();
keyframe.setTime(this.readFloat());
var easingType = this.readInt(false);
@@ -670,12 +670,11 @@ cc.BuilderReader = cc.Class.extend({
keyframe.setEasingOpt(easingOpt);
if (type === CCB_PROPTYPE_CHECK) {
- value = this.readBool();
+ value = !!this._data[this._currentByte++];
} else if (type === CCB_PROPTYPE_BYTE) {
- value = this.readByte();
+ value = this._data[this._currentByte++];
} else if (type === CCB_PROPTYPE_COLOR3) {
- var c = cc.color(this.readByte(), this.readByte(), this.readByte());
- value = cc.Color3BWapper.create(c);
+ value = cc.color(this._data[this._currentByte++], this._data[this._currentByte++], this._data[this._currentByte++]);
} else if (type === CCB_PROPTYPE_FLOATXY) {
value = [this.readFloat(), this.readFloat()];
} else if (type === CCB_PROPTYPE_DEGREES) {
@@ -707,7 +706,7 @@ cc.BuilderReader = cc.Class.extend({
return keyframe;
},
- _readHeader:function () {
+ _readHeader: function () {
/* If no bytes loaded, don't crash about it. */
if (!this._data)
return false;
@@ -727,36 +726,36 @@ cc.BuilderReader = cc.Class.extend({
return false;
}
- this._jsControlled = this.readBool();
+ this._jsControlled = !!this._data[this._currentByte++];
this._animationManager._jsControlled = this._jsControlled;
// no need to set if it is "jscontrolled". It is obvious.
return true;
},
- _readStringFromBytes:function (startIndex, strLen, reverse) {
+ _readStringFromBytes: function (startIndex, strLen, reverse) {
reverse = reverse || false;
var strValue = "";
- var i, locData = this._data, locCurrentByte = this._currentByte;
+ var i, locData = this._data;
if (reverse) {
for (i = strLen - 1; i >= 0; i--)
- strValue += String.fromCharCode(locData[locCurrentByte + i]);
+ strValue += String.fromCharCode(locData[startIndex + i]);
} else {
for (i = 0; i < strLen; i++)
- strValue += String.fromCharCode(locData[locCurrentByte + i]);
+ strValue += String.fromCharCode(locData[startIndex + i]);
}
return strValue;
},
- _readStringCache:function () {
+ _readStringCache: function () {
var numStrings = this.readInt(false);
for (var i = 0; i < numStrings; i++)
this._readStringCacheEntry();
return true;
},
- _readStringCacheEntry:function () {
- var b0 = this.readByte();
- var b1 = this.readByte();
+ _readStringCacheEntry: function () {
+ var b0 = this._data[this._currentByte++];
+ var b1 = this._data[this._currentByte++];
var numBytes = b0 << 8 | b1;
@@ -772,7 +771,7 @@ cc.BuilderReader = cc.Class.extend({
this._stringCache.push(str);
},
- _readNodeGraph:function (parent) {
+ _readNodeGraph: function (parent) {
/* Read class name. */
var className = this.readCachedString();
@@ -838,9 +837,9 @@ cc.BuilderReader = cc.Class.extend({
ccNodeLoader.parseProperties(node, parent, this);
//handle sub ccb files(remove middle node)
- var isCCBFileNode = node instanceof cc.BuilderFile;
+ var isCCBFileNode = !!node.ccbFileNode;
if (isCCBFileNode) {
- var embeddedNode = node.getCCBFileNode();
+ var embeddedNode = node.ccbFileNode;
embeddedNode.setPosition(node.getPosition());
embeddedNode.setRotation(node.getRotation());
embeddedNode.setScaleX(node.getScaleX());
@@ -850,7 +849,7 @@ cc.BuilderReader = cc.Class.extend({
//embeddedNode.ignoreAnchorPointForPosition(node.isIgnoreAnchorPointForPosition());
locActionManager.moveAnimationsFromNode(node, embeddedNode);
- node.setCCBFileNode(null);
+ node.ccbFileNode = null;
node = embeddedNode;
}
var target = null, locMemberAssigner = null;
@@ -887,16 +886,16 @@ cc.BuilderReader = cc.Class.extend({
// Assign custom properties.
if (ccNodeLoader.getCustomProperties().length > 0) {
var customAssigned = false;
- if(!locJsControlled) {
+ if (!locJsControlled) {
target = node;
- if(target != null && target.onAssignCCBCustomProperty != null) {
+ if (target != null && target.onAssignCCBCustomProperty != null) {
var customProperties = ccNodeLoader.getCustomProperties();
var customPropKeys = customProperties.allKeys();
- for(i = 0;i < customPropKeys.length;i++){
+ for (i = 0; i < customPropKeys.length; i++) {
var customPropValue = customProperties.objectForKey(customPropKeys[i]);
customAssigned = target.onAssignCCBCustomProperty(target, customPropKeys[i], customPropValue);
locMemberAssigner = this._ccbMemberVariableAssigner;
- if(!customAssigned && (locMemberAssigner != null) && (locMemberAssigner.onAssignCCBCustomProperty != null))
+ if (!customAssigned && (locMemberAssigner != null) && (locMemberAssigner.onAssignCCBCustomProperty != null))
customAssigned = locMemberAssigner.onAssignCCBCustomProperty(target, customPropKeys[i], customPropValue);
}
}
@@ -926,32 +925,12 @@ cc.BuilderReader = cc.Class.extend({
return node;
},
- _getBit:function () {
- var bit = (this._data[this._currentByte] & (1 << this._currentBit)) !== 0;
- this._currentBit++;
-
- if (this._currentBit >= 8) {
- this._currentBit = 0;
- this._currentByte++;
- if(this._currentByte > this._data.length)
- throw new Error("out of the data bound");
- }
- return bit;
- },
-
- _alignBits:function () {
- if (this._currentBit) {
- this._currentBit = 0;
- this._currentByte++;
- }
- },
-
- _readUTF8:function () {
+ _readUTF8: function () {
}
});
cc.BuilderReader._ccbResolutionScale = 1;
-cc.BuilderReader.setResolutionScale = function(scale){
+cc.BuilderReader.setResolutionScale = function (scale) {
cc.BuilderReader._ccbResolutionScale = scale;
};
@@ -970,14 +949,14 @@ cc.BuilderReader.loadAsScene = function (ccbFilePath, owner, parentSize, ccbRoot
};
cc.BuilderReader._controllerClassCache = {};
-cc.BuilderReader.registerController = function(controllerName, controller){
+cc.BuilderReader.registerController = function (controllerName, controller) {
cc.BuilderReader._controllerClassCache[controllerName] = cc.Class.extend(controller);
};
cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) {
ccbRootPath = ccbRootPath || cc.BuilderReader.getResourcePath();
var reader = new cc.BuilderReader(cc.NodeLoaderLibrary.newDefaultCCNodeLoaderLibrary());
reader.setCCBRootPath(ccbRootPath);
- if((ccbFilePath.length < 5)||(ccbFilePath.toLowerCase().lastIndexOf(".ccbi") !== ccbFilePath.length - 5))
+ if ((ccbFilePath.length < 5) || (ccbFilePath.toLowerCase().lastIndexOf(".ccbi") !== ccbFilePath.length - 5))
ccbFilePath = ccbFilePath + ".ccbi";
var node = reader.readNodeGraphFromFile(ccbFilePath, owner, parentSize);
@@ -993,7 +972,7 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) {
callbackName = ownerCallbackNames[i];
callbackNode = ownerCallbackNodes[i];
callbackControlEvents = ownerCallbackControlEvents[i];
- if(callbackNode instanceof cc.ControlButton)
+ if (callbackNode instanceof cc.ControlButton)
callbackNode.addTargetWithActionForControlEvents(owner, owner[callbackName], callbackControlEvents); //register all type of events
else
callbackNode.setCallback(owner[callbackName], owner);
@@ -1011,7 +990,7 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) {
var nodesWithAnimationManagers = reader.getNodesWithAnimationManagers();
var animationManagersForNodes = reader.getAnimationManagersForNodes();
- if(!nodesWithAnimationManagers || !animationManagersForNodes)
+ if (!nodesWithAnimationManagers || !animationManagersForNodes)
return node;
var controllerClassCache = cc.BuilderReader._controllerClassCache;
@@ -1028,7 +1007,7 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) {
// Create a controller
var controllerClass = controllerClassCache[controllerName];
- if(!controllerClass) throw new Error("Can not find controller : " + controllerName);
+ if (!controllerClass) throw new Error("Can not find controller : " + controllerName);
var controller = new controllerClass();
controller.controllerName = controllerName;
@@ -1043,7 +1022,7 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) {
callbackName = documentCallbackNames[j];
callbackNode = documentCallbackNodes[j];
callbackControlEvents = documentCallbackControlEvents[j];
- if(callbackNode instanceof cc.ControlButton)
+ if (callbackNode instanceof cc.ControlButton)
callbackNode.addTargetWithActionForControlEvents(controller, controller[callbackName], callbackControlEvents); //register all type of events
else
callbackNode.setCallback(controller[callbackName], controller);
@@ -1069,7 +1048,7 @@ cc.BuilderReader.load = function (ccbFilePath, owner, parentSize, ccbRootPath) {
var callbackType = callbackSplit[0];
var kfCallbackName = callbackSplit[1];
- if (callbackType == 1){ // Document callback
+ if (callbackType == 1) { // Document callback
animationManager.setCallFunc(cc.callFunc(controller[kfCallbackName], controller), keyframeCallbacks[j]);
} else if (callbackType == 2 && owner) {// Owner callback
animationManager.setCallFunc(cc.callFunc(owner[kfCallbackName], owner), keyframeCallbacks[j]);
@@ -1123,4 +1102,4 @@ cc.BuilderReader.concat = function (stringA, stringB) {
return stringA + stringB;
};
-cc.loader.register(["ccbi"], cc._binaryLoader);
\ No newline at end of file
+cc.loader.register(["ccbi"], cc._binaryLoader);
diff --git a/extensions/ccb-reader/CCBReaderUtil.js b/extensions/ccb-reader/CCBReaderUtil.js
index d3ebcfa821..0de9c4fa30 100644
--- a/extensions/ccb-reader/CCBReaderUtil.js
+++ b/extensions/ccb-reader/CCBReaderUtil.js
@@ -25,17 +25,22 @@
****************************************************************************/
cc.NodeLoaderListener = cc.Class.extend({
- onNodeLoaded:function(node,nodeLoader){}
+ onNodeLoaded: function (node, nodeLoader) {
+ }
});
cc.BuilderSelectorResolver = cc.Class.extend({
- onResolveCCBCCMenuItemSelector:function(target, selectorName){},
- onResolveCCBCCCallFuncSelector:function(target, selectorName){},
- onResolveCCBCCControlSelector:function(target,selectorName){}
+ onResolveCCBCCMenuItemSelector: function (target, selectorName) {
+ },
+ onResolveCCBCCCallFuncSelector: function (target, selectorName) {
+ },
+ onResolveCCBCCControlSelector: function (target, selectorName) {
+ }
});
cc.BuilderScriptOwnerProtocol = cc.Class.extend({
- createNew:function(){}
+ createNew: function () {
+ }
});
cc.BuilderMemberVariableAssigner = cc.Class.extend({
@@ -47,7 +52,9 @@ cc.BuilderMemberVariableAssigner = cc.Class.extend({
* @param {cc.Node} node The member variable.
* @return {Boolean} Whether the assignment was successful.
*/
- onAssignCCBMemberVariable:function(target,memberVariableName, node){ return false;},
+ onAssignCCBMemberVariable: function (target, memberVariableName, node) {
+ return false;
+ },
/**
* The callback function of assigning custom properties.
@@ -57,5 +64,7 @@ cc.BuilderMemberVariableAssigner = cc.Class.extend({
* @param {*} value The value of the property.
* @return {Boolean} Whether the assignment was successful.
*/
- onAssignCCBCustomProperty:function(target, memberVariableName, value){ return false; }
+ onAssignCCBCustomProperty: function (target, memberVariableName, value) {
+ return false;
+ }
});
diff --git a/extensions/ccb-reader/CCBRelativePositioning.js b/extensions/ccb-reader/CCBRelativePositioning.js
index 2b2df87bef..ed0d29a255 100644
--- a/extensions/ccb-reader/CCBRelativePositioning.js
+++ b/extensions/ccb-reader/CCBRelativePositioning.js
@@ -24,40 +24,15 @@
THE SOFTWARE.
****************************************************************************/
-cc.getAbsolutePosition = function(pt, type, containerSize, propName){
- var absPt = cc.p(0,0);
- if(type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_LEFT)
- absPt = pt;
- else if(type === CCB_POSITIONTYPE_RELATIVE_TOP_LEFT){
- absPt.x = pt.x;
- absPt.y = containerSize.height - pt.y;
- } else if(type === CCB_POSITIONTYPE_RELATIVE_TOP_RIGHT){
- absPt.x = containerSize.width - pt.x;
- absPt.y = containerSize.height - pt.y;
- } else if (type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_RIGHT) {
- absPt.x = containerSize.width - pt.x;
- absPt.y = pt.y;
- } else if (type === CCB_POSITIONTYPE_PERCENT) {
- absPt.x = (containerSize.width * pt.x / 100.0);
- absPt.y = (containerSize.height * pt.y / 100.0);
- } else if (type === CCB_POSITIONTYPE_MULTIPLY_RESOLUTION) {
- var resolutionScale = cc.BuilderReader.getResolutionScale();
- absPt.x = pt.x * resolutionScale;
- absPt.y = pt.y * resolutionScale;
- }
-
- return absPt;
-};
-
-cc._getAbsolutePosition = function(x, y, type, containerSize, propName){
- var absPt = cc.p(0,0);
- if(type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_LEFT){
+cc.getAbsolutePosition = function (x, y, type, containerSize, propName, out) {
+ var absPt = out || cc.p(0, 0);
+ if (type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_LEFT) {
absPt.x = x;
absPt.y = y;
- } else if(type === CCB_POSITIONTYPE_RELATIVE_TOP_LEFT){
+ } else if (type === CCB_POSITIONTYPE_RELATIVE_TOP_LEFT) {
absPt.x = x;
absPt.y = containerSize.height - y;
- } else if(type === CCB_POSITIONTYPE_RELATIVE_TOP_RIGHT){
+ } else if (type === CCB_POSITIONTYPE_RELATIVE_TOP_RIGHT) {
absPt.x = containerSize.width - x;
absPt.y = containerSize.height - y;
} else if (type === CCB_POSITIONTYPE_RELATIVE_BOTTOM_RIGHT) {
@@ -74,8 +49,8 @@ cc._getAbsolutePosition = function(x, y, type, containerSize, propName){
return absPt;
};
-cc.setRelativeScale = function(node,scaleX, scaleY, type, propName){
- if(!node)
+cc.setRelativeScale = function (node, scaleX, scaleY, type, propName) {
+ if (!node)
throw new Error("cc.setRelativeScale(): node should be non-null");
if (type === CCB_POSITIONTYPE_MULTIPLY_RESOLUTION) {
@@ -85,6 +60,5 @@ cc.setRelativeScale = function(node,scaleX, scaleY, type, propName){
scaleY *= resolutionScale;
}
- node.setScaleX(scaleX);
- node.setScaleY(scaleY);
-};
\ No newline at end of file
+ node.setScale(scaleX, scaleY);
+};
diff --git a/extensions/ccb-reader/CCBValue.js b/extensions/ccb-reader/CCBValue.js
index 781c25d861..dee4c7ba71 100644
--- a/extensions/ccb-reader/CCBValue.js
+++ b/extensions/ccb-reader/CCBValue.js
@@ -34,43 +34,22 @@ cc.BOOL_VALUE = 3;
cc.UNSIGNEDCHAR_VALUE = 4;
-
-cc.Color3BWapper = cc.Class.extend({
- _color:null,
- ctor:function () {
- this._color = cc.color(0, 0, 0);
- },
- getColor:function () {
- return this._color;
- }
-});
-
-cc.Color3BWapper.create = function (color) {
- var ret = new cc.Color3BWapper();
- if (ret) {
- ret._color.r = color.r;
- ret._color.g = color.g;
- ret._color.b = color.b;
- }
- return ret;
-};
-
cc.BuilderValue = cc.Class.extend({
- _value:null,
- _type:0,
+ _value: null,
+ _type: 0,
- getIntValue:function () {
+ getIntValue: function () {
},
- getFloatValue:function () {
+ getFloatValue: function () {
},
- getBoolValue:function () {
+ getBoolValue: function () {
},
- getByteValue:function () {
+ getByteValue: function () {
},
- getPointer:function () {
+ getPointer: function () {
},
- getValue:function(){
+ getValue: function () {
return this._value;
}
});
diff --git a/extensions/ccb-reader/CCControlLoader.js b/extensions/ccb-reader/CCControlLoader.js
index 901f8509dd..3b1a5d6518 100644
--- a/extensions/ccb-reader/CCControlLoader.js
+++ b/extensions/ccb-reader/CCControlLoader.js
@@ -27,12 +27,14 @@
var PROPERTY_CCBFILE = "ccbFile";
cc.BuilderFileLoader = cc.NodeLoader.extend({
- _createCCNode:function (parent, ccbReader) {
- return cc.BuilderFile.create();
+ _createCCNode: function (parent, ccbReader) {
+ var node = new cc.Node();
+ node.ccbFileNode = null;
+ return node;
},
- onHandlePropTypeCCBFile:function (node, parent, propertyName, ccbFileNode, ccbReader) {
+ onHandlePropTypeCCBFile: function (node, parent, propertyName, ccbFileNode, ccbReader) {
if (propertyName === PROPERTY_CCBFILE) {
- node.setCCBFileNode(ccbFileNode);
+ node.ccbFileNode = ccbFileNode;
} else {
cc.NodeLoader.prototype.onHandlePropTypeCCBFile.call(this, node, parent, propertyName, ccbFileNode, ccbReader);
}
@@ -48,16 +50,16 @@ var PROPERTY_SELECTED = "selected";
var PROPERTY_CCCONTROL = "ccControl";
cc.ControlLoader = cc.NodeLoader.extend({
- _createCCNode:function (parent, ccbReander) {
+ _createCCNode: function (parent, ccbReander) {
},
- onHandlePropTypeBlockCCControl:function (node, parent, propertyName, blockCCControlData, ccbReader) {
+ onHandlePropTypeBlockCCControl: function (node, parent, propertyName, blockCCControlData, ccbReader) {
if (propertyName === PROPERTY_CCCONTROL) {
node.addTargetWithActionForControlEvents(blockCCControlData.target, blockCCControlData.selCCControlHandler, blockCCControlData.controlEvents);
} else {
cc.NodeLoader.prototype.onHandlePropTypeBlockCCControl.call(this, node, parent, propertyName, blockCCControlData, ccbReader);
}
},
- onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) {
+ onHandlePropTypeCheck: function (node, parent, propertyName, check, ccbReader) {
if (propertyName === PROPERTY_ENABLED) {
node.setEnabled(check);
} else if (propertyName === PROPERTY_SELECTED) {
@@ -88,18 +90,18 @@ var PROPERTY_BACKGROUNDSPRITEFRAME_HIGHLIGHTED = "backgroundSpriteFrame|2";
var PROPERTY_BACKGROUNDSPRITEFRAME_DISABLED = "backgroundSpriteFrame|3";
cc.ControlButtonLoader = cc.ControlLoader.extend({
- _createCCNode:function (parent, ccbReader) {
+ _createCCNode: function (parent, ccbReader) {
return new cc.ControlButton();
},
- onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) {
+ onHandlePropTypeCheck: function (node, parent, propertyName, check, ccbReader) {
if (propertyName === PROPERTY_ZOOMONTOUCHDOWN) {
- node.setZoomOnTouchDown(check);
+ node.zoomOnTouchDown = check;
} else {
cc.ControlLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader);
}
},
- onHandlePropTypeString:function (node, parent, propertyName, stringValue, ccbReader) {
+ onHandlePropTypeString: function (node, parent, propertyName, stringValue, ccbReader) {
if (propertyName === PROPERTY_TITLE_NORMAL) {
node.setTitleForState(stringValue, cc.CONTROL_STATE_NORMAL);
} else if (propertyName === PROPERTY_TITLE_HIGHLIGHTED) {
@@ -110,7 +112,7 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({
cc.ControlLoader.prototype.onHandlePropTypeString.call(this, node, parent, propertyName, stringValue, ccbReader);
}
},
- onHandlePropTypeFontTTF:function (node, parent, propertyName, fontTTF, ccbReader) {
+ onHandlePropTypeFontTTF: function (node, parent, propertyName, fontTTF, ccbReader) {
if (propertyName === PROPERTY_TITLETTF_NORMAL) {
node.setTitleTTFForState(fontTTF, cc.CONTROL_STATE_NORMAL);
} else if (propertyName === PROPERTY_TITLETTF_HIGHLIGHTED) {
@@ -121,7 +123,7 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({
cc.ControlLoader.prototype.onHandlePropTypeFontTTF.call(this, node, parent, propertyName, fontTTF, ccbReader);
}
},
- onHandlePropTypeFloatScale:function (node, parent, propertyName, floatScale, ccbReader) {
+ onHandlePropTypeFloatScale: function (node, parent, propertyName, floatScale, ccbReader) {
if (propertyName === PROPERTY_TITLETTFSIZE_NORMAL) {
node.setTitleTTFSizeForState(floatScale, cc.CONTROL_STATE_NORMAL);
} else if (propertyName === PROPERTY_TITLETTFSIZE_HIGHLIGHTED) {
@@ -132,21 +134,21 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({
cc.ControlLoader.prototype.onHandlePropTypeFloatScale.call(this, node, parent, propertyName, floatScale, ccbReader);
}
},
- onHandlePropTypePoint:function (node, parent, propertyName, point, ccbReader) {
+ onHandlePropTypePoint: function (node, parent, propertyName, point, ccbReader) {
if (propertyName === PROPERTY_LABELANCHORPOINT) {
node.setLabelAnchorPoint(point);
} else {
cc.ControlLoader.prototype.onHandlePropTypePoint.call(this, node, parent, propertyName, point, ccbReader);
}
},
- onHandlePropTypeSize:function (node, parent, propertyName, size, ccbReader) {
+ onHandlePropTypeSize: function (node, parent, propertyName, size, ccbReader) {
if (propertyName === PROPERTY_PREFEREDSIZE) {
node.setPreferredSize(size);
} else {
cc.ControlLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size, ccbReader);
}
},
- onHandlePropTypeSpriteFrame:function (node, parent, propertyName, spriteFrame, ccbReader) {
+ onHandlePropTypeSpriteFrame: function (node, parent, propertyName, spriteFrame, ccbReader) {
if (propertyName === PROPERTY_BACKGROUNDSPRITEFRAME_NORMAL) {
if (spriteFrame != null) {
node.setBackgroundSpriteFrameForState(spriteFrame, cc.CONTROL_STATE_NORMAL);
@@ -163,7 +165,7 @@ cc.ControlButtonLoader = cc.ControlLoader.extend({
cc.ControlLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, spriteFrame, ccbReader);
}
},
- onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
+ onHandlePropTypeColor3: function (node, parent, propertyName, ccColor3B, ccbReader) {
if (propertyName === PROPERTY_TITLECOLOR_NORMAL) {
node.setTitleColorForState(ccColor3B, cc.CONTROL_STATE_NORMAL);
} else if (propertyName === PROPERTY_TITLECOLOR_HIGHLIGHTED) {
@@ -187,19 +189,19 @@ var PROPERTY_BOUNCES = "bounces";
var PROPERTY_SCALE = "scale";
cc.ScrollViewLoader = cc.NodeLoader.extend({
- _createCCNode:function (parent, ccbReader) {
+ _createCCNode: function (parent, ccbReader) {
return new cc.ScrollView();
},
- onHandlePropTypeSize:function(node,parent,propertyName,size,ccbReader){
- if(propertyName === PROPERTY_CONTENTSIZE){
+ onHandlePropTypeSize: function (node, parent, propertyName, size, ccbReader) {
+ if (propertyName === PROPERTY_CONTENTSIZE) {
node.setViewSize(size);
- }else{
- cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node,parent,propertyName,size,ccbReader);
+ } else {
+ cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size, ccbReader);
}
},
- onHandlePropTypeCCBFile:function (node, parent, propertyName, ccbFileNode, ccbReader) {
+ onHandlePropTypeCCBFile: function (node, parent, propertyName, ccbFileNode, ccbReader) {
if (propertyName === PROPERTY_CONTAINER) {
node.setContainer(ccbFileNode);
node.updateInset();
@@ -207,7 +209,7 @@ cc.ScrollViewLoader = cc.NodeLoader.extend({
cc.NodeLoader.prototype.onHandlePropTypeCCBFile.call(this, node, parent, propertyName, ccbFileNode, ccbReader);
}
},
- onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) {
+ onHandlePropTypeCheck: function (node, parent, propertyName, check, ccbReader) {
if (propertyName === PROPERTY_CLIPSTOBOUNDS) {
node.setClippingToBounds(check);
} else if (propertyName === PROPERTY_BOUNCES) {
@@ -216,14 +218,14 @@ cc.ScrollViewLoader = cc.NodeLoader.extend({
cc.NodeLoader.prototype.onHandlePropTypeCheck.call(this, node, parent, propertyName, check, ccbReader);
}
},
- onHandlePropTypeFloat:function (node, parent, propertyName, floatValue, ccbReader) {
+ onHandlePropTypeFloat: function (node, parent, propertyName, floatValue, ccbReader) {
if (propertyName === PROPERTY_SCALE) {
node.setScale(floatValue);
} else {
cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue, ccbReader);
}
},
- onHandlePropTypeIntegerLabeled:function (node, parent, propertyName, integerLabeled, ccbReader) {
+ onHandlePropTypeIntegerLabeled: function (node, parent, propertyName, integerLabeled, ccbReader) {
if (propertyName === PROPERTY_DIRECTION) {
node.setDirection(integerLabeled);
} else {
@@ -242,12 +244,12 @@ var PROPERTY_COLOR = "color";
var PROPERTY_OPACITY = "opacity";
var PROPERTY_BLENDFUNC = "blendFunc";
var PROPERTY_INSETLEFT = "insetLeft";
-var PROPERTY_INSETTOP = "insetTop" ;
+var PROPERTY_INSETTOP = "insetTop";
var PROPERTY_INSETRIGHT = "insetRight";
var PROPERTY_INSETBOTTOM = "insetBottom";
cc.Scale9SpriteLoader = cc.NodeLoader.extend({
- _createCCNode:function(parent,ccbReader){
+ _createCCNode: function (parent, ccbReader) {
var sprite = new cc.Scale9Sprite();
sprite.setAnchorPoint(0, 0);
@@ -255,63 +257,63 @@ cc.Scale9SpriteLoader = cc.NodeLoader.extend({
return sprite;
},
- onHandlePropTypeColor3:function(node, parent, propertyName, ccColor3B,ccbReader){
- if(propertyName === PROPERTY_COLOR) {
- if(ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255){
+ onHandlePropTypeColor3: function (node, parent, propertyName, ccColor3B, ccbReader) {
+ if (propertyName === PROPERTY_COLOR) {
+ if (ccColor3B.r !== 255 || ccColor3B.g !== 255 || ccColor3B.b !== 255) {
node.setColor(ccColor3B);
}
} else {
- cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B,ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeColor3.call(this, node, parent, propertyName, ccColor3B, ccbReader);
}
},
- onHandlePropTypeByte:function(node, parent, propertyName, byteValue,ccbReader){
- if(propertyName === PROPERTY_OPACITY) {
+ onHandlePropTypeByte: function (node, parent, propertyName, byteValue, ccbReader) {
+ if (propertyName === PROPERTY_OPACITY) {
node.setOpacity(byteValue);
} else {
- cc.NodeLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue,ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeByte.call(this, node, parent, propertyName, byteValue, ccbReader);
}
},
- onHandlePropTypeBlendFunc:function(node, parent, propertyName, ccBlendFunc,ccbReader){
- if(propertyName === PROPERTY_BLENDFUNC) {
+ onHandlePropTypeBlendFunc: function (node, parent, propertyName, ccBlendFunc, ccbReader) {
+ if (propertyName === PROPERTY_BLENDFUNC) {
// TODO Not exported by CocosBuilder yet!
// node.setBlendFunc(ccBlendFunc);
} else {
- cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc,ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeBlendFunc.call(this, node, parent, propertyName, ccBlendFunc, ccbReader);
}
},
- onHandlePropTypeSpriteFrame:function(node, parent, propertyName, spriteFrame,ccbReader){
- if(propertyName === PROPERTY_SPRITEFRAME) {
+ onHandlePropTypeSpriteFrame: function (node, parent, propertyName, spriteFrame, ccbReader) {
+ if (propertyName === PROPERTY_SPRITEFRAME) {
node.setSpriteFrame(spriteFrame);
} else {
- cc.NodeLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, spriteFrame,ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeSpriteFrame.call(this, node, parent, propertyName, spriteFrame, ccbReader);
}
},
- onHandlePropTypeSize:function(node, parent, propertyName, size,ccbReader){
- if(propertyName === PROPERTY_CONTENTSIZE) {
+ onHandlePropTypeSize: function (node, parent, propertyName, size, ccbReader) {
+ if (propertyName === PROPERTY_CONTENTSIZE) {
//node.setContentSize(size);
- } else if(propertyName === PROPERTY_PREFEREDSIZE) {
+ } else if (propertyName === PROPERTY_PREFEREDSIZE) {
node.setPreferredSize(size);
} else {
- cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size,ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeSize.call(this, node, parent, propertyName, size, ccbReader);
}
},
- onHandlePropTypeFloat:function(node, parent, propertyName, floatValue,ccbReader){
- if(propertyName === PROPERTY_INSETLEFT) {
+ onHandlePropTypeFloat: function (node, parent, propertyName, floatValue, ccbReader) {
+ if (propertyName === PROPERTY_INSETLEFT) {
node.setInsetLeft(floatValue);
- } else if(propertyName === PROPERTY_INSETTOP) {
+ } else if (propertyName === PROPERTY_INSETTOP) {
node.setInsetTop(floatValue);
- } else if(propertyName === PROPERTY_INSETRIGHT) {
+ } else if (propertyName === PROPERTY_INSETRIGHT) {
node.setInsetRight(floatValue);
- } else if(propertyName === PROPERTY_INSETBOTTOM) {
+ } else if (propertyName === PROPERTY_INSETBOTTOM) {
node.setInsetBottom(floatValue);
} else {
- cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue,ccbReader);
+ cc.NodeLoader.prototype.onHandlePropTypeFloat.call(this, node, parent, propertyName, floatValue, ccbReader);
}
}
});
-cc.Scale9SpriteLoader.loader = function(){
- return new cc.Scale9SpriteLoader();
+cc.Scale9SpriteLoader.loader = function () {
+ return new cc.Scale9SpriteLoader();
};
diff --git a/extensions/ccb-reader/CCNodeLoader.js b/extensions/ccb-reader/CCNodeLoader.js
index 67b575f41a..afa434b4d2 100644
--- a/extensions/ccb-reader/CCNodeLoader.js
+++ b/extensions/ccb-reader/CCNodeLoader.js
@@ -54,19 +54,30 @@ function BlockCCControlData(selCCControlHandler, target, controlEvents) {
}
cc.NodeLoader = cc.Class.extend({
- _customProperties:null,
+ _customProperties: null,
+ _pt: null,
+ _size: null,
+ _arr2: null,
- ctor:function(){
+ ctor: function () {
this._customProperties = new cc._Dictionary();
+ this._pt = cc.p();
+ this._size = cc.size();
+ this._arr2 = new Array(2);
+ this._blockControlData = {
+ selCCControlHandler: null,
+ target: null,
+ controlEvents: null
+ };
},
- loadCCNode:function (parent, ccbReader) {
+ loadCCNode: function (parent, ccbReader) {
return this._createCCNode(parent, ccbReader);
//this.parseProperties(node, parent, ccbReader);
//return node;
},
- parseProperties:function (node, parent, ccbReader) {
+ parseProperties: function (node, parent, ccbReader) {
var numRegularProps = ccbReader.readInt(false);
var numExturaProps = ccbReader.readInt(false);
var propertyCount = numRegularProps + numExturaProps;
@@ -79,26 +90,26 @@ cc.NodeLoader = cc.Class.extend({
// Check if the property can be set for this platform
var setProp = false;
- var platform = ccbReader.readByte();
- if ((platform === CCB_PLATFORM_ALL) ||(platform === CCB_PLATFORM_IOS) ||(platform === CCB_PLATFORM_MAC) )
+ var platform = ccbReader._data[ccbReader._currentByte++];
+ if ((platform === CCB_PLATFORM_ALL) || (platform === CCB_PLATFORM_IOS) || (platform === CCB_PLATFORM_MAC))
setProp = true;
//forward properties for sub ccb files
- if(node instanceof cc.BuilderFile){
- if(node.getCCBFileNode() && isExtraProp){
- node = node.getCCBFileNode();
+ if (isExtraProp) {
+ if (node.ccbFileNode) {
+ node = node.ccbFileNode;
//skip properties that doesn't have a value to override
var getExtraPropsNames = node.userObject;
setProp = getExtraPropsNames.indexOf(propertyName) !== -1;
+ } else if (node === ccbReader._animationManager.getRootNode()) {
+ var extraPropsNames = node.userObject;
+ if (!extraPropsNames) {
+ extraPropsNames = [];
+ node.userObject = extraPropsNames;
+ }
+ extraPropsNames.push(propertyName);
}
- } else if(isExtraProp && node === ccbReader.getAnimationManager().getRootNode()){
- var extraPropsNames = node.userObject;
- if(!extraPropsNames){
- extraPropsNames = [];
- node.userObject = extraPropsNames;
- }
- extraPropsNames.push(propertyName);
- }
+ }
switch (type) {
case CCB_PROPTYPE_POSITION:
@@ -327,53 +338,52 @@ cc.NodeLoader = cc.Class.extend({
}
},
- getCustomProperties:function(){
+ getCustomProperties: function () {
return this._customProperties;
},
- _createCCNode:function (parent, ccbReader) {
+ _createCCNode: function (parent, ccbReader) {
return new cc.Node();
},
- parsePropTypePosition:function (node, parent, ccbReader, propertyName) {
+ parsePropTypePosition: function (node, parent, ccbReader, propertyName) {
var x = ccbReader.readFloat();
var y = ccbReader.readFloat();
var type = ccbReader.readInt(false);
- var containerSize = ccbReader.getAnimationManager().getContainerSize(parent);
- var pt = cc._getAbsolutePosition(x,y,type,containerSize,propertyName);
- node.setPosition(cc.getAbsolutePosition(pt,type,containerSize,propertyName)); //different to -x node.setPosition(pt);
+ // var containerSize = ccbReader._animationManager.getContainerSize(parent);
+ var containerSize = parent ? parent._contentSize : ccbReader._animationManager._rootContainerSize;
+ cc.getAbsolutePosition(x, y, type, containerSize, propertyName, this._pt);
+ node.setPosition(this._pt);
- if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
- var baseValue = [x,y,type];
- ccbReader.getAnimationManager().setBaseValue(baseValue,node,propertyName);
+ if (ccbReader._animatedProps.indexOf(propertyName) > -1) {
+ var baseValue = [x, y, type];
+ ccbReader._animationManager.setBaseValue(baseValue, node, propertyName);
}
-
- return pt;
+ return this._pt;
},
- parsePropTypePoint:function (node, parent, ccbReader) {
- var x = ccbReader.readFloat();
- var y = ccbReader.readFloat();
-
- return cc.p(x, y);
+ parsePropTypePoint: function (node, parent, ccbReader) {
+ this._pt.x = ccbReader.readFloat();
+ this._pt.y = ccbReader.readFloat();
+ return this._pt;
},
- parsePropTypePointLock:function (node, parent, ccbReader) {
- var x = ccbReader.readFloat();
- var y = ccbReader.readFloat();
-
- return cc.p(x, y);
+ parsePropTypePointLock: function (node, parent, ccbReader) {
+ this._pt.x = ccbReader.readFloat();
+ this._pt.y = ccbReader.readFloat();
+ return this._pt;
},
- parsePropTypeSize:function (node, parent, ccbReader) {
+ parsePropTypeSize: function (node, parent, ccbReader) {
var width = ccbReader.readFloat();
var height = ccbReader.readFloat();
var type = ccbReader.readInt(false);
- var containerSize = ccbReader.getAnimationManager().getContainerSize(parent);
+ // var containerSize = ccbReader._animationManager.getContainerSize(parent);
+ var containerSize = parent ? parent._contentSize : ccbReader._animationManager._rootContainerSize;
switch (type) {
case CCB_SIZETYPE_ABSOLUTE:
@@ -402,43 +412,46 @@ cc.NodeLoader = cc.Class.extend({
cc.log("Unknown CCB type.");
break;
}
-
- return cc.size(width, height);
+ this._size.width = width;
+ this._size.height = height;
+ return this._size;
},
- parsePropTypeScaleLock:function (node, parent, ccbReader, propertyName) {
+ parsePropTypeScaleLock: function (node, parent, ccbReader, propertyName) {
var x = ccbReader.readFloat();
var y = ccbReader.readFloat();
var type = ccbReader.readInt(false);
- cc.setRelativeScale(node,x,y,type,propertyName);
+ // cc.setRelativeScale(node, x, y, type, propertyName);
- if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
- ccbReader.getAnimationManager().setBaseValue([x,y,type],node,propertyName);
+ if (ccbReader._animatedProps.indexOf(propertyName) > -1) {
+ ccbReader._animationManager.setBaseValue([x, y, type], node, propertyName);
}
if (type === CCB_SCALETYPE_MULTIPLY_RESOLUTION) {
- x *= cc.BuilderReader.getResolutionScale();
- y *= cc.BuilderReader.getResolutionScale();
+ var resolutionScale = cc.BuilderReader.getResolutionScale();
+ x *= resolutionScale;
+ y *= resolutionScale;
}
-
- return [x, y];
+ this._pt.x = x;
+ this._pt.y = y;
+ return this._pt;
},
- parsePropTypeFloat:function (node, parent, ccbReader) {
+ parsePropTypeFloat: function (node, parent, ccbReader) {
return ccbReader.readFloat();
},
- parsePropTypeDegrees:function (node, parent, ccbReader, propertyName) {
- var ret = ccbReader.readFloat();
- if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
- ccbReader.getAnimationManager().setBaseValue(ret,node, propertyName);
+ parsePropTypeDegrees: function (node, parent, ccbReader, propertyName) {
+ var degrees = ccbReader.readFloat();
+ if (ccbReader._animatedProps.indexOf(propertyName) > -1) {
+ ccbReader._animationManager.setBaseValue(degrees, node, propertyName);
}
- return ret;
+ return degrees;
},
- parsePropTypeFloatScale:function (node, parent, ccbReader) {
+ parsePropTypeFloatScale: function (node, parent, ccbReader) {
var f = ccbReader.readFloat();
var type = ccbReader.readInt(false);
@@ -450,36 +463,36 @@ cc.NodeLoader = cc.Class.extend({
return f;
},
- parsePropTypeInteger:function (node, parent, ccbReader) {
+ parsePropTypeInteger: function (node, parent, ccbReader) {
return ccbReader.readInt(true);
},
- parsePropTypeIntegerLabeled:function (node, parent, ccbReader) {
+ parsePropTypeIntegerLabeled: function (node, parent, ccbReader) {
return ccbReader.readInt(true);
},
- parsePropTypeFloatVar:function (node, parent, ccbReader) {
- var f = ccbReader.readFloat();
- var fVar = ccbReader.readFloat();
- return [f, fVar];
+ parsePropTypeFloatVar: function (node, parent, ccbReader) {
+ this._arr2[0] = ccbReader.readFloat();
+ this._arr2[1] = ccbReader.readFloat();
+ return this._arr2;
},
- parsePropTypeCheck:function (node, parent, ccbReader, propertyName) {
- var ret = ccbReader.readBool();
- if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
- ccbReader.getAnimationManager().setBaseValue(ret,node, propertyName);
+ parsePropTypeCheck: function (node, parent, ccbReader, propertyName) {
+ var check = !!ccbReader._data[ccbReader._currentByte++];
+ if (ccbReader._animatedProps.indexOf(propertyName) > -1) {
+ ccbReader._animationManager.setBaseValue(check, node, propertyName);
}
- return ret;
+ return check;
},
- parsePropTypeSpriteFrame:function (node, parent, ccbReader, propertyName) {
+ parsePropTypeSpriteFrame: function (node, parent, ccbReader, propertyName) {
var spriteSheet = ccbReader.readCachedString();
- var spriteFile = ccbReader.readCachedString();
+ var spriteFile = ccbReader.readCachedString();
var spriteFrame;
- if(spriteFile != null && spriteFile.length !== 0){
- if(spriteSheet.length === 0){
- spriteFile = ccbReader.getCCBRootPath() + spriteFile;
+ if (spriteFile) {
+ if (spriteSheet.length === 0) {
+ spriteFile = ccbReader._ccbRootPath + spriteFile;
var texture = cc.textureCache.addImage(spriteFile);
var locContentSize = texture.getContentSize();
@@ -487,24 +500,24 @@ cc.NodeLoader = cc.Class.extend({
spriteFrame = new cc.SpriteFrame(texture, bounds);
} else {
var frameCache = cc.spriteFrameCache;
- spriteSheet = ccbReader.getCCBRootPath() + spriteSheet;
+ spriteSheet = ccbReader._ccbRootPath + spriteSheet;
//load the sprite sheet only if it is not loaded
- if(ccbReader.getLoadedSpriteSheet().indexOf(spriteSheet) === -1){
+ if (ccbReader._loadedSpriteSheets.indexOf(spriteSheet) === -1) {
frameCache.addSpriteFrames(spriteSheet);
- ccbReader.getLoadedSpriteSheet().push(spriteSheet);
+ ccbReader._loadedSpriteSheets.push(spriteSheet);
}
spriteFrame = frameCache.getSpriteFrame(spriteFile);
}
- if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
- ccbReader.getAnimationManager().setBaseValue(spriteFrame,node,propertyName);
+ if (ccbReader._animatedProps.indexOf(propertyName) > -1) {
+ ccbReader._animationManager.setBaseValue(spriteFrame, node, propertyName);
}
}
return spriteFrame;
},
- parsePropTypeAnimation:function (node, parent, ccbReader) {
- var animationFile = ccbReader.getCCBRootPath() + ccbReader.readCachedString();
+ parsePropTypeAnimation: function (node, parent, ccbReader) {
+ var animationFile = ccbReader._ccbRootPath + ccbReader.readCachedString();
var animation = ccbReader.readCachedString();
var ccAnimation = null;
@@ -517,7 +530,7 @@ cc.NodeLoader = cc.Class.extend({
animation = cc.BuilderReader.lastPathComponent(animation);
animationFile = cc.BuilderReader.lastPathComponent(animationFile);
- if (animation != null && animation !== "") {
+ if (animation) {
var animationCache = cc.animationCache;
animationCache.addAnimations(animationFile);
@@ -526,34 +539,34 @@ cc.NodeLoader = cc.Class.extend({
return ccAnimation;
},
- parsePropTypeTexture:function (node, parent, ccbReader) {
- var spriteFile = ccbReader.getCCBRootPath() + ccbReader.readCachedString();
+ parsePropTypeTexture: function (node, parent, ccbReader) {
+ var spriteFile = ccbReader._ccbRootPath + ccbReader.readCachedString();
- if(spriteFile !== "")
+ if (spriteFile)
return cc.textureCache.addImage(spriteFile);
return null;
},
- parsePropTypeByte:function (node, parent, ccbReader, propertyName) {
- var ret = ccbReader.readByte();
- if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
- ccbReader.getAnimationManager().setBaseValue(ret,node, propertyName);
+ parsePropTypeByte: function (node, parent, ccbReader, propertyName) {
+ var ret = ccbReader._data[ccbReader._currentByte++];
+ if (ccbReader._animatedProps.indexOf(propertyName) > -1) {
+ ccbReader._animationManager.setBaseValue(ret, node, propertyName);
}
return ret;
},
- parsePropTypeColor3:function (node, parent, ccbReader, propertyName) {
- var red = ccbReader.readByte();
- var green = ccbReader.readByte();
- var blue = ccbReader.readByte();
- var color = {r:red, g:green, b:blue };
- if(ccbReader.getAnimatedProperties().indexOf(propertyName) > -1){
- ccbReader.getAnimationManager().setBaseValue(cc.Color3BWapper.create(color),node, propertyName);
+ parsePropTypeColor3: function (node, parent, ccbReader, propertyName) {
+ var red = ccbReader._data[ccbReader._currentByte++];
+ var green = ccbReader._data[ccbReader._currentByte++];
+ var blue = ccbReader._data[ccbReader._currentByte++];
+ var color = cc.color(red, green, blue);
+ if (ccbReader._animatedProps.indexOf(propertyName) > -1) {
+ ccbReader._animationManager.setBaseValue(color, node, propertyName);
}
return color;
},
- parsePropTypeColor4FVar:function (node, parent, ccbReader) {
+ parsePropTypeColor4FVar: function (node, parent, ccbReader) {
//TODO Color4F doesn't supports on HTML5
var red = 0 | (ccbReader.readFloat() * 255);
var green = 0 | (ccbReader.readFloat() * 255);
@@ -566,40 +579,39 @@ cc.NodeLoader = cc.Class.extend({
var alphaVar = ccbReader.readFloat();
alphaVar = alphaVar <= 1 ? (0 | (alphaVar * 255)) : alphaVar;
- var colors = [];
- colors[0] = {r:red, g:green, b:blue, a:alpha};
- colors[1] = {r:redVar, g:greenVar, b:blueVar, a:alphaVar};
+ this._arr2[0] = {r: red, g: green, b: blue, a: alpha};
+ this._arr2[1] = {r: redVar, g: greenVar, b: blueVar, a: alphaVar};
- return colors;
+ return this._arr2;
},
- parsePropTypeFlip:function (node, parent, ccbReader) {
- var flipX = ccbReader.readBool();
- var flipY = ccbReader.readBool();
+ parsePropTypeFlip: function (node, parent, ccbReader) {
+ this._arr2[0] = !!ccbReader._data[ccbReader._currentByte++];
+ this._arr2[1] = !!ccbReader._data[ccbReader._currentByte++];
- return [flipX, flipY];
+ return this._arr2;
},
- parsePropTypeBlendFunc:function (node, parent, ccbReader) {
+ parsePropTypeBlendFunc: function (node, parent, ccbReader) {
var source = ccbReader.readInt(false);
var destination = ccbReader.readInt(false);
return new cc.BlendFunc(source, destination);
},
- parsePropTypeFntFile:function (node, parent, ccbReader) {
+ parsePropTypeFntFile: function (node, parent, ccbReader) {
return ccbReader.readCachedString();
},
- parsePropTypeString:function (node, parent, ccbReader) {
+ parsePropTypeString: function (node, parent, ccbReader) {
return ccbReader.readCachedString();
},
- parsePropTypeText:function (node, parent, ccbReader) {
+ parsePropTypeText: function (node, parent, ccbReader) {
return ccbReader.readCachedString();
},
- parsePropTypeFontTTF:function (node, parent, ccbReader) {
+ parsePropTypeFontTTF: function (node, parent, ccbReader) {
return ccbReader.readCachedString();
//var ttfEnding = ".ttf";
@@ -607,21 +619,21 @@ cc.NodeLoader = cc.Class.extend({
/* If the fontTTF comes with the ".ttf" extension, prepend the absolute path.
* System fonts come without the ".ttf" extension and do not need the path prepended. */
/*if (cc.CCBReader.endsWith(fontTTF.toLowerCase(), ttfEnding)) {
- fontTTF = ccbReader.getCCBRootPath() + fontTTF;
- }*/
+ fontTTF = ccbReader.getCCBRootPath() + fontTTF;
+ }*/
},
- parsePropTypeBlock:function (node, parent, ccbReader) {
+ parsePropTypeBlock: function (node, parent, ccbReader) {
var selectorName = ccbReader.readCachedString();
var selectorTarget = ccbReader.readInt(false);
if (selectorTarget !== CCB_TARGETTYPE_NONE) {
var target = null;
- if(!ccbReader.isJSControlled()) {
+ if (!ccbReader._jsControlled) {
if (selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT) {
- target = ccbReader.getAnimationManager().getRootNode();
+ target = ccbReader._animationManager._rootNode;
} else if (selectorTarget === CCB_TARGETTYPE_OWNER) {
- target = ccbReader.getOwner();
+ target = ccbReader._owner;
}
if (target !== null) {
@@ -633,15 +645,15 @@ cc.NodeLoader = cc.Class.extend({
selMenuHandler = target.onResolveCCBCCMenuItemSelector(target, selectorName);
if (selMenuHandler === 0) {
- var ccbSelectorResolver = ccbReader.getCCBSelectorResolver();
- if (ccbSelectorResolver != null)
+ var ccbSelectorResolver = ccbReader._ccbSelectorResolver;
+ if (ccbSelectorResolver)
selMenuHandler = ccbSelectorResolver.onResolveCCBCCMenuItemSelector(target, selectorName);
}
if (selMenuHandler === 0) {
- cc.log("Skipping selector '" +selectorName+ "' since no CCBSelectorResolver is present.");
+ cc.log("Skipping selector '" + selectorName + "' since no CCBSelectorResolver is present.");
} else {
- return new BlockData(selMenuHandler,target);
+ return new BlockData(selMenuHandler, target);
}
} else {
cc.log("Unexpected empty selector.");
@@ -650,7 +662,7 @@ cc.NodeLoader = cc.Class.extend({
cc.log("Unexpected NULL target for selector.");
}
} else {
- if(selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT){
+ if (selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT) {
ccbReader.addDocumentCallbackNode(node);
ccbReader.addDocumentCallbackName(selectorName);
ccbReader.addDocumentCallbackControlEvents(0);
@@ -664,18 +676,18 @@ cc.NodeLoader = cc.Class.extend({
return null;
},
- parsePropTypeBlockCCControl:function (node, parent, ccbReader) {
+ parsePropTypeBlockCCControl: function (node, parent, ccbReader) {
var selectorName = ccbReader.readCachedString();
var selectorTarget = ccbReader.readInt(false);
var controlEvents = ccbReader.readInt(false);
if (selectorTarget !== CCB_TARGETTYPE_NONE) {
- if(!ccbReader.isJSControlled()){
+ if (!ccbReader._jsControlled) {
var target = null;
if (selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT) {
- target = ccbReader.getAnimationManager().getRootNode();
+ target = ccbReader._animationManager._rootNode;
} else if (selectorTarget === CCB_TARGETTYPE_OWNER) {
- target = ccbReader.getOwner();
+ target = ccbReader._owner;
}
if (target !== null) {
@@ -686,7 +698,7 @@ cc.NodeLoader = cc.Class.extend({
selCCControlHandler = target.onResolveCCBCCControlSelector(target, selectorName);
}
if (selCCControlHandler === 0) {
- var ccbSelectorResolver = ccbReader.getCCBSelectorResolver();
+ var ccbSelectorResolver = ccbReader._ccbSelectorResolver;
if (ccbSelectorResolver != null) {
selCCControlHandler = ccbSelectorResolver.onResolveCCBCCControlSelector(target, selectorName);
}
@@ -695,7 +707,10 @@ cc.NodeLoader = cc.Class.extend({
if (selCCControlHandler === 0) {
cc.log("Skipping selector '" + selectorName + "' since no CCBSelectorResolver is present.");
} else {
- return new BlockCCControlData(selCCControlHandler,target,controlEvents);
+ this._blockControlData.selCCControlHandler = selCCControlHandler;
+ this._blockControlData.target = target;
+ this._blockControlData.controlEvents = controlEvents;
+ return this._blockControlData;
}
} else {
cc.log("Unexpected empty selector.");
@@ -704,7 +719,7 @@ cc.NodeLoader = cc.Class.extend({
cc.log("Unexpected NULL target for selector.");
}
} else {
- if(selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT){
+ if (selectorTarget === CCB_TARGETTYPE_DOCUMENTROOT) {
ccbReader.addDocumentCallbackNode(node);
ccbReader.addDocumentCallbackName(selectorName);
ccbReader.addDocumentCallbackControlEvents(controlEvents);
@@ -718,8 +733,8 @@ cc.NodeLoader = cc.Class.extend({
return null;
},
- parsePropTypeCCBFile:function (node, parent, ccbReader) {
- var ccbFileName = ccbReader.getCCBRootPath() + ccbReader.readCachedString();
+ parsePropTypeCCBFile: function (node, parent, ccbReader) {
+ var ccbFileName = ccbReader._ccbRootPath + ccbReader.readCachedString();
/* Change path extension to .ccbi. */
var ccbFileWithoutPathExtension = cc.BuilderReader.deletePathExtension(ccbFileName);
@@ -728,33 +743,34 @@ cc.NodeLoader = cc.Class.extend({
var myCCBReader = new cc.BuilderReader(ccbReader);
var bytes = cc.loader.getRes(ccbFileName);
- if(!bytes){
+ if (!bytes) {
var realUrl = cc.loader.getUrl(ccbFileName);
+ realUrl = hlddz.convertToDownloadURL(realUrl);
bytes = cc.loader.loadBinarySync(realUrl);
cc.loader.cache[ccbFileName] = bytes;
}
- myCCBReader.initWithData(bytes,ccbReader.getOwner());
- myCCBReader.getAnimationManager().setRootContainerSize(parent.getContentSize());
- myCCBReader.setAnimationManagers(ccbReader.getAnimationManagers());
+ myCCBReader.initWithData(bytes, ccbReader._owner);
+ myCCBReader._animationManager.setRootContainerSize(parent._contentSize);
+ myCCBReader.setAnimationManagers(ccbReader._animationManagers);
- myCCBReader.getAnimationManager().setOwner(ccbReader.getOwner());
+ myCCBReader._animationManager.setOwner(ccbReader._owner);
var ccbFileNode = myCCBReader.readFileWithCleanUp(false);
- ccbReader.setAnimationManagers(myCCBReader.getAnimationManagers());
+ ccbReader.setAnimationManagers(myCCBReader._animationManagers);
- if(ccbFileNode && myCCBReader.getAnimationManager().getAutoPlaySequenceId() !== -1)
- myCCBReader.getAnimationManager().runAnimations(myCCBReader.getAnimationManager().getAutoPlaySequenceId(),0);
+ if (ccbFileNode && myCCBReader._animationManager._autoPlaySequenceId !== -1)
+ myCCBReader._animationManager.runAnimations(myCCBReader._animationManager._autoPlaySequenceId, 0);
return ccbFileNode;
},
- parsePropTypeFloatXY:function(node, parent, ccbReader){
- var x = ccbReader.readFloat();
- var y = ccbReader.readFloat();
- return [x,y];
+ parsePropTypeFloatXY: function (node, parent, ccbReader) {
+ this._pt.x = ccbReader.readFloat();
+ this._pt.y = ccbReader.readFloat();
+ return this._pt;
},
- onHandlePropTypePosition:function (node, parent, propertyName, position, ccbReader) {
+ onHandlePropTypePosition: function (node, parent, propertyName, position, ccbReader) {
if (propertyName === PROPERTY_POSITION) {
node.setPosition(position);
} else {
@@ -762,7 +778,7 @@ cc.NodeLoader = cc.Class.extend({
}
},
- onHandlePropTypePoint:function (node, parent, propertyName, position, ccbReader) {
+ onHandlePropTypePoint: function (node, parent, propertyName, position, ccbReader) {
if (propertyName === PROPERTY_ANCHORPOINT) {
node.setAnchorPoint(position);
} else {
@@ -770,11 +786,11 @@ cc.NodeLoader = cc.Class.extend({
}
},
- onHandlePropTypePointLock:function (node, parent, propertyName, pointLock, ccbReader) {
+ onHandlePropTypePointLock: function (node, parent, propertyName, pointLock, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeSize:function (node, parent, propertyName, sizeValue, ccbReader) {
+ onHandlePropTypeSize: function (node, parent, propertyName, sizeValue, ccbReader) {
if (propertyName === PROPERTY_CONTENTSIZE) {
node.setContentSize(sizeValue);
} else {
@@ -782,35 +798,34 @@ cc.NodeLoader = cc.Class.extend({
}
},
- onHandlePropTypeScaleLock:function (node, parent, propertyName, scaleLock, ccbReader) {
+ onHandlePropTypeScaleLock: function (node, parent, propertyName, scaleLock, ccbReader) {
if (propertyName === PROPERTY_SCALE) {
- node.setScaleX(scaleLock[0]);
- node.setScaleY(scaleLock[1]);
+ node.setScale(scaleLock.x, scaleLock.y);
} else {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
}
},
onHandlePropTypeFloatXY: function (node, parent, propertyName, xy, ccbReader) {
if (propertyName === PROPERTY_SKEW) {
- node.setSkewX(xy[0]);
- node.setSkewY(xy[1]);
+ node._skewX = xy.x;
+ node._skewY = xy.y;
} else {
var nameX = propertyName + "X";
var nameY = propertyName + "Y";
if (!node[nameX] || !node[nameY])
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
//TODO throw an error when source code was confused
- node[nameX](xy[0]);
- node[nameY](xy[1]);
+ node[nameX](xy.x);
+ node[nameY](xy.y);
}
},
- onHandlePropTypeFloat:function (node, parent, propertyName, floatValue, ccbReader) {
+ onHandlePropTypeFloat: function (node, parent, propertyName, floatValue, ccbReader) {
//ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
// It may be a custom property, add it to custom property dictionary.
this._customProperties.setObject(floatValue, propertyName);
},
- onHandlePropTypeDegrees:function (node, parent, propertyName, degrees, ccbReader) {
+ onHandlePropTypeDegrees: function (node, parent, propertyName, degrees, ccbReader) {
if (propertyName === PROPERTY_ROTATION) {
node.setRotation(degrees);
} else {
@@ -818,83 +833,83 @@ cc.NodeLoader = cc.Class.extend({
}
},
- onHandlePropTypeFloatScale:function (node, parent, propertyName, floatScale, ccbReader) {
+ onHandlePropTypeFloatScale: function (node, parent, propertyName, floatScale, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeInteger:function (node, parent, propertyName, integer, ccbReader) {
+ onHandlePropTypeInteger: function (node, parent, propertyName, integer, ccbReader) {
if (propertyName === PROPERTY_TAG) {
- node.setTag(integer);
+ node.tag = integer;
} else {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
}
},
- onHandlePropTypeIntegerLabeled:function (node, parent, propertyName, integerLabeled, ccbReader) {
+ onHandlePropTypeIntegerLabeled: function (node, parent, propertyName, integerLabeled, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeFloatVar:function (node, parent, propertyName, floatVar, ccbReader) {
+ onHandlePropTypeFloatVar: function (node, parent, propertyName, floatVar, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeCheck:function (node, parent, propertyName, check, ccbReader) {
+ onHandlePropTypeCheck: function (node, parent, propertyName, check, ccbReader) {
if (propertyName === PROPERTY_VISIBLE) {
- node.setVisible(check);
+ node._visible = check;
} else if (propertyName === PROPERTY_IGNOREANCHORPOINTFORPOSITION) {
- node.ignoreAnchorPointForPosition(check);
+ node._ignoreAnchorPointForPosition = check;
} else {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
}
},
- onHandlePropTypeSpriteFrame:function (node, parent, propertyName, spriteFrame, ccbReader) {
+ onHandlePropTypeSpriteFrame: function (node, parent, propertyName, spriteFrame, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeAnimation:function (node, parent, propertyName, ccAnimation, ccbReader) {
+ onHandlePropTypeAnimation: function (node, parent, propertyName, ccAnimation, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeTexture:function (node, parent, propertyName, ccTexture2D, ccbReader) {
+ onHandlePropTypeTexture: function (node, parent, propertyName, ccTexture2D, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeByte:function (node, parent, propertyName, byteValue, ccbReader) {
+ onHandlePropTypeByte: function (node, parent, propertyName, byteValue, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeColor3:function (node, parent, propertyName, ccColor3B, ccbReader) {
+ onHandlePropTypeColor3: function (node, parent, propertyName, ccColor3B, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeColor4FVar:function (node, parent, propertyName, ccColor4FVar, ccbReader) {
+ onHandlePropTypeColor4FVar: function (node, parent, propertyName, ccColor4FVar, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeFlip:function (node, parent, propertyName, flip, ccbReader) {
+ onHandlePropTypeFlip: function (node, parent, propertyName, flip, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeBlendFunc:function (node, parent, propertyName, ccBlendFunc, ccbReader) {
+ onHandlePropTypeBlendFunc: function (node, parent, propertyName, ccBlendFunc, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeFntFile:function (node, parent, propertyName, fntFile, ccbReader) {
+ onHandlePropTypeFntFile: function (node, parent, propertyName, fntFile, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeString:function (node, parent, propertyName, strValue, ccbReader) {
+ onHandlePropTypeString: function (node, parent, propertyName, strValue, ccbReader) {
//ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
// It may be a custom property, add it to custom property dictionary.
this._customProperties.setObject(strValue, propertyName);
},
- onHandlePropTypeText:function (node, parent, propertyName, textValue, ccbReader) {
+ onHandlePropTypeText: function (node, parent, propertyName, textValue, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeFontTTF:function (node, parent, propertyName, fontTTF, ccbReader) {
+ onHandlePropTypeFontTTF: function (node, parent, propertyName, fontTTF, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeBlock:function (node, parent, propertyName, blockData, ccbReader) {
+ onHandlePropTypeBlock: function (node, parent, propertyName, blockData, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeBlockCCControl:function (node, parent, propertyName, blockCCControlData, ccbReader) {
+ onHandlePropTypeBlockCCControl: function (node, parent, propertyName, blockCCControlData, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
},
- onHandlePropTypeCCBFile:function (node, parent, propertyName, ccbFileNode, ccbReader) {
+ onHandlePropTypeCCBFile: function (node, parent, propertyName, ccbFileNode, ccbReader) {
ASSERT_FAIL_UNEXPECTED_PROPERTY(propertyName);
}
});
diff --git a/extensions/ccpool/CCPool.js b/extensions/ccpool/CCPool.js
index 489ae1d9c6..2159c091c8 100644
--- a/extensions/ccpool/CCPool.js
+++ b/extensions/ccpool/CCPool.js
@@ -62,7 +62,7 @@ cc.pool = /** @lends cc.pool# */{
putInPool: function (obj) {
var pid = obj.constructor.prototype['__pid'];
if (!pid) {
- var desc = { writable: true, enumerable: false, configurable: true };
+ var desc = {writable: true, enumerable: false, configurable: true};
desc.value = ClassManager.getNewID();
Object.defineProperty(obj.constructor.prototype, '__pid', desc);
}
@@ -143,4 +143,4 @@ cc.pool = /** @lends cc.pool# */{
}
this._pool = {};
}
-};
\ No newline at end of file
+};
diff --git a/extensions/ccui/base-classes/CCProtectedNode.js b/extensions/ccui/base-classes/CCProtectedNode.js
index 8407e7e633..1925572fa5 100644
--- a/extensions/ccui/base-classes/CCProtectedNode.js
+++ b/extensions/ccui/base-classes/CCProtectedNode.js
@@ -31,7 +31,7 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
_protectedChildren: null,
_reorderProtectedChildDirty: false,
- _insertProtectedChild: function(child, z){
+ _insertProtectedChild: function (child, z) {
this._reorderProtectedChildDirty = true;
this._protectedChildren.push(child);
child._setLocalZOrder(z);
@@ -41,11 +41,71 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
* @function
*/
- ctor: function(){
+ ctor: function () {
cc.Node.prototype.ctor.call(this);
this._protectedChildren = [];
},
+ visit: function (parent) {
+ var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null;
+
+ // quick return if not visible
+ if (!this._visible) {
+ cmd._propagateFlagsDown(parentCmd);
+ return;
+ }
+
+ var renderer = cc.renderer;
+ var i, children = this._children, len = children.length, child;
+ var j, pChildren = this._protectedChildren, pLen = pChildren.length, pChild;
+
+ cmd.visit(parentCmd);
+
+ var locGrid = this.grid;
+ if (locGrid && locGrid._active)
+ locGrid.beforeDraw();
+
+ if (this._reorderChildDirty) this.sortAllChildren();
+ if (this._reorderProtectedChildDirty) this.sortAllProtectedChildren();
+
+ // draw children zOrder < 0
+ for (i = 0; i < len; i++) {
+ child = children[i];
+ if (child._localZOrder < 0) {
+ child.visit(this);
+ }
+ else {
+ break;
+ }
+ }
+ for (j = 0; j < pLen; j++) {
+ pChild = pChildren[j];
+ if (pChild && pChild._localZOrder < 0) {
+ cmd._changeProtectedChild(pChild);
+ pChild.visit(this);
+ }
+ else
+ break;
+ }
+
+ renderer.pushRenderCommand(cmd);
+
+ for (; i < len; i++) {
+ children[i].visit(this);
+ }
+ for (; j < pLen; j++) {
+ pChild = pChildren[j];
+ if (!pChild) continue;
+ cmd._changeProtectedChild(pChild);
+ pChild.visit(this);
+ }
+
+ if (locGrid && locGrid._active)
+ locGrid.afterDraw(this);
+
+ cmd._dirtyFlag = 0;
+ },
+
/**
*
* Adds a child to the container with z order and tag
@@ -55,25 +115,25 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
* @param {Number} [localZOrder] Z order for drawing priority. Please refer to `setLocalZOrder(int)`
* @param {Number} [tag] An integer to identify the node easily. Please refer to `setTag(int)`
*/
- addProtectedChild: function(child, localZOrder, tag){
- cc.assert(child != null, "child must be non-nil");
- cc.assert(!child.parent, "child already added. It can't be added again");
+ addProtectedChild: function (child, localZOrder, tag) {
+ cc.assert(child != null, "child must be non-nil");
+ cc.assert(!child.parent, "child already added. It can't be added again");
localZOrder = localZOrder || child.getLocalZOrder();
- if(tag)
+ if (tag)
child.setTag(tag);
this._insertProtectedChild(child, localZOrder);
child.setParent(this);
child.setOrderOfArrival(cc.s_globalOrderOfArrival);
- if(this._running){
- child.onEnter();
+ if (this._running) {
+ child._performRecursive(cc.Node._stateCallbackType.onEnter);
// prevent onEnterTransitionDidFinish to be called twice when a node is added in onEnter
- if(this._isTransitionFinished)
- child.onEnterTransitionDidFinish();
+ if (this._isTransitionFinished)
+ child._performRecursive(cc.Node._stateCallbackType.onEnterTransitionDidFinish);
}
- if(this._cascadeColorEnabled)
+ if (this._cascadeColorEnabled)
this._renderCmd.setCascadeColorEnabledDirty();
if (this._cascadeOpacityEnabled)
this._renderCmd.setCascadeOpacityEnabledDirty();
@@ -84,11 +144,11 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
* @param {Number} tag An identifier to find the child node.
* @return {cc.Node} a Node object whose tag equals to the input parameter
*/
- getProtectedChildByTag: function(tag){
+ getProtectedChildByTag: function (tag) {
cc.assert(tag !== cc.NODE_TAG_INVALID, "Invalid tag");
var locChildren = this._protectedChildren;
- for(var i = 0, len = locChildren.length; i < len; i++)
- if(locChildren.getTag() === tag)
+ for (var i = 0, len = locChildren.length; i < len; i++)
+ if (locChildren.getTag() === tag)
return locChildren[i];
return null;
},
@@ -98,23 +158,23 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
* @param {cc.Node} child The child node which will be removed.
* @param {Boolean} [cleanup=true] true if all running actions and callbacks on the child node will be cleanup, false otherwise.
*/
- removeProtectedChild: function(child, cleanup){
- if(cleanup == null)
+ removeProtectedChild: function (child, cleanup) {
+ if (cleanup == null)
cleanup = true;
- var locChildren = this._protectedChildren;
- if(locChildren.length === 0)
+ var locChildren = this._protectedChildren;
+ if (locChildren.length === 0)
return;
var idx = locChildren.indexOf(child);
- if(idx > -1){
- if(this._running){
- child.onExitTransitionDidStart();
- child.onExit();
- }
+ if (idx > -1) {
+ if (this._running) {
+ child._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart);
+ child._performRecursive(cc.Node._stateCallbackType.onExit);
+ }
// If you don't do cleanup, the child's actions will not get removed and the
// its scheduledSelectors_ dict will not get released!
if (cleanup)
- child.cleanup();
+ child._performRecursive(cc.Node._stateCallbackType.cleanup);
// set parent nil at the end
child.setParent(null);
@@ -128,10 +188,10 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
* @param {Number} tag
* @param {Boolean} [cleanup=true]
*/
- removeProtectedChildByTag: function(tag, cleanup){
- cc.assert( tag !== cc.NODE_TAG_INVALID, "Invalid tag");
+ removeProtectedChildByTag: function (tag, cleanup) {
+ cc.assert(tag !== cc.NODE_TAG_INVALID, "Invalid tag");
- if(cleanup == null)
+ if (cleanup == null)
cleanup = true;
var child = this.getProtectedChildByTag(tag);
@@ -146,7 +206,7 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
* Removes all children from the container with a cleanup.
* @see cc.ProtectedNode#removeAllProtectedChildrenWithCleanup
*/
- removeAllProtectedChildren: function(){
+ removeAllProtectedChildren: function () {
this.removeAllProtectedChildrenWithCleanup(true);
},
@@ -154,23 +214,23 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
* Removes all children from the container, and do a cleanup to all running actions depending on the cleanup parameter.
* @param {Boolean} [cleanup=true] true if all running actions on all children nodes should be cleanup, false otherwise.
*/
- removeAllProtectedChildrenWithCleanup: function(cleanup){
- if(cleanup == null)
+ removeAllProtectedChildrenWithCleanup: function (cleanup) {
+ if (cleanup == null)
cleanup = true;
var locChildren = this._protectedChildren;
// not using detachChild improves speed here
- for (var i = 0, len = locChildren.length; i< len; i++) {
+ for (var i = 0, len = locChildren.length; i < len; i++) {
var child = locChildren[i];
// IMPORTANT:
// -1st do onExit
// -2nd cleanup
- if(this._running){
- child.onExitTransitionDidStart();
- child.onExit();
+ if (this._running) {
+ child._performRecursive(cc.Node._stateCallbackType.onExitTransitionDidStart);
+ child._performRecursive(cc.Node._stateCallbackType.onExit);
}
if (cleanup)
- child.cleanup();
+ child._performRecursive(cc.Node._stateCallbackType.cleanup);
// set parent nil at the end
child.setParent(null);
}
@@ -182,8 +242,8 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
* @param {cc.Node} child An already added child node. It MUST be already added.
* @param {Number} localZOrder Z order for drawing priority. Please refer to setLocalZOrder(int)
*/
- reorderProtectedChild: function(child, localZOrder){
- cc.assert( child != null, "Child must be non-nil");
+ reorderProtectedChild: function (child, localZOrder) {
+ cc.assert(child != null, "Child must be non-nil");
this._reorderProtectedChildDirty = true;
child.setOrderOfArrival(cc.s_globalOrderOfArrival++);
child._setLocalZOrder(localZOrder);
@@ -196,27 +256,27 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
* @note Don't call this manually unless a child added needs to be removed in the same frame
*
*/
- sortAllProtectedChildren: function(){
+ sortAllProtectedChildren: function () {
if (this._reorderProtectedChildDirty) {
var _children = this._protectedChildren;
// insertion sort
- var len = _children.length, i, j, tmp;
- for(i=1; i= 0){
- if(tmp._localZOrder < _children[j]._localZOrder){
- _children[j+1] = _children[j];
- }else if(tmp._localZOrder === _children[j]._localZOrder && tmp.arrivalOrder < _children[j].arrivalOrder){
- _children[j+1] = _children[j];
- }else
+ while (j >= 0) {
+ if (tmp._localZOrder < _children[j]._localZOrder) {
+ _children[j + 1] = _children[j];
+ } else if (tmp._localZOrder === _children[j]._localZOrder && tmp.arrivalOrder < _children[j].arrivalOrder) {
+ _children[j + 1] = _children[j];
+ } else
break;
j--;
}
- _children[j+1] = tmp;
+ _children[j + 1] = tmp;
}
//don't need to check children recursively, that's done in visit of each child
@@ -224,71 +284,11 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
}
},
- _changePosition: function(){},
-
- /**
- * Stops itself and its children and protected children's all running actions and schedulers
- * @override
- */
- cleanup: function(){
- cc.Node.prototype.cleanup.call(this);
- var locChildren = this._protectedChildren;
- for(var i = 0 , len = locChildren.length; i < len; i++)
- locChildren[i].cleanup();
- },
-
- /**
- * Calls its parent's onEnter and calls its protected children's onEnter
- * @override
- */
- onEnter: function(){
- cc.Node.prototype.onEnter.call(this);
- var locChildren = this._protectedChildren;
- for(var i = 0, len = locChildren.length;i< len;i++)
- locChildren[i].onEnter();
- },
-
- /**
- *
- * Event callback that is invoked when the Node enters in the 'stage'.
- * If the Node enters the 'stage' with a transition, this event is called when the transition finishes.
- * If you override onEnterTransitionDidFinish, you shall call its parent's one, e.g. Node::onEnterTransitionDidFinish()
- *
- * @override
- */
- onEnterTransitionDidFinish: function(){
- cc.Node.prototype.onEnterTransitionDidFinish.call(this);
- var locChildren = this._protectedChildren;
- for(var i = 0, len = locChildren.length;i< len;i++)
- locChildren[i].onEnterTransitionDidFinish();
- },
-
- /**
- * Calls its parent's onExit and calls its protected children's onExit
- * @override
- */
- onExit:function(){
- cc.Node.prototype.onExit.call(this);
- var locChildren = this._protectedChildren;
- for(var i = 0, len = locChildren.length;i< len;i++)
- locChildren[i].onExit();
- },
-
- /**
- *
- * Event callback that is called every time the Node leaves the 'stage'.
- * If the Node leaves the 'stage' with a transition, this callback is called when the transition starts.
- *
- */
- onExitTransitionDidStart: function(){
- cc.Node.prototype.onExitTransitionDidStart.call(this);
- var locChildren = this._protectedChildren;
- for(var i = 0, len = locChildren.length;i< len;i++)
- locChildren[i].onExitTransitionDidStart();
+ _changePosition: function () {
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return new cc.ProtectedNode.CanvasRenderCmd(this);
else
return new cc.ProtectedNode.WebGLRenderCmd(this);
@@ -300,6 +300,6 @@ cc.ProtectedNode = cc.Node.extend(/** @lends cc.ProtectedNode# */{
* @deprecated since v3.0, please use new cc.ProtectedNode() instead.
* @return cc.ProtectedNode
*/
-cc.ProtectedNode.create = function(){
+cc.ProtectedNode.create = function () {
return new cc.ProtectedNode();
-};
\ No newline at end of file
+};
diff --git a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js
index 1e36802e0d..1ae8b1e62e 100644
--- a/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js
+++ b/extensions/ccui/base-classes/CCProtectedNodeCanvasRenderCmd.js
@@ -22,7 +22,7 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
+(function () {
cc.ProtectedNode.RenderCmd = {
_updateDisplayColor: function (parentColor) {
var node = this._node;
@@ -55,16 +55,16 @@
selChildren = node._children;
for (i = 0, len = selChildren.length; i < len; i++) {
item = selChildren[i];
- if (item && item._renderCmd){
+ if (item && item._renderCmd) {
item._renderCmd._updateDisplayColor(locDispColor);
item._renderCmd._updateColor();
}
}
}
selChildren = node._protectedChildren;
- for(i = 0, len = selChildren.length;i < len; i++){
+ for (i = 0, len = selChildren.length; i < len; i++) {
item = selChildren[i];
- if(item && item._renderCmd){
+ if (item && item._renderCmd) {
item._renderCmd._updateDisplayColor(locDispColor);
item._renderCmd._updateColor();
}
@@ -97,16 +97,16 @@
selChildren = node._children;
for (i = 0, len = selChildren.length; i < len; i++) {
item = selChildren[i];
- if (item && item._renderCmd){
+ if (item && item._renderCmd) {
item._renderCmd._updateDisplayOpacity(this._displayedOpacity);
item._renderCmd._updateColor();
}
}
}
selChildren = node._protectedChildren;
- for(i = 0, len = selChildren.length;i < len; i++){
+ for (i = 0, len = selChildren.length; i < len; i++) {
item = selChildren[i];
- if(item && item._renderCmd){
+ if (item && item._renderCmd) {
item._renderCmd._updateDisplayOpacity(this._displayedOpacity);
item._renderCmd._updateColor();
}
@@ -139,7 +139,7 @@
};
cc.ProtectedNode.CanvasRenderCmd = function (renderable) {
- cc.Node.CanvasRenderCmd.call(this, renderable);
+ this._rootCtor(renderable);
this._cachedParent = null;
this._cacheDirty = false;
};
@@ -147,74 +147,23 @@
var proto = cc.ProtectedNode.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
cc.inject(cc.ProtectedNode.RenderCmd, proto);
proto.constructor = cc.ProtectedNode.CanvasRenderCmd;
+ proto._pNodeCmdCtor = cc.ProtectedNode.CanvasRenderCmd;
- proto.visit = function(parentCmd){
- var node = this._node;
- // quick return if not visible
- if (!node._visible)
- return;
-
- //visit for canvas
- var i, j;
- var children = node._children, child;
- var locChildren = node._children, locProtectedChildren = node._protectedChildren;
- var childLen = locChildren.length, pLen = locProtectedChildren.length;
-
- this._syncStatus(parentCmd);
-
- node.sortAllChildren();
- node.sortAllProtectedChildren();
-
- var pChild;
- // draw children zOrder < 0
- for (i = 0; i < childLen; i++) {
- child = children[i];
- if (child._localZOrder < 0)
- child.visit(this);
- else
- break;
- }
- for (j = 0; j < pLen; j++) {
- pChild = locProtectedChildren[j];
- if (pChild && pChild._localZOrder < 0){
- this._changeProtectedChild(pChild);
- pChild.visit(this);
- }
- else
- break;
- }
-
- cc.renderer.pushRenderCommand(this);
-
- for (; i < childLen; i++)
- children[i] && children[i].visit(this);
- for (; j < pLen; j++){
- pChild = locProtectedChildren[j];
- if(!pChild) continue;
- this._changeProtectedChild(pChild);
- pChild.visit(this);
- }
-
- this._dirtyFlag = 0;
- this._cacheDirty = false;
- };
-
- proto.transform = function(parentCmd, recursive){
+ proto.transform = function (parentCmd, recursive) {
var node = this._node;
- if(node._changePosition)
+ if (node._changePosition)
node._changePosition();
this.originTransform(parentCmd, recursive);
var i, len, locChildren = node._protectedChildren;
- if(recursive && locChildren && locChildren.length !== 0){
- for(i = 0, len = locChildren.length; i< len; i++){
+ if (recursive && locChildren && locChildren.length !== 0) {
+ for (i = 0, len = locChildren.length; i < len; i++) {
locChildren[i]._renderCmd.transform(this, recursive);
}
}
};
- proto.pNodeVisit = proto.visit;
proto.pNodeTransform = proto.transform;
-})();
\ No newline at end of file
+})();
diff --git a/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js b/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js
index 6640c7cf9b..b22907d383 100644
--- a/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js
+++ b/extensions/ccui/base-classes/CCProtectedNodeWebGLRenderCmd.js
@@ -22,83 +22,29 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- if(!cc.Node.WebGLRenderCmd)
+(function () {
+ if (!cc.Node.WebGLRenderCmd)
return;
cc.ProtectedNode.WebGLRenderCmd = function (renderable) {
- cc.Node.WebGLRenderCmd.call(this, renderable);
+ this._rootCtor(renderable);
};
var proto = cc.ProtectedNode.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
cc.inject(cc.ProtectedNode.RenderCmd, proto);
proto.constructor = cc.ProtectedNode.WebGLRenderCmd;
+ proto._pNodeCmdCtor = cc.ProtectedNode.WebGLRenderCmd;
- proto.visit = function(parentCmd){
- var node = this._node;
- // quick return if not visible
- if (!node._visible)
- return;
- var i, j;
-
- this._syncStatus(parentCmd);
-
- var locGrid = node.grid;
- if (locGrid && locGrid._active)
- locGrid.beforeDraw();
-
- var locChildren = node._children, locProtectedChildren = node._protectedChildren;
- var childLen = locChildren.length, pLen = locProtectedChildren.length;
- node.sortAllChildren();
- node.sortAllProtectedChildren();
-
- var pChild;
- // draw children zOrder < 0
- for (i = 0; i < childLen; i++) {
- if (locChildren[i] && locChildren[i]._localZOrder < 0)
- locChildren[i].visit(this);
- else
- break;
- }
- for(j = 0; j < pLen; j++){
- pChild = locProtectedChildren[j];
- if (pChild && pChild._localZOrder < 0){
- this._changeProtectedChild(pChild);
- pChild.visit(this);
- }else
- break;
- }
-
- cc.renderer.pushRenderCommand(this);
-
- // draw children zOrder >= 0
- for (; i < childLen; i++) {
- locChildren[i] && locChildren[i].visit(this);
- }
- for (; j < pLen; j++) {
- pChild = locProtectedChildren[j];
- if(!pChild) continue;
- this._changeProtectedChild(pChild);
- pChild.visit(this);
- }
-
- if (locGrid && locGrid._active)
- locGrid.afterDraw(node);
-
- this._dirtyFlag = 0;
- };
-
- proto.transform = function(parentCmd, recursive){
+ proto.transform = function (parentCmd, recursive) {
this.originTransform(parentCmd, recursive);
var i, len,
locChildren = this._node._protectedChildren;
- if(recursive && locChildren && locChildren.length !== 0){
- for(i = 0, len = locChildren.length; i< len; i++){
+ if (recursive && locChildren && locChildren.length !== 0) {
+ for (i = 0, len = locChildren.length; i < len; i++) {
locChildren[i]._renderCmd.transform(this, recursive);
}
}
};
- proto.pNodeVisit = proto.visit;
proto.pNodeTransform = proto.transform;
-})();
\ No newline at end of file
+})();
diff --git a/extensions/ccui/base-classes/UIScale9Sprite.js b/extensions/ccui/base-classes/UIScale9Sprite.js
index dcb9215268..95df94cbc7 100644
--- a/extensions/ccui/base-classes/UIScale9Sprite.js
+++ b/extensions/ccui/base-classes/UIScale9Sprite.js
@@ -1,8 +1,11 @@
+/* global ccui */
+
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
Copyright (c) 2012 Neofect. All rights reserved.
+ Copyright (c) 2016 zilongshanren. All rights reserved.
http://www.cocos2d-x.org
@@ -26,6 +29,297 @@
Created by Jung Sang-Taik on 2012-03-16
****************************************************************************/
+(function () {
+
+var dataPool = {
+ _pool: {},
+ _lengths: [],
+ put: function (data) {
+ var length = data.length;
+ if (!this._pool[length]) {
+ this._pool[length] = [data];
+ this._lengths.push(length);
+ this._lengths.sort();
+ }
+ else {
+ this._pool[length].push(data);
+ }
+ },
+ get: function (length) {
+ var id;
+ for (var i = 0; i < this._lengths.length; i++) {
+ if (this._lengths[i] >= length) {
+ id = this._lengths[i];
+ break;
+ }
+ }
+ if (id) {
+ return this._pool[id].pop();
+ }
+ else {
+ return undefined;
+ }
+ }
+};
+
+var FIX_ARTIFACTS_BY_STRECHING_TEXEL = cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL, cornerId = [], webgl;
+
+
+var simpleQuadGenerator = {
+ _rebuildQuads_base: function (sprite, spriteFrame, contentSize, isTrimmedContentSize) {
+ //build vertices
+ var vertices = sprite._vertices,
+ wt = sprite._renderCmd._worldTransform,
+ l, b, r, t;
+ if (isTrimmedContentSize) {
+ l = 0;
+ b = 0;
+ r = contentSize.width;
+ t = contentSize.height;
+ } else {
+ var originalSize = spriteFrame._originalSize;
+ var rect = spriteFrame._rect;
+ var offset = spriteFrame._offset;
+ var scaleX = contentSize.width / originalSize.width;
+ var scaleY = contentSize.height / originalSize.height;
+ var trimmLeft = offset.x + (originalSize.width - rect.width) / 2;
+ var trimmRight = offset.x - (originalSize.width - rect.width) / 2;
+ var trimmedBottom = offset.y + (originalSize.height - rect.height) / 2;
+ var trimmedTop = offset.y - (originalSize.height - rect.height) / 2;
+
+ l = trimmLeft * scaleX;
+ b = trimmedBottom * scaleY;
+ r = contentSize.width + trimmRight * scaleX;
+ t = contentSize.height + trimmedTop * scaleY;
+ }
+
+ if (vertices.length < 8) {
+ dataPool.put(vertices);
+ vertices = dataPool.get(8) || new Float32Array(8);
+ sprite._vertices = vertices;
+ }
+ // bl, br, tl, tr
+ if (webgl) {
+ vertices[0] = l * wt.a + b * wt.c + wt.tx;
+ vertices[1] = l * wt.b + b * wt.d + wt.ty;
+ vertices[2] = r * wt.a + b * wt.c + wt.tx;
+ vertices[3] = r * wt.b + b * wt.d + wt.ty;
+ vertices[4] = l * wt.a + t * wt.c + wt.tx;
+ vertices[5] = l * wt.b + t * wt.d + wt.ty;
+ vertices[6] = r * wt.a + t * wt.c + wt.tx;
+ vertices[7] = r * wt.b + t * wt.d + wt.ty;
+ }
+ else {
+ vertices[0] = l;
+ vertices[1] = b;
+ vertices[2] = r;
+ vertices[3] = b;
+ vertices[4] = l;
+ vertices[5] = t;
+ vertices[6] = r;
+ vertices[7] = t;
+ }
+
+ cornerId[0] = 0;
+ cornerId[1] = 2;
+ cornerId[2] = 4;
+ cornerId[3] = 6;
+
+ //build uvs
+ if (sprite._uvsDirty) {
+ this._calculateUVs(sprite, spriteFrame);
+ }
+
+ sprite._vertCount = 4;
+ },
+
+ _calculateUVs: function (sprite, spriteFrame) {
+ var uvs = sprite._uvs;
+ var atlasWidth = spriteFrame._texture._pixelsWide;
+ var atlasHeight = spriteFrame._texture._pixelsHigh;
+ var textureRect = spriteFrame._rect;
+ textureRect = cc.rectPointsToPixels(textureRect);
+
+ if (uvs.length < 8) {
+ dataPool.put(uvs);
+ uvs = dataPool.get(8) || new Float32Array(8);
+ sprite._uvs = uvs;
+ }
+
+ //uv computation should take spritesheet into account.
+ var l, b, r, t;
+ var texelCorrect = FIX_ARTIFACTS_BY_STRECHING_TEXEL ? 0.5 : 0;
+
+ if (spriteFrame._rotated) {
+ l = (textureRect.x + texelCorrect) / atlasWidth;
+ b = (textureRect.y + textureRect.width - texelCorrect) / atlasHeight;
+ r = (textureRect.x + textureRect.height - texelCorrect) / atlasWidth;
+ t = (textureRect.y + texelCorrect) / atlasHeight;
+ uvs[0] = l; uvs[1] = t;
+ uvs[2] = l; uvs[3] = b;
+ uvs[4] = r; uvs[5] = t;
+ uvs[6] = r; uvs[7] = b;
+ }
+ else {
+ l = (textureRect.x + texelCorrect) / atlasWidth;
+ b = (textureRect.y + textureRect.height - texelCorrect) / atlasHeight;
+ r = (textureRect.x + textureRect.width - texelCorrect) / atlasWidth;
+ t = (textureRect.y + texelCorrect) / atlasHeight;
+ uvs[0] = l; uvs[1] = b;
+ uvs[2] = r; uvs[3] = b;
+ uvs[4] = l; uvs[5] = t;
+ uvs[6] = r; uvs[7] = t;
+ }
+ }
+};
+
+var scale9QuadGenerator = {
+ x: new Array(4),
+ y: new Array(4),
+ _rebuildQuads_base: function (sprite, spriteFrame, contentSize, insetLeft, insetRight, insetTop, insetBottom) {
+ //build vertices
+ var vertices = sprite._vertices;
+ var wt = sprite._renderCmd._worldTransform;
+ var leftWidth, centerWidth, rightWidth;
+ var topHeight, centerHeight, bottomHeight;
+ var rect = spriteFrame._rect;
+
+ leftWidth = insetLeft;
+ rightWidth = insetRight;
+ centerWidth = rect.width - leftWidth - rightWidth;
+ topHeight = insetTop;
+ bottomHeight = insetBottom;
+ centerHeight = rect.height - topHeight - bottomHeight;
+
+ var preferSize = contentSize;
+ var sizableWidth = preferSize.width - leftWidth - rightWidth;
+ var sizableHeight = preferSize.height - topHeight - bottomHeight;
+ var xScale = preferSize.width / (leftWidth + rightWidth);
+ var yScale = preferSize.height / (topHeight + bottomHeight);
+ xScale = xScale > 1 ? 1 : xScale;
+ yScale = yScale > 1 ? 1 : yScale;
+ sizableWidth = sizableWidth < 0 ? 0 : sizableWidth;
+ sizableHeight = sizableHeight < 0 ? 0 : sizableHeight;
+ var x = this.x;
+ var y = this.y;
+ x[0] = 0;
+ x[1] = leftWidth * xScale;
+ x[2] = x[1] + sizableWidth;
+ x[3] = preferSize.width;
+ y[0] = 0;
+ y[1] = bottomHeight * yScale;
+ y[2] = y[1] + sizableHeight;
+ y[3] = preferSize.height;
+
+ if (vertices.length < 32) {
+ dataPool.put(vertices);
+ vertices = dataPool.get(32) || new Float32Array(32);
+ sprite._vertices = vertices;
+ }
+ var offset = 0, row, col;
+ if (webgl) {
+ for (row = 0; row < 4; row++) {
+ for (col = 0; col < 4; col++) {
+ vertices[offset] = x[col] * wt.a + y[row] * wt.c + wt.tx;
+ vertices[offset+1] = x[col] * wt.b + y[row] * wt.d + wt.ty;
+ offset += 2;
+ }
+ }
+ }
+ else {
+ for (row = 0; row < 4; row++) {
+ for (col = 0; col < 4; col++) {
+ vertices[offset] = x[col];
+ vertices[offset+1] = y[row];
+ offset += 2;
+ }
+ }
+ }
+
+ cornerId[0] = 0;
+ cornerId[1] = 6;
+ cornerId[2] = 24;
+ cornerId[3] = 30;
+
+ //build uvs
+ if (sprite._uvsDirty) {
+ this._calculateUVs(sprite, spriteFrame, insetLeft, insetRight, insetTop, insetBottom);
+ }
+ },
+
+ _calculateUVs: function (sprite, spriteFrame, insetLeft, insetRight, insetTop, insetBottom) {
+ var uvs = sprite._uvs;
+ var rect = spriteFrame._rect;
+ var atlasWidth = spriteFrame._texture._pixelsWide;
+ var atlasHeight = spriteFrame._texture._pixelsHigh;
+
+ //caculate texture coordinate
+ var leftWidth, centerWidth, rightWidth;
+ var topHeight, centerHeight, bottomHeight;
+ var textureRect = spriteFrame._rect;
+ textureRect = cc.rectPointsToPixels(textureRect);
+ rect = cc.rectPointsToPixels(rect);
+ var scale = cc.contentScaleFactor();
+
+ leftWidth = insetLeft * scale;
+ rightWidth = insetRight * scale;
+ centerWidth = rect.width - leftWidth - rightWidth;
+ topHeight = insetTop * scale;
+ bottomHeight = insetBottom * scale;
+ centerHeight = rect.height - topHeight - bottomHeight;
+
+ if (uvs.length < 32) {
+ dataPool.put(uvs);
+ uvs = dataPool.get(32) || new Float32Array(32);
+ sprite._uvs = uvs;
+ }
+
+ //uv computation should take spritesheet into account.
+ var u = this.x;
+ var v = this.y;
+ var texelCorrect = FIX_ARTIFACTS_BY_STRECHING_TEXEL ? 0.5 : 0;
+ var offset = 0, row, col;
+
+ if (spriteFrame._rotated) {
+ u[0] = (textureRect.x + texelCorrect) / atlasWidth;
+ u[1] = (bottomHeight + textureRect.x) / atlasWidth;
+ u[2] = (bottomHeight + centerHeight + textureRect.x) / atlasWidth;
+ u[3] = (textureRect.x + textureRect.height - texelCorrect) / atlasWidth;
+
+ v[3] = (textureRect.y + texelCorrect) / atlasHeight;
+ v[2] = (leftWidth + textureRect.y) / atlasHeight;
+ v[1] = (leftWidth + centerWidth + textureRect.y) / atlasHeight;
+ v[0] = (textureRect.y + textureRect.width - texelCorrect) / atlasHeight;
+
+ for (row = 0; row < 4; row++) {
+ for (col = 0; col < 4; col++) {
+ uvs[offset] = u[row];
+ uvs[offset+1] = v[3-col];
+ offset += 2;
+ }
+ }
+ }
+ else {
+ u[0] = (textureRect.x + texelCorrect) / atlasWidth;
+ u[1] = (leftWidth + textureRect.x) / atlasWidth;
+ u[2] = (leftWidth + centerWidth + textureRect.x) / atlasWidth;
+ u[3] = (textureRect.x + textureRect.width - texelCorrect) / atlasWidth;
+
+ v[3] = (textureRect.y + texelCorrect) / atlasHeight;
+ v[2] = (topHeight + textureRect.y) / atlasHeight;
+ v[1] = (topHeight + centerHeight + textureRect.y) / atlasHeight;
+ v[0] = (textureRect.y + textureRect.height - texelCorrect) / atlasHeight;
+
+ for (row = 0; row < 4; row++) {
+ for (col = 0; col < 4; col++) {
+ uvs[offset] = u[col];
+ uvs[offset+1] = v[row];
+ offset += 2;
+ }
+ }
+ }
+ }
+};
/**
*
@@ -35,7 +329,6 @@
* to specific areas of a sprite. With 9-slice scaling (3x3 grid),
* you can ensure that the sprite does not become distorted when
* scaled.
- * @note: it will refactor in v3.1
* @see http://yannickloriot.com/library/ios/cccontrolextension/Classes/CCScale9Sprite.html
*
* @class
@@ -50,161 +343,41 @@
*/
ccui.Scale9Sprite = cc.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprite# */{
- _spriteRect: null,
- _capInsetsInternal: null,
- _positionsAreDirty: false,
-
+ //resource data, could be async loaded.
+ _spriteFrame: null,
_scale9Image: null,
- _topLeft: null,
- _top: null,
- _topRight: null,
- _left: null,
- _centre: null,
- _right: null,
- _bottomLeft: null,
- _bottom: null,
- _bottomRight: null,
-
- _scale9Enabled: true,
- _brightState: 0,
- _renderers: null,
- _opacityModifyRGB: false,
-
- _originalSize: null,
- _preferredSize: null,
- _opacity: 0,
- _color: null,
- _capInsets: null,
+ //scale 9 data
_insetLeft: 0,
- _insetTop: 0,
_insetRight: 0,
+ _insetTop: 0,
_insetBottom: 0,
-
- _spriteFrameRotated: false,
- _textureLoaded:false,
- _className:"Scale9Sprite",
+ //blend function
+ _blendFunc: null,
+ //sliced or simple
+ _renderingType: 1,
+ //bright or not
+ _brightState: 0,
+ _opacityModifyRGB: false,
+ //rendering quads shared by canvas and webgl
+ _rawVerts: null,
+ _rawUvs: null,
+ _vertices: null,
+ _uvs: null,
+ _vertCount: 0,
+ _quadsDirty: true,
+ _uvsDirty: true,
+ _isTriangle: false,
+ _isTrimmedContentSize: false,
+ _textureLoaded: false,
//v3.3
_flippedX: false,
_flippedY: false,
+ _className: "Scale9Sprite",
/**
- * return texture is loaded
- * @returns {boolean}
- */
- textureLoaded:function(){
- return this._textureLoaded;
- },
-
- /**
- * add texture loaded event listener
- * @param {Function} callback
- * @param {Object} target
- * @deprecated since 3.1, please use addEventListener instead
- */
- addLoadedEventListener:function(callback, target){
- this.addEventListener("load", callback, target);
- },
-
- _updateCapInset: function () {
- var insets, locInsetLeft = this._insetLeft, locInsetTop = this._insetTop, locInsetRight = this._insetRight;
- var locSpriteRect = this._spriteRect, locInsetBottom = this._insetBottom;
- if (locInsetLeft === 0 && locInsetTop === 0 && locInsetRight === 0 && locInsetBottom === 0) {
- insets = cc.rect(0, 0, 0, 0);
- } else {
- insets = this._spriteFrameRotated ? cc.rect(locInsetBottom, locInsetLeft,
- locSpriteRect.width - locInsetRight - locInsetLeft,
- locSpriteRect.height - locInsetTop - locInsetBottom) :
- cc.rect(locInsetLeft, locInsetTop,
- locSpriteRect.width - locInsetLeft - locInsetRight,
- locSpriteRect.height - locInsetTop - locInsetBottom);
- }
- this.setCapInsets(insets);
- },
-
- _updatePositions: function () {
- // Check that instances are non-NULL
- if (!((this._topLeft) && (this._topRight) && (this._bottomRight) &&
- (this._bottomLeft) && (this._centre))) {
- // if any of the above sprites are NULL, return
- return;
- }
-
- var size = this._contentSize;
- var locTopLeft = this._topLeft, locTopRight = this._topRight, locBottomRight = this._bottomRight, locBottomLeft = this._bottomLeft;
- var locLeft = this._left, locRight = this._right, locTop = this._top, locBottom = this._bottom;
- var locCenter = this._centre, locCenterContentSize = this._centre.getContentSize();
- var locTopLeftContentSize = locTopLeft.getContentSize();
- var locBottomLeftContentSize = locBottomLeft.getContentSize();
-
- var sizableWidth = size.width - locTopLeftContentSize.width - locTopRight.getContentSize().width;
- var sizableHeight = size.height - locTopLeftContentSize.height - locBottomRight.getContentSize().height;
-
- var horizontalScale = sizableWidth / locCenterContentSize.width;
- var verticalScale = sizableHeight / locCenterContentSize.height;
-
- var rescaledWidth = locCenterContentSize.width * horizontalScale;
- var rescaledHeight = locCenterContentSize.height * verticalScale;
-
- var leftWidth = locBottomLeftContentSize.width;
- var bottomHeight = locBottomLeftContentSize.height;
- var centerOffset = cc.p(this._offset.x * horizontalScale, this._offset.y*verticalScale);
-
- if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
- //browser is in canvas mode, need to manually control rounding to prevent overlapping pixels
- var roundedRescaledWidth = Math.round(rescaledWidth);
- if (rescaledWidth !== roundedRescaledWidth) {
- rescaledWidth = roundedRescaledWidth;
- horizontalScale = rescaledWidth / locCenterContentSize.width;
- }
- var roundedRescaledHeight = Math.round(rescaledHeight);
- if (rescaledHeight !== roundedRescaledHeight) {
- rescaledHeight = roundedRescaledHeight;
- verticalScale = rescaledHeight / locCenterContentSize.height;
- }
- }
-
- locCenter.setScaleX(horizontalScale);
- locCenter.setScaleY(verticalScale);
-
- locBottomLeft.setAnchorPoint(1, 1);
- locBottomLeft.setPosition(leftWidth,bottomHeight);
-
- locBottomRight.setAnchorPoint(0, 1);
- locBottomRight.setPosition(leftWidth+rescaledWidth,bottomHeight);
-
-
- locTopLeft.setAnchorPoint(1, 0);
- locTopLeft.setPosition(leftWidth, bottomHeight+rescaledHeight);
-
- locTopRight.setAnchorPoint(0, 0);
- locTopRight.setPosition(leftWidth+rescaledWidth, bottomHeight+rescaledHeight);
-
- locLeft.setAnchorPoint(1, 0.5);
- locLeft.setPosition(leftWidth, bottomHeight+rescaledHeight/2 + centerOffset.y);
- locLeft.setScaleY(verticalScale);
-
- locRight.setAnchorPoint(0, 0.5);
- locRight.setPosition(leftWidth+rescaledWidth,bottomHeight+rescaledHeight/2 + centerOffset.y);
- locRight.setScaleY(verticalScale);
-
- locTop.setAnchorPoint(0.5, 0);
- locTop.setPosition(leftWidth+rescaledWidth/2 + centerOffset.x,bottomHeight+rescaledHeight);
- locTop.setScaleX(horizontalScale);
-
- locBottom.setAnchorPoint(0.5, 1);
- locBottom.setPosition(leftWidth+rescaledWidth/2 + centerOffset.x,bottomHeight);
- locBottom.setScaleX(horizontalScale);
-
- locCenter.setAnchorPoint(0.5, 0.5);
- locCenter.setPosition(leftWidth+rescaledWidth/2 + centerOffset.x, bottomHeight+rescaledHeight/2 + centerOffset.y);
- locCenter.setScaleX(horizontalScale);
- locCenter.setScaleY(verticalScale);
- },
-
- /**
- * Constructor function. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
+ * Constructor function.
* @function
* @param {string|cc.SpriteFrame} file file name of texture or a SpriteFrame
* @param {cc.Rect} rectOrCapInsets
@@ -213,14 +386,18 @@ ccui.Scale9Sprite = cc.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprit
*/
ctor: function (file, rectOrCapInsets, capInsets) {
cc.Node.prototype.ctor.call(this);
+
+ //for async texture load
this._loader = new cc.Sprite.LoadManager();
- this._spriteRect = cc.rect(0, 0, 0, 0);
- this._capInsetsInternal = cc.rect(0, 0, 0, 0);
- this._originalSize = cc.size(0, 0);
- this._preferredSize = cc.size(0, 0);
- this._capInsets = cc.rect(0, 0, 0, 0);
- this._renderers = [];
+ this._renderCmd.setState(this._brightState);
+ this._blendFunc = cc.BlendFunc._alphaPremultiplied();
+ this.setAnchorPoint(cc.p(0.5, 0.5));
+ // Init vertex data for simple
+ this._rawVerts = null;
+ this._rawUvs = null;
+ this._vertices = dataPool.get(8) || new Float32Array(8);
+ this._uvs = dataPool.get(8) || new Float32Array(8);
if (file !== undefined) {
if (file instanceof cc.SpriteFrame)
@@ -233,97 +410,19 @@ ccui.Scale9Sprite = cc.Scale9Sprite = cc.Node.extend(/** @lends ccui.Scale9Sprit
this.initWithFile(file, rectOrCapInsets, capInsets);
}
}
- else {
- this.init();
- this.setCascadeColorEnabled(true);
- this.setCascadeOpacityEnabled(true);
- this.setAnchorPoint(0.5, 0.5);
- this._positionsAreDirty = true;
- }
- },
- getSprite: function () {
- return this._scale9Image;
- },
-
- /** Original sprite's size. */
- getOriginalSize: function () {
- return cc.size(this._originalSize);
- },
-
- //if the preferredSize component is given as -1, it is ignored
- getPreferredSize: function () {
- return cc.size(this._preferredSize);
- },
- _getPreferredWidth: function () {
- return this._preferredSize.width;
- },
- _getPreferredHeight: function () {
- return this._preferredSize.height;
- },
-
- _asyncSetPreferredSize: function () {
- this.removeEventListener('load', this._asyncSetPreferredSize, this);
- this.setPreferredSize(this._cachePreferredSize);
- this._cachePreferredSize = null;
- },
- setPreferredSize: function (preferredSize) {
- if (!preferredSize) return;
- if (!this._textureLoaded) {
- this._cachePreferredSize = preferredSize;
- this.removeEventListener('load', this._asyncSetPreferredSize, this);
- this.addEventListener('load', this._asyncSetPreferredSize, this);
- return false;
- }
- this.setContentSize(preferredSize);
- this._preferredSize = preferredSize;
- if (this._positionsAreDirty) {
- this._updatePositions();
- this._positionsAreDirty = false;
- this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.cacheDirty);
+ if (webgl === undefined) {
+ webgl = cc._renderType === cc.game.RENDER_TYPE_WEBGL;
}
},
- _setPreferredWidth: function (value) {
- this._setWidth(value);
- this._preferredSize.width = value;
- },
- _setPreferredHeight: function (value) {
- this._setHeight(value);
- this._preferredSize.height = value;
- },
-
- /** Opacity: conforms to CCRGBAProtocol protocol */
- setOpacity: function (opacity) {
- cc.Node.prototype.setOpacity.call(this, opacity);
- if(this._scale9Enabled) {
- var pChildren = this._renderers;
- for(var i=0; i 0 && rotatedCenterBounds.height > 0 )
- this._renderers.push(this._centre);
-
- // Top
- if(!this._top)
- this._top = new cc.Sprite();
- this._top.initWithTexture(selTexture, rotatedCenterTopBounds, rotated);
- if(rotatedCenterTopBounds.width > 0 && rotatedCenterTopBounds.height > 0 )
- this._renderers.push(this._top);
-
- // Bottom
- if(!this._bottom)
- this._bottom = new cc.Sprite();
- this._bottom.initWithTexture(selTexture, rotatedCenterBottomBounds, rotated);
- if(rotatedCenterBottomBounds.width > 0 && rotatedCenterBottomBounds.height > 0 )
- this._renderers.push(this._bottom);
-
- // Left
- if(!this._left)
- this._left = new cc.Sprite();
- this._left.initWithTexture(selTexture, rotatedLeftCenterBounds, rotated);
- if(rotatedLeftCenterBounds.width > 0 && rotatedLeftCenterBounds.height > 0 )
- this._renderers.push(this._left);
-
- // Right
- if(!this._right)
- this._right = new cc.Sprite();
- this._right.initWithTexture(selTexture, rotatedRightCenterBounds, rotated);
- if(rotatedRightCenterBounds.width > 0 && rotatedRightCenterBounds.height > 0 )
- this._renderers.push(this._right);
-
- // Top left
- if(!this._topLeft)
- this._topLeft = new cc.Sprite();
- this._topLeft.initWithTexture(selTexture, rotatedLeftTopBounds, rotated);
- if(rotatedLeftTopBounds.width > 0 && rotatedLeftTopBounds.height > 0 )
- this._renderers.push(this._topLeft);
-
- // Top right
- if(!this._topRight)
- this._topRight = new cc.Sprite();
- this._topRight.initWithTexture(selTexture, rotatedRightTopBounds, rotated);
- if(rotatedRightTopBounds.width > 0 && rotatedRightTopBounds.height > 0 )
- this._renderers.push(this._topRight);
-
- // Bottom left
- if(!this._bottomLeft)
- this._bottomLeft = new cc.Sprite();
- this._bottomLeft.initWithTexture(selTexture, rotatedLeftBottomBounds, rotated);
- if(rotatedLeftBottomBounds.width > 0 && rotatedLeftBottomBounds.height > 0 )
- this._renderers.push(this._bottomLeft);
-
- // Bottom right
- if(!this._bottomRight)
- this._bottomRight = new cc.Sprite();
- this._bottomRight.initWithTexture(selTexture, rotatedRightBottomBounds, rotated);
- if(rotatedRightBottomBounds.width > 0 && rotatedRightBottomBounds.height > 0 )
- this._renderers.push(this._bottomRight);
+ else {
+ this._blendFunc.src = blendFunc || cc.BLEND_SRC;
+ this._blendFunc.dst = dst || cc.BLEND_DST;
+ }
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty);
},
+
/**
- * @brief Update Scale9Sprite with a specified sprite.
+ * Returns the blending function that is currently being used.
*
- * @param sprite A sprite pointer.
- * @param spriteRect A delimitation zone.
- * @param spriteFrameRotated Whether the sprite is rotated or not.
- * @param offset The offset when slice the sprite.
- * @param originalSize The origial size of the sprite.
- * @param capInsets The Values to use for the cap insets.
- * @return True if update success, false otherwise.
+ * @return A BlendFunc structure with source and destination factor which specified pixel arithmetic.
*/
- updateWithSprite: function(sprite, spriteRect, spriteFrameRotated, offset, originalSize, capInsets) {
- if (!sprite) return false;
-
- this._loader.clear();
- this._textureLoaded = sprite._textureLoaded;
- if (!sprite._textureLoaded) {
- this._loader.once(sprite, function () {
- this.updateWithSprite(sprite, spriteRect, spriteFrameRotated, offset, originalSize, capInsets);
- this.dispatchEvent("load");
- }, this);
- return false;
- }
+ getBlendFunc: function () {
+ return new cc.BlendFunc(this._blendFunc.src, this._blendFunc.dst);
+ },
- this._scale9Image = sprite;
- if(!this._scale9Image) return false;
- var tmpTexture = this._scale9Image.getTexture();
- this._textureLoaded = tmpTexture && tmpTexture.isLoaded();
-
- var spriteFrame = sprite.getSpriteFrame();
- if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
- // Clipping will reset the properties - canvas mode
- if (spriteFrame && tmpTexture._htmlElementObj instanceof window.HTMLCanvasElement) {
- spriteFrameRotated = false;
- spriteRect = { x: 0, y: 0, height: spriteRect.height, width: spriteRect.width }
- }
- }
+ setPreferredSize: function (preferredSize) {
+ if (!preferredSize || cc.sizeEqualToSize(this._contentSize, preferredSize)) return;
+ this.setContentSize(preferredSize);
+ },
- var opacity = this.getOpacity();
- var color = this.getColor();
- this._renderers.length = 0;
- var rect = spriteRect;
- var size = originalSize;
+ getPreferredSize: function () {
+ return this.getContentSize();
+ },
- if(cc._rectEqualToZero(rect)) {
- var textureSize = tmpTexture.getContentSize();
- rect = cc.rect(0, 0, textureSize.width, textureSize.height);
+ // overrides
+ setContentSize: function (width, height) {
+ if (height === undefined) {
+ height = width.height;
+ width = width.width;
+ }
+ if (width === this._contentSize.width && height === this._contentSize.height) {
+ return;
}
- if(size.width === 0 && size.height === 0)
- size = cc.size(rect.width, rect.height);
- this._capInsets = capInsets;
- this._spriteRect = rect;
- this._offset = offset;
- this._spriteFrameRotated = spriteFrameRotated;
- this._originalSize = size;
- this._preferredSize = size;
- this._capInsetsInternal = capInsets;
- if(this._scale9Enabled)
- this.createSlicedSprites();
- else
- this._scale9Image.initWithTexture(tmpTexture, this._spriteRect, this._spriteFrameRotated);
- this.setState(this._brightState);
- this.setContentSize(size);
- this.setOpacity(opacity);
- this.setColor(color);
- return true;
+ cc.Node.prototype.setContentSize.call(this, width, height);
+ this._quadsDirty = true;
},
- /**
- * Update the scale9Sprite with a SpriteBatchNode.
- * @param {cc.SpriteBatchNode} batchNode
- * @param {cc.Rect} originalRect
- * @param {boolean} rotated
- * @param {cc.Rect} capInsets
- * @returns {boolean}
- */
- updateWithBatchNode: function (batchNode, originalRect, rotated, capInsets) {
- if (!batchNode) {
- return false;
- }
- var texture = batchNode.getTexture();
- this._loader.clear();
- var loaded = this._textureLoaded = texture.isLoaded();
- if (!loaded) {
- this._loader.once(texture, function () {
- this.updateWithBatchNode(batchNode, originalRect, rotated, capInsets);
- this.dispatchEvent("load");
- }, this);
- return false;
+ getContentSize: function () {
+ if(this._renderingType === ccui.Scale9Sprite.RenderingType.SIMPLE) {
+ if(this._spriteFrame) {
+ return this._spriteFrame._originalSize;
+ }
+ return cc.size(this._contentSize);
+ } else {
+ return cc.size(this._contentSize);
}
+ },
- var sprite = new cc.Sprite(texture);
- var pos = cc.p(0,0);
- var originalSize = cc.size(originalRect.width,originalRect.height);
+ _setWidth: function (value) {
+ cc.Node.prototype._setWidth.call(this, value);
+ this._quadsDirty = true;
+ },
- return this.updateWithSprite(sprite, originalRect, rotated, pos, originalSize, capInsets);
+ _setHeight: function (value) {
+ cc.Node.prototype._setHeight.call(this, value);
+ this._quadsDirty = true;
},
/**
- * set the sprite frame of ccui.Scale9Sprite
- * @param {cc.SpriteFrame} spriteFrame
- * @param {cc.rect} capInsets
+ * Change the state of 9-slice sprite.
+ * @see `State`
+ * @param state A enum value in State.
*/
- setSpriteFrame: function (spriteFrame, capInsets) {
- // Reset insets
- capInsets = capInsets || cc.rect();
- var texture = spriteFrame.getTexture();
- this._textureLoaded = texture._textureLoaded;
- this._loader.clear();
- if (!texture._textureLoaded) {
- this._loader.once(spriteFrame, function () {
- this.setSpriteFrame(spriteFrame, capInsets);
- this.dispatchEvent("load");
- }, this);
- return false;
- }
+ setState: function (state) {
+ this._brightState = state;
+ this._renderCmd.setState(state);
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty);
+ },
- var sprite = new cc.Sprite(spriteFrame.getTexture());
- this.updateWithSprite(sprite, spriteFrame.getRect(),spriteFrame.isRotated(),spriteFrame.getOffset(),spriteFrame.getOriginalSize(),capInsets);
- this._insetLeft = capInsets.x;
- this._insetTop = capInsets.y;
- this._insetRight = this._originalSize.width - this._insetLeft - capInsets.width;
- this._insetBottom = this._originalSize.height - this._insetTop - capInsets.height;
+ /**
+ * Query the current bright state.
+ * @return @see `State`
+ */
+ getState: function () {
+ return this._brightState;
},
- //v3.3
/**
- * Sets ccui.Scale9Sprite's state
- * @since v3.3
- * @param {Number} state
+ * change the rendering type, could be simple or slice
+ * @return @see `RenderingType`
*/
- setState: function (state) {
- if (state === ccui.Scale9Sprite.state.NORMAL || state === ccui.Scale9Sprite.state.GRAY) {
- this._brightState = state;
- this._renderCmd.setState(state);
- }
+ setRenderingType: function (type) {
+ if (this._renderingType === type) return;
+
+ this._renderingType = type;
+ this._quadsDirty = true;
+ this._uvsDirty = true;
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty);
},
/**
- * @brief Toggle 9-slice feature.
- * If Scale9Sprite is 9-slice disabled, the Scale9Sprite will rendered as a normal sprite.
- * @param {boolean} enabled True to enable 9-slice, false otherwise.
+ * get the rendering type, could be simple or slice
+ * @return @see `RenderingType`
*/
- setScale9Enabled: function (enabled) {
- if (this._scale9Enabled === enabled)
- {
- return;
- }
- this._scale9Enabled = enabled;
- this._renderers.length = 0;
- //we must invalide the transform when toggling scale9enabled
- cc.Node.transformDirty = true;
- if (this._scale9Enabled) {
- if (this._scale9Image) {
- this.updateWithSprite(this._scale9Image,
- this._spriteRect,
- this._spriteFrameRotated,
- this._offset,
- this._originalSize,
- this._capInsets);
- }
- }
- this._positionsAreDirty = true;
+ getRenderingType: function () {
+ return this._renderingType;
},
-
- _setRenderersPosition: function() {
- if(this._positionsAreDirty) {
- this._updatePositions();
- this._adjustScale9ImagePosition();
- this._positionsAreDirty = false;
- }
+ /**
+ * change the left border of 9 slice sprite, it should be specified before trimmed.
+ * @param insetLeft left border.
+ */
+ setInsetLeft: function (insetLeft) {
+ this._insetLeft = insetLeft;
+ this._quadsDirty = true;
+ this._uvsDirty = true;
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty);
},
-
- _adjustScale9ImagePosition: function() {
- var image = this._scale9Image;
- var contentSize = this._contentSize;
- if(image) {
- image.x = contentSize.width * image.getAnchorPoint().x;
- image.y = contentSize.height * image.getAnchorPoint().y;
- }
+ /**
+ * get the left border of 9 slice sprite, the result is specified before trimmed.
+ * @return left border.
+ */
+ getInsetLeft: function () {
+ return this._insetLeft;
},
-
- _adjustScale9ImageScale: function() {
- var image = this._scale9Image;
- var contentSize = this._contentSize;
- if(image) {
- image.setScale(contentSize.width/image.width, contentSize.height/image.height);
- }
+ /**
+ * change the top border of 9 slice sprite, it should be specified before trimmed.
+ * @param insetTop top border.
+ */
+ setInsetTop: function (insetTop) {
+ this._insetTop = insetTop;
+ this._quadsDirty = true;
+ this._uvsDirty = true;
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty);
},
/**
- * Sets whether the widget should be flipped horizontally or not.
- * @since v3.3
- * @param flippedX true if the widget should be flipped horizontally, false otherwise.
+ * get the top border of 9 slice sprite, the result is specified before trimmed.
+ * @return top border.
*/
- setFlippedX: function(flippedX){
- var realScale = this.getScaleX();
- this._flippedX = flippedX;
- this.setScaleX(realScale);
- this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.cacheDirty);
+ getInsetTop: function () {
+ return this._insetTop;
},
/**
- *
- * Returns the flag which indicates whether the widget is flipped horizontally or not.
- *
- * It only flips the texture of the widget, and not the texture of the widget's children.
- * Also, flipping the texture doesn't alter the anchorPoint.
- * If you want to flip the anchorPoint too, and/or to flip the children too use:
- * widget->setScaleX(sprite->getScaleX() * -1);
- *
- * @since v3.3
- * @return {Boolean} true if the widget is flipped horizontally, false otherwise.
+ * change the right border of 9 slice sprite, it should be specified before trimmed.
+ * @param insetRight right border.
*/
- isFlippedX: function(){
- return this._flippedX;
+ setInsetRight: function (insetRight) {
+ this._insetRight = insetRight;
+ this._quadsDirty = true;
+ this._uvsDirty = true;
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty);
},
/**
- * Sets whether the widget should be flipped vertically or not.
- * @since v3.3
- * @param flippedY true if the widget should be flipped vertically, false otherwise.
+ * get the right border of 9 slice sprite, the result is specified before trimmed.
+ * @return right border.
*/
- setFlippedY:function(flippedY){
- var realScale = this.getScaleY();
- this._flippedY = flippedY;
- this.setScaleY(realScale);
- this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.cacheDirty);
+ getInsetRight: function () {
+ return this._insetRight;
},
/**
- *
- * Return the flag which indicates whether the widget is flipped vertically or not.
- *
- * It only flips the texture of the widget, and not the texture of the widget's children.
- * Also, flipping the texture doesn't alter the anchorPoint.
- * If you want to flip the anchorPoint too, and/or to flip the children too use:
- * widget->setScaleY(widget->getScaleY() * -1);
- *
- * @since v3.3
- * @return {Boolean} true if the widget is flipped vertically, false otherwise.
+ * change the bottom border of 9 slice sprite, it should be specified before trimmed.
+ * @param insetBottom bottom border.
*/
- isFlippedY:function(){
- return this._flippedY;
+ setInsetBottom: function (insetBottom) {
+ this._insetBottom = insetBottom;
+ this._quadsDirty = true;
+ this._uvsDirty = true;
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty);
},
-
- setScaleX: function (scaleX) {
- if (this._flippedX)
- scaleX = scaleX * -1;
- cc.Node.prototype.setScaleX.call(this, scaleX);
- this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.cacheDirty);
+ /**
+ * get the bottom border of 9 slice sprite, the result is specified before trimmed.
+ * @return bottom border.
+ */
+ getInsetBottom: function () {
+ return this._insetBottom;
},
- setScaleY: function (scaleY) {
- if (this._flippedY)
- scaleY = scaleY * -1;
- cc.Node.prototype.setScaleY.call(this, scaleY);
- this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.cacheDirty);
- },
+ _rebuildQuads: function () {
+ if (!this._spriteFrame || !this._spriteFrame._textureLoaded) {
+ return;
+ }
- setScale: function (scaleX, scaleY) {
- if(scaleY === undefined)
- scaleY = scaleX;
- this.setScaleX(scaleX);
- this.setScaleY(scaleY);
- },
+ this._updateBlendFunc();
- getScaleX: function () {
- var originalScale = cc.Node.prototype.getScaleX.call(this);
- if (this._flippedX)
- originalScale = originalScale * -1.0;
- return originalScale;
- },
+ this._isTriangle = false;
+ switch (this._renderingType) {
+ case RenderingType.SIMPLE:
+ simpleQuadGenerator._rebuildQuads_base(this, this._spriteFrame, this._contentSize, this._isTrimmedContentSize);
+ break;
+ case RenderingType.SLICED:
+ scale9QuadGenerator._rebuildQuads_base(this, this._spriteFrame, this._contentSize, this._insetLeft, this._insetRight, this._insetTop, this._insetBottom);
+ break;
+ default:
+ this._quadsDirty = false;
+ this._uvsDirty = false;
+ cc.error('Can not generate quad');
+ return;
+ }
- getScaleY: function () {
- var originalScale = cc.Node.prototype.getScaleY.call(this);
- if (this._flippedY)
- originalScale = originalScale * -1.0;
- return originalScale;
- },
- getScale: function () {
- if(this.getScaleX() !== this.getScaleY())
- cc.log("Scale9Sprite#scale. ScaleX != ScaleY. Don't know which one to return");
- return this.getScaleX();
+ this._quadsDirty = false;
+ this._uvsDirty = false;
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
return new ccui.Scale9Sprite.CanvasRenderCmd(this);
else
return new ccui.Scale9Sprite.WebGLRenderCmd(this);
@@ -1220,3 +922,15 @@ ccui.Scale9Sprite.POSITIONS_TOPLEFT = 6;
ccui.Scale9Sprite.POSITIONS_BOTTOMRIGHT = 7;
ccui.Scale9Sprite.state = {NORMAL: 0, GRAY: 1};
+
+var RenderingType = ccui.Scale9Sprite.RenderingType = {
+ /**
+ * @property {Number} SIMPLE
+ */
+ SIMPLE: 0,
+ /**
+ * @property {Number} SLICED
+ */
+ SLICED: 1
+};
+})();
diff --git a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js
index 57a27ed3c3..12f1bcaf82 100644
--- a/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js
+++ b/extensions/ccui/base-classes/UIScale9SpriteCanvasRenderCmd.js
@@ -1,5 +1,5 @@
/****************************************************************************
- Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
@@ -25,170 +25,130 @@
(function() {
ccui.Scale9Sprite.CanvasRenderCmd = function (renderable) {
cc.Node.CanvasRenderCmd.call(this, renderable);
- this._cachedParent = null;
- this._cacheDirty = false;
- this._state = ccui.Scale9Sprite.state.NORMAL;
+ this._needDraw = true;
- var node = this._node;
- var locCacheCanvas = this._cacheCanvas = document.createElement('canvas');
- locCacheCanvas.width = 1;
- locCacheCanvas.height = 1;
- this._cacheContext = new cc.CanvasContextWrapper(locCacheCanvas.getContext("2d"));
- var locTexture = this._cacheTexture = new cc.Texture2D();
- locTexture.initWithElement(locCacheCanvas);
- locTexture.handleLoadedTexture();
- this._cacheSprite = new cc.Sprite(locTexture);
- this._cacheSprite.setAnchorPoint(0,0);
- node.addChild(this._cacheSprite);
+ this._state = ccui.Scale9Sprite.state.NORMAL;
+ this._originalTexture = this._textureToRender = null;
};
var proto = ccui.Scale9Sprite.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
proto.constructor = ccui.Scale9Sprite.CanvasRenderCmd;
- proto.visit = function(parentCmd){
- var node = this._node;
- if(!node._visible)
- return;
-
- if (node._positionsAreDirty) {
- node._updatePositions();
- node._positionsAreDirty = false;
- }
-
- this.originVisit(parentCmd);
+ proto.transform = function(parentCmd, recursive){
+ this.originTransform(parentCmd, recursive);
+ this._node._rebuildQuads();
};
- proto.transform = function(parentCmd){
- var node = this._node;
- cc.Node.CanvasRenderCmd.prototype.transform.call(this, parentCmd);
- if (node._positionsAreDirty) {
- node._updatePositions();
- node._positionsAreDirty = false;
- }
-
- var children = node._children;
- for(var i=0; i 0 && sh > 0 && w > 0 && h > 0) {
+ context.drawImage(image,
+ sx, sy, sw, sh,
+ x, y, w, h);
+ }
+ }
}
- else
- break;
+ cc.g_NumberOfDraws += 9;
+ } else {
+ var quadCount = Math.floor(node._vertCount / 4);
+ for (i = 0, off = 0; i < quadCount; i++) {
+ x = vertices[off];
+ y = vertices[off+1];
+ w = vertices[off+6] - x;
+ h = vertices[off+7] - y;
+ y = - y - h;
+
+ sx = uvs[off] * textureWidth;
+ sy = uvs[off+7] * textureHeight;
+ sw = (uvs[off+6] - uvs[off]) * textureWidth;
+ sh = (uvs[off+1] - uvs[off+7]) * textureHeight;
+
+
+ if (this._textureToRender._pattern !== '') {
+ wrapper.setFillStyle(context.createPattern(image, this._textureToRender._pattern));
+ context.fillRect(x, y, w, h);
+ } else {
+ if (sw > 0 && sh > 0 && w > 0 && h > 0) {
+ context.drawImage(image,
+ sx, sy, sw, sh,
+ x, y, w, h);
+ }
+ }
+ off += 8;
+ }
+ cc.g_NumberOfDraws += quadCount;
}
}
- else {
- var tempCmd = node._scale9Image._renderCmd;
- node._adjustScale9ImagePosition();
- node._adjustScale9ImageScale();
- tempCmd.updateStatus();
- cc.renderer.pushRenderCommand(node._scale9Image._renderCmd);
- }
- //draw to cache canvas
- var selTexture = node._scale9Image.getTexture();
- if(selTexture && this._state === ccui.Scale9Sprite.state.GRAY)
- selTexture._switchToGray(true);
- locContext.setTransform(1, 0, 0, 1, 0, 0);
- locContext.clearRect(0, 0, sizeInPixels.width, sizeInPixels.height);
- cc.renderer._renderingToCacheCanvas(wrapper, node.__instanceId, locScaleFactor, locScaleFactor);
- cc.renderer._turnToNormalMode();
- if(selTexture && this._state === ccui.Scale9Sprite.state.GRAY)
- selTexture._switchToGray(false);
-
- if(contentSizeChanged)
- this._cacheSprite.setTextureRect(cc.rect(0,0, size.width, size.height));
-
- if(!this._cacheSprite.getParent())
- node.addChild(this._cacheSprite, -1);
- this._cacheSprite._renderCmd._updateColor();
};
- proto.setState = function(state){
- var locScale9Image = this._node._scale9Image;
- if(!locScale9Image)
- return;
- this._state = state;
- this.setDirtyFlag(cc.Node._dirtyFlags.cacheDirty);
- };
})();
diff --git a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js
index b8541b46d0..16df4ee947 100644
--- a/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js
+++ b/extensions/ccui/base-classes/UIScale9SpriteWebGLRenderCmd.js
@@ -1,5 +1,5 @@
/****************************************************************************
- Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
@@ -23,191 +23,137 @@
****************************************************************************/
(function() {
- if(!cc.Node.WebGLRenderCmd)
- return;
+ if(!cc.Node.WebGLRenderCmd) return;
+
ccui.Scale9Sprite.WebGLRenderCmd = function (renderable) {
cc.Node.WebGLRenderCmd.call(this, renderable);
- this._cachedParent = null;
- this._cacheDirty = false;
+
+ this._needDraw = true;
+
+ this._color = new Uint32Array(1);
+ this._dirty = false;
+ this._shaderProgram = cc.shaderCache.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLOR);
};
+
+
+ var Scale9Sprite = ccui.Scale9Sprite;
var proto = ccui.Scale9Sprite.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
proto.constructor = ccui.Scale9Sprite.WebGLRenderCmd;
- proto.setShaderProgram = function (shaderProgram) {
- var node = this._node;
- if (node._scale9Enabled) {
- var renderers = node._renderers, l = renderers.length;
- for (var i = 0; i < l; i++) {
- if (renderers[i]) {
- renderers[i]._renderCmd._shaderProgram = shaderProgram;
- }
- }
- }
- else {
- node._scale9Image._renderCmd._shaderProgram = shaderProgram;
- }
- this._shaderProgram = shaderProgram;
+ proto.needDraw = function () {
+ return this._needDraw && this._node.loaded();
};
- proto.visit = function(parentCmd) {
- var node = this._node;
- if (!node._visible)
- return;
- if (!node._scale9Image)
- return;
-
- if (node._positionsAreDirty) {
- node._updatePositions();
- node._positionsAreDirty = false;
- }
-
- parentCmd = parentCmd || this.getParentRenderCmd();
- if (node._parent && node._parent._renderCmd)
- this._curLevel = node._parent._renderCmd._curLevel + 1;
-
- this._syncStatus(parentCmd);
-
- if (node._scale9Enabled) {
- var locRenderers = node._renderers;
- var rendererLen = locRenderers.length;
- for (var j=0; j < rendererLen; j++) {
- var renderer = locRenderers[j];
- if (renderer) {
- var tempCmd = renderer._renderCmd;
- tempCmd.visit(this);
- }
- else
- break;
+ proto._uploadSliced = function (vertices, uvs, color, z, f32buffer, ui32buffer, offset) {
+ var off;
+ for (var r = 0; r < 3; ++r) {
+ for (var c = 0; c < 3; ++c) {
+ off = r*8 + c*2;
+ // lb
+ f32buffer[offset] = vertices[off];
+ f32buffer[offset+1] = vertices[off+1];
+ f32buffer[offset+2] = z;
+ ui32buffer[offset+3] = color[0];
+ f32buffer[offset+4] = uvs[off];
+ f32buffer[offset+5] = uvs[off+1];
+ offset += 6;
+ // rb
+ f32buffer[offset] = vertices[off+2];
+ f32buffer[offset + 1] = vertices[off+3];
+ f32buffer[offset + 2] = z;
+ ui32buffer[offset + 3] = color[0];
+ f32buffer[offset + 4] = uvs[off+2];
+ f32buffer[offset + 5] = uvs[off+3];
+ offset += 6;
+ // lt
+ f32buffer[offset] = vertices[off+8];
+ f32buffer[offset + 1] = vertices[off+9];
+ f32buffer[offset + 2] = z;
+ ui32buffer[offset + 3] = color[0];
+ f32buffer[offset + 4] = uvs[off+8];
+ f32buffer[offset + 5] = uvs[off+9];
+ offset += 6;
+ // rt
+ f32buffer[offset] = vertices[off+10];
+ f32buffer[offset + 1] = vertices[off+11];
+ f32buffer[offset + 2] = z;
+ ui32buffer[offset + 3] = color[0];
+ f32buffer[offset + 4] = uvs[off+10];
+ f32buffer[offset + 5] = uvs[off+11];
+ offset += 6;
}
}
- else {
- node._adjustScale9ImageScale();
- node._adjustScale9ImagePosition();
- node._scale9Image._renderCmd.visit(this);
- }
- this._dirtyFlag = 0;
- this.originVisit(parentCmd);
+ return 36;
};
- proto.transform = function(parentCmd, recursive){
- var node = this._node;
- parentCmd = parentCmd || this.getParentRenderCmd();
+ proto.transform = function (parentCmd, recursive) {
this.originTransform(parentCmd, recursive);
- if (node._positionsAreDirty) {
- node._updatePositions();
- node._positionsAreDirty = false;
- }
- if(node._scale9Enabled) {
- var locRenderers = node._renderers;
- var protectChildLen = locRenderers.length;
- var flags = cc.Node._dirtyFlags;
- for(var j=0; j < protectChildLen; j++) {
- var pchild = locRenderers[j];
- if(pchild) {
- pchild._vertexZ = parentCmd._node._vertexZ;
- var tempCmd = pchild._renderCmd;
- tempCmd.transform(this, true);
- tempCmd._dirtyFlag = tempCmd._dirtyFlag & flags.transformDirty ^ tempCmd._dirtyFlag;
- }
- else {
- break;
- }
- }
- }
- else {
- node._adjustScale9ImageScale();
- node._adjustScale9ImagePosition();
- node._scale9Image._renderCmd.transform(this, true);
- }
+ this._node._rebuildQuads();
};
- proto.setDirtyFlag = function (dirtyFlag, child) {
- // ignore cache dirty, it's only for canvas
- if (dirtyFlag === cc.Node._dirtyFlags.cacheDirty)
- dirtyFlag = cc.Node._dirtyFlags.transformDirty;
- cc.Node.RenderCmd.prototype.setDirtyFlag.call(this, dirtyFlag, child);
+ proto._setColorDirty = function () {
};
- proto._syncStatus = function (parentCmd){
- cc.Node.WebGLRenderCmd.prototype._syncStatus.call(this, parentCmd);
- this._updateDisplayColor(this._displayedColor);
- this._updateDisplayOpacity(this._displayedOpacity);
- };
-
- proto._updateDisplayColor = function(parentColor){
- cc.Node.WebGLRenderCmd.prototype._updateDisplayColor.call(this, parentColor);
+ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){
var node = this._node;
- var scale9Image = node._scale9Image;
- parentColor = this._displayedColor;
- if(node._scale9Enabled) {
- var pChildren = node._renderers;
- for(var i=0; i
* Sets whether the widget is enabled
@@ -346,12 +332,14 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
*/
setEnabled: function (enabled) {
this._enabled = enabled;
+ this.setBright(enabled);
},
/**
* initializes renderer of widget.
*/
- _initRenderer: function () {},
+ _initRenderer: function () {
+ },
/**
* Sets _customSize of ccui.Widget, if ignoreSize is true, the content size is its renderer's contentSize, otherwise the content size is parameter.
@@ -361,15 +349,16 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @override
*/
setContentSize: function(contentSize, height){
- var locWidth = (height === undefined) ? contentSize.width : contentSize;
- var locHeight = (height === undefined) ? contentSize.height : height;
- cc.Node.prototype.setContentSize.call(this, locWidth, locHeight);
+ cc.Node.prototype.setContentSize.call(this, contentSize, height);
+
+ var locWidth = this._contentSize.width;
+ var locHeight = this._contentSize.height;
this._customSize.width = locWidth;
this._customSize.height = locHeight;
if(this._unifySize){
//unify size logic
- } else if (this._ignoreSize){
+ } else if (this._ignoreSize) {
this._contentSize = this.getVirtualRendererSize();
}
if (!this._usingLayoutComponent && this._running) {
@@ -378,15 +367,23 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
this._sizePercent.x = (pSize.width > 0.0) ? locWidth / pSize.width : 0.0;
this._sizePercent.y = (pSize.height > 0.0) ? locHeight / pSize.height : 0.0;
}
- this._onSizeChanged();
+
+ if (this._running) {
+ this._onSizeChanged();
+ } else {
+ this._sizeDirty = true;
+ }
},
_setWidth: function (w) {
+ if (w === this._contentSize.width) {
+ return;
+ }
cc.Node.prototype._setWidth.call(this, w);
this._customSize.width = w;
if(this._unifySize){
//unify size logic
- } else if (this._ignoreSize){
+ } else if (this._ignoreSize) {
this._contentSize = this.getVirtualRendererSize();
}
@@ -395,14 +392,23 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
var locWidth = widgetParent ? widgetParent.width : this._parent.width;
this._sizePercent.x = locWidth > 0 ? this._customSize.width / locWidth : 0;
}
- this._onSizeChanged();
+
+ if (this._running) {
+ this._onSizeChanged();
+ } else {
+ this._sizeDirty = true;
+ }
},
_setHeight: function (h) {
+ if (h === this._contentSize.height) {
+ return;
+ }
+
cc.Node.prototype._setHeight.call(this, h);
this._customSize.height = h;
if(this._unifySize){
//unify size logic
- } else if (this._ignoreSize){
+ } else if (this._ignoreSize) {
this._contentSize = this.getVirtualRendererSize();
}
@@ -411,7 +417,12 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
var locH = widgetParent ? widgetParent.height : this._parent.height;
this._sizePercent.y = locH > 0 ? this._customSize.height / locH : 0;
}
- this._onSizeChanged();
+
+ if (this._running) {
+ this._onSizeChanged();
+ } else {
+ this._sizeDirty = true;
+ }
},
/**
@@ -481,9 +492,9 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @param {cc.Size} [parentSize] parent size
*/
updateSizeAndPosition: function (parentSize) {
- if(!parentSize){
+ if (!parentSize) {
var widgetParent = this.getWidgetParent();
- if(widgetParent)
+ if (widgetParent)
parentSize = widgetParent.getLayoutSize();
else
parentSize = this._parent.getContentSize();
@@ -491,7 +502,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
switch (this._sizeType) {
case ccui.Widget.SIZE_ABSOLUTE:
- if(this._ignoreSize)
+ if (this._ignoreSize)
this.setContentSize(this.getVirtualRendererSize());
else
this.setContentSize(this._customSize);
@@ -499,8 +510,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
this._sizePercent.y = (parentSize.height > 0) ? this._customSize.height / parentSize.height : 0;
break;
case ccui.Widget.SIZE_PERCENT:
- var cSize = cc.size(parentSize.width * this._sizePercent.x , parentSize.height * this._sizePercent.y);
- if(this._ignoreSize)
+ var cSize = cc.size(parentSize.width * this._sizePercent.x, parentSize.height * this._sizePercent.y);
+ if (this._ignoreSize)
this.setContentSize(this.getVirtualRendererSize());
else
this.setContentSize(cSize);
@@ -527,9 +538,9 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
default:
break;
}
- if(this._parent instanceof ccui.ImageView){
+ if (this._parent instanceof ccui.ImageView) {
var renderer = this._parent._imageRenderer;
- if(renderer && !renderer._textureLoaded)
+ if (renderer && !renderer._textureLoaded)
return;
}
this.setPosition(absPos);
@@ -565,11 +576,11 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
return;
}
- if(this._ignoreSize === ignore)
+ if (this._ignoreSize === ignore)
return;
this._ignoreSize = ignore;
- this.setContentSize( ignore ? this.getVirtualRendererSize() : this._customSize );
+ this.setContentSize(ignore ? this.getVirtualRendererSize() : this._customSize);
//this._onSizeChanged();
},
@@ -593,7 +604,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* Gets layout size of ccui.Widget.
* @returns {cc.Size}
*/
- getLayoutSize: function(){
+ getLayoutSize: function () {
return cc.size(this._contentSize);
},
@@ -634,7 +645,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
/**
* Gets the content size of widget. Content size is widget's texture size.
*/
- getVirtualRendererSize:function(){
+ getVirtualRendererSize: function () {
return cc.size(this._contentSize);
},
@@ -643,12 +654,13 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
*/
_onSizeChanged: function () {
if(!this._usingLayoutComponent){
- var locChildren = this.getChildren();
+ var locChildren = this.getChildren();
for (var i = 0, len = locChildren.length; i < len; i++) {
var child = locChildren[i];
- if(child instanceof ccui.Widget)
+ if (child instanceof ccui.Widget)
child.updateSizeAndPosition();
}
+ this._sizeDirty = false;
}
},
@@ -662,7 +674,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
this._touchEnabled = enable; //TODO need consider remove and re-add.
if (this._touchEnabled) {
- if(!this._touchListener)
+ if (!this._touchListener)
this._touchListener = cc.EventListener.create({
event: cc.EventListener.TOUCH_ONE_BY_ONE,
swallowTouches: true,
@@ -688,7 +700,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* Determines if the widget is highlighted
* @returns {boolean} true if the widget is highlighted, false if the widget is not highlighted .
*/
- isHighlighted: function(){
+ isHighlighted: function () {
return this._highlight;
},
@@ -696,7 +708,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* Sets whether the widget is highlighted. The default value is false, a widget is default to not highlighted
* @param highlight true if the widget is highlighted, false if the widget is not highlighted.
*/
- setHighlighted:function(highlight){
+ setHighlighted: function (highlight) {
if (highlight === this._highlight)
return;
this._highlight = highlight;
@@ -725,9 +737,9 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
setFocused: function (focus) {
this._focused = focus;
//make sure there is only one focusedWidget
- if (focus){
+ if (focus) {
ccui.Widget._focusedWidget = this;
- if(ccui.Widget._focusNavigationController)
+ if (ccui.Widget._focusNavigationController)
ccui.Widget._focusNavigationController._setFirstFocsuedWidget(this);
}
},
@@ -736,7 +748,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* returns whether the widget could accept focus.
* @returns {boolean} true represent the widget could accept focus, false represent the widget couldn't accept focus
*/
- isFocusEnabled: function(){
+ isFocusEnabled: function () {
return this._focusEnabled;
},
@@ -744,7 +756,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* sets whether the widget could accept focus.
* @param {Boolean} enable true represent the widget could accept focus, false represent the widget couldn't accept focus
*/
- setFocusEnabled: function(enable){
+ setFocusEnabled: function (enable) {
this._focusEnabled = enable;
},
@@ -757,12 +769,12 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @param current the current focused widget
* @return the next focused widget in a layout
*/
- findNextFocusedWidget: function( direction, current){
- if (null === this.onNextFocusedWidget || null == this.onNextFocusedWidget(direction) ) {
+ findNextFocusedWidget: function (direction, current) {
+ if (null === this.onNextFocusedWidget || null == this.onNextFocusedWidget(direction)) {
var isLayout = current instanceof ccui.Layout;
if (this.isFocused() || isLayout) {
var layout = this.getParent();
- if (null === layout || !(layout instanceof ccui.Layout)){
+ if (null === layout || !(layout instanceof ccui.Layout)) {
//the outer layout's default behaviour is : loop focus
if (isLayout)
return current.findNextFocusedWidget(direction, current);
@@ -781,7 +793,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
/**
* when a widget calls this method, it will get focus immediately.
*/
- requestFocus: function(){
+ requestFocus: function () {
if (this === ccui.Widget._focusedWidget)
return;
this.dispatchFocusEvent(ccui.Widget._focusedWidget, this);
@@ -790,7 +802,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
/**
* no matter what widget object you call this method on , it will return you the exact one focused widget
*/
- getCurrentFocusedWidget: function(){
+ getCurrentFocusedWidget: function () {
return ccui.Widget._focusedWidget;
},
@@ -813,10 +825,10 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @param {ccui.Widget} sender
* @param {cc.Touch} touch
*/
- interceptTouchEvent: function(eventType, sender, touch){
+ interceptTouchEvent: function (eventType, sender, touch) {
var widgetParent = this.getWidgetParent();
if (widgetParent)
- widgetParent.interceptTouchEvent(eventType,sender,touch);
+ widgetParent.interceptTouchEvent(eventType, sender, touch);
},
/**
@@ -824,7 +836,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @param {ccui.Widget} widgetLostFocus
* @param {ccui.Widget} widgetGetFocus
*/
- onFocusChange: function(widgetLostFocus, widgetGetFocus){
+ onFocusChange: function (widgetLostFocus, widgetGetFocus) {
//only change focus when there is indeed a get&lose happens
if (widgetLostFocus)
widgetLostFocus.setFocused(false);
@@ -837,12 +849,12 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @param {ccui.Widget} widgetLostFocus
* @param {ccui.Widget} widgetGetFocus
*/
- dispatchFocusEvent: function(widgetLostFocus, widgetGetFocus){
+ dispatchFocusEvent: function (widgetLostFocus, widgetGetFocus) {
//if the widgetLoseFocus doesn't get focus, it will use the previous focused widget instead
if (widgetLostFocus && !widgetLostFocus.isFocused())
widgetLostFocus = ccui.Widget._focusedWidget;
- if (widgetGetFocus !== widgetLostFocus){
+ if (widgetGetFocus !== widgetLostFocus) {
if (widgetGetFocus && widgetGetFocus.onFocusChanged)
widgetGetFocus.onFocusChanged(widgetLostFocus, widgetGetFocus);
if (widgetLostFocus && widgetGetFocus.onFocusChanged)
@@ -886,13 +898,16 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
}
},
- _onPressStateChangedToNormal: function () {},
+ _onPressStateChangedToNormal: function () {
+ },
- _onPressStateChangedToPressed: function () {},
+ _onPressStateChangedToPressed: function () {
+ },
- _onPressStateChangedToDisabled: function () {},
+ _onPressStateChangedToDisabled: function () {
+ },
- _updateChildrenDisplayedRGBA: function(){
+ _updateChildrenDisplayedRGBA: function () {
this.setColor(this.getColor());
this.setOpacity(this.getOpacity());
},
@@ -900,7 +915,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
/**
* A call back function when widget lost of focus.
*/
- didNotSelectSelf: function () {},
+ didNotSelectSelf: function () {
+ },
/**
*
@@ -919,11 +935,11 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
*/
onTouchBegan: function (touch, event) {
this._hit = false;
- if (this.isVisible() && this.isEnabled() && this._isAncestorsEnabled() && this._isAncestorsVisible(this) ){
+ if (this.isVisible() && this.isEnabled() && this._isAncestorsEnabled() && this._isAncestorsVisible(this)) {
var touchPoint = touch.getLocation();
this._touchBeganPosition.x = touchPoint.x;
this._touchBeganPosition.y = touchPoint.y;
- if(this.hitTest(this._touchBeganPosition) && this.isClippingParentContainsPoint(this._touchBeganPosition))
+ if (this.hitTest(this._touchBeganPosition) && this.isClippingParentContainsPoint(this._touchBeganPosition))
this._hit = true;
}
if (!this._hit) {
@@ -942,9 +958,9 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
return true;
},
- propagateTouchEvent: function(event, sender, touch){
+ propagateTouchEvent: function (event, sender, touch) {
var widgetParent = this.getWidgetParent();
- if (widgetParent){
+ if (widgetParent) {
widgetParent.interceptTouchEvent(event, sender, touch);
}
},
@@ -1056,7 +1072,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @param {Object} target
*/
addTouchEventListener: function (selector, target) {
- if(target === undefined)
+ if (target === undefined)
this._touchEventCallback = selector;
else {
this._touchEventSelector = selector;
@@ -1064,7 +1080,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
}
},
- addClickEventListener: function(callback){
+ addClickEventListener: function (callback) {
this._clickEventListener = callback;
},
@@ -1074,7 +1090,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @returns {boolean} true if the point is in widget's space, false otherwise.
*/
hitTest: function (pt) {
- var bb = cc.rect(0,0, this._contentSize.width, this._contentSize.height);
+ var bb = cc.rect(0, 0, this._contentSize.width, this._contentSize.height);
return cc.rectContainsPoint(bb, this.convertToNodeSpace(pt));
},
@@ -1083,7 +1099,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @param {cc.Point} pt location point
* @returns {Boolean}
*/
- isClippingParentContainsPoint: function(pt){
+ isClippingParentContainsPoint: function (pt) {
this._affectByClipping = false;
var parent = this.getParent();
var clippingParent = null;
@@ -1206,6 +1222,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
return;
}
this._positionPercent.x = percent;
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
},
_setYPercent: function (percent) {
if (this._usingLayoutComponent){
@@ -1215,6 +1232,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
return;
}
this._positionPercent.y = percent;
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.transformDirty);
},
/**
@@ -1322,7 +1340,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
return this._flippedY;
},
- _adaptRenderers: function(){},
+ _adaptRenderers: function () {
+ },
/**
* Determines if the widget is bright
@@ -1376,15 +1395,15 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* Gets the position of touch began event.
* @returns {cc.Point}
*/
- getTouchBeganPosition: function(){
- return cc.p(this._touchBeganPosition);
+ getTouchBeganPosition: function () {
+ return cc.p(this._touchBeganPosition);
},
/**
* Gets the position of touch moved event
* @returns {cc.Point}
*/
- getTouchMovePosition: function(){
+ getTouchMovePosition: function () {
return cc.p(this._touchMovePosition);
},
@@ -1392,7 +1411,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* Gets the position of touch end event
* @returns {cc.Point}
*/
- getTouchEndPosition:function(){
+ getTouchEndPosition: function () {
return cc.p(this._touchEndPosition);
},
@@ -1409,7 +1428,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @param {ccui.LayoutParameter} parameter
*/
setLayoutParameter: function (parameter) {
- if(!parameter)
+ if (!parameter)
return;
this._layoutParameterDictionary[parameter.getLayoutType()] = parameter;
this._layoutParameterType = parameter.getLayoutType();
@@ -1457,7 +1476,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
}
},
- _copySpecialProperties: function (model) {},
+ _copySpecialProperties: function (model) {
+ },
_copyProperties: function (widget) {
this.setEnabled(widget.isEnabled());
@@ -1509,7 +1529,6 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
if (parameter)
this.setLayoutParameter(parameter.clone());
}
- this._onSizeChanged();
},
/*temp action*/
@@ -1526,7 +1545,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @deprecated since v3.0, please use getLeftBoundary instead.
* @returns {number}
*/
- getLeftInParent: function(){
+ getLeftInParent: function () {
cc.log("getLeftInParent is deprecated. Please use getLeftBoundary instead.");
return this.getLeftBoundary();
},
@@ -1536,7 +1555,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @deprecated since v3.0, please use getBottomBoundary instead.
* @returns {number}
*/
- getBottomInParent: function(){
+ getBottomInParent: function () {
cc.log("getBottomInParent is deprecated. Please use getBottomBoundary instead.");
return this.getBottomBoundary();
},
@@ -1546,7 +1565,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @deprecated since v3.0, please use getRightBoundary instead.
* @returns {number}
*/
- getRightInParent: function(){
+ getRightInParent: function () {
cc.log("getRightInParent is deprecated. Please use getRightBoundary instead.");
return this.getRightBoundary();
},
@@ -1556,7 +1575,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @deprecated since v3.0, please use getTopBoundary instead.
* @returns {number}
*/
- getTopInParent: function(){
+ getTopInParent: function () {
cc.log("getTopInParent is deprecated. Please use getTopBoundary instead.");
return this.getTopBoundary();
},
@@ -1673,6 +1692,14 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
cc.arrayRemoveObject(this._nodes, node);
},
+ _getNormalGLProgram: function () {
+ return cc.shaderCache.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLOR);
+ },
+
+ _getGrayGLProgram: function () {
+ return cc.shaderCache.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLOR_GRAY);
+ },
+
/**
* Removes node by tag
* @deprecated since v3.0, please use removeChildByTag instead.
@@ -1699,14 +1726,14 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
this._nodes.length = 0;
},
- _findLayout: function(){
+ _findLayout: function () {
cc.renderer.childrenOrderDirty = true;
var layout = this._parent;
- while(layout){
- if(layout._doLayout){
+ while (layout) {
+ if (layout._doLayout) {
layout._doLayoutDirty = true;
break;
- }else
+ } else
layout = layout._parent;
}
},
@@ -1734,42 +1761,42 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @since v3.3
* @param {function} callback
*/
- addCCSEventListener: function(callback){
+ addCCSEventListener: function (callback) {
this._ccEventCallback = callback;
},
//override the scale functions.
- setScaleX: function(scaleX){
+ setScaleX: function (scaleX) {
if (this._flippedX)
scaleX = scaleX * -1;
cc.Node.prototype.setScaleX.call(this, scaleX);
},
- setScaleY: function(scaleY){
+ setScaleY: function (scaleY) {
if (this._flippedY)
scaleY = scaleY * -1;
cc.Node.prototype.setScaleY.call(this, scaleY);
},
- setScale: function(scaleX, scaleY){
- if(scaleY === undefined)
+ setScale: function (scaleX, scaleY) {
+ if (scaleY === undefined)
scaleY = scaleX;
this.setScaleX(scaleX);
this.setScaleY(scaleY);
},
- getScaleX: function(){
+ getScaleX: function () {
var originalScale = cc.Node.prototype.getScaleX.call(this);
if (this._flippedX)
originalScale = originalScale * -1.0;
return originalScale;
},
- getScaleY: function(){
+ getScaleY: function () {
var originalScale = cc.Node.prototype.getScaleY.call(this);
if (this._flippedY)
originalScale = originalScale * -1.0;
return originalScale;
},
- getScale: function(){
- if(this.getScaleX() !== this.getScaleY())
+ getScale: function () {
+ if (this.getScaleX() !== this.getScaleY())
cc.log("Widget#scale. ScaleX != ScaleY. Don't know which one to return");
return this.getScaleX();
},
@@ -1779,7 +1806,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @since v3.3
* @param {String} callbackName
*/
- setCallbackName: function(callbackName){
+ setCallbackName: function (callbackName) {
this._callbackName = callbackName;
},
@@ -1788,7 +1815,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @since v3.3
* @returns {String|Null}
*/
- getCallbackName: function(){
+ getCallbackName: function () {
return this._callbackName;
},
@@ -1797,7 +1824,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @since v3.3
* @param {String} callbackType
*/
- setCallbackType: function(callbackType){
+ setCallbackType: function (callbackType) {
this._callbackType = callbackType;
},
@@ -1806,7 +1833,7 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
* @since v3.3
* @returns {String|null}
*/
- getCallbackType: function(){
+ getCallbackType: function () {
return this._callbackType;
},
@@ -1828,8 +1855,8 @@ ccui.Widget = ccui.ProtectedNode.extend(/** @lends ccui.Widget# */{
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
return new ccui.Widget.WebGLRenderCmd(this);
else
return new ccui.Widget.CanvasRenderCmd(this);
@@ -1904,8 +1931,8 @@ ccui.Widget._focusNavigationController = null;
* @note it doesn't implemented on Web
* @param {Boolean} enable set true to enable dpad focus navigation, otherwise disable dpad focus navigation
*/
-ccui.Widget.enableDpadNavigation = function(enable){
- if (enable){
+ccui.Widget.enableDpadNavigation = function (enable) {
+ if (enable) {
if (null == ccui.Widget._focusNavigationController) {
ccui.Widget._focusNavigationController = new ccui._FocusNavigationController();
if (ccui.Widget._focusedWidget) {
@@ -1914,7 +1941,7 @@ ccui.Widget.enableDpadNavigation = function(enable){
}
ccui.Widget._focusNavigationController.enableFocusNavigation(true);
} else {
- if(ccui.Widget._focusNavigationController){
+ if (ccui.Widget._focusNavigationController) {
ccui.Widget._focusNavigationController.enableFocusNavigation(false);
ccui.Widget._focusNavigationController = null;
}
@@ -1926,7 +1953,7 @@ ccui.Widget.enableDpadNavigation = function(enable){
* @function
* @returns {null|ccui.Widget}
*/
-ccui.Widget.getCurrentFocusedWidget = function(){
+ccui.Widget.getCurrentFocusedWidget = function () {
return ccui.Widget._focusedWidget;
};
diff --git a/extensions/ccui/base-classes/UIWidgetRenderCmd.js b/extensions/ccui/base-classes/UIWidgetRenderCmd.js
index 9119c327dd..fca76f9735 100644
--- a/extensions/ccui/base-classes/UIWidgetRenderCmd.js
+++ b/extensions/ccui/base-classes/UIWidgetRenderCmd.js
@@ -25,7 +25,7 @@
cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
ccui.Widget.CanvasRenderCmd = function (renderable) {
- cc.ProtectedNode.CanvasRenderCmd.call(this, renderable);
+ this._pNodeCmdCtor(renderable);
this._needDraw = false;
};
@@ -33,14 +33,27 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
proto.constructor = ccui.Widget.CanvasRenderCmd;
proto.visit = function (parentCmd) {
- var node = this._node;
- if (node._visible) {
- node._adaptRenderers();
- this.pNodeVisit(parentCmd);
+ var node = this._node, renderer = cc.renderer;
+
+ parentCmd = parentCmd || this.getParentRenderCmd();
+ if (parentCmd)
+ this._curLevel = parentCmd._curLevel + 1;
+
+ if (isNaN(node._customZ)) {
+ node._vertexZ = renderer.assignedZ;
+ renderer.assignedZ += renderer.assignedZStep;
}
+
+ node._adaptRenderers();
+ this._syncStatus(parentCmd);
};
proto.transform = function (parentCmd, recursive) {
+ if (!this._transform) {
+ this._transform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0};
+ this._worldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0};
+ }
+
var node = this._node;
if (node._visible && node._running) {
node._adaptRenderers();
@@ -58,11 +71,10 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
}
};
- proto.widgetVisit = proto.visit;
proto.widgetTransform = proto.transform;
} else {
ccui.Widget.WebGLRenderCmd = function (renderable) {
- cc.ProtectedNode.WebGLRenderCmd.call(this, renderable);
+ this._pNodeCmdCtor(renderable);
this._needDraw = false;
};
@@ -70,14 +82,27 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
proto.constructor = ccui.Widget.WebGLRenderCmd;
proto.visit = function (parentCmd) {
- var node = this._node;
- if (node._visible) {
- node._adaptRenderers();
- this.pNodeVisit(parentCmd);
+ var node = this._node, renderer = cc.renderer;
+
+ parentCmd = parentCmd || this.getParentRenderCmd();
+ if (parentCmd)
+ this._curLevel = parentCmd._curLevel + 1;
+
+ if (isNaN(node._customZ)) {
+ node._vertexZ = renderer.assignedZ;
+ renderer.assignedZ += renderer.assignedZStep;
}
+
+ node._adaptRenderers();
+ this._syncStatus(parentCmd);
};
- proto.transform = function(parentCmd, recursive){
+ proto.transform = function (parentCmd, recursive) {
+ if (!this._transform) {
+ this._transform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0};
+ this._worldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0};
+ }
+
var node = this._node;
if (node._visible && node._running) {
node._adaptRenderers();
@@ -96,7 +121,6 @@ cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
}
};
- proto.widgetVisit = proto.visit;
proto.widgetTransform = proto.transform;
}
});
diff --git a/extensions/ccui/layouts/UILayout.js b/extensions/ccui/layouts/UILayout.js
index ff4d82bf5c..34361aa8a9 100644
--- a/extensions/ccui/layouts/UILayout.js
+++ b/extensions/ccui/layouts/UILayout.js
@@ -63,11 +63,11 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
_finalPositionX: 0,
_finalPositionY: 0,
- _backGroundImageOpacity:0,
+ _backGroundImageOpacity: 0,
_loopFocus: false, //whether enable loop focus or not
__passFocusToChild: true, //on default, it will pass the focus to the next nearest widget
- _isFocusPassing:false, //when finding the next focused widget, use this variable to pass focus between layout & widget
+ _isFocusPassing: false, //when finding the next focused widget, use this variable to pass focus between layout & widget
_isInterceptTouch: false,
/**
@@ -89,7 +89,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
this.ignoreContentAdaptWithSize(false);
this.setContentSize(cc.size(0, 0));
this.setAnchorPoint(0, 0);
- this.onPassFocusToChild = this._findNearestChildWidgetIndex.bind(this);
+ this.onPassFocusToChild = this._findNearestChildWidgetIndex.bind(this);
this._backGroundImageCapInsets = cc.rect(0, 0, 0, 0);
@@ -107,10 +107,10 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* Calls its parent's onEnter, and calls its clippingStencil's onEnter if clippingStencil isn't null.
* @override
*/
- onEnter: function(){
+ onEnter: function () {
ccui.Widget.prototype.onEnter.call(this);
if (this._clippingStencil)
- this._clippingStencil.onEnter();
+ this._clippingStencil._performRecursive(cc.Node._stateCallbackType.onEnter);
this._doLayoutDirty = true;
this._clippingRectDirty = true;
},
@@ -119,17 +119,91 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* Calls its parent's onExit, and calls its clippingStencil's onExit if clippingStencil isn't null.
* @override
*/
- onExit: function(){
+ onExit: function () {
ccui.Widget.prototype.onExit.call(this);
if (this._clippingStencil)
- this._clippingStencil.onExit();
+ this._clippingStencil._performRecursive(cc.Node._stateCallbackType.onExit);
+ },
+
+ /**
+ *
+ * Calls adaptRenderers (its subclass will override it.) and do layout.
+ * If clippingEnabled is true, it will clip/scissor area.
+ *
+ * @override
+ * @param {cc.Node} [parent]
+ */
+ visit: function (parent) {
+ var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null;
+
+ // quick return if not visible
+ if (!this._visible) {
+ cmd._propagateFlagsDown(parentCmd);
+ return;
+ }
+
+ this._adaptRenderers();
+ this._doLayout();
+
+ var renderer = cc.renderer;
+ cmd.visit(parentCmd);
+
+ var stencilClipping = this._clippingEnabled && this._clippingType === ccui.Layout.CLIPPING_STENCIL;
+ var scissorClipping = this._clippingEnabled && this._clippingType === ccui.Layout.CLIPPING_SCISSOR;
+
+ if (stencilClipping) {
+ cmd.stencilClippingVisit(parentCmd);
+ }
+ else if (scissorClipping) {
+ cmd.scissorClippingVisit(parentCmd);
+ }
+
+ var i, children = this._children, len = children.length, child;
+ var j, pChildren = this._protectedChildren, pLen = pChildren.length, pChild;
+
+ if (this._reorderChildDirty) this.sortAllChildren();
+ if (this._reorderProtectedChildDirty) this.sortAllProtectedChildren();
+ // draw children zOrder < 0
+ for (i = 0; i < len; i++) {
+ child = children[i];
+ if (child._localZOrder < 0) {
+ child.visit(this);
+ }
+ else break;
+ }
+ for (j = 0; j < pLen; j++) {
+ pChild = pChildren[j];
+ if (pChild._localZOrder < 0) {
+ cmd._changeProtectedChild(pChild);
+ pChild.visit(this);
+ }
+ else break;
+ }
+ // draw children zOrder >= 0
+ for (; i < len; i++) {
+ children[i].visit(this);
+ }
+ for (; j < pLen; j++) {
+ pChild = pChildren[j];
+ cmd._changeProtectedChild(pChild);
+ pChild.visit(this);
+ }
+
+ if (stencilClipping) {
+ cmd.postStencilVisit();
+ }
+ else if (scissorClipping) {
+ cmd.postScissorVisit();
+ }
+
+ cmd._dirtyFlag = 0;
},
/**
* If a layout is loop focused which means that the focus movement will be inside the layout
* @param {Boolean} loop pass true to let the focus movement loop inside the layout
*/
- setLoopFocus: function(loop){
+ setLoopFocus: function (loop) {
this._loopFocus = loop;
},
@@ -137,7 +211,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* Gets whether enable focus loop
* @returns {boolean} If focus loop is enabled, then it will return true, otherwise it returns false. The default value is false.
*/
- isLoopFocus: function(){
+ isLoopFocus: function () {
return this._loopFocus;
},
@@ -145,7 +219,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* Specifies whether the layout pass its focus to its child
* @param pass To specify whether the layout pass its focus to its child
*/
- setPassFocusToChild: function(pass){
+ setPassFocusToChild: function (pass) {
this.__passFocusToChild = pass;
},
@@ -153,7 +227,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* Returns whether the layout will pass the focus to its children or not. The default value is true
* @returns {boolean} To query whether the layout will pass the focus to its children or not. The default value is true
*/
- isPassFocusToChild: function(){
+ isPassFocusToChild: function () {
return this.__passFocusToChild;
},
@@ -164,7 +238,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @param {ccui.Widget} current the current focused widget
* @returns {ccui.Widget} return the index of widget in the layout
*/
- findNextFocusedWidget: function(direction, current){
+ findNextFocusedWidget: function (direction, current) {
if (this._isFocusPassing || this.isFocused()) {
var parent = this.getParent();
this._isFocusPassing = false;
@@ -181,31 +255,31 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
return this;
parent._isFocusPassing = true;
return parent.findNextFocusedWidget(direction, this);
- } else if(current.isFocused() || current instanceof ccui.Layout) {
+ } else if (current.isFocused() || current instanceof ccui.Layout) {
if (this._layoutType === ccui.Layout.LINEAR_HORIZONTAL) {
- switch (direction){
+ switch (direction) {
case ccui.Widget.LEFT:
return this._getPreviousFocusedWidget(direction, current);
- break;
+ break;
case ccui.Widget.RIGHT:
return this._getNextFocusedWidget(direction, current);
- break;
+ break;
case ccui.Widget.DOWN:
case ccui.Widget.UP:
- if (this._isLastWidgetInContainer(this, direction)){
+ if (this._isLastWidgetInContainer(this, direction)) {
if (this._isWidgetAncestorSupportLoopFocus(current, direction))
return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this);
return current;
} else {
return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this);
}
- break;
+ break;
default:
cc.assert(0, "Invalid Focus Direction");
return current;
}
} else if (this._layoutType === ccui.Layout.LINEAR_VERTICAL) {
- switch (direction){
+ switch (direction) {
case ccui.Widget.LEFT:
case ccui.Widget.RIGHT:
if (this._isLastWidgetInContainer(this, direction)) {
@@ -215,7 +289,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
}
else
return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this);
- break;
+ break;
case ccui.Widget.DOWN:
return this._getNextFocusedWidget(direction, current);
break;
@@ -282,7 +356,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* and sets the layout dirty flag to true.
* @param {Boolean} cleanup true if all running actions on all children nodes should be cleanup, false otherwise.
*/
- removeAllChildrenWithCleanup: function(cleanup){
+ removeAllChildrenWithCleanup: function (cleanup) {
ccui.Widget.prototype.removeAllChildrenWithCleanup.call(this, cleanup);
this._doLayoutDirty = true;
},
@@ -295,36 +369,6 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
return this._clippingEnabled;
},
- /**
- *
- * Calls adaptRenderers (its subclass will override it.) and do layout.
- * If clippingEnabled is true, it will clip/scissor area.
- *
- * @override
- * @param {cc.Node.RenderCmd} [parentCmd]
- */
- visit: function (parentCmd) {
- if (!this._visible)
- return;
- this._adaptRenderers();
- this._doLayout();
-
- if (this._clippingEnabled) {
- switch (this._clippingType) {
- case ccui.Layout.CLIPPING_STENCIL:
- this._renderCmd.stencilClippingVisit(parentCmd);
- break;
- case ccui.Layout.CLIPPING_SCISSOR:
- this._renderCmd.scissorClippingVisit(parentCmd);
- break;
- default:
- break;
- }
- } else {
- ccui.Widget.prototype.visit.call(this, parentCmd);
- }
- },
-
/**
* Changes if layout can clip it's content and locChild.
* If you really need this, please enable it. But it would reduce the rendering efficiency.
@@ -337,15 +381,15 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
switch (this._clippingType) {
case ccui.Layout.CLIPPING_SCISSOR:
case ccui.Layout.CLIPPING_STENCIL:
- if (able){
+ if (able) {
this._clippingStencil = new cc.DrawNode();
this._renderCmd.rebindStencilRendering(this._clippingStencil);
if (this._running)
- this._clippingStencil.onEnter();
+ this._clippingStencil._performRecursive(cc.Node._stateCallbackType.onEnter);
this._setStencilClippingSize(this._contentSize);
} else {
if (this._running && this._clippingStencil)
- this._clippingStencil.onExit();
+ this._clippingStencil._performRecursive(cc.Node._stateCallbackType.onExit);
this._clippingStencil = null;
}
break;
@@ -415,8 +459,8 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
var right = Math.min(worldPos.x + scissorWidth, parentClippingRect.x + parentClippingRect.width);
var top = Math.min(worldPos.y + scissorHeight, parentClippingRect.y + parentClippingRect.height);
- this._clippingRect.width = Math.max(0.0, right - this._clippingRect.x);
- this._clippingRect.height = Math.max(0.0, top - this._clippingRect.y);
+ this._clippingRect.width = Math.max(0.0, right - this._clippingRect.x);
+ this._clippingRect.height = Math.max(0.0, top - this._clippingRect.y);
} else {
this._clippingRect.x = worldPos.x;
this._clippingRect.y = worldPos.y;
@@ -477,7 +521,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
if (!fileName)
return;
texType = texType || ccui.Widget.LOCAL_TEXTURE;
- if (this._backGroundImage === null){
+ if (this._backGroundImage === null) {
this._addBackGroundImage();
this.setBackGroundImageScale9Enabled(this._backGroundScale9Enabled);
}
@@ -507,7 +551,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @param {cc.Rect} capInsets capinsets of background image.
*/
setBackGroundImageCapInsets: function (capInsets) {
- if(!capInsets)
+ if (!capInsets)
return;
var locInsets = this._backGroundImageCapInsets;
locInsets.x = capInsets.x;
@@ -780,7 +824,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
},
_updateBackGroundImageColor: function () {
- if(this._backGroundImage)
+ if (this._backGroundImage)
this._backGroundImage.setColor(this._backGroundImageColor);
},
@@ -802,7 +846,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
var locChild = null;
for (var i = 0; i < layoutChildrenArray.length; i++) {
locChild = layoutChildrenArray[i];
- if(locChild instanceof ccui.Widget)
+ if (locChild instanceof ccui.Widget)
this._supplyTheLayoutParameterLackToChild(locChild);
}
this._doLayoutDirty = true;
@@ -835,20 +879,20 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
this._doLayoutDirty = false;
},
- _getLayoutContentSize: function(){
+ _getLayoutContentSize: function () {
return this.getContentSize();
},
- _getLayoutElements: function(){
+ _getLayoutElements: function () {
return this.getChildren();
},
- _updateBackGroundImageOpacity: function(){
+ _updateBackGroundImageOpacity: function () {
if (this._backGroundImage)
this._backGroundImage.setOpacity(this._backGroundImageOpacity);
},
- _updateBackGroundImageRGBA: function(){
+ _updateBackGroundImageRGBA: function () {
if (this._backGroundImage) {
this._backGroundImage.setColor(this._backGroundImageColor);
this._backGroundImage.setOpacity(this._backGroundImageOpacity);
@@ -860,13 +904,13 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {cc.Size}
* @private
*/
- _getLayoutAccumulatedSize: function(){
+ _getLayoutAccumulatedSize: function () {
var children = this.getChildren();
- var layoutSize = cc.size(0, 0);
+ var layoutSize = cc.size(0, 0);
var widgetCount = 0, locSize;
- for(var i = 0, len = children.length; i < len; i++) {
+ for (var i = 0, len = children.length; i < len; i++) {
var layout = children[i];
- if (null !== layout && layout instanceof ccui.Layout){
+ if (null !== layout && layout instanceof ccui.Layout) {
locSize = layout._getLayoutAccumulatedSize();
layoutSize.width += locSize.width;
layoutSize.height += locSize.height;
@@ -875,8 +919,8 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
widgetCount++;
var m = layout.getLayoutParameter().getMargin();
locSize = layout.getContentSize();
- layoutSize.width += locSize.width + (m.right + m.left) * 0.5;
- layoutSize.height += locSize.height + (m.top + m.bottom) * 0.5;
+ layoutSize.width += locSize.width + (m.right + m.left) * 0.5;
+ layoutSize.height += locSize.height + (m.top + m.bottom) * 0.5;
}
}
}
@@ -884,10 +928,10 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
//substract extra size
var type = this.getLayoutType();
if (type === ccui.Layout.LINEAR_HORIZONTAL)
- layoutSize.height = layoutSize.height - layoutSize.height/widgetCount * (widgetCount-1);
+ layoutSize.height = layoutSize.height - layoutSize.height / widgetCount * (widgetCount - 1);
if (type === ccui.Layout.LINEAR_VERTICAL)
- layoutSize.width = layoutSize.width - layoutSize.width/widgetCount * (widgetCount-1);
+ layoutSize.width = layoutSize.width - layoutSize.width / widgetCount * (widgetCount - 1);
return layoutSize;
},
@@ -899,7 +943,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {Number}
* @private
*/
- _findNearestChildWidgetIndex: function(direction, baseWidget){
+ _findNearestChildWidgetIndex: function (direction, baseWidget) {
if (baseWidget == null || baseWidget === this)
return this._findFirstFocusEnabledWidgetIndex();
@@ -912,9 +956,9 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
while (index < count) {
var w = locChildren[index];
if (w && w instanceof ccui.Widget && w.isFocusEnabled()) {
- var length = (w instanceof ccui.Layout)? w._calculateNearestDistance(baseWidget)
+ var length = (w instanceof ccui.Layout) ? w._calculateNearestDistance(baseWidget)
: cc.pLength(cc.pSub(this._getWorldCenterPoint(w), widgetPosition));
- if (length < distance){
+ if (length < distance) {
found = index;
distance = length;
}
@@ -935,7 +979,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {Number} The index of child widget in the container
* @private
*/
- _findFarthestChildWidgetIndex: function(direction, baseWidget){
+ _findFarthestChildWidgetIndex: function (direction, baseWidget) {
if (baseWidget == null || baseWidget === this)
return this._findFirstFocusEnabledWidgetIndex();
@@ -944,20 +988,20 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
var distance = -cc.FLT_MAX, found = 0;
if (direction === ccui.Widget.LEFT || direction === ccui.Widget.RIGHT || direction === ccui.Widget.DOWN || direction === ccui.Widget.UP) {
- var widgetPosition = this._getWorldCenterPoint(baseWidget);
- while (index < count) {
+ var widgetPosition = this._getWorldCenterPoint(baseWidget);
+ while (index < count) {
var w = locChildren[index];
if (w && w instanceof ccui.Widget && w.isFocusEnabled()) {
- var length = (w instanceof ccui.Layout)?w._calculateFarthestDistance(baseWidget)
+ var length = (w instanceof ccui.Layout) ? w._calculateFarthestDistance(baseWidget)
: cc.pLength(cc.pSub(this._getWorldCenterPoint(w), widgetPosition));
- if (length > distance){
+ if (length > distance) {
found = index;
distance = length;
}
}
index++;
}
- return found;
+ return found;
}
cc.log("invalid focus direction!!!");
return 0;
@@ -969,9 +1013,9 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {Number} return the nearest distance between the baseWidget and the layout's children
* @private
*/
- _calculateNearestDistance: function(baseWidget){
+ _calculateNearestDistance: function (baseWidget) {
var distance = cc.FLT_MAX;
- var widgetPosition = this._getWorldCenterPoint(baseWidget);
+ var widgetPosition = this._getWorldCenterPoint(baseWidget);
var locChildren = this._children;
for (var i = 0, len = locChildren.length; i < len; i++) {
@@ -996,9 +1040,9 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {number}
* @private
*/
- _calculateFarthestDistance:function(baseWidget){
+ _calculateFarthestDistance: function (baseWidget) {
var distance = -cc.FLT_MAX;
- var widgetPosition = this._getWorldCenterPoint(baseWidget);
+ var widgetPosition = this._getWorldCenterPoint(baseWidget);
var locChildren = this._children;
for (var i = 0, len = locChildren.length; i < len; i++) {
@@ -1026,7 +1070,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @param baseWidget
* @private
*/
- _findProperSearchingFunctor: function(direction, baseWidget){
+ _findProperSearchingFunctor: function (direction, baseWidget) {
if (baseWidget === undefined)
return;
@@ -1038,13 +1082,13 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
} else if (direction === ccui.Widget.RIGHT) {
this.onPassFocusToChild = (previousWidgetPosition.x > widgetPosition.x) ? this._findFarthestChildWidgetIndex
: this._findNearestChildWidgetIndex;
- }else if(direction === ccui.Widget.DOWN) {
+ } else if (direction === ccui.Widget.DOWN) {
this.onPassFocusToChild = (previousWidgetPosition.y > widgetPosition.y) ? this._findNearestChildWidgetIndex
: this._findFarthestChildWidgetIndex;
- }else if(direction === ccui.Widget.UP) {
+ } else if (direction === ccui.Widget.UP) {
this.onPassFocusToChild = (previousWidgetPosition.y < widgetPosition.y) ? this._findNearestChildWidgetIndex
: this._findFarthestChildWidgetIndex;
- }else
+ } else
cc.log("invalid direction!");
},
@@ -1053,15 +1097,15 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {ccui.Widget}
* @private
*/
- _findFirstNonLayoutWidget:function(){
+ _findFirstNonLayoutWidget: function () {
var locChildren = this._children;
- for(var i = 0, len = locChildren.length; i < len; i++) {
+ for (var i = 0, len = locChildren.length; i < len; i++) {
var child = locChildren[i];
- if (child instanceof ccui.Layout){
+ if (child instanceof ccui.Layout) {
var widget = child._findFirstNonLayoutWidget();
- if(widget)
+ if (widget)
return widget;
- } else{
+ } else {
if (child instanceof ccui.Widget)
return child;
}
@@ -1074,7 +1118,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {number}
* @private
*/
- _findFirstFocusEnabledWidgetIndex: function(){
+ _findFirstFocusEnabledWidgetIndex: function () {
var index = 0, locChildren = this.getChildren();
var count = locChildren.length;
while (index < count) {
@@ -1092,9 +1136,9 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {*}
* @private
*/
- _findFocusEnabledChildWidgetByIndex: function(index){
+ _findFocusEnabledChildWidgetByIndex: function (index) {
var widget = this._getChildWidgetByIndex(index);
- if (widget){
+ if (widget) {
if (widget.isFocusEnabled())
return widget;
index = index + 1;
@@ -1109,10 +1153,10 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {cc.Point}
* @private
*/
- _getWorldCenterPoint: function(widget){
+ _getWorldCenterPoint: function (widget) {
//FIXEDME: we don't need to calculate the content size of layout anymore
- var widgetSize = widget instanceof ccui.Layout ? widget._getLayoutAccumulatedSize() : widget.getContentSize();
- return widget.convertToWorldSpace(cc.p(widgetSize.width /2, widgetSize.height /2));
+ var widgetSize = widget instanceof ccui.Layout ? widget._getLayoutAccumulatedSize() : widget.getContentSize();
+ return widget.convertToWorldSpace(cc.p(widgetSize.width / 2, widgetSize.height / 2));
},
/**
@@ -1122,9 +1166,9 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {ccui.Widget} the next focused widget
* @private
*/
- _getNextFocusedWidget: function(direction, current){
+ _getNextFocusedWidget: function (direction, current) {
var nextWidget = null, locChildren = this._children;
- var previousWidgetPos = locChildren.indexOf(current);
+ var previousWidgetPos = locChildren.indexOf(current);
previousWidgetPos = previousWidgetPos + 1;
if (previousWidgetPos < locChildren.length) {
nextWidget = this._getChildWidgetByIndex(previousWidgetPos);
@@ -1159,8 +1203,8 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
return this._getNextFocusedWidget(direction, nextWidget);
} else
return (current instanceof ccui.Layout) ? current : ccui.Widget._focusedWidget;
- } else{
- if (this._isLastWidgetInContainer(current, direction)){
+ } else {
+ if (this._isLastWidgetInContainer(current, direction)) {
if (this._isWidgetAncestorSupportLoopFocus(this, direction))
return ccui.Widget.prototype.findNextFocusedWidget.call(this, direction, this);
return (current instanceof ccui.Layout) ? current : ccui.Widget._focusedWidget;
@@ -1177,14 +1221,14 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {ccui.Widget} the next focused widget
* @private
*/
- _getPreviousFocusedWidget: function(direction, current){
+ _getPreviousFocusedWidget: function (direction, current) {
var nextWidget = null, locChildren = this._children;
var previousWidgetPos = locChildren.indexOf(current);
previousWidgetPos = previousWidgetPos - 1;
- if (previousWidgetPos >= 0){
+ if (previousWidgetPos >= 0) {
nextWidget = this._getChildWidgetByIndex(previousWidgetPos);
if (nextWidget.isFocusEnabled()) {
- if (nextWidget instanceof ccui.Layout){
+ if (nextWidget instanceof ccui.Layout) {
nextWidget._isFocusPassing = true;
return nextWidget.findNextFocusedWidget(direction, nextWidget);
}
@@ -1192,13 +1236,13 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
return nextWidget;
} else
return this._getPreviousFocusedWidget(direction, nextWidget); //handling the disabled widget, there is no actual focus lose or get, so we don't need any envet
- }else {
- if (this._loopFocus){
+ } else {
+ if (this._loopFocus) {
if (this._checkFocusEnabledChild()) {
- previousWidgetPos = locChildren.length -1;
+ previousWidgetPos = locChildren.length - 1;
nextWidget = this._getChildWidgetByIndex(previousWidgetPos);
- if (nextWidget.isFocusEnabled()){
- if (nextWidget instanceof ccui.Layout){
+ if (nextWidget.isFocusEnabled()) {
+ if (nextWidget instanceof ccui.Layout) {
nextWidget._isFocusPassing = true;
return nextWidget.findNextFocusedWidget(direction, nextWidget);
} else {
@@ -1255,7 +1299,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {Boolean}
* @private
*/
- _isLastWidgetInContainer:function(widget, direction){
+ _isLastWidgetInContainer: function (widget, direction) {
var parent = widget.getParent();
if (parent == null || !(parent instanceof ccui.Layout))
return true;
@@ -1280,8 +1324,8 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
if (direction === ccui.Widget.UP)
return this._isLastWidgetInContainer(parent, direction);
- } else if(parent.getLayoutType() === ccui.Layout.LINEAR_VERTICAL){
- if (direction === ccui.Widget.UP){
+ } else if (parent.getLayoutType() === ccui.Layout.LINEAR_VERTICAL) {
+ if (direction === ccui.Widget.UP) {
if (index === 0)
return this._isLastWidgetInContainer(parent, direction);
else
@@ -1311,7 +1355,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {Boolean}
* @private
*/
- _isWidgetAncestorSupportLoopFocus: function(widget, direction){
+ _isWidgetAncestorSupportLoopFocus: function (widget, direction) {
var parent = widget.getParent();
if (parent == null || !(parent instanceof ccui.Layout))
return false;
@@ -1323,12 +1367,12 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
else
return this._isWidgetAncestorSupportLoopFocus(parent, direction);
}
- if (layoutType === ccui.Layout.LINEAR_VERTICAL){
+ if (layoutType === ccui.Layout.LINEAR_VERTICAL) {
if (direction === ccui.Widget.DOWN || direction === ccui.Widget.UP)
return true;
else
return this._isWidgetAncestorSupportLoopFocus(parent, direction);
- } else{
+ } else {
cc.assert(0, "invalid layout type");
return false;
}
@@ -1343,7 +1387,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {ccui.Widget}
* @private
*/
- _passFocusToChild: function(direction, current){
+ _passFocusToChild: function (direction, current) {
if (this._checkFocusEnabledChild()) {
var previousWidget = ccui.Widget.getCurrentFocusedWidget();
this._findProperSearchingFunctor(direction, previousWidget);
@@ -1357,7 +1401,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
this.dispatchFocusEvent(current, widget);
return widget;
}
- }else
+ } else
return this;
},
@@ -1366,9 +1410,9 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
* @returns {boolean}
* @private
*/
- _checkFocusEnabledChild: function(){
+ _checkFocusEnabledChild: function () {
var locChildren = this._children;
- for(var i = 0, len = locChildren.length; i < len; i++){
+ for (var i = 0, len = locChildren.length; i < len; i++) {
var widget = locChildren[i];
if (widget && widget instanceof ccui.Widget && widget.isFocusEnabled())
return true;
@@ -1393,7 +1437,7 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
},
_copySpecialProperties: function (layout) {
- if(!(layout instanceof ccui.Layout))
+ if (!(layout instanceof ccui.Layout))
return;
this.setBackGroundImageScale9Enabled(layout._backGroundScale9Enabled);
this.setBackGroundImage(layout._backGroundImageFileName, layout._bgImageTexType);
@@ -1414,13 +1458,13 @@ ccui.Layout = ccui.Widget.extend(/** @lends ccui.Layout# */{
/**
* force refresh widget layout
*/
- forceDoLayout: function(){
+ forceDoLayout: function () {
this.requestDoLayout();
this._doLayout();
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
return new ccui.Layout.WebGLRenderCmd(this);
else
return new ccui.Layout.CanvasRenderCmd(this);
@@ -1524,4 +1568,4 @@ ccui.Layout.BACKGROUND_IMAGE_ZORDER = -1;
* @type {number}
* @constant
*/
-ccui.Layout.BACKGROUND_RENDERER_ZORDER = -2;
\ No newline at end of file
+ccui.Layout.BACKGROUND_RENDERER_ZORDER = -2;
diff --git a/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js b/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js
index aa78743222..7d847ccedd 100644
--- a/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js
+++ b/extensions/ccui/layouts/UILayoutCanvasRenderCmd.js
@@ -23,54 +23,21 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- ccui.Layout.CanvasRenderCmd = function(renderable){
- ccui.ProtectedNode.CanvasRenderCmd.call(this, renderable);
+(function () {
+ ccui.Layout.CanvasRenderCmd = function (renderable) {
+ this._pNodeCmdCtor(renderable);
this._needDraw = false;
- this._rendererSaveCmd = new cc.CustomRenderCmd(this, this._onRenderSaveCmd);
- this._rendererClipCmd = new cc.CustomRenderCmd(this, this._onRenderClipCmd);
- this._rendererRestoreCmd = new cc.CustomRenderCmd(this, this._onRenderRestoreCmd);
- this._rendererSaveCmd._canUseDirtyRegion = true;
- this._rendererClipCmd._canUseDirtyRegion = true;
- this._rendererRestoreCmd._canUseDirtyRegion = true;
+ this._rendererSaveCmd = null;
+ this._rendererClipCmd = null;
+ this._rendererRestoreCmd = null;
};
var proto = ccui.Layout.CanvasRenderCmd.prototype = Object.create(ccui.ProtectedNode.CanvasRenderCmd.prototype);
proto.constructor = ccui.Layout.CanvasRenderCmd;
+ proto._layoutCmdCtor = ccui.Layout.CanvasRenderCmd;
- cc.game.addEventListener(cc.game.EVENT_RENDERER_INITED, function () {
- if (ccui.Widget.CanvasRenderCmd) {
- ccui.Layout.CanvasRenderCmd.prototype.widgetVisit = ccui.Widget.CanvasRenderCmd.prototype.widgetVisit;
- }
- });
-
- proto.visit = function(parentCmd){
- var node = this._node;
- if (!node._visible)
- return;
- node._adaptRenderers();
- node._doLayout();
-
- if (node._clippingEnabled) {
- switch (node._clippingType) {
- case ccui.Layout.CLIPPING_STENCIL:
- this.stencilClippingVisit(parentCmd);
- break;
- case ccui.Layout.CLIPPING_SCISSOR:
- this.scissorClippingVisit(parentCmd);
- break;
- default:
- break;
- }
- } else {
- this.widgetVisit(parentCmd);
- }
- };
-
- proto.layoutVisit = proto.visit;
-
- proto._onRenderSaveCmd = function(ctx, scaleX, scaleY){
+ proto._onRenderSaveCmd = function (ctx, scaleX, scaleY) {
var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
wrapper.save();
wrapper.save();
@@ -81,31 +48,31 @@
var element = buffer[i], vertices = element.verts;
var firstPoint = vertices[0];
context.beginPath();
- context.moveTo(firstPoint.x, -firstPoint.y );
+ context.moveTo(firstPoint.x, -firstPoint.y);
for (var j = 1, len = vertices.length; j < len; j++)
- context.lineTo(vertices[j].x , -vertices[j].y );
+ context.lineTo(vertices[j].x, -vertices[j].y);
context.closePath();
}
};
- proto._onRenderClipCmd = function(ctx){
+ proto._onRenderClipCmd = function (ctx) {
var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
wrapper.restore();
context.clip();
};
- proto._onRenderRestoreCmd = function(ctx){
+ proto._onRenderRestoreCmd = function (ctx) {
var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
wrapper.restore();
};
- proto.rebindStencilRendering = function(stencil){
+ proto.rebindStencilRendering = function (stencil) {
stencil._renderCmd.rendering = this.__stencilDraw;
stencil._renderCmd._canUseDirtyRegion = true;
};
- proto.__stencilDraw = function(ctx,scaleX, scaleY){ //Only for Canvas
+ proto.__stencilDraw = function (ctx, scaleX, scaleY) { //Only for Canvas
//do nothing, rendering in layout
};
@@ -114,42 +81,23 @@
if (!node._clippingStencil || !node._clippingStencil.isVisible())
return;
- this._syncStatus(parentCmd);
+ if (!this._rendererSaveCmd) {
+ this._rendererSaveCmd = new cc.CustomRenderCmd(this, this._onRenderSaveCmd);
+ this._rendererClipCmd = new cc.CustomRenderCmd(this, this._onRenderClipCmd);
+ this._rendererRestoreCmd = new cc.CustomRenderCmd(this, this._onRenderRestoreCmd);
+ }
cc.renderer.pushRenderCommand(this._rendererSaveCmd);
node._clippingStencil.visit(this);
cc.renderer.pushRenderCommand(this._rendererClipCmd);
- node.sortAllChildren();
- node.sortAllProtectedChildren();
-
- var children = node._children;
- var j=0, locProtectChildren = node._protectedChildren, i = 0, locChild;
- var iLen = children.length, jLen = locProtectChildren.length;
-
- for( ; i < iLen; i++ ){
- locChild = children[i];
- if ( locChild && locChild.getLocalZOrder() < 0 )
- locChild.visit(this);
- else
- break;
- }
- for( ; j < jLen; j++ ) {
- locChild = locProtectChildren[j];
- if ( locChild && locChild.getLocalZOrder() < 0 )
- locChild.visit(this);
- else
- break;
- }
- for (; i < iLen; i++)
- children[i].visit(this);
- for (; j < jLen; j++)
- locProtectChildren[j].visit(this);
- cc.renderer.pushRenderCommand(this._rendererRestoreCmd);
- this._dirtyFlag = 0;
+ };
+
+ proto.postStencilVisit = proto.postScissorVisit = function () {
+ cc.renderer.pushRenderCommand(this._rendererRestoreCmd);
};
ccui.Layout.CanvasRenderCmd._getSharedCache = function () {
return (cc.ClippingNode._sharedCache) || (cc.ClippingNode._sharedCache = document.createElement("canvas"));
};
-})();
\ No newline at end of file
+})();
diff --git a/extensions/ccui/layouts/UILayoutManager.js b/extensions/ccui/layouts/UILayoutManager.js
index d69a36618c..9f89d13e75 100644
--- a/extensions/ccui/layouts/UILayoutManager.js
+++ b/extensions/ccui/layouts/UILayoutManager.js
@@ -45,7 +45,7 @@ ccui.getLayoutManager = function (type) {
* @name ccui.linearVerticalLayoutManager
*/
ccui.linearVerticalLayoutManager = /** @lends ccui.linearVerticalLayoutManager# */{
- _doLayout: function(layout){
+ _doLayout: function (layout) {
var layoutSize = layout._getLayoutContentSize();
var container = layout._getLayoutElements();
var topBoundary = layoutSize.height;
@@ -55,13 +55,13 @@ ccui.linearVerticalLayoutManager = /** @lends ccui.linearVerticalLayoutManager#
if (child) {
var layoutParameter = child.getLayoutParameter();
- if (layoutParameter){
+ if (layoutParameter) {
var childGravity = layoutParameter.getGravity();
var ap = child.getAnchorPoint();
var cs = child.getContentSize();
var finalPosX = ap.x * cs.width;
var finalPosY = topBoundary - ((1.0 - ap.y) * cs.height);
- switch (childGravity){
+ switch (childGravity) {
case ccui.LinearLayoutParameter.NONE:
case ccui.LinearLayoutParameter.LEFT:
break;
@@ -91,21 +91,21 @@ ccui.linearVerticalLayoutManager = /** @lends ccui.linearVerticalLayoutManager#
* @name ccui.linearHorizontalLayoutManager
*/
ccui.linearHorizontalLayoutManager = /** @lends ccui.linearHorizontalLayoutManager# */{
- _doLayout: function(layout){
+ _doLayout: function (layout) {
var layoutSize = layout._getLayoutContentSize();
var container = layout._getLayoutElements();
var leftBoundary = 0.0;
- for (var i = 0, len = container.length; i < len; i++) {
+ for (var i = 0, len = container.length; i < len; i++) {
var child = container[i];
if (child) {
var layoutParameter = child.getLayoutParameter();
- if (layoutParameter){
+ if (layoutParameter) {
var childGravity = layoutParameter.getGravity();
var ap = child.getAnchorPoint();
var cs = child.getContentSize();
var finalPosX = leftBoundary + (ap.x * cs.width);
var finalPosY = layoutSize.height - (1.0 - ap.y) * cs.height;
- switch (childGravity){
+ switch (childGravity) {
case ccui.LinearLayoutParameter.NONE:
case ccui.LinearLayoutParameter.TOP:
break;
@@ -138,16 +138,16 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
_unlayoutChildCount: 0,
_widgetChildren: [],
_widget: null,
- _finalPositionX:0,
- _finalPositionY:0,
- _relativeWidgetLP:null,
+ _finalPositionX: 0,
+ _finalPositionY: 0,
+ _relativeWidgetLP: null,
- _doLayout: function(layout){
+ _doLayout: function (layout) {
this._widgetChildren = this._getAllWidgets(layout);
var locChildren = this._widgetChildren;
while (this._unlayoutChildCount > 0) {
- for (var i = 0, len = locChildren.length; i < len; i++) {
+ for (var i = 0, len = locChildren.length; i < len; i++) {
this._widget = locChildren[i];
var layoutParameter = this._widget.getLayoutParameter();
@@ -170,11 +170,11 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
this._widgetChildren.length = 0;
},
- _getAllWidgets: function(layout){
+ _getAllWidgets: function (layout) {
var container = layout._getLayoutElements();
var locWidgetChildren = this._widgetChildren;
locWidgetChildren.length = 0;
- for (var i = 0, len = container.length; i < len; i++){
+ for (var i = 0, len = container.length; i < len; i++) {
var child = container[i];
if (child && child instanceof ccui.Widget) {
var layoutParameter = child.getLayoutParameter();
@@ -186,18 +186,18 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
return locWidgetChildren;
},
- _getRelativeWidget: function(widget){
+ _getRelativeWidget: function (widget) {
var relativeWidget = null;
var layoutParameter = widget.getLayoutParameter();
var relativeName = layoutParameter.getRelativeToWidgetName();
if (relativeName && relativeName.length !== 0) {
- var locChildren = this._widgetChildren;
- for(var i = 0, len = locChildren.length; i < len; i++){
+ var locChildren = this._widgetChildren;
+ for (var i = 0, len = locChildren.length; i < len; i++) {
var child = locChildren[i];
if (child){
var rlayoutParameter = child.getLayoutParameter();
- if (rlayoutParameter && rlayoutParameter.getRelativeName() === relativeName) {
+ if (rlayoutParameter && rlayoutParameter.getRelativeName() === relativeName) {
relativeWidget = child;
this._relativeWidgetLP = rlayoutParameter;
break;
@@ -208,7 +208,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
return relativeWidget;
},
- _calculateFinalPositionWithRelativeWidget: function(layout){
+ _calculateFinalPositionWithRelativeWidget: function (layout) {
var locWidget = this._widget;
var ap = locWidget.getAnchorPoint();
var cs = locWidget.getContentSize();
@@ -261,7 +261,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
break;
case ccui.RelativeLayoutParameter.LOCATION_ABOVE_LEFTALIGN:
- if (relativeWidget){
+ if (relativeWidget) {
if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
return false;
this._finalPositionY = relativeWidget.getTopBoundary() + ap.y * cs.height;
@@ -269,7 +269,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
}
break;
case ccui.RelativeLayoutParameter.LOCATION_ABOVE_CENTER:
- if (relativeWidget){
+ if (relativeWidget) {
if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
return false;
var rbs = relativeWidget.getContentSize();
@@ -286,7 +286,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
}
break;
case ccui.RelativeLayoutParameter.LOCATION_LEFT_OF_TOPALIGN:
- if (relativeWidget){
+ if (relativeWidget) {
if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
return false;
this._finalPositionY = relativeWidget.getTopBoundary() - (1.0 - ap.y) * cs.height;
@@ -311,7 +311,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
}
break;
case ccui.RelativeLayoutParameter.LOCATION_RIGHT_OF_TOPALIGN:
- if (relativeWidget){
+ if (relativeWidget) {
if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
return false;
this._finalPositionY = relativeWidget.getTopBoundary() - (1.0 - ap.y) * cs.height;
@@ -319,7 +319,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
}
break;
case ccui.RelativeLayoutParameter.LOCATION_RIGHT_OF_CENTER:
- if (relativeWidget){
+ if (relativeWidget) {
if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
return false;
var rbs = relativeWidget.getContentSize();
@@ -329,7 +329,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
}
break;
case ccui.RelativeLayoutParameter.LOCATION_RIGHT_OF_BOTTOMALIGN:
- if (relativeWidget){
+ if (relativeWidget) {
if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
return false;
this._finalPositionY = relativeWidget.getBottomBoundary() + ap.y * cs.height;
@@ -337,10 +337,10 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
}
break;
case ccui.RelativeLayoutParameter.LOCATION_BELOW_LEFTALIGN:
- if (relativeWidget){
+ if (relativeWidget) {
if (this._relativeWidgetLP && !this._relativeWidgetLP._put)
return false;
- this._finalPositionY = relativeWidget.getBottomBoundary() - (1.0 - ap.y) * cs.height;
+ this._finalPositionY = relativeWidget.getBottomBoundary() - (1.0 - ap.y) * cs.height;
this._finalPositionX = relativeWidget.getLeftBoundary() + ap.x * cs.width;
}
break;
@@ -367,7 +367,7 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
return true;
},
- _calculateFinalPositionWithRelativeAlign: function(){
+ _calculateFinalPositionWithRelativeAlign: function () {
var layoutParameter = this._widget.getLayoutParameter();
var mg = layoutParameter.getMargin();
@@ -454,4 +454,4 @@ ccui.relativeLayoutManager = /** @lends ccui.relativeLayoutManager# */{
break;
}
}
-};
\ No newline at end of file
+};
diff --git a/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js
index 9fd8544f8c..e83dc0c765 100644
--- a/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js
+++ b/extensions/ccui/layouts/UILayoutWebGLRenderCmd.js
@@ -23,11 +23,11 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- if(!ccui.ProtectedNode.WebGLRenderCmd)
+(function () {
+ if (!ccui.ProtectedNode.WebGLRenderCmd)
return;
- ccui.Layout.WebGLRenderCmd = function(renderable){
- ccui.ProtectedNode.WebGLRenderCmd.call(this, renderable);
+ ccui.Layout.WebGLRenderCmd = function (renderable) {
+ this._pNodeCmdCtor(renderable);
this._needDraw = false;
this._currentStencilEnabled = 0;
@@ -36,46 +36,25 @@
this._mask_layer_le = 0;
- this._beforeVisitCmdStencil = new cc.CustomRenderCmd(this, this._onBeforeVisitStencil);
- this._afterDrawStencilCmd = new cc.CustomRenderCmd(this, this._onAfterDrawStencil);
- this._afterVisitCmdStencil = new cc.CustomRenderCmd(this, this._onAfterVisitStencil);
- this._beforeVisitCmdScissor = new cc.CustomRenderCmd(this, this._onBeforeVisitScissor);
- this._afterVisitCmdScissor = new cc.CustomRenderCmd(this, this._onAfterVisitScissor);
+ this._beforeVisitCmdStencil = null;
+ this._afterDrawStencilCmd = null;
+ this._afterVisitCmdStencil = null;
+ this._beforeVisitCmdScissor = null;
+ this._afterVisitCmdScissor = null;
};
var proto = ccui.Layout.WebGLRenderCmd.prototype = Object.create(ccui.ProtectedNode.WebGLRenderCmd.prototype);
proto.constructor = ccui.Layout.WebGLRenderCmd;
+ proto._layoutCmdCtor = ccui.Layout.CanvasRenderCmd;
- proto.visit = function(parentCmd){
- var node = this._node;
- if (!node._visible)
- return;
+ proto._syncStatus = function (parentCmd) {
+ this._originSyncStatus(parentCmd);
- if(parentCmd && (parentCmd._dirtyFlag & cc.Node._dirtyFlags.transformDirty))
- node._clippingRectDirty = true;
-
- node._adaptRenderers();
- node._doLayout();
-
- if (node._clippingEnabled) {
- switch (node._clippingType) {
- case ccui.Layout.CLIPPING_STENCIL:
- this.stencilClippingVisit(parentCmd);
- break;
- case ccui.Layout.CLIPPING_SCISSOR:
- this.scissorClippingVisit(parentCmd);
- break;
- default:
- break;
- }
- } else {
- this.pNodeVisit(parentCmd);
- }
+ if (parentCmd && (parentCmd._dirtyFlag & cc.Node._dirtyFlags.transformDirty))
+ this._node._clippingRectDirty = true;
};
-
- proto.layoutVisit = proto.visit;
-
- proto._onBeforeVisitStencil = function(ctx){
+
+ proto._onBeforeVisitStencil = function (ctx) {
var gl = ctx || cc._renderContext;
ccui.Layout.WebGLRenderCmd._layer++;
@@ -98,23 +77,21 @@
gl.stencilMask(mask_layer);
gl.clear(gl.STENCIL_BUFFER_BIT);
-
};
- proto._onAfterDrawStencil = function(ctx){
+ proto._onAfterDrawStencil = function (ctx) {
var gl = ctx || cc._renderContext;
gl.depthMask(true);
gl.stencilFunc(gl.EQUAL, this._mask_layer_le, this._mask_layer_le);
gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
};
- proto._onAfterVisitStencil = function(ctx){
+ proto._onAfterVisitStencil = function (ctx) {
var gl = ctx || cc._renderContext;
ccui.Layout.WebGLRenderCmd._layer--;
- if (this._currentStencilEnabled)
- {
+ if (this._currentStencilEnabled) {
var mask_layer = 0x1 << ccui.Layout.WebGLRenderCmd._layer;
var mask_layer_l = mask_layer - 1;
var mask_layer_le = mask_layer | mask_layer_l;
@@ -122,13 +99,12 @@
gl.stencilMask(mask_layer);
gl.stencilFunc(gl.EQUAL, mask_layer_le, mask_layer_le);
}
- else
- {
+ else {
gl.disable(gl.STENCIL_TEST);
}
};
- proto._onBeforeVisitScissor = function(ctx){
+ proto._onBeforeVisitScissor = function (ctx) {
this._node._clippingRectDirty = true;
var clippingRect = this._node._getClippingRect();
var gl = ctx || cc._renderContext;
@@ -146,11 +122,11 @@
}
};
- proto._onAfterVisitScissor = function(ctx){
+ proto._onAfterVisitScissor = function (ctx) {
var gl = ctx || cc._renderContext;
if (this._scissorOldState) {
if (!cc.rectEqualToRect(this._clippingOldRect, this._node._clippingRect)) {
- cc.view.setScissorInPoints( this._clippingOldRect.x,
+ cc.view.setScissorInPoints(this._clippingOldRect.x,
this._clippingOldRect.y,
this._clippingOldRect.width,
this._clippingOldRect.height);
@@ -160,13 +136,14 @@
gl.disable(gl.SCISSOR_TEST);
}
};
-
- proto.rebindStencilRendering = function(stencil){};
- proto.transform = function(parentCmd, recursive){
+ proto.rebindStencilRendering = function (stencil) {
+ };
+
+ proto.transform = function (parentCmd, recursive) {
var node = this._node;
this.pNodeTransform(parentCmd, recursive);
- if(node._clippingStencil)
+ if (node._clippingStencil)
node._clippingStencil._renderCmd.transform(this, recursive);
};
@@ -184,60 +161,41 @@
ccui.Layout.WebGLRenderCmd._visit_once = false;
}
// draw everything, as if there where no stencil
- cc.Node.prototype.visit.call(node, parentCmd);
return;
}
+ if (!this._beforeVisitCmdStencil) {
+ this._beforeVisitCmdStencil = new cc.CustomRenderCmd(this, this._onBeforeVisitStencil);
+ this._afterDrawStencilCmd = new cc.CustomRenderCmd(this, this._onAfterDrawStencil);
+ this._afterVisitCmdStencil = new cc.CustomRenderCmd(this, this._onAfterVisitStencil);
+ }
+
cc.renderer.pushRenderCommand(this._beforeVisitCmdStencil);
//optimize performance for javascript
var currentStack = cc.current_stack;
currentStack.stack.push(currentStack.top);
- this._syncStatus(parentCmd);
- this._dirtyFlag = 0;
currentStack.top = this._stackMatrix;
node._clippingStencil.visit(this);
cc.renderer.pushRenderCommand(this._afterDrawStencilCmd);
+ };
- // draw (according to the stencil test func) this node and its childs
- var i = 0; // used by _children
- var j = 0; // used by _protectedChildren
-
- node.sortAllChildren();
- node.sortAllProtectedChildren();
- var locChildren = node._children, locProtectChildren = node._protectedChildren;
- var iLen = locChildren.length, jLen = locProtectChildren.length, child;
- for( ; i < iLen; i++ ){
- child = locChildren[i];
- if ( child && child.getLocalZOrder() < 0 )
- child.visit(this);
- else
- break;
- }
- for( ; j < jLen; j++ ) {
- child = locProtectChildren[j];
- if ( child && child.getLocalZOrder() < 0 )
- child.visit(this);
- else
- break;
- }
-
- for (; i < iLen; i++)
- locChildren[i].visit(this);
- for (; j < jLen; j++)
- locProtectChildren[j].visit(this);
-
- cc.renderer.pushRenderCommand(this._afterVisitCmdStencil);
-
- //optimize performance for javascript
- currentStack.top = currentStack.stack.pop();
+ proto.postStencilVisit = function () {
+ renderer.pushRenderCommand(cmd._afterVisitCmdStencil);
+ cc.current_stack.top = cc.current_stack.stack.pop();
};
- proto.scissorClippingVisit = function(parentCmd){
+ proto.scissorClippingVisit = function (parentCmd) {
+ if (!this._beforeVisitCmdScissor) {
+ this._beforeVisitCmdScissor = new cc.CustomRenderCmd(this, this._onBeforeVisitScissor);
+ this._afterVisitCmdScissor = new cc.CustomRenderCmd(this, this._onAfterVisitScissor);
+ }
cc.renderer.pushRenderCommand(this._beforeVisitCmdScissor);
- this.pNodeVisit(parentCmd);
+ };
+
+ proto.postScissorVisit = function () {
cc.renderer.pushRenderCommand(this._afterVisitCmdScissor);
};
diff --git a/extensions/ccui/system/UIHelper.js b/extensions/ccui/system/UIHelper.js
index ec4ba83de5..327bf8dca6 100644
--- a/extensions/ccui/system/UIHelper.js
+++ b/extensions/ccui/system/UIHelper.js
@@ -32,71 +32,71 @@
* @name ccui.helper
*/
ccui.helper = {
- /**
- * Finds a widget whose tag equals to param tag from root widget.
- * @param {ccui.Widget} root
- * @param {number} tag
- * @returns {ccui.Widget}
- */
- seekWidgetByTag: function (root, tag) {
- if (!root)
- return null;
- if (root.getTag() === tag)
- return root;
-
- var arrayRootChildren = root.getChildren();
- var length = arrayRootChildren.length;
- for (var i = 0; i < length; i++) {
- var child = arrayRootChildren[i];
- var res = ccui.helper.seekWidgetByTag(child, tag);
- if (res !== null)
- return res;
- }
- return null;
- },
-
- /**
- * Finds a widget whose name equals to param name from root widget.
- * @param {ccui.Widget} root
- * @param {String} name
- * @returns {ccui.Widget}
- */
- seekWidgetByName: function (root, name) {
- if (!root)
- return null;
- if (root.getName() === name)
- return root;
- var arrayRootChildren = root.getChildren();
- var length = arrayRootChildren.length;
- for (var i = 0; i < length; i++) {
- var child = arrayRootChildren[i];
- var res = ccui.helper.seekWidgetByName(child, name);
- if (res !== null)
- return res;
- }
- return null;
- },
-
- /**
- * Finds a widget whose name equals to param name from root widget.
- * RelativeLayout will call this method to find the widget witch is needed.
- * @param {ccui.Widget} root
- * @param {String} name
- * @returns {ccui.Widget}
- */
- seekWidgetByRelativeName: function (root, name) {
- if (!root)
- return null;
- var arrayRootChildren = root.getChildren();
- var length = arrayRootChildren.length;
- for (var i = 0; i < length; i++) {
- var child = arrayRootChildren[i];
- var layoutParameter = child.getLayoutParameter(ccui.LayoutParameter.RELATIVE);
- if (layoutParameter && layoutParameter.getRelativeName() === name)
- return child;
- }
- return null;
- },
+ /**
+ * Finds a widget whose tag equals to param tag from root widget.
+ * @param {ccui.Widget} root
+ * @param {number} tag
+ * @returns {ccui.Widget}
+ */
+ seekWidgetByTag: function (root, tag) {
+ if (!root)
+ return null;
+ if (root.getTag() === tag)
+ return root;
+
+ var arrayRootChildren = root.getChildren();
+ var length = arrayRootChildren.length;
+ for (var i = 0; i < length; i++) {
+ var child = arrayRootChildren[i];
+ var res = ccui.helper.seekWidgetByTag(child, tag);
+ if (res !== null)
+ return res;
+ }
+ return null;
+ },
+
+ /**
+ * Finds a widget whose name equals to param name from root widget.
+ * @param {ccui.Widget} root
+ * @param {String} name
+ * @returns {ccui.Widget}
+ */
+ seekWidgetByName: function (root, name) {
+ if (!root)
+ return null;
+ if (root.getName() === name)
+ return root;
+ var arrayRootChildren = root.getChildren();
+ var length = arrayRootChildren.length;
+ for (var i = 0; i < length; i++) {
+ var child = arrayRootChildren[i];
+ var res = ccui.helper.seekWidgetByName(child, name);
+ if (res !== null)
+ return res;
+ }
+ return null;
+ },
+
+ /**
+ * Finds a widget whose name equals to param name from root widget.
+ * RelativeLayout will call this method to find the widget witch is needed.
+ * @param {ccui.Widget} root
+ * @param {String} name
+ * @returns {ccui.Widget}
+ */
+ seekWidgetByRelativeName: function (root, name) {
+ if (!root)
+ return null;
+ var arrayRootChildren = root.getChildren();
+ var length = arrayRootChildren.length;
+ for (var i = 0; i < length; i++) {
+ var child = arrayRootChildren[i];
+ var layoutParameter = child.getLayoutParameter(ccui.LayoutParameter.RELATIVE);
+ if (layoutParameter && layoutParameter.getRelativeName() === name)
+ return child;
+ }
+ return null;
+ },
/**
* Finds a widget whose action tag equals to param name from root widget.
@@ -104,28 +104,28 @@ ccui.helper = {
* @param {Number} tag
* @returns {ccui.Widget}
*/
- seekActionWidgetByActionTag: function (root, tag) {
- if (!root)
- return null;
- if (root.getActionTag() === tag)
- return root;
- var arrayRootChildren = root.getChildren();
- for (var i = 0; i < arrayRootChildren.length; i++) {
- var child = arrayRootChildren[i];
- var res = ccui.helper.seekActionWidgetByActionTag(child, tag);
- if (res !== null)
- return res;
- }
- return null;
- } ,
+ seekActionWidgetByActionTag: function (root, tag) {
+ if (!root)
+ return null;
+ if (root.getActionTag() === tag)
+ return root;
+ var arrayRootChildren = root.getChildren();
+ for (var i = 0; i < arrayRootChildren.length; i++) {
+ var child = arrayRootChildren[i];
+ var res = ccui.helper.seekActionWidgetByActionTag(child, tag);
+ if (res !== null)
+ return res;
+ }
+ return null;
+ },
_activeLayout: true,
/**
* Refresh object and it's children layout state
* @param {cc.Node} rootNode
*/
- doLayout: function(rootNode){
- if(!this._activeLayout)
+ doLayout: function (rootNode) {
+ if (!this._activeLayout)
return;
var children = rootNode.getChildren(), node;
for(var i = 0, len = children.length;i < len; i++) {
@@ -137,7 +137,7 @@ ccui.helper = {
}
},
- changeLayoutSystemActiveState: function(active){
+ changeLayoutSystemActiveState: function (active) {
this._activeLayout = active;
},
@@ -162,10 +162,10 @@ ccui.helper = {
return cc.rect(x, y, width, height);
},
- _createSpriteFromBase64: function(base64String, key) {
+ _createSpriteFromBase64: function (base64String, key) {
var texture2D = cc.textureCache.getTextureForKey(key);
- if(!texture2D) {
+ if (!texture2D) {
var image = new Image();
image.src = base64String;
cc.textureCache.cacheImage(key, image);
diff --git a/extensions/ccui/uiwidgets/UIButton.js b/extensions/ccui/uiwidgets/UIButton.js
index fc65d2e6dd..4741e2e767 100644
--- a/extensions/ccui/uiwidgets/UIButton.js
+++ b/extensions/ccui/uiwidgets/UIButton.js
@@ -1,6 +1,7 @@
/****************************************************************************
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2015-2016 zilongshanren
http://www.cocos2d-x.org
@@ -32,13 +33,14 @@
* @property {String} titleFont - The content string font of the button title
* @property {Number} titleFontSize - The content string font size of the button title
* @property {String} titleFontName - The content string font name of the button title
- * @property {cc.Color} titleFontColor - The content string font color of the button title
+ * @property {cc.Color} titleColor - The content string font color of the button title
* @property {Boolean} pressedActionEnabled - Indicate whether button has zoom effect when clicked
*/
ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
- _buttonNormalRenderer: null,
- _buttonClickedRenderer: null,
- _buttonDisableRenderer: null,
+ _buttonScale9Renderer: null,
+ _buttonNormalSpriteFrame: null,
+ _buttonClickedSpriteFrame: null,
+ _buttonDisableSpriteFrame: null,
_titleRenderer: null,
_normalFileName: "",
@@ -49,23 +51,15 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
_scale9Enabled: false,
_capInsetsNormal: null,
- _capInsetsPressed: null,
- _capInsetsDisabled: null,
_normalTexType: ccui.Widget.LOCAL_TEXTURE,
_pressedTexType: ccui.Widget.LOCAL_TEXTURE,
_disabledTexType: ccui.Widget.LOCAL_TEXTURE,
_normalTextureSize: null,
- _pressedTextureSize: null,
- _disabledTextureSize: null,
pressedActionEnabled: false,
_titleColor: null,
- _normalTextureScaleXInSize: 1,
- _normalTextureScaleYInSize: 1,
- _pressedTextureScaleXInSize: 1,
- _pressedTextureScaleYInSize: 1,
_zoomScale: 0.1,
@@ -75,8 +69,6 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
_className: "Button",
_normalTextureAdaptDirty: true,
- _pressedTextureAdaptDirty: true,
- _disabledTextureAdaptDirty: true,
_fontName: "Thonburi",
_fontSize: 12,
@@ -95,33 +87,35 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
*/
ctor: function (normalImage, selectedImage, disableImage, texType) {
this._capInsetsNormal = cc.rect(0, 0, 0, 0);
- this._capInsetsPressed = cc.rect(0, 0, 0, 0);
- this._capInsetsDisabled = cc.rect(0, 0, 0, 0);
this._normalTextureSize = cc.size(0, 0);
- this._pressedTextureSize = cc.size(0, 0);
- this._disabledTextureSize = cc.size(0, 0);
- this._titleColor = cc.color.WHITE;
ccui.Widget.prototype.ctor.call(this);
this.setTouchEnabled(true);
+ this._normalLoader = new cc.Sprite.LoadManager();
+ this._clickedLoader = new cc.Sprite.LoadManager();
+ this._disabledLoader = new cc.Sprite.LoadManager();
+
if (normalImage) {
this.loadTextures(normalImage, selectedImage,disableImage, texType);
}
},
+ _createTitleRendererIfNeeded: function ( ) {
+ if(!this._titleRenderer) {
+ this._titleRenderer = new cc.LabelTTF("");
+ this._titleRenderer.setAnchorPoint(0.5, 0.5);
+ this._titleColor = cc.color.WHITE;
+ this._titleRenderer.setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_CENTER);
+ this.addProtectedChild(this._titleRenderer, ccui.Button.TITLE_RENDERER_ZORDER, -1);
+ }
+ },
+
_initRenderer: function () {
- //todo create Scale9Sprite
- this._buttonNormalRenderer = new cc.Sprite();
- this._buttonClickedRenderer = new cc.Sprite();
- this._buttonDisableRenderer = new cc.Sprite();
- this._titleRenderer = new cc.LabelTTF("");
- this._titleRenderer.setAnchorPoint(0.5, 0.5);
- this._titleRenderer.setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_CENTER);
+ this._buttonScale9Renderer = new ccui.Scale9Sprite();
+
+ this._buttonScale9Renderer.setRenderingType(ccui.Scale9Sprite.RenderingType.SIMPLE);
- this.addProtectedChild(this._buttonNormalRenderer, ccui.Button.NORMAL_RENDERER_ZORDER, -1);
- this.addProtectedChild(this._buttonClickedRenderer, ccui.Button.PRESSED_RENDERER_ZORDER, -1);
- this.addProtectedChild(this._buttonDisableRenderer, ccui.Button.DISABLED_RENDERER_ZORDER, -1);
- this.addProtectedChild(this._titleRenderer, ccui.Button.TITLE_RENDERER_ZORDER, -1);
+ this.addProtectedChild(this._buttonScale9Renderer, ccui.Button.DISABLED_RENDERER_ZORDER, -1);
},
/**
@@ -129,37 +123,18 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
* @param {Boolean} able true that using scale9 renderer, false otherwise.
*/
setScale9Enabled: function (able) {
- //todo create Scale9Sprite
if (this._scale9Enabled === able)
return;
this._brightStyle = ccui.Widget.BRIGHT_STYLE_NONE;
this._scale9Enabled = able;
- this.removeProtectedChild(this._buttonNormalRenderer);
- this.removeProtectedChild(this._buttonClickedRenderer);
- this.removeProtectedChild(this._buttonDisableRenderer);
-
if (this._scale9Enabled) {
- this._buttonNormalRenderer = new ccui.Scale9Sprite();
- this._buttonClickedRenderer = new ccui.Scale9Sprite();
- this._buttonDisableRenderer = new ccui.Scale9Sprite();
+ this._buttonScale9Renderer.setRenderingType(ccui.Scale9Sprite.RenderingType.SLICED);
} else {
- this._buttonNormalRenderer = new cc.Sprite();
- this._buttonClickedRenderer = new cc.Sprite();
- this._buttonDisableRenderer = new cc.Sprite();
+ this._buttonScale9Renderer.setRenderingType(ccui.Scale9Sprite.RenderingType.SIMPLE);
}
- this._buttonClickedRenderer.setVisible(false);
- this._buttonDisableRenderer.setVisible(false);
-
- this.loadTextureNormal(this._normalFileName, this._normalTexType);
- this.loadTexturePressed(this._clickedFileName, this._pressedTexType);
- this.loadTextureDisabled(this._disabledFileName, this._disabledTexType);
-
- this.addProtectedChild(this._buttonNormalRenderer, ccui.Button.NORMAL_RENDERER_ZORDER, -1);
- this.addProtectedChild(this._buttonClickedRenderer, ccui.Button.PRESSED_RENDERER_ZORDER, -1);
- this.addProtectedChild(this._buttonDisableRenderer, ccui.Button.DISABLED_RENDERER_ZORDER, -1);
if (this._scale9Enabled) {
var ignoreBefore = this._ignoreSize;
this.ignoreContentAdaptWithSize(false);
@@ -167,14 +142,11 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
} else {
this.ignoreContentAdaptWithSize(this._prevIgnoreSize);
}
- this.setCapInsetsNormalRenderer(this._capInsetsNormal);
- this.setCapInsetsPressedRenderer(this._capInsetsPressed);
- this.setCapInsetsDisabledRenderer(this._capInsetsDisabled);
+ this.setCapInsets(this._capInsetsNormal);
+
this.setBright(this._bright);
this._normalTextureAdaptDirty = true;
- this._pressedTextureAdaptDirty = true;
- this._disabledTextureAdaptDirty = true;
},
/**
@@ -209,8 +181,10 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
if (this._unifySize)
return this._getNormalSize();
- if (!this._normalTextureLoaded && this._titleRenderer.getString().length > 0) {
- return this._titleRenderer.getContentSize();
+ if (!this._normalTextureLoaded ) {
+ if(this._titleRenderer && this._titleRenderer.getString().length > 0) {
+ return this._titleRenderer.getContentSize();
+ }
}
return cc.size(this._normalTextureSize);
},
@@ -228,52 +202,91 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
this.loadTextureDisabled(disabled, texType);
},
+ _createSpriteFrameWithFile: function (file) {
+ var texture = cc.textureCache.getTextureForKey(file);
+ if (!texture) {
+ texture = cc.textureCache.addImage(file);
+ }
+ if(!texture._textureLoaded) {
+ return texture;
+ }
+
+ var textureSize = texture.getContentSize();
+ var rect = cc.rect(0, 0, textureSize.width, textureSize.height);
+ return new cc.SpriteFrame(texture, rect);
+ },
+
+ _createSpriteFrameWithName: function (name) {
+ var frame = cc.spriteFrameCache.getSpriteFrame(name);
+ if (frame == null) {
+ cc.log("ccui.Scale9Sprite.initWithSpriteFrameName(): can't find the sprite frame by spriteFrameName");
+ return null;
+ }
+
+ return frame;
+ },
+
/**
* Load normal state texture for button.
* @param {String} normal normal state of texture's filename.
* @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType
*/
loadTextureNormal: function (normal, texType) {
- if (!normal)
- return;
+ if (!normal) return;
+
texType = texType || ccui.Widget.LOCAL_TEXTURE;
this._normalFileName = normal;
this._normalTexType = texType;
- var self = this;
- var normalRenderer = this._buttonNormalRenderer;
- if(!normalRenderer._textureLoaded){
- normalRenderer.addEventListener("load", function(){
- self.loadTextureNormal(self._normalFileName, self._normalTexType);
- });
- }
+ var normalSpriteFrame;
switch (this._normalTexType){
case ccui.Widget.LOCAL_TEXTURE:
- //SetTexture cannot load resource
- normalRenderer.initWithFile(normal);
- break;
+ normalSpriteFrame = this._createSpriteFrameWithFile(normal);
+ break;
case ccui.Widget.PLIST_TEXTURE:
- //SetTexture cannot load resource
- if (normal[0] === "#") {
- normal = normal.substr(1, normal.length - 1);
- }
- normalRenderer.initWithSpriteFrameName(normal);
- break;
- default:
- break;
+ if (normal[0] === "#") {
+ normal = normal.substr(1, normal.length - 1);
+ }
+ normalSpriteFrame = this._createSpriteFrameWithName(normal);
+ break;
+ default:
+ break;
+ }
+
+ if(!normalSpriteFrame) {
+ return;
}
- this._normalTextureLoaded = normalRenderer._textureLoaded;
+ if(!normalSpriteFrame._textureLoaded) {
+ this._normalLoader.clear();
+ this._normalLoader.once(normalSpriteFrame, function () {
+ this.loadTextureNormal(this._normalFileName, this._normalTexType);
+ }, this);
+ return;
+ }
- this._normalTextureSize = this._buttonNormalRenderer.getContentSize();
+ this._normalTextureLoaded = normalSpriteFrame._textureLoaded;
+ this._buttonNormalSpriteFrame = normalSpriteFrame;
+ this._buttonScale9Renderer.setSpriteFrame(normalSpriteFrame);
+ if (this._scale9Enabled){
+ this._buttonScale9Renderer.setCapInsets(this._capInsetsNormal);
+ }
+
+ // FIXME: https://github.com/cocos2d/cocos2d-x/issues/12249
+ if(!this._ignoreSize && cc.sizeEqualToSize(this._customSize, cc.size(0, 0))) {
+ this._customSize = this._buttonScale9Renderer.getContentSize();
+ }
+
+ this._normalTextureSize = this._buttonScale9Renderer.getContentSize();
this._updateChildrenDisplayedRGBA();
if (this._unifySize){
if (this._scale9Enabled){
- normalRenderer.setCapInsets(this._capInsetsNormal);
+ this._buttonScale9Renderer.setCapInsets(this._capInsetsNormal);
this._updateContentSizeWithTextureSize(this._getNormalSize());
}
- }else
+ }else {
this._updateContentSizeWithTextureSize(this._normalTextureSize);
+ }
this._normalTextureAdaptDirty = true;
this._findLayout();
@@ -291,39 +304,35 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
this._clickedFileName = selected;
this._pressedTexType = texType;
- var self = this;
- var clickedRenderer = this._buttonClickedRenderer;
- if(!clickedRenderer._textureLoaded){
- clickedRenderer.addEventListener("load", function(){
- self.loadTexturePressed(self._clickedFileName, self._pressedTexType);
- });
- }
-
+ var clickedSpriteFrame;
switch (this._pressedTexType) {
- case ccui.Widget.LOCAL_TEXTURE:
- //SetTexture cannot load resource
- clickedRenderer.initWithFile(selected);
- break;
- case ccui.Widget.PLIST_TEXTURE:
- //SetTexture cannot load resource
- if (selected[0] === "#") {
- selected = selected.substr(1, selected.length - 1);
- }
- clickedRenderer.initWithSpriteFrameName(selected);
- break;
- default:
- break;
+ case ccui.Widget.LOCAL_TEXTURE:
+ clickedSpriteFrame = this._createSpriteFrameWithFile(selected);
+ break;
+ case ccui.Widget.PLIST_TEXTURE:
+ if (selected[0] === "#") {
+ selected = selected.substr(1, selected.length - 1);
+ }
+ clickedSpriteFrame = this._createSpriteFrameWithName(selected);
+ break;
+ default:
+ break;
}
- if (this._scale9Enabled)
- clickedRenderer.setCapInsets(this._capInsetsPressed);
+ if(!clickedSpriteFrame) return;
- this._pressedTextureSize = this._buttonClickedRenderer.getContentSize();
+ if(!clickedSpriteFrame._textureLoaded) {
+ this._clickedLoader.clear();
+ this._clickedLoader.once(clickedSpriteFrame, function () {
+ this.loadTexturePressed(this._clickedFileName, this._pressedTexType);
+ }, this);
+ return;
+ }
+
+ this._buttonClickedSpriteFrame = clickedSpriteFrame;
this._updateChildrenDisplayedRGBA();
this._pressedTextureLoaded = true;
- this._pressedTextureAdaptDirty = true;
- this._findLayout();
},
/**
@@ -339,38 +348,35 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
this._disabledFileName = disabled;
this._disabledTexType = texType;
- var self = this;
- var disabledRenderer = this._buttonDisableRenderer;
- if(!disabledRenderer._textureLoaded){
- disabledRenderer.addEventListener("load", function() {
- self.loadTextureDisabled(self._disabledFileName, self._disabledTexType);
- });
- }
-
+ var disabledSpriteframe;
switch (this._disabledTexType) {
- case ccui.Widget.LOCAL_TEXTURE:
- //SetTexture cannot load resource
- disabledRenderer.initWithFile(disabled);
- break;
- case ccui.Widget.PLIST_TEXTURE:
- //SetTexture cannot load resource
- if (disabled[0] === "#") {
- disabled = disabled.substr(1, disabled.length - 1);
- }
- disabledRenderer.initWithSpriteFrameName(disabled);
- break;
- default:
- break;
+ case ccui.Widget.LOCAL_TEXTURE:
+ disabledSpriteframe = this._createSpriteFrameWithFile(disabled);
+ break;
+ case ccui.Widget.PLIST_TEXTURE:
+ if (disabled[0] === "#") {
+ disabled = disabled.substr(1, disabled.length - 1);
+ }
+ disabledSpriteframe = this._createSpriteFrameWithName(disabled);
+ break;
+ default:
+ break;
}
- if (this._scale9Enabled)
- disabledRenderer.setCapInsets(this._capInsetsDisabled);
+ if(!disabledSpriteframe) return;
- this._disabledTextureSize = this._buttonDisableRenderer.getContentSize();
+ if(!disabledSpriteframe._textureLoaded) {
+ this._disabledLoader.clear();
+ this._disabledLoader.once(disabledSpriteframe, function () {
+ this.loadTextureDisabled(this._disabledFileName, this._disabledTexType);
+ }, this);
+ return;
+ }
+
+ this._buttonDisableSpriteFrame = disabledSpriteframe;
this._updateChildrenDisplayedRGBA();
this._disabledTextureLoaded = true;
- this._disabledTextureAdaptDirty = true;
this._findLayout();
},
@@ -380,8 +386,6 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
*/
setCapInsets: function (capInsets) {
this.setCapInsetsNormalRenderer(capInsets);
- this.setCapInsetsPressedRenderer(capInsets);
- this.setCapInsetsDisabledRenderer(capInsets);
},
/**
@@ -389,7 +393,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
* @param {cc.Rect} capInsets
*/
setCapInsetsNormalRenderer: function (capInsets) {
- if(!capInsets)
+ if(!capInsets || !this._scale9Enabled)
return;
var x = capInsets.x, y = capInsets.y;
@@ -409,9 +413,8 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
locInsets.width = width;
locInsets.height = height;
- if (!this._scale9Enabled)
- return;
- this._buttonNormalRenderer.setCapInsets(locInsets);
+ this._capInsetsNormal = locInsets;
+ this._buttonScale9Renderer.setCapInsets(locInsets);
},
/**
@@ -427,28 +430,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
* @param {cc.Rect} capInsets
*/
setCapInsetsPressedRenderer: function (capInsets) {
- if(!capInsets || !this._scale9Enabled)
- return;
-
- var x = capInsets.x, y = capInsets.y;
- var width = capInsets.width, height = capInsets.height;
-
- if (this._pressedTextureSize.width < width) {
- x = 0;
- width = 0;
- }
- if (this._pressedTextureSize.height < height) {
- y = 0;
- height = 0;
- }
-
- var locInsets = this._capInsetsPressed;
- locInsets.x = x;
- locInsets.y = y;
- locInsets.width = width;
- locInsets.height = height;
-
- this._buttonClickedRenderer.setCapInsets(locInsets);
+ this.setCapInsetsNormalRenderer(capInsets);
},
/**
@@ -456,7 +438,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
* @returns {cc.Rect}
*/
getCapInsetsPressedRenderer: function () {
- return cc.rect(this._capInsetsPressed);
+ return cc.rect(this._capInsetsNormal);
},
/**
@@ -464,28 +446,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
* @param {cc.Rect} capInsets
*/
setCapInsetsDisabledRenderer: function (capInsets) {
- if(!capInsets || !this._scale9Enabled)
- return;
-
- var x = capInsets.x, y = capInsets.y;
- var width = capInsets.width, height = capInsets.height;
-
- if (this._disabledTextureSize.width < width) {
- x = 0;
- width = 0;
- }
- if (this._disabledTextureSize.height < height) {
- y = 0;
- height = 0;
- }
-
- var locInsets = this._capInsetsDisabled;
- locInsets.x = x;
- locInsets.y = y;
- locInsets.width = width;
- locInsets.height = height;
-
- this._buttonDisableRenderer.setCapInsets(locInsets);
+ this.setCapInsetsNormalRenderer(capInsets);
},
/**
@@ -493,93 +454,95 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
* @returns {cc.Rect}
*/
getCapInsetsDisabledRenderer: function () {
- return cc.rect(this._capInsetsDisabled);
+ return cc.rect(this._capInsetsNormal);
},
_onPressStateChangedToNormal: function () {
- this._buttonNormalRenderer.setVisible(true);
- this._buttonClickedRenderer.setVisible(false);
- this._buttonDisableRenderer.setVisible(false);
- if (this._scale9Enabled)
- this._buttonNormalRenderer.setState( ccui.Scale9Sprite.state.NORMAL);
+ this._buttonScale9Renderer.setSpriteFrame(this._buttonNormalSpriteFrame);
+
+ this._buttonScale9Renderer.setState( ccui.Scale9Sprite.state.NORMAL);
+
if (this._pressedTextureLoaded) {
if (this.pressedActionEnabled){
- this._buttonNormalRenderer.stopAllActions();
- this._buttonClickedRenderer.stopAllActions();
- //var zoomAction = cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, this._normalTextureScaleXInSize, this._normalTextureScaleYInSize);
- //fixme: the zoomAction will run in the next frame which will cause the _buttonNormalRenderer to a wrong scale
- //this._buttonNormalRenderer.runAction(zoomAction);
- this._buttonNormalRenderer.setScale(this._normalTextureScaleXInSize, this._normalTextureScaleYInSize);
- this._buttonClickedRenderer.setScale(this._pressedTextureScaleXInSize, this._pressedTextureScaleYInSize);
-
- this._titleRenderer.stopAllActions();
- if (this._unifySize){
- var zoomTitleAction = cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, 1, 1);
- this._titleRenderer.runAction(zoomTitleAction);
- }else{
- this._titleRenderer.setScaleX(1);
- this._titleRenderer.setScaleY(1);
+ this._buttonScale9Renderer.stopAllActions();
+ this._buttonScale9Renderer.setScale(1.0);
+
+ if(this._titleRenderer) {
+ this._titleRenderer.stopAllActions();
+
+ if (this._unifySize){
+ var zoomTitleAction = cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, 1, 1);
+ this._titleRenderer.runAction(zoomTitleAction);
+ }else{
+ this._titleRenderer.setScaleX(1);
+ this._titleRenderer.setScaleY(1);
+ }
}
+
}
} else {
- this._buttonNormalRenderer.stopAllActions();
- this._buttonNormalRenderer.setScale(this._normalTextureScaleXInSize, this._normalTextureScaleYInSize);
+ this._buttonScale9Renderer.stopAllActions();
+ this._buttonScale9Renderer.setScale(1.0);
- this._titleRenderer.stopAllActions();
- if (this._scale9Enabled)
- this._buttonNormalRenderer.setColor(cc.color.WHITE);
+ if (this._scale9Enabled) {
+ this._buttonScale9Renderer.setColor(cc.color.WHITE);
+ }
- this._titleRenderer.setScaleX(1);
- this._titleRenderer.setScaleY(1);
+ if(this._titleRenderer) {
+ this._titleRenderer.stopAllActions();
+
+ this._titleRenderer.setScaleX(1);
+ this._titleRenderer.setScaleY(1);
+ }
}
},
_onPressStateChangedToPressed: function () {
- var locNormalRenderer = this._buttonNormalRenderer;
- if (this._scale9Enabled)
- locNormalRenderer.setState(ccui.Scale9Sprite.state.NORMAL);
+ this._buttonScale9Renderer.setState(ccui.Scale9Sprite.state.NORMAL);
if (this._pressedTextureLoaded) {
- locNormalRenderer.setVisible(false);
- this._buttonClickedRenderer.setVisible(true);
- this._buttonDisableRenderer.setVisible(false);
- if (this.pressedActionEnabled) {
- locNormalRenderer.stopAllActions();
- this._buttonClickedRenderer.stopAllActions();
- var zoomAction = cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, this._pressedTextureScaleXInSize + this._zoomScale,
- this._pressedTextureScaleYInSize + this._zoomScale);
- this._buttonClickedRenderer.runAction(zoomAction);
- locNormalRenderer.setScale(this._pressedTextureScaleXInSize + this._zoomScale, this._pressedTextureScaleYInSize + this._zoomScale);
+ this._buttonScale9Renderer.setSpriteFrame(this._buttonClickedSpriteFrame);
- this._titleRenderer.stopAllActions();
- this._titleRenderer.runAction(cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP, 1 + this._zoomScale, 1 + this._zoomScale));
+ if (this.pressedActionEnabled) {
+ this._buttonScale9Renderer.stopAllActions();
+
+ var zoomAction = cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP,
+ 1.0 + this._zoomScale,
+ 1.0 + this._zoomScale);
+ this._buttonScale9Renderer.runAction(zoomAction);
+
+ if(this._titleRenderer) {
+ this._titleRenderer.stopAllActions();
+ this._titleRenderer.runAction(cc.scaleTo(ccui.Button.ZOOM_ACTION_TIME_STEP,
+ 1 + this._zoomScale,
+ 1 + this._zoomScale));
+ }
}
} else {
- locNormalRenderer.setVisible(true);
- this._buttonClickedRenderer.setVisible(true);
- this._buttonDisableRenderer.setVisible(false);
- locNormalRenderer.stopAllActions();
- locNormalRenderer.setScale(this._normalTextureScaleXInSize + this._zoomScale, this._normalTextureScaleYInSize + this._zoomScale);
+ this._buttonScale9Renderer.setSpriteFrame(this._buttonClickedSpriteFrame);
+
+ this._buttonScale9Renderer.stopAllActions();
+ this._buttonScale9Renderer.setScale(1.0 + this._zoomScale, 1.0 + this._zoomScale);
- this._titleRenderer.stopAllActions();
- this._titleRenderer.setScaleX(1 + this._zoomScale);
- this._titleRenderer.setScaleY(1 + this._zoomScale);
+ if (this._titleRenderer) {
+ this._titleRenderer.stopAllActions();
+ this._titleRenderer.setScaleX(1 + this._zoomScale);
+ this._titleRenderer.setScaleY(1 + this._zoomScale);
+ }
}
},
_onPressStateChangedToDisabled: function () {
//if disable resource is null
if (!this._disabledTextureLoaded){
- if (this._normalTextureLoaded && this._scale9Enabled)
- this._buttonNormalRenderer.setState(ccui.Scale9Sprite.state.GRAY);
+ if (this._normalTextureLoaded) {
+ this._buttonScale9Renderer.setState(ccui.Scale9Sprite.state.GRAY);
+ }
}else{
- this._buttonNormalRenderer.setVisible(false);
- this._buttonDisableRenderer.setVisible(true);
+ this._buttonScale9Renderer.setSpriteFrame(this._buttonDisableSpriteFrame);
}
- this._buttonClickedRenderer.setVisible(false);
- this._buttonNormalRenderer.setScale(this._normalTextureScaleXInSize, this._normalTextureScaleYInSize);
- this._buttonClickedRenderer.setScale(this._pressedTextureScaleXInSize, this._pressedTextureScaleYInSize);
+ this._buttonScale9Renderer.setScale(1.0);
},
_updateContentSize: function(){
@@ -600,10 +563,10 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
_onSizeChanged: function () {
ccui.Widget.prototype._onSizeChanged.call(this);
- this._updateTitleLocation();
+ if(this._titleRenderer) {
+ this._updateTitleLocation();
+ }
this._normalTextureAdaptDirty = true;
- this._pressedTextureAdaptDirty = true;
- this._disabledTextureAdaptDirty = true;
},
/**
@@ -611,97 +574,12 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
* @returns {cc.Node}
*/
getVirtualRenderer: function () {
- if (this._bright) {
- switch (this._brightStyle) {
- case ccui.Widget.BRIGHT_STYLE_NORMAL:
- return this._buttonNormalRenderer;
- case ccui.Widget.BRIGHT_STYLE_HIGH_LIGHT:
- return this._buttonClickedRenderer;
- default:
- return null;
- }
- } else
- return this._buttonDisableRenderer;
+ return this._buttonScale9Renderer;
},
_normalTextureScaleChangedWithSize: function () {
- if(this._ignoreSize && !this._unifySize){
- if(!this._scale9Enabled){
- this._buttonNormalRenderer.setScale(1);
- this._normalTextureScaleXInSize = this._normalTextureScaleYInSize = 1;
- }
- }else{
- if (this._scale9Enabled){
- this._buttonNormalRenderer.setPreferredSize(this._contentSize);
- this._normalTextureScaleXInSize = this._normalTextureScaleYInSize = 1;
- this._buttonNormalRenderer.setScale(this._normalTextureScaleXInSize, this._normalTextureScaleYInSize);
- }else{
- var textureSize = this._normalTextureSize;
- if (textureSize.width <= 0 || textureSize.height <= 0)
- {
- this._buttonNormalRenderer.setScale(1);
- return;
- }
- var scaleX = this._contentSize.width / textureSize.width;
- var scaleY = this._contentSize.height / textureSize.height;
- this._buttonNormalRenderer.setScaleX(scaleX);
- this._buttonNormalRenderer.setScaleY(scaleY);
- this._normalTextureScaleXInSize = scaleX;
- this._normalTextureScaleYInSize = scaleY;
- }
- }
- this._buttonNormalRenderer.setPosition(this._contentSize.width / 2, this._contentSize.height / 2);
- },
-
- _pressedTextureScaleChangedWithSize: function () {
- if (this._ignoreSize && !this._unifySize) {
- if (!this._scale9Enabled) {
- this._buttonClickedRenderer.setScale(1);
- this._pressedTextureScaleXInSize = this._pressedTextureScaleYInSize = 1;
- }
- } else {
- if (this._scale9Enabled) {
- this._buttonClickedRenderer.setPreferredSize(this._contentSize);
- this._pressedTextureScaleXInSize = this._pressedTextureScaleYInSize = 1;
- this._buttonClickedRenderer.setScale(this._pressedTextureScaleXInSize, this._pressedTextureScaleYInSize);
- } else {
- var textureSize = this._pressedTextureSize;
- if (textureSize.width <= 0 || textureSize.height <= 0) {
- this._buttonClickedRenderer.setScale(1);
- return;
- }
- var scaleX = this._contentSize.width / textureSize.width;
- var scaleY = this._contentSize.height / textureSize.height;
- this._buttonClickedRenderer.setScaleX(scaleX);
- this._buttonClickedRenderer.setScaleY(scaleY);
- this._pressedTextureScaleXInSize = scaleX;
- this._pressedTextureScaleYInSize = scaleY;
- }
- }
- this._buttonClickedRenderer.setPosition(this._contentSize.width / 2, this._contentSize.height / 2);
- },
-
- _disabledTextureScaleChangedWithSize: function () {
- if(this._ignoreSize && !this._unifySize){
- if (this._scale9Enabled)
- this._buttonDisableRenderer.setScale(1);
- }else {
- if (this._scale9Enabled){
- this._buttonDisableRenderer.setScale(1);
- this._buttonDisableRenderer.setPreferredSize(this._contentSize);
- }else{
- var textureSize = this._disabledTextureSize;
- if (textureSize.width <= 0 || textureSize.height <= 0) {
- this._buttonDisableRenderer.setScale(1);
- return;
- }
- var scaleX = this._contentSize.width / textureSize.width;
- var scaleY = this._contentSize.height / textureSize.height;
- this._buttonDisableRenderer.setScaleX(scaleX);
- this._buttonDisableRenderer.setScaleY(scaleY);
- }
- }
- this._buttonDisableRenderer.setPosition(this._contentSize.width / 2, this._contentSize.height / 2);
+ this._buttonScale9Renderer.setContentSize(this._contentSize);
+ this._buttonScale9Renderer.setPosition(this._contentSize.width / 2, this._contentSize.height / 2);
},
_adaptRenderers: function(){
@@ -709,14 +587,6 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
this._normalTextureScaleChangedWithSize();
this._normalTextureAdaptDirty = false;
}
- if (this._pressedTextureAdaptDirty) {
- this._pressedTextureScaleChangedWithSize();
- this._pressedTextureAdaptDirty = false;
- }
- if (this._disabledTextureAdaptDirty) {
- this._disabledTextureScaleChangedWithSize();
- this._disabledTextureAdaptDirty = false;
- }
},
_updateTitleLocation: function(){
@@ -736,8 +606,10 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
* @param {String} text
*/
setTitleText: function (text) {
- if(text === this.getTitleText())
- return;
+ if(text === this.getTitleText()) return;
+
+ this._createTitleRendererIfNeeded();
+
this._titleRenderer.setString(text);
if (this._ignoreSize){
var s = this.getVirtualRendererSize();
@@ -752,7 +624,10 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
* @returns {String} text
*/
getTitleText: function () {
- return this._titleRenderer.getString();
+ if(this._titleRenderer) {
+ return this._titleRenderer.getString();
+ }
+ return "";
},
/**
@@ -760,6 +635,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
* @param {cc.Color} color
*/
setTitleColor: function (color) {
+ this._createTitleRendererIfNeeded();
this._titleRenderer.setFontFillColor(color);
},
@@ -768,7 +644,10 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
* @returns {cc.Color}
*/
getTitleColor: function () {
- return this._titleRenderer._getFillStyle();
+ if (this._titleRenderer) {
+ return this._titleRenderer._getFillStyle();
+ }
+ return cc.color.WHITE;
},
/**
@@ -776,6 +655,8 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
* @param {cc.Size} size
*/
setTitleFontSize: function (size) {
+ this._createTitleRendererIfNeeded();
+
this._titleRenderer.setFontSize(size);
this._fontSize = size;
},
@@ -785,7 +666,10 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
* @returns {Number}
*/
getTitleFontSize: function () {
- return this._titleRenderer.getFontSize();
+ if (this._titleRenderer) {
+ return this._titleRenderer.getFontSize();
+ }
+ return this._fontSize;
},
/**
@@ -821,6 +705,8 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
* @param {String} fontName
*/
setTitleFontName: function (fontName) {
+ this._createTitleRendererIfNeeded();
+
this._titleRenderer.setFontName(fontName);
this._fontName = fontName;
},
@@ -839,7 +725,10 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
* @returns {String}
*/
getTitleFontName: function () {
- return this._titleRenderer.getFontName();
+ if(this._titleRenderer) {
+ return this._titleRenderer.getFontName();
+ }
+ return this._fontName;
},
_setTitleFont: function (font) {
@@ -864,17 +753,19 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
_copySpecialProperties: function (uiButton) {
this._prevIgnoreSize = uiButton._prevIgnoreSize;
+ this._capInsetsNormal = uiButton._capInsetsNormal;
this.setScale9Enabled(uiButton._scale9Enabled);
+
this.loadTextureNormal(uiButton._normalFileName, uiButton._normalTexType);
this.loadTexturePressed(uiButton._clickedFileName, uiButton._pressedTexType);
this.loadTextureDisabled(uiButton._disabledFileName, uiButton._disabledTexType);
- this.setCapInsetsNormalRenderer(uiButton._capInsetsNormal);
- this.setCapInsetsPressedRenderer(uiButton._capInsetsPressed);
- this.setCapInsetsDisabledRenderer(uiButton._capInsetsDisabled);
- this.setTitleText(uiButton.getTitleText());
- this.setTitleFontName(uiButton.getTitleFontName());
- this.setTitleFontSize(uiButton.getTitleFontSize());
- this.setTitleColor(uiButton.getTitleColor());
+
+ if(uiButton._titleRenderer && uiButton._titleRenderer._string) {
+ this.setTitleText(uiButton.getTitleText());
+ this.setTitleFontName(uiButton.getTitleFontName());
+ this.setTitleFontSize(uiButton.getTitleFontSize());
+ this.setTitleColor(uiButton.getTitleColor());
+ }
this.setPressedActionEnabled(uiButton.pressedActionEnabled);
this.setZoomScale(uiButton._zoomScale);
},
@@ -884,9 +775,7 @@ ccui.Button = ccui.Widget.extend(/** @lends ccui.Button# */{
if (this._titleRenderer !== null)
titleSize = this._titleRenderer.getContentSize();
- var imageSize;
- if (this._buttonNormalRenderer !== null)
- imageSize = this._buttonNormalRenderer.getContentSize();
+ var imageSize = this._buttonScale9Renderer.getContentSize();
var width = titleSize.width > imageSize.width ? titleSize.width : imageSize.width;
var height = titleSize.height > imageSize.height ? titleSize.height : imageSize.height;
diff --git a/extensions/ccui/uiwidgets/UIImageView.js b/extensions/ccui/uiwidgets/UIImageView.js
index b7e6511bf9..fed3c958db 100644
--- a/extensions/ccui/uiwidgets/UIImageView.js
+++ b/extensions/ccui/uiwidgets/UIImageView.js
@@ -63,8 +63,8 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{
},
_initRenderer: function () {
- //todo create Scale9Sprite and setScale9Enabled(false)
- this._imageRenderer = new cc.Sprite();
+ this._imageRenderer = new ccui.Scale9Sprite();
+ this._imageRenderer.setRenderingType(ccui.Scale9Sprite.RenderingType.SIMPLE);
this.addProtectedChild(this._imageRenderer, ccui.ImageView.RENDERER_ZORDER, -1);
},
@@ -74,9 +74,7 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{
* @param {ccui.Widget.LOCAL_TEXTURE|ccui.Widget.PLIST_TEXTURE} texType
*/
loadTexture: function (fileName, texType) {
- //todo use this code when _initRenderer use Scale9Sprite
- //if (!fileName || (this._textureFile == fileName && this._imageTexType == texType)) {
- if (!fileName) {
+ if (!fileName || (this._textureFile == fileName && this._imageTexType == texType)) {
return;
}
var self = this;
@@ -85,12 +83,6 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{
this._imageTexType = texType;
var imageRenderer = self._imageRenderer;
- if(!imageRenderer._textureLoaded){
- imageRenderer.addEventListener("load", function(){
- self.loadTexture(self._textureFile, self._imageTexType);
- });
- }
-
switch (self._imageTexType) {
case ccui.Widget.LOCAL_TEXTURE:
if(self._scale9Enabled){
@@ -114,6 +106,28 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{
break;
}
+ if(!imageRenderer._textureLoaded){
+ var handleTextureLoadedEvent = function(){
+ imageRenderer.removeEventListener("load", handleTextureLoadedEvent);
+
+ if(!self._ignoreSize && cc.sizeEqualToSize(self._customSize, cc.size(0, 0))) {
+ self._customSize = self._imageRenderer.getContentSize();
+ }
+
+ self._imageTextureSize = imageRenderer.getContentSize();
+
+ self._updateChildrenDisplayedRGBA();
+
+ self._updateContentSizeWithTextureSize(self._imageTextureSize);
+ };
+
+ imageRenderer.addEventListener("load", handleTextureLoadedEvent);
+ }
+
+ if(!this._ignoreSize && cc.sizeEqualToSize(this._customSize, cc.size(0, 0))) {
+ this._customSize = this._imageRenderer.getContentSize();
+ }
+
self._imageTextureSize = imageRenderer.getContentSize();
this._updateChildrenDisplayedRGBA();
@@ -128,9 +142,8 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{
* Sets texture rect
* @param {cc.Rect} rect
*/
- setTextureRect: function (rect) {
- if (!this._scale9Enabled)
- this._imageRenderer.setTextureRect(rect);
+ setTextureRect: function () {
+ cc.warn('ImageView.setTextureRect is deprecated!');
},
/**
@@ -138,20 +151,17 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{
* @param {Boolean} able
*/
setScale9Enabled: function (able) {
- //todo setScale9Enabled
if (this._scale9Enabled === able)
return;
this._scale9Enabled = able;
- this.removeProtectedChild(this._imageRenderer);
- this._imageRenderer = null;
+
if (this._scale9Enabled) {
- this._imageRenderer = new ccui.Scale9Sprite();
+ this._imageRenderer.setRenderingType(ccui.Scale9Sprite.RenderingType.SLICED);
} else {
- this._imageRenderer = new cc.Sprite();
+ this._imageRenderer.setRenderingType(ccui.Scale9Sprite.RenderingType.SIMPLE);
}
- this.loadTexture(this._textureFile, this._imageTexType);
- this.addProtectedChild(this._imageRenderer, ccui.ImageView.RENDERER_ZORDER, -1);
+
if (this._scale9Enabled) {
var ignoreBefore = this._ignoreSize;
this.ignoreContentAdaptWithSize(false);
@@ -187,16 +197,15 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{
* @param {cc.Rect} capInsets
*/
setCapInsets: function (capInsets) {
- if(!capInsets)
- return;
+ if(!capInsets) return;
+
var locInsets = this._capInsets;
locInsets.x = capInsets.x;
locInsets.y = capInsets.y;
locInsets.width = capInsets.width;
locInsets.height = capInsets.height;
- if (!this._scale9Enabled)
- return;
+ if (!this._scale9Enabled) return;
this._imageRenderer.setCapInsets(capInsets);
},
@@ -238,23 +247,7 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{
},
_imageTextureScaleChangedWithSize: function () {
- if (this._ignoreSize) {
- if (!this._scale9Enabled)
- this._imageRenderer.setScale(1.0);
- } else {
- if (this._scale9Enabled){
- this._imageRenderer.setPreferredSize(this._contentSize);
- this._imageRenderer.setScale(1);
- } else {
- var textureSize = this._imageTextureSize;
- if (textureSize.width <= 0.0 || textureSize.height <= 0.0) {
- this._imageRenderer.setScale(1.0);
- return;
- }
- this._imageRenderer.setScaleX(this._contentSize.width / textureSize.width);
- this._imageRenderer.setScaleY(this._contentSize.height / textureSize.height);
- }
- }
+ this._imageRenderer.setContentSize(this._contentSize);
this._imageRenderer.setPosition(this._contentSize.width / 2.0, this._contentSize.height / 2.0);
},
@@ -274,9 +267,9 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{
_copySpecialProperties: function (imageView) {
if(imageView instanceof ccui.ImageView){
this._prevIgnoreSize = imageView._prevIgnoreSize;
- this.setScale9Enabled(imageView._scale9Enabled);
+ this._capInsets = imageView._capInsets;
this.loadTexture(imageView._textureFile, imageView._imageTexType);
- this.setCapInsets(imageView._capInsets);
+ this.setScale9Enabled(imageView._scale9Enabled);
}
},
/**
@@ -287,17 +280,12 @@ ccui.ImageView = ccui.Widget.extend(/** @lends ccui.ImageView# */{
* @override
*/
setContentSize: function(contentSize, height){
- if(height != null)
+ if (height) {
contentSize = cc.size(contentSize, height);
- ccui.Widget.prototype.setContentSize.call(this, contentSize);
- if(!this._scale9Enabled){
- var iContentSize = this._imageRenderer.getContentSize();
- this._imageRenderer.setScaleX(contentSize.width / iContentSize.width);
- this._imageRenderer.setScaleY(contentSize.height / iContentSize.height);
- }else{
- this._imageRenderer.setContentSize(contentSize);
}
+ ccui.Widget.prototype.setContentSize.call(this, contentSize);
+ this._imageRenderer.setContentSize(contentSize);
}
});
diff --git a/extensions/ccui/uiwidgets/UILoadingBar.js b/extensions/ccui/uiwidgets/UILoadingBar.js
index 9113121c6d..1fdba04c17 100644
--- a/extensions/ccui/uiwidgets/UILoadingBar.js
+++ b/extensions/ccui/uiwidgets/UILoadingBar.js
@@ -61,9 +61,9 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
this._capInsets = cc.rect(0, 0, 0, 0);
ccui.Widget.prototype.ctor.call(this);
- if(textureName !== undefined)
+ if (textureName !== undefined)
this.loadTexture(textureName);
- if(percentage !== undefined)
+ if (percentage !== undefined)
this.setPercent(percentage);
},
@@ -86,16 +86,16 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
switch (this._direction) {
case ccui.LoadingBar.TYPE_LEFT:
this._barRenderer.setAnchorPoint(0, 0.5);
- this._barRenderer.setPosition(0, this._contentSize.height*0.5);
- if (!this._scale9Enabled)
- this._barRenderer.setFlippedX(false);
+ this._barRenderer.setPosition(0, this._contentSize.height * 0.5);
+ if (!this._scale9Enabled)
+ this._barRenderer.setFlippedX(false);
break;
case ccui.LoadingBar.TYPE_RIGHT:
this._barRenderer.setAnchorPoint(1, 0.5);
- this._barRenderer.setPosition(this._totalLength,this._contentSize.height*0.5);
- if (!this._scale9Enabled)
- this._barRenderer.setFlippedX(true);
+ this._barRenderer.setPosition(this._totalLength, this._contentSize.height * 0.5);
+ if (!this._scale9Enabled)
+ this._barRenderer.setFlippedX(true);
break;
}
@@ -124,8 +124,8 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
var barRenderer = this._barRenderer;
var self = this;
- if(!barRenderer._textureLoaded){
- barRenderer.addEventListener("load", function(){
+ if (!barRenderer._textureLoaded) {
+ barRenderer.addEventListener("load", function () {
self.loadTexture(self._textureFile, self._renderBarTexType);
self._setPercent(self._percent);
});
@@ -148,12 +148,12 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
switch (this._direction) {
case ccui.LoadingBar.TYPE_LEFT:
- barRenderer.setAnchorPoint(0,0.5);
+ barRenderer.setAnchorPoint(0, 0.5);
if (!this._scale9Enabled)
barRenderer.setFlippedX(false);
break;
case ccui.LoadingBar.TYPE_RIGHT:
- barRenderer.setAnchorPoint(1,0.5);
+ barRenderer.setAnchorPoint(1, 0.5);
if (!this._scale9Enabled)
barRenderer.setFlippedX(true);
break;
@@ -207,7 +207,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
* @param {cc.Rect} capInsets
*/
setCapInsets: function (capInsets) {
- if(!capInsets)
+ if (!capInsets)
return;
var locInsets = this._capInsets;
locInsets.x = capInsets.x;
@@ -232,9 +232,9 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
* @param {number} percent percent value from 1 to 100.
*/
setPercent: function (percent) {
- if(percent > 100)
+ if (percent > 100)
percent = 100;
- if(percent < 0)
+ if (percent < 0)
percent = 0;
if (percent === this._percent)
return;
@@ -242,7 +242,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
this._setPercent(percent);
},
- _setPercent: function(){
+ _setPercent: function () {
var res, rect, spriteRenderer, spriteTextureRect;
if (this._totalLength <= 0)
@@ -274,7 +274,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
* @param {Number|cc.Size} contentSize
* @param {Number} [height]
*/
- setContentSize: function(contentSize, height){
+ setContentSize: function (contentSize, height) {
ccui.Widget.prototype.setContentSize.call(this, contentSize, height);
this._totalLength = (height === undefined) ? contentSize.width : contentSize;
},
@@ -292,8 +292,8 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
this._barRendererAdaptDirty = true;
},
- _adaptRenderers: function(){
- if (this._barRendererAdaptDirty){
+ _adaptRenderers: function () {
+ if (this._barRendererAdaptDirty) {
this._barRendererScaleChangedWithSize();
this._barRendererAdaptDirty = false;
}
@@ -315,7 +315,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
* Returns the texture size of renderer.
* @returns {cc.Size|*}
*/
- getVirtualRendererSize:function(){
+ getVirtualRendererSize: function () {
return cc.size(this._barRendererTextureSize);
},
@@ -340,7 +340,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
}
} else {
this._totalLength = locContentSize.width;
- if (this._scale9Enabled){
+ if (this._scale9Enabled) {
this._setScale9Scale();
locBarRender.setScale(1.0);
} else {
@@ -385,7 +385,7 @@ ccui.LoadingBar = ccui.Widget.extend(/** @lends ccui.LoadingBar# */{
},
_copySpecialProperties: function (loadingBar) {
- if(loadingBar instanceof ccui.LoadingBar){
+ if (loadingBar instanceof ccui.LoadingBar) {
this._prevIgnoreSize = loadingBar._prevIgnoreSize;
this.setScale9Enabled(loadingBar._scale9Enabled);
this.loadTexture(loadingBar._textureFile, loadingBar._renderBarTexType);
@@ -440,4 +440,4 @@ ccui.LoadingBar.TYPE_RIGHT = 1;
* @constant
* @type {number}
*/
-ccui.LoadingBar.RENDERER_ZORDER = -1;
\ No newline at end of file
+ccui.LoadingBar.RENDERER_ZORDER = -1;
diff --git a/extensions/ccui/uiwidgets/UIRichText.js b/extensions/ccui/uiwidgets/UIRichText.js
index 1247d00f7d..c0572561f4 100644
--- a/extensions/ccui/uiwidgets/UIRichText.js
+++ b/extensions/ccui/uiwidgets/UIRichText.js
@@ -32,7 +32,7 @@ ccui.RichElement = ccui.Class.extend(/** @lends ccui.RichElement# */{
_type: 0,
_tag: 0,
_color: null,
- _opacity:0,
+ _opacity: 0,
/**
* Constructor of ccui.RichElement
*/
@@ -46,7 +46,7 @@ ccui.RichElement = ccui.Class.extend(/** @lends ccui.RichElement# */{
this._color.b = color.b;
}
this._opacity = opacity || 0;
- if(opacity === undefined) {
+ if (opacity === undefined) {
this._color.a = color.a;
}
else {
@@ -256,7 +256,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{
removeElement: function (element) {
if (cc.isNumber(element))
this._richElements.splice(element, 1);
- else
+ else
cc.arrayRemoveObject(this._richElements, element);
this._formatTextDirty = true;
},
@@ -276,7 +276,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{
var elementRenderer = null;
switch (element._type) {
case ccui.RichElement.TEXT:
- if( element._fontDefinition)
+ if (element._fontDefinition)
elementRenderer = new cc.LabelTTF(element._text, element._fontDefinition);
else //todo: There may be ambiguous
elementRenderer = new cc.LabelTTF(element._text, element._fontName, element._fontSize);
@@ -300,7 +300,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{
element = locRichElements[i];
switch (element._type) {
case ccui.RichElement.TEXT:
- if( element._fontDefinition)
+ if (element._fontDefinition)
this._handleTextRenderer(element._text, element._fontDefinition, element._fontDefinition.fontSize, element._fontDefinition.fillStyle);
else
this._handleTextRenderer(element._text, element._fontName, element._fontSize, element._color);
@@ -329,10 +329,10 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{
* @private
*/
_handleTextRenderer: function (text, fontNameOrFontDef, fontSize, color) {
- if(text === "")
+ if (text === "")
return;
- if(text === "\n"){ //Force Line Breaking
+ if (text === "\n") { //Force Line Breaking
this._addNewLine();
return;
}
@@ -349,21 +349,20 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{
var cutWords = curText.substr(leftLength, curText.length - 1);
var validLeftLength = leftLength > 0;
- if(this._lineBreakOnSpace){
+ if (this._lineBreakOnSpace) {
var lastSpaceIndex = leftWords.lastIndexOf(' ');
- leftLength = lastSpaceIndex === -1 ? leftLength : lastSpaceIndex+1 ;
+ leftLength = lastSpaceIndex === -1 ? leftLength : lastSpaceIndex + 1;
cutWords = curText.substr(leftLength, curText.length - 1);
validLeftLength = leftLength > 0 && cutWords !== " ";
}
if (validLeftLength) {
var leftRenderer = null;
- if( fontNameOrFontDef instanceof cc.FontDefinition)
- {
+ if (fontNameOrFontDef instanceof cc.FontDefinition) {
leftRenderer = new cc.LabelTTF(leftWords.substr(0, leftLength), fontNameOrFontDef);
leftRenderer.setOpacity(fontNameOrFontDef.fillStyle.a); //TODO: Verify that might not be needed...
- }else{
- leftRenderer = new cc.LabelTTF(leftWords.substr(0, leftLength), fontNameOrFontDef, fontSize);
+ } else {
+ leftRenderer = new cc.LabelTTF(leftWords.substr(0, leftLength), fontNameOrFontDef, fontSize);
leftRenderer.setColor(color);
leftRenderer.setOpacity(color.a);
}
@@ -373,9 +372,9 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{
this._addNewLine();
this._handleTextRenderer(cutWords, fontNameOrFontDef, fontSize, color);
} else {
- if( fontNameOrFontDef instanceof cc.FontDefinition) {
+ if (fontNameOrFontDef instanceof cc.FontDefinition) {
textRenderer.setOpacity(fontNameOrFontDef.fillStyle.a); //TODO: Verify that might not be needed...
- }else {
+ } else {
textRenderer.setColor(color);
textRenderer.setOpacity(color.a);
}
@@ -432,7 +431,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{
}
//Text flow horizontal alignment:
- if(this._textHorizontalAlignment !== cc.TEXT_ALIGNMENT_LEFT) {
+ if (this._textHorizontalAlignment !== cc.TEXT_ALIGNMENT_LEFT) {
offsetX = 0;
if (this._textHorizontalAlignment === cc.TEXT_ALIGNMENT_RIGHT)
offsetX = this._contentSize.width - nextPosX;
@@ -473,7 +472,7 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{
nextPosX += l.getContentSize().width;
}
//Text flow alignment(s)
- if( this._textHorizontalAlignment !== cc.TEXT_ALIGNMENT_LEFT || this._textVerticalAlignment !== cc.VERTICAL_TEXT_ALIGNMENT_TOP) {
+ if (this._textHorizontalAlignment !== cc.TEXT_ALIGNMENT_LEFT || this._textVerticalAlignment !== cc.VERTICAL_TEXT_ALIGNMENT_TOP) {
offsetX = 0;
if (this._textHorizontalAlignment === cc.TEXT_ALIGNMENT_RIGHT)
offsetX = this._contentSize.width - nextPosX;
@@ -498,12 +497,12 @@ ccui.RichText = ccui.Widget.extend(/** @lends ccui.RichText# */{
}
var length = locElementRenders.length;
- for (i = 0; i= ballRect.x &&
nsp.x <= (ballRect.x + ballRect.width) &&
nsp.y >= ballRect.y &&
@@ -507,7 +506,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{
* @returns {number}
*/
_getPercentWithBallPos: function (px) {
- return ((px/this._barLength)*100);
+ return ((px / this._barLength) * 100);
},
/**
@@ -525,13 +524,13 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{
* @param {Function} selector
* @param {Object} [target=]
*/
- addEventListener: function(selector, target){
+ addEventListener: function (selector, target) {
this._sliderEventSelector = selector; //when target is undefined, _sliderEventSelector = _eventCallback
this._sliderEventListener = target;
},
_percentChangedEvent: function () {
- if(this._sliderEventSelector){
+ if (this._sliderEventSelector) {
if (this._sliderEventListener)
this._sliderEventSelector.call(this._sliderEventListener, this, ccui.Slider.EVENT_PERCENT_CHANGED);
else
@@ -555,14 +554,12 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{
this._progressBarRendererDirty = true;
},
- _adaptRenderers: function(){
- if (this._barRendererAdaptDirty)
- {
+ _adaptRenderers: function () {
+ if (this._barRendererAdaptDirty) {
this._barRendererScaleChangedWithSize();
this._barRendererAdaptDirty = false;
}
- if (this._progressBarRendererDirty)
- {
+ if (this._progressBarRendererDirty) {
this._progressBarRendererScaleChangedWithSize();
this._progressBarRendererDirty = false;
}
@@ -572,7 +569,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{
* Returns the content size of bar renderer.
* @returns {cc.Size}
*/
- getVirtualRendererSize: function(){
+ getVirtualRendererSize: function () {
return this._barRenderer.getContentSize();
},
@@ -585,13 +582,13 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{
},
_barRendererScaleChangedWithSize: function () {
- if (this._unifySize){
+ if (this._unifySize) {
this._barLength = this._contentSize.width;
this._barRenderer.setPreferredSize(this._contentSize);
- }else if(this._ignoreSize) {
+ } else if (this._ignoreSize) {
this._barRenderer.setScale(1.0);
this._barLength = this._contentSize.width;
- }else {
+ } else {
this._barLength = this._contentSize.width;
if (this._scale9Enabled) {
this._barRenderer.setPreferredSize(this._contentSize);
@@ -600,7 +597,7 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{
var btextureSize = this._barTextureSize;
if (btextureSize.width <= 0.0 || btextureSize.height <= 0.0) {
this._barRenderer.setScale(1.0);
- }else{
+ } else {
var bscaleX = this._contentSize.width / btextureSize.width;
var bscaleY = this._contentSize.height / btextureSize.height;
this._barRenderer.setScaleX(bscaleX);
@@ -613,9 +610,9 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{
},
_progressBarRendererScaleChangedWithSize: function () {
- if(this._unifySize){
+ if (this._unifySize) {
this._progressBarRenderer.setPreferredSize(this._contentSize);
- }else if(this._ignoreSize) {
+ } else if (this._ignoreSize) {
if (!this._scale9Enabled) {
var ptextureSize = this._progressBarTextureSize;
var pscaleX = this._contentSize.width / ptextureSize.width;
@@ -651,48 +648,65 @@ ccui.Slider = ccui.Widget.extend(/** @lends ccui.Slider# */{
this._slidBallDisabledRenderer.setVisible(false);
this._slidBallNormalRenderer.setScale(this._sliderBallNormalTextureScaleX, this._sliderBallNormalTextureScaleY);
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
+ this._slidBallNormalRenderer._renderCmd._shaderProgram = this._getNormalGLProgram();
+ } else {
+ // TODO: add canvas support
+ }
},
_onPressStateChangedToPressed: function () {
- if (!this._slidBallPressedTextureFile){
+ if (!this._slidBallPressedTextureFile) {
this._slidBallNormalRenderer.setScale(this._sliderBallNormalTextureScaleX + this._zoomScale, this._sliderBallNormalTextureScaleY + this._zoomScale);
- }else{
+ } else {
this._slidBallNormalRenderer.setVisible(false);
this._slidBallPressedRenderer.setVisible(true);
this._slidBallDisabledRenderer.setVisible(false);
}
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
+ this._slidBallNormalRenderer._renderCmd._shaderProgram = this._getNormalGLProgram();
+ } else {
+ // TODO: add canvas support
+ }
},
_onPressStateChangedToDisabled: function () {
- if (this._slidBallDisabledTextureFile){
+ if (this._slidBallDisabledTextureFile) {
this._slidBallNormalRenderer.setVisible(false);
this._slidBallDisabledRenderer.setVisible(true);
+ } else {
+ this._slidBallNormalRenderer.setVisible(true);
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
+ this._slidBallNormalRenderer._renderCmd._shaderProgram = this._getGrayGLProgram();
+ } else {
+ // TODO: add canvas support
+ }
}
this._slidBallNormalRenderer.setScale(this._sliderBallNormalTextureScaleX, this._sliderBallNormalTextureScaleY);
this._slidBallPressedRenderer.setVisible(false);
},
- setZoomScale: function(scale){
+ setZoomScale: function (scale) {
this._zoomScale = scale;
},
- getZoomScale: function(){
+ getZoomScale: function () {
return this._zoomScale;
},
- getSlidBallNormalRenderer : function () {
+ getSlidBallNormalRenderer: function () {
return this._slidBallNormalRenderer;
},
- getSlidBallPressedRenderer : function () {
+ getSlidBallPressedRenderer: function () {
return this._slidBallPressedRenderer;
},
- getSlidBallDisabledRenderer : function () {
+ getSlidBallDisabledRenderer: function () {
return this._slidBallDisabledRenderer;
},
- getSlidBallRenderer : function () {
+ getSlidBallRenderer: function () {
return this._slidBallRenderer;
},
@@ -770,4 +784,4 @@ ccui.Slider.PROGRESSBAR_RENDERER_ZORDER = -2;
* @constant
* @type {number}
*/
-ccui.Slider.BALL_RENDERER_ZORDER = -1;
\ No newline at end of file
+ccui.Slider.BALL_RENDERER_ZORDER = -1;
diff --git a/extensions/ccui/uiwidgets/UIText.js b/extensions/ccui/uiwidgets/UIText.js
index bfa1198a77..5d72e061c4 100644
--- a/extensions/ccui/uiwidgets/UIText.js
+++ b/extensions/ccui/uiwidgets/UIText.js
@@ -45,7 +45,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
_normalScaleValueY: 1,
_fontName: "Arial",
_fontSize: 16,
- _onSelectedScaleOffset:0.5,
+ _onSelectedScaleOffset: 0.5,
_labelRenderer: null,
_textAreaSize: null,
_textVerticalAlignment: 0,
@@ -98,10 +98,14 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
* @param {String} text
*/
setString: function (text) {
- if(text === this._labelRenderer.getString())
- return;
- this._labelRenderer.setString(text);
+ if(text === this._labelRenderer.getString()) return;
+ this._setString(text);
+
this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize());
+ },
+
+ _setString: function (text) {
+ this._labelRenderer.setString(text);
this._labelRendererAdaptDirty = true;
},
@@ -136,9 +140,13 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
* @param {Number} size
*/
setFontSize: function (size) {
+ this._setFontSize(size);
+ this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize());
+ },
+
+ _setFontSize: function (size) {
this._labelRenderer.setFontSize(size);
this._fontSize = size;
- this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize());
this._labelRendererAdaptDirty = true;
},
@@ -155,12 +163,20 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
* @return {String} name
*/
setFontName: function (name) {
+ this._setFontName(name);
+ this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize());
+ },
+
+ _setFontName: function (name) {
this._fontName = name;
this._labelRenderer.setFontName(name);
- this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize());
this._labelRendererAdaptDirty = true;
},
+ _updateUITextContentSize: function () {
+ this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize());
+ },
+
/**
* Returns font name of ccui.Text.
* @returns {string}
@@ -186,8 +202,8 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
* Returns the type of ccui.Text.
* @returns {null}
*/
- getType: function(){
- return this._type;
+ getType: function () {
+ return this._type;
},
/**
@@ -195,11 +211,15 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
* @param {cc.Size} size
*/
setTextAreaSize: function (size) {
+ this._setTextAreaSize(size);
+ this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize());
+ },
+
+ _setTextAreaSize: function (size) {
this._labelRenderer.setDimensions(size);
if (!this._ignoreSize){
this._customSize = size;
}
- this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize());
this._labelRendererAdaptDirty = true;
},
@@ -207,7 +227,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
* Returns renderer's dimension.
* @returns {cc.Size}
*/
- getTextAreaSize: function(){
+ getTextAreaSize: function () {
return this._labelRenderer.getDimensions();
},
@@ -216,8 +236,13 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
* @param {cc.TEXT_ALIGNMENT_LEFT|cc.TEXT_ALIGNMENT_CENTER|cc.TEXT_ALIGNMENT_RIGHT} alignment Horizontal Alignment
*/
setTextHorizontalAlignment: function (alignment) {
- this._labelRenderer.setHorizontalAlignment(alignment);
+ this._setTextHorizontalAlignment(alignment);
this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize());
+ },
+
+
+ _setTextHorizontalAlignment: function (alignment) {
+ this._labelRenderer.setHorizontalAlignment(alignment);
this._labelRendererAdaptDirty = true;
},
@@ -234,11 +259,14 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
* @param {cc.VERTICAL_TEXT_ALIGNMENT_TOP|cc.VERTICAL_TEXT_ALIGNMENT_CENTER|cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM} alignment
*/
setTextVerticalAlignment: function (alignment) {
- this._labelRenderer.setVerticalAlignment(alignment);
+ this._setTextVerticalAlignment(alignment);
this._updateContentSizeWithTextureSize(this._labelRenderer.getContentSize());
- this._labelRendererAdaptDirty = true;
},
+ _setTextVerticalAlignment: function (alignment) {
+ this._labelRenderer.setVerticalAlignment(alignment);
+ this._labelRendererAdaptDirty = true;
+ },
/**
* Gets text vertical alignment.
* @returns {VERTICAL_TEXT_ALIGNMENT_TOP|VERTICAL_TEXT_ALIGNMENT_CENTER|VERTICAL_TEXT_ALIGNMENT_BOTTOM}
@@ -285,7 +313,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
this._labelRendererAdaptDirty = true;
},
- _adaptRenderers: function(){
+ _adaptRenderers: function () {
if (this._labelRendererAdaptDirty) {
this._labelScaleChangedWithSize();
this._labelRendererAdaptDirty = false;
@@ -297,7 +325,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
* @override
* @returns {cc.Size}
*/
- getVirtualRendererSize: function(){
+ getVirtualRendererSize: function () {
return this._labelRenderer.getContentSize();
},
@@ -310,7 +338,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
},
//@since v3.3
- getAutoRenderSize: function(){
+ getAutoRenderSize: function () {
var virtualSize = this._labelRenderer.getContentSize();
if (!this._ignoreSize) {
this._labelRenderer.setDimensions(0, 0);
@@ -323,7 +351,6 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
_labelScaleChangedWithSize: function () {
var locContentSize = this._contentSize;
if (this._ignoreSize) {
- this._labelRenderer.setDimensions(0,0);
this._labelRenderer.setScale(1.0);
this._normalScaleValueX = this._normalScaleValueY = 1;
} else {
@@ -357,7 +384,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
* @param {cc.Size} offset
* @param {Number} blurRadius
*/
- enableShadow: function(shadowColor, offset, blurRadius){
+ enableShadow: function (shadowColor, offset, blurRadius) {
this._labelRenderer.enableShadow(shadowColor, offset, blurRadius);
},
@@ -366,7 +393,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
* @param {cc.Color} outlineColor
* @param {cc.Size} outlineSize
*/
- enableOutline: function(outlineColor, outlineSize){
+ enableOutline: function (outlineColor, outlineSize) {
this._labelRenderer.enableStroke(outlineColor, outlineSize);
},
@@ -374,7 +401,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
* Enables glow color
* @param glowColor
*/
- enableGlow: function(glowColor){
+ enableGlow: function (glowColor) {
if (this._type === ccui.Text.Type.TTF)
this._labelRenderer.enableGlow(glowColor);
},
@@ -382,8 +409,8 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
/**
* Disables renderer's effect.
*/
- disableEffect: function(){
- if(this._labelRenderer.disableEffect)
+ disableEffect: function () {
+ if (this._labelRenderer.disableEffect)
this._labelRenderer.disableEffect();
},
@@ -392,7 +419,7 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
},
_copySpecialProperties: function (uiLabel) {
- if(uiLabel instanceof ccui.Text){
+ if (uiLabel instanceof ccui.Text) {
this.setFontName(uiLabel._fontName);
this.setFontSize(uiLabel.getFontSize());
this.setString(uiLabel.getString());
@@ -422,20 +449,20 @@ ccui.Text = ccui.Widget.extend(/** @lends ccui.Text# */{
return this._textAreaSize.height;
},
- _changePosition: function(){
+ _changePosition: function () {
this._adaptRenderers();
},
- setColor: function(color){
+ setColor: function (color) {
cc.ProtectedNode.prototype.setColor.call(this, color);
this._labelRenderer.setColor(color);
},
- setTextColor: function(color){
+ setTextColor: function (color) {
this._labelRenderer.setFontFillColor(color);
},
- getTextColor: function(){
+ getTextColor: function () {
return this._labelRenderer._getFillStyle();
}
});
@@ -495,4 +522,4 @@ ccui.Text.RENDERER_ZORDER = -1;
ccui.Text.Type = {
SYSTEM: 0,
TTF: 1
-};
\ No newline at end of file
+};
diff --git a/extensions/ccui/uiwidgets/UITextAtlas.js b/extensions/ccui/uiwidgets/UITextAtlas.js
index b13b34d67e..98c4b89e63 100644
--- a/extensions/ccui/uiwidgets/UITextAtlas.js
+++ b/extensions/ccui/uiwidgets/UITextAtlas.js
@@ -63,6 +63,11 @@ ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{
this._labelAtlasRenderer = new cc.LabelAtlas();
this._labelAtlasRenderer.setAnchorPoint(cc.p(0.5, 0.5));
this.addProtectedChild(this._labelAtlasRenderer, ccui.TextAtlas.RENDERER_ZORDER, -1);
+
+ this._labelAtlasRenderer.addEventListener('load', function () {
+ this._updateContentSizeWithTextureSize(this._labelAtlasRenderer.getContentSize());
+ this._findLayout();
+ }, this);
},
/**
@@ -97,7 +102,7 @@ ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{
* @param {String} value
*/
setString: function (value) {
- if(value === this._labelAtlasRenderer.getString())
+ if (value === this._labelAtlasRenderer.getString())
return;
this._stringValue = value;
this._labelAtlasRenderer.setString(value);
@@ -137,7 +142,7 @@ ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{
* Returns the length of string.
* @returns {*|Number|long|int}
*/
- getStringLength: function(){
+ getStringLength: function () {
return this._labelAtlasRenderer.getStringLength();
},
@@ -146,8 +151,8 @@ ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{
this._labelAtlasRendererAdaptDirty = true;
},
- _adaptRenderers: function(){
- if (this._labelAtlasRendererAdaptDirty){
+ _adaptRenderers: function () {
+ if (this._labelAtlasRendererAdaptDirty) {
this._labelAtlasScaleChangedWithSize();
this._labelAtlasRendererAdaptDirty = false;
}
@@ -158,7 +163,7 @@ ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{
* @overrider
* @returns {cc.Size}
*/
- getVirtualRendererSize: function(){
+ getVirtualRendererSize: function () {
return this._labelAtlasRenderer.getContentSize();
},
@@ -195,7 +200,7 @@ ccui.TextAtlas = ccui.Widget.extend(/** @lends ccui.TextAtlas# */{
},
_copySpecialProperties: function (labelAtlas) {
- if (labelAtlas){
+ if (labelAtlas) {
this.setProperty(labelAtlas._stringValue, labelAtlas._charMapFileName, labelAtlas._itemWidth, labelAtlas._itemHeight, labelAtlas._startCharMap);
}
},
@@ -228,4 +233,4 @@ ccui.TextAtlas.create = function (stringValue, charMapFile, itemWidth, itemHeigh
* The zOrder value of ccui.TextAtlas's renderer.
* @type {number}
*/
-ccui.TextAtlas.RENDERER_ZORDER = -1;
\ No newline at end of file
+ccui.TextAtlas.RENDERER_ZORDER = -1;
diff --git a/extensions/ccui/uiwidgets/UITextBMFont.js b/extensions/ccui/uiwidgets/UITextBMFont.js
index 1430d4aafd..25c92315cb 100644
--- a/extensions/ccui/uiwidgets/UITextBMFont.js
+++ b/extensions/ccui/uiwidgets/UITextBMFont.js
@@ -49,6 +49,7 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo
*/
ctor: function (text, filename) {
ccui.Widget.prototype.ctor.call(this);
+ this._loader = new cc.Sprite.LoadManager();
if (filename !== undefined) {
this.setFntFile(filename);
@@ -77,18 +78,10 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo
var _self = this;
var locRenderer = _self._labelBMFontRenderer;
- if(!locRenderer._textureLoaded){
- locRenderer.addEventListener("load", function(){
- _self.setFntFile(_self._fntFileName);
- var parent = _self.parent;
- while (parent) {
- if (parent.requestDoLayout) {
- parent.requestDoLayout();
- break;
- }
- parent = parent.parent;
- }
- });
+ if (!locRenderer._textureLoaded) {
+ locRenderer.addEventListener("load", function () {
+ _self.setFntFile(_self._fntFileName);
+ });
}
},
@@ -107,7 +100,14 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo
* @param {String} value
*/
setString: function (value) {
- if(value === this._labelBMFontRenderer.getString())
+ this._loader.clear();
+ if (!this._labelBMFontRenderer._textureLoaded) {
+ this._loader.add(this._labelBMFontRenderer, function () {
+ this.setString(value);
+ }, this);
+ return;
+ }
+ if (value === this._labelBMFontRenderer.getString())
return;
this._stringValue = value;
this._labelBMFontRenderer.setString(value);
@@ -129,7 +129,7 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo
* Returns the length of TextBMFont's string.
* @returns {Number}
*/
- getStringLength: function(){
+ getStringLength: function () {
return this._labelBMFontRenderer.getStringLength();
},
@@ -138,8 +138,8 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo
this._labelBMFontRendererAdaptDirty = true;
},
- _adaptRenderers: function(){
- if (this._labelBMFontRendererAdaptDirty){
+ _adaptRenderers: function () {
+ if (this._labelBMFontRendererAdaptDirty) {
this._labelBMFontScaleChangedWithSize();
this._labelBMFontRendererAdaptDirty = false;
}
@@ -150,7 +150,7 @@ ccui.LabelBMFont = ccui.TextBMFont = ccui.Widget.extend(/** @lends ccui.TextBMFo
* @override
* @returns {cc.Size}
*/
- getVirtualRendererSize: function(){
+ getVirtualRendererSize: function () {
return this._labelBMFontRenderer.getContentSize();
},
diff --git a/extensions/ccui/uiwidgets/UIVideoPlayer.js b/extensions/ccui/uiwidgets/UIVideoPlayer.js
index afff6fd2a7..e4e3351040 100644
--- a/extensions/ccui/uiwidgets/UIVideoPlayer.js
+++ b/extensions/ccui/uiwidgets/UIVideoPlayer.js
@@ -38,24 +38,51 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
_playing: false,
_stopped: true,
- ctor: function(path){
+ ctor: function (path) {
ccui.Widget.prototype.ctor.call(this);
this._EventList = {};
- if(path)
+ if (path)
this.setURL(path);
},
- _createRenderCmd: function(){
+ _createRenderCmd: function () {
return new ccui.VideoPlayer.RenderCmd(this);
},
+ visit: function () {
+ var cmd = this._renderCmd,
+ div = cmd._div,
+ container = cc.container,
+ eventManager = cc.eventManager;
+ if (this._visible) {
+ container.appendChild(cmd._video);
+ if (this._listener === null)
+ this._listener = cc.eventManager.addCustomListener(cc.game.EVENT_RESIZE, function () {
+ cmd.resize();
+ });
+ } else {
+ var hasChild = false;
+ if ('contains' in container) {
+ hasChild = container.contains(cmd._video);
+ } else {
+ hasChild = container.compareDocumentPosition(cmd._video) % 16;
+ }
+ if (hasChild)
+ container.removeChild(cmd._video);
+ eventManager.removeListener(cmd._listener);
+ cmd._listener = null;
+ }
+ cmd.updateStatus();
+ cmd.resize();
+ },
+
/**
* Set the video address
* Automatically replace extname
* All supported video formats will be added to the video
* @param {String} address
*/
- setURL: function(address){
+ setURL: function (address) {
this._renderCmd.updateURL(address);
},
@@ -63,28 +90,28 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
* Get the video path
* @returns {String}
*/
- getURL: function() {
+ getURL: function () {
return this._renderCmd._url;
},
/**
* Play the video
*/
- play: function(){
+ play: function () {
var self = this,
video = this._renderCmd._video;
- if(video){
+ if (video) {
this._played = true;
video.pause();
- if(this._stopped !== false || this._playing !== false || this._played !== true)
+ if (this._stopped !== false || this._playing !== false || this._played !== true)
video.currentTime = 0;
- if(ccui.VideoPlayer._polyfill.autoplayAfterOperation){
- setTimeout(function(){
+ if (ccui.VideoPlayer._polyfill.autoplayAfterOperation) {
+ setTimeout(function () {
video.play();
self._playing = true;
self._stopped = false;
}, 20);
- }else{
+ } else {
video.play();
this._playing = true;
this._stopped = false;
@@ -95,9 +122,9 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
/**
* Pause the video
*/
- pause: function(){
+ pause: function () {
var video = this._renderCmd._video;
- if(video && this._playing === true && this._stopped === false){
+ if (video && this._playing === true && this._stopped === false) {
video.pause();
this._playing = false;
}
@@ -106,8 +133,8 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
/**
* Resume the video
*/
- resume: function(){
- if(this._stopped === false && this._playing === false && this._played === true){
+ resume: function () {
+ if (this._stopped === false && this._playing === false && this._played === true) {
this.play();
}
},
@@ -115,17 +142,17 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
/**
* Stop the video
*/
- stop: function(){
+ stop: function () {
var self = this,
video = this._renderCmd._video;
- if(video){
+ if (video) {
video.pause();
video.currentTime = 0;
this._playing = false;
this._stopped = true;
}
- setTimeout(function(){
+ setTimeout(function () {
self._dispatchEvent(ccui.VideoPlayer.EventType.STOPPED);
}, 0);
},
@@ -133,12 +160,12 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
* Jump to the specified point in time
* @param {Number} sec
*/
- seekTo: function(sec){
+ seekTo: function (sec) {
var video = this._renderCmd._video;
- if(video){
+ if (video) {
video.currentTime = sec;
- if(ccui.VideoPlayer._polyfill.autoplayAfterOperation && this.isPlaying()){
- setTimeout(function(){
+ if (ccui.VideoPlayer._polyfill.autoplayAfterOperation && this.isPlaying()) {
+ setTimeout(function () {
video.play();
}, 20);
}
@@ -149,9 +176,9 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
* Whether the video is playing
* @returns {boolean}
*/
- isPlaying: function(){
- if(ccui.VideoPlayer._polyfill.autoplayAfterOperation && this._playing){
- setTimeout(function(){
+ isPlaying: function () {
+ if (ccui.VideoPlayer._polyfill.autoplayAfterOperation && this._playing) {
+ setTimeout(function () {
video.play();
}, 20);
}
@@ -161,10 +188,10 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
/**
* Whether to keep the aspect ratio
*/
- setKeepAspectRatioEnabled: function(enable){
+ setKeepAspectRatioEnabled: function (enable) {
cc.log("On the web is always keep the aspect ratio");
},
- isKeepAspectRatioEnabled: function(){
+ isKeepAspectRatioEnabled: function () {
return false;
},
@@ -173,10 +200,10 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
* May appear inconsistent in different browsers
* @param {boolean} enable
*/
- setFullScreenEnabled: function(enable){
+ setFullScreenEnabled: function (enable) {
var video = this._renderCmd._video;
- if(video){
- if(enable)
+ if (video) {
+ if (enable)
cc.screen.requestFullScreen(video);
else
cc.screen.exitFullScreen(video);
@@ -186,7 +213,7 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
/**
* Determine whether already full screen
*/
- isFullScreenEnabled: function(){
+ isFullScreenEnabled: function () {
cc.log("Can't know status");
},
@@ -195,7 +222,7 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
* @param {ccui.VideoPlayer.EventType} event
* @param {Function} callback
*/
- setEventListener: function(event, callback){
+ setEventListener: function (event, callback) {
this._EventList[event] = callback;
},
@@ -203,11 +230,11 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
* Delete events
* @param {ccui.VideoPlayer.EventType} event
*/
- removeEventListener: function(event){
+ removeEventListener: function (event) {
this._EventList[event] = null;
},
- _dispatchEvent: function(event) {
+ _dispatchEvent: function (event) {
var callback = this._EventList[event];
if (callback)
callback.call(this, this, this._renderCmd._video.src);
@@ -216,43 +243,40 @@ ccui.VideoPlayer = ccui.Widget.extend(/** @lends ccui.VideoPlayer# */{
/**
* Trigger playing events
*/
- onPlayEvent: function(){
+ onPlayEvent: function () {
var list = this._EventList[ccui.VideoPlayer.EventType.PLAYING];
- if(list)
- for(var i=0; i -1)
+ if (index > -1)
this._items.splice(index, 1);
this._onItemListChanged();
@@ -269,7 +265,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
/**
* Removes all children from ccui.ListView.
*/
- removeAllChildren: function(){
+ removeAllChildren: function () {
this.removeAllChildrenWithCleanup(true);
},
@@ -277,7 +273,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Removes all children from ccui.ListView and do a cleanup all running actions depending on the cleanup parameter.
* @param {Boolean} cleanup
*/
- removeAllChildrenWithCleanup: function(cleanup){
+ removeAllChildrenWithCleanup: function (cleanup) {
ccui.ScrollView.prototype.removeAllChildrenWithCleanup.call(this, cleanup);
this._items = [];
@@ -320,7 +316,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
/**
* Removes all items from ccui.ListView.
*/
- removeAllItems: function(){
+ removeAllItems: function () {
this.removeAllChildren();
},
@@ -349,7 +345,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* @returns {Number} the index of item.
*/
getIndex: function (item) {
- if(item == null)
+ if (item == null)
return -1;
return this._items.indexOf(item);
},
@@ -369,8 +365,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Set magnetic type of ListView.
* @param {ccui.ListView.MAGNETIC_NONE|ccui.ListView.MAGNETIC_CENTER,ccui.ListView.MAGNETIC_BOTH_END|ccui.ListView.MAGNETIC_LEFT|ccui.ListView.MAGNETIC_RIGHT|ccui.ListView.MAGNETIC_TOP|ccui.ListView.MAGNETIC_BOTTOM} magneticType
*/
- setMagneticType: function(magneticType)
- {
+ setMagneticType: function (magneticType) {
this._magneticType = magneticType;
this._onItemListChanged();
this._startMagneticScroll();
@@ -380,8 +375,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Get magnetic type of ListView.
* @returns {number}
*/
- getMagneticType: function()
- {
+ getMagneticType: function () {
return this._magneticType;
},
@@ -389,8 +383,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Set magnetic allowed out of boundary.
* @param {boolean} magneticAllowedOutOfBoundary
*/
- setMagneticAllowedOutOfBoundary: function(magneticAllowedOutOfBoundary)
- {
+ setMagneticAllowedOutOfBoundary: function (magneticAllowedOutOfBoundary) {
this._magneticAllowedOutOfBoundary = magneticAllowedOutOfBoundary;
},
@@ -398,8 +391,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Query whether the magnetic out of boundary is allowed.
* @returns {boolean}
*/
- getMagneticAllowedOutOfBoundary: function()
- {
+ getMagneticAllowedOutOfBoundary: function () {
return this._magneticAllowedOutOfBoundary;
},
@@ -418,7 +410,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Returns the margin between each item.
* @returns {Number}
*/
- getItemsMargin:function(){
+ getItemsMargin: function () {
return this._itemsMargin;
},
@@ -443,21 +435,17 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
ccui.ScrollView.prototype.setDirection.call(this, dir);
},
- _getHowMuchOutOfBoundary: function(addition)
- {
- if(addition === undefined)
+ _getHowMuchOutOfBoundary: function (addition) {
+ if (addition === undefined)
addition = cc.p(0, 0);
- if(!this._magneticAllowedOutOfBoundary || this._items.length === 0)
- {
+ if (!this._magneticAllowedOutOfBoundary || this._items.length === 0) {
return ccui.ScrollView.prototype._getHowMuchOutOfBoundary.call(this, addition);
}
- else if(this._magneticType === ccui.ListView.MAGNETIC_NONE || this._magneticType === ccui.ListView.MAGNETIC_BOTH_END)
- {
+ else if (this._magneticType === ccui.ListView.MAGNETIC_NONE || this._magneticType === ccui.ListView.MAGNETIC_BOTH_END) {
return ccui.ScrollView.prototype._getHowMuchOutOfBoundary.call(this, addition);
}
- else if(addition.x === 0 && addition.y === 0 && !this._outOfBoundaryAmountDirty)
- {
+ else if (addition.x === 0 && addition.y === 0 && !this._outOfBoundaryAmountDirty) {
return this._outOfBoundaryAmount;
}
@@ -472,8 +460,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
var firstItemAdjustment = cc.p(0, 0);
var lastItemAdjustment = cc.p(0, 0);
- switch (this._magneticType)
- {
+ switch (this._magneticType) {
case ccui.ListView.MAGNETIC_CENTER:
firstItemAdjustment.x = (contentSize.width - this._items[0].width) / 2;
firstItemAdjustment.y = (contentSize.height - this._items[0].height) / 2;
@@ -503,55 +490,44 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
// Calculate the actual amount
var outOfBoundaryAmount = cc.p(0, 0);
- if(this._innerContainer.getLeftBoundary() + addition.x > leftBoundary)
- {
+ if (this._innerContainer.getLeftBoundary() + addition.x > leftBoundary) {
outOfBoundaryAmount.x = leftBoundary - (this._innerContainer.getLeftBoundary() + addition.x);
}
- else if(this._innerContainer.getRightBoundary() + addition.x < rightBoundary)
- {
+ else if (this._innerContainer.getRightBoundary() + addition.x < rightBoundary) {
outOfBoundaryAmount.x = rightBoundary - (this._innerContainer.getRightBoundary() + addition.x);
}
- if(this._innerContainer.getTopBoundary() + addition.y < topBoundary)
- {
+ if (this._innerContainer.getTopBoundary() + addition.y < topBoundary) {
outOfBoundaryAmount.y = topBoundary - (this._innerContainer.getTopBoundary() + addition.y);
}
- else if(this._innerContainer.getBottomBoundary() + addition.y > bottomBoundary)
- {
+ else if (this._innerContainer.getBottomBoundary() + addition.y > bottomBoundary) {
outOfBoundaryAmount.y = bottomBoundary - (this._innerContainer.getBottomBoundary() + addition.y);
}
- if(addition.x === 0 && addition.y === 0)
- {
+ if (addition.x === 0 && addition.y === 0) {
this._outOfBoundaryAmount = outOfBoundaryAmount;
this._outOfBoundaryAmountDirty = false;
}
return outOfBoundaryAmount;
},
- _calculateItemPositionWithAnchor: function(item, itemAnchorPoint)
- {
+ _calculateItemPositionWithAnchor: function (item, itemAnchorPoint) {
var origin = cc.p(item.getLeftBoundary(), item.getBottomBoundary());
var size = item.getContentSize();
- return cc.p(origin. x + size.width * itemAnchorPoint.x, origin.y + size.height * itemAnchorPoint.y);
+ return cc.p(origin.x + size.width * itemAnchorPoint.x, origin.y + size.height * itemAnchorPoint.y);
},
- _findClosestItem: function(targetPosition, items, itemAnchorPoint, firstIndex, distanceFromFirst, lastIndex, distanceFromLast)
- {
+ _findClosestItem: function (targetPosition, items, itemAnchorPoint, firstIndex, distanceFromFirst, lastIndex, distanceFromLast) {
cc.assert(firstIndex >= 0 && lastIndex < items.length && firstIndex <= lastIndex, "");
- if (firstIndex === lastIndex)
- {
+ if (firstIndex === lastIndex) {
return items[firstIndex];
}
- if (lastIndex - firstIndex === 1)
- {
- if (distanceFromFirst <= distanceFromLast)
- {
+ if (lastIndex - firstIndex === 1) {
+ if (distanceFromFirst <= distanceFromLast) {
return items[firstIndex];
}
- else
- {
+ else {
return items[lastIndex];
}
}
@@ -561,13 +537,11 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
var itemPosition = this._calculateItemPositionWithAnchor(items[midIndex], itemAnchorPoint);
var distanceFromMid = cc.pLength(cc.pSub(targetPosition, itemPosition));
- if (distanceFromFirst <= distanceFromLast)
- {
+ if (distanceFromFirst <= distanceFromLast) {
// Left half
return this._findClosestItem(targetPosition, items, itemAnchorPoint, firstIndex, distanceFromFirst, midIndex, distanceFromMid);
}
- else
- {
+ else {
// Right half
return this._findClosestItem(targetPosition, items, itemAnchorPoint, midIndex, distanceFromMid, lastIndex, distanceFromLast);
}
@@ -580,10 +554,8 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* @param {cc.Point} itemAnchorPoint Specifies an anchor point of each item for position to calculate distance.
* @returns {?ccui.Widget} A item instance if list view is not empty. Otherwise, returns null.
*/
- getClosestItemToPosition: function(targetPosition, itemAnchorPoint)
- {
- if (this._items.length === 0)
- {
+ getClosestItemToPosition: function (targetPosition, itemAnchorPoint) {
+ if (this._items.length === 0) {
return null;
}
@@ -608,8 +580,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* @returns {?ccui.Widget} A item instance if list view is not empty. Otherwise, returns null.
*/
- getClosestItemToPositionInCurrentView: function(positionRatioInView, itemAnchorPoint)
- {
+ getClosestItemToPositionInCurrentView: function (positionRatioInView, itemAnchorPoint) {
// Calculate the target position
var contentSize = this.getContentSize();
var targetPosition = cc.pMult(this._innerContainer.getPosition(), -1);
@@ -623,8 +594,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Query the center item
* @returns {?ccui.Widget} A item instance.
*/
- getCenterItemInCurrentView: function()
- {
+ getCenterItemInCurrentView: function () {
return this.getClosestItemToPositionInCurrentView(cc.p(0.5, 0.5), cc.p(0.5, 0.5));
},
@@ -632,10 +602,8 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Query the leftmost item in horizontal list
* @returns {?ccui.Widget} A item instance.
*/
- getLeftmostItemInCurrentView: function()
- {
- if(this._direction === ccui.ScrollView.DIR_HORIZONTAL)
- {
+ getLeftmostItemInCurrentView: function () {
+ if (this._direction === ccui.ScrollView.DIR_HORIZONTAL) {
return this.getClosestItemToPositionInCurrentView(cc.p(0, 0.5), cc.p(0.5, 0.5));
}
@@ -646,10 +614,8 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Query the rightmost item in horizontal list
* @returns {?ccui.Widget} A item instance.
*/
- getRightmostItemInCurrentView: function()
- {
- if(this._direction === ccui.ScrollView.DIR_HORIZONTAL)
- {
+ getRightmostItemInCurrentView: function () {
+ if (this._direction === ccui.ScrollView.DIR_HORIZONTAL) {
return this.getClosestItemToPositionInCurrentView(cc.p(1, 0.5), cc.p(0.5, 0.5));
}
@@ -660,10 +626,8 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Query the topmost item in horizontal list
* @returns {?ccui.Widget} A item instance.
*/
- getTopmostItemInCurrentView: function()
- {
- if(this._direction === ccui.ScrollView.DIR_VERTICAL)
- {
+ getTopmostItemInCurrentView: function () {
+ if (this._direction === ccui.ScrollView.DIR_VERTICAL) {
return this.getClosestItemToPositionInCurrentView(cc.p(0.5, 1), cc.p(0.5, 0.5));
}
@@ -674,18 +638,15 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Query the topmost item in horizontal list
* @returns {?ccui.Widget} A item instance.
*/
- getBottommostItemInCurrentView: function()
- {
- if(this._direction === ccui.ScrollView.DIR_VERTICAL)
- {
+ getBottommostItemInCurrentView: function () {
+ if (this._direction === ccui.ScrollView.DIR_VERTICAL) {
return this.getClosestItemToPositionInCurrentView(cc.p(0.5, 0), cc.p(0.5, 0.5));
}
return null;
},
- _calculateItemDestination: function(positionRatioInView, item, itemAnchorPoint)
- {
+ _calculateItemDestination: function (positionRatioInView, item, itemAnchorPoint) {
var contentSize = this.getContentSize();
var positionInView = cc.p(0, 0);
positionInView.x += contentSize.width * positionRatioInView.x;
@@ -695,68 +656,57 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
return cc.pMult(cc.pSub(itemPosition, positionInView), -1);
},
- jumpToBottom: function()
- {
+ jumpToBottom: function () {
this.doLayout();
ccui.ScrollView.prototype.jumpToBottom.call(this);
},
- jumpToTop: function()
- {
+ jumpToTop: function () {
this.doLayout();
ccui.ScrollView.prototype.jumpToTop.call(this);
},
- jumpToLeft: function()
- {
+ jumpToLeft: function () {
this.doLayout();
ccui.ScrollView.prototype.jumpToLeft.call(this);
},
- jumpToRight: function()
- {
+ jumpToRight: function () {
this.doLayout();
ccui.ScrollView.prototype.jumpToRight.call(this);
},
- jumpToTopLeft: function()
- {
+ jumpToTopLeft: function () {
this.doLayout();
ccui.ScrollView.prototype.jumpToTopLeft.call(this);
},
- jumpToTopRight: function()
- {
+ jumpToTopRight: function () {
this.doLayout();
ccui.ScrollView.prototype.jumpToTopRight.call(this);
},
- jumpToBottomLeft: function()
- {
+ jumpToBottomLeft: function () {
this.doLayout();
ccui.ScrollView.prototype.jumpToBottomLeft.call(this);
},
- jumpToBottomRight: function()
- {
+ jumpToBottomRight: function () {
this.doLayout();
ccui.ScrollView.prototype.jumpToBottomRight.call(this);
},
- jumpToPercentVertical: function(percent)
- {
+ jumpToPercentVertical: function (percent) {
this.doLayout();
ccui.ScrollView.prototype.jumpToPercentVertical.call(this, percent);
},
- jumpToPercentHorizontal: function(percent)
- {
+ jumpToPercentHorizontal: function (percent) {
this.doLayout();
ccui.ScrollView.prototype.jumpToPercentHorizontal.call(this, percent);
},
- jumpToPercentBothDirection: function(percent)
- {
+ jumpToPercentBothDirection: function (percent) {
this.doLayout();
ccui.ScrollView.prototype.jumpToPercentBothDirection.call(this, percent);
},
@@ -767,19 +717,17 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* @param {cc.Point} positionRatioInView Specifies the position with ratio in list view's content size.
* @param {cc.Point} itemAnchorPoint Specifies an anchor point of each item for position to calculate distance.
*/
- jumpToItem: function(itemIndex, positionRatioInView, itemAnchorPoint)
- {
+ jumpToItem: function (itemIndex, positionRatioInView, itemAnchorPoint) {
var item = this.getItem(itemIndex);
- if(!item)
+ if (!item)
return;
this.doLayout();
var destination = this._calculateItemDestination(positionRatioInView, item, itemAnchorPoint);
- if(!this.bounceEnabled)
- {
+ if (!this.bounceEnabled) {
var delta = cc.pSub(destination, this._innerContainer.getPosition());
var outOfBoundary = this._getHowMuchOutOfBoundary(delta);
destination.x += outOfBoundary.x;
@@ -796,14 +744,13 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* @param {cc.Point} itemAnchorPoint Specifies an anchor point of each item for position to calculate distance.
* @param {number} [timeInSec = 1.0] Scroll time
*/
- scrollToItem: function(itemIndex, positionRatioInView, itemAnchorPoint, timeInSec)
- {
- if(timeInSec === undefined)
+ scrollToItem: function (itemIndex, positionRatioInView, itemAnchorPoint, timeInSec) {
+ if (timeInSec === undefined)
timeInSec = 1;
var item = this.getItem(itemIndex);
- if(!item)
+ if (!item)
return;
var destination = this._calculateItemDestination(positionRatioInView, item, itemAnchorPoint);
@@ -829,16 +776,15 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
/**
* provides a public _doLayout function for Editor. it calls _doLayout.
*/
- doLayout: function(){
+ doLayout: function () {
this._doLayout();
},
- requestDoLayout: function()
- {
+ requestDoLayout: function () {
this._refreshViewDirty = true;
},
- _doLayout: function(){
+ _doLayout: function () {
//ccui.Layout.prototype._doLayout.call(this);
if (this._refreshViewDirty) {
var locItems = this._items;
@@ -868,19 +814,19 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
* Adds callback function called ListView event triggered
* @param {Function} selector
*/
- addEventListener: function(selector){
+ addEventListener: function (selector) {
this._ccListViewEventCallback = selector;
},
_selectedItemEvent: function (event) {
var eventEnum = (event === ccui.Widget.TOUCH_BEGAN) ? ccui.ListView.ON_SELECTED_ITEM_START : ccui.ListView.ON_SELECTED_ITEM_END;
- if(this._listViewEventSelector){
+ if (this._listViewEventSelector) {
if (this._listViewEventListener)
this._listViewEventSelector.call(this._listViewEventListener, this, eventEnum);
else
this._listViewEventSelector(this, eventEnum);
}
- if(this._ccListViewEventCallback)
+ if (this._ccListViewEventCallback)
this._ccListViewEventCallback(this, eventEnum);
},
@@ -943,7 +889,7 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
},
_copySpecialProperties: function (listView) {
- if(listView instanceof ccui.ListView){
+ if (listView instanceof ccui.ListView) {
ccui.ScrollView.prototype._copySpecialProperties.call(this, listView);
this.setItemModel(listView._model);
this.setItemsMargin(listView._itemsMargin);
@@ -954,27 +900,21 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
}
},
- _startAttenuatingAutoScroll: function(deltaMove, initialVelocity)
- {
+ _startAttenuatingAutoScroll: function (deltaMove, initialVelocity) {
var adjustedDeltaMove = deltaMove;
- if(this._items.length !== 0 && this._magneticType !== ccui.ListView.MAGNETIC_NONE)
- {
+ if (this._items.length !== 0 && this._magneticType !== ccui.ListView.MAGNETIC_NONE) {
adjustedDeltaMove = this._flattenVectorByDirection(adjustedDeltaMove);
var howMuchOutOfBoundary = this._getHowMuchOutOfBoundary(adjustedDeltaMove);
// If the destination is out of boundary, do nothing here. Because it will be handled by bouncing back.
- if(howMuchOutOfBoundary.x === 0 && howMuchOutOfBoundary.y === 0 )
- {
+ if (howMuchOutOfBoundary.x === 0 && howMuchOutOfBoundary.y === 0) {
var magType = this._magneticType;
- if(magType === ccui.ListView.MAGNETIC_BOTH_END)
- {
- if(this._direction === ccui.ScrollView.DIR_HORIZONTAL)
- {
+ if (magType === ccui.ListView.MAGNETIC_BOTH_END) {
+ if (this._direction === ccui.ScrollView.DIR_HORIZONTAL) {
magType = (adjustedDeltaMove.x > 0 ? ccui.ListView.MAGNETIC_LEFT : ccui.ListView.MAGNETIC_RIGHT);
}
- else if(this._direction === ccui.ScrollView.DIR_VERTICAL)
- {
+ else if (this._direction === ccui.ScrollView.DIR_VERTICAL) {
magType = (adjustedDeltaMove.y > 0 ? ccui.ListView.MAGNETIC_BOTTOM : ccui.ListView.MAGNETIC_TOP);
}
}
@@ -990,34 +930,37 @@ ccui.ListView = ccui.ScrollView.extend(/** @lends ccui.ListView# */{
adjustedDeltaMove = cc.pSub(magneticPosition, itemPosition);
}
}
- ccui.ScrollView.prototype._startAttenuatingAutoScroll.call(this,adjustedDeltaMove, initialVelocity);
- },
-
- _getAnchorPointByMagneticType: function(magneticType)
- {
- switch(magneticType)
- {
- case ccui.ListView.MAGNETIC_NONE: return cc.p(0, 0);
- case ccui.ListView.MAGNETIC_BOTH_END: return cc.p(0, 1);
- case ccui.ListView.MAGNETIC_CENTER: return cc.p(0.5, 0.5);
- case ccui.ListView.MAGNETIC_LEFT: return cc.p(0, 0.5);
- case ccui.ListView.MAGNETIC_RIGHT: return cc.p(1, 0.5);
- case ccui.ListView.MAGNETIC_TOP: return cc.p(0.5, 1);
- case ccui.ListView.MAGNETIC_BOTTOM: return cc.p(0.5, 0);
+ ccui.ScrollView.prototype._startAttenuatingAutoScroll.call(this, adjustedDeltaMove, initialVelocity);
+ },
+
+ _getAnchorPointByMagneticType: function (magneticType) {
+ switch (magneticType) {
+ case ccui.ListView.MAGNETIC_NONE:
+ return cc.p(0, 0);
+ case ccui.ListView.MAGNETIC_BOTH_END:
+ return cc.p(0, 1);
+ case ccui.ListView.MAGNETIC_CENTER:
+ return cc.p(0.5, 0.5);
+ case ccui.ListView.MAGNETIC_LEFT:
+ return cc.p(0, 0.5);
+ case ccui.ListView.MAGNETIC_RIGHT:
+ return cc.p(1, 0.5);
+ case ccui.ListView.MAGNETIC_TOP:
+ return cc.p(0.5, 1);
+ case ccui.ListView.MAGNETIC_BOTTOM:
+ return cc.p(0.5, 0);
}
return cc.p(0, 0);
},
- _startMagneticScroll: function()
- {
- if(this._items.length === 0 || this._magneticType === ccui.ListView.MAGNETIC_NONE)
- {
+ _startMagneticScroll: function () {
+ if (this._items.length === 0 || this._magneticType === ccui.ListView.MAGNETIC_NONE) {
return;
}
// Find the closest item
- var magneticAnchorPoint =this._getAnchorPointByMagneticType(this._magneticType);
+ var magneticAnchorPoint = this._getAnchorPointByMagneticType(this._magneticType);
var magneticPosition = cc.pMult(this._innerContainer.getPosition(), -1);
magneticPosition.x += this.width * magneticAnchorPoint.x;
magneticPosition.y += this.height * magneticAnchorPoint.y;
diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js b/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js
index 6c48c6e743..e37853778a 100644
--- a/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js
+++ b/extensions/ccui/uiwidgets/scroll-widget/UIPageView.js
@@ -38,7 +38,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
_childFocusCancelOffset: 0,
_pageViewEventListener: null,
_pageViewEventSelector: null,
- _className:"PageView",
+ _className: "PageView",
_indicator: null,
_indicatorPositionAsAnchorPoint: null,
@@ -77,8 +77,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Insert a page into the end of PageView.
* @param {ccui.Widget} page Page to be inserted.
*/
- addPage: function(page)
- {
+ addPage: function (page) {
this.pushBackCustomItem(page);
},
@@ -87,8 +86,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* @param {ccui.Widget} page Page to be inserted.
* @param {number} idx A given index.
*/
- insertPage: function(page, idx)
- {
+ insertPage: function (page, idx) {
this.insertCustomItem(page, idx);
},
@@ -111,7 +109,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
/**
* Removes all pages from PageView
*/
- removeAllPages: function(){
+ removeAllPages: function () {
this.removeAllItems();
},
@@ -132,14 +130,13 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
},
- _doLayout: function(){
+ _doLayout: function () {
if (!this._refreshViewDirty)
return;
ccui.ListView.prototype._doLayout.call(this);
- if(this._indicator)
- {
+ if (this._indicator) {
var index = this.getIndex(this.getCenterItemInCurrentView());
this._indicator.indicate(index);
}
@@ -151,20 +148,16 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Changes scroll direction of ccui.PageView.
* @param {ccui.ScrollView.DIR_NONE | ccui.ScrollView.DIR_VERTICAL | ccui.ScrollView.DIR_HORIZONTAL | ccui.ScrollView.DIR_BOTH} direction
*/
- setDirection: function(direction)
- {
+ setDirection: function (direction) {
ccui.ListView.prototype.setDirection.call(this, direction);
- if(direction === ccui.ScrollView.DIR_HORIZONTAL)
- {
+ if (direction === ccui.ScrollView.DIR_HORIZONTAL) {
this._indicatorPositionAsAnchorPoint = cc.p(0.5, 0.1);
}
- else if(direction === ccui.ScrollView.DIR_VERTICAL)
- {
+ else if (direction === ccui.ScrollView.DIR_VERTICAL) {
this._indicatorPositionAsAnchorPoint = cc.p(0.1, 0.5);
}
- if(this._indicator)
- {
+ if (this._indicator) {
this._indicator.setDirection(direction);
this._refreshIndicatorPosition();
}
@@ -176,7 +169,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* @param threshold
* @deprecated Since v3.9, this method has no effect.
*/
- setCustomScrollThreshold: function(threshold){
+ setCustomScrollThreshold: function (threshold) {
},
@@ -185,7 +178,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* @since v3.2
* @deprecated Since v3.9, this method always returns 0.
*/
- getCustomScrollThreshold: function(){
+ getCustomScrollThreshold: function () {
return 0;
},
@@ -194,52 +187,44 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* @since v3.2
* @deprecated Since v3.9, this method has no effect.
*/
- setUsingCustomScrollThreshold: function(flag){
+ setUsingCustomScrollThreshold: function (flag) {
},
/**
* Queries whether we are using user defined scroll page threshold or not
* @deprecated Since v3.9, this method always returns false.
*/
- isUsingCustomScrollThreshold: function(){
+ isUsingCustomScrollThreshold: function () {
return false;
},
- _moveInnerContainer: function(deltaMove, canStartBounceBack)
- {
+ _moveInnerContainer: function (deltaMove, canStartBounceBack) {
ccui.ListView.prototype._moveInnerContainer.call(this, deltaMove, canStartBounceBack);
this._curPageIdx = this.getIndex(this.getCenterItemInCurrentView());
- if(this._indicator)
- {
+ if (this._indicator) {
this._indicator.indicate(this._curPageIdx);
}
},
- _onItemListChanged: function()
- {
+ _onItemListChanged: function () {
ccui.ListView.prototype._onItemListChanged.call(this);
- if(this._indicator)
- {
+ if (this._indicator) {
this._indicator.reset(this._items.length);
}
},
- _onSizeChanged: function()
- {
+ _onSizeChanged: function () {
ccui.ListView.prototype._onSizeChanged.call(this);
this._refreshIndicatorPosition();
},
- _remedyLayoutParameter: function (item)
- {
+ _remedyLayoutParameter: function (item) {
item.setContentSize(this.getContentSize());
ccui.ListView.prototype._remedyLayoutParameter.call(this, item);
},
-
- _refreshIndicatorPosition: function()
- {
- if(this._indicator)
- {
+
+ _refreshIndicatorPosition: function () {
+ if (this._indicator) {
var contentSize = this.getContentSize();
var posX = contentSize.width * this._indicatorPositionAsAnchorPoint.x;
var posY = contentSize.height * this._indicatorPositionAsAnchorPoint.y;
@@ -257,12 +242,10 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
var touchMoveVelocity = this._flattenVectorByDirection(this._calculateTouchMoveVelocity());
var INERTIA_THRESHOLD = 500;
- if(cc.pLength(touchMoveVelocity) < INERTIA_THRESHOLD)
- {
+ if (cc.pLength(touchMoveVelocity) < INERTIA_THRESHOLD) {
this._startMagneticScroll();
}
- else
- {
+ else {
// Handle paging by inertia force.
var currentPage = this.getItem(this._curPageIdx);
var destination = this._calculateItemDestination(cc.p(0.5, 0.5), currentPage, cc.p(0.5, 0.5));
@@ -271,18 +254,14 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
// If the direction of displacement to current page and the direction of touch are same, just start magnetic scroll to the current page.
// Otherwise, move to the next page of touch direction.
- if(touchMoveVelocity.x * deltaToCurrentPage.x > 0 || touchMoveVelocity.y * deltaToCurrentPage.y > 0)
- {
+ if (touchMoveVelocity.x * deltaToCurrentPage.x > 0 || touchMoveVelocity.y * deltaToCurrentPage.y > 0) {
this._startMagneticScroll();
}
- else
- {
- if(touchMoveVelocity.x < 0 || touchMoveVelocity.y > 0)
- {
+ else {
+ if (touchMoveVelocity.x < 0 || touchMoveVelocity.y > 0) {
++this._curPageIdx;
}
- else
- {
+ else {
--this._curPageIdx;
}
this._curPageIdx = Math.min(this._curPageIdx, this._items.length);
@@ -293,19 +272,18 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
},
- _getAutoScrollStopEpsilon: function()
- {
+ _getAutoScrollStopEpsilon: function () {
return 0.001;
},
_pageTurningEvent: function () {
- if(this._pageViewEventSelector){
+ if (this._pageViewEventSelector) {
if (this._pageViewEventListener)
this._pageViewEventSelector.call(this._pageViewEventListener, this, ccui.PageView.EVENT_TURNING);
else
this._pageViewEventSelector(this, ccui.PageView.EVENT_TURNING);
}
- if(this._ccEventCallback)
+ if (this._ccEventCallback)
this._ccEventCallback(this, ccui.PageView.EVENT_TURNING);
},
@@ -320,9 +298,9 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
this._pageViewEventListener = target;
},
- addEventListener: function(selector){
- this._ccEventCallback = function(ref, eventType) {
- if(eventType == ccui.ScrollView.EVENT_AUTOSCROLL_ENDED)
+ addEventListener: function (selector) {
+ this._ccEventCallback = function (ref, eventType) {
+ if (eventType == ccui.ScrollView.EVENT_AUTOSCROLL_ENDED)
selector(this, eventType)
};
},
@@ -332,8 +310,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* This is the different between scrollToPage.
* @param {number} index A given index in PageView. Index start from 0 to pageCount -1.
*/
- setCurrentPageIndex: function(index)
- {
+ setCurrentPageIndex: function (index) {
this.jumpToItem(index, cc.p(0.5, 0.5), cc.p(0.5, 0.5));
},
@@ -343,8 +320,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* @param {number} index A given index in PageView. Index start from 0 to pageCount -1.
* @deprecated since v3.9, this is deprecated. Use `setCurrentPageIndex()` instead.
*/
- setCurPageIndex: function(index)
- {
+ setCurPageIndex: function (index) {
this.setCurrentPageIndex(index);
},
@@ -370,7 +346,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Returns all pages of PageView
* @returns {Array}
*/
- getPages:function(){
+ getPages: function () {
return this.getItems();
},
@@ -379,7 +355,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* @param {Number} index
* @returns {ccui.Layout}
*/
- getPage: function(index){
+ getPage: function (index) {
return this.getItem(index);
},
@@ -416,20 +392,16 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Toggle page indicator enabled.
* @param {boolean} enabled True if enable page indicator, false otherwise.
*/
- setIndicatorEnabled: function(enabled)
- {
- if(enabled == (this._indicator !== null))
- {
+ setIndicatorEnabled: function (enabled) {
+ if (enabled == (this._indicator !== null)) {
return;
}
- if(!enabled)
- {
+ if (!enabled) {
this.removeProtectedChild(this._indicator);
this._indicator = null;
}
- else
- {
+ else {
this._indicator = new ccui.PageViewIndicator();
this._indicator.setDirection(this.getDirection());
this.addProtectedChild(this._indicator, 10000);
@@ -442,8 +414,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Query page indicator state.
* @returns {boolean} True if page indicator is enabled, false otherwise.
*/
- getIndicatorEnabled: function()
- {
+ getIndicatorEnabled: function () {
return this._indicator !== null;
},
@@ -451,8 +422,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Set the page indicator's position using anchor point.
* @param {cc.Point} positionAsAnchorPoint The position as anchor point.
*/
- setIndicatorPositionAsAnchorPoint: function(positionAsAnchorPoint)
- {
+ setIndicatorPositionAsAnchorPoint: function (positionAsAnchorPoint) {
this._indicatorPositionAsAnchorPoint = positionAsAnchorPoint;
this._refreshIndicatorPosition();
},
@@ -461,8 +431,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Get the page indicator's position as anchor point.
* @returns {cc.Point}
*/
- getIndicatorPositionAsAnchorPoint: function()
- {
+ getIndicatorPositionAsAnchorPoint: function () {
return this._indicatorPositionAsAnchorPoint;
},
@@ -470,10 +439,8 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Set the page indicator's position in page view.
* @param {cc.Point} position The position in page view
*/
- setIndicatorPosition: function(position)
- {
- if(this._indicator)
- {
+ setIndicatorPosition: function (position) {
+ if (this._indicator) {
var contentSize = this.getContentSize();
this._indicatorPositionAsAnchorPoint.x = position.x / contentSize.width;
this._indicatorPositionAsAnchorPoint.y = position.y / contentSize.height;
@@ -485,8 +452,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Get the page indicator's position.
* @returns {cc.Point}
*/
- getIndicatorPosition: function()
- {
+ getIndicatorPosition: function () {
cc.assert(this._indicator !== null, "");
return this._indicator.getPosition();
},
@@ -495,10 +461,8 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Set space between page indicator's index nodes.
* @param {number} spaceBetweenIndexNodes Space between nodes in pixel.
*/
- setIndicatorSpaceBetweenIndexNodes: function(spaceBetweenIndexNodes)
- {
- if(this._indicator)
- {
+ setIndicatorSpaceBetweenIndexNodes: function (spaceBetweenIndexNodes) {
+ if (this._indicator) {
this._indicator.setSpaceBetweenIndexNodes(spaceBetweenIndexNodes);
}
},
@@ -507,8 +471,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Get the space between page indicator's index nodes.
* @returns {number}
*/
- getIndicatorSpaceBetweenIndexNodes: function()
- {
+ getIndicatorSpaceBetweenIndexNodes: function () {
cc.assert(this._indicator !== null, "");
return this._indicator.getSpaceBetweenIndexNodes();
},
@@ -517,10 +480,8 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Set color of page indicator's selected index.
* @param {cc.Color} color Color for indicator
*/
- setIndicatorSelectedIndexColor: function(color)
- {
- if(this._indicator)
- {
+ setIndicatorSelectedIndexColor: function (color) {
+ if (this._indicator) {
this._indicator.setSelectedIndexColor(color);
}
},
@@ -529,8 +490,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Get the color of page indicator's selected index.
* @returns {cc.Color}
*/
- getIndicatorSelectedIndexColor: function()
- {
+ getIndicatorSelectedIndexColor: function () {
cc.assert(this._indicator !== null, "");
return this._indicator.getSelectedIndexColor();
},
@@ -539,10 +499,8 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Set color of page indicator's index nodes.
* @param {cc.Color} color Color for indicator
*/
- setIndicatorIndexNodesColor: function(color)
- {
- if(this._indicator)
- {
+ setIndicatorIndexNodesColor: function (color) {
+ if (this._indicator) {
this._indicator.setIndexNodesColor(color);
}
},
@@ -551,8 +509,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Get the color of page indicator's index nodes.
* @returns {cc.Color}
*/
- getIndicatorIndexNodesColor: function()
- {
+ getIndicatorIndexNodesColor: function () {
cc.assert(this._indicator !== null, "");
return this._indicator.getIndexNodesColor();
},
@@ -561,10 +518,8 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Set scale of page indicator's index nodes.
* @param {Number} scale Scale for indicator
*/
- setIndicatorIndexNodesScale: function(indexNodesScale)
- {
- if(this._indicator)
- {
+ setIndicatorIndexNodesScale: function (indexNodesScale) {
+ if (this._indicator) {
this._indicator.setIndexNodesScale(indexNodesScale);
this._indicator.indicate(this._curPageIdx);
}
@@ -574,8 +529,7 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* Get the scale of page indicator's index nodes.
* @returns {Number}
*/
- getIndicatorIndexNodesScale: function()
- {
+ getIndicatorIndexNodesScale: function () {
cc.assert(this._indicator !== null, "");
return this._indicator.getIndexNodesScale();
},
@@ -585,10 +539,8 @@ ccui.PageView = ccui.ListView.extend(/** @lends ccui.PageView# */{
* @param {String} texName
* @param {ccui.Widget.LOCAL_TEXTURE | ccui.Widget.PLIST_TEXTURE} [texType = ccui.Widget.LOCAL_TEXTURE]
*/
- setIndicatorIndexNodesTexture: function(texName, texType)
- {
- if(this._indicator)
- {
+ setIndicatorIndexNodesTexture: function (texName, texType) {
+ if (this._indicator) {
this._indicator.setIndexNodesTexture(texName, texType);
this._indicator.indicate(this._curPageIdx);
}
diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIPageViewIndicator.js b/extensions/ccui/uiwidgets/scroll-widget/UIPageViewIndicator.js
index 4ffb42b51d..8044ba2269 100644
--- a/extensions/ccui/uiwidgets/scroll-widget/UIPageViewIndicator.js
+++ b/extensions/ccui/uiwidgets/scroll-widget/UIPageViewIndicator.js
@@ -67,8 +67,7 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* Sets direction of indicator
* @param {ccui.ScrollView.DIR_NONE | ccui.ScrollView.DIR_VERTICAL | ccui.ScrollView.DIR_HORIZONTAL | ccui.ScrollView.DIR_BOTH} direction
*/
- setDirection: function(direction)
- {
+ setDirection: function (direction) {
this._direction = direction;
this._rearrange();
},
@@ -77,14 +76,11 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* resets indicator with new page count.
* @param {number} numberOfTotalPages
*/
- reset: function(numberOfTotalPages)
- {
- while(this._indexNodes.length < numberOfTotalPages)
- {
+ reset: function (numberOfTotalPages) {
+ while (this._indexNodes.length < numberOfTotalPages) {
this._increaseNumberOfPages();
}
- while(this._indexNodes.length > numberOfTotalPages)
- {
+ while (this._indexNodes.length > numberOfTotalPages) {
this._decreaseNumberOfPages();
}
this._rearrange();
@@ -95,19 +91,15 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* Indicates node by index
* @param {number} index
*/
- indicate: function(index)
- {
- if (index < 0 || index >= this._indexNodes.length)
- {
+ indicate: function (index) {
+ if (index < 0 || index >= this._indexNodes.length) {
return;
}
this._currentIndexNode.setPosition(this._indexNodes[index].getPosition());
},
- _rearrange: function()
- {
- if(this._indexNodes.length === 0)
- {
+ _rearrange: function () {
+ if (this._indexNodes.length === 0) {
return;
}
@@ -121,15 +113,12 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
var totalSizeValue = sizeValue * numberOfItems + this._spaceBetweenIndexNodes * (numberOfItems - 1);
var posValue = -(totalSizeValue / 2) + (sizeValue / 2);
- for(var i = 0; i < this._indexNodes.length; ++i)
- {
+ for (var i = 0; i < this._indexNodes.length; ++i) {
var position;
- if(horizontal)
- {
+ if (horizontal) {
position = cc.p(posValue, indexNodeSize.height / 2.0);
}
- else
- {
+ else {
position = cc.p(indexNodeSize.width / 2.0, -posValue);
}
this._indexNodes[i].setPosition(position);
@@ -141,10 +130,8 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* Sets space between index nodes.
* @param {number} spaceBetweenIndexNodes
*/
- setSpaceBetweenIndexNodes: function(spaceBetweenIndexNodes)
- {
- if(this._spaceBetweenIndexNodes === spaceBetweenIndexNodes)
- {
+ setSpaceBetweenIndexNodes: function (spaceBetweenIndexNodes) {
+ if (this._spaceBetweenIndexNodes === spaceBetweenIndexNodes) {
return;
}
this._spaceBetweenIndexNodes = spaceBetweenIndexNodes;
@@ -155,8 +142,7 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* Gets space between index nodes.
* @returns {number}
*/
- getSpaceBetweenIndexNodes: function()
- {
+ getSpaceBetweenIndexNodes: function () {
return this._spaceBetweenIndexNodes;
},
@@ -164,8 +150,7 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* Sets color of selected index node
* @param {cc.Color} color
*/
- setSelectedIndexColor: function(color)
- {
+ setSelectedIndexColor: function (color) {
this._currentIndexNode.setColor(color);
},
@@ -173,8 +158,7 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* Gets color of selected index node
* @returns {cc.Color}
*/
- getSelectedIndexColor: function()
- {
+ getSelectedIndexColor: function () {
return this._currentIndexNode.getColor();
},
@@ -182,12 +166,10 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* Sets color of index nodes
* @param {cc.Color} indexNodesColor
*/
- setIndexNodesColor: function(indexNodesColor)
- {
+ setIndexNodesColor: function (indexNodesColor) {
this._indexNodesColor = indexNodesColor;
- for(var i = 0 ; i < this._indexNodes.length; ++i)
- {
+ for (var i = 0; i < this._indexNodes.length; ++i) {
this._indexNodes[i].setColor(indexNodesColor);
}
},
@@ -196,8 +178,7 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* Gets color of index nodes
* @returns {cc.Color}
*/
- getIndexNodesColor: function()
- {
+ getIndexNodesColor: function () {
var locRealColor = this._indexNodesColor;
return cc.color(locRealColor.r, locRealColor.g, locRealColor.b, locRealColor.a);
},
@@ -206,19 +187,16 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* Sets scale of index nodes
* @param {Number} indexNodesScale
*/
- setIndexNodesScale: function(indexNodesScale)
- {
- if(this._indexNodesScale === indexNodesScale)
- {
+ setIndexNodesScale: function (indexNodesScale) {
+ if (this._indexNodesScale === indexNodesScale) {
return;
}
this._indexNodesScale = indexNodesScale;
this._currentIndexNode.setScale(indexNodesScale);
- for(var i = 0 ; i < this._indexNodes.length; ++i)
- {
- this._indexNodes[i].setScale(this,_indexNodesScale);
+ for (var i = 0; i < this._indexNodes.length; ++i) {
+ this._indexNodes[i].setScale(this, _indexNodesScale);
}
this._rearrange();
@@ -228,8 +206,7 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* Gets scale of index nodes
* @returns {Number}
*/
- getIndexNodesScale: function()
- {
+ getIndexNodesScale: function () {
return this._indexNodesScale;
},
@@ -238,28 +215,24 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
* @param {String} texName
* @param {ccui.Widget.LOCAL_TEXTURE | ccui.Widget.PLIST_TEXTURE} [texType = ccui.Widget.LOCAL_TEXTURE]
*/
- setIndexNodesTexture: function(texName, texType)
- {
- if(texType === undefined)
+ setIndexNodesTexture: function (texName, texType) {
+ if (texType === undefined)
texType = ccui.Widget.LOCAL_TEXTURE;
this._useDefaultTexture = false;
this._indexNodesTextureFile = texName;
this._indexNodesTexType = texType;
- switch (texType)
- {
+ switch (texType) {
case ccui.Widget.LOCAL_TEXTURE:
this._currentIndexNode.setTexture(texName);
- for(var i = 0 ; i < this._indexNodes.length; ++i)
- {
+ for (var i = 0; i < this._indexNodes.length; ++i) {
this._indexNodes[i].setTexture(texName);
}
break;
case ccui.Widget.PLIST_TEXTURE:
this._currentIndexNode.setSpriteFrame(texName);
- for(var i = 0 ; i < this._indexNodes.length; ++i)
- {
+ for (var i = 0; i < this._indexNodes.length; ++i) {
this._indexNodes[i].setSpriteFrame(texName);
}
break;
@@ -270,19 +243,15 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
this._rearrange();
},
- _increaseNumberOfPages: function()
- {
+ _increaseNumberOfPages: function () {
var indexNode;
- if(this._useDefaultTexture)
- {
+ if (this._useDefaultTexture) {
indexNode = ccui.helper._createSpriteFromBase64(ccui.PageViewIndicator.CIRCLE_IMAGE, ccui.PageViewIndicator.CIRCLE_IMAGE_KEY);
}
- else
- {
+ else {
indexNode = new cc.Sprite();
- switch (this._indexNodesTexType)
- {
+ switch (this._indexNodesTexType) {
case ccui.Widget.LOCAL_TEXTURE:
indexNode.initWithFile(this._indexNodesTextureFile);
break;
@@ -301,10 +270,8 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
this._indexNodes.push(indexNode);
},
- _decreaseNumberOfPages: function()
- {
- if(this._indexNodes.length === 0)
- {
+ _decreaseNumberOfPages: function () {
+ if (this._indexNodes.length === 0) {
return;
}
this.removeProtectedChild(this._indexNodes[0]);
@@ -314,10 +281,8 @@ ccui.PageViewIndicator = ccui.ProtectedNode.extend(/** @lends ccui.PageViewIndic
/**
* Removes all index nodes.
*/
- clear: function()
- {
- for(var i = 0; i < this._indexNodes.length; ++i)
- {
+ clear: function () {
+ for (var i = 0; i < this._indexNodes.length; ++i) {
this.removeProtectedChild(this._indexNodes[i]);
}
this._indexNodes.length = 0;
diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js
index 0a71cdf1a3..79741c9525 100644
--- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js
+++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollView.js
@@ -47,12 +47,12 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
_touchMoveDisplacements: null,
_touchMoveTimeDeltas: null,
_touchMovePreviousTimestamp: 0,
- _touchTotalTimeThreshold : 0.5,
+ _touchTotalTimeThreshold: 0.5,
_autoScrolling: false,
_autoScrollTargetDelta: null,
_autoScrollAttenuate: true,
- _autoScrollStartPosition : null,
+ _autoScrollStartPosition: null,
_autoScrollTotalTime: 0,
_autoScrollAccumulatedTime: 0,
_autoScrollCurrentlyOutOfBoundary: false,
@@ -109,19 +109,6 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
this.setTouchEnabled(true);
},
- /**
- * Initializes a ccui.ScrollView. Please do not call this function by yourself, you should pass the parameters to constructor to initialize it.
- * @returns {boolean}
- */
- init: function () {
- if (ccui.Layout.prototype.init.call(this)) {
-
-
- return true;
- }
- return false;
- },
-
/**
* Calls the parent class' onEnter and schedules update function.
* @override
@@ -136,6 +123,73 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
ccui.Layout.prototype.onExit.call(this);
},
+ visit: function (parent) {
+ var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null;
+
+ // quick return if not visible
+ if (!this._visible) {
+ cmd._propagateFlagsDown(parentCmd);
+ return;
+ }
+
+ this._adaptRenderers();
+ this._doLayout();
+
+ var renderer = cc.renderer;
+ cmd.visit(parentCmd);
+
+ renderer.pushRenderCommand(cmd);
+ if (cmd instanceof ccui.ScrollView.WebGLRenderCmd) {
+ var currentID = this.__instanceId;
+ renderer._turnToCacheMode(currentID);
+ }
+
+ var stencilClipping = this._clippingEnabled && this._clippingType === ccui.Layout.CLIPPING_STENCIL;
+ var scissorClipping = this._clippingEnabled && this._clippingType === ccui.Layout.CLIPPING_SCISSOR;
+
+ if (stencilClipping) {
+ cmd.stencilClippingVisit(parentCmd);
+ }
+ else if (scissorClipping) {
+ cmd.scissorClippingVisit(parentCmd);
+ }
+
+ var i, children = this._children, len = children.length, child;
+ var j, pChildren = this._protectedChildren, pLen = pChildren.length, pChild;
+
+ if (this._reorderChildDirty) this.sortAllChildren();
+ if (this._reorderProtectedChildDirty) this.sortAllProtectedChildren();
+ for (i = 0; i < len; i++) {
+ child = children[i];
+ if (child && child._visible) {
+ child.visit(this);
+ }
+ }
+ for (j = 0; j < pLen; j++) {
+ pChild = pChildren[j];
+ if (pChild && pChild._visible) {
+ cmd._changeProtectedChild(pChild);
+ pChild.visit(this);
+ }
+ }
+
+ if (stencilClipping) {
+ cmd.postStencilVisit();
+ }
+ else if (scissorClipping) {
+ cmd.postScissorVisit();
+ }
+
+ if (cmd instanceof ccui.ScrollView.WebGLRenderCmd) {
+ renderer._turnToNormalMode();
+ }
+
+ // Need to update children after do layout
+ this.updateChildren();
+
+ cmd._dirtyFlag = 0;
+ },
+
/**
* When a widget is in a layout, you could call this method to get the next focused widget within a specified _direction.
* If the widget is not in a layout, it will return itself
@@ -144,7 +198,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
* @param {ccui.Widget} current the current focused widget
* @returns {ccui.Widget}
*/
- findNextFocusedWidget: function(direction, current){
+ findNextFocusedWidget: function (direction, current) {
if (this.getLayoutType() === ccui.Layout.LINEAR_VERTICAL
|| this.getLayoutType() === ccui.Layout.LINEAR_HORIZONTAL) {
return this._innerContainer.findNextFocusedWidget(direction, current);
@@ -156,7 +210,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
ccui.Layout.prototype._initRenderer.call(this);
this._innerContainer = new ccui.Layout();
- this._innerContainer.setColor(cc.color(255,255,255));
+ this._innerContainer.setColor(cc.color(255, 255, 255));
this._innerContainer.setOpacity(255);
this._innerContainer.setCascadeColorEnabled(true);
this._innerContainer.setCascadeOpacityEnabled(true);
@@ -164,8 +218,8 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
this.addProtectedChild(this._innerContainer, 1, 1);
},
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_WEBGL)
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
return new ccui.ScrollView.WebGLRenderCmd(this);
else
return new ccui.ScrollView.CanvasRenderCmd(this);
@@ -193,7 +247,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
* @param {cc.Size} size inner container size.
*/
setInnerContainerSize: function (size) {
- var innerContainer = this._innerContainer,
+ var innerContainer = this._innerContainer,
locSize = this._contentSize,
innerSizeWidth = locSize.width, innerSizeHeight = locSize.height;
@@ -283,23 +337,18 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
*
* @param {cc.Point} position Inner container position.
*/
- setInnerContainerPosition: function(position)
- {
- if(position.x === this._innerContainer.getPositionX() && position.y === this._innerContainer.getPositionY())
- {
+ setInnerContainerPosition: function (position) {
+ if (position.x === this._innerContainer.getPositionX() && position.y === this._innerContainer.getPositionY()) {
return;
}
this._innerContainer.setPosition(position);
this._outOfBoundaryAmountDirty = true;
// Process bouncing events
- if(this.bounceEnabled)
- {
- for(var _direction = ccui.ScrollView.MOVEDIR_TOP; _direction < ccui.ScrollView.MOVEDIR_RIGHT; ++_direction)
- {
- if(this._isOutOfBoundary(_direction))
- {
- this._processScrollEvent(_direction, true);
+ if (this.bounceEnabled) {
+ for (var _direction = ccui.ScrollView.MOVEDIR_TOP; _direction < ccui.ScrollView.MOVEDIR_RIGHT; ++_direction) {
+ if (this._isOutOfBoundary(_direction)) {
+ this._processScrollEvent(_direction, true);
}
}
}
@@ -312,8 +361,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
*
* @return The inner container position.
*/
- getInnerContainerPosition: function()
- {
+ getInnerContainerPosition: function () {
return this._innerContainer.getPosition();
},
@@ -334,7 +382,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
},
_isInContainer: function (widget) {
- if(!this._clippingEnabled)
+ if (!this._clippingEnabled)
return true;
var wPos = widget._position,
wSize = widget._contentSize,
@@ -359,9 +407,9 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
updateChildren: function () {
var child, i, l;
var childrenArray = this._innerContainer._children;
- for(i = 0, l = childrenArray.length; i < l; i++) {
+ for (i = 0, l = childrenArray.length; i < l; i++) {
child = childrenArray[i];
- if(child._inViewRect === true && this._isInContainer(child) === false)
+ if (child._inViewRect === true && this._isInContainer(child) === false)
child._inViewRect = false;
else if (child._inViewRect === false && this._isInContainer(child) === true)
child._inViewRect = true;
@@ -375,9 +423,9 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
* @returns {boolean}
*/
addChild: function (widget, zOrder, tag) {
- if(!widget)
+ if (!widget)
return false;
- if(this._isInContainer(widget) === false)
+ if (this._isInContainer(widget) === false)
widget._inViewRect = false;
zOrder = zOrder || widget.getLocalZOrder();
tag = tag || widget.getTag();
@@ -395,7 +443,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
* Removes all children.
* @param {Boolean} cleanup
*/
- removeAllChildrenWithCleanup: function(cleanup){
+ removeAllChildrenWithCleanup: function (cleanup) {
this._innerContainer.removeAllChildrenWithCleanup(cleanup);
},
@@ -444,59 +492,48 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
return this._innerContainer.getChildByName(name);
},
- _flattenVectorByDirection: function(vector)
- {
- var result = cc.p(0 ,0);
+ _flattenVectorByDirection: function (vector) {
+ var result = cc.p(0, 0);
result.x = (this._direction === ccui.ScrollView.DIR_VERTICAL ? 0 : vector.x);
result.y = (this._direction === ccui.ScrollView.DIR_HORIZONTAL ? 0 : vector.y);
return result;
},
- _getHowMuchOutOfBoundary: function(addition)
- {
- if(addition === undefined)
+ _getHowMuchOutOfBoundary: function (addition) {
+ if (addition === undefined)
addition = cc.p(0, 0);
- if(addition.x === 0 && addition.y === 0 && !this._outOfBoundaryAmountDirty)
- {
+ if (addition.x === 0 && addition.y === 0 && !this._outOfBoundaryAmountDirty) {
return this._outOfBoundaryAmount;
}
var outOfBoundaryAmount = cc.p(0, 0);
- if(this._innerContainer.getLeftBoundary() + addition.x > this._leftBoundary)
- {
+ if (this._innerContainer.getLeftBoundary() + addition.x > this._leftBoundary) {
outOfBoundaryAmount.x = this._leftBoundary - (this._innerContainer.getLeftBoundary() + addition.x);
}
- else if(this._innerContainer.getRightBoundary() + addition.x < this._rightBoundary)
- {
+ else if (this._innerContainer.getRightBoundary() + addition.x < this._rightBoundary) {
outOfBoundaryAmount.x = this._rightBoundary - (this._innerContainer.getRightBoundary() + addition.x);
}
- if(this._innerContainer.getTopBoundary() + addition.y < this._topBoundary)
- {
+ if (this._innerContainer.getTopBoundary() + addition.y < this._topBoundary) {
outOfBoundaryAmount.y = this._topBoundary - (this._innerContainer.getTopBoundary() + addition.y);
}
- else if(this._innerContainer.getBottomBoundary() + addition.y > this._bottomBoundary)
- {
+ else if (this._innerContainer.getBottomBoundary() + addition.y > this._bottomBoundary) {
outOfBoundaryAmount.y = this._bottomBoundary - (this._innerContainer.getBottomBoundary() + addition.y);
}
- if(addition.x === 0 && addition.y === 0 )
- {
+ if (addition.x === 0 && addition.y === 0) {
this._outOfBoundaryAmount = outOfBoundaryAmount;
this._outOfBoundaryAmountDirty = false;
}
return outOfBoundaryAmount;
},
- _isOutOfBoundary: function(dir)
- {
+ _isOutOfBoundary: function (dir) {
var outOfBoundary = this._getHowMuchOutOfBoundary();
- if(dir !== undefined)
- {
- switch (dir)
- {
+ if (dir !== undefined) {
+ switch (dir) {
case ccui.ScrollView.MOVEDIR_TOP:
return outOfBoundary.y > 0;
case ccui.ScrollView.MOVEDIR_BOTTOM:
@@ -507,8 +544,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
return outOfBoundary.x > 0;
}
}
- else
- {
+ else {
return !this._fltEqualZero(outOfBoundary);
}
@@ -516,17 +552,15 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
},
- _moveInnerContainer: function(deltaMove, canStartBounceBack)
- {
+ _moveInnerContainer: function (deltaMove, canStartBounceBack) {
var adjustedMove = this._flattenVectorByDirection(deltaMove);
this.setInnerContainerPosition(cc.pAdd(this.getInnerContainerPosition(), adjustedMove));
- var outOfBoundary =this._getHowMuchOutOfBoundary();
+ var outOfBoundary = this._getHowMuchOutOfBoundary();
this._updateScrollBar(outOfBoundary);
- if(this.bounceEnabled && canStartBounceBack)
- {
+ if (this.bounceEnabled && canStartBounceBack) {
this._startBounceBackIfNeeded();
}
},
@@ -543,22 +577,18 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
}
},
- _calculateTouchMoveVelocity: function()
- {
+ _calculateTouchMoveVelocity: function () {
var totalTime = 0;
- for(var i = 0; i < this._touchMoveTimeDeltas.length; ++i)
- {
+ for (var i = 0; i < this._touchMoveTimeDeltas.length; ++i) {
totalTime += this._touchMoveTimeDeltas[i];
}
- if(totalTime == 0 || totalTime >= this._touchTotalTimeThreshold)
- {
+ if (totalTime == 0 || totalTime >= this._touchTotalTimeThreshold) {
return cc.p(0, 0);
}
- var totalMovement = cc.p(0 ,0);
+ var totalMovement = cc.p(0, 0);
- for(var i = 0; i < this._touchMoveDisplacements.length; ++i)
- {
+ for (var i = 0; i < this._touchMoveDisplacements.length; ++i) {
totalMovement.x += this._touchMoveDisplacements[i].x;
totalMovement.y += this._touchMoveDisplacements[i].y;
}
@@ -570,8 +600,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
* Set the touch total time threshold
* @param {Number} touchTotalTimeThreshold
*/
- setTouchTotalTimeThreshold: function(touchTotalTimeThreshold)
- {
+ setTouchTotalTimeThreshold: function (touchTotalTimeThreshold) {
this._touchTotalTimeThreshold = touchTotalTimeThreshold;
},
@@ -580,27 +609,22 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
* Get the touch total time threshold
* @returns {Number}
*/
- getTouchTotalTimeThreshold: function()
- {
+ getTouchTotalTimeThreshold: function () {
return this._touchTotalTimeThreshold;
},
- _startInertiaScroll: function(touchMoveVelocity)
- {
+ _startInertiaScroll: function (touchMoveVelocity) {
var MOVEMENT_FACTOR = 0.7;
var inertiaTotalMovement = cc.pMult(touchMoveVelocity, MOVEMENT_FACTOR);
this._startAttenuatingAutoScroll(inertiaTotalMovement, touchMoveVelocity);
},
- _startBounceBackIfNeeded: function()
- {
- if (!this.bounceEnabled)
- {
+ _startBounceBackIfNeeded: function () {
+ if (!this.bounceEnabled) {
return false;
}
var bounceBackAmount = this._getHowMuchOutOfBoundary();
- if(this._fltEqualZero(bounceBackAmount))
- {
+ if (this._fltEqualZero(bounceBackAmount)) {
return false;
}
@@ -609,25 +633,21 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
return true;
},
- _startAutoScrollToDestination: function(destination, timeInSec, attenuated)
- {
- this._startAutoScroll(cc.pSub(destination , this._innerContainer.getPosition()), timeInSec, attenuated);
+ _startAutoScrollToDestination: function (destination, timeInSec, attenuated) {
+ this._startAutoScroll(cc.pSub(destination, this._innerContainer.getPosition()), timeInSec, attenuated);
},
- _calculateAutoScrollTimeByInitialSpeed: function(initialSpeed)
- {
+ _calculateAutoScrollTimeByInitialSpeed: function (initialSpeed) {
// Calculate the time from the initial speed according to quintic polynomial.
return Math.sqrt(Math.sqrt(initialSpeed / 5));
},
- _startAttenuatingAutoScroll: function(deltaMove, initialVelocity)
- {
- var time = this._calculateAutoScrollTimeByInitialSpeed(cc.pLength(initialVelocity));
+ _startAttenuatingAutoScroll: function (deltaMove, initialVelocity) {
+ var time = this._calculateAutoScrollTimeByInitialSpeed(cc.pLength(initialVelocity));
this._startAutoScroll(deltaMove, time, true);
},
- _startAutoScroll: function(deltaMove, timeInSec, attenuated)
- {
+ _startAutoScroll: function (deltaMove, timeInSec, attenuated) {
var adjustedDeltaMove = this._flattenVectorByDirection(deltaMove);
this._autoScrolling = true;
@@ -637,16 +657,14 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
this._autoScrollTotalTime = timeInSec;
this._autoScrollAccumulatedTime = 0;
this._autoScrollBraking = false;
- this._autoScrollBrakingStartPosition = cc.p(0,0 );
+ this._autoScrollBrakingStartPosition = cc.p(0, 0);
// If the destination is also out of boundary of same side, start brake from beggining.
var currentOutOfBoundary = this._getHowMuchOutOfBoundary();
- if(!this._fltEqualZero(currentOutOfBoundary))
- {
+ if (!this._fltEqualZero(currentOutOfBoundary)) {
this._autoScrollCurrentlyOutOfBoundary = true;
var afterOutOfBoundary = this._getHowMuchOutOfBoundary(adjustedDeltaMove);
- if(currentOutOfBoundary.x * afterOutOfBoundary.x > 0 || currentOutOfBoundary.y * afterOutOfBoundary.y > 0)
- {
+ if (currentOutOfBoundary.x * afterOutOfBoundary.x > 0 || currentOutOfBoundary.y * afterOutOfBoundary.y > 0) {
this._autoScrollBraking = true;
}
}
@@ -655,51 +673,42 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
/**
* Immediately stops inner container scroll initiated by any of the "scrollTo*" member functions
*/
- stopAutoScroll: function()
- {
+ stopAutoScroll: function () {
this._autoScrolling = false;
this._autoScrollAttenuate = true;
this._autoScrollTotalTime = 0;
this._autoScrollAccumulatedTime = 0;
},
- _isNecessaryAutoScrollBrake: function()
- {
- if(this._autoScrollBraking)
- {
+ _isNecessaryAutoScrollBrake: function () {
+ if (this._autoScrollBraking) {
return true;
}
- if(this._isOutOfBoundary())
- {
+ if (this._isOutOfBoundary()) {
// It just went out of boundary.
- if(!this._autoScrollCurrentlyOutOfBoundary)
- {
+ if (!this._autoScrollCurrentlyOutOfBoundary) {
this._autoScrollCurrentlyOutOfBoundary = true;
this._autoScrollBraking = true;
this._autoScrollBrakingStartPosition = this.getInnerContainerPosition();
return true;
}
}
- else
- {
+ else {
this._autoScrollCurrentlyOutOfBoundary = false;
}
return false;
},
- _getAutoScrollStopEpsilon: function()
- {
+ _getAutoScrollStopEpsilon: function () {
return 0.0001;
},
- _fltEqualZero: function(point)
- {
- return (Math.abs(point.x) <= 0.0001 && Math.abs(point.y) <= 0.0001);
+ _fltEqualZero: function (point) {
+ return (Math.abs(point.x) <= 0.0001 && Math.abs(point.y) <= 0.0001);
},
- _processAutoScrolling: function(deltaTime)
- {
+ _processAutoScrolling: function (deltaTime) {
var OUT_OF_BOUNDARY_BREAKING_FACTOR = 0.05;
// Make auto scroll shorter if it needs to deaccelerate.
var brakingFactor = (this._isNecessaryAutoScrollBrake() ? OUT_OF_BOUNDARY_BREAKING_FACTOR : 1);
@@ -709,28 +718,24 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
// Calculate the progress percentage
var percentage = Math.min(1, this._autoScrollAccumulatedTime / this._autoScrollTotalTime);
- if(this._autoScrollAttenuate)
- {
+ if (this._autoScrollAttenuate) {
percentage -= 1;
percentage = percentage * percentage * percentage * percentage * percentage + 1;
}
// Calculate the new position
- var newPosition = cc.pAdd(this._autoScrollStartPosition, cc.pMult(this._autoScrollTargetDelta,percentage));
+ var newPosition = cc.pAdd(this._autoScrollStartPosition, cc.pMult(this._autoScrollTargetDelta, percentage));
var reachedEnd = Math.abs(percentage - 1) <= this._getAutoScrollStopEpsilon();
- if(this.bounceEnabled)
- {
+ if (this.bounceEnabled) {
// The new position is adjusted if out of boundary
newPosition = cc.pAdd(this._autoScrollBrakingStartPosition, cc.pMult(cc.pSub(newPosition, this._autoScrollBrakingStartPosition), brakingFactor));
}
- else
- {
+ else {
// Don't let go out of boundary
var moveDelta = cc.pSub(newPosition, this.getInnerContainerPosition());
var outOfBoundary = this._getHowMuchOutOfBoundary(moveDelta);
- if(!this._fltEqualZero(outOfBoundary))
- {
+ if (!this._fltEqualZero(outOfBoundary)) {
newPosition.x += outOfBoundary.x;
newPosition.y += outOfBoundary.y;
@@ -739,8 +744,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
}
// Finish auto scroll if it ended
- if(reachedEnd)
- {
+ if (reachedEnd) {
this._autoScrolling = false;
this._dispatchEvent(ccui.ScrollView.EVENT_AUTOSCROLL_ENDED);
}
@@ -748,10 +752,8 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
this._moveInnerContainer(cc.pSub(newPosition, this.getInnerContainerPosition()), reachedEnd);
},
- _jumpToDestination: function (desOrX, y)
- {
- if(desOrX.x === undefined)
- {
+ _jumpToDestination: function (desOrX, y) {
+ if (desOrX.x === undefined) {
desOrX = cc.p(desOrX, y);
}
@@ -759,19 +761,16 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
this._moveInnerContainer(cc.pSub(desOrX, this.getInnerContainerPosition()), true);
},
- _scrollChildren: function(deltaMove)
- {
+ _scrollChildren: function (deltaMove) {
var realMove = deltaMove;
- if(this.bounceEnabled)
- {
+ if (this.bounceEnabled) {
// If the position of the inner container is out of the boundary, the offsets should be divided by two.
var outOfBoundary = this._getHowMuchOutOfBoundary();
realMove.x *= (outOfBoundary.x == 0 ? 1 : 0.5);
realMove.y *= (outOfBoundary.y == 0 ? 1 : 0.5);
}
- if(!this.bounceEnabled)
- {
+ if (!this.bounceEnabled) {
var outOfBoundary = this._getHowMuchOutOfBoundary(realMove);
realMove.x += outOfBoundary.x;
realMove.y += outOfBoundary.y;
@@ -785,16 +784,14 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
if (realMove.y > 0.0) // up
{
var icBottomPos = this._innerContainer.getBottomBoundary();
- if (icBottomPos + realMove.y >= this._bottomBoundary)
- {
+ if (icBottomPos + realMove.y >= this._bottomBoundary) {
scrolledToBottom = true;
}
}
else if (realMove.y < 0.0) // down
{
var icTopPos = this._innerContainer.getTopBoundary();
- if (icTopPos + realMove.y <= this._topBoundary)
- {
+ if (icTopPos + realMove.y <= this._topBoundary) {
scrolledToTop = true;
}
}
@@ -802,39 +799,32 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
if (realMove.x < 0.0) // left
{
var icRightPos = this._innerContainer.getRightBoundary();
- if (icRightPos + realMove.x <= this._rightBoundary)
- {
+ if (icRightPos + realMove.x <= this._rightBoundary) {
scrolledToRight = true;
}
}
else if (realMove.x > 0.0) // right
{
var icLeftPos = this._innerContainer.getLeftBoundary();
- if (icLeftPos + realMove.x >= this._leftBoundary)
- {
+ if (icLeftPos + realMove.x >= this._leftBoundary) {
scrolledToLeft = true;
}
}
this._moveInnerContainer(realMove, false);
- if(realMove.x != 0 || realMove.y != 0)
- {
+ if (realMove.x != 0 || realMove.y != 0) {
this._processScrollingEvent();
}
- if(scrolledToBottom)
- {
+ if (scrolledToBottom) {
this._processScrollEvent(ccui.ScrollView.MOVEDIR_BOTTOM, false);
}
- if(scrolledToTop)
- {
+ if (scrolledToTop) {
this._processScrollEvent(ccui.ScrollView.MOVEDIR_TOP, false);
}
- if(scrolledToLeft)
- {
+ if (scrolledToLeft) {
this._processScrollEvent(ccui.ScrollView.MOVEDIR_LEFT, false);
}
- if(scrolledToRight)
- {
+ if (scrolledToRight) {
this._processScrollEvent(ccui.ScrollView.MOVEDIR_RIGHT, false);
}
},
@@ -902,7 +892,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
}
var inSize = this._innerContainer.getContentSize();
this._startAutoScrollToDestination(cc.p(this._contentSize.width - inSize.width,
- this._contentSize.height - inSize.height), time, attenuated);
+ this._contentSize.height - inSize.height), time, attenuated);
},
/**
@@ -1075,13 +1065,11 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
this._jumpToDestination(-(percent.x * w / 100), minY + percent.y * h / 100);
},
- _gatherTouchMove: function(delta)
- {
+ _gatherTouchMove: function (delta) {
var NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED = 5;
- while(this._touchMoveDisplacements.length >= NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED)
- {
- this._touchMoveDisplacements.splice(0,1);
- this._touchMoveTimeDeltas.splice(0,1)
+ while (this._touchMoveDisplacements.length >= NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED) {
+ this._touchMoveDisplacements.splice(0, 1);
+ this._touchMoveTimeDeltas.splice(0, 1)
}
this._touchMoveDisplacements.push(delta);
@@ -1131,11 +1119,9 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
this._bePressed = false;
var bounceBackStarted = this._startBounceBackIfNeeded();
- if(!bounceBackStarted && this.inertiaScrollEnabled)
- {
+ if (!bounceBackStarted && this.inertiaScrollEnabled) {
var touchMoveVelocity = this._calculateTouchMoveVelocity();
- if(touchMoveVelocity.x !== 0 || touchMoveVelocity.y !== 0)
- {
+ if (touchMoveVelocity.x !== 0 || touchMoveVelocity.y !== 0) {
this._startInertiaScroll(touchMoveVelocity);
}
}
@@ -1158,7 +1144,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
*/
onTouchBegan: function (touch, event) {
var pass = ccui.Layout.prototype.onTouchBegan.call(this, touch, event);
- if(!this._isInterceptTouch){
+ if (!this._isInterceptTouch) {
if (this._hit)
this._handlePressLogic(touch);
}
@@ -1172,7 +1158,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
*/
onTouchMoved: function (touch, event) {
ccui.Layout.prototype.onTouchMoved.call(this, touch, event);
- if(!this._isInterceptTouch)
+ if (!this._isInterceptTouch)
this._handleMoveLogic(touch);
},
@@ -1183,7 +1169,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
*/
onTouchEnded: function (touch, event) {
ccui.Layout.prototype.onTouchEnded.call(this, touch, event);
- if(!this._isInterceptTouch)
+ if (!this._isInterceptTouch)
this._handleReleaseLogic(touch);
this._isInterceptTouch = false;
},
@@ -1222,7 +1208,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
return;
}
- if(this._direction === ccui.ScrollView.DIR_NONE)
+ if (this._direction === ccui.ScrollView.DIR_NONE)
return;
var touchPoint = touch.getLocation();
@@ -1253,12 +1239,10 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
}
},
- _processScrollEvent: function(_directionEvent, bounce)
- {
+ _processScrollEvent: function (_directionEvent, bounce) {
var event = 0;
- switch(_directionEvent)
- {
+ switch (_directionEvent) {
case ccui.ScrollView.MOVEDIR_TOP:
event = (bounce ? ccui.ScrollView.EVENT_BOUNCE_TOP : ccui.ScrollView.EVENT_SCROLL_TO_TOP);
break;
@@ -1276,20 +1260,18 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
this._dispatchEvent(event);
},
- _processScrollingEvent: function()
- {
- this._dispatchEvent( ccui.ScrollView.EVENT_SCROLLING);
+ _processScrollingEvent: function () {
+ this._dispatchEvent(ccui.ScrollView.EVENT_SCROLLING);
},
- _dispatchEvent: function(event)
- {
- if(this._scrollViewEventSelector){
+ _dispatchEvent: function (event) {
+ if (this._scrollViewEventSelector) {
if (this._scrollViewEventListener)
this._scrollViewEventSelector.call(this._scrollViewEventListener, this, event);
else
this._scrollViewEventSelector(this, event);
}
- if(this._ccEventCallback)
+ if (this._ccEventCallback)
this._ccEventCallback(this, event);
},
@@ -1308,7 +1290,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
* Adds callback function called ScrollView event triggered
* @param {Function} selector
*/
- addEventListener: function(selector){
+ addEventListener: function (selector) {
this._ccEventCallback = selector;
},
@@ -1670,7 +1652,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
return "ScrollView";
},
- _createCloneInstance: function(){
+ _createCloneInstance: function () {
return new ccui.ScrollView();
},
@@ -1679,7 +1661,7 @@ ccui.ScrollView = ccui.Layout.extend(/** @lends ccui.ScrollView# */{
},
_copySpecialProperties: function (scrollView) {
- if(scrollView instanceof ccui.ScrollView) {
+ if (scrollView instanceof ccui.ScrollView) {
ccui.Layout.prototype._copySpecialProperties.call(this, scrollView);
this.setInnerContainerSize(scrollView.getInnerContainerSize());
this.setInnerContainerPosition(scrollView.getInnerContainerPosition());
diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewBar.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewBar.js
index ab425afcc6..4e9c1840a7 100644
--- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewBar.js
+++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewBar.js
@@ -41,16 +41,16 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
_lowerHalfCircle: null,
_body: null,
- _opacity : 255,
+ _opacity: 255,
- _marginFromBoundary : 0,
+ _marginFromBoundary: 0,
_marginForLength: 0,
_touching: false,
_autoHideEnabled: true,
- autoHideTime : 0,
- _autoHideRemainingTime : 0,
+ autoHideTime: 0,
+ _autoHideRemainingTime: 0,
_className: "ScrollViewBar",
/**
@@ -62,7 +62,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
ctor: function (parent, direction) {
cc.ProtectedNode.prototype.ctor.call(this);
this._direction = direction;
- this._parentScroll = parent;
+ this._parentScroll = parent;
this._marginFromBoundary = ccui.ScrollViewBar.DEFAULT_MARGIN;
this._marginForLength = ccui.ScrollViewBar.DEFAULT_MARGIN;
@@ -91,7 +91,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
this.addProtectedChild(this._upperHalfCircle);
this.addProtectedChild(this._lowerHalfCircle);
- this._body = ccui.helper._createSpriteFromBase64(ccui.ScrollViewBar.BODY_IMAGE_1_PIXEL_HEIGHT, ccui.ScrollViewBar.BODY_IMAGE_1_PIXEL_HEIGHT_KEY);
+ this._body = ccui.helper._createSpriteFromBase64(ccui.ScrollViewBar.BODY_IMAGE_1_PIXEL_HEIGHT, ccui.ScrollViewBar.BODY_IMAGE_1_PIXEL_HEIGHT_KEY);
this._body.setAnchorPoint(cc.p(0.5, 0));
this.addProtectedChild(this._body);
@@ -100,8 +100,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
cc.ProtectedNode.prototype.setOpacity.call(this, 0);
this._autoHideRemainingTime = 0;
- if(this._direction === ccui.ScrollView.DIR_HORIZONTAL)
- {
+ if (this._direction === ccui.ScrollView.DIR_HORIZONTAL) {
this.setRotation(90);
}
},
@@ -110,22 +109,18 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
* Set the scroll bar position from the left-bottom corner (horizontal) or right-top corner (vertical).
* @param {cc.Point} positionFromCorner The position from the left-bottom corner (horizontal) or right-top corner (vertical).
*/
- setPositionFromCorner: function(positionFromCorner)
- {
- if(this._direction === ccui.ScrollView.DIR_VERTICAL)
- {
+ setPositionFromCorner: function (positionFromCorner) {
+ if (this._direction === ccui.ScrollView.DIR_VERTICAL) {
this._marginForLength = positionFromCorner.y;
this._marginFromBoundary = positionFromCorner.x;
}
- else
- {
+ else {
this._marginForLength = positionFromCorner.x;
this._marginFromBoundary = positionFromCorner.y;
}
},
- onEnter: function()
- {
+ onEnter: function () {
cc.ProtectedNode.prototype.onEnter.call(this);
this.scheduleUpdate();
},
@@ -134,14 +129,11 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
* Get the scroll bar position from the left-bottom corner (horizontal) or right-top corner (vertical).
* @returns {cc.Point}
*/
- getPositionFromCorner: function()
- {
- if(this._direction === ccui.ScrollView.DIR_VERTICAL)
- {
+ getPositionFromCorner: function () {
+ if (this._direction === ccui.ScrollView.DIR_VERTICAL) {
return cc.p(this._marginFromBoundary, this._marginForLength);
}
- else
- {
+ else {
return cc.p(this._marginForLength, this._marginFromBoundary);
}
},
@@ -149,8 +141,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
* Set the scroll bar's width
* @param {number} width The scroll bar's width
*/
- setWidth: function(width)
- {
+ setWidth: function (width) {
var scale = width / this._body.width;
this._body.setScaleX(scale);
this._upperHalfCircle.setScale(scale);
@@ -161,8 +152,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
* Get the scroll bar's width
* @returns {number} the scroll bar's width
*/
- getWidth: function()
- {
+ getWidth: function () {
return this._body.getBoundingBox().width;
},
@@ -170,11 +160,10 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
* Set scroll bar auto hide state
* @param {boolean} autoHideEnabled scroll bar auto hide state
*/
- setAutoHideEnabled: function(autoHideEnabled)
- {
+ setAutoHideEnabled: function (autoHideEnabled) {
this._autoHideEnabled = autoHideEnabled;
- if(!this._autoHideEnabled && !this._touching && this._autoHideRemainingTime <= 0)
+ if (!this._autoHideEnabled && !this._touching && this._autoHideRemainingTime <= 0)
cc.ProtectedNode.prototype.setOpacity.call(this, this.opacity);
else
cc.ProtectedNode.prototype.setOpacity.call(this, 0);
@@ -183,8 +172,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
* Query scroll bar auto hide state
* @returns {boolean} True if scroll bar auto hide is enabled, false otherwise.
*/
- isAutoHideEnabled: function()
- {
+ isAutoHideEnabled: function () {
return this._autoHideEnabled;
},
@@ -192,8 +180,7 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
* Set scroll bar opacity
* @param {number} opacity scroll bar opacity
*/
- setOpacity: function(opacity)
- {
+ setOpacity: function (opacity) {
this._opacity = opacity;
},
@@ -201,51 +188,42 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
* Get scroll bar opacity
* @returns {number}
*/
- getOpacity: function()
- {
+ getOpacity: function () {
return this._opacity;
},
- _updateLength: function(length)
- {
+ _updateLength: function (length) {
var ratio = length / this._body.getTextureRect().height;
this._body.setScaleY(ratio);
this._upperHalfCircle.setPositionY(this._body.getPositionY() + length);
},
- _processAutoHide: function(dt)
- {
- if(!this._autoHideEnabled || this._autoHideRemainingTime <= 0)
- {
+ _processAutoHide: function (dt) {
+ if (!this._autoHideEnabled || this._autoHideRemainingTime <= 0) {
return;
}
- else if(this._touching)
- {
+ else if (this._touching) {
// If it is touching, don't auto hide.
return;
}
this._autoHideRemainingTime -= dt;
- if(this._autoHideRemainingTime <= this.autoHideTime)
- {
- this. _autoHideRemainingTime = Math.max(0, this._autoHideRemainingTime);
+ if (this._autoHideRemainingTime <= this.autoHideTime) {
+ this._autoHideRemainingTime = Math.max(0, this._autoHideRemainingTime);
cc.ProtectedNode.prototype.setOpacity.call(this, this._opacity * (this._autoHideRemainingTime / this.autoHideTime));
}
},
- update: function(dt)
- {
+ update: function (dt) {
this._processAutoHide(dt);
},
/**
* This is called by parent ScrollView when a touch is began. Don't call this directly.
*/
- onTouchBegan: function()
- {
- if(!this._autoHideEnabled)
- {
+ onTouchBegan: function () {
+ if (!this._autoHideEnabled) {
return;
}
this._touching = true;
@@ -254,16 +232,13 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
/**
* This is called by parent ScrollView when a touch is ended. Don't call this directly.
*/
- onTouchEnded: function()
- {
- if(!this._autoHideEnabled)
- {
+ onTouchEnded: function () {
+ if (!this._autoHideEnabled) {
return;
}
this._touching = false;
- if(this._autoHideRemainingTime <= 0)
- {
+ if (this._autoHideRemainingTime <= 0) {
// If the remaining time is 0, it means that it didn't moved after touch started so scroll bar is not showing.
return;
}
@@ -275,10 +250,8 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
*
* @param {cc.Point} outOfBoundary amount how much the inner container of ScrollView is out of boundary
*/
- onScrolled: function(outOfBoundary)
- {
- if(this._autoHideEnabled)
- {
+ onScrolled: function (outOfBoundary) {
+ if (this._autoHideEnabled) {
this._autoHideRemainingTime = this.autoHideTime;
cc.ProtectedNode.prototype.setOpacity.call(this, this.opacity);
}
@@ -290,15 +263,13 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
var outOfBoundaryValue = 0;
var innerContainerPosition = 0;
- if(this._direction === ccui.ScrollView.DIR_VERTICAL)
- {
+ if (this._direction === ccui.ScrollView.DIR_VERTICAL) {
innerContainerMeasure = innerContainer.height;
scrollViewMeasure = this._parentScroll.height;
outOfBoundaryValue = outOfBoundary.y;
innerContainerPosition = -innerContainer.getPositionY();
}
- else if(this._direction === ccui.ScrollView.DIR_HORIZONTAL)
- {
+ else if (this._direction === ccui.ScrollView.DIR_HORIZONTAL) {
innerContainerMeasure = innerContainer.width;
scrollViewMeasure = this._parentScroll.width;
outOfBoundaryValue = outOfBoundary.x;
@@ -311,11 +282,9 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
this.setPosition(position);
},
- _calculateLength: function(innerContainerMeasure, scrollViewMeasure, outOfBoundaryValue)
- {
+ _calculateLength: function (innerContainerMeasure, scrollViewMeasure, outOfBoundaryValue) {
var denominatorValue = innerContainerMeasure;
- if(outOfBoundaryValue !== 0)
- {
+ if (outOfBoundaryValue !== 0) {
// If it is out of boundary, the length of scroll bar gets shorter quickly.
var GETTING_SHORTER_FACTOR = 20;
denominatorValue += (outOfBoundaryValue > 0 ? outOfBoundaryValue : -outOfBoundaryValue) * GETTING_SHORTER_FACTOR;
@@ -325,18 +294,15 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
return Math.abs(scrollViewMeasure - 2 * this._marginForLength) * lengthRatio;
},
- _calculatePosition: function(innerContainerMeasure, scrollViewMeasure, innerContainerPosition, outOfBoundaryValue, length)
- {
+ _calculatePosition: function (innerContainerMeasure, scrollViewMeasure, innerContainerPosition, outOfBoundaryValue, length) {
var denominatorValue = innerContainerMeasure - scrollViewMeasure;
- if(outOfBoundaryValue !== 0)
- {
+ if (outOfBoundaryValue !== 0) {
denominatorValue += Math.abs(outOfBoundaryValue);
}
var positionRatio = 0;
- if(denominatorValue !== 0)
- {
+ if (denominatorValue !== 0) {
positionRatio = innerContainerPosition / denominatorValue;
positionRatio = Math.max(positionRatio, 0);
positionRatio = Math.min(positionRatio, 1);
@@ -344,12 +310,10 @@ ccui.ScrollViewBar = ccui.ProtectedNode.extend(/** @lends ccui.ScrollViewBar# */
var position = (scrollViewMeasure - length - 2 * this._marginForLength) * positionRatio + this._marginForLength;
- if(this._direction === ccui.ScrollView.DIR_VERTICAL)
- {
+ if (this._direction === ccui.ScrollView.DIR_VERTICAL) {
return cc.p(this._parentScroll.width - this._marginFromBoundary, position);
}
- else
- {
+ else {
return cc.p(position, this._marginFromBoundary);
}
}
diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js
index a96de5790a..4607932e9d 100644
--- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js
+++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewCanvasRenderCmd.js
@@ -1,8 +1,8 @@
-(function(){
- if(!ccui.ProtectedNode.CanvasRenderCmd)
+(function () {
+ if (!ccui.ProtectedNode.CanvasRenderCmd)
return;
- ccui.ScrollView.CanvasRenderCmd = function(renderable){
- ccui.Layout.CanvasRenderCmd.call(this, renderable);
+ ccui.ScrollView.CanvasRenderCmd = function (renderable) {
+ this._layoutCmdCtor(renderable);
//this._needDraw = true;
this._dirty = false;
};
@@ -10,24 +10,9 @@
var proto = ccui.ScrollView.CanvasRenderCmd.prototype = Object.create(ccui.Layout.CanvasRenderCmd.prototype);
proto.constructor = ccui.ScrollView.CanvasRenderCmd;
- proto.visit = function(parentCmd) {
- var node = this._node;
- if (!node._visible)
- return;
- var currentID = node.__instanceId;
-
- cc.renderer.pushRenderCommand(this);
- //cc.renderer._turnToCacheMode(currentID);
-
- this.layoutVisit(parentCmd);
-
- this._dirtyFlag = 0;
- //cc.renderer._turnToNormalMode();
- };
-
proto.rendering = function (ctx) {
var currentID = this._node.__instanceId;
- var locCmds = cc.renderer._cacheToCanvasCmds[currentID], i, len,
+ var i, locCmds = cc.renderer._cacheToCanvasCmds[currentID], len,
scaleX = cc.view.getScaleX(),
scaleY = cc.view.getScaleY();
var context = ctx || cc._renderContext;
@@ -37,9 +22,9 @@
for (i = 0, len = locCmds.length; i < len; i++) {
var checkNode = locCmds[i]._node;
- if(checkNode instanceof ccui.ScrollView)
+ if (checkNode instanceof ccui.ScrollView)
continue;
- if(checkNode && checkNode._parent && checkNode._parent._inViewRect === false)
+ if (checkNode && checkNode._parent && checkNode._parent._inViewRect === false)
continue;
locCmds[i].rendering(context, scaleX, scaleY);
}
diff --git a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js
index 413d23aff0..97ba7ff66b 100644
--- a/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js
+++ b/extensions/ccui/uiwidgets/scroll-widget/UIScrollViewWebGLRenderCmd.js
@@ -1,9 +1,8 @@
-
-(function(){
- if(!ccui.ProtectedNode.WebGLRenderCmd)
+(function () {
+ if (!ccui.ProtectedNode.WebGLRenderCmd)
return;
- ccui.ScrollView.WebGLRenderCmd = function(renderable){
- ccui.Layout.WebGLRenderCmd.call(this, renderable);
+ ccui.ScrollView.WebGLRenderCmd = function (renderable) {
+ this._layoutCmdCtor(renderable);
this._needDraw = true;
this._dirty = false;
};
@@ -11,24 +10,7 @@
var proto = ccui.ScrollView.WebGLRenderCmd.prototype = Object.create(ccui.Layout.WebGLRenderCmd.prototype);
proto.constructor = ccui.ScrollView.WebGLRenderCmd;
- proto.visit = function(parentCmd) {
- var node = this._node;
- if (!node._visible)
- return;
- var currentID = this._node.__instanceId;
-
- cc.renderer.pushRenderCommand(this);
- cc.renderer._turnToCacheMode(currentID);
-
- this.layoutVisit(parentCmd);
- // Need to update children after do layout
- node.updateChildren();
-
- this._dirtyFlag = 0;
- cc.renderer._turnToNormalMode();
- };
-
- proto.rendering = function(ctx){
+ proto.rendering = function (ctx) {
var currentID = this._node.__instanceId,
locCmds = cc.renderer._cacheToBufferCmds[currentID],
i, len, checkNode, cmd,
@@ -45,9 +27,7 @@
for (i = 0, len = locCmds.length; i < len; i++) {
cmd = locCmds[i];
checkNode = cmd._node;
- if(checkNode instanceof ccui.ScrollView)
- continue;
- if(checkNode && checkNode._parent && checkNode._parent._inViewRect === false)
+ if (checkNode && checkNode._parent && checkNode._parent._inViewRect === false)
continue;
if (cmd.uploadData) {
diff --git a/extensions/cocostudio/action/CCActionManager.js b/extensions/cocostudio/action/CCActionManager.js
index 434fb83327..0a5dc68b9f 100644
--- a/extensions/cocostudio/action/CCActionManager.js
+++ b/extensions/cocostudio/action/CCActionManager.js
@@ -84,8 +84,8 @@ ccs.actionManager = /** @lends ccs.actionManager# */{
if (action)
action.play(fun);
},
-
- /**
+
+ /**
* Stop an Action with a name.
* @param {String} jsonName
* @param {String} actionName
@@ -103,10 +103,10 @@ ccs.actionManager = /** @lends ccs.actionManager# */{
this._actionDic = {};
},
- /**
- * Clear data: Release all actions.
- */
- clear: function() {
- this._actionDic = {};
- }
+ /**
+ * Clear data: Release all actions.
+ */
+ clear: function () {
+ this._actionDic = {};
+ }
};
diff --git a/extensions/cocostudio/action/CCActionNode.js b/extensions/cocostudio/action/CCActionNode.js
index 199c7d110f..d029830088 100644
--- a/extensions/cocostudio/action/CCActionNode.js
+++ b/extensions/cocostudio/action/CCActionNode.js
@@ -72,12 +72,12 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{
var actionFrameDic = actionFrameList[i];
var frameIndex = actionFrameDic["frameid"];
var frameTweenType = actionFrameDic["tweenType"];
- if(frameTweenType == null)
+ if (frameTweenType == null)
frameTweenType = 0;
var frameTweenParameterNum = actionFrameDic["tweenParameter"];
var frameTweenParameter = [];
- for (var j = 0; j < frameTweenParameterNum; j++){
+ for (var j = 0; j < frameTweenParameterNum; j++) {
var value = actionFrameDic["tweenParameter"][j];
frameTweenParameter.push(value);
}
@@ -86,7 +86,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{
if (actionFrameDic["positionx"] !== undefined) {
var positionX = actionFrameDic["positionx"];
var positionY = actionFrameDic["positiony"];
- if(positionOffset && node.parent){
+ if (positionOffset && node.parent) {
var AnchorPointIn = node.parent.getAnchorPointInPoints();
positionX += AnchorPointIn.x;
positionY += AnchorPointIn.y;
@@ -249,7 +249,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{
* @param {ccs.ActionFrame} frame
*/
deleteFrame: function (frame) {
- if (frame == null)
+ if (frame === undefined)
return;
var frameType = frame.frameType;
var array = this._frameArray[frameType];
@@ -265,7 +265,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{
},
_refreshActionProperty: function () {
- if (this._object === null)
+ if (!this._object)
return null;
var locSpawnArray = [];
for (var i = 0; i < this._frameArrayNum; i++) {
@@ -284,10 +284,10 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{
else {
locAction = locFrame.getAction(0);
}
- if(locAction)
+ if (locAction)
locSequenceArray.push(locAction);
}
- if(locSequenceArray){
+ if (locSequenceArray) {
var locSequence = cc.sequence(locSequenceArray);
if (locSequence !== null)
locSpawnArray.push(locSequence);
@@ -304,9 +304,9 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{
* @param {cc.CallFunc} fun
*/
playAction: function (fun) {
- if (this._object === null || this._actionSpawn === null)
+ if (!this._object || !this._actionSpawn)
return;
- if(fun)
+ if (fun)
this._action = cc.sequence(this._actionSpawn, fun);
else
this._action = cc.sequence(this._actionSpawn);
@@ -325,7 +325,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{
stopAction: function () {
var node = this.getActionNode();
if (node !== null && this._action !== null) {
- if(!this._action.isDone())
+ if (!this._action.isDone())
node.stopAction(this._action);
}
},
@@ -356,7 +356,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{
*/
getLastFrameIndex: function () {
var locFrameindex = -1;
- var locIsFindFrame = false ,locFrameArray = this._frameArray;
+ var locIsFindFrame = false, locFrameArray = this._frameArray;
for (var i = 0, len = this._frameArrayNum; i < len; i++) {
var locArray = locFrameArray[i];
if (locArray.length <= 0)
@@ -381,7 +381,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{
var locUnitTime = this.getUnitTime();
for (var i = 0; i < this._frameArrayNum; i++) {
var locArray = this._frameArray[i];
- if (locArray === null)
+ if (!locArray)
continue;
for (var j = 0; j < locArray.length; j++) {
@@ -423,7 +423,7 @@ ccs.ActionNode = ccs.Class.extend(/** @lends ccs.ActionNode# */{
* @returns {Boolean} that if the action is done once time
*/
isActionDoneOnce: function () {
- if (this._action === null)
+ if (!this._action)
return true;
return this._action.isDone();
}
diff --git a/extensions/cocostudio/armature/CCArmature.js b/extensions/cocostudio/armature/CCArmature.js
index 2f03c1710e..3836c34afd 100644
--- a/extensions/cocostudio/armature/CCArmature.js
+++ b/extensions/cocostudio/armature/CCArmature.js
@@ -41,7 +41,6 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{
animation: null,
armatureData: null,
batchNode: null,
- _textureAtlas: null,
_parentBone: null,
_boneDic: null,
_topBoneList: null,
@@ -70,6 +69,8 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{
this._armatureTransformDirty = true;
this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST};
name && ccs.Armature.prototype.init.call(this, name, parentBone);
+ // Hack way to avoid RendererWebGL from skipping Armature
+ this._texture = {};
},
/**
@@ -79,7 +80,6 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{
* @return {Boolean}
*/
init: function (name, parentBone) {
- cc.Node.prototype.init.call(this);
if (parentBone)
this._parentBone = parentBone;
this.removeAllChildren();
@@ -150,8 +150,21 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{
return true;
},
+ visit: function (parent) {
+ var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null;
+
+ // quick return if not visible
+ if (!this._visible) {
+ cmd._propagateFlagsDown(parentCmd);
+ return;
+ }
+
+ cmd.visit(parentCmd);
+ cmd._dirtyFlag = 0;
+ },
+
addChild: function (child, localZOrder, tag) {
- if(child instanceof ccui.Widget){
+ if (child instanceof ccui.Widget) {
cc.log("Armature doesn't support to add Widget as its child, it will be fix soon.");
return;
}
@@ -194,7 +207,7 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{
addBone: function (bone, parentName) {
cc.assert(bone, "Argument must be non-nil");
var locBoneDic = this._boneDic;
- if(bone.getName())
+ if (bone.getName())
cc.assert(!locBoneDic[bone.getName()], "bone already added. It can't be added again");
if (parentName) {
@@ -282,7 +295,7 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{
this.setAnchorPoint(locOffsetPoint.x / rect.width, locOffsetPoint.y / rect.height);
},
- getOffsetPoints: function(){
+ getOffsetPoints: function () {
return {x: this._offsetPoint.x, y: this._offsetPoint.y};
},
@@ -345,21 +358,21 @@ ccs.Armature = ccs.Node.extend(/** @lends ccs.Armature# */{
* This boundingBox will calculate all bones' boundingBox every time
* @returns {cc.Rect}
*/
- getBoundingBox: function(){
+ getBoundingBox: function () {
var minX, minY, maxX, maxY = 0;
var first = true;
var boundingBox = cc.rect(0, 0, 0, 0), locChildren = this._children;
var len = locChildren.length;
- for (var i=0; i= ccs.CONST_VERSION_COMBINED){
+ if (this._dataVersion >= ccs.CONST_VERSION_COMBINED) {
ccs.TransformHelp.nodeConcat(locTweenData, this._boneData);
locTweenData.scaleX -= 1;
locTweenData.scaleY -= 1;
@@ -182,7 +182,7 @@ ccs.Bone = ccs.Node.extend(/** @lends ccs.Bone# */{
locWorldInfo.skewX = locTweenData.skewX + this._skewX + cc.degreesToRadians(this._rotationX);
locWorldInfo.skewY = locTweenData.skewY + this._skewY - cc.degreesToRadians(this._rotationY);
- if(this._parentBone)
+ if (this._parentBone)
this._applyParentTransform(this._parentBone);
else {
if (this._armatureParentBone)
@@ -195,7 +195,7 @@ ccs.Bone = ccs.Node.extend(/** @lends ccs.Bone# */{
}
ccs.displayFactory.updateDisplay(this, delta, this._boneTransformDirty || this._armature.getArmatureTransformDirty());
- for(var i=0; i 0 && this._children.getIndex(bone) !== -1 ) {
- if(recursion) {
+ if (this._children.length > 0 && this._children.getIndex(bone) !== -1) {
+ if (recursion) {
var ccbones = bone._children;
- for(var i=0; i= 0) && (index < locDisplayList.length) )
+ if ((index >= 0) && (index < locDisplayList.length))
decoDisplay = locDisplayList[index];
- else{
+ else {
decoDisplay = new ccs.DecorativeDisplay();
locDisplayList.push(decoDisplay);
}
- if(display instanceof ccs.DisplayData){
+ if (display instanceof ccs.DisplayData) {
ccs.displayFactory.addDisplay(this._bone, decoDisplay, display);
//! if changed display index is current display index, then change current display to the new display
- if(index === this._displayIndex) {
+ if (index === this._displayIndex) {
this._displayIndex = -1;
this.changeDisplayWithIndex(index, false);
}
@@ -117,14 +117,14 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
if (!find)
display.setSkinData(new ccs.BaseData());
}
- } else if (display instanceof cc.ParticleSystem){
+ } else if (display instanceof cc.ParticleSystem) {
displayData = new ccs.ParticleDisplayData();
display.removeFromParent();
- display.cleanup();
+ display._performRecursive(cc.Node._stateCallbackType.cleanup);
var armature = this._bone.getArmature();
if (armature)
display.setParent(armature);
- } else if(display instanceof ccs.Armature) {
+ } else if (display instanceof ccs.Armature) {
displayData = new ccs.ArmatureDisplayData();
displayData.displayName = display.getName();
display.setParentBone(this._bone);
@@ -134,15 +134,15 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
decoDisplay.setDisplayData(displayData);
//! if changed display index is current display index, then change current display to the new display
- if(index === this._displayIndex) {
+ if (index === this._displayIndex) {
this._displayIndex = -1;
this.changeDisplayWithIndex(index, false);
}
},
- _addDisplayOther:function(decoDisplay,display){
+ _addDisplayOther: function (decoDisplay, display) {
var displayData = null;
- if (display instanceof ccs.Skin){
+ if (display instanceof ccs.Skin) {
var skin = display;
skin.setBone(this._bone);
displayData = new ccs.SpriteDisplayData();
@@ -151,7 +151,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
var spriteDisplayData = decoDisplay.getDisplayData();
if (spriteDisplayData instanceof ccs.SpriteDisplayData)
skin.setSkinData(spriteDisplayData.skinData);
- else{
+ else {
var find = false;
for (var i = this._decoDisplayList.length - 2; i >= 0; i--) {
var dd = this._decoDisplayList[i];
@@ -170,16 +170,16 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
}
}
- else if (display instanceof cc.ParticleSystem){
+ else if (display instanceof cc.ParticleSystem) {
displayData = new ccs.ParticleDisplayData();
displayData.displayName = display._plistFile;
}
- else if (display instanceof ccs.Armature){
+ else if (display instanceof ccs.Armature) {
displayData = new ccs.ArmatureDisplayData();
displayData.displayName = display.getName();
display.setParentBone(this._bone);
}
- else {
+ else {
displayData = new ccs.DisplayData();
}
decoDisplay.setDisplay(display);
@@ -190,7 +190,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
* Removes display node from list.
* @param {Number} index
*/
- removeDisplay:function (index) {
+ removeDisplay: function (index) {
this._decoDisplayList.splice(index, 1);
if (index === this._displayIndex) {
this.setCurrentDecorativeDisplay(null);
@@ -202,7 +202,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
* Returns the display node list.
* @returns {Array}
*/
- getDecorativeDisplayList:function(){
+ getDecorativeDisplayList: function () {
return this._decoDisplayList;
},
@@ -215,7 +215,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
* @param {Number} index The index of the display you want to change
* @param {Boolean} force If true, then force change display to specified display, or current display will set to display index edit in the flash every key frame.
*/
- changeDisplayWithIndex:function (index, force) {
+ changeDisplayWithIndex: function (index, force) {
if (index >= this._decoDisplayList.length) {
cc.log("the index value is out of range");
return;
@@ -230,7 +230,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
//! If displayIndex < 0, it means you want to hide you display
if (index < 0) {
- if(this._displayRenderNode) {
+ if (this._displayRenderNode) {
this._displayRenderNode.removeFromParent(true);
this.setCurrentDecorativeDisplay(null);
}
@@ -258,7 +258,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
* Sets current decorative display.
* @param {ccs.DecorativeDisplay} decoDisplay
*/
- setCurrentDecorativeDisplay:function (decoDisplay) {
+ setCurrentDecorativeDisplay: function (decoDisplay) {
var locCurrentDecoDisplay = this._currentDecoDisplay;
if (ccs.ENABLE_PHYSICS_CHIPMUNK_DETECT || ccs.ENABLE_PHYSICS_SAVE_CALCULATED_VERTEX) {
if (locCurrentDecoDisplay && locCurrentDecoDisplay.getColliderDetector())
@@ -299,7 +299,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
this._displayRenderNode.setVisible(this._visible);
this._displayType = this._currentDecoDisplay.getDisplayData().displayType;
- }else
+ } else
this._displayType = ccs.DISPLAY_TYPE_MAX;
@@ -310,7 +310,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
* Returns the current display render node.
* @returns {cc.Node}
*/
- getDisplayRenderNode:function () {
+ getDisplayRenderNode: function () {
return this._displayRenderNode;
},
@@ -318,7 +318,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
* Returns the type of display render node.
* @returns {Number}
*/
- getDisplayRenderNodeType:function(){
+ getDisplayRenderNodeType: function () {
return this._displayType;
},
@@ -326,7 +326,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
* Returns the index of display render node.
* @returns {Number}
*/
- getCurrentDisplayIndex:function () {
+ getCurrentDisplayIndex: function () {
return this._displayIndex;
},
@@ -334,7 +334,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
* Returns the current decorative display
* @returns {ccs.DecorativeDisplay}
*/
- getCurrentDecorativeDisplay:function () {
+ getCurrentDecorativeDisplay: function () {
return this._currentDecoDisplay;
},
@@ -343,7 +343,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
* @param index
* @returns {ccs.DecorativeDisplay}
*/
- getDecorativeDisplayByIndex:function (index) {
+ getDecorativeDisplayByIndex: function (index) {
return this._decoDisplayList[index];
},
@@ -355,7 +355,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
*
* @param {ccs.BoneData} boneData
*/
- initDisplayList:function (boneData) {
+ initDisplayList: function (boneData) {
this._decoDisplayList.length = 0;
if (!boneData)
return;
@@ -382,7 +382,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
if (y !== undefined)
point = cc.p(point, y);
- if(this._currentDecoDisplay.getDisplayData().displayType === ccs.DISPLAY_TYPE_SPRITE){
+ if (this._currentDecoDisplay.getDisplayData().displayType === ccs.DISPLAY_TYPE_SPRITE) {
/*
* First we first check if the point is in the sprite content rect. If false, then we continue to check
* the contour point. If this step is also false, then we can say the bone not contain this point.
@@ -402,7 +402,7 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
*
* @param {boolean} visible
*/
- setVisible:function (visible) {
+ setVisible: function (visible) {
if (!this._displayRenderNode)
return;
this._visible = visible;
@@ -413,39 +413,39 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
* Determines if the display is visible
* @returns {boolean} true if the node is visible, false if the node is hidden.
*/
- isVisible:function () {
+ isVisible: function () {
return this._visible;
},
- getContentSize:function () {
+ getContentSize: function () {
if (!this._displayRenderNode)
return cc.size(0, 0);
return this._displayRenderNode.getContentSize();
},
- getBoundingBox:function () {
+ getBoundingBox: function () {
if (!this._displayRenderNode)
return cc.rect(0, 0, 0, 0);
return this._displayRenderNode.getBoundingBox();
},
- getAnchorPoint:function () {
+ getAnchorPoint: function () {
if (!this._displayRenderNode)
- return cc.p(0, 0);
+ return cc.p(0, 0);
return this._displayRenderNode.getAnchorPoint();
},
- getAnchorPointInPoints:function () {
+ getAnchorPointInPoints: function () {
if (!this._displayRenderNode)
- return cc.p(0, 0);
+ return cc.p(0, 0);
return this._displayRenderNode.getAnchorPointInPoints();
},
- getForceChangeDisplay:function () {
+ getForceChangeDisplay: function () {
return this._forceChangeDisplay;
},
- release:function () {
+ release: function () {
this._decoDisplayList = null;
if (this._displayRenderNode) {
this._displayRenderNode.removeFromParent(true);
@@ -462,4 +462,4 @@ ccs.DisplayManager = ccs.Class.extend(/** @lends ccs.DisplayManager */{
*/
ccs.DisplayManager.create = function (bone) {
return new ccs.DisplayManager(bone);
-};
\ No newline at end of file
+};
diff --git a/extensions/cocostudio/armature/display/CCSkinRenderCmd.js b/extensions/cocostudio/armature/display/CCSkinRenderCmd.js
index a57b625494..eabcd02f00 100644
--- a/extensions/cocostudio/armature/display/CCSkinRenderCmd.js
+++ b/extensions/cocostudio/armature/display/CCSkinRenderCmd.js
@@ -23,10 +23,15 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
+(function () {
ccs.Skin.RenderCmd = {
_realWorldTM: null,
transform: function (parentCmd, recursive) {
+ if (!this._transform) {
+ this._transform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0};
+ this._worldTransform = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0};
+ }
+
var node = this._node,
pt = parentCmd ? parentCmd._worldTransform : null,
t = this._transform,
@@ -35,15 +40,15 @@
if (dirty || pt) {
this.originTransform();
- cc.affineTransformConcatIn(t, node.bone.getNodeToArmatureTransform());
- this._dirtyFlag = this._dirtyFlag & cc.Node._dirtyFlags.transformDirty ^ this._dirtyFlag;
+ cc.affineTransformConcatIn(this._transform, node.bone.getNodeToArmatureTransform());
+ this._dirtyFlag &= ~cc.Node._dirtyFlags.transformDirty;
}
if (pt) {
- wt.a = t.a * pt.a + t.b * pt.c;
- wt.b = t.a * pt.b + t.b * pt.d;
- wt.c = t.c * pt.a + t.d * pt.c;
- wt.d = t.c * pt.b + t.d * pt.d;
+ wt.a = t.a * pt.a + t.b * pt.c;
+ wt.b = t.a * pt.b + t.b * pt.d;
+ wt.c = t.c * pt.a + t.d * pt.c;
+ wt.d = t.c * pt.b + t.d * pt.d;
wt.tx = t.tx * pt.a + t.ty * pt.c + pt.tx;
wt.ty = t.tx * pt.b + t.ty * pt.d + pt.ty;
@@ -63,16 +68,16 @@
}
}
else {
- wt.a = t.a;
- wt.b = t.b;
- wt.c = t.c;
- wt.d = t.d;
+ wt.a = t.a;
+ wt.b = t.b;
+ wt.c = t.c;
+ wt.d = t.d;
wt.tx = t.tx;
wt.ty = t.ty;
}
var rwtm = this._realWorldTM;
- if(rwtm) {
- rwtm.a = t.a; rwtm.b = t.b; rwtm.c = t.c; rwtm.d = t.d; rwtm.tx= t.tx; rwtm.ty = t.ty;
+ if (rwtm) {
+ rwtm.a = t.a; rwtm.b = t.b; rwtm.c = t.c; rwtm.d = t.d; rwtm.tx = t.tx; rwtm.ty = t.ty;
cc.affineTransformConcatIn(rwtm, this._node.bone.getArmature()._renderCmd._worldTransform);
}
},
@@ -90,8 +95,8 @@
}
};
- ccs.Skin.CanvasRenderCmd = function(renderable){
- cc.Sprite.CanvasRenderCmd.call(this, renderable);
+ ccs.Skin.CanvasRenderCmd = function (renderable) {
+ this._spriteCmdCtor(renderable);
this._realWorldTM = {a: 1, b: 0, c: 0, d: 1, tx: 0, ty: 0};
};
@@ -111,8 +116,8 @@
this._currentRegion.updateRegion(this.getLocalBB(), this._realWorldTM);
};
- ccs.Skin.WebGLRenderCmd = function(renderable){
- cc.Sprite.WebGLRenderCmd.call(this, renderable);
+ ccs.Skin.WebGLRenderCmd = function (renderable) {
+ this._spriteCmdCtor(renderable);
};
proto = ccs.Skin.WebGLRenderCmd.prototype = Object.create(cc.Sprite.WebGLRenderCmd.prototype);
diff --git a/extensions/cocostudio/loader/load.js b/extensions/cocostudio/loader/load.js
index 46ac7eab01..bf75cce354 100644
--- a/extensions/cocostudio/loader/load.js
+++ b/extensions/cocostudio/loader/load.js
@@ -22,7 +22,7 @@
THE SOFTWARE.
****************************************************************************/
-ccs._load = (function(){
+ccs._load = (function () {
/**
* load file
@@ -31,43 +31,43 @@ ccs._load = (function(){
* @param {String} [path=] - Resource search path
* @returns {*}
*/
- var load = function(file, type, path){
+ var load = function (file, type, path) {
var json = cc.loader.getRes(file);
- if(!json)
+ if (!json)
return cc.log("%s does not exist", file);
var ext = extname(file).toLocaleLowerCase();
- if(ext !== "json" && ext !== "exportjson")
+ if (ext !== "json" && ext !== "exportjson")
return cc.log("%s load error, must be json file", file);
var parse;
- if(!type){
- if(json["widgetTree"])
+ if (!type) {
+ if (json["widgetTree"])
parse = parser["ccui"];
- else if(json["nodeTree"])
+ else if (json["nodeTree"])
parse = parser["timeline"];
- else if(json["Content"] && json["Content"]["Content"])
+ else if (json["Content"] && json["Content"]["Content"])
parse = parser["timeline"];
- else if(json["gameobjects"])
+ else if (json["gameobjects"])
parse = parser["scene"];
- }else{
+ } else {
parse = parser[type];
}
- if(!parse){
+ if (!parse) {
cc.log("Can't find the parser : %s", file);
return new cc.Node();
}
var version = json["version"] || json["Version"];
- if(!version && json["armature_data"]){
+ if (!version && json["armature_data"]) {
cc.warn("%s is armature. please use:", file);
cc.warn(" ccs.armatureDataManager.addArmatureFileInfoAsync(%s);", file);
cc.warn(" var armature = new ccs.Armature('name');");
return new cc.Node();
}
var currentParser = getParser(parse, version);
- if(!currentParser){
+ if (!currentParser) {
cc.log("Can't find the parser : %s", file);
return new cc.Node();
}
@@ -82,24 +82,24 @@ ccs._load = (function(){
"scene": {}
};
- load.registerParser = function(name, version, target){
- if(!name || !version || !target)
+ load.registerParser = function (name, version, target) {
+ if (!name || !version || !target)
return cc.log("register parser error");
- if(!parser[name])
+ if (!parser[name])
parser[name] = {};
parser[name][version] = target;
};
- load.getParser = function(name, version){
- if(name && version)
+ load.getParser = function (name, version) {
+ if (name && version)
return parser[name] ? parser[name][version] : undefined;
- if(name)
+ if (name)
return parser[name];
return parser;
};
//Gets the file extension
- var extname = function(fileName){
+ var extname = function (fileName) {
var arr = fileName.match(extnameReg);
return ( arr && arr[1] ) ? arr[1] : null;
};
@@ -107,10 +107,10 @@ ccs._load = (function(){
var parserReg = /([^\.](\.\*)?)*$/;
- var getParser = function(parser, version){
- if(parser[version])
+ var getParser = function (parser, version) {
+ if (parser[version])
return parser[version];
- else if(version === "*")
+ else if (version === "*")
return null;
else
return getParser(parser, version.replace(parserReg, "*"));
@@ -122,25 +122,25 @@ ccs._load = (function(){
ccs._parser = cc.Class.extend({
- ctor: function(){
+ ctor: function () {
this.parsers = {};
},
_dirnameReg: /\S*\//,
- _dirname: function(path){
+ _dirname: function (path) {
var arr = path.match(this._dirnameReg);
return (arr && arr[0]) ? arr[0] : "";
},
- getClass: function(json){
+ getClass: function (json) {
return json["classname"];
},
- getNodeJson: function(json){
+ getNodeJson: function (json) {
return json["widgetTree"];
},
- parse: function(file, json, resourcePath){
+ parse: function (file, json, resourcePath) {
resourcePath = resourcePath || this._dirname(file);
this.pretreatment(json, resourcePath);
var node = this.parseNode(this.getNodeJson(json), resourcePath, file);
@@ -148,14 +148,16 @@ ccs._parser = cc.Class.extend({
return node;
},
- pretreatment: function(json, resourcePath, file){},
+ pretreatment: function (json, resourcePath, file) {
+ },
- deferred: function(json, resourcePath, node, file){},
+ deferred: function (json, resourcePath, node, file) {
+ },
- parseNode: function(json, resourcePath){
+ parseNode: function (json, resourcePath) {
var parser = this.parsers[this.getClass(json)];
var widget = null;
- if(parser)
+ if (parser)
widget = parser.call(this, json, resourcePath);
else
cc.log("Can't find the parser : %s", this.getClass(json));
@@ -163,7 +165,7 @@ ccs._parser = cc.Class.extend({
return widget;
},
- registerParser: function(widget, parse){
+ registerParser: function (widget, parse) {
this.parsers[widget] = parse;
}
});
@@ -180,7 +182,7 @@ ccs._parser = cc.Class.extend({
* @param {String} [path=] Resource path
* @returns {{node: cc.Node, action: cc.Action}}
*/
-ccs.load = function(file, path){
+ccs.load = function (file, path) {
var object = {
node: null,
action: null
@@ -188,7 +190,7 @@ ccs.load = function(file, path){
object.node = ccs._load(file, null, path);
object.action = ccs._load(file, "action", path);
- if(object.action && object.action.tag === -1 && object.node)
+ if (object.action && object.action.tag === -1 && object.node)
object.action.tag = object.node.tag;
return object;
};
@@ -208,10 +210,10 @@ ccs.load.preload = true;
* @param {String} [path=] Resource path
* @returns {{node: cc.Node, action: cc.Action}}
*/
-ccs.loadWithVisibleSize = function(file, path){
+ccs.loadWithVisibleSize = function (file, path) {
var object = ccs.load(file, path);
var size = cc.director.getVisibleSize();
- if(object.node && size){
+ if (object.node && size) {
object.node.setContentSize(size.width, size.height);
ccui.helper.doLayout(object.node);
}
@@ -229,7 +231,7 @@ ccs.actionTimelineCache = {
* @param file
* @returns {*}
*/
- createAction: function(file){
+ createAction: function (file) {
return ccs._load(file, "action");
}
};
@@ -242,37 +244,37 @@ ccs.csLoader = {
* @param file
* @returns {*}
*/
- createNode: function(file){
+ createNode: function (file) {
return ccs._load(file);
}
};
cc.loader.register(["json"], {
- load : function(realUrl, url, res, cb){
- cc.loader.loadJson(realUrl, function(error, data){
+ load: function (realUrl, url, res, cb) {
+ cc.loader.loadJson(realUrl, function (error, data) {
var path = cc.path;
- if(data && data["Content"] && data["Content"]["Content"]["UsedResources"]){
+ if (data && data["Content"] && data["Content"]["Content"]["UsedResources"]) {
var UsedResources = data["Content"]["Content"]["UsedResources"],
dirname = path.dirname(url),
list = [],
tmpUrl, normalUrl;
- for(var i=0; i= 1700){
+ if (!version || versionNum >= 1700) {
cc.warn("Not supported file types, Please try use the ccs.load");
return null;
}
@@ -63,16 +63,16 @@
* @param callback
* @deprecated This function will be deprecated sooner or later please use parser.registerParser
*/
- registerTypeAndCallBack: function(classType, ins, object, callback){
+ registerTypeAndCallBack: function (classType, ins, object, callback) {
var parser = ccs._load.getParser("ccui")["*"];
var func = callback.bind(object);
- parser.registerParser(classType, function(options, resourcePath){
+ parser.registerParser(classType, function (options, resourcePath) {
var widget = new ins();
var uiOptions = options["options"];
object.setPropsFromJsonDictionary && object.setPropsFromJsonDictionary(widget, uiOptions);
this.generalAttributes(widget, uiOptions);
var customProperty = uiOptions["customProperty"];
- if(customProperty)
+ if (customProperty)
customProperty = JSON.parse(customProperty);
else
customProperty = {};
@@ -90,13 +90,13 @@
* @param {String} version version string.
* @returns {Number}
*/
- getVersionInteger: function(version){
- if(!version || typeof version !== "string") return 0;
+ getVersionInteger: function (version) {
+ if (!version || typeof version !== "string") return 0;
var arr = version.split(".");
if (arr.length !== 4)
return 0;
var num = 0;
- arr.forEach(function(n, i){
+ arr.forEach(function (n, i) {
num += n * Math.pow(10, 3 - i);
});
return num;
@@ -127,12 +127,12 @@
* Returns the file path
* @returns {string}
*/
- getFilePath: function(){
+ getFilePath: function () {
return this._filePath;
},
//@deprecated This function will be deprecated sooner or later
- setFilePath: function(path){
+ setFilePath: function (path) {
this._filePath = path;
},
@@ -141,7 +141,7 @@
* Returns the parsed object map. (analytic function)
* @returns {Object}
*/
- getParseObjectMap: function(){
+ getParseObjectMap: function () {
return ccs._load.getParser("ccui")["*"]["parsers"];
},
@@ -150,31 +150,32 @@
* Returns the parsed callback map. (analytic function)
* @returns {*}
*/
- getParseCallBackMap: function(){
+ getParseCallBackMap: function () {
return ccs._load.getParser("ccui")["*"]["parsers"];
},
//@deprecated This function will be deprecated sooner or later
- clear: function(){}
+ clear: function () {
+ }
};
var parser = ccs._load.getParser("ccui")["*"];
- ccs.imageViewReader = {setPropsFromJsonDictionary: parser.ImageViewAttributes};
- ccs.buttonReader = {setPropsFromJsonDictionary: parser.ButtonAttributes};
- ccs.checkBoxReader = {setPropsFromJsonDictionary: parser.CheckBoxAttributes};
+ ccs.imageViewReader = {setPropsFromJsonDictionary: parser.ImageViewAttributes};
+ ccs.buttonReader = {setPropsFromJsonDictionary: parser.ButtonAttributes};
+ ccs.checkBoxReader = {setPropsFromJsonDictionary: parser.CheckBoxAttributes};
ccs.labelAtlasReader = {setPropsFromJsonDictionary: parser.TextAtlasAttributes};
- ccs.labelBMFontReader= {setPropsFromJsonDictionary: parser.TextBMFontAttributes};
- ccs.labelReader = {setPropsFromJsonDictionary: parser.TextAttributes};
- ccs.layoutReader = {setPropsFromJsonDictionary: parser.LayoutAttributes};
- ccs.listViewReader = {setPropsFromJsonDictionary: parser.ListViewAttributes};
+ ccs.labelBMFontReader = {setPropsFromJsonDictionary: parser.TextBMFontAttributes};
+ ccs.labelReader = {setPropsFromJsonDictionary: parser.TextAttributes};
+ ccs.layoutReader = {setPropsFromJsonDictionary: parser.LayoutAttributes};
+ ccs.listViewReader = {setPropsFromJsonDictionary: parser.ListViewAttributes};
ccs.loadingBarReader = {setPropsFromJsonDictionary: parser.LoadingBarAttributes};
- ccs.pageViewReader = {setPropsFromJsonDictionary: parser.PageViewAttributes};
+ ccs.pageViewReader = {setPropsFromJsonDictionary: parser.PageViewAttributes};
ccs.scrollViewReader = {setPropsFromJsonDictionary: parser.ScrollViewAttributes};
- ccs.sliderReader = {setPropsFromJsonDictionary: parser.SliderAttributes};
- ccs.textFieldReader = {setPropsFromJsonDictionary: parser.TextFieldAttributes};
+ ccs.sliderReader = {setPropsFromJsonDictionary: parser.SliderAttributes};
+ ccs.textFieldReader = {setPropsFromJsonDictionary: parser.TextFieldAttributes};
})();
-(function(){
+(function () {
ccs.sceneReader = {
_node: null,
@@ -185,7 +186,7 @@
* @param file
* @returns {*}
*/
- createNodeWithSceneFile: function(file){
+ createNodeWithSceneFile: function (file) {
var node = ccs._load(file, "scene");
this._node = node;
return node;
@@ -196,7 +197,7 @@
* @param {Number} tag
* @returns {cc.Node|null}
*/
- getNodeByTag: function(tag){
+ getNodeByTag: function (tag) {
if (this._node == null)
return null;
if (this._node.getTag() === tag)
@@ -228,7 +229,7 @@
* Returns the version of ccs.SceneReader.
* @returns {string}
*/
- version: function(){
+ version: function () {
return "*";
},
@@ -237,15 +238,16 @@
* Sets the listener to reader.
* Cannot use
*/
- setTarget: function(){},
+ setTarget: function () {
+ },
//@deprecated This function will be deprecated sooner or later
/**
* Clear all triggers and stops all sounds.
*/
- clear: function(){
+ clear: function () {
ccs.triggerManager.removeAll();
cc.audioEngine.end();
}
};
-})();
\ No newline at end of file
+})();
diff --git a/extensions/cocostudio/loader/parsers/scene-1.x.js b/extensions/cocostudio/loader/parsers/scene-1.x.js
index 04569cb17f..8982f26bfc 100644
--- a/extensions/cocostudio/loader/parsers/scene-1.x.js
+++ b/extensions/cocostudio/loader/parsers/scene-1.x.js
@@ -22,18 +22,18 @@
THE SOFTWARE.
****************************************************************************/
-(function(load, baseParser){
+(function (load, baseParser) {
var Parser = baseParser.extend({
- getNodeJson: function(json){
+ getNodeJson: function (json) {
return json;
},
- parseNode: function(json, resourcePath){
+ parseNode: function (json, resourcePath) {
var parser = this.parsers[this.getClass(json)];
var node = null;
- if(parser)
+ if (parser)
node = parser.call(this, json, resourcePath);
else
cc.log("Can't find the parser : %s", this.getClass(json));
@@ -41,32 +41,32 @@
return node;
},
- deferred: function(json, resourcePath, node, file){
- ccs.triggerManager.parse(json["Triggers"]||[]);
- if(ccs.sceneReader)
+ deferred: function (json, resourcePath, node, file) {
+ ccs.triggerManager.parse(json["Triggers"] || []);
+ if (ccs.sceneReader)
ccs.sceneReader._node = node;
},
- setPropertyFromJsonDict: function(node, json){
- var x = (cc.isUndefined(json["x"]))?0:json["x"];
- var y = (cc.isUndefined(json["y"]))?0:json["y"];
+ setPropertyFromJsonDict: function (node, json) {
+ var x = (cc.isUndefined(json["x"])) ? 0 : json["x"];
+ var y = (cc.isUndefined(json["y"])) ? 0 : json["y"];
node.setPosition(x, y);
- var bVisible = Boolean((cc.isUndefined(json["visible"]))?1:json["visible"]);
+ var bVisible = Boolean((cc.isUndefined(json["visible"])) ? 1 : json["visible"]);
node.setVisible(bVisible);
- var nTag = (cc.isUndefined(json["objecttag"]))?-1:json["objecttag"];
+ var nTag = (cc.isUndefined(json["objecttag"])) ? -1 : json["objecttag"];
node.setTag(nTag);
- var nZorder = (cc.isUndefined(json["zorder"]))?0:json["zorder"];
+ var nZorder = (cc.isUndefined(json["zorder"])) ? 0 : json["zorder"];
node.setLocalZOrder(nZorder);
- var fScaleX = (cc.isUndefined(json["scalex"]))?1:json["scalex"];
- var fScaleY = (cc.isUndefined(json["scaley"]))?1:json["scaley"];
+ var fScaleX = (cc.isUndefined(json["scalex"])) ? 1 : json["scalex"];
+ var fScaleY = (cc.isUndefined(json["scaley"])) ? 1 : json["scaley"];
node.setScaleX(fScaleX);
node.setScaleY(fScaleY);
- var fRotationZ = (cc.isUndefined(json["rotation"]))?0:json["rotation"];
+ var fRotationZ = (cc.isUndefined(json["rotation"])) ? 0 : json["rotation"];
node.setRotation(fRotationZ);
var sName = json["name"] || "";
@@ -77,24 +77,24 @@
var parser = new Parser();
- parser.parseChild = function(node, objects, resourcePath){
+ parser.parseChild = function (node, objects, resourcePath) {
for (var i = 0; i < objects.length; i++) {
var child,
options = objects[i];
- if(options)
+ if (options)
child = this.parseNode(options, resourcePath);
- if(child)
+ if (child)
node.addChild(child);
}
};
var componentsParser = {
- "CCSprite": function(node, component, resourcePath){
+ "CCSprite": function (node, component, resourcePath) {
var child = new cc.Sprite();
- loadTexture(component["fileData"], resourcePath, function(path, type){
- if(type === 0)
+ loadTexture(component["fileData"], resourcePath, function (path, type) {
+ if (type === 0)
child.setTexture(path);
- else if(type === 1){
+ else if (type === 1) {
var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path);
child.setSpriteFrame(spriteFrame);
}
@@ -103,20 +103,20 @@
node.addComponent(render);
return render;
},
- "CCTMXTiledMap": function(node, component, resourcePath){
+ "CCTMXTiledMap": function (node, component, resourcePath) {
var child = null;
- loadTexture(component["fileData"], resourcePath, function(path, type){
- if(type === 0)
+ loadTexture(component["fileData"], resourcePath, function (path, type) {
+ if (type === 0)
child = new cc.TMXTiledMap(path);
});
var render = new ccs.ComRender(child, "CCTMXTiledMap");
node.addComponent(render);
return render;
},
- "CCParticleSystemQuad": function(node, component, resourcePath){
+ "CCParticleSystemQuad": function (node, component, resourcePath) {
var child = null;
- loadTexture(component["fileData"], resourcePath, function(path, type){
- if(type === 0)
+ loadTexture(component["fileData"], resourcePath, function (path, type) {
+ if (type === 0)
child = new cc.ParticleSystem(path);
else
cc.log("unknown resourcetype on CCParticleSystemQuad!");
@@ -126,10 +126,10 @@
node.addComponent(render);
return render;
},
- "CCArmature": function(node, component, resourcePath){
+ "CCArmature": function (node, component, resourcePath) {
var child = null;
- loadTexture(component["fileData"], resourcePath, function(path, type){
- if(type === 0){
+ loadTexture(component["fileData"], resourcePath, function (path, type) {
+ if (type === 0) {
var jsonDict = cc.loader.getRes(path);
if (!jsonDict) cc.log("Please load the resource [%s] first!", path);
var armature_data = jsonDict["armature_data"];
@@ -139,7 +139,7 @@
child = new ccs.Armature(name);
}
});
- if(child){
+ if (child) {
var render = new ccs.ComRender(child, "CCArmature");
node.addComponent(render);
var actionName = component["selectedactionname"];
@@ -150,101 +150,103 @@
}
},
- "CCComAudio": function(node, component, resourcePath){
+ "CCComAudio": function (node, component, resourcePath) {
var audio = null;
- loadTexture(component["fileData"], resourcePath, function(path, type){
- if(type === 0){
+ loadTexture(component["fileData"], resourcePath, function (path, type) {
+ if (type === 0) {
audio = new ccs.ComAudio();
audio.preloadEffect(path);
var name = component["name"];
- if(name)
+ if (name)
audio.setName(name);
node.addComponent(audio);
}
});
},
- "CCComAttribute": function(node, component, resourcePath){
+ "CCComAttribute": function (node, component, resourcePath) {
var attribute = null;
- loadTexture(component["fileData"], resourcePath, function(path, type){
- if(type === 0){
+ loadTexture(component["fileData"], resourcePath, function (path, type) {
+ if (type === 0) {
attribute = new ccs.ComAttribute();
if (path !== "")
attribute.parse(path);
node.addComponent(attribute);
- }else
+ } else
cc.log("unknown resourcetype on CCComAttribute!");
});
return attribute;
},
- "CCBackgroundAudio": function(node, component, resourcePath){
+ "CCBackgroundAudio": function (node, component, resourcePath) {
var audio = null;
- loadTexture(component["fileData"], resourcePath, function(path, type){
- if(type === 0){
+ loadTexture(component["fileData"], resourcePath, function (path, type) {
+ if (type === 0) {
audio = new ccs.ComAudio();
audio.preloadBackgroundMusic(path);
- audio.setFile(path);var bLoop = Boolean(component["loop"] || 0);
+ audio.setFile(path);
+ var bLoop = Boolean(component["loop"] || 0);
audio.setLoop(bLoop);
var name = component["name"];
- if(name)
+ if (name)
audio.setName(name);
node.addComponent(audio);
audio.playBackgroundMusic(path, bLoop);
}
});
},
- "GUIComponent": function(node, component, resourcePath){
+ "GUIComponent": function (node, component, resourcePath) {
var widget = null;
- loadTexture(component["fileData"], resourcePath, function(path, type){
+ loadTexture(component["fileData"], resourcePath, function (path, type) {
widget = ccs._load(path, "ccui");
});
var render = new ccs.ComRender(widget, "GUIComponent");
node.addComponent(render);
return render;
},
- "CCScene": function(){}
+ "CCScene": function () {
+ }
};
var loadedPlist = {};
- var loadTexture = function(json, resourcePath, cb){
- if(json != null){
+ var loadTexture = function (json, resourcePath, cb) {
+ if (json != null) {
var path = json["path"];
var type = json["resourceType"];
var plist = json["plist"];
- if(!path)
+ if (!path)
return;
- if(plist){
- if(cc.loader.getRes(resourcePath + plist)){
+ if (plist) {
+ if (cc.loader.getRes(resourcePath + plist)) {
loadedPlist[resourcePath + plist] = true;
cc.spriteFrameCache.addSpriteFrames(resourcePath + plist);
- }else{
- if(!loadedPlist[resourcePath + plist])
+ } else {
+ if (!loadedPlist[resourcePath + plist])
cc.log("%s need to be preloaded", resourcePath + plist);
}
}
- if(type !== 0)
+ if (type !== 0)
cb(path, type);
else
cb(resourcePath + path, type);
}
};
- parser.parseComponents = function(node, json, resourcePath){
- if(!node || !json)
+ parser.parseComponents = function (node, json, resourcePath) {
+ if (!node || !json)
return;
- json.forEach(function(component){
+ json.forEach(function (component) {
var parser = componentsParser[component["classname"]];
var render = null;
- if(parser)
+ if (parser)
render = parser(node, component, resourcePath);
else
cc.log("Can't find the component parser : %s", component["classname"]);
var name = component["name"];
- if(render && name){
+ if (render && name) {
render.setName(name);
}
});
};
- parser.registerParser("CCNode", function(options, resourcePath){
+ parser.registerParser("CCNode", function (options, resourcePath) {
var node = new cc.Node();
this.setPropertyFromJsonDict(node, options);
this.parseChild.call(this, node, options["gameobjects"], resourcePath);
diff --git a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js
index 61a04a2fbf..1e9d907805 100644
--- a/extensions/cocostudio/loader/parsers/timelineParser-1.x.js
+++ b/extensions/cocostudio/loader/parsers/timelineParser-1.x.js
@@ -22,22 +22,22 @@
THE SOFTWARE.
****************************************************************************/
-(function(load, baseParser){
+(function (load, baseParser) {
var loadedPlist = {};
var Parser = baseParser.extend({
- getNodeJson: function(json){
+ getNodeJson: function (json) {
return json["nodeTree"];
},
- addSpriteFrame: function(plists, pngs, resourcePath){
- if(!plists || !pngs || plists.length !== pngs.length)
+ addSpriteFrame: function (plists, pngs, resourcePath) {
+ if (!plists || !pngs || plists.length !== pngs.length)
return;
for (var i = 0; i < plists.length; i++) {
var plist = resourcePath + plists[i];
- if(!cc.loader.getRes(plist) && !loadedPlist[plist])
+ if (!cc.loader.getRes(plist) && !loadedPlist[plist])
cc.log("%s need to be preloaded", plist);
else
loadedPlist[plist] = true;
@@ -48,67 +48,65 @@
}
},
- pretreatment: function(json, resourcePath, file){
+ pretreatment: function (json, resourcePath, file) {
this.addSpriteFrame(json["textures"], json["texturesPng"], resourcePath);
}
});
var parser = new Parser();
- parser.generalAttributes = function(node, options){
- var width = options["width"] !=null ? options["width"] : 0;
- var height = options["height"] !=null ? options["height"] : 0;
- var x = options["x"] !=null ? options["x"] : 0;
- var y = options["y"] !=null ? options["y"] : 0;
- var scalex = options["scaleX"] !=null ? options["scaleX"] : 1;
- var scaley = options["scaleY"] !=null ? options["scaleY"] : 1;
- var rotation = options["rotation"] !=null ? options["rotation"] : 0;
- var rotationSkewX = options["rotationSkewX"]!=null ? options["rotationSkewX"] : 0;
- var rotationSkewY = options["rotationSkewY"]!=null ? options["rotationSkewY"] : 0;
- var skewx = options["skewX"] !=null ? options["skewX"] : 0;
- var skewy = options["skewY"] !=null ? options["skewY"] : 0;
- var anchorx = options["anchorPointX"] !=null ? options["anchorPointX"] : 0.5;
- var anchory = options["anchorPointY"] !=null ? options["anchorPointY"] : 0.5;
- var alpha = options["opacity"] !=null ? options["opacity"] : 255;
- var red = options["colorR"] !=null ? options["colorR"] : 255;
- var green = options["colorG"] !=null ? options["colorG"] : 255;
- var blue = options["colorB"] !=null ? options["colorB"] : 255;
- var zorder = options["colorR"] !=null ? options["colorR"] : 0;
- var tag = options["tag"] !=null ? options["tag"] : 0;
- var actionTag = options["actionTag"] !=null ? options["actionTag"] : 0;
- var visible = options["visible"] !=null ? options["visible"] : true;
+ parser.generalAttributes = function (node, options) {
+ var width = options["width"] != null ? options["width"] : 0;
+ var height = options["height"] != null ? options["height"] : 0;
+ var x = options["x"] != null ? options["x"] : 0;
+ var y = options["y"] != null ? options["y"] : 0;
+ var scalex = options["scaleX"] != null ? options["scaleX"] : 1;
+ var scaley = options["scaleY"] != null ? options["scaleY"] : 1;
+ var rotation = options["rotation"] != null ? options["rotation"] : 0;
+ var rotationSkewX = options["rotationSkewX"] != null ? options["rotationSkewX"] : 0;
+ var rotationSkewY = options["rotationSkewY"] != null ? options["rotationSkewY"] : 0;
+ var skewx = options["skewX"] != null ? options["skewX"] : 0;
+ var skewy = options["skewY"] != null ? options["skewY"] : 0;
+ var anchorx = options["anchorPointX"] != null ? options["anchorPointX"] : 0.5;
+ var anchory = options["anchorPointY"] != null ? options["anchorPointY"] : 0.5;
+ var alpha = options["opacity"] != null ? options["opacity"] : 255;
+ var red = options["colorR"] != null ? options["colorR"] : 255;
+ var green = options["colorG"] != null ? options["colorG"] : 255;
+ var blue = options["colorB"] != null ? options["colorB"] : 255;
+ var zorder = options["colorR"] != null ? options["colorR"] : 0;
+ var tag = options["tag"] != null ? options["tag"] : 0;
+ var actionTag = options["actionTag"] != null ? options["actionTag"] : 0;
+ var visible = options["visible"] != null ? options["visible"] : true;
- if(x != 0 || y != 0)
+ if (x != 0 || y != 0)
node.setPosition(cc.p(x, y));
- if(scalex != 1)
+ if (scalex != 1)
node.setScaleX(scalex);
- if(scaley != 1)
+ if (scaley != 1)
node.setScaleY(scaley);
if (rotation != 0)
node.setRotation(rotation);
- if(rotationSkewX != 0)
+ if (rotationSkewX != 0)
node.setRotationX(rotationSkewX);
- if(rotationSkewY != 0)
+ if (rotationSkewY != 0)
node.setRotationY(rotationSkewY);
- if(skewx != 0)
+ if (skewx != 0)
node.setSkewX(skewx);
- if(skewy != 0)
+ if (skewy != 0)
node.setSkewY(skewy);
- if(anchorx != 0.5 || anchory != 0.5)
+ if (anchorx != 0.5 || anchory != 0.5)
node.setAnchorPoint(cc.p(anchorx, anchory));
- if(width != 0 || height != 0)
+ if (width != 0 || height != 0)
node.setContentSize(cc.size(width, height));
- if(zorder != 0)
+ if (zorder != 0)
node.setLocalZOrder(zorder);
- if(visible != true)
+ if (visible != true)
node.setVisible(visible);
- if(alpha != 255)
- {
+ if (alpha != 255) {
node.setOpacity(alpha);
}
- if(red != 255 || green != 255 || blue != 255)
- {
+ if (red != 255 || green != 255 || blue != 255) {
node.setColor(cc.color(red, green, blue));
}
@@ -117,32 +115,32 @@
node.setUserObject(new ccs.ActionTimelineData(actionTag));
};
- parser.parseComponent = function(node, options){
- if(!options) return;
- for (var i = 0; i < options.length; ++i){
+ parser.parseComponent = function (node, options) {
+ if (!options) return;
+ for (var i = 0; i < options.length; ++i) {
var dic = options[i];
var component = this.loadComponent(dic);
- if (component){
+ if (component) {
node.addComponent(component);
}
}
};
- parser.parseChild = function(parse, widget, options, resourcePath){
+ parser.parseChild = function (parse, widget, options, resourcePath) {
var children = options["children"];
for (var i = 0; i < children.length; i++) {
var child = this.parseNode(children[i], resourcePath);
- if(child){
- if(widget instanceof ccui.PageView){
- if(child instanceof ccui.Layout)
+ if (child) {
+ if (widget instanceof ccui.PageView) {
+ if (child instanceof ccui.Layout)
widget.addPage(child);
} else {
- if(widget instanceof ccui.ListView){
- if(child instanceof ccui.Widget)
+ if (widget instanceof ccui.ListView) {
+ if (child instanceof ccui.Widget)
widget.pushBackCustomItem(child);
} else {
- if(!(widget instanceof ccui.Layout) && child instanceof ccui.Widget) {
- if(child.getPositionType() === ccui.Widget.POSITION_PERCENT) {
+ if (!(widget instanceof ccui.Layout) && child instanceof ccui.Widget) {
+ if (child.getPositionType() === ccui.Widget.POSITION_PERCENT) {
var position = child.getPositionPercent();
var anchor = widget.getAnchorPoint();
child.setPositionPercent(cc.p(position.x + anchor.x, position.y + anchor.y));
@@ -158,53 +156,53 @@
}
};
- parser.initNode = function(options){
+ parser.initNode = function (options) {
var node = new cc.Node();
this.generalAttributes(node, options);
return node;
};
- parser.initSubGraph = function(options){
+ parser.initSubGraph = function (options) {
var filePath = options["fileName"];
var node;
- if (filePath && "" !== filePath){
+ if (filePath && "" !== filePath) {
node = this.createNode(filePath);
- }else{
+ } else {
node = new ccs.Node();
}
this.generalAttributes(node, options);
return node;
};
- parser.initSprite = function(options, resourcePath){
+ parser.initSprite = function (options, resourcePath) {
var path = options["fileName"];
var sprite;
- if(path != null){
+ if (path != null) {
var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path);
- if(!spriteFrame){
+ if (!spriteFrame) {
path = resourcePath + path;
sprite = new ccs.Sprite(path);
- }else{
+ } else {
sprite = ccs.Sprite.createWithSpriteFrame(spriteFrame);
}
- if(!sprite){
+ if (!sprite) {
sprite = new cc.Sprite();
cc.log("filePath is empty. Create a sprite with no texture");
}
- }else{
+ } else {
sprite = new ccs.Sprite();
}
this.generalAttributes(sprite, options);
var flipX = options["flipX"];
var flipY = options["flipY"];
- if(flipX != false)
+ if (flipX != false)
sprite.setFlippedX(flipX);
- if(flipY != false)
+ if (flipY != false)
sprite.setFlippedY(flipY);
return sprite;
};
- parser.initParticle = function(options, resourcePath){
+ parser.initParticle = function (options, resourcePath) {
var filePath = options["plistFile"];
var num = options["tmxFile"];
var particle = new cc.ParticleSystemQuad(filePath);
@@ -212,41 +210,41 @@
this.generalAttributes(particle, options);
return particle;
};
- parser.initTMXTiledMap = function(options, resourcePath){
+ parser.initTMXTiledMap = function (options, resourcePath) {
var tmxFile = options["tmxFile"];
var tmxString = options["tmxString"];
//todo check path and resourcePath
var path = options["resourcePath"];
var tmx = null;
- if (tmxFile && "" !== tmxFile){
+ if (tmxFile && "" !== tmxFile) {
tmx = new cc.TMXTiledMap(tmxFile);
- }else if (tmxString && "" !== tmxString && path && "" !== path){
+ } else if (tmxString && "" !== tmxString && path && "" !== path) {
tmx = new cc.TMXTiledMap(tmxString, path);
}
return tmx;
};
var uiParser = load.getParser("ccui")["*"];
- parser.initWidget = function(options, resourcePath){
+ parser.initWidget = function (options, resourcePath) {
var type = options["classname"];
var parser = uiParser.parsers[type];
- if(!parser)
+ if (!parser)
return cc.log("%s parser is not found", type);
var node = parser.call(uiParser, options, resourcePath);
- if(node){
+ if (node) {
var rotationSkewX = options["rotationSkewX"];
var rotationSkewY = options["rotationSkewY"];
- var skewx = options["skewX"];
- var skewy = options["skewY"];
- if(rotationSkewX != 0)
+ var skewx = options["skewX"];
+ var skewy = options["skewY"];
+ if (rotationSkewX != 0)
node.setRotationX(rotationSkewX);
- if(rotationSkewY != 0)
+ if (rotationSkewY != 0)
node.setRotationY(rotationSkewY);
- if(skewx != 0)
+ if (skewx != 0)
node.setSkewX(skewx);
- if(skewy != 0)
+ if (skewy != 0)
node.setSkewY(skewy);
var actionTag = options["actionTag"];
@@ -278,8 +276,8 @@
{name: "TextField", handle: parser.initWidget}
];
- register.forEach(function(item){
- parser.registerParser(item.name, function(options, parse, resourcePath){
+ register.forEach(function (item) {
+ parser.registerParser(item.name, function (options, parse, resourcePath) {
var node = item.handle.call(this, options["options"]);
this.parseComponent(node, options["components"]);
this.parseChild(parse, node, options, resourcePath);
diff --git a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js
index f8da6b0210..c823ce8737 100644
--- a/extensions/cocostudio/loader/parsers/timelineParser-2.x.js
+++ b/extensions/cocostudio/loader/parsers/timelineParser-2.x.js
@@ -22,15 +22,15 @@
THE SOFTWARE.
****************************************************************************/
-(function(load, baseParser){
+(function (load, baseParser) {
var DEBUG = false;
var Parser = baseParser.extend({
- parse: function(file, json, path){
+ parse: function (file, json, path) {
var resourcePath;
- if(path !== undefined)
+ if (path !== undefined)
resourcePath = path;
else
resourcePath = this._dirname(file);
@@ -40,15 +40,15 @@
return node;
},
- getNodeJson: function(json){
+ getNodeJson: function (json) {
var content = json["Content"];
- if(content["ObjectData"])
+ if (content["ObjectData"])
return content["ObjectData"];
return content["Content"]["ObjectData"];
},
- getClass: function(json){
+ getClass: function (json) {
return json["ctype"];
}
@@ -56,8 +56,8 @@
var parser = new Parser();
- var getParam = function(value, dValue){
- if(value === undefined)
+ var getParam = function (value, dValue) {
+ if (value === undefined)
return dValue;
else
return value;
@@ -67,19 +67,19 @@
// NODE //
//////////
- parser.generalAttributes = function(node, json){
- if(json["Name"] != null)
+ parser.generalAttributes = function (node, json) {
+ if (json["Name"] != null)
node.setName(json["Name"]);
var position = json["Position"];
- if(position != null && (position["X"] != null || position["Y"] != null))
- node.setPosition(cc.p(position["X"]||0, position["Y"]||0));
+ if (position != null && (position["X"] != null || position["Y"] != null))
+ node.setPosition(cc.p(position["X"] || 0, position["Y"] || 0));
var scale = json["Scale"];
- if(scale != null){
- if(scale["ScaleX"] != null)
+ if (scale != null) {
+ if (scale["ScaleX"] != null)
node.setScaleX(scale["ScaleX"]);
- if(scale["ScaleY"] != null)
+ if (scale["ScaleY"] != null)
node.setScaleY(scale["ScaleY"]);
}
@@ -93,12 +93,12 @@
var anchor = json["AnchorPoint"];
- if(anchor != null){
- if(anchor["ScaleX"] == null)
+ if (anchor != null) {
+ if (anchor["ScaleX"] == null)
anchor["ScaleX"] = 0;
- if(anchor["ScaleY"] == null)
+ if (anchor["ScaleY"] == null)
anchor["ScaleY"] = 0;
- if(anchor["ScaleX"] != 0.5 || anchor["ScaleY"] != 0.5)
+ if (anchor["ScaleX"] != 0.5 || anchor["ScaleY"] != 0.5)
node.setAnchorPoint(cc.p(anchor["ScaleX"], anchor["ScaleY"]));
}
@@ -109,7 +109,7 @@
node.setVisible(visible);
var size = json["Size"];
- if(size)
+ if (size)
setContentSize(node, size);
if (json["Alpha"] != null)
@@ -120,7 +120,7 @@
var actionTag = json["ActionTag"] || 0;
var extensionData = new ccs.ComExtensionData();
var customProperty = json["UserData"];
- if(customProperty !== undefined)
+ if (customProperty !== undefined)
extensionData.setCustomProperty(customProperty);
extensionData.setActionTag(actionTag);
if (node.getComponent("ComExtensionData"))
@@ -133,21 +133,21 @@
setLayoutComponent(node, json);
};
- parser.parseChild = function(node, children, resourcePath){
- if(!node || !children) return;
+ parser.parseChild = function (node, children, resourcePath) {
+ if (!node || !children) return;
for (var i = 0; i < children.length; i++) {
var child = this.parseNode(children[i], resourcePath);
- if(child){
- if(node instanceof ccui.PageView){
- if(child instanceof ccui.Layout)
+ if (child) {
+ if (node instanceof ccui.PageView) {
+ if (child instanceof ccui.Layout)
node.addPage(child);
} else {
- if(node instanceof ccui.ListView){
- if(child instanceof ccui.Widget)
+ if (node instanceof ccui.ListView) {
+ if (child instanceof ccui.Widget)
node.pushBackCustomItem(child);
} else {
- if(!(node instanceof ccui.Layout) && child instanceof ccui.Widget) {
- if(child.getPositionType() === ccui.Widget.POSITION_PERCENT) {
+ if (!(node instanceof ccui.Layout) && child instanceof ccui.Widget) {
+ if (child.getPositionType() === ccui.Widget.POSITION_PERCENT) {
var position = child.getPositionPercent();
var anchor = node.getAnchorPoint();
child.setPositionPercent(cc.p(position.x + anchor.x, position.y + anchor.y));
@@ -165,12 +165,12 @@
* @param json
* @returns {cc.Node}
*/
- parser.initSingleNode = function(json){
+ parser.initSingleNode = function (json) {
var node = new cc.Node();
this.generalAttributes(node, json);
var color = json["CColor"];
- if(color != null)
+ if (color != null)
node.setColor(getColor(color));
return node;
@@ -182,21 +182,21 @@
* @param resourcePath
* @returns {cc.Sprite}
*/
- parser.initSprite = function(json, resourcePath){
- var node = new cc.Sprite();
+ parser.initSprite = function (json, resourcePath) {
+ var node = new cc.Sprite();
- loadTexture(json["FileData"], resourcePath, function(path, type){
- if(type === 0)
+ loadTexture(json["FileData"], resourcePath, function (path, type) {
+ if (type === 0)
node.setTexture(path);
- else if(type === 1){
+ else if (type === 1) {
var spriteFrame = cc.spriteFrameCache.getSpriteFrame(path);
- if(spriteFrame)
+ if (spriteFrame)
node.setSpriteFrame(spriteFrame);
}
});
var blendData = json["BlendFunc"];
- if(json["BlendFunc"]) {
+ if (json["BlendFunc"]) {
var blendFunc = cc.BlendFunc.ALPHA_PREMULTIPLIED;
if (blendData["Src"] !== undefined)
blendFunc.src = blendData["Src"];
@@ -205,14 +205,14 @@
node.setBlendFunc(blendFunc);
}
- if(json["FlipX"])
+ if (json["FlipX"])
node.setFlippedX(true);
- if(json["FlipY"])
+ if (json["FlipY"])
node.setFlippedY(true);
this.generalAttributes(node, json);
var color = json["CColor"];
- if(color != null)
+ if (color != null)
node.setColor(getColor(color));
return node;
@@ -224,11 +224,11 @@
* @param resourcePath
* @returns {*}
*/
- parser.initParticle = function(json, resourcePath){
+ parser.initParticle = function (json, resourcePath) {
var node,
self = this;
- loadTexture(json["FileData"], resourcePath, function(path, type){
- if(!cc.loader.getRes(path))
+ loadTexture(json["FileData"], resourcePath, function (path, type) {
+ if (!cc.loader.getRes(path))
cc.log("%s need to be preloaded", path);
node = new cc.ParticleSystem(path);
self.generalAttributes(node, json);
@@ -236,11 +236,11 @@
!cc.sys.isNative && node.setDrawMode(cc.ParticleSystem.TEXTURE_MODE);
var blendData = json["BlendFunc"];
- if(json["BlendFunc"]){
+ if (json["BlendFunc"]) {
var blendFunc = cc.BlendFunc.ALPHA_PREMULTIPLIED;
- if(blendData["Src"] !== undefined)
+ if (blendData["Src"] !== undefined)
blendFunc.src = blendData["Src"];
- if(blendData["Dst"] !== undefined)
+ if (blendData["Dst"] !== undefined)
blendFunc.dst = blendData["Dst"];
node.setBlendFunc(blendFunc);
}
@@ -270,7 +270,7 @@
widget.setActionTag(actionTag);
var extensionData = new ccs.ComExtensionData();
var customProperty = json["UserData"];
- if(customProperty !== undefined)
+ if (customProperty !== undefined)
extensionData.setCustomProperty(customProperty);
extensionData.setActionTag(actionTag);
if (widget.getComponent("ComExtensionData"))
@@ -347,26 +347,26 @@
bindCallback(widget, json);
};
- var bindCallback = function(widget, json){
+ var bindCallback = function (widget, json) {
var callBackType = json["CallBackType"];
var callBackName = json["CallBackName"];
- var callBack = function(e){
- if(typeof widget[callBackName] === "function")
+ var callBack = function (e) {
+ if (typeof widget[callBackName] === "function")
widget[callBackName](e);
};
- if(callBackType === "Click"){
+ if (callBackType === "Click") {
widget.addClickEventListener(callBack);
- }else if(callBackType === "Touch"){
+ } else if (callBackType === "Touch") {
widget.addTouchEventListener(callBack);
- }else if(callBackType === "Event"){
+ } else if (callBackType === "Event") {
widget.addCCSEventListener(callBack);
}
};
- var setLayoutComponent = function(widget, json){
+ var setLayoutComponent = function (widget, json) {
var layoutComponent = ccui.LayoutComponent.bindLayoutComponent(widget);
- if(!layoutComponent)
+ if (!layoutComponent)
return;
var positionXPercentEnabled = json["PositionPercentXEnable"] || json["PositionPercentXEnabled"] || false;
@@ -378,8 +378,8 @@
positionXPercent = PrePosition["X"] || 0;
positionYPercent = PrePosition["Y"] || 0;
}
- var sizeXPercentEnable = json["PercentWidthEnable"] || json["PercentWidthEnabled"] || false;
- var sizeYPercentEnable = json["PercentHeightEnable"]|| json["PercentHeightEnabled"] || false;
+ var sizeXPercentEnable = json["PercentWidthEnable"] || json["PercentWidthEnabled"] || false;
+ var sizeYPercentEnable = json["PercentHeightEnable"] || json["PercentHeightEnabled"] || false;
var sizeXPercent = 0,
sizeYPercent = 0,
PreSize = json["PreSize"];
@@ -441,18 +441,18 @@
layoutComponent.setRightMargin(rightMargin);
};
- var setLayoutBackground = function(layout, single, first, end){
- if( layout.getBackGroundColorType() === 2 ){
+ var setLayoutBackground = function (layout, single, first, end) {
+ if (layout.getBackGroundColorType() === 2) {
first = first || {};
end = end || {};
layout.setBackGroundColor(getColor(first), getColor(end));
- }else{
+ } else {
single = single || {};
layout.setBackGroundColor(getColor(single));
}
};
- var setLayoutBackgroundVector = function(widget, vector){
+ var setLayoutBackgroundVector = function (widget, vector) {
var x = vector["ScaleX"] || 0;
var y = vector["ScaleY"] || 0;
widget.setBackGroundColorVector(cc.p(x, y));
@@ -464,34 +464,34 @@
* @param resourcePath
* @returns {ccui.Layout}
*/
- parser.initPanel = function(json, resourcePath){
+ parser.initPanel = function (json, resourcePath) {
var widget = new ccui.Layout();
this.widgetAttributes(widget, json);
var clipEnabled = json["ClipAble"] || false;
- if(clipEnabled != null)
+ if (clipEnabled != null)
widget.setClippingEnabled(clipEnabled);
var colorType = getParam(json["ComboBoxIndex"], 0);
widget.setBackGroundColorType(colorType);
var bgColorOpacity = getParam(json["BackColorAlpha"], 255);
- if(bgColorOpacity != null)
+ if (bgColorOpacity != null)
widget.setBackGroundColorOpacity(bgColorOpacity);
var backGroundScale9Enabled = json["Scale9Enable"];
- if(backGroundScale9Enabled != null)
+ if (backGroundScale9Enabled != null)
widget.setBackGroundImageScale9Enabled(backGroundScale9Enabled);
var opacity = getParam(json["Alpha"], 255);
widget.setOpacity(opacity);
- loadTexture(json["FileData"], resourcePath, function(path, type){
+ loadTexture(json["FileData"], resourcePath, function (path, type) {
widget.setBackGroundImage(path, type);
});
- if(backGroundScale9Enabled){
+ if (backGroundScale9Enabled) {
var scale9OriginX = json["Scale9OriginX"] || 0;
var scale9OriginY = json["Scale9OriginY"] || 0;
@@ -503,8 +503,8 @@
));
setContentSize(widget, json["Size"]);
- }else{
- if (!widget.isIgnoreContentAdaptWithSize()){
+ } else {
+ if (!widget.isIgnoreContentAdaptWithSize()) {
setContentSize(widget, json["Size"]);
}
@@ -521,37 +521,39 @@
* @param json
* @param resourcePath
*/
- parser.initText = function(json, resourcePath){
+ parser.initText = function (json, resourcePath) {
var widget = new ccui.Text();
var touchScaleEnabled = json["TouchScaleChangeAble"];
- if(touchScaleEnabled != null)
+ if (touchScaleEnabled != null)
widget.setTouchScaleChangeEnabled(touchScaleEnabled);
var text = json["LabelText"];
- if(text != null)
+ if (text != null)
widget.setString(text);
var fontSize = json["FontSize"];
- if(fontSize != null)
+ if (fontSize != null)
widget.setFontSize(fontSize);
var fontName = json["FontName"];
- if(fontName != null)
+ if (fontName != null)
widget.setFontName(fontName);
var areaWidth = json["AreaWidth"];
var areaHeight = json["areaHeight"];
- if(areaWidth && areaHeight)
+ if (areaWidth && areaHeight)
widget.setTextAreaSize(cc.size(areaWidth, areaHeight));
var h_alignment = json["HorizontalAlignmentType"] || "HT_Left";
- switch(h_alignment){
+ switch (h_alignment) {
case "HT_Right":
- h_alignment = 2; break;
+ h_alignment = 2;
+ break;
case "HT_Center":
- h_alignment = 1; break;
+ h_alignment = 1;
+ break;
case "HT_Left":
default:
h_alignment = 0;
@@ -559,11 +561,13 @@
widget.setTextHorizontalAlignment(h_alignment);
var v_alignment = json["VerticalAlignmentType"] || "VT_Top";
- switch(v_alignment){
+ switch (v_alignment) {
case "VT_Bottom":
- v_alignment = 2; break;
+ v_alignment = 2;
+ break;
case "VT_Center":
- v_alignment = 1; break;
+ v_alignment = 1;
+ break;
case "VT_Top":
default:
v_alignment = 0;
@@ -571,10 +575,10 @@
widget.setTextVerticalAlignment(v_alignment);
var fontResource = json["FontResource"];
- if(fontResource != null){
+ if (fontResource != null) {
var path = fontResource["Path"];
//resoutceType = fontResource["Type"];
- if(path != null){
+ if (path != null) {
if (cc.sys.isNative) {
fontName = cc.path.join(cc.loader.resPath, resourcePath, path);
} else {
@@ -585,10 +589,10 @@
}
}
- if(json["OutlineEnabled"] && json["OutlineColor"] && widget.enableOutline)
+ if (json["OutlineEnabled"] && json["OutlineColor"] && widget.enableOutline)
widget.enableOutline(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1));
- if(json["ShadowEnabled"] && json["ShadowColor"] && widget.enableShadow)
+ if (json["ShadowEnabled"] && json["ShadowColor"] && widget.enableShadow)
widget.enableShadow(
getColor(json["ShadowColor"]),
cc.size(getParam(json["ShadowOffsetX"], 2), getParam(json["ShadowOffsetY"], -2)),
@@ -596,7 +600,7 @@
);
var isCustomSize = json["IsCustomSize"];
- if(isCustomSize != null)
+ if (isCustomSize != null)
widget.ignoreContentAdaptWithSize(!isCustomSize);
widget.setUnifySizeEnabled(false);
@@ -615,39 +619,39 @@
* @param json
* @param resourcePath
*/
- parser.initButton = function(json, resourcePath){
+ parser.initButton = function (json, resourcePath) {
var widget = new ccui.Button();
- loadTexture(json["NormalFileData"], resourcePath, function(path, type){
+ loadTexture(json["NormalFileData"], resourcePath, function (path, type) {
widget.loadTextureNormal(path, type);
});
- loadTexture(json["PressedFileData"], resourcePath, function(path, type){
+ loadTexture(json["PressedFileData"], resourcePath, function (path, type) {
widget.loadTexturePressed(path, type);
});
- loadTexture(json["DisabledFileData"], resourcePath, function(path, type){
+ loadTexture(json["DisabledFileData"], resourcePath, function (path, type) {
widget.loadTextureDisabled(path, type);
});
var scale9Enabled = getParam(json["Scale9Enable"], false);
- if(scale9Enabled) {
+ if (scale9Enabled) {
widget.setScale9Enabled(scale9Enabled);
}
var text = json["ButtonText"];
- if(text != null)
+ if (text != null)
widget.setTitleText(text);
var fontSize = json["FontSize"];
- if(fontSize != null)
+ if (fontSize != null)
widget.setTitleFontSize(fontSize);
var fontName = json["FontName"];
- if(fontName != null)
+ if (fontName != null)
widget.setTitleFontName(fontName);
var textColor = json["TextColor"];
- if(textColor != null)
+ if (textColor != null)
widget.setTitleColor(getColor(textColor));
var displaystate = getParam(json["DisplayState"], true);
@@ -655,10 +659,10 @@
widget.setEnabled(displaystate);
var fontResource = json["FontResource"];
- if(fontResource != null){
+ if (fontResource != null) {
var path = fontResource["Path"];
//resoutceType = fontResource["Type"];
- if(path != null){
+ if (path != null) {
if (cc.sys.isNative) {
fontName = cc.path.join(cc.loader.resPath, resourcePath, path);
} else {
@@ -670,26 +674,26 @@
}
var label = widget.getTitleRenderer();
- if(label && json["ShadowEnabled"] && json["ShadowColor"] && label.enableShadow){
+ if (label && json["ShadowEnabled"] && json["ShadowColor"] && label.enableShadow) {
label.enableShadow(
getColor(json["ShadowColor"]),
cc.size(getParam(json["ShadowOffsetX"], 2), getParam(json["ShadowOffsetY"], -2)),
json["ShadowBlurRadius"] || 0
);
}
- if(label && json["OutlineEnabled"] && json["OutlineColor"] && label.enableStroke)
+ if (label && json["OutlineEnabled"] && json["OutlineColor"] && label.enableStroke)
label.enableStroke(getColor(json["OutlineColor"]), getParam(json["OutlineSize"], 1));
this.widgetAttributes(widget, json);
- if(scale9Enabled) {
+ if (scale9Enabled) {
widget.setUnifySizeEnabled(false);
widget.ignoreContentAdaptWithSize(false);
var capInsets = cc.rect(
- json["Scale9OriginX"] || 0,
- json["Scale9OriginY"] || 0,
- json["Scale9Width"] || 0,
- json["Scale9Height"] || 0
+ json["Scale9OriginX"] || 0,
+ json["Scale9OriginY"] || 0,
+ json["Scale9Width"] || 0,
+ json["Scale9Height"] || 0
);
widget.setCapInsets(capInsets);
@@ -706,7 +710,7 @@
* @param json
* @param resourcePath
*/
- parser.initCheckBox = function(json, resourcePath){
+ parser.initCheckBox = function (json, resourcePath) {
var widget = new ccui.CheckBox();
@@ -720,8 +724,8 @@
{name: "NodeDisableFileData", handle: widget.loadTextureFrontCrossDisabled}
];
- dataList.forEach(function(item){
- loadTexture(json[item.name], resourcePath, function(path, type){
+ dataList.forEach(function (item) {
+ loadTexture(json[item.name], resourcePath, function (path, type) {
item.handle.call(widget, path, type);
});
});
@@ -741,12 +745,12 @@
* @param json
* @param resourcePath
*/
- parser.initScrollView = function(json, resourcePath){
+ parser.initScrollView = function (json, resourcePath) {
var widget = new ccui.ScrollView();
this.widgetAttributes(widget, json);
- loadTexture(json["FileData"], resourcePath, function(path, type){
+ loadTexture(json["FileData"], resourcePath, function (path, type) {
widget.setBackGroundImage(path, type);
});
@@ -757,11 +761,11 @@
widget.setBackGroundColorType(colorType);
var bgColorOpacity = json["BackColorAlpha"];
- if(bgColorOpacity != null)
+ if (bgColorOpacity != null)
widget.setBackGroundColorOpacity(bgColorOpacity);
var backGroundScale9Enabled = json["Scale9Enable"];
- if(backGroundScale9Enabled){
+ if (backGroundScale9Enabled) {
widget.setBackGroundImageScale9Enabled(true);
@@ -773,7 +777,7 @@
scale9OriginX, scale9OriginY, scale9Width, scale9Height
));
setContentSize(widget, json["Size"]);
- }else if(!widget.isIgnoreContentAdaptWithSize()){
+ } else if (!widget.isIgnoreContentAdaptWithSize()) {
setContentSize(widget, json["Size"]);
}
@@ -788,9 +792,9 @@
widget.setInnerContainerSize(innerSize);
var direction = 0;
- if(json["ScrollDirectionType"] === "Vertical") direction = 1;
- if(json["ScrollDirectionType"] === "Horizontal") direction = 2;
- if(json["ScrollDirectionType"] === "Vertical_Horizontal") direction = 3;
+ if (json["ScrollDirectionType"] === "Vertical") direction = 1;
+ if (json["ScrollDirectionType"] === "Horizontal") direction = 2;
+ if (json["ScrollDirectionType"] === "Vertical_Horizontal") direction = 3;
widget.setDirection(direction);
var bounceEnabled = getParam(json["IsBounceEnabled"], false);
@@ -804,19 +808,19 @@
* @param json
* @param resourcePath
*/
- parser.initImageView = function(json, resourcePath){
+ parser.initImageView = function (json, resourcePath) {
var widget = new ccui.ImageView();
- loadTexture(json["FileData"], resourcePath, function(path, type){
+ loadTexture(json["FileData"], resourcePath, function (path, type) {
widget.loadTexture(path, type);
});
- loadTexture(json["ImageFileData"], resourcePath, function(path, type){
+ loadTexture(json["ImageFileData"], resourcePath, function (path, type) {
widget.loadTexture(path, type);
});
var scale9Enabled = json["Scale9Enable"];
- if(scale9Enabled){
+ if (scale9Enabled) {
widget.setScale9Enabled(true);
widget.setUnifySizeEnabled(false);
widget.ignoreContentAdaptWithSize(false);
@@ -826,7 +830,7 @@
var scale9Width = json["Scale9Width"] || 0;
var scale9Height = json["Scale9Height"] || 0;
widget.setCapInsets(cc.rect(
- scale9OriginX ,
+ scale9OriginX,
scale9OriginY,
scale9Width,
scale9Height
@@ -845,13 +849,13 @@
* @param resourcePath
* @returns {ccui.LoadingBar}
*/
- parser.initLoadingBar = function(json, resourcePath){
+ parser.initLoadingBar = function (json, resourcePath) {
var widget = new ccui.LoadingBar();
this.widgetAttributes(widget, json);
- loadTexture(json["ImageFileData"], resourcePath, function(path, type){
+ loadTexture(json["ImageFileData"], resourcePath, function (path, type) {
widget.loadTexture(path, type);
});
@@ -859,7 +863,7 @@
widget.setDirection(direction);
var percent = getParam(json["ProgressInfo"], 80);
- if(percent != null)
+ if (percent != null)
widget.setPercent(percent);
return widget;
@@ -871,7 +875,7 @@
* @param json
* @param resourcePath
*/
- parser.initSlider = function(json, resourcePath){
+ parser.initSlider = function (json, resourcePath) {
var widget = new ccui.Slider();
var loader = cc.loader;
@@ -885,9 +889,9 @@
{name: "BallDisabledData", handle: widget.loadSlidBallTextureDisabled},
{name: "ProgressBarData", handle: widget.loadProgressBarTexture}
];
- textureList.forEach(function(item){
- loadTexture(json[item.name], resourcePath, function(path, type){
- if(type === 0 && !loader.getRes(path))
+ textureList.forEach(function (item) {
+ loadTexture(json[item.name], resourcePath, function (path, type) {
+ if (type === 0 && !loader.getRes(path))
cc.log("%s need to be preloaded", path);
item.handle.call(widget, path, type);
});
@@ -908,13 +912,13 @@
* @param json
* @param resourcePath
*/
- parser.initPageView = function(json, resourcePath){
+ parser.initPageView = function (json, resourcePath) {
var widget = new ccui.PageView();
this.widgetAttributes(widget, json);
- loadTexture(json["FileData"], resourcePath, function(path, type){
+ loadTexture(json["FileData"], resourcePath, function (path, type) {
widget.setBackGroundImage(path, type);
});
@@ -922,7 +926,7 @@
widget.setClippingEnabled(clipEnabled);
var backGroundScale9Enabled = json["Scale9Enable"];
- if(backGroundScale9Enabled){
+ if (backGroundScale9Enabled) {
widget.setBackGroundImageScale9Enabled(true);
var scale9OriginX = json["Scale9OriginX"] || 0;
@@ -944,7 +948,7 @@
setLayoutBackgroundVector(widget, json["ColorVector"]);
var bgColorOpacity = json["BackColorAlpha"];
- if(bgColorOpacity != null)
+ if (bgColorOpacity != null)
widget.setBackGroundColorOpacity(bgColorOpacity);
setContentSize(widget, json["Size"]);
@@ -959,13 +963,13 @@
* @param resourcePath
* @returns {ccui.ListView}
*/
- parser.initListView = function(json, resourcePath){
+ parser.initListView = function (json, resourcePath) {
var widget = new ccui.ListView();
this.widgetAttributes(widget, json);
- loadTexture(json["FileData"], resourcePath, function(path, type){
+ loadTexture(json["FileData"], resourcePath, function (path, type) {
widget.setBackGroundImage(path, type);
});
@@ -977,7 +981,7 @@
var bgColorOpacity = getParam(json["BackColorAlpha"], 255);
var backGroundScale9Enabled = json["Scale9Enable"];
- if(backGroundScale9Enabled){
+ if (backGroundScale9Enabled) {
widget.setBackGroundImageScale9Enabled(true);
var scale9OriginX = json["Scale9OriginX"] || 0;
@@ -995,15 +999,15 @@
var directionType = getParam(json["DirectionType"], ccui.ListView.DIR_HORIZONTAL);
var verticalType = getParam(json["VerticalType"], "Align_Left");
var horizontalType = getParam(json["HorizontalType"], "Align_Top");
- if(!directionType){
+ if (!directionType) {
widget.setDirection(ccui.ScrollView.DIR_HORIZONTAL);
- if(verticalType === "Align_Bottom")
+ if (verticalType === "Align_Bottom")
widget.setGravity(ccui.ListView.GRAVITY_BOTTOM);
- else if(verticalType === "Align_VerticalCenter")
+ else if (verticalType === "Align_VerticalCenter")
widget.setGravity(ccui.ListView.GRAVITY_CENTER_VERTICAL);
else
widget.setGravity(ccui.ListView.GRAVITY_TOP);
- }else if(directionType === "Vertical"){
+ } else if (directionType === "Vertical") {
widget.setDirection(ccui.ScrollView.DIR_VERTICAL);
if (horizontalType === "")
widget.setGravity(ccui.ListView.GRAVITY_LEFT);
@@ -1022,13 +1026,13 @@
var innerSize = json["InnerNodeSize"];
//Width
- if(innerSize != null)
- widget.setInnerContainerSize(cc.size(innerSize["Widget"]||0, innerSize["Height"]||0));
+ if (innerSize != null)
+ widget.setInnerContainerSize(cc.size(innerSize["Widget"] || 0, innerSize["Height"] || 0));
setLayoutBackground(widget, json["SingleColor"], json["FirstColor"], json["EndColor"]);
setLayoutBackgroundVector(widget, json["ColorVector"]);
- if(bgColorOpacity != null)
+ if (bgColorOpacity != null)
widget.setBackGroundColorOpacity(bgColorOpacity);
setContentSize(widget, json["Size"]);
@@ -1042,7 +1046,7 @@
* @param resourcePath
* @returns {ccui.TextAtlas}
*/
- parser.initTextAtlas = function(json, resourcePath){
+ parser.initTextAtlas = function (json, resourcePath) {
var widget = new ccui.TextAtlas();
@@ -1052,10 +1056,10 @@
var startCharMap = json["StartChar"];
- loadTexture(json["LabelAtlasFileImage_CNB"], resourcePath, function(path, type){
- if(!cc.loader.getRes(path))
+ loadTexture(json["LabelAtlasFileImage_CNB"], resourcePath, function (path, type) {
+ if (!cc.loader.getRes(path))
cc.log("%s need to be preloaded", path);
- if(type === 0){
+ if (type === 0) {
widget.setProperty(stringValue, path, itemWidth, itemHeight, startCharMap);
}
});
@@ -1073,19 +1077,19 @@
* @param resourcePath
* @returns {ccui.TextBMFont}
*/
- parser.initTextBMFont = function(json, resourcePath){
-
+ parser.initTextBMFont = function (json, resourcePath) {
var widget = new ccui.TextBMFont();
this.widgetAttributes(widget, json);
- var text = json["LabelText"];
- widget.setString(text);
-
- loadTexture(json["LabelBMFontFile_CNB"], resourcePath, function(path, type){
- if(!cc.loader.getRes(path))
+ loadTexture(json["LabelBMFontFile_CNB"], resourcePath, function (path, type) {
+ if (!cc.loader.getRes(path))
cc.log("%s need to be pre loaded", path);
widget.setFntFile(path);
});
+
+ var text = json["LabelText"];
+ widget.setString(text);
+
widget.ignoreContentAdaptWithSize(true);
return widget;
};
@@ -1096,30 +1100,30 @@
* @param resourcePath
* @returns {ccui.TextField}
*/
- parser.initTextField = function(json, resourcePath){
+ parser.initTextField = function (json, resourcePath) {
var widget = new ccui.TextField();
var passwordEnabled = json["PasswordEnable"];
- if(passwordEnabled){
+ if (passwordEnabled) {
widget.setPasswordEnabled(true);
var passwordStyleText = json["PasswordStyleText"] || "*";
widget.setPasswordStyleText(passwordStyleText);
}
var placeHolder = json["PlaceHolderText"];
- if(placeHolder != null)
+ if (placeHolder != null)
widget.setPlaceHolder(placeHolder);
var fontSize = json["FontSize"];
- if(fontSize != null)
+ if (fontSize != null)
widget.setFontSize(fontSize);
var fontName = json["FontName"];
- if(fontName != null)
+ if (fontName != null)
widget.setFontName(fontName);
var maxLengthEnabled = json["MaxLengthEnable"];
- if(maxLengthEnabled){
+ if (maxLengthEnabled) {
widget.setMaxLengthEnabled(true);
var maxLength = json["MaxLengthText"] || 0;
widget.setMaxLength(maxLength);
@@ -1129,14 +1133,14 @@
this.widgetAttributes(widget, json);
var text = json["LabelText"];
- if(text != null)
+ if (text != null)
widget.setString(text);
var fontResource = json["FontResource"];
- if(fontResource != null){
+ if (fontResource != null) {
var path = fontResource["Path"];
//resoutceType = fontResource["Type"];
- if(path != null){
+ if (path != null) {
if (cc.sys.isNative) {
fontName = cc.path.join(cc.loader.resPath, resourcePath, path);
} else {
@@ -1151,10 +1155,10 @@
widget.ignoreContentAdaptWithSize(false);
var color = json["CColor"];
- if(color != null)
+ if (color != null)
widget.setTextColor(getColor(color));
- if (!widget.isIgnoreContentAdaptWithSize()){
+ if (!widget.isIgnoreContentAdaptWithSize()) {
setContentSize(widget, json["Size"]);
if (cc.sys.isNative)
widget.getVirtualRenderer().setLineBreakWithoutSpace(true);
@@ -1170,14 +1174,14 @@
* @param json
* @param resourcePath
*/
- parser.initSimpleAudio = function(json, resourcePath){
+ parser.initSimpleAudio = function (json, resourcePath) {
var node = new ccs.ComAudio();
var loop = json["Loop"] || false;
//var volume = json["Volume"] || 0;
//cc.audioEngine.setMusicVolume(volume);
node.setLoop(loop);
- loadTexture(json["FileData"], resourcePath, function(path, type){
+ loadTexture(json["FileData"], resourcePath, function (path, type) {
node.setFile(path);
});
@@ -1189,12 +1193,12 @@
* @param resourcePath
* @returns {*}
*/
- parser.initGameMap = function(json, resourcePath){
+ parser.initGameMap = function (json, resourcePath) {
var node = null;
- loadTexture(json["FileData"], resourcePath, function(path, type){
- if(type === 0)
+ loadTexture(json["FileData"], resourcePath, function (path, type) {
+ if (type === 0)
node = new cc.TMXTiledMap(path);
parser.generalAttributes(node, json);
@@ -1209,17 +1213,17 @@
* @param resourcePath
* @returns {*}
*/
- parser.initProjectNode = function(json, resourcePath){
+ parser.initProjectNode = function (json, resourcePath) {
var projectFile = json["FileData"];
- if(projectFile != null && projectFile["Path"]){
+ if (projectFile != null && projectFile["Path"]) {
var file = resourcePath + projectFile["Path"];
- if(cc.loader.getRes(file)){
+ if (cc.loader.getRes(file)) {
var obj = ccs.load(file, resourcePath);
parser.generalAttributes(obj.node, json);
- if(obj.action && obj.node){
+ if (obj.action && obj.node) {
obj.action.tag = obj.node.tag;
var InnerActionSpeed = json["InnerActionSpeed"];
- if(InnerActionSpeed !== undefined)
+ if (InnerActionSpeed !== undefined)
obj.action.setTimeSpeed(InnerActionSpeed);
obj.node.runAction(obj.action);
obj.action.gotoFrameAndPause(0);
@@ -1230,10 +1234,10 @@
}
};
- var getFileName = function(name){
- if(!name) return "";
+ var getFileName = function (name) {
+ if (!name) return "";
var arr = name.match(/([^\/]+)\.[^\/]+$/);
- if(arr && arr[1])
+ if (arr && arr[1])
return arr[1];
else
return "";
@@ -1244,7 +1248,7 @@
* @param json
* @param resourcePath
*/
- parser.initArmature = function(json, resourcePath){
+ parser.initArmature = function (json, resourcePath) {
var node = new ccs.Armature();
@@ -1254,24 +1258,24 @@
var currentAnimationName = json["CurrentAnimationName"];
- loadTexture(json["FileData"], resourcePath, function(path, type){
+ loadTexture(json["FileData"], resourcePath, function (path, type) {
var plists, pngs;
var armJson = cc.loader.getRes(path);
- if(!armJson)
+ if (!armJson)
cc.log("%s need to be preloaded", path);
- else{
+ else {
plists = armJson["config_file_path"];
pngs = armJson["config_png_path"];
- plists.forEach(function(plist, index){
- if(pngs[index])
+ plists.forEach(function (plist, index) {
+ if (pngs[index])
cc.spriteFrameCache.addSpriteFrames(plist, pngs[index]);
});
}
ccs.armatureDataManager.addArmatureFileInfo(path);
node.init(getFileName(path));
- if(isAutoPlay)
+ if (isAutoPlay)
node.getAnimation().play(currentAnimationName, -1, isLoop);
- else{
+ else {
node.getAnimation().play(currentAnimationName);
node.getAnimation().gotoAndPause(0);
}
@@ -1286,65 +1290,65 @@
return node;
};
- parser.initBoneNode = function(json, resourcePath){
+ parser.initBoneNode = function (json, resourcePath) {
var node = new ccs.BoneNode();
var length = json["Length"];
- if(length !== undefined)
+ if (length !== undefined)
node.setDebugDrawLength(length);
var blendFunc = json["BlendFunc"];
- if(blendFunc && blendFunc["Src"] !== undefined && blendFunc["Dst"] !== undefined)
+ if (blendFunc && blendFunc["Src"] !== undefined && blendFunc["Dst"] !== undefined)
node.setBlendFunc(new cc.BlendFunc(blendFunc["Src"], blendFunc["Dst"]));
parser.generalAttributes(node, json);
var color = json["CColor"];
- if(color && (color["R"] !== undefined || color["G"] !== undefined || color["B"] !== undefined))
+ if (color && (color["R"] !== undefined || color["G"] !== undefined || color["B"] !== undefined))
node.setColor(getColor(color));
return node;
};
- parser.initSkeletonNode = function(json){
+ parser.initSkeletonNode = function (json) {
var node = new ccs.SkeletonNode();
parser.generalAttributes(node, json);
var color = json["CColor"];
- if(color && (color["R"] !== undefined || color["G"] !== undefined || color["B"] !== undefined))
+ if (color && (color["R"] !== undefined || color["G"] !== undefined || color["B"] !== undefined))
node.setColor(getColor(color));
return node;
};
var loadedPlist = {};
- var loadTexture = function(json, resourcePath, cb){
- if(json != null){
+ var loadTexture = function (json, resourcePath, cb) {
+ if (json != null) {
var path = json["Path"];
var type;
- if(json["Type"] === "Default" || json["Type"] === "Normal")
+ if (json["Type"] === "Default" || json["Type"] === "Normal")
type = 0;
else
type = 1;
var plist = json["Plist"];
- if(plist){
- if(cc.loader.getRes(resourcePath + plist)){
+ if (plist) {
+ if (cc.loader.getRes(resourcePath + plist)) {
loadedPlist[resourcePath + plist] = true;
cc.spriteFrameCache.addSpriteFrames(resourcePath + plist);
- }else{
- if(!loadedPlist[resourcePath + plist] && !cc.spriteFrameCache.getSpriteFrame(path))
+ } else {
+ if (!loadedPlist[resourcePath + plist] && !cc.spriteFrameCache.getSpriteFrame(path))
cc.log("%s need to be preloaded", resourcePath + plist);
}
}
- if(type !== 0){
- if(cc.spriteFrameCache.getSpriteFrame(path))
+ if (type !== 0) {
+ if (cc.spriteFrameCache.getSpriteFrame(path))
cb(path, type);
else
cc.log("failed to get spriteFrame: %s", path);
- }else
+ } else
cb(resourcePath + path, type);
}
};
- var getColor = function(json){
- if(!json) return;
+ var getColor = function (json) {
+ if (!json) return;
var r = json["R"] != null ? json["R"] : 255;
var g = json["G"] != null ? json["G"] : 255;
var b = json["B"] != null ? json["B"] : 255;
@@ -1352,10 +1356,10 @@
return cc.color(r, g, b, a);
};
- var setContentSize = function(node, size){
+ var setContentSize = function (node, size) {
var x = size["X"] || 0;
var y = size["Y"] || 0;
- if(size)
+ if (size)
node.setContentSize(cc.size(x, y));
};
@@ -1388,8 +1392,8 @@
{name: "SkeletonNodeObjectData", handle: parser.initSkeletonNode}
];
- register.forEach(function(item){
- parser.registerParser(item.name, function(options, resourcePath){
+ register.forEach(function (item) {
+ parser.registerParser(item.name, function (options, resourcePath) {
var node = item.handle.call(this, options, resourcePath);
this.parseChild(node, options["Children"], resourcePath);
DEBUG && node && (node.__parserName = item.name);
diff --git a/extensions/cocostudio/loader/parsers/uiParser-1.x.js b/extensions/cocostudio/loader/parsers/uiParser-1.x.js
index 8c345d4128..e6904df62d 100644
--- a/extensions/cocostudio/loader/parsers/uiParser-1.x.js
+++ b/extensions/cocostudio/loader/parsers/uiParser-1.x.js
@@ -22,49 +22,120 @@
THE SOFTWARE.
****************************************************************************/
-(function(load, baseParser){
+(function (load, baseParser) {
+
+ var _stack = new Array(50);
var Parser = baseParser.extend({
- addSpriteFrame: function(textures, resourcePath){
- if(!textures) return;
+ addSpriteFrame: function (textures, resourcePath) {
+ if (!textures) return;
for (var i = 0; i < textures.length; i++) {
cc.spriteFrameCache.addSpriteFrames(resourcePath + textures[i]);
}
},
- pretreatment: function(json, resourcePath){
+ pretreatment: function (json, resourcePath) {
this.addSpriteFrame(json["textures"], resourcePath);
},
- deferred: function(json, resourcePath, node, file){
- if(node){
- ccs.actionManager.initWithDictionary(file, json["animation"], node);
- node.setContentSize(cc.size(json["designWidth"], json["designHeight"]));
+ parseRecursive: function (json, resourcePath) {
+ var index = 1;
+ var rootNode = null;
+ var parser, curr, className, options, position, anchor, anchorPP,
+ node, parent, child, children;
+ _stack[0] = json;
+ while (index > 0) {
+ index--;
+ curr = _stack[index];
+ // Avoid memory leak
+ _stack[index] = null;
+ if (!curr) continue;
+
+ // Parse node
+ className = curr["classname"];
+ parser = this.parsers[className];
+ if (!parser) {
+ cc.log("Can't find the parser : %s", className);
+ continue;
+ }
+ node = new parser.object();
+ if (!node) continue;
+ if (!rootNode) {
+ rootNode = node;
+ }
+
+ // Parse attributes
+ options = curr["options"];
+ this.generalAttributes(node, options);
+ parser.handle(node, options, resourcePath);
+ this.colorAttributes(node, options);
+
+ parent = curr.parent;
+ curr.parent = null;
+ if (parent instanceof ccui.PageView) {
+ parent.addPage(node);
+ }
+ else if (parent instanceof ccui.ListView) {
+ parent.pushBackCustomItem(node);
+ }
+ else if (parent) {
+ if (!(parent instanceof ccui.Layout)) {
+ if (node.getPositionType() === ccui.Widget.POSITION_PERCENT) {
+ position = node._positionPercent;
+ anchor = parent._anchorPoint;
+ node._positionPercent.x = position.x + anchor.x;
+ node._positionPercent.y = position.y + anchor.y;
+ }
+ anchorPP = parent._renderCmd._anchorPointInPoints;
+ node._position.x += anchorPP.x;
+ node._position.y += anchorPP.y;
+ node.setNodeDirty();
+ }
+ parent.addChild(node);
+ }
+
+ children = curr["children"];
+ if (children && children.length > 0) {
+ for (var i = children.length - 1; i >= 0; i--) {
+ _stack[index] = children[i];
+ _stack[index].parent = node;
+ index++;
+ }
+ }
}
- }
+ return rootNode;
+ },
- });
- var parser = new Parser();
+ parse: function (file, json, resourcePath) {
+ resourcePath = resourcePath || this._dirname(file);
+ this.pretreatment(json, resourcePath);
+ var node = this.parseRecursive(json["widgetTree"], resourcePath);
- parser.generalAttributes = function(widget, options){
- var ignoreSizeExsit = options["ignoreSize"];
- if(ignoreSizeExsit != null)
- widget.ignoreContentAdaptWithSize(ignoreSizeExsit);
+ node && this.deferred(json, resourcePath, node, file);
+ return node;
+ },
- if (options["sizeType"])
- {
- widget.setSizeType(options["sizeType"]);
+ deferred: function (json, resourcePath, node, file) {
+ if (node) {
+ ccs.actionManager.initWithDictionary(file, json["animation"], node);
+ node.setContentSize(json["designWidth"], json["designHeight"]);
+ }
}
- if (options["positionType"])
- {
- widget.setPositionType(options["positionType"]);
- }
+ });
+ var parser = new Parser();
- widget.setSizePercent(cc.p(options["sizePercentX"], options["sizePercentY"]));
- widget.setPositionPercent(cc.p(options["positionPercentX"], options["positionPercentY"]));
+ parser.generalAttributes = function (widget, options) {
+ widget._ignoreSize = options["ignoreSize"] || true;
+ widget._sizeType = options["sizeType"] || 0;
+ widget._positionType = options["positionType"] || 0;
+
+ widget._sizePercent.x = options["sizePercentX"] || 0;
+ widget._sizePercent.y = options["sizePercentY"] || 0;
+ widget._positionPercent.x = options["positionPercentX"] || 0;
+ widget._positionPercent.y = options["positionPercentY"] || 0;
/* adapt screen */
var w = 0, h = 0;
@@ -74,77 +145,69 @@
w = screenSize.width;
h = screenSize.height;
} else {
- w = options["width"];
- h = options["height"];
+ w = options["width"] || 0;
+ h = options["height"] || 0;
}
+
+ var anchorPointX = options["anchorPointX"];
+ var anchorPointY = options["anchorPointY"];
+
+ widget._anchorPoint.x = isNaN(anchorPointX) ? 0.5 : anchorPointX;
+ widget._anchorPoint.y = isNaN(anchorPointY) ? 0.5 : anchorPointY;
+
widget.setContentSize(w, h);
widget.setTag(options["tag"]);
widget.setActionTag(options["actiontag"]);
widget.setTouchEnabled(options["touchAble"]);
- var name = options["name"];
- var widgetName = name ? name : "default";
- widget.setName(widgetName);
-
- var x = options["x"];
- var y = options["y"];
- widget.setPosition(x, y);
-
- var sx = options["scaleX"]!=null ? options["scaleX"] : 1;
- widget.setScaleX(sx);
- var sy = options["scaleY"]!=null ? options["scaleY"] : 1;
- widget.setScaleY(sy);
+ widget._name = options["name"] || "default";
- var rt = options["rotation"] || 0;
- widget.setRotation(rt);
+ widget._position.x = options["x"] || 0;
+ widget._position.y = options["y"] || 0;
+ widget._scaleX = options["scaleX"] || 1;
+ widget._scaleY = options["scaleY"] || 1;
+ widget._rotationX = widget._rotationY = options["rotation"] || 0;
- var vb = options["visible"] || false;
- if(vb != null)
- widget.setVisible(vb);
- widget.setLocalZOrder(options["ZOrder"]);
+ widget._visible = options["visible"] || false;
+ widget._localZOrder = options["ZOrder"] || 0;
var layout = options["layoutParameter"];
- if(layout != null){
+ if (layout != null) {
var layoutParameterDic = options["layoutParameter"];
- var paramType = layoutParameterDic["type"];
+ var paramType = isNaN(layoutParameterDic["type"]) ? 2 : layoutParameterDic["type"];
var parameter = null;
- switch(paramType){
+ switch (paramType) {
case 0:
break;
case 1:
parameter = new ccui.LinearLayoutParameter();
- var gravity = layoutParameterDic["gravity"];
- parameter.setGravity(gravity);
+ parameter._linearGravity = layoutParameterDic["gravity"] || 0;
break;
case 2:
parameter = new ccui.RelativeLayoutParameter();
- var rParameter = parameter;
- var relativeName = layoutParameterDic["relativeName"];
- rParameter.setRelativeName(relativeName);
- var relativeToName = layoutParameterDic["relativeToName"];
- rParameter.setRelativeToWidgetName(relativeToName);
- var align = layoutParameterDic["align"];
- rParameter.setAlign(align);
+ parameter._relativeLayoutName = layoutParameterDic["relativeName"];
+ parameter._relativeWidgetName = layoutParameterDic["relativeToName"];
+ parameter._relativeAlign = layoutParameterDic["align"] || 0;
break;
default:
break;
}
- if(parameter != null){
- var mgl = layoutParameterDic["marginLeft"]||0;
- var mgt = layoutParameterDic["marginTop"]||0;
- var mgr = layoutParameterDic["marginRight"]||0;
- var mgb = layoutParameterDic["marginDown"]||0;
- parameter.setMargin(mgl, mgt, mgr, mgb);
+ if (parameter != null) {
+ var margin = parameter._margin;
+ margin.left = layoutParameterDic["marginLeft"] || 0;
+ margin.top = layoutParameterDic["marginTop"] || 0;
+ margin.right = layoutParameterDic["marginRight"] || 0;
+ margin.bottom = layoutParameterDic["marginDown"] || 0;
widget.setLayoutParameter(parameter);
}
}
};
- parser.colorAttributes = function(widget, options){
- var op = options["opacity"];
- if(op != null)
+ parser.colorAttributes = function (widget, options) {
+ var op = options["opacity"] !== null ? options["opacity"] : 255;
+ if (op != null)
widget.setOpacity(op);
var colorR = options["colorR"];
var colorG = options["colorG"];
@@ -155,55 +218,9 @@
widget.setFlippedY(options["flipY"]);
};
- parser.anchorPointAttributes = function(widget, options){
- var isAnchorPointXExists = options["anchorPointX"];
- var anchorPointXInFile;
- if (isAnchorPointXExists != null)
- anchorPointXInFile = options["anchorPointX"];
- else
- anchorPointXInFile = widget.getAnchorPoint().x;
-
- var isAnchorPointYExists = options["anchorPointY"];
- var anchorPointYInFile;
- if (isAnchorPointYExists != null)
- anchorPointYInFile = options["anchorPointY"];
- else
- anchorPointYInFile = widget.getAnchorPoint().y;
-
- if (isAnchorPointXExists != null || isAnchorPointYExists != null)
- widget.setAnchorPoint(cc.p(anchorPointXInFile, anchorPointYInFile));
- };
-
- parser.parseChild = function(widget, options, resourcePath){
- var children = options["children"];
- for (var i = 0; i < children.length; i++) {
- var child = this.parseNode(children[i], resourcePath);
- if(child){
- if(widget instanceof ccui.PageView)
- widget.addPage(child);
- else {
- if(widget instanceof ccui.ListView){
- widget.pushBackCustomItem(child);
- } else {
- if(!(widget instanceof ccui.Layout)) {
- if(child.getPositionType() === ccui.Widget.POSITION_PERCENT) {
- var position = child.getPositionPercent();
- var anchor = widget.getAnchorPoint();
- child.setPositionPercent(cc.p(position.x + anchor.x, position.y + anchor.y));
- }
- var AnchorPointIn = widget.getAnchorPointInPoints();
- child.setPosition(cc.p(child.getPositionX() + AnchorPointIn.x, child.getPositionY() + AnchorPointIn.y));
- }
- widget.addChild(child);
- }
- }
- }
- }
- };
-
- var getPath = function(res, type, path, cb){
- if(path){
- if(type === 0)
+ var getPath = function (res, type, path, cb) {
+ if (path) {
+ if (type === 0)
cb(res + path, type);
else
cb(path, type);
@@ -213,16 +230,16 @@
/**
* Panel parser (UILayout)
*/
- parser.LayoutAttributes = function(widget, options, resourcePath){
+ parser.LayoutAttributes = function (widget, options, resourcePath) {
var w = 0, h = 0;
var adaptScreen = options["adaptScreen"];
- if (adaptScreen){
+ if (adaptScreen) {
var screenSize = cc.director.getWinSize();
w = screenSize.width;
h = screenSize.height;
- }else{
- w = options["width"];
- h = options["height"];
+ } else {
+ w = options["width"] || 0;
+ h = options["height"] || 0;
}
widget.setSize(cc.size(w, h));
@@ -230,25 +247,25 @@
var backGroundScale9Enable = options["backGroundScale9Enable"];
widget.setBackGroundImageScale9Enabled(backGroundScale9Enable);
- var cr = options["bgColorR"];
- var cg = options["bgColorG"];
- var cb = options["bgColorB"];
+ var cr = options["bgColorR"] || 0;
+ var cg = options["bgColorG"] || 0;
+ var cb = options["bgColorB"] || 0;
- var scr = options["bgStartColorR"];
- var scg = options["bgStartColorG"];
- var scb = options["bgStartColorB"];
+ var scr = isNaN(options["bgStartColorR"]) ? 255 : options["bgStartColorR"];
+ var scg = isNaN(options["bgStartColorG"]) ? 255 : options["bgStartColorG"];
+ var scb = isNaN(options["bgStartColorB"]) ? 255 : options["bgStartColorB"];
- var ecr = options["bgEndColorR"];
- var ecg = options["bgEndColorG"];
- var ecb = options["bgEndColorB"];
+ var ecr = isNaN(options["bgEndColorR"]) ? 255 : options["bgEndColorR"];
+ var ecg = isNaN(options["bgEndColorG"]) ? 255 : options["bgEndColorG"];
+ var ecb = isNaN(options["bgEndColorB"]) ? 255 : options["bgEndColorB"];
- var bgcv1 = options["vectorX"];
- var bgcv2 = options["vectorY"];
+ var bgcv1 = options["vectorX"] || 0;
+ var bgcv2 = options["vectorY"] || 0;
widget.setBackGroundColorVector(cc.p(bgcv1, bgcv2));
- var co = options["bgColorOpacity"];
+ var co = options["bgColorOpacity"] || 0;
- var colorType = options["colorType"];
+ var colorType = options["colorType"] || 0;
widget.setBackGroundColorType(colorType/*ui.LayoutBackGroundColorType(colorType)*/);
widget.setBackGroundColor(cc.color(scr, scg, scb), cc.color(ecr, ecg, ecb));
widget.setBackGroundColor(cc.color(cr, cg, cb));
@@ -256,82 +273,82 @@
var imageFileNameDic = options["backGroundImageData"];
- if(imageFileNameDic){
- getPath(resourcePath, imageFileNameDic["resourceType"], imageFileNameDic["path"], function(path, type){
+ if (imageFileNameDic) {
+ getPath(resourcePath, imageFileNameDic["resourceType"] || 0, imageFileNameDic["path"], function (path, type) {
widget.setBackGroundImage(path, type);
});
}
- if (backGroundScale9Enable){
- var cx = options["capInsetsX"];
- var cy = options["capInsetsY"];
- var cw = options["capInsetsWidth"];
- var ch = options["capInsetsHeight"];
+ if (backGroundScale9Enable) {
+ var cx = options["capInsetsX"] || 0;
+ var cy = options["capInsetsY"] || 0;
+ var cw = isNaN(options["capInsetsWidth"]) ? 1 : options["capInsetsWidth"];
+ var ch = isNaN(options["capInsetsHeight"]) ? 1 : options["capInsetsHeight"];
widget.setBackGroundImageCapInsets(cc.rect(cx, cy, cw, ch));
}
- if (options["layoutType"])
- {
+ if (options["layoutType"]) {
widget.setLayoutType(options["layoutType"]);
}
};
/**
* Button parser (UIButton)
*/
- parser.ButtonAttributes = function(widget, options, resourcePath){
+ parser.ButtonAttributes = function (widget, options, resourcePath) {
var button = widget;
var scale9Enable = options["scale9Enable"];
button.setScale9Enabled(scale9Enable);
var normalDic = options["normalData"];
- getPath(resourcePath, normalDic["resourceType"], normalDic["path"], function(path, type){
+ getPath(resourcePath, normalDic["resourceType"] || 0, normalDic["path"], function (path, type) {
button.loadTextureNormal(path, type);
});
var pressedDic = options["pressedData"];
- getPath(resourcePath, pressedDic["resourceType"], pressedDic["path"], function(path, type){
+ getPath(resourcePath, pressedDic["resourceType"] || 0, pressedDic["path"], function (path, type) {
button.loadTexturePressed(path, type);
});
var disabledDic = options["disabledData"];
- getPath(resourcePath, disabledDic["resourceType"], disabledDic["path"], function(path, type){
+ getPath(resourcePath, disabledDic["resourceType"] || 0, disabledDic["path"], function (path, type) {
button.loadTextureDisabled(path, type);
});
if (scale9Enable) {
- var cx = options["capInsetsX"];
- var cy = options["capInsetsY"];
- var cw = options["capInsetsWidth"];
- var ch = options["capInsetsHeight"];
+ var cx = options["capInsetsX"] || 0;
+ var cy = options["capInsetsY"] || 0;
+ var cw = isNaN(options["capInsetsWidth"]) ? 1 : options["capInsetsWidth"];
+ var ch = isNaN(options["capInsetsHeight"]) ? 1 : options["capInsetsHeight"];
button.setCapInsets(cc.rect(cx, cy, cw, ch));
- var sw = options["scale9Width"];
- var sh = options["scale9Height"];
+ var sw = options["scale9Width"] || 0;
+ var sh = options["scale9Height"] || 0;
if (sw != null && sh != null)
button.setSize(cc.size(sw, sh));
}
- var text = options["text"];
- if (text != null)
+ var text = options["text"] || "";
+ if (text) {
button.setTitleText(text);
- var cr = options["textColorR"];
- var cg = options["textColorG"];
- var cb = options["textColorB"];
- var cri = cr!==null?options["textColorR"]:255;
- var cgi = cg!==null?options["textColorG"]:255;
- var cbi = cb!==null?options["textColorB"]:255;
-
- button.setTitleColor(cc.color(cri,cgi,cbi));
- var fs = options["fontSize"];
- if (fs != null)
- button.setTitleFontSize(options["fontSize"]);
- var fn = options["fontName"];
- if (fn)
- button.setTitleFontName(options["fontName"]);
+ var cr = options["textColorR"];
+ var cg = options["textColorG"];
+ var cb = options["textColorB"];
+ var cri = (cr !== null) ? options["textColorR"] : 255;
+ var cgi = (cg !== null) ? options["textColorG"] : 255;
+ var cbi = (cb !== null) ? options["textColorB"] : 255;
+
+ button.setTitleColor(cc.color(cri, cgi, cbi));
+ var fs = options["fontSize"];
+ if (fs != null)
+ button.setTitleFontSize(options["fontSize"]);
+ var fn = options["fontName"];
+ if (fn)
+ button.setTitleFontName(options["fontName"]);
+ }
};
/**
* CheckBox parser (UICheckBox)
*/
- parser.CheckBoxAttributes = function(widget, options, resourcePath){
+ parser.CheckBoxAttributes = function (widget, options, resourcePath) {
//load background image
var backGroundDic = options["backGroundBoxData"];
- getPath(resourcePath, backGroundDic["resourceType"], backGroundDic["path"], function(path, type){
+ getPath(resourcePath, backGroundDic["resourceType"] || 0, backGroundDic["path"], function (path, type) {
widget.loadTextureBackGround(path, type);
});
@@ -341,13 +358,13 @@
resourcePath,
backGroundSelectedDic["resourceType"] || backGroundDic["resourceType"],
backGroundSelectedDic["path"] || backGroundDic["path"],
- function(path, type){
- widget.loadTextureBackGroundSelected(path, type);
- });
+ function (path, type) {
+ widget.loadTextureBackGroundSelected(path, type);
+ });
//load frontCross image
var frontCrossDic = options["frontCrossData"];
- getPath(resourcePath, frontCrossDic["resourceType"], frontCrossDic["path"], function(path, type){
+ getPath(resourcePath, frontCrossDic["resourceType"] || 0, frontCrossDic["path"], function (path, type) {
widget.loadTextureFrontCross(path, type);
});
@@ -357,13 +374,13 @@
resourcePath,
backGroundDisabledDic["resourceType"] || frontCrossDic["resourceType"],
backGroundDisabledDic["path"] || frontCrossDic["path"],
- function(path, type){
- widget.loadTextureBackGroundDisabled(path, type);
- });
+ function (path, type) {
+ widget.loadTextureBackGroundDisabled(path, type);
+ });
///load frontCrossDisabledData
var frontCrossDisabledDic = options["frontCrossDisabledData"];
- getPath(resourcePath, frontCrossDisabledDic["resourceType"], frontCrossDisabledDic["path"], function(path, type){
+ getPath(resourcePath, frontCrossDisabledDic["resourceType"] || 0, frontCrossDisabledDic["path"], function (path, type) {
widget.loadTextureFrontCrossDisabled(path, type);
});
@@ -373,33 +390,32 @@
/**
* ImageView parser (UIImageView)
*/
- parser.ImageViewAttributes = function(widget, options, resourcePath){
+ parser.ImageViewAttributes = function (widget, options, resourcePath) {
var imageFileNameDic = options["fileNameData"]
- getPath(resourcePath, imageFileNameDic["resourceType"], imageFileNameDic["path"], function(path, type){
+ getPath(resourcePath, imageFileNameDic["resourceType"] || 0, imageFileNameDic["path"], function (path, type) {
widget.loadTexture(path, type);
});
var scale9EnableExist = options["scale9Enable"];
var scale9Enable = false;
- if (scale9EnableExist){
+ if (scale9EnableExist) {
scale9Enable = options["scale9Enable"];
}
widget.setScale9Enabled(scale9Enable);
- if (scale9Enable){
- var sw = options["scale9Width"];
- var sh = options["scale9Height"];
- if (sw && sh)
- {
- var swf = options["scale9Width"];
- var shf = options["scale9Height"];
+ if (scale9Enable) {
+ var sw = options["scale9Width"] || 0;
+ var sh = options["scale9Height"] || 0;
+ if (sw && sh) {
+ var swf = options["scale9Width"] || 0;
+ var shf = options["scale9Height"] || 0;
widget.setSize(cc.size(swf, shf));
}
- var cx = options["capInsetsX"];
- var cy = options["capInsetsY"];
- var cw = options["capInsetsWidth"];
- var ch = options["capInsetsHeight"];
+ var cx = options["capInsetsX"] || 0;
+ var cy = options["capInsetsY"] || 0;
+ var cw = isNaN(options["capInsetsWidth"]) ? 1 : options["capInsetsWidth"];
+ var ch = isNaN(options["capInsetsHeight"]) ? 1 : options["capInsetsHeight"];
widget.setCapInsets(cc.rect(cx, cy, cw, ch));
@@ -408,16 +424,16 @@
/**
* TextAtlas parser (UITextAtlas)
*/
- parser.TextAtlasAttributes = function(widget, options, resourcePath){
+ parser.TextAtlasAttributes = function (widget, options, resourcePath) {
var sv = options["stringValue"];
var cmf = options["charMapFileData"]; // || options["charMapFile"];
var iw = options["itemWidth"];
var ih = options["itemHeight"];
var scm = options["startCharMap"];
- if (sv != null && cmf && iw != null && ih != null && scm != null){
+ if (sv != null && cmf && iw != null && ih != null && scm != null) {
var cmftDic = options["charMapFileData"];
- var cmfType = cmftDic["resourceType"];
- switch (cmfType){
+ var cmfType = cmftDic["resourceType"] || 0;
+ switch (cmfType) {
case 0:
var tp_c = resourcePath;
var cmfPath = cmftDic["path"];
@@ -435,9 +451,9 @@
/**
* TextBMFont parser (UITextBMFont)
*/
- parser.TextBMFontAttributes = function(widget, options, resourcePath){
+ parser.TextBMFontAttributes = function (widget, options, resourcePath) {
var cmftDic = options["fileNameData"];
- var cmfType = cmftDic["resourceType"];
+ var cmfType = cmftDic["resourceType"] || 0;
switch (cmfType) {
case 0:
var tp_c = resourcePath;
@@ -452,88 +468,92 @@
break;
}
- var text = options["text"];
+ var text = options["text"] || "";
widget.setString(text);
};
/**
* Text parser (UIText)
*/
var regTTF = /\.ttf$/;
- parser.TextAttributes = function(widget, options, resourcePath){
+ parser.TextAttributes = function (widget, options, resourcePath) {
var touchScaleChangeAble = options["touchScaleEnable"];
widget.setTouchScaleChangeEnabled(touchScaleChangeAble);
- var text = options["text"];
- widget.setString(text);
+ var text = options["text"] || "";
+ if(text) {
+ widget._setString(text);
+ }
+
var fs = options["fontSize"];
- if (fs != null){
- widget.setFontSize(options["fontSize"]);
+ if (fs != null) {
+ widget._setFontSize(options["fontSize"]);
}
var fn = options["fontName"];
- if (fn != null){
- if(cc.sys.isNative){
- if(regTTF.test(fn)){
+ if (fn != null) {
+ if (cc.sys.isNative) {
+ if (regTTF.test(fn)) {
widget.setFontName(cc.path.join(cc.loader.resPath, resourcePath, fn));
- }else{
+ } else {
widget.setFontName(fn);
}
- }else{
- widget.setFontName(fn.replace(regTTF, ''));
+ } else {
+ widget._setFontName(fn.replace(regTTF, ''));
}
}
- var aw = options["areaWidth"];
- var ah = options["areaHeight"];
- if (aw != null && ah != null){
+ var aw = options["areaWidth"] || 0;
+ var ah = options["areaHeight"] || 0;
+ if (aw && ah) {
var size = cc.size(options["areaWidth"], options["areaHeight"]);
- widget.setTextAreaSize(size);
+ widget._setTextAreaSize(size);
}
- var ha = options["hAlignment"];
- if (ha != null){
- widget.setTextHorizontalAlignment(options["hAlignment"]);
+ var ha = options["hAlignment"] || 0;
+ if (ha != null) {
+ widget._setTextHorizontalAlignment(ha);
}
- var va = options["vAlignment"];
- if (va != null){
- widget.setTextVerticalAlignment(options["vAlignment"]);
+ var va = options["vAlignment"] || 0;
+ if (va != null) {
+ widget._setTextVerticalAlignment(va);
}
+ widget._updateUITextContentSize();
};
/**
* ListView parser (UIListView)
*/
- parser.ListViewAttributes = function(widget, options, resoutcePath){
- parser.ScrollViewAttributes(widget, options,resoutcePath);
- var direction = options["direction"];
+ parser.ListViewAttributes = function (widget, options, resoutcePath) {
+ parser.ScrollViewAttributes(widget, options, resoutcePath);
+ var direction = options["direction"] || 1;
widget.setDirection(direction);
- var gravity = options["gravity"];
+ var gravity = options["gravity"] || 0;
widget.setGravity(gravity);
- var itemMargin = options["itemMargin"];
+ var itemMargin = options["itemMargin"] || 0;
widget.setItemsMargin(itemMargin);
};
/**
* LoadingBar parser (UILoadingBar)
*/
- parser.LoadingBarAttributes = function(widget, options, resourcePath){
+ parser.LoadingBarAttributes = function (widget, options, resourcePath) {
var imageFileNameDic = options["textureData"];
- getPath(resourcePath, imageFileNameDic["resourceType"], imageFileNameDic["path"], function(path, type){
+ getPath(resourcePath, imageFileNameDic["resourceType"] || 0, imageFileNameDic["path"], function (path, type) {
widget.loadTexture(path, type);
});
var scale9Enable = options["scale9Enable"];
widget.setScale9Enabled(scale9Enable);
- if (scale9Enable){
- var cx = options["capInsetsX"];
- var cy = options["capInsetsY"];
- var cw = options["capInsetsWidth"];
- var ch = options["capInsetsHeight"];
+ if (scale9Enable) {
+ var cx = options["capInsetsX"] || 0;
+ var cy = options["capInsetsY"] || 0;
+ var cw = isNaN(options["capInsetsWidth"]) ? 1 : options["capInsetsWidth"];
+ var ch = isNaN(options["capInsetsHeight"]) ? 1 : options["capInsetsHeight"];
widget.setCapInsets(cc.rect(cx, cy, cw, ch));
- var width = options["width"];
- var height = options["height"];
+ var width = options["width"] || 0;
+ var height = options["height"] || 0;
widget.setSize(cc.size(width, height));
}
- widget.setDirection(options["direction"]);
- widget.setPercent(options["percent"]);
+ widget.setDirection(options["direction"] || 0);
+ widget.setPercent(options["percent"] || 0);
};
/**
* PageView parser (UIPageView)
@@ -542,20 +562,20 @@
/**
* ScrollView parser (UIScrollView)
*/
- parser.ScrollViewAttributes = function(widget, options, resoutcePath){
- parser.LayoutAttributes(widget, options,resoutcePath);
- var innerWidth = options["innerWidth"]!=null ? options["innerWidth"] : 200;
- var innerHeight = options["innerHeight"]!=null ? options["innerHeight"] : 200;
+ parser.ScrollViewAttributes = function (widget, options, resoutcePath) {
+ parser.LayoutAttributes(widget, options, resoutcePath);
+ var innerWidth = options["innerWidth"] != null ? options["innerWidth"] : 200;
+ var innerHeight = options["innerHeight"] != null ? options["innerHeight"] : 200;
widget.setInnerContainerSize(cc.size(innerWidth, innerHeight));
- var direction = options["direction"]!=null ? options["direction"] : 1;
+ var direction = options["direction"] != null ? options["direction"] : 1;
widget.setDirection(direction);
widget.setBounceEnabled(options["bounceEnable"]);
};
/**
* Slider parser (UISlider)
*/
- parser.SliderAttributes = function(widget, options, resourcePath){
+ parser.SliderAttributes = function (widget, options, resourcePath) {
var slider = widget;
@@ -565,24 +585,24 @@
var barLength = options["length"];
var imageFileNameDic = options["barFileNameData"];
- var imageFileType = imageFileNameDic["resourceType"];
+ var imageFileType = imageFileNameDic["resourceType"] || 0;
var imageFileName = imageFileNameDic["path"];
- if(bt != null){
- if(barTextureScale9Enable){
- getPath(resourcePath, imageFileType, imageFileName, function(path, type){
+ if (bt != null) {
+ if (barTextureScale9Enable) {
+ getPath(resourcePath, imageFileType, imageFileName, function (path, type) {
slider.loadBarTexture(path, type);
});
slider.setSize(cc.size(barLength, slider.getContentSize().height));
}
- }else{
- getPath(resourcePath, imageFileType, imageFileName, function(path, type){
+ } else {
+ getPath(resourcePath, imageFileType, imageFileName, function (path, type) {
slider.loadBarTexture(path, type);
});
}
var normalDic = options["ballNormalData"];
- getPath(resourcePath, normalDic["resourceType"], normalDic["path"], function(path, type){
+ getPath(resourcePath, normalDic["resourceType"] || 0, normalDic["path"], function (path, type) {
slider.loadSlidBallTextureNormal(path, type);
});
@@ -591,115 +611,100 @@
resourcePath,
pressedDic["resourceType"] || normalDic["resourceType"],
pressedDic["path"] || normalDic["path"],
- function(path, type){
+ function (path, type) {
slider.loadSlidBallTexturePressed(path, type);
- });
+ });
var disabledDic = options["ballDisabledData"];
- getPath(resourcePath, disabledDic["resourceType"], disabledDic["path"], function(path, type){
+ getPath(resourcePath, disabledDic["resourceType"] || 0, disabledDic["path"], function (path, type) {
slider.loadSlidBallTextureDisabled(path, type);
});
var progressBarDic = options["progressBarData"];
- getPath(resourcePath, progressBarDic["resourceType"], progressBarDic["path"], function(path, type){
+ getPath(resourcePath, progressBarDic["resourceType"] || 0, progressBarDic["path"], function (path, type) {
slider.loadProgressBarTexture(path, type);
});
};
/**
* TextField parser (UITextField)
*/
- parser.TextFieldAttributes = function(widget, options, resourcePath){
- var ph = options["placeHolder"];
- if(ph)
+ parser.TextFieldAttributes = function (widget, options, resourcePath) {
+ var ph = options["placeHolder"] || "";
+ if (ph)
widget.setPlaceHolder(ph);
- widget.setString(options["text"]||"");
+ widget.setString(options["text"] || "");
var fs = options["fontSize"];
- if(fs)
+ if (fs)
widget.setFontSize(fs);
var fn = options["fontName"];
- if (fn != null){
- if(cc.sys.isNative){
- if(regTTF.test(fn)){
+ if (fn != null) {
+ if (cc.sys.isNative) {
+ if (regTTF.test(fn)) {
widget.setFontName(cc.path.join(cc.loader.resPath, resourcePath, fn));
- }else{
+ } else {
widget.setFontName(fn);
}
- }else{
+ } else {
widget.setFontName(fn.replace(regTTF, ''));
}
}
- var tsw = options["touchSizeWidth"];
- var tsh = options["touchSizeHeight"];
- if(tsw!=null && tsh!=null)
+ var tsw = options["touchSizeWidth"] || 0;
+ var tsh = options["touchSizeHeight"] || 0;
+ if (tsw != null && tsh != null)
widget.setTouchSize(tsw, tsh);
- var dw = options["width"];
- var dh = options["height"];
- if(dw > 0 || dh > 0){
+ var dw = options["width"] || 0;
+ var dh = options["height"] || 0;
+ if (dw > 0 || dh > 0) {
//textField.setSize(cc.size(dw, dh));
}
var maxLengthEnable = options["maxLengthEnable"];
widget.setMaxLengthEnabled(maxLengthEnable);
- if(maxLengthEnable){
+ if (maxLengthEnable) {
var maxLength = options["maxLength"];
widget.setMaxLength(maxLength);
}
var passwordEnable = options["passwordEnable"];
widget.setPasswordEnabled(passwordEnable);
- if(passwordEnable)
+ if (passwordEnable)
widget.setPasswordStyleText(options["passwordStyleText"]);
- var aw = options["areaWidth"];
- var ah = options["areaHeight"];
- if(aw && ah){
+ var aw = options["areaWidth"] || 0;
+ var ah = options["areaHeight"] || 0;
+ if (aw && ah) {
var size = cc.size(aw, ah);
widget.setTextAreaSize(size);
}
- var ha = options["hAlignment"];
- if(ha)
+ var ha = options["hAlignment"] || 0;
+ if (ha)
widget.setTextHorizontalAlignment(ha);
- var va = options["vAlignment"];
- if(va)
+ var va = options["vAlignment"] || 0;
+ if (va)
widget.setTextVerticalAlignment(va);
- var r = options["colorR"];
- var g = options["colorG"];
- var b = options["colorB"];
- if (r !== undefined && g !== undefined && b !== undefined) {
- widget.setTextColor(cc.color(r, g, b));
- }
+ var r = isNaN(options["colorR"]) ? 255 : options["colorR"];
+ var g = isNaN(options["colorG"]) ? 255 : options["colorG"];
+ var b = isNaN(options["colorB"]) ? 255 : options["colorB"];
+ widget.setTextColor(cc.color(r, g, b));
};
- var register = [
- {name: "Panel", object: ccui.Layout, handle: parser.LayoutAttributes},
- {name: "Button", object: ccui.Button, handle: parser.ButtonAttributes},
- {name: "CheckBox", object: ccui.CheckBox, handle: parser.CheckBoxAttributes},
- {name: "ImageView", object: ccui.ImageView, handle: parser.ImageViewAttributes},
- {name: "LabelAtlas", object: ccui.TextAtlas, handle: parser.TextAtlasAttributes},
- {name: "LabelBMFont", object: ccui.TextBMFont, handle: parser.TextBMFontAttributes},
- {name: "Label", object: ccui.Text, handle: parser.TextAttributes},
- {name: "ListView", object: ccui.ListView, handle: parser.ListViewAttributes},
- {name: "LoadingBar", object: ccui.LoadingBar, handle: parser.LoadingBarAttributes},
- {name: "PageView", object: ccui.PageView, handle: parser.PageViewAttributes},
- {name: "ScrollView", object: ccui.ScrollView, handle: parser.ScrollViewAttributes},
- {name: "Slider", object: ccui.Slider, handle: parser.SliderAttributes},
- {name: "TextField", object: ccui.TextField, handle: parser.TextFieldAttributes}
- ];
-
- register.forEach(function(item){
- parser.registerParser(item.name, function(options, resourcePath){
- var widget = new item.object;
- var uiOptions = options["options"];
- parser.generalAttributes(widget, uiOptions);
- item.handle(widget, uiOptions, resourcePath);
- parser.colorAttributes(widget, uiOptions);
- parser.anchorPointAttributes(widget, uiOptions);
- parser.parseChild.call(this, widget, options, resourcePath);
- return widget;
- });
- });
+ parser.parsers = {
+ "Panel": {object: ccui.Layout, handle: parser.LayoutAttributes},
+ "Button": {object: ccui.Button, handle: parser.ButtonAttributes},
+ "CheckBox": {object: ccui.CheckBox, handle: parser.CheckBoxAttributes},
+ "ImageView": {object: ccui.ImageView, handle: parser.ImageViewAttributes},
+ "LabelAtlas": {object: ccui.TextAtlas, handle: parser.TextAtlasAttributes},
+ "LabelBMFont": {object: ccui.TextBMFont, handle: parser.TextBMFontAttributes},
+ "Label": {object: ccui.Text, handle: parser.TextAttributes},
+ "ListView": {object: ccui.ListView, handle: parser.ListViewAttributes},
+ "LoadingBar": {object: ccui.LoadingBar, handle: parser.LoadingBarAttributes},
+ "PageView": {object: ccui.PageView, handle: parser.PageViewAttributes},
+ "ScrollView": {object: ccui.ScrollView, handle: parser.ScrollViewAttributes},
+ "Slider": {object: ccui.Slider, handle: parser.SliderAttributes},
+ "TextField": {object: ccui.TextField, handle: parser.TextFieldAttributes}
+ };
load.registerParser("ccui", "*", parser);
-})(ccs._load, ccs._parser);
\ No newline at end of file
+})(ccs._load, ccs._parser);
diff --git a/extensions/cocostudio/timeline/ActionTimeline.js b/extensions/cocostudio/timeline/ActionTimeline.js
index cdf57b58dc..fd899ae120 100644
--- a/extensions/cocostudio/timeline/ActionTimeline.js
+++ b/extensions/cocostudio/timeline/ActionTimeline.js
@@ -34,11 +34,11 @@ ccs.ActionTimelineData = ccs.Class.extend({
_actionTag: 0,
- ctor: function(actionTag){
+ ctor: function (actionTag) {
this._init(actionTag);
},
- _init: function(actionTag){
+ _init: function (actionTag) {
this._actionTag = actionTag;
return true;
},
@@ -47,20 +47,20 @@ ccs.ActionTimelineData = ccs.Class.extend({
* Set the action tag.
* @param {number} actionTag
*/
- setActionTag: function(actionTag){
+ setActionTag: function (actionTag) {
this._actionTag = actionTag;
},
/**
* Gets the action tag.
*/
- getActionTag: function(){
+ getActionTag: function () {
return this._actionTag;
}
});
-ccs.AnimationInfo = function(name, start, end){
+ccs.AnimationInfo = function (name, start, end) {
this.name = name;
this.startIndex = start;
this.endIndex = end;
@@ -110,7 +110,7 @@ ccs.ComExtensionData.create = function(){
* @param actionTag
* @returns {ccs.ActionTimelineData}
*/
-ccs.ActionTimelineData.create = function(actionTag){
+ccs.ActionTimelineData.create = function (actionTag) {
return new ccs.ActionTimelineData(actionTag);
};
@@ -130,7 +130,7 @@ ccs.ActionTimeline = cc.Action.extend({
_duration: 0,
_time: null,
_timeSpeed: 1,
- _frameInternal: 1/60,
+ _frameInternal: 1 / 60,
_playing: false,
_currentFrame: 0,
_startFrame: 0,
@@ -140,7 +140,7 @@ ccs.ActionTimeline = cc.Action.extend({
_animationInfos: null,
_lastFrameListener: null,
- ctor: function(){
+ ctor: function () {
cc.Action.prototype.ctor.call(this);
this._timelineMap = {};
this._timelineList = [];
@@ -148,29 +148,28 @@ ccs.ActionTimeline = cc.Action.extend({
this.init();
},
- _gotoFrame: function(frameIndex){
+ _gotoFrame: function (frameIndex) {
var size = this._timelineList.length;
- for(var i = 0; i < size; i++)
- {
+ for (var i = 0; i < size; i++) {
this._timelineList[i]._gotoFrame(frameIndex);
}
},
- _stepToFrame: function(frameIndex){
+ _stepToFrame: function (frameIndex) {
var size = this._timelineList.length;
- for(var i = 0; i < size; i++){
+ for (var i = 0; i < size; i++) {
this._timelineList[i]._stepToFrame(frameIndex);
}
},
//emit frame event, call it when enter a frame
- _emitFrameEvent: function(frame){
- if(this._frameEventListener){
+ _emitFrameEvent: function (frame) {
+ if (this._frameEventListener) {
this._frameEventListener(frame);
}
},
- init: function(){
+ init: function () {
return true;
},
@@ -181,23 +180,23 @@ ccs.ActionTimeline = cc.Action.extend({
* @param [currentFrameIndex=] set current frame index.
* @param [loop=] Whether or not the animation need loop.
*/
- gotoFrameAndPlay: function(startIndex, endIndex, currentFrameIndex, loop){
+ gotoFrameAndPlay: function (startIndex, endIndex, currentFrameIndex, loop) {
//Consolidation parameters
var i = 0,
argLen = arguments.length;
var num = [],
bool;
- for(i; i= this._startFrame && frameIndex <= this._endFrame){
+ setCurrentFrame: function (frameIndex) {
+ if (frameIndex >= this._startFrame && frameIndex <= this._endFrame) {
this._currentFrame = frameIndex;
this._time = this._currentFrame * this._frameInternal;
- }else{
+ } else {
cc.log("frame index is not between start frame and end frame");
}
@@ -309,7 +308,7 @@ ccs.ActionTimeline = cc.Action.extend({
* Get current frame.
* @returns {number}
*/
- getCurrentFrame: function(){
+ getCurrentFrame: function () {
return this._currentFrame;
},
@@ -317,7 +316,7 @@ ccs.ActionTimeline = cc.Action.extend({
* add Timeline to ActionTimeline
* @param {ccs.Timeline} timeline
*/
- addTimeline: function(timeline){
+ addTimeline: function (timeline) {
var tag = timeline.getActionTag();
if (!this._timelineMap[tag]) {
this._timelineMap[tag] = [];
@@ -335,13 +334,13 @@ ccs.ActionTimeline = cc.Action.extend({
* remove Timeline to ActionTimeline
* @param {ccs.Timeline} timeline
*/
- removeTimeline: function(timeline){
+ removeTimeline: function (timeline) {
var tag = timeline.getActionTag();
if (this._timelineMap[tag]) {
- if(this._timelineMap[tag].some(function(item){
- if(item === timeline)
- return true;
- })) {
+ if (this._timelineMap[tag].some(function (item) {
+ if (item === timeline)
+ return true;
+ })) {
cc.arrayRemoveObject(this._timelineMap[tag], timeline);
cc.arrayRemoveObject(this._timelineList, timeline);
timeline.setActionTimeline(null);
@@ -353,7 +352,7 @@ ccs.ActionTimeline = cc.Action.extend({
* Gets the timeline list
* @returns {array | null}
*/
- getTimelines: function(){
+ getTimelines: function () {
return this._timelineList;
},
@@ -361,14 +360,14 @@ ccs.ActionTimeline = cc.Action.extend({
* Set the Frame event
* @param {function} listener
*/
- setFrameEventCallFunc: function(listener){
+ setFrameEventCallFunc: function (listener) {
this._frameEventListener = listener;
},
/**
* remove event
*/
- clearFrameEventCallFunc: function(){
+ clearFrameEventCallFunc: function () {
this._frameEventListener = null;
},
@@ -376,15 +375,14 @@ ccs.ActionTimeline = cc.Action.extend({
* Clone this timeline
* @returns {ccs.ActionTimeline}
*/
- clone: function(){
+ clone: function () {
var newAction = new ccs.ActionTimeline();
newAction.setDuration(this._duration);
newAction.setTimeSpeed(this._timeSpeed);
- for (var a in this._timelineMap){
+ for (var a in this._timelineMap) {
var timelines = this._timelineMap[a];
- for(var b in timelines)
- {
+ for (var b in timelines) {
var timeline = timelines[b];
var newTimeline = timeline.clone();
newAction.addTimeline(newTimeline);
@@ -399,7 +397,7 @@ ccs.ActionTimeline = cc.Action.extend({
* Reverse is not defined;
* @returns {null}
*/
- reverse: function(){
+ reverse: function () {
return null;
},
@@ -407,42 +405,40 @@ ccs.ActionTimeline = cc.Action.extend({
* Stepping of this time line.
* @param {number} delta
*/
- step: function(delta){
- if (!this._playing || this._timelineMap.length === 0 || this._duration === 0)
- {
+ step: function (delta) {
+ if (!this._playing || this._timelineMap.length === 0 || this._duration === 0) {
return;
}
this._time += delta * this._timeSpeed;
var endoffset = this._time - this._endFrame * this._frameInternal;
- if(endoffset < this._frameInternal){
+ if (endoffset < this._frameInternal) {
this._currentFrame = Math.floor(this._time / this._frameInternal);
this._stepToFrame(this._currentFrame);
- if(endoffset >= 0 && this._lastFrameListener)
+ if (endoffset >= 0 && this._lastFrameListener)
this._lastFrameListener();
- }else{
+ } else {
this._playing = this._loop;
- if(!this._playing){
+ if (!this._playing) {
this._time = this._endFrame * this._frameInternal;
- if (this._currentFrame != this._endFrame){
+ if (this._currentFrame != this._endFrame) {
this._currentFrame = this._endFrame;
this._stepToFrame(this._currentFrame);
- if(this._lastFrameListener)
+ if (this._lastFrameListener)
this._lastFrameListener();
}
- }else
+ } else
this.gotoFrameAndPlay(this._startFrame, this._endFrame, this._loop);
}
},
- _foreachNodeDescendant: function(parent, callback){
+ _foreachNodeDescendant: function (parent, callback) {
callback(parent);
var children = parent.getChildren();
- for (var i=0; i 0){
+ while (boneStack.length > 0) {
var top = boneStack.pop();
var topCmd = top._renderCmd;
topCmd._syncStatus(topCmd.getParentRenderCmd());
@@ -205,7 +209,7 @@ ccs.SkeletonNode = (function(){
var topChildren = top.getChildBones();
- for (var childbone, i=0; i= this._frames[0].getFrameIndex())
+ do {
+ if (frameIndex < this._frames[0].getFrameIndex()) {
+ if (this._currentKeyFrameIndex >= this._frames[0].getFrameIndex())
needEnterFrame = true;
this._fromIndex = 0;
@@ -211,7 +209,7 @@ ccs.Timeline = ccs.Class.extend({
this._currentKeyFrameIndex = 0;
this._betweenDuration = this._frames[0].getFrameIndex();
break;
- }else if(frameIndex >= this._frames[length - 1].getFrameIndex()){
+ } else if (frameIndex >= this._frames[length - 1].getFrameIndex()) {
this._fromIndex = length - 1;
this._toIndex = 0;
@@ -225,14 +223,13 @@ ccs.Timeline = ccs.Class.extend({
var low = 0,
high = length - 1,
mid = 0;
- while(low <= high){
- mid = Math.ceil(( low + high )/2);
- if(frameIndex >= this._frames[mid].getFrameIndex() && frameIndex < this._frames[mid + 1].getFrameIndex())
- {
+ while (low <= high) {
+ mid = Math.ceil(( low + high ) / 2);
+ if (frameIndex >= this._frames[mid].getFrameIndex() && frameIndex < this._frames[mid + 1].getFrameIndex()) {
target = mid;
break;
}
- if(this._frames[mid].getFrameIndex()>frameIndex)
+ if (this._frames[mid].getFrameIndex() > frameIndex)
high = mid - 1;
else
low = mid + 1;
@@ -240,37 +237,36 @@ ccs.Timeline = ccs.Class.extend({
this._fromIndex = target;
- if(length > 1)
+ if (length > 1)
this._toIndex = (target + 1) | 0;
else
this._toIndex = (target) | 0;
from = this._frames[this._fromIndex];
- to = this._frames[this._toIndex];
+ to = this._frames[this._toIndex];
from = this._frames[target];
- to = this._frames[target+1];
+ to = this._frames[target + 1];
- if(target === 0 && this._currentKeyFrameIndex < from.getFrameIndex())
+ if (target === 0 && this._currentKeyFrameIndex < from.getFrameIndex())
needEnterFrame = true;
this._currentKeyFrameIndex = from.getFrameIndex();
this._betweenDuration = to.getFrameIndex() - from.getFrameIndex();
} while (0);
- if(needEnterFrame || this._currentKeyFrame != from) {
+ if (needEnterFrame || this._currentKeyFrame != from) {
this._currentKeyFrame = from;
this._currentKeyFrame.onEnter(to);
}
},
- _updateCurrentKeyFrame: function(frameIndex){
- if(frameIndex > 60)
+ _updateCurrentKeyFrame: function (frameIndex) {
+ if (frameIndex > 60)
var a = 0;
//! If play to current frame's front or back, then find current frame again
- if (frameIndex < this._currentKeyFrameIndex || frameIndex >= this._currentKeyFrameIndex + this._betweenDuration)
- {
+ if (frameIndex < this._currentKeyFrameIndex || frameIndex >= this._currentKeyFrameIndex + this._betweenDuration) {
var from = null;
var to = null;
@@ -278,29 +274,26 @@ ccs.Timeline = ccs.Class.extend({
{
var length = this._frames.length;
- if (frameIndex < this._frames[0].getFrameIndex())
- {
+ if (frameIndex < this._frames[0].getFrameIndex()) {
from = to = this._frames[0];
this._currentKeyFrameIndex = 0;
this._betweenDuration = this._frames[0].getFrameIndex();
break;
}
- else if(frameIndex >= this._frames[length - 1].getFrameIndex())
- {
+ else if (frameIndex >= this._frames[length - 1].getFrameIndex()) {
var lastFrameIndex = this._frames[length - 1].getFrameIndex();
- if(this._currentKeyFrameIndex >= lastFrameIndex)
+ if (this._currentKeyFrameIndex >= lastFrameIndex)
return;
frameIndex = lastFrameIndex;
}
- do{
+ do {
this._fromIndex = this._toIndex;
from = this._frames[this._fromIndex];
- this._currentKeyFrameIndex = from.getFrameIndex();
+ this._currentKeyFrameIndex = from.getFrameIndex();
this._toIndex = this._fromIndex + 1;
- if (this._toIndex >= length)
- {
+ if (this._toIndex >= length) {
this._toIndex = 0;
}
@@ -308,11 +301,11 @@ ccs.Timeline = ccs.Class.extend({
if (frameIndex === from.getFrameIndex())
break;
- if(frameIndex > from.getFrameIndex() && frameIndex < to.getFrameIndex())
+ if (frameIndex > from.getFrameIndex() && frameIndex < to.getFrameIndex())
break;
- if(from.isEnterWhenPassed())
+ if (from.isEnterWhenPassed())
from.onEnter(to);
- }while (true);
+ } while (true);
this._betweenDuration = to.getFrameIndex() - from.getFrameIndex();
@@ -331,6 +324,6 @@ ccs.Timeline = ccs.Class.extend({
* @deprecated v3.0, please use new ccs.Timeline() instead.
* @returns {ccs.Timeline}
*/
-ccs.Timeline.create = function(){
+ccs.Timeline.create = function () {
return new ccs.Timeline();
-};
\ No newline at end of file
+};
diff --git a/extensions/editbox/CCEditBox.js b/extensions/editbox/CCEditBox.js
index c928dba439..3a535438f2 100644
--- a/extensions/editbox/CCEditBox.js
+++ b/extensions/editbox/CCEditBox.js
@@ -1,7 +1,7 @@
/****************************************************************************
- Copyright (c) 2011-2012 cocos2d-x.org
- Copyright (c) 2013-2014 Chukong Technologies Inc.
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2012 James Chen
+ Copyright (c) 2011-2012 cocos2d-x.org
http://www.cocos2d-x.org
@@ -180,12 +180,13 @@ cc.EditBoxDelegate = cc.Class.extend({
}
});
+
/**
*
cc.EditBox is a brief Class for edit box.
* You can use this widget to gather small amounts of text from the user.
*
* @class
- * @extends cc.ControlButton
+ * @extends cc.Node
*
* @property {String} string - Content string of edit box
* @property {String} maxLength - Max length of the content string
@@ -204,36 +205,22 @@ cc.EditBoxDelegate = cc.Class.extend({
* @property {Number} returnType - <@writeonly> Return type of edit box, value should be one of the KeyboardReturnType constants.
*
*/
-cc.EditBox = cc.ControlButton.extend({
- _domInputSprite: null,
-
+cc.EditBox = cc.Node.extend({
+ _backgroundSprite: null,
_delegate: null,
_editBoxInputMode: cc.EDITBOX_INPUT_MODE_ANY,
_editBoxInputFlag: cc.EDITBOX_INPUT_FLAG_SENSITIVE,
_keyboardReturnType: cc.KEYBOARD_RETURNTYPE_DEFAULT,
-
- _text: "",
- _placeholderText: "",
- _textColor: null,
- _placeholderColor: null,
_maxLength: 50,
- _adjustHeight: 18,
-
- _edTxt: null,
- _edFontSize: 14,
- _edFontName: "Arial",
-
- _placeholderFontName: "",
+ _text: '',
+ _textColor: null,
+ _placeholderText: '',
+ _placeholderFontName: '',
_placeholderFontSize: 14,
-
- _tooltip: false,
- _className: "EditBox",
-
- _onCanvasClick : null,
- _inputEvent : null,
- _keyPressEvent : null,
- _focusEvent : null,
- _blurEvent : null,
+ _placeholderColor: null,
+ _className: 'EditBox',
+ _touchListener: null,
+ _touchEnabled: true,
/**
* constructor of cc.EditBox
@@ -242,215 +229,229 @@ cc.EditBox = cc.ControlButton.extend({
* @param {cc.Scale9Sprite} press9SpriteBg
* @param {cc.Scale9Sprite} disabled9SpriteBg
*/
- ctor: function (size, normal9SpriteBg, press9SpriteBg, disabled9SpriteBg) {
- cc.ControlButton.prototype.ctor.call(this);
+ ctor: function (size, normal9SpriteBg) {
+ cc.Node.prototype.ctor.call(this);
+ this._anchorPoint = cc.p(0.5, 0.5);
this._textColor = cc.color.WHITE;
this._placeholderColor = cc.color.GRAY;
- this.setContentSize(size);
- var tmpDOMSprite = this._domInputSprite = new cc.Sprite();
- tmpDOMSprite.draw = function () {}; //redefine draw function
- this.addChild(tmpDOMSprite);
- var tmpEdTxt = this._edTxt = document.createElement("input");
- tmpEdTxt.type = "text";
- tmpEdTxt.style.fontSize = this._edFontSize + "px";
- tmpEdTxt.style.color = "#000000";
- tmpEdTxt.style.border = 0;
- tmpEdTxt.style.background = "transparent";
- //tmpEdTxt.style.paddingLeft = "2px";
- tmpEdTxt.style.width = "100%";
- tmpEdTxt.style.height = "100%";
- tmpEdTxt.style.active = 0;
- tmpEdTxt.style.outline = "medium";
- tmpEdTxt.style.padding = "0";
- this.__fullscreen = false;
- var onCanvasClick = function() { this._edTxt.blur();};
- this._onCanvasClick = onCanvasClick.bind(this);
-
- var inputEvent = function () {
- if (this._delegate && this._delegate.editBoxTextChanged)
- this._delegate.editBoxTextChanged(this, this._edTxt.value);
- };
- this._inputEvent = inputEvent.bind(this);
- var keypressEvent = function ( e ) {
- if (e.keyCode === cc.KEY.enter) {
- e.stopPropagation();
- e.preventDefault();
- if (this._delegate && this._delegate.editBoxReturn)
- this._delegate.editBoxReturn(this);
- cc._canvas.focus();
- }
- };
- this._keyPressEvent = keypressEvent.bind(this);
- var focusEvent = function () {
- // Exit fullscreen
- if(cc.view.isAutoFullScreenEnabled()) {
- this.__fullscreen = true;
- cc.view.enableAutoFullScreen(false);
- cc.screen.exitFullScreen();
- } else {
- this.__fullscreen = false;
- }
+ this._renderCmd._createLabels();
+ this.createDomElementIfNeeded();
+ this.initWithSizeAndBackgroundSprite(size, normal9SpriteBg);
- if (this._edTxt.value === this._placeholderText) {
- this._edTxt.value = "";
- this._edTxt.style.fontSize = this._edFontSize + "px";
- this._edTxt.style.color = cc.colorToHex(this._textColor);
- if (this._editBoxInputFlag === cc.EDITBOX_INPUT_FLAG_PASSWORD)
- this._edTxt.type = "password";
- else
- this._edTxt.type = "text";
- }
- if (this._delegate && this._delegate.editBoxEditingDidBegin)
- this._delegate.editBoxEditingDidBegin(this);
- cc._canvas.addEventListener("click", this._onCanvasClick);
- };
- this._focusEvent = focusEvent.bind(this);
- var blurEvent = function () {
- // Resume fullscreen logic
- if(this.__fullscreen) {
- cc.view.enableAutoFullScreen(true);
- }
+ this._touchListener = cc.EventListener.create({
+ event: cc.EventListener.TOUCH_ONE_BY_ONE,
+ swallowTouches: true,
+ onTouchBegan: this._onTouchBegan.bind(this),
+ onTouchEnded: this._onTouchEnded.bind(this)
+ });
+ cc.eventManager.addListener(this._touchListener, this);
- if (this._edTxt.value === "") {
- this._edTxt.value = this._placeholderText;
- this._edTxt.style.fontSize = this._placeholderFontSize + "px";
- this._edTxt.style.color = cc.colorToHex(this._placeholderColor);
- this._edTxt.type = "text";
- }
- if (this._delegate && this._delegate.editBoxEditingDidEnd)
- this._delegate.editBoxEditingDidEnd(this);
- cc._canvas.removeEventListener('click', this._onCanvasClick);
- };
- this._blurEvent = blurEvent.bind(this);
+ this.setInputFlag(this._editBoxInputFlag);
+ },
+
+ setTouchEnabled: function (enable) {
+ if (this._touchEnabled === enable) {
+ return;
+ }
+ this._touchEnabled = enable;
+ if (this._touchEnabled) {
+ cc.eventManager.addListener(this._touchListener, this);
+ } else {
+ cc.eventManager.removeListener(this._touchListener);
+ }
+ },
- tmpEdTxt.addEventListener("input", this._inputEvent);
- tmpEdTxt.addEventListener("keypress", this._keyPressEvent);
- tmpEdTxt.addEventListener("focus", this._focusEvent);
- tmpEdTxt.addEventListener("blur", this._blurEvent);
+ _createRenderCmd: function () {
+ if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
+ return new cc.EditBox.CanvasRenderCmd(this);
+ } else {
+ return new cc.EditBox.WebGLRenderCmd(this);
+ }
+ },
- cc.DOM.convert(tmpDOMSprite);
- tmpDOMSprite.dom.appendChild(tmpEdTxt);
- tmpDOMSprite.dom.showTooltipDiv = false;
- tmpDOMSprite.dom.style.width = (size.width - 6) + "px";
- tmpDOMSprite.dom.style.height = (size.height - 6) + "px";
+ setContentSize: function (width, height) {
+ if (width.width !== undefined && width.height !== undefined) {
+ height = width.height;
+ width = width.width;
+ }
+ cc.Node.prototype.setContentSize.call(this, width, height);
+ this._updateEditBoxSize(width, height);
+ },
+
+ setVisible: function (visible) {
+ cc.Node.prototype.setVisible.call(this, visible);
+ this._renderCmd.updateVisibility();
+ },
+
+ createDomElementIfNeeded: function () {
+ if (!this._renderCmd._edTxt) {
+ this._renderCmd._createDomTextArea();
+ }
+ },
+
+ setTabIndex: function (index) {
+ if (this._renderCmd._edTxt) {
+ this._renderCmd._edTxt.tabIndex = index;
+ }
+ },
+
+ getTabIndex: function () {
+ if (this._renderCmd._edTxt) {
+ return this._renderCmd._edTxt.tabIndex;
+ }
+ cc.warn('The dom control is not created!');
+ return -1;
+ },
+
+ setFocus: function () {
+ if (this._renderCmd._edTxt) {
+ this._renderCmd._edTxt.focus();
+ }
+ },
+
+ isFocused: function () {
+ if (this._renderCmd._edTxt) {
+ return document.activeElement === this._renderCmd._edTxt;
+ }
+ cc.warn('The dom control is not created!');
+ return false;
+ },
+
+ stayOnTop: function (flag) {
+ if (this._alwaysOnTop === flag) return;
+
+ this._alwaysOnTop = flag;
+ this._renderCmd.stayOnTop(this._alwaysOnTop);
+ },
+
+ cleanup: function () {
+ this._super();
+
+ this._renderCmd._removeDomFromGameContainer();
+ },
+
+ _isAncestorsVisible: function (node) {
+ if (null == node)
+ return true;
+
+ var parent = node.getParent();
+
+ if (parent && !parent.isVisible())
+ return false;
+ return this._isAncestorsVisible(parent);
+ },
+
+ _onTouchBegan: function (touch) {
+ if (!this.isVisible() || !this._isAncestorsVisible(this)) {
+ return;
+ }
+ var touchPoint = touch.getLocation();
+ var bb = cc.rect(0, 0, this._contentSize.width, this._contentSize.height);
+ var hitted = cc.rectContainsPoint(bb, this.convertToNodeSpace(touchPoint));
+ if (hitted) {
+ return true;
+ }
+ else {
+ this._renderCmd._endEditing();
+ return false;
+ }
+ },
- //this._domInputSprite.dom.style.borderWidth = "1px";
- //this._domInputSprite.dom.style.borderStyle = "solid";
- //this._domInputSprite.dom.style.borderRadius = "8px";
- tmpDOMSprite.canvas.remove();
+ _onTouchEnded: function () {
+ if (!this.isVisible() || !this._isAncestorsVisible(this)) {
+ return;
+ }
+ this._renderCmd._beginEditing();
+ },
- if (this.initWithSizeAndBackgroundSprite(size, normal9SpriteBg)) {
- if (press9SpriteBg)
- this.setBackgroundSpriteForState(press9SpriteBg, cc.CONTROL_STATE_HIGHLIGHTED);
- if (disabled9SpriteBg)
- this.setBackgroundSpriteForState(disabled9SpriteBg, cc.CONTROL_STATE_DISABLED);
+ _updateBackgroundSpriteSize: function (width, height) {
+ if (this._backgroundSprite) {
+ this._backgroundSprite.setContentSize(width, height);
}
},
+ _updateEditBoxSize: function (size, height) {
+ var newWidth = (typeof size.width === 'number') ? size.width : size;
+ var newHeight = (typeof size.height === 'number') ? size.height : height;
+
+ this._updateBackgroundSpriteSize(newWidth, newHeight);
+ this._renderCmd.updateSize(newWidth, newHeight);
+ },
+
+ setLineHeight: function (lineHeight) {
+ this._renderCmd.setLineHeight(lineHeight);
+ },
+
/**
- * Set the font.
+ * Sets the font.
* @param {String} fontName The font name.
* @param {Number} fontSize The font size.
*/
setFont: function (fontName, fontSize) {
- this._edFontSize = fontSize;
- this._edFontName = fontName;
- this._setFontToEditBox();
+ this._renderCmd.setFont(fontName, fontSize);
},
_setFont: function (fontStyle) {
- var res = cc.LabelTTF._fontStyleRE.exec(fontStyle);
- if (res) {
- this._edFontSize = parseInt(res[1]);
- this._edFontName = res[2];
- this._setFontToEditBox();
- }
+ this._renderCmd._setFont(fontStyle);
+ },
+
+ getBackgroundSprite: function () {
+ return this._backgroundSprite;
},
/**
- * set fontName
+ * Sets fontName
* @param {String} fontName
*/
setFontName: function (fontName) {
- this._edFontName = fontName;
- this._setFontToEditBox();
+ this._renderCmd.setFontName(fontName);
},
/**
- * set fontSize
+ * Sets fontSize
* @param {Number} fontSize
*/
setFontSize: function (fontSize) {
- this._edFontSize = fontSize;
- this._setFontToEditBox();
- },
-
- _setFontToEditBox: function () {
- if (this._edTxt.value !== this._placeholderText) {
- this._edTxt.style.fontFamily = this._edFontName;
- this._edTxt.style.fontSize = this._edFontSize + "px";
- if (this._editBoxInputFlag === cc.EDITBOX_INPUT_FLAG_PASSWORD)
- this._edTxt.type = "password";
- else
- this._edTxt.type = "text";
- }
- },
-
- /**
- * Set the text entered in the edit box.
- * @deprecated
- * @param {string} text The given text.
- */
- setText: function (text) {
- cc.log("Please use the setString");
- this.setString(text);
+ this._renderCmd.setFontSize(fontSize);
},
/**
- * Set the text entered in the edit box.
+ * Sets the text entered in the edit box.
* @param {string} text The given text.
*/
setString: function (text) {
- if (text != null) {
- if (text === "") {
- this._edTxt.value = this._placeholderText;
- this._edTxt.style.color = cc.colorToHex(this._placeholderColor);
- this._edTxt.type = "text";
- } else {
- this._edTxt.value = text;
- this._edTxt.style.color = cc.colorToHex(this._textColor);
- if (this._editBoxInputFlag === cc.EDITBOX_INPUT_FLAG_PASSWORD)
- this._edTxt.type = "password";
- else
- this._edTxt.type = "text";
- }
+ if (text.length >= this._maxLength) {
+ text = text.slice(0, this._maxLength);
}
+ this._text = text;
+ this._renderCmd.setString(text);
},
/**
- * Set the font color of the widget's text.
+ * Sets the font color of the widget's text.
* @param {cc.Color} color
*/
setFontColor: function (color) {
this._textColor = color;
- if (this._edTxt.value !== this._placeholderText) {
- this._edTxt.style.color = cc.colorToHex(color);
- }
+ this._renderCmd.setFontColor(color);
},
/**
- *
* Sets the maximum input length of the edit box.
* Setting this value enables multiline input mode by default.
- *
* @param {Number} maxLength The maximum length.
*/
setMaxLength: function (maxLength) {
- if (!isNaN(maxLength) && maxLength > 0) {
+ if (!isNaN(maxLength)) {
+ if (maxLength < 0) {
+ //we can't set Number.MAX_VALUE to input's maxLength property
+ //so we use a magic number here, it should works at most use cases.
+ maxLength = 65535;
+ }
this._maxLength = maxLength;
- this._edTxt.maxLength = maxLength;
+ this._renderCmd.setMaxLength(maxLength);
}
},
@@ -463,108 +464,79 @@ cc.EditBox = cc.ControlButton.extend({
},
/**
- * Set a text in the edit box that acts as a placeholder when an edit box is empty.
+ * Sets a text in the edit box that acts as a placeholder when an edit box is empty.
* @param {string} text The given text.
*/
setPlaceHolder: function (text) {
- if (text != null) {
- var oldPlaceholderText = this._placeholderText;
+ if (text !== null) {
+ this._renderCmd.setPlaceHolder(text);
this._placeholderText = text;
- if (this._edTxt.value === oldPlaceholderText) {
- this._edTxt.value = text;
- this._edTxt.style.color = cc.colorToHex(this._placeholderColor);
- this._setPlaceholderFontToEditText();
- }
}
},
/**
- * Set the placeholder's font.
+ * Sets the placeholder's font.
* @param {String} fontName
* @param {Number} fontSize
*/
setPlaceholderFont: function (fontName, fontSize) {
this._placeholderFontName = fontName;
this._placeholderFontSize = fontSize;
- this._setPlaceholderFontToEditText();
+ this._renderCmd._updateDOMPlaceholderFontStyle();
},
+
_setPlaceholderFont: function (fontStyle) {
var res = cc.LabelTTF._fontStyleRE.exec(fontStyle);
if (res) {
this._placeholderFontName = res[2];
this._placeholderFontSize = parseInt(res[1]);
- this._setPlaceholderFontToEditText();
+ this._renderCmd._updateDOMPlaceholderFontStyle();
}
},
/**
- * Set the placeholder's fontName.
+ * Sets the placeholder's fontName.
* @param {String} fontName
*/
setPlaceholderFontName: function (fontName) {
this._placeholderFontName = fontName;
- this._setPlaceholderFontToEditText();
+ this._renderCmd._updateDOMPlaceholderFontStyle();
},
/**
- * Set the placeholder's fontSize.
+ * Sets the placeholder's fontSize.
* @param {Number} fontSize
*/
setPlaceholderFontSize: function (fontSize) {
this._placeholderFontSize = fontSize;
- this._setPlaceholderFontToEditText();
- },
-
- _setPlaceholderFontToEditText: function () {
- if (this._edTxt.value === this._placeholderText) {
- this._edTxt.style.fontFamily = this._placeholderFontName;
- this._edTxt.style.fontSize = this._placeholderFontSize + "px";
- this._edTxt.type = "text";
- }
+ this._renderCmd._updateDOMPlaceholderFontStyle();
},
/**
- * Set the font color of the placeholder text when the edit box is empty.
+ * Sets the font color of the placeholder text when the edit box is empty.
* @param {cc.Color} color
*/
setPlaceholderFontColor: function (color) {
this._placeholderColor = color;
- if (this._edTxt.value === this._placeholderText) {
- this._edTxt.style.color = cc.colorToHex(color);
- }
+ this._renderCmd.setPlaceholderFontColor(color);
},
/**
- * Set the input flags that are to be applied to the edit box.
+ * Sets the input flags that are to be applied to the edit box.
* @param {Number} inputFlag One of the EditBoxInputFlag constants.
* e.g.cc.EDITBOX_INPUT_FLAG_PASSWORD
*/
setInputFlag: function (inputFlag) {
this._editBoxInputFlag = inputFlag;
- if ((this._edTxt.value !== this._placeholderText) && (inputFlag === cc.EDITBOX_INPUT_FLAG_PASSWORD))
- this._edTxt.type = "password";
- else
- this._edTxt.type = "text";
- },
-
- /**
- * Gets the input string of the edit box.
- * @deprecated
- * @return {string}
- */
- getText: function () {
- cc.log("Please use the getString");
- return this._edTxt.value;
+ this._renderCmd.setInputFlag(inputFlag);
},
/**
- * Gets the input string of the edit box.
+ * Gets the input string of the edit box.
* @return {string}
*/
getString: function () {
- if(this._edTxt.value === this._placeholderText)
- return "";
- return this._edTxt.value;
+ return this._text;
},
/**
@@ -573,23 +545,26 @@ cc.EditBox = cc.ControlButton.extend({
* @param {cc.Color | cc.Scale9Sprite} normal9SpriteBg
*/
initWithSizeAndBackgroundSprite: function (size, normal9SpriteBg) {
- if (this.initWithBackgroundSprite(normal9SpriteBg)) {
- this._domInputSprite.x = 3;
- this._domInputSprite.y = 3;
-
- this.setZoomOnTouchDown(false);
- this.setPreferredSize(size);
- this.x = 0;
- this.y = 0;
- this._addTargetWithActionForControlEvent(this, this.touchDownAction, cc.CONTROL_EVENT_TOUCH_UP_INSIDE);
- return true;
+ if (this._backgroundSprite) {
+ this._backgroundSprite.removeFromParent();
}
- return false;
+ this._backgroundSprite = normal9SpriteBg;
+ this.setContentSize(size);
+
+ if (this._backgroundSprite && !this._backgroundSprite.parent) {
+ this._backgroundSprite.setAnchorPoint(cc.p(0, 0));
+ this.addChild(this._backgroundSprite);
+
+ this._updateBackgroundSpriteSize(size.width, size.height);
+ }
+
+ this.x = 0;
+ this.y = 0;
+ return true;
},
- /* override functions */
/**
- * Set the delegate for edit box.
+ * Sets the delegate for edit box.
* @param {cc.EditBoxDelegate} delegate
*/
setDelegate: function (delegate) {
@@ -597,7 +572,7 @@ cc.EditBox = cc.ControlButton.extend({
},
/**
- * Get a text in the edit box that acts as a placeholder when an
+ * Gets the text in the edit box that acts as a placeholder when an
* edit box is empty.
* @return {String}
*/
@@ -606,49 +581,29 @@ cc.EditBox = cc.ControlButton.extend({
},
/**
- * Set the input mode of the edit box.
+ * Sets the input mode of the edit box.
* @param {Number} inputMode One of the EditBoxInputMode constants.
*/
setInputMode: function (inputMode) {
+ if (this._editBoxInputMode === inputMode) return;
+
+ var oldText = this.getString();
this._editBoxInputMode = inputMode;
+
+ this._renderCmd.setInputMode(inputMode);
+ this._renderCmd.transform();
+
+ this.setString(oldText);
+ this._renderCmd._updateLabelPosition(this.getContentSize());
},
/**
- * Set the return type that are to be applied to the edit box.
+ * Sets the return type that are to be applied to the edit box.
* @param {Number} returnType One of the CCKeyboardReturnType constants.
*/
setReturnType: function (returnType) {
this._keyboardReturnType = returnType;
- },
-
- keyboardWillShow: function (info) {
- var rectTracked = cc.EditBox.getRect(this);
- // some adjustment for margin between the keyboard and the edit box.
- rectTracked.y -= 4;
- // if the keyboard area doesn't intersect with the tracking node area, nothing needs to be done.
- if (!rectTracked.intersectsRect(info.end)) {
- cc.log("needn't to adjust view layout.");
- return;
- }
-
- // assume keyboard at the bottom of screen, calculate the vertical adjustment.
- this._adjustHeight = info.end.getMaxY() - rectTracked.getMinY();
- // CCLOG("CCEditBox:needAdjustVerticalPosition(%f)", m_fAdjustHeight);
-
- //callback
- },
- keyboardDidShow: function (info) {
- },
- keyboardWillHide: function (info) {
- //if (m_pEditBoxImpl != NULL) {
- // m_pEditBoxImpl->doAnimationWhenKeyboardMove(info.duration, -m_fAdjustHeight);
- //}
- },
- keyboardDidHide: function (info) {
- },
-
- touchDownAction: function (sender, controlEvent) {
- //this._editBoxImpl.openKeyboard();
+ this._renderCmd._updateDomInputType();
},
/**
@@ -658,20 +613,10 @@ cc.EditBox = cc.ControlButton.extend({
*/
initWithBackgroundColor: function (size, bgColor) {
this._edWidth = size.width;
- this.dom.style.width = this._edWidth.toString() + "px";
+ this.dom.style.width = this._edWidth.toString() + 'px';
this._edHeight = size.height;
- this.dom.style.height = this._edHeight.toString() + "px";
+ this.dom.style.height = this._edHeight.toString() + 'px';
this.dom.style.backgroundColor = cc.colorToHex(bgColor);
- },
-
- cleanup : function () {
- this._edTxt.removeEventListener("input", this._inputEvent);
- this._edTxt.removeEventListener("keypress", this._keyPressEvent);
- this._edTxt.removeEventListener("focus", this._focusEvent);
- this._edTxt.removeEventListener("blur", this._blurEvent);
- cc._canvas.removeEventListener('click', this._onCanvasClick);
-
- this._super();
}
});
@@ -680,64 +625,52 @@ var _p = cc.EditBox.prototype;
// Extended properties
/** @expose */
_p.font;
-cc.defineGetterSetter(_p, "font", null, _p._setFont);
+cc.defineGetterSetter(_p, 'font', null, _p._setFont);
/** @expose */
_p.fontName;
-cc.defineGetterSetter(_p, "fontName", null, _p.setFontName);
+cc.defineGetterSetter(_p, 'fontName', null, _p.setFontName);
/** @expose */
_p.fontSize;
-cc.defineGetterSetter(_p, "fontSize", null, _p.setFontSize);
+cc.defineGetterSetter(_p, 'fontSize', null, _p.setFontSize);
/** @expose */
_p.fontColor;
-cc.defineGetterSetter(_p, "fontColor", null, _p.setFontColor);
+cc.defineGetterSetter(_p, 'fontColor', null, _p.setFontColor);
/** @expose */
_p.string;
-cc.defineGetterSetter(_p, "string", _p.getString, _p.setString);
+cc.defineGetterSetter(_p, 'string', _p.getString, _p.setString);
/** @expose */
_p.maxLength;
-cc.defineGetterSetter(_p, "maxLength", _p.getMaxLength, _p.setMaxLength);
+cc.defineGetterSetter(_p, 'maxLength', _p.getMaxLength, _p.setMaxLength);
/** @expose */
_p.placeHolder;
-cc.defineGetterSetter(_p, "placeHolder", _p.getPlaceHolder, _p.setPlaceHolder);
+cc.defineGetterSetter(_p, 'placeholder', _p.getPlaceHolder, _p.setPlaceHolder);
/** @expose */
_p.placeHolderFont;
-cc.defineGetterSetter(_p, "placeHolderFont", null, _p._setPlaceholderFont);
+cc.defineGetterSetter(_p, 'placeholderFont', null, _p._setPlaceholderFont);
/** @expose */
_p.placeHolderFontName;
-cc.defineGetterSetter(_p, "placeHolderFontName", null, _p.setPlaceholderFontName);
+cc.defineGetterSetter(_p, 'placeholderFontName', null, _p.setPlaceholderFontName);
/** @expose */
_p.placeHolderFontSize;
-cc.defineGetterSetter(_p, "placeHolderFontSize", null, _p.setPlaceholderFontSize);
+cc.defineGetterSetter(_p, 'placeholderFontSize', null, _p.setPlaceholderFontSize);
/** @expose */
_p.placeHolderFontColor;
-cc.defineGetterSetter(_p, "placeHolderFontColor", null, _p.setPlaceholderFontColor);
+cc.defineGetterSetter(_p, 'placeholderFontColor', null, _p.setPlaceholderFontColor);
/** @expose */
_p.inputFlag;
-cc.defineGetterSetter(_p, "inputFlag", null, _p.setInputFlag);
+cc.defineGetterSetter(_p, 'inputFlag', null, _p.setInputFlag);
/** @expose */
_p.delegate;
-cc.defineGetterSetter(_p, "delegate", null, _p.setDelegate);
+cc.defineGetterSetter(_p, 'delegate', null, _p.setDelegate);
/** @expose */
_p.inputMode;
-cc.defineGetterSetter(_p, "inputMode", null, _p.setInputMode);
+cc.defineGetterSetter(_p, 'inputMode', null, _p.setInputMode);
/** @expose */
_p.returnType;
-cc.defineGetterSetter(_p, "returnType", null, _p.setReturnType);
+cc.defineGetterSetter(_p, 'returnType', null, _p.setReturnType);
_p = null;
-/**
- * get the rect of a node in world coordinate frame
- * @function
- * @param {cc.Node} node
- * @return {cc.Rect}
- */
-cc.EditBox.getRect = function (node) {
- var contentSize = node.getContentSize();
- var rect = cc.rect(0, 0, contentSize.width, contentSize.height);
- return cc.rectApplyAffineTransform(rect, node.getNodeToWorldTransform());
-};
-
/**
* create a edit box with size and background-color or
* @deprecated since v3.0, please use new cc.EditBox(size, normal9SpriteBg, press9SpriteBg, disabled9SpriteBg) instead
@@ -752,5 +685,736 @@ cc.EditBox.create = function (size, normal9SpriteBg, press9SpriteBg, disabled9Sp
};
+(function (editbox) {
+ editbox._polyfill = {
+ zoomInvalid: false
+ };
+
+ if (cc.sys.OS_ANDROID === cc.sys.os
+ && (cc.sys.browserType === cc.sys.BROWSER_TYPE_SOUGOU
+ || cc.sys.browserType === cc.sys.BROWSER_TYPE_360)) {
+ editbox._polyfill.zoomInvalid = true;
+ }
+})(cc.EditBox);
+
+(function (polyfill) {
+ // https://segmentfault.com/q/1010000002914610
+ var SCROLLY = 40;
+ var TIMER_NAME = 400;
+ var LEFT_PADDING = 2;
+
+ function adjustEditBoxPosition (editBox) {
+ var worldPos = editBox.convertToWorldSpace(cc.p(0,0));
+ var windowHeight = cc.visibleRect.height;
+ var windowWidth = cc.visibleRect.width;
+ var factor = 0.5;
+ if(windowWidth > windowHeight) {
+ factor = 0.7;
+ }
+ setTimeout(function() {
+ if(window.scrollY < SCROLLY && worldPos.y < windowHeight * factor) {
+ var scrollOffset = windowHeight * factor - worldPos.y - window.scrollY;
+ if (scrollOffset < 35) scrollOffset = 35;
+ if (scrollOffset > 320) scrollOffset = 320;
+ window.scrollTo(scrollOffset, scrollOffset);
+ }
+ }, TIMER_NAME);
+ }
+
+ var capitalize = function(string) {
+ return string.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
+ };
+
+ function capitalizeFirstLetter(string) {
+ return string.charAt(0).toUpperCase() + string.slice(1);
+ }
+
+ var EditBoxImpl = function () {
+ };
+ var proto = EditBoxImpl.prototype = Object.create(Object.prototype);
+
+ proto.updateMatrix = function () {
+ if (!this._edTxt) return;
+
+ var node = this._node, scaleX = cc.view._scaleX, scaleY = cc.view._scaleY;
+ var dpr = cc.view._devicePixelRatio;
+ var t = this._worldTransform;
+
+ scaleX /= dpr;
+ scaleY /= dpr;
+
+ var container = cc.game.container;
+ var a = t.a * scaleX, b = t.b, c = t.c, d = t.d * scaleY;
+
+ var offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft);
+ var offsetY = container && container.style.paddingBottom && parseInt(container.style.paddingBottom);
+ var tx = t.tx * scaleX + offsetX, ty = t.ty * scaleY + offsetY;
+
+ if (polyfill.zoomInvalid) {
+ this.updateSize(node._contentSize.width * a, node._contentSize.height * d);
+ a = 1;
+ d = 1;
+ }
+
+ var matrix = "matrix(" + a + "," + -b + "," + -c + "," + d + "," + tx + "," + -ty + ")";
+ this._edTxt.style['transform'] = matrix;
+ this._edTxt.style['-webkit-transform'] = matrix;
+ this._edTxt.style['transform-origin'] = '0px 100% 0px';
+ this._edTxt.style['-webkit-transform-origin'] = '0px 100% 0px';
+ };
+
+ proto.updateVisibility = function () {
+ if (!this._edTxt) return;
+
+ if (this._node.visible) {
+ this._edTxt.style.visibility = 'visible';
+ } else {
+ this._edTxt.style.visibility = 'hidden';
+ }
+ };
+
+ proto.stayOnTop = function (flag) {
+ if (flag) {
+ this._removeLabels();
+ this._edTxt.style.display = '';
+ } else {
+ this._createLabels();
+ this._edTxt.style.display = 'none';
+ this._showLabels();
+ }
+ };
+
+ // Called before editbox focus to register cc.view status
+ proto._beginEditingOnMobile = function (editBox) {
+ this.__orientationChanged = function () {
+ adjustEditBoxPosition(editBox);
+ };
+
+ window.addEventListener('orientationchange', this.__orientationChanged);
+
+ if (cc.view.isAutoFullScreenEnabled()) {
+ this.__fullscreen = true;
+ cc.view.enableAutoFullScreen(false);
+ cc.screen.exitFullScreen();
+ } else {
+ this.__fullscreen = false;
+ }
+ this.__autoResize = cc.view.__resizeWithBrowserSize;
+ cc.view.resizeWithBrowserSize(false);
+ };
+ // Called after keyboard disappeared to readapte the game view
+ proto._endEditingOnMobile = function () {
+ if (this.__rotateScreen) {
+ var containerStyle = cc.game.container.style;
+ containerStyle['-webkit-transform'] = 'rotate(90deg)';
+ containerStyle.transform = 'rotate(90deg)';
+
+ var view = cc.view;
+ var width = view._originalDesignResolutionSize.width;
+ var height = view._originalDesignResolutionSize.height;
+ if (width > 0) {
+ view.setDesignResolutionSize(width, height, view._resolutionPolicy);
+ }
+ this.__rotateScreen = false;
+ }
+
+ window.removeEventListener('orientationchange', this.__orientationChanged);
+
+ window.scrollTo(0, 0);
+ if (this.__fullscreen) {
+ cc.view.enableAutoFullScreen(true);
+ }
+ if (this.__autoResize) {
+ cc.view.resizeWithBrowserSize(true);
+ }
+ };
+ // Called after editbox focus to readapte the game view
+ proto._onFocusOnMobile = function (editBox) {
+ if (cc.view._isRotated) {
+ var containerStyle = cc.game.container.style;
+ containerStyle['-webkit-transform'] = 'rotate(0deg)';
+ containerStyle.transform = 'rotate(0deg)';
+ containerStyle.margin = '0px';
+ // cc.view._isRotated = false;
+ // var policy = cc.view.getResolutionPolicy();
+ // policy.apply(cc.view, cc.view.getDesignResolutionSize());
+ // cc.view._isRotated = true;
+ //use window scrollTo to adjust the input area
+ window.scrollTo(35, 35);
+ this.__rotateScreen = true;
+ } else {
+ this.__rotateScreen = false;
+ }
+ adjustEditBoxPosition(editBox);
+ };
+
+
+ proto._createDomInput = function () {
+ this._removeDomFromGameContainer();
+ var thisPointer = this;
+ var tmpEdTxt = this._edTxt = document.createElement('input');
+ tmpEdTxt.type = 'text';
+ tmpEdTxt.style.fontFamily = this._edFontName;
+ tmpEdTxt.style.fontSize = this._edFontSize + 'px';
+ tmpEdTxt.style.color = '#000000';
+ tmpEdTxt.style.border = 0;
+ tmpEdTxt.style.background = 'transparent';
+ tmpEdTxt.style.width = '100%';
+ tmpEdTxt.style.height = '100%';
+ tmpEdTxt.style.active = 0;
+ tmpEdTxt.style.outline = 'medium';
+ tmpEdTxt.style.padding = '0';
+ tmpEdTxt.style.textTransform = 'uppercase';
+ tmpEdTxt.style.display = 'none';
+
+ tmpEdTxt.style.position = "absolute";
+ tmpEdTxt.style.bottom = "0px";
+ tmpEdTxt.style.left = LEFT_PADDING + "px";
+ tmpEdTxt.style.className = "cocosEditBox";
+ this.setMaxLength(thisPointer._editBox._maxLength);
+
+ tmpEdTxt.addEventListener('input', function () {
+ var editBox = thisPointer._editBox;
+
+
+ if (this.value.length > this.maxLength) {
+ this.value = this.value.slice(0, this.maxLength);
+ }
+
+ if (editBox._delegate && editBox._delegate.editBoxTextChanged) {
+ if (editBox._text !== this.value) {
+ editBox._text = this.value;
+ thisPointer._updateDomTextCases();
+ editBox._delegate.editBoxTextChanged(editBox, editBox._text);
+ }
+ }
+ });
+ tmpEdTxt.addEventListener('keypress', function (e) {
+ var editBox = thisPointer._editBox;
+
+ if (e.keyCode === cc.KEY.enter) {
+ e.stopPropagation();
+ e.preventDefault();
+ if (this.value === '') {
+ this.style.fontSize = editBox._placeholderFontSize + 'px';
+ this.style.color = cc.colorToHex(editBox._placeholderColor);
+ }
+
+ editBox._text = this.value;
+ thisPointer._updateDomTextCases();
+
+ thisPointer._endEditing();
+ if (editBox._delegate && editBox._delegate.editBoxReturn) {
+ editBox._delegate.editBoxReturn(editBox);
+ }
+ cc._canvas.focus();
+ }
+ });
+
+ tmpEdTxt.addEventListener('focus', function () {
+ var editBox = thisPointer._editBox;
+ this.style.fontSize = thisPointer._edFontSize + 'px';
+ this.style.color = cc.colorToHex(editBox._textColor);
+ thisPointer._hiddenLabels();
+
+ if (cc.sys.isMobile) {
+ thisPointer._onFocusOnMobile(editBox);
+ }
+
+ if (editBox._delegate && editBox._delegate.editBoxEditingDidBegin) {
+ editBox._delegate.editBoxEditingDidBegin(editBox);
+ }
+ });
+ tmpEdTxt.addEventListener('blur', function () {
+ var editBox = thisPointer._editBox;
+ editBox._text = this.value;
+ thisPointer._updateDomTextCases();
+
+ if (editBox._delegate && editBox._delegate.editBoxEditingDidEnd) {
+ editBox._delegate.editBoxEditingDidEnd(editBox);
+ }
+
+ if (this.value === '') {
+ this.style.fontSize = editBox._placeholderFontSize + 'px';
+ this.style.color = cc.colorToHex(editBox._placeholderColor);
+ }
+ thisPointer._endEditing();
+ });
+
+ this._addDomToGameContainer();
+ return tmpEdTxt;
+ };
+
+ proto._createDomTextArea = function () {
+ this._removeDomFromGameContainer();
+ var thisPointer = this;
+ var tmpEdTxt = this._edTxt = document.createElement('textarea');
+ tmpEdTxt.type = 'text';
+ tmpEdTxt.style.fontFamily = this._edFontName;
+ tmpEdTxt.style.fontSize = this._edFontSize + 'px';
+ tmpEdTxt.style.color = '#000000';
+ tmpEdTxt.style.border = 0;
+ tmpEdTxt.style.background = 'transparent';
+ tmpEdTxt.style.width = '100%';
+ tmpEdTxt.style.height = '100%';
+ tmpEdTxt.style.active = 0;
+ tmpEdTxt.style.outline = 'medium';
+ tmpEdTxt.style.padding = '0';
+ tmpEdTxt.style.resize = 'none';
+ tmpEdTxt.style.textTransform = 'uppercase';
+ tmpEdTxt.style.overflow_y = 'scroll';
+ tmpEdTxt.style.display = 'none';
+ tmpEdTxt.style.position = "absolute";
+ tmpEdTxt.style.bottom = "0px";
+ tmpEdTxt.style.left = LEFT_PADDING + "px";
+ tmpEdTxt.style.className = "cocosEditBox";
+ this.setMaxLength(thisPointer._editBox._maxLength);
+
+ tmpEdTxt.addEventListener('input', function () {
+ if (this.value.length > this.maxLength) {
+ this.value = this.value.slice(0, this.maxLength);
+ }
+
+ var editBox = thisPointer._editBox;
+ if (editBox._delegate && editBox._delegate.editBoxTextChanged) {
+ if (editBox._text.toLowerCase() !== this.value.toLowerCase()) {
+ editBox._text = this.value;
+ thisPointer._updateDomTextCases();
+ editBox._delegate.editBoxTextChanged(editBox, editBox._text);
+ }
+ }
+ });
+
+ tmpEdTxt.addEventListener('focus', function () {
+ var editBox = thisPointer._editBox;
+ thisPointer._hiddenLabels();
+
+ this.style.fontSize = thisPointer._edFontSize + 'px';
+ this.style.color = cc.colorToHex(editBox._textColor);
+
+ if (cc.sys.isMobile) {
+ thisPointer._onFocusOnMobile(editBox);
+ }
+
+ if (editBox._delegate && editBox._delegate.editBoxEditingDidBegin) {
+ editBox._delegate.editBoxEditingDidBegin(editBox);
+ }
+
+ });
+ tmpEdTxt.addEventListener('keypress', function (e) {
+ var editBox = thisPointer._editBox;
+
+ if (e.keyCode === cc.KEY.enter) {
+ e.stopPropagation();
+
+ if (editBox._delegate && editBox._delegate.editBoxReturn) {
+ editBox._delegate.editBoxReturn(editBox);
+ }
+ }
+ });
+ tmpEdTxt.addEventListener('blur', function () {
+ var editBox = thisPointer._editBox;
+ editBox._text = this.value;
+ thisPointer._updateDomTextCases();
+
+ if (editBox._delegate && editBox._delegate.editBoxEditingDidEnd) {
+ editBox._delegate.editBoxEditingDidEnd(editBox);
+ }
+
+ if (this.value === '') {
+ this.style.fontSize = editBox._placeholderFontSize + 'px';
+ this.style.color = cc.colorToHex(editBox._placeholderColor);
+ }
+
+ thisPointer._endEditing();
+ });
+
+ this._addDomToGameContainer();
+ return tmpEdTxt;
+ };
+
+ proto._createLabels = function () {
+ var editBoxSize = this._editBox.getContentSize();
+ if (!this._textLabel) {
+ this._textLabel = new cc.LabelTTF();
+ this._textLabel.setAnchorPoint(cc.p(0, 1));
+ this._editBox.addChild(this._textLabel, 100);
+ }
+
+ if (!this._placeholderLabel) {
+ this._placeholderLabel = new cc.LabelTTF();
+ this._placeholderLabel.setAnchorPoint(cc.p(0, 1));
+ this._placeholderLabel.setColor(cc.color.GRAY);
+ this._editBox.addChild(this._placeholderLabel, 100);
+ }
+
+ this._updateLabelPosition(editBoxSize);
+ };
+
+ proto._removeLabels = function () {
+ if (!this._textLabel) return;
+
+ this._editBox.removeChild(this._textLabel);
+ this._textLabel = null;
+ };
+
+ proto._updateLabelPosition = function (editBoxSize) {
+ if (!this._textLabel || !this._placeholderLabel) return;
+
+ var labelContentSize = cc.size(editBoxSize.width - LEFT_PADDING, editBoxSize.height);
+ this._textLabel.setContentSize(labelContentSize);
+ this._textLabel.setDimensions(labelContentSize);
+ this._placeholderLabel.setLineHeight(editBoxSize.height);
+ var placeholderLabelSize = this._placeholderLabel.getContentSize();
+
+ if (this._editBox._editBoxInputMode === cc.EDITBOX_INPUT_MODE_ANY) {
+ this._textLabel.setPosition(LEFT_PADDING, editBoxSize.height);
+ this._placeholderLabel.setPosition(LEFT_PADDING, editBoxSize.height);
+ this._placeholderLabel.setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_TOP);
+ this._textLabel.setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_TOP);
+ // this._textLabel.enableWrapText(true);
+ }
+ else {
+ // this._textLabel.enableWrapText(false);
+ this._textLabel.setPosition(LEFT_PADDING, editBoxSize.height);
+ this._placeholderLabel.setPosition(LEFT_PADDING, (editBoxSize.height + placeholderLabelSize.height) / 2);
+ this._placeholderLabel.setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_CENTER);
+ this._textLabel.setVerticalAlignment(cc.VERTICAL_TEXT_ALIGNMENT_CENTER);
+ }
+
+ };
+
+ proto.setLineHeight = function (lineHeight) {
+ if (this._textLabel) {
+ this._textLabel.setLineHeight(lineHeight);
+ }
+ };
+
+ proto._hiddenLabels = function () {
+ if (this._textLabel) {
+ this._textLabel.setVisible(false);
+ }
+
+ if (this._placeholderLabel) {
+ this._placeholderLabel.setVisible(false);
+ }
+ };
+
+ proto._updateDomTextCases = function () {
+ var inputFlag = this._editBox._editBoxInputFlag;
+ if (inputFlag === cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_ALL_CHARACTERS) {
+ this._editBox._text = this._editBox._text.toUpperCase();
+ }
+ else if (inputFlag === cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_WORD) {
+ this._editBox._text = capitalize(this._editBox._text);
+ }
+ else if (inputFlag === cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_SENTENCE) {
+ this._editBox._text = capitalizeFirstLetter(this._editBox._text);
+ }
+ };
+
+ proto._updateLabelStringStyle = function () {
+ if (this._edTxt.type === 'password') {
+ var passwordString = '';
+ var len = this._editBox._text.length;
+ for (var i = 0; i < len; ++i) {
+ passwordString += '\u25CF';
+ }
+ if (this._textLabel) {
+ this._textLabel.setString(passwordString);
+ }
+ } else {
+ this._updateDomTextCases();
+ if (this._textLabel) {
+ this._textLabel.setString(this._editBox._text);
+ }
+ }
+ };
+
+ proto._showLabels = function () {
+ this._hiddenLabels();
+ if (this._edTxt.value === '') {
+ if (this._placeholderLabel) {
+ this._placeholderLabel.setVisible(true);
+ this._placeholderLabel.setString(this._editBox._placeholderText);
+ }
+ }
+ else {
+ if (this._textLabel) {
+ this._textLabel.setVisible(true);
+ this._textLabel.setString(this._editBox._text);
+ }
+ }
+ this._updateLabelStringStyle();
+ };
+
+ proto._beginEditing = function () {
+ if (!this._editBox._alwaysOnTop) {
+ if (this._edTxt.style.display === 'none') {
+ this._edTxt.style.display = '';
+ this._edTxt.focus();
+ }
+ }
+
+ if (cc.sys.isMobile && !this._editingMode) {
+ // Pre adaptation and
+ this._beginEditingOnMobile(this._editBox);
+ }
+ this._editingMode = true;
+ };
+
+ proto._endEditing = function () {
+ if (!this._editBox._alwaysOnTop) {
+ this._edTxt.style.display = 'none';
+ }
+ this._showLabels();
+ if (cc.sys.isMobile && this._editingMode) {
+ var self = this;
+ // Delay end editing adaptation to ensure virtual keyboard is disapeared
+ setTimeout(function () {
+ self._endEditingOnMobile();
+ }, TIMER_NAME);
+ }
+ this._editingMode = false;
+ };
+
+ proto._setFont = function (fontStyle) {
+ var res = cc.LabelTTF._fontStyleRE.exec(fontStyle);
+ var textFontName = res[2];
+ var textFontSize = parseInt(res[1]);
+ if (res) {
+ this.setFont(textFontName, textFontSize);
+ }
+ };
+
+ proto.setFont = function (fontName, fontSize) {
+ this._edFontName = fontName || this._edFontName;
+ this._edFontSize = fontSize || this._edFontSize;
+ this._updateDOMFontStyle();
+ };
+
+ proto.setFontName = function (fontName) {
+ this._edFontName = fontName || this._edFontName;
+ this._updateDOMFontStyle();
+ };
+
+ proto.setFontSize = function (fontSize) {
+ this._edFontSize = fontSize || this._edFontSize;
+ this._updateDOMFontStyle();
+ };
+
+ proto.setFontColor = function (color) {
+ if (!this._edTxt) return;
+
+ if (this._edTxt.value !== this._editBox._placeholderText) {
+ this._edTxt.style.color = cc.colorToHex(color);
+ }
+ if (this._textLabel) {
+ this._textLabel.setColor(color);
+ }
+ };
+
+ proto.setPlaceHolder = function (text) {
+ this._placeholderLabel.setString(text);
+ };
+
+ proto.setMaxLength = function (maxLength) {
+ if (!this._edTxt) return;
+ this._edTxt.maxLength = maxLength;
+ };
+
+ proto._updateDOMPlaceholderFontStyle = function () {
+ this._placeholderLabel.setFontName(this._editBox._placeholderFontName);
+ this._placeholderLabel.setFontSize(this._editBox._placeholderFontSize);
+ };
+
+ proto.setPlaceholderFontColor = function (color) {
+ this._placeholderLabel.setColor(color);
+ };
+
+ proto._updateDomInputType = function () {
+ var inputMode = this._editBox._editBoxInputMode;
+ if (inputMode === cc.EDITBOX_INPUT_MODE_EMAILADDR) {
+ this._edTxt.type = 'email';
+ } else if (inputMode === cc.EDITBOX_INPUT_MODE_DECIMAL ||
+ inputMode === cc.EDITBOX_INPUT_MODE_NUMERIC) {
+ this._edTxt.type = 'number';
+ } else if (inputMode === cc.EDITBOX_INPUT_MODE_PHONENUMBER) {
+ this._edTxt.type = 'number';
+ this._edTxt.pattern = '[0-9]*';
+ } else if (inputMode === cc.EDITBOX_INPUT_MODE_URL) {
+ this._edTxt.type = 'url';
+ } else {
+ this._edTxt.type = 'text';
+
+ if (this._editBox._keyboardReturnType === cc.KEYBOARD_RETURNTYPE_SEARCH) {
+ this._edTxt.type = 'search';
+ }
+ }
+
+ if (this._editBox._editBoxInputFlag === cc.EDITBOX_INPUT_FLAG_PASSWORD) {
+ this._edTxt.type = 'password';
+ }
+ };
+
+ proto.setInputFlag = function (inputFlag) {
+ if (!this._edTxt) return;
+
+ this._updateDomInputType();
+
+ this._edTxt.style.textTransform = 'none';
+
+ if (inputFlag === cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_ALL_CHARACTERS) {
+ this._edTxt.style.textTransform = 'uppercase';
+ }
+ else if (inputFlag === cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_WORD) {
+ this._edTxt.style.textTransform = 'capitalize';
+ }
+ this._updateLabelStringStyle();
+ };
+
+ proto.setInputMode = function (inputMode) {
+ if (inputMode === cc.EDITBOX_INPUT_MODE_ANY) {
+ this._createDomTextArea();
+ }
+ else {
+ this._createDomInput();
+ }
+
+ this._updateDomInputType();
+ var contentSize = this._node.getContentSize();
+ this.updateSize(contentSize.width, contentSize.height);
+ };
+
+ proto.setString = function (text) {
+ if (!this._edTxt) return;
+
+ if (text !== null) {
+ this._edTxt.value = text;
+
+ if (text === '') {
+ if (this._placeholderLabel) {
+ this._placeholderLabel.setString(this._editBox._placeholderText);
+ this._placeholderLabel.setColor(this._editBox._placeholderColor);
+ }
+ if (!this._editingMode) {
+ if (this._placeholderLabel) {
+ this._placeholderLabel.setVisible(true);
+ }
+
+ if (this._textLabel) {
+ this._textLabel.setVisible(false);
+ }
+ }
+ }
+ else {
+ this._edTxt.style.color = cc.colorToHex(this._editBox._textColor);
+ if (this._textLabel) {
+ this._textLabel.setColor(this._editBox._textColor);
+ }
+ if (!this._editingMode) {
+ if (this._placeholderLabel) {
+ this._placeholderLabel.setVisible(false);
+ }
+ if (this._textLabel) {
+ this._textLabel.setVisible(true);
+ }
+ }
+
+ this._updateLabelStringStyle();
+ }
+ }
+ };
+
+ proto._updateDOMFontStyle = function () {
+ if (!this._edTxt) return;
+
+ if (this._edTxt.value !== '') {
+ this._edTxt.style.fontFamily = this._edFontName;
+ this._edTxt.style.fontSize = this._edFontSize + 'px';
+ }
+ if (this._textLabel) {
+ this._textLabel.setFontSize(this._edFontSize);
+ this._textLabel.setFontName(this._edFontName);
+ }
+ };
+
+
+ proto.updateSize = function (newWidth, newHeight) {
+ var editboxDomNode = this._edTxt;
+ if (!editboxDomNode) return;
+
+ editboxDomNode.style['width'] = newWidth + 'px';
+ editboxDomNode.style['height'] = newHeight + 'px';
+
+ this._updateLabelPosition(cc.size(newWidth, newHeight));
+ };
+
+ proto._addDomToGameContainer = function () {
+ cc.game.container.appendChild(this._edTxt);
+ };
+
+ proto._removeDomFromGameContainer = function () {
+ var editBox = this._edTxt;
+ if (editBox) {
+ var hasChild = false;
+ if ('contains' in cc.game.container) {
+ hasChild = cc.game.container.contains(editBox);
+ } else {
+ hasChild = cc.game.container.compareDocumentPosition(editBox) % 16;
+ }
+ if (hasChild)
+ cc.game.container.removeChild(editBox);
+ }
+ this._edTxt = null;
+ };
+
+ proto.initializeRenderCmd = function (node) {
+ this._editBox = node;
+
+ //it's a dom node, may be assigned with Input or TextArea.
+ this._edFontSize = 14;
+ this._edFontName = 'Arial';
+ this._textLabel = null;
+ this._placeholderLabel = null;
+ this._editingMode = false;
+
+ this.__fullscreen = false;
+ this.__autoResize = false;
+ this.__rotateScreen = false;
+ this.__orientationChanged = null;
+ };
+
+ //define the canvas render command
+ cc.EditBox.CanvasRenderCmd = function (node) {
+ this._rootCtor(node);
+ this.initializeRenderCmd(node);
+ };
+
+ var canvasRenderCmdProto = cc.EditBox.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
+
+ cc.inject(proto, canvasRenderCmdProto);
+ canvasRenderCmdProto.constructor = cc.EditBox.CanvasRenderCmd;
+
+ canvasRenderCmdProto.transform = function (parentCmd, recursive) {
+ this.originTransform(parentCmd, recursive);
+ this.updateMatrix();
+ };
+
+
+ //define the webgl render command
+ cc.EditBox.WebGLRenderCmd = function (node) {
+ this._rootCtor(node);
+ this.initializeRenderCmd(node);
+ };
+
+ var webGLRenderCmdProto = cc.EditBox.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
+ cc.inject(proto, webGLRenderCmdProto);
+ webGLRenderCmdProto.constructor = cc.EditBox.WebGLRenderCmd;
+ webGLRenderCmdProto.transform = function (parentCmd, recursive) {
+ this.originTransform(parentCmd, recursive);
+ this.updateMatrix();
+ };
+}(cc.EditBox._polyfill));
diff --git a/extensions/editbox/CCdomNode.js b/extensions/editbox/CCdomNode.js
deleted file mode 100644
index 5074596750..0000000000
--- a/extensions/editbox/CCdomNode.js
+++ /dev/null
@@ -1,659 +0,0 @@
-/****************************************************************************
- Copyright (c) 2011-2012 cocos2d-x.org
- Copyright (c) 2013-2014 Chukong Technologies Inc.
-
- http://www.cocos2d-x.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-/**
- * the DOM object
- * @namespace
- * @name cc.DOM
- */
-cc.DOM = {};
-
-/**
- * @function
- * @private
- * @param node
- */
-cc.DOM._addMethods = function (node) {
- for (var funcs in cc.DOM.methods) {
- node[funcs] = cc.DOM.methods[funcs];
- }
-
- // Redefine getter setter
- cc.defineGetterSetter(node, "x", node.getPositionX, node.setPositionX);
- cc.defineGetterSetter(node, "y", node.getPositionY, node.setPositionY);
- cc.defineGetterSetter(node, "width", node._getWidth, node._setWidth);
- cc.defineGetterSetter(node, "height", node._getHeight, node._setHeight);
- cc.defineGetterSetter(node, "anchorX", node._getAnchorX, node._setAnchorX);
- cc.defineGetterSetter(node, "anchorY", node._getAnchorY, node._setAnchorY);
- cc.defineGetterSetter(node, "scale", node.getScale, node.setScale);
- cc.defineGetterSetter(node, "scaleX", node.getScaleX, node.setScaleX);
- cc.defineGetterSetter(node, "scaleY", node.getScaleY, node.setScaleY);
- cc.defineGetterSetter(node, "rotation", node.getRotation, node.setRotation);
- cc.defineGetterSetter(node, "skewX", node.getSkewX, node.setSkewX);
- cc.defineGetterSetter(node, "skewY", node.getSkewY, node.setSkewY);
- cc.defineGetterSetter(node, "visible", node.isVisible, node.setVisible);
- cc.defineGetterSetter(node, "parent", node.getParent, node.setParent);
- cc.defineGetterSetter(node, "opacity", node.getOpacity, node.setOpacity);
-};
-cc.DOM.methods = /** @lends cc.DOM# */{
- /**
- * Replace the set position of ccNode
- * @param {cc.Point|Number} x
- * @param {Number} y
- */
- setPosition:function (x, y) {
- if (y === undefined) {
- this._position.x = x.x;
- this._position.y = x.y;
- } else {
- this._position.x = x;
- this._position.y = y;
- }
- this.setNodeDirty();
- this.dom.translates(this._position.x, -this._position.y);
- },
- /**
- * replace set Position Y of ccNode
- * @param {Number} y
- */
- setPositionY:function (y) {
- this._position.y = y;
- this.setNodeDirty();
- this.dom.translates(this._position.x, -this._position.y);
- },
-
- /**
- * replace set Position X of ccNode
- * @param {Number} x
- */
- setPositionX:function (x) {
- this._position.x = x;
- this.setNodeDirty();
- this.dom.translates(this._position.x, -this._position.y);
- },
-
- /**
- * replace set Scale of ccNode
- * @param {object|Number} scale
- * @param {Number} scaleY
- */
- setScale:function (scale, scaleY) {
- //save dirty region when before change
- //this._addDirtyRegionToDirector(this.getBoundingBoxToWorld());
-
- this._scaleX = scale;
- this._scaleY = scaleY || scale;
-
- //save dirty region when after changed
- //this._addDirtyRegionToDirector(this.getBoundingBoxToWorld());
- this.setNodeDirty();
- this.dom.resize(this._scaleX, this._scaleY);
- },
-
- /**
- * replace set Scale X of ccNode
- * @param {Number} x
- */
- setScaleX:function (x) {
- this._scaleX = x;
- this.setNodeDirty();
- this.dom.resize(this._scaleX, this._scaleY);
- },
-
- /**
- * replace set Scale Y of ccNode
- * @param {Number} y
- */
- setScaleY:function (y) {
- this._scaleY = y;
- this.setNodeDirty();
- this.dom.resize(this._scaleX, this._scaleY);
- },
-
- /**
- * replace set anchorpoint of ccNode
- * @param {cc.Point|Number} point The anchor point of node or The anchor point.x of node.
- * @param {Number} [y] The anchor point.y of node.
- */
- setAnchorPoint:function (point, y) {
- var cmd = this._renderCmd;
-
- var locAnchorPoint = this._anchorPoint;
- if (y === undefined) {
- locAnchorPoint.x = point.x;
- locAnchorPoint.y = point.y;
- } else {
- locAnchorPoint.x = point;
- locAnchorPoint.y = y;
- }
- var locAPP = cmd._anchorPointInPoints, locSize = this._contentSize;
- locAPP.x = locSize.width * locAnchorPoint.x;
- locAPP.y = locSize.height * locAnchorPoint.y;
-
- this.dom.style[cc.$.pfx + 'TransformOrigin'] = '' + locAPP.x + 'px ' + -locAPP.y + 'px';
- if (this.ignoreAnchor) {
- this.dom.style.marginLeft = 0;
- this.dom.style.marginBottom = 0;
- } else {
- this.dom.style.marginLeft = (this.isToggler) ? 0 : -locAPP.x + 'px';
- this.dom.style.marginBottom = -locAPP.y + 'px';
- }
- this.setNodeDirty();
- },
-
- /**
- * replace set anchorpoint x of ccNode
- * @param {Number} x The anchor x of node.
- */
- _setAnchorX:function (x) {
- var locAnchorPoint = this._anchorPoint;
- var cmd = this._renderCmd;
-
- if (x === locAnchorPoint.x)
- return;
- locAnchorPoint.x = x;
-
- var locAPP = cmd._anchorPointInPoints, locSize = this._contentSize;
- locAPP.x = locSize.width * locAnchorPoint.x;
-
- this.dom.style[cc.$.pfx + 'TransformOrigin'] = '' + locAPP.x + 'px ' + -locAPP.y + 'px';
- if (this.ignoreAnchor) {
- this.dom.style.marginLeft = 0;
- this.dom.style.marginBottom = 0;
- } else {
- this.dom.style.marginLeft = (this.isToggler) ? 0 : -locAPP.x + 'px';
- }
- this.setNodeDirty();
- },
-
- /**
- * replace set anchorpoint y of ccNode
- * @param {Number} y The anchor y of node.
- */
- _setAnchorY:function (y) {
- var locAnchorPoint = this._anchorPoint;
- var cmd = this._renderCmd;
-
- if (y === locAnchorPoint.y)
- return;
- locAnchorPoint.y = y;
-
- var locAPP = cmd._anchorPointInPoints, locSize = this._contentSize;
- locAPP.y = locSize.height * locAnchorPoint.y;
-
- this.dom.style[cc.$.pfx + 'TransformOrigin'] = '' + locAPP.x + 'px ' + -locAPP.y + 'px';
- if (this.ignoreAnchor) {
- this.dom.style.marginLeft = 0;
- this.dom.style.marginBottom = 0;
- } else {
- this.dom.style.marginBottom = -locAPP.y + 'px';
- }
- this.setNodeDirty();
- },
-
- /**
- * replace set ContentSize of ccNode
- * @param {cc.Size|Number} size The untransformed size of the node or The untransformed size's width of the node.
- * @param {Number} [height] The untransformed size's height of the node.
- */
- setContentSize:function (size, height) {
- var cmd = this._renderCmd;
-
- var locContentSize = this._contentSize;
- if (height === undefined) {
- locContentSize.width = size.width;
- locContentSize.height = size.height;
- } else {
- locContentSize.width = size;
- locContentSize.height = height;
- }
- var locAPP = cmd._anchorPointInPoints, locAnchorPoint = this._anchorPoint;
- locAPP.x = locContentSize.width * locAnchorPoint.x;
- locAPP.y = locContentSize.height * locAnchorPoint.y;
- this.dom.width = locContentSize.width;
- this.dom.height = locContentSize.height;
- this.setAnchorPoint(this.getAnchorPoint());
- if (this.canvas) {
- this.canvas.width = locContentSize.width;
- this.canvas.height = locContentSize.height;
- }
- this.setNodeDirty();
- this.redraw();
- },
-
- /**
- * replace set width of ccNode
- * @param {Number} width The untransformed size's width of the node.
- */
- _setWidth:function (width) {
- var locContentSize = this._contentSize;
- var cmd = this._renderCmd;
- if (width === locContentSize.width)
- return;
- locContentSize.width = width;
-
- var locAPP = cmd._anchorPointInPoints, locAnchorPoint = this._anchorPoint;
- locAPP.x = locContentSize.width * locAnchorPoint.x;
- this.dom.width = locContentSize.width;
- this.anchorX = locAnchorPoint.x;
- if (this.canvas) {
- this.canvas.width = locContentSize.width;
- }
- this.setNodeDirty();
- this.redraw();
- },
-
- /**
- * replace set height of ccNode
- * @param {Number} height The untransformed size's height of the node.
- */
- _setHeight:function (height) {
- var locContentSize = this._contentSize;
- var cmd = this._renderCmd;
- if (height === locContentSize.height)
- return;
- locContentSize.height = height;
-
- var locAPP = cmd._anchorPointInPoints, locAnchorPoint = this._anchorPoint;
- locAPP.y = locContentSize.height * locAnchorPoint.y;
- this.dom.height = locContentSize.height;
- this.anchorY = locAnchorPoint.y;
- if (this.canvas) {
- this.canvas.height = locContentSize.height;
- }
- this.setNodeDirty();
- this.redraw();
- },
-
- /**
- * replace set Rotation of ccNode
- * @param {Number} newRotation
- */
- setRotation:function (newRotation) {
- if (this._rotation === newRotation)
- return;
-
- this._rotationX = this._rotationY = newRotation;
- this.setNodeDirty();
- this.dom.rotate(newRotation);
- },
-
- /**
- * replace set SkewX of ccNode
- * @param {Number} x
- */
- setSkewX:function (x) {
- this._skewX = x;
- this.setNodeDirty();
- this.dom.setSkew(this._skewX, this._skewY);
- },
-
- /**
- * replace set SkewY of ccNode
- * @param {Number} y
- */
- setSkewY:function (y) {
- this._skewY = y;
- this.setNodeDirty();
- this.dom.setSkew(this._skewX, this._skewY);
- },
-
- /**
- * replace set Visible of ccNode
- * @param {Boolean} x
- */
- setVisible:function (x) {
- this._visible = x;
- this.setNodeDirty();
- if (this.dom)
- this.dom.style.display = (x) ? 'block' : 'none';
- },
- _setLocalZOrder:function (z) {
- this._localZOrder = z;
- this.setNodeDirty();
- if (this.dom)
- this.dom.zIndex = z;
- },
-
- /**
- * replace set Parent of ccNode
- * @param {cc.Node} p
- */
- setParent:function (p) {
- this._parent = p;
-
- if (p !== null) {
- p.setAnchorPoint(p.getAnchorPoint());
- this.setNodeDirty();
- cc.DOM.parentDOM(this);
- }
- },
-
- /**
- * replace resume Schedule and actions of ccNode
- */
- resume:function () {
- this.getScheduler().resumeTarget(this);
- this.getActionManager().resumeTarget(this);
- cc.eventManager.resumeTarget(this);
- //if dom does not have parent, but node has no parent and its running
- if (this.dom && !this.dom.parentNode) {
- if (!this.getParent()) {
- if(this.dom.id === ""){
- cc.DOM._createEGLViewDiv(this);
- }else{
- this.dom.appendTo(cc.container);
- }
- } else {
- cc.DOM.parentDOM(this);
- }
- }
- if (this.dom)
- this.dom.style.visibility = "visible";
- },
-
- /**
- * replace pause Schedule and Actions of ccNode
- */
- pause:function () {
- this.getScheduler().pauseTarget(this);
- this.getActionManager().pauseTarget(this);
- cc.eventManager.pauseTarget(this);
- if (this.dom) {
- this.dom.style.visibility = 'hidden';
- }
- },
-
- /**
- * replace clean up of ccNode
- */
- cleanup:function () {
- // actions
- this.stopAllActions();
- this.unscheduleAllCallbacks();
-
- cc.eventManager.removeListeners(this);
-
- // timers
- this._arrayMakeObjectsPerformSelector(this._children, cc.Node._stateCallbackType.cleanup);
- if (this.dom) {
- this.dom.remove();
- }
- },
- setOpacity:function (o) {
- this._opacity = o;
- this.dom.style.opacity = o / 255;
- },
- /**
- * refresh/updates the DOM element
- */
- redraw:function () {
- if (this.isSprite) {
- var tmp = this._children;
- this._children = [];
- cc.Sprite.prototype.visit.call(this, this.ctx);
- this._children = tmp;
- }
- else {
- cc.Sprite.prototype.visit.call(this, this.ctx);
- }
- }
-};
-
-cc.DOM._resetEGLViewDiv = function(){
- var div = cc.$("#EGLViewDiv");
- if(div){
- var view = cc.view;
- var designSize = view.getDesignResolutionSize();
- var viewPortRect = view.getViewPortRect();
- var screenSize = view.getFrameSize();
- var pixelRatio = view.getDevicePixelRatio();
- var designSizeWidth = designSize.width, designSizeHeight = designSize.height;
- var paddingLeft = parseInt(cc.container.style.paddingLeft),
- paddingBottom = parseInt(cc.container.style.paddingBottom);
- if((designSize.width === 0) && (designSize.height === 0)){
- designSizeWidth = screenSize.width;
- designSizeHeight = screenSize.height;
- }
-
- var viewPortWidth = viewPortRect.width/pixelRatio;
- if((viewPortRect.width === 0) && (viewPortRect.height === 0)){
- viewPortWidth = screenSize.width;
- }
-
- div.style.position = 'absolute';
- //x.dom.style.display='block';
- div.style.width = designSizeWidth + "px";
- div.style.maxHeight = designSizeHeight + "px";
- div.style.margin = 0;
-
- div.resize(view.getScaleX()/pixelRatio, view.getScaleY()/pixelRatio);
- div.translates(paddingLeft, -paddingBottom);
- if (view.getResolutionPolicy() === view._rpNoBorder) {
- div.style.left = (view.getFrameSize().width - designSizeWidth)/2 + "px";
- div.style.bottom = (view.getFrameSize().height - designSizeHeight*view.getScaleY()/pixelRatio)/2 + "px";
- }
- else {
- div.style.left = (designSizeWidth*view.getScaleX()/pixelRatio - designSizeWidth) / 2 + "px";
- div.style.bottom = "0px";
- }
- }
-};
-
-/**
- * @function
- * @private
- * @param x
- * @return {Boolean}
- */
-cc.DOM.parentDOM = function (x) {
- var p = x.getParent();
- //if has parent, parent need to have dom too
- if (!p || !x.dom)
- return false;
- if (!p.dom) {
- cc.DOM.placeHolder(p);
- p.setParent = cc.DOM.methods.setParent;
- }
- //if parent have dom, attach self to parent
- x.dom.appendTo(p.dom);
- p.setAnchorPoint(p.getAnchorPoint());
-
- if (p.getParent()) {
- 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 {
- cc.DOM._createEGLViewDiv(p);
- }
- }
- }
- return true;
-};
-
-cc.DOM._createEGLViewDiv = function(p){
- var div = cc.$("#EGLViewDiv");
- if(!div){
- div = cc.$new("div");
- div.id = "EGLViewDiv";
- }
-
- var view = cc.view;
- var designSize = view.getDesignResolutionSize();
- var viewPortRect = view.getViewPortRect();
- var screenSize = view.getFrameSize();
- var pixelRatio = view.getDevicePixelRatio();
- var designSizeWidth = designSize.width, designSizeHeight = designSize.height;
- var paddingLeft = parseInt(cc.container.style.paddingLeft),
- paddingBottom = parseInt(cc.container.style.paddingBottom);
- if ((designSize.width === 0) && (designSize.height === 0)) {
- designSizeWidth = screenSize.width;
- designSizeHeight = screenSize.height;
- }
-
- var viewPortWidth = viewPortRect.width/pixelRatio;
- if ((viewPortRect.width === 0) && (viewPortRect.height === 0)) {
- viewPortWidth = screenSize.width;
- }
-
- div.style.position = 'absolute';
- //x.dom.style.display='block';
- div.style.width = designSizeWidth + "px";
- div.style.maxHeight = designSizeHeight + "px";
- div.style.margin = 0;
-
- div.resize(view.getScaleX()/pixelRatio, view.getScaleY()/pixelRatio);
- div.translates(paddingLeft, -paddingBottom);
- if (view.getResolutionPolicy() === view._rpNoBorder) {
- div.style.left = (screenSize.width - designSizeWidth)/2 + "px";
- div.style.bottom = (screenSize.height - designSizeHeight*view.getScaleY()/pixelRatio)/2 + "px";
- }
- else {
- div.style.left = (designSizeWidth*view.getScaleX()/pixelRatio - designSizeWidth) / 2 + "px";
- div.style.bottom = "0px";
- }
-
- p.dom.appendTo(div);
- div.appendTo(cc.container);
-};
-
-/**
- * @function
- * @private
- * @param x
- */
-cc.DOM.setTransform = function (x) {
- if (x.ctx) {
- x.ctx.translate(x.getAnchorPointInPoints().x, x.getAnchorPointInPoints().y);
- if (x.isSprite) {
- var tmp = x._children;
- x._children = [];
- cc.Sprite.prototype.visit.call(x);
- x._children = tmp;
- }
- else {
- cc.Sprite.prototype.visit.call(x);
- }
- }
- if (x.dom) {
- x.dom.position.x = x.getPositionX();
- x.dom.position.y = -x.getPositionY();
- x.dom.rotation = x.getRotation();
- x.dom.scale = {x:x.getScaleX(), y:x.getScaleY()};
- x.dom.skew = {x:x.getSkewX(), y:x.getSkewY()};
- if (x.setAnchorPoint)
- x.setAnchorPoint(x.getAnchorPoint());
- x.dom.transforms();
- }
-
-};
-
-/**
- * @function
- * @private
- * @param x
- */
-cc.DOM.forSprite = function (x) {
- x.dom = cc.$new('div');
- x.canvas = cc.$new('canvas');
- var locContentSize = x.getContentSize();
- x.canvas.width = locContentSize.width;
- x.canvas.height = locContentSize.height;
- x.dom.style.position = 'absolute';
- x.dom.style.bottom = 0;
- x.ctx = x.canvas.getContext('2d');
- x.dom.appendChild(x.canvas);
- if (x.getParent()) {
- cc.DOM.parentDOM(x);
- }
- x.isSprite = true;
-};
-
-/**
- * This creates divs for parent Nodes that are related to the current node
- * @function
- * @private
- * @param x
- */
-cc.DOM.placeHolder = function (x) {
- //creating a placeholder dom to simulate other ccNode in the hierarchy
- x.dom = cc.$new('div');
- x.placeholder = true;
- x.dom.style.position = 'absolute';
- x.dom.style.bottom = 0;
- //x.dom.style.display='block';
- x.dom.style.width = (x.getContentSize().width || cc.director.getWinSize().width) + "px";
- x.dom.style.maxHeight = (x.getContentSize().height || cc.director.getWinSize().height) + "px";
- x.dom.style.margin = 0;
- cc.DOM.setTransform(x);
- x.dom.transforms();
- cc.DOM._addMethods(x);
- //x.dom.style.border = 'red 1px dotted';
-};
-
-/**
- * Converts cc.Sprite or cc.MenuItem to DOM elements
- * It currently only supports cc.Sprite and cc.MenuItem
- * @function
- * @param {cc.Sprite|cc.MenuItem|Array} nodeObject
- * @example
- * // example
- * cc.DOM.convert(Sprite1, Sprite2, Menuitem);
- *
- * var myDOMElements = [Sprite1, Sprite2, MenuItem];
- * cc.DOM.convert(myDOMElements);
- */
-cc.DOM.convert = function (nodeObject) {
- //if passing by list, make it an array
- if (arguments.length > 1) {
- cc.DOM.convert(arguments);
- return;
- } else if (arguments.length === 1 && !arguments[0].length) {
- cc.DOM.convert([arguments[0]]);
- return;
- }
- var args = arguments[0];
- for (var i = 0; i < args.length; i++) {
- //first check if its sprite
- if (args[i] instanceof cc.Sprite) {
- // create a canvas
- if (!args[i].dom)
- cc.DOM.forSprite(args[i]);
- } else {
- cc.log('DOM converter only supports sprite and menuitems yet');
- }
- cc.DOM._addMethods(args[i]);
- args[i].visit = function () {
- };
- args[i].transform = function () {
- };
- cc.DOM.setTransform(args[i]);
- args[i].setVisible(args[i].isVisible());
- }
-};
diff --git a/extensions/gui/control-extension/CCControl.js b/extensions/gui/control-extension/CCControl.js
index 2ff72a7ee7..e4071a3ef2 100644
--- a/extensions/gui/control-extension/CCControl.js
+++ b/extensions/gui/control-extension/CCControl.js
@@ -148,29 +148,26 @@ cc.Control = cc.Layer.extend(/** @lends cc.Control# */{
},
init: function () {
- if (cc.Layer.prototype.init.call(this)) {
- // Initialise instance variables
- this._state = cc.CONTROL_STATE_NORMAL;
- this._enabled = true;
- this._selected = false;
- this._highlighted = false;
-
- var listener = cc.EventListener.create({
- event: cc.EventListener.TOUCH_ONE_BY_ONE,
- swallowTouches: true
- });
- if (this.onTouchBegan)
- listener.onTouchBegan = this.onTouchBegan.bind(this);
- if (this.onTouchMoved)
- listener.onTouchMoved = this.onTouchMoved.bind(this);
- if (this.onTouchEnded)
- listener.onTouchEnded = this.onTouchEnded.bind(this);
- if (this.onTouchCancelled)
- listener.onTouchCancelled = this.onTouchCancelled.bind(this);
- this._touchListener = listener;
- return true;
- } else
- return false;
+ // Initialise instance variables
+ this._state = cc.CONTROL_STATE_NORMAL;
+ this._enabled = true;
+ this._selected = false;
+ this._highlighted = false;
+
+ var listener = cc.EventListener.create({
+ event: cc.EventListener.TOUCH_ONE_BY_ONE,
+ swallowTouches: true
+ });
+ if (this.onTouchBegan)
+ listener.onTouchBegan = this.onTouchBegan.bind(this);
+ if (this.onTouchMoved)
+ listener.onTouchMoved = this.onTouchMoved.bind(this);
+ if (this.onTouchEnded)
+ listener.onTouchEnded = this.onTouchEnded.bind(this);
+ if (this.onTouchCancelled)
+ listener.onTouchCancelled = this.onTouchCancelled.bind(this);
+ this._touchListener = listener;
+ return true;
},
onEnter: function () {
diff --git a/extensions/gui/scrollview/CCScrollView.js b/extensions/gui/scrollview/CCScrollView.js
index f28592f67b..bedba0ac04 100644
--- a/extensions/gui/scrollview/CCScrollView.js
+++ b/extensions/gui/scrollview/CCScrollView.js
@@ -40,19 +40,19 @@ var SCROLL_DEACCEL_RATE = 0.95;
var SCROLL_DEACCEL_DIST = 1.0;
var BOUNCE_DURATION = 0.15;
var INSET_RATIO = 0.2;
-var MOVE_INCH = 7.0/160.0;
+var MOVE_INCH = 7.0 / 160.0;
var BOUNCE_BACK_FACTOR = 0.35;
-cc.convertDistanceFromPointToInch = function(pointDis){
+cc.convertDistanceFromPointToInch = function (pointDis) {
var eglViewer = cc.view;
- var factor = (eglViewer.getScaleX() + eglViewer.getScaleY())/2;
+ var factor = (eglViewer.getScaleX() + eglViewer.getScaleY()) / 2;
return (pointDis * factor) / 160; // CCDevice::getDPI() default value
};
cc.ScrollViewDelegate = cc.Class.extend({
- scrollViewDidScroll:function (view) {
+ scrollViewDidScroll: function (view) {
},
- scrollViewDidZoom:function (view) {
+ scrollViewDidZoom: function (view) {
}
});
@@ -72,35 +72,35 @@ cc.ScrollViewDelegate = cc.Class.extend({
* @property {Boolean} clippingToBounds - Indicate whether the scroll view clips its children
*/
cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
- _zoomScale:0,
- _minZoomScale:0,
- _maxZoomScale:0,
- _delegate:null,
- _direction:cc.SCROLLVIEW_DIRECTION_BOTH,
- _dragging:false,
- _contentOffset:null,
- _container:null,
- _touchMoved:false,
- _maxInset:null,
- _minInset:null,
- _bounceable:false,
- _clippingToBounds:false,
- _scrollDistance:null,
- _touchPoint:null,
- _touchLength:0,
- _touches:null,
- _viewSize:null,
- _minScale:0,
- _maxScale:0,
+ _zoomScale: 0,
+ _minZoomScale: 0,
+ _maxZoomScale: 0,
+ _delegate: null,
+ _direction: cc.SCROLLVIEW_DIRECTION_BOTH,
+ _dragging: false,
+ _contentOffset: null,
+ _container: null,
+ _touchMoved: false,
+ _maxInset: null,
+ _minInset: null,
+ _bounceable: false,
+ _clippingToBounds: false,
+ _scrollDistance: null,
+ _touchPoint: null,
+ _touchLength: 0,
+ _touches: null,
+ _viewSize: null,
+ _minScale: 0,
+ _maxScale: 0,
//scissor rect for parent, just for restoring GL_SCISSOR_BOX
- _parentScissorRect:null,
- _scissorRestored:false,
+ _parentScissorRect: null,
+ _scissorRestored: false,
// cache object
- _tmpViewRect:null,
+ _tmpViewRect: null,
_touchListener: null,
- _className:"ScrollView",
+ _className: "ScrollView",
/**
* @contructor
@@ -108,26 +108,26 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
* @param container
* @returns {ScrollView}
*/
- ctor:function (size, container) {
+ ctor: function (size, container) {
cc.Layer.prototype.ctor.call(this);
- this._contentOffset = cc.p(0,0);
+ this._contentOffset = cc.p(0, 0);
this._maxInset = cc.p(0, 0);
this._minInset = cc.p(0, 0);
this._scrollDistance = cc.p(0, 0);
this._touchPoint = cc.p(0, 0);
this._touches = [];
this._viewSize = cc.size(0, 0);
- this._parentScissorRect = new cc.Rect(0,0,0,0);
- this._tmpViewRect = new cc.Rect(0,0,0,0);
+ this._parentScissorRect = new cc.Rect(0, 0, 0, 0);
+ this._tmpViewRect = new cc.Rect(0, 0, 0, 0);
- if(container != undefined)
+ if (container != undefined)
this.initWithViewSize(size, container);
else
this.initWithViewSize(cc.size(200, 200), null);
},
- init:function () {
+ init: function () {
return this.initWithViewSize(cc.size(200, 200), null);
},
@@ -137,8 +137,8 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
* @param {cc.Node} container
* @return {Boolean}
*/
- initWithViewSize:function (size, container) {
- var pZero = cc.p(0,0);
+ initWithViewSize: function (size, container) {
+ var pZero = cc.p(0, 0);
if (cc.Layer.prototype.init.call(this)) {
if (!container && !this._container) {
container = new cc.Layer();
@@ -165,6 +165,38 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
return false;
},
+ visit: function (parent) {
+ var cmd = this._renderCmd, parentCmd = parent ? parent._renderCmd : null;
+
+ // quick return if not visible
+ if (!this._visible) {
+ cmd._propagateFlagsDown(parentCmd);
+ return;
+ }
+
+ var renderer = cc.renderer;
+ cmd.visit(parentCmd);
+
+ if (this._clippingToBounds) {
+ renderer.pushRenderCommand(cmd.startCmd);
+ }
+
+ var i, children = this._children, len = children.length;
+ if (len > 0) {
+ if (this._reorderChildDirty) {
+ this.sortAllChildren();
+ }
+ for (i = 0; i < len; i++) {
+ children[i].visit(this);
+ }
+ }
+
+ if (this._clippingToBounds) {
+ renderer.pushRenderCommand(cmd.endCmd);
+ }
+ cmd._dirtyFlag = 0;
+ },
+
/**
* Sets a new content offset. It ignores max/min offset. It just sets what's given. (just like UIKit's UIScrollView)
*
@@ -192,7 +224,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
},
- getContentOffset:function () {
+ getContentOffset: function () {
var locPos = this._container.getPosition();
return cc.p(locPos.x, locPos.y);
},
@@ -204,7 +236,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
* @param {cc.Point} offset new offset
* @param {Number} dt animation duration
*/
- setContentOffsetInDuration:function (offset, dt) {
+ setContentOffsetInDuration: function (offset, dt) {
var scroll = cc.moveTo(dt, offset);
var expire = cc.callFunc(this._stoppedAnimatedScroll, this);
this._container.runAction(cc.sequence(scroll, expire));
@@ -246,7 +278,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
}
},
- getZoomScale:function () {
+ getZoomScale: function () {
return this._container.getScale();
},
@@ -256,7 +288,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
* @param {Number} s a new scale value
* @param {Number} dt animation duration
*/
- setZoomScaleInDuration:function (s, dt) {
+ setZoomScaleInDuration: function (s, dt) {
if (dt > 0) {
var locScale = this._container.getScale();
if (locScale !== s) {
@@ -272,7 +304,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
* Returns the current container's minimum offset. You may want this while you animate scrolling by yourself
* @return {cc.Point} Returns the current container's minimum offset.
*/
- minContainerOffset:function () {
+ minContainerOffset: function () {
var locContainer = this._container;
var locContentSize = locContainer.getContentSize(), locViewSize = this._viewSize;
return cc.p(locViewSize.width - locContentSize.width * locContainer.getScaleX(),
@@ -283,7 +315,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
* Returns the current container's maximum offset. You may want this while you animate scrolling by yourself
* @return {cc.Point} Returns the current container's maximum offset.
*/
- maxContainerOffset:function () {
+ maxContainerOffset: function () {
return cc.p(0.0, 0.0);
},
@@ -292,7 +324,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
* @param {cc.Node} node
* @return {Boolean} YES if it is in visible bounds
*/
- isNodeVisible:function (node) {
+ isNodeVisible: function (node) {
var offset = this.getContentOffset();
var size = this.getViewSize();
var scale = this.getZoomScale();
@@ -305,7 +337,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
/**
* Provided to make scroll view compatible with SWLayer's pause method
*/
- pause:function (sender) {
+ pause: function (sender) {
this._container.pause();
var selChildren = this._container.getChildren();
for (var i = 0; i < selChildren.length; i++) {
@@ -317,7 +349,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
/**
* Provided to make scroll view compatible with SWLayer's resume method
*/
- resume:function (sender) {
+ resume: function (sender) {
var selChildren = this._container.getChildren();
for (var i = 0, len = selChildren.length; i < len; i++) {
selChildren[i].resume();
@@ -326,16 +358,16 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
this._super();
},
- isDragging:function () {
+ isDragging: function () {
return this._dragging;
},
- isTouchMoved:function () {
+ isTouchMoved: function () {
return this._touchMoved;
},
- isBounceable:function () {
+ isBounceable: function () {
return this._bounceable;
},
- setBounceable:function (bounceable) {
+ setBounceable: function (bounceable) {
this._bounceable = bounceable;
},
@@ -346,20 +378,20 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
* Hence, this scroll view will use a separate size property.
*
*/
- getViewSize:function () {
+ getViewSize: function () {
return this._viewSize;
},
- setViewSize:function (size) {
+ setViewSize: function (size) {
this._viewSize = size;
- cc.Node.prototype.setContentSize.call(this,size);
+ cc.Node.prototype.setContentSize.call(this, size);
},
- getContainer:function () {
+ getContainer: function () {
return this._container;
},
- setContainer:function (container) {
+ setContainer: function (container) {
// Make sure that 'm_pContainer' has a non-NULL value since there are
// lots of logic that use 'm_pContainer'.
if (!container)
@@ -378,23 +410,23 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
/**
* direction allowed to scroll. CCScrollViewDirectionBoth by default.
*/
- getDirection:function () {
+ getDirection: function () {
return this._direction;
},
- setDirection:function (direction) {
+ setDirection: function (direction) {
this._direction = direction;
},
- getDelegate:function () {
+ getDelegate: function () {
return this._delegate;
},
- setDelegate:function (delegate) {
+ setDelegate: function (delegate) {
this._delegate = delegate;
},
/** override functions */
// optional
- onTouchBegan:function (touch, event) {
+ onTouchBegan: function (touch, event) {
for (var c = this; c != null; c = c.parent) {
if (!c.isVisible())
return false;
@@ -430,7 +462,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
return true;
},
- onTouchMoved:function (touch, event) {
+ onTouchMoved: function (touch, event) {
if (!this.isVisible())
return;
@@ -447,17 +479,17 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
var moveDistance = cc.pSub(newPoint, this._touchPoint);
var dis = 0.0, locDirection = this._direction, pos;
- if (locDirection === cc.SCROLLVIEW_DIRECTION_VERTICAL){
+ if (locDirection === cc.SCROLLVIEW_DIRECTION_VERTICAL) {
dis = moveDistance.y;
pos = this._container.getPositionY();
if (!(this.minContainerOffset().y <= pos && pos <= this.maxContainerOffset().y))
moveDistance.y *= BOUNCE_BACK_FACTOR;
- } else if (locDirection === cc.SCROLLVIEW_DIRECTION_HORIZONTAL){
+ } else if (locDirection === cc.SCROLLVIEW_DIRECTION_HORIZONTAL) {
dis = moveDistance.x;
pos = this._container.getPositionX();
if (!(this.minContainerOffset().x <= pos && pos <= this.maxContainerOffset().x))
moveDistance.x *= BOUNCE_BACK_FACTOR;
- }else {
+ } else {
dis = Math.sqrt(moveDistance.x * moveDistance.x + moveDistance.y * moveDistance.y);
pos = this._container.getPositionY();
@@ -470,12 +502,12 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
moveDistance.x *= BOUNCE_BACK_FACTOR;
}
- if (!this._touchMoved && Math.abs(cc.convertDistanceFromPointToInch(dis)) < MOVE_INCH ){
+ if (!this._touchMoved && Math.abs(cc.convertDistanceFromPointToInch(dis)) < MOVE_INCH) {
//CCLOG("Invalid movement, distance = [%f, %f], disInch = %f", moveDistance.x, moveDistance.y);
return;
}
- if (!this._touchMoved){
+ if (!this._touchMoved) {
moveDistance.x = 0;
moveDistance.y = 0;
}
@@ -509,7 +541,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
}
},
- onTouchEnded:function (touch, event) {
+ onTouchEnded: function (touch, event) {
if (!this.isVisible())
return;
@@ -521,7 +553,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
this._touchMoved = false;
},
- onTouchCancelled:function (touch, event) {
+ onTouchCancelled: function (touch, event) {
if (!this.isVisible())
return;
@@ -532,33 +564,33 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
setContentSize: function (size, height) {
if (this.getContainer() !== null) {
- if(height === undefined)
+ if (height === undefined)
this.getContainer().setContentSize(size);
else
this.getContainer().setContentSize(size, height);
this.updateInset();
}
},
- _setWidth: function (value) {
- var container = this.getContainer();
- if (container !== null) {
- container._setWidth(value);
- this.updateInset();
- }
- },
- _setHeight: function (value) {
- var container = this.getContainer();
- if (container !== null) {
- container._setHeight(value);
- this.updateInset();
- }
- },
-
- getContentSize:function () {
+ _setWidth: function (value) {
+ var container = this.getContainer();
+ if (container !== null) {
+ container._setWidth(value);
+ this.updateInset();
+ }
+ },
+ _setHeight: function (value) {
+ var container = this.getContainer();
+ if (container !== null) {
+ container._setHeight(value);
+ this.updateInset();
+ }
+ },
+
+ getContentSize: function () {
return this._container.getContentSize();
},
- updateInset:function () {
+ updateInset: function () {
if (this.getContainer() !== null) {
var locViewSize = this._viewSize;
var tempOffset = this.maxContainerOffset();
@@ -573,15 +605,15 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
/**
* Determines whether it clips its children or not.
*/
- isClippingToBounds:function () {
+ isClippingToBounds: function () {
return this._clippingToBounds;
},
- setClippingToBounds:function (clippingToBounds) {
+ setClippingToBounds: function (clippingToBounds) {
this._clippingToBounds = clippingToBounds;
},
- addChild:function (child, zOrder, tag) {
+ addChild: function (child, zOrder, tag) {
if (!child)
throw new Error("child must not nil!");
@@ -597,12 +629,12 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
}
},
- isTouchEnabled: function(){
+ isTouchEnabled: function () {
return this._touchListener !== null;
},
- setTouchEnabled:function (e) {
- if(this._touchListener)
+ setTouchEnabled: function (e) {
+ if (this._touchListener)
cc.eventManager.removeListener(this._touchListener);
this._touchListener = null;
if (!e) {
@@ -613,13 +645,13 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
var listener = cc.EventListener.create({
event: cc.EventListener.TOUCH_ONE_BY_ONE
});
- if(this.onTouchBegan)
+ if (this.onTouchBegan)
listener.onTouchBegan = this.onTouchBegan.bind(this);
- if(this.onTouchMoved)
+ if (this.onTouchMoved)
listener.onTouchMoved = this.onTouchMoved.bind(this);
- if(this.onTouchEnded)
+ if (this.onTouchEnded)
listener.onTouchEnded = this.onTouchEnded.bind(this);
- if(this.onTouchCancelled)
+ if (this.onTouchCancelled)
listener.onTouchCancelled = this.onTouchCancelled.bind(this);
this._touchListener = listener;
cc.eventManager.addListener(listener, this);
@@ -632,7 +664,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
* @param size view size
* @return initialized scroll view object
*/
- _initWithViewSize:function (size) {
+ _initWithViewSize: function (size) {
return null;
},
@@ -641,7 +673,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
*
* @param animated If YES, relocation is animated
*/
- _relocateContainer:function (animated) {
+ _relocateContainer: function (animated) {
var min = this.minContainerOffset();
var max = this.maxContainerOffset();
var locDirection = this._direction;
@@ -669,7 +701,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
*
* @param {Number} dt delta
*/
- _deaccelerateScrolling:function (dt) {
+ _deaccelerateScrolling: function (dt) {
if (this._dragging) {
this.unschedule(this._deaccelerateScrolling);
return;
@@ -678,7 +710,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
var maxInset, minInset;
var oldPosition = this._container.getPosition();
var locScrollDistance = this._scrollDistance;
- this._container.setPosition(oldPosition.x + locScrollDistance.x , oldPosition.y + locScrollDistance.y);
+ this._container.setPosition(oldPosition.x + locScrollDistance.x, oldPosition.y + locScrollDistance.y);
if (this._bounceable) {
maxInset = this._maxInset;
minInset = this._minInset;
@@ -709,7 +741,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
/**
* This method makes sure auto scrolling causes delegate to invoke its method
*/
- _performedAnimatedScroll:function (dt) {
+ _performedAnimatedScroll: function (dt) {
if (this._dragging) {
this.unschedule(this._performedAnimatedScroll);
return;
@@ -721,7 +753,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
/**
* Expire animated scroll delegate calls
*/
- _stoppedAnimatedScroll:function (node) {
+ _stoppedAnimatedScroll: function (node) {
this.unschedule(this._performedAnimatedScroll);
// After the animation stopped, "scrollViewDidScroll" should be invoked, this could fix the bug of lack of tableview cells.
if (this._delegate && this._delegate.scrollViewDidScroll) {
@@ -732,11 +764,11 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
/**
* Zoom handling
*/
- _handleZoom:function () {
+ _handleZoom: function () {
},
- _getViewRect:function(){
- var screenPos = this.convertToWorldSpace(cc.p(0,0));
+ _getViewRect: function () {
+ var screenPos = this.convertToWorldSpace(cc.p(0, 0));
var locViewSize = this._viewSize;
var scaleX = this.getScaleX();
@@ -767,7 +799,7 @@ cc.ScrollView = cc.Layer.extend(/** @lends cc.ScrollView# */{
return locViewRect;
},
- _createRenderCmd: function(){
+ _createRenderCmd: function () {
if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
return new cc.ScrollView.CanvasRenderCmd(this);
} else {
@@ -815,4 +847,4 @@ _p = null;
*/
cc.ScrollView.create = function (size, container) {
return new cc.ScrollView(size, container);
-};
\ No newline at end of file
+};
diff --git a/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js b/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js
index 7b5e89c715..0cc063f846 100644
--- a/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js
+++ b/extensions/gui/scrollview/CCScrollViewCanvasRenderCmd.js
@@ -22,9 +22,9 @@
THE SOFTWARE.
****************************************************************************/
-(function() {
- cc.ScrollView.CanvasRenderCmd = function(renderable){
- cc.Layer.CanvasRenderCmd.call(this, renderable);
+(function () {
+ cc.ScrollView.CanvasRenderCmd = function (renderable) {
+ this._layerCmdCtor(renderable);
this._needDraw = false;
this.startCmd = new cc.CustomRenderCmd(this, this._startCmd);
@@ -36,7 +36,7 @@
var proto = cc.ScrollView.CanvasRenderCmd.prototype = Object.create(cc.Layer.CanvasRenderCmd.prototype);
proto.constructor = cc.ScrollView.CanvasRenderCmd;
- proto._startCmd = function(ctx, scaleX, scaleY){
+ proto._startCmd = function (ctx, scaleX, scaleY) {
var node = this._node;
var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
wrapper.save();
@@ -57,29 +57,8 @@
}
};
- proto._endCmd = function(wrapper){
+ proto._endCmd = function (wrapper) {
wrapper = wrapper || cc._renderContext;
wrapper.restore();
};
-
- proto.visit = function(parentCmd){
- var node = this._node;
- if (!node._visible) return;
-
- var i, locChildren = node._children, childrenLen;
-
- this._syncStatus(parentCmd);
- cc.renderer.pushRenderCommand(this.startCmd);
-
- if (locChildren && locChildren.length > 0) {
- childrenLen = locChildren.length;
- node.sortAllChildren();
- for (i = 0; i < childrenLen; i++) {
- locChildren[i]._renderCmd.visit(this);
- }
- }
- cc.renderer.pushRenderCommand(this.endCmd);
-
- this._dirtyFlag = 0;
- };
})();
diff --git a/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js b/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js
index d435aac834..3d837db14f 100644
--- a/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js
+++ b/extensions/gui/scrollview/CCScrollViewWebGLRenderCmd.js
@@ -22,9 +22,9 @@
THE SOFTWARE.
****************************************************************************/
-(function() {
- cc.ScrollView.WebGLRenderCmd = function(renderable){
- cc.Layer.WebGLRenderCmd.call(this, renderable);
+(function () {
+ cc.ScrollView.WebGLRenderCmd = function (renderable) {
+ this._layerCmdCtor(renderable);
this._needDraw = false;
this.startCmd = new cc.CustomRenderCmd(this, this._startCmd);
@@ -34,11 +34,11 @@
var proto = cc.ScrollView.WebGLRenderCmd.prototype = Object.create(cc.Layer.WebGLRenderCmd.prototype);
proto.constructor = cc.ScrollView.WebGLRenderCmd;
- proto._startCmd = function(){
+ proto._startCmd = function () {
var node = this._node;
var EGLViewer = cc.view;
var frame = node._getViewRect();
- if(EGLViewer.isScissorEnabled()){
+ if (EGLViewer.isScissorEnabled()) {
node._scissorRestored = true;
node._parentScissorRect = EGLViewer.getScissorRect();
//set the intersection of m_tParentScissorRect and frame as the new scissor rect
@@ -50,7 +50,7 @@
var yy = Math.min(frame.y + frame.height, locPSRect.y + locPSRect.height);
EGLViewer.setScissorInPoints(x, y, xx - x, yy - y);
}
- }else{
+ } else {
var ctx = cc._renderContext;
ctx.enable(ctx.SCISSOR_TEST);
//clip
@@ -58,49 +58,14 @@
}
};
- proto._endCmd = function(){
+ proto._endCmd = function () {
var node = this._node;
if (node._scissorRestored) { //restore the parent's scissor rect
var rect = node._parentScissorRect;
cc.view.setScissorInPoints(rect.x, rect.y, rect.width, rect.height);
- }else{
+ } else {
var ctx = cc._renderContext;
ctx.disable(ctx.SCISSOR_TEST);
}
};
-
- proto.visit = function(parentCmd){
- var node = this._node;
- if (!node._visible) return;
-
- var i, locChildren = node._children, selChild, childrenLen;
-
- this._syncStatus(parentCmd);
-
- if (node._clippingToBounds) {
- cc.renderer.pushRenderCommand(this.startCmd);
- }
-
- if (locChildren && locChildren.length > 0) {
- childrenLen = locChildren.length;
- // draw children zOrder < 0
- for (i = 0; i < childrenLen; i++) {
- selChild = locChildren[i];
- if (selChild && selChild._localZOrder < 0)
- selChild._renderCmd.visit();
- else
- break;
- }
-
- // draw children zOrder >= 0
- for (; i < childrenLen; i++)
- locChildren[i]._renderCmd.visit();
- }
-
- if (node._clippingToBounds) {
- cc.renderer.pushRenderCommand(this.endCmd);
- }
-
- this._dirtyFlag = 0;
- };
-})();
\ No newline at end of file
+})();
diff --git a/extensions/gui/scrollview/CCTableView.js b/extensions/gui/scrollview/CCTableView.js
index b7b8ef044f..a197ada84a 100644
--- a/extensions/gui/scrollview/CCTableView.js
+++ b/extensions/gui/scrollview/CCTableView.js
@@ -48,30 +48,30 @@ cc.TABLEVIEW_FILL_BOTTOMUP = 1;
* @property {Number} objectId - The index used internally by SWTableView and its subclasses
*/
cc.TableViewCell = cc.Node.extend(/** @lends cc.TableViewCell# */{
- _idx:0,
- _className:"TableViewCell",
+ _idx: 0,
+ _className: "TableViewCell",
/**
* The index used internally by SWTableView and its subclasses
*/
- getIdx:function () {
+ getIdx: function () {
return this._idx;
},
- setIdx:function (idx) {
+ setIdx: function (idx) {
this._idx = idx;
},
/**
* Cleans up any resources linked to this cell and resets idx property.
*/
- reset:function () {
+ reset: function () {
this._idx = cc.INVALID_INDEX;
},
- setObjectID:function (idx) {
+ setObjectID: function (idx) {
this._idx = idx;
},
- getObjectID:function () {
+ getObjectID: function () {
return this._idx;
}
});
@@ -94,7 +94,7 @@ cc.TableViewDelegate = cc.ScrollViewDelegate.extend(/** @lends cc.TableViewDeleg
* @param {cc.TableView} table table contains the given cell
* @param {cc.TableViewCell} cell cell that is touched
*/
- tableCellTouched:function (table, cell) {
+ tableCellTouched: function (table, cell) {
},
/**
@@ -103,7 +103,7 @@ cc.TableViewDelegate = cc.ScrollViewDelegate.extend(/** @lends cc.TableViewDeleg
* @param {cc.TableView} table table contains the given cell
* @param {cc.TableViewCell} cell cell that is pressed
*/
- tableCellHighlight:function(table, cell){
+ tableCellHighlight: function (table, cell) {
},
/**
@@ -112,7 +112,7 @@ cc.TableViewDelegate = cc.ScrollViewDelegate.extend(/** @lends cc.TableViewDeleg
* @param {cc.TableView} table table contains the given cell
* @param {cc.TableViewCell} cell cell that is pressed
*/
- tableCellUnhighlight:function(table, cell){
+ tableCellUnhighlight: function (table, cell) {
},
@@ -125,7 +125,7 @@ cc.TableViewDelegate = cc.ScrollViewDelegate.extend(/** @lends cc.TableViewDeleg
* @param table table contains the given cell
* @param cell cell that is pressed
*/
- tableCellWillRecycle:function(table, cell){
+ tableCellWillRecycle: function (table, cell) {
}
});
@@ -140,7 +140,7 @@ cc.TableViewDataSource = cc.Class.extend(/** @lends cc.TableViewDataSource# */{
* @param {Number} idx the index of a cell to get a size
* @return {cc.Size} size of a cell at given index
*/
- tableCellSizeForIndex:function(table, idx){
+ tableCellSizeForIndex: function (table, idx) {
return this.cellSizeForTable(table);
},
/**
@@ -149,8 +149,8 @@ cc.TableViewDataSource = cc.Class.extend(/** @lends cc.TableViewDataSource# */{
* @param {cc.TableView} table table to hold the instances of Class
* @return {cc.Size} cell size
*/
- cellSizeForTable:function (table) {
- return cc.size(0,0);
+ cellSizeForTable: function (table) {
+ return cc.size(0, 0);
},
/**
@@ -159,7 +159,7 @@ cc.TableViewDataSource = cc.Class.extend(/** @lends cc.TableViewDataSource# */{
* @param idx index to search for a cell
* @return {cc.TableView} cell found at idx
*/
- tableCellAtIndex:function (table, idx) {
+ tableCellAtIndex: function (table, idx) {
return null;
},
@@ -168,7 +168,7 @@ cc.TableViewDataSource = cc.Class.extend(/** @lends cc.TableViewDataSource# */{
* @param {cc.TableView} table table to hold the instances of Class
* @return {Number} number of cells
*/
- numberOfCellsInTableView:function (table) {
+ numberOfCellsInTableView: function (table) {
return 0;
}
});
@@ -186,14 +186,14 @@ cc.TableViewDataSource = cc.Class.extend(/** @lends cc.TableViewDataSource# */{
*
*/
cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
- _vOrdering:null,
- _indices:null,
- _cellsFreed:null,
- _dataSource:null,
- _tableViewDelegate:null,
- _oldDirection:null,
- _cellsPositions:null, //vector with all cell positions
- _touchedCell:null,
+ _vOrdering: null,
+ _indices: null,
+ _cellsFreed: null,
+ _dataSource: null,
+ _tableViewDelegate: null,
+ _oldDirection: null,
+ _cellsPositions: null, //vector with all cell positions
+ _touchedCell: null,
/**
* The
@@ -201,7 +201,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
* @param size
* @param container
*/
- ctor:function (dataSource, size, container) {
+ ctor: function (dataSource, size, container) {
cc.ScrollView.prototype.ctor.call(this);
this._oldDirection = cc.SCROLLVIEW_DIRECTION_NONE;
this._cellsPositions = [];
@@ -212,7 +212,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
this._updateContentSize();
},
- __indexFromOffset:function (offset) {
+ __indexFromOffset: function (offset) {
var low = 0;
var high = this._dataSource.numberOfCellsInTableView(this) - 1;
var search;
@@ -226,16 +226,16 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
}
var locCellsPositions = this._cellsPositions;
- while (high >= low){
- var index = 0|(low + (high - low) / 2);
+ while (high >= low) {
+ var index = 0 | (low + (high - low) / 2);
var cellStart = locCellsPositions[index];
var cellEnd = locCellsPositions[index + 1];
- if (search >= cellStart && search <= cellEnd){
+ if (search >= cellStart && search <= cellEnd) {
return index;
- } else if (search < cellStart){
+ } else if (search < cellStart) {
high = index - 1;
- }else {
+ } else {
low = index + 1;
}
}
@@ -245,7 +245,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
return -1;
},
- _indexFromOffset:function (offset) {
+ _indexFromOffset: function (offset) {
var locOffset = {x: offset.x, y: offset.y};
var locDataSource = this._dataSource;
var maxIdx = locDataSource.numberOfCellsInTableView(this) - 1;
@@ -262,7 +262,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
return index;
},
- __offsetFromIndex:function (index) {
+ __offsetFromIndex: function (index) {
var offset;
switch (this.getDirection()) {
case cc.SCROLLVIEW_DIRECTION_HORIZONTAL:
@@ -276,7 +276,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
return offset;
},
- _offsetFromIndex:function (index) {
+ _offsetFromIndex: function (index) {
var offset = this.__offsetFromIndex(index);
var cellSize = this._dataSource.tableCellSizeForIndex(this, index);
@@ -286,14 +286,14 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
return offset;
},
- _updateCellPositions:function(){
+ _updateCellPositions: function () {
var cellsCount = this._dataSource.numberOfCellsInTableView(this);
var locCellsPositions = this._cellsPositions;
- if (cellsCount > 0){
+ if (cellsCount > 0) {
var currentPos = 0;
var cellSize, locDataSource = this._dataSource;
- for (var i=0; i < cellsCount; i++) {
+ for (var i = 0; i < cellsCount; i++) {
locCellsPositions[i] = currentPos;
cellSize = locDataSource.tableCellSizeForIndex(this, i);
switch (this.getDirection()) {
@@ -309,12 +309,12 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
}
},
- _updateContentSize:function () {
+ _updateContentSize: function () {
var size = cc.size(0, 0);
var cellsCount = this._dataSource.numberOfCellsInTableView(this);
- if(cellsCount > 0){
+ if (cellsCount > 0) {
var maxPosition = this._cellsPositions[cellsCount];
switch (this.getDirection()) {
case cc.SCROLLVIEW_DIRECTION_HORIZONTAL:
@@ -338,8 +338,8 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
}
},
- _moveCellOutOfSight:function (cell) {
- if(this._tableViewDelegate && this._tableViewDelegate.tableCellWillRecycle)
+ _moveCellOutOfSight: function (cell) {
+ if (this._tableViewDelegate && this._tableViewDelegate.tableCellWillRecycle)
this._tableViewDelegate.tableCellWillRecycle(this, cell);
this._cellsFreed.addObject(cell);
@@ -352,50 +352,52 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
}
},
- _setIndexForCell:function (index, cell) {
+ _setIndexForCell: function (index, cell) {
cell.setAnchorPoint(0, 0);
cell.setPosition(this._offsetFromIndex(index));
cell.setIdx(index);
},
- _addCellIfNecessary:function (cell) {
+ _addCellIfNecessary: function (cell) {
if (cell.getParent() !== this.getContainer()) {
this.getContainer().addChild(cell);
}
this._cellsUsed.insertSortedObject(cell);
var locIndices = this._indices, addIdx = cell.getIdx();
- if(locIndices.indexOf(addIdx) === -1){
+ if (locIndices.indexOf(addIdx) === -1) {
locIndices.push(addIdx);
//sort
- locIndices.sort(function(a,b){return a-b;});
+ locIndices.sort(function (a, b) {
+ return a - b;
+ });
}
},
/**
* data source
*/
- getDataSource:function () {
+ getDataSource: function () {
return this._dataSource;
},
- setDataSource:function (source) {
+ setDataSource: function (source) {
this._dataSource = source;
},
/**
* delegate
*/
- getDelegate:function () {
+ getDelegate: function () {
return this._tableViewDelegate;
},
- setDelegate:function (delegate) {
+ setDelegate: function (delegate) {
this._tableViewDelegate = delegate;
},
/**
* determines how cell is ordered and filled in the view.
*/
- setVerticalFillOrder:function (fillOrder) {
+ setVerticalFillOrder: function (fillOrder) {
if (this._vOrdering !== fillOrder) {
this._vOrdering = fillOrder;
if (this._cellsUsed.count() > 0) {
@@ -403,11 +405,11 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
}
}
},
- getVerticalFillOrder:function () {
+ getVerticalFillOrder: function () {
return this._vOrdering;
},
- initWithViewSize:function (size, container) {
+ initWithViewSize: function (size, container) {
if (cc.ScrollView.prototype.initWithViewSize.call(this, size, container)) {
this._cellsUsed = new cc.ArrayForObjectSorting();
this._cellsFreed = new cc.ArrayForObjectSorting();
@@ -427,7 +429,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
*
* @param idx index to find a cell
*/
- updateCellAtIndex:function (idx) {
+ updateCellAtIndex: function (idx) {
if (idx === cc.INVALID_INDEX || idx > this._dataSource.numberOfCellsInTableView(this) - 1)
return;
@@ -445,7 +447,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
*
* @param idx location to insert
*/
- insertCellAtIndex:function (idx) {
+ insertCellAtIndex: function (idx) {
if (idx === cc.INVALID_INDEX || idx > this._dataSource.numberOfCellsInTableView(this) - 1)
return;
@@ -473,7 +475,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
*
* @param idx index to find a cell
*/
- removeCellAtIndex:function (idx) {
+ removeCellAtIndex: function (idx) {
if (idx === cc.INVALID_INDEX || idx > this._dataSource.numberOfCellsInTableView(this) - 1)
return;
@@ -498,13 +500,13 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
/**
* reloads data from data source. the view will be refreshed.
*/
- reloadData:function () {
+ reloadData: function () {
this._oldDirection = cc.SCROLLVIEW_DIRECTION_NONE;
var locCellsUsed = this._cellsUsed, locCellsFreed = this._cellsFreed, locContainer = this.getContainer();
for (var i = 0, len = locCellsUsed.count(); i < len; i++) {
var cell = locCellsUsed.objectAtIndex(i);
- if(this._tableViewDelegate && this._tableViewDelegate.tableCellWillRecycle)
+ if (this._tableViewDelegate && this._tableViewDelegate.tableCellWillRecycle)
this._tableViewDelegate.tableCellWillRecycle(this, cell);
locCellsFreed.addObject(cell);
@@ -529,7 +531,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
*
* @return {TableViewCell} free cell
*/
- dequeueCell:function () {
+ dequeueCell: function () {
if (this._cellsFreed.count() === 0) {
return null;
} else {
@@ -545,14 +547,14 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
* @param idx index
* @return {cc.TableViewCell} a cell at a given index
*/
- cellAtIndex:function (idx) {
+ cellAtIndex: function (idx) {
var i = this._indices.indexOf(idx);
if (i === -1)
return null;
return this._cellsUsed.objectWithObjectID(idx);
},
- scrollViewDidScroll:function (view) {
+ scrollViewDidScroll: function (view) {
var locDataSource = this._dataSource;
var countOfItems = locDataSource.numberOfCellsInTableView(this);
if (0 === countOfItems)
@@ -561,24 +563,24 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
if (this._tableViewDelegate !== null && this._tableViewDelegate.scrollViewDidScroll)
this._tableViewDelegate.scrollViewDidScroll(this);
- var idx = 0, locViewSize = this._viewSize, locContainer = this.getContainer();
+ var idx = 0, locViewSize = this._viewSize, locContainer = this.getContainer();
var offset = this.getContentOffset();
offset.x *= -1;
offset.y *= -1;
- var maxIdx = Math.max(countOfItems-1, 0);
+ var maxIdx = Math.max(countOfItems - 1, 0);
if (this._vOrdering === cc.TABLEVIEW_FILL_TOPDOWN)
- offset.y = offset.y + locViewSize.height/locContainer.getScaleY();
+ offset.y = offset.y + locViewSize.height / locContainer.getScaleY();
var startIdx = this._indexFromOffset(offset);
if (startIdx === cc.INVALID_INDEX)
startIdx = countOfItems - 1;
if (this._vOrdering === cc.TABLEVIEW_FILL_TOPDOWN)
- offset.y -= locViewSize.height/locContainer.getScaleY();
+ offset.y -= locViewSize.height / locContainer.getScaleY();
else
- offset.y += locViewSize.height/locContainer.getScaleY();
- offset.x += locViewSize.width/locContainer.getScaleX();
+ offset.y += locViewSize.height / locContainer.getScaleY();
+ offset.x += locViewSize.width / locContainer.getScaleX();
var endIdx = this._indexFromOffset(offset);
if (endIdx === cc.INVALID_INDEX)
@@ -619,24 +621,24 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
}
},
- scrollViewDidZoom:function (view) {
+ scrollViewDidZoom: function (view) {
},
- onTouchEnded:function (touch, event) {
+ onTouchEnded: function (touch, event) {
if (!this.isVisible())
return;
- if (this._touchedCell){
+ if (this._touchedCell) {
var bb = this.getBoundingBox();
var tmpOrigin = cc.p(bb.x, bb.y);
tmpOrigin = this._parent.convertToWorldSpace(tmpOrigin);
bb.x = tmpOrigin.x;
bb.y = tmpOrigin.y;
var locTableViewDelegate = this._tableViewDelegate;
- if (cc.rectContainsPoint(bb, touch.getLocation()) && locTableViewDelegate !== null){
- if(locTableViewDelegate.tableCellUnhighlight)
+ if (cc.rectContainsPoint(bb, touch.getLocation()) && locTableViewDelegate !== null) {
+ if (locTableViewDelegate.tableCellUnhighlight)
locTableViewDelegate.tableCellUnhighlight(this, this._touchedCell);
- if(locTableViewDelegate.tableCellTouched)
+ if (locTableViewDelegate.tableCellTouched)
locTableViewDelegate.tableCellTouched(this, this._touchedCell);
}
this._touchedCell = null;
@@ -644,7 +646,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
cc.ScrollView.prototype.onTouchEnded.call(this, touch, event);
},
- onTouchBegan:function(touch, event){
+ onTouchBegan: function (touch, event) {
for (var c = this; c != null; c = c.parent) {
if (!c.isVisible())
return false;
@@ -652,7 +654,7 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
var touchResult = cc.ScrollView.prototype.onTouchBegan.call(this, touch, event);
- if(this._touches.length === 1) {
+ if (this._touches.length === 1) {
var index, point;
point = this.getContainer().convertTouchToNodeSpace(touch);
@@ -661,12 +663,12 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
if (index === cc.INVALID_INDEX)
this._touchedCell = null;
else
- this._touchedCell = this.cellAtIndex(index);
+ this._touchedCell = this.cellAtIndex(index);
if (this._touchedCell && this._tableViewDelegate !== null && this._tableViewDelegate.tableCellHighlight)
this._tableViewDelegate.tableCellHighlight(this, this._touchedCell);
- } else if(this._touchedCell) {
- if(this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight)
+ } else if (this._touchedCell) {
+ if (this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight)
this._tableViewDelegate.tableCellUnhighlight(this, this._touchedCell);
this._touchedCell = null;
}
@@ -674,21 +676,21 @@ cc.TableView = cc.ScrollView.extend(/** @lends cc.TableView# */{
return touchResult;
},
- onTouchMoved: function(touch, event){
+ onTouchMoved: function (touch, event) {
cc.ScrollView.prototype.onTouchMoved.call(this, touch, event);
if (this._touchedCell && this.isTouchMoved()) {
- if(this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight)
+ if (this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight)
this._tableViewDelegate.tableCellUnhighlight(this, this._touchedCell);
this._touchedCell = null;
}
},
- onTouchCancelled: function(touch, event){
+ onTouchCancelled: function (touch, event) {
cc.ScrollView.prototype.onTouchCancelled.call(this, touch, event);
if (this._touchedCell) {
- if(this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight)
+ if (this._tableViewDelegate !== null && this._tableViewDelegate.tableCellUnhighlight)
this._tableViewDelegate.tableCellUnhighlight(this, this._touchedCell);
this._touchedCell = null;
}
diff --git a/extensions/spine/CCSkeleton.js b/extensions/spine/CCSkeleton.js
index 9bab9e8d16..97a99f4edb 100644
--- a/extensions/spine/CCSkeleton.js
+++ b/extensions/spine/CCSkeleton.js
@@ -31,33 +31,7 @@
*/
var sp = sp || {};
-/**
- * The vertex index of spine.
- * @constant
- * @type {{X1: number, Y1: number, X2: number, Y2: number, X3: number, Y3: number, X4: number, Y4: number}}
- */
-sp.VERTEX_INDEX = {
- X1: 0,
- Y1: 1,
- X2: 2,
- Y2: 3,
- X3: 4,
- Y3: 5,
- X4: 6,
- Y4: 7
-};
-
-/**
- * The attachment type of spine. It contains three type: REGION(0), BOUNDING_BOX(1), MESH(2) and SKINNED_MESH.
- * @constant
- * @type {{REGION: number, BOUNDING_BOX: number, REGION_SEQUENCE: number, MESH: number}}
- */
-sp.ATTACHMENT_TYPE = {
- REGION: 0,
- BOUNDING_BOX: 1,
- MESH: 2,
- SKINNED_MESH:3
-};
+var spine = sp.spine;
/**
*
@@ -78,7 +52,6 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{
_premultipliedAlpha: false,
_ownsSkeletonData: null,
_atlas: null,
- _blendFunc: null,
/**
* The constructor of sp.Skeleton. override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
@@ -105,10 +78,18 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{
init: function () {
cc.Node.prototype.init.call(this);
this._premultipliedAlpha = (cc._renderType === cc.game.RENDER_TYPE_WEBGL && cc.OPTIMIZE_BLEND_FUNC_FOR_PREMULTIPLIED_ALPHA);
- this._blendFunc = {src: cc.BLEND_SRC, dst: cc.BLEND_DST};
+ },
+
+ onEnter: function () {
+ cc.Node.prototype.onEnter.call(this);
this.scheduleUpdate();
},
+ onExit: function () {
+ this.unscheduleUpdate();
+ cc.Node.prototype.onExit.call(this);
+ },
+
/**
* Sets whether open debug slots.
* @param {boolean} enable true to open, false to close.
@@ -171,7 +152,7 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{
/**
* Initializes sp.Skeleton with Data.
- * @param {spine.SkeletonData|String} skeletonDataFile
+ * @param {sp.spine.SkeletonData|String} skeletonDataFile
* @param {String|spine.Atlas|spine.SkeletonData} atlasFile atlas filename or atlas data or owns SkeletonData
* @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations.
*/
@@ -183,7 +164,7 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{
if (cc.isString(argAtlasFile)) {
var data = cc.loader.getRes(argAtlasFile);
sp._atlasLoader.setAtlasFile(argAtlasFile);
- atlas = new spine.Atlas(data, sp._atlasLoader);
+ atlas = new spine.TextureAtlas(data, sp._atlasLoader.load.bind(sp._atlasLoader));
} else {
atlas = atlasFile;
}
@@ -211,38 +192,25 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{
*/
getBoundingBox: function () {
var minX = cc.FLT_MAX, minY = cc.FLT_MAX, maxX = cc.FLT_MIN, maxY = cc.FLT_MIN;
- var scaleX = this.getScaleX(), scaleY = this.getScaleY(), vertices = [],
- slots = this._skeleton.slots, VERTEX = sp.VERTEX_INDEX;
+ var scaleX = this.getScaleX(), scaleY = this.getScaleY(), vertices,
+ slots = this._skeleton.slots, VERTEX = spine.RegionAttachment;
for (var i = 0, slotCount = slots.length; i < slotCount; ++i) {
var slot = slots[i];
- if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION)
- continue;
var attachment = slot.attachment;
- this._computeRegionAttachmentWorldVertices(attachment, slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices);
- minX = Math.min(minX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX);
- minY = Math.min(minY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY);
- maxX = Math.max(maxX, vertices[VERTEX.X1] * scaleX, vertices[VERTEX.X4] * scaleX, vertices[VERTEX.X2] * scaleX, vertices[VERTEX.X3] * scaleX);
- maxY = Math.max(maxY, vertices[VERTEX.Y1] * scaleY, vertices[VERTEX.Y4] * scaleY, vertices[VERTEX.Y2] * scaleY, vertices[VERTEX.Y3] * scaleY);
+ if (!attachment || !(attachment instanceof spine.RegionAttachment))
+ continue;
+ vertices = spine.Utils.setArraySize(new Array(), 8, 0);
+ attachment.computeWorldVertices(slot.bone, vertices, 0, 2);
+ minX = Math.min(minX, vertices[VERTEX.OX1] * scaleX, vertices[VERTEX.OX4] * scaleX, vertices[VERTEX.OX2] * scaleX, vertices[VERTEX.OX3] * scaleX);
+ minY = Math.min(minY, vertices[VERTEX.OY1] * scaleY, vertices[VERTEX.OY4] * scaleY, vertices[VERTEX.OY2] * scaleY, vertices[VERTEX.OY3] * scaleY);
+ maxX = Math.max(maxX, vertices[VERTEX.OX1] * scaleX, vertices[VERTEX.OX4] * scaleX, vertices[VERTEX.OX2] * scaleX, vertices[VERTEX.OX3] * scaleX);
+ maxY = Math.max(maxY, vertices[VERTEX.OY1] * scaleY, vertices[VERTEX.OY4] * scaleY, vertices[VERTEX.OY2] * scaleY, vertices[VERTEX.OY3] * scaleY);
}
var position = this.getPosition();
return cc.rect(position.x + minX, position.y + minY, maxX - minX, maxY - minY);
},
- _computeRegionAttachmentWorldVertices : function(self, x, y, bone, vertices){
- var offset = self.offset, vertexIndex = sp.VERTEX_INDEX;
- x += bone.worldX;
- y += bone.worldY;
- vertices[vertexIndex.X1] = offset[vertexIndex.X1] * bone.m00 + offset[vertexIndex.Y1] * bone.m01 + x;
- vertices[vertexIndex.Y1] = offset[vertexIndex.X1] * bone.m10 + offset[vertexIndex.Y1] * bone.m11 + y;
- vertices[vertexIndex.X2] = offset[vertexIndex.X2] * bone.m00 + offset[vertexIndex.Y2] * bone.m01 + x;
- vertices[vertexIndex.Y2] = offset[vertexIndex.X2] * bone.m10 + offset[vertexIndex.Y2] * bone.m11 + y;
- vertices[vertexIndex.X3] = offset[vertexIndex.X3] * bone.m00 + offset[vertexIndex.Y3] * bone.m01 + x;
- vertices[vertexIndex.Y3] = offset[vertexIndex.X3] * bone.m10 + offset[vertexIndex.Y3] * bone.m11 + y;
- vertices[vertexIndex.X4] = offset[vertexIndex.X4] * bone.m00 + offset[vertexIndex.Y4] * bone.m01 + x;
- vertices[vertexIndex.Y4] = offset[vertexIndex.X4] * bone.m10 + offset[vertexIndex.Y4] * bone.m11 + y;
- },
-
/**
* Computes the world SRT from the local SRT for each bone.
*/
@@ -274,7 +242,7 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{
/**
* Finds a bone by name. This does a string comparison for every bone.
* @param {String} boneName
- * @returns {spine.Bone}
+ * @returns {sp.spine.Bone}
*/
findBone: function (boneName) {
return this._skeleton.findBone(boneName);
@@ -283,7 +251,7 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{
/**
* Finds a slot by name. This does a string comparison for every slot.
* @param {String} slotName
- * @returns {spine.Slot}
+ * @returns {sp.spine.Slot}
*/
findSlot: function (slotName) {
return this._skeleton.findSlot(slotName);
@@ -292,7 +260,7 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{
/**
* Finds a skin by name and makes it the active skin. This does a string comparison for every skin. Note that setting the skin does not change which attachments are visible.
* @param {string} skinName
- * @returns {spine.Skin}
+ * @returns {sp.spine.Skin}
*/
setSkin: function (skinName) {
return this._skeleton.setSkinByName(skinName);
@@ -302,10 +270,10 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{
* Returns the attachment for the slot and attachment name. The skeleton looks first in its skin, then in the skeleton data’s default skin.
* @param {String} slotName
* @param {String} attachmentName
- * @returns {spine.RegionAttachment|spine.BoundingBoxAttachment}
+ * @returns {sp.spine.Attachment}
*/
getAttachment: function (slotName, attachmentName) {
- return this._skeleton.getAttachmentBySlotName(slotName, attachmentName);
+ return this._skeleton.getAttachmentByName(slotName, attachmentName);
},
/**
@@ -335,8 +303,8 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{
/**
* Sets skeleton data to sp.Skeleton.
- * @param {spine.SkeletonData} skeletonData
- * @param {spine.SkeletonData} ownsSkeletonData
+ * @param {sp.spine.SkeletonData} skeletonData
+ * @param {sp.spine.SkeletonData} ownsSkeletonData
*/
setSkeletonData: function (skeletonData, ownsSkeletonData) {
if(skeletonData.width != null && skeletonData.height != null)
@@ -352,11 +320,11 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{
/**
* Return the renderer of attachment.
- * @param {spine.RegionAttachment|spine.BoundingBoxAttachment} regionAttachment
- * @returns {cc.Node}
+ * @param {sp.spine.RegionAttachment|sp.spine.BoundingBoxAttachment} regionAttachment
+ * @returns {sp.spine.TextureAtlasRegion}
*/
getTextureAtlas: function (regionAttachment) {
- return regionAttachment.rendererObject.page.rendererObject;
+ return regionAttachment.region;
},
/**
@@ -364,23 +332,23 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{
* @returns {cc.BlendFunc}
*/
getBlendFunc: function () {
- return this._blendFunc;
+ var slot = this._skeleton.drawOrder[0];
+ if (slot) {
+ var blend = this._renderCmd._getBlendFunc(slot.data.blendMode, this._premultipliedAlpha);
+ return blend;
+ }
+ else {
+ return {};
+ }
},
/**
- * Sets the blendFunc of sp.Skeleton.
+ * Sets the blendFunc of sp.Skeleton, it won't have any effect for skeleton, skeleton is using slot's data to determine the blend function.
* @param {cc.BlendFunc|Number} src
* @param {Number} [dst]
*/
setBlendFunc: function (src, dst) {
- var locBlendFunc = this._blendFunc;
- if (dst === undefined) {
- locBlendFunc.src = src.src;
- locBlendFunc.dst = src.dst;
- } else {
- locBlendFunc.src = src;
- locBlendFunc.dst = dst;
- }
+ return;
},
/**
@@ -392,6 +360,14 @@ sp.Skeleton = cc.Node.extend(/** @lends sp.Skeleton# */{
}
});
+cc.defineGetterSetter(sp.Skeleton.prototype, "opacityModifyRGB", sp.Skeleton.prototype.isOpacityModifyRGB);
+
+// For renderer webgl to identify skeleton's default texture and blend function
+cc.defineGetterSetter(sp.Skeleton.prototype, "_blendFunc", sp.Skeleton.prototype.getBlendFunc);
+cc.defineGetterSetter(sp.Skeleton.prototype, '_texture', function () {
+ return this._renderCmd._currTexture;
+});
+
/**
* Creates a skeleton object.
* @deprecated since v3.0, please use new sp.Skeleton(skeletonDataFile, atlasFile, scale) instead.
diff --git a/extensions/spine/CCSkeletonAnimation.js b/extensions/spine/CCSkeletonAnimation.js
index f78d56cc89..17f0f25675 100644
--- a/extensions/spine/CCSkeletonAnimation.js
+++ b/extensions/spine/CCSkeletonAnimation.js
@@ -24,35 +24,17 @@
THE SOFTWARE.
****************************************************************************/
-/**
- * @ignore
- */
-sp._atlasPage_createTexture_webGL = function (self, path) {
- var texture = cc.textureCache.addImage(path);
- self.rendererObject = new cc.TextureAtlas(texture, 128);
- self.width = texture.getPixelsWide();
- self.height = texture.getPixelsHigh();
-};
-
-sp._atlasPage_createTexture_canvas = function(self, path) {
- self._texture = cc.textureCache.addImage(path);
-};
-
-sp._atlasPage_disposeTexture = function (self) {
- self.rendererObject.release();
-};
-
sp._atlasLoader = {
spAtlasFile:null,
setAtlasFile:function(spAtlasFile){
this.spAtlasFile = spAtlasFile;
},
- load:function(page, line, spAtlas){
+ load:function(line){
var texturePath = cc.path.join(cc.path.dirname(this.spAtlasFile), line);
- if (cc._renderType === cc.game.RENDER_TYPE_WEBGL)
- sp._atlasPage_createTexture_webGL(page,texturePath);
- else
- sp._atlasPage_createTexture_canvas(page,texturePath);
+ var texture = cc.textureCache.addImage(texturePath);
+ var tex = new sp.SkeletonTexture({ width: texture.getPixelsWide(), height: texture.getPixelsHigh() });
+ tex.setRealTexture(texture);
+ return tex;
},
unload:function(obj){
}
@@ -65,28 +47,86 @@ sp._atlasLoader = {
*/
sp.ANIMATION_EVENT_TYPE = {
START: 0,
- END: 1,
- COMPLETE: 2,
- EVENT: 3
+ INTERRUPT: 1,
+ END: 2,
+ DISPOSE: 3,
+ COMPLETE: 4,
+ EVENT: 5
};
-sp.TrackEntryListeners = function(startListener, endListener, completeListener, eventListener){
+sp.TrackEntryListeners = function (startListener, endListener, completeListener, eventListener, interruptListener, disposeListener) {
this.startListener = startListener || null;
this.endListener = endListener || null;
this.completeListener = completeListener || null;
this.eventListener = eventListener || null;
+ this.interruptListener = interruptListener || null;
+ this.disposeListener = disposeListener || null;
+ this.callback = null;
+ this.callbackTarget = null;
+ this.skeletonNode = null;
};
-sp.TrackEntryListeners.getListeners = function(entry){
- if(!entry.rendererObject){
- entry.rendererObject = new sp.TrackEntryListeners();
- entry.listener = sp.trackEntryCallback;
+var proto = sp.TrackEntryListeners.prototype;
+proto.start = function(trackEntry) {
+ if (this.startListener) {
+ this.startListener(trackEntry);
+ }
+ if (this.callback) {
+ this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, sp.ANIMATION_EVENT_TYPE.START, null, 0);
+ }
+};
+
+proto.interrupt = function(trackEntry) {
+ if (this.interruptListener) {
+ this.interruptListener(trackEntry);
+ }
+ if (this.callback) {
+ this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, sp.ANIMATION_EVENT_TYPE.INTERRUPT, null, 0);
}
- return entry.rendererObject;
};
-sp.trackEntryCallback = function(state, trackIndex, type, event, loopCount) {
- state.rendererObject.onTrackEntryEvent(trackIndex, type, event, loopCount);
+proto.end = function (trackEntry) {
+ if (this.endListener) {
+ this.endListener(trackEntry);
+ }
+ if (this.callback) {
+ this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, sp.ANIMATION_EVENT_TYPE.END, null, 0);
+ }
+};
+
+proto.dispose = function (trackEntry) {
+ if (this.disposeListener) {
+ this.disposeListener(trackEntry);
+ }
+ if (this.callback) {
+ this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, sp.ANIMATION_EVENT_TYPE.DISPOSE, null, 0);
+ }
+};
+
+proto.complete = function (trackEntry) {
+ var loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd);
+ if (this.completeListener) {
+ this.completeListener(trackEntry, loopCount);
+ }
+ if (this.callback) {
+ this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, sp.ANIMATION_EVENT_TYPE.COMPLETE, null, loopCount);
+ }
+};
+
+proto.event = function (trackEntry, event) {
+ if (this.eventListener) {
+ this.eventListener(trackEntry, event);
+ }
+ if (this.callback) {
+ this.callback.call(this.callbackTarget, this.skeletonNode, trackEntry, sp.ANIMATION_EVENT_TYPE.EVENT, event, 0);
+ }
+};
+
+sp.TrackEntryListeners.getListeners = function(entry){
+ if(!entry.listener){
+ entry.listener = new sp.TrackEntryListeners();
+ }
+ return entry.listener;
};
/**
@@ -99,14 +139,9 @@ sp.trackEntryCallback = function(state, trackIndex, type, event, loopCount) {
*/
sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{
_state: null,
- _target: null,
- _callback: null,
_ownsAnimationStateData: false,
- _startListener: null,
- _endListener: null,
- _completeListener: null,
- _eventListener: null,
+ _listener: null,
/**
* Initializes a sp.SkeletonAnimation. please do not call this function by yourself, you should pass the parameters to constructor to initialize it.
@@ -120,15 +155,13 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{
/**
* Sets animation state data to sp.SkeletonAnimation.
- * @param {spine.AnimationStateData} stateData
+ * @param {sp.spine.AnimationStateData} stateData
*/
setAnimationStateData: function (stateData) {
var state = new spine.AnimationState(stateData);
+ this._listener = new sp.TrackEntryListeners();
state.rendererObject = this;
- state.onStart = this._onAnimationStateStart.bind(this);
- state.onComplete = this._onAnimationStateComplete.bind(this);
- state.onEnd = this._onAnimationStateEnd.bind(this);
- state.onEvent = this._onAnimationStateEvent.bind(this);
+ state.addListener(this._listener);
this._state = state;
},
@@ -139,7 +172,7 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{
* @param {Number} duration
*/
setMix: function (fromAnimation, toAnimation, duration) {
- this._state.data.setMixByName(fromAnimation, toAnimation, duration);
+ this._state.data.setMixWith(fromAnimation, toAnimation, duration);
},
/**
@@ -148,8 +181,9 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{
* @param {Function} callback
*/
setAnimationListener: function (target, callback) {
- this._target = target;
- this._callback = callback;
+ this._listener.callbackTarget = target;
+ this._listener.callback = callback;
+ this._listener.skeletonNode = this;
},
/**
@@ -157,7 +191,7 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{
* @param {Number} trackIndex
* @param {String} name
* @param {Boolean} loop
- * @returns {spine.TrackEntry|null}
+ * @returns {sp.spine.TrackEntry|null}
*/
setAnimation: function (trackIndex, name, loop) {
var animation = this._skeleton.data.findAnimation(name);
@@ -165,7 +199,7 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{
cc.log("Spine: Animation not found: " + name);
return null;
}
- return this._state.setAnimation(trackIndex, animation, loop);
+ return this._state.setAnimationWith(trackIndex, animation, loop);
},
/**
@@ -174,7 +208,7 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{
* @param {String} name
* @param {Boolean} loop
* @param {Number} [delay=0]
- * @returns {spine.TrackEntry|null}
+ * @returns {sp.spine.TrackEntry|null}
*/
addAnimation: function (trackIndex, name, loop, delay) {
delay = delay == null ? 0 : delay;
@@ -183,13 +217,22 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{
cc.log("Spine: Animation not found:" + name);
return null;
}
- return this._state.addAnimation(trackIndex, animation, loop, delay);
+ return this._state.addAnimationWith(trackIndex, animation, loop, delay);
+ },
+
+ /**
+ * Find animation with specified name
+ * @param {String} name
+ * @returns {sp.spine.Animation|null}
+ */
+ findAnimation: function (name) {
+ return this._skeleton.data.findAnimation(name);
},
/**
* Returns track entry by trackIndex.
* @param trackIndex
- * @returns {spine.TrackEntry|null}
+ * @returns {sp.spine.TrackEntry|null}
*/
getCurrent: function (trackIndex) {
return this._state.getCurrent(trackIndex);
@@ -219,6 +262,7 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{
update: function (dt) {
this._super(dt);
dt *= this._timeScale;
+ this._renderCmd.setDirtyFlag(cc.Node._dirtyFlags.contentDirty);
this._state.update(dt);
this._state.apply(this._skeleton);
this._skeleton.updateWorldTransform();
@@ -230,7 +274,15 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{
* @param {function} listener
*/
setStartListener: function(listener){
- this._startListener = listener;
+ this._listener.startListener = listener;
+ },
+
+ /**
+ * Set the interrupt listener
+ * @param {function} listener
+ */
+ setInterruptListener: function(listener) {
+ this._listener.interruptListener = listener;
},
/**
@@ -238,25 +290,41 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{
* @param {function} listener
*/
setEndListener: function(listener) {
- this._endListener = listener;
+ this._listener.endListener = listener;
+ },
+
+ /**
+ * Set the dispose listener
+ * @param {function} listener
+ */
+ setDisposeListener: function(listener) {
+ this._listener.disposeListener = listener;
},
setCompleteListener: function(listener) {
- this._completeListener = listener;
+ this._listener.completeListener = listener;
},
setEventListener: function(listener){
- this._eventListener = listener;
+ this._listener.eventListener = listener;
},
setTrackStartListener: function(entry, listener){
sp.TrackEntryListeners.getListeners(entry).startListener = listener;
},
+ setTrackInterruptListener: function(entry, listener){
+ sp.TrackEntryListeners.getListeners(entry).interruptListener = listener;
+ },
+
setTrackEndListener: function(entry, listener){
sp.TrackEntryListeners.getListeners(entry).endListener = listener;
},
+ setTrackDisposeListener: function(entry, listener){
+ sp.TrackEntryListeners.getListeners(entry).disposeListener = listener;
+ },
+
setTrackCompleteListener: function(entry, listener){
sp.TrackEntryListeners.getListeners(entry).completeListener = listener;
},
@@ -265,73 +333,8 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{
sp.TrackEntryListeners.getListeners(entry).eventListener = listener;
},
- onTrackEntryEvent: function(traceIndex, type, event, loopCount){
- var entry = this._state.getCurrent(traceIndex);
- if(!entry.rendererObject)
- return;
- var listeners = entry.rendererObject;
- switch (type){
- case sp.ANIMATION_EVENT_TYPE.START:
- if(listeners.startListener)
- listeners.startListener(traceIndex);
- break;
- case sp.ANIMATION_EVENT_TYPE.END:
- if(listeners.endListener)
- listeners.endListener(traceIndex);
- break;
- case sp.ANIMATION_EVENT_TYPE.COMPLETE:
- if(listeners.completeListener)
- listeners.completeListener(traceIndex, loopCount);
- break;
- case sp.ANIMATION_EVENT_TYPE.EVENT:
- if(listeners.eventListener)
- listeners.eventListener(traceIndex, event);
- break;
- }
- },
-
- onAnimationStateEvent: function(trackIndex, type, event, loopCount) {
- switch(type){
- case sp.ANIMATION_EVENT_TYPE.START:
- if(this._startListener)
- this._startListener(trackIndex);
- break;
- case sp.ANIMATION_EVENT_TYPE.END:
- if(this._endListener)
- this._endListener(trackIndex);
- break;
- case sp.ANIMATION_EVENT_TYPE.COMPLETE:
- if(this._completeListener)
- this._completeListener(trackIndex, loopCount);
- break;
- case sp.ANIMATION_EVENT_TYPE.EVENT:
- if(this._eventListener)
- this._eventListener(trackIndex, event);
- break;
- }
- },
-
getState: function(){
return this._state;
- },
-
- _onAnimationStateStart: function (trackIndex) {
- this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.START, null, 0);
- },
- _onAnimationStateEnd: function (trackIndex) {
- this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.END, null, 0);
- },
- _onAnimationStateComplete: function (trackIndex, count) {
- this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.COMPLETE, null, count);
- },
- _onAnimationStateEvent: function (trackIndex, event) {
- this._animationStateCallback(trackIndex, sp.ANIMATION_EVENT_TYPE.EVENT, event, 0);
- },
- _animationStateCallback: function (trackIndex, type, event, loopCount) {
- this.onAnimationStateEvent(trackIndex, type, event, loopCount);
- if (this._target && this._callback) {
- this._callback.call(this._target, this, trackIndex, type, event, loopCount)
- }
}
});
@@ -343,6 +346,6 @@ sp.SkeletonAnimation = sp.Skeleton.extend(/** @lends sp.SkeletonAnimation# */{
* @param {Number} [scale] scale can be specified on the JSON or binary loader which will scale the bone positions, image sizes, and animation translations.
* @returns {sp.Skeleton}
*/
-sp.SkeletonAnimation.create = function (skeletonDataFile, atlasFile/* or atlas*/, scale) {
+sp.SkeletonAnimation.createWithJsonFile = sp.SkeletonAnimation.create = function (skeletonDataFile, atlasFile/* or atlas*/, scale) {
return new sp.SkeletonAnimation(skeletonDataFile, atlasFile, scale);
-};
\ No newline at end of file
+};
diff --git a/extensions/spine/CCSkeletonCanvasRenderCmd.js b/extensions/spine/CCSkeletonCanvasRenderCmd.js
index 589ab62c53..f31924ec19 100644
--- a/extensions/spine/CCSkeletonCanvasRenderCmd.js
+++ b/extensions/spine/CCSkeletonCanvasRenderCmd.js
@@ -22,200 +22,226 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- sp.Skeleton.CanvasRenderCmd = function(renderableObject){
- cc.Node.CanvasRenderCmd.call(this, renderableObject);
- this._needDraw = true;
- };
-
- var proto = sp.Skeleton.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
- proto.constructor = sp.Skeleton.CanvasRenderCmd;
-
- proto.rendering = function (wrapper, scaleX, scaleY) {
- var node = this._node, i, n, slot, slotNode;
- wrapper = wrapper || cc._renderContext;
-
- var locSkeleton = node._skeleton, drawOrder = locSkeleton.drawOrder;
- for(i = 0, n = drawOrder.length; i < n; i++){
- slot = drawOrder[i];
- slotNode = slot._slotNode;
- if(slotNode._visible && slotNode._renderCmd && slot.currentSprite){
- slotNode._renderCmd.transform(this, true);
- slot.currentSprite._renderCmd.rendering(wrapper, scaleX, scaleY);
- slotNode._renderCmd._dirtyFlag = slot.currentSprite._renderCmd._dirtyFlag = 0;
- }
+(function () {
+
+var spine = sp.spine;
+
+sp.Skeleton.CanvasRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
+ this._needDraw = true;
+};
+
+var proto = sp.Skeleton.CanvasRenderCmd.prototype = Object.create(cc.Node.CanvasRenderCmd.prototype);
+proto.constructor = sp.Skeleton.CanvasRenderCmd;
+
+proto.rendering = function (wrapper, scaleX, scaleY) {
+ var node = this._node, i, n, slot, slotNode;
+ wrapper = wrapper || cc._renderContext;
+
+ var locSkeleton = node._skeleton, drawOrder = locSkeleton.drawOrder;
+ for (i = 0, n = drawOrder.length; i < n; i++) {
+ slot = drawOrder[i];
+ slotNode = slot._slotNode;
+ if (slotNode._visible && slotNode._renderCmd && slot.currentSprite) {
+ slotNode._renderCmd.transform(this, true);
+ slot.currentSprite._renderCmd.rendering(wrapper, scaleX, scaleY);
+ slotNode._renderCmd._dirtyFlag = slot.currentSprite._renderCmd._dirtyFlag = 0;
}
-
- if (!node._debugSlots && !node._debugBones)
- return;
-
- wrapper.setTransform(this._worldTransform, scaleX, scaleY);
- wrapper.setGlobalAlpha(1);
- var attachment, drawingUtil = cc._drawingUtil;
- if (node._debugSlots) {
- // Slots.
- drawingUtil.setDrawColor(0, 0, 255, 255);
- drawingUtil.setLineWidth(1);
-
- var points = [];
- for (i = 0, n = locSkeleton.slots.length; i < n; i++) {
- slot = locSkeleton.drawOrder[i];
- if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION)
- continue;
- attachment = slot.attachment;
- this._updateRegionAttachmentSlot(attachment, slot, points);
- drawingUtil.drawPoly(points, 4, true);
- }
+ }
+
+ if (!node._debugSlots && !node._debugBones)
+ return;
+
+ wrapper.setTransform(this._worldTransform, scaleX, scaleY);
+ wrapper.setGlobalAlpha(1);
+ var attachment, drawingUtil = cc._drawingUtil;
+ if (node._debugSlots) {
+ // Slots.
+ drawingUtil.setDrawColor(0, 0, 255, 255);
+ drawingUtil.setLineWidth(1);
+
+ var points = [];
+ for (i = 0, n = locSkeleton.slots.length; i < n; i++) {
+ slot = locSkeleton.drawOrder[i];
+ if (!slot.attachment || !(slot.attachment instanceof spine.RegionAttachment))
+ continue;
+ attachment = slot.attachment;
+ this._updateRegionAttachmentSlot(attachment, slot, points);
+ drawingUtil.drawPoly(points, 4, true);
+ }
+ }
+
+ if (node._debugBones) {
+ // Bone lengths.
+ var bone;
+ drawingUtil.setLineWidth(2);
+ drawingUtil.setDrawColor(255, 0, 0, 255);
+
+ for (i = 0, n = locSkeleton.bones.length; i < n; i++) {
+ bone = locSkeleton.bones[i];
+ var x = bone.data.length * bone.a + bone.worldX;
+ var y = bone.data.length * bone.c + bone.worldY;
+ drawingUtil.drawLine(
+ {x: bone.worldX, y: bone.worldY},
+ {x: x, y: y});
}
- if (node._debugBones) {
- // Bone lengths.
- var bone;
- drawingUtil.setLineWidth(2);
- drawingUtil.setDrawColor(255, 0, 0, 255);
-
- for (i = 0, n = locSkeleton.bones.length; i < n; i++) {
- bone = locSkeleton.bones[i];
- var x = bone.data.length * bone.m00 + bone.worldX;
- var y = bone.data.length * bone.m10 + bone.worldY;
- drawingUtil.drawLine(
- {x: bone.worldX, y: bone.worldY},
- {x: x, y: y});
- }
-
- // Bone origins.
- drawingUtil.setPointSize(4);
- drawingUtil.setDrawColor(0, 0, 255, 255); // Root bone is blue.
+ // Bone origins.
+ var pointSize = 4;
+ drawingUtil.setDrawColor(0, 0, 255, 255); // Root bone is blue.
- for (i = 0, n = locSkeleton.bones.length; i < n; i++) {
- bone = locSkeleton.bones[i];
- drawingUtil.drawPoint({x: bone.worldX, y: bone.worldY});
- if (i === 0)
- drawingUtil.setDrawColor(0, 255, 0, 255);
- }
+ for (i = 0, n = locSkeleton.bones.length; i < n; i++) {
+ bone = locSkeleton.bones[i];
+ drawingUtil.drawPoint({x: bone.worldX, y: bone.worldY}, pointSize);
+ if (i === 0)
+ drawingUtil.setDrawColor(0, 255, 0, 255);
}
- };
-
- proto._updateRegionAttachmentSlot = function(attachment, slot, points) {
- if(!points)
- return;
-
- var vertices = {}, VERTEX = sp.VERTEX_INDEX, bone = slot.bone;
- attachment.computeVertices(bone.skeleton.x, bone.skeleton.y, bone, vertices);
- points.length = 0;
- points.push(cc.p(vertices[VERTEX.X1], vertices[VERTEX.Y1]));
- points.push(cc.p(vertices[VERTEX.X4], vertices[VERTEX.Y4]));
- points.push(cc.p(vertices[VERTEX.X3], vertices[VERTEX.Y3]));
- points.push(cc.p(vertices[VERTEX.X2], vertices[VERTEX.Y2]));
- };
-
- proto._createChildFormSkeletonData = function(){
- var node = this._node;
- var locSkeleton = node._skeleton, spriteName, sprite;
- for (var i = 0, n = locSkeleton.slots.length; i < n; i++) {
- var slot = locSkeleton.slots[i], attachment = slot.attachment;
- var slotNode = new cc.Node();
- slot._slotNode = slotNode;
-
- if(attachment instanceof spine.RegionAttachment){
- spriteName = attachment.rendererObject.name;
- sprite = this._createSprite(slot, attachment);
- slot.currentSprite = sprite;
- slot.currentSpriteName = spriteName;
- slotNode.addChild(sprite);
- } else if(attachment instanceof spine.MeshAttachment){
- //todo for mesh
- }
+ }
+};
+
+proto.updateStatus = function() {
+ this.originUpdateStatus();
+ this._updateCurrentRegions();
+ this._regionFlag = cc.Node.CanvasRenderCmd.RegionStatus.DirtyDouble;
+ this._dirtyFlag &= ~cc.Node._dirtyFlags.contentDirty;
+};
+
+proto.getLocalBB = function() {
+ return this._node.getBoundingBox();
+};
+
+proto._updateRegionAttachmentSlot = function (attachment, slot, points) {
+ if (!points)
+ return;
+
+ var vertices = spine.Utils.setArraySize(new Array(), 8, 0);
+ attachment.computeWorldVertices(slot.bone, vertices, 0, 2);
+ var VERTEX = spine.RegionAttachment;
+ points.length = 0;
+ points.push(cc.p(vertices[VERTEX.OX1], vertices[VERTEX.OY1]));
+ points.push(cc.p(vertices[VERTEX.OX4], vertices[VERTEX.OY4]));
+ points.push(cc.p(vertices[VERTEX.OX3], vertices[VERTEX.OY3]));
+ points.push(cc.p(vertices[VERTEX.OX2], vertices[VERTEX.OY2]));
+};
+
+proto._createChildFormSkeletonData = function () {
+ var node = this._node;
+ var locSkeleton = node._skeleton, spriteName, sprite;
+ for (var i = 0, n = locSkeleton.slots.length; i < n; i++) {
+ var slot = locSkeleton.slots[i], attachment = slot.attachment;
+ var slotNode = new cc.Node();
+ slot._slotNode = slotNode;
+
+ if (attachment instanceof spine.RegionAttachment) {
+ spriteName = attachment.region.name;
+ sprite = this._createSprite(slot, attachment);
+ slot.currentSprite = sprite;
+ slot.currentSpriteName = spriteName;
+ slotNode.addChild(sprite);
+ } else if (attachment instanceof spine.MeshAttachment) {
+ //todo for mesh
}
- };
-
- var loaded = function (sprite, texture, rendererObject, attachment) {
- var rect = new cc.Rect(rendererObject.x, rendererObject.y, rendererObject.width, rendererObject.height);
- sprite.initWithTexture(texture, rect, rendererObject.rotate, false);
- sprite._rect.width = attachment.width;
- sprite._rect.height = attachment.height;
- sprite.setContentSize(attachment.width, attachment.height);
- sprite.setRotation(-attachment.rotation);
- sprite.setScale(rendererObject.width / rendererObject.originalWidth * attachment.scaleX,
- rendererObject.height / rendererObject.originalHeight * attachment.scaleY);
- };
-
- proto._createSprite = function(slot, attachment){
- var rendererObject = attachment.rendererObject;
- var texture = rendererObject.page._texture;
- var sprite = new cc.Sprite();
- if (texture.isLoaded()) {
- loaded(sprite, texture, rendererObject, attachment);
- } else {
- texture.addEventListener('load', function () {
- loaded(sprite, texture, rendererObject, attachment);
- }, this);
+ }
+};
+
+var loaded = function (sprite, texture, attachment) {
+ var rendererObject = attachment.region;
+ var rect = new cc.Rect(rendererObject.x, rendererObject.y, rendererObject.width, rendererObject.height);
+ sprite.initWithTexture(texture, rect, rendererObject.rotate, false);
+ sprite._rect.width = attachment.width;
+ sprite._rect.height = attachment.height;
+ sprite.setContentSize(attachment.width, attachment.height);
+ sprite.setRotation(-attachment.rotation);
+ sprite.setScale(rendererObject.width / rendererObject.originalWidth * attachment.scaleX,
+ rendererObject.height / rendererObject.originalHeight * attachment.scaleY);
+};
+
+proto._createSprite = function (slot, attachment) {
+ var rendererObject = attachment.region;
+ var texture = rendererObject.texture.getRealTexture();
+ var sprite = new cc.Sprite();
+ if (texture.isLoaded()) {
+ loaded(sprite, texture, attachment);
+ } else {
+ texture.addEventListener('load', function () {
+ loaded(sprite, texture, attachment);
+ }, this);
+ }
+ slot.sprites = slot.sprites || {};
+ slot.sprites[rendererObject.name] = sprite;
+ return sprite;
+};
+
+proto._updateChild = function () {
+ var locSkeleton = this._node._skeleton, slots = locSkeleton.slots;
+ var color = this._displayedColor, opacity = this._displayedOpacity;
+ var i, n, selSprite, ax, ay;
+
+ var slot, attachment, slotNode;
+ for (i = 0, n = slots.length; i < n; i++) {
+ slot = slots[i];
+ attachment = slot.attachment;
+ slotNode = slot._slotNode;
+ if (!attachment) {
+ slotNode.setVisible(false);
+ continue;
}
- slot.sprites = slot.sprites || {};
- slot.sprites[rendererObject.name] = sprite;
- return sprite;
- };
-
- proto._updateChild = function(){
- var locSkeleton = this._node._skeleton, slots = locSkeleton.slots;
- var i, n, selSprite;
-
- var slot, attachment, slotNode;
- for(i = 0, n = slots.length; i < n; i++){
- slot = slots[i];
- attachment = slot.attachment;
- slotNode = slot._slotNode;
- if(!attachment){
- slotNode.setVisible(false);
- continue;
- }
- var type = attachment.type;
- if (type === spine.AttachmentType.region){
- if(attachment.rendererObject){
- if(!slot.currentSpriteName || slot.currentSpriteName !== attachment.name){
- var spriteName = attachment.rendererObject.name;
- if(slot.currentSprite !== undefined)
- slot.currentSprite.setVisible(false);
- slot.sprites = slot.sprites ||{};
- if(slot.sprites[spriteName] !== undefined)
- slot.sprites[spriteName].setVisible(true);
- else{
- var sprite = this._createSprite(slot, attachment);
- slotNode.addChild(sprite);
- }
- slot.currentSprite = slot.sprites[spriteName];
- slot.currentSpriteName = spriteName;
+ if (attachment instanceof spine.RegionAttachment) {
+ if (attachment.region) {
+ if (!slot.currentSpriteName || slot.currentSpriteName !== attachment.name) {
+ var spriteName = attachment.region.name;
+ if (slot.currentSprite !== undefined)
+ slot.currentSprite.setVisible(false);
+ slot.sprites = slot.sprites || {};
+ if (slot.sprites[spriteName] !== undefined)
+ slot.sprites[spriteName].setVisible(true);
+ else {
+ var sprite = this._createSprite(slot, attachment);
+ slotNode.addChild(sprite);
}
+ slot.currentSprite = slot.sprites[spriteName];
+ slot.currentSpriteName = spriteName;
}
- var bone = slot.bone;
- slotNode.setPosition(bone.worldX + attachment.x * bone.m00 + attachment.y * bone.m01,
- bone.worldY + attachment.x * bone.m10 + attachment.y * bone.m11);
- slotNode.setScale(bone.worldScaleX, bone.worldScaleY);
-
- //set the color and opacity
- selSprite = slot.currentSprite;
- selSprite._flippedX = bone.worldFlipX;
- selSprite._flippedY = bone.worldFlipY;
- if(selSprite._flippedY || selSprite._flippedX){
- slotNode.setRotation(bone.worldRotation);
- selSprite.setRotation(attachment.rotation);
- }else{
- slotNode.setRotation(-bone.worldRotation);
- selSprite.setRotation(-attachment.rotation);
- }
-
- //hack for sprite
- selSprite._renderCmd._displayedOpacity = 0 | (this._node.getOpacity() * locSkeleton.a * slot.a);
- var r = 0 | (locSkeleton.r * slot.r * 255), g = 0 | (locSkeleton.g * slot.g * 255), b = 0 | (locSkeleton.b * slot.b * 255);
- selSprite.setColor(cc.color(r,g,b));
- selSprite._renderCmd._updateColor();
- } else if (type === spine.AttachmentType.skinnedmesh) {
- //todo for mesh
+ }
+ var bone = slot.bone;
+ if (attachment.region.offsetX === 0 && attachment.region.offsetY === 0) {
+ ax = attachment.x;
+ ay = attachment.y;
+ }
+ else {
+ //var regionScaleX = attachment.width / attachment.regionOriginalWidth * attachment.scaleX;
+ //ax = attachment.x + attachment.regionOffsetX * regionScaleX - (attachment.width * attachment.scaleX - attachment.regionWidth * regionScaleX) / 2;
+ ax = (attachment.offset[0] + attachment.offset[4]) * 0.5;
+ ay = (attachment.offset[1] + attachment.offset[5]) * 0.5;
+ }
+ slotNode.setPosition(bone.worldX + ax * bone.a + ay * bone.b, bone.worldY + ax * bone.c + ay * bone.d);
+ slotNode.setScale(bone.getWorldScaleX(), bone.getWorldScaleY());
+
+ //set the color and opacity
+ selSprite = slot.currentSprite;
+ selSprite._flippedX = bone.skeleton.flipX;
+ selSprite._flippedY = bone.skeleton.flipY;
+ if (selSprite._flippedY || selSprite._flippedX) {
+ slotNode.setRotation(bone.getWorldRotationX());
+ selSprite.setRotation(attachment.rotation);
} else {
- slotNode.setVisible(false);
- continue;
+ slotNode.setRotation(-bone.getWorldRotationX());
+ selSprite.setRotation(-attachment.rotation);
}
- slotNode.setVisible(true);
+
+ //hack for sprite
+ selSprite._renderCmd._displayedOpacity = 0 | (opacity * slot.color.a);
+ var r = 0 | (color.r * slot.color.r), g = 0 | (color.g * slot.color.g), b = 0 | (color.b * slot.color.b);
+ selSprite.setColor(cc.color(r, g, b));
+ selSprite._renderCmd._updateColor();
+ } else if (attachment instanceof spine.MeshAttachment) {
+ // Can not render mesh
+ } else {
+ slotNode.setVisible(false);
+ continue;
}
- };
-})();
\ No newline at end of file
+ slotNode.setVisible(true);
+ }
+};
+
+})();
diff --git a/extensions/spine/CCSkeletonTexture.js b/extensions/spine/CCSkeletonTexture.js
new file mode 100644
index 0000000000..9250369c30
--- /dev/null
+++ b/extensions/spine/CCSkeletonTexture.js
@@ -0,0 +1,67 @@
+/****************************************************************************
+ Copyright (c) 2017 Chukong Technologies Inc.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+sp.SkeletonTexture = function (image) {
+ sp.spine.Texture.call(this, image);
+};
+cc.inherits(sp.SkeletonTexture, sp.spine.Texture);
+cc.extend(sp.SkeletonTexture.prototype, {
+ name: 'sp.SkeletonTexture',
+ _texture: null,
+
+ setRealTexture: function(tex) {
+ this._texture = tex;
+ },
+
+ getRealTexture: function() {
+ return this._texture;
+ },
+
+ setFilters: function(minFilter, magFilter) {
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
+ var gl = cc._renderContext;
+ this.bind();
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
+ }
+ },
+
+ setWraps: function(uWrap, vWrap) {
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
+ var gl = cc._renderContext;
+ this.bind();
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, uWrap);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, vWrap);
+ }
+ },
+
+ dispose: function() {
+ },
+
+ bind: function() {
+ if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
+ cc.glBindTexture2D(this._texture);
+ }
+ }
+});
\ No newline at end of file
diff --git a/extensions/spine/CCSkeletonWebGLRenderCmd.js b/extensions/spine/CCSkeletonWebGLRenderCmd.js
index 9eb185a204..535e4c0ac5 100644
--- a/extensions/spine/CCSkeletonWebGLRenderCmd.js
+++ b/extensions/spine/CCSkeletonWebGLRenderCmd.js
@@ -22,248 +22,326 @@
THE SOFTWARE.
****************************************************************************/
-(function(){
- sp.Skeleton.WebGLRenderCmd = function (renderableObject) {
- cc.Node.WebGLRenderCmd.call(this, renderableObject);
- this._needDraw = true;
- this._matrix = new cc.math.Matrix4();
- this._matrix.identity();
- this._tmpQuad = new cc.V3F_C4B_T2F_Quad();
- this.setShaderProgram(cc.shaderCache.programForKey(cc.SHADER_POSITION_TEXTURECOLOR));
- };
-
- var proto = sp.Skeleton.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
- proto.constructor = sp.Skeleton.WebGLRenderCmd;
-
- proto.rendering = function (ctx) {
- var node = this._node, tmpQuad = this._tmpQuad;
- var color = node.getColor(), locSkeleton = node._skeleton;
-
- var blendMode, textureAtlas, attachment, slot, i, n;
- var locBlendFunc = node._blendFunc;
- var premultiAlpha = node._premultipliedAlpha;
-
- var wt = this._worldTransform;
- this._matrix.mat[0] = wt.a;
- this._matrix.mat[4] = wt.c;
- this._matrix.mat[12] = wt.tx;
- this._matrix.mat[1] = wt.b;
- this._matrix.mat[5] = wt.d;
- this._matrix.mat[13] = wt.ty;
-
- this._shaderProgram.use();
- this._shaderProgram._setUniformForMVPMatrixWithMat4(this._matrix);
- // cc.glBlendFunc(locBlendFunc.src, locBlendFunc.dst);
- locSkeleton.r = color.r / 255;
- locSkeleton.g = color.g / 255;
- locSkeleton.b = color.b / 255;
- locSkeleton.a = node.getOpacity() / 255;
- if (premultiAlpha) {
- locSkeleton.r *= locSkeleton.a;
- locSkeleton.g *= locSkeleton.a;
- locSkeleton.b *= locSkeleton.a;
+(function () {
+
+var spine = sp.spine;
+
+sp.Skeleton.WebGLRenderCmd = function (renderableObject) {
+ this._rootCtor(renderableObject);
+ this._needDraw = true;
+ this._matrix = new cc.math.Matrix4();
+ this._matrix.identity();
+ this._currTexture = null;
+ this._currBlendFunc = {};
+ this.vertexType = cc.renderer.VertexType.CUSTOM;
+ this.setShaderProgram(cc.shaderCache.programForKey(cc.SHADER_SPRITE_POSITION_TEXTURECOLOR));
+};
+
+var proto = sp.Skeleton.WebGLRenderCmd.prototype = Object.create(cc.Node.WebGLRenderCmd.prototype);
+proto.constructor = sp.Skeleton.WebGLRenderCmd;
+
+proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){
+ var node = this._node;
+ var color = this._displayedColor, locSkeleton = node._skeleton;
+
+ var attachment, slot, i, n;
+ var premultiAlpha = node._premultipliedAlpha;
+
+ locSkeleton.r = color.r / 255;
+ locSkeleton.g = color.g / 255;
+ locSkeleton.b = color.b / 255;
+ locSkeleton.a = this._displayedOpacity / 255;
+ if (premultiAlpha) {
+ locSkeleton.r *= locSkeleton.a;
+ locSkeleton.g *= locSkeleton.a;
+ locSkeleton.b *= locSkeleton.a;
+ }
+
+ var debugSlotsInfo = null;
+ if (this._node._debugSlots) {
+ debugSlotsInfo = [];
+ }
+
+ for (i = 0, n = locSkeleton.drawOrder.length; i < n; i++) {
+ slot = locSkeleton.drawOrder[i];
+ if (!slot.attachment)
+ continue;
+ attachment = slot.attachment;
+
+ // get the vertices length
+ var vertCount = 0;
+ if (attachment instanceof spine.RegionAttachment) {
+ vertCount = 6; // a quad = two triangles = six vertices
+ }
+ else if (attachment instanceof spine.MeshAttachment) {
+ vertCount = attachment.regionUVs.length / 2;
+ }
+ else {
+ continue;
}
- //for (i = 0, n = locSkeleton.slots.length; i < n; i++) {
- for (i = 0, n = locSkeleton.drawOrder.length; i < n; i++) {
- slot = locSkeleton.drawOrder[i];
- if (!slot.attachment)
- continue;
- attachment = slot.attachment;
-
- switch(slot.attachment.type) {
- case sp.ATTACHMENT_TYPE.REGION:
- this._updateRegionAttachmentQuad(attachment, slot, tmpQuad, premultiAlpha);
- break;
- case sp.ATTACHMENT_TYPE.MESH:
- this._updateMeshAttachmentQuad(attachment, slot, tmpQuad, premultiAlpha);
- break;
- case sp.ATTACHMENT_TYPE.SKINNED_MESH:
- break;
- default:
- continue;
- }
+ // no vertices to render
+ if (vertCount === 0) {
+ continue;
+ }
- var regionTextureAtlas = node.getTextureAtlas(attachment);
+ var regionTextureAtlas = node.getTextureAtlas(attachment);
- if (slot.data.blendMode != blendMode) {
- if (textureAtlas) {
- textureAtlas.drawQuads();
- textureAtlas.removeAllQuads();
- }
- blendMode = slot.data.blendMode;
- switch (blendMode) {
- case spine.BlendMode.additive:
- cc.glBlendFunc(premultiAlpha ? cc.ONE : cc.SRC_ALPHA, cc.ONE);
- break;
- case spine.BlendMode.multiply:
- cc.glBlendFunc(cc.DST_COLOR, cc.ONE_MINUS_SRC_ALPHA);
- break;
- case spine.BlendMode.screen:
- cc.glBlendFunc(cc.ONE, cc.ONE_MINUS_SRC_COLOR);
- break;
- default:
- cc.glBlendFunc(locBlendFunc.src, locBlendFunc.dst);
- }
- } else if (regionTextureAtlas != textureAtlas && textureAtlas) {
- textureAtlas.drawQuads();
- textureAtlas.removeAllQuads();
- }
- textureAtlas = regionTextureAtlas;
-
- var quadCount = textureAtlas.getTotalQuads();
- if (textureAtlas.getCapacity() == quadCount) {
- textureAtlas.drawQuads();
- textureAtlas.removeAllQuads();
- if (!textureAtlas.resizeCapacity(textureAtlas.getCapacity() * 2))
- return;
- }
+ // Broken for changing batch info
+ this._currTexture = regionTextureAtlas.texture.getRealTexture();
+ var batchBroken = cc.renderer._updateBatchedInfo(this._currTexture, this._getBlendFunc(slot.data.blendMode, premultiAlpha), this._glProgramState);
+
+ // keep the same logic with RendererWebGL.js, avoid vertex data overflow
+ var uploadAll = vertexDataOffset / 6 + vertCount > (cc.BATCH_VERTEX_COUNT - 200) * 0.5;
+ // Broken for vertex data overflow
+ if (!batchBroken && uploadAll) {
+ // render the cached data
+ cc.renderer._batchRendering();
+ batchBroken = true;
+ }
+ if (batchBroken) {
+ vertexDataOffset = 0;
+ }
- textureAtlas.updateQuad(tmpQuad, quadCount);
+ // update the vertex buffer
+ var slotDebugPoints = null;
+ if (attachment instanceof spine.RegionAttachment) {
+ slotDebugPoints = this._uploadRegionAttachmentData(attachment, slot, premultiAlpha, f32buffer, ui32buffer, vertexDataOffset);
+ }
+ else if (attachment instanceof spine.MeshAttachment) {
+ this._uploadMeshAttachmentData(attachment, slot, premultiAlpha, f32buffer, ui32buffer, vertexDataOffset);
+ }
+ else {
+ continue;
}
- if (textureAtlas) {
- textureAtlas.drawQuads();
- textureAtlas.removeAllQuads();
+ if (this._node._debugSlots) {
+ debugSlotsInfo[i] = slotDebugPoints;
}
- if (node._debugBones || node._debugSlots) {
- cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW);
- cc.current_stack.stack.push(cc.current_stack.top);
- cc.current_stack.top = this._matrix;
- var drawingUtil = cc._drawingUtil;
-
- if (node._debugSlots) {
- // Slots.
- drawingUtil.setDrawColor(0, 0, 255, 255);
- drawingUtil.setLineWidth(1);
-
- for (i = 0, n = locSkeleton.slots.length; i < n; i++) {
- slot = locSkeleton.drawOrder[i];
- if (!slot.attachment || slot.attachment.type != sp.ATTACHMENT_TYPE.REGION)
- continue;
- attachment = slot.attachment;
- this._updateRegionAttachmentQuad(attachment, slot, tmpQuad);
-
- var points = [];
- points.push(cc.p(tmpQuad.bl.vertices.x, tmpQuad.bl.vertices.y));
- points.push(cc.p(tmpQuad.br.vertices.x, tmpQuad.br.vertices.y));
- points.push(cc.p(tmpQuad.tr.vertices.x, tmpQuad.tr.vertices.y));
- points.push(cc.p(tmpQuad.tl.vertices.x, tmpQuad.tl.vertices.y));
+ // update the index buffer
+ if (attachment instanceof spine.RegionAttachment) {
+ cc.renderer._increaseBatchingSize(vertCount, cc.renderer.VertexType.TRIANGLE);
+ } else {
+ cc.renderer._increaseBatchingSize(vertCount, cc.renderer.VertexType.CUSTOM, attachment.triangles);
+ }
+ // update the index data
+ vertexDataOffset += vertCount * 6;
+ }
+
+ if (node._debugBones || node._debugSlots) {
+ // flush previous vertices
+ cc.renderer._batchRendering();
+
+ var wt = this._worldTransform, mat = this._matrix.mat;
+ mat[0] = wt.a;
+ mat[4] = wt.c;
+ mat[12] = wt.tx;
+ mat[1] = wt.b;
+ mat[5] = wt.d;
+ mat[13] = wt.ty;
+ cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW);
+ cc.current_stack.stack.push(cc.current_stack.top);
+ cc.current_stack.top = this._matrix;
+ var drawingUtil = cc._drawingUtil;
+
+ if (node._debugSlots && debugSlotsInfo && debugSlotsInfo.length > 0) {
+ // Slots.
+ drawingUtil.setDrawColor(0, 0, 255, 255);
+ drawingUtil.setLineWidth(1);
+
+ for (i = 0, n = locSkeleton.slots.length; i < n; i++) {
+ var points = debugSlotsInfo[i];
+ if (points) {
drawingUtil.drawPoly(points, 4, true);
}
}
+ }
- if (node._debugBones) {
- // Bone lengths.
- var bone;
- drawingUtil.setLineWidth(2);
- drawingUtil.setDrawColor(255, 0, 0, 255);
-
- for (i = 0, n = locSkeleton.bones.length; i < n; i++) {
- bone = locSkeleton.bones[i];
- var x = bone.data.length * bone.m00 + bone.worldX;
- var y = bone.data.length * bone.m10 + bone.worldY;
- drawingUtil.drawLine(cc.p(bone.worldX, bone.worldY), cc.p(x, y));
- }
+ if (node._debugBones) {
+ // Bone lengths.
+ var bone;
+ drawingUtil.setLineWidth(2);
+ drawingUtil.setDrawColor(255, 0, 0, 255);
+
+ for (i = 0, n = locSkeleton.bones.length; i < n; i++) {
+ bone = locSkeleton.bones[i];
+ var x = bone.data.length * bone.a + bone.worldX;
+ var y = bone.data.length * bone.c + bone.worldY;
+ drawingUtil.drawLine(cc.p(bone.worldX, bone.worldY), cc.p(x, y));
+ }
- // Bone origins.
- drawingUtil.setPointSize(4);
- drawingUtil.setDrawColor(0, 0, 255, 255); // Root bone is blue.
+ // Bone origins.
+ drawingUtil.setPointSize(4);
+ drawingUtil.setDrawColor(0, 0, 255, 255); // Root bone is blue.
- for (i = 0, n = locSkeleton.bones.length; i < n; i++) {
- bone = locSkeleton.bones[i];
- drawingUtil.drawPoint(cc.p(bone.worldX, bone.worldY));
- if (i == 0) {
- drawingUtil.setDrawColor(0, 255, 0, 255);
- }
+ for (i = 0, n = locSkeleton.bones.length; i < n; i++) {
+ bone = locSkeleton.bones[i];
+ drawingUtil.drawPoint(cc.p(bone.worldX, bone.worldY));
+ if (i == 0) {
+ drawingUtil.setDrawColor(0, 255, 0, 255);
}
}
- cc.kmGLPopMatrix();
}
- };
+ cc.kmGLPopMatrix();
+ }
+
+ return 0;
+};
+
+proto._getBlendFunc = function (blendMode, premultiAlpha) {
+ var ret = this._currBlendFunc;
+ switch (blendMode) {
+ case spine.BlendMode.Normal:
+ ret.src = premultiAlpha ? cc.ONE : cc.SRC_ALPHA;
+ ret.dst = cc.ONE_MINUS_SRC_ALPHA;
+ break;
+ case spine.BlendMode.Additive:
+ ret.src = premultiAlpha ? cc.ONE : cc.SRC_ALPHA;
+ ret.dst = cc.ONE;
+ break;
+ case spine.BlendMode.Multiply:
+ ret.src = cc.DST_COLOR;
+ ret.dst = cc.ONE_MINUS_SRC_ALPHA;
+ break;
+ case spine.BlendMode.Screen:
+ ret.src = cc.ONE;
+ ret.dst = cc.ONE_MINUS_SRC_COLOR;
+ break;
+ default:
+ ret = this._node._blendFunc;
+ break;
+ }
+
+ return ret;
+};
+
+proto._createChildFormSkeletonData = function(){};
+
+proto._updateChild = function(){};
+
+proto._uploadRegionAttachmentData = function(attachment, slot, premultipliedAlpha, f32buffer, ui32buffer, vertexDataOffset) {
+ // the vertices in format:
+ // [
+ // X1, Y1, C1R, C1G, C1B, C1A, U1, V1, // bottom left
+ // X2, Y2, C2R, C2G, C2B, C2A, U2, V2, // top left
+ // X3, Y3, C3R, C3G, C3B, C3A, U3, V3, // top right
+ // X4, Y4, C4R, C4G, C4B, C4A, U4, V4 // bottom right
+ // ]
+ //
+ var nodeColor = this._displayedColor;
+ var nodeR = nodeColor.r,
+ nodeG = nodeColor.g,
+ nodeB = nodeColor.b,
+ nodeA = this._displayedOpacity;
+
+ var vertices = spine.Utils.setArraySize(new Array(), 8, 0);
+ attachment.computeWorldVertices(slot.bone, vertices, 0, 2);
+
+ var uvs = attachment.uvs;
+
+ // get the colors data
+ var skeleton = slot.bone.skeleton;
+ var skeletonColor = skeleton.color;
+ var slotColor = slot.color;
+ var regionColor = attachment.color;
+ var alpha = skeletonColor.a * slotColor.a * regionColor.a;
+ var multiplier = premultipliedAlpha ? alpha : 1;
+ var colors = attachment.tempColor;
+ colors.set(skeletonColor.r * slotColor.r * regionColor.r * multiplier,
+ skeletonColor.g * slotColor.g * regionColor.g * multiplier,
+ skeletonColor.b * slotColor.b * regionColor.b * multiplier,
+ alpha);
+
+ var wt = this._worldTransform,
+ wa = wt.a, wb = wt.b, wc = wt.c, wd = wt.d,
+ wx = wt.tx, wy = wt.ty,
+ z = this._node.vertexZ;
+
+ var offset = vertexDataOffset;
+ // generate 6 vertices data (two triangles) from the quad vertices
+ // using two angles : (0, 1, 2) & (0, 2, 3)
+ for (var i = 0; i < 6; i++) {
+ var srcIdx = i < 4 ? i % 3 : i - 2;
+ var vx = vertices[srcIdx * 2],
+ vy = vertices[srcIdx * 2 + 1];
+ var x = vx * wa + vy * wc + wx,
+ y = vx * wb + vy * wd + wy;
+ var r = colors.r * nodeR,
+ g = colors.g * nodeG,
+ b = colors.b * nodeB,
+ a = colors.a * nodeA;
+ var color = ((a<<24) | (b<<16) | (g<<8) | r);
+ f32buffer[offset] = x;
+ f32buffer[offset + 1] = y;
+ f32buffer[offset + 2] = z;
+ ui32buffer[offset + 3] = color;
+ f32buffer[offset + 4] = uvs[srcIdx * 2];
+ f32buffer[offset + 5] = uvs[srcIdx * 2 + 1];
+ offset += 6;
+ }
+
+ if (this._node._debugSlots) {
+ // return the quad points info if debug slot enabled
+ var VERTEX = spine.RegionAttachment;
+ return [
+ cc.p(vertices[VERTEX.OX1], vertices[VERTEX.OY1]),
+ cc.p(vertices[VERTEX.OX2], vertices[VERTEX.OY2]),
+ cc.p(vertices[VERTEX.OX3], vertices[VERTEX.OY3]),
+ cc.p(vertices[VERTEX.OX4], vertices[VERTEX.OY4])
+ ];
+ }
+};
+
+proto._uploadMeshAttachmentData = function(attachment, slot, premultipliedAlpha, f32buffer, ui32buffer, vertexDataOffset) {
+ var wt = this._worldTransform,
+ wa = wt.a, wb = wt.b, wc = wt.c, wd = wt.d,
+ wx = wt.tx, wy = wt.ty,
+ z = this._node.vertexZ;
+ // get the vertex data
+ var verticesLength = attachment.worldVerticesLength;
+ var vertices = spine.Utils.setArraySize(new Array(), verticesLength, 0);
+ attachment.computeWorldVertices(slot, 0, verticesLength, vertices, 0, 2);
+
+ var uvs = attachment.uvs;
+
+ // get the colors data
+ var skeleton = slot.bone.skeleton;
+ var skeletonColor = skeleton.color, slotColor = slot.color, meshColor = attachment.color;
+ var alpha = skeletonColor.a * slotColor.a * meshColor.a;
+ var multiplier = premultipliedAlpha ? alpha : 1;
+ var colors = attachment.tempColor;
+ colors.set(skeletonColor.r * slotColor.r * meshColor.r * multiplier,
+ skeletonColor.g * slotColor.g * meshColor.g * multiplier,
+ skeletonColor.b * slotColor.b * meshColor.b * multiplier,
+ alpha);
+
+ var offset = vertexDataOffset;
+ var nodeColor = this._displayedColor;
+ var nodeR = nodeColor.r,
+ nodeG = nodeColor.g,
+ nodeB = nodeColor.b,
+ nodeA = this._displayedOpacity;
+ for (var i = 0, n = vertices.length; i < n; i += 2) {
+ var vx = vertices[i],
+ vy = vertices[i + 1];
+ var x = vx * wa + vy * wb + wx,
+ y = vx * wc + vy * wd + wy;
+ var r = colors.r * nodeR,
+ g = colors.g * nodeG,
+ b = colors.b * nodeB,
+ a = colors.a * nodeA;
+ var color = ((a<<24) | (b<<16) | (g<<8) | r);
+
+ f32buffer[offset] = x;
+ f32buffer[offset + 1] = y;
+ f32buffer[offset + 2] = z;
+ ui32buffer[offset + 3] = color;
+ f32buffer[offset + 4] = uvs[i];
+ f32buffer[offset + 5] = uvs[i + 1];
+ offset += 6;
+ }
+};
- proto._createChildFormSkeletonData = function(){};
-
- proto._updateChild = function(){};
-
- proto._updateRegionAttachmentQuad = function(self, slot, quad, premultipliedAlpha) {
- var vertices = {};
- self.computeVertices(slot.bone.skeleton.x, slot.bone.skeleton.y, slot.bone, vertices);
- var r = slot.bone.skeleton.r * slot.r * 255;
- var g = slot.bone.skeleton.g * slot.g * 255;
- var b = slot.bone.skeleton.b * slot.b * 255;
- var normalizedAlpha = slot.bone.skeleton.a * slot.a;
-
- if (premultipliedAlpha) {
- r *= normalizedAlpha;
- g *= normalizedAlpha;
- b *= normalizedAlpha;
- }
- var a = normalizedAlpha * 255;
-
- quad.bl.colors.r = quad.tl.colors.r = quad.tr.colors.r = quad.br.colors.r = r;
- quad.bl.colors.g = quad.tl.colors.g = quad.tr.colors.g = quad.br.colors.g = g;
- quad.bl.colors.b = quad.tl.colors.b = quad.tr.colors.b = quad.br.colors.b = b;
- quad.bl.colors.a = quad.tl.colors.a = quad.tr.colors.a = quad.br.colors.a = a;
-
- var VERTEX = sp.VERTEX_INDEX;
- quad.bl.vertices.x = vertices[VERTEX.X1];
- quad.bl.vertices.y = vertices[VERTEX.Y1];
- quad.tl.vertices.x = vertices[VERTEX.X2];
- quad.tl.vertices.y = vertices[VERTEX.Y2];
- quad.tr.vertices.x = vertices[VERTEX.X3];
- quad.tr.vertices.y = vertices[VERTEX.Y3];
- quad.br.vertices.x = vertices[VERTEX.X4];
- quad.br.vertices.y = vertices[VERTEX.Y4];
-
- quad.bl.texCoords.u = self.uvs[VERTEX.X1];
- quad.bl.texCoords.v = self.uvs[VERTEX.Y1];
- quad.tl.texCoords.u = self.uvs[VERTEX.X2];
- quad.tl.texCoords.v = self.uvs[VERTEX.Y2];
- quad.tr.texCoords.u = self.uvs[VERTEX.X3];
- quad.tr.texCoords.v = self.uvs[VERTEX.Y3];
- quad.br.texCoords.u = self.uvs[VERTEX.X4];
- quad.br.texCoords.v = self.uvs[VERTEX.Y4];
- };
-
- proto._updateMeshAttachmentQuad = function(self, slot, quad, premultipliedAlpha) {
- var vertices = {};
- self.computeWorldVertices(slot.bone.x, slot.bone.y, slot, vertices);
- var r = slot.bone.skeleton.r * slot.r * 255;
- var g = slot.bone.skeleton.g * slot.g * 255;
- var b = slot.bone.skeleton.b * slot.b * 255;
- var normalizedAlpha = slot.bone.skeleton.a * slot.a;
- if (premultipliedAlpha) {
- r *= normalizedAlpha;
- g *= normalizedAlpha;
- b *= normalizedAlpha;
- }
- var a = normalizedAlpha * 255;
-
- quad.bl.colors.r = quad.tl.colors.r = quad.tr.colors.r = quad.br.colors.r = r;
- quad.bl.colors.g = quad.tl.colors.g = quad.tr.colors.g = quad.br.colors.g = g;
- quad.bl.colors.b = quad.tl.colors.b = quad.tr.colors.b = quad.br.colors.b = b;
- quad.bl.colors.a = quad.tl.colors.a = quad.tr.colors.a = quad.br.colors.a = a;
-
- var VERTEX = sp.VERTEX_INDEX;
- quad.bl.vertices.x = vertices[VERTEX.X1];
- quad.bl.vertices.y = vertices[VERTEX.Y1];
- quad.tl.vertices.x = vertices[VERTEX.X2];
- quad.tl.vertices.y = vertices[VERTEX.Y2];
- quad.tr.vertices.x = vertices[VERTEX.X3];
- quad.tr.vertices.y = vertices[VERTEX.Y3];
- quad.br.vertices.x = vertices[VERTEX.X4];
- quad.br.vertices.y = vertices[VERTEX.Y4];
-
- quad.bl.texCoords.u = self.uvs[VERTEX.X1];
- quad.bl.texCoords.v = self.uvs[VERTEX.Y1];
- quad.tl.texCoords.u = self.uvs[VERTEX.X2];
- quad.tl.texCoords.v = self.uvs[VERTEX.Y2];
- quad.tr.texCoords.u = self.uvs[VERTEX.X3];
- quad.tr.texCoords.v = self.uvs[VERTEX.Y3];
- quad.br.texCoords.u = self.uvs[VERTEX.X4];
- quad.br.texCoords.v = self.uvs[VERTEX.Y4];
- };
})();
diff --git a/extensions/spine/LICENSE b/extensions/spine/LICENSE
new file mode 100644
index 0000000000..daceab94a4
--- /dev/null
+++ b/extensions/spine/LICENSE
@@ -0,0 +1,27 @@
+Spine Runtimes Software License v2.5
+
+Copyright (c) 2013-2016, Esoteric Software
+All rights reserved.
+
+You are granted a perpetual, non-exclusive, non-sublicensable, and
+non-transferable license to use, install, execute, and perform the Spine
+Runtimes software and derivative works solely for personal or internal
+use. Without the written permission of Esoteric Software (see Section 2 of
+the Spine Software License Agreement), you may not (a) modify, translate,
+adapt, or develop new applications using the Spine Runtimes or otherwise
+create derivative works or improvements of the Spine Runtimes or (b) remove,
+delete, alter, or obscure any trademarks or any copyright, trademark, patent,
+or other intellectual property or proprietary rights notices on or in the
+Software, including any copy thereof. Redistributions in binary or source
+form must include this license and terms.
+
+THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
+IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
+EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
+SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF
+USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
+IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
+ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
diff --git a/extensions/spine/Spine.js b/extensions/spine/Spine.js
index 4fe7807715..e7c0d894ea 100644
--- a/extensions/spine/Spine.js
+++ b/extensions/spine/Spine.js
@@ -1,2731 +1,6458 @@
-/******************************************************************************
- * Spine Runtimes Software License
- * Version 2.3
- *
- * Copyright (c) 2013-2015, Esoteric Software
- * All rights reserved.
- *
- * You are granted a perpetual, non-exclusive, non-sublicensable and
- * non-transferable license to use, install, execute and perform the Spine
- * Runtimes Software (the "Software") and derivative works solely for personal
- * or internal use. Without the written permission of Esoteric Software (see
- * Section 2 of the Spine Software License Agreement), you may not (a) modify,
- * translate, adapt or otherwise create derivative works, improvements of the
- * Software or develop new applications using the Software or (b) remove,
- * delete, alter or obscure any trademarks or any copyright, trademark, patent
- * or other intellectual property or proprietary rights notices on or in the
- * Software, including any copy thereof. Redistributions in binary or source
- * form must include this license and terms.
- *
- * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
- * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
- * EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
- * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
- * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
- * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
- * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
- * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- *****************************************************************************/
-
-var spine = {
- radDeg: 180 / Math.PI,
- degRad: Math.PI / 180,
- temp: [],
- Float32Array: (typeof(Float32Array) === 'undefined') ? Array : Float32Array,
- Uint16Array: (typeof(Uint16Array) === 'undefined') ? Array : Uint16Array
-};
-
-spine.BoneData = function (name, parent) {
- this.length = this.x = this.y = this.rotation = 0;
- this.scaleX = this.scaleY = 1;
-
- this.name = name;
- this.parent = parent;
-};
-
-spine.BoneData.prototype = {
- length: 0,
- x: 0, y: 0,
- rotation: 0,
- scaleX: 1, scaleY: 1,
- inheritScale: true,
- inheritRotation: true,
- flipX: false, flipY: false
-};
-
-spine.BlendMode = {
- normal: 0,
- additive: 1,
- multiply: 2,
- screen: 3
-};
-
-spine.SlotData = function (name, boneData) {
- this.r = this.g = this.b = this.a = 1;
- this.blendMode = spine.BlendMode.normal;
-
- this.name = name;
- this.boneData = boneData;
-};
-spine.SlotData.prototype = {
- r: 1, g: 1, b: 1, a: 1,
- attachmentName: null,
- blendMode: spine.BlendMode.normal
-};
-
-spine.IkConstraintData = function (name) {
- this.bendDirection = this.mix = 1;
-
- this.name = name;
- this.bones = [];
-};
-spine.IkConstraintData.prototype = {
- target: null,
- bendDirection: 1,
- mix: 1
-};
-
-spine.Bone = function (boneData, skeleton, parent) {
- this.x = this.y = this.rotation = this.rotationIK = 0;
- this.scaleX = this.scaleY = 1;
- this.flipX = this.flipY = false;
- this.m00 = this.m01 = this.worldX = 0; // a b x
- this.m10 = this.m11= this.worldY = 0; // c d y
- this.worldRotation = 0;
- this.worldScaleX = this.worldScaleY = 1;
- this.worldFlipX = this.worldFlipY = false;
-
- this.data = boneData;
- this.skeleton = skeleton;
- this.parent = parent;
- this.setToSetupPose();
-};
-spine.Bone.yDown = false;
-spine.Bone.prototype = {
- x: 0, y: 0,
- rotation: 0, rotationIK: 0,
- scaleX: 1, scaleY: 1,
- flipX: false, flipY: false,
- m00: 0, m01: 0, worldX: 0, // a b x
- m10: 0, m11: 0, worldY: 0, // c d y
- worldRotation: 0,
- worldScaleX: 1, worldScaleY: 1,
- worldFlipX: false, worldFlipY: false,
- updateWorldTransform: function () {
- var parent = this.parent;
- if (parent) {
- this.worldX = this.x * parent.m00 + this.y * parent.m01 + parent.worldX;
- this.worldY = this.x * parent.m10 + this.y * parent.m11 + parent.worldY;
- if (this.data.inheritScale) {
- this.worldScaleX = parent.worldScaleX * this.scaleX;
- this.worldScaleY = parent.worldScaleY * this.scaleY;
- } else {
- this.worldScaleX = this.scaleX;
- this.worldScaleY = this.scaleY;
- }
- this.worldRotation = this.data.inheritRotation ? (parent.worldRotation + this.rotationIK) : this.rotationIK;
- this.worldFlipX = parent.worldFlipX != this.flipX;
- this.worldFlipY = parent.worldFlipY != this.flipY;
- } else {
- var skeletonFlipX = this.skeleton.flipX, skeletonFlipY = this.skeleton.flipY;
- this.worldX = skeletonFlipX ? -this.x : this.x;
- this.worldY = (skeletonFlipY != spine.Bone.yDown) ? -this.y : this.y;
- this.worldScaleX = this.scaleX;
- this.worldScaleY = this.scaleY;
- this.worldRotation = this.rotationIK;
- this.worldFlipX = skeletonFlipX != this.flipX;
- this.worldFlipY = skeletonFlipY != this.flipY;
- }
- var radians = this.worldRotation * spine.degRad;
- var cos = Math.cos(radians);
- var sin = Math.sin(radians);
- if (this.worldFlipX) {
- this.m00 = -cos * this.worldScaleX;
- this.m01 = sin * this.worldScaleY;
- } else {
- this.m00 = cos * this.worldScaleX;
- this.m01 = -sin * this.worldScaleY;
- }
- if (this.worldFlipY != spine.Bone.yDown) {
- this.m10 = -sin * this.worldScaleX;
- this.m11 = -cos * this.worldScaleY;
- } else {
- this.m10 = sin * this.worldScaleX;
- this.m11 = cos * this.worldScaleY;
- }
- },
- setToSetupPose: function () {
- var data = this.data;
- this.x = data.x;
- this.y = data.y;
- this.rotation = data.rotation;
- this.rotationIK = this.rotation;
- this.scaleX = data.scaleX;
- this.scaleY = data.scaleY;
- this.flipX = data.flipX;
- this.flipY = data.flipY;
- },
- worldToLocal: function (world) {
- var dx = world[0] - this.worldX, dy = world[1] - this.worldY;
- var m00 = this.m00, m10 = this.m10, m01 = this.m01, m11 = this.m11;
- if (this.worldFlipX != (this.worldFlipY != spine.Bone.yDown)) {
- m00 = -m00;
- m11 = -m11;
- }
- var invDet = 1 / (m00 * m11 - m01 * m10);
- world[0] = dx * m00 * invDet - dy * m01 * invDet;
- world[1] = dy * m11 * invDet - dx * m10 * invDet;
- },
- localToWorld: function (local) {
- var localX = local[0], localY = local[1];
- local[0] = localX * this.m00 + localY * this.m01 + this.worldX;
- local[1] = localX * this.m10 + localY * this.m11 + this.worldY;
- }
-};
-
-spine.Slot = function (slotData, bone) {
- this.r = this.g = this.b = this.a = 1;
- this._attachmentTime = 0;
-
- this.data = slotData;
- this.bone = bone;
- this.setToSetupPose();
-};
-spine.Slot.prototype = {
- r: 1, g: 1, b: 1, a: 1,
- _attachmentTime: 0,
- attachment: null,
- attachmentVertices: [],
- setAttachment: function (attachment) {
- this.attachment = attachment;
- this._attachmentTime = this.bone.skeleton.time;
- this.attachmentVertices.length = 0;
- },
- setAttachmentTime: function (time) {
- this._attachmentTime = this.bone.skeleton.time - time;
- },
- getAttachmentTime: function () {
- return this.bone.skeleton.time - this._attachmentTime;
- },
- setToSetupPose: function () {
- var data = this.data;
- this.r = data.r;
- this.g = data.g;
- this.b = data.b;
- this.a = data.a;
-
- var slotDatas = this.bone.skeleton.data.slots;
- for (var i = 0, n = slotDatas.length; i < n; i++) {
- if (slotDatas[i] == data) {
- this.setAttachment(!data.attachmentName ? null : this.bone.skeleton.getAttachmentBySlotIndex(i, data.attachmentName));
- break;
- }
- }
- }
-};
-
-spine.IkConstraint = function (data, skeleton) {
- this.data = data;
- this.mix = data.mix;
- this.bendDirection = data.bendDirection;
-
- this.bones = [];
- for (var i = 0, n = data.bones.length; i < n; i++)
- this.bones.push(skeleton.findBone(data.bones[i].name));
- this.target = skeleton.findBone(data.target.name);
-};
-spine.IkConstraint.prototype = {
- apply: function () {
- var target = this.target;
- var bones = this.bones;
- switch (bones.length) {
- case 1:
- spine.IkConstraint.apply1(bones[0], target.worldX, target.worldY, this.mix);
- break;
- case 2:
- spine.IkConstraint.apply2(bones[0], bones[1], target.worldX, target.worldY, this.bendDirection, this.mix);
- break;
- }
- }
-};
-/** Adjusts the bone rotation so the tip is as close to the target position as possible. The target is specified in the world
- * coordinate system. */
-spine.IkConstraint.apply1 = function (bone, targetX, targetY, alpha) {
- var parentRotation = (!bone.data.inheritRotation || !bone.parent) ? 0 : bone.parent.worldRotation;
- var rotation = bone.rotation;
- var rotationIK = Math.atan2(targetY - bone.worldY, targetX - bone.worldX) * spine.radDeg;
- if (bone.worldFlipX != (bone.worldFlipY != spine.Bone.yDown)) rotationIK = -rotationIK;
- rotationIK -= parentRotation;
- bone.rotationIK = rotation + (rotationIK - rotation) * alpha;
-};
-/** Adjusts the parent and child bone rotations so the tip of the child is as close to the target position as possible. The
- * target is specified in the world coordinate system.
- * @param child Any descendant bone of the parent. */
-spine.IkConstraint.apply2 = function (parent, child, targetX, targetY, bendDirection, alpha) {
- var childRotation = child.rotation, parentRotation = parent.rotation;
- if (!alpha) {
- child.rotationIK = childRotation;
- parent.rotationIK = parentRotation;
- return;
- }
- var positionX, positionY, tempPosition = spine.temp;
- var parentParent = parent.parent;
- if (parentParent) {
- tempPosition[0] = targetX;
- tempPosition[1] = targetY;
- parentParent.worldToLocal(tempPosition);
- targetX = (tempPosition[0] - parent.x) * parentParent.worldScaleX;
- targetY = (tempPosition[1] - parent.y) * parentParent.worldScaleY;
- } else {
- targetX -= parent.x;
- targetY -= parent.y;
- }
- if (child.parent == parent) {
- positionX = child.x;
- positionY = child.y;
- } else {
- tempPosition[0] = child.x;
- tempPosition[1] = child.y;
- child.parent.localToWorld(tempPosition);
- parent.worldToLocal(tempPosition);
- positionX = tempPosition[0];
- positionY = tempPosition[1];
- }
- var childX = positionX * parent.worldScaleX, childY = positionY * parent.worldScaleY;
- var offset = Math.atan2(childY, childX);
- var len1 = Math.sqrt(childX * childX + childY * childY), len2 = child.data.length * child.worldScaleX;
- // Based on code by Ryan Juckett with permission: Copyright (c) 2008-2009 Ryan Juckett, http://www.ryanjuckett.com/
- var cosDenom = 2 * len1 * len2;
- if (cosDenom < 0.0001) {
- child.rotationIK = childRotation + (Math.atan2(targetY, targetX) * spine.radDeg - parentRotation - childRotation) * alpha;
- return;
- }
- var cos = (targetX * targetX + targetY * targetY - len1 * len1 - len2 * len2) / cosDenom;
- if (cos < -1)
- cos = -1;
- else if (cos > 1)
- cos = 1;
- var childAngle = Math.acos(cos) * bendDirection;
- var adjacent = len1 + len2 * cos, opposite = len2 * Math.sin(childAngle);
- var parentAngle = Math.atan2(targetY * adjacent - targetX * opposite, targetX * adjacent + targetY * opposite);
- var rotation = (parentAngle - offset) * spine.radDeg - parentRotation;
- if (rotation > 180)
- rotation -= 360;
- else if (rotation < -180) //
- rotation += 360;
- parent.rotationIK = parentRotation + rotation * alpha;
- rotation = (childAngle + offset) * spine.radDeg - childRotation;
- if (rotation > 180)
- rotation -= 360;
- else if (rotation < -180) //
- rotation += 360;
- child.rotationIK = childRotation + (rotation + parent.worldRotation - child.parent.worldRotation) * alpha;
-};
-
-spine.Skin = function (name) {
- this.name = name;
- this.attachments = {};
-};
-spine.Skin.prototype = {
- addAttachment: function (slotIndex, name, attachment) {
- this.attachments[slotIndex + ":" + name] = attachment;
- },
- getAttachment: function (slotIndex, name) {
- return this.attachments[slotIndex + ":" + name];
- },
- _attachAll: function (skeleton, oldSkin) {
- for (var key in oldSkin.attachments) {
- var colon = key.indexOf(":");
- var slotIndex = parseInt(key.substring(0, colon));
- var name = key.substring(colon + 1);
- var slot = skeleton.slots[slotIndex];
- if (slot.attachment && slot.attachment.name == name) {
- var attachment = this.getAttachment(slotIndex, name);
- if (attachment) slot.setAttachment(attachment);
- }
- }
- }
-};
-
-spine.Animation = function (name, timelines, duration) {
- this.name = name;
- this.timelines = timelines;
- this.duration = duration;
-};
-spine.Animation.prototype = {
- apply: function (skeleton, lastTime, time, loop, events) {
- if (loop && this.duration != 0) {
- time %= this.duration;
- lastTime %= this.duration;
- }
- var timelines = this.timelines;
- for (var i = 0, n = timelines.length; i < n; i++)
- timelines[i].apply(skeleton, lastTime, time, events, 1);
- },
- mix: function (skeleton, lastTime, time, loop, events, alpha) {
- if (loop && this.duration != 0) {
- time %= this.duration;
- lastTime %= this.duration;
- }
- var timelines = this.timelines;
- for (var i = 0, n = timelines.length; i < n; i++)
- timelines[i].apply(skeleton, lastTime, time, events, alpha);
- }
-};
-spine.Animation.binarySearch = function (values, target, step) {
- var low = 0;
- var high = Math.floor(values.length / step) - 2;
- if (!high) return step;
- var current = high >>> 1;
- while (true) {
- if (values[(current + 1) * step] <= target)
- low = current + 1;
- else
- high = current;
- if (low == high) return (low + 1) * step;
- current = (low + high) >>> 1;
- }
-};
-spine.Animation.binarySearch1 = function (values, target) {
- var low = 0;
- var high = values.length - 2;
- if (!high) return 1;
- var current = high >>> 1;
- while (true) {
- if (values[current + 1] <= target)
- low = current + 1;
- else
- high = current;
- if (low == high) return low + 1;
- current = (low + high) >>> 1;
- }
-};
-spine.Animation.linearSearch = function (values, target, step) {
- for (var i = 0, last = values.length - step; i <= last; i += step)
- if (values[i] > target) return i;
- return -1;
-};
-
-spine.Curves = function (frameCount) {
- this.curves = []; // type, x, y, ...
- //this.curves.length = (frameCount - 1) * 19/*BEZIER_SIZE*/;
-};
-spine.Curves.prototype = {
- setLinear: function (frameIndex) {
- this.curves[frameIndex * 19/*BEZIER_SIZE*/] = 0/*LINEAR*/;
- },
- setStepped: function (frameIndex) {
- this.curves[frameIndex * 19/*BEZIER_SIZE*/] = 1/*STEPPED*/;
- },
- /** Sets the control handle positions for an interpolation bezier curve used to transition from this keyframe to the next.
- * cx1 and cx2 are from 0 to 1, representing the percent of time between the two keyframes. cy1 and cy2 are the percent of
- * the difference between the keyframe's values. */
- setCurve: function (frameIndex, cx1, cy1, cx2, cy2) {
- var subdiv1 = 1 / 10/*BEZIER_SEGMENTS*/, subdiv2 = subdiv1 * subdiv1, subdiv3 = subdiv2 * subdiv1;
- var pre1 = 3 * subdiv1, pre2 = 3 * subdiv2, pre4 = 6 * subdiv2, pre5 = 6 * subdiv3;
- var tmp1x = -cx1 * 2 + cx2, tmp1y = -cy1 * 2 + cy2, tmp2x = (cx1 - cx2) * 3 + 1, tmp2y = (cy1 - cy2) * 3 + 1;
- var dfx = cx1 * pre1 + tmp1x * pre2 + tmp2x * subdiv3, dfy = cy1 * pre1 + tmp1y * pre2 + tmp2y * subdiv3;
- var ddfx = tmp1x * pre4 + tmp2x * pre5, ddfy = tmp1y * pre4 + tmp2y * pre5;
- var dddfx = tmp2x * pre5, dddfy = tmp2y * pre5;
-
- var i = frameIndex * 19/*BEZIER_SIZE*/;
- var curves = this.curves;
- curves[i++] = 2/*BEZIER*/;
-
- var x = dfx, y = dfy;
- for (var n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) {
- curves[i] = x;
- curves[i + 1] = y;
- dfx += ddfx;
- dfy += ddfy;
- ddfx += dddfx;
- ddfy += dddfy;
- x += dfx;
- y += dfy;
- }
- },
- getCurvePercent: function (frameIndex, percent) {
- percent = percent < 0 ? 0 : (percent > 1 ? 1 : percent);
- var curves = this.curves;
- var i = frameIndex * 19/*BEZIER_SIZE*/;
- var type = curves[i];
- if (type === 0/*LINEAR*/) return percent;
- if (type == 1/*STEPPED*/) return 0;
- i++;
- var x = 0;
- for (var start = i, n = i + 19/*BEZIER_SIZE*/ - 1; i < n; i += 2) {
- x = curves[i];
- if (x >= percent) {
- var prevX, prevY;
- if (i == start) {
- prevX = 0;
- prevY = 0;
- } else {
- prevX = curves[i - 2];
- prevY = curves[i - 1];
- }
- return prevY + (curves[i + 1] - prevY) * (percent - prevX) / (x - prevX);
- }
- }
- var y = curves[i - 1];
- return y + (1 - y) * (percent - x) / (1 - x); // Last point is 1,1.
- }
-};
-
-spine.RotateTimeline = function (frameCount) {
- this.boneIndex = 0;
-
- this.curves = new spine.Curves(frameCount);
- this.frames = []; // time, angle, ...
- this.frames.length = frameCount * 2;
-};
-spine.RotateTimeline.prototype = {
- boneIndex: 0,
- getFrameCount: function () {
- return this.frames.length / 2;
- },
- setFrame: function (frameIndex, time, angle) {
- frameIndex *= 2;
- this.frames[frameIndex] = time;
- this.frames[frameIndex + 1] = angle;
- },
- apply: function (skeleton, lastTime, time, firedEvents, alpha) {
- var frames = this.frames;
- if (time < frames[0]) return; // Time is before first frame.
-
- var bone = skeleton.bones[this.boneIndex];
-
- if (time >= frames[frames.length - 2]) { // Time is after last frame.
- var amount = bone.data.rotation + frames[frames.length - 1] - bone.rotation;
- while (amount > 180)
- amount -= 360;
- while (amount < -180)
- amount += 360;
- bone.rotation += amount * alpha;
- return;
- }
-
- // Interpolate between the previous frame and the current frame.
- var frameIndex = spine.Animation.binarySearch(frames, time, 2);
- var prevFrameValue = frames[frameIndex - 1];
- var frameTime = frames[frameIndex];
- var percent = 1 - (time - frameTime) / (frames[frameIndex - 2/*PREV_FRAME_TIME*/] - frameTime);
- percent = this.curves.getCurvePercent(frameIndex / 2 - 1, percent);
-
- var amount = frames[frameIndex + 1/*FRAME_VALUE*/] - prevFrameValue;
- while (amount > 180)
- amount -= 360;
- while (amount < -180)
- amount += 360;
- amount = bone.data.rotation + (prevFrameValue + amount * percent) - bone.rotation;
- while (amount > 180)
- amount -= 360;
- while (amount < -180)
- amount += 360;
- bone.rotation += amount * alpha;
- }
-};
-
-spine.TranslateTimeline = function (frameCount) {
- this.boneIndex = 0;
-
- this.curves = new spine.Curves(frameCount);
- this.frames = []; // time, x, y, ...
- this.frames.length = frameCount * 3;
-};
-spine.TranslateTimeline.prototype = {
- boneIndex: 0,
- getFrameCount: function () {
- return this.frames.length / 3;
- },
- setFrame: function (frameIndex, time, x, y) {
- frameIndex *= 3;
- this.frames[frameIndex] = time;
- this.frames[frameIndex + 1] = x;
- this.frames[frameIndex + 2] = y;
- },
- apply: function (skeleton, lastTime, time, firedEvents, alpha) {
- var frames = this.frames;
- if (time < frames[0]) return; // Time is before first frame.
-
- var bone = skeleton.bones[this.boneIndex];
-
- if (time >= frames[frames.length - 3]) { // Time is after last frame.
- bone.x += (bone.data.x + frames[frames.length - 2] - bone.x) * alpha;
- bone.y += (bone.data.y + frames[frames.length - 1] - bone.y) * alpha;
- return;
- }
-
- // Interpolate between the previous frame and the current frame.
- var frameIndex = spine.Animation.binarySearch(frames, time, 3);
- var prevFrameX = frames[frameIndex - 2];
- var prevFrameY = frames[frameIndex - 1];
- var frameTime = frames[frameIndex];
- var percent = 1 - (time - frameTime) / (frames[frameIndex + -3/*PREV_FRAME_TIME*/] - frameTime);
- percent = this.curves.getCurvePercent(frameIndex / 3 - 1, percent);
-
- bone.x += (bone.data.x + prevFrameX + (frames[frameIndex + 1/*FRAME_X*/] - prevFrameX) * percent - bone.x) * alpha;
- bone.y += (bone.data.y + prevFrameY + (frames[frameIndex + 2/*FRAME_Y*/] - prevFrameY) * percent - bone.y) * alpha;
- }
-};
-
-spine.ScaleTimeline = function (frameCount) {
- this.boneIndex = 0;
-
- this.curves = new spine.Curves(frameCount);
- this.frames = []; // time, x, y, ...
- this.frames.length = frameCount * 3;
-};
-spine.ScaleTimeline.prototype = {
- boneIndex: 0,
- getFrameCount: function () {
- return this.frames.length / 3;
- },
- setFrame: function (frameIndex, time, x, y) {
- frameIndex *= 3;
- this.frames[frameIndex] = time;
- this.frames[frameIndex + 1] = x;
- this.frames[frameIndex + 2] = y;
- },
- apply: function (skeleton, lastTime, time, firedEvents, alpha) {
- var frames = this.frames;
- if (time < frames[0]) return; // Time is before first frame.
-
- var bone = skeleton.bones[this.boneIndex];
-
- if (time >= frames[frames.length - 3]) { // Time is after last frame.
- bone.scaleX += (bone.data.scaleX * frames[frames.length - 2] - bone.scaleX) * alpha;
- bone.scaleY += (bone.data.scaleY * frames[frames.length - 1] - bone.scaleY) * alpha;
- return;
- }
-
- // Interpolate between the previous frame and the current frame.
- var frameIndex = spine.Animation.binarySearch(frames, time, 3);
- var prevFrameX = frames[frameIndex - 2];
- var prevFrameY = frames[frameIndex - 1];
- var frameTime = frames[frameIndex];
- var percent = 1 - (time - frameTime) / (frames[frameIndex + -3/*PREV_FRAME_TIME*/] - frameTime);
- percent = this.curves.getCurvePercent(frameIndex / 3 - 1, percent);
-
- bone.scaleX += (bone.data.scaleX * (prevFrameX + (frames[frameIndex + 1/*FRAME_X*/] - prevFrameX) * percent) - bone.scaleX) * alpha;
- bone.scaleY += (bone.data.scaleY * (prevFrameY + (frames[frameIndex + 2/*FRAME_Y*/] - prevFrameY) * percent) - bone.scaleY) * alpha;
- }
-};
-
-spine.ColorTimeline = function (frameCount) {
- this.boneIndex = 0;
-
- this.curves = new spine.Curves(frameCount);
- this.frames = []; // time, r, g, b, a, ...
- this.frames.length = frameCount * 5;
-};
-spine.ColorTimeline.prototype = {
- slotIndex: 0,
- getFrameCount: function () {
- return this.frames.length / 5;
- },
- setFrame: function (frameIndex, time, r, g, b, a) {
- frameIndex *= 5;
- this.frames[frameIndex] = time;
- this.frames[frameIndex + 1] = r;
- this.frames[frameIndex + 2] = g;
- this.frames[frameIndex + 3] = b;
- this.frames[frameIndex + 4] = a;
- },
- apply: function (skeleton, lastTime, time, firedEvents, alpha) {
- var frames = this.frames;
- if (time < frames[0]) return; // Time is before first frame.
-
- var r, g, b, a;
- if (time >= frames[frames.length - 5]) {
- // Time is after last frame.
- var i = frames.length - 1;
- r = frames[i - 3];
- g = frames[i - 2];
- b = frames[i - 1];
- a = frames[i];
- } else {
- // Interpolate between the previous frame and the current frame.
- var frameIndex = spine.Animation.binarySearch(frames, time, 5);
- var prevFrameR = frames[frameIndex - 4];
- var prevFrameG = frames[frameIndex - 3];
- var prevFrameB = frames[frameIndex - 2];
- var prevFrameA = frames[frameIndex - 1];
- var frameTime = frames[frameIndex];
- var percent = 1 - (time - frameTime) / (frames[frameIndex - 5/*PREV_FRAME_TIME*/] - frameTime);
- percent = this.curves.getCurvePercent(frameIndex / 5 - 1, percent);
-
- r = prevFrameR + (frames[frameIndex + 1/*FRAME_R*/] - prevFrameR) * percent;
- g = prevFrameG + (frames[frameIndex + 2/*FRAME_G*/] - prevFrameG) * percent;
- b = prevFrameB + (frames[frameIndex + 3/*FRAME_B*/] - prevFrameB) * percent;
- a = prevFrameA + (frames[frameIndex + 4/*FRAME_A*/] - prevFrameA) * percent;
- }
- var slot = skeleton.slots[this.slotIndex];
- if (alpha < 1) {
- slot.r += (r - slot.r) * alpha;
- slot.g += (g - slot.g) * alpha;
- slot.b += (b - slot.b) * alpha;
- slot.a += (a - slot.a) * alpha;
- } else {
- slot.r = r;
- slot.g = g;
- slot.b = b;
- slot.a = a;
- }
- }
-};
-
-spine.AttachmentTimeline = function (frameCount) {
- this.slotIndex = 0;
-
- this.curves = new spine.Curves(frameCount);
- this.frames = []; // time, ...
- this.frames.length = frameCount;
- this.attachmentNames = [];
- this.attachmentNames.length = frameCount;
-};
-spine.AttachmentTimeline.prototype = {
- slotIndex: 0,
- getFrameCount: function () {
- return this.frames.length;
- },
- setFrame: function (frameIndex, time, attachmentName) {
- this.frames[frameIndex] = time;
- this.attachmentNames[frameIndex] = attachmentName;
- },
- apply: function (skeleton, lastTime, time, firedEvents, alpha) {
- var frames = this.frames;
- if (time < frames[0]) {
- if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0);
- return;
- } else if (lastTime > time) //
- lastTime = -1;
-
- var frameIndex = time >= frames[frames.length - 1] ? frames.length - 1 : spine.Animation.binarySearch1(frames, time) - 1;
- if (frames[frameIndex] < lastTime) return;
-
- var attachmentName = this.attachmentNames[frameIndex];
- skeleton.slots[this.slotIndex].setAttachment(
- !attachmentName ? null : skeleton.getAttachmentBySlotIndex(this.slotIndex, attachmentName));
- }
-};
-
-spine.EventTimeline = function (frameCount) {
- this.frames = []; // time, ...
- this.frames.length = frameCount;
- this.events = [];
- this.events.length = frameCount;
-};
-spine.EventTimeline.prototype = {
- getFrameCount: function () {
- return this.frames.length;
- },
- setFrame: function (frameIndex, time, event) {
- this.frames[frameIndex] = time;
- this.events[frameIndex] = event;
- },
- /** Fires events for frames > lastTime and <= time. */
- apply: function (skeleton, lastTime, time, firedEvents, alpha) {
- if (!firedEvents) return;
-
- var frames = this.frames;
- var frameCount = frames.length;
-
- if (lastTime > time) { // Fire events after last time for looped animations.
- this.apply(skeleton, lastTime, Number.MAX_VALUE, firedEvents, alpha);
- lastTime = -1;
- } else if (lastTime >= frames[frameCount - 1]) // Last time is after last frame.
- return;
- if (time < frames[0]) return; // Time is before first frame.
-
- var frameIndex;
- if (lastTime < frames[0])
- frameIndex = 0;
- else {
- frameIndex = spine.Animation.binarySearch1(frames, lastTime);
- var frame = frames[frameIndex];
- while (frameIndex > 0) { // Fire multiple events with the same frame.
- if (frames[frameIndex - 1] != frame) break;
- frameIndex--;
- }
- }
- var events = this.events;
- for (; frameIndex < frameCount && time >= frames[frameIndex]; frameIndex++)
- firedEvents.push(events[frameIndex]);
- }
-};
-
-spine.DrawOrderTimeline = function (frameCount) {
- this.frames = []; // time, ...
- this.frames.length = frameCount;
- this.drawOrders = [];
- this.drawOrders.length = frameCount;
-};
-spine.DrawOrderTimeline.prototype = {
- getFrameCount: function () {
- return this.frames.length;
- },
- setFrame: function (frameIndex, time, drawOrder) {
- this.frames[frameIndex] = time;
- this.drawOrders[frameIndex] = drawOrder;
- },
- apply: function (skeleton, lastTime, time, firedEvents, alpha) {
- var frames = this.frames;
- if (time < frames[0]) return; // Time is before first frame.
-
- var frameIndex;
- if (time >= frames[frames.length - 1]) // Time is after last frame.
- frameIndex = frames.length - 1;
- else
- frameIndex = spine.Animation.binarySearch1(frames, time) - 1;
-
- var drawOrder = skeleton.drawOrder;
- var slots = skeleton.slots;
- var drawOrderToSetupIndex = this.drawOrders[frameIndex];
- if (!drawOrderToSetupIndex) {
- for (var i = 0, n = slots.length; i < n; i++)
- drawOrder[i] = slots[i];
- } else {
- for (var i = 0, n = drawOrderToSetupIndex.length; i < n; i++)
- drawOrder[i] = skeleton.slots[drawOrderToSetupIndex[i]];
- }
-
- }
-};
-
-spine.FfdTimeline = function (frameCount) {
- this.slotIndex = this.attachment = 0;
-
- this.curves = new spine.Curves(frameCount);
- this.frames = [];
- this.frames.length = frameCount;
- this.frameVertices = [];
- this.frameVertices.length = frameCount;
-};
-spine.FfdTimeline.prototype = {
- slotIndex: 0,
- attachment: 0,
- getFrameCount: function () {
- return this.frames.length;
- },
- setFrame: function (frameIndex, time, vertices) {
- this.frames[frameIndex] = time;
- this.frameVertices[frameIndex] = vertices;
- },
- apply: function (skeleton, lastTime, time, firedEvents, alpha) {
- var slot = skeleton.slots[this.slotIndex];
- if (slot.attachment != this.attachment) return;
-
- var frames = this.frames;
- if (time < frames[0]) return; // Time is before first frame.
-
- var frameVertices = this.frameVertices;
- var vertexCount = frameVertices[0].length;
-
- var vertices = slot.attachmentVertices;
- if (vertices.length != vertexCount) alpha = 1;
- vertices.length = vertexCount;
-
- if (time >= frames[frames.length - 1]) { // Time is after last frame.
- var lastVertices = frameVertices[frames.length - 1];
- if (alpha < 1) {
- for (var i = 0; i < vertexCount; i++)
- vertices[i] += (lastVertices[i] - vertices[i]) * alpha;
- } else {
- for (var i = 0; i < vertexCount; i++)
- vertices[i] = lastVertices[i];
- }
- return;
- }
-
- // Interpolate between the previous frame and the current frame.
- var frameIndex = spine.Animation.binarySearch1(frames, time);
- var frameTime = frames[frameIndex];
- var percent = 1 - (time - frameTime) / (frames[frameIndex - 1] - frameTime);
- percent = this.curves.getCurvePercent(frameIndex - 1, percent < 0 ? 0 : (percent > 1 ? 1 : percent));
-
- var prevVertices = frameVertices[frameIndex - 1];
- var nextVertices = frameVertices[frameIndex];
-
- if (alpha < 1) {
- for (var i = 0; i < vertexCount; i++) {
- var prev = prevVertices[i];
- vertices[i] += (prev + (nextVertices[i] - prev) * percent - vertices[i]) * alpha;
- }
- } else {
- for (var i = 0; i < vertexCount; i++) {
- var prev = prevVertices[i];
- vertices[i] = prev + (nextVertices[i] - prev) * percent;
- }
- }
- }
-};
-
-spine.IkConstraintTimeline = function (frameCount) {
- this.ikConstraintIndex = 0;
-
- this.curves = new spine.Curves(frameCount);
- this.frames = []; // time, mix, bendDirection, ...
- this.frames.length = frameCount * 3;
-};
-spine.IkConstraintTimeline.prototype = {
- ikConstraintIndex: 0,
- getFrameCount: function () {
- return this.frames.length / 3;
- },
- setFrame: function (frameIndex, time, mix, bendDirection) {
- frameIndex *= 3;
- this.frames[frameIndex] = time;
- this.frames[frameIndex + 1] = mix;
- this.frames[frameIndex + 2] = bendDirection;
- },
- apply: function (skeleton, lastTime, time, firedEvents, alpha) {
- var frames = this.frames;
- if (time < frames[0]) return; // Time is before first frame.
-
- var ikConstraint = skeleton.ikConstraints[this.ikConstraintIndex];
-
- if (time >= frames[frames.length - 3]) { // Time is after last frame.
- ikConstraint.mix += (frames[frames.length - 2] - ikConstraint.mix) * alpha;
- ikConstraint.bendDirection = frames[frames.length - 1];
- return;
- }
-
- // Interpolate between the previous frame and the current frame.
- var frameIndex = spine.Animation.binarySearch(frames, time, 3);
- var prevFrameMix = frames[frameIndex + -2/*PREV_FRAME_MIX*/];
- var frameTime = frames[frameIndex];
- var percent = 1 - (time - frameTime) / (frames[frameIndex + -3/*PREV_FRAME_TIME*/] - frameTime);
- percent = this.curves.getCurvePercent(frameIndex / 3 - 1, percent);
-
- var mix = prevFrameMix + (frames[frameIndex + 1/*FRAME_MIX*/] - prevFrameMix) * percent;
- ikConstraint.mix += (mix - ikConstraint.mix) * alpha;
- ikConstraint.bendDirection = frames[frameIndex + -1/*PREV_FRAME_BEND_DIRECTION*/];
- }
-};
-
-spine.FlipXTimeline = function (frameCount) {
- this.boneIndex = 0;
-
- this.curves = new spine.Curves(frameCount);
- this.frames = []; // time, flip, ...
- this.frames.length = frameCount * 2;
-};
-spine.FlipXTimeline.prototype = {
- boneIndex: 0,
- getFrameCount: function () {
- return this.frames.length / 2;
- },
- setFrame: function (frameIndex, time, flip) {
- frameIndex *= 2;
- this.frames[frameIndex] = time;
- this.frames[frameIndex + 1] = flip ? 1 : 0;
- },
- apply: function (skeleton, lastTime, time, firedEvents, alpha) {
- var frames = this.frames;
- if (time < frames[0]) {
- if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0);
- return;
- } else if (lastTime > time) //
- lastTime = -1;
- var frameIndex = (time >= frames[frames.length - 2] ? frames.length : spine.Animation.binarySearch(frames, time, 2)) - 2;
- if (frames[frameIndex] < lastTime) return;
- skeleton.bones[this.boneIndex].flipX = frames[frameIndex + 1] != 0;
- }
-};
-
-spine.FlipYTimeline = function (frameCount) {
- this.boneIndex = 0;
-
- this.curves = new spine.Curves(frameCount);
- this.frames = []; // time, flip, ...
- this.frames.length = frameCount * 2;
-};
-spine.FlipYTimeline.prototype = {
- boneIndex: 0,
- getFrameCount: function () {
- return this.frames.length / 2;
- },
- setFrame: function (frameIndex, time, flip) {
- frameIndex *= 2;
- this.frames[frameIndex] = time;
- this.frames[frameIndex + 1] = flip ? 1 : 0;
- },
- apply: function (skeleton, lastTime, time, firedEvents, alpha) {
- var frames = this.frames;
- if (time < frames[0]) {
- if (lastTime > time) this.apply(skeleton, lastTime, Number.MAX_VALUE, null, 0);
- return;
- } else if (lastTime > time) //
- lastTime = -1;
- var frameIndex = (time >= frames[frames.length - 2] ? frames.length : spine.Animation.binarySearch(frames, time, 2)) - 2;
- if (frames[frameIndex] < lastTime) return;
- skeleton.bones[this.boneIndex].flipY = frames[frameIndex + 1] != 0;
- }
-};
-
-spine.SkeletonData = function () {
- this.width = this.height = 0;
-
- this.bones = [];
- this.slots = [];
- this.skins = [];
- this.events = [];
- this.animations = [];
- this.ikConstraints = [];
-};
-spine.SkeletonData.prototype = {
- name: null,
- defaultSkin: null,
- width: 0, height: 0,
- version: null, hash: null,
- /** @return May be null. */
- findBone: function (boneName) {
- var bones = this.bones;
- for (var i = 0, n = bones.length; i < n; i++)
- if (bones[i].name == boneName) return bones[i];
- return null;
- },
- /** @return -1 if the bone was not found. */
- findBoneIndex: function (boneName) {
- var bones = this.bones;
- for (var i = 0, n = bones.length; i < n; i++)
- if (bones[i].name == boneName) return i;
- return -1;
- },
- /** @return May be null. */
- findSlot: function (slotName) {
- var slots = this.slots;
- for (var i = 0, n = slots.length; i < n; i++) {
- if (slots[i].name == slotName) return slot[i];
- }
- return null;
- },
- /** @return -1 if the bone was not found. */
- findSlotIndex: function (slotName) {
- var slots = this.slots;
- for (var i = 0, n = slots.length; i < n; i++)
- if (slots[i].name == slotName) return i;
- return -1;
- },
- /** @return May be null. */
- findSkin: function (skinName) {
- var skins = this.skins;
- for (var i = 0, n = skins.length; i < n; i++)
- if (skins[i].name == skinName) return skins[i];
- return null;
- },
- /** @return May be null. */
- findEvent: function (eventName) {
- var events = this.events;
- for (var i = 0, n = events.length; i < n; i++)
- if (events[i].name == eventName) return events[i];
- return null;
- },
- /** @return May be null. */
- findAnimation: function (animationName) {
- var animations = this.animations;
- for (var i = 0, n = animations.length; i < n; i++)
- if (animations[i].name == animationName) return animations[i];
- return null;
- },
- /** @return May be null. */
- findIkConstraint: function (ikConstraintName) {
- var ikConstraints = this.ikConstraints;
- for (var i = 0, n = ikConstraints.length; i < n; i++)
- if (ikConstraints[i].name == ikConstraintName) return ikConstraints[i];
- return null;
- }
-};
-
-spine.Skeleton = function (skeletonData) {
- this.x = this.y = 0;
- this.r = this.g = this.b = this.a = 1;
- this.time = 0;
- this.flipX = this.flipY = false;
-
- this.data = skeletonData;
-
- this.bones = [];
- for (var i = 0, n = skeletonData.bones.length; i < n; i++) {
- var boneData = skeletonData.bones[i];
- var parent = !boneData.parent ? null : this.bones[skeletonData.bones.indexOf(boneData.parent)];
- this.bones.push(new spine.Bone(boneData, this, parent));
- }
-
- this.slots = [];
- this.drawOrder = [];
- for (var i = 0, n = skeletonData.slots.length; i < n; i++) {
- var slotData = skeletonData.slots[i];
- var bone = this.bones[skeletonData.bones.indexOf(slotData.boneData)];
- var slot = new spine.Slot(slotData, bone);
- this.slots.push(slot);
- this.drawOrder.push(slot);
- }
-
- this.ikConstraints = [];
- for (var i = 0, n = skeletonData.ikConstraints.length; i < n; i++)
- this.ikConstraints.push(new spine.IkConstraint(skeletonData.ikConstraints[i], this));
-
- this.boneCache = [];
- this.updateCache();
-};
-spine.Skeleton.prototype = {
- x: 0, y: 0,
- skin: null,
- r: 1, g: 1, b: 1, a: 1,
- time: 0,
- flipX: false, flipY: false,
- /** Caches information about bones and IK constraints. Must be called if bones or IK constraints are added or removed. */
- updateCache: function () {
- var ikConstraints = this.ikConstraints;
- var ikConstraintsCount = ikConstraints.length;
-
- var arrayCount = ikConstraintsCount + 1;
- var boneCache = this.boneCache;
- if (boneCache.length > arrayCount) boneCache.length = arrayCount;
- for (var i = 0, n = boneCache.length; i < n; i++)
- boneCache[i].length = 0;
- while (boneCache.length < arrayCount)
- boneCache[boneCache.length] = [];
-
- var nonIkBones = boneCache[0];
- var bones = this.bones;
-
- outer:
- for (var i = 0, n = bones.length; i < n; i++) {
- var bone = bones[i];
- var current = bone;
- do {
- for (var ii = 0; ii < ikConstraintsCount; ii++) {
- var ikConstraint = ikConstraints[ii];
- var parent = ikConstraint.bones[0];
- var child= ikConstraint.bones[ikConstraint.bones.length - 1];
- while (true) {
- if (current == child) {
- boneCache[ii].push(bone);
- boneCache[ii + 1].push(bone);
- continue outer;
- }
- if (child == parent) break;
- child = child.parent;
- }
- }
- current = current.parent;
- } while (current);
- nonIkBones[nonIkBones.length] = bone;
- }
- },
- /** Updates the world transform for each bone. */
- updateWorldTransform: function () {
- var bones = this.bones;
- for (var i = 0, n = bones.length; i < n; i++) {
- var bone = bones[i];
- bone.rotationIK = bone.rotation;
- }
- var i = 0, last = this.boneCache.length - 1;
- while (true) {
- var cacheBones = this.boneCache[i];
- for (var ii = 0, nn = cacheBones.length; ii < nn; ii++)
- cacheBones[ii].updateWorldTransform();
- if (i == last) break;
- this.ikConstraints[i].apply();
- i++;
- }
- },
- /** Sets the bones and slots to their setup pose values. */
- setToSetupPose: function () {
- this.setBonesToSetupPose();
- this.setSlotsToSetupPose();
- },
- setBonesToSetupPose: function () {
- var bones = this.bones;
- for (var i = 0, n = bones.length; i < n; i++)
- bones[i].setToSetupPose();
-
- var ikConstraints = this.ikConstraints;
- for (var i = 0, n = ikConstraints.length; i < n; i++) {
- var ikConstraint = ikConstraints[i];
- ikConstraint.bendDirection = ikConstraint.data.bendDirection;
- ikConstraint.mix = ikConstraint.data.mix;
- }
- },
- setSlotsToSetupPose: function () {
- var slots = this.slots;
- var drawOrder = this.drawOrder;
- for (var i = 0, n = slots.length; i < n; i++) {
- drawOrder[i] = slots[i];
- slots[i].setToSetupPose(i);
- }
- },
- /** @return May return null. */
- getRootBone: function () {
- return this.bones.length ? this.bones[0] : null;
- },
- /** @return May be null. */
- findBone: function (boneName) {
- var bones = this.bones;
- for (var i = 0, n = bones.length; i < n; i++)
- if (bones[i].data.name == boneName) return bones[i];
- return null;
- },
- /** @return -1 if the bone was not found. */
- findBoneIndex: function (boneName) {
- var bones = this.bones;
- for (var i = 0, n = bones.length; i < n; i++)
- if (bones[i].data.name == boneName) return i;
- return -1;
- },
- /** @return May be null. */
- findSlot: function (slotName) {
- var slots = this.slots;
- for (var i = 0, n = slots.length; i < n; i++)
- if (slots[i].data.name == slotName) return slots[i];
- return null;
- },
- /** @return -1 if the bone was not found. */
- findSlotIndex: function (slotName) {
- var slots = this.slots;
- for (var i = 0, n = slots.length; i < n; i++)
- if (slots[i].data.name == slotName) return i;
- return -1;
- },
- setSkinByName: function (skinName) {
- var skin = this.data.findSkin(skinName);
- if (!skin) throw new Error("Skin not found: " + skinName);
- this.setSkin(skin);
- },
- /** Sets the skin used to look up attachments before looking in the {@link SkeletonData#getDefaultSkin() default skin}.
- * Attachments from the new skin are attached if the corresponding attachment from the old skin was attached. If there was
- * no old skin, each slot's setup mode attachment is attached from the new skin.
- * @param newSkin May be null. */
- setSkin: function (newSkin) {
- if (newSkin) {
- if (this.skin)
- newSkin._attachAll(this, this.skin);
- else {
- var slots = this.slots;
- for (var i = 0, n = slots.length; i < n; i++) {
- var slot = slots[i];
- var name = slot.data.attachmentName;
- if (name) {
- var attachment = newSkin.getAttachment(i, name);
- if (attachment) slot.setAttachment(attachment);
- }
- }
- }
- }
- this.skin = newSkin;
- },
- /** @return May be null. */
- getAttachmentBySlotName: function (slotName, attachmentName) {
- return this.getAttachmentBySlotIndex(this.data.findSlotIndex(slotName), attachmentName);
- },
- /** @return May be null. */
- getAttachmentBySlotIndex: function (slotIndex, attachmentName) {
- if (this.skin) {
- var attachment = this.skin.getAttachment(slotIndex, attachmentName);
- if (attachment) return attachment;
- }
- if (this.data.defaultSkin) return this.data.defaultSkin.getAttachment(slotIndex, attachmentName);
- return null;
- },
- /** @param attachmentName May be null. */
- setAttachment: function (slotName, attachmentName) {
- var slots = this.slots;
- for (var i = 0, n = slots.length; i < n; i++) {
- var slot = slots[i];
- if (slot.data.name == slotName) {
- var attachment = null;
- if (attachmentName) {
- attachment = this.getAttachmentBySlotIndex(i, attachmentName);
- if (!attachment) throw new Error("Attachment not found: " + attachmentName + ", for slot: " + slotName);
- }
- slot.setAttachment(attachment);
- return;
- }
- }
- throw new Error("Slot not found: " + slotName);
- },
- /** @return May be null. */
- findIkConstraint: function (ikConstraintName) {
- var ikConstraints = this.ikConstraints;
- for (var i = 0, n = ikConstraints.length; i < n; i++)
- if (ikConstraints[i].data.name == ikConstraintName) return ikConstraints[i];
- return null;
- },
- update: function (delta) {
- this.time += delta;
- }
-};
-
-spine.EventData = function (name) {
- this.intValue = this.floatValue = 0;
-
- this.name = name;
-};
-spine.EventData.prototype = {
- intValue: 0,
- floatValue: 0,
- stringValue: null
-};
-
-spine.Event = function (data) {
- this.intValue = this.floatValue = 0;
-
- this.data = data;
-};
-spine.Event.prototype = {
- intValue: 0,
- floatValue: 0,
- stringValue: null
-};
-
-spine.AttachmentType = {
- region: 0,
- boundingbox: 1,
- mesh: 2,
- skinnedmesh: 3
-};
-
-spine.RegionAttachment = function (name) {
- this.type = spine.AttachmentType.region;
- this.x = this.y = this.rotation = 0;
- this.scaleX = this.scaleY = 1;
- this.width = this.height = 0;
- this.r = this.g = this.b = this.a = 1;
- this.regionOffsetX = this.regionOffsetY = this.regionWidth = this.regionHeight = this.regionOriginalWidth = this.regionOriginalHeight = 0;
-
- this.name = name;
- this.offset = [];
- this.offset.length = 8;
- this.uvs = [];
- this.uvs.length = 8;
-};
-spine.RegionAttachment.prototype = {
- x: 0, y: 0,
- rotation: 0,
- scaleX: 1, scaleY: 1,
- width: 0, height: 0,
- r: 1, g: 1, b: 1, a: 1,
- path: null,
- rendererObject: null,
- regionOffsetX: 0, regionOffsetY: 0,
- regionWidth: 0, regionHeight: 0,
- regionOriginalWidth: 0, regionOriginalHeight: 0,
- setUVs: function (u, v, u2, v2, rotate) {
- var uvs = this.uvs;
- if (rotate) {
- uvs[2/*X2*/] = u;
- uvs[3/*Y2*/] = v2;
- uvs[4/*X3*/] = u;
- uvs[5/*Y3*/] = v;
- uvs[6/*X4*/] = u2;
- uvs[7/*Y4*/] = v;
- uvs[0/*X1*/] = u2;
- uvs[1/*Y1*/] = v2;
- } else {
- uvs[0/*X1*/] = u;
- uvs[1/*Y1*/] = v2;
- uvs[2/*X2*/] = u;
- uvs[3/*Y2*/] = v;
- uvs[4/*X3*/] = u2;
- uvs[5/*Y3*/] = v;
- uvs[6/*X4*/] = u2;
- uvs[7/*Y4*/] = v2;
- }
- },
- updateOffset: function () {
- var regionScaleX = this.width / this.regionOriginalWidth * this.scaleX;
- var regionScaleY = this.height / this.regionOriginalHeight * this.scaleY;
- var localX = -this.width / 2 * this.scaleX + this.regionOffsetX * regionScaleX;
- var localY = -this.height / 2 * this.scaleY + this.regionOffsetY * regionScaleY;
- var localX2 = localX + this.regionWidth * regionScaleX;
- var localY2 = localY + this.regionHeight * regionScaleY;
- var radians = this.rotation * spine.degRad;
- var cos = Math.cos(radians);
- var sin = Math.sin(radians);
- var localXCos = localX * cos + this.x;
- var localXSin = localX * sin;
- var localYCos = localY * cos + this.y;
- var localYSin = localY * sin;
- var localX2Cos = localX2 * cos + this.x;
- var localX2Sin = localX2 * sin;
- var localY2Cos = localY2 * cos + this.y;
- var localY2Sin = localY2 * sin;
- var offset = this.offset;
- offset[0/*X1*/] = localXCos - localYSin;
- offset[1/*Y1*/] = localYCos + localXSin;
- offset[2/*X2*/] = localXCos - localY2Sin;
- offset[3/*Y2*/] = localY2Cos + localXSin;
- offset[4/*X3*/] = localX2Cos - localY2Sin;
- offset[5/*Y3*/] = localY2Cos + localX2Sin;
- offset[6/*X4*/] = localX2Cos - localYSin;
- offset[7/*Y4*/] = localYCos + localX2Sin;
- },
- computeVertices: function (x, y, bone, vertices) {
- x += bone.worldX;
- y += bone.worldY;
- var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11;
- var offset = this.offset;
- vertices[0/*X1*/] = offset[0/*X1*/] * m00 + offset[1/*Y1*/] * m01 + x;
- vertices[1/*Y1*/] = offset[0/*X1*/] * m10 + offset[1/*Y1*/] * m11 + y;
- vertices[2/*X2*/] = offset[2/*X2*/] * m00 + offset[3/*Y2*/] * m01 + x;
- vertices[3/*Y2*/] = offset[2/*X2*/] * m10 + offset[3/*Y2*/] * m11 + y;
- vertices[4/*X3*/] = offset[4/*X3*/] * m00 + offset[5/*X3*/] * m01 + x;
- vertices[5/*X3*/] = offset[4/*X3*/] * m10 + offset[5/*X3*/] * m11 + y;
- vertices[6/*X4*/] = offset[6/*X4*/] * m00 + offset[7/*Y4*/] * m01 + x;
- vertices[7/*Y4*/] = offset[6/*X4*/] * m10 + offset[7/*Y4*/] * m11 + y;
- }
-};
-
-spine.MeshAttachment = function (name) {
- this.type = spine.AttachmentType.mesh;
- this.hullLength = 0;
- this.r = this.g = this.b = this.a = 1;
- this.regionU = this.regionV = this.regionV2 = 0;
- this.regionRotate = false;
- this.regionOffsetX = this.regionOffsetY = this.regionWidth = this.regionHeight = this.regionOriginalWidth = this.regionOriginalHeight = 0;
- this.width = this.height = 0;
-
- this.name = name;
-};
-spine.MeshAttachment.prototype = {
- vertices: null,
- uvs: null,
- regionUVs: null,
- triangles: null,
- hullLength: 0,
- r: 1, g: 1, b: 1, a: 1,
- path: null,
- rendererObject: null,
- regionU: 0, regionV: 0, regionU2: 0, regionV2: 0, regionRotate: false,
- regionOffsetX: 0, regionOffsetY: 0,
- regionWidth: 0, regionHeight: 0,
- regionOriginalWidth: 0, regionOriginalHeight: 0,
- edges: null,
- width: 0, height: 0,
- updateUVs: function () {
- var width = this.regionU2 - this.regionU, height = this.regionV2 - this.regionV;
- var n = this.regionUVs.length;
- if (!this.uvs || this.uvs.length != n) {
- this.uvs = new spine.Float32Array(n);
- }
- if (this.regionRotate) {
- for (var i = 0; i < n; i += 2) {
- this.uvs[i] = this.regionU + this.regionUVs[i + 1] * width;
- this.uvs[i + 1] = this.regionV + height - this.regionUVs[i] * height;
- }
- } else {
- for (var i = 0; i < n; i += 2) {
- this.uvs[i] = this.regionU + this.regionUVs[i] * width;
- this.uvs[i + 1] = this.regionV + this.regionUVs[i + 1] * height;
- }
- }
- },
- computeWorldVertices: function (x, y, slot, worldVertices) {
- var bone = slot.bone;
- x += bone.worldX;
- y += bone.worldY;
- var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11;
- var vertices = this.vertices;
- var verticesCount = vertices.length;
- if (slot.attachmentVertices.length == verticesCount) vertices = slot.attachmentVertices;
- for (var i = 0; i < verticesCount; i += 2) {
- var vx = vertices[i];
- var vy = vertices[i + 1];
- worldVertices[i] = vx * m00 + vy * m01 + x;
- worldVertices[i + 1] = vx * m10 + vy * m11 + y;
- }
- }
-};
-
-spine.SkinnedMeshAttachment = function (name) {
- this.type = spine.AttachmentType.skinnedmesh;
- this.hullLength = 0;
- this.r = this.g = this.b = this.a = 1;
- this.regionU = this.regionV = this.regionU2 = this.regionV2 = 0;
- this.regionRotate = false;
- this.regionOffsetX = this.regionOffsetY = this.regionWidth = this.regionHeight = this.regionOriginalWidth = this.regionOriginalHeight = 0;
- this.width = this.height = 0;
-
- this.name = name;
-};
-spine.SkinnedMeshAttachment.prototype = {
- bones: null,
- weights: null,
- uvs: null,
- regionUVs: null,
- triangles: null,
- hullLength: 0,
- r: 1, g: 1, b: 1, a: 1,
- path: null,
- rendererObject: null,
- regionU: 0, regionV: 0, regionU2: 0, regionV2: 0, regionRotate: false,
- regionOffsetX: 0, regionOffsetY: 0,
- regionWidth: 0, regionHeight: 0,
- regionOriginalWidth: 0, regionOriginalHeight: 0,
- edges: null,
- width: 0, height: 0,
- updateUVs: function (u, v, u2, v2, rotate) {
- var width = this.regionU2 - this.regionU, height = this.regionV2 - this.regionV;
- var n = this.regionUVs.length;
- if (!this.uvs || this.uvs.length != n) {
- this.uvs = new spine.Float32Array(n);
- }
- if (this.regionRotate) {
- for (var i = 0; i < n; i += 2) {
- this.uvs[i] = this.regionU + this.regionUVs[i + 1] * width;
- this.uvs[i + 1] = this.regionV + height - this.regionUVs[i] * height;
- }
- } else {
- for (var i = 0; i < n; i += 2) {
- this.uvs[i] = this.regionU + this.regionUVs[i] * width;
- this.uvs[i + 1] = this.regionV + this.regionUVs[i + 1] * height;
- }
- }
- },
- computeWorldVertices: function (x, y, slot, worldVertices) {
- var skeletonBones = slot.bone.skeleton.bones;
- var weights = this.weights;
- var bones = this.bones;
-
- var w = 0, v = 0, b = 0, f = 0, n = bones.length, nn;
- var wx, wy, bone, vx, vy, weight;
- if (!slot.attachmentVertices.length) {
- for (; v < n; w += 2) {
- wx = 0;
- wy = 0;
- nn = bones[v++] + v;
- for (; v < nn; v++, b += 3) {
- bone = skeletonBones[bones[v]];
- vx = weights[b];
- vy = weights[b + 1];
- weight = weights[b + 2];
- wx += (vx * bone.m00 + vy * bone.m01 + bone.worldX) * weight;
- wy += (vx * bone.m10 + vy * bone.m11 + bone.worldY) * weight;
- }
- worldVertices[w] = wx + x;
- worldVertices[w + 1] = wy + y;
- }
- } else {
- var ffd = slot.attachmentVertices;
- for (; v < n; w += 2) {
- wx = 0;
- wy = 0;
- nn = bones[v++] + v;
- for (; v < nn; v++, b += 3, f += 2) {
- bone = skeletonBones[bones[v]];
- vx = weights[b] + ffd[f];
- vy = weights[b + 1] + ffd[f + 1];
- weight = weights[b + 2];
- wx += (vx * bone.m00 + vy * bone.m01 + bone.worldX) * weight;
- wy += (vx * bone.m10 + vy * bone.m11 + bone.worldY) * weight;
- }
- worldVertices[w] = wx + x;
- worldVertices[w + 1] = wy + y;
- }
- }
- }
-};
-
-spine.BoundingBoxAttachment = function (name) {
- this.type = spine.AttachmentType.boundingbox;
-
- this.name = name;
- this.vertices = [];
-};
-spine.BoundingBoxAttachment.prototype = {
- computeWorldVertices: function (x, y, bone, worldVertices) {
- x += bone.worldX;
- y += bone.worldY;
- var m00 = bone.m00, m01 = bone.m01, m10 = bone.m10, m11 = bone.m11;
- var vertices = this.vertices;
- for (var i = 0, n = vertices.length; i < n; i += 2) {
- var px = vertices[i];
- var py = vertices[i + 1];
- worldVertices[i] = px * m00 + py * m01 + x;
- worldVertices[i + 1] = px * m10 + py * m11 + y;
- }
- }
-};
-
-spine.AnimationStateData = function (skeletonData) {
- this.skeletonData = skeletonData;
- this.animationToMixTime = {};
-
- this.defaultMix = 0;
-};
-spine.AnimationStateData.prototype = {
- defaultMix: 0,
- setMixByName: function (fromName, toName, duration) {
- var from = this.skeletonData.findAnimation(fromName);
- if (!from) throw new Error("Animation not found: " + fromName);
- var to = this.skeletonData.findAnimation(toName);
- if (!to) throw new Error("Animation not found: " + toName);
- this.setMix(from, to, duration);
- },
- setMix: function (from, to, duration) {
- this.animationToMixTime[from.name + ":" + to.name] = duration;
- },
- getMix: function (from, to) {
- var key = from.name + ":" + to.name;
- return this.animationToMixTime.hasOwnProperty(key) ? this.animationToMixTime[key] : this.defaultMix;
- }
-};
-
-spine.TrackEntry = function () {
- this.delay = this.time = this.endTime = 0;
- this.lastTime = -1;
- this.timeScale = 1;
- this.mixTime = this.mixDuration = 1;
- this.mix = 1;
-};
-spine.TrackEntry.prototype = {
- next: null, previous: null,
- animation: null,
- loop: false,
- delay: 0, time: 0, lastTime: -1, endTime: 0,
- timeScale: 1,
- mixTime: 0, mixDuration: 0, mix: 1,
- onStart: null, onEnd: null, onComplete: null, onEvent: null
-};
-
-spine.AnimationState = function (stateData) {
- this.timeScale = 1;
-
- this.data = stateData;
- this.tracks = [];
- this.events = [];
-};
-spine.AnimationState.prototype = {
- onStart: null,
- onEnd: null,
- onComplete: null,
- onEvent: null,
- timeScale: 1,
- update: function (delta) {
- delta *= this.timeScale;
- for (var i = 0; i < this.tracks.length; i++) {
- var current = this.tracks[i];
- if (!current) continue;
-
- current.time += delta * current.timeScale;
- if (current.previous) {
- var previousDelta = delta * current.previous.timeScale;
- current.previous.time += previousDelta;
- current.mixTime += previousDelta;
- }
-
- var next = current.next;
- if (next) {
- next.time = current.lastTime - next.delay;
- if (next.time >= 0) this.setCurrent(i, next);
- } else {
- // End non-looping animation when it reaches its end time and there is no next entry.
- if (!current.loop && current.lastTime >= current.endTime) this.clearTrack(i);
- }
- }
- },
- apply: function (skeleton) {
- for (var i = 0; i < this.tracks.length; i++) {
- var current = this.tracks[i];
- if (!current) continue;
-
- this.events.length = 0;
-
- var time = current.time;
- var lastTime = current.lastTime;
- var endTime = current.endTime;
- var loop = current.loop;
- if (!loop && time > endTime) time = endTime;
-
- var previous = current.previous;
- if (!previous) {
- if (current.mix == 1)
- current.animation.apply(skeleton, current.lastTime, time, loop, this.events);
- else
- current.animation.mix(skeleton, current.lastTime, time, loop, this.events, current.mix);
- } else {
- var previousTime = previous.time;
- if (!previous.loop && previousTime > previous.endTime) previousTime = previous.endTime;
- previous.animation.apply(skeleton, previousTime, previousTime, previous.loop, null);
-
- var alpha = current.mixTime / current.mixDuration * current.mix;
- if (alpha >= 1) {
- alpha = 1;
- current.previous = null;
- }
- current.animation.mix(skeleton, current.lastTime, time, loop, this.events, alpha);
- }
-
- for (var ii = 0, nn = this.events.length; ii < nn; ii++) {
- var event = this.events[ii];
- if (current.onEvent) current.onEvent(i, event);
- if (this.onEvent) this.onEvent(i, event);
- }
-
- // Check if completed the animation or a loop iteration.
- if (loop ? (lastTime % endTime > time % endTime) : (lastTime < endTime && time >= endTime)) {
- var count = Math.floor(time / endTime);
- if (current.onComplete) current.onComplete(i, count);
- if (this.onComplete) this.onComplete(i, count);
- }
-
- current.lastTime = current.time;
- }
- },
- clearTracks: function () {
- for (var i = 0, n = this.tracks.length; i < n; i++)
- this.clearTrack(i);
- this.tracks.length = 0;
- },
- clearTrack: function (trackIndex) {
- if (trackIndex >= this.tracks.length) return;
- var current = this.tracks[trackIndex];
- if (!current) return;
-
- if (current.onEnd) current.onEnd(trackIndex);
- if (this.onEnd) this.onEnd(trackIndex);
-
- this.tracks[trackIndex] = null;
- },
- _expandToIndex: function (index) {
- if (index < this.tracks.length) return this.tracks[index];
- while (index >= this.tracks.length)
- this.tracks.push(null);
- return null;
- },
- setCurrent: function (index, entry) {
- var current = this._expandToIndex(index);
- if (current) {
- var previous = current.previous;
- current.previous = null;
-
- if (current.onEnd) current.onEnd(index);
- if (this.onEnd) this.onEnd(index);
-
- entry.mixDuration = this.data.getMix(current.animation, entry.animation);
- if (entry.mixDuration > 0) {
- entry.mixTime = 0;
- // If a mix is in progress, mix from the closest animation.
- if (previous && current.mixTime / current.mixDuration < 0.5)
- entry.previous = previous;
- else
- entry.previous = current;
- }
- }
-
- this.tracks[index] = entry;
-
- if (entry.onStart) entry.onStart(index);
- if (this.onStart) this.onStart(index);
- },
- setAnimationByName: function (trackIndex, animationName, loop) {
- var animation = this.data.skeletonData.findAnimation(animationName);
- if (!animation) throw new Error("Animation not found: " + animationName);
- return this.setAnimation(trackIndex, animation, loop);
- },
- /** Set the current animation. Any queued animations are cleared. */
- setAnimation: function (trackIndex, animation, loop) {
- var entry = new spine.TrackEntry();
- entry.animation = animation;
- entry.loop = loop;
- entry.endTime = animation.duration;
- this.setCurrent(trackIndex, entry);
- return entry;
- },
- addAnimationByName: function (trackIndex, animationName, loop, delay) {
- var animation = this.data.skeletonData.findAnimation(animationName);
- if (!animation) throw new Error("Animation not found: " + animationName);
- return this.addAnimation(trackIndex, animation, loop, delay);
- },
- /** Adds an animation to be played delay seconds after the current or last queued animation.
- * @param delay May be <= 0 to use duration of previous animation minus any mix duration plus the negative delay. */
- addAnimation: function (trackIndex, animation, loop, delay) {
- var entry = new spine.TrackEntry();
- entry.animation = animation;
- entry.loop = loop;
- entry.endTime = animation.duration;
-
- var last = this._expandToIndex(trackIndex);
- if (last) {
- while (last.next)
- last = last.next;
- last.next = entry;
- } else
- this.tracks[trackIndex] = entry;
-
- if (delay <= 0) {
- if (last)
- delay += last.endTime - this.data.getMix(last.animation, animation);
- else
- delay = 0;
- }
- entry.delay = delay;
-
- return entry;
- },
- /** May be null. */
- getCurrent: function (trackIndex) {
- if (trackIndex >= this.tracks.length) return null;
- return this.tracks[trackIndex];
- }
-};
-
-spine.SkeletonJson = function (attachmentLoader) {
- this.scale = 1;
-
- this.attachmentLoader = attachmentLoader;
-};
-spine.SkeletonJson.prototype = {
- scale: 1,
- readSkeletonData: function (root, name) {
- var skeletonData = new spine.SkeletonData();
- skeletonData.name = name;
-
- // Skeleton.
- var skeletonMap = root["skeleton"];
- if (skeletonMap) {
- skeletonData.hash = skeletonMap["hash"];
- skeletonData.version = skeletonMap["spine"];
- skeletonData.width = skeletonMap["width"] || 0;
- skeletonData.height = skeletonMap["height"] || 0;
- }
-
- // Bones.
- var bones = root["bones"];
- for (var i = 0, n = bones.length; i < n; i++) {
- var boneMap = bones[i];
- var parent = null;
- if (boneMap["parent"]) {
- parent = skeletonData.findBone(boneMap["parent"]);
- if (!parent) throw new Error("Parent bone not found: " + boneMap["parent"]);
- }
- var boneData = new spine.BoneData(boneMap["name"], parent);
- boneData.length = (boneMap["length"] || 0) * this.scale;
- boneData.x = (boneMap["x"] || 0) * this.scale;
- boneData.y = (boneMap["y"] || 0) * this.scale;
- boneData.rotation = (boneMap["rotation"] || 0);
- boneData.scaleX = boneMap.hasOwnProperty("scaleX") ? boneMap["scaleX"] : 1;
- boneData.scaleY = boneMap.hasOwnProperty("scaleY") ? boneMap["scaleY"] : 1;
- boneData.inheritScale = boneMap.hasOwnProperty("inheritScale") ? boneMap["inheritScale"] : true;
- boneData.inheritRotation = boneMap.hasOwnProperty("inheritRotation") ? boneMap["inheritRotation"] : true;
- skeletonData.bones.push(boneData);
- }
-
- // IK constraints.
- var ik = root["ik"];
- if (ik) {
- for (var i = 0, n = ik.length; i < n; i++) {
- var ikMap = ik[i];
- var ikConstraintData = new spine.IkConstraintData(ikMap["name"]);
-
- var bones = ikMap["bones"];
- for (var ii = 0, nn = bones.length; ii < nn; ii++) {
- var bone = skeletonData.findBone(bones[ii]);
- if (!bone) throw new Error("IK bone not found: " + bones[ii]);
- ikConstraintData.bones.push(bone);
- }
-
- ikConstraintData.target = skeletonData.findBone(ikMap["target"]);
- if (!ikConstraintData.target) throw new Error("Target bone not found: " + ikMap["target"]);
-
- ikConstraintData.bendDirection = (!ikMap.hasOwnProperty("bendPositive") || ikMap["bendPositive"]) ? 1 : -1;
- ikConstraintData.mix = ikMap.hasOwnProperty("mix") ? ikMap["mix"] : 1;
-
- skeletonData.ikConstraints.push(ikConstraintData);
- }
- }
-
- // Slots.
- var slots = root["slots"];
- for (var i = 0, n = slots.length; i < n; i++) {
- var slotMap = slots[i];
- var boneData = skeletonData.findBone(slotMap["bone"]);
- if (!boneData) throw new Error("Slot bone not found: " + slotMap["bone"]);
- var slotData = new spine.SlotData(slotMap["name"], boneData);
-
- var color = slotMap["color"];
- if (color) {
- slotData.r = this.toColor(color, 0);
- slotData.g = this.toColor(color, 1);
- slotData.b = this.toColor(color, 2);
- slotData.a = this.toColor(color, 3);
- }
-
- slotData.attachmentName = slotMap["attachment"];
- slotData.blendMode = spine.BlendMode[slotMap["blend"] || "normal"];
-
- skeletonData.slots.push(slotData);
- }
-
- // Skins.
- var skins = root["skins"];
- for (var skinName in skins) {
- if (!skins.hasOwnProperty(skinName)) continue;
- var skinMap = skins[skinName];
- var skin = new spine.Skin(skinName);
- for (var slotName in skinMap) {
- if (!skinMap.hasOwnProperty(slotName)) continue;
- var slotIndex = skeletonData.findSlotIndex(slotName);
- var slotEntry = skinMap[slotName];
- for (var attachmentName in slotEntry) {
- if (!slotEntry.hasOwnProperty(attachmentName)) continue;
- var attachment = this.readAttachment(skin, attachmentName, slotEntry[attachmentName]);
- if (attachment) skin.addAttachment(slotIndex, attachmentName, attachment);
- }
- }
- skeletonData.skins.push(skin);
- if (skin.name == "default") skeletonData.defaultSkin = skin;
- }
-
- // Events.
- var events = root["events"];
- for (var eventName in events) {
- if (!events.hasOwnProperty(eventName)) continue;
- var eventMap = events[eventName];
- var eventData = new spine.EventData(eventName);
- eventData.intValue = eventMap["int"] || 0;
- eventData.floatValue = eventMap["float"] || 0;
- eventData.stringValue = eventMap["string"] || null;
- skeletonData.events.push(eventData);
- }
-
- // Animations.
- var animations = root["animations"];
- for (var animationName in animations) {
- if (!animations.hasOwnProperty(animationName)) continue;
- this.readAnimation(animationName, animations[animationName], skeletonData);
- }
-
- return skeletonData;
- },
- readAttachment: function (skin, name, map) {
- name = map["name"] || name;
-
- var type = spine.AttachmentType[map["type"] || "region"];
- var path = map["path"] || name;
-
- var scale = this.scale;
- if (type == spine.AttachmentType.region) {
- var region = this.attachmentLoader.newRegionAttachment(skin, name, path);
- if (!region) return null;
- region.path = path;
- region.x = (map["x"] || 0) * scale;
- region.y = (map["y"] || 0) * scale;
- region.scaleX = map.hasOwnProperty("scaleX") ? map["scaleX"] : 1;
- region.scaleY = map.hasOwnProperty("scaleY") ? map["scaleY"] : 1;
- region.rotation = map["rotation"] || 0;
- region.width = (map["width"] || 0) * scale;
- region.height = (map["height"] || 0) * scale;
-
- var color = map["color"];
- if (color) {
- region.r = this.toColor(color, 0);
- region.g = this.toColor(color, 1);
- region.b = this.toColor(color, 2);
- region.a = this.toColor(color, 3);
- }
-
- region.updateOffset();
- return region;
- } else if (type == spine.AttachmentType.mesh) {
- var mesh = this.attachmentLoader.newMeshAttachment(skin, name, path);
- if (!mesh) return null;
- mesh.path = path;
- mesh.vertices = this.getFloatArray(map, "vertices", scale);
- mesh.triangles = this.getIntArray(map, "triangles");
- mesh.regionUVs = this.getFloatArray(map, "uvs", 1);
- mesh.updateUVs();
-
- color = map["color"];
- if (color) {
- mesh.r = this.toColor(color, 0);
- mesh.g = this.toColor(color, 1);
- mesh.b = this.toColor(color, 2);
- mesh.a = this.toColor(color, 3);
- }
-
- mesh.hullLength = (map["hull"] || 0) * 2;
- if (map["edges"]) mesh.edges = this.getIntArray(map, "edges");
- mesh.width = (map["width"] || 0) * scale;
- mesh.height = (map["height"] || 0) * scale;
- return mesh;
- } else if (type == spine.AttachmentType.skinnedmesh) {
- var mesh = this.attachmentLoader.newSkinnedMeshAttachment(skin, name, path);
- if (!mesh) return null;
- mesh.path = path;
-
- var uvs = this.getFloatArray(map, "uvs", 1);
- var vertices = this.getFloatArray(map, "vertices", 1);
- var weights = [];
- var bones = [];
- for (var i = 0, n = vertices.length; i < n; ) {
- var boneCount = vertices[i++] | 0;
- bones[bones.length] = boneCount;
- for (var nn = i + boneCount * 4; i < nn; ) {
- bones[bones.length] = vertices[i];
- weights[weights.length] = vertices[i + 1] * scale;
- weights[weights.length] = vertices[i + 2] * scale;
- weights[weights.length] = vertices[i + 3];
- i += 4;
- }
- }
- mesh.bones = bones;
- mesh.weights = weights;
- mesh.triangles = this.getIntArray(map, "triangles");
- mesh.regionUVs = uvs;
- mesh.updateUVs();
-
- color = map["color"];
- if (color) {
- mesh.r = this.toColor(color, 0);
- mesh.g = this.toColor(color, 1);
- mesh.b = this.toColor(color, 2);
- mesh.a = this.toColor(color, 3);
- }
-
- mesh.hullLength = (map["hull"] || 0) * 2;
- if (map["edges"]) mesh.edges = this.getIntArray(map, "edges");
- mesh.width = (map["width"] || 0) * scale;
- mesh.height = (map["height"] || 0) * scale;
- return mesh;
- } else if (type == spine.AttachmentType.boundingbox) {
- var attachment = this.attachmentLoader.newBoundingBoxAttachment(skin, name);
- var vertices = map["vertices"];
- for (var i = 0, n = vertices.length; i < n; i++)
- attachment.vertices.push(vertices[i] * scale);
- return attachment;
- }
- throw new Error("Unknown attachment type: " + type);
- },
- readAnimation: function (name, map, skeletonData) {
- var timelines = [];
- var duration = 0;
-
- var slots = map["slots"];
- for (var slotName in slots) {
- if (!slots.hasOwnProperty(slotName)) continue;
- var slotMap = slots[slotName];
- var slotIndex = skeletonData.findSlotIndex(slotName);
-
- for (var timelineName in slotMap) {
- if (!slotMap.hasOwnProperty(timelineName)) continue;
- var values = slotMap[timelineName];
- if (timelineName == "color") {
- var timeline = new spine.ColorTimeline(values.length);
- timeline.slotIndex = slotIndex;
-
- var frameIndex = 0;
- for (var i = 0, n = values.length; i < n; i++) {
- var valueMap = values[i];
- var color = valueMap["color"];
- var r = this.toColor(color, 0);
- var g = this.toColor(color, 1);
- var b = this.toColor(color, 2);
- var a = this.toColor(color, 3);
- timeline.setFrame(frameIndex, valueMap["time"], r, g, b, a);
- this.readCurve(timeline, frameIndex, valueMap);
- frameIndex++;
- }
- timelines.push(timeline);
- duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 5 - 5]);
-
- } else if (timelineName == "attachment") {
- var timeline = new spine.AttachmentTimeline(values.length);
- timeline.slotIndex = slotIndex;
-
- var frameIndex = 0;
- for (var i = 0, n = values.length; i < n; i++) {
- var valueMap = values[i];
- timeline.setFrame(frameIndex++, valueMap["time"], valueMap["name"]);
- }
- timelines.push(timeline);
- duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]);
-
- } else
- throw new Error("Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")");
- }
- }
-
- var bones = map["bones"];
- for (var boneName in bones) {
- if (!bones.hasOwnProperty(boneName)) continue;
- var boneIndex = skeletonData.findBoneIndex(boneName);
- if (boneIndex == -1) throw new Error("Bone not found: " + boneName);
- var boneMap = bones[boneName];
-
- for (var timelineName in boneMap) {
- if (!boneMap.hasOwnProperty(timelineName)) continue;
- var values = boneMap[timelineName];
- if (timelineName == "rotate") {
- var timeline = new spine.RotateTimeline(values.length);
- timeline.boneIndex = boneIndex;
-
- var frameIndex = 0;
- for (var i = 0, n = values.length; i < n; i++) {
- var valueMap = values[i];
- timeline.setFrame(frameIndex, valueMap["time"], valueMap["angle"]);
- this.readCurve(timeline, frameIndex, valueMap);
- frameIndex++;
- }
- timelines.push(timeline);
- duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 2 - 2]);
-
- } else if (timelineName == "translate" || timelineName == "scale") {
- var timeline;
- var timelineScale = 1;
- if (timelineName == "scale")
- timeline = new spine.ScaleTimeline(values.length);
- else {
- timeline = new spine.TranslateTimeline(values.length);
- timelineScale = this.scale;
- }
- timeline.boneIndex = boneIndex;
-
- var frameIndex = 0;
- for (var i = 0, n = values.length; i < n; i++) {
- var valueMap = values[i];
- var x = (valueMap["x"] || 0) * timelineScale;
- var y = (valueMap["y"] || 0) * timelineScale;
- timeline.setFrame(frameIndex, valueMap["time"], x, y);
- this.readCurve(timeline, frameIndex, valueMap);
- frameIndex++;
- }
- timelines.push(timeline);
- duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 3 - 3]);
-
- } else if (timelineName == "flipX" || timelineName == "flipY") {
- var x = timelineName == "flipX";
- var timeline = x ? new spine.FlipXTimeline(values.length) : new spine.FlipYTimeline(values.length);
- timeline.boneIndex = boneIndex;
-
- var field = x ? "x" : "y";
- var frameIndex = 0;
- for (var i = 0, n = values.length; i < n; i++) {
- var valueMap = values[i];
- timeline.setFrame(frameIndex, valueMap["time"], valueMap[field] || false);
- frameIndex++;
- }
- timelines.push(timeline);
- duration = Math.max(duration, timeline.frames[timeline.getFrameCount() * 2 - 2]);
- } else
- throw new Error("Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")");
- }
- }
-
- var ikMap = map["ik"];
- for (var ikConstraintName in ikMap) {
- if (!ikMap.hasOwnProperty(ikConstraintName)) continue;
- var ikConstraint = skeletonData.findIkConstraint(ikConstraintName);
- var values = ikMap[ikConstraintName];
- var timeline = new spine.IkConstraintTimeline(values.length);
- timeline.ikConstraintIndex = skeletonData.ikConstraints.indexOf(ikConstraint);
- var frameIndex = 0;
- for (var i = 0, n = values.length; i < n; i++) {
- var valueMap = values[i];
- var mix = valueMap.hasOwnProperty("mix") ? valueMap["mix"] : 1;
- var bendDirection = (!valueMap.hasOwnProperty("bendPositive") || valueMap["bendPositive"]) ? 1 : -1;
- timeline.setFrame(frameIndex, valueMap["time"], mix, bendDirection);
- this.readCurve(timeline, frameIndex, valueMap);
- frameIndex++;
- }
- timelines.push(timeline);
- duration = Math.max(duration, timeline.frames[timeline.frameCount * 3 - 3]);
- }
-
- var ffd = map["ffd"];
- for (var skinName in ffd) {
- var skin = skeletonData.findSkin(skinName);
- var slotMap = ffd[skinName];
- for (slotName in slotMap) {
- var slotIndex = skeletonData.findSlotIndex(slotName);
- var meshMap = slotMap[slotName];
- for (var meshName in meshMap) {
- var values = meshMap[meshName];
- var timeline = new spine.FfdTimeline(values.length);
- var attachment = skin.getAttachment(slotIndex, meshName);
- if (!attachment) throw new Error("FFD attachment not found: " + meshName);
- timeline.slotIndex = slotIndex;
- timeline.attachment = attachment;
-
- var isMesh = attachment.type == spine.AttachmentType.mesh;
- var vertexCount;
- if (isMesh)
- vertexCount = attachment.vertices.length;
- else
- vertexCount = attachment.weights.length / 3 * 2;
-
- var frameIndex = 0;
- for (var i = 0, n = values.length; i < n; i++) {
- var valueMap = values[i];
- var vertices;
- if (!valueMap["vertices"]) {
- if (isMesh)
- vertices = attachment.vertices;
- else {
- vertices = [];
- vertices.length = vertexCount;
- }
- } else {
- var verticesValue = valueMap["vertices"];
- var vertices = [];
- vertices.length = vertexCount;
- var start = valueMap["offset"] || 0;
- var nn = verticesValue.length;
- if (this.scale == 1) {
- for (var ii = 0; ii < nn; ii++)
- vertices[ii + start] = verticesValue[ii];
- } else {
- for (var ii = 0; ii < nn; ii++)
- vertices[ii + start] = verticesValue[ii] * this.scale;
- }
- if (isMesh) {
- var meshVertices = attachment.vertices;
- for (var ii = 0, nn = vertices.length; ii < nn; ii++)
- vertices[ii] += meshVertices[ii];
- }
- }
-
- timeline.setFrame(frameIndex, valueMap["time"], vertices);
- this.readCurve(timeline, frameIndex, valueMap);
- frameIndex++;
- }
- timelines[timelines.length] = timeline;
- duration = Math.max(duration, timeline.frames[timeline.frameCount - 1]);
- }
- }
- }
-
- var drawOrderValues = map["drawOrder"];
- if (!drawOrderValues) drawOrderValues = map["draworder"];
- if (drawOrderValues) {
- var timeline = new spine.DrawOrderTimeline(drawOrderValues.length);
- var slotCount = skeletonData.slots.length;
- var frameIndex = 0;
- for (var i = 0, n = drawOrderValues.length; i < n; i++) {
- var drawOrderMap = drawOrderValues[i];
- var drawOrder = null;
- if (drawOrderMap["offsets"]) {
- drawOrder = [];
- drawOrder.length = slotCount;
- for (var ii = slotCount - 1; ii >= 0; ii--)
- drawOrder[ii] = -1;
- var offsets = drawOrderMap["offsets"];
- var unchanged = [];
- unchanged.length = slotCount - offsets.length;
- var originalIndex = 0, unchangedIndex = 0;
- for (var ii = 0, nn = offsets.length; ii < nn; ii++) {
- var offsetMap = offsets[ii];
- var slotIndex = skeletonData.findSlotIndex(offsetMap["slot"]);
- if (slotIndex == -1) throw new Error("Slot not found: " + offsetMap["slot"]);
- // Collect unchanged items.
- while (originalIndex != slotIndex)
- unchanged[unchangedIndex++] = originalIndex++;
- // Set changed items.
- drawOrder[originalIndex + offsetMap["offset"]] = originalIndex++;
- }
- // Collect remaining unchanged items.
- while (originalIndex < slotCount)
- unchanged[unchangedIndex++] = originalIndex++;
- // Fill in unchanged items.
- for (var ii = slotCount - 1; ii >= 0; ii--)
- if (drawOrder[ii] == -1) drawOrder[ii] = unchanged[--unchangedIndex];
- }
- timeline.setFrame(frameIndex++, drawOrderMap["time"], drawOrder);
- }
- timelines.push(timeline);
- duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]);
- }
-
- var events = map["events"];
- if (events) {
- var timeline = new spine.EventTimeline(events.length);
- var frameIndex = 0;
- for (var i = 0, n = events.length; i < n; i++) {
- var eventMap = events[i];
- var eventData = skeletonData.findEvent(eventMap["name"]);
- if (!eventData) throw new Error("Event not found: " + eventMap["name"]);
- var event = new spine.Event(eventData);
- event.intValue = eventMap.hasOwnProperty("int") ? eventMap["int"] : eventData.intValue;
- event.floatValue = eventMap.hasOwnProperty("float") ? eventMap["float"] : eventData.floatValue;
- event.stringValue = eventMap.hasOwnProperty("string") ? eventMap["string"] : eventData.stringValue;
- timeline.setFrame(frameIndex++, eventMap["time"], event);
- }
- timelines.push(timeline);
- duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]);
- }
-
- skeletonData.animations.push(new spine.Animation(name, timelines, duration));
- },
- readCurve: function (timeline, frameIndex, valueMap) {
- var curve = valueMap["curve"];
- if (!curve)
- timeline.curves.setLinear(frameIndex);
- else if (curve == "stepped")
- timeline.curves.setStepped(frameIndex);
- else if (curve instanceof Array)
- timeline.curves.setCurve(frameIndex, curve[0], curve[1], curve[2], curve[3]);
- },
- toColor: function (hexString, colorIndex) {
- if (hexString.length != 8) throw new Error("Color hexadecimal length must be 8, received: " + hexString);
- return parseInt(hexString.substring(colorIndex * 2, (colorIndex * 2) + 2), 16) / 255;
- },
- getFloatArray: function (map, name, scale) {
- var list = map[name];
- var values = new spine.Float32Array(list.length);
- var i = 0, n = list.length;
- if (scale == 1) {
- for (; i < n; i++)
- values[i] = list[i];
- } else {
- for (; i < n; i++)
- values[i] = list[i] * scale;
- }
- return values;
- },
- getIntArray: function (map, name) {
- var list = map[name];
- var values = new spine.Uint16Array(list.length);
- for (var i = 0, n = list.length; i < n; i++)
- values[i] = list[i] | 0;
- return values;
- }
-};
-
-spine.Atlas = function (atlasText, textureLoader) {
- this.textureLoader = textureLoader;
- this.pages = [];
- this.regions = [];
-
- var reader = new spine.AtlasReader(atlasText);
- var tuple = [];
- tuple.length = 4;
- var page = null;
- while (true) {
- var line = reader.readLine();
- if (line === null) break;
- line = reader.trim(line);
- if (!line.length)
- page = null;
- else if (!page) {
- page = new spine.AtlasPage();
- page.name = line;
-
- if (reader.readTuple(tuple) == 2) { // size is only optional for an atlas packed with an old TexturePacker.
- page.width = parseInt(tuple[0]);
- page.height = parseInt(tuple[1]);
- reader.readTuple(tuple);
- }
- page.format = spine.Atlas.Format[tuple[0]];
-
- reader.readTuple(tuple);
- page.minFilter = spine.Atlas.TextureFilter[tuple[0]];
- page.magFilter = spine.Atlas.TextureFilter[tuple[1]];
-
- var direction = reader.readValue();
- page.uWrap = spine.Atlas.TextureWrap.clampToEdge;
- page.vWrap = spine.Atlas.TextureWrap.clampToEdge;
- if (direction == "x")
- page.uWrap = spine.Atlas.TextureWrap.repeat;
- else if (direction == "y")
- page.vWrap = spine.Atlas.TextureWrap.repeat;
- else if (direction == "xy")
- page.uWrap = page.vWrap = spine.Atlas.TextureWrap.repeat;
-
- textureLoader.load(page, line, this);
-
- this.pages.push(page);
-
- } else {
- var region = new spine.AtlasRegion();
- region.name = line;
- region.page = page;
-
- region.rotate = reader.readValue() == "true";
-
- reader.readTuple(tuple);
- var x = parseInt(tuple[0]);
- var y = parseInt(tuple[1]);
-
- reader.readTuple(tuple);
- var width = parseInt(tuple[0]);
- var height = parseInt(tuple[1]);
-
- region.u = x / page.width;
- region.v = y / page.height;
- if (region.rotate) {
- region.u2 = (x + height) / page.width;
- region.v2 = (y + width) / page.height;
- } else {
- region.u2 = (x + width) / page.width;
- region.v2 = (y + height) / page.height;
- }
- region.x = x;
- region.y = y;
- region.width = Math.abs(width);
- region.height = Math.abs(height);
-
- if (reader.readTuple(tuple) == 4) { // split is optional
- region.splits = [parseInt(tuple[0]), parseInt(tuple[1]), parseInt(tuple[2]), parseInt(tuple[3])];
-
- if (reader.readTuple(tuple) == 4) { // pad is optional, but only present with splits
- region.pads = [parseInt(tuple[0]), parseInt(tuple[1]), parseInt(tuple[2]), parseInt(tuple[3])];
-
- reader.readTuple(tuple);
- }
- }
-
- region.originalWidth = parseInt(tuple[0]);
- region.originalHeight = parseInt(tuple[1]);
-
- reader.readTuple(tuple);
- region.offsetX = parseInt(tuple[0]);
- region.offsetY = parseInt(tuple[1]);
-
- region.index = parseInt(reader.readValue());
-
- this.regions.push(region);
- }
- }
-};
-spine.Atlas.prototype = {
- findRegion: function (name) {
- var regions = this.regions;
- for (var i = 0, n = regions.length; i < n; i++)
- if (regions[i].name == name) return regions[i];
- return null;
- },
- dispose: function () {
- var pages = this.pages;
- for (var i = 0, n = pages.length; i < n; i++)
- this.textureLoader.unload(pages[i].rendererObject);
- },
- updateUVs: function (page) {
- var regions = this.regions;
- for (var i = 0, n = regions.length; i < n; i++) {
- var region = regions[i];
- if (region.page != page) continue;
- region.u = region.x / page.width;
- region.v = region.y / page.height;
- if (region.rotate) {
- region.u2 = (region.x + region.height) / page.width;
- region.v2 = (region.y + region.width) / page.height;
- } else {
- region.u2 = (region.x + region.width) / page.width;
- region.v2 = (region.y + region.height) / page.height;
- }
- }
- }
-};
-
-spine.Atlas.Format = {
- alpha: 0,
- intensity: 1,
- luminanceAlpha: 2,
- rgb565: 3,
- rgba4444: 4,
- rgb888: 5,
- rgba8888: 6
-};
-
-spine.Atlas.TextureFilter = {
- nearest: 0,
- linear: 1,
- mipMap: 2,
- mipMapNearestNearest: 3,
- mipMapLinearNearest: 4,
- mipMapNearestLinear: 5,
- mipMapLinearLinear: 6
-};
-
-spine.Atlas.TextureWrap = {
- mirroredRepeat: 0,
- clampToEdge: 1,
- repeat: 2
-};
-
-spine.AtlasPage = function () {
- this.width = this.height = 0;
-};
-spine.AtlasPage.prototype = {
- name: null,
- format: null,
- minFilter: null,
- magFilter: null,
- uWrap: null,
- vWrap: null,
- rendererObject: null,
- width: 0,
- height: 0
-};
-
-spine.AtlasRegion = function () {
- this.x = this.y = this.width = this.height =
- this.u = this.v = this.u2 = this.v2 =
- this.offsetX = this.offsetY =
- this.originalWidth = this.originalHeight = 0;
- this.index = 0;
-};
-spine.AtlasRegion.prototype = {
- page: null,
- name: null,
- x: 0, y: 0,
- width: 0, height: 0,
- u: 0, v: 0, u2: 0, v2: 0,
- offsetX: 0, offsetY: 0,
- originalWidth: 0, originalHeight: 0,
- index: 0,
- rotate: false,
- splits: null,
- pads: null
-};
-
-spine.AtlasReader = function (text) {
- this.index = 0;
-
- this.lines = text.split(/\r\n|\r|\n/);
-};
-spine.AtlasReader.prototype = {
- index: 0,
- trim: function (value) {
- return value.replace(/^\s+|\s+$/g, "");
- },
- readLine: function () {
- if (this.index >= this.lines.length) return null;
- return this.lines[this.index++];
- },
- readValue: function () {
- var line = this.readLine();
- var colon = line.indexOf(":");
- if (colon == -1) throw new Error("Invalid line: " + line);
- return this.trim(line.substring(colon + 1));
- },
- /** Returns the number of tuple values read (1, 2 or 4). */
- readTuple: function (tuple) {
- var line = this.readLine();
- var colon = line.indexOf(":");
- if (colon == -1) throw new Error("Invalid line: " + line);
- var i = 0, lastMatch = colon + 1;
- for (; i < 3; i++) {
- var comma = line.indexOf(",", lastMatch);
- if (comma == -1) break;
- tuple[i] = this.trim(line.substr(lastMatch, comma - lastMatch));
- lastMatch = comma + 1;
- }
- tuple[i] = this.trim(line.substring(lastMatch));
- return i + 1;
- }
-};
-
-spine.AtlasAttachmentLoader = function (atlas) {
- this.atlas = atlas;
-};
-spine.AtlasAttachmentLoader.prototype = {
- newRegionAttachment: function (skin, name, path) {
- var region = this.atlas.findRegion(path);
- if (!region) throw new Error("Region not found in atlas: " + path + " (region attachment: " + name + ")");
- var attachment = new spine.RegionAttachment(name);
- attachment.rendererObject = region;
- attachment.setUVs(region.u, region.v, region.u2, region.v2, region.rotate);
- attachment.regionOffsetX = region.offsetX;
- attachment.regionOffsetY = region.offsetY;
- attachment.regionWidth = region.width;
- attachment.regionHeight = region.height;
- attachment.regionOriginalWidth = region.originalWidth;
- attachment.regionOriginalHeight = region.originalHeight;
- return attachment;
- },
- newMeshAttachment: function (skin, name, path) {
- var region = this.atlas.findRegion(path);
- if (!region) throw new Error("Region not found in atlas: " + path + " (mesh attachment: " + name + ")");
- var attachment = new spine.MeshAttachment(name);
- attachment.rendererObject = region;
- attachment.regionU = region.u;
- attachment.regionV = region.v;
- attachment.regionU2 = region.u2;
- attachment.regionV2 = region.v2;
- attachment.regionRotate = region.rotate;
- attachment.regionOffsetX = region.offsetX;
- attachment.regionOffsetY = region.offsetY;
- attachment.regionWidth = region.width;
- attachment.regionHeight = region.height;
- attachment.regionOriginalWidth = region.originalWidth;
- attachment.regionOriginalHeight = region.originalHeight;
- return attachment;
- },
- newSkinnedMeshAttachment: function (skin, name, path) {
- var region = this.atlas.findRegion(path);
- if (!region) throw new Error("Region not found in atlas: " + path + " (skinned mesh attachment: " + name + ")");
- var attachment = new spine.SkinnedMeshAttachment(name);
- attachment.rendererObject = region;
- attachment.regionU = region.u;
- attachment.regionV = region.v;
- attachment.regionU2 = region.u2;
- attachment.regionV2 = region.v2;
- attachment.regionRotate = region.rotate;
- attachment.regionOffsetX = region.offsetX;
- attachment.regionOffsetY = region.offsetY;
- attachment.regionWidth = region.width;
- attachment.regionHeight = region.height;
- attachment.regionOriginalWidth = region.originalWidth;
- attachment.regionOriginalHeight = region.originalHeight;
- return attachment;
- },
- newBoundingBoxAttachment: function (skin, name) {
- return new spine.BoundingBoxAttachment(name);
- }
-};
-
-spine.SkeletonBounds = function () {
- this.minX = this.minY = this.maxX = this.maxY = 0;
-
- this.polygonPool = [];
- this.polygons = [];
- this.boundingBoxes = [];
-};
-spine.SkeletonBounds.prototype = {
- minX: 0, minY: 0, maxX: 0, maxY: 0,
- update: function (skeleton, updateAabb) {
- var slots = skeleton.slots;
- var slotCount = slots.length;
- var x = skeleton.x, y = skeleton.y;
- var boundingBoxes = this.boundingBoxes;
- var polygonPool = this.polygonPool;
- var polygons = this.polygons;
-
- boundingBoxes.length = 0;
- for (var i = 0, n = polygons.length; i < n; i++)
- polygonPool.push(polygons[i]);
- polygons.length = 0;
-
- for (var i = 0; i < slotCount; i++) {
- var slot = slots[i];
- var boundingBox = slot.attachment;
- if (boundingBox.type != spine.AttachmentType.boundingbox) continue;
- boundingBoxes.push(boundingBox);
-
- var poolCount = polygonPool.length, polygon;
- if (poolCount > 0) {
- polygon = polygonPool[poolCount - 1];
- polygonPool.splice(poolCount - 1, 1);
- } else
- polygon = [];
- polygons.push(polygon);
-
- polygon.length = boundingBox.vertices.length;
- boundingBox.computeWorldVertices(x, y, slot.bone, polygon);
- }
-
- if (updateAabb) this.aabbCompute();
- },
- aabbCompute: function () {
- var polygons = this.polygons;
- var minX = Number.MAX_VALUE, minY = Number.MAX_VALUE, maxX = Number.MIN_VALUE, maxY = Number.MIN_VALUE;
- for (var i = 0, n = polygons.length; i < n; i++) {
- var vertices = polygons[i];
- for (var ii = 0, nn = vertices.length; ii < nn; ii += 2) {
- var x = vertices[ii];
- var y = vertices[ii + 1];
- minX = Math.min(minX, x);
- minY = Math.min(minY, y);
- maxX = Math.max(maxX, x);
- maxY = Math.max(maxY, y);
- }
- }
- this.minX = minX;
- this.minY = minY;
- this.maxX = maxX;
- this.maxY = maxY;
- },
- /** Returns true if the axis aligned bounding box contains the point. */
- aabbContainsPoint: function (x, y) {
- return x >= this.minX && x <= this.maxX && y >= this.minY && y <= this.maxY;
- },
- /** Returns true if the axis aligned bounding box intersects the line segment. */
- aabbIntersectsSegment: function (x1, y1, x2, y2) {
- var minX = this.minX, minY = this.minY, maxX = this.maxX, maxY = this.maxY;
- if ((x1 <= minX && x2 <= minX) || (y1 <= minY && y2 <= minY) || (x1 >= maxX && x2 >= maxX) || (y1 >= maxY && y2 >= maxY))
- return false;
- var m = (y2 - y1) / (x2 - x1);
- var y = m * (minX - x1) + y1;
- if (y > minY && y < maxY) return true;
- y = m * (maxX - x1) + y1;
- if (y > minY && y < maxY) return true;
- var x = (minY - y1) / m + x1;
- if (x > minX && x < maxX) return true;
- x = (maxY - y1) / m + x1;
- if (x > minX && x < maxX) return true;
- return false;
- },
- /** Returns true if the axis aligned bounding box intersects the axis aligned bounding box of the specified bounds. */
- aabbIntersectsSkeleton: function (bounds) {
- return this.minX < bounds.maxX && this.maxX > bounds.minX && this.minY < bounds.maxY && this.maxY > bounds.minY;
- },
- /** Returns the first bounding box attachment that contains the point, or null. When doing many checks, it is usually more
- * efficient to only call this method if {@link #aabbContainsPoint(float, float)} returns true. */
- containsPoint: function (x, y) {
- var polygons = this.polygons;
- for (var i = 0, n = polygons.length; i < n; i++)
- if (this.polygonContainsPoint(polygons[i], x, y)) return this.boundingBoxes[i];
- return null;
- },
- /** Returns the first bounding box attachment that contains the line segment, or null. When doing many checks, it is usually
- * more efficient to only call this method if {@link #aabbIntersectsSegment(float, float, float, float)} returns true. */
- intersectsSegment: function (x1, y1, x2, y2) {
- var polygons = this.polygons;
- for (var i = 0, n = polygons.length; i < n; i++)
- if (polygons[i].intersectsSegment(x1, y1, x2, y2)) return this.boundingBoxes[i];
- return null;
- },
- /** Returns true if the polygon contains the point. */
- polygonContainsPoint: function (polygon, x, y) {
- var nn = polygon.length;
- var prevIndex = nn - 2;
- var inside = false;
- for (var ii = 0; ii < nn; ii += 2) {
- var vertexY = polygon[ii + 1];
- var prevY = polygon[prevIndex + 1];
- if ((vertexY < y && prevY >= y) || (prevY < y && vertexY >= y)) {
- var vertexX = polygon[ii];
- if (vertexX + (y - vertexY) / (prevY - vertexY) * (polygon[prevIndex] - vertexX) < x) inside = !inside;
- }
- prevIndex = ii;
- }
- return inside;
- },
- /** Returns true if the polygon contains the line segment. */
- polygonIntersectsSegment: function (polygon, x1, y1, x2, y2) {
- var nn = polygon.length;
- var width12 = x1 - x2, height12 = y1 - y2;
- var det1 = x1 * y2 - y1 * x2;
- var x3 = polygon[nn - 2], y3 = polygon[nn - 1];
- for (var ii = 0; ii < nn; ii += 2) {
- var x4 = polygon[ii], y4 = polygon[ii + 1];
- var det2 = x3 * y4 - y3 * x4;
- var width34 = x3 - x4, height34 = y3 - y4;
- var det3 = width12 * height34 - height12 * width34;
- var x = (det1 * width34 - width12 * det2) / det3;
- if (((x >= x3 && x <= x4) || (x >= x4 && x <= x3)) && ((x >= x1 && x <= x2) || (x >= x2 && x <= x1))) {
- var y = (det1 * height34 - height12 * det2) / det3;
- if (((y >= y3 && y <= y4) || (y >= y4 && y <= y3)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1))) return true;
- }
- x3 = x4;
- y3 = y4;
- }
- return false;
- },
- getPolygon: function (attachment) {
- var index = this.boundingBoxes.indexOf(attachment);
- return index == -1 ? null : this.polygons[index];
- },
- getWidth: function () {
- return this.maxX - this.minX;
- },
- getHeight: function () {
- return this.maxY - this.minY;
- }
-};
+// Spine runtime version 3.6.39
+
+var __extends = (this && this.__extends) || (function () {
+ var extendStatics = Object.setPrototypeOf ||
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
+ return function (d, b) {
+ extendStatics(d, b);
+ function __() { this.constructor = d; }
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
+ };
+})();
+var spine;
+(function (spine) {
+ var Animation = (function () {
+ function Animation(name, timelines, duration) {
+ if (name == null)
+ throw new Error("name cannot be null.");
+ if (timelines == null)
+ throw new Error("timelines cannot be null.");
+ this.name = name;
+ this.timelines = timelines;
+ this.duration = duration;
+ }
+ Animation.prototype.apply = function (skeleton, lastTime, time, loop, events, alpha, pose, direction) {
+ if (skeleton == null)
+ throw new Error("skeleton cannot be null.");
+ if (loop && this.duration != 0) {
+ time %= this.duration;
+ if (lastTime > 0)
+ lastTime %= this.duration;
+ }
+ var timelines = this.timelines;
+ for (var i = 0, n = timelines.length; i < n; i++)
+ timelines[i].apply(skeleton, lastTime, time, events, alpha, pose, direction);
+ };
+ Animation.binarySearch = function (values, target, step) {
+ if (step === void 0) { step = 1; }
+ var low = 0;
+ var high = values.length / step - 2;
+ if (high == 0)
+ return step;
+ var current = high >>> 1;
+ while (true) {
+ if (values[(current + 1) * step] <= target)
+ low = current + 1;
+ else
+ high = current;
+ if (low == high)
+ return (low + 1) * step;
+ current = (low + high) >>> 1;
+ }
+ };
+ Animation.linearSearch = function (values, target, step) {
+ for (var i = 0, last = values.length - step; i <= last; i += step)
+ if (values[i] > target)
+ return i;
+ return -1;
+ };
+ return Animation;
+ }());
+ spine.Animation = Animation;
+ var MixPose;
+ (function (MixPose) {
+ MixPose[MixPose["setup"] = 0] = "setup";
+ MixPose[MixPose["current"] = 1] = "current";
+ MixPose[MixPose["currentLayered"] = 2] = "currentLayered";
+ })(MixPose = spine.MixPose || (spine.MixPose = {}));
+ var MixDirection;
+ (function (MixDirection) {
+ MixDirection[MixDirection["in"] = 0] = "in";
+ MixDirection[MixDirection["out"] = 1] = "out";
+ })(MixDirection = spine.MixDirection || (spine.MixDirection = {}));
+ var TimelineType;
+ (function (TimelineType) {
+ TimelineType[TimelineType["rotate"] = 0] = "rotate";
+ TimelineType[TimelineType["translate"] = 1] = "translate";
+ TimelineType[TimelineType["scale"] = 2] = "scale";
+ TimelineType[TimelineType["shear"] = 3] = "shear";
+ TimelineType[TimelineType["attachment"] = 4] = "attachment";
+ TimelineType[TimelineType["color"] = 5] = "color";
+ TimelineType[TimelineType["deform"] = 6] = "deform";
+ TimelineType[TimelineType["event"] = 7] = "event";
+ TimelineType[TimelineType["drawOrder"] = 8] = "drawOrder";
+ TimelineType[TimelineType["ikConstraint"] = 9] = "ikConstraint";
+ TimelineType[TimelineType["transformConstraint"] = 10] = "transformConstraint";
+ TimelineType[TimelineType["pathConstraintPosition"] = 11] = "pathConstraintPosition";
+ TimelineType[TimelineType["pathConstraintSpacing"] = 12] = "pathConstraintSpacing";
+ TimelineType[TimelineType["pathConstraintMix"] = 13] = "pathConstraintMix";
+ TimelineType[TimelineType["twoColor"] = 14] = "twoColor";
+ })(TimelineType = spine.TimelineType || (spine.TimelineType = {}));
+ var CurveTimeline = (function () {
+ function CurveTimeline(frameCount) {
+ if (frameCount <= 0)
+ throw new Error("frameCount must be > 0: " + frameCount);
+ this.curves = spine.Utils.newFloatArray((frameCount - 1) * CurveTimeline.BEZIER_SIZE);
+ }
+ CurveTimeline.prototype.getFrameCount = function () {
+ return this.curves.length / CurveTimeline.BEZIER_SIZE + 1;
+ };
+ CurveTimeline.prototype.setLinear = function (frameIndex) {
+ this.curves[frameIndex * CurveTimeline.BEZIER_SIZE] = CurveTimeline.LINEAR;
+ };
+ CurveTimeline.prototype.setStepped = function (frameIndex) {
+ this.curves[frameIndex * CurveTimeline.BEZIER_SIZE] = CurveTimeline.STEPPED;
+ };
+ CurveTimeline.prototype.getCurveType = function (frameIndex) {
+ var index = frameIndex * CurveTimeline.BEZIER_SIZE;
+ if (index == this.curves.length)
+ return CurveTimeline.LINEAR;
+ var type = this.curves[index];
+ if (type == CurveTimeline.LINEAR)
+ return CurveTimeline.LINEAR;
+ if (type == CurveTimeline.STEPPED)
+ return CurveTimeline.STEPPED;
+ return CurveTimeline.BEZIER;
+ };
+ CurveTimeline.prototype.setCurve = function (frameIndex, cx1, cy1, cx2, cy2) {
+ var tmpx = (-cx1 * 2 + cx2) * 0.03, tmpy = (-cy1 * 2 + cy2) * 0.03;
+ var dddfx = ((cx1 - cx2) * 3 + 1) * 0.006, dddfy = ((cy1 - cy2) * 3 + 1) * 0.006;
+ var ddfx = tmpx * 2 + dddfx, ddfy = tmpy * 2 + dddfy;
+ var dfx = cx1 * 0.3 + tmpx + dddfx * 0.16666667, dfy = cy1 * 0.3 + tmpy + dddfy * 0.16666667;
+ var i = frameIndex * CurveTimeline.BEZIER_SIZE;
+ var curves = this.curves;
+ curves[i++] = CurveTimeline.BEZIER;
+ var x = dfx, y = dfy;
+ for (var n = i + CurveTimeline.BEZIER_SIZE - 1; i < n; i += 2) {
+ curves[i] = x;
+ curves[i + 1] = y;
+ dfx += ddfx;
+ dfy += ddfy;
+ ddfx += dddfx;
+ ddfy += dddfy;
+ x += dfx;
+ y += dfy;
+ }
+ };
+ CurveTimeline.prototype.getCurvePercent = function (frameIndex, percent) {
+ percent = spine.MathUtils.clamp(percent, 0, 1);
+ var curves = this.curves;
+ var i = frameIndex * CurveTimeline.BEZIER_SIZE;
+ var type = curves[i];
+ if (type == CurveTimeline.LINEAR)
+ return percent;
+ if (type == CurveTimeline.STEPPED)
+ return 0;
+ i++;
+ var x = 0;
+ for (var start = i, n = i + CurveTimeline.BEZIER_SIZE - 1; i < n; i += 2) {
+ x = curves[i];
+ if (x >= percent) {
+ var prevX = void 0, prevY = void 0;
+ if (i == start) {
+ prevX = 0;
+ prevY = 0;
+ }
+ else {
+ prevX = curves[i - 2];
+ prevY = curves[i - 1];
+ }
+ return prevY + (curves[i + 1] - prevY) * (percent - prevX) / (x - prevX);
+ }
+ }
+ var y = curves[i - 1];
+ return y + (1 - y) * (percent - x) / (1 - x);
+ };
+ return CurveTimeline;
+ }());
+ CurveTimeline.LINEAR = 0;
+ CurveTimeline.STEPPED = 1;
+ CurveTimeline.BEZIER = 2;
+ CurveTimeline.BEZIER_SIZE = 10 * 2 - 1;
+ spine.CurveTimeline = CurveTimeline;
+ var RotateTimeline = (function (_super) {
+ __extends(RotateTimeline, _super);
+ function RotateTimeline(frameCount) {
+ var _this = _super.call(this, frameCount) || this;
+ _this.frames = spine.Utils.newFloatArray(frameCount << 1);
+ return _this;
+ }
+ RotateTimeline.prototype.getPropertyId = function () {
+ return (TimelineType.rotate << 24) + this.boneIndex;
+ };
+ RotateTimeline.prototype.setFrame = function (frameIndex, time, degrees) {
+ frameIndex <<= 1;
+ this.frames[frameIndex] = time;
+ this.frames[frameIndex + RotateTimeline.ROTATION] = degrees;
+ };
+ RotateTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, pose, direction) {
+ var frames = this.frames;
+ var bone = skeleton.bones[this.boneIndex];
+ if (time < frames[0]) {
+ switch (pose) {
+ case MixPose.setup:
+ bone.rotation = bone.data.rotation;
+ return;
+ case MixPose.current:
+ var r_1 = bone.data.rotation - bone.rotation;
+ r_1 -= (16384 - ((16384.499999999996 - r_1 / 360) | 0)) * 360;
+ bone.rotation += r_1 * alpha;
+ }
+ return;
+ }
+ if (time >= frames[frames.length - RotateTimeline.ENTRIES]) {
+ if (pose == MixPose.setup)
+ bone.rotation = bone.data.rotation + frames[frames.length + RotateTimeline.PREV_ROTATION] * alpha;
+ else {
+ var r_2 = bone.data.rotation + frames[frames.length + RotateTimeline.PREV_ROTATION] - bone.rotation;
+ r_2 -= (16384 - ((16384.499999999996 - r_2 / 360) | 0)) * 360;
+ bone.rotation += r_2 * alpha;
+ }
+ return;
+ }
+ var frame = Animation.binarySearch(frames, time, RotateTimeline.ENTRIES);
+ var prevRotation = frames[frame + RotateTimeline.PREV_ROTATION];
+ var frameTime = frames[frame];
+ var percent = this.getCurvePercent((frame >> 1) - 1, 1 - (time - frameTime) / (frames[frame + RotateTimeline.PREV_TIME] - frameTime));
+ var r = frames[frame + RotateTimeline.ROTATION] - prevRotation;
+ r -= (16384 - ((16384.499999999996 - r / 360) | 0)) * 360;
+ r = prevRotation + r * percent;
+ if (pose == MixPose.setup) {
+ r -= (16384 - ((16384.499999999996 - r / 360) | 0)) * 360;
+ bone.rotation = bone.data.rotation + r * alpha;
+ }
+ else {
+ r = bone.data.rotation + r - bone.rotation;
+ r -= (16384 - ((16384.499999999996 - r / 360) | 0)) * 360;
+ bone.rotation += r * alpha;
+ }
+ };
+ return RotateTimeline;
+ }(CurveTimeline));
+ RotateTimeline.ENTRIES = 2;
+ RotateTimeline.PREV_TIME = -2;
+ RotateTimeline.PREV_ROTATION = -1;
+ RotateTimeline.ROTATION = 1;
+ spine.RotateTimeline = RotateTimeline;
+ var TranslateTimeline = (function (_super) {
+ __extends(TranslateTimeline, _super);
+ function TranslateTimeline(frameCount) {
+ var _this = _super.call(this, frameCount) || this;
+ _this.frames = spine.Utils.newFloatArray(frameCount * TranslateTimeline.ENTRIES);
+ return _this;
+ }
+ TranslateTimeline.prototype.getPropertyId = function () {
+ return (TimelineType.translate << 24) + this.boneIndex;
+ };
+ TranslateTimeline.prototype.setFrame = function (frameIndex, time, x, y) {
+ frameIndex *= TranslateTimeline.ENTRIES;
+ this.frames[frameIndex] = time;
+ this.frames[frameIndex + TranslateTimeline.X] = x;
+ this.frames[frameIndex + TranslateTimeline.Y] = y;
+ };
+ TranslateTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, pose, direction) {
+ var frames = this.frames;
+ var bone = skeleton.bones[this.boneIndex];
+ if (time < frames[0]) {
+ switch (pose) {
+ case MixPose.setup:
+ bone.x = bone.data.x;
+ bone.y = bone.data.y;
+ return;
+ case MixPose.current:
+ bone.x += (bone.data.x - bone.x) * alpha;
+ bone.y += (bone.data.y - bone.y) * alpha;
+ }
+ return;
+ }
+ var x = 0, y = 0;
+ if (time >= frames[frames.length - TranslateTimeline.ENTRIES]) {
+ x = frames[frames.length + TranslateTimeline.PREV_X];
+ y = frames[frames.length + TranslateTimeline.PREV_Y];
+ }
+ else {
+ var frame = Animation.binarySearch(frames, time, TranslateTimeline.ENTRIES);
+ x = frames[frame + TranslateTimeline.PREV_X];
+ y = frames[frame + TranslateTimeline.PREV_Y];
+ var frameTime = frames[frame];
+ var percent = this.getCurvePercent(frame / TranslateTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + TranslateTimeline.PREV_TIME] - frameTime));
+ x += (frames[frame + TranslateTimeline.X] - x) * percent;
+ y += (frames[frame + TranslateTimeline.Y] - y) * percent;
+ }
+ if (pose == MixPose.setup) {
+ bone.x = bone.data.x + x * alpha;
+ bone.y = bone.data.y + y * alpha;
+ }
+ else {
+ bone.x += (bone.data.x + x - bone.x) * alpha;
+ bone.y += (bone.data.y + y - bone.y) * alpha;
+ }
+ };
+ return TranslateTimeline;
+ }(CurveTimeline));
+ TranslateTimeline.ENTRIES = 3;
+ TranslateTimeline.PREV_TIME = -3;
+ TranslateTimeline.PREV_X = -2;
+ TranslateTimeline.PREV_Y = -1;
+ TranslateTimeline.X = 1;
+ TranslateTimeline.Y = 2;
+ spine.TranslateTimeline = TranslateTimeline;
+ var ScaleTimeline = (function (_super) {
+ __extends(ScaleTimeline, _super);
+ function ScaleTimeline(frameCount) {
+ return _super.call(this, frameCount) || this;
+ }
+ ScaleTimeline.prototype.getPropertyId = function () {
+ return (TimelineType.scale << 24) + this.boneIndex;
+ };
+ ScaleTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, pose, direction) {
+ var frames = this.frames;
+ var bone = skeleton.bones[this.boneIndex];
+ if (time < frames[0]) {
+ switch (pose) {
+ case MixPose.setup:
+ bone.scaleX = bone.data.scaleX;
+ bone.scaleY = bone.data.scaleY;
+ return;
+ case MixPose.current:
+ bone.scaleX += (bone.data.scaleX - bone.scaleX) * alpha;
+ bone.scaleY += (bone.data.scaleY - bone.scaleY) * alpha;
+ }
+ return;
+ }
+ var x = 0, y = 0;
+ if (time >= frames[frames.length - ScaleTimeline.ENTRIES]) {
+ x = frames[frames.length + ScaleTimeline.PREV_X] * bone.data.scaleX;
+ y = frames[frames.length + ScaleTimeline.PREV_Y] * bone.data.scaleY;
+ }
+ else {
+ var frame = Animation.binarySearch(frames, time, ScaleTimeline.ENTRIES);
+ x = frames[frame + ScaleTimeline.PREV_X];
+ y = frames[frame + ScaleTimeline.PREV_Y];
+ var frameTime = frames[frame];
+ var percent = this.getCurvePercent(frame / ScaleTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + ScaleTimeline.PREV_TIME] - frameTime));
+ x = (x + (frames[frame + ScaleTimeline.X] - x) * percent) * bone.data.scaleX;
+ y = (y + (frames[frame + ScaleTimeline.Y] - y) * percent) * bone.data.scaleY;
+ }
+ if (alpha == 1) {
+ bone.scaleX = x;
+ bone.scaleY = y;
+ }
+ else {
+ var bx = 0, by = 0;
+ if (pose == MixPose.setup) {
+ bx = bone.data.scaleX;
+ by = bone.data.scaleY;
+ }
+ else {
+ bx = bone.scaleX;
+ by = bone.scaleY;
+ }
+ if (direction == MixDirection.out) {
+ x = Math.abs(x) * spine.MathUtils.signum(bx);
+ y = Math.abs(y) * spine.MathUtils.signum(by);
+ }
+ else {
+ bx = Math.abs(bx) * spine.MathUtils.signum(x);
+ by = Math.abs(by) * spine.MathUtils.signum(y);
+ }
+ bone.scaleX = bx + (x - bx) * alpha;
+ bone.scaleY = by + (y - by) * alpha;
+ }
+ };
+ return ScaleTimeline;
+ }(TranslateTimeline));
+ spine.ScaleTimeline = ScaleTimeline;
+ var ShearTimeline = (function (_super) {
+ __extends(ShearTimeline, _super);
+ function ShearTimeline(frameCount) {
+ return _super.call(this, frameCount) || this;
+ }
+ ShearTimeline.prototype.getPropertyId = function () {
+ return (TimelineType.shear << 24) + this.boneIndex;
+ };
+ ShearTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, pose, direction) {
+ var frames = this.frames;
+ var bone = skeleton.bones[this.boneIndex];
+ if (time < frames[0]) {
+ switch (pose) {
+ case MixPose.setup:
+ bone.shearX = bone.data.shearX;
+ bone.shearY = bone.data.shearY;
+ return;
+ case MixPose.current:
+ bone.shearX += (bone.data.shearX - bone.shearX) * alpha;
+ bone.shearY += (bone.data.shearY - bone.shearY) * alpha;
+ }
+ return;
+ }
+ var x = 0, y = 0;
+ if (time >= frames[frames.length - ShearTimeline.ENTRIES]) {
+ x = frames[frames.length + ShearTimeline.PREV_X];
+ y = frames[frames.length + ShearTimeline.PREV_Y];
+ }
+ else {
+ var frame = Animation.binarySearch(frames, time, ShearTimeline.ENTRIES);
+ x = frames[frame + ShearTimeline.PREV_X];
+ y = frames[frame + ShearTimeline.PREV_Y];
+ var frameTime = frames[frame];
+ var percent = this.getCurvePercent(frame / ShearTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + ShearTimeline.PREV_TIME] - frameTime));
+ x = x + (frames[frame + ShearTimeline.X] - x) * percent;
+ y = y + (frames[frame + ShearTimeline.Y] - y) * percent;
+ }
+ if (pose == MixPose.setup) {
+ bone.shearX = bone.data.shearX + x * alpha;
+ bone.shearY = bone.data.shearY + y * alpha;
+ }
+ else {
+ bone.shearX += (bone.data.shearX + x - bone.shearX) * alpha;
+ bone.shearY += (bone.data.shearY + y - bone.shearY) * alpha;
+ }
+ };
+ return ShearTimeline;
+ }(TranslateTimeline));
+ spine.ShearTimeline = ShearTimeline;
+ var ColorTimeline = (function (_super) {
+ __extends(ColorTimeline, _super);
+ function ColorTimeline(frameCount) {
+ var _this = _super.call(this, frameCount) || this;
+ _this.frames = spine.Utils.newFloatArray(frameCount * ColorTimeline.ENTRIES);
+ return _this;
+ }
+ ColorTimeline.prototype.getPropertyId = function () {
+ return (TimelineType.color << 24) + this.slotIndex;
+ };
+ ColorTimeline.prototype.setFrame = function (frameIndex, time, r, g, b, a) {
+ frameIndex *= ColorTimeline.ENTRIES;
+ this.frames[frameIndex] = time;
+ this.frames[frameIndex + ColorTimeline.R] = r;
+ this.frames[frameIndex + ColorTimeline.G] = g;
+ this.frames[frameIndex + ColorTimeline.B] = b;
+ this.frames[frameIndex + ColorTimeline.A] = a;
+ };
+ ColorTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, pose, direction) {
+ var slot = skeleton.slots[this.slotIndex];
+ var frames = this.frames;
+ if (time < frames[0]) {
+ switch (pose) {
+ case MixPose.setup:
+ slot.color.setFromColor(slot.data.color);
+ return;
+ case MixPose.current:
+ var color = slot.color, setup = slot.data.color;
+ color.add((setup.r - color.r) * alpha, (setup.g - color.g) * alpha, (setup.b - color.b) * alpha, (setup.a - color.a) * alpha);
+ }
+ return;
+ }
+ var r = 0, g = 0, b = 0, a = 0;
+ if (time >= frames[frames.length - ColorTimeline.ENTRIES]) {
+ var i = frames.length;
+ r = frames[i + ColorTimeline.PREV_R];
+ g = frames[i + ColorTimeline.PREV_G];
+ b = frames[i + ColorTimeline.PREV_B];
+ a = frames[i + ColorTimeline.PREV_A];
+ }
+ else {
+ var frame = Animation.binarySearch(frames, time, ColorTimeline.ENTRIES);
+ r = frames[frame + ColorTimeline.PREV_R];
+ g = frames[frame + ColorTimeline.PREV_G];
+ b = frames[frame + ColorTimeline.PREV_B];
+ a = frames[frame + ColorTimeline.PREV_A];
+ var frameTime = frames[frame];
+ var percent = this.getCurvePercent(frame / ColorTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + ColorTimeline.PREV_TIME] - frameTime));
+ r += (frames[frame + ColorTimeline.R] - r) * percent;
+ g += (frames[frame + ColorTimeline.G] - g) * percent;
+ b += (frames[frame + ColorTimeline.B] - b) * percent;
+ a += (frames[frame + ColorTimeline.A] - a) * percent;
+ }
+ if (alpha == 1)
+ slot.color.set(r, g, b, a);
+ else {
+ var color = slot.color;
+ if (pose == MixPose.setup)
+ color.setFromColor(slot.data.color);
+ color.add((r - color.r) * alpha, (g - color.g) * alpha, (b - color.b) * alpha, (a - color.a) * alpha);
+ }
+ };
+ return ColorTimeline;
+ }(CurveTimeline));
+ ColorTimeline.ENTRIES = 5;
+ ColorTimeline.PREV_TIME = -5;
+ ColorTimeline.PREV_R = -4;
+ ColorTimeline.PREV_G = -3;
+ ColorTimeline.PREV_B = -2;
+ ColorTimeline.PREV_A = -1;
+ ColorTimeline.R = 1;
+ ColorTimeline.G = 2;
+ ColorTimeline.B = 3;
+ ColorTimeline.A = 4;
+ spine.ColorTimeline = ColorTimeline;
+ var TwoColorTimeline = (function (_super) {
+ __extends(TwoColorTimeline, _super);
+ function TwoColorTimeline(frameCount) {
+ var _this = _super.call(this, frameCount) || this;
+ _this.frames = spine.Utils.newFloatArray(frameCount * TwoColorTimeline.ENTRIES);
+ return _this;
+ }
+ TwoColorTimeline.prototype.getPropertyId = function () {
+ return (TimelineType.twoColor << 24) + this.slotIndex;
+ };
+ TwoColorTimeline.prototype.setFrame = function (frameIndex, time, r, g, b, a, r2, g2, b2) {
+ frameIndex *= TwoColorTimeline.ENTRIES;
+ this.frames[frameIndex] = time;
+ this.frames[frameIndex + TwoColorTimeline.R] = r;
+ this.frames[frameIndex + TwoColorTimeline.G] = g;
+ this.frames[frameIndex + TwoColorTimeline.B] = b;
+ this.frames[frameIndex + TwoColorTimeline.A] = a;
+ this.frames[frameIndex + TwoColorTimeline.R2] = r2;
+ this.frames[frameIndex + TwoColorTimeline.G2] = g2;
+ this.frames[frameIndex + TwoColorTimeline.B2] = b2;
+ };
+ TwoColorTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, pose, direction) {
+ var slot = skeleton.slots[this.slotIndex];
+ var frames = this.frames;
+ if (time < frames[0]) {
+ switch (pose) {
+ case MixPose.setup:
+ slot.color.setFromColor(slot.data.color);
+ slot.darkColor.setFromColor(slot.data.darkColor);
+ return;
+ case MixPose.current:
+ var light = slot.color, dark = slot.darkColor, setupLight = slot.data.color, setupDark = slot.data.darkColor;
+ light.add((setupLight.r - light.r) * alpha, (setupLight.g - light.g) * alpha, (setupLight.b - light.b) * alpha, (setupLight.a - light.a) * alpha);
+ dark.add((setupDark.r - dark.r) * alpha, (setupDark.g - dark.g) * alpha, (setupDark.b - dark.b) * alpha, 0);
+ }
+ return;
+ }
+ var r = 0, g = 0, b = 0, a = 0, r2 = 0, g2 = 0, b2 = 0;
+ if (time >= frames[frames.length - TwoColorTimeline.ENTRIES]) {
+ var i = frames.length;
+ r = frames[i + TwoColorTimeline.PREV_R];
+ g = frames[i + TwoColorTimeline.PREV_G];
+ b = frames[i + TwoColorTimeline.PREV_B];
+ a = frames[i + TwoColorTimeline.PREV_A];
+ r2 = frames[i + TwoColorTimeline.PREV_R2];
+ g2 = frames[i + TwoColorTimeline.PREV_G2];
+ b2 = frames[i + TwoColorTimeline.PREV_B2];
+ }
+ else {
+ var frame = Animation.binarySearch(frames, time, TwoColorTimeline.ENTRIES);
+ r = frames[frame + TwoColorTimeline.PREV_R];
+ g = frames[frame + TwoColorTimeline.PREV_G];
+ b = frames[frame + TwoColorTimeline.PREV_B];
+ a = frames[frame + TwoColorTimeline.PREV_A];
+ r2 = frames[frame + TwoColorTimeline.PREV_R2];
+ g2 = frames[frame + TwoColorTimeline.PREV_G2];
+ b2 = frames[frame + TwoColorTimeline.PREV_B2];
+ var frameTime = frames[frame];
+ var percent = this.getCurvePercent(frame / TwoColorTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + TwoColorTimeline.PREV_TIME] - frameTime));
+ r += (frames[frame + TwoColorTimeline.R] - r) * percent;
+ g += (frames[frame + TwoColorTimeline.G] - g) * percent;
+ b += (frames[frame + TwoColorTimeline.B] - b) * percent;
+ a += (frames[frame + TwoColorTimeline.A] - a) * percent;
+ r2 += (frames[frame + TwoColorTimeline.R2] - r2) * percent;
+ g2 += (frames[frame + TwoColorTimeline.G2] - g2) * percent;
+ b2 += (frames[frame + TwoColorTimeline.B2] - b2) * percent;
+ }
+ if (alpha == 1) {
+ slot.color.set(r, g, b, a);
+ slot.darkColor.set(r2, g2, b2, 1);
+ }
+ else {
+ var light = slot.color, dark = slot.darkColor;
+ if (pose == MixPose.setup) {
+ light.setFromColor(slot.data.color);
+ dark.setFromColor(slot.data.darkColor);
+ }
+ light.add((r - light.r) * alpha, (g - light.g) * alpha, (b - light.b) * alpha, (a - light.a) * alpha);
+ dark.add((r2 - dark.r) * alpha, (g2 - dark.g) * alpha, (b2 - dark.b) * alpha, 0);
+ }
+ };
+ return TwoColorTimeline;
+ }(CurveTimeline));
+ TwoColorTimeline.ENTRIES = 8;
+ TwoColorTimeline.PREV_TIME = -8;
+ TwoColorTimeline.PREV_R = -7;
+ TwoColorTimeline.PREV_G = -6;
+ TwoColorTimeline.PREV_B = -5;
+ TwoColorTimeline.PREV_A = -4;
+ TwoColorTimeline.PREV_R2 = -3;
+ TwoColorTimeline.PREV_G2 = -2;
+ TwoColorTimeline.PREV_B2 = -1;
+ TwoColorTimeline.R = 1;
+ TwoColorTimeline.G = 2;
+ TwoColorTimeline.B = 3;
+ TwoColorTimeline.A = 4;
+ TwoColorTimeline.R2 = 5;
+ TwoColorTimeline.G2 = 6;
+ TwoColorTimeline.B2 = 7;
+ spine.TwoColorTimeline = TwoColorTimeline;
+ var AttachmentTimeline = (function () {
+ function AttachmentTimeline(frameCount) {
+ this.frames = spine.Utils.newFloatArray(frameCount);
+ this.attachmentNames = new Array(frameCount);
+ }
+ AttachmentTimeline.prototype.getPropertyId = function () {
+ return (TimelineType.attachment << 24) + this.slotIndex;
+ };
+ AttachmentTimeline.prototype.getFrameCount = function () {
+ return this.frames.length;
+ };
+ AttachmentTimeline.prototype.setFrame = function (frameIndex, time, attachmentName) {
+ this.frames[frameIndex] = time;
+ this.attachmentNames[frameIndex] = attachmentName;
+ };
+ AttachmentTimeline.prototype.apply = function (skeleton, lastTime, time, events, alpha, pose, direction) {
+ var slot = skeleton.slots[this.slotIndex];
+ if (direction == MixDirection.out && pose == MixPose.setup) {
+ var attachmentName_1 = slot.data.attachmentName;
+ slot.setAttachment(attachmentName_1 == null ? null : skeleton.getAttachment(this.slotIndex, attachmentName_1));
+ return;
+ }
+ var frames = this.frames;
+ if (time < frames[0]) {
+ if (pose == MixPose.setup) {
+ var attachmentName_2 = slot.data.attachmentName;
+ slot.setAttachment(attachmentName_2 == null ? null : skeleton.getAttachment(this.slotIndex, attachmentName_2));
+ }
+ return;
+ }
+ var frameIndex = 0;
+ if (time >= frames[frames.length - 1])
+ frameIndex = frames.length - 1;
+ else
+ frameIndex = Animation.binarySearch(frames, time, 1) - 1;
+ var attachmentName = this.attachmentNames[frameIndex];
+ skeleton.slots[this.slotIndex]
+ .setAttachment(attachmentName == null ? null : skeleton.getAttachment(this.slotIndex, attachmentName));
+ };
+ return AttachmentTimeline;
+ }());
+ spine.AttachmentTimeline = AttachmentTimeline;
+ var zeros = null;
+ var DeformTimeline = (function (_super) {
+ __extends(DeformTimeline, _super);
+ function DeformTimeline(frameCount) {
+ var _this = _super.call(this, frameCount) || this;
+ _this.frames = spine.Utils.newFloatArray(frameCount);
+ _this.frameVertices = new Array(frameCount);
+ if (zeros == null)
+ zeros = spine.Utils.newFloatArray(64);
+ return _this;
+ }
+ DeformTimeline.prototype.getPropertyId = function () {
+ return (TimelineType.deform << 27) + +this.attachment.id + this.slotIndex;
+ };
+ DeformTimeline.prototype.setFrame = function (frameIndex, time, vertices) {
+ this.frames[frameIndex] = time;
+ this.frameVertices[frameIndex] = vertices;
+ };
+ DeformTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, pose, direction) {
+ var slot = skeleton.slots[this.slotIndex];
+ var slotAttachment = slot.getAttachment();
+ if (!(slotAttachment instanceof spine.VertexAttachment) || !slotAttachment.applyDeform(this.attachment))
+ return;
+ var verticesArray = slot.attachmentVertices;
+ var frameVertices = this.frameVertices;
+ var vertexCount = frameVertices[0].length;
+ var vertices = spine.Utils.setArraySize(verticesArray, vertexCount);
+ var frames = this.frames;
+ if (time < frames[0]) {
+ var vertexAttachment = slotAttachment;
+ switch (pose) {
+ case MixPose.setup:
+ var zeroVertices;
+ if (vertexAttachment.bones == null) {
+ zeroVertices = vertexAttachment.vertices;
+ }
+ else {
+ zeroVertices = zeros;
+ if (zeroVertices.length < vertexCount)
+ zeros = zeroVertices = spine.Utils.newFloatArray(vertexCount);
+ }
+ spine.Utils.arrayCopy(zeroVertices, 0, vertices, 0, vertexCount);
+ return;
+ case MixPose.current:
+ if (alpha == 1)
+ break;
+ if (vertexAttachment.bones == null) {
+ var setupVertices = vertexAttachment.vertices;
+ for (var i = 0; i < vertexCount; i++)
+ vertices[i] += (setupVertices[i] - vertices[i]) * alpha;
+ }
+ else {
+ alpha = 1 - alpha;
+ for (var i = 0; i < vertexCount; i++)
+ vertices[i] *= alpha;
+ }
+ }
+ return;
+ }
+ if (time >= frames[frames.length - 1]) {
+ var lastVertices = frameVertices[frames.length - 1];
+ if (alpha == 1) {
+ spine.Utils.arrayCopy(lastVertices, 0, vertices, 0, vertexCount);
+ }
+ else if (pose == MixPose.setup) {
+ var vertexAttachment = slotAttachment;
+ if (vertexAttachment.bones == null) {
+ var setupVertices_1 = vertexAttachment.vertices;
+ for (var i_1 = 0; i_1 < vertexCount; i_1++) {
+ var setup = setupVertices_1[i_1];
+ vertices[i_1] = setup + (lastVertices[i_1] - setup) * alpha;
+ }
+ }
+ else {
+ for (var i_2 = 0; i_2 < vertexCount; i_2++)
+ vertices[i_2] = lastVertices[i_2] * alpha;
+ }
+ }
+ else {
+ for (var i_3 = 0; i_3 < vertexCount; i_3++)
+ vertices[i_3] += (lastVertices[i_3] - vertices[i_3]) * alpha;
+ }
+ return;
+ }
+ var frame = Animation.binarySearch(frames, time);
+ var prevVertices = frameVertices[frame - 1];
+ var nextVertices = frameVertices[frame];
+ var frameTime = frames[frame];
+ var percent = this.getCurvePercent(frame - 1, 1 - (time - frameTime) / (frames[frame - 1] - frameTime));
+ if (alpha == 1) {
+ for (var i_4 = 0; i_4 < vertexCount; i_4++) {
+ var prev = prevVertices[i_4];
+ vertices[i_4] = prev + (nextVertices[i_4] - prev) * percent;
+ }
+ }
+ else if (pose == MixPose.setup) {
+ var vertexAttachment = slotAttachment;
+ if (vertexAttachment.bones == null) {
+ var setupVertices_2 = vertexAttachment.vertices;
+ for (var i_5 = 0; i_5 < vertexCount; i_5++) {
+ var prev = prevVertices[i_5], setup = setupVertices_2[i_5];
+ vertices[i_5] = setup + (prev + (nextVertices[i_5] - prev) * percent - setup) * alpha;
+ }
+ }
+ else {
+ for (var i_6 = 0; i_6 < vertexCount; i_6++) {
+ var prev = prevVertices[i_6];
+ vertices[i_6] = (prev + (nextVertices[i_6] - prev) * percent) * alpha;
+ }
+ }
+ }
+ else {
+ for (var i_7 = 0; i_7 < vertexCount; i_7++) {
+ var prev = prevVertices[i_7];
+ vertices[i_7] += (prev + (nextVertices[i_7] - prev) * percent - vertices[i_7]) * alpha;
+ }
+ }
+ };
+ return DeformTimeline;
+ }(CurveTimeline));
+ spine.DeformTimeline = DeformTimeline;
+ var EventTimeline = (function () {
+ function EventTimeline(frameCount) {
+ this.frames = spine.Utils.newFloatArray(frameCount);
+ this.events = new Array(frameCount);
+ }
+ EventTimeline.prototype.getPropertyId = function () {
+ return TimelineType.event << 24;
+ };
+ EventTimeline.prototype.getFrameCount = function () {
+ return this.frames.length;
+ };
+ EventTimeline.prototype.setFrame = function (frameIndex, event) {
+ this.frames[frameIndex] = event.time;
+ this.events[frameIndex] = event;
+ };
+ EventTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, pose, direction) {
+ if (firedEvents == null)
+ return;
+ var frames = this.frames;
+ var frameCount = this.frames.length;
+ if (lastTime > time) {
+ this.apply(skeleton, lastTime, Number.MAX_VALUE, firedEvents, alpha, pose, direction);
+ lastTime = -1;
+ }
+ else if (lastTime >= frames[frameCount - 1])
+ return;
+ if (time < frames[0])
+ return;
+ var frame = 0;
+ if (lastTime < frames[0])
+ frame = 0;
+ else {
+ frame = Animation.binarySearch(frames, lastTime);
+ var frameTime = frames[frame];
+ while (frame > 0) {
+ if (frames[frame - 1] != frameTime)
+ break;
+ frame--;
+ }
+ }
+ for (; frame < frameCount && time >= frames[frame]; frame++)
+ firedEvents.push(this.events[frame]);
+ };
+ return EventTimeline;
+ }());
+ spine.EventTimeline = EventTimeline;
+ var DrawOrderTimeline = (function () {
+ function DrawOrderTimeline(frameCount) {
+ this.frames = spine.Utils.newFloatArray(frameCount);
+ this.drawOrders = new Array(frameCount);
+ }
+ DrawOrderTimeline.prototype.getPropertyId = function () {
+ return TimelineType.drawOrder << 24;
+ };
+ DrawOrderTimeline.prototype.getFrameCount = function () {
+ return this.frames.length;
+ };
+ DrawOrderTimeline.prototype.setFrame = function (frameIndex, time, drawOrder) {
+ this.frames[frameIndex] = time;
+ this.drawOrders[frameIndex] = drawOrder;
+ };
+ DrawOrderTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, pose, direction) {
+ var drawOrder = skeleton.drawOrder;
+ var slots = skeleton.slots;
+ if (direction == MixDirection.out && pose == MixPose.setup) {
+ spine.Utils.arrayCopy(skeleton.slots, 0, skeleton.drawOrder, 0, skeleton.slots.length);
+ return;
+ }
+ var frames = this.frames;
+ if (time < frames[0]) {
+ if (pose == MixPose.setup)
+ spine.Utils.arrayCopy(skeleton.slots, 0, skeleton.drawOrder, 0, skeleton.slots.length);
+ return;
+ }
+ var frame = 0;
+ if (time >= frames[frames.length - 1])
+ frame = frames.length - 1;
+ else
+ frame = Animation.binarySearch(frames, time) - 1;
+ var drawOrderToSetupIndex = this.drawOrders[frame];
+ if (drawOrderToSetupIndex == null)
+ spine.Utils.arrayCopy(slots, 0, drawOrder, 0, slots.length);
+ else {
+ for (var i = 0, n = drawOrderToSetupIndex.length; i < n; i++)
+ drawOrder[i] = slots[drawOrderToSetupIndex[i]];
+ }
+ };
+ return DrawOrderTimeline;
+ }());
+ spine.DrawOrderTimeline = DrawOrderTimeline;
+ var IkConstraintTimeline = (function (_super) {
+ __extends(IkConstraintTimeline, _super);
+ function IkConstraintTimeline(frameCount) {
+ var _this = _super.call(this, frameCount) || this;
+ _this.frames = spine.Utils.newFloatArray(frameCount * IkConstraintTimeline.ENTRIES);
+ return _this;
+ }
+ IkConstraintTimeline.prototype.getPropertyId = function () {
+ return (TimelineType.ikConstraint << 24) + this.ikConstraintIndex;
+ };
+ IkConstraintTimeline.prototype.setFrame = function (frameIndex, time, mix, bendDirection) {
+ frameIndex *= IkConstraintTimeline.ENTRIES;
+ this.frames[frameIndex] = time;
+ this.frames[frameIndex + IkConstraintTimeline.MIX] = mix;
+ this.frames[frameIndex + IkConstraintTimeline.BEND_DIRECTION] = bendDirection;
+ };
+ IkConstraintTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, pose, direction) {
+ var frames = this.frames;
+ var constraint = skeleton.ikConstraints[this.ikConstraintIndex];
+ if (time < frames[0]) {
+ switch (pose) {
+ case MixPose.setup:
+ constraint.mix = constraint.data.mix;
+ constraint.bendDirection = constraint.data.bendDirection;
+ return;
+ case MixPose.current:
+ constraint.mix += (constraint.data.mix - constraint.mix) * alpha;
+ constraint.bendDirection = constraint.data.bendDirection;
+ }
+ return;
+ }
+ if (time >= frames[frames.length - IkConstraintTimeline.ENTRIES]) {
+ if (pose == MixPose.setup) {
+ constraint.mix = constraint.data.mix + (frames[frames.length + IkConstraintTimeline.PREV_MIX] - constraint.data.mix) * alpha;
+ constraint.bendDirection = direction == MixDirection.out ? constraint.data.bendDirection
+ : frames[frames.length + IkConstraintTimeline.PREV_BEND_DIRECTION];
+ }
+ else {
+ constraint.mix += (frames[frames.length + IkConstraintTimeline.PREV_MIX] - constraint.mix) * alpha;
+ if (direction == MixDirection["in"])
+ constraint.bendDirection = frames[frames.length + IkConstraintTimeline.PREV_BEND_DIRECTION];
+ }
+ return;
+ }
+ var frame = Animation.binarySearch(frames, time, IkConstraintTimeline.ENTRIES);
+ var mix = frames[frame + IkConstraintTimeline.PREV_MIX];
+ var frameTime = frames[frame];
+ var percent = this.getCurvePercent(frame / IkConstraintTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + IkConstraintTimeline.PREV_TIME] - frameTime));
+ if (pose == MixPose.setup) {
+ constraint.mix = constraint.data.mix + (mix + (frames[frame + IkConstraintTimeline.MIX] - mix) * percent - constraint.data.mix) * alpha;
+ constraint.bendDirection = direction == MixDirection.out ? constraint.data.bendDirection : frames[frame + IkConstraintTimeline.PREV_BEND_DIRECTION];
+ }
+ else {
+ constraint.mix += (mix + (frames[frame + IkConstraintTimeline.MIX] - mix) * percent - constraint.mix) * alpha;
+ if (direction == MixDirection["in"])
+ constraint.bendDirection = frames[frame + IkConstraintTimeline.PREV_BEND_DIRECTION];
+ }
+ };
+ return IkConstraintTimeline;
+ }(CurveTimeline));
+ IkConstraintTimeline.ENTRIES = 3;
+ IkConstraintTimeline.PREV_TIME = -3;
+ IkConstraintTimeline.PREV_MIX = -2;
+ IkConstraintTimeline.PREV_BEND_DIRECTION = -1;
+ IkConstraintTimeline.MIX = 1;
+ IkConstraintTimeline.BEND_DIRECTION = 2;
+ spine.IkConstraintTimeline = IkConstraintTimeline;
+ var TransformConstraintTimeline = (function (_super) {
+ __extends(TransformConstraintTimeline, _super);
+ function TransformConstraintTimeline(frameCount) {
+ var _this = _super.call(this, frameCount) || this;
+ _this.frames = spine.Utils.newFloatArray(frameCount * TransformConstraintTimeline.ENTRIES);
+ return _this;
+ }
+ TransformConstraintTimeline.prototype.getPropertyId = function () {
+ return (TimelineType.transformConstraint << 24) + this.transformConstraintIndex;
+ };
+ TransformConstraintTimeline.prototype.setFrame = function (frameIndex, time, rotateMix, translateMix, scaleMix, shearMix) {
+ frameIndex *= TransformConstraintTimeline.ENTRIES;
+ this.frames[frameIndex] = time;
+ this.frames[frameIndex + TransformConstraintTimeline.ROTATE] = rotateMix;
+ this.frames[frameIndex + TransformConstraintTimeline.TRANSLATE] = translateMix;
+ this.frames[frameIndex + TransformConstraintTimeline.SCALE] = scaleMix;
+ this.frames[frameIndex + TransformConstraintTimeline.SHEAR] = shearMix;
+ };
+ TransformConstraintTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, pose, direction) {
+ var frames = this.frames;
+ var constraint = skeleton.transformConstraints[this.transformConstraintIndex];
+ if (time < frames[0]) {
+ var data = constraint.data;
+ switch (pose) {
+ case MixPose.setup:
+ constraint.rotateMix = data.rotateMix;
+ constraint.translateMix = data.translateMix;
+ constraint.scaleMix = data.scaleMix;
+ constraint.shearMix = data.shearMix;
+ return;
+ case MixPose.current:
+ constraint.rotateMix += (data.rotateMix - constraint.rotateMix) * alpha;
+ constraint.translateMix += (data.translateMix - constraint.translateMix) * alpha;
+ constraint.scaleMix += (data.scaleMix - constraint.scaleMix) * alpha;
+ constraint.shearMix += (data.shearMix - constraint.shearMix) * alpha;
+ }
+ return;
+ }
+ var rotate = 0, translate = 0, scale = 0, shear = 0;
+ if (time >= frames[frames.length - TransformConstraintTimeline.ENTRIES]) {
+ var i = frames.length;
+ rotate = frames[i + TransformConstraintTimeline.PREV_ROTATE];
+ translate = frames[i + TransformConstraintTimeline.PREV_TRANSLATE];
+ scale = frames[i + TransformConstraintTimeline.PREV_SCALE];
+ shear = frames[i + TransformConstraintTimeline.PREV_SHEAR];
+ }
+ else {
+ var frame = Animation.binarySearch(frames, time, TransformConstraintTimeline.ENTRIES);
+ rotate = frames[frame + TransformConstraintTimeline.PREV_ROTATE];
+ translate = frames[frame + TransformConstraintTimeline.PREV_TRANSLATE];
+ scale = frames[frame + TransformConstraintTimeline.PREV_SCALE];
+ shear = frames[frame + TransformConstraintTimeline.PREV_SHEAR];
+ var frameTime = frames[frame];
+ var percent = this.getCurvePercent(frame / TransformConstraintTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + TransformConstraintTimeline.PREV_TIME] - frameTime));
+ rotate += (frames[frame + TransformConstraintTimeline.ROTATE] - rotate) * percent;
+ translate += (frames[frame + TransformConstraintTimeline.TRANSLATE] - translate) * percent;
+ scale += (frames[frame + TransformConstraintTimeline.SCALE] - scale) * percent;
+ shear += (frames[frame + TransformConstraintTimeline.SHEAR] - shear) * percent;
+ }
+ if (pose == MixPose.setup) {
+ var data = constraint.data;
+ constraint.rotateMix = data.rotateMix + (rotate - data.rotateMix) * alpha;
+ constraint.translateMix = data.translateMix + (translate - data.translateMix) * alpha;
+ constraint.scaleMix = data.scaleMix + (scale - data.scaleMix) * alpha;
+ constraint.shearMix = data.shearMix + (shear - data.shearMix) * alpha;
+ }
+ else {
+ constraint.rotateMix += (rotate - constraint.rotateMix) * alpha;
+ constraint.translateMix += (translate - constraint.translateMix) * alpha;
+ constraint.scaleMix += (scale - constraint.scaleMix) * alpha;
+ constraint.shearMix += (shear - constraint.shearMix) * alpha;
+ }
+ };
+ return TransformConstraintTimeline;
+ }(CurveTimeline));
+ TransformConstraintTimeline.ENTRIES = 5;
+ TransformConstraintTimeline.PREV_TIME = -5;
+ TransformConstraintTimeline.PREV_ROTATE = -4;
+ TransformConstraintTimeline.PREV_TRANSLATE = -3;
+ TransformConstraintTimeline.PREV_SCALE = -2;
+ TransformConstraintTimeline.PREV_SHEAR = -1;
+ TransformConstraintTimeline.ROTATE = 1;
+ TransformConstraintTimeline.TRANSLATE = 2;
+ TransformConstraintTimeline.SCALE = 3;
+ TransformConstraintTimeline.SHEAR = 4;
+ spine.TransformConstraintTimeline = TransformConstraintTimeline;
+ var PathConstraintPositionTimeline = (function (_super) {
+ __extends(PathConstraintPositionTimeline, _super);
+ function PathConstraintPositionTimeline(frameCount) {
+ var _this = _super.call(this, frameCount) || this;
+ _this.frames = spine.Utils.newFloatArray(frameCount * PathConstraintPositionTimeline.ENTRIES);
+ return _this;
+ }
+ PathConstraintPositionTimeline.prototype.getPropertyId = function () {
+ return (TimelineType.pathConstraintPosition << 24) + this.pathConstraintIndex;
+ };
+ PathConstraintPositionTimeline.prototype.setFrame = function (frameIndex, time, value) {
+ frameIndex *= PathConstraintPositionTimeline.ENTRIES;
+ this.frames[frameIndex] = time;
+ this.frames[frameIndex + PathConstraintPositionTimeline.VALUE] = value;
+ };
+ PathConstraintPositionTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, pose, direction) {
+ var frames = this.frames;
+ var constraint = skeleton.pathConstraints[this.pathConstraintIndex];
+ if (time < frames[0]) {
+ switch (pose) {
+ case MixPose.setup:
+ constraint.position = constraint.data.position;
+ return;
+ case MixPose.current:
+ constraint.position += (constraint.data.position - constraint.position) * alpha;
+ }
+ return;
+ }
+ var position = 0;
+ if (time >= frames[frames.length - PathConstraintPositionTimeline.ENTRIES])
+ position = frames[frames.length + PathConstraintPositionTimeline.PREV_VALUE];
+ else {
+ var frame = Animation.binarySearch(frames, time, PathConstraintPositionTimeline.ENTRIES);
+ position = frames[frame + PathConstraintPositionTimeline.PREV_VALUE];
+ var frameTime = frames[frame];
+ var percent = this.getCurvePercent(frame / PathConstraintPositionTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PathConstraintPositionTimeline.PREV_TIME] - frameTime));
+ position += (frames[frame + PathConstraintPositionTimeline.VALUE] - position) * percent;
+ }
+ if (pose == MixPose.setup)
+ constraint.position = constraint.data.position + (position - constraint.data.position) * alpha;
+ else
+ constraint.position += (position - constraint.position) * alpha;
+ };
+ return PathConstraintPositionTimeline;
+ }(CurveTimeline));
+ PathConstraintPositionTimeline.ENTRIES = 2;
+ PathConstraintPositionTimeline.PREV_TIME = -2;
+ PathConstraintPositionTimeline.PREV_VALUE = -1;
+ PathConstraintPositionTimeline.VALUE = 1;
+ spine.PathConstraintPositionTimeline = PathConstraintPositionTimeline;
+ var PathConstraintSpacingTimeline = (function (_super) {
+ __extends(PathConstraintSpacingTimeline, _super);
+ function PathConstraintSpacingTimeline(frameCount) {
+ return _super.call(this, frameCount) || this;
+ }
+ PathConstraintSpacingTimeline.prototype.getPropertyId = function () {
+ return (TimelineType.pathConstraintSpacing << 24) + this.pathConstraintIndex;
+ };
+ PathConstraintSpacingTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, pose, direction) {
+ var frames = this.frames;
+ var constraint = skeleton.pathConstraints[this.pathConstraintIndex];
+ if (time < frames[0]) {
+ switch (pose) {
+ case MixPose.setup:
+ constraint.spacing = constraint.data.spacing;
+ return;
+ case MixPose.current:
+ constraint.spacing += (constraint.data.spacing - constraint.spacing) * alpha;
+ }
+ return;
+ }
+ var spacing = 0;
+ if (time >= frames[frames.length - PathConstraintSpacingTimeline.ENTRIES])
+ spacing = frames[frames.length + PathConstraintSpacingTimeline.PREV_VALUE];
+ else {
+ var frame = Animation.binarySearch(frames, time, PathConstraintSpacingTimeline.ENTRIES);
+ spacing = frames[frame + PathConstraintSpacingTimeline.PREV_VALUE];
+ var frameTime = frames[frame];
+ var percent = this.getCurvePercent(frame / PathConstraintSpacingTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PathConstraintSpacingTimeline.PREV_TIME] - frameTime));
+ spacing += (frames[frame + PathConstraintSpacingTimeline.VALUE] - spacing) * percent;
+ }
+ if (pose == MixPose.setup)
+ constraint.spacing = constraint.data.spacing + (spacing - constraint.data.spacing) * alpha;
+ else
+ constraint.spacing += (spacing - constraint.spacing) * alpha;
+ };
+ return PathConstraintSpacingTimeline;
+ }(PathConstraintPositionTimeline));
+ spine.PathConstraintSpacingTimeline = PathConstraintSpacingTimeline;
+ var PathConstraintMixTimeline = (function (_super) {
+ __extends(PathConstraintMixTimeline, _super);
+ function PathConstraintMixTimeline(frameCount) {
+ var _this = _super.call(this, frameCount) || this;
+ _this.frames = spine.Utils.newFloatArray(frameCount * PathConstraintMixTimeline.ENTRIES);
+ return _this;
+ }
+ PathConstraintMixTimeline.prototype.getPropertyId = function () {
+ return (TimelineType.pathConstraintMix << 24) + this.pathConstraintIndex;
+ };
+ PathConstraintMixTimeline.prototype.setFrame = function (frameIndex, time, rotateMix, translateMix) {
+ frameIndex *= PathConstraintMixTimeline.ENTRIES;
+ this.frames[frameIndex] = time;
+ this.frames[frameIndex + PathConstraintMixTimeline.ROTATE] = rotateMix;
+ this.frames[frameIndex + PathConstraintMixTimeline.TRANSLATE] = translateMix;
+ };
+ PathConstraintMixTimeline.prototype.apply = function (skeleton, lastTime, time, firedEvents, alpha, pose, direction) {
+ var frames = this.frames;
+ var constraint = skeleton.pathConstraints[this.pathConstraintIndex];
+ if (time < frames[0]) {
+ switch (pose) {
+ case MixPose.setup:
+ constraint.rotateMix = constraint.data.rotateMix;
+ constraint.translateMix = constraint.data.translateMix;
+ return;
+ case MixPose.current:
+ constraint.rotateMix += (constraint.data.rotateMix - constraint.rotateMix) * alpha;
+ constraint.translateMix += (constraint.data.translateMix - constraint.translateMix) * alpha;
+ }
+ return;
+ }
+ var rotate = 0, translate = 0;
+ if (time >= frames[frames.length - PathConstraintMixTimeline.ENTRIES]) {
+ rotate = frames[frames.length + PathConstraintMixTimeline.PREV_ROTATE];
+ translate = frames[frames.length + PathConstraintMixTimeline.PREV_TRANSLATE];
+ }
+ else {
+ var frame = Animation.binarySearch(frames, time, PathConstraintMixTimeline.ENTRIES);
+ rotate = frames[frame + PathConstraintMixTimeline.PREV_ROTATE];
+ translate = frames[frame + PathConstraintMixTimeline.PREV_TRANSLATE];
+ var frameTime = frames[frame];
+ var percent = this.getCurvePercent(frame / PathConstraintMixTimeline.ENTRIES - 1, 1 - (time - frameTime) / (frames[frame + PathConstraintMixTimeline.PREV_TIME] - frameTime));
+ rotate += (frames[frame + PathConstraintMixTimeline.ROTATE] - rotate) * percent;
+ translate += (frames[frame + PathConstraintMixTimeline.TRANSLATE] - translate) * percent;
+ }
+ if (pose == MixPose.setup) {
+ constraint.rotateMix = constraint.data.rotateMix + (rotate - constraint.data.rotateMix) * alpha;
+ constraint.translateMix = constraint.data.translateMix + (translate - constraint.data.translateMix) * alpha;
+ }
+ else {
+ constraint.rotateMix += (rotate - constraint.rotateMix) * alpha;
+ constraint.translateMix += (translate - constraint.translateMix) * alpha;
+ }
+ };
+ return PathConstraintMixTimeline;
+ }(CurveTimeline));
+ PathConstraintMixTimeline.ENTRIES = 3;
+ PathConstraintMixTimeline.PREV_TIME = -3;
+ PathConstraintMixTimeline.PREV_ROTATE = -2;
+ PathConstraintMixTimeline.PREV_TRANSLATE = -1;
+ PathConstraintMixTimeline.ROTATE = 1;
+ PathConstraintMixTimeline.TRANSLATE = 2;
+ spine.PathConstraintMixTimeline = PathConstraintMixTimeline;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var AnimationState = (function () {
+ function AnimationState(data) {
+ this.tracks = new Array();
+ this.events = new Array();
+ this.listeners = new Array();
+ this.queue = new EventQueue(this);
+ this.propertyIDs = new spine.IntSet();
+ this.mixingTo = new Array();
+ this.animationsChanged = false;
+ this.timeScale = 1;
+ this.trackEntryPool = new spine.Pool(function () { return new TrackEntry(); });
+ this.data = data;
+ }
+ AnimationState.prototype.update = function (delta) {
+ delta *= this.timeScale;
+ var tracks = this.tracks;
+ for (var i = 0, n = tracks.length; i < n; i++) {
+ var current = tracks[i];
+ if (current == null)
+ continue;
+ current.animationLast = current.nextAnimationLast;
+ current.trackLast = current.nextTrackLast;
+ var currentDelta = delta * current.timeScale;
+ if (current.delay > 0) {
+ current.delay -= currentDelta;
+ if (current.delay > 0)
+ continue;
+ currentDelta = -current.delay;
+ current.delay = 0;
+ }
+ var next = current.next;
+ if (next != null) {
+ var nextTime = current.trackLast - next.delay;
+ if (nextTime >= 0) {
+ next.delay = 0;
+ next.trackTime = nextTime + delta * next.timeScale;
+ current.trackTime += currentDelta;
+ this.setCurrent(i, next, true);
+ while (next.mixingFrom != null) {
+ next.mixTime += currentDelta;
+ next = next.mixingFrom;
+ }
+ continue;
+ }
+ }
+ else if (current.trackLast >= current.trackEnd && current.mixingFrom == null) {
+ tracks[i] = null;
+ this.queue.end(current);
+ this.disposeNext(current);
+ continue;
+ }
+ if (current.mixingFrom != null && this.updateMixingFrom(current, delta)) {
+ var from = current.mixingFrom;
+ current.mixingFrom = null;
+ while (from != null) {
+ this.queue.end(from);
+ from = from.mixingFrom;
+ }
+ }
+ current.trackTime += currentDelta;
+ }
+ this.queue.drain();
+ };
+ AnimationState.prototype.updateMixingFrom = function (to, delta) {
+ var from = to.mixingFrom;
+ if (from == null)
+ return true;
+ var finished = this.updateMixingFrom(from, delta);
+ if (to.mixTime > 0 && (to.mixTime >= to.mixDuration || to.timeScale == 0)) {
+ if (from.totalAlpha == 0 || to.mixDuration == 0) {
+ to.mixingFrom = from.mixingFrom;
+ to.interruptAlpha = from.interruptAlpha;
+ this.queue.end(from);
+ }
+ return finished;
+ }
+ from.animationLast = from.nextAnimationLast;
+ from.trackLast = from.nextTrackLast;
+ from.trackTime += delta * from.timeScale;
+ to.mixTime += delta * to.timeScale;
+ return false;
+ };
+ AnimationState.prototype.apply = function (skeleton) {
+ if (skeleton == null)
+ throw new Error("skeleton cannot be null.");
+ if (this.animationsChanged)
+ this._animationsChanged();
+ var events = this.events;
+ var tracks = this.tracks;
+ var applied = false;
+ for (var i = 0, n = tracks.length; i < n; i++) {
+ var current = tracks[i];
+ if (current == null || current.delay > 0)
+ continue;
+ applied = true;
+ var currentPose = i == 0 ? spine.MixPose.current : spine.MixPose.currentLayered;
+ var mix = current.alpha;
+ if (current.mixingFrom != null)
+ mix *= this.applyMixingFrom(current, skeleton, currentPose);
+ else if (current.trackTime >= current.trackEnd && current.next == null)
+ mix = 0;
+ var animationLast = current.animationLast, animationTime = current.getAnimationTime();
+ var timelineCount = current.animation.timelines.length;
+ var timelines = current.animation.timelines;
+ if (mix == 1) {
+ for (var ii = 0; ii < timelineCount; ii++)
+ timelines[ii].apply(skeleton, animationLast, animationTime, events, 1, spine.MixPose.setup, spine.MixDirection["in"]);
+ }
+ else {
+ var timelineData = current.timelineData;
+ var firstFrame = current.timelinesRotation.length == 0;
+ if (firstFrame)
+ spine.Utils.setArraySize(current.timelinesRotation, timelineCount << 1, null);
+ var timelinesRotation = current.timelinesRotation;
+ for (var ii = 0; ii < timelineCount; ii++) {
+ var timeline = timelines[ii];
+ var pose = timelineData[ii] >= AnimationState.FIRST ? spine.MixPose.setup : currentPose;
+ if (timeline instanceof spine.RotateTimeline) {
+ this.applyRotateTimeline(timeline, skeleton, animationTime, mix, pose, timelinesRotation, ii << 1, firstFrame);
+ }
+ else
+ timeline.apply(skeleton, animationLast, animationTime, events, mix, pose, spine.MixDirection["in"]);
+ }
+ }
+ this.queueEvents(current, animationTime);
+ events.length = 0;
+ current.nextAnimationLast = animationTime;
+ current.nextTrackLast = current.trackTime;
+ }
+ this.queue.drain();
+ return applied;
+ };
+ AnimationState.prototype.applyMixingFrom = function (to, skeleton, currentPose) {
+ var from = to.mixingFrom;
+ if (from.mixingFrom != null)
+ this.applyMixingFrom(from, skeleton, currentPose);
+ var mix = 0;
+ if (to.mixDuration == 0)
+ mix = 1;
+ else {
+ mix = to.mixTime / to.mixDuration;
+ if (mix > 1)
+ mix = 1;
+ }
+ var events = mix < from.eventThreshold ? this.events : null;
+ var attachments = mix < from.attachmentThreshold, drawOrder = mix < from.drawOrderThreshold;
+ var animationLast = from.animationLast, animationTime = from.getAnimationTime();
+ var timelineCount = from.animation.timelines.length;
+ var timelines = from.animation.timelines;
+ var timelineData = from.timelineData;
+ var timelineDipMix = from.timelineDipMix;
+ var firstFrame = from.timelinesRotation.length == 0;
+ if (firstFrame)
+ spine.Utils.setArraySize(from.timelinesRotation, timelineCount << 1, null);
+ var timelinesRotation = from.timelinesRotation;
+ var pose;
+ var alphaDip = from.alpha * to.interruptAlpha, alphaMix = alphaDip * (1 - mix), alpha = 0;
+ from.totalAlpha = 0;
+ for (var i = 0; i < timelineCount; i++) {
+ var timeline = timelines[i];
+ switch (timelineData[i]) {
+ case AnimationState.SUBSEQUENT:
+ if (!attachments && timeline instanceof spine.AttachmentTimeline)
+ continue;
+ if (!drawOrder && timeline instanceof spine.DrawOrderTimeline)
+ continue;
+ pose = currentPose;
+ alpha = alphaMix;
+ break;
+ case AnimationState.FIRST:
+ pose = spine.MixPose.setup;
+ alpha = alphaMix;
+ break;
+ case AnimationState.DIP:
+ pose = spine.MixPose.setup;
+ alpha = alphaDip;
+ break;
+ default:
+ pose = spine.MixPose.setup;
+ alpha = alphaDip;
+ var dipMix = timelineDipMix[i];
+ alpha *= Math.max(0, 1 - dipMix.mixTime / dipMix.mixDuration);
+ break;
+ }
+ from.totalAlpha += alpha;
+ if (timeline instanceof spine.RotateTimeline)
+ this.applyRotateTimeline(timeline, skeleton, animationTime, alpha, pose, timelinesRotation, i << 1, firstFrame);
+ else {
+ timeline.apply(skeleton, animationLast, animationTime, events, alpha, pose, spine.MixDirection.out);
+ }
+ }
+ if (to.mixDuration > 0)
+ this.queueEvents(from, animationTime);
+ this.events.length = 0;
+ from.nextAnimationLast = animationTime;
+ from.nextTrackLast = from.trackTime;
+ return mix;
+ };
+ AnimationState.prototype.applyRotateTimeline = function (timeline, skeleton, time, alpha, pose, timelinesRotation, i, firstFrame) {
+ if (firstFrame)
+ timelinesRotation[i] = 0;
+ if (alpha == 1) {
+ timeline.apply(skeleton, 0, time, null, 1, pose, spine.MixDirection["in"]);
+ return;
+ }
+ var rotateTimeline = timeline;
+ var frames = rotateTimeline.frames;
+ var bone = skeleton.bones[rotateTimeline.boneIndex];
+ if (time < frames[0]) {
+ if (pose == spine.MixPose.setup)
+ bone.rotation = bone.data.rotation;
+ return;
+ }
+ var r2 = 0;
+ if (time >= frames[frames.length - spine.RotateTimeline.ENTRIES])
+ r2 = bone.data.rotation + frames[frames.length + spine.RotateTimeline.PREV_ROTATION];
+ else {
+ var frame = spine.Animation.binarySearch(frames, time, spine.RotateTimeline.ENTRIES);
+ var prevRotation = frames[frame + spine.RotateTimeline.PREV_ROTATION];
+ var frameTime = frames[frame];
+ var percent = rotateTimeline.getCurvePercent((frame >> 1) - 1, 1 - (time - frameTime) / (frames[frame + spine.RotateTimeline.PREV_TIME] - frameTime));
+ r2 = frames[frame + spine.RotateTimeline.ROTATION] - prevRotation;
+ r2 -= (16384 - ((16384.499999999996 - r2 / 360) | 0)) * 360;
+ r2 = prevRotation + r2 * percent + bone.data.rotation;
+ r2 -= (16384 - ((16384.499999999996 - r2 / 360) | 0)) * 360;
+ }
+ var r1 = pose == spine.MixPose.setup ? bone.data.rotation : bone.rotation;
+ var total = 0, diff = r2 - r1;
+ if (diff == 0) {
+ total = timelinesRotation[i];
+ }
+ else {
+ diff -= (16384 - ((16384.499999999996 - diff / 360) | 0)) * 360;
+ var lastTotal = 0, lastDiff = 0;
+ if (firstFrame) {
+ lastTotal = 0;
+ lastDiff = diff;
+ }
+ else {
+ lastTotal = timelinesRotation[i];
+ lastDiff = timelinesRotation[i + 1];
+ }
+ var current = diff > 0, dir = lastTotal >= 0;
+ if (spine.MathUtils.signum(lastDiff) != spine.MathUtils.signum(diff) && Math.abs(lastDiff) <= 90) {
+ if (Math.abs(lastTotal) > 180)
+ lastTotal += 360 * spine.MathUtils.signum(lastTotal);
+ dir = current;
+ }
+ total = diff + lastTotal - lastTotal % 360;
+ if (dir != current)
+ total += 360 * spine.MathUtils.signum(lastTotal);
+ timelinesRotation[i] = total;
+ }
+ timelinesRotation[i + 1] = diff;
+ r1 += total * alpha;
+ bone.rotation = r1 - (16384 - ((16384.499999999996 - r1 / 360) | 0)) * 360;
+ };
+ AnimationState.prototype.queueEvents = function (entry, animationTime) {
+ var animationStart = entry.animationStart, animationEnd = entry.animationEnd;
+ var duration = animationEnd - animationStart;
+ var trackLastWrapped = entry.trackLast % duration;
+ var events = this.events;
+ var i = 0, n = events.length;
+ for (; i < n; i++) {
+ var event_1 = events[i];
+ if (event_1.time < trackLastWrapped)
+ break;
+ if (event_1.time > animationEnd)
+ continue;
+ this.queue.event(entry, event_1);
+ }
+ if (entry.loop ? (trackLastWrapped > entry.trackTime % duration)
+ : (animationTime >= animationEnd && entry.animationLast < animationEnd)) {
+ this.queue.complete(entry);
+ }
+ for (; i < n; i++) {
+ var event_2 = events[i];
+ if (event_2.time < animationStart)
+ continue;
+ this.queue.event(entry, events[i]);
+ }
+ };
+ AnimationState.prototype.clearTracks = function () {
+ var oldDrainDisabled = this.queue.drainDisabled;
+ this.queue.drainDisabled = true;
+ for (var i = 0, n = this.tracks.length; i < n; i++)
+ this.clearTrack(i);
+ this.tracks.length = 0;
+ this.queue.drainDisabled = oldDrainDisabled;
+ this.queue.drain();
+ };
+ AnimationState.prototype.clearTrack = function (trackIndex) {
+ if (trackIndex >= this.tracks.length)
+ return;
+ var current = this.tracks[trackIndex];
+ if (current == null)
+ return;
+ this.queue.end(current);
+ this.disposeNext(current);
+ var entry = current;
+ while (true) {
+ var from = entry.mixingFrom;
+ if (from == null)
+ break;
+ this.queue.end(from);
+ entry.mixingFrom = null;
+ entry = from;
+ }
+ this.tracks[current.trackIndex] = null;
+ this.queue.drain();
+ };
+ AnimationState.prototype.setCurrent = function (index, current, interrupt) {
+ var from = this.expandToIndex(index);
+ this.tracks[index] = current;
+ if (from != null) {
+ if (interrupt)
+ this.queue.interrupt(from);
+ current.mixingFrom = from;
+ current.mixTime = 0;
+ if (from.mixingFrom != null && from.mixDuration > 0)
+ current.interruptAlpha *= Math.min(1, from.mixTime / from.mixDuration);
+ from.timelinesRotation.length = 0;
+ }
+ this.queue.start(current);
+ };
+ AnimationState.prototype.setAnimation = function (trackIndex, animationName, loop) {
+ var animation = this.data.skeletonData.findAnimation(animationName);
+ if (animation == null)
+ throw new Error("Animation not found: " + animationName);
+ return this.setAnimationWith(trackIndex, animation, loop);
+ };
+ AnimationState.prototype.setAnimationWith = function (trackIndex, animation, loop) {
+ if (animation == null)
+ throw new Error("animation cannot be null.");
+ var interrupt = true;
+ var current = this.expandToIndex(trackIndex);
+ if (current != null) {
+ if (current.nextTrackLast == -1) {
+ this.tracks[trackIndex] = current.mixingFrom;
+ this.queue.interrupt(current);
+ this.queue.end(current);
+ this.disposeNext(current);
+ current = current.mixingFrom;
+ interrupt = false;
+ }
+ else
+ this.disposeNext(current);
+ }
+ var entry = this.trackEntry(trackIndex, animation, loop, current);
+ this.setCurrent(trackIndex, entry, interrupt);
+ this.queue.drain();
+ return entry;
+ };
+ AnimationState.prototype.addAnimation = function (trackIndex, animationName, loop, delay) {
+ var animation = this.data.skeletonData.findAnimation(animationName);
+ if (animation == null)
+ throw new Error("Animation not found: " + animationName);
+ return this.addAnimationWith(trackIndex, animation, loop, delay);
+ };
+ AnimationState.prototype.addAnimationWith = function (trackIndex, animation, loop, delay) {
+ if (animation == null)
+ throw new Error("animation cannot be null.");
+ var last = this.expandToIndex(trackIndex);
+ if (last != null) {
+ while (last.next != null)
+ last = last.next;
+ }
+ var entry = this.trackEntry(trackIndex, animation, loop, last);
+ if (last == null) {
+ this.setCurrent(trackIndex, entry, true);
+ this.queue.drain();
+ }
+ else {
+ last.next = entry;
+ if (delay <= 0) {
+ var duration = last.animationEnd - last.animationStart;
+ if (duration != 0)
+ delay += duration * (1 + ((last.trackTime / duration) | 0)) - this.data.getMix(last.animation, animation);
+ else
+ delay = 0;
+ }
+ }
+ entry.delay = delay;
+ return entry;
+ };
+ AnimationState.prototype.setEmptyAnimation = function (trackIndex, mixDuration) {
+ var entry = this.setAnimationWith(trackIndex, AnimationState.emptyAnimation, false);
+ entry.mixDuration = mixDuration;
+ entry.trackEnd = mixDuration;
+ return entry;
+ };
+ AnimationState.prototype.addEmptyAnimation = function (trackIndex, mixDuration, delay) {
+ if (delay <= 0)
+ delay -= mixDuration;
+ var entry = this.addAnimationWith(trackIndex, AnimationState.emptyAnimation, false, delay);
+ entry.mixDuration = mixDuration;
+ entry.trackEnd = mixDuration;
+ return entry;
+ };
+ AnimationState.prototype.setEmptyAnimations = function (mixDuration) {
+ var oldDrainDisabled = this.queue.drainDisabled;
+ this.queue.drainDisabled = true;
+ for (var i = 0, n = this.tracks.length; i < n; i++) {
+ var current = this.tracks[i];
+ if (current != null)
+ this.setEmptyAnimation(current.trackIndex, mixDuration);
+ }
+ this.queue.drainDisabled = oldDrainDisabled;
+ this.queue.drain();
+ };
+ AnimationState.prototype.expandToIndex = function (index) {
+ if (index < this.tracks.length)
+ return this.tracks[index];
+ spine.Utils.ensureArrayCapacity(this.tracks, index - this.tracks.length + 1, null);
+ this.tracks.length = index + 1;
+ return null;
+ };
+ AnimationState.prototype.trackEntry = function (trackIndex, animation, loop, last) {
+ var entry = this.trackEntryPool.obtain();
+ entry.trackIndex = trackIndex;
+ entry.animation = animation;
+ entry.loop = loop;
+ entry.eventThreshold = 0;
+ entry.attachmentThreshold = 0;
+ entry.drawOrderThreshold = 0;
+ entry.animationStart = 0;
+ entry.animationEnd = animation.duration;
+ entry.animationLast = -1;
+ entry.nextAnimationLast = -1;
+ entry.delay = 0;
+ entry.trackTime = 0;
+ entry.trackLast = -1;
+ entry.nextTrackLast = -1;
+ entry.trackEnd = Number.MAX_VALUE;
+ entry.timeScale = 1;
+ entry.alpha = 1;
+ entry.interruptAlpha = 1;
+ entry.mixTime = 0;
+ entry.mixDuration = last == null ? 0 : this.data.getMix(last.animation, animation);
+ return entry;
+ };
+ AnimationState.prototype.disposeNext = function (entry) {
+ var next = entry.next;
+ while (next != null) {
+ this.queue.dispose(next);
+ next = next.next;
+ }
+ entry.next = null;
+ };
+ AnimationState.prototype._animationsChanged = function () {
+ this.animationsChanged = false;
+ var propertyIDs = this.propertyIDs;
+ propertyIDs.clear();
+ var mixingTo = this.mixingTo;
+ for (var i = 0, n = this.tracks.length; i < n; i++) {
+ var entry = this.tracks[i];
+ if (entry != null)
+ entry.setTimelineData(null, mixingTo, propertyIDs);
+ }
+ };
+ AnimationState.prototype.getCurrent = function (trackIndex) {
+ if (trackIndex >= this.tracks.length)
+ return null;
+ return this.tracks[trackIndex];
+ };
+ AnimationState.prototype.addListener = function (listener) {
+ if (listener == null)
+ throw new Error("listener cannot be null.");
+ this.listeners.push(listener);
+ };
+ AnimationState.prototype.removeListener = function (listener) {
+ var index = this.listeners.indexOf(listener);
+ if (index >= 0)
+ this.listeners.splice(index, 1);
+ };
+ AnimationState.prototype.clearListeners = function () {
+ this.listeners.length = 0;
+ };
+ AnimationState.prototype.clearListenerNotifications = function () {
+ this.queue.clear();
+ };
+ return AnimationState;
+ }());
+ AnimationState.emptyAnimation = new spine.Animation("", [], 0);
+ AnimationState.SUBSEQUENT = 0;
+ AnimationState.FIRST = 1;
+ AnimationState.DIP = 2;
+ AnimationState.DIP_MIX = 3;
+ spine.AnimationState = AnimationState;
+ var TrackEntry = (function () {
+ function TrackEntry() {
+ this.timelineData = new Array();
+ this.timelineDipMix = new Array();
+ this.timelinesRotation = new Array();
+ }
+ TrackEntry.prototype.reset = function () {
+ this.next = null;
+ this.mixingFrom = null;
+ this.animation = null;
+ this.listener = null;
+ this.timelineData.length = 0;
+ this.timelineDipMix.length = 0;
+ this.timelinesRotation.length = 0;
+ };
+ TrackEntry.prototype.setTimelineData = function (to, mixingToArray, propertyIDs) {
+ if (to != null)
+ mixingToArray.push(to);
+ var lastEntry = this.mixingFrom != null ? this.mixingFrom.setTimelineData(this, mixingToArray, propertyIDs) : this;
+ if (to != null)
+ mixingToArray.pop();
+ var mixingTo = mixingToArray;
+ var mixingToLast = mixingToArray.length - 1;
+ var timelines = this.animation.timelines;
+ var timelinesCount = this.animation.timelines.length;
+ var timelineData = spine.Utils.setArraySize(this.timelineData, timelinesCount);
+ this.timelineDipMix.length = 0;
+ var timelineDipMix = spine.Utils.setArraySize(this.timelineDipMix, timelinesCount);
+ outer: for (var i = 0; i < timelinesCount; i++) {
+ var id = timelines[i].getPropertyId();
+ if (!propertyIDs.add(id))
+ timelineData[i] = AnimationState.SUBSEQUENT;
+ else if (to == null || !to.hasTimeline(id))
+ timelineData[i] = AnimationState.FIRST;
+ else {
+ for (var ii = mixingToLast; ii >= 0; ii--) {
+ var entry = mixingTo[ii];
+ if (!entry.hasTimeline(id)) {
+ if (entry.mixDuration > 0) {
+ timelineData[i] = AnimationState.DIP_MIX;
+ timelineDipMix[i] = entry;
+ continue outer;
+ }
+ }
+ }
+ timelineData[i] = AnimationState.DIP;
+ }
+ }
+ return lastEntry;
+ };
+ TrackEntry.prototype.hasTimeline = function (id) {
+ var timelines = this.animation.timelines;
+ for (var i = 0, n = timelines.length; i < n; i++)
+ if (timelines[i].getPropertyId() == id)
+ return true;
+ return false;
+ };
+ TrackEntry.prototype.getAnimationTime = function () {
+ if (this.loop) {
+ var duration = this.animationEnd - this.animationStart;
+ if (duration == 0)
+ return this.animationStart;
+ return (this.trackTime % duration) + this.animationStart;
+ }
+ return Math.min(this.trackTime + this.animationStart, this.animationEnd);
+ };
+ TrackEntry.prototype.setAnimationLast = function (animationLast) {
+ this.animationLast = animationLast;
+ this.nextAnimationLast = animationLast;
+ };
+ TrackEntry.prototype.isComplete = function () {
+ return this.trackTime >= this.animationEnd - this.animationStart;
+ };
+ TrackEntry.prototype.resetRotationDirections = function () {
+ this.timelinesRotation.length = 0;
+ };
+ return TrackEntry;
+ }());
+ spine.TrackEntry = TrackEntry;
+ var EventQueue = (function () {
+ function EventQueue(animState) {
+ this.objects = [];
+ this.drainDisabled = false;
+ this.animState = animState;
+ }
+ EventQueue.prototype.start = function (entry) {
+ this.objects.push(EventType.start);
+ this.objects.push(entry);
+ this.animState.animationsChanged = true;
+ };
+ EventQueue.prototype.interrupt = function (entry) {
+ this.objects.push(EventType.interrupt);
+ this.objects.push(entry);
+ };
+ EventQueue.prototype.end = function (entry) {
+ this.objects.push(EventType.end);
+ this.objects.push(entry);
+ this.animState.animationsChanged = true;
+ };
+ EventQueue.prototype.dispose = function (entry) {
+ this.objects.push(EventType.dispose);
+ this.objects.push(entry);
+ };
+ EventQueue.prototype.complete = function (entry) {
+ this.objects.push(EventType.complete);
+ this.objects.push(entry);
+ };
+ EventQueue.prototype.event = function (entry, event) {
+ this.objects.push(EventType.event);
+ this.objects.push(entry);
+ this.objects.push(event);
+ };
+ EventQueue.prototype.drain = function () {
+ if (this.drainDisabled)
+ return;
+ this.drainDisabled = true;
+ var objects = this.objects;
+ var listeners = this.animState.listeners;
+ for (var i = 0; i < objects.length; i += 2) {
+ var type = objects[i];
+ var entry = objects[i + 1];
+ switch (type) {
+ case EventType.start:
+ if (entry.listener != null && entry.listener.start)
+ entry.listener.start(entry);
+ for (var ii = 0; ii < listeners.length; ii++)
+ if (listeners[ii].start)
+ listeners[ii].start(entry);
+ break;
+ case EventType.interrupt:
+ if (entry.listener != null && entry.listener.interrupt)
+ entry.listener.interrupt(entry);
+ for (var ii = 0; ii < listeners.length; ii++)
+ if (listeners[ii].interrupt)
+ listeners[ii].interrupt(entry);
+ break;
+ case EventType.end:
+ if (entry.listener != null && entry.listener.end)
+ entry.listener.end(entry);
+ for (var ii = 0; ii < listeners.length; ii++)
+ if (listeners[ii].end)
+ listeners[ii].end(entry);
+ case EventType.dispose:
+ if (entry.listener != null && entry.listener.dispose)
+ entry.listener.dispose(entry);
+ for (var ii = 0; ii < listeners.length; ii++)
+ if (listeners[ii].dispose)
+ listeners[ii].dispose(entry);
+ this.animState.trackEntryPool.free(entry);
+ break;
+ case EventType.complete:
+ if (entry.listener != null && entry.listener.complete)
+ entry.listener.complete(entry);
+ for (var ii = 0; ii < listeners.length; ii++)
+ if (listeners[ii].complete)
+ listeners[ii].complete(entry);
+ break;
+ case EventType.event:
+ var event_3 = objects[i++ + 2];
+ if (entry.listener != null && entry.listener.event)
+ entry.listener.event(entry, event_3);
+ for (var ii = 0; ii < listeners.length; ii++)
+ if (listeners[ii].event)
+ listeners[ii].event(entry, event_3);
+ break;
+ }
+ }
+ this.clear();
+ this.drainDisabled = false;
+ };
+ EventQueue.prototype.clear = function () {
+ this.objects.length = 0;
+ };
+ return EventQueue;
+ }());
+ spine.EventQueue = EventQueue;
+ var EventType;
+ (function (EventType) {
+ EventType[EventType["start"] = 0] = "start";
+ EventType[EventType["interrupt"] = 1] = "interrupt";
+ EventType[EventType["end"] = 2] = "end";
+ EventType[EventType["dispose"] = 3] = "dispose";
+ EventType[EventType["complete"] = 4] = "complete";
+ EventType[EventType["event"] = 5] = "event";
+ })(EventType = spine.EventType || (spine.EventType = {}));
+ var AnimationStateAdapter2 = (function () {
+ function AnimationStateAdapter2() {
+ }
+ AnimationStateAdapter2.prototype.start = function (entry) {
+ };
+ AnimationStateAdapter2.prototype.interrupt = function (entry) {
+ };
+ AnimationStateAdapter2.prototype.end = function (entry) {
+ };
+ AnimationStateAdapter2.prototype.dispose = function (entry) {
+ };
+ AnimationStateAdapter2.prototype.complete = function (entry) {
+ };
+ AnimationStateAdapter2.prototype.event = function (entry, event) {
+ };
+ return AnimationStateAdapter2;
+ }());
+ spine.AnimationStateAdapter2 = AnimationStateAdapter2;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var AnimationStateData = (function () {
+ function AnimationStateData(skeletonData) {
+ this.animationToMixTime = {};
+ this.defaultMix = 0;
+ if (skeletonData == null)
+ throw new Error("skeletonData cannot be null.");
+ this.skeletonData = skeletonData;
+ }
+ AnimationStateData.prototype.setMix = function (fromName, toName, duration) {
+ var from = this.skeletonData.findAnimation(fromName);
+ if (from == null)
+ throw new Error("Animation not found: " + fromName);
+ var to = this.skeletonData.findAnimation(toName);
+ if (to == null)
+ throw new Error("Animation not found: " + toName);
+ this.setMixWith(from, to, duration);
+ };
+ AnimationStateData.prototype.setMixWith = function (from, to, duration) {
+ if (from == null)
+ throw new Error("from cannot be null.");
+ if (to == null)
+ throw new Error("to cannot be null.");
+ var key = from.name + to.name;
+ this.animationToMixTime[key] = duration;
+ };
+ AnimationStateData.prototype.getMix = function (from, to) {
+ var key = from.name + to.name;
+ var value = this.animationToMixTime[key];
+ return value === undefined ? this.defaultMix : value;
+ };
+ return AnimationStateData;
+ }());
+ spine.AnimationStateData = AnimationStateData;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var AssetManager = (function () {
+ function AssetManager(textureLoader, pathPrefix) {
+ if (pathPrefix === void 0) { pathPrefix = ""; }
+ this.assets = {};
+ this.errors = {};
+ this.toLoad = 0;
+ this.loaded = 0;
+ this.textureLoader = textureLoader;
+ this.pathPrefix = pathPrefix;
+ }
+ AssetManager.prototype.loadText = function (path, success, error) {
+ var _this = this;
+ if (success === void 0) { success = null; }
+ if (error === void 0) { error = null; }
+ path = this.pathPrefix + path;
+ this.toLoad++;
+ var request = new XMLHttpRequest();
+ request.onreadystatechange = function () {
+ if (request.readyState == XMLHttpRequest.DONE) {
+ if (request.status >= 200 && request.status < 300) {
+ _this.assets[path] = request.responseText;
+ if (success)
+ success(path, request.responseText);
+ }
+ else {
+ _this.errors[path] = "Couldn't load text " + path + ": status " + request.status + ", " + request.responseText;
+ if (error)
+ error(path, "Couldn't load text " + path + ": status " + request.status + ", " + request.responseText);
+ }
+ _this.toLoad--;
+ _this.loaded++;
+ }
+ };
+ request.open("GET", path, true);
+ request.send();
+ };
+ AssetManager.prototype.loadTexture = function (path, success, error) {
+ var _this = this;
+ if (success === void 0) { success = null; }
+ if (error === void 0) { error = null; }
+ path = this.pathPrefix + path;
+ this.toLoad++;
+ var img = new Image();
+ img.crossOrigin = "anonymous";
+ img.onload = function (ev) {
+ var texture = _this.textureLoader(img);
+ _this.assets[path] = texture;
+ _this.toLoad--;
+ _this.loaded++;
+ if (success)
+ success(path, img);
+ };
+ img.onerror = function (ev) {
+ _this.errors[path] = "Couldn't load image " + path;
+ _this.toLoad--;
+ _this.loaded++;
+ if (error)
+ error(path, "Couldn't load image " + path);
+ };
+ img.src = path;
+ };
+ AssetManager.prototype.loadTextureData = function (path, data, success, error) {
+ var _this = this;
+ if (success === void 0) { success = null; }
+ if (error === void 0) { error = null; }
+ path = this.pathPrefix + path;
+ this.toLoad++;
+ var img = new Image();
+ img.onload = function (ev) {
+ var texture = _this.textureLoader(img);
+ _this.assets[path] = texture;
+ _this.toLoad--;
+ _this.loaded++;
+ if (success)
+ success(path, img);
+ };
+ img.onerror = function (ev) {
+ _this.errors[path] = "Couldn't load image " + path;
+ _this.toLoad--;
+ _this.loaded++;
+ if (error)
+ error(path, "Couldn't load image " + path);
+ };
+ img.src = data;
+ };
+ AssetManager.prototype.get = function (path) {
+ path = this.pathPrefix + path;
+ return this.assets[path];
+ };
+ AssetManager.prototype.remove = function (path) {
+ path = this.pathPrefix + path;
+ var asset = this.assets[path];
+ if (asset.dispose)
+ asset.dispose();
+ this.assets[path] = null;
+ };
+ AssetManager.prototype.removeAll = function () {
+ for (var key in this.assets) {
+ var asset = this.assets[key];
+ if (asset.dispose)
+ asset.dispose();
+ }
+ this.assets = {};
+ };
+ AssetManager.prototype.isLoadingComplete = function () {
+ return this.toLoad == 0;
+ };
+ AssetManager.prototype.getToLoad = function () {
+ return this.toLoad;
+ };
+ AssetManager.prototype.getLoaded = function () {
+ return this.loaded;
+ };
+ AssetManager.prototype.dispose = function () {
+ this.removeAll();
+ };
+ AssetManager.prototype.hasErrors = function () {
+ return Object.keys(this.errors).length > 0;
+ };
+ AssetManager.prototype.getErrors = function () {
+ return this.errors;
+ };
+ return AssetManager;
+ }());
+ spine.AssetManager = AssetManager;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var AtlasAttachmentLoader = (function () {
+ function AtlasAttachmentLoader(atlas) {
+ this.atlas = atlas;
+ }
+ AtlasAttachmentLoader.prototype.newRegionAttachment = function (skin, name, path) {
+ var region = this.atlas.findRegion(path);
+ if (region == null)
+ throw new Error("Region not found in atlas: " + path + " (region attachment: " + name + ")");
+ region.renderObject = region;
+ var attachment = new spine.RegionAttachment(name);
+ attachment.setRegion(region);
+ return attachment;
+ };
+ AtlasAttachmentLoader.prototype.newMeshAttachment = function (skin, name, path) {
+ var region = this.atlas.findRegion(path);
+ if (region == null)
+ throw new Error("Region not found in atlas: " + path + " (mesh attachment: " + name + ")");
+ region.renderObject = region;
+ var attachment = new spine.MeshAttachment(name);
+ attachment.region = region;
+ return attachment;
+ };
+ AtlasAttachmentLoader.prototype.newBoundingBoxAttachment = function (skin, name) {
+ return new spine.BoundingBoxAttachment(name);
+ };
+ AtlasAttachmentLoader.prototype.newPathAttachment = function (skin, name) {
+ return new spine.PathAttachment(name);
+ };
+ AtlasAttachmentLoader.prototype.newPointAttachment = function (skin, name) {
+ return new spine.PointAttachment(name);
+ };
+ AtlasAttachmentLoader.prototype.newClippingAttachment = function (skin, name) {
+ return new spine.ClippingAttachment(name);
+ };
+ return AtlasAttachmentLoader;
+ }());
+ spine.AtlasAttachmentLoader = AtlasAttachmentLoader;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var BlendMode;
+ (function (BlendMode) {
+ BlendMode[BlendMode["Normal"] = 0] = "Normal";
+ BlendMode[BlendMode["Additive"] = 1] = "Additive";
+ BlendMode[BlendMode["Multiply"] = 2] = "Multiply";
+ BlendMode[BlendMode["Screen"] = 3] = "Screen";
+ })(BlendMode = spine.BlendMode || (spine.BlendMode = {}));
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var Bone = (function () {
+ function Bone(data, skeleton, parent) {
+ this.children = new Array();
+ this.x = 0;
+ this.y = 0;
+ this.rotation = 0;
+ this.scaleX = 0;
+ this.scaleY = 0;
+ this.shearX = 0;
+ this.shearY = 0;
+ this.ax = 0;
+ this.ay = 0;
+ this.arotation = 0;
+ this.ascaleX = 0;
+ this.ascaleY = 0;
+ this.ashearX = 0;
+ this.ashearY = 0;
+ this.appliedValid = false;
+ this.a = 0;
+ this.b = 0;
+ this.worldX = 0;
+ this.c = 0;
+ this.d = 0;
+ this.worldY = 0;
+ this.sorted = false;
+ if (data == null)
+ throw new Error("data cannot be null.");
+ if (skeleton == null)
+ throw new Error("skeleton cannot be null.");
+ this.data = data;
+ this.skeleton = skeleton;
+ this.parent = parent;
+ this.setToSetupPose();
+ }
+ Bone.prototype.update = function () {
+ this.updateWorldTransformWith(this.x, this.y, this.rotation, this.scaleX, this.scaleY, this.shearX, this.shearY);
+ };
+ Bone.prototype.updateWorldTransform = function () {
+ this.updateWorldTransformWith(this.x, this.y, this.rotation, this.scaleX, this.scaleY, this.shearX, this.shearY);
+ };
+ Bone.prototype.updateWorldTransformWith = function (x, y, rotation, scaleX, scaleY, shearX, shearY) {
+ this.ax = x;
+ this.ay = y;
+ this.arotation = rotation;
+ this.ascaleX = scaleX;
+ this.ascaleY = scaleY;
+ this.ashearX = shearX;
+ this.ashearY = shearY;
+ this.appliedValid = true;
+ var parent = this.parent;
+ if (parent == null) {
+ var rotationY = rotation + 90 + shearY;
+ var la = spine.MathUtils.cosDeg(rotation + shearX) * scaleX;
+ var lb = spine.MathUtils.cosDeg(rotationY) * scaleY;
+ var lc = spine.MathUtils.sinDeg(rotation + shearX) * scaleX;
+ var ld = spine.MathUtils.sinDeg(rotationY) * scaleY;
+ var skeleton = this.skeleton;
+ if (skeleton.flipX) {
+ x = -x;
+ la = -la;
+ lb = -lb;
+ }
+ if (skeleton.flipY) {
+ y = -y;
+ lc = -lc;
+ ld = -ld;
+ }
+ this.a = la;
+ this.b = lb;
+ this.c = lc;
+ this.d = ld;
+ this.worldX = x + skeleton.x;
+ this.worldY = y + skeleton.y;
+ return;
+ }
+ var pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d;
+ this.worldX = pa * x + pb * y + parent.worldX;
+ this.worldY = pc * x + pd * y + parent.worldY;
+ switch (this.data.transformMode) {
+ case spine.TransformMode.Normal: {
+ var rotationY = rotation + 90 + shearY;
+ var la = spine.MathUtils.cosDeg(rotation + shearX) * scaleX;
+ var lb = spine.MathUtils.cosDeg(rotationY) * scaleY;
+ var lc = spine.MathUtils.sinDeg(rotation + shearX) * scaleX;
+ var ld = spine.MathUtils.sinDeg(rotationY) * scaleY;
+ this.a = pa * la + pb * lc;
+ this.b = pa * lb + pb * ld;
+ this.c = pc * la + pd * lc;
+ this.d = pc * lb + pd * ld;
+ return;
+ }
+ case spine.TransformMode.OnlyTranslation: {
+ var rotationY = rotation + 90 + shearY;
+ this.a = spine.MathUtils.cosDeg(rotation + shearX) * scaleX;
+ this.b = spine.MathUtils.cosDeg(rotationY) * scaleY;
+ this.c = spine.MathUtils.sinDeg(rotation + shearX) * scaleX;
+ this.d = spine.MathUtils.sinDeg(rotationY) * scaleY;
+ break;
+ }
+ case spine.TransformMode.NoRotationOrReflection: {
+ var s = pa * pa + pc * pc;
+ var prx = 0;
+ if (s > 0.0001) {
+ s = Math.abs(pa * pd - pb * pc) / s;
+ pb = pc * s;
+ pd = pa * s;
+ prx = Math.atan2(pc, pa) * spine.MathUtils.radDeg;
+ }
+ else {
+ pa = 0;
+ pc = 0;
+ prx = 90 - Math.atan2(pd, pb) * spine.MathUtils.radDeg;
+ }
+ var rx = rotation + shearX - prx;
+ var ry = rotation + shearY - prx + 90;
+ var la = spine.MathUtils.cosDeg(rx) * scaleX;
+ var lb = spine.MathUtils.cosDeg(ry) * scaleY;
+ var lc = spine.MathUtils.sinDeg(rx) * scaleX;
+ var ld = spine.MathUtils.sinDeg(ry) * scaleY;
+ this.a = pa * la - pb * lc;
+ this.b = pa * lb - pb * ld;
+ this.c = pc * la + pd * lc;
+ this.d = pc * lb + pd * ld;
+ break;
+ }
+ case spine.TransformMode.NoScale:
+ case spine.TransformMode.NoScaleOrReflection: {
+ var cos = spine.MathUtils.cosDeg(rotation);
+ var sin = spine.MathUtils.sinDeg(rotation);
+ var za = pa * cos + pb * sin;
+ var zc = pc * cos + pd * sin;
+ var s = Math.sqrt(za * za + zc * zc);
+ if (s > 0.00001)
+ s = 1 / s;
+ za *= s;
+ zc *= s;
+ s = Math.sqrt(za * za + zc * zc);
+ var r = Math.PI / 2 + Math.atan2(zc, za);
+ var zb = Math.cos(r) * s;
+ var zd = Math.sin(r) * s;
+ var la = spine.MathUtils.cosDeg(shearX) * scaleX;
+ var lb = spine.MathUtils.cosDeg(90 + shearY) * scaleY;
+ var lc = spine.MathUtils.sinDeg(shearX) * scaleX;
+ var ld = spine.MathUtils.sinDeg(90 + shearY) * scaleY;
+ if (this.data.transformMode != spine.TransformMode.NoScaleOrReflection ? pa * pd - pb * pc < 0 : this.skeleton.flipX != this.skeleton.flipY) {
+ zb = -zb;
+ zd = -zd;
+ }
+ this.a = za * la + zb * lc;
+ this.b = za * lb + zb * ld;
+ this.c = zc * la + zd * lc;
+ this.d = zc * lb + zd * ld;
+ return;
+ }
+ }
+ if (this.skeleton.flipX) {
+ this.a = -this.a;
+ this.b = -this.b;
+ }
+ if (this.skeleton.flipY) {
+ this.c = -this.c;
+ this.d = -this.d;
+ }
+ };
+ Bone.prototype.setToSetupPose = function () {
+ var data = this.data;
+ this.x = data.x;
+ this.y = data.y;
+ this.rotation = data.rotation;
+ this.scaleX = data.scaleX;
+ this.scaleY = data.scaleY;
+ this.shearX = data.shearX;
+ this.shearY = data.shearY;
+ };
+ Bone.prototype.getWorldRotationX = function () {
+ return Math.atan2(this.c, this.a) * spine.MathUtils.radDeg;
+ };
+ Bone.prototype.getWorldRotationY = function () {
+ return Math.atan2(this.d, this.b) * spine.MathUtils.radDeg;
+ };
+ Bone.prototype.getWorldScaleX = function () {
+ return Math.sqrt(this.a * this.a + this.c * this.c);
+ };
+ Bone.prototype.getWorldScaleY = function () {
+ return Math.sqrt(this.b * this.b + this.d * this.d);
+ };
+ Bone.prototype.updateAppliedTransform = function () {
+ this.appliedValid = true;
+ var parent = this.parent;
+ if (parent == null) {
+ this.ax = this.worldX;
+ this.ay = this.worldY;
+ this.arotation = Math.atan2(this.c, this.a) * spine.MathUtils.radDeg;
+ this.ascaleX = Math.sqrt(this.a * this.a + this.c * this.c);
+ this.ascaleY = Math.sqrt(this.b * this.b + this.d * this.d);
+ this.ashearX = 0;
+ this.ashearY = Math.atan2(this.a * this.b + this.c * this.d, this.a * this.d - this.b * this.c) * spine.MathUtils.radDeg;
+ return;
+ }
+ var pa = parent.a, pb = parent.b, pc = parent.c, pd = parent.d;
+ var pid = 1 / (pa * pd - pb * pc);
+ var dx = this.worldX - parent.worldX, dy = this.worldY - parent.worldY;
+ this.ax = (dx * pd * pid - dy * pb * pid);
+ this.ay = (dy * pa * pid - dx * pc * pid);
+ var ia = pid * pd;
+ var id = pid * pa;
+ var ib = pid * pb;
+ var ic = pid * pc;
+ var ra = ia * this.a - ib * this.c;
+ var rb = ia * this.b - ib * this.d;
+ var rc = id * this.c - ic * this.a;
+ var rd = id * this.d - ic * this.b;
+ this.ashearX = 0;
+ this.ascaleX = Math.sqrt(ra * ra + rc * rc);
+ if (this.ascaleX > 0.0001) {
+ var det = ra * rd - rb * rc;
+ this.ascaleY = det / this.ascaleX;
+ this.ashearY = Math.atan2(ra * rb + rc * rd, det) * spine.MathUtils.radDeg;
+ this.arotation = Math.atan2(rc, ra) * spine.MathUtils.radDeg;
+ }
+ else {
+ this.ascaleX = 0;
+ this.ascaleY = Math.sqrt(rb * rb + rd * rd);
+ this.ashearY = 0;
+ this.arotation = 90 - Math.atan2(rd, rb) * spine.MathUtils.radDeg;
+ }
+ };
+ Bone.prototype.worldToLocal = function (world) {
+ var a = this.a, b = this.b, c = this.c, d = this.d;
+ var invDet = 1 / (a * d - b * c);
+ var x = world.x - this.worldX, y = world.y - this.worldY;
+ world.x = (x * d * invDet - y * b * invDet);
+ world.y = (y * a * invDet - x * c * invDet);
+ return world;
+ };
+ Bone.prototype.localToWorld = function (local) {
+ var x = local.x, y = local.y;
+ local.x = x * this.a + y * this.b + this.worldX;
+ local.y = x * this.c + y * this.d + this.worldY;
+ return local;
+ };
+ Bone.prototype.worldToLocalRotation = function (worldRotation) {
+ var sin = spine.MathUtils.sinDeg(worldRotation), cos = spine.MathUtils.cosDeg(worldRotation);
+ return Math.atan2(this.a * sin - this.c * cos, this.d * cos - this.b * sin) * spine.MathUtils.radDeg;
+ };
+ Bone.prototype.localToWorldRotation = function (localRotation) {
+ var sin = spine.MathUtils.sinDeg(localRotation), cos = spine.MathUtils.cosDeg(localRotation);
+ return Math.atan2(cos * this.c + sin * this.d, cos * this.a + sin * this.b) * spine.MathUtils.radDeg;
+ };
+ Bone.prototype.rotateWorld = function (degrees) {
+ var a = this.a, b = this.b, c = this.c, d = this.d;
+ var cos = spine.MathUtils.cosDeg(degrees), sin = spine.MathUtils.sinDeg(degrees);
+ this.a = cos * a - sin * c;
+ this.b = cos * b - sin * d;
+ this.c = sin * a + cos * c;
+ this.d = sin * b + cos * d;
+ this.appliedValid = false;
+ };
+ return Bone;
+ }());
+ spine.Bone = Bone;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var BoneData = (function () {
+ function BoneData(index, name, parent) {
+ this.x = 0;
+ this.y = 0;
+ this.rotation = 0;
+ this.scaleX = 1;
+ this.scaleY = 1;
+ this.shearX = 0;
+ this.shearY = 0;
+ this.transformMode = TransformMode.Normal;
+ if (index < 0)
+ throw new Error("index must be >= 0.");
+ if (name == null)
+ throw new Error("name cannot be null.");
+ this.index = index;
+ this.name = name;
+ this.parent = parent;
+ }
+ return BoneData;
+ }());
+ spine.BoneData = BoneData;
+ var TransformMode;
+ (function (TransformMode) {
+ TransformMode[TransformMode["Normal"] = 0] = "Normal";
+ TransformMode[TransformMode["OnlyTranslation"] = 1] = "OnlyTranslation";
+ TransformMode[TransformMode["NoRotationOrReflection"] = 2] = "NoRotationOrReflection";
+ TransformMode[TransformMode["NoScale"] = 3] = "NoScale";
+ TransformMode[TransformMode["NoScaleOrReflection"] = 4] = "NoScaleOrReflection";
+ })(TransformMode = spine.TransformMode || (spine.TransformMode = {}));
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var Event = (function () {
+ function Event(time, data) {
+ if (data == null)
+ throw new Error("data cannot be null.");
+ this.time = time;
+ this.data = data;
+ }
+ return Event;
+ }());
+ spine.Event = Event;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var EventData = (function () {
+ function EventData(name) {
+ this.name = name;
+ }
+ return EventData;
+ }());
+ spine.EventData = EventData;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var IkConstraint = (function () {
+ function IkConstraint(data, skeleton) {
+ this.mix = 1;
+ this.bendDirection = 0;
+ if (data == null)
+ throw new Error("data cannot be null.");
+ if (skeleton == null)
+ throw new Error("skeleton cannot be null.");
+ this.data = data;
+ this.mix = data.mix;
+ this.bendDirection = data.bendDirection;
+ this.bones = new Array();
+ for (var i = 0; i < data.bones.length; i++)
+ this.bones.push(skeleton.findBone(data.bones[i].name));
+ this.target = skeleton.findBone(data.target.name);
+ }
+ IkConstraint.prototype.getOrder = function () {
+ return this.data.order;
+ };
+ IkConstraint.prototype.apply = function () {
+ this.update();
+ };
+ IkConstraint.prototype.update = function () {
+ var target = this.target;
+ var bones = this.bones;
+ switch (bones.length) {
+ case 1:
+ this.apply1(bones[0], target.worldX, target.worldY, this.mix);
+ break;
+ case 2:
+ this.apply2(bones[0], bones[1], target.worldX, target.worldY, this.bendDirection, this.mix);
+ break;
+ }
+ };
+ IkConstraint.prototype.apply1 = function (bone, targetX, targetY, alpha) {
+ if (!bone.appliedValid)
+ bone.updateAppliedTransform();
+ var p = bone.parent;
+ var id = 1 / (p.a * p.d - p.b * p.c);
+ var x = targetX - p.worldX, y = targetY - p.worldY;
+ var tx = (x * p.d - y * p.b) * id - bone.ax, ty = (y * p.a - x * p.c) * id - bone.ay;
+ var rotationIK = Math.atan2(ty, tx) * spine.MathUtils.radDeg - bone.ashearX - bone.arotation;
+ if (bone.ascaleX < 0)
+ rotationIK += 180;
+ if (rotationIK > 180)
+ rotationIK -= 360;
+ else if (rotationIK < -180)
+ rotationIK += 360;
+ bone.updateWorldTransformWith(bone.ax, bone.ay, bone.arotation + rotationIK * alpha, bone.ascaleX, bone.ascaleY, bone.ashearX, bone.ashearY);
+ };
+ IkConstraint.prototype.apply2 = function (parent, child, targetX, targetY, bendDir, alpha) {
+ if (alpha == 0) {
+ child.updateWorldTransform();
+ return;
+ }
+ if (!parent.appliedValid)
+ parent.updateAppliedTransform();
+ if (!child.appliedValid)
+ child.updateAppliedTransform();
+ var px = parent.ax, py = parent.ay, psx = parent.ascaleX, psy = parent.ascaleY, csx = child.ascaleX;
+ var os1 = 0, os2 = 0, s2 = 0;
+ if (psx < 0) {
+ psx = -psx;
+ os1 = 180;
+ s2 = -1;
+ }
+ else {
+ os1 = 0;
+ s2 = 1;
+ }
+ if (psy < 0) {
+ psy = -psy;
+ s2 = -s2;
+ }
+ if (csx < 0) {
+ csx = -csx;
+ os2 = 180;
+ }
+ else
+ os2 = 0;
+ var cx = child.ax, cy = 0, cwx = 0, cwy = 0, a = parent.a, b = parent.b, c = parent.c, d = parent.d;
+ var u = Math.abs(psx - psy) <= 0.0001;
+ if (!u) {
+ cy = 0;
+ cwx = a * cx + parent.worldX;
+ cwy = c * cx + parent.worldY;
+ }
+ else {
+ cy = child.ay;
+ cwx = a * cx + b * cy + parent.worldX;
+ cwy = c * cx + d * cy + parent.worldY;
+ }
+ var pp = parent.parent;
+ a = pp.a;
+ b = pp.b;
+ c = pp.c;
+ d = pp.d;
+ var id = 1 / (a * d - b * c), x = targetX - pp.worldX, y = targetY - pp.worldY;
+ var tx = (x * d - y * b) * id - px, ty = (y * a - x * c) * id - py;
+ x = cwx - pp.worldX;
+ y = cwy - pp.worldY;
+ var dx = (x * d - y * b) * id - px, dy = (y * a - x * c) * id - py;
+ var l1 = Math.sqrt(dx * dx + dy * dy), l2 = child.data.length * csx, a1 = 0, a2 = 0;
+ outer: if (u) {
+ l2 *= psx;
+ var cos = (tx * tx + ty * ty - l1 * l1 - l2 * l2) / (2 * l1 * l2);
+ if (cos < -1)
+ cos = -1;
+ else if (cos > 1)
+ cos = 1;
+ a2 = Math.acos(cos) * bendDir;
+ a = l1 + l2 * cos;
+ b = l2 * Math.sin(a2);
+ a1 = Math.atan2(ty * a - tx * b, tx * a + ty * b);
+ }
+ else {
+ a = psx * l2;
+ b = psy * l2;
+ var aa = a * a, bb = b * b, dd = tx * tx + ty * ty, ta = Math.atan2(ty, tx);
+ c = bb * l1 * l1 + aa * dd - aa * bb;
+ var c1 = -2 * bb * l1, c2 = bb - aa;
+ d = c1 * c1 - 4 * c2 * c;
+ if (d >= 0) {
+ var q = Math.sqrt(d);
+ if (c1 < 0)
+ q = -q;
+ q = -(c1 + q) / 2;
+ var r0 = q / c2, r1 = c / q;
+ var r = Math.abs(r0) < Math.abs(r1) ? r0 : r1;
+ if (r * r <= dd) {
+ y = Math.sqrt(dd - r * r) * bendDir;
+ a1 = ta - Math.atan2(y, r);
+ a2 = Math.atan2(y / psy, (r - l1) / psx);
+ break outer;
+ }
+ }
+ var minAngle = spine.MathUtils.PI, minX = l1 - a, minDist = minX * minX, minY = 0;
+ var maxAngle = 0, maxX = l1 + a, maxDist = maxX * maxX, maxY = 0;
+ c = -a * l1 / (aa - bb);
+ if (c >= -1 && c <= 1) {
+ c = Math.acos(c);
+ x = a * Math.cos(c) + l1;
+ y = b * Math.sin(c);
+ d = x * x + y * y;
+ if (d < minDist) {
+ minAngle = c;
+ minDist = d;
+ minX = x;
+ minY = y;
+ }
+ if (d > maxDist) {
+ maxAngle = c;
+ maxDist = d;
+ maxX = x;
+ maxY = y;
+ }
+ }
+ if (dd <= (minDist + maxDist) / 2) {
+ a1 = ta - Math.atan2(minY * bendDir, minX);
+ a2 = minAngle * bendDir;
+ }
+ else {
+ a1 = ta - Math.atan2(maxY * bendDir, maxX);
+ a2 = maxAngle * bendDir;
+ }
+ }
+ var os = Math.atan2(cy, cx) * s2;
+ var rotation = parent.arotation;
+ a1 = (a1 - os) * spine.MathUtils.radDeg + os1 - rotation;
+ if (a1 > 180)
+ a1 -= 360;
+ else if (a1 < -180)
+ a1 += 360;
+ parent.updateWorldTransformWith(px, py, rotation + a1 * alpha, parent.ascaleX, parent.ascaleY, 0, 0);
+ rotation = child.arotation;
+ a2 = ((a2 + os) * spine.MathUtils.radDeg - child.ashearX) * s2 + os2 - rotation;
+ if (a2 > 180)
+ a2 -= 360;
+ else if (a2 < -180)
+ a2 += 360;
+ child.updateWorldTransformWith(cx, cy, rotation + a2 * alpha, child.ascaleX, child.ascaleY, child.ashearX, child.ashearY);
+ };
+ return IkConstraint;
+ }());
+ spine.IkConstraint = IkConstraint;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var IkConstraintData = (function () {
+ function IkConstraintData(name) {
+ this.order = 0;
+ this.bones = new Array();
+ this.bendDirection = 1;
+ this.mix = 1;
+ this.name = name;
+ }
+ return IkConstraintData;
+ }());
+ spine.IkConstraintData = IkConstraintData;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var PathConstraint = (function () {
+ function PathConstraint(data, skeleton) {
+ this.position = 0;
+ this.spacing = 0;
+ this.rotateMix = 0;
+ this.translateMix = 0;
+ this.spaces = new Array();
+ this.positions = new Array();
+ this.world = new Array();
+ this.curves = new Array();
+ this.lengths = new Array();
+ this.segments = new Array();
+ if (data == null)
+ throw new Error("data cannot be null.");
+ if (skeleton == null)
+ throw new Error("skeleton cannot be null.");
+ this.data = data;
+ this.bones = new Array();
+ for (var i = 0, n = data.bones.length; i < n; i++)
+ this.bones.push(skeleton.findBone(data.bones[i].name));
+ this.target = skeleton.findSlot(data.target.name);
+ this.position = data.position;
+ this.spacing = data.spacing;
+ this.rotateMix = data.rotateMix;
+ this.translateMix = data.translateMix;
+ }
+ PathConstraint.prototype.apply = function () {
+ this.update();
+ };
+ PathConstraint.prototype.update = function () {
+ var attachment = this.target.getAttachment();
+ if (!(attachment instanceof spine.PathAttachment))
+ return;
+ var rotateMix = this.rotateMix, translateMix = this.translateMix;
+ var translate = translateMix > 0, rotate = rotateMix > 0;
+ if (!translate && !rotate)
+ return;
+ var data = this.data;
+ var spacingMode = data.spacingMode;
+ var lengthSpacing = spacingMode == spine.SpacingMode.Length;
+ var rotateMode = data.rotateMode;
+ var tangents = rotateMode == spine.RotateMode.Tangent, scale = rotateMode == spine.RotateMode.ChainScale;
+ var boneCount = this.bones.length, spacesCount = tangents ? boneCount : boneCount + 1;
+ var bones = this.bones;
+ var spaces = spine.Utils.setArraySize(this.spaces, spacesCount), lengths = null;
+ var spacing = this.spacing;
+ if (scale || lengthSpacing) {
+ if (scale)
+ lengths = spine.Utils.setArraySize(this.lengths, boneCount);
+ for (var i = 0, n = spacesCount - 1; i < n;) {
+ var bone = bones[i];
+ var setupLength = bone.data.length;
+ if (setupLength == 0)
+ setupLength = 0.0000001;
+ var x = setupLength * bone.a, y = setupLength * bone.c;
+ var length_1 = Math.sqrt(x * x + y * y);
+ if (scale)
+ lengths[i] = length_1;
+ spaces[++i] = (lengthSpacing ? setupLength + spacing : spacing) * length_1 / setupLength;
+ }
+ }
+ else {
+ for (var i = 1; i < spacesCount; i++)
+ spaces[i] = spacing;
+ }
+ var positions = this.computeWorldPositions(attachment, spacesCount, tangents, data.positionMode == spine.PositionMode.Percent, spacingMode == spine.SpacingMode.Percent);
+ var boneX = positions[0], boneY = positions[1], offsetRotation = data.offsetRotation;
+ var tip = false;
+ if (offsetRotation == 0)
+ tip = rotateMode == spine.RotateMode.Chain;
+ else {
+ tip = false;
+ var p = this.target.bone;
+ offsetRotation *= p.a * p.d - p.b * p.c > 0 ? spine.MathUtils.degRad : -spine.MathUtils.degRad;
+ }
+ for (var i = 0, p = 3; i < boneCount; i++, p += 3) {
+ var bone = bones[i];
+ bone.worldX += (boneX - bone.worldX) * translateMix;
+ bone.worldY += (boneY - bone.worldY) * translateMix;
+ var x = positions[p], y = positions[p + 1], dx = x - boneX, dy = y - boneY;
+ if (scale) {
+ var length_2 = lengths[i];
+ if (length_2 != 0) {
+ var s = (Math.sqrt(dx * dx + dy * dy) / length_2 - 1) * rotateMix + 1;
+ bone.a *= s;
+ bone.c *= s;
+ }
+ }
+ boneX = x;
+ boneY = y;
+ if (rotate) {
+ var a = bone.a, b = bone.b, c = bone.c, d = bone.d, r = 0, cos = 0, sin = 0;
+ if (tangents)
+ r = positions[p - 1];
+ else if (spaces[i + 1] == 0)
+ r = positions[p + 2];
+ else
+ r = Math.atan2(dy, dx);
+ r -= Math.atan2(c, a);
+ if (tip) {
+ cos = Math.cos(r);
+ sin = Math.sin(r);
+ var length_3 = bone.data.length;
+ boneX += (length_3 * (cos * a - sin * c) - dx) * rotateMix;
+ boneY += (length_3 * (sin * a + cos * c) - dy) * rotateMix;
+ }
+ else {
+ r += offsetRotation;
+ }
+ if (r > spine.MathUtils.PI)
+ r -= spine.MathUtils.PI2;
+ else if (r < -spine.MathUtils.PI)
+ r += spine.MathUtils.PI2;
+ r *= rotateMix;
+ cos = Math.cos(r);
+ sin = Math.sin(r);
+ bone.a = cos * a - sin * c;
+ bone.b = cos * b - sin * d;
+ bone.c = sin * a + cos * c;
+ bone.d = sin * b + cos * d;
+ }
+ bone.appliedValid = false;
+ }
+ };
+ PathConstraint.prototype.computeWorldPositions = function (path, spacesCount, tangents, percentPosition, percentSpacing) {
+ var target = this.target;
+ var position = this.position;
+ var spaces = this.spaces, out = spine.Utils.setArraySize(this.positions, spacesCount * 3 + 2), world = null;
+ var closed = path.closed;
+ var verticesLength = path.worldVerticesLength, curveCount = verticesLength / 6, prevCurve = PathConstraint.NONE;
+ if (!path.constantSpeed) {
+ var lengths = path.lengths;
+ curveCount -= closed ? 1 : 2;
+ var pathLength_1 = lengths[curveCount];
+ if (percentPosition)
+ position *= pathLength_1;
+ if (percentSpacing) {
+ for (var i = 0; i < spacesCount; i++)
+ spaces[i] *= pathLength_1;
+ }
+ world = spine.Utils.setArraySize(this.world, 8);
+ for (var i = 0, o = 0, curve = 0; i < spacesCount; i++, o += 3) {
+ var space = spaces[i];
+ position += space;
+ var p = position;
+ if (closed) {
+ p %= pathLength_1;
+ if (p < 0)
+ p += pathLength_1;
+ curve = 0;
+ }
+ else if (p < 0) {
+ if (prevCurve != PathConstraint.BEFORE) {
+ prevCurve = PathConstraint.BEFORE;
+ path.computeWorldVertices(target, 2, 4, world, 0, 2);
+ }
+ this.addBeforePosition(p, world, 0, out, o);
+ continue;
+ }
+ else if (p > pathLength_1) {
+ if (prevCurve != PathConstraint.AFTER) {
+ prevCurve = PathConstraint.AFTER;
+ path.computeWorldVertices(target, verticesLength - 6, 4, world, 0, 2);
+ }
+ this.addAfterPosition(p - pathLength_1, world, 0, out, o);
+ continue;
+ }
+ for (;; curve++) {
+ var length_4 = lengths[curve];
+ if (p > length_4)
+ continue;
+ if (curve == 0)
+ p /= length_4;
+ else {
+ var prev = lengths[curve - 1];
+ p = (p - prev) / (length_4 - prev);
+ }
+ break;
+ }
+ if (curve != prevCurve) {
+ prevCurve = curve;
+ if (closed && curve == curveCount) {
+ path.computeWorldVertices(target, verticesLength - 4, 4, world, 0, 2);
+ path.computeWorldVertices(target, 0, 4, world, 4, 2);
+ }
+ else
+ path.computeWorldVertices(target, curve * 6 + 2, 8, world, 0, 2);
+ }
+ this.addCurvePosition(p, world[0], world[1], world[2], world[3], world[4], world[5], world[6], world[7], out, o, tangents || (i > 0 && space == 0));
+ }
+ return out;
+ }
+ if (closed) {
+ verticesLength += 2;
+ world = spine.Utils.setArraySize(this.world, verticesLength);
+ path.computeWorldVertices(target, 2, verticesLength - 4, world, 0, 2);
+ path.computeWorldVertices(target, 0, 2, world, verticesLength - 4, 2);
+ world[verticesLength - 2] = world[0];
+ world[verticesLength - 1] = world[1];
+ }
+ else {
+ curveCount--;
+ verticesLength -= 4;
+ world = spine.Utils.setArraySize(this.world, verticesLength);
+ path.computeWorldVertices(target, 2, verticesLength, world, 0, 2);
+ }
+ var curves = spine.Utils.setArraySize(this.curves, curveCount);
+ var pathLength = 0;
+ var x1 = world[0], y1 = world[1], cx1 = 0, cy1 = 0, cx2 = 0, cy2 = 0, x2 = 0, y2 = 0;
+ var tmpx = 0, tmpy = 0, dddfx = 0, dddfy = 0, ddfx = 0, ddfy = 0, dfx = 0, dfy = 0;
+ for (var i = 0, w = 2; i < curveCount; i++, w += 6) {
+ cx1 = world[w];
+ cy1 = world[w + 1];
+ cx2 = world[w + 2];
+ cy2 = world[w + 3];
+ x2 = world[w + 4];
+ y2 = world[w + 5];
+ tmpx = (x1 - cx1 * 2 + cx2) * 0.1875;
+ tmpy = (y1 - cy1 * 2 + cy2) * 0.1875;
+ dddfx = ((cx1 - cx2) * 3 - x1 + x2) * 0.09375;
+ dddfy = ((cy1 - cy2) * 3 - y1 + y2) * 0.09375;
+ ddfx = tmpx * 2 + dddfx;
+ ddfy = tmpy * 2 + dddfy;
+ dfx = (cx1 - x1) * 0.75 + tmpx + dddfx * 0.16666667;
+ dfy = (cy1 - y1) * 0.75 + tmpy + dddfy * 0.16666667;
+ pathLength += Math.sqrt(dfx * dfx + dfy * dfy);
+ dfx += ddfx;
+ dfy += ddfy;
+ ddfx += dddfx;
+ ddfy += dddfy;
+ pathLength += Math.sqrt(dfx * dfx + dfy * dfy);
+ dfx += ddfx;
+ dfy += ddfy;
+ pathLength += Math.sqrt(dfx * dfx + dfy * dfy);
+ dfx += ddfx + dddfx;
+ dfy += ddfy + dddfy;
+ pathLength += Math.sqrt(dfx * dfx + dfy * dfy);
+ curves[i] = pathLength;
+ x1 = x2;
+ y1 = y2;
+ }
+ if (percentPosition)
+ position *= pathLength;
+ if (percentSpacing) {
+ for (var i = 0; i < spacesCount; i++)
+ spaces[i] *= pathLength;
+ }
+ var segments = this.segments;
+ var curveLength = 0;
+ for (var i = 0, o = 0, curve = 0, segment = 0; i < spacesCount; i++, o += 3) {
+ var space = spaces[i];
+ position += space;
+ var p = position;
+ if (closed) {
+ p %= pathLength;
+ if (p < 0)
+ p += pathLength;
+ curve = 0;
+ }
+ else if (p < 0) {
+ this.addBeforePosition(p, world, 0, out, o);
+ continue;
+ }
+ else if (p > pathLength) {
+ this.addAfterPosition(p - pathLength, world, verticesLength - 4, out, o);
+ continue;
+ }
+ for (;; curve++) {
+ var length_5 = curves[curve];
+ if (p > length_5)
+ continue;
+ if (curve == 0)
+ p /= length_5;
+ else {
+ var prev = curves[curve - 1];
+ p = (p - prev) / (length_5 - prev);
+ }
+ break;
+ }
+ if (curve != prevCurve) {
+ prevCurve = curve;
+ var ii = curve * 6;
+ x1 = world[ii];
+ y1 = world[ii + 1];
+ cx1 = world[ii + 2];
+ cy1 = world[ii + 3];
+ cx2 = world[ii + 4];
+ cy2 = world[ii + 5];
+ x2 = world[ii + 6];
+ y2 = world[ii + 7];
+ tmpx = (x1 - cx1 * 2 + cx2) * 0.03;
+ tmpy = (y1 - cy1 * 2 + cy2) * 0.03;
+ dddfx = ((cx1 - cx2) * 3 - x1 + x2) * 0.006;
+ dddfy = ((cy1 - cy2) * 3 - y1 + y2) * 0.006;
+ ddfx = tmpx * 2 + dddfx;
+ ddfy = tmpy * 2 + dddfy;
+ dfx = (cx1 - x1) * 0.3 + tmpx + dddfx * 0.16666667;
+ dfy = (cy1 - y1) * 0.3 + tmpy + dddfy * 0.16666667;
+ curveLength = Math.sqrt(dfx * dfx + dfy * dfy);
+ segments[0] = curveLength;
+ for (ii = 1; ii < 8; ii++) {
+ dfx += ddfx;
+ dfy += ddfy;
+ ddfx += dddfx;
+ ddfy += dddfy;
+ curveLength += Math.sqrt(dfx * dfx + dfy * dfy);
+ segments[ii] = curveLength;
+ }
+ dfx += ddfx;
+ dfy += ddfy;
+ curveLength += Math.sqrt(dfx * dfx + dfy * dfy);
+ segments[8] = curveLength;
+ dfx += ddfx + dddfx;
+ dfy += ddfy + dddfy;
+ curveLength += Math.sqrt(dfx * dfx + dfy * dfy);
+ segments[9] = curveLength;
+ segment = 0;
+ }
+ p *= curveLength;
+ for (;; segment++) {
+ var length_6 = segments[segment];
+ if (p > length_6)
+ continue;
+ if (segment == 0)
+ p /= length_6;
+ else {
+ var prev = segments[segment - 1];
+ p = segment + (p - prev) / (length_6 - prev);
+ }
+ break;
+ }
+ this.addCurvePosition(p * 0.1, x1, y1, cx1, cy1, cx2, cy2, x2, y2, out, o, tangents || (i > 0 && space == 0));
+ }
+ return out;
+ };
+ PathConstraint.prototype.addBeforePosition = function (p, temp, i, out, o) {
+ var x1 = temp[i], y1 = temp[i + 1], dx = temp[i + 2] - x1, dy = temp[i + 3] - y1, r = Math.atan2(dy, dx);
+ out[o] = x1 + p * Math.cos(r);
+ out[o + 1] = y1 + p * Math.sin(r);
+ out[o + 2] = r;
+ };
+ PathConstraint.prototype.addAfterPosition = function (p, temp, i, out, o) {
+ var x1 = temp[i + 2], y1 = temp[i + 3], dx = x1 - temp[i], dy = y1 - temp[i + 1], r = Math.atan2(dy, dx);
+ out[o] = x1 + p * Math.cos(r);
+ out[o + 1] = y1 + p * Math.sin(r);
+ out[o + 2] = r;
+ };
+ PathConstraint.prototype.addCurvePosition = function (p, x1, y1, cx1, cy1, cx2, cy2, x2, y2, out, o, tangents) {
+ if (p == 0 || isNaN(p))
+ p = 0.0001;
+ var tt = p * p, ttt = tt * p, u = 1 - p, uu = u * u, uuu = uu * u;
+ var ut = u * p, ut3 = ut * 3, uut3 = u * ut3, utt3 = ut3 * p;
+ var x = x1 * uuu + cx1 * uut3 + cx2 * utt3 + x2 * ttt, y = y1 * uuu + cy1 * uut3 + cy2 * utt3 + y2 * ttt;
+ out[o] = x;
+ out[o + 1] = y;
+ if (tangents)
+ out[o + 2] = Math.atan2(y - (y1 * uu + cy1 * ut * 2 + cy2 * tt), x - (x1 * uu + cx1 * ut * 2 + cx2 * tt));
+ };
+ PathConstraint.prototype.getOrder = function () {
+ return this.data.order;
+ };
+ return PathConstraint;
+ }());
+ PathConstraint.NONE = -1;
+ PathConstraint.BEFORE = -2;
+ PathConstraint.AFTER = -3;
+ spine.PathConstraint = PathConstraint;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var PathConstraintData = (function () {
+ function PathConstraintData(name) {
+ this.order = 0;
+ this.bones = new Array();
+ this.name = name;
+ }
+ return PathConstraintData;
+ }());
+ spine.PathConstraintData = PathConstraintData;
+ var PositionMode;
+ (function (PositionMode) {
+ PositionMode[PositionMode["Fixed"] = 0] = "Fixed";
+ PositionMode[PositionMode["Percent"] = 1] = "Percent";
+ })(PositionMode = spine.PositionMode || (spine.PositionMode = {}));
+ var SpacingMode;
+ (function (SpacingMode) {
+ SpacingMode[SpacingMode["Length"] = 0] = "Length";
+ SpacingMode[SpacingMode["Fixed"] = 1] = "Fixed";
+ SpacingMode[SpacingMode["Percent"] = 2] = "Percent";
+ })(SpacingMode = spine.SpacingMode || (spine.SpacingMode = {}));
+ var RotateMode;
+ (function (RotateMode) {
+ RotateMode[RotateMode["Tangent"] = 0] = "Tangent";
+ RotateMode[RotateMode["Chain"] = 1] = "Chain";
+ RotateMode[RotateMode["ChainScale"] = 2] = "ChainScale";
+ })(RotateMode = spine.RotateMode || (spine.RotateMode = {}));
+})(spine || (spine = {}));
+(function () {
+ if (!Math.fround) {
+ Math.fround = (function (array) {
+ return function (x) {
+ return array[0] = x, array[0];
+ };
+ })(new Float32Array(1));
+ }
+})();
+var spine;
+(function (spine) {
+ var Assets = (function () {
+ function Assets(clientId) {
+ this.toLoad = new Array();
+ this.assets = {};
+ this.clientId = clientId;
+ }
+ Assets.prototype.loaded = function () {
+ var i = 0;
+ for (var v in this.assets)
+ i++;
+ return i;
+ };
+ return Assets;
+ }());
+ var SharedAssetManager = (function () {
+ function SharedAssetManager(pathPrefix) {
+ if (pathPrefix === void 0) { pathPrefix = ""; }
+ this.clientAssets = {};
+ this.queuedAssets = {};
+ this.rawAssets = {};
+ this.errors = {};
+ this.pathPrefix = pathPrefix;
+ }
+ SharedAssetManager.prototype.queueAsset = function (clientId, textureLoader, path) {
+ var clientAssets = this.clientAssets[clientId];
+ if (clientAssets === null || clientAssets === undefined) {
+ clientAssets = new Assets(clientId);
+ this.clientAssets[clientId] = clientAssets;
+ }
+ if (textureLoader !== null)
+ clientAssets.textureLoader = textureLoader;
+ clientAssets.toLoad.push(path);
+ if (this.queuedAssets[path] === path) {
+ return false;
+ }
+ else {
+ this.queuedAssets[path] = path;
+ return true;
+ }
+ };
+ SharedAssetManager.prototype.loadText = function (clientId, path) {
+ var _this = this;
+ path = this.pathPrefix + path;
+ if (!this.queueAsset(clientId, null, path))
+ return;
+ var request = new XMLHttpRequest();
+ request.onreadystatechange = function () {
+ if (request.readyState == XMLHttpRequest.DONE) {
+ if (request.status >= 200 && request.status < 300) {
+ _this.rawAssets[path] = request.responseText;
+ }
+ else {
+ _this.errors[path] = "Couldn't load text " + path + ": status " + request.status + ", " + request.responseText;
+ }
+ }
+ };
+ request.open("GET", path, true);
+ request.send();
+ };
+ SharedAssetManager.prototype.loadJson = function (clientId, path) {
+ var _this = this;
+ path = this.pathPrefix + path;
+ if (!this.queueAsset(clientId, null, path))
+ return;
+ var request = new XMLHttpRequest();
+ request.onreadystatechange = function () {
+ if (request.readyState == XMLHttpRequest.DONE) {
+ if (request.status >= 200 && request.status < 300) {
+ _this.rawAssets[path] = JSON.parse(request.responseText);
+ }
+ else {
+ _this.errors[path] = "Couldn't load text " + path + ": status " + request.status + ", " + request.responseText;
+ }
+ }
+ };
+ request.open("GET", path, true);
+ request.send();
+ };
+ SharedAssetManager.prototype.loadTexture = function (clientId, textureLoader, path) {
+ var _this = this;
+ path = this.pathPrefix + path;
+ if (!this.queueAsset(clientId, textureLoader, path))
+ return;
+ var img = new Image();
+ img.src = path;
+ img.crossOrigin = "anonymous";
+ img.onload = function (ev) {
+ _this.rawAssets[path] = img;
+ };
+ img.onerror = function (ev) {
+ _this.errors[path] = "Couldn't load image " + path;
+ };
+ };
+ SharedAssetManager.prototype.get = function (clientId, path) {
+ path = this.pathPrefix + path;
+ var clientAssets = this.clientAssets[clientId];
+ if (clientAssets === null || clientAssets === undefined)
+ return true;
+ return clientAssets.assets[path];
+ };
+ SharedAssetManager.prototype.updateClientAssets = function (clientAssets) {
+ for (var i = 0; i < clientAssets.toLoad.length; i++) {
+ var path = clientAssets.toLoad[i];
+ var asset = clientAssets.assets[path];
+ if (asset === null || asset === undefined) {
+ var rawAsset = this.rawAssets[path];
+ if (rawAsset === null || rawAsset === undefined)
+ continue;
+ if (rawAsset instanceof HTMLImageElement) {
+ clientAssets.assets[path] = clientAssets.textureLoader(rawAsset);
+ }
+ else {
+ clientAssets.assets[path] = rawAsset;
+ }
+ }
+ }
+ };
+ SharedAssetManager.prototype.isLoadingComplete = function (clientId) {
+ var clientAssets = this.clientAssets[clientId];
+ if (clientAssets === null || clientAssets === undefined)
+ return true;
+ this.updateClientAssets(clientAssets);
+ return clientAssets.toLoad.length == clientAssets.loaded();
+ };
+ SharedAssetManager.prototype.dispose = function () {
+ };
+ SharedAssetManager.prototype.hasErrors = function () {
+ return Object.keys(this.errors).length > 0;
+ };
+ SharedAssetManager.prototype.getErrors = function () {
+ return this.errors;
+ };
+ return SharedAssetManager;
+ }());
+ spine.SharedAssetManager = SharedAssetManager;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var Skeleton = (function () {
+ function Skeleton(data) {
+ this._updateCache = new Array();
+ this.updateCacheReset = new Array();
+ this.time = 0;
+ this.flipX = false;
+ this.flipY = false;
+ this.x = 0;
+ this.y = 0;
+ if (data == null)
+ throw new Error("data cannot be null.");
+ this.data = data;
+ this.bones = new Array();
+ for (var i = 0; i < data.bones.length; i++) {
+ var boneData = data.bones[i];
+ var bone = void 0;
+ if (boneData.parent == null)
+ bone = new spine.Bone(boneData, this, null);
+ else {
+ var parent_1 = this.bones[boneData.parent.index];
+ bone = new spine.Bone(boneData, this, parent_1);
+ parent_1.children.push(bone);
+ }
+ this.bones.push(bone);
+ }
+ this.slots = new Array();
+ this.drawOrder = new Array();
+ for (var i = 0; i < data.slots.length; i++) {
+ var slotData = data.slots[i];
+ var bone = this.bones[slotData.boneData.index];
+ var slot = new spine.Slot(slotData, bone);
+ this.slots.push(slot);
+ this.drawOrder.push(slot);
+ }
+ this.ikConstraints = new Array();
+ for (var i = 0; i < data.ikConstraints.length; i++) {
+ var ikConstraintData = data.ikConstraints[i];
+ this.ikConstraints.push(new spine.IkConstraint(ikConstraintData, this));
+ }
+ this.transformConstraints = new Array();
+ for (var i = 0; i < data.transformConstraints.length; i++) {
+ var transformConstraintData = data.transformConstraints[i];
+ this.transformConstraints.push(new spine.TransformConstraint(transformConstraintData, this));
+ }
+ this.pathConstraints = new Array();
+ for (var i = 0; i < data.pathConstraints.length; i++) {
+ var pathConstraintData = data.pathConstraints[i];
+ this.pathConstraints.push(new spine.PathConstraint(pathConstraintData, this));
+ }
+ this.color = new spine.Color(1, 1, 1, 1);
+ this.updateCache();
+ }
+ Skeleton.prototype.updateCache = function () {
+ var updateCache = this._updateCache;
+ updateCache.length = 0;
+ this.updateCacheReset.length = 0;
+ var bones = this.bones;
+ for (var i = 0, n = bones.length; i < n; i++)
+ bones[i].sorted = false;
+ var ikConstraints = this.ikConstraints;
+ var transformConstraints = this.transformConstraints;
+ var pathConstraints = this.pathConstraints;
+ var ikCount = ikConstraints.length, transformCount = transformConstraints.length, pathCount = pathConstraints.length;
+ var constraintCount = ikCount + transformCount + pathCount;
+ outer: for (var i = 0; i < constraintCount; i++) {
+ for (var ii = 0; ii < ikCount; ii++) {
+ var constraint = ikConstraints[ii];
+ if (constraint.data.order == i) {
+ this.sortIkConstraint(constraint);
+ continue outer;
+ }
+ }
+ for (var ii = 0; ii < transformCount; ii++) {
+ var constraint = transformConstraints[ii];
+ if (constraint.data.order == i) {
+ this.sortTransformConstraint(constraint);
+ continue outer;
+ }
+ }
+ for (var ii = 0; ii < pathCount; ii++) {
+ var constraint = pathConstraints[ii];
+ if (constraint.data.order == i) {
+ this.sortPathConstraint(constraint);
+ continue outer;
+ }
+ }
+ }
+ for (var i = 0, n = bones.length; i < n; i++)
+ this.sortBone(bones[i]);
+ };
+ Skeleton.prototype.sortIkConstraint = function (constraint) {
+ var target = constraint.target;
+ this.sortBone(target);
+ var constrained = constraint.bones;
+ var parent = constrained[0];
+ this.sortBone(parent);
+ if (constrained.length > 1) {
+ var child = constrained[constrained.length - 1];
+ if (!(this._updateCache.indexOf(child) > -1))
+ this.updateCacheReset.push(child);
+ }
+ this._updateCache.push(constraint);
+ this.sortReset(parent.children);
+ constrained[constrained.length - 1].sorted = true;
+ };
+ Skeleton.prototype.sortPathConstraint = function (constraint) {
+ var slot = constraint.target;
+ var slotIndex = slot.data.index;
+ var slotBone = slot.bone;
+ if (this.skin != null)
+ this.sortPathConstraintAttachment(this.skin, slotIndex, slotBone);
+ if (this.data.defaultSkin != null && this.data.defaultSkin != this.skin)
+ this.sortPathConstraintAttachment(this.data.defaultSkin, slotIndex, slotBone);
+ for (var i = 0, n = this.data.skins.length; i < n; i++)
+ this.sortPathConstraintAttachment(this.data.skins[i], slotIndex, slotBone);
+ var attachment = slot.getAttachment();
+ if (attachment instanceof spine.PathAttachment)
+ this.sortPathConstraintAttachmentWith(attachment, slotBone);
+ var constrained = constraint.bones;
+ var boneCount = constrained.length;
+ for (var i = 0; i < boneCount; i++)
+ this.sortBone(constrained[i]);
+ this._updateCache.push(constraint);
+ for (var i = 0; i < boneCount; i++)
+ this.sortReset(constrained[i].children);
+ for (var i = 0; i < boneCount; i++)
+ constrained[i].sorted = true;
+ };
+ Skeleton.prototype.sortTransformConstraint = function (constraint) {
+ this.sortBone(constraint.target);
+ var constrained = constraint.bones;
+ var boneCount = constrained.length;
+ if (constraint.data.local) {
+ for (var i = 0; i < boneCount; i++) {
+ var child = constrained[i];
+ this.sortBone(child.parent);
+ if (!(this._updateCache.indexOf(child) > -1))
+ this.updateCacheReset.push(child);
+ }
+ }
+ else {
+ for (var i = 0; i < boneCount; i++) {
+ this.sortBone(constrained[i]);
+ }
+ }
+ this._updateCache.push(constraint);
+ for (var ii = 0; ii < boneCount; ii++)
+ this.sortReset(constrained[ii].children);
+ for (var ii = 0; ii < boneCount; ii++)
+ constrained[ii].sorted = true;
+ };
+ Skeleton.prototype.sortPathConstraintAttachment = function (skin, slotIndex, slotBone) {
+ var attachments = skin.attachments[slotIndex];
+ if (!attachments)
+ return;
+ for (var key in attachments) {
+ this.sortPathConstraintAttachmentWith(attachments[key], slotBone);
+ }
+ };
+ Skeleton.prototype.sortPathConstraintAttachmentWith = function (attachment, slotBone) {
+ if (!(attachment instanceof spine.PathAttachment))
+ return;
+ var pathBones = attachment.bones;
+ if (pathBones == null)
+ this.sortBone(slotBone);
+ else {
+ var bones = this.bones;
+ var i = 0;
+ while (i < pathBones.length) {
+ var boneCount = pathBones[i++];
+ for (var n = i + boneCount; i < n; i++) {
+ var boneIndex = pathBones[i];
+ this.sortBone(bones[boneIndex]);
+ }
+ }
+ }
+ };
+ Skeleton.prototype.sortBone = function (bone) {
+ if (bone.sorted)
+ return;
+ var parent = bone.parent;
+ if (parent != null)
+ this.sortBone(parent);
+ bone.sorted = true;
+ this._updateCache.push(bone);
+ };
+ Skeleton.prototype.sortReset = function (bones) {
+ for (var i = 0, n = bones.length; i < n; i++) {
+ var bone = bones[i];
+ if (bone.sorted)
+ this.sortReset(bone.children);
+ bone.sorted = false;
+ }
+ };
+ Skeleton.prototype.updateWorldTransform = function () {
+ var updateCacheReset = this.updateCacheReset;
+ for (var i = 0, n = updateCacheReset.length; i < n; i++) {
+ var bone = updateCacheReset[i];
+ bone.ax = bone.x;
+ bone.ay = bone.y;
+ bone.arotation = bone.rotation;
+ bone.ascaleX = bone.scaleX;
+ bone.ascaleY = bone.scaleY;
+ bone.ashearX = bone.shearX;
+ bone.ashearY = bone.shearY;
+ bone.appliedValid = true;
+ }
+ var updateCache = this._updateCache;
+ for (var i = 0, n = updateCache.length; i < n; i++)
+ updateCache[i].update();
+ };
+ Skeleton.prototype.setToSetupPose = function () {
+ this.setBonesToSetupPose();
+ this.setSlotsToSetupPose();
+ };
+ Skeleton.prototype.setBonesToSetupPose = function () {
+ var bones = this.bones;
+ for (var i = 0, n = bones.length; i < n; i++)
+ bones[i].setToSetupPose();
+ var ikConstraints = this.ikConstraints;
+ for (var i = 0, n = ikConstraints.length; i < n; i++) {
+ var constraint = ikConstraints[i];
+ constraint.bendDirection = constraint.data.bendDirection;
+ constraint.mix = constraint.data.mix;
+ }
+ var transformConstraints = this.transformConstraints;
+ for (var i = 0, n = transformConstraints.length; i < n; i++) {
+ var constraint = transformConstraints[i];
+ var data = constraint.data;
+ constraint.rotateMix = data.rotateMix;
+ constraint.translateMix = data.translateMix;
+ constraint.scaleMix = data.scaleMix;
+ constraint.shearMix = data.shearMix;
+ }
+ var pathConstraints = this.pathConstraints;
+ for (var i = 0, n = pathConstraints.length; i < n; i++) {
+ var constraint = pathConstraints[i];
+ var data = constraint.data;
+ constraint.position = data.position;
+ constraint.spacing = data.spacing;
+ constraint.rotateMix = data.rotateMix;
+ constraint.translateMix = data.translateMix;
+ }
+ };
+ Skeleton.prototype.setSlotsToSetupPose = function () {
+ var slots = this.slots;
+ spine.Utils.arrayCopy(slots, 0, this.drawOrder, 0, slots.length);
+ for (var i = 0, n = slots.length; i < n; i++)
+ slots[i].setToSetupPose();
+ };
+ Skeleton.prototype.getRootBone = function () {
+ if (this.bones.length == 0)
+ return null;
+ return this.bones[0];
+ };
+ Skeleton.prototype.findBone = function (boneName) {
+ if (boneName == null)
+ throw new Error("boneName cannot be null.");
+ var bones = this.bones;
+ for (var i = 0, n = bones.length; i < n; i++) {
+ var bone = bones[i];
+ if (bone.data.name == boneName)
+ return bone;
+ }
+ return null;
+ };
+ Skeleton.prototype.findBoneIndex = function (boneName) {
+ if (boneName == null)
+ throw new Error("boneName cannot be null.");
+ var bones = this.bones;
+ for (var i = 0, n = bones.length; i < n; i++)
+ if (bones[i].data.name == boneName)
+ return i;
+ return -1;
+ };
+ Skeleton.prototype.findSlot = function (slotName) {
+ if (slotName == null)
+ throw new Error("slotName cannot be null.");
+ var slots = this.slots;
+ for (var i = 0, n = slots.length; i < n; i++) {
+ var slot = slots[i];
+ if (slot.data.name == slotName)
+ return slot;
+ }
+ return null;
+ };
+ Skeleton.prototype.findSlotIndex = function (slotName) {
+ if (slotName == null)
+ throw new Error("slotName cannot be null.");
+ var slots = this.slots;
+ for (var i = 0, n = slots.length; i < n; i++)
+ if (slots[i].data.name == slotName)
+ return i;
+ return -1;
+ };
+ Skeleton.prototype.setSkinByName = function (skinName) {
+ var skin = this.data.findSkin(skinName);
+ if (skin == null)
+ throw new Error("Skin not found: " + skinName);
+ this.setSkin(skin);
+ };
+ Skeleton.prototype.setSkin = function (newSkin) {
+ if (newSkin != null) {
+ if (this.skin != null)
+ newSkin.attachAll(this, this.skin);
+ else {
+ var slots = this.slots;
+ for (var i = 0, n = slots.length; i < n; i++) {
+ var slot = slots[i];
+ var name_1 = slot.data.attachmentName;
+ if (name_1 != null) {
+ var attachment = newSkin.getAttachment(i, name_1);
+ if (attachment != null)
+ slot.setAttachment(attachment);
+ }
+ }
+ }
+ }
+ this.skin = newSkin;
+ };
+ Skeleton.prototype.getAttachmentByName = function (slotName, attachmentName) {
+ return this.getAttachment(this.data.findSlotIndex(slotName), attachmentName);
+ };
+ Skeleton.prototype.getAttachment = function (slotIndex, attachmentName) {
+ if (attachmentName == null)
+ throw new Error("attachmentName cannot be null.");
+ if (this.skin != null) {
+ var attachment = this.skin.getAttachment(slotIndex, attachmentName);
+ if (attachment != null)
+ return attachment;
+ }
+ if (this.data.defaultSkin != null)
+ return this.data.defaultSkin.getAttachment(slotIndex, attachmentName);
+ return null;
+ };
+ Skeleton.prototype.setAttachment = function (slotName, attachmentName) {
+ if (slotName == null)
+ throw new Error("slotName cannot be null.");
+ var slots = this.slots;
+ for (var i = 0, n = slots.length; i < n; i++) {
+ var slot = slots[i];
+ if (slot.data.name == slotName) {
+ var attachment = null;
+ if (attachmentName != null) {
+ attachment = this.getAttachment(i, attachmentName);
+ if (attachment == null)
+ throw new Error("Attachment not found: " + attachmentName + ", for slot: " + slotName);
+ }
+ slot.setAttachment(attachment);
+ return;
+ }
+ }
+ throw new Error("Slot not found: " + slotName);
+ };
+ Skeleton.prototype.findIkConstraint = function (constraintName) {
+ if (constraintName == null)
+ throw new Error("constraintName cannot be null.");
+ var ikConstraints = this.ikConstraints;
+ for (var i = 0, n = ikConstraints.length; i < n; i++) {
+ var ikConstraint = ikConstraints[i];
+ if (ikConstraint.data.name == constraintName)
+ return ikConstraint;
+ }
+ return null;
+ };
+ Skeleton.prototype.findTransformConstraint = function (constraintName) {
+ if (constraintName == null)
+ throw new Error("constraintName cannot be null.");
+ var transformConstraints = this.transformConstraints;
+ for (var i = 0, n = transformConstraints.length; i < n; i++) {
+ var constraint = transformConstraints[i];
+ if (constraint.data.name == constraintName)
+ return constraint;
+ }
+ return null;
+ };
+ Skeleton.prototype.findPathConstraint = function (constraintName) {
+ if (constraintName == null)
+ throw new Error("constraintName cannot be null.");
+ var pathConstraints = this.pathConstraints;
+ for (var i = 0, n = pathConstraints.length; i < n; i++) {
+ var constraint = pathConstraints[i];
+ if (constraint.data.name == constraintName)
+ return constraint;
+ }
+ return null;
+ };
+ Skeleton.prototype.getBounds = function (offset, size, temp) {
+ if (offset == null)
+ throw new Error("offset cannot be null.");
+ if (size == null)
+ throw new Error("size cannot be null.");
+ var drawOrder = this.drawOrder;
+ var minX = Number.POSITIVE_INFINITY, minY = Number.POSITIVE_INFINITY, maxX = Number.NEGATIVE_INFINITY, maxY = Number.NEGATIVE_INFINITY;
+ for (var i = 0, n = drawOrder.length; i < n; i++) {
+ var slot = drawOrder[i];
+ var verticesLength = 0;
+ var vertices = null;
+ var attachment = slot.getAttachment();
+ if (attachment instanceof spine.RegionAttachment) {
+ verticesLength = 8;
+ vertices = spine.Utils.setArraySize(temp, verticesLength, 0);
+ attachment.computeWorldVertices(slot.bone, vertices, 0, 2);
+ }
+ else if (attachment instanceof spine.MeshAttachment) {
+ var mesh = attachment;
+ verticesLength = mesh.worldVerticesLength;
+ vertices = spine.Utils.setArraySize(temp, verticesLength, 0);
+ mesh.computeWorldVertices(slot, 0, verticesLength, vertices, 0, 2);
+ }
+ if (vertices != null) {
+ for (var ii = 0, nn = vertices.length; ii < nn; ii += 2) {
+ var x = vertices[ii], y = vertices[ii + 1];
+ minX = Math.min(minX, x);
+ minY = Math.min(minY, y);
+ maxX = Math.max(maxX, x);
+ maxY = Math.max(maxY, y);
+ }
+ }
+ }
+ offset.set(minX, minY);
+ size.set(maxX - minX, maxY - minY);
+ };
+ Skeleton.prototype.update = function (delta) {
+ this.time += delta;
+ };
+ return Skeleton;
+ }());
+ spine.Skeleton = Skeleton;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var SkeletonBounds = (function () {
+ function SkeletonBounds() {
+ this.minX = 0;
+ this.minY = 0;
+ this.maxX = 0;
+ this.maxY = 0;
+ this.boundingBoxes = new Array();
+ this.polygons = new Array();
+ this.polygonPool = new spine.Pool(function () {
+ return spine.Utils.newFloatArray(16);
+ });
+ }
+ SkeletonBounds.prototype.update = function (skeleton, updateAabb) {
+ if (skeleton == null)
+ throw new Error("skeleton cannot be null.");
+ var boundingBoxes = this.boundingBoxes;
+ var polygons = this.polygons;
+ var polygonPool = this.polygonPool;
+ var slots = skeleton.slots;
+ var slotCount = slots.length;
+ boundingBoxes.length = 0;
+ polygonPool.freeAll(polygons);
+ polygons.length = 0;
+ for (var i = 0; i < slotCount; i++) {
+ var slot = slots[i];
+ var attachment = slot.getAttachment();
+ if (attachment instanceof spine.BoundingBoxAttachment) {
+ var boundingBox = attachment;
+ boundingBoxes.push(boundingBox);
+ var polygon = polygonPool.obtain();
+ if (polygon.length != boundingBox.worldVerticesLength) {
+ polygon = spine.Utils.newFloatArray(boundingBox.worldVerticesLength);
+ }
+ polygons.push(polygon);
+ boundingBox.computeWorldVertices(slot, 0, boundingBox.worldVerticesLength, polygon, 0, 2);
+ }
+ }
+ if (updateAabb) {
+ this.aabbCompute();
+ }
+ else {
+ this.minX = Number.POSITIVE_INFINITY;
+ this.minY = Number.POSITIVE_INFINITY;
+ this.maxX = Number.NEGATIVE_INFINITY;
+ this.maxY = Number.NEGATIVE_INFINITY;
+ }
+ };
+ SkeletonBounds.prototype.aabbCompute = function () {
+ var minX = Number.POSITIVE_INFINITY, minY = Number.POSITIVE_INFINITY, maxX = Number.NEGATIVE_INFINITY, maxY = Number.NEGATIVE_INFINITY;
+ var polygons = this.polygons;
+ for (var i = 0, n = polygons.length; i < n; i++) {
+ var polygon = polygons[i];
+ var vertices = polygon;
+ for (var ii = 0, nn = polygon.length; ii < nn; ii += 2) {
+ var x = vertices[ii];
+ var y = vertices[ii + 1];
+ minX = Math.min(minX, x);
+ minY = Math.min(minY, y);
+ maxX = Math.max(maxX, x);
+ maxY = Math.max(maxY, y);
+ }
+ }
+ this.minX = minX;
+ this.minY = minY;
+ this.maxX = maxX;
+ this.maxY = maxY;
+ };
+ SkeletonBounds.prototype.aabbContainsPoint = function (x, y) {
+ return x >= this.minX && x <= this.maxX && y >= this.minY && y <= this.maxY;
+ };
+ SkeletonBounds.prototype.aabbIntersectsSegment = function (x1, y1, x2, y2) {
+ var minX = this.minX;
+ var minY = this.minY;
+ var maxX = this.maxX;
+ var maxY = this.maxY;
+ if ((x1 <= minX && x2 <= minX) || (y1 <= minY && y2 <= minY) || (x1 >= maxX && x2 >= maxX) || (y1 >= maxY && y2 >= maxY))
+ return false;
+ var m = (y2 - y1) / (x2 - x1);
+ var y = m * (minX - x1) + y1;
+ if (y > minY && y < maxY)
+ return true;
+ y = m * (maxX - x1) + y1;
+ if (y > minY && y < maxY)
+ return true;
+ var x = (minY - y1) / m + x1;
+ if (x > minX && x < maxX)
+ return true;
+ x = (maxY - y1) / m + x1;
+ if (x > minX && x < maxX)
+ return true;
+ return false;
+ };
+ SkeletonBounds.prototype.aabbIntersectsSkeleton = function (bounds) {
+ return this.minX < bounds.maxX && this.maxX > bounds.minX && this.minY < bounds.maxY && this.maxY > bounds.minY;
+ };
+ SkeletonBounds.prototype.containsPoint = function (x, y) {
+ var polygons = this.polygons;
+ for (var i = 0, n = polygons.length; i < n; i++)
+ if (this.containsPointPolygon(polygons[i], x, y))
+ return this.boundingBoxes[i];
+ return null;
+ };
+ SkeletonBounds.prototype.containsPointPolygon = function (polygon, x, y) {
+ var vertices = polygon;
+ var nn = polygon.length;
+ var prevIndex = nn - 2;
+ var inside = false;
+ for (var ii = 0; ii < nn; ii += 2) {
+ var vertexY = vertices[ii + 1];
+ var prevY = vertices[prevIndex + 1];
+ if ((vertexY < y && prevY >= y) || (prevY < y && vertexY >= y)) {
+ var vertexX = vertices[ii];
+ if (vertexX + (y - vertexY) / (prevY - vertexY) * (vertices[prevIndex] - vertexX) < x)
+ inside = !inside;
+ }
+ prevIndex = ii;
+ }
+ return inside;
+ };
+ SkeletonBounds.prototype.intersectsSegment = function (x1, y1, x2, y2) {
+ var polygons = this.polygons;
+ for (var i = 0, n = polygons.length; i < n; i++)
+ if (this.intersectsSegmentPolygon(polygons[i], x1, y1, x2, y2))
+ return this.boundingBoxes[i];
+ return null;
+ };
+ SkeletonBounds.prototype.intersectsSegmentPolygon = function (polygon, x1, y1, x2, y2) {
+ var vertices = polygon;
+ var nn = polygon.length;
+ var width12 = x1 - x2, height12 = y1 - y2;
+ var det1 = x1 * y2 - y1 * x2;
+ var x3 = vertices[nn - 2], y3 = vertices[nn - 1];
+ for (var ii = 0; ii < nn; ii += 2) {
+ var x4 = vertices[ii], y4 = vertices[ii + 1];
+ var det2 = x3 * y4 - y3 * x4;
+ var width34 = x3 - x4, height34 = y3 - y4;
+ var det3 = width12 * height34 - height12 * width34;
+ var x = (det1 * width34 - width12 * det2) / det3;
+ if (((x >= x3 && x <= x4) || (x >= x4 && x <= x3)) && ((x >= x1 && x <= x2) || (x >= x2 && x <= x1))) {
+ var y = (det1 * height34 - height12 * det2) / det3;
+ if (((y >= y3 && y <= y4) || (y >= y4 && y <= y3)) && ((y >= y1 && y <= y2) || (y >= y2 && y <= y1)))
+ return true;
+ }
+ x3 = x4;
+ y3 = y4;
+ }
+ return false;
+ };
+ SkeletonBounds.prototype.getPolygon = function (boundingBox) {
+ if (boundingBox == null)
+ throw new Error("boundingBox cannot be null.");
+ var index = this.boundingBoxes.indexOf(boundingBox);
+ return index == -1 ? null : this.polygons[index];
+ };
+ SkeletonBounds.prototype.getWidth = function () {
+ return this.maxX - this.minX;
+ };
+ SkeletonBounds.prototype.getHeight = function () {
+ return this.maxY - this.minY;
+ };
+ return SkeletonBounds;
+ }());
+ spine.SkeletonBounds = SkeletonBounds;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var SkeletonClipping = (function () {
+ function SkeletonClipping() {
+ this.triangulator = new spine.Triangulator();
+ this.clippingPolygon = new Array();
+ this.clipOutput = new Array();
+ this.clippedVertices = new Array();
+ this.clippedTriangles = new Array();
+ this.scratch = new Array();
+ }
+ SkeletonClipping.prototype.clipStart = function (slot, clip) {
+ if (this.clipAttachment != null)
+ return 0;
+ this.clipAttachment = clip;
+ var n = clip.worldVerticesLength;
+ var vertices = spine.Utils.setArraySize(this.clippingPolygon, n);
+ clip.computeWorldVertices(slot, 0, n, vertices, 0, 2);
+ var clippingPolygon = this.clippingPolygon;
+ SkeletonClipping.makeClockwise(clippingPolygon);
+ var clippingPolygons = this.clippingPolygons = this.triangulator.decompose(clippingPolygon, this.triangulator.triangulate(clippingPolygon));
+ for (var i = 0, n_1 = clippingPolygons.length; i < n_1; i++) {
+ var polygon = clippingPolygons[i];
+ SkeletonClipping.makeClockwise(polygon);
+ polygon.push(polygon[0]);
+ polygon.push(polygon[1]);
+ }
+ return clippingPolygons.length;
+ };
+ SkeletonClipping.prototype.clipEndWithSlot = function (slot) {
+ if (this.clipAttachment != null && this.clipAttachment.endSlot == slot.data)
+ this.clipEnd();
+ };
+ SkeletonClipping.prototype.clipEnd = function () {
+ if (this.clipAttachment == null)
+ return;
+ this.clipAttachment = null;
+ this.clippingPolygons = null;
+ this.clippedVertices.length = 0;
+ this.clippedTriangles.length = 0;
+ this.clippingPolygon.length = 0;
+ };
+ SkeletonClipping.prototype.isClipping = function () {
+ return this.clipAttachment != null;
+ };
+ SkeletonClipping.prototype.clipTriangles = function (vertices, verticesLength, triangles, trianglesLength, uvs, light, dark, twoColor) {
+ var clipOutput = this.clipOutput, clippedVertices = this.clippedVertices;
+ var clippedTriangles = this.clippedTriangles;
+ var polygons = this.clippingPolygons;
+ var polygonsCount = this.clippingPolygons.length;
+ var vertexSize = twoColor ? 12 : 8;
+ var index = 0;
+ clippedVertices.length = 0;
+ clippedTriangles.length = 0;
+ outer: for (var i = 0; i < trianglesLength; i += 3) {
+ var vertexOffset = triangles[i] << 1;
+ var x1 = vertices[vertexOffset], y1 = vertices[vertexOffset + 1];
+ var u1 = uvs[vertexOffset], v1 = uvs[vertexOffset + 1];
+ vertexOffset = triangles[i + 1] << 1;
+ var x2 = vertices[vertexOffset], y2 = vertices[vertexOffset + 1];
+ var u2 = uvs[vertexOffset], v2 = uvs[vertexOffset + 1];
+ vertexOffset = triangles[i + 2] << 1;
+ var x3 = vertices[vertexOffset], y3 = vertices[vertexOffset + 1];
+ var u3 = uvs[vertexOffset], v3 = uvs[vertexOffset + 1];
+ for (var p = 0; p < polygonsCount; p++) {
+ var s = clippedVertices.length;
+ if (this.clip(x1, y1, x2, y2, x3, y3, polygons[p], clipOutput)) {
+ var clipOutputLength = clipOutput.length;
+ if (clipOutputLength == 0)
+ continue;
+ var d0 = y2 - y3, d1 = x3 - x2, d2 = x1 - x3, d4 = y3 - y1;
+ var d = 1 / (d0 * d2 + d1 * (y1 - y3));
+ var clipOutputCount = clipOutputLength >> 1;
+ var clipOutputItems = this.clipOutput;
+ var clippedVerticesItems = spine.Utils.setArraySize(clippedVertices, s + clipOutputCount * vertexSize);
+ for (var ii = 0; ii < clipOutputLength; ii += 2) {
+ var x = clipOutputItems[ii], y = clipOutputItems[ii + 1];
+ clippedVerticesItems[s] = x;
+ clippedVerticesItems[s + 1] = y;
+ clippedVerticesItems[s + 2] = light.r;
+ clippedVerticesItems[s + 3] = light.g;
+ clippedVerticesItems[s + 4] = light.b;
+ clippedVerticesItems[s + 5] = light.a;
+ var c0 = x - x3, c1 = y - y3;
+ var a = (d0 * c0 + d1 * c1) * d;
+ var b = (d4 * c0 + d2 * c1) * d;
+ var c = 1 - a - b;
+ clippedVerticesItems[s + 6] = u1 * a + u2 * b + u3 * c;
+ clippedVerticesItems[s + 7] = v1 * a + v2 * b + v3 * c;
+ if (twoColor) {
+ clippedVerticesItems[s + 8] = dark.r;
+ clippedVerticesItems[s + 9] = dark.g;
+ clippedVerticesItems[s + 10] = dark.b;
+ clippedVerticesItems[s + 11] = dark.a;
+ }
+ s += vertexSize;
+ }
+ s = clippedTriangles.length;
+ var clippedTrianglesItems = spine.Utils.setArraySize(clippedTriangles, s + 3 * (clipOutputCount - 2));
+ clipOutputCount--;
+ for (var ii = 1; ii < clipOutputCount; ii++) {
+ clippedTrianglesItems[s] = index;
+ clippedTrianglesItems[s + 1] = (index + ii);
+ clippedTrianglesItems[s + 2] = (index + ii + 1);
+ s += 3;
+ }
+ index += clipOutputCount + 1;
+ }
+ else {
+ var clippedVerticesItems = spine.Utils.setArraySize(clippedVertices, s + 3 * vertexSize);
+ clippedVerticesItems[s] = x1;
+ clippedVerticesItems[s + 1] = y1;
+ clippedVerticesItems[s + 2] = light.r;
+ clippedVerticesItems[s + 3] = light.g;
+ clippedVerticesItems[s + 4] = light.b;
+ clippedVerticesItems[s + 5] = light.a;
+ if (!twoColor) {
+ clippedVerticesItems[s + 6] = u1;
+ clippedVerticesItems[s + 7] = v1;
+ clippedVerticesItems[s + 8] = x2;
+ clippedVerticesItems[s + 9] = y2;
+ clippedVerticesItems[s + 10] = light.r;
+ clippedVerticesItems[s + 11] = light.g;
+ clippedVerticesItems[s + 12] = light.b;
+ clippedVerticesItems[s + 13] = light.a;
+ clippedVerticesItems[s + 14] = u2;
+ clippedVerticesItems[s + 15] = v2;
+ clippedVerticesItems[s + 16] = x3;
+ clippedVerticesItems[s + 17] = y3;
+ clippedVerticesItems[s + 18] = light.r;
+ clippedVerticesItems[s + 19] = light.g;
+ clippedVerticesItems[s + 20] = light.b;
+ clippedVerticesItems[s + 21] = light.a;
+ clippedVerticesItems[s + 22] = u3;
+ clippedVerticesItems[s + 23] = v3;
+ }
+ else {
+ clippedVerticesItems[s + 6] = u1;
+ clippedVerticesItems[s + 7] = v1;
+ clippedVerticesItems[s + 8] = dark.r;
+ clippedVerticesItems[s + 9] = dark.g;
+ clippedVerticesItems[s + 10] = dark.b;
+ clippedVerticesItems[s + 11] = dark.a;
+ clippedVerticesItems[s + 12] = x2;
+ clippedVerticesItems[s + 13] = y2;
+ clippedVerticesItems[s + 14] = light.r;
+ clippedVerticesItems[s + 15] = light.g;
+ clippedVerticesItems[s + 16] = light.b;
+ clippedVerticesItems[s + 17] = light.a;
+ clippedVerticesItems[s + 18] = u2;
+ clippedVerticesItems[s + 19] = v2;
+ clippedVerticesItems[s + 20] = dark.r;
+ clippedVerticesItems[s + 21] = dark.g;
+ clippedVerticesItems[s + 22] = dark.b;
+ clippedVerticesItems[s + 23] = dark.a;
+ clippedVerticesItems[s + 24] = x3;
+ clippedVerticesItems[s + 25] = y3;
+ clippedVerticesItems[s + 26] = light.r;
+ clippedVerticesItems[s + 27] = light.g;
+ clippedVerticesItems[s + 28] = light.b;
+ clippedVerticesItems[s + 29] = light.a;
+ clippedVerticesItems[s + 30] = u3;
+ clippedVerticesItems[s + 31] = v3;
+ clippedVerticesItems[s + 32] = dark.r;
+ clippedVerticesItems[s + 33] = dark.g;
+ clippedVerticesItems[s + 34] = dark.b;
+ clippedVerticesItems[s + 35] = dark.a;
+ }
+ s = clippedTriangles.length;
+ var clippedTrianglesItems = spine.Utils.setArraySize(clippedTriangles, s + 3);
+ clippedTrianglesItems[s] = index;
+ clippedTrianglesItems[s + 1] = (index + 1);
+ clippedTrianglesItems[s + 2] = (index + 2);
+ index += 3;
+ continue outer;
+ }
+ }
+ }
+ };
+ SkeletonClipping.prototype.clip = function (x1, y1, x2, y2, x3, y3, clippingArea, output) {
+ var originalOutput = output;
+ var clipped = false;
+ var input = null;
+ if (clippingArea.length % 4 >= 2) {
+ input = output;
+ output = this.scratch;
+ }
+ else
+ input = this.scratch;
+ input.length = 0;
+ input.push(x1);
+ input.push(y1);
+ input.push(x2);
+ input.push(y2);
+ input.push(x3);
+ input.push(y3);
+ input.push(x1);
+ input.push(y1);
+ output.length = 0;
+ var clippingVertices = clippingArea;
+ var clippingVerticesLast = clippingArea.length - 4;
+ for (var i = 0;; i += 2) {
+ var edgeX = clippingVertices[i], edgeY = clippingVertices[i + 1];
+ var edgeX2 = clippingVertices[i + 2], edgeY2 = clippingVertices[i + 3];
+ var deltaX = edgeX - edgeX2, deltaY = edgeY - edgeY2;
+ var inputVertices = input;
+ var inputVerticesLength = input.length - 2, outputStart = output.length;
+ for (var ii = 0; ii < inputVerticesLength; ii += 2) {
+ var inputX = inputVertices[ii], inputY = inputVertices[ii + 1];
+ var inputX2 = inputVertices[ii + 2], inputY2 = inputVertices[ii + 3];
+ var side2 = deltaX * (inputY2 - edgeY2) - deltaY * (inputX2 - edgeX2) > 0;
+ if (deltaX * (inputY - edgeY2) - deltaY * (inputX - edgeX2) > 0) {
+ if (side2) {
+ output.push(inputX2);
+ output.push(inputY2);
+ continue;
+ }
+ var c0 = inputY2 - inputY, c2 = inputX2 - inputX;
+ var ua = (c2 * (edgeY - inputY) - c0 * (edgeX - inputX)) / (c0 * (edgeX2 - edgeX) - c2 * (edgeY2 - edgeY));
+ output.push(edgeX + (edgeX2 - edgeX) * ua);
+ output.push(edgeY + (edgeY2 - edgeY) * ua);
+ }
+ else if (side2) {
+ var c0 = inputY2 - inputY, c2 = inputX2 - inputX;
+ var ua = (c2 * (edgeY - inputY) - c0 * (edgeX - inputX)) / (c0 * (edgeX2 - edgeX) - c2 * (edgeY2 - edgeY));
+ output.push(edgeX + (edgeX2 - edgeX) * ua);
+ output.push(edgeY + (edgeY2 - edgeY) * ua);
+ output.push(inputX2);
+ output.push(inputY2);
+ }
+ clipped = true;
+ }
+ if (outputStart == output.length) {
+ originalOutput.length = 0;
+ return true;
+ }
+ output.push(output[0]);
+ output.push(output[1]);
+ if (i == clippingVerticesLast)
+ break;
+ var temp = output;
+ output = input;
+ output.length = 0;
+ input = temp;
+ }
+ if (originalOutput != output) {
+ originalOutput.length = 0;
+ for (var i = 0, n = output.length - 2; i < n; i++)
+ originalOutput[i] = output[i];
+ }
+ else
+ originalOutput.length = originalOutput.length - 2;
+ return clipped;
+ };
+ SkeletonClipping.makeClockwise = function (polygon) {
+ var vertices = polygon;
+ var verticeslength = polygon.length;
+ var area = vertices[verticeslength - 2] * vertices[1] - vertices[0] * vertices[verticeslength - 1], p1x = 0, p1y = 0, p2x = 0, p2y = 0;
+ for (var i = 0, n = verticeslength - 3; i < n; i += 2) {
+ p1x = vertices[i];
+ p1y = vertices[i + 1];
+ p2x = vertices[i + 2];
+ p2y = vertices[i + 3];
+ area += p1x * p2y - p2x * p1y;
+ }
+ if (area < 0)
+ return;
+ for (var i = 0, lastX = verticeslength - 2, n = verticeslength >> 1; i < n; i += 2) {
+ var x = vertices[i], y = vertices[i + 1];
+ var other = lastX - i;
+ vertices[i] = vertices[other];
+ vertices[i + 1] = vertices[other + 1];
+ vertices[other] = x;
+ vertices[other + 1] = y;
+ }
+ };
+ return SkeletonClipping;
+ }());
+ spine.SkeletonClipping = SkeletonClipping;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var SkeletonData = (function () {
+ function SkeletonData() {
+ this.bones = new Array();
+ this.slots = new Array();
+ this.skins = new Array();
+ this.events = new Array();
+ this.animations = new Array();
+ this.ikConstraints = new Array();
+ this.transformConstraints = new Array();
+ this.pathConstraints = new Array();
+ this.fps = 0;
+ }
+ SkeletonData.prototype.findBone = function (boneName) {
+ if (boneName == null)
+ throw new Error("boneName cannot be null.");
+ var bones = this.bones;
+ for (var i = 0, n = bones.length; i < n; i++) {
+ var bone = bones[i];
+ if (bone.name == boneName)
+ return bone;
+ }
+ return null;
+ };
+ SkeletonData.prototype.findBoneIndex = function (boneName) {
+ if (boneName == null)
+ throw new Error("boneName cannot be null.");
+ var bones = this.bones;
+ for (var i = 0, n = bones.length; i < n; i++)
+ if (bones[i].name == boneName)
+ return i;
+ return -1;
+ };
+ SkeletonData.prototype.findSlot = function (slotName) {
+ if (slotName == null)
+ throw new Error("slotName cannot be null.");
+ var slots = this.slots;
+ for (var i = 0, n = slots.length; i < n; i++) {
+ var slot = slots[i];
+ if (slot.name == slotName)
+ return slot;
+ }
+ return null;
+ };
+ SkeletonData.prototype.findSlotIndex = function (slotName) {
+ if (slotName == null)
+ throw new Error("slotName cannot be null.");
+ var slots = this.slots;
+ for (var i = 0, n = slots.length; i < n; i++)
+ if (slots[i].name == slotName)
+ return i;
+ return -1;
+ };
+ SkeletonData.prototype.findSkin = function (skinName) {
+ if (skinName == null)
+ throw new Error("skinName cannot be null.");
+ var skins = this.skins;
+ for (var i = 0, n = skins.length; i < n; i++) {
+ var skin = skins[i];
+ if (skin.name == skinName)
+ return skin;
+ }
+ return null;
+ };
+ SkeletonData.prototype.findEvent = function (eventDataName) {
+ if (eventDataName == null)
+ throw new Error("eventDataName cannot be null.");
+ var events = this.events;
+ for (var i = 0, n = events.length; i < n; i++) {
+ var event_4 = events[i];
+ if (event_4.name == eventDataName)
+ return event_4;
+ }
+ return null;
+ };
+ SkeletonData.prototype.findAnimation = function (animationName) {
+ if (animationName == null)
+ throw new Error("animationName cannot be null.");
+ var animations = this.animations;
+ for (var i = 0, n = animations.length; i < n; i++) {
+ var animation = animations[i];
+ if (animation.name == animationName)
+ return animation;
+ }
+ return null;
+ };
+ SkeletonData.prototype.findIkConstraint = function (constraintName) {
+ if (constraintName == null)
+ throw new Error("constraintName cannot be null.");
+ var ikConstraints = this.ikConstraints;
+ for (var i = 0, n = ikConstraints.length; i < n; i++) {
+ var constraint = ikConstraints[i];
+ if (constraint.name == constraintName)
+ return constraint;
+ }
+ return null;
+ };
+ SkeletonData.prototype.findTransformConstraint = function (constraintName) {
+ if (constraintName == null)
+ throw new Error("constraintName cannot be null.");
+ var transformConstraints = this.transformConstraints;
+ for (var i = 0, n = transformConstraints.length; i < n; i++) {
+ var constraint = transformConstraints[i];
+ if (constraint.name == constraintName)
+ return constraint;
+ }
+ return null;
+ };
+ SkeletonData.prototype.findPathConstraint = function (constraintName) {
+ if (constraintName == null)
+ throw new Error("constraintName cannot be null.");
+ var pathConstraints = this.pathConstraints;
+ for (var i = 0, n = pathConstraints.length; i < n; i++) {
+ var constraint = pathConstraints[i];
+ if (constraint.name == constraintName)
+ return constraint;
+ }
+ return null;
+ };
+ SkeletonData.prototype.findPathConstraintIndex = function (pathConstraintName) {
+ if (pathConstraintName == null)
+ throw new Error("pathConstraintName cannot be null.");
+ var pathConstraints = this.pathConstraints;
+ for (var i = 0, n = pathConstraints.length; i < n; i++)
+ if (pathConstraints[i].name == pathConstraintName)
+ return i;
+ return -1;
+ };
+ return SkeletonData;
+ }());
+ spine.SkeletonData = SkeletonData;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var SkeletonJson = (function () {
+ function SkeletonJson(attachmentLoader) {
+ this.scale = 1;
+ this.linkedMeshes = new Array();
+ this.attachmentLoader = attachmentLoader;
+ }
+ SkeletonJson.prototype.readSkeletonData = function (json) {
+ var scale = this.scale;
+ var skeletonData = new spine.SkeletonData();
+ var root = typeof (json) === "string" ? JSON.parse(json) : json;
+ var skeletonMap = root.skeleton;
+ if (skeletonMap != null) {
+ skeletonData.hash = skeletonMap.hash;
+ skeletonData.version = skeletonMap.spine;
+ skeletonData.width = skeletonMap.width;
+ skeletonData.height = skeletonMap.height;
+ skeletonData.fps = skeletonMap.fps;
+ skeletonData.imagesPath = skeletonMap.images;
+ }
+ if (root.bones) {
+ for (var i = 0; i < root.bones.length; i++) {
+ var boneMap = root.bones[i];
+ var parent_2 = null;
+ var parentName = this.getValue(boneMap, "parent", null);
+ if (parentName != null) {
+ parent_2 = skeletonData.findBone(parentName);
+ if (parent_2 == null)
+ throw new Error("Parent bone not found: " + parentName);
+ }
+ var data = new spine.BoneData(skeletonData.bones.length, boneMap.name, parent_2);
+ data.length = this.getValue(boneMap, "length", 0) * scale;
+ data.x = this.getValue(boneMap, "x", 0) * scale;
+ data.y = this.getValue(boneMap, "y", 0) * scale;
+ data.rotation = this.getValue(boneMap, "rotation", 0);
+ data.scaleX = this.getValue(boneMap, "scaleX", 1);
+ data.scaleY = this.getValue(boneMap, "scaleY", 1);
+ data.shearX = this.getValue(boneMap, "shearX", 0);
+ data.shearY = this.getValue(boneMap, "shearY", 0);
+ data.transformMode = SkeletonJson.transformModeFromString(this.getValue(boneMap, "transform", "normal"));
+ skeletonData.bones.push(data);
+ }
+ }
+ if (root.slots) {
+ for (var i = 0; i < root.slots.length; i++) {
+ var slotMap = root.slots[i];
+ var slotName = slotMap.name;
+ var boneName = slotMap.bone;
+ var boneData = skeletonData.findBone(boneName);
+ if (boneData == null)
+ throw new Error("Slot bone not found: " + boneName);
+ var data = new spine.SlotData(skeletonData.slots.length, slotName, boneData);
+ var color = this.getValue(slotMap, "color", null);
+ if (color != null)
+ data.color.setFromString(color);
+ var dark = this.getValue(slotMap, "dark", null);
+ if (dark != null) {
+ data.darkColor = new spine.Color(1, 1, 1, 1);
+ data.darkColor.setFromString(dark);
+ }
+ data.attachmentName = this.getValue(slotMap, "attachment", null);
+ data.blendMode = SkeletonJson.blendModeFromString(this.getValue(slotMap, "blend", "normal"));
+ skeletonData.slots.push(data);
+ }
+ }
+ if (root.ik) {
+ for (var i = 0; i < root.ik.length; i++) {
+ var constraintMap = root.ik[i];
+ var data = new spine.IkConstraintData(constraintMap.name);
+ data.order = this.getValue(constraintMap, "order", 0);
+ for (var j = 0; j < constraintMap.bones.length; j++) {
+ var boneName = constraintMap.bones[j];
+ var bone = skeletonData.findBone(boneName);
+ if (bone == null)
+ throw new Error("IK bone not found: " + boneName);
+ data.bones.push(bone);
+ }
+ var targetName = constraintMap.target;
+ data.target = skeletonData.findBone(targetName);
+ if (data.target == null)
+ throw new Error("IK target bone not found: " + targetName);
+ data.bendDirection = this.getValue(constraintMap, "bendPositive", true) ? 1 : -1;
+ data.mix = this.getValue(constraintMap, "mix", 1);
+ skeletonData.ikConstraints.push(data);
+ }
+ }
+ if (root.transform) {
+ for (var i = 0; i < root.transform.length; i++) {
+ var constraintMap = root.transform[i];
+ var data = new spine.TransformConstraintData(constraintMap.name);
+ data.order = this.getValue(constraintMap, "order", 0);
+ for (var j = 0; j < constraintMap.bones.length; j++) {
+ var boneName = constraintMap.bones[j];
+ var bone = skeletonData.findBone(boneName);
+ if (bone == null)
+ throw new Error("Transform constraint bone not found: " + boneName);
+ data.bones.push(bone);
+ }
+ var targetName = constraintMap.target;
+ data.target = skeletonData.findBone(targetName);
+ if (data.target == null)
+ throw new Error("Transform constraint target bone not found: " + targetName);
+ data.local = this.getValue(constraintMap, "local", false);
+ data.relative = this.getValue(constraintMap, "relative", false);
+ data.offsetRotation = this.getValue(constraintMap, "rotation", 0);
+ data.offsetX = this.getValue(constraintMap, "x", 0) * scale;
+ data.offsetY = this.getValue(constraintMap, "y", 0) * scale;
+ data.offsetScaleX = this.getValue(constraintMap, "scaleX", 0);
+ data.offsetScaleY = this.getValue(constraintMap, "scaleY", 0);
+ data.offsetShearY = this.getValue(constraintMap, "shearY", 0);
+ data.rotateMix = this.getValue(constraintMap, "rotateMix", 1);
+ data.translateMix = this.getValue(constraintMap, "translateMix", 1);
+ data.scaleMix = this.getValue(constraintMap, "scaleMix", 1);
+ data.shearMix = this.getValue(constraintMap, "shearMix", 1);
+ skeletonData.transformConstraints.push(data);
+ }
+ }
+ if (root.path) {
+ for (var i = 0; i < root.path.length; i++) {
+ var constraintMap = root.path[i];
+ var data = new spine.PathConstraintData(constraintMap.name);
+ data.order = this.getValue(constraintMap, "order", 0);
+ for (var j = 0; j < constraintMap.bones.length; j++) {
+ var boneName = constraintMap.bones[j];
+ var bone = skeletonData.findBone(boneName);
+ if (bone == null)
+ throw new Error("Transform constraint bone not found: " + boneName);
+ data.bones.push(bone);
+ }
+ var targetName = constraintMap.target;
+ data.target = skeletonData.findSlot(targetName);
+ if (data.target == null)
+ throw new Error("Path target slot not found: " + targetName);
+ data.positionMode = SkeletonJson.positionModeFromString(this.getValue(constraintMap, "positionMode", "percent"));
+ data.spacingMode = SkeletonJson.spacingModeFromString(this.getValue(constraintMap, "spacingMode", "length"));
+ data.rotateMode = SkeletonJson.rotateModeFromString(this.getValue(constraintMap, "rotateMode", "tangent"));
+ data.offsetRotation = this.getValue(constraintMap, "rotation", 0);
+ data.position = this.getValue(constraintMap, "position", 0);
+ if (data.positionMode == spine.PositionMode.Fixed)
+ data.position *= scale;
+ data.spacing = this.getValue(constraintMap, "spacing", 0);
+ if (data.spacingMode == spine.SpacingMode.Length || data.spacingMode == spine.SpacingMode.Fixed)
+ data.spacing *= scale;
+ data.rotateMix = this.getValue(constraintMap, "rotateMix", 1);
+ data.translateMix = this.getValue(constraintMap, "translateMix", 1);
+ skeletonData.pathConstraints.push(data);
+ }
+ }
+ if (root.skins) {
+ for (var skinName in root.skins) {
+ var skinMap = root.skins[skinName];
+ var skin = new spine.Skin(skinName);
+ for (var slotName in skinMap) {
+ var slotIndex = skeletonData.findSlotIndex(slotName);
+ if (slotIndex == -1)
+ throw new Error("Slot not found: " + slotName);
+ var slotMap = skinMap[slotName];
+ for (var entryName in slotMap) {
+ var attachment = this.readAttachment(slotMap[entryName], skin, slotIndex, entryName, skeletonData);
+ if (attachment != null)
+ skin.addAttachment(slotIndex, entryName, attachment);
+ }
+ }
+ skeletonData.skins.push(skin);
+ if (skin.name == "default")
+ skeletonData.defaultSkin = skin;
+ }
+ }
+ for (var i = 0, n = this.linkedMeshes.length; i < n; i++) {
+ var linkedMesh = this.linkedMeshes[i];
+ var skin = linkedMesh.skin == null ? skeletonData.defaultSkin : skeletonData.findSkin(linkedMesh.skin);
+ if (skin == null)
+ throw new Error("Skin not found: " + linkedMesh.skin);
+ var parent_3 = skin.getAttachment(linkedMesh.slotIndex, linkedMesh.parent);
+ if (parent_3 == null)
+ throw new Error("Parent mesh not found: " + linkedMesh.parent);
+ linkedMesh.mesh.setParentMesh(parent_3);
+ linkedMesh.mesh.updateUVs();
+ }
+ this.linkedMeshes.length = 0;
+ if (root.events) {
+ for (var eventName in root.events) {
+ var eventMap = root.events[eventName];
+ var data = new spine.EventData(eventName);
+ data.intValue = this.getValue(eventMap, "int", 0);
+ data.floatValue = this.getValue(eventMap, "float", 0);
+ data.stringValue = this.getValue(eventMap, "string", "");
+ skeletonData.events.push(data);
+ }
+ }
+ if (root.animations) {
+ for (var animationName in root.animations) {
+ var animationMap = root.animations[animationName];
+ this.readAnimation(animationMap, animationName, skeletonData);
+ }
+ }
+ return skeletonData;
+ };
+ SkeletonJson.prototype.readAttachment = function (map, skin, slotIndex, name, skeletonData) {
+ var scale = this.scale;
+ name = this.getValue(map, "name", name);
+ var type = this.getValue(map, "type", "region");
+ switch (type) {
+ case "region": {
+ var path = this.getValue(map, "path", name);
+ var region = this.attachmentLoader.newRegionAttachment(skin, name, path);
+ if (region == null)
+ return null;
+ region.path = path;
+ region.x = this.getValue(map, "x", 0) * scale;
+ region.y = this.getValue(map, "y", 0) * scale;
+ region.scaleX = this.getValue(map, "scaleX", 1);
+ region.scaleY = this.getValue(map, "scaleY", 1);
+ region.rotation = this.getValue(map, "rotation", 0);
+ region.width = map.width * scale;
+ region.height = map.height * scale;
+ var color = this.getValue(map, "color", null);
+ if (color != null)
+ region.color.setFromString(color);
+ region.updateOffset();
+ return region;
+ }
+ case "boundingbox": {
+ var box = this.attachmentLoader.newBoundingBoxAttachment(skin, name);
+ if (box == null)
+ return null;
+ this.readVertices(map, box, map.vertexCount << 1);
+ var color = this.getValue(map, "color", null);
+ if (color != null)
+ box.color.setFromString(color);
+ return box;
+ }
+ case "mesh":
+ case "linkedmesh": {
+ var path = this.getValue(map, "path", name);
+ var mesh = this.attachmentLoader.newMeshAttachment(skin, name, path);
+ if (mesh == null)
+ return null;
+ mesh.path = path;
+ var color = this.getValue(map, "color", null);
+ if (color != null)
+ mesh.color.setFromString(color);
+ var parent_4 = this.getValue(map, "parent", null);
+ if (parent_4 != null) {
+ mesh.inheritDeform = this.getValue(map, "deform", true);
+ this.linkedMeshes.push(new LinkedMesh(mesh, this.getValue(map, "skin", null), slotIndex, parent_4));
+ return mesh;
+ }
+ var uvs = map.uvs;
+ this.readVertices(map, mesh, uvs.length);
+ mesh.triangles = map.triangles;
+ mesh.regionUVs = uvs;
+ mesh.updateUVs();
+ mesh.hullLength = this.getValue(map, "hull", 0) * 2;
+ return mesh;
+ }
+ case "path": {
+ var path = this.attachmentLoader.newPathAttachment(skin, name);
+ if (path == null)
+ return null;
+ path.closed = this.getValue(map, "closed", false);
+ path.constantSpeed = this.getValue(map, "constantSpeed", true);
+ var vertexCount = map.vertexCount;
+ this.readVertices(map, path, vertexCount << 1);
+ var lengths = spine.Utils.newArray(vertexCount / 3, 0);
+ for (var i = 0; i < map.lengths.length; i++)
+ lengths[i] = map.lengths[i] * scale;
+ path.lengths = lengths;
+ var color = this.getValue(map, "color", null);
+ if (color != null)
+ path.color.setFromString(color);
+ return path;
+ }
+ case "point": {
+ var point = this.attachmentLoader.newPointAttachment(skin, name);
+ if (point == null)
+ return null;
+ point.x = this.getValue(map, "x", 0) * scale;
+ point.y = this.getValue(map, "y", 0) * scale;
+ point.rotation = this.getValue(map, "rotation", 0);
+ var color = this.getValue(map, "color", null);
+ if (color != null)
+ point.color.setFromString(color);
+ return point;
+ }
+ case "clipping": {
+ var clip = this.attachmentLoader.newClippingAttachment(skin, name);
+ if (clip == null)
+ return null;
+ var end = this.getValue(map, "end", null);
+ if (end != null) {
+ var slot = skeletonData.findSlot(end);
+ if (slot == null)
+ throw new Error("Clipping end slot not found: " + end);
+ clip.endSlot = slot;
+ }
+ var vertexCount = map.vertexCount;
+ this.readVertices(map, clip, vertexCount << 1);
+ var color = this.getValue(map, "color", null);
+ if (color != null)
+ clip.color.setFromString(color);
+ return clip;
+ }
+ }
+ return null;
+ };
+ SkeletonJson.prototype.readVertices = function (map, attachment, verticesLength) {
+ var scale = this.scale;
+ attachment.worldVerticesLength = verticesLength;
+ var vertices = map.vertices;
+ if (verticesLength == vertices.length) {
+ var scaledVertices = spine.Utils.toFloatArray(vertices);
+ if (scale != 1) {
+ for (var i = 0, n = vertices.length; i < n; i++)
+ scaledVertices[i] *= scale;
+ }
+ attachment.vertices = scaledVertices;
+ return;
+ }
+ var weights = new Array();
+ var bones = new Array();
+ for (var i = 0, n = vertices.length; i < n;) {
+ var boneCount = vertices[i++];
+ bones.push(boneCount);
+ for (var nn = i + boneCount * 4; i < nn; i += 4) {
+ bones.push(vertices[i]);
+ weights.push(vertices[i + 1] * scale);
+ weights.push(vertices[i + 2] * scale);
+ weights.push(vertices[i + 3]);
+ }
+ }
+ attachment.bones = bones;
+ attachment.vertices = spine.Utils.toFloatArray(weights);
+ };
+ SkeletonJson.prototype.readAnimation = function (map, name, skeletonData) {
+ var scale = this.scale;
+ var timelines = new Array();
+ var duration = 0;
+ if (map.slots) {
+ for (var slotName in map.slots) {
+ var slotMap = map.slots[slotName];
+ var slotIndex = skeletonData.findSlotIndex(slotName);
+ if (slotIndex == -1)
+ throw new Error("Slot not found: " + slotName);
+ for (var timelineName in slotMap) {
+ var timelineMap = slotMap[timelineName];
+ if (timelineName == "attachment") {
+ var timeline = new spine.AttachmentTimeline(timelineMap.length);
+ timeline.slotIndex = slotIndex;
+ var frameIndex = 0;
+ for (var i = 0; i < timelineMap.length; i++) {
+ var valueMap = timelineMap[i];
+ timeline.setFrame(frameIndex++, valueMap.time, valueMap.name);
+ }
+ timelines.push(timeline);
+ duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]);
+ }
+ else if (timelineName == "color") {
+ var timeline = new spine.ColorTimeline(timelineMap.length);
+ timeline.slotIndex = slotIndex;
+ var frameIndex = 0;
+ for (var i = 0; i < timelineMap.length; i++) {
+ var valueMap = timelineMap[i];
+ var color = new spine.Color();
+ color.setFromString(valueMap.color);
+ timeline.setFrame(frameIndex, valueMap.time, color.r, color.g, color.b, color.a);
+ this.readCurve(valueMap, timeline, frameIndex);
+ frameIndex++;
+ }
+ timelines.push(timeline);
+ duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.ColorTimeline.ENTRIES]);
+ }
+ else if (timelineName == "twoColor") {
+ var timeline = new spine.TwoColorTimeline(timelineMap.length);
+ timeline.slotIndex = slotIndex;
+ var frameIndex = 0;
+ for (var i = 0; i < timelineMap.length; i++) {
+ var valueMap = timelineMap[i];
+ var light = new spine.Color();
+ var dark = new spine.Color();
+ light.setFromString(valueMap.light);
+ dark.setFromString(valueMap.dark);
+ timeline.setFrame(frameIndex, valueMap.time, light.r, light.g, light.b, light.a, dark.r, dark.g, dark.b);
+ this.readCurve(valueMap, timeline, frameIndex);
+ frameIndex++;
+ }
+ timelines.push(timeline);
+ duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.TwoColorTimeline.ENTRIES]);
+ }
+ else
+ throw new Error("Invalid timeline type for a slot: " + timelineName + " (" + slotName + ")");
+ }
+ }
+ }
+ if (map.bones) {
+ for (var boneName in map.bones) {
+ var boneMap = map.bones[boneName];
+ var boneIndex = skeletonData.findBoneIndex(boneName);
+ if (boneIndex == -1)
+ throw new Error("Bone not found: " + boneName);
+ for (var timelineName in boneMap) {
+ var timelineMap = boneMap[timelineName];
+ if (timelineName === "rotate") {
+ var timeline = new spine.RotateTimeline(timelineMap.length);
+ timeline.boneIndex = boneIndex;
+ var frameIndex = 0;
+ for (var i = 0; i < timelineMap.length; i++) {
+ var valueMap = timelineMap[i];
+ timeline.setFrame(frameIndex, valueMap.time, valueMap.angle);
+ this.readCurve(valueMap, timeline, frameIndex);
+ frameIndex++;
+ }
+ timelines.push(timeline);
+ duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.RotateTimeline.ENTRIES]);
+ }
+ else if (timelineName === "translate" || timelineName === "scale" || timelineName === "shear") {
+ var timeline = null;
+ var timelineScale = 1;
+ if (timelineName === "scale")
+ timeline = new spine.ScaleTimeline(timelineMap.length);
+ else if (timelineName === "shear")
+ timeline = new spine.ShearTimeline(timelineMap.length);
+ else {
+ timeline = new spine.TranslateTimeline(timelineMap.length);
+ timelineScale = scale;
+ }
+ timeline.boneIndex = boneIndex;
+ var frameIndex = 0;
+ for (var i = 0; i < timelineMap.length; i++) {
+ var valueMap = timelineMap[i];
+ var x = this.getValue(valueMap, "x", 0), y = this.getValue(valueMap, "y", 0);
+ timeline.setFrame(frameIndex, valueMap.time, x * timelineScale, y * timelineScale);
+ this.readCurve(valueMap, timeline, frameIndex);
+ frameIndex++;
+ }
+ timelines.push(timeline);
+ duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.TranslateTimeline.ENTRIES]);
+ }
+ else
+ throw new Error("Invalid timeline type for a bone: " + timelineName + " (" + boneName + ")");
+ }
+ }
+ }
+ if (map.ik) {
+ for (var constraintName in map.ik) {
+ var constraintMap = map.ik[constraintName];
+ var constraint = skeletonData.findIkConstraint(constraintName);
+ var timeline = new spine.IkConstraintTimeline(constraintMap.length);
+ timeline.ikConstraintIndex = skeletonData.ikConstraints.indexOf(constraint);
+ var frameIndex = 0;
+ for (var i = 0; i < constraintMap.length; i++) {
+ var valueMap = constraintMap[i];
+ timeline.setFrame(frameIndex, valueMap.time, this.getValue(valueMap, "mix", 1), this.getValue(valueMap, "bendPositive", true) ? 1 : -1);
+ this.readCurve(valueMap, timeline, frameIndex);
+ frameIndex++;
+ }
+ timelines.push(timeline);
+ duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.IkConstraintTimeline.ENTRIES]);
+ }
+ }
+ if (map.transform) {
+ for (var constraintName in map.transform) {
+ var constraintMap = map.transform[constraintName];
+ var constraint = skeletonData.findTransformConstraint(constraintName);
+ var timeline = new spine.TransformConstraintTimeline(constraintMap.length);
+ timeline.transformConstraintIndex = skeletonData.transformConstraints.indexOf(constraint);
+ var frameIndex = 0;
+ for (var i = 0; i < constraintMap.length; i++) {
+ var valueMap = constraintMap[i];
+ timeline.setFrame(frameIndex, valueMap.time, this.getValue(valueMap, "rotateMix", 1), this.getValue(valueMap, "translateMix", 1), this.getValue(valueMap, "scaleMix", 1), this.getValue(valueMap, "shearMix", 1));
+ this.readCurve(valueMap, timeline, frameIndex);
+ frameIndex++;
+ }
+ timelines.push(timeline);
+ duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.TransformConstraintTimeline.ENTRIES]);
+ }
+ }
+ if (map.paths) {
+ for (var constraintName in map.paths) {
+ var constraintMap = map.paths[constraintName];
+ var index = skeletonData.findPathConstraintIndex(constraintName);
+ if (index == -1)
+ throw new Error("Path constraint not found: " + constraintName);
+ var data = skeletonData.pathConstraints[index];
+ for (var timelineName in constraintMap) {
+ var timelineMap = constraintMap[timelineName];
+ if (timelineName === "position" || timelineName === "spacing") {
+ var timeline = null;
+ var timelineScale = 1;
+ if (timelineName === "spacing") {
+ timeline = new spine.PathConstraintSpacingTimeline(timelineMap.length);
+ if (data.spacingMode == spine.SpacingMode.Length || data.spacingMode == spine.SpacingMode.Fixed)
+ timelineScale = scale;
+ }
+ else {
+ timeline = new spine.PathConstraintPositionTimeline(timelineMap.length);
+ if (data.positionMode == spine.PositionMode.Fixed)
+ timelineScale = scale;
+ }
+ timeline.pathConstraintIndex = index;
+ var frameIndex = 0;
+ for (var i = 0; i < timelineMap.length; i++) {
+ var valueMap = timelineMap[i];
+ timeline.setFrame(frameIndex, valueMap.time, this.getValue(valueMap, timelineName, 0) * timelineScale);
+ this.readCurve(valueMap, timeline, frameIndex);
+ frameIndex++;
+ }
+ timelines.push(timeline);
+ duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.PathConstraintPositionTimeline.ENTRIES]);
+ }
+ else if (timelineName === "mix") {
+ var timeline = new spine.PathConstraintMixTimeline(timelineMap.length);
+ timeline.pathConstraintIndex = index;
+ var frameIndex = 0;
+ for (var i = 0; i < timelineMap.length; i++) {
+ var valueMap = timelineMap[i];
+ timeline.setFrame(frameIndex, valueMap.time, this.getValue(valueMap, "rotateMix", 1), this.getValue(valueMap, "translateMix", 1));
+ this.readCurve(valueMap, timeline, frameIndex);
+ frameIndex++;
+ }
+ timelines.push(timeline);
+ duration = Math.max(duration, timeline.frames[(timeline.getFrameCount() - 1) * spine.PathConstraintMixTimeline.ENTRIES]);
+ }
+ }
+ }
+ }
+ if (map.deform) {
+ for (var deformName in map.deform) {
+ var deformMap = map.deform[deformName];
+ var skin = skeletonData.findSkin(deformName);
+ if (skin == null)
+ throw new Error("Skin not found: " + deformName);
+ for (var slotName in deformMap) {
+ var slotMap = deformMap[slotName];
+ var slotIndex = skeletonData.findSlotIndex(slotName);
+ if (slotIndex == -1)
+ throw new Error("Slot not found: " + slotMap.name);
+ for (var timelineName in slotMap) {
+ var timelineMap = slotMap[timelineName];
+ var attachment = skin.getAttachment(slotIndex, timelineName);
+ if (attachment == null)
+ throw new Error("Deform attachment not found: " + timelineMap.name);
+ var weighted = attachment.bones != null;
+ var vertices = attachment.vertices;
+ var deformLength = weighted ? vertices.length / 3 * 2 : vertices.length;
+ var timeline = new spine.DeformTimeline(timelineMap.length);
+ timeline.slotIndex = slotIndex;
+ timeline.attachment = attachment;
+ var frameIndex = 0;
+ for (var j = 0; j < timelineMap.length; j++) {
+ var valueMap = timelineMap[j];
+ var deform = void 0;
+ var verticesValue = this.getValue(valueMap, "vertices", null);
+ if (verticesValue == null)
+ deform = weighted ? spine.Utils.newFloatArray(deformLength) : vertices;
+ else {
+ deform = spine.Utils.newFloatArray(deformLength);
+ var start = this.getValue(valueMap, "offset", 0);
+ spine.Utils.arrayCopy(verticesValue, 0, deform, start, verticesValue.length);
+ if (scale != 1) {
+ for (var i = start, n = i + verticesValue.length; i < n; i++)
+ deform[i] *= scale;
+ }
+ if (!weighted) {
+ for (var i = 0; i < deformLength; i++)
+ deform[i] += vertices[i];
+ }
+ }
+ timeline.setFrame(frameIndex, valueMap.time, deform);
+ this.readCurve(valueMap, timeline, frameIndex);
+ frameIndex++;
+ }
+ timelines.push(timeline);
+ duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]);
+ }
+ }
+ }
+ }
+ var drawOrderNode = map.drawOrder;
+ if (drawOrderNode == null)
+ drawOrderNode = map.draworder;
+ if (drawOrderNode != null) {
+ var timeline = new spine.DrawOrderTimeline(drawOrderNode.length);
+ var slotCount = skeletonData.slots.length;
+ var frameIndex = 0;
+ for (var j = 0; j < drawOrderNode.length; j++) {
+ var drawOrderMap = drawOrderNode[j];
+ var drawOrder = null;
+ var offsets = this.getValue(drawOrderMap, "offsets", null);
+ if (offsets != null) {
+ drawOrder = spine.Utils.newArray(slotCount, -1);
+ var unchanged = spine.Utils.newArray(slotCount - offsets.length, 0);
+ var originalIndex = 0, unchangedIndex = 0;
+ for (var i = 0; i < offsets.length; i++) {
+ var offsetMap = offsets[i];
+ var slotIndex = skeletonData.findSlotIndex(offsetMap.slot);
+ if (slotIndex == -1)
+ throw new Error("Slot not found: " + offsetMap.slot);
+ while (originalIndex != slotIndex)
+ unchanged[unchangedIndex++] = originalIndex++;
+ drawOrder[originalIndex + offsetMap.offset] = originalIndex++;
+ }
+ while (originalIndex < slotCount)
+ unchanged[unchangedIndex++] = originalIndex++;
+ for (var i = slotCount - 1; i >= 0; i--)
+ if (drawOrder[i] == -1)
+ drawOrder[i] = unchanged[--unchangedIndex];
+ }
+ timeline.setFrame(frameIndex++, drawOrderMap.time, drawOrder);
+ }
+ timelines.push(timeline);
+ duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]);
+ }
+ if (map.events) {
+ var timeline = new spine.EventTimeline(map.events.length);
+ var frameIndex = 0;
+ for (var i = 0; i < map.events.length; i++) {
+ var eventMap = map.events[i];
+ var eventData = skeletonData.findEvent(eventMap.name);
+ if (eventData == null)
+ throw new Error("Event not found: " + eventMap.name);
+ var event_5 = new spine.Event(spine.Utils.toSinglePrecision(eventMap.time), eventData);
+ event_5.intValue = this.getValue(eventMap, "int", eventData.intValue);
+ event_5.floatValue = this.getValue(eventMap, "float", eventData.floatValue);
+ event_5.stringValue = this.getValue(eventMap, "string", eventData.stringValue);
+ timeline.setFrame(frameIndex++, event_5);
+ }
+ timelines.push(timeline);
+ duration = Math.max(duration, timeline.frames[timeline.getFrameCount() - 1]);
+ }
+ if (isNaN(duration)) {
+ throw new Error("Error while parsing animation, duration is NaN");
+ }
+ skeletonData.animations.push(new spine.Animation(name, timelines, duration));
+ };
+ SkeletonJson.prototype.readCurve = function (map, timeline, frameIndex) {
+ if (!map.curve)
+ return;
+ if (map.curve === "stepped")
+ timeline.setStepped(frameIndex);
+ else if (Object.prototype.toString.call(map.curve) === '[object Array]') {
+ var curve = map.curve;
+ timeline.setCurve(frameIndex, curve[0], curve[1], curve[2], curve[3]);
+ }
+ };
+ SkeletonJson.prototype.getValue = function (map, prop, defaultValue) {
+ return map[prop] !== undefined ? map[prop] : defaultValue;
+ };
+ SkeletonJson.blendModeFromString = function (str) {
+ str = str.toLowerCase();
+ if (str == "normal")
+ return spine.BlendMode.Normal;
+ if (str == "additive")
+ return spine.BlendMode.Additive;
+ if (str == "multiply")
+ return spine.BlendMode.Multiply;
+ if (str == "screen")
+ return spine.BlendMode.Screen;
+ throw new Error("Unknown blend mode: " + str);
+ };
+ SkeletonJson.positionModeFromString = function (str) {
+ str = str.toLowerCase();
+ if (str == "fixed")
+ return spine.PositionMode.Fixed;
+ if (str == "percent")
+ return spine.PositionMode.Percent;
+ throw new Error("Unknown position mode: " + str);
+ };
+ SkeletonJson.spacingModeFromString = function (str) {
+ str = str.toLowerCase();
+ if (str == "length")
+ return spine.SpacingMode.Length;
+ if (str == "fixed")
+ return spine.SpacingMode.Fixed;
+ if (str == "percent")
+ return spine.SpacingMode.Percent;
+ throw new Error("Unknown position mode: " + str);
+ };
+ SkeletonJson.rotateModeFromString = function (str) {
+ str = str.toLowerCase();
+ if (str == "tangent")
+ return spine.RotateMode.Tangent;
+ if (str == "chain")
+ return spine.RotateMode.Chain;
+ if (str == "chainscale")
+ return spine.RotateMode.ChainScale;
+ throw new Error("Unknown rotate mode: " + str);
+ };
+ SkeletonJson.transformModeFromString = function (str) {
+ str = str.toLowerCase();
+ if (str == "normal")
+ return spine.TransformMode.Normal;
+ if (str == "onlytranslation")
+ return spine.TransformMode.OnlyTranslation;
+ if (str == "norotationorreflection")
+ return spine.TransformMode.NoRotationOrReflection;
+ if (str == "noscale")
+ return spine.TransformMode.NoScale;
+ if (str == "noscaleorreflection")
+ return spine.TransformMode.NoScaleOrReflection;
+ throw new Error("Unknown transform mode: " + str);
+ };
+ return SkeletonJson;
+ }());
+ spine.SkeletonJson = SkeletonJson;
+ var LinkedMesh = (function () {
+ function LinkedMesh(mesh, skin, slotIndex, parent) {
+ this.mesh = mesh;
+ this.skin = skin;
+ this.slotIndex = slotIndex;
+ this.parent = parent;
+ }
+ return LinkedMesh;
+ }());
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var Skin = (function () {
+ function Skin(name) {
+ this.attachments = new Array();
+ if (name == null)
+ throw new Error("name cannot be null.");
+ this.name = name;
+ }
+ Skin.prototype.addAttachment = function (slotIndex, name, attachment) {
+ if (attachment == null)
+ throw new Error("attachment cannot be null.");
+ var attachments = this.attachments;
+ if (slotIndex >= attachments.length)
+ attachments.length = slotIndex + 1;
+ if (!attachments[slotIndex])
+ attachments[slotIndex] = {};
+ attachments[slotIndex][name] = attachment;
+ };
+ Skin.prototype.getAttachment = function (slotIndex, name) {
+ var dictionary = this.attachments[slotIndex];
+ return dictionary ? dictionary[name] : null;
+ };
+ Skin.prototype.attachAll = function (skeleton, oldSkin) {
+ var slotIndex = 0;
+ for (var i = 0; i < skeleton.slots.length; i++) {
+ var slot = skeleton.slots[i];
+ var slotAttachment = slot.getAttachment();
+ if (slotAttachment && slotIndex < oldSkin.attachments.length) {
+ var dictionary = oldSkin.attachments[slotIndex];
+ for (var key in dictionary) {
+ var skinAttachment = dictionary[key];
+ if (slotAttachment == skinAttachment) {
+ var attachment = this.getAttachment(slotIndex, key);
+ if (attachment != null)
+ slot.setAttachment(attachment);
+ break;
+ }
+ }
+ }
+ slotIndex++;
+ }
+ };
+ return Skin;
+ }());
+ spine.Skin = Skin;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var Slot = (function () {
+ function Slot(data, bone) {
+ this.attachmentVertices = new Array();
+ if (data == null)
+ throw new Error("data cannot be null.");
+ if (bone == null)
+ throw new Error("bone cannot be null.");
+ this.data = data;
+ this.bone = bone;
+ this.color = new spine.Color();
+ this.darkColor = data.darkColor == null ? null : new spine.Color();
+ this.setToSetupPose();
+ }
+ Slot.prototype.getAttachment = function () {
+ return this.attachment;
+ };
+ Slot.prototype.setAttachment = function (attachment) {
+ if (this.attachment == attachment)
+ return;
+ this.attachment = attachment;
+ this.attachmentTime = this.bone.skeleton.time;
+ this.attachmentVertices.length = 0;
+ };
+ Slot.prototype.setAttachmentTime = function (time) {
+ this.attachmentTime = this.bone.skeleton.time - time;
+ };
+ Slot.prototype.getAttachmentTime = function () {
+ return this.bone.skeleton.time - this.attachmentTime;
+ };
+ Slot.prototype.setToSetupPose = function () {
+ this.color.setFromColor(this.data.color);
+ if (this.darkColor != null)
+ this.darkColor.setFromColor(this.data.darkColor);
+ if (this.data.attachmentName == null)
+ this.attachment = null;
+ else {
+ this.attachment = null;
+ this.setAttachment(this.bone.skeleton.getAttachment(this.data.index, this.data.attachmentName));
+ }
+ };
+ return Slot;
+ }());
+ spine.Slot = Slot;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var SlotData = (function () {
+ function SlotData(index, name, boneData) {
+ this.color = new spine.Color(1, 1, 1, 1);
+ if (index < 0)
+ throw new Error("index must be >= 0.");
+ if (name == null)
+ throw new Error("name cannot be null.");
+ if (boneData == null)
+ throw new Error("boneData cannot be null.");
+ this.index = index;
+ this.name = name;
+ this.boneData = boneData;
+ }
+ return SlotData;
+ }());
+ spine.SlotData = SlotData;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var Texture = (function () {
+ function Texture(image) {
+ this._image = image;
+ }
+ Texture.prototype.getImage = function () {
+ return this._image;
+ };
+ Texture.filterFromString = function (text) {
+ switch (text.toLowerCase()) {
+ case "nearest": return TextureFilter.Nearest;
+ case "linear": return TextureFilter.Linear;
+ case "mipmap": return TextureFilter.MipMap;
+ case "mipmapnearestnearest": return TextureFilter.MipMapNearestNearest;
+ case "mipmaplinearnearest": return TextureFilter.MipMapLinearNearest;
+ case "mipmapnearestlinear": return TextureFilter.MipMapNearestLinear;
+ case "mipmaplinearlinear": return TextureFilter.MipMapLinearLinear;
+ default: throw new Error("Unknown texture filter " + text);
+ }
+ };
+ Texture.wrapFromString = function (text) {
+ switch (text.toLowerCase()) {
+ case "mirroredtepeat": return TextureWrap.MirroredRepeat;
+ case "clamptoedge": return TextureWrap.ClampToEdge;
+ case "repeat": return TextureWrap.Repeat;
+ default: throw new Error("Unknown texture wrap " + text);
+ }
+ };
+ return Texture;
+ }());
+ spine.Texture = Texture;
+ var TextureFilter;
+ (function (TextureFilter) {
+ TextureFilter[TextureFilter["Nearest"] = 9728] = "Nearest";
+ TextureFilter[TextureFilter["Linear"] = 9729] = "Linear";
+ TextureFilter[TextureFilter["MipMap"] = 9987] = "MipMap";
+ TextureFilter[TextureFilter["MipMapNearestNearest"] = 9984] = "MipMapNearestNearest";
+ TextureFilter[TextureFilter["MipMapLinearNearest"] = 9985] = "MipMapLinearNearest";
+ TextureFilter[TextureFilter["MipMapNearestLinear"] = 9986] = "MipMapNearestLinear";
+ TextureFilter[TextureFilter["MipMapLinearLinear"] = 9987] = "MipMapLinearLinear";
+ })(TextureFilter = spine.TextureFilter || (spine.TextureFilter = {}));
+ var TextureWrap;
+ (function (TextureWrap) {
+ TextureWrap[TextureWrap["MirroredRepeat"] = 33648] = "MirroredRepeat";
+ TextureWrap[TextureWrap["ClampToEdge"] = 33071] = "ClampToEdge";
+ TextureWrap[TextureWrap["Repeat"] = 10497] = "Repeat";
+ })(TextureWrap = spine.TextureWrap || (spine.TextureWrap = {}));
+ var TextureRegion = (function () {
+ function TextureRegion() {
+ this.u = 0;
+ this.v = 0;
+ this.u2 = 0;
+ this.v2 = 0;
+ this.width = 0;
+ this.height = 0;
+ this.rotate = false;
+ this.offsetX = 0;
+ this.offsetY = 0;
+ this.originalWidth = 0;
+ this.originalHeight = 0;
+ }
+ return TextureRegion;
+ }());
+ spine.TextureRegion = TextureRegion;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var TextureAtlas = (function () {
+ function TextureAtlas(atlasText, textureLoader) {
+ this.pages = new Array();
+ this.regions = new Array();
+ this.load(atlasText, textureLoader);
+ }
+ TextureAtlas.prototype.load = function (atlasText, textureLoader) {
+ if (textureLoader == null)
+ throw new Error("textureLoader cannot be null.");
+ var reader = new TextureAtlasReader(atlasText);
+ var tuple = new Array(4);
+ var page = null;
+ while (true) {
+ var line = reader.readLine();
+ if (line == null)
+ break;
+ line = line.trim();
+ if (line.length == 0)
+ page = null;
+ else if (!page) {
+ page = new TextureAtlasPage();
+ page.name = line;
+ if (reader.readTuple(tuple) == 2) {
+ page.width = parseInt(tuple[0]);
+ page.height = parseInt(tuple[1]);
+ reader.readTuple(tuple);
+ }
+ reader.readTuple(tuple);
+ page.minFilter = spine.Texture.filterFromString(tuple[0]);
+ page.magFilter = spine.Texture.filterFromString(tuple[1]);
+ var direction = reader.readValue();
+ page.uWrap = spine.TextureWrap.ClampToEdge;
+ page.vWrap = spine.TextureWrap.ClampToEdge;
+ if (direction == "x")
+ page.uWrap = spine.TextureWrap.Repeat;
+ else if (direction == "y")
+ page.vWrap = spine.TextureWrap.Repeat;
+ else if (direction == "xy")
+ page.uWrap = page.vWrap = spine.TextureWrap.Repeat;
+ page.texture = textureLoader(line);
+ page.texture.setFilters(page.minFilter, page.magFilter);
+ page.texture.setWraps(page.uWrap, page.vWrap);
+ page.width = page.texture.getImage().width;
+ page.height = page.texture.getImage().height;
+ this.pages.push(page);
+ }
+ else {
+ var region = new TextureAtlasRegion();
+ region.name = line;
+ region.page = page;
+ region.rotate = reader.readValue() == "true";
+ reader.readTuple(tuple);
+ var x = parseInt(tuple[0]);
+ var y = parseInt(tuple[1]);
+ reader.readTuple(tuple);
+ var width = parseInt(tuple[0]);
+ var height = parseInt(tuple[1]);
+ region.u = x / page.width;
+ region.v = y / page.height;
+ if (region.rotate) {
+ region.u2 = (x + height) / page.width;
+ region.v2 = (y + width) / page.height;
+ }
+ else {
+ region.u2 = (x + width) / page.width;
+ region.v2 = (y + height) / page.height;
+ }
+ region.x = x;
+ region.y = y;
+ region.width = Math.abs(width);
+ region.height = Math.abs(height);
+ if (reader.readTuple(tuple) == 4) {
+ if (reader.readTuple(tuple) == 4) {
+ reader.readTuple(tuple);
+ }
+ }
+ region.originalWidth = parseInt(tuple[0]);
+ region.originalHeight = parseInt(tuple[1]);
+ reader.readTuple(tuple);
+ region.offsetX = parseInt(tuple[0]);
+ region.offsetY = parseInt(tuple[1]);
+ region.index = parseInt(reader.readValue());
+ region.texture = page.texture;
+ this.regions.push(region);
+ }
+ }
+ };
+ TextureAtlas.prototype.findRegion = function (name) {
+ for (var i = 0; i < this.regions.length; i++) {
+ if (this.regions[i].name == name) {
+ return this.regions[i];
+ }
+ }
+ return null;
+ };
+ TextureAtlas.prototype.dispose = function () {
+ for (var i = 0; i < this.pages.length; i++) {
+ this.pages[i].texture.dispose();
+ }
+ };
+ return TextureAtlas;
+ }());
+ spine.TextureAtlas = TextureAtlas;
+ var TextureAtlasReader = (function () {
+ function TextureAtlasReader(text) {
+ this.index = 0;
+ this.lines = text.split(/\r\n|\r|\n/);
+ }
+ TextureAtlasReader.prototype.readLine = function () {
+ if (this.index >= this.lines.length)
+ return null;
+ return this.lines[this.index++];
+ };
+ TextureAtlasReader.prototype.readValue = function () {
+ var line = this.readLine();
+ var colon = line.indexOf(":");
+ if (colon == -1)
+ throw new Error("Invalid line: " + line);
+ return line.substring(colon + 1).trim();
+ };
+ TextureAtlasReader.prototype.readTuple = function (tuple) {
+ var line = this.readLine();
+ var colon = line.indexOf(":");
+ if (colon == -1)
+ throw new Error("Invalid line: " + line);
+ var i = 0, lastMatch = colon + 1;
+ for (; i < 3; i++) {
+ var comma = line.indexOf(",", lastMatch);
+ if (comma == -1)
+ break;
+ tuple[i] = line.substr(lastMatch, comma - lastMatch).trim();
+ lastMatch = comma + 1;
+ }
+ tuple[i] = line.substring(lastMatch).trim();
+ return i + 1;
+ };
+ return TextureAtlasReader;
+ }());
+ var TextureAtlasPage = (function () {
+ function TextureAtlasPage() {
+ }
+ return TextureAtlasPage;
+ }());
+ spine.TextureAtlasPage = TextureAtlasPage;
+ var TextureAtlasRegion = (function (_super) {
+ __extends(TextureAtlasRegion, _super);
+ function TextureAtlasRegion() {
+ return _super !== null && _super.apply(this, arguments) || this;
+ }
+ return TextureAtlasRegion;
+ }(spine.TextureRegion));
+ spine.TextureAtlasRegion = TextureAtlasRegion;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var TransformConstraint = (function () {
+ function TransformConstraint(data, skeleton) {
+ this.rotateMix = 0;
+ this.translateMix = 0;
+ this.scaleMix = 0;
+ this.shearMix = 0;
+ this.temp = new spine.Vector2();
+ if (data == null)
+ throw new Error("data cannot be null.");
+ if (skeleton == null)
+ throw new Error("skeleton cannot be null.");
+ this.data = data;
+ this.rotateMix = data.rotateMix;
+ this.translateMix = data.translateMix;
+ this.scaleMix = data.scaleMix;
+ this.shearMix = data.shearMix;
+ this.bones = new Array();
+ for (var i = 0; i < data.bones.length; i++)
+ this.bones.push(skeleton.findBone(data.bones[i].name));
+ this.target = skeleton.findBone(data.target.name);
+ }
+ TransformConstraint.prototype.apply = function () {
+ this.update();
+ };
+ TransformConstraint.prototype.update = function () {
+ if (this.data.local) {
+ if (this.data.relative)
+ this.applyRelativeLocal();
+ else
+ this.applyAbsoluteLocal();
+ }
+ else {
+ if (this.data.relative)
+ this.applyRelativeWorld();
+ else
+ this.applyAbsoluteWorld();
+ }
+ };
+ TransformConstraint.prototype.applyAbsoluteWorld = function () {
+ var rotateMix = this.rotateMix, translateMix = this.translateMix, scaleMix = this.scaleMix, shearMix = this.shearMix;
+ var target = this.target;
+ var ta = target.a, tb = target.b, tc = target.c, td = target.d;
+ var degRadReflect = ta * td - tb * tc > 0 ? spine.MathUtils.degRad : -spine.MathUtils.degRad;
+ var offsetRotation = this.data.offsetRotation * degRadReflect;
+ var offsetShearY = this.data.offsetShearY * degRadReflect;
+ var bones = this.bones;
+ for (var i = 0, n = bones.length; i < n; i++) {
+ var bone = bones[i];
+ var modified = false;
+ if (rotateMix != 0) {
+ var a = bone.a, b = bone.b, c = bone.c, d = bone.d;
+ var r = Math.atan2(tc, ta) - Math.atan2(c, a) + offsetRotation;
+ if (r > spine.MathUtils.PI)
+ r -= spine.MathUtils.PI2;
+ else if (r < -spine.MathUtils.PI)
+ r += spine.MathUtils.PI2;
+ r *= rotateMix;
+ var cos = Math.cos(r), sin = Math.sin(r);
+ bone.a = cos * a - sin * c;
+ bone.b = cos * b - sin * d;
+ bone.c = sin * a + cos * c;
+ bone.d = sin * b + cos * d;
+ modified = true;
+ }
+ if (translateMix != 0) {
+ var temp = this.temp;
+ target.localToWorld(temp.set(this.data.offsetX, this.data.offsetY));
+ bone.worldX += (temp.x - bone.worldX) * translateMix;
+ bone.worldY += (temp.y - bone.worldY) * translateMix;
+ modified = true;
+ }
+ if (scaleMix > 0) {
+ var s = Math.sqrt(bone.a * bone.a + bone.c * bone.c);
+ var ts = Math.sqrt(ta * ta + tc * tc);
+ if (s > 0.00001)
+ s = (s + (ts - s + this.data.offsetScaleX) * scaleMix) / s;
+ bone.a *= s;
+ bone.c *= s;
+ s = Math.sqrt(bone.b * bone.b + bone.d * bone.d);
+ ts = Math.sqrt(tb * tb + td * td);
+ if (s > 0.00001)
+ s = (s + (ts - s + this.data.offsetScaleY) * scaleMix) / s;
+ bone.b *= s;
+ bone.d *= s;
+ modified = true;
+ }
+ if (shearMix > 0) {
+ var b = bone.b, d = bone.d;
+ var by = Math.atan2(d, b);
+ var r = Math.atan2(td, tb) - Math.atan2(tc, ta) - (by - Math.atan2(bone.c, bone.a));
+ if (r > spine.MathUtils.PI)
+ r -= spine.MathUtils.PI2;
+ else if (r < -spine.MathUtils.PI)
+ r += spine.MathUtils.PI2;
+ r = by + (r + offsetShearY) * shearMix;
+ var s = Math.sqrt(b * b + d * d);
+ bone.b = Math.cos(r) * s;
+ bone.d = Math.sin(r) * s;
+ modified = true;
+ }
+ if (modified)
+ bone.appliedValid = false;
+ }
+ };
+ TransformConstraint.prototype.applyRelativeWorld = function () {
+ var rotateMix = this.rotateMix, translateMix = this.translateMix, scaleMix = this.scaleMix, shearMix = this.shearMix;
+ var target = this.target;
+ var ta = target.a, tb = target.b, tc = target.c, td = target.d;
+ var degRadReflect = ta * td - tb * tc > 0 ? spine.MathUtils.degRad : -spine.MathUtils.degRad;
+ var offsetRotation = this.data.offsetRotation * degRadReflect, offsetShearY = this.data.offsetShearY * degRadReflect;
+ var bones = this.bones;
+ for (var i = 0, n = bones.length; i < n; i++) {
+ var bone = bones[i];
+ var modified = false;
+ if (rotateMix != 0) {
+ var a = bone.a, b = bone.b, c = bone.c, d = bone.d;
+ var r = Math.atan2(tc, ta) + offsetRotation;
+ if (r > spine.MathUtils.PI)
+ r -= spine.MathUtils.PI2;
+ else if (r < -spine.MathUtils.PI)
+ r += spine.MathUtils.PI2;
+ r *= rotateMix;
+ var cos = Math.cos(r), sin = Math.sin(r);
+ bone.a = cos * a - sin * c;
+ bone.b = cos * b - sin * d;
+ bone.c = sin * a + cos * c;
+ bone.d = sin * b + cos * d;
+ modified = true;
+ }
+ if (translateMix != 0) {
+ var temp = this.temp;
+ target.localToWorld(temp.set(this.data.offsetX, this.data.offsetY));
+ bone.worldX += temp.x * translateMix;
+ bone.worldY += temp.y * translateMix;
+ modified = true;
+ }
+ if (scaleMix > 0) {
+ var s = (Math.sqrt(ta * ta + tc * tc) - 1 + this.data.offsetScaleX) * scaleMix + 1;
+ bone.a *= s;
+ bone.c *= s;
+ s = (Math.sqrt(tb * tb + td * td) - 1 + this.data.offsetScaleY) * scaleMix + 1;
+ bone.b *= s;
+ bone.d *= s;
+ modified = true;
+ }
+ if (shearMix > 0) {
+ var r = Math.atan2(td, tb) - Math.atan2(tc, ta);
+ if (r > spine.MathUtils.PI)
+ r -= spine.MathUtils.PI2;
+ else if (r < -spine.MathUtils.PI)
+ r += spine.MathUtils.PI2;
+ var b = bone.b, d = bone.d;
+ r = Math.atan2(d, b) + (r - spine.MathUtils.PI / 2 + offsetShearY) * shearMix;
+ var s = Math.sqrt(b * b + d * d);
+ bone.b = Math.cos(r) * s;
+ bone.d = Math.sin(r) * s;
+ modified = true;
+ }
+ if (modified)
+ bone.appliedValid = false;
+ }
+ };
+ TransformConstraint.prototype.applyAbsoluteLocal = function () {
+ var rotateMix = this.rotateMix, translateMix = this.translateMix, scaleMix = this.scaleMix, shearMix = this.shearMix;
+ var target = this.target;
+ if (!target.appliedValid)
+ target.updateAppliedTransform();
+ var bones = this.bones;
+ for (var i = 0, n = bones.length; i < n; i++) {
+ var bone = bones[i];
+ if (!bone.appliedValid)
+ bone.updateAppliedTransform();
+ var rotation = bone.arotation;
+ if (rotateMix != 0) {
+ var r = target.arotation - rotation + this.data.offsetRotation;
+ r -= (16384 - ((16384.499999999996 - r / 360) | 0)) * 360;
+ rotation += r * rotateMix;
+ }
+ var x = bone.ax, y = bone.ay;
+ if (translateMix != 0) {
+ x += (target.ax - x + this.data.offsetX) * translateMix;
+ y += (target.ay - y + this.data.offsetY) * translateMix;
+ }
+ var scaleX = bone.ascaleX, scaleY = bone.ascaleY;
+ if (scaleMix > 0) {
+ if (scaleX > 0.00001)
+ scaleX = (scaleX + (target.ascaleX - scaleX + this.data.offsetScaleX) * scaleMix) / scaleX;
+ if (scaleY > 0.00001)
+ scaleY = (scaleY + (target.ascaleY - scaleY + this.data.offsetScaleY) * scaleMix) / scaleY;
+ }
+ var shearY = bone.ashearY;
+ if (shearMix > 0) {
+ var r = target.ashearY - shearY + this.data.offsetShearY;
+ r -= (16384 - ((16384.499999999996 - r / 360) | 0)) * 360;
+ bone.shearY += r * shearMix;
+ }
+ bone.updateWorldTransformWith(x, y, rotation, scaleX, scaleY, bone.ashearX, shearY);
+ }
+ };
+ TransformConstraint.prototype.applyRelativeLocal = function () {
+ var rotateMix = this.rotateMix, translateMix = this.translateMix, scaleMix = this.scaleMix, shearMix = this.shearMix;
+ var target = this.target;
+ if (!target.appliedValid)
+ target.updateAppliedTransform();
+ var bones = this.bones;
+ for (var i = 0, n = bones.length; i < n; i++) {
+ var bone = bones[i];
+ if (!bone.appliedValid)
+ bone.updateAppliedTransform();
+ var rotation = bone.arotation;
+ if (rotateMix != 0)
+ rotation += (target.arotation + this.data.offsetRotation) * rotateMix;
+ var x = bone.ax, y = bone.ay;
+ if (translateMix != 0) {
+ x += (target.ax + this.data.offsetX) * translateMix;
+ y += (target.ay + this.data.offsetY) * translateMix;
+ }
+ var scaleX = bone.ascaleX, scaleY = bone.ascaleY;
+ if (scaleMix > 0) {
+ if (scaleX > 0.00001)
+ scaleX *= ((target.ascaleX - 1 + this.data.offsetScaleX) * scaleMix) + 1;
+ if (scaleY > 0.00001)
+ scaleY *= ((target.ascaleY - 1 + this.data.offsetScaleY) * scaleMix) + 1;
+ }
+ var shearY = bone.ashearY;
+ if (shearMix > 0)
+ shearY += (target.ashearY + this.data.offsetShearY) * shearMix;
+ bone.updateWorldTransformWith(x, y, rotation, scaleX, scaleY, bone.ashearX, shearY);
+ }
+ };
+ TransformConstraint.prototype.getOrder = function () {
+ return this.data.order;
+ };
+ return TransformConstraint;
+ }());
+ spine.TransformConstraint = TransformConstraint;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var TransformConstraintData = (function () {
+ function TransformConstraintData(name) {
+ this.order = 0;
+ this.bones = new Array();
+ this.rotateMix = 0;
+ this.translateMix = 0;
+ this.scaleMix = 0;
+ this.shearMix = 0;
+ this.offsetRotation = 0;
+ this.offsetX = 0;
+ this.offsetY = 0;
+ this.offsetScaleX = 0;
+ this.offsetScaleY = 0;
+ this.offsetShearY = 0;
+ this.relative = false;
+ this.local = false;
+ if (name == null)
+ throw new Error("name cannot be null.");
+ this.name = name;
+ }
+ return TransformConstraintData;
+ }());
+ spine.TransformConstraintData = TransformConstraintData;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var Triangulator = (function () {
+ function Triangulator() {
+ this.convexPolygons = new Array();
+ this.convexPolygonsIndices = new Array();
+ this.indicesArray = new Array();
+ this.isConcaveArray = new Array();
+ this.triangles = new Array();
+ this.polygonPool = new spine.Pool(function () {
+ return new Array();
+ });
+ this.polygonIndicesPool = new spine.Pool(function () {
+ return new Array();
+ });
+ }
+ Triangulator.prototype.triangulate = function (verticesArray) {
+ var vertices = verticesArray;
+ var vertexCount = verticesArray.length >> 1;
+ var indices = this.indicesArray;
+ indices.length = 0;
+ for (var i = 0; i < vertexCount; i++)
+ indices[i] = i;
+ var isConcave = this.isConcaveArray;
+ isConcave.length = 0;
+ for (var i = 0, n = vertexCount; i < n; ++i)
+ isConcave[i] = Triangulator.isConcave(i, vertexCount, vertices, indices);
+ var triangles = this.triangles;
+ triangles.length = 0;
+ while (vertexCount > 3) {
+ var previous = vertexCount - 1, i = 0, next = 1;
+ while (true) {
+ outer: if (!isConcave[i]) {
+ var p1 = indices[previous] << 1, p2 = indices[i] << 1, p3 = indices[next] << 1;
+ var p1x = vertices[p1], p1y = vertices[p1 + 1];
+ var p2x = vertices[p2], p2y = vertices[p2 + 1];
+ var p3x = vertices[p3], p3y = vertices[p3 + 1];
+ for (var ii = (next + 1) % vertexCount; ii != previous; ii = (ii + 1) % vertexCount) {
+ if (!isConcave[ii])
+ continue;
+ var v = indices[ii] << 1;
+ var vx = vertices[v], vy = vertices[v + 1];
+ if (Triangulator.positiveArea(p3x, p3y, p1x, p1y, vx, vy)) {
+ if (Triangulator.positiveArea(p1x, p1y, p2x, p2y, vx, vy)) {
+ if (Triangulator.positiveArea(p2x, p2y, p3x, p3y, vx, vy))
+ break outer;
+ }
+ }
+ }
+ break;
+ }
+ if (next == 0) {
+ do {
+ if (!isConcave[i])
+ break;
+ i--;
+ } while (i > 0);
+ break;
+ }
+ previous = i;
+ i = next;
+ next = (next + 1) % vertexCount;
+ }
+ triangles.push(indices[(vertexCount + i - 1) % vertexCount]);
+ triangles.push(indices[i]);
+ triangles.push(indices[(i + 1) % vertexCount]);
+ indices.splice(i, 1);
+ isConcave.splice(i, 1);
+ vertexCount--;
+ var previousIndex = (vertexCount + i - 1) % vertexCount;
+ var nextIndex = i == vertexCount ? 0 : i;
+ isConcave[previousIndex] = Triangulator.isConcave(previousIndex, vertexCount, vertices, indices);
+ isConcave[nextIndex] = Triangulator.isConcave(nextIndex, vertexCount, vertices, indices);
+ }
+ if (vertexCount == 3) {
+ triangles.push(indices[2]);
+ triangles.push(indices[0]);
+ triangles.push(indices[1]);
+ }
+ return triangles;
+ };
+ Triangulator.prototype.decompose = function (verticesArray, triangles) {
+ var vertices = verticesArray;
+ var convexPolygons = this.convexPolygons;
+ this.polygonPool.freeAll(convexPolygons);
+ convexPolygons.length = 0;
+ var convexPolygonsIndices = this.convexPolygonsIndices;
+ this.polygonIndicesPool.freeAll(convexPolygonsIndices);
+ convexPolygonsIndices.length = 0;
+ var polygonIndices = this.polygonIndicesPool.obtain();
+ polygonIndices.length = 0;
+ var polygon = this.polygonPool.obtain();
+ polygon.length = 0;
+ var fanBaseIndex = -1, lastWinding = 0;
+ for (var i = 0, n = triangles.length; i < n; i += 3) {
+ var t1 = triangles[i] << 1, t2 = triangles[i + 1] << 1, t3 = triangles[i + 2] << 1;
+ var x1 = vertices[t1], y1 = vertices[t1 + 1];
+ var x2 = vertices[t2], y2 = vertices[t2 + 1];
+ var x3 = vertices[t3], y3 = vertices[t3 + 1];
+ var merged = false;
+ if (fanBaseIndex == t1) {
+ var o = polygon.length - 4;
+ var winding1 = Triangulator.winding(polygon[o], polygon[o + 1], polygon[o + 2], polygon[o + 3], x3, y3);
+ var winding2 = Triangulator.winding(x3, y3, polygon[0], polygon[1], polygon[2], polygon[3]);
+ if (winding1 == lastWinding && winding2 == lastWinding) {
+ polygon.push(x3);
+ polygon.push(y3);
+ polygonIndices.push(t3);
+ merged = true;
+ }
+ }
+ if (!merged) {
+ if (polygon.length > 0) {
+ convexPolygons.push(polygon);
+ convexPolygonsIndices.push(polygonIndices);
+ }
+ else {
+ this.polygonPool.free(polygon);
+ this.polygonIndicesPool.free(polygonIndices);
+ }
+ polygon = this.polygonPool.obtain();
+ polygon.length = 0;
+ polygon.push(x1);
+ polygon.push(y1);
+ polygon.push(x2);
+ polygon.push(y2);
+ polygon.push(x3);
+ polygon.push(y3);
+ polygonIndices = this.polygonIndicesPool.obtain();
+ polygonIndices.length = 0;
+ polygonIndices.push(t1);
+ polygonIndices.push(t2);
+ polygonIndices.push(t3);
+ lastWinding = Triangulator.winding(x1, y1, x2, y2, x3, y3);
+ fanBaseIndex = t1;
+ }
+ }
+ if (polygon.length > 0) {
+ convexPolygons.push(polygon);
+ convexPolygonsIndices.push(polygonIndices);
+ }
+ for (var i = 0, n = convexPolygons.length; i < n; i++) {
+ polygonIndices = convexPolygonsIndices[i];
+ if (polygonIndices.length == 0)
+ continue;
+ var firstIndex = polygonIndices[0];
+ var lastIndex = polygonIndices[polygonIndices.length - 1];
+ polygon = convexPolygons[i];
+ var o = polygon.length - 4;
+ var prevPrevX = polygon[o], prevPrevY = polygon[o + 1];
+ var prevX = polygon[o + 2], prevY = polygon[o + 3];
+ var firstX = polygon[0], firstY = polygon[1];
+ var secondX = polygon[2], secondY = polygon[3];
+ var winding = Triangulator.winding(prevPrevX, prevPrevY, prevX, prevY, firstX, firstY);
+ for (var ii = 0; ii < n; ii++) {
+ if (ii == i)
+ continue;
+ var otherIndices = convexPolygonsIndices[ii];
+ if (otherIndices.length != 3)
+ continue;
+ var otherFirstIndex = otherIndices[0];
+ var otherSecondIndex = otherIndices[1];
+ var otherLastIndex = otherIndices[2];
+ var otherPoly = convexPolygons[ii];
+ var x3 = otherPoly[otherPoly.length - 2], y3 = otherPoly[otherPoly.length - 1];
+ if (otherFirstIndex != firstIndex || otherSecondIndex != lastIndex)
+ continue;
+ var winding1 = Triangulator.winding(prevPrevX, prevPrevY, prevX, prevY, x3, y3);
+ var winding2 = Triangulator.winding(x3, y3, firstX, firstY, secondX, secondY);
+ if (winding1 == winding && winding2 == winding) {
+ otherPoly.length = 0;
+ otherIndices.length = 0;
+ polygon.push(x3);
+ polygon.push(y3);
+ polygonIndices.push(otherLastIndex);
+ prevPrevX = prevX;
+ prevPrevY = prevY;
+ prevX = x3;
+ prevY = y3;
+ ii = 0;
+ }
+ }
+ }
+ for (var i = convexPolygons.length - 1; i >= 0; i--) {
+ polygon = convexPolygons[i];
+ if (polygon.length == 0) {
+ convexPolygons.splice(i, 1);
+ this.polygonPool.free(polygon);
+ polygonIndices = convexPolygonsIndices[i];
+ convexPolygonsIndices.splice(i, 1);
+ this.polygonIndicesPool.free(polygonIndices);
+ }
+ }
+ return convexPolygons;
+ };
+ Triangulator.isConcave = function (index, vertexCount, vertices, indices) {
+ var previous = indices[(vertexCount + index - 1) % vertexCount] << 1;
+ var current = indices[index] << 1;
+ var next = indices[(index + 1) % vertexCount] << 1;
+ return !this.positiveArea(vertices[previous], vertices[previous + 1], vertices[current], vertices[current + 1], vertices[next], vertices[next + 1]);
+ };
+ Triangulator.positiveArea = function (p1x, p1y, p2x, p2y, p3x, p3y) {
+ return p1x * (p3y - p2y) + p2x * (p1y - p3y) + p3x * (p2y - p1y) >= 0;
+ };
+ Triangulator.winding = function (p1x, p1y, p2x, p2y, p3x, p3y) {
+ var px = p2x - p1x, py = p2y - p1y;
+ return p3x * py - p3y * px + px * p1y - p1x * py >= 0 ? 1 : -1;
+ };
+ return Triangulator;
+ }());
+ spine.Triangulator = Triangulator;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var IntSet = (function () {
+ function IntSet() {
+ this.array = new Array();
+ }
+ IntSet.prototype.add = function (value) {
+ var contains = this.contains(value);
+ this.array[value | 0] = value | 0;
+ return !contains;
+ };
+ IntSet.prototype.contains = function (value) {
+ return this.array[value | 0] != undefined;
+ };
+ IntSet.prototype.remove = function (value) {
+ this.array[value | 0] = undefined;
+ };
+ IntSet.prototype.clear = function () {
+ this.array.length = 0;
+ };
+ return IntSet;
+ }());
+ spine.IntSet = IntSet;
+ var Color = (function () {
+ function Color(r, g, b, a) {
+ if (r === void 0) { r = 0; }
+ if (g === void 0) { g = 0; }
+ if (b === void 0) { b = 0; }
+ if (a === void 0) { a = 0; }
+ this.r = r;
+ this.g = g;
+ this.b = b;
+ this.a = a;
+ }
+ Color.prototype.set = function (r, g, b, a) {
+ this.r = r;
+ this.g = g;
+ this.b = b;
+ this.a = a;
+ this.clamp();
+ return this;
+ };
+ Color.prototype.setFromColor = function (c) {
+ this.r = c.r;
+ this.g = c.g;
+ this.b = c.b;
+ this.a = c.a;
+ return this;
+ };
+ Color.prototype.setFromString = function (hex) {
+ hex = hex.charAt(0) == '#' ? hex.substr(1) : hex;
+ this.r = parseInt(hex.substr(0, 2), 16) / 255.0;
+ this.g = parseInt(hex.substr(2, 2), 16) / 255.0;
+ this.b = parseInt(hex.substr(4, 2), 16) / 255.0;
+ this.a = (hex.length != 8 ? 255 : parseInt(hex.substr(6, 2), 16)) / 255.0;
+ return this;
+ };
+ Color.prototype.add = function (r, g, b, a) {
+ this.r += r;
+ this.g += g;
+ this.b += b;
+ this.a += a;
+ this.clamp();
+ return this;
+ };
+ Color.prototype.clamp = function () {
+ if (this.r < 0)
+ this.r = 0;
+ else if (this.r > 1)
+ this.r = 1;
+ if (this.g < 0)
+ this.g = 0;
+ else if (this.g > 1)
+ this.g = 1;
+ if (this.b < 0)
+ this.b = 0;
+ else if (this.b > 1)
+ this.b = 1;
+ if (this.a < 0)
+ this.a = 0;
+ else if (this.a > 1)
+ this.a = 1;
+ return this;
+ };
+ return Color;
+ }());
+ Color.WHITE = new Color(1, 1, 1, 1);
+ Color.RED = new Color(1, 0, 0, 1);
+ Color.GREEN = new Color(0, 1, 0, 1);
+ Color.BLUE = new Color(0, 0, 1, 1);
+ Color.MAGENTA = new Color(1, 0, 1, 1);
+ spine.Color = Color;
+ var MathUtils = (function () {
+ function MathUtils() {
+ }
+ MathUtils.clamp = function (value, min, max) {
+ if (value < min)
+ return min;
+ if (value > max)
+ return max;
+ return value;
+ };
+ MathUtils.cosDeg = function (degrees) {
+ return Math.cos(degrees * MathUtils.degRad);
+ };
+ MathUtils.sinDeg = function (degrees) {
+ return Math.sin(degrees * MathUtils.degRad);
+ };
+ MathUtils.signum = function (value) {
+ return value > 0 ? 1 : value < 0 ? -1 : 0;
+ };
+ MathUtils.toInt = function (x) {
+ return x > 0 ? Math.floor(x) : Math.ceil(x);
+ };
+ MathUtils.cbrt = function (x) {
+ var y = Math.pow(Math.abs(x), 1 / 3);
+ return x < 0 ? -y : y;
+ };
+ MathUtils.randomTriangular = function (min, max) {
+ return MathUtils.randomTriangularWith(min, max, (min + max) * 0.5);
+ };
+ MathUtils.randomTriangularWith = function (min, max, mode) {
+ var u = Math.random();
+ var d = max - min;
+ if (u <= (mode - min) / d)
+ return min + Math.sqrt(u * d * (mode - min));
+ return max - Math.sqrt((1 - u) * d * (max - mode));
+ };
+ return MathUtils;
+ }());
+ MathUtils.PI = 3.1415927;
+ MathUtils.PI2 = MathUtils.PI * 2;
+ MathUtils.radiansToDegrees = 180 / MathUtils.PI;
+ MathUtils.radDeg = MathUtils.radiansToDegrees;
+ MathUtils.degreesToRadians = MathUtils.PI / 180;
+ MathUtils.degRad = MathUtils.degreesToRadians;
+ spine.MathUtils = MathUtils;
+ var Interpolation = (function () {
+ function Interpolation() {
+ }
+ Interpolation.prototype.apply = function (start, end, a) {
+ return start + (end - start) * this.applyInternal(a);
+ };
+ return Interpolation;
+ }());
+ spine.Interpolation = Interpolation;
+ var Pow = (function (_super) {
+ __extends(Pow, _super);
+ function Pow(power) {
+ var _this = _super.call(this) || this;
+ _this.power = 2;
+ _this.power = power;
+ return _this;
+ }
+ Pow.prototype.applyInternal = function (a) {
+ if (a <= 0.5)
+ return Math.pow(a * 2, this.power) / 2;
+ return Math.pow((a - 1) * 2, this.power) / (this.power % 2 == 0 ? -2 : 2) + 1;
+ };
+ return Pow;
+ }(Interpolation));
+ spine.Pow = Pow;
+ var PowOut = (function (_super) {
+ __extends(PowOut, _super);
+ function PowOut(power) {
+ return _super.call(this, power) || this;
+ }
+ PowOut.prototype.applyInternal = function (a) {
+ return Math.pow(a - 1, this.power) * (this.power % 2 == 0 ? -1 : 1) + 1;
+ };
+ return PowOut;
+ }(Pow));
+ spine.PowOut = PowOut;
+ var Utils = (function () {
+ function Utils() {
+ }
+ Utils.arrayCopy = function (source, sourceStart, dest, destStart, numElements) {
+ for (var i = sourceStart, j = destStart; i < sourceStart + numElements; i++, j++) {
+ dest[j] = source[i];
+ }
+ };
+ Utils.setArraySize = function (array, size, value) {
+ if (value === void 0) { value = 0; }
+ var oldSize = array.length;
+ if (oldSize == size)
+ return array;
+ array.length = size;
+ if (oldSize < size) {
+ for (var i = oldSize; i < size; i++)
+ array[i] = value;
+ }
+ return array;
+ };
+ Utils.ensureArrayCapacity = function (array, size, value) {
+ if (value === void 0) { value = 0; }
+ if (array.length >= size)
+ return array;
+ return Utils.setArraySize(array, size, value);
+ };
+ Utils.newArray = function (size, defaultValue) {
+ var array = new Array(size);
+ for (var i = 0; i < size; i++)
+ array[i] = defaultValue;
+ return array;
+ };
+ Utils.newFloatArray = function (size) {
+ if (Utils.SUPPORTS_TYPED_ARRAYS) {
+ return new Float32Array(size);
+ }
+ else {
+ var array = new Array(size);
+ for (var i = 0; i < array.length; i++)
+ array[i] = 0;
+ return array;
+ }
+ };
+ Utils.newShortArray = function (size) {
+ if (Utils.SUPPORTS_TYPED_ARRAYS) {
+ return new Int16Array(size);
+ }
+ else {
+ var array = new Array(size);
+ for (var i = 0; i < array.length; i++)
+ array[i] = 0;
+ return array;
+ }
+ };
+ Utils.toFloatArray = function (array) {
+ return Utils.SUPPORTS_TYPED_ARRAYS ? new Float32Array(array) : array;
+ };
+ Utils.toSinglePrecision = function (value) {
+ return Utils.SUPPORTS_TYPED_ARRAYS ? Math.fround(value) : value;
+ };
+ return Utils;
+ }());
+ Utils.SUPPORTS_TYPED_ARRAYS = typeof (Float32Array) !== "undefined";
+ spine.Utils = Utils;
+ var DebugUtils = (function () {
+ function DebugUtils() {
+ }
+ DebugUtils.logBones = function (skeleton) {
+ for (var i = 0; i < skeleton.bones.length; i++) {
+ var bone = skeleton.bones[i];
+ console.log(bone.data.name + ", " + bone.a + ", " + bone.b + ", " + bone.c + ", " + bone.d + ", " + bone.worldX + ", " + bone.worldY);
+ }
+ };
+ return DebugUtils;
+ }());
+ spine.DebugUtils = DebugUtils;
+ var Pool = (function () {
+ function Pool(instantiator) {
+ this.items = new Array();
+ this.instantiator = instantiator;
+ }
+ Pool.prototype.obtain = function () {
+ return this.items.length > 0 ? this.items.pop() : this.instantiator();
+ };
+ Pool.prototype.free = function (item) {
+ if (item.reset)
+ item.reset();
+ this.items.push(item);
+ };
+ Pool.prototype.freeAll = function (items) {
+ for (var i = 0; i < items.length; i++) {
+ if (items[i].reset)
+ items[i].reset();
+ this.items[i] = items[i];
+ }
+ };
+ Pool.prototype.clear = function () {
+ this.items.length = 0;
+ };
+ return Pool;
+ }());
+ spine.Pool = Pool;
+ var Vector2 = (function () {
+ function Vector2(x, y) {
+ if (x === void 0) { x = 0; }
+ if (y === void 0) { y = 0; }
+ this.x = x;
+ this.y = y;
+ }
+ Vector2.prototype.set = function (x, y) {
+ this.x = x;
+ this.y = y;
+ return this;
+ };
+ Vector2.prototype.length = function () {
+ var x = this.x;
+ var y = this.y;
+ return Math.sqrt(x * x + y * y);
+ };
+ Vector2.prototype.normalize = function () {
+ var len = this.length();
+ if (len != 0) {
+ this.x /= len;
+ this.y /= len;
+ }
+ return this;
+ };
+ return Vector2;
+ }());
+ spine.Vector2 = Vector2;
+ var TimeKeeper = (function () {
+ function TimeKeeper() {
+ this.maxDelta = 0.064;
+ this.framesPerSecond = 0;
+ this.delta = 0;
+ this.totalTime = 0;
+ this.lastTime = Date.now() / 1000;
+ this.frameCount = 0;
+ this.frameTime = 0;
+ }
+ TimeKeeper.prototype.update = function () {
+ var now = Date.now() / 1000;
+ this.delta = now - this.lastTime;
+ this.frameTime += this.delta;
+ this.totalTime += this.delta;
+ if (this.delta > this.maxDelta)
+ this.delta = this.maxDelta;
+ this.lastTime = now;
+ this.frameCount++;
+ if (this.frameTime > 1) {
+ this.framesPerSecond = this.frameCount / this.frameTime;
+ this.frameTime = 0;
+ this.frameCount = 0;
+ }
+ };
+ return TimeKeeper;
+ }());
+ spine.TimeKeeper = TimeKeeper;
+ var WindowedMean = (function () {
+ function WindowedMean(windowSize) {
+ if (windowSize === void 0) { windowSize = 32; }
+ this.addedValues = 0;
+ this.lastValue = 0;
+ this.mean = 0;
+ this.dirty = true;
+ this.values = new Array(windowSize);
+ }
+ WindowedMean.prototype.hasEnoughData = function () {
+ return this.addedValues >= this.values.length;
+ };
+ WindowedMean.prototype.addValue = function (value) {
+ if (this.addedValues < this.values.length)
+ this.addedValues++;
+ this.values[this.lastValue++] = value;
+ if (this.lastValue > this.values.length - 1)
+ this.lastValue = 0;
+ this.dirty = true;
+ };
+ WindowedMean.prototype.getMean = function () {
+ if (this.hasEnoughData()) {
+ if (this.dirty) {
+ var mean = 0;
+ for (var i = 0; i < this.values.length; i++) {
+ mean += this.values[i];
+ }
+ this.mean = mean / this.values.length;
+ this.dirty = false;
+ }
+ return this.mean;
+ }
+ else {
+ return 0;
+ }
+ };
+ return WindowedMean;
+ }());
+ spine.WindowedMean = WindowedMean;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var Attachment = (function () {
+ function Attachment(name) {
+ if (name == null)
+ throw new Error("name cannot be null.");
+ this.name = name;
+ }
+ return Attachment;
+ }());
+ spine.Attachment = Attachment;
+ var VertexAttachment = (function (_super) {
+ __extends(VertexAttachment, _super);
+ function VertexAttachment(name) {
+ var _this = _super.call(this, name) || this;
+ _this.id = (VertexAttachment.nextID++ & 65535) << 11;
+ _this.worldVerticesLength = 0;
+ return _this;
+ }
+ VertexAttachment.prototype.computeWorldVertices = function (slot, start, count, worldVertices, offset, stride) {
+ count = offset + (count >> 1) * stride;
+ var skeleton = slot.bone.skeleton;
+ var deformArray = slot.attachmentVertices;
+ var vertices = this.vertices;
+ var bones = this.bones;
+ if (bones == null) {
+ if (deformArray.length > 0)
+ vertices = deformArray;
+ var bone = slot.bone;
+ var x = bone.worldX;
+ var y = bone.worldY;
+ var a = bone.a, b = bone.b, c = bone.c, d = bone.d;
+ for (var v_1 = start, w = offset; w < count; v_1 += 2, w += stride) {
+ var vx = vertices[v_1], vy = vertices[v_1 + 1];
+ worldVertices[w] = vx * a + vy * b + x;
+ worldVertices[w + 1] = vx * c + vy * d + y;
+ }
+ return;
+ }
+ var v = 0, skip = 0;
+ for (var i = 0; i < start; i += 2) {
+ var n = bones[v];
+ v += n + 1;
+ skip += n;
+ }
+ var skeletonBones = skeleton.bones;
+ if (deformArray.length == 0) {
+ for (var w = offset, b = skip * 3; w < count; w += stride) {
+ var wx = 0, wy = 0;
+ var n = bones[v++];
+ n += v;
+ for (; v < n; v++, b += 3) {
+ var bone = skeletonBones[bones[v]];
+ var vx = vertices[b], vy = vertices[b + 1], weight = vertices[b + 2];
+ wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight;
+ wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight;
+ }
+ worldVertices[w] = wx;
+ worldVertices[w + 1] = wy;
+ }
+ }
+ else {
+ var deform = deformArray;
+ for (var w = offset, b = skip * 3, f = skip << 1; w < count; w += stride) {
+ var wx = 0, wy = 0;
+ var n = bones[v++];
+ n += v;
+ for (; v < n; v++, b += 3, f += 2) {
+ var bone = skeletonBones[bones[v]];
+ var vx = vertices[b] + deform[f], vy = vertices[b + 1] + deform[f + 1], weight = vertices[b + 2];
+ wx += (vx * bone.a + vy * bone.b + bone.worldX) * weight;
+ wy += (vx * bone.c + vy * bone.d + bone.worldY) * weight;
+ }
+ worldVertices[w] = wx;
+ worldVertices[w + 1] = wy;
+ }
+ }
+ };
+ VertexAttachment.prototype.applyDeform = function (sourceAttachment) {
+ return this == sourceAttachment;
+ };
+ return VertexAttachment;
+ }(Attachment));
+ VertexAttachment.nextID = 0;
+ spine.VertexAttachment = VertexAttachment;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var AttachmentType;
+ (function (AttachmentType) {
+ AttachmentType[AttachmentType["Region"] = 0] = "Region";
+ AttachmentType[AttachmentType["BoundingBox"] = 1] = "BoundingBox";
+ AttachmentType[AttachmentType["Mesh"] = 2] = "Mesh";
+ AttachmentType[AttachmentType["LinkedMesh"] = 3] = "LinkedMesh";
+ AttachmentType[AttachmentType["Path"] = 4] = "Path";
+ AttachmentType[AttachmentType["Point"] = 5] = "Point";
+ })(AttachmentType = spine.AttachmentType || (spine.AttachmentType = {}));
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var BoundingBoxAttachment = (function (_super) {
+ __extends(BoundingBoxAttachment, _super);
+ function BoundingBoxAttachment(name) {
+ var _this = _super.call(this, name) || this;
+ _this.color = new spine.Color(1, 1, 1, 1);
+ return _this;
+ }
+ return BoundingBoxAttachment;
+ }(spine.VertexAttachment));
+ spine.BoundingBoxAttachment = BoundingBoxAttachment;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var ClippingAttachment = (function (_super) {
+ __extends(ClippingAttachment, _super);
+ function ClippingAttachment(name) {
+ var _this = _super.call(this, name) || this;
+ _this.color = new spine.Color(0.2275, 0.2275, 0.8078, 1);
+ return _this;
+ }
+ return ClippingAttachment;
+ }(spine.VertexAttachment));
+ spine.ClippingAttachment = ClippingAttachment;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var MeshAttachment = (function (_super) {
+ __extends(MeshAttachment, _super);
+ function MeshAttachment(name) {
+ var _this = _super.call(this, name) || this;
+ _this.color = new spine.Color(1, 1, 1, 1);
+ _this.inheritDeform = false;
+ _this.tempColor = new spine.Color(0, 0, 0, 0);
+ return _this;
+ }
+ MeshAttachment.prototype.updateUVs = function () {
+ var u = 0, v = 0, width = 0, height = 0;
+ if (this.region == null) {
+ u = v = 0;
+ width = height = 1;
+ }
+ else {
+ u = this.region.u;
+ v = this.region.v;
+ width = this.region.u2 - u;
+ height = this.region.v2 - v;
+ }
+ var regionUVs = this.regionUVs;
+ if (this.uvs == null || this.uvs.length != regionUVs.length)
+ this.uvs = spine.Utils.newFloatArray(regionUVs.length);
+ var uvs = this.uvs;
+ if (this.region.rotate) {
+ for (var i = 0, n = uvs.length; i < n; i += 2) {
+ uvs[i] = u + regionUVs[i + 1] * width;
+ uvs[i + 1] = v + height - regionUVs[i] * height;
+ }
+ }
+ else {
+ for (var i = 0, n = uvs.length; i < n; i += 2) {
+ uvs[i] = u + regionUVs[i] * width;
+ uvs[i + 1] = v + regionUVs[i + 1] * height;
+ }
+ }
+ };
+ MeshAttachment.prototype.applyDeform = function (sourceAttachment) {
+ return this == sourceAttachment || (this.inheritDeform && this.parentMesh == sourceAttachment);
+ };
+ MeshAttachment.prototype.getParentMesh = function () {
+ return this.parentMesh;
+ };
+ MeshAttachment.prototype.setParentMesh = function (parentMesh) {
+ this.parentMesh = parentMesh;
+ if (parentMesh != null) {
+ this.bones = parentMesh.bones;
+ this.vertices = parentMesh.vertices;
+ this.worldVerticesLength = parentMesh.worldVerticesLength;
+ this.regionUVs = parentMesh.regionUVs;
+ this.triangles = parentMesh.triangles;
+ this.hullLength = parentMesh.hullLength;
+ this.worldVerticesLength = parentMesh.worldVerticesLength;
+ }
+ };
+ return MeshAttachment;
+ }(spine.VertexAttachment));
+ spine.MeshAttachment = MeshAttachment;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var PathAttachment = (function (_super) {
+ __extends(PathAttachment, _super);
+ function PathAttachment(name) {
+ var _this = _super.call(this, name) || this;
+ _this.closed = false;
+ _this.constantSpeed = false;
+ _this.color = new spine.Color(1, 1, 1, 1);
+ return _this;
+ }
+ return PathAttachment;
+ }(spine.VertexAttachment));
+ spine.PathAttachment = PathAttachment;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var PointAttachment = (function (_super) {
+ __extends(PointAttachment, _super);
+ function PointAttachment(name) {
+ var _this = _super.call(this, name) || this;
+ _this.color = new spine.Color(0.38, 0.94, 0, 1);
+ return _this;
+ }
+ PointAttachment.prototype.computeWorldPosition = function (bone, point) {
+ point.x = this.x * bone.a + this.y * bone.b + bone.worldX;
+ point.y = this.x * bone.c + this.y * bone.d + bone.worldY;
+ return point;
+ };
+ PointAttachment.prototype.computeWorldRotation = function (bone) {
+ var cos = spine.MathUtils.cosDeg(this.rotation), sin = spine.MathUtils.sinDeg(this.rotation);
+ var x = cos * bone.a + sin * bone.b;
+ var y = cos * bone.c + sin * bone.d;
+ return Math.atan2(y, x) * spine.MathUtils.radDeg;
+ };
+ return PointAttachment;
+ }(spine.VertexAttachment));
+ spine.PointAttachment = PointAttachment;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var RegionAttachment = (function (_super) {
+ __extends(RegionAttachment, _super);
+ function RegionAttachment(name) {
+ var _this = _super.call(this, name) || this;
+ _this.x = 0;
+ _this.y = 0;
+ _this.scaleX = 1;
+ _this.scaleY = 1;
+ _this.rotation = 0;
+ _this.width = 0;
+ _this.height = 0;
+ _this.color = new spine.Color(1, 1, 1, 1);
+ _this.offset = spine.Utils.newFloatArray(8);
+ _this.uvs = spine.Utils.newFloatArray(8);
+ _this.tempColor = new spine.Color(1, 1, 1, 1);
+ return _this;
+ }
+ RegionAttachment.prototype.updateOffset = function () {
+ var regionScaleX = this.width / this.region.originalWidth * this.scaleX;
+ var regionScaleY = this.height / this.region.originalHeight * this.scaleY;
+ var localX = -this.width / 2 * this.scaleX + this.region.offsetX * regionScaleX;
+ var localY = -this.height / 2 * this.scaleY + this.region.offsetY * regionScaleY;
+ var localX2 = localX + this.region.width * regionScaleX;
+ var localY2 = localY + this.region.height * regionScaleY;
+ var radians = this.rotation * Math.PI / 180;
+ var cos = Math.cos(radians);
+ var sin = Math.sin(radians);
+ var localXCos = localX * cos + this.x;
+ var localXSin = localX * sin;
+ var localYCos = localY * cos + this.y;
+ var localYSin = localY * sin;
+ var localX2Cos = localX2 * cos + this.x;
+ var localX2Sin = localX2 * sin;
+ var localY2Cos = localY2 * cos + this.y;
+ var localY2Sin = localY2 * sin;
+ var offset = this.offset;
+ offset[RegionAttachment.OX1] = localXCos - localYSin;
+ offset[RegionAttachment.OY1] = localYCos + localXSin;
+ offset[RegionAttachment.OX2] = localXCos - localY2Sin;
+ offset[RegionAttachment.OY2] = localY2Cos + localXSin;
+ offset[RegionAttachment.OX3] = localX2Cos - localY2Sin;
+ offset[RegionAttachment.OY3] = localY2Cos + localX2Sin;
+ offset[RegionAttachment.OX4] = localX2Cos - localYSin;
+ offset[RegionAttachment.OY4] = localYCos + localX2Sin;
+ };
+ RegionAttachment.prototype.setRegion = function (region) {
+ this.region = region;
+ var uvs = this.uvs;
+ if (region.rotate) {
+ uvs[2] = region.u;
+ uvs[3] = region.v2;
+ uvs[4] = region.u;
+ uvs[5] = region.v;
+ uvs[6] = region.u2;
+ uvs[7] = region.v;
+ uvs[0] = region.u2;
+ uvs[1] = region.v2;
+ }
+ else {
+ uvs[0] = region.u;
+ uvs[1] = region.v2;
+ uvs[2] = region.u;
+ uvs[3] = region.v;
+ uvs[4] = region.u2;
+ uvs[5] = region.v;
+ uvs[6] = region.u2;
+ uvs[7] = region.v2;
+ }
+ };
+ RegionAttachment.prototype.computeWorldVertices = function (bone, worldVertices, offset, stride) {
+ var vertexOffset = this.offset;
+ var x = bone.worldX, y = bone.worldY;
+ var a = bone.a, b = bone.b, c = bone.c, d = bone.d;
+ var offsetX = 0, offsetY = 0;
+ offsetX = vertexOffset[RegionAttachment.OX1];
+ offsetY = vertexOffset[RegionAttachment.OY1];
+ worldVertices[offset] = offsetX * a + offsetY * b + x;
+ worldVertices[offset + 1] = offsetX * c + offsetY * d + y;
+ offset += stride;
+ offsetX = vertexOffset[RegionAttachment.OX2];
+ offsetY = vertexOffset[RegionAttachment.OY2];
+ worldVertices[offset] = offsetX * a + offsetY * b + x;
+ worldVertices[offset + 1] = offsetX * c + offsetY * d + y;
+ offset += stride;
+ offsetX = vertexOffset[RegionAttachment.OX3];
+ offsetY = vertexOffset[RegionAttachment.OY3];
+ worldVertices[offset] = offsetX * a + offsetY * b + x;
+ worldVertices[offset + 1] = offsetX * c + offsetY * d + y;
+ offset += stride;
+ offsetX = vertexOffset[RegionAttachment.OX4];
+ offsetY = vertexOffset[RegionAttachment.OY4];
+ worldVertices[offset] = offsetX * a + offsetY * b + x;
+ worldVertices[offset + 1] = offsetX * c + offsetY * d + y;
+ };
+ return RegionAttachment;
+ }(spine.Attachment));
+ RegionAttachment.OX1 = 0;
+ RegionAttachment.OY1 = 1;
+ RegionAttachment.OX2 = 2;
+ RegionAttachment.OY2 = 3;
+ RegionAttachment.OX3 = 4;
+ RegionAttachment.OY3 = 5;
+ RegionAttachment.OX4 = 6;
+ RegionAttachment.OY4 = 7;
+ RegionAttachment.X1 = 0;
+ RegionAttachment.Y1 = 1;
+ RegionAttachment.C1R = 2;
+ RegionAttachment.C1G = 3;
+ RegionAttachment.C1B = 4;
+ RegionAttachment.C1A = 5;
+ RegionAttachment.U1 = 6;
+ RegionAttachment.V1 = 7;
+ RegionAttachment.X2 = 8;
+ RegionAttachment.Y2 = 9;
+ RegionAttachment.C2R = 10;
+ RegionAttachment.C2G = 11;
+ RegionAttachment.C2B = 12;
+ RegionAttachment.C2A = 13;
+ RegionAttachment.U2 = 14;
+ RegionAttachment.V2 = 15;
+ RegionAttachment.X3 = 16;
+ RegionAttachment.Y3 = 17;
+ RegionAttachment.C3R = 18;
+ RegionAttachment.C3G = 19;
+ RegionAttachment.C3B = 20;
+ RegionAttachment.C3A = 21;
+ RegionAttachment.U3 = 22;
+ RegionAttachment.V3 = 23;
+ RegionAttachment.X4 = 24;
+ RegionAttachment.Y4 = 25;
+ RegionAttachment.C4R = 26;
+ RegionAttachment.C4G = 27;
+ RegionAttachment.C4B = 28;
+ RegionAttachment.C4A = 29;
+ RegionAttachment.U4 = 30;
+ RegionAttachment.V4 = 31;
+ spine.RegionAttachment = RegionAttachment;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var JitterEffect = (function () {
+ function JitterEffect(jitterX, jitterY) {
+ this.jitterX = 0;
+ this.jitterY = 0;
+ this.jitterX = jitterX;
+ this.jitterY = jitterY;
+ }
+ JitterEffect.prototype.begin = function (skeleton) {
+ };
+ JitterEffect.prototype.transform = function (position, uv, light, dark) {
+ position.x += spine.MathUtils.randomTriangular(-this.jitterX, this.jitterY);
+ position.y += spine.MathUtils.randomTriangular(-this.jitterX, this.jitterY);
+ };
+ JitterEffect.prototype.end = function () {
+ };
+ return JitterEffect;
+ }());
+ spine.JitterEffect = JitterEffect;
+})(spine || (spine = {}));
+var spine;
+(function (spine) {
+ var SwirlEffect = (function () {
+ function SwirlEffect(radius) {
+ this.centerX = 0;
+ this.centerY = 0;
+ this.radius = 0;
+ this.angle = 0;
+ this.worldX = 0;
+ this.worldY = 0;
+ this.radius = radius;
+ }
+ SwirlEffect.prototype.begin = function (skeleton) {
+ this.worldX = skeleton.x + this.centerX;
+ this.worldY = skeleton.y + this.centerY;
+ };
+ SwirlEffect.prototype.transform = function (position, uv, light, dark) {
+ var radAngle = this.angle * spine.MathUtils.degreesToRadians;
+ var x = position.x - this.worldX;
+ var y = position.y - this.worldY;
+ var dist = Math.sqrt(x * x + y * y);
+ if (dist < this.radius) {
+ var theta = SwirlEffect.interpolation.apply(0, radAngle, (this.radius - dist) / this.radius);
+ var cos = Math.cos(theta);
+ var sin = Math.sin(theta);
+ position.x = cos * x - sin * y + this.worldX;
+ position.y = sin * x + cos * y + this.worldY;
+ }
+ };
+ SwirlEffect.prototype.end = function () {
+ };
+ return SwirlEffect;
+ }());
+ SwirlEffect.interpolation = new spine.PowOut(2);
+ spine.SwirlEffect = SwirlEffect;
+})(spine || (spine = {}));
+
+var sp = sp || {};
+sp.spine = spine;
diff --git a/moduleConfig.json b/moduleConfig.json
index bebf4f2b6c..55a9e81c60 100644
--- a/moduleConfig.json
+++ b/moduleConfig.json
@@ -34,9 +34,7 @@
"core",
"cocos2d/compression/ZipUtils.js",
- "cocos2d/compression/base64.js",
- "cocos2d/compression/gzip.js",
- "cocos2d/compression/zlib.min.js"
+ "cocos2d/compression/base64.js"
],
"core" : [
"cocos2d/core/event-manager/CCEventHelper.js",
@@ -51,8 +49,6 @@
"cocos2d/core/platform/CCConfig.js",
"cocos2d/core/platform/miniFramework.js",
"cocos2d/core/platform/CCMacro.js",
- "cocos2d/core/platform/CCTypesWebGL.js",
- "cocos2d/core/platform/CCTypesPropertyDefine.js",
"cocos2d/core/platform/CCTypes.js",
"cocos2d/core/platform/CCEGLView.js",
"cocos2d/core/platform/CCScreen.js",
@@ -72,6 +68,7 @@
"cocos2d/core/event-manager/CCEventManager.js",
"cocos2d/core/event-manager/CCEventExtension.js",
+ "cocos2d/core/renderer/GlobalVertexBuffer.js",
"cocos2d/core/renderer/RendererCanvas.js",
"cocos2d/core/renderer/RendererWebGL.js",
"cocos2d/core/renderer/DirtyRegion.js",
@@ -156,13 +153,12 @@
],
"labels" : [
"core",
-
- "cocos2d/labels/CCLabelAtlas.js",
- "cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js",
- "cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js",
"cocos2d/labels/CCLabelBMFont.js",
"cocos2d/labels/CCLabelBMFontCanvasRenderCmd.js",
- "cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js"
+ "cocos2d/labels/CCLabelBMFontWebGLRenderCmd.js",
+ "cocos2d/labels/CCLabelAtlas.js",
+ "cocos2d/labels/CCLabelAtlasCanvasRenderCmd.js",
+ "cocos2d/labels/CCLabelAtlasWebGLRenderCmd.js"
],
"menus" : [
"core", "actions",
@@ -232,6 +228,7 @@
"cocos2d/shaders/CCShaders.js",
"cocos2d/shaders/CCShaderCache.js",
"cocos2d/shaders/CCGLProgram.js",
+ "cocos2d/shaders/CCGLProgramState.js",
"cocos2d/shaders/CCGLStateCache.js"
],
"shape-nodes" : [
@@ -250,6 +247,9 @@
"tilemap" : [
"core", "compression",
+ "cocos2d/compression/gzip.js",
+ "cocos2d/compression/zlib.min.js",
+
"cocos2d/tilemap/CCTGAlib.js",
"cocos2d/tilemap/CCTMXTiledMap.js",
"cocos2d/tilemap/CCTMXXMLParser.js",
@@ -292,7 +292,6 @@
"editbox" : [
"core", "gui",
- "extensions/editbox/CCdomNode.js",
"extensions/editbox/CCEditBox.js"
],
"ccpool" : [
@@ -442,6 +441,7 @@
"extensions/spine/Spine.js",
"extensions/spine/CCSkeleton.js",
"extensions/spine/CCSkeletonAnimation.js",
+ "extensions/spine/CCSkeletonTexture.js",
"extensions/spine/CCSkeletonCanvasRenderCmd.js",
"extensions/spine/CCSkeletonWebGLRenderCmd.js"
],
@@ -491,4 +491,4 @@
"external" : ["box2d", "chipmunk", "socketio", "pluginx", "gaf"]
},
"bootFile" : "CCBoot.js"
-}
\ No newline at end of file
+}
diff --git a/tools/build.xml b/tools/build.xml
index a70c8a5a0b..519f9867e9 100644
--- a/tools/build.xml
+++ b/tools/build.xml
@@ -5,9 +5,9 @@
classpath="./compiler/compiler.jar"/>
+ sourceMapOutputFile="./../lib/cocos2d-js-v3.15-sourcemap" sourceMapFormat="V3">
@@ -306,9 +306,9 @@
+ sourceMapOutputFile="./../lib/cocos2d-js-v3.15-core-sourcemap" sourceMapFormat="V3">