Merge pull request #1630 from jareguo/master

优化引擎脚本加载时间
This commit is contained in:
Wang Nan
2017-05-05 13:41:01 +08:00
committed by GitHub
38 changed files with 5681 additions and 5612 deletions
+1 -2
View File
@@ -266,7 +266,7 @@ if (CC_DEV) {
"3610": "The type of %s must be cc.Float or cc.Integer, not Number.", //getTypeChecker_7
"3611": "Can not indicate the '%s' attribute for %s, which its default value is type of %s.", //getTypeChecker_8
"3612": "%s Just set the default value to 'new %s()' and it will be handled properly.", //getTypeChecker_9
"3613": "'No need to use 'serializable: false' or 'editorOnly: true' for the getter of '%s.%s', every getter is actually non-serialized.", //defineGetSet
"3613": "'No need to specify the '%s' attribute for the getter of '%s.%s', every getter is actually non-serialized.", //defineGetSet
"3615": "Each script can have at most one Component.", //define_2
"3616": "Should not specify class name %s for Component which defines in project.", //define_3
"3617": "ctor of CCClass '%s' should not accept any arguments.", //_createCtor
@@ -291,7 +291,6 @@ if (CC_DEV) {
"3636": "Do not set default value to non-empty object, unless the object defines its own 'clone' function. Set default value of %s.%s to null or {}, and initialize in 'onLoad' or 'ctor' please. (just like 'this.%s = {foo: bar};')", //defineProp_2
"3637": "Can not declare %s.%s, it is already defined in the prototype of %s", //defineProp_3
"3638": "'%s': the getter of '%s' is already defined!", //defineGetSet_2
"3639": "Can not apply the specified attribute to the getter of '%s.%s', attribute index: %s", //defineGetSet_3
"3640": "'%s': the setter of '%s' is already defined!", //defineGetSet_4
"3641": "Can not construct %s because it contains object property.", //getNewValueTypeCode
"3642": "Cannot define %s.%s because static member name can not be '%s'.", //CCClass_4
+152 -153
View File
@@ -73,7 +73,7 @@ var WrapMode = cc.Enum({
cc.WrapMode = WrapMode;
// For internal
var WrappedInfo = function (info) {
function WrappedInfo (info) {
if (info) {
this.set(info);
return;
@@ -84,7 +84,7 @@ var WrappedInfo = function (info) {
this.direction = 1;
this.stopped = true;
this.iterations = 0;
};
}
WrappedInfo.prototype.set = function (info) {
for (var k in info) {
@@ -99,9 +99,9 @@ WrappedInfo.prototype.set = function (info) {
*
* @extends Playable
*/
var AnimationNodeBase = function () {
function AnimationNodeBase () {
Playable.call(this);
};
}
JS.extend(AnimationNodeBase, Playable);
/**
@@ -257,167 +257,166 @@ function AnimationNode (animator, curves, timingInput) {
}
JS.extend(AnimationNode, AnimationNodeBase);
JS.mixin(AnimationNode.prototype, {
var proto = AnimationNode.prototype;
update: function (delta) {
proto.update = function (delta) {
// calculate delay time
// calculate delay time
if (this._duringDelay) {
this._timeNoScale += delta;
if (this._timeNoScale < this.delay) {
// still waiting
return;
}
else {
this._duringDelay = false;
}
//// start play
// delta -= (this._timeNoScale - this.delay);
}
// make first frame perfect
//var playPerfectFirstFrame = (this.time === 0);
if (this._firstFramePlayed) {
this.time += (delta * this.speed);
if (this._duringDelay) {
this._timeNoScale += delta;
if (this._timeNoScale < this.delay) {
// still waiting
return;
}
else {
this._firstFramePlayed = true;
this._duringDelay = false;
}
//// start play
// delta -= (this._timeNoScale - this.delay);
}
// sample
var info = this.sample();
// make first frame perfect
if (!this._lastWrappedInfo) {
this._lastWrappedInfo = new WrappedInfo(info);
}
//var playPerfectFirstFrame = (this.time === 0);
if (this._firstFramePlayed) {
this.time += (delta * this.speed);
}
else {
this._firstFramePlayed = true;
}
var anotherIteration = (info.iterations | 0) > (this._lastWrappedInfo.iterations | 0);
if (this.repeatCount > 1 && anotherIteration) {
if ((this.wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse) {
if (this._lastWrappedInfo.direction < 0) {
this.emit('lastframe', this);
}
}
else {
if (this._lastWrappedInfo.direction > 0) {
this.emit('lastframe', this);
}
// sample
var info = this.sample();
if (!this._lastWrappedInfo) {
this._lastWrappedInfo = new WrappedInfo(info);
}
var anotherIteration = (info.iterations | 0) > (this._lastWrappedInfo.iterations | 0);
if (this.repeatCount > 1 && anotherIteration) {
if ((this.wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse) {
if (this._lastWrappedInfo.direction < 0) {
this.emit('lastframe', this);
}
}
if (info.stopped) {
this.stop();
this.emit('finished', this);
}
this._lastWrappedInfo.set(info);
},
_needRevers: function (currentIterations) {
var wrapMode = this.wrapMode;
var needRevers = false;
if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) {
var isEnd = currentIterations - (currentIterations | 0) === 0;
if (isEnd && (currentIterations > 0)) {
currentIterations -= 1;
}
var isOddIteration = currentIterations & 1;
if (isOddIteration) {
needRevers = !needRevers;
else {
if (this._lastWrappedInfo.direction > 0) {
this.emit('lastframe', this);
}
}
if ((wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse) {
}
if (info.stopped) {
this.stop();
this.emit('finished', this);
}
this._lastWrappedInfo.set(info);
};
proto._needRevers = function (currentIterations) {
var wrapMode = this.wrapMode;
var needRevers = false;
if ((wrapMode & WrapModeMask.PingPong) === WrapModeMask.PingPong) {
var isEnd = currentIterations - (currentIterations | 0) === 0;
if (isEnd && (currentIterations > 0)) {
currentIterations -= 1;
}
var isOddIteration = currentIterations & 1;
if (isOddIteration) {
needRevers = !needRevers;
}
return needRevers;
},
getWrappedInfo: function (time, info) {
info = info || new WrappedInfo();
var stopped = false;
var duration = this.duration;
var ratio = 0;
var wrapMode = this.wrapMode;
var currentIterations = Math.abs(time / duration);
if (currentIterations > this.repeatCount) currentIterations = this.repeatCount;
var needRevers = false;
if (wrapMode & WrapModeMask.ShouldWrap) {
needRevers = this._needRevers(currentIterations);
}
var direction = needRevers ? -1 : 1;
if (this.speed < 0) direction *= -1;
if (currentIterations >= this.repeatCount) {
stopped = true;
var tempRatio = this.repeatCount - (this.repeatCount | 0);
if (tempRatio === 0) {
tempRatio = 1; // 如果播放过,动画不复位
}
time = tempRatio * duration * (time > 0 ? 1 : -1);
}
if (time > duration) {
var tempTime = time % duration;
time = tempTime === 0 ? duration : tempTime;
}
else if (time < 0) {
time = time % duration;
if (time !== 0 ) time += duration;
}
// calculate wrapped time
if (wrapMode & WrapModeMask.ShouldWrap) {
if (needRevers) time = duration - time;
}
ratio = time / duration;
info.ratio = ratio;
info.time = time;
info.direction = direction;
info.stopped = stopped;
info.iterations = currentIterations;
return info;
},
sample: function () {
var info = this.getWrappedInfo(this.time, this._wrappedInfo);
var curves = this.curves;
for (var i = 0, len = curves.length; i < len; i++) {
var curve = curves[i];
curve.sample(info.time, info.ratio, this);
}
return info;
},
onStop: function () {
this.emit('stop', this);
},
onPlay: function () {
this.emit('play', this);
},
onPause: function () {
this.emit('pause', this);
},
onResume: function () {
this.emit('resume', this);
}
});
if ((wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse) {
needRevers = !needRevers;
}
return needRevers;
};
cc.defineGetterSetter(AnimationNode.prototype, 'wrapMode',
proto.getWrappedInfo = function (time, info) {
info = info || new WrappedInfo();
var stopped = false;
var duration = this.duration;
var ratio = 0;
var wrapMode = this.wrapMode;
var currentIterations = Math.abs(time / duration);
if (currentIterations > this.repeatCount) currentIterations = this.repeatCount;
var needRevers = false;
if (wrapMode & WrapModeMask.ShouldWrap) {
needRevers = this._needRevers(currentIterations);
}
var direction = needRevers ? -1 : 1;
if (this.speed < 0) direction *= -1;
if (currentIterations >= this.repeatCount) {
stopped = true;
var tempRatio = this.repeatCount - (this.repeatCount | 0);
if (tempRatio === 0) {
tempRatio = 1; // 如果播放过,动画不复位
}
time = tempRatio * duration * (time > 0 ? 1 : -1);
}
if (time > duration) {
var tempTime = time % duration;
time = tempTime === 0 ? duration : tempTime;
}
else if (time < 0) {
time = time % duration;
if (time !== 0 ) time += duration;
}
// calculate wrapped time
if (wrapMode & WrapModeMask.ShouldWrap) {
if (needRevers) time = duration - time;
}
ratio = time / duration;
info.ratio = ratio;
info.time = time;
info.direction = direction;
info.stopped = stopped;
info.iterations = currentIterations;
return info;
};
proto.sample = function () {
var info = this.getWrappedInfo(this.time, this._wrappedInfo);
var curves = this.curves;
for (var i = 0, len = curves.length; i < len; i++) {
var curve = curves[i];
curve.sample(info.time, info.ratio, this);
}
return info;
};
proto.onStop = function () {
this.emit('stop', this);
};
proto.onPlay = function () {
this.emit('play', this);
};
proto.onPause = function () {
this.emit('pause', this);
};
proto.onResume = function () {
this.emit('resume', this);
};
JS.getset(proto, 'wrapMode',
function () {
return this._wrapMode;
},
@@ -438,13 +437,13 @@ cc.defineGetterSetter(AnimationNode.prototype, 'wrapMode',
}
);
cc.js.mixin(AnimationNode.prototype, cc.EventTarget.prototype);
cc.js.mixin(proto, cc.EventTarget.prototype);
cc.AnimationNode = AnimationNode;
module.exports = {
WrapModeMask: WrapModeMask,
WrapMode: WrapMode,
AnimationNode: AnimationNode,
WrappedInfo: WrappedInfo
WrapModeMask,
WrapMode,
AnimationNode,
WrappedInfo
};
+70 -69
View File
@@ -159,7 +159,7 @@ HashTimerEntry.put = function (entry) {
* Light weight timer
* @extends cc.Class
*/
var CallbackTimer = function () {
function CallbackTimer () {
this._scheduler = null;
this._elapsed = -1;
this._runForever = false;
@@ -171,84 +171,85 @@ var CallbackTimer = function () {
this._target = null;
this._callback = null;
}
var proto = CallbackTimer.prototype;
proto.initWithCallback = function (scheduler, callback, target, seconds, repeat, delay) {
this._scheduler = scheduler;
this._target = target;
this._callback = callback;
this._elapsed = -1;
this._interval = seconds;
this._delay = delay;
this._useDelay = (this._delay > 0);
this._repeat = repeat;
this._runForever = (this._repeat === cc.macro.REPEAT_FOREVER);
return true;
};
cc.js.mixin(CallbackTimer.prototype, {
initWithCallback: function (scheduler, callback, target, seconds, repeat, delay) {
this._scheduler = scheduler;
this._target = target;
this._callback = callback;
/**
* @return {Number} returns interval of timer
*/
proto.getInterval = function(){return this._interval;};
/**
* @param {Number} interval set interval in seconds
*/
proto.setInterval = function(interval){this._interval = interval;};
this._elapsed = -1;
this._interval = seconds;
this._delay = delay;
this._useDelay = (this._delay > 0);
this._repeat = repeat;
this._runForever = (this._repeat === cc.macro.REPEAT_FOREVER);
return true;
},
/**
* @return {Number} returns interval of timer
*/
getInterval : function(){return this._interval;},
/**
* @param {Number} interval set interval in seconds
*/
setInterval : function(interval){this._interval = interval;},
/**
* triggers the timer
* @param {Number} dt delta time
*/
proto.update = function (dt) {
if (this._elapsed === -1) {
this._elapsed = 0;
this._timesExecuted = 0;
} else {
this._elapsed += dt;
if (this._runForever && !this._useDelay) {//standard timer usage
if (this._elapsed >= this._interval) {
this.trigger();
this._elapsed = 0;
}
} else {//advanced usage
if (this._useDelay) {
if (this._elapsed >= this._delay) {
this.trigger();
/**
* triggers the timer
* @param {Number} dt delta time
*/
update: function (dt) {
if (this._elapsed === -1) {
this._elapsed = 0;
this._timesExecuted = 0;
} else {
this._elapsed += dt;
if (this._runForever && !this._useDelay) {//standard timer usage
this._elapsed -= this._delay;
this._timesExecuted += 1;
this._useDelay = false;
}
} else {
if (this._elapsed >= this._interval) {
this.trigger();
this._elapsed = 0;
this._timesExecuted += 1;
}
} else {//advanced usage
if (this._useDelay) {
if (this._elapsed >= this._delay) {
this.trigger();
this._elapsed -= this._delay;
this._timesExecuted += 1;
this._useDelay = false;
}
} else {
if (this._elapsed >= this._interval) {
this.trigger();
this._elapsed = 0;
this._timesExecuted += 1;
}
}
if (this._callback && !this._runForever && this._timesExecuted > this._repeat)
this.cancel();
}
if (this._callback && !this._runForever && this._timesExecuted > this._repeat)
this.cancel();
}
},
getCallback: function(){
return this._callback;
},
trigger: function () {
if (this._target && this._callback){
this._callback.call(this._target, this._elapsed);
}
},
cancel: function () {
//override
this._scheduler.unschedule(this._callback, this._target);
}
});
};
proto.getCallback = function(){
return this._callback;
};
proto.trigger = function () {
if (this._target && this._callback){
this._callback.call(this._target, this._elapsed);
}
};
proto.cancel = function () {
//override
this._scheduler.unschedule(this._callback, this._target);
};
var _timers = [];
CallbackTimer.get = function () {
+53 -54
View File
@@ -24,6 +24,7 @@
****************************************************************************/
var CCObject = require('../platform/CCObject');
var JS = require('../platform/js');
var idGenerater = new (require('../platform/id-generater'))('Comp');
var IsOnEnableCalled = CCObject.Flags.IsOnEnableCalled;
@@ -624,8 +625,8 @@ if (CC_EDITOR || CC_TEST) {
// NON-INHERITED STATIC MEMBERS
Object.defineProperty(Component, '_inspector', { value: '', writable: true });
Object.defineProperty(Component, '_icon', { value: '', writable: true });
JS.value(Component, '_inspector', '', true);
JS.value(Component, '_icon', '', true);
// COMPONENT HELPERS
@@ -640,67 +641,65 @@ if (CC_EDITOR || CC_TEST) {
};
}
// use defineProperty to prevent inherited by sub classes
Object.defineProperty(Component, '_registerEditorProps', {
value (cls, props) {
var reqComp = props.requireComponent;
if (reqComp) {
cls._requireComponent = reqComp;
}
var order = props.executionOrder;
if (order && typeof order === 'number') {
cls._executionOrder = order;
}
if (CC_EDITOR || CC_TEST) {
var name = cc.js.getClassName(cls);
for (var key in props) {
var val = props[key];
switch (key) {
case 'executeInEditMode':
cls._executeInEditMode = !!val;
break;
// we make this non-enumerable, to prevent inherited by sub classes.
JS.value(Component, '_registerEditorProps', function (cls, props) {
var reqComp = props.requireComponent;
if (reqComp) {
cls._requireComponent = reqComp;
}
var order = props.executionOrder;
if (order && typeof order === 'number') {
cls._executionOrder = order;
}
if (CC_EDITOR || CC_TEST) {
var name = cc.js.getClassName(cls);
for (var key in props) {
var val = props[key];
switch (key) {
case 'executeInEditMode':
cls._executeInEditMode = !!val;
break;
case 'playOnFocus':
if (val) {
var willExecuteInEditMode = ('executeInEditMode' in props) ? props.executeInEditMode : cls._executeInEditMode;
if (willExecuteInEditMode) {
cls._playOnFocus = true;
}
else {
cc.warnID(3601, name);
}
case 'playOnFocus':
if (val) {
var willExecuteInEditMode = ('executeInEditMode' in props) ? props.executeInEditMode : cls._executeInEditMode;
if (willExecuteInEditMode) {
cls._playOnFocus = true;
}
break;
else {
cc.warnID(3601, name);
}
}
break;
case 'inspector':
Object.defineProperty(cls, '_inspector', { value: val, writable: true });
break;
case 'inspector':
JS.value(cls, '_inspector', val, true);
break;
case 'icon':
Object.defineProperty(cls, '_icon', { value: val, writable: true });
break;
case 'icon':
JS.value(cls, '_icon', val, true);
break;
case 'menu':
Component._addMenuItem(cls, val, props.menuPriority);
break;
case 'menu':
Component._addMenuItem(cls, val, props.menuPriority);
break;
case 'disallowMultiple':
cls._disallowMultiple = cls;
break;
case 'disallowMultiple':
cls._disallowMultiple = cls;
break;
case 'requireComponent':
case 'executionOrder':
// skip here
break;
case 'requireComponent':
case 'executionOrder':
// skip here
break;
case 'help':
cls._help = val;
break;
case 'help':
cls._help = val;
break;
default:
cc.warnID(3602, key, name);
break;
}
default:
cc.warnID(3602, key, name);
break;
}
}
}
+262 -262
View File
@@ -49,156 +49,156 @@ var EventMouse = function (eventType, bubbles) {
};
JS.extend(EventMouse, cc.Event);
JS.mixin(EventMouse.prototype, {
/**
* !#en Sets scroll data.
* !#zh 设置鼠标的滚动数据。
* @method setScrollData
* @param {Number} scrollX
* @param {Number} scrollY
*/
setScrollData: function (scrollX, scrollY) {
this._scrollX = scrollX;
this._scrollY = scrollY;
},
var proto = EventMouse.prototype;
/**
* !#en Returns the x axis scroll value.
* !#zh 获取鼠标滚动的X轴距离,只有滚动时才有效。
* @method getScrollX
* @returns {Number}
*/
getScrollX: function () {
return this._scrollX;
},
/**
* !#en Sets scroll data.
* !#zh 设置鼠标的滚动数据。
* @method setScrollData
* @param {Number} scrollX
* @param {Number} scrollY
*/
proto.setScrollData = function (scrollX, scrollY) {
this._scrollX = scrollX;
this._scrollY = scrollY;
};
/**
* !#en Returns the y axis scroll value.
* !#zh 获取滚轮滚动的 Y 轴距离,只有滚动时才有效。
* @method getScrollY
* @returns {Number}
*/
getScrollY: function () {
return this._scrollY;
},
/**
* !#en Returns the x axis scroll value.
* !#zh 获取鼠标滚动的X轴距离,只有滚动时才有效。
* @method getScrollX
* @returns {Number}
*/
proto.getScrollX = function () {
return this._scrollX;
};
/**
* !#en Sets cursor location.
* !#zh 设置当前鼠标位置。
* @method setLocation
* @param {Number} x
* @param {Number} y
*/
setLocation: function (x, y) {
this._x = x;
this._y = y;
},
/**
* !#en Returns the y axis scroll value.
* !#zh 获取滚轮滚动的 Y 轴距离,只有滚动时才有效。
* @method getScrollY
* @returns {Number}
*/
proto.getScrollY = function () {
return this._scrollY;
};
/**
* !#en Returns cursor location.
* !#zh 获取鼠标位置对象,对象包含 x 和 y 属性。
* @method getLocation
* @return {Vec2} location
*/
getLocation: function () {
return {x: this._x, y: this._y};
},
/**
* !#en Sets cursor location.
* !#zh 设置当前鼠标位置。
* @method setLocation
* @param {Number} x
* @param {Number} y
*/
proto.setLocation = function (x, y) {
this._x = x;
this._y = y;
};
/**
* !#en Returns the current cursor location in screen coordinates.
* !#zh 获取当前事件在游戏窗口内的坐标位置对象,对象包含 x 和 y 属性。
* @method getLocationInView
* @return {Vec2}
*/
getLocationInView: function() {
return {x: this._x, y: cc.view._designResolutionSize.height - this._y};
},
/**
* !#en Returns cursor location.
* !#zh 获取鼠标位置对象,对象包含 x 和 y 属性。
* @method getLocation
* @return {Vec2} location
*/
proto.getLocation = function () {
return {x: this._x, y: this._y};
};
_setPrevCursor: function (x, y) {
this._prevX = x;
this._prevY = y;
},
/**
* !#en Returns the current cursor location in screen coordinates.
* !#zh 获取当前事件在游戏窗口内的坐标位置对象,对象包含 x 和 y 属性。
* @method getLocationInView
* @return {Vec2}
*/
proto.getLocationInView = function() {
return {x: this._x, y: cc.view._designResolutionSize.height - this._y};
};
/**
* !#en Returns the previous touch location.
* !#zh 获取鼠标点击在上一次事件时的位置对象,对象包含 x 和 y 属性。
* @method getPreviousLocation
* @return {Vec2}
*/
getPreviousLocation:function () {
return {x: this._prevX, y: this._prevY};
},
proto._setPrevCursor = function (x, y) {
this._prevX = x;
this._prevY = y;
};
/**
* !#en Returns the delta distance from the previous location to current location.
* !#zh 获取鼠标距离上一次事件移动的距离对象,对象包含 x 和 y 属性。
* @method getDelta
* @return {Vec2}
*/
getDelta: function () {
return {x: this._x - this._prevX, y: this._y - this._prevY};
},
/**
* !#en Returns the previous touch location.
* !#zh 获取鼠标点击在上一次事件时的位置对象,对象包含 x 和 y 属性。
* @method getPreviousLocation
* @return {Vec2}
*/
proto.getPreviousLocation = function () {
return {x: this._prevX, y: this._prevY};
};
/**
* !#en Returns the X axis delta distance from the previous location to current location.
* !#zh 获取鼠标距离上一次事件移动的 X 轴距离。
* @method getDeltaX
* @return {Number}
*/
getDeltaX: function () {
return this._x - this._prevX;
},
/**
* !#en Returns the delta distance from the previous location to current location.
* !#zh 获取鼠标距离上一次事件移动的距离对象,对象包含 x 和 y 属性。
* @method getDelta
* @return {Vec2}
*/
proto.getDelta = function () {
return {x: this._x - this._prevX, y: this._y - this._prevY};
};
/**
* !#en Returns the Y axis delta distance from the previous location to current location.
* !#zh 获取鼠标距离上一次事件移动的 Y 轴距离。
* @method getDeltaY
* @return {Number}
*/
getDeltaY: function () {
return this._y - this._prevY;
},
/**
* !#en Returns the X axis delta distance from the previous location to current location.
* !#zh 获取鼠标距离上一次事件移动的 X 轴距离。
* @method getDeltaX
* @return {Number}
*/
proto.getDeltaX = function () {
return this._x - this._prevX;
};
/**
* !#en Sets mouse button.
* !#zh 设置鼠标按键。
* @method setButton
* @param {Number} button
*/
setButton: function (button) {
this._button = button;
},
/**
* !#en Returns the Y axis delta distance from the previous location to current location.
* !#zh 获取鼠标距离上一次事件移动的 Y 轴距离。
* @method getDeltaY
* @return {Number}
*/
proto.getDeltaY = function () {
return this._y - this._prevY;
};
/**
* !#en Returns mouse button.
* !#zh 获取鼠标按键。
* @method getButton
* @returns {Number}
*/
getButton: function () {
return this._button;
},
/**
* !#en Sets mouse button.
* !#zh 设置鼠标按键。
* @method setButton
* @param {Number} button
*/
proto.setButton = function (button) {
this._button = button;
};
/**
* !#en Returns location X axis data.
* !#zh 获取鼠标当前位置 X 轴。
* @method getLocationX
* @returns {Number}
*/
getLocationX: function () {
return this._x;
},
/**
* !#en Returns mouse button.
* !#zh 获取鼠标按键。
* @method getButton
* @returns {Number}
*/
proto.getButton = function () {
return this._button;
};
/**
* !#en Returns location Y axis data.
* !#zh 获取鼠标当前位置 Y 轴。
* @method getLocationY
* @returns {Number}
*/
getLocationY: function () {
return this._y;
}
});
/**
* !#en Returns location X axis data.
* !#zh 获取鼠标当前位置 X 轴。
* @method getLocationX
* @returns {Number}
*/
proto.getLocationX = function () {
return this._x;
};
/**
* !#en Returns location Y axis data.
* !#zh 获取鼠标当前位置 Y 轴。
* @method getLocationY
* @returns {Number}
*/
proto.getLocationY = function () {
return this._y;
};
//Inner event types of MouseEvent
/**
@@ -334,146 +334,146 @@ var EventTouch = function (touchArr, bubbles) {
};
JS.extend(EventTouch, cc.Event);
JS.mixin(EventTouch.prototype, {
/**
* !#en Returns event code.
* !#zh 获取事件类型。
* @method getEventCode
* @returns {Number}
*/
getEventCode: function () {
return this._eventCode;
},
proto = EventTouch.prototype;
/**
* !#en Returns touches of event.
* !#zh 获取触摸点的列表。
* @method getTouches
* @returns {Array}
*/
getTouches: function () {
return this._touches;
},
/**
* !#en Returns event code.
* !#zh 获取事件类型。
* @method getEventCode
* @returns {Number}
*/
proto.getEventCode = function () {
return this._eventCode;
};
_setEventCode: function (eventCode) {
this._eventCode = eventCode;
},
/**
* !#en Returns touches of event.
* !#zh 获取触摸点的列表。
* @method getTouches
* @returns {Array}
*/
proto.getTouches = function () {
return this._touches;
};
_setTouches: function (touches) {
this._touches = touches;
},
proto._setEventCode = function (eventCode) {
this._eventCode = eventCode;
};
/**
* !#en Sets touch location.
* !#zh 设置当前触点位置
* @method setLocation
* @param {Number} x
* @param {Number} y
*/
setLocation: function (x, y) {
this.touch && this.touch.setTouchInfo(this.touch.getID(), x, y);
},
proto._setTouches = function (touches) {
this._touches = touches;
};
/**
* !#en Returns touch location.
* !#zh 获取触点位置。
* @method getLocation
* @return {Vec2} location
*/
getLocation: function () {
return this.touch ? this.touch.getLocation() : cc.v2();
},
/**
* !#en Sets touch location.
* !#zh 设置当前触点位置
* @method setLocation
* @param {Number} x
* @param {Number} y
*/
proto.setLocation = function (x, y) {
this.touch && this.touch.setTouchInfo(this.touch.getID(), x, y);
};
/**
* !#en Returns the current touch location in screen coordinates.
* !#zh 获取当前触点在游戏窗口中的位置。
* @method getLocationInView
* @return {Vec2}
*/
getLocationInView: function() {
return this.touch ? this.touch.getLocationInView() : cc.v2();
},
/**
* !#en Returns touch location.
* !#zh 获取触点位置。
* @method getLocation
* @return {Vec2} location
*/
proto.getLocation = function () {
return this.touch ? this.touch.getLocation() : cc.v2();
};
/**
* !#en Returns the previous touch location.
* !#zh 获取触点在上一次事件时的位置对象,对象包含 x 和 y 属性。
* @method getPreviousLocation
* @return {Vec2}
*/
getPreviousLocation:function () {
return this.touch ? this.touch.getPreviousLocation() : cc.v2();
},
/**
* !#en Returns the current touch location in screen coordinates.
* !#zh 获取当前触点在游戏窗口中的位置。
* @method getLocationInView
* @return {Vec2}
*/
proto.getLocationInView = function() {
return this.touch ? this.touch.getLocationInView() : cc.v2();
};
/**
* !#en Returns the start touch location.
* !#zh 获获取触点落下时的位置对象,对象包含 x 和 y 属性。
* @method getStartLocation
* @returns {Vec2}
*/
getStartLocation: function() {
return this.touch ? this.touch.getStartLocation() : cc.v2();
},
/**
* !#en Returns the previous touch location.
* !#zh 获取触点在上一次事件时的位置对象,对象包含 x 和 y 属性。
* @method getPreviousLocation
* @return {Vec2}
*/
proto.getPreviousLocation = function () {
return this.touch ? this.touch.getPreviousLocation() : cc.v2();
};
/**
* !#en Returns the id of cc.Touch.
* !#zh 触点的标识 ID,可以用来在多点触摸中跟踪触点。
* @method getID
* @return {Number}
*/
getID:function () {
return this.touch ? this.touch.getID() : null;
},
/**
* !#en Returns the start touch location.
* !#zh 获获取触点落下时的位置对象,对象包含 x 和 y 属性。
* @method getStartLocation
* @returns {Vec2}
*/
proto.getStartLocation = function() {
return this.touch ? this.touch.getStartLocation() : cc.v2();
};
/**
* !#en Returns the delta distance from the previous location to current location.
* !#zh 获取触点距离上一次事件移动的距离对象,对象包含 x 和 y 属性。
* @method getDelta
* @return {Vec2}
*/
getDelta: function () {
return this.touch ? this.touch.getDelta() : cc.v2();
},
/**
* !#en Returns the id of cc.Touch.
* !#zh 触点的标识 ID,可以用来在多点触摸中跟踪触点。
* @method getID
* @return {Number}
*/
proto.getID = function () {
return this.touch ? this.touch.getID() : null;
};
/**
* !#en Returns the X axis delta distance from the previous location to current location.
* !#zh 获取触点距离上一次事件移动的 x 轴距离。
* @method getDeltaX
* @return {Number}
*/
getDeltaX: function () {
return this.touch ? this.touch.getDelta().x : 0;
},
/**
* !#en Returns the delta distance from the previous location to current location.
* !#zh 获取触点距离上一次事件移动的距离对象,对象包含 x 和 y 属性。
* @method getDelta
* @return {Vec2}
*/
proto.getDelta = function () {
return this.touch ? this.touch.getDelta() : cc.v2();
};
/**
* !#en Returns the Y axis delta distance from the previous location to current location.
* !#zh 获取触点距离上一次事件移动的 y 轴距离。
* @method getDeltaY
* @return {Number}
*/
getDeltaY: function () {
return this.touch ? this.touch.getDelta().y : 0;
},
/**
* !#en Returns the X axis delta distance from the previous location to current location.
* !#zh 获取触点距离上一次事件移动的 x 轴距离。
* @method getDeltaX
* @return {Number}
*/
proto.getDeltaX = function () {
return this.touch ? this.touch.getDelta().x : 0;
},
/**
* !#en Returns location X axis data.
* !#zh 获取当前触点 X 轴位置。
* @method getLocationX
* @returns {Number}
*/
getLocationX: function () {
return this.touch ? this.touch.getLocationX() : 0;
},
/**
* !#en Returns the Y axis delta distance from the previous location to current location.
* !#zh 获取触点距离上一次事件移动的 y 轴距离。
* @method getDeltaY
* @return {Number}
*/
proto.getDeltaY = function () {
return this.touch ? this.touch.getDelta().y : 0;
};
/**
* !#en Returns location Y axis data.
* !#zh 获取当前触点 Y 轴位置。
* @method getLocationY
* @returns {Number}
*/
getLocationY: function () {
return this.touch ? this.touch.getLocationY() : 0;
}
});
/**
* !#en Returns location X axis data.
* !#zh 获取当前触点 X 轴位置。
* @method getLocationX
* @returns {Number}
*/
proto.getLocationX = function () {
return this.touch ? this.touch.getLocationX() : 0;
};
/**
* !#en Returns location Y axis data.
* !#zh 获取当前触点 Y 轴位置。
* @method getLocationY
* @returns {Number}
*/
proto.getLocationY = function () {
return this.touch ? this.touch.getLocationY() : 0;
};
/**
* !#en The maximum touch numbers
+253 -253
View File
@@ -116,7 +116,7 @@ var _doDispatchEvent = function (owner, event) {
*
* @class EventTarget
*/
var EventTarget = function () {
function EventTarget () {
/*
* @property _capturingListeners
* @type {EventListeners}
@@ -132,261 +132,261 @@ var EventTarget = function () {
* @private
*/
this._bubblingListeners = null;
}
var proto = EventTarget.prototype;
/**
* !#en Checks whether the EventTarget object has any callback registered for a specific type of event.
* !#zh 检查事件目标对象是否有为特定类型的事件注册的回调。
* @param {String} type - The type of event.
* @param {Boolean} checkCapture - Check for capturing or bubbling phase, check bubbling phase by default.
* @return {Boolean} True if a callback of the specified type is registered in specified phase; false otherwise.
*/
proto.hasEventListener = function (type, checkCapture) {
if (checkCapture && this._capturingListeners && this._capturingListeners.has(type))
return true;
if (!checkCapture && this._bubblingListeners && this._bubblingListeners.has(type))
return true;
return false;
};
JS.mixin(EventTarget.prototype, {
/**
* !#en Checks whether the EventTarget object has any callback registered for a specific type of event.
* !#zh 检查事件目标对象是否有为特定类型的事件注册的回调。
* @param {String} type - The type of event.
* @param {Boolean} checkCapture - Check for capturing or bubbling phase, check bubbling phase by default.
* @return {Boolean} True if a callback of the specified type is registered in specified phase; false otherwise.
*/
hasEventListener: function (type, checkCapture) {
if (checkCapture && this._capturingListeners && this._capturingListeners.has(type))
return true;
if (!checkCapture && this._bubblingListeners && this._bubblingListeners.has(type))
return true;
return false;
},
/**
* !#en
* Register an callback of a specific event type on the EventTarget.
* !#zh
* 注册事件目标的特定事件类型回调。
*
* @method on
* @param {String} type - A string representing the event type to listen for.
* @param {Function} callback - The callback that will be invoked when the event is dispatched.
* The callback is ignored if it is a duplicate (the callbacks are unique).
* @param {Event} callback.param event
* @param {Object} [target] - The target to invoke the callback, can be null
* @param {Boolean} [useCapture=false] - When set to true, the capture argument prevents callback
* from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE.
* When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE.
* Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET.
* @return {Function} - Just returns the incoming callback so you can save the anonymous function easier.
* @example
* node.on(cc.Node.EventType.TOUCH_END, function (event) {
* cc.log("this is callback");
* }, node);
*/
on: function (type, callback, target, useCapture) {
// Accept also patameters like: (type, callback, useCapture)
if (typeof target === 'boolean') {
useCapture = target;
target = undefined;
}
else useCapture = !!useCapture;
if (!callback) {
cc.errorID(6800);
return;
}
var listeners = null;
if (useCapture) {
listeners = this._capturingListeners = this._capturingListeners || new EventListeners();
}
else {
listeners = this._bubblingListeners = this._bubblingListeners || new EventListeners();
}
if ( ! listeners.has(type, callback, target) ) {
listeners.add(type, callback, target);
if (target && target.__eventTargets)
target.__eventTargets.push(this);
}
return callback;
},
/**
* !#en
* Removes the callback previously registered with the same type, callback, target and or useCapture.
* !#zh
* 删除之前与同类型,回调,目标或 useCapture 注册的回调。
*
* @method off
* @param {String} type - A string representing the event type being removed.
* @param {Function} callback - The callback to remove.
* @param {Object} [target] - The target to invoke the callback, if it's not given, only callback without target will be removed
* @param {Boolean} [useCapture=false] - Specifies whether the callback being removed was registered as a capturing callback or not.
* If not specified, useCapture defaults to false. If a callback was registered twice,
* one with capture and one without, each must be removed separately. Removal of a capturing callback
* does not affect a non-capturing version of the same listener, and vice versa.
* @example
* // register touchEnd eventListener
* var touchEnd = node.on(cc.Node.EventType.TOUCH_END, function (event) {
* cc.log("this is callback");
* }, node);
* // remove touchEnd eventListener
* node.off(cc.Node.EventType.TOUCH_END, touchEnd, node);
*/
off: function (type, callback, target, useCapture) {
// Accept also patameters like: (type, callback, useCapture)
if (typeof target === 'boolean') {
useCapture = target;
target = undefined;
}
else useCapture = !!useCapture;
if (!callback) {
return;
}
var listeners = useCapture ? this._capturingListeners : this._bubblingListeners;
if (listeners) {
listeners.remove(type, callback, target);
if (target && target.__eventTargets) {
fastRemove(target.__eventTargets, this);
}
}
},
/**
* !#en Removes all callbacks previously registered with the same target (passed as parameter).
* This is not for removing all listeners in the current event target,
* and this is not for removing all listeners the target parameter have registered.
* It's only for removing all listeners (callback and target couple) registered on the current event target by the target parameter.
* !#zh 在当前 EventTarget 上删除指定目标(target 参数)注册的所有事件监听器。
* 这个函数无法删除当前 EventTarget 的所有事件监听器,也无法删除 target 参数所注册的所有事件监听器。
* 这个函数只能删除 target 参数在当前 EventTarget 上注册的所有事件监听器。
* @method targetOff
* @param {Object} target - The target to be searched for all related listeners
*/
targetOff: function (target) {
if (this._capturingListeners) {
this._capturingListeners.removeAll(target);
}
if (this._bubblingListeners) {
this._bubblingListeners.removeAll(target);
}
},
/**
* !#en
* Register an callback of a specific event type on the EventTarget,
* the callback will remove itself after the first time it is triggered.
* !#zh
* 注册事件目标的特定事件类型回调,回调会在第一时间被触发后删除自身。
*
* @method once
* @param {String} type - A string representing the event type to listen for.
* @param {Function} callback - The callback that will be invoked when the event is dispatched.
* The callback is ignored if it is a duplicate (the callbacks are unique).
* @param {Event} callback.param event
* @param {Object} [target] - The target to invoke the callback, can be null
* @param {Boolean} [useCapture=false] - When set to true, the capture argument prevents callback
* from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE.
* When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE.
* Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET.
* @example
* node.once(cc.Node.EventType.TOUCH_END, function (event) {
* cc.log("this is callback");
* }, node);
*/
once: function (type, callback, target, useCapture) {
var self = this;
var cb = function (event) {
self.off(type, cb, target, useCapture);
callback.call(this, event);
};
this.on(type, cb, target, useCapture);
},
/**
* !#en
* Dispatches an event into the event flow.
* The event target is the EventTarget object upon which the dispatchEvent() method is called.
* !#zh 分发事件到事件流中。
*
* @method dispatchEvent
* @param {Event} event - The Event object that is dispatched into the event flow
*/
dispatchEvent: function (event) {
_doDispatchEvent(this, event);
cachedArray.length = 0;
},
/**
* !#en
* Send an event to this object directly, this method will not propagate the event to any other objects.
* The event will be created from the supplied message, you can get the "detail" argument from event.detail.
* !#zh
* 该对象直接发送事件, 这种方法不会对事件传播到任何其他对象。
*
* @method emit
* @param {String} message - the message to send
* @param {*} [detail] - whatever argument the message needs
*/
emit: function (message, detail) {
if (CC_DEV && typeof message !== 'string') {
cc.errorID(6801);
return;
}
//don't emit event when listeners are not exists.
var caplisteners = this._capturingListeners && this._capturingListeners._callbackTable[message];
var bublisteners = this._bubblingListeners && this._bubblingListeners._callbackTable[message];
if ((!caplisteners || caplisteners.length === 0) && (!bublisteners || bublisteners.length === 0)) {
return;
}
var event = cc.Event.EventCustom.get(message);
event.detail = detail;
// Event.AT_TARGET
event.eventPhase = 2;
event.target = event.currentTarget = this;
if (caplisteners) {
this._capturingListeners.invoke(event);
}
if (bublisteners && !event._propagationImmediateStopped) {
this._bubblingListeners.invoke(event);
}
cc.Event.EventCustom.put(event);
},
/*
* Get whether the target is active for events.
* The name is for avoiding conflict with user defined functions.
*
* Subclasses can override this method to make event target active or inactive.
* @method _isTargetActive
* @param {String} type - the event type
* @return {Boolean} - A boolean value indicates the event target is active or not
*/
_isTargetActive: function (type) {
return true;
},
/*
* Get all the targets listening to the supplied type of event in the target's capturing phase.
* The capturing phase comprises the journey from the root to the last node BEFORE the event target's node.
* The result should save in the array parameter, and MUST SORT from child nodes to parent nodes.
*
* Subclasses can override this method to make event propagable.
* @method _getCapturingTargets
* @param {String} type - the event type
* @param {Array} array - the array to receive targets
* @example {@link utils/api/engine/docs/cocos2d/core/event/_getCapturingTargets.js}
*/
_getCapturingTargets: function (type, array) {
},
/*
* Get all the targets listening to the supplied type of event in the target's bubbling phase.
* The bubbling phase comprises any SUBSEQUENT nodes encountered on the return trip to the root of the tree.
* The result should save in the array parameter, and MUST SORT from child nodes to parent nodes.
*
* Subclasses can override this method to make event propagable.
* @method _getBubblingTargets
* @param {String} type - the event type
* @param {Array} array - the array to receive targets
*/
_getBubblingTargets: function (type, array) {
// Object can override this method to make event propagable.
/**
* !#en
* Register an callback of a specific event type on the EventTarget.
* !#zh
* 注册事件目标的特定事件类型回调。
*
* @method on
* @param {String} type - A string representing the event type to listen for.
* @param {Function} callback - The callback that will be invoked when the event is dispatched.
* The callback is ignored if it is a duplicate (the callbacks are unique).
* @param {Event} callback.param event
* @param {Object} [target] - The target to invoke the callback, can be null
* @param {Boolean} [useCapture=false] - When set to true, the capture argument prevents callback
* from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE.
* When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE.
* Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET.
* @return {Function} - Just returns the incoming callback so you can save the anonymous function easier.
* @example
* node.on(cc.Node.EventType.TOUCH_END, function (event) {
* cc.log("this is callback");
* }, node);
*/
proto.on = function (type, callback, target, useCapture) {
// Accept also patameters like: (type, callback, useCapture)
if (typeof target === 'boolean') {
useCapture = target;
target = undefined;
}
});
else useCapture = !!useCapture;
if (!callback) {
cc.errorID(6800);
return;
}
var listeners = null;
if (useCapture) {
listeners = this._capturingListeners = this._capturingListeners || new EventListeners();
}
else {
listeners = this._bubblingListeners = this._bubblingListeners || new EventListeners();
}
if ( ! listeners.has(type, callback, target) ) {
listeners.add(type, callback, target);
if (target && target.__eventTargets)
target.__eventTargets.push(this);
}
return callback;
};
/**
* !#en
* Removes the callback previously registered with the same type, callback, target and or useCapture.
* !#zh
* 删除之前与同类型,回调,目标或 useCapture 注册的回调。
*
* @method off
* @param {String} type - A string representing the event type being removed.
* @param {Function} callback - The callback to remove.
* @param {Object} [target] - The target to invoke the callback, if it's not given, only callback without target will be removed
* @param {Boolean} [useCapture=false] - Specifies whether the callback being removed was registered as a capturing callback or not.
* If not specified, useCapture defaults to false. If a callback was registered twice,
* one with capture and one without, each must be removed separately. Removal of a capturing callback
* does not affect a non-capturing version of the same listener, and vice versa.
* @example
* // register touchEnd eventListener
* var touchEnd = node.on(cc.Node.EventType.TOUCH_END, function (event) {
* cc.log("this is callback");
* }, node);
* // remove touchEnd eventListener
* node.off(cc.Node.EventType.TOUCH_END, touchEnd, node);
*/
proto.off = function (type, callback, target, useCapture) {
// Accept also patameters like: (type, callback, useCapture)
if (typeof target === 'boolean') {
useCapture = target;
target = undefined;
}
else useCapture = !!useCapture;
if (!callback) {
return;
}
var listeners = useCapture ? this._capturingListeners : this._bubblingListeners;
if (listeners) {
listeners.remove(type, callback, target);
if (target && target.__eventTargets) {
fastRemove(target.__eventTargets, this);
}
}
};
/**
* !#en Removes all callbacks previously registered with the same target (passed as parameter).
* This is not for removing all listeners in the current event target,
* and this is not for removing all listeners the target parameter have registered.
* It's only for removing all listeners (callback and target couple) registered on the current event target by the target parameter.
* !#zh 在当前 EventTarget 上删除指定目标(target 参数)注册的所有事件监听器。
* 这个函数无法删除当前 EventTarget 的所有事件监听器,也无法删除 target 参数所注册的所有事件监听器。
* 这个函数只能删除 target 参数在当前 EventTarget 上注册的所有事件监听器。
* @method targetOff
* @param {Object} target - The target to be searched for all related listeners
*/
proto.targetOff = function (target) {
if (this._capturingListeners) {
this._capturingListeners.removeAll(target);
}
if (this._bubblingListeners) {
this._bubblingListeners.removeAll(target);
}
};
/**
* !#en
* Register an callback of a specific event type on the EventTarget,
* the callback will remove itself after the first time it is triggered.
* !#zh
* 注册事件目标的特定事件类型回调,回调会在第一时间被触发后删除自身。
*
* @method once
* @param {String} type - A string representing the event type to listen for.
* @param {Function} callback - The callback that will be invoked when the event is dispatched.
* The callback is ignored if it is a duplicate (the callbacks are unique).
* @param {Event} callback.param event
* @param {Object} [target] - The target to invoke the callback, can be null
* @param {Boolean} [useCapture=false] - When set to true, the capture argument prevents callback
* from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE.
* When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE.
* Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET.
* @example
* node.once(cc.Node.EventType.TOUCH_END, function (event) {
* cc.log("this is callback");
* }, node);
*/
proto.once = function (type, callback, target, useCapture) {
var self = this;
var cb = function (event) {
self.off(type, cb, target, useCapture);
callback.call(this, event);
};
this.on(type, cb, target, useCapture);
};
/**
* !#en
* Dispatches an event into the event flow.
* The event target is the EventTarget object upon which the dispatchEvent() method is called.
* !#zh 分发事件到事件流中。
*
* @method dispatchEvent
* @param {Event} event - The Event object that is dispatched into the event flow
*/
proto.dispatchEvent = function (event) {
_doDispatchEvent(this, event);
cachedArray.length = 0;
};
/**
* !#en
* Send an event to this object directly, this method will not propagate the event to any other objects.
* The event will be created from the supplied message, you can get the "detail" argument from event.detail.
* !#zh
* 该对象直接发送事件, 这种方法不会对事件传播到任何其他对象。
*
* @method emit
* @param {String} message - the message to send
* @param {*} [detail] - whatever argument the message needs
*/
proto.emit = function (message, detail) {
if (CC_DEV && typeof message !== 'string') {
cc.errorID(6801);
return;
}
//don't emit event when listeners are not exists.
var caplisteners = this._capturingListeners && this._capturingListeners._callbackTable[message];
var bublisteners = this._bubblingListeners && this._bubblingListeners._callbackTable[message];
if ((!caplisteners || caplisteners.length === 0) && (!bublisteners || bublisteners.length === 0)) {
return;
}
var event = cc.Event.EventCustom.get(message);
event.detail = detail;
// Event.AT_TARGET
event.eventPhase = 2;
event.target = event.currentTarget = this;
if (caplisteners) {
this._capturingListeners.invoke(event);
}
if (bublisteners && !event._propagationImmediateStopped) {
this._bubblingListeners.invoke(event);
}
cc.Event.EventCustom.put(event);
};
/*
* Get whether the target is active for events.
* The name is for avoiding conflict with user defined functions.
*
* Subclasses can override this method to make event target active or inactive.
* @method _isTargetActive
* @param {String} type - the event type
* @return {Boolean} - A boolean value indicates the event target is active or not
*/
proto._isTargetActive = function (type) {
return true;
};
/*
* Get all the targets listening to the supplied type of event in the target's capturing phase.
* The capturing phase comprises the journey from the root to the last node BEFORE the event target's node.
* The result should save in the array parameter, and MUST SORT from child nodes to parent nodes.
*
* Subclasses can override this method to make event propagable.
* @method _getCapturingTargets
* @param {String} type - the event type
* @param {Array} array - the array to receive targets
* @example {@link utils/api/engine/docs/cocos2d/core/event/_getCapturingTargets.js}
*/
proto._getCapturingTargets = function (type, array) {
};
/*
* Get all the targets listening to the supplied type of event in the target's bubbling phase.
* The bubbling phase comprises any SUBSEQUENT nodes encountered on the return trip to the root of the tree.
* The result should save in the array parameter, and MUST SORT from child nodes to parent nodes.
*
* Subclasses can override this method to make event propagable.
* @method _getBubblingTargets
* @param {String} type - the event type
* @param {Array} array - the array to receive targets
*/
proto._getBubblingTargets = function (type, array) {
// Object can override this method to make event propagable.
};
// Improve performance of function call (avoid using EventTarget.prototype.on.call)
EventTarget.prototype._EventTargetOn = EventTarget.prototype.on;
EventTarget.prototype._EventTargetOnce = EventTarget.prototype.once;
+28 -28
View File
@@ -294,37 +294,37 @@ var EventCustom = function (type, bubbles) {
};
JS.extend(EventCustom, cc.Event);
JS.mixin(EventCustom.prototype, {
reset: EventCustom,
/**
* !#en Sets user data
* !#zh 设置用户数据
* @method setUserData
* @param {*} data
*/
setUserData: function (data) {
this.detail = data;
},
EventCustom.prototype.reset = EventCustom;
/**
* !#en Gets user data
* !#zh 获取用户数据
* @method getUserData
* @returns {*}
*/
getUserData: function () {
return this.detail;
},
/**
* !#en Sets user data
* !#zh 设置用户数据
* @method setUserData
* @param {*} data
*/
EventCustom.prototype.setUserData = function (data) {
this.detail = data;
};
/**
* !#en Gets user data
* !#zh 获取用户数据
* @method getUserData
* @returns {*}
*/
EventCustom.prototype.getUserData = function () {
return this.detail;
};
/**
* !#en Gets event name
* !#zh 获取事件名称
* @method getEventName
* @returns {String}
*/
EventCustom.prototype.getEventName = cc.Event.prototype.getType;
/**
* !#en Gets event name
* !#zh 获取事件名称
* @method getEventName
* @returns {String}
*/
getEventName: cc.Event.prototype.getType
});
var _eventPool = [];
var MAX_POOL_SIZE = 10;
+117 -118
View File
@@ -93,128 +93,127 @@ _p.rendering = function (ctx, scaleX, scaleY) {
};
// draw api
Js.mixin(_p, {
setStrokeColor: function (v) {
var strokeStyle = 'rgba(' + (0 | v.r) + ',' + (0 | v.g) + ',' + (0 | v.b) + ',' + v.a / 255 + ')';
this.cmds.push(['strokeStyle', strokeStyle]);
this.style.strokeStyle = strokeStyle;
},
setFillColor: function (v) {
var fillStyle = 'rgba(' + (0 | v.r) + ',' + (0 | v.g) + ',' + (0 | v.b) + ',' + v.a / 255 + ')';
this.cmds.push(['fillStyle', fillStyle]);
this.style.fillStyle = fillStyle;
},
_p.setStrokeColor = function (v) {
var strokeStyle = 'rgba(' + (0 | v.r) + ',' + (0 | v.g) + ',' + (0 | v.b) + ',' + v.a / 255 + ')';
this.cmds.push(['strokeStyle', strokeStyle]);
this.style.strokeStyle = strokeStyle;
};
setLineWidth: function (v) {
this.cmds.push(['lineWidth', v]);
this.style.lineWidth = v;
},
_p.setFillColor = function (v) {
var fillStyle = 'rgba(' + (0 | v.r) + ',' + (0 | v.g) + ',' + (0 | v.b) + ',' + v.a / 255 + ')';
this.cmds.push(['fillStyle', fillStyle]);
this.style.fillStyle = fillStyle;
};
setLineCap: function (v) {
var lineCap = 'butt';
if (v === LineCap.BUTT) {
lineCap = 'butt';
}
else if (v === LineCap.ROUND) {
lineCap = 'round';
}
else if (v === LineCap.SQUARE) {
lineCap = 'square';
}
this.cmds.push(['lineCap', lineCap]);
this.style.lineCap = lineCap;
},
_p.setLineWidth = function (v) {
this.cmds.push(['lineWidth', v]);
this.style.lineWidth = v;
};
setLineJoin: function (v) {
var lineJoin = 'bevel';
if (v === LineJoin.BEVEL) {
lineJoin = 'bevel';
}
else if (v === LineJoin.ROUND) {
lineJoin = 'round';
}
else if (v === LineJoin.MITER) {
lineJoin = 'miter';
}
this.cmds.push(['lineJoin', lineJoin]);
this.style.lineJoin = lineJoin;
},
setMiterLimit: function (v) {
this.cmds.push(['miterLimit', v]);
this.style.miterLimit = v;
},
// draw functions
beginPath: function () {
},
moveTo: function (x, y) {
this.cmds.push(['moveTo', [x, y]]);
},
lineTo: function (x, y) {
this.cmds.push(['lineTo', [x, y]]);
},
bezierCurveTo: function (c1x, c1y, c2x, c2y, x, y) {
this.cmds.push(['bezierCurveTo', [c1x, c1y, c2x, c2y, x, y]]);
},
quadraticCurveTo: function (cx, cy, x, y) {
this.cmds.push(['quadraticCurveTo', [cx, cy, x, y]]);
},
arc: function (cx, cy, r, startAngle, endAngle, counterclockwise) {
Helper.arc(this, cx, cy, r, startAngle, endAngle, counterclockwise);
},
ellipse: function (cx, cy, rx, ry) {
Helper.ellipse(this, cx, cy, rx, ry);
},
circle: function (cx, cy, r) {
Helper.ellipse(this, cx, cy, r, r);
},
rect: function (x, y, w, h) {
this.moveTo(x, y);
this.lineTo(x+w, y);
this.lineTo(x+w, y+h);
this.lineTo(x, y+h);
this.close();
},
roundRect: function (x, y, w, h, r) {
Helper.roundRect(this, x, y, w, h, r);
},
fillRect: function (x, y, w, h) {
this.cmds.push(['fillRect', [x, y, w, h]]);
this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
},
close: function () {
this.cmds.push(['closePath', []]);
},
stroke: function () {
this.cmds.push(['stroke', []]);
this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
},
fill: function () {
this.cmds.push(['fill', []]);
this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
},
clear: function () {
this.cmds.length = 0;
this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
_p.setLineCap = function (v) {
var lineCap = 'butt';
if (v === LineCap.BUTT) {
lineCap = 'butt';
}
});
else if (v === LineCap.ROUND) {
lineCap = 'round';
}
else if (v === LineCap.SQUARE) {
lineCap = 'square';
}
this.cmds.push(['lineCap', lineCap]);
this.style.lineCap = lineCap;
};
_p.setLineJoin = function (v) {
var lineJoin = 'bevel';
if (v === LineJoin.BEVEL) {
lineJoin = 'bevel';
}
else if (v === LineJoin.ROUND) {
lineJoin = 'round';
}
else if (v === LineJoin.MITER) {
lineJoin = 'miter';
}
this.cmds.push(['lineJoin', lineJoin]);
this.style.lineJoin = lineJoin;
};
_p.setMiterLimit = function (v) {
this.cmds.push(['miterLimit', v]);
this.style.miterLimit = v;
};
// draw functions
_p.beginPath = function () {
};
_p.moveTo = function (x, y) {
this.cmds.push(['moveTo', [x, y]]);
};
_p.lineTo = function (x, y) {
this.cmds.push(['lineTo', [x, y]]);
};
_p.bezierCurveTo = function (c1x, c1y, c2x, c2y, x, y) {
this.cmds.push(['bezierCurveTo', [c1x, c1y, c2x, c2y, x, y]]);
};
_p.quadraticCurveTo = function (cx, cy, x, y) {
this.cmds.push(['quadraticCurveTo', [cx, cy, x, y]]);
};
_p.arc = function (cx, cy, r, startAngle, endAngle, counterclockwise) {
Helper.arc(this, cx, cy, r, startAngle, endAngle, counterclockwise);
};
_p.ellipse = function (cx, cy, rx, ry) {
Helper.ellipse(this, cx, cy, rx, ry);
};
_p.circle = function (cx, cy, r) {
Helper.ellipse(this, cx, cy, r, r);
};
_p.rect = function (x, y, w, h) {
this.moveTo(x, y);
this.lineTo(x+w, y);
this.lineTo(x+w, y+h);
this.lineTo(x, y+h);
this.close();
};
_p.roundRect = function (x, y, w, h, r) {
Helper.roundRect(this, x, y, w, h, r);
};
_p.fillRect = function (x, y, w, h) {
this.cmds.push(['fillRect', [x, y, w, h]]);
this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
};
_p.close = function () {
this.cmds.push(['closePath', []]);
};
_p.stroke = function () {
this.cmds.push(['stroke', []]);
this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
};
_p.fill = function () {
this.cmds.push(['fill', []]);
this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
};
_p.clear = function () {
this.cmds.length = 0;
this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
};
module.exports = CanvasRenderCmd;
+95 -96
View File
@@ -58,124 +58,123 @@ var GraphicsNode = _ccsg.Node.extend({
var _p = GraphicsNode.prototype;
// draw api
Js.mixin(_p, {
// properties
_strokeColor: null,
_fillColor: null,
_lineWidth: 1,
// properties
_p._strokeColor = null;
_p._fillColor = null;
_lineCap: LineCap.BUTT,
_lineJoin: LineJoin.MITER,
_p._lineWidth = 1;
_miterLimit: 10,
_p._lineCap = LineCap.BUTT;
_p._lineJoin = LineJoin.MITER;
setStrokeColor: function (v) {
this._strokeColor = v;
this._renderCmd.setStrokeColor(v);
},
getStrokeColor: function () {
return this._strokeColor;
},
_p._miterLimit = 10;
setFillColor: function (v) {
this._fillColor = v;
this._renderCmd.setFillColor(v);
},
getFillColor: function () {
return this._fillColor;
},
_p.setStrokeColor = function (v) {
this._strokeColor = v;
this._renderCmd.setStrokeColor(v);
};
_p.getStrokeColor = function () {
return this._strokeColor;
};
setLineWidth: function (v) {
this._lineWidth = v;
this._renderCmd.setLineWidth(v);
},
getLineWidth: function () {
return this._lineWidth;
},
_p.setFillColor = function (v) {
this._fillColor = v;
this._renderCmd.setFillColor(v);
};
_p.getFillColor = function () {
return this._fillColor;
};
setLineCap: function (v) {
this._lineCap = v;
this._renderCmd.setLineCap(v);
},
getLineCap: function () {
return this._lineCap;
},
_p.setLineWidth = function (v) {
this._lineWidth = v;
this._renderCmd.setLineWidth(v);
};
_p.getLineWidth = function () {
return this._lineWidth;
};
setLineJoin: function (v) {
this._lineJoin = v;
this._renderCmd.setLineJoin(v);
},
getLineJoin: function () {
return this._lineJoin;
},
_p.setLineCap = function (v) {
this._lineCap = v;
this._renderCmd.setLineCap(v);
};
_p.getLineCap = function () {
return this._lineCap;
};
setMiterLimit: function (v) {
this._miterLimit = v;
this._renderCmd.setMiterLimit(v);
},
getMiterLimit: function () {
return this._miterLimit;
},
_p.setLineJoin = function (v) {
this._lineJoin = v;
this._renderCmd.setLineJoin(v);
};
_p.getLineJoin = function () {
return this._lineJoin;
};
// draw functions
beginPath: function () {
this._renderCmd.beginPath();
},
_p.setMiterLimit = function (v) {
this._miterLimit = v;
this._renderCmd.setMiterLimit(v);
};
_p.getMiterLimit = function () {
return this._miterLimit;
};
moveTo: function (x, y) {
this._renderCmd.moveTo(x, y);
},
// draw functions
lineTo: function (x, y) {
this._renderCmd.lineTo(x, y);
},
_p.beginPath = function () {
this._renderCmd.beginPath();
};
bezierCurveTo: function (c1x, c1y, c2x, c2y, x, y) {
this._renderCmd.bezierCurveTo(c1x, c1y, c2x, c2y, x, y);
},
_p.moveTo = function (x, y) {
this._renderCmd.moveTo(x, y);
};
quadraticCurveTo: function (cx, cy, x, y) {
this._renderCmd.quadraticCurveTo(cx, cy, x, y);
},
_p.lineTo = function (x, y) {
this._renderCmd.lineTo(x, y);
};
//
arc: function (cx, cy, r, a0, a1, counterclockwise) {
this._renderCmd.arc(cx, cy, r, a0, a1, counterclockwise);
},
_p.bezierCurveTo = function (c1x, c1y, c2x, c2y, x, y) {
this._renderCmd.bezierCurveTo(c1x, c1y, c2x, c2y, x, y);
};
ellipse: function (cx, cy, rx, ry) {
this._renderCmd.ellipse(cx, cy, rx, ry);
},
_p.quadraticCurveTo = function (cx, cy, x, y) {
this._renderCmd.quadraticCurveTo(cx, cy, x, y);
};
circle: function (cx, cy, r) {
this._renderCmd.circle(cx, cy, r);
},
//
_p.arc = function (cx, cy, r, a0, a1, counterclockwise) {
this._renderCmd.arc(cx, cy, r, a0, a1, counterclockwise);
};
rect: function (x, y, w, h) {
this._renderCmd.rect(x, y, w, h);
},
_p.ellipse = function (cx, cy, rx, ry) {
this._renderCmd.ellipse(cx, cy, rx, ry);
};
roundRect: function (x, y, w, h, r) {
this._renderCmd.roundRect(x, y, w, h, r);
},
_p.circle = function (cx, cy, r) {
this._renderCmd.circle(cx, cy, r);
};
fillRect: function (x, y, w, h) {
this._renderCmd.fillRect(x, y, w, h);
},
_p.rect = function (x, y, w, h) {
this._renderCmd.rect(x, y, w, h);
};
close: function () {
this._renderCmd.close();
},
_p.roundRect = function (x, y, w, h, r) {
this._renderCmd.roundRect(x, y, w, h, r);
};
stroke: function () {
this._renderCmd.stroke();
},
_p.fillRect = function (x, y, w, h) {
this._renderCmd.fillRect(x, y, w, h);
};
fill: function () {
this._renderCmd.fill();
}
});
_p.close = function () {
this._renderCmd.close();
};
_p.stroke = function () {
this._renderCmd.stroke();
};
_p.fill = function () {
this._renderCmd.fill();
};
module.exports = GraphicsNode;
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+100 -100
View File
@@ -47,121 +47,121 @@ function isMatchByWord (path, test) {
return true;
}
cc.js.mixin(AssetTable.prototype, {
var proto = AssetTable.prototype;
getUuid: function (path, type) {
path = cc.url.normalize(path);
var item = this._pathToUuid[path];
if (item) {
proto.getUuid = function (path, type) {
path = cc.url.normalize(path);
var item = this._pathToUuid[path];
if (item) {
if (Array.isArray(item)) {
if (type) {
for (var i = 0; i < item.length; i++) {
var entry = item[i];
if (cc.isChildClassOf(entry.type, type)) {
return entry.uuid;
}
}
}
else {
return item[0].uuid;
}
}
else if (!type || cc.isChildClassOf(item.type, type)) {
return item.uuid;
}
}
return '';
};
proto.getUuidArray = function (path, type, out_urls) {
path = cc.url.normalize(path);
if (path[path.length - 1] === '/') {
path = path.slice(0, -1);
}
var path2uuid = this._pathToUuid;
var uuids = [];
var isChildClassOf = cc.isChildClassOf;
for (var p in path2uuid) {
if ((p.startsWith(path) && isMatchByWord(p, path)) || !path) {
var item = path2uuid[p];
if (Array.isArray(item)) {
if (type) {
for (var i = 0; i < item.length; i++) {
var entry = item[i];
if (cc.isChildClassOf(entry.type, type)) {
return entry.uuid;
}
}
}
else {
return item[0].uuid;
}
}
else if (!type || cc.isChildClassOf(item.type, type)) {
return item.uuid;
}
}
return '';
},
getUuidArray: function (path, type, out_urls) {
path = cc.url.normalize(path);
if (path[path.length - 1] === '/') {
path = path.slice(0, -1);
}
var path2uuid = this._pathToUuid;
var uuids = [];
var isChildClassOf = cc.isChildClassOf;
for (var p in path2uuid) {
if ((p.startsWith(path) && isMatchByWord(p, path)) || !path) {
var item = path2uuid[p];
if (Array.isArray(item)) {
for (var i = 0; i < item.length; i++) {
var entry = item[i];
if (!type || isChildClassOf(entry.type, type)) {
uuids.push(entry.uuid);
if (out_urls) {
out_urls.push(p);
}
}
}
}
else {
if (!type || isChildClassOf(item.type, type)) {
uuids.push(item.uuid);
for (var i = 0; i < item.length; i++) {
var entry = item[i];
if (!type || isChildClassOf(entry.type, type)) {
uuids.push(entry.uuid);
if (out_urls) {
out_urls.push(p);
}
}
}
}
}
return uuids;
},
/**
* !#en Returns all asset paths in the table.
* !#zh 返回表中的所有资源路径。
* @method getAllPaths
* @return {string[]}
*/
getAllPaths: function () {
return Object.keys(this._pathToUuid);
},
/**
* !#en TODO
* !#zh 以路径为 key,uuid 为值添加到表中。
* @method add
* @param {String} path - the path to load, should NOT include filename extensions.
* @param {String} uuid
* @param {Function} type
* @param {Boolean} isMainAsset
* @private
*/
add: function (path, uuid, type, isMainAsset) {
// remove extname
// (can not use path.slice because length of extname maybe 0)
path = path.substring(0, path.length - cc.path.extname(path).length);
var newEntry = new Entry(uuid, type);
var pathToUuid = this._pathToUuid;
var exists = pathToUuid[path];
if (exists) {
if (Array.isArray(exists)) {
if (isMainAsset) {
// load main asset first
exists.unshift(newEntry);
}
else {
exists.push(newEntry);
else {
if (!type || isChildClassOf(item.type, type)) {
uuids.push(item.uuid);
if (out_urls) {
out_urls.push(p);
}
}
}
}
}
return uuids;
};
/**
* !#en Returns all asset paths in the table.
* !#zh 返回表中的所有资源路径。
* @method getAllPaths
* @return {string[]}
*/
proto.getAllPaths = function () {
return Object.keys(this._pathToUuid);
};
/**
* !#en TODO
* !#zh 以路径为 key,uuid 为值添加到表中。
* @method add
* @param {String} path - the path to load, should NOT include filename extensions.
* @param {String} uuid
* @param {Function} type
* @param {Boolean} isMainAsset
* @private
*/
proto.add = function (path, uuid, type, isMainAsset) {
// remove extname
// (can not use path.slice because length of extname maybe 0)
path = path.substring(0, path.length - cc.path.extname(path).length);
var newEntry = new Entry(uuid, type);
var pathToUuid = this._pathToUuid;
var exists = pathToUuid[path];
if (exists) {
if (Array.isArray(exists)) {
if (isMainAsset) {
// load main asset first
exists.unshift(newEntry);
}
else {
if (isMainAsset) {
pathToUuid[path] = [newEntry, exists];
}
else {
pathToUuid[path] = [exists, newEntry];
}
exists.push(newEntry);
}
}
else {
pathToUuid[path] = newEntry;
if (isMainAsset) {
pathToUuid[path] = [newEntry, exists];
}
else {
pathToUuid[path] = [exists, newEntry];
}
}
},
reset: function () {
this._pathToUuid = {};
}
});
else {
pathToUuid[path] = newEntry;
}
};
proto.reset = function () {
this._pathToUuid = {};
};
module.exports = AssetTable;
+37 -38
View File
@@ -319,47 +319,46 @@ var Downloader = function (extMap) {
this.extMap = JS.mixin(extMap, defaultMap);
};
Downloader.ID = ID;
JS.mixin(Downloader.prototype, {
/**
* Add custom supported types handler or modify existing type handler.
* @method addHandlers
* @param {Object} extMap Custom supported types with corresponded handler
*/
addHandlers: function (extMap) {
JS.mixin(this.extMap, extMap);
},
handle: function (item, callback) {
var self = this;
var downloadFunc = this.extMap[item.type] || this.extMap['default'];
if (this._curConcurrent < this.maxConcurrent) {
this._curConcurrent++;
downloadFunc.call(this, item, function (err, result) {
// Concurrent logic
self._curConcurrent = Math.max(0, self._curConcurrent - 1);
while (self._curConcurrent < self.maxConcurrent) {
var nextOne = self._loadQueue.shift();
if (!nextOne) {
break;
}
self.handle(nextOne.item, nextOne.callback);
/**
* Add custom supported types handler or modify existing type handler.
* @method addHandlers
* @param {Object} extMap Custom supported types with corresponded handler
*/
Downloader.prototype.addHandlers = function (extMap) {
JS.mixin(this.extMap, extMap);
};
Downloader.prototype.handle = function (item, callback) {
var self = this;
var downloadFunc = this.extMap[item.type] || this.extMap['default'];
if (this._curConcurrent < this.maxConcurrent) {
this._curConcurrent++;
downloadFunc.call(this, item, function (err, result) {
// Concurrent logic
self._curConcurrent = Math.max(0, self._curConcurrent - 1);
while (self._curConcurrent < self.maxConcurrent) {
var nextOne = self._loadQueue.shift();
if (!nextOne) {
break;
}
self.handle(nextOne.item, nextOne.callback);
}
callback && callback(err, result);
});
}
else if (item.ignoreMaxConcurrency) {
downloadFunc.call(this, item, function (err, result) {
callback && callback(err, result);
});
}
else {
this._loadQueue.push({
item: item,
callback: callback
});
}
callback && callback(err, result);
});
}
});
else if (item.ignoreMaxConcurrency) {
downloadFunc.call(this, item, function (err, result) {
callback && callback(err, result);
});
}
else {
this._loadQueue.push({
item: item,
callback: callback
});
}
};
Pipeline.Downloader = module.exports = Downloader;
+20 -21
View File
@@ -137,27 +137,26 @@ var Loader = function (extMap) {
this.extMap = JS.mixin(extMap, defaultMap);
};
Loader.ID = ID;
JS.mixin(Loader.prototype, {
/**
* Add custom supported types handler or modify existing type handler.
* @method addHandlers
* @param {Object} extMap Custom supported types with corresponded handler
*/
addHandlers: function (extMap) {
this.extMap = JS.mixin(this.extMap, extMap);
},
handle: function (item, callback) {
var loadFunc = this.extMap[item.type] || this.extMap['default'];
loadFunc.call(this, item, function (err, result) {
if (err) {
callback && callback(err);
}
else {
callback && callback(null, result);
}
});
}
});
/**
* Add custom supported types handler or modify existing type handler.
* @method addHandlers
* @param {Object} extMap Custom supported types with corresponded handler
*/
Loader.prototype.addHandlers = function (extMap) {
this.extMap = JS.mixin(this.extMap, extMap);
};
Loader.prototype.handle = function (item, callback) {
var loadFunc = this.extMap[item.type] || this.extMap['default'];
loadFunc.call(this, item, function (err, result) {
if (err) {
callback && callback(err);
}
else {
callback && callback(null, result);
}
});
};
Pipeline.Loader = module.exports = Loader;
+302 -301
View File
@@ -449,315 +449,316 @@ LoadingItems.finishDep = function (depId) {
}
};
JS.mixin(LoadingItems.prototype, CallbacksInvoker.prototype, {
/**
* !#en Add urls to the LoadingItems queue.
* !#zh 向一个 LoadingItems 队列添加加载项。
* @method append
* @param {Array} urlList The url list to be appended, the url can be object or string
* @return {Array} The accepted url list, some invalid items could be refused.
*/
append: function (urlList, owner) {
if (!this.active) {
return [];
}
var proto = LoadingItems.prototype;
JS.mixin(proto, CallbacksInvoker.prototype);
this._appending = true;
var accepted = [], i, url, item;
for (i = 0; i < urlList.length; ++i) {
url = urlList[i];
/**
* !#en Add urls to the LoadingItems queue.
* !#zh 向一个 LoadingItems 队列添加加载项。
* @method append
* @param {Array} urlList The url list to be appended, the url can be object or string
* @return {Array} The accepted url list, some invalid items could be refused.
*/
proto.append = function (urlList, owner) {
if (!this.active) {
return [];
}
// Already queued in another items queue, url is actually the item
if (url.queueId && !this.map[url.id]) {
this.map[url.id] = url;
// Queued and completed or Owner circle referenced by dependency
if (url.complete || checkCircleReference(owner, url)) {
this._appending = true;
var accepted = [], i, url, item;
for (i = 0; i < urlList.length; ++i) {
url = urlList[i];
// Already queued in another items queue, url is actually the item
if (url.queueId && !this.map[url.id]) {
this.map[url.id] = url;
// Queued and completed or Owner circle referenced by dependency
if (url.complete || checkCircleReference(owner, url)) {
this.totalCount++;
// console.log('----- Completed already or circle referenced ' + url.id + ', rest: ' + (this.totalCount - this.completedCount-1));
this.itemComplete(url.id);
continue;
}
// Not completed yet, should wait it
else {
var self = this;
var queue = _queues[url.queueId];
if (queue) {
this.totalCount++;
// console.log('----- Completed already or circle referenced ' + url.id + ', rest: ' + (this.totalCount - this.completedCount-1));
this.itemComplete(url.id);
continue;
}
// Not completed yet, should wait it
else {
var self = this;
var queue = _queues[url.queueId];
if (queue) {
this.totalCount++;
LoadingItems.registerDep(owner || this._id, url.id);
// console.log('+++++ Waited ' + url.id);
queue.addListener(url.id, function (item) {
// console.log('----- Completed by waiting ' + item.id + ', rest: ' + (self.totalCount - self.completedCount-1));
self.itemComplete(item.id);
});
}
continue;
}
}
// Queue new items
if (isIdValid(url)) {
item = createItem(url, this._id);
var key = item.id;
// No duplicated url
if (!this.map[key]) {
this.map[key] = item;
this.totalCount++;
LoadingItems.registerDep(owner || this._id, key);
accepted.push(item);
// console.log('+++++ Appended ' + item.id);
LoadingItems.registerDep(owner || this._id, url.id);
// console.log('+++++ Waited ' + url.id);
queue.addListener(url.id, function (item) {
// console.log('----- Completed by waiting ' + item.id + ', rest: ' + (self.totalCount - self.completedCount-1));
self.itemComplete(item.id);
});
}
continue;
}
}
this._appending = false;
// Manually complete
if (this.completedCount === this.totalCount) {
// console.log('===== All Completed ');
this.allComplete();
}
else {
this._pipeline.flowIn(accepted);
}
return accepted;
},
_childOnProgress: function (item) {
if (this.onProgress) {
var dep = _queueDeps[this._id];
this.onProgress(dep ? dep.completed.length : this.completedCount, dep ? dep.deps.length : this.totalCount, item);
}
},
/**
* !#en Complete a LoadingItems queue, please do not call this method unless you know what's happening.
* !#zh 完成一个 LoadingItems 队列,请不要调用这个函数,除非你知道自己在做什么。
* @method allComplete
*/
allComplete: function () {
var errors = this._errorUrls.length === 0 ? null : this._errorUrls;
if (this.onComplete) {
this.onComplete(errors, this);
}
},
/**
* !#en Check whether all items are completed.
* !#zh 检查是否所有加载项都已经完成。
* @method isCompleted
* @return {Boolean}
*/
isCompleted: function () {
return this.completedCount >= this.totalCount;
},
/**
* !#en Check whether an item is completed.
* !#zh 通过 id 检查指定加载项是否已经加载完成。
* @method isItemCompleted
* @param {String} id The item's id.
* @return {Boolean}
*/
isItemCompleted: function (id) {
return !!this.completed[id];
},
/**
* !#en Check whether an item exists.
* !#zh 通过 id 检查加载项是否存在。
* @method exists
* @param {String} id The item's id.
* @return {Boolean}
*/
exists: function (id) {
return !!this.map[id];
},
/**
* !#en Returns the content of an internal item.
* !#zh 通过 id 获取指定对象的内容。
* @method getContent
* @param {String} id The item's id.
* @return {Object}
*/
getContent: function (id) {
var item = this.map[id];
var ret = null;
if (item) {
if (item.content) {
ret = item.content;
// Queue new items
if (isIdValid(url)) {
item = createItem(url, this._id);
var key = item.id;
// No duplicated url
if (!this.map[key]) {
this.map[key] = item;
this.totalCount++;
LoadingItems.registerDep(owner || this._id, key);
accepted.push(item);
// console.log('+++++ Appended ' + item.id);
}
else if (item.alias) {
ret = this.getContent(item.alias);
}
}
return ret;
},
/**
* !#en Returns the error of an internal item.
* !#zh 通过 id 获取指定对象的错误信息。
* @method getError
* @param {String} id The item's id.
* @return {Object}
*/
getError: function (id) {
var item = this.map[id];
var ret = null;
if (item) {
if (item.error) {
ret = item.error;
} else if (item.alias) {
ret = this.getError(item.alias);
}
}
return ret;
},
/**
* !#en Add a listener for an item, the callback will be invoked when the item is completed.
* !#zh 监听加载项(通过 key 指定)的完成事件。
* @method addListener
* @param {String} key
* @param {Function} callback - can be null
* @param {Object} target - can be null
* @return {Boolean} whether the key is new
*/
addListener: CallbacksInvoker.prototype.add,
/**
* !#en
* Check if the specified key has any registered callback. </br>
* If a callback is also specified, it will only return true if the callback is registered.
* !#zh
* 检查指定的加载项是否有完成事件监听器。</br>
* 如果同时还指定了一个回调方法,并且回调有注册,它只会返回 true。
* @method hasListener
* @param {String} key
* @param {Function} [callback]
* @param {Object} [target]
* @return {Boolean}
*/
hasListener: CallbacksInvoker.prototype.has,
/**
* !#en
* Removes a listener. </br>
* It will only remove when key, callback, target all match correctly.
* !#zh
* 移除指定加载项已经注册的完成事件监听器。</br>
* 只会删除 key, callback, target 均匹配的监听器。
* @method remove
* @param {String} key
* @param {Function} callback
* @param {Object} target
* @return {Boolean} removed
*/
removeListener: CallbacksInvoker.prototype.remove,
/**
* !#en
* Removes all callbacks registered in a certain event
* type or all callbacks registered with a certain target.
* !#zh 删除指定目标的所有完成事件监听器。
* @method removeAllListeners
* @param {String|Object} key - The event key to be removed or the target to be removed
*/
removeAllListeners: CallbacksInvoker.prototype.removeAll,
/**
* !#en Remove an item, can only remove completed item, ongoing item can not be removed.
* !#zh 移除加载项,这里只会移除已经完成的加载项,正在进行的加载项将不能被删除。
* @param {String} url
*/
removeItem: function (url) {
var item = this.map[url];
if (!item) return;
if (!this.completed[item.alias || url]) return;
delete this.completed[url];
delete this.map[url];
if (item.alias) {
delete this.completed[item.alias];
delete this.map[item.alias];
}
this.completedCount--;
this.totalCount--;
},
/**
* !#en Complete an item in the LoadingItems queue, please do not call this method unless you know what's happening.
* !#zh 通知 LoadingItems 队列一个 item 对象已完成,请不要调用这个函数,除非你知道自己在做什么。
* @method itemComplete
* @param {String} id The item url
*/
itemComplete: function (id) {
var item = this.map[id];
if (!item) {
return;
}
// Register or unregister errors
var errorListId = this._errorUrls.indexOf(id);
if (item.error && errorListId === -1) {
this._errorUrls.push(id);
}
else if (!item.error && errorListId !== -1) {
this._errorUrls.splice(errorListId, 1);
}
this.completed[id] = item;
this.completedCount++;
LoadingItems.finishDep(item.id);
if (this.onProgress) {
var dep = _queueDeps[this._id];
this.onProgress(dep ? dep.completed.length : this.completedCount, dep ? dep.deps.length : this.totalCount, item);
}
this.invokeAndRemove(id, item);
// All completed
if (!this._appending && this.completedCount >= this.totalCount) {
// console.log('===== All Completed ');
this.allComplete();
}
},
/**
* !#en Destroy the LoadingItems queue, the queue object won't be garbage collected, it will be recycled, so every after destroy is not reliable.
* !#zh 销毁一个 LoadingItems 队列,这个队列对象会被内部缓冲池回收,所以销毁后的所有内部信息都是不可依赖的。
* @method destroy
*/
destroy: function () {
this.active = false;
this._appending = false;
this._pipeline = null;
this._ownerQueue = null;
this._errorUrls.length = 0;
this.onProgress = null;
this.onComplete = null;
this.map = {};
this.completed = {};
this.totalCount = 0;
this.completedCount = 0;
// Reinitialize CallbacksInvoker, generate three new objects, could be improved
CallbacksInvoker.call(this);
_queues[this._id] = null;
if (_queueDeps[this._id]) {
_queueDeps[this._id].completed.length = 0;
_queueDeps[this._id].deps.length = 0;
}
if (_pool.indexOf(this) === -1 && _pool.length < _POOL_MAX_LENGTH) {
_pool.push(this);
}
}
});
this._appending = false;
// Manually complete
if (this.completedCount === this.totalCount) {
// console.log('===== All Completed ');
this.allComplete();
}
else {
this._pipeline.flowIn(accepted);
}
return accepted;
};
proto._childOnProgress = function (item) {
if (this.onProgress) {
var dep = _queueDeps[this._id];
this.onProgress(dep ? dep.completed.length : this.completedCount, dep ? dep.deps.length : this.totalCount, item);
}
};
/**
* !#en Complete a LoadingItems queue, please do not call this method unless you know what's happening.
* !#zh 完成一个 LoadingItems 队列,请不要调用这个函数,除非你知道自己在做什么。
* @method allComplete
*/
proto.allComplete = function () {
var errors = this._errorUrls.length === 0 ? null : this._errorUrls;
if (this.onComplete) {
this.onComplete(errors, this);
}
};
/**
* !#en Check whether all items are completed.
* !#zh 检查是否所有加载项都已经完成。
* @method isCompleted
* @return {Boolean}
*/
proto.isCompleted = function () {
return this.completedCount >= this.totalCount;
};
/**
* !#en Check whether an item is completed.
* !#zh 通过 id 检查指定加载项是否已经加载完成。
* @method isItemCompleted
* @param {String} id The item's id.
* @return {Boolean}
*/
proto.isItemCompleted = function (id) {
return !!this.completed[id];
};
/**
* !#en Check whether an item exists.
* !#zh 通过 id 检查加载项是否存在。
* @method exists
* @param {String} id The item's id.
* @return {Boolean}
*/
proto.exists = function (id) {
return !!this.map[id];
};
/**
* !#en Returns the content of an internal item.
* !#zh 通过 id 获取指定对象的内容。
* @method getContent
* @param {String} id The item's id.
* @return {Object}
*/
proto.getContent = function (id) {
var item = this.map[id];
var ret = null;
if (item) {
if (item.content) {
ret = item.content;
}
else if (item.alias) {
ret = this.getContent(item.alias);
}
}
return ret;
};
/**
* !#en Returns the error of an internal item.
* !#zh 通过 id 获取指定对象的错误信息。
* @method getError
* @param {String} id The item's id.
* @return {Object}
*/
proto.getError = function (id) {
var item = this.map[id];
var ret = null;
if (item) {
if (item.error) {
ret = item.error;
} else if (item.alias) {
ret = this.getError(item.alias);
}
}
return ret;
};
/**
* !#en Add a listener for an item, the callback will be invoked when the item is completed.
* !#zh 监听加载项(通过 key 指定)的完成事件。
* @method addListener
* @param {String} key
* @param {Function} callback - can be null
* @param {Object} target - can be null
* @return {Boolean} whether the key is new
*/
proto.addListener = CallbacksInvoker.prototype.add;
/**
* !#en
* Check if the specified key has any registered callback. </br>
* If a callback is also specified, it will only return true if the callback is registered.
* !#zh
* 检查指定的加载项是否有完成事件监听器。</br>
* 如果同时还指定了一个回调方法,并且回调有注册,它只会返回 true。
* @method hasListener
* @param {String} key
* @param {Function} [callback]
* @param {Object} [target]
* @return {Boolean}
*/
proto.hasListener = CallbacksInvoker.prototype.has;
/**
* !#en
* Removes a listener. </br>
* It will only remove when key, callback, target all match correctly.
* !#zh
* 移除指定加载项已经注册的完成事件监听器。</br>
* 只会删除 key, callback, target 均匹配的监听器。
* @method remove
* @param {String} key
* @param {Function} callback
* @param {Object} target
* @return {Boolean} removed
*/
proto.removeListener = CallbacksInvoker.prototype.remove;
/**
* !#en
* Removes all callbacks registered in a certain event
* type or all callbacks registered with a certain target.
* !#zh 删除指定目标的所有完成事件监听器。
* @method removeAllListeners
* @param {String|Object} key - The event key to be removed or the target to be removed
*/
proto.removeAllListeners = CallbacksInvoker.prototype.removeAll;
/**
* !#en Remove an item, can only remove completed item, ongoing item can not be removed.
* !#zh 移除加载项,这里只会移除已经完成的加载项,正在进行的加载项将不能被删除。
* @param {String} url
*/
proto.removeItem = function (url) {
var item = this.map[url];
if (!item) return;
if (!this.completed[item.alias || url]) return;
delete this.completed[url];
delete this.map[url];
if (item.alias) {
delete this.completed[item.alias];
delete this.map[item.alias];
}
this.completedCount--;
this.totalCount--;
};
/**
* !#en Complete an item in the LoadingItems queue, please do not call this method unless you know what's happening.
* !#zh 通知 LoadingItems 队列一个 item 对象已完成,请不要调用这个函数,除非你知道自己在做什么。
* @method itemComplete
* @param {String} id The item url
*/
proto.itemComplete = function (id) {
var item = this.map[id];
if (!item) {
return;
}
// Register or unregister errors
var errorListId = this._errorUrls.indexOf(id);
if (item.error && errorListId === -1) {
this._errorUrls.push(id);
}
else if (!item.error && errorListId !== -1) {
this._errorUrls.splice(errorListId, 1);
}
this.completed[id] = item;
this.completedCount++;
LoadingItems.finishDep(item.id);
if (this.onProgress) {
var dep = _queueDeps[this._id];
this.onProgress(dep ? dep.completed.length : this.completedCount, dep ? dep.deps.length : this.totalCount, item);
}
this.invokeAndRemove(id, item);
// All completed
if (!this._appending && this.completedCount >= this.totalCount) {
// console.log('===== All Completed ');
this.allComplete();
}
};
/**
* !#en Destroy the LoadingItems queue, the queue object won't be garbage collected, it will be recycled, so every after destroy is not reliable.
* !#zh 销毁一个 LoadingItems 队列,这个队列对象会被内部缓冲池回收,所以销毁后的所有内部信息都是不可依赖的。
* @method destroy
*/
proto.destroy = function () {
this.active = false;
this._appending = false;
this._pipeline = null;
this._ownerQueue = null;
this._errorUrls.length = 0;
this.onProgress = null;
this.onComplete = null;
this.map = {};
this.completed = {};
this.totalCount = 0;
this.completedCount = 0;
// Reinitialize CallbacksInvoker, generate three new objects, could be improved
CallbacksInvoker.call(this);
_queues[this._id] = null;
if (_queueDeps[this._id]) {
_queueDeps[this._id].completed.length = 0;
_queueDeps[this._id].deps.length = 0;
}
if (_pool.indexOf(this) === -1 && _pool.length < _POOL_MAX_LENGTH) {
_pool.push(this);
}
};
cc.LoadingItems = module.exports = LoadingItems;
+230 -230
View File
@@ -167,245 +167,245 @@ var Pipeline = function (pipes) {
Pipeline.ItemState = ItemState;
JS.mixin(Pipeline.prototype, {
/**
* !#en
* Insert a new pipe at the given index of the pipeline. </br>
* A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline.
* !#zh
* 在给定的索引位置插入一个新的 pipe。</br>
* 一个 pipe 必须包含一个字符串类型的 ‘id’ 和 ‘handle’ 函数,该 id 在 pipeline 必须是唯一标识。
* @method insertPipe
* @param {Object} pipe The pipe to be inserted
* @param {Number} index The index to insert
*/
insertPipe: function (pipe, index) {
// Must have handle and id, handle for flow, id for state flag
if (!pipe.handle || !pipe.id) {
return;
}
var proto = Pipeline.prototype;
pipe.pipeline = this;
pipe.flowIn = pipe.async ? asyncFlow : syncFlow;
if (index < this._pipes.length) {
pipe.next = this._pipes[index];
this._pipes.splice(index, 0, pipe);
}
else {
pipe.next = null;
this._pipes.push(pipe);
}
},
/**
* !#en
* Insert a new pipe at the given index of the pipeline. </br>
* A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline.
* !#zh
* 在给定的索引位置插入一个新的 pipe。</br>
* 一个 pipe 必须包含一个字符串类型的 ‘id’ 和 ‘handle’ 函数,该 id 在 pipeline 必须是唯一标识。
* @method insertPipe
* @param {Object} pipe The pipe to be inserted
* @param {Number} index The index to insert
*/
proto.insertPipe = function (pipe, index) {
// Must have handle and id, handle for flow, id for state flag
if (!pipe.handle || !pipe.id) {
return;
}
/**
* !#en
* Add a new pipe at the end of the pipeline. </br>
* A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline.
* !#zh
* 添加一个新的 pipe 到 pipeline 尾部。 </br>
* 该 pipe 必须包含一个字符串类型 ‘id’ 和 ‘handle’ 函数,该 id 在 pipeline 必须是唯一标识。
* @method appendPipe
* @param {Object} pipe The pipe to be appended
*/
appendPipe: function (pipe) {
// Must have handle and id, handle for flow, id for state flag
if (!pipe.handle || !pipe.id) {
return;
}
pipe.pipeline = this;
pipe.pipeline = this;
pipe.flowIn = pipe.async ? asyncFlow : syncFlow;
if (index < this._pipes.length) {
pipe.next = this._pipes[index];
this._pipes.splice(index, 0, pipe);
}
else {
pipe.next = null;
pipe.flowIn = pipe.async ? asyncFlow : syncFlow;
this._pipes.push(pipe);
},
}
};
/**
* !#en
* Let new items flow into the pipeline. </br>
* Each item can be a simple url string or an object,
* if it's an object, it must contain `id` property. </br>
* You can specify its type by `type` property, by default, the type is the extension name in url. </br>
* By adding a `skips` property including pipe ids, you can skip these pipe. </br>
* The object can contain any supplementary property as you want. </br>
* !#zh
* 让新的 item 流入 pipeline 中。</br>
* 这里的每个 item 可以是一个简单字符串类型的 url 或者是一个对象,
* 如果它是一个对象的话,他必须要包含 ‘id’ 属性。</br>
* 你也可以指定它的 ‘type’ 属性类型,默认情况下,该类型是 ‘url’ 的后缀名。</br>
* 也通过添加一个 包含 ‘skips’ 属性的 item 对象,你就可以跳过 skips 中包含的 pipe。</br>
* 该对象可以包含任何附加属性。
* @method flowIn
* @param {Array} items
* @example
* pipeline.flowIn([
* 'res/Background.png',
* {
* id: 'res/scene.json',
* type: 'scene',
* name: 'scene',
* skips: ['Downloader']
* }
* ]);
*/
flowIn: function (items) {
var i, pipe = this._pipes[0], item;
if (pipe) {
for (i = 0; i < items.length; i++) {
item = items[i];
this._cache[item.id] = item;
pipe.flowIn(item);
}
}
else {
for (i = 0; i < items.length; i++) {
this.flowOut(items[i]);
}
}
},
/**
* !#en
* Add a new pipe at the end of the pipeline. </br>
* A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline.
* !#zh
* 添加一个新的 pipe 到 pipeline 尾部。 </br>
* 该 pipe 必须包含一个字符串类型 ‘id’ 和 ‘handle’ 函数,该 id 在 pipeline 必须是唯一标识。
* @method appendPipe
* @param {Object} pipe The pipe to be appended
*/
proto.appendPipe = function (pipe) {
// Must have handle and id, handle for flow, id for state flag
if (!pipe.handle || !pipe.id) {
return;
}
/**
* !#en
* Let new items flow into the pipeline and give a callback when the list of items are all completed. </br>
* This is for loading dependencies for an existing item in flow, usually used in a pipe logic. </br>
* For example, we have a loader for scene configuration file in JSON, the scene will only be fully loaded </br>
* after all its dependencies are loaded, then you will need to use function to flow in all dependencies </br>
* found in the configuration file, and finish the loader pipe only after all dependencies are loaded (in the callback).
* !#zh
* 让新 items 流入 pipeline 并且当 item 列表完成时进行回调函数。</br>
* 这个 API 的使用通常是为了加载依赖项。</br>
* 例如:</br>
* 我们需要加载一个场景配置的 JSON 文件,该场景会将所有的依赖项全部都加载完毕以后,进行回调表示加载完毕。
* @method flowInDeps
* @deprecated since v1.3
* @param {Array} urlList
* @param {Function} callback
* @return {Array} Items accepted by the pipeline
*/
flowInDeps: function (owner, urlList, callback) {
var deps = LoadingItems.create(this, function (errors, items) {
callback(errors, items);
items.destroy();
});
return deps.append(urlList, owner);
},
pipe.pipeline = this;
pipe.next = null;
pipe.flowIn = pipe.async ? asyncFlow : syncFlow;
this._pipes.push(pipe);
};
flowOut: function (item) {
if (item.error) {
delete this._cache[item.id];
}
else if (!this._cache[item.id]) {
/**
* !#en
* Let new items flow into the pipeline. </br>
* Each item can be a simple url string or an object,
* if it's an object, it must contain `id` property. </br>
* You can specify its type by `type` property, by default, the type is the extension name in url. </br>
* By adding a `skips` property including pipe ids, you can skip these pipe. </br>
* The object can contain any supplementary property as you want. </br>
* !#zh
* 让新的 item 流入 pipeline 中。</br>
* 这里的每个 item 可以是一个简单字符串类型的 url 或者是一个对象,
* 如果它是一个对象的话,他必须要包含 ‘id’ 属性。</br>
* 你也可以指定它的 ‘type’ 属性类型,默认情况下,该类型是 ‘url’ 的后缀名。</br>
* 也通过添加一个 包含 ‘skips’ 属性的 item 对象,你就可以跳过 skips 中包含的 pipe。</br>
* 该对象可以包含任何附加属性。
* @method flowIn
* @param {Array} items
* @example
* pipeline.flowIn([
* 'res/Background.png',
* {
* id: 'res/scene.json',
* type: 'scene',
* name: 'scene',
* skips: ['Downloader']
* }
* ]);
*/
proto.flowIn = function (items) {
var i, pipe = this._pipes[0], item;
if (pipe) {
for (i = 0; i < items.length; i++) {
item = items[i];
this._cache[item.id] = item;
}
item.complete = true;
LoadingItems.itemComplete(item);
},
/**
* !#en
* Copy the item states from one source item to all destination items. </br>
* It's quite useful when a pipe generate new items from one source item,</br>
* then you should flowIn these generated items into pipeline, </br>
* but you probably want them to skip all pipes the source item already go through,</br>
* you can achieve it with this API. </br>
* </br>
* For example, an unzip pipe will generate more items, but you won't want them to pass unzip or download pipe again.
* !#zh
* 从一个源 item 向所有目标 item 复制它的 pipe 状态,用于避免重复通过部分 pipe。</br>
* 当一个源 item 生成了一系列新的 items 时很有用,</br>
* 你希望让这些新的依赖项进入 pipeline,但是又不希望它们通过源 item 已经经过的 pipe,</br>
* 但是你可能希望他们源 item 已经通过并跳过所有 pipes,</br>
* 这个时候就可以使用这个 API。
* @method copyItemStates
* @param {Object} srcItem The source item
* @param {Array|Object} dstItems A single destination item or an array of destination items
*/
copyItemStates: function (srcItem, dstItems) {
if (!(dstItems instanceof Array)) {
dstItems.states = srcItem.states;
return;
}
for (var i = 0; i < dstItems.length; ++i) {
dstItems[i].states = srcItem.states;
}
},
/**
* !#en Returns whether the pipeline is flowing (contains item) currently.
* !#zh 获取 pipeline 当前是否正在处理中。
* @method isFlowing
* @return {Boolean}
* @deprecated since v1.3
*/
isFlowing: function () {
return true;
},
/**
* !#en Returns all items in pipeline.
* !#zh 获取 pipeline 中的所有 items。
* @method getItems
* @return {LoadingItems}
* @deprecated since v1.3
*/
getItems: function () {
return null;
},
/**
* !#en Returns an item in pipeline.
* !#zh 根据 id 获取一个 item
* @method getItem
* @param {Object} id The id of the item
* @return {Object}
*/
getItem: function (id) {
var item = this._cache[id];
if (!item)
return item;
// downloader.js downloadUuid
if (item.alias)
item = this._cache[item.alias];
return item;
},
/**
* !#en Removes an completed item in pipeline.
* It will only remove the cache in the pipeline or loader, its dependencies won't be released.
* cc.loader provided another method to completely cleanup the resource and its dependencies,
* please refer to {{#crossLink "loader/release:method"}}cc.loader.release{{/crossLink}}
* !#zh 移除指定的已完成 item。
* 这将仅仅从 pipeline 或者 loader 中删除其缓存,并不会释放它所依赖的资源。
* cc.loader 中提供了另一种删除资源及其依赖的清理方法,请参考 {{#crossLink "loader/release:method"}}cc.loader.release{{/crossLink}}
* @method removeItem
* @param {Object} id The id of the item
* @return {Boolean} succeed or not
*/
removeItem: function (id) {
var removed = this._cache[id];
if (removed && removed.complete) {
delete this._cache[id];
}
return removed;
},
/**
* !#en Clear the current pipeline, this function will clean up the items.
* !#zh 清空当前 pipeline,该函数将清理 items。
* @method clear
*/
clear: function () {
for (var id in this._cache) {
var item = this._cache[id];
delete this._cache[id];
if (!item.complete) {
item.error = new Error('Canceled manually');
this.flowOut(item);
}
pipe.flowIn(item);
}
}
});
else {
for (i = 0; i < items.length; i++) {
this.flowOut(items[i]);
}
}
};
/**
* !#en
* Let new items flow into the pipeline and give a callback when the list of items are all completed. </br>
* This is for loading dependencies for an existing item in flow, usually used in a pipe logic. </br>
* For example, we have a loader for scene configuration file in JSON, the scene will only be fully loaded </br>
* after all its dependencies are loaded, then you will need to use function to flow in all dependencies </br>
* found in the configuration file, and finish the loader pipe only after all dependencies are loaded (in the callback).
* !#zh
* 让新 items 流入 pipeline 并且当 item 列表完成时进行回调函数。</br>
* 这个 API 的使用通常是为了加载依赖项。</br>
* 例如:</br>
* 我们需要加载一个场景配置的 JSON 文件,该场景会将所有的依赖项全部都加载完毕以后,进行回调表示加载完毕。
* @method flowInDeps
* @deprecated since v1.3
* @param {Array} urlList
* @param {Function} callback
* @return {Array} Items accepted by the pipeline
*/
proto.flowInDeps = function (owner, urlList, callback) {
var deps = LoadingItems.create(this, function (errors, items) {
callback(errors, items);
items.destroy();
});
return deps.append(urlList, owner);
};
proto.flowOut = function (item) {
if (item.error) {
delete this._cache[item.id];
}
else if (!this._cache[item.id]) {
this._cache[item.id] = item;
}
item.complete = true;
LoadingItems.itemComplete(item);
};
/**
* !#en
* Copy the item states from one source item to all destination items. </br>
* It's quite useful when a pipe generate new items from one source item,</br>
* then you should flowIn these generated items into pipeline, </br>
* but you probably want them to skip all pipes the source item already go through,</br>
* you can achieve it with this API. </br>
* </br>
* For example, an unzip pipe will generate more items, but you won't want them to pass unzip or download pipe again.
* !#zh
* 从一个源 item 向所有目标 item 复制它的 pipe 状态,用于避免重复通过部分 pipe。</br>
* 当一个源 item 生成了一系列新的 items 时很有用,</br>
* 你希望让这些新的依赖项进入 pipeline,但是又不希望它们通过源 item 已经经过的 pipe,</br>
* 但是你可能希望他们源 item 已经通过并跳过所有 pipes,</br>
* 这个时候就可以使用这个 API。
* @method copyItemStates
* @param {Object} srcItem The source item
* @param {Array|Object} dstItems A single destination item or an array of destination items
*/
proto.copyItemStates = function (srcItem, dstItems) {
if (!(dstItems instanceof Array)) {
dstItems.states = srcItem.states;
return;
}
for (var i = 0; i < dstItems.length; ++i) {
dstItems[i].states = srcItem.states;
}
};
/**
* !#en Returns whether the pipeline is flowing (contains item) currently.
* !#zh 获取 pipeline 当前是否正在处理中。
* @method isFlowing
* @return {Boolean}
* @deprecated since v1.3
*/
proto.isFlowing = function () {
return true;
};
/**
* !#en Returns all items in pipeline.
* !#zh 获取 pipeline 中的所有 items。
* @method getItems
* @return {LoadingItems}
* @deprecated since v1.3
*/
proto.getItems = function () {
return null;
};
/**
* !#en Returns an item in pipeline.
* !#zh 根据 id 获取一个 item
* @method getItem
* @param {Object} id The id of the item
* @return {Object}
*/
proto.getItem = function (id) {
var item = this._cache[id];
if (!item)
return item;
// downloader.js downloadUuid
if (item.alias)
item = this._cache[item.alias];
return item;
};
/**
* !#en Removes an completed item in pipeline.
* It will only remove the cache in the pipeline or loader, its dependencies won't be released.
* cc.loader provided another method to completely cleanup the resource and its dependencies,
* please refer to {{#crossLink "loader/release:method"}}cc.loader.release{{/crossLink}}
* !#zh 移除指定的已完成 item。
* 这将仅仅从 pipeline 或者 loader 中删除其缓存,并不会释放它所依赖的资源。
* cc.loader 中提供了另一种删除资源及其依赖的清理方法,请参考 {{#crossLink "loader/release:method"}}cc.loader.release{{/crossLink}}
* @method removeItem
* @param {Object} id The id of the item
* @return {Boolean} succeed or not
*/
proto.removeItem = function (id) {
var removed = this._cache[id];
if (removed && removed.complete) {
delete this._cache[id];
}
return removed;
};
/**
* !#en Clear the current pipeline, this function will clean up the items.
* !#zh 清空当前 pipeline,该函数将清理 items。
* @method clear
*/
proto.clear = function () {
for (var id in this._cache) {
var item = this._cache[id];
delete this._cache[id];
if (!item.complete) {
item.error = new Error('Canceled manually');
this.flowOut(item);
}
}
};
cc.Pipeline = module.exports = Pipeline;
+85 -104
View File
@@ -29,6 +29,7 @@ var Utils = require('./utils');
var _isPlainEmptyObj_DEV = Utils.isPlainEmptyObj_DEV;
var _cloneable_DEV = Utils.cloneable_DEV;
var Attr = require('./attribute');
var DELIMETER = Attr.DELIMETER;
var getTypeChecker = Attr.getTypeChecker;
var preprocess = require('./preprocess-class');
var Misc = require('../utils/misc');
@@ -104,7 +105,10 @@ function appendProp (cls, name) {
pushUnique(cls.__props__, name);
}
function defineProp (cls, className, propName, defaultValue, attrs, es6) {
var tmpArray = [];
function defineProp (cls, className, propName, val, es6) {
var defaultValue = val.default;
if (CC_DEV) {
if (!es6) {
// check default object value
@@ -141,27 +145,27 @@ function defineProp (cls, className, propName, defaultValue, attrs, es6) {
appendProp(cls, propName);
// apply attributes
var attrs = parseAttributes(cls, val, className, propName, false);
if (attrs) {
var onAfterProp = null;
var onAfterProp = tmpArray;
for (var i = 0; i < attrs.length; i++) {
var attr = attrs[i];
Attr.attr(cls, propName, attr);
// register callback
if (attr._onAfterProp) {
onAfterProp = onAfterProp || [];
onAfterProp.push(attr._onAfterProp);
}
}
// call callback
if (onAfterProp) {
for (var c = 0; c < onAfterProp.length; c++) {
onAfterProp[c](cls, propName);
}
for (var c = 0; c < onAfterProp.length; c++) {
onAfterProp[c](cls, propName);
}
tmpArray.length = 0;
attrs.length = 0;
}
}
function defineGetSet (cls, name, propName, val, attrs, es6) {
function defineGetSet (cls, name, propName, val, es6) {
var getter = val.get;
var setter = val.set;
var proto = cls.prototype;
@@ -173,26 +177,12 @@ function defineGetSet (cls, name, propName, val, attrs, es6) {
return;
}
if (attrs) {
for (var i = 0; i < attrs.length; ++i) {
var attr = attrs[i];
if (CC_DEV && attr._canUsedInGetter === false) {
cc.errorID(3639, name, propName, i);
continue;
}
var attrs = parseAttributes(cls, val, name, propName, true);
attrs.length = 0;
Attr.attr(cls, propName, attr);
// check attributes
if (CC_DEV && (attr.serializable === false || attr.editorOnly === true)) {
cc.warnID(3613, name, propName);
}
}
}
var ForceSerializable = false;
const ForceSerializable = false;
if (!ForceSerializable) {
Attr.attr(cls, propName, Attr.NonSerialized);
Attr.setClassAttr(cls, propName, 'serializable', false);
}
if (ForceSerializable || CC_DEV) {
// 不论是否 visible 都要添加到 props,否则 asset watcher 不能正常工作
@@ -200,18 +190,8 @@ function defineGetSet (cls, name, propName, val, attrs, es6) {
}
if (!es6) {
if (d) {
Object.defineProperty(proto, propName, {
get: getter
});
}
else {
Object.defineProperty(proto, propName, {
get: getter,
configurable: true,
enumerable: true
});
}
var setterUndefined = !d;
JS.get(proto, propName, getter, setterUndefined, setterUndefined);
}
if (CC_DEV) {
@@ -225,26 +205,16 @@ function defineGetSet (cls, name, propName, val, attrs, es6) {
if (d && d.set) {
return cc.errorID(3640, name, propName);
}
Object.defineProperty(proto, propName, {
set: setter,
configurable: true,
enumerable: true
});
JS.set(proto, propName, setter, true, true);
}
Attr.setClassAttr(cls, propName, 'hasSetter', true); // 方便 editor 做判断
}
else if (!es6) {
if (d) {
Object.defineProperty(proto, propName, {
set: setter
});
JS.set(proto, propName, setter);
}
else {
Object.defineProperty(proto, propName, {
set: setter,
configurable: true,
enumerable: true
});
JS.set(proto, propName, setter, true, true);
}
}
}
@@ -325,22 +295,13 @@ function doDefine (className, baseClass, mixins, options) {
fireClass = _createCtor(ctors, baseClass, className, options);
// extend - Create a new Class that inherits from this Class
Object.defineProperty(fireClass, 'extend', {
value: function (options) {
options.extends = this;
return CCClass(options);
},
writable: true,
configurable: true
// enumerable should be false
});
JS.value(fireClass, 'extend', function (options) {
options.extends = this;
return CCClass(options);
}, true);
}
Object.defineProperty(fireClass, '__ctors__', {
value: ctors.length > 0 ? ctors : null,
writable: true,
// enumerable should be false
});
JS.value(fireClass, '__ctors__', ctors.length > 0 ? ctors : null, true);
var prototype = fireClass.prototype;
@@ -505,7 +466,7 @@ function compileProps (actualClass) {
for (var i = 0; i < propList.length; i++) {
var prop = propList[i];
var attrKey = prop + Attr.DELIMETER + 'default';
var attrKey = prop + DELIMETER + 'default';
if (attrKey in attrs) { // getter does not have default
var statement;
if (IDENTIFIER_RE.test(prop)) {
@@ -774,12 +735,11 @@ function declareProperties (cls, className, properties, baseClass, mixins, es6)
for (var propName in properties) {
var val = properties[propName];
var attrs = parseAttributes(val, className, propName);
if ('default' in val) {
defineProp(cls, className, propName, val.default, attrs, es6);
defineProp(cls, className, propName, val, es6);
}
else {
defineGetSet(cls, className, propName, val, attrs, es6);
defineGetSet(cls, className, propName, val, es6);
}
}
}
@@ -936,13 +896,8 @@ function CCClass (options) {
if (!preprocess.validateMethod(func, funcName, name, cls, base)) {
continue;
}
// use defineProperty to redefine some super method defined as getter
Object.defineProperty(cls.prototype, funcName, {
value: func,
enumerable: true,
configurable: true,
writable: true,
});
// use value to redefine some super method defined as getter
JS.value(cls.prototype, funcName, func, true, true);
}
@@ -985,11 +940,11 @@ CCClass._fastDefine = function (className, constructor, serializableFields) {
JS.setClassName(className, constructor);
//constructor.__ctors__ = constructor.__ctors__ || null;
var props = constructor.__props__ = Object.keys(serializableFields);
var attrProtos = Attr.getClassAttrsProto(constructor);
for (var i = 0; i < props.length; i++) {
var key = props[i];
var val = serializableFields[key];
Attr.setClassAttr(constructor, key, 'visible', false);
Attr.setClassAttr(constructor, key, 'default', val);
attrProtos[key + DELIMETER + 'visible'] = false;
attrProtos[key + DELIMETER + 'default'] = serializableFields[key];
}
};
@@ -1061,9 +1016,16 @@ var PrimitiveTypes = {
String: 'String',
};
var tmpAttrs = [];
function parseAttributes (attrs, className, propName) {
function parseAttributes (cls, attrs, className, propName, usedInGetter) {
var ERR_Type = CC_DEV ? 'The %s of %s must be type %s' : '';
var attrsProto = null;
var attrsProtoKey = '';
function getAttrsProto () {
attrsProtoKey = propName + DELIMETER;
return attrsProto = Attr.getClassAttrsProto(cls);
}
tmpAttrs.length = 0;
var result = tmpAttrs;
@@ -1121,18 +1083,11 @@ function parseAttributes (attrs, className, propName) {
}
}
function parseSimpleAttr (attrName, expectType, attrCreater) {
function parseSimpleAttr (attrName, expectType) {
if (attrName in attrs) {
var val = attrs[attrName];
if (typeof val === expectType) {
if ( !attrCreater ) {
var attr = {};
attr[attrName] = val;
result.push(attr);
}
else {
result.push(typeof attrCreater === 'function' ? attrCreater(val) : attrCreater);
}
(attrsProto || getAttrsProto())[attrsProtoKey + attrName] = val;
}
else if (CC_DEV) {
cc.error(ERR_Type, attrName, className, propName, expectType);
@@ -1140,26 +1095,54 @@ function parseAttributes (attrs, className, propName) {
}
}
parseSimpleAttr('rawType', 'string', Attr.RawType);
parseSimpleAttr('editorOnly', 'boolean', Attr.EditorOnly);
// if (attrs.rawType) {
// if (CC_DEV && usedInGetter) {
// cc.errorID(3613, "rawType", name, propName);
// }
// else {
// var val = attrs.rawType;
// if (typeof val === 'string') {
// result.push(Attr.RawType(val));
// }
// else if (CC_DEV) {
// cc.error(ERR_Type, "rawType", className, propName, 'string');
// }
// }
// }
if (attrs.editorOnly) {
if (CC_DEV && usedInGetter) {
cc.errorID(3613, "editorOnly", name, propName);
}
else {
(attrsProto || getAttrsProto())[attrsProtoKey + 'editorOnly'] = true;
}
}
//parseSimpleAttr('preventDeferredLoad', 'boolean');
if (CC_DEV) {
parseSimpleAttr('displayName', 'string');
parseSimpleAttr('multiline', 'boolean', {multiline: true});
parseSimpleAttr('readonly', 'boolean', {readonly: true});
parseSimpleAttr('multiline', 'boolean');
if (attrs.readonly) {
(attrsProto || getAttrsProto())[attrsProtoKey + 'readonly'] = true;
}
parseSimpleAttr('tooltip', 'string');
parseSimpleAttr('slide', 'boolean');
}
if (attrs.url) {
result.push({ saveUrlAsAsset: true });
(attrsProto || getAttrsProto())[attrsProtoKey + 'saveUrlAsAsset'] = true;
}
if (attrs.serializable === false) {
result.push(Attr.NonSerialized);
if (CC_DEV && usedInGetter) {
cc.errorID(3613, "serializable", name, propName);
}
else {
(attrsProto || getAttrsProto())[attrsProtoKey + 'serializable'] = false;
}
}
if (CC_EDITOR) {
if ('animatable' in attrs && !attrs.animatable) {
result.push({ animatable: false });
(attrsProto || getAttrsProto())[attrsProtoKey + 'animatable'] = false;
}
}
@@ -1167,29 +1150,27 @@ function parseAttributes (attrs, className, propName) {
var visible = attrs.visible;
if (typeof visible !== 'undefined') {
if (!visible) {
result.push({visible: false});
(attrsProto || getAttrsProto())[attrsProtoKey + 'visible'] = false;
}
else if (typeof visible === 'function') {
result.push({visible: visible});
(attrsProto || getAttrsProto())[attrsProtoKey + 'visible'] = visible;
}
}
else {
var startsWithUS = (propName.charCodeAt(0) === 95);
if (startsWithUS) {
result.push({visible: false});
(attrsProto || getAttrsProto())[attrsProtoKey + 'visible'] = false;
}
}
}
//if (attrs.custom) {
// result.push( { custom: attrs.custom });
//}
var range = attrs.range;
if (range) {
if (Array.isArray(range)) {
if (range.length >= 2) {
result.push({ min: range[0], max: range[1], step: range[2] });
(attrsProto || getAttrsProto())[attrsProtoKey + 'min'] = range[0];
attrsProto[attrsProtoKey + 'max'] = range[1];
attrsProto[attrsProtoKey + 'step'] = range[2];
}
else if (CC_DEV) {
cc.errorID(3647);
+6 -14
View File
@@ -59,21 +59,13 @@ function CCObject () {
}
CCClass.fastDefine('cc.Object', CCObject, { _name: '', _objFlags: 0 });
function defineNotInheritable (obj, prop, value, writable) {
Object.defineProperty(obj, prop, {
value: value,
writable: !!writable
// enumerable is false by default
});
}
/**
* Bit mask that controls object states.
* @enum Flags
* @static
* @private
*/
defineNotInheritable(CCObject, 'Flags', {
JS.value(CCObject, 'Flags', {
Destroyed: Destroyed,
//ToDestroy: ToDestroy,
@@ -189,10 +181,10 @@ function deferredDestroy () {
}
}
defineNotInheritable(CCObject, '_deferredDestroy', deferredDestroy);
JS.value(CCObject, '_deferredDestroy', deferredDestroy);
if (CC_EDITOR) {
defineNotInheritable(CCObject, '_clearDeferredDestroyTimer', function () {
JS.value(CCObject, '_clearDeferredDestroyTimer', function () {
if (deferredDestroyTimer !== null) {
clearImmediate(deferredDestroyTimer);
deferredDestroyTimer = null;
@@ -394,7 +386,7 @@ prototype._destruct = function () {
var destruct = ctor.__destruct__;
if (!destruct) {
destruct = compileDestruct(this, ctor);
defineNotInheritable(ctor, '__destruct__', destruct, true);
JS.value(ctor, '__destruct__', destruct, true);
}
destruct(this);
};
@@ -466,10 +458,10 @@ cc.isValid = function (value) {
};
if (CC_EDITOR || CC_TEST) {
defineNotInheritable(CCObject, '_willDestroy', function (obj) {
JS.value(CCObject, '_willDestroy', function (obj) {
return !(obj._objFlags & Destroyed) && (obj._objFlags & ToDestroy) > 0;
});
defineNotInheritable(CCObject, '_cancelDestroy', function (obj) {
JS.value(CCObject, '_cancelDestroy', function (obj) {
obj._objFlags &= ~ToDestroy;
JS.array.fastRemove(objectsToDestroy, obj);
});
+51 -57
View File
@@ -646,19 +646,21 @@ else {
var _tmpCanvas1 = document.createElement("canvas"),
_tmpCanvas2 = document.createElement("canvas");
cc.create3DContext = function (canvas, opt_attribs) {
var names = ["webgl", "experimental-webgl", "webkit-3d", "moz-webgl"];
var context = null;
for (var ii = 0; ii < names.length; ++ii) {
cc.create3DContext = function (canvas, opt_attribs, opt_contextType) {
if (opt_contextType) {
try {
context = canvas.getContext(names[ii], opt_attribs);
return canvas.getContext(opt_contextType, opt_attribs);
} catch (e) {
}
if (context) {
break;
return null;
}
}
return context;
else {
return cc.create3DContext(canvas, opt_attribs, "webgl") ||
cc.create3DContext(canvas, opt_attribs, "experimental-webgl") ||
cc.create3DContext(canvas, opt_attribs, "webkit-3d") ||
cc.create3DContext(canvas, opt_attribs, "moz-webgl") ||
null;
}
};
//Whether or not the Canvas BlendModes are supported.
@@ -717,56 +719,48 @@ else {
var _supportCanvas = !!_tmpCanvas1.getContext("2d");
var _supportWebGL = false;
if (win.WebGLRenderingContext) {
var tmpCanvas = document.createElement("CANVAS");
try{
var context = cc.create3DContext(tmpCanvas);
if (context) {
_supportWebGL = true;
}
if (_supportWebGL && sys.os === sys.OS_IOS && sys.osMainVersion === 9) {
// Not activating WebGL in iOS 9 UIWebView because it may crash when entering background
if (!window.indexedDB) {
_supportWebGL = false;
}
}
if (_supportWebGL && sys.os === sys.OS_ANDROID) {
var browserVer = parseFloat(sys.browserVersion);
switch (sys.browserType) {
case sys.BROWSER_TYPE_MOBILE_QQ:
case sys.BROWSER_TYPE_BAIDU:
case sys.BROWSER_TYPE_BAIDU_APP:
// QQ & Baidu Brwoser 6.2+ (using blink kernel)
if (browserVer >= 6.2) {
_supportWebGL = true;
}
else {
_supportWebGL = false;
}
break;
case sys.BROWSER_TYPE_ANDROID:
// Android 5+ default browser
if (sys.osMainVersion && sys.osMainVersion >= 5) {
_supportWebGL = true;
}
break;
case sys.BROWSER_TYPE_CHROME:
// Chrome on android supports WebGL from v. 30
if(browserVer >= 30.0) {
_supportWebGL = true;
} else {
_supportWebGL = false;
}
break;
case sys.BROWSER_TYPE_360:
case sys.BROWSER_TYPE_UC:
_supportWebGL = false;
}
if (cc.create3DContext(document.createElement("CANVAS"))) {
_supportWebGL = true;
}
if (_supportWebGL && sys.os === sys.OS_IOS && sys.osMainVersion === 9) {
// Not activating WebGL in iOS 9 UIWebView because it may crash when entering background
if (!win.indexedDB) {
_supportWebGL = false;
}
}
if (_supportWebGL && sys.os === sys.OS_ANDROID) {
var browserVer = parseFloat(sys.browserVersion);
switch (sys.browserType) {
case sys.BROWSER_TYPE_MOBILE_QQ:
case sys.BROWSER_TYPE_BAIDU:
case sys.BROWSER_TYPE_BAIDU_APP:
// QQ & Baidu Brwoser 6.2+ (using blink kernel)
if (browserVer >= 6.2) {
_supportWebGL = true;
}
else {
_supportWebGL = false;
}
break;
case sys.BROWSER_TYPE_ANDROID:
// Android 5+ default browser
if (sys.osMainVersion && sys.osMainVersion >= 5) {
_supportWebGL = true;
}
break;
case sys.BROWSER_TYPE_CHROME:
// Chrome on android supports WebGL from v. 30
if(browserVer >= 30.0) {
_supportWebGL = true;
} else {
_supportWebGL = false;
}
break;
case sys.BROWSER_TYPE_360:
case sys.BROWSER_TYPE_UC:
_supportWebGL = false;
}
}
catch (e) {}
tmpCanvas = null;
}
/**
+4 -4
View File
@@ -136,10 +136,10 @@ Class.extend = function (props) {
for (var name in props) {
var isFunc = (typeof props[name] === "function");
var override = (typeof _super[name] === "function");
var hasSuperCall = fnTest.test(props[name]);
if (isFunc && override && hasSuperCall) {
var override = isFunc && (typeof _super[name] === "function");
var hasSuperCall = override && fnTest.test(props[name]);
if (hasSuperCall) {
desc.value = (function (name, fn) {
return CC_JSB ? function (...args) {
var tmp = this._super;
+54 -60
View File
@@ -29,9 +29,12 @@ var isPlainEmptyObj = require('./utils').isPlainEmptyObj_DEV;
function createAttrsSingle (owner, ownerCtor, superAttrs) {
var AttrsCtor;
if (CC_DEV) {
var ctorName = ownerCtor.name + '_ATTRS';
if (owner !== ownerCtor) {
ctorName += '_INSTANCE';
var ctorName = ownerCtor.name;
if (owner === ownerCtor) {
ctorName += '_ATTRS';
}
else {
ctorName += '_ATTRS_INSTANCE';
}
AttrsCtor = Function('return (function ' + ctorName + '(){});')();
}
@@ -42,9 +45,7 @@ function createAttrsSingle (owner, ownerCtor, superAttrs) {
JS.extend(AttrsCtor, superAttrs.constructor);
}
var attrs = new AttrsCtor();
Object.defineProperty(owner, '__attrs__', {
value: attrs,
});
JS.value(owner, '__attrs__', attrs);
return attrs;
}
@@ -126,13 +127,19 @@ function attr (ctor, propName, newAttrs) {
}
}
// returns a readonly meta object
function getClassAttrs (ctor) {
return (ctor.hasOwnProperty('__attrs__') && ctor.__attrs__) || createAttrs(ctor);
}
// returns a writable meta object, used to set multi attributes
function getClassAttrsProto (ctor) {
return getClassAttrs(ctor).constructor.prototype;
}
function setClassAttr (ctor, propName, key, value) {
var attrs = getClassAttrs(ctor);
attrs.constructor.prototype[propName + DELIMETER + key] = value;
var proto = getClassAttrsProto(ctor);
proto[propName + DELIMETER + key] = value;
}
/**
@@ -222,7 +229,6 @@ cc.String = 'String';
/*
BuiltinAttributes: {
default: defaultValue,
_canUsedInGetter: true, (default true)
_canUsedInSetter: false, (default false) (NYI)
}
Getter or Setter: {
@@ -236,16 +242,6 @@ Callbacks: {
}
*/
var NonSerialized = {
serializable: false,
_canUsedInGetter: false
};
var EditorOnly = {
editorOnly: true,
_canUsedInGetter: false
};
function getTypeChecker (type, attrName) {
if (CC_DEV) {
return function (constructor, mainPropName) {
@@ -343,55 +339,53 @@ function ObjectType (typeCtor) {
};
}
function RawType (typename) {
var NEED_EXT_TYPES = ['image', 'json', 'text', 'audio']; // the types need to specify exact extname
return {
// type: 'raw',
rawType: typename,
serializable: false,
// hideInInspector: true,
_canUsedInGetter: false,
// function RawType (typename) {
// var NEED_EXT_TYPES = ['image', 'json', 'text', 'audio']; // the types need to specify exact extname
// return {
// // type: 'raw',
// rawType: typename,
// serializable: false,
// // hideInInspector: true,
_onAfterProp: function (constructor, mainPropName) {
// check raw object
var checked = !CC_DEV || (function checkRawType(constructor) {
if (! cc.isChildClassOf(constructor, cc.Asset)) {
cc.errorID(3630);
return false;
}
var attrs = getClassAttrs(constructor);
var found = false;
for (var p = 0; p < constructor.__props__.length; p++) {
var propName = constructor.__props__[p];
var rawType = attrs[propName + DELIMETER + 'rawType'];
if (rawType) {
var containsUppercase = (rawType.toLowerCase() !== rawType);
if (containsUppercase) {
cc.errorID(3631);
return false;
}
if (found) {
cc.errorID(3632);
return false;
}
found = true;
}
}
return true;
})(constructor);
}
};
}
// _onAfterProp: function (constructor, mainPropName) {
// // check raw object
// var checked = !CC_DEV || (function checkRawType(constructor) {
// if (! cc.isChildClassOf(constructor, cc.Asset)) {
// cc.errorID(3630);
// return false;
// }
// var attrs = getClassAttrs(constructor);
// var found = false;
// for (var p = 0; p < constructor.__props__.length; p++) {
// var propName = constructor.__props__[p];
// var rawType = attrs[propName + DELIMETER + 'rawType'];
// if (rawType) {
// var containsUppercase = (rawType.toLowerCase() !== rawType);
// if (containsUppercase) {
// cc.errorID(3631);
// return false;
// }
// if (found) {
// cc.errorID(3632);
// return false;
// }
// found = true;
// }
// }
// return true;
// })(constructor);
// }
// };
// }
module.exports = {
attr: attr,
getClassAttrs: getClassAttrs,
getClassAttrsProto: getClassAttrsProto,
setClassAttr: setClassAttr,
DELIMETER: DELIMETER,
getTypeChecker: getTypeChecker,
NonSerialized: NonSerialized,
EditorOnly: EditorOnly,
ObjectType: ObjectType,
RawType: RawType,
// RawType: RawType,
ScriptUuid: {}, // the value will be represented as a uuid string
};
+1 -1
View File
@@ -453,7 +453,7 @@ var _Deserializer = (function () {
// if (CC_TEST && !isPhantomJS) {
// cc.log(deserialize);
// }
Object.defineProperty(klass, '__deserialize__', { value: deserialize, writable: true });
JS.value(klass, '__deserialize__', deserialize, true);
}
deserialize(self, obj, serialized, klass, target);
// if preview or build
+209 -210
View File
@@ -176,234 +176,233 @@ function Parser (obj, parent) {
this.objsToClear_iN$t.length = 0;
}
JS.mixin(Parser.prototype, {
var proto = Parser.prototype;
getFuncModule: function (func, usedInNew) {
var clsName = JS.getClassName(func);
var clsNameIsModule = clsName.indexOf('.') !== -1;
if (clsNameIsModule) {
try {
// ensure is module
clsNameIsModule = (func === Function('return ' + clsName)());
if (clsNameIsModule) {
return clsName;
}
proto.getFuncModule = function (func, usedInNew) {
var clsName = JS.getClassName(func);
var clsNameIsModule = clsName.indexOf('.') !== -1;
if (clsNameIsModule) {
try {
// ensure is module
clsNameIsModule = (func === Function('return ' + clsName)());
if (clsNameIsModule) {
return clsName;
}
catch (e) {}
}
var index = this.funcs.indexOf(func);
if (index < 0) {
index = this.funcs.length;
this.funcs.push(func);
}
var res = 'F[' + index + ']';
return usedInNew ? '(' + res + ')' : res;
},
catch (e) {}
}
var index = this.funcs.indexOf(func);
if (index < 0) {
index = this.funcs.length;
this.funcs.push(func);
}
var res = 'F[' + index + ']';
return usedInNew ? '(' + res + ')' : res;
};
getObjRef: function (obj) {
var index = this.objs.indexOf(obj);
if (index < 0) {
index = this.objs.length;
this.objs.push(obj);
}
return 'O[' + index + ']';
},
proto.getObjRef = function (obj) {
var index = this.objs.indexOf(obj);
if (index < 0) {
index = this.objs.length;
this.objs.push(obj);
}
return 'O[' + index + ']';
};
enumerateCCClass: function (codeArray, obj, klass) {
var props = klass.__props__;
var attrs = Attr.getClassAttrs(klass);
for (var p = 0; p < props.length; p++) {
var key = props[p];
if (CC_EDITOR && key === '_id') {
proto.enumerateCCClass = function (codeArray, obj, klass) {
var props = klass.__props__;
var attrs = Attr.getClassAttrs(klass);
for (var p = 0; p < props.length; p++) {
var key = props[p];
if (CC_EDITOR && key === '_id') {
if (obj instanceof cc._BaseNode || obj instanceof cc.Component) {
continue;
}
}
if (attrs[key + SERIALIZABLE] !== false) {
var val = obj[key];
if (equalsToDefault(attrs[key + DEFAULT], val)) {
continue;
}
this.writeObjectField(codeArray, obj, key, val);
}
}
};
proto.instantiateArray = function (value) {
if (value.length === 0) {
return '[]';
}
var arrayVar = 't' + (++this.localVariableId);
var declaration = new Declaration(arrayVar, 'new Array(' + value.length + ')');
var codeArray = [declaration];
// assign a _iN$t flag to indicate that this object has been parsed.
value._iN$t = {
globalVar: '', // the name of declared global variable used to access this object
source: codeArray, // the source code array for this object
};
this.objsToClear_iN$t.push(value);
for (var i = 0; i < value.length; ++i) {
var statement = arrayVar + '[' + i + ']=';
this.writeFiled(codeArray, statement, value, i, value[i]);
}
return codeArray;
};
proto.enumerateField = function (obj, key, value) {
if (typeof value === 'object' && value) {
var _iN$t = value._iN$t;
if (_iN$t) {
// parsed
var globalVar = _iN$t.globalVar;
if (!globalVar) {
// declare a global var
globalVar = _iN$t.globalVar = 'v' + (++this.globalVariableId);
this.globalVariables.push(globalVar);
// insert assignment statement to assign to global var
var line = _iN$t.source[LINE_INDEX_OF_NEW_OBJ];
_iN$t.source[LINE_INDEX_OF_NEW_OBJ] = mergeDeclaration(globalVar + '=', line);
// if (typeof line ==='string' && line.startsWith(VAR)) {
// // var o=xxx -> var o=global=xxx
// var LEN_OF_VAR_O = 5;
// _iN$t.source[LINE_INDEX_OF_NEW_OBJ] = line.slice(0, LEN_OF_VAR_O) + '=' + globalVar + line.slice(LEN_OF_VAR_O);
// }
}
return globalVar;
}
else if (Array.isArray(value)) {
return this.instantiateArray(value);
}
else {
return this.instantiateObj(value);
}
}
else if (typeof value === 'function') {
return this.getFuncModule(value);
}
else if (typeof value === 'string') {
return escapeForJS(value);
}
else {
if (key === '_objFlags' && obj instanceof CCObject) {
value &= PersistentMask;
}
return value;
}
};
proto.writeObjectField = function (codeArray, obj, key, value) {
var statement;
if (IDENTIFIER_RE.test(key)) {
statement = LOCAL_OBJ + '.' + key + '=';
}
else {
statement = LOCAL_OBJ + '[' + escapeForJS(key) + ']=';
}
this.writeFiled(codeArray, statement, obj, key, value);
};
proto.writeFiled = function (codeArray, statement, obj, key, value) {
var expression = this.enumerateField(obj, key, value);
if (Array.isArray(expression)) {
expression[0] = mergeDeclaration(statement, expression[0]);
codeArray.push(expression);
}
else {
codeArray.push(mergeDeclaration(statement, expression) + ';');
}
};
// codeArray - the source code array for this object
proto.enumerateObject = function (codeArray, obj) {
var klass = obj.constructor;
if (cc.Class._isCCClass(klass)) {
this.enumerateCCClass(codeArray, obj, klass);
}
else {
// primitive javascript object
for (var key in obj) {
if (!obj.hasOwnProperty(key) ||
(key.charCodeAt(0) === 95 && key.charCodeAt(1) === 95 && // starts with "__"
key !== '__type__')
) {
continue;
}
var value = obj[key];
if (typeof value === 'object' && value && value === obj._iN$t) {
continue;
}
this.writeObjectField(codeArray, obj, key, value);
}
}
};
proto.instantiateObj = function (obj) {
if (obj instanceof cc.ValueType) {
return CCClass.getNewValueTypeCode(obj);
}
if (obj instanceof cc.Asset) {
// register to asset list and just return the reference.
return this.getObjRef(obj);
}
if (obj._objFlags & Destroyed) {
// the same as cc.isValid(obj)
return null;
}
var createCode;
var ctor = obj.constructor;
if (cc.Class._isCCClass(ctor)) {
if (this.parent) {
if (this.parent instanceof cc.Component) {
if (obj instanceof cc._BaseNode || obj instanceof cc.Component) {
continue;
return this.getObjRef(obj);
}
}
if (attrs[key + SERIALIZABLE] !== false) {
var val = obj[key];
if (equalsToDefault(attrs[key + DEFAULT], val)) {
continue;
}
this.writeObjectField(codeArray, obj, key, val);
}
}
},
instantiateArray: function (value) {
if (value.length === 0) {
return '[]';
}
var arrayVar = 't' + (++this.localVariableId);
var declaration = new Declaration(arrayVar, 'new Array(' + value.length + ')');
var codeArray = [declaration];
// assign a _iN$t flag to indicate that this object has been parsed.
value._iN$t = {
globalVar: '', // the name of declared global variable used to access this object
source: codeArray, // the source code array for this object
};
this.objsToClear_iN$t.push(value);
for (var i = 0; i < value.length; ++i) {
var statement = arrayVar + '[' + i + ']=';
this.writeFiled(codeArray, statement, value, i, value[i]);
}
return codeArray;
},
enumerateField: function (obj, key, value) {
if (typeof value === 'object' && value) {
var _iN$t = value._iN$t;
if (_iN$t) {
// parsed
var globalVar = _iN$t.globalVar;
if (!globalVar) {
// declare a global var
globalVar = _iN$t.globalVar = 'v' + (++this.globalVariableId);
this.globalVariables.push(globalVar);
// insert assignment statement to assign to global var
var line = _iN$t.source[LINE_INDEX_OF_NEW_OBJ];
_iN$t.source[LINE_INDEX_OF_NEW_OBJ] = mergeDeclaration(globalVar + '=', line);
// if (typeof line ==='string' && line.startsWith(VAR)) {
// // var o=xxx -> var o=global=xxx
// var LEN_OF_VAR_O = 5;
// _iN$t.source[LINE_INDEX_OF_NEW_OBJ] = line.slice(0, LEN_OF_VAR_O) + '=' + globalVar + line.slice(LEN_OF_VAR_O);
// }
}
return globalVar;
}
else if (Array.isArray(value)) {
return this.instantiateArray(value);
}
else {
return this.instantiateObj(value);
}
}
else if (typeof value === 'function') {
return this.getFuncModule(value);
}
else if (typeof value === 'string') {
return escapeForJS(value);
}
else {
if (key === '_objFlags' && obj instanceof CCObject) {
value &= PersistentMask;
}
return value;
}
},
writeObjectField: function (codeArray, obj, key, value) {
var statement;
if (IDENTIFIER_RE.test(key)) {
statement = LOCAL_OBJ + '.' + key + '=';
}
else {
statement = LOCAL_OBJ + '[' + escapeForJS(key) + ']=';
}
this.writeFiled(codeArray, statement, obj, key, value);
},
writeFiled: function (codeArray, statement, obj, key, value) {
var expression = this.enumerateField(obj, key, value);
if (Array.isArray(expression)) {
expression[0] = mergeDeclaration(statement, expression[0]);
codeArray.push(expression);
}
else {
codeArray.push(mergeDeclaration(statement, expression) + ';');
}
},
// codeArray - the source code array for this object
enumerateObject: function (codeArray, obj) {
var klass = obj.constructor;
if (cc.Class._isCCClass(klass)) {
this.enumerateCCClass(codeArray, obj, klass);
}
else {
// primitive javascript object
for (var key in obj) {
if (!obj.hasOwnProperty(key) ||
(key.charCodeAt(0) === 95 && key.charCodeAt(1) === 95 && // starts with "__"
key !== '__type__')
) {
continue;
}
var value = obj[key];
if (typeof value === 'object' && value && value === obj._iN$t) {
continue;
}
this.writeObjectField(codeArray, obj, key, value);
}
}
},
instantiateObj: function (obj) {
if (obj instanceof cc.ValueType) {
return CCClass.getNewValueTypeCode(obj);
}
if (obj instanceof cc.Asset) {
// register to asset list and just return the reference.
return this.getObjRef(obj);
}
if (obj._objFlags & Destroyed) {
// the same as cc.isValid(obj)
return null;
}
var createCode;
var ctor = obj.constructor;
if (cc.Class._isCCClass(ctor)) {
if (this.parent) {
if (this.parent instanceof cc.Component) {
if (obj instanceof cc._BaseNode || obj instanceof cc.Component) {
else if (this.parent instanceof cc._BaseNode) {
if (obj instanceof cc._BaseNode) {
if (!obj.isChildOf(this.parent)) {
// should not clone other nodes if not descendant
return this.getObjRef(obj);
}
}
else if (this.parent instanceof cc._BaseNode) {
if (obj instanceof cc._BaseNode) {
if (!obj.isChildOf(this.parent)) {
// should not clone other nodes if not descendant
return this.getObjRef(obj);
}
}
else if (obj instanceof cc.Component) {
if (!obj.node.isChildOf(this.parent)) {
// should not clone other component if not descendant
return this.getObjRef(obj);
}
else if (obj instanceof cc.Component) {
if (!obj.node.isChildOf(this.parent)) {
// should not clone other component if not descendant
return this.getObjRef(obj);
}
}
}
createCode = new Declaration(LOCAL_OBJ, 'new ' + this.getFuncModule(ctor, true) + '()');
}
else if (ctor === Object) {
createCode = new Declaration(LOCAL_OBJ, '{}');
}
else {
// do not clone unknown type
return this.getObjRef(obj);
}
createCode = new Declaration(LOCAL_OBJ, 'new ' + this.getFuncModule(ctor, true) + '()');
}
else if (ctor === Object) {
createCode = new Declaration(LOCAL_OBJ, '{}');
}
else {
// do not clone unknown type
return this.getObjRef(obj);
}
var codeArray = [createCode];
var codeArray = [createCode];
// assign a _iN$t flag to indicate that this object has been parsed.
obj._iN$t = {
globalVar: '', // the name of declared global variable used to access this object
source: codeArray, // the source code array for this object
//propName: '', // the propName this object defined in its source code,
// // if defined, use LOCAL_OBJ.propName to access the obj, else just use o
};
this.objsToClear_iN$t.push(obj);
// assign a _iN$t flag to indicate that this object has been parsed.
obj._iN$t = {
globalVar: '', // the name of declared global variable used to access this object
source: codeArray, // the source code array for this object
//propName: '', // the propName this object defined in its source code,
// // if defined, use LOCAL_OBJ.propName to access the obj, else just use o
};
this.objsToClear_iN$t.push(obj);
this.enumerateObject(codeArray, obj);
return ['(function(){',
codeArray,
'return o;})();'];
},
});
this.enumerateObject(codeArray, obj);
return ['(function(){',
codeArray,
'return o;})();'];
};
function compile (node) {
+108 -59
View File
@@ -234,6 +234,106 @@ var js = {
getPropertyDescriptor: _getPropertyDescriptor
};
var tmpValueDesc = {
value: undefined,
enumerable: false,
writable: false,
configurable: true
};
/**
* Define value, just help to call Object.defineProperty.<br>
* The configurable will be true.
* @method value
* @param {Object} obj
* @param {String} prop
* @param {any} value
* @param {Boolean} [writable=false]
* @param {Boolean} [enumerable=false]
*/
js.value = function (obj, prop, value, writable, enumerable) {
tmpValueDesc.value = value;
tmpValueDesc.writable = writable;
tmpValueDesc.enumerable = enumerable;
Object.defineProperty(obj, prop, tmpValueDesc);
tmpValueDesc.value = undefined;
};
var tmpGetSetDesc = {
get: null,
set: null,
enumerable: false,
};
/**
* Define get set accessor, just help to call Object.defineProperty(...)
* @method getset
* @param {Object} obj
* @param {String} prop
* @param {Function} getter
* @param {Function} setter
* @param {Boolean} [enumerable=false]
*/
js.getset = function (obj, prop, getter, setter, enumerable) {
if (typeof setter !== 'function') {
enumerable = setter;
setter = undefined;
}
tmpGetSetDesc.get = getter;
tmpGetSetDesc.set = setter;
tmpGetSetDesc.enumerable = enumerable;
Object.defineProperty(obj, prop, tmpGetSetDesc);
tmpGetSetDesc.get = null;
tmpGetSetDesc.set = null;
};
var tmpGetDesc = {
get: null,
enumerable: false,
configurable: false
};
/**
* Define get accessor, just help to call Object.defineProperty(...)
* @method get
* @param {Object} obj
* @param {String} prop
* @param {Function} getter
* @param {Boolean} [enumerable=false]
* @param {Boolean} [configurable=false]
*/
js.get = function (obj, prop, getter, enumerable, configurable) {
tmpGetDesc.get = getter;
tmpGetDesc.enumerable = enumerable;
tmpGetDesc.configurable = configurable;
Object.defineProperty(obj, prop, tmpGetDesc);
tmpGetDesc.get = null;
};
var tmpSetDesc = {
set: null,
enumerable: false,
configurable: false
};
/**
* Define set accessor, just help to call Object.defineProperty(...)
* @method set
* @param {Object} obj
* @param {String} prop
* @param {Function} setter
* @param {Boolean} [enumerable=false]
* @param {Boolean} [configurable=false]
*/
js.set = function (obj, prop, setter, enumerable, configurable) {
tmpSetDesc.set = setter;
tmpSetDesc.enumerable = enumerable;
tmpSetDesc.configurable = configurable;
Object.defineProperty(obj, prop, tmpSetDesc);
tmpSetDesc.set = null;
};
/**
* Get class name of the object, if object is just a {} (and which class named 'Object'), it will return "".
* (modified from <a href="http://stackoverflow.com/questions/1249531/how-to-get-a-javascript-objects-class">the code from this stackoverflow post</a>)
@@ -429,91 +529,40 @@ cc.js.unregisterClass to remove the id of unused class';
};
if (CC_DEV) {
Object.defineProperty(js, '_registeredClassIds', {
get: function () {
js.getset(js, '_registeredClassIds',
function () {
var dump = {};
for (var id in _idToClass) {
dump[id] = _idToClass[id];
}
return dump;
},
set: function (value) {
function (value) {
js.clear(_idToClass);
for (var id in value) {
_idToClass[id] = value[id];
}
}
});
Object.defineProperty(js, '_registeredClassNames', {
get: function () {
);
js.getset(js, '_registeredClassNames',
function () {
var dump = {};
for (var id in _nameToClass) {
dump[id] = _nameToClass[id];
}
return dump;
},
set: function (value) {
function (value) {
js.clear(_nameToClass);
for (var id in value) {
_nameToClass[id] = value[id];
}
}
});
);
}
})();
/**
* Define get set accessor, just help to call Object.defineProperty(...)
* @method getset
* @param {any} obj
* @param {String} prop
* @param {Function} getter
* @param {Function} setter
* @param {Boolean} [enumerable=false]
*/
js.getset = function (obj, prop, getter, setter, enumerable) {
if (typeof setter !== 'function') {
enumerable = setter;
setter = undefined;
}
Object.defineProperty(obj, prop, {
get: getter,
set: setter,
enumerable: !!enumerable
});
};
/**
* Define get accessor, just help to call Object.defineProperty(...)
* @method get
* @param {any} obj
* @param {String} prop
* @param {Function} getter
* @param {Boolean} [enumerable=false]
*/
js.get = function (obj, prop, getter, enumerable) {
Object.defineProperty(obj, prop, {
get: getter,
enumerable: !!enumerable
});
};
/**
* Define set accessor, just help to call Object.defineProperty(...)
* @method set
* @param {any} obj
* @param {String} prop
* @param {Function} setter
* @param {Boolean} [enumerable=false]
*/
js.set = function (obj, prop, setter, enumerable) {
Object.defineProperty(obj, prop, {
set: setter,
enumerable: !!enumerable
});
};
/**
* Defines a polyfill field for obsoleted codes.
* @method obsolete
+18 -20
View File
@@ -88,27 +88,25 @@ module.exports = {
};
if (CC_DEV) {
cc.js.mixin(module.exports, {
///**
// * @param {Object} obj
// * @return {Boolean} is {} ?
// */
isPlainEmptyObj_DEV: function (obj) {
if (!obj || obj.constructor !== Object) {
return false;
}
// jshint ignore: start
for (var k in obj) {
return false;
}
// jshint ignore: end
return true;
},
cloneable_DEV: function (obj) {
return obj && typeof obj.clone === 'function' &&
(obj.constructor.prototype.hasOwnProperty('clone') || obj.hasOwnProperty('clone'));
///**
// * @param {Object} obj
// * @return {Boolean} is {} ?
// */
module.exports.isPlainEmptyObj_DEV = function (obj) {
if (!obj || obj.constructor !== Object) {
return false;
}
});
// jshint ignore: start
for (var k in obj) {
return false;
}
// jshint ignore: end
return true;
};
module.exports.cloneable_DEV = function (obj) {
return obj && typeof obj.clone === 'function' &&
(obj.constructor.prototype.hasOwnProperty('clone') || obj.hasOwnProperty('clone'));
};
}
if (CC_TEST) {
+409 -414
View File
@@ -604,455 +604,450 @@ game.once(game.EVENT_RENDERER_INITED, function () {
return renderCanvas;
};
JS.mixin(Texture2D.prototype, {
_generateTextureCacheForColor: function(){
if (this.channelCache)
return this.channelCache;
_p._generateTextureCacheForColor = function(){
if (this.channelCache)
return this.channelCache;
var textureCache = [
document.createElement("canvas"),
document.createElement("canvas"),
document.createElement("canvas"),
document.createElement("canvas")
];
//todo texture onload
renderToCache(this._htmlElementObj, textureCache);
return this.channelCache = textureCache;
},
var textureCache = [
document.createElement("canvas"),
document.createElement("canvas"),
document.createElement("canvas"),
document.createElement("canvas")
];
//todo texture onload
renderToCache(this._htmlElementObj, textureCache);
return this.channelCache = textureCache;
};
_switchToGray: function(toGray){
if(!this._textureLoaded || this._isGray === toGray)
return;
this._isGray = toGray;
if(this._isGray){
this._backupElement = this._htmlElementObj;
if(!this._grayElementObj)
this._grayElementObj = generateGrayTexture(this._htmlElementObj);
this._htmlElementObj = this._grayElementObj;
} else {
if(this._backupElement !== null)
this._htmlElementObj = this._backupElement;
}
},
_generateGrayTexture: function() {
if(!this._textureLoaded)
return null;
var grayElement = generateGrayTexture(this._htmlElementObj);;
var newTexture = new Texture2D();
newTexture.initWithElement(grayElement);
newTexture.handleLoadedTexture();
return newTexture;
},
//change color function
_generateColorTexture: sys._supportCanvasNewBlendModes ? function(r, g, b, rect, canvas) {
var onlyCanvas = false;
if(canvas)
onlyCanvas = true;
else
canvas = document.createElement("canvas");
var textureImage = this._htmlElementObj;
if(!rect)
rect = cc.rect(0, 0, textureImage.width, textureImage.height);
canvas.width = rect.width;
canvas.height = rect.height;
if(rect.width && rect.height) {
var context = canvas.getContext("2d");
context.globalCompositeOperation = "source-over";
context.fillStyle = "rgb(" + (r|0) + "," + (g|0) + "," + (b|0) + ")";
context.fillRect(0, 0, rect.width, rect.height);
context.globalCompositeOperation = "multiply";
context.drawImage(
textureImage,
rect.x, rect.y, rect.width, rect.height,
0, 0, rect.width, rect.height
);
context.globalCompositeOperation = "destination-atop";
context.drawImage(
textureImage,
rect.x, rect.y, rect.width, rect.height,
0, 0, rect.width, rect.height
);
}
if(onlyCanvas)
return canvas;
var newTexture = new Texture2D();
newTexture.initWithElement(canvas);
newTexture.handleLoadedTexture();
return newTexture;
} : function(r, g, b, rect, canvas){
var onlyCanvas = false;
if(canvas)
onlyCanvas = true;
else
canvas = document.createElement("canvas");
var textureImage = this._htmlElementObj;
if(!rect)
rect = cc.rect(0, 0, textureImage.width, textureImage.height);
canvas.width = rect.width;
canvas.height = rect.height;
if(rect.width && rect.height) {
var context = canvas.getContext("2d");
context.drawImage(
textureImage,
rect.x, rect.y, rect.width, rect.height,
0, 0, rect.width, rect.height
);
var imageData = context.getImageData(0,0,canvas.width, canvas.height);
var data = imageData.data;
r = r/255;
g = g/255;
b = b/255;
for (var i = 0; i < data.length; i += 4) {
data[i] = data[i] * r;
data[i + 1] = data[i+1] * g;
data[i + 2] = data[i+2] * b;
}
context.putImageData(imageData, 0, 0);
}
if(onlyCanvas)
return canvas;
var newTexture = new Texture2D();
newTexture.initWithElement(canvas);
newTexture.handleLoadedTexture();
return newTexture;
_p._switchToGray = function(toGray){
if(!this._textureLoaded || this._isGray === toGray)
return;
this._isGray = toGray;
if(this._isGray){
this._backupElement = this._htmlElementObj;
if(!this._grayElementObj)
this._grayElementObj = generateGrayTexture(this._htmlElementObj);
this._htmlElementObj = this._grayElementObj;
} else {
if(this._backupElement !== null)
this._htmlElementObj = this._backupElement;
}
});
};
_p._generateGrayTexture = function() {
if(!this._textureLoaded)
return null;
var grayElement = generateGrayTexture(this._htmlElementObj);;
var newTexture = new Texture2D();
newTexture.initWithElement(grayElement);
newTexture.handleLoadedTexture();
return newTexture;
};
//change color function
_p._generateColorTexture = sys._supportCanvasNewBlendModes ? function(r, g, b, rect, canvas) {
var onlyCanvas = false;
if(canvas)
onlyCanvas = true;
else
canvas = document.createElement("canvas");
var textureImage = this._htmlElementObj;
if(!rect)
rect = cc.rect(0, 0, textureImage.width, textureImage.height);
canvas.width = rect.width;
canvas.height = rect.height;
if(rect.width && rect.height) {
var context = canvas.getContext("2d");
context.globalCompositeOperation = "source-over";
context.fillStyle = "rgb(" + (r|0) + "," + (g|0) + "," + (b|0) + ")";
context.fillRect(0, 0, rect.width, rect.height);
context.globalCompositeOperation = "multiply";
context.drawImage(
textureImage,
rect.x, rect.y, rect.width, rect.height,
0, 0, rect.width, rect.height
);
context.globalCompositeOperation = "destination-atop";
context.drawImage(
textureImage,
rect.x, rect.y, rect.width, rect.height,
0, 0, rect.width, rect.height
);
}
if(onlyCanvas)
return canvas;
var newTexture = new Texture2D();
newTexture.initWithElement(canvas);
newTexture.handleLoadedTexture();
return newTexture;
} : function(r, g, b, rect, canvas){
var onlyCanvas = false;
if(canvas)
onlyCanvas = true;
else
canvas = document.createElement("canvas");
var textureImage = this._htmlElementObj;
if(!rect)
rect = cc.rect(0, 0, textureImage.width, textureImage.height);
canvas.width = rect.width;
canvas.height = rect.height;
if(rect.width && rect.height) {
var context = canvas.getContext("2d");
context.drawImage(
textureImage,
rect.x, rect.y, rect.width, rect.height,
0, 0, rect.width, rect.height
);
var imageData = context.getImageData(0,0,canvas.width, canvas.height);
var data = imageData.data;
r = r/255;
g = g/255;
b = b/255;
for (var i = 0; i < data.length; i += 4) {
data[i] = data[i] * r;
data[i + 1] = data[i+1] * g;
data[i + 2] = data[i+2] * b;
}
context.putImageData(imageData, 0, 0);
}
if(onlyCanvas)
return canvas;
var newTexture = new Texture2D();
newTexture.initWithElement(canvas);
newTexture.handleLoadedTexture();
return newTexture;
};
} else if (cc._renderType === game.RENDER_TYPE_WEBGL) {
JS.mixin(Texture2D.prototype, {
_p.initWithData = function (data, pixelFormat, pixelsWide, pixelsHigh, contentSize) {
var self = this, tex2d = Texture2D;
var gl = cc._renderContext;
var format = gl.RGBA, type = gl.UNSIGNED_BYTE;
initWithData: function (data, pixelFormat, pixelsWide, pixelsHigh, contentSize) {
var self = this, tex2d = Texture2D;
var gl = cc._renderContext;
var format = gl.RGBA, type = gl.UNSIGNED_BYTE;
var bitsPerPixel = Texture2D._B[pixelFormat];
var bytesPerRow = pixelsWide * bitsPerPixel / 8;
if (bytesPerRow % 8 === 0) {
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 8);
} else if (bytesPerRow % 4 === 0) {
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
} else if (bytesPerRow % 2 === 0) {
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 2);
} else {
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
}
self._webTextureObj = gl.createTexture();
cc.gl.bindTexture2D(self);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
// Specify OpenGL texture image
switch (pixelFormat) {
case tex2d.PIXEL_FORMAT_RGBA8888:
format = gl.RGBA;
break;
case tex2d.PIXEL_FORMAT_RGB888:
format = gl.RGB;
break;
case tex2d.PIXEL_FORMAT_RGBA4444:
type = gl.UNSIGNED_SHORT_4_4_4_4;
break;
case tex2d.PIXEL_FORMAT_RGB5A1:
type = gl.UNSIGNED_SHORT_5_5_5_1;
break;
case tex2d.PIXEL_FORMAT_RGB565:
type = gl.UNSIGNED_SHORT_5_6_5;
break;
case tex2d.PIXEL_FORMAT_AI88:
format = gl.LUMINANCE_ALPHA;
break;
case tex2d.PIXEL_FORMAT_A8:
format = gl.ALPHA;
break;
case tex2d.PIXEL_FORMAT_I8:
format = gl.LUMINANCE;
break;
default:
cc.assertID(0, 3113);
}
gl.texImage2D(gl.TEXTURE_2D, 0, format, pixelsWide, pixelsHigh, 0, format, type, data);
self._contentSize.width = contentSize.width;
self._contentSize.height = contentSize.height;
self._pixelWidth = pixelsWide;
self._pixelHeight = pixelsHigh;
self._pixelFormat = pixelFormat;
self._hasPremultipliedAlpha = false;
self._hasMipmaps = false;
self._textureLoaded = true;
return true;
},
initWithImage: function (uiImage) {
if (uiImage == null) {
cc.logID(3104);
return false;
}
var imageWidth = uiImage.getWidth();
var imageHeight = uiImage.getHeight();
var maxTextureSize = cc.configuration.getMaxTextureSize();
if (imageWidth > maxTextureSize || imageHeight > maxTextureSize) {
cc.logID(3105, imageWidth, imageHeight, maxTextureSize, maxTextureSize);
return false;
}
this._textureLoaded = true;
// always load premultiplied images
return this._initPremultipliedATextureWithImage(uiImage, imageWidth, imageHeight);
},
initWithElement: function (element) {
if (!element)
return;
this._webTextureObj = cc._renderContext.createTexture();
this._htmlElementObj = element;
this._textureLoaded = true;
},
// [premultiplied=false]
handleLoadedTexture: function (premultiplied) {
premultiplied = !!premultiplied;
var self = this;
// Not sure about this ! Some texture need to be updated even after loaded
if (!game._rendererInitialized) {
return;
}
if (!self._htmlElementObj || !self._htmlElementObj.width || !self._htmlElementObj.height) {
return;
}
//upload image to buffer
var gl = cc._renderContext;
cc.gl.bindTexture2D(self);
var bitsPerPixel = Texture2D._B[pixelFormat];
var bytesPerRow = pixelsWide * bitsPerPixel / 8;
if (bytesPerRow % 8 === 0) {
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 8);
} else if (bytesPerRow % 4 === 0) {
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
if(premultiplied)
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
} else if (bytesPerRow % 2 === 0) {
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 2);
} else {
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
}
// Specify OpenGL texture image
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, self._htmlElementObj);
self._webTextureObj = gl.createTexture();
cc.gl.bindTexture2D(self);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
// Specify OpenGL texture image
switch (pixelFormat) {
case tex2d.PIXEL_FORMAT_RGBA8888:
format = gl.RGBA;
break;
case tex2d.PIXEL_FORMAT_RGB888:
format = gl.RGB;
break;
case tex2d.PIXEL_FORMAT_RGBA4444:
type = gl.UNSIGNED_SHORT_4_4_4_4;
break;
case tex2d.PIXEL_FORMAT_RGB5A1:
type = gl.UNSIGNED_SHORT_5_5_5_1;
break;
case tex2d.PIXEL_FORMAT_RGB565:
type = gl.UNSIGNED_SHORT_5_6_5;
break;
case tex2d.PIXEL_FORMAT_AI88:
format = gl.LUMINANCE_ALPHA;
break;
case tex2d.PIXEL_FORMAT_A8:
format = gl.ALPHA;
break;
case tex2d.PIXEL_FORMAT_I8:
format = gl.LUMINANCE;
break;
default:
cc.assertID(0, 3113);
}
gl.texImage2D(gl.TEXTURE_2D, 0, format, pixelsWide, pixelsHigh, 0, format, type, data);
self._contentSize.width = contentSize.width;
self._contentSize.height = contentSize.height;
self._pixelWidth = pixelsWide;
self._pixelHeight = pixelsHigh;
self._pixelFormat = pixelFormat;
self._hasPremultipliedAlpha = false;
self._hasMipmaps = false;
self._textureLoaded = true;
return true;
};
_p.initWithImage = function (uiImage) {
if (uiImage == null) {
cc.logID(3104);
return false;
}
var imageWidth = uiImage.getWidth();
var imageHeight = uiImage.getHeight();
var maxTextureSize = cc.configuration.getMaxTextureSize();
if (imageWidth > maxTextureSize || imageHeight > maxTextureSize) {
cc.logID(3105, imageWidth, imageHeight, maxTextureSize, maxTextureSize);
return false;
}
this._textureLoaded = true;
// always load premultiplied images
return this._initPremultipliedATextureWithImage(uiImage, imageWidth, imageHeight);
};
_p.initWithElement = function (element) {
if (!element)
return;
this._webTextureObj = cc._renderContext.createTexture();
this._htmlElementObj = element;
this._textureLoaded = true;
};
// [premultiplied=false]
_p.handleLoadedTexture = function (premultiplied) {
premultiplied = !!premultiplied;
var self = this;
// Not sure about this ! Some texture need to be updated even after loaded
if (!game._rendererInitialized) {
return;
}
if (!self._htmlElementObj || !self._htmlElementObj.width || !self._htmlElementObj.height) {
return;
}
//upload image to buffer
var gl = cc._renderContext;
cc.gl.bindTexture2D(self);
gl.pixelStorei(gl.UNPACK_ALIGNMENT, 4);
if(premultiplied)
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
// Specify OpenGL texture image
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, self._htmlElementObj);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
cc.gl.bindTexture2D(null);
if(premultiplied)
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
var pixelsWide = self._htmlElementObj.width;
var pixelsHigh = self._htmlElementObj.height;
self._pixelWidth = self._contentSize.width = pixelsWide;
self._pixelHeight = self._contentSize.height = pixelsHigh;
self._pixelFormat = Texture2D.PIXEL_FORMAT_RGBA8888;
self._hasPremultipliedAlpha = premultiplied;
self._hasMipmaps = false;
self._textureLoaded = true;
if (cc.view._antiAliasEnabled) {
self.setAntiAliasTexParameters();
}
else {
self.setAliasTexParameters();
}
self._htmlElementObj = null;
//dispatch load event to listener.
self.emit("load");
};
_p.setTexParameters = function (texParams, magFilter, wrapS, wrapT) {
var _t = this;
var gl = cc._renderContext;
if(magFilter !== undefined)
texParams = {minFilter: texParams, magFilter: magFilter, wrapS: wrapS, wrapT: wrapT};
cc.assertID((_t._pixelWidth === misc.NextPOT(_t._pixelWidth) && _t._pixelHeight === misc.NextPOT(_t._pixelHeight)) ||
(texParams.wrapS === gl.CLAMP_TO_EDGE && texParams.wrapT === gl.CLAMP_TO_EDGE),
3116);
cc.gl.bindTexture2D(_t);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texParams.minFilter);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texParams.magFilter);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, texParams.wrapS);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, texParams.wrapT);
};
_p.setAntiAliasTexParameters = function () {
var gl = cc._renderContext;
cc.gl.bindTexture2D(this);
if (!this._hasMipmaps)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
else
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
};
cc.gl.bindTexture2D(null);
if(premultiplied)
gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
_p.setAliasTexParameters = function () {
var gl = cc._renderContext;
var pixelsWide = self._htmlElementObj.width;
var pixelsHigh = self._htmlElementObj.height;
cc.gl.bindTexture2D(this);
if (!this._hasMipmaps)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
else
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
};
self._pixelWidth = self._contentSize.width = pixelsWide;
self._pixelHeight = self._contentSize.height = pixelsHigh;
self._pixelFormat = Texture2D.PIXEL_FORMAT_RGBA8888;
_p.generateMipmap = function () {
var _t = this;
cc.assertID(_t._pixelWidth === misc.NextPOT(_t._pixelWidth) && _t._pixelHeight === misc.NextPOT(_t._pixelHeight), 3117);
self._hasPremultipliedAlpha = premultiplied;
self._hasMipmaps = false;
self._textureLoaded = true;
cc.gl.bindTexture2D(_t);
cc._renderContext.generateMipmap(cc._renderContext.TEXTURE_2D);
_t._hasMipmaps = true;
};
if (cc.view._antiAliasEnabled) {
self.setAntiAliasTexParameters();
}
else {
self.setAliasTexParameters();
_p.stringForFormat = function () {
return Texture2D._M[this._pixelFormat];
};
_p.bitsPerPixelForFormat = function (format) {//TODO I want to delete the format argument, use this._pixelFormat
format = format || this._pixelFormat;
var value = Texture2D._B[format];
if (value != null) return value;
cc.logID(3110, format);
return -1;
};
_p._initPremultipliedATextureWithImage = function (uiImage, width, height) {
var tex2d = Texture2D;
var tempData = uiImage.getData();
var inPixel32 = null;
var inPixel8 = null;
var outPixel16 = null;
var hasAlpha = uiImage.hasAlpha();
var imageSize = cc.size(uiImage.getWidth(), uiImage.getHeight());
var pixelFormat = tex2d.defaultPixelFormat;
var bpp = uiImage.getBitsPerComponent();
var i;
// compute pixel format
if (!hasAlpha) {
if (bpp >= 8) {
pixelFormat = tex2d.PIXEL_FORMAT_RGB888;
} else {
cc.logID(3111);
pixelFormat = tex2d.PIXEL_FORMAT_RGB565;
}
}
self._htmlElementObj = null;
// Repack the pixel data into the right format
var length = width * height;
//dispatch load event to listener.
self.emit("load");
},
setTexParameters: function (texParams, magFilter, wrapS, wrapT) {
var _t = this;
var gl = cc._renderContext;
if(magFilter !== undefined)
texParams = {minFilter: texParams, magFilter: magFilter, wrapS: wrapS, wrapT: wrapT};
cc.assertID((_t._pixelWidth === misc.NextPOT(_t._pixelWidth) && _t._pixelHeight === misc.NextPOT(_t._pixelHeight)) ||
(texParams.wrapS === gl.CLAMP_TO_EDGE && texParams.wrapT === gl.CLAMP_TO_EDGE),
3116);
cc.gl.bindTexture2D(_t);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, texParams.minFilter);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, texParams.magFilter);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, texParams.wrapS);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, texParams.wrapT);
},
setAntiAliasTexParameters: function () {
var gl = cc._renderContext;
cc.gl.bindTexture2D(this);
if (!this._hasMipmaps)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
else
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
},
setAliasTexParameters: function () {
var gl = cc._renderContext;
cc.gl.bindTexture2D(this);
if (!this._hasMipmaps)
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
else
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST_MIPMAP_NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
},
generateMipmap: function () {
var _t = this;
cc.assertID(_t._pixelWidth === misc.NextPOT(_t._pixelWidth) && _t._pixelHeight === misc.NextPOT(_t._pixelHeight), 3117);
cc.gl.bindTexture2D(_t);
cc._renderContext.generateMipmap(cc._renderContext.TEXTURE_2D);
_t._hasMipmaps = true;
},
stringForFormat: function () {
return Texture2D._M[this._pixelFormat];
},
bitsPerPixelForFormat: function (format) {//TODO I want to delete the format argument, use this._pixelFormat
format = format || this._pixelFormat;
var value = Texture2D._B[format];
if (value != null) return value;
cc.logID(3110, format);
return -1;
},
_initPremultipliedATextureWithImage: function (uiImage, width, height) {
var tex2d = Texture2D;
var tempData = uiImage.getData();
var inPixel32 = null;
var inPixel8 = null;
var outPixel16 = null;
var hasAlpha = uiImage.hasAlpha();
var imageSize = cc.size(uiImage.getWidth(), uiImage.getHeight());
var pixelFormat = tex2d.defaultPixelFormat;
var bpp = uiImage.getBitsPerComponent();
var i;
// compute pixel format
if (!hasAlpha) {
if (bpp >= 8) {
pixelFormat = tex2d.PIXEL_FORMAT_RGB888;
} else {
cc.logID(3111);
pixelFormat = tex2d.PIXEL_FORMAT_RGB565;
}
}
// Repack the pixel data into the right format
var length = width * height;
if (pixelFormat === tex2d.PIXEL_FORMAT_RGB565) {
if (hasAlpha) {
// Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGGBBBBB"
tempData = new Uint16Array(width * height);
inPixel32 = uiImage.getData();
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
}
} else {
// Convert "RRRRRRRRRGGGGGGGGBBBBBBBB" to "RRRRRGGGGGGBBBBB"
tempData = new Uint16Array(width * height);
inPixel8 = uiImage.getData();
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
}
}
} else if (pixelFormat === tex2d.PIXEL_FORMAT_RGBA4444) {
// Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRGGGGBBBBAAAA"
tempData = new Uint16Array(width * height);
inPixel32 = uiImage.getData();
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
}
} else if (pixelFormat === tex2d.PIXEL_FORMAT_RGB5A1) {
// Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGBBBBBA"
if (pixelFormat === tex2d.PIXEL_FORMAT_RGB565) {
if (hasAlpha) {
// Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGGBBBBB"
tempData = new Uint16Array(width * height);
inPixel32 = uiImage.getData();
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) >> 2) << 5) | // G
((((inPixel32[i] >> 16) & 0xFF) >> 3) << 0); // B
}
} else if (pixelFormat === tex2d.PIXEL_FORMAT_A8) {
// Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "AAAAAAAA"
tempData = new Uint8Array(width * height);
inPixel32 = uiImage.getData();
} else {
// Convert "RRRRRRRRRGGGGGGGGBBBBBBBB" to "RRRRRGGGGGGBBBBB"
tempData = new Uint16Array(width * height);
inPixel8 = uiImage.getData();
for (i = 0; i < length; ++i) {
tempData[i] = (inPixel32 >> 24) & 0xFF; // A
tempData[i] =
(((inPixel8[i] & 0xFF) >> 3) << 11) | // R
(((inPixel8[i] & 0xFF) >> 2) << 5) | // G
(((inPixel8[i] & 0xFF) >> 3) << 0); // B
}
}
} else if (pixelFormat === tex2d.PIXEL_FORMAT_RGBA4444) {
// Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRGGGGBBBBAAAA"
tempData = new Uint16Array(width * height);
inPixel32 = uiImage.getData();
if (hasAlpha && pixelFormat === tex2d.PIXEL_FORMAT_RGB888) {
// Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRRRRGGGGGGGGBBBBBBBB"
inPixel32 = uiImage.getData();
tempData = new Uint8Array(width * height * 3);
for (i = 0; i < length; ++i) {
tempData[i * 3] = (inPixel32 >> 0) & 0xFF; // R
tempData[i * 3 + 1] = (inPixel32 >> 8) & 0xFF; // G
tempData[i * 3 + 2] = (inPixel32 >> 16) & 0xFF; // B
}
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
}
} else if (pixelFormat === tex2d.PIXEL_FORMAT_RGB5A1) {
// Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRGGGGGBBBBBA"
tempData = new Uint16Array(width * height);
inPixel32 = uiImage.getData();
this.initWithData(tempData, pixelFormat, width, height, imageSize);
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
}
} else if (pixelFormat === tex2d.PIXEL_FORMAT_A8) {
// Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "AAAAAAAA"
tempData = new Uint8Array(width * height);
inPixel32 = uiImage.getData();
if (tempData != uiImage.getData())
tempData = null;
this._hasPremultipliedAlpha = uiImage.isPremultipliedAlpha();
return true;
for (i = 0; i < length; ++i) {
tempData[i] = (inPixel32 >> 24) & 0xFF; // A
}
}
});
if (hasAlpha && pixelFormat === tex2d.PIXEL_FORMAT_RGB888) {
// Convert "RRRRRRRRRGGGGGGGGBBBBBBBBAAAAAAAA" to "RRRRRRRRGGGGGGGGBBBBBBBB"
inPixel32 = uiImage.getData();
tempData = new Uint8Array(width * height * 3);
for (i = 0; i < length; ++i) {
tempData[i * 3] = (inPixel32 >> 0) & 0xFF; // R
tempData[i * 3 + 1] = (inPixel32 >> 8) & 0xFF; // G
tempData[i * 3 + 2] = (inPixel32 >> 16) & 0xFF; // B
}
}
this.initWithData(tempData, pixelFormat, width, height, imageSize);
if (tempData != uiImage.getData())
tempData = null;
this._hasPremultipliedAlpha = uiImage.isPremultipliedAlpha();
return true;
};
}
});
+61 -63
View File
@@ -623,74 +623,72 @@ cc.defineGetterSetter(_p, "quads", _p.getQuads, _p.setQuads);
game.once(game.EVENT_RENDERER_INITED, function () {
if (cc._renderType === game.RENDER_TYPE_WEBGL) {
JS.mixin(TextureAtlas.prototype, {
_setupVBO: function () {
var _t = this;
var gl = cc._renderContext;
//create WebGLBuffer
_t._buffersVBO[0] = gl.createBuffer();
_t._buffersVBO[1] = gl.createBuffer();
TextureAtlas.prototype._setupVBO = function () {
var _t = this;
var gl = cc._renderContext;
//create WebGLBuffer
_t._buffersVBO[0] = gl.createBuffer();
_t._buffersVBO[1] = gl.createBuffer();
_t._quadsWebBuffer = gl.createBuffer();
_t._mapBuffers();
},
_t._quadsWebBuffer = gl.createBuffer();
_t._mapBuffers();
};
_mapBuffers: function () {
var _t = this;
var gl = cc._renderContext;
TextureAtlas.prototype._mapBuffers = function () {
var _t = this;
var gl = cc._renderContext;
gl.bindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer);
gl.bindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer);
gl.bufferData(gl.ARRAY_BUFFER, _t._quadsArrayBuffer, gl.DYNAMIC_DRAW);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _t._buffersVBO[1]);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, _t._indices, gl.STATIC_DRAW);
//cc.checkGLErrorDebug();
};
TextureAtlas.prototype.drawQuads = function () {
this.drawNumberOfQuads(this._totalQuads, 0);
};
TextureAtlas.prototype.drawNumberOfQuads = function (n, start) {
var _t = this;
start = start || 0;
if (0 === n || !_t.texture || !_t.texture.isLoaded())
return;
var gl = cc._renderContext;
cc.gl.bindTexture2D(_t.texture);
//
// Using VBO without VAO
//
//vertices
//gl.bindBuffer(gl.ARRAY_BUFFER, _t._buffersVBO[0]);
// XXX: update is done in draw... perhaps it should be done in a timer
gl.bindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer);
gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION);
gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_COLOR);
gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_TEX_COORDS);
if (_t.dirty){
gl.bufferData(gl.ARRAY_BUFFER, _t._quadsArrayBuffer, gl.DYNAMIC_DRAW);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _t._buffersVBO[1]);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, _t._indices, gl.STATIC_DRAW);
//cc.checkGLErrorDebug();
},
drawQuads: function () {
this.drawNumberOfQuads(this._totalQuads, 0);
},
drawNumberOfQuads: function (n, start) {
var _t = this;
start = start || 0;
if (0 === n || !_t.texture || !_t.texture.isLoaded())
return;
var gl = cc._renderContext;
cc.gl.bindTexture2D(_t.texture);
//
// Using VBO without VAO
//
//vertices
//gl.bindBuffer(gl.ARRAY_BUFFER, _t._buffersVBO[0]);
// XXX: update is done in draw... perhaps it should be done in a timer
gl.bindBuffer(gl.ARRAY_BUFFER, _t._quadsWebBuffer);
gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION);
gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_COLOR);
gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_TEX_COORDS);
if (_t.dirty){
gl.bufferData(gl.ARRAY_BUFFER, _t._quadsArrayBuffer, gl.DYNAMIC_DRAW);
_t.dirty = false;
}
gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0); // vertices
gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12); // colors
gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16); // tex coords
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _t._buffersVBO[1]);
if (cc.macro.TEXTURE_ATLAS_USE_TRIANGLE_STRIP)
gl.drawElements(gl.TRIANGLE_STRIP, n * 6, gl.UNSIGNED_SHORT, start * 6 * _t._indices.BYTES_PER_ELEMENT);
else
gl.drawElements(gl.TRIANGLES, n * 6, gl.UNSIGNED_SHORT, start * 6 * _t._indices.BYTES_PER_ELEMENT);
cc.g_NumberOfDraws++;
//cc.checkGLErrorDebug();
_t.dirty = false;
}
});
gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0); // vertices
gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12); // colors
gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16); // tex coords
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _t._buffersVBO[1]);
if (cc.macro.TEXTURE_ATLAS_USE_TRIANGLE_STRIP)
gl.drawElements(gl.TRIANGLE_STRIP, n * 6, gl.UNSIGNED_SHORT, start * 6 * _t._indices.BYTES_PER_ELEMENT);
else
gl.drawElements(gl.TRIANGLES, n * 6, gl.UNSIGNED_SHORT, start * 6 * _t._indices.BYTES_PER_ELEMENT);
cc.g_NumberOfDraws++;
//cc.checkGLErrorDebug();
};
}
});
+1 -1
View File
@@ -149,7 +149,7 @@ m.imagePool = {
this.count++;
}
}
}
};
module.exports = m;
+3 -4
View File
@@ -161,12 +161,11 @@ var Color = (function () {
MAGENTA: [255, 0, 255]
};
for (var colorName in DefaultColors) {
var colorGetter = (function (r, g, b, a) {
JS.get(Color, colorName, (function (rgba) {
return function () {
return new Color(r, g, b, a);
return new Color(rgba[0], rgba[1], rgba[2], rgba[3]);
};
}).apply(null, DefaultColors[colorName]);
Object.defineProperty(Color, colorName, { get: colorGetter });
})(DefaultColors[colorName]));
}
var proto = Color.prototype;
+28 -28
View File
@@ -215,13 +215,13 @@ proto.toString = function () {
* @property xMin
* @type {Number}
*/
Object.defineProperty(proto, 'xMin', {
get: function () { return this.x; },
set: function (value) {
JS.getset(proto, 'xMin',
function () { return this.x; },
function (value) {
this.width += this.x - value;
this.x = value;
}
});
);
/**
* !#en TODO
@@ -229,13 +229,13 @@ Object.defineProperty(proto, 'xMin', {
* @property yMin
* @type {Number}
*/
Object.defineProperty(proto, 'yMin', {
get: function () { return this.y; },
set: function (value) {
JS.getset(proto, 'yMin',
function () { return this.y; },
function (value) {
this.height += this.y - value;
this.y = value;
}
});
);
/**
* !#en TODO
@@ -243,10 +243,10 @@ Object.defineProperty(proto, 'yMin', {
* @property xMax
* @type {Number}
*/
Object.defineProperty(proto, 'xMax', {
get: function () { return this.x + this.width; },
set: function (value) { this.width = value - this.x; }
});
JS.getset(proto, 'xMax',
function () { return this.x + this.width; },
function (value) { this.width = value - this.x; }
);
/**
* !#en TODO
@@ -254,56 +254,56 @@ Object.defineProperty(proto, 'xMax', {
* @property yMax
* @type {Number}
*/
Object.defineProperty(proto, 'yMax', {
get: function () { return this.y + this.height; },
set: function (value) { this.height = value - this.y; }
});
JS.getset(proto, 'yMax',
function () { return this.y + this.height; },
function (value) { this.height = value - this.y; }
);
/**
* !#en The position of the center of the rectangle.
* !#zh 矩形的中心点。
* @property {Vec2} center
*/
Object.defineProperty(proto, 'center', {
get: function () {
JS.getset(proto, 'center',
function () {
return new cc.Vec2(this.x + this.width * 0.5,
this.y + this.height * 0.5);
},
set: function (value) {
function (value) {
this.x = value.x - this.width * 0.5;
this.y = value.y - this.height * 0.5;
}
});
);
/**
* !#en The X and Y position of the rectangle.
* !#zh 矩形的 x 和 y 坐标。
* @property {Vec2} origin
*/
Object.defineProperty(proto, 'origin', {
get () {
JS.getset(proto, 'origin',
function () {
return new cc.Vec2(this.x, this.y);
},
set (value) {
function (value) {
this.x = value.x;
this.y = value.y;
}
});
);
/**
* !#en Width and height of the rectangle.
* !#zh 矩形的大小。
* @property {Size} size
*/
Object.defineProperty(proto, 'size', {
get: function () {
JS.getset(proto, 'size',
function () {
return new cc.Size(this.width, this.height);
},
set: function (value) {
function (value) {
this.width = value.width;
this.height = value.height;
}
});
);
/**
* !#en TODO
+20 -18
View File
@@ -34,17 +34,19 @@ var JS = require('../platform/js');
function ValueType () {}
JS.setClassName('cc.ValueType', ValueType);
JS.mixin(ValueType.prototype, {
var proto = ValueType.prototype;
if (CC_EDITOR) {
/**
* !#en This method returns an exact copy of current value.
* !#zh 克隆当前值,该方法返回一个新对象,新对象的值和原对象相等。
* @method clone
* @return {ValueType}
*/
clone: CC_EDITOR && function () {
proto.clone = function () {
cc.errorID(5801, JS.getClassName(this));
return null;
},
};
/**
* !#en Compares this object with the other one.
@@ -53,20 +55,10 @@ JS.mixin(ValueType.prototype, {
* @param {ValueType} other
* @return {Boolean}
*/
equals: CC_EDITOR && function (other) {
proto.equals = function (other) {
cc.errorID(5802, JS.getClassName(this));
return false;
},
/**
* !#en TODO
* !#zh 转换为方便阅读的字符串。
* @method toString
* @return {string}
*/
toString: function () {
return '' + {};
},
};
/**
* !#en
@@ -80,11 +72,21 @@ JS.mixin(ValueType.prototype, {
* @param {number} ratio - the interpolation coefficient
* @return {ValueType}
*/
lerp: CC_EDITOR && function (to, ratio) {
proto.lerp = function (to, ratio) {
cc.warnID(5800, JS.getClassName(this));
return this.clone();
}
});
};
}
/**
* !#en TODO
* !#zh 转换为方便阅读的字符串。
* @method toString
* @return {string}
*/
proto.toString = function () {
return '' + {};
};
cc.ValueType = ValueType;
module.exports = ValueType;
+462 -462
View File
@@ -63,475 +63,475 @@ CCClass.fastDefine('cc.Vec2', Vec2, { x: 0, y: 0 });
* @property {Number} y
*/
JS.mixin(Vec2.prototype, {
var proto = Vec2.prototype;
/**
* !#en clone a Vec2 value
* !#zh 克隆一个 Vec2 值
* @method clone
* @return {Vec2}
*/
clone: function () {
return new Vec2(this.x, this.y);
},
/**
* !#en TODO
* !#zh 设置向量值。
* @method set
* @param {Vec2} newValue - !#en new value to set. !#zh 要设置的新值
* @return {Vec2} returns this
* @chainable
*/
set: function (newValue) {
this.x = newValue.x;
this.y = newValue.y;
/**
* !#en clone a Vec2 value
* !#zh 克隆一个 Vec2 值
* @method clone
* @return {Vec2}
*/
proto.clone = function () {
return new Vec2(this.x, this.y);
};
/**
* !#en TODO
* !#zh 设置向量值。
* @method set
* @param {Vec2} newValue - !#en new value to set. !#zh 要设置的新值
* @return {Vec2} returns this
* @chainable
*/
proto.set = function (newValue) {
this.x = newValue.x;
this.y = newValue.y;
return this;
};
/**
* !#en TODO
* !#zh 当前的向量是否与指定的向量相等。
* @method equals
* @param {Vec2} other
* @return {Boolean}
*/
proto.equals = function (other) {
return other && this.x === other.x && this.y === other.y;
};
/**
* !#en TODO
* !#zh 转换为方便阅读的字符串。
* @method toString
* @return {string}
*/
proto.toString = function () {
return "(" +
this.x.toFixed(2) + ", " +
this.y.toFixed(2) + ")"
;
};
/**
* !#en TODO
* !#zh 线性插值。
* @method lerp
* @param {Vec2} to
* @param {number} ratio - the interpolation coefficient
* @param {Vec2} [out] - optional, the receiving vector
* @return {Vec2}
*/
proto.lerp = function (to, ratio, out) {
out = out || new Vec2();
var x = this.x;
var y = this.y;
out.x = x + (to.x - x) * ratio;
out.y = y + (to.y - y) * ratio;
return out;
};
/**
* !#en Adds this vector. If you want to save result to another vector, use add() instead.
* !#zh 向量加法。如果你想保存结果到另一个向量,使用 add() 代替。
* @method addSelf
* @param {Vec2} vector
* @return {Vec2} returns this
* @chainable
* @example
* var v = cc.v2(10, 10);
* v.addSelf(cc.v2(5, 5));// return Vec2 {x: 15, y: 15};
*/
proto.addSelf = function (vector) {
this.x += vector.x;
this.y += vector.y;
return this;
};
/**
* !#en Adds two vectors, and returns the new result.
* !#zh 向量加法,并返回新结果。
* @method add
* @param {Vec2} vector
* @param {Vec2} [out] - optional, the receiving vector
* @return {Vec2} the result
* @example
* var v = cc.v2(10, 10);
* v.add(cc.v2(5, 5)); // return Vec2 {x: 15, y: 15};
* var v1;
* v.add(cc.v2(5, 5), v1); // return Vec2 {x: 15, y: 15};
*/
proto.add = function (vector, out) {
out = out || new Vec2();
out.x = this.x + vector.x;
out.y = this.y + vector.y;
return out;
};
/**
* !#en Subtracts one vector from this. If you want to save result to another vector, use sub() instead.
* !#zh 向量减法。如果你想保存结果到另一个向量,可使用 sub() 代替。
* @method subSelf
* @param {Vec2} vector
* @return {Vec2} returns this
* @chainable
* @example
* var v = cc.v2(10, 10);
* v.subSelf(cc.v2(5, 5));// return Vec2 {x: 5, y: 5};
*/
proto.subSelf = function (vector) {
this.x -= vector.x;
this.y -= vector.y;
return this;
};
/**
* !#en Subtracts one vector from this, and returns the new result.
* !#zh 向量减法,并返回新结果。
* @method sub
* @param {Vec2} vector
* @param {Vec2} [out] - optional, the receiving vector
* @return {Vec2} the result
* @example
* var v = cc.v2(10, 10);
* v.sub(cc.v2(5, 5)); // return Vec2 {x: 5, y: 5};
* var v1;
* v.sub(cc.v2(5, 5), v1); // return Vec2 {x: 5, y: 5};
*/
proto.sub = function (vector, out) {
out = out || new Vec2();
out.x = this.x - vector.x;
out.y = this.y - vector.y;
return out;
};
/**
* !#en Multiplies this by a number. If you want to save result to another vector, use mul() instead.
* !#zh 缩放当前向量。如果你想结果保存到另一个向量,可使用 mul() 代替。
* @method mulSelf
* @param {number} num
* @return {Vec2} returns this
* @chainable
* @example
* var v = cc.v2(10, 10);
* v.mulSelf(5);// return Vec2 {x: 50, y: 50};
*/
proto.mulSelf = function (num) {
this.x *= num;
this.y *= num;
return this;
};
/**
* !#en Multiplies by a number, and returns the new result.
* !#zh 缩放当前向量,并返回新结果。
* @method mul
* @param {number} num
* @param {Vec2} [out] - optional, the receiving vector
* @return {Vec2} the result
* @example
* var v = cc.v2(10, 10);
* v.mul(5); // return Vec2 {x: 50, y: 50};
* var v1;
* v.mul(5, v1); // return Vec2 {x: 50, y: 50};
*/
proto.mul = function (num, out) {
out = out || new Vec2();
out.x = this.x * num;
out.y = this.y * num;
return out;
};
/**
* !#en Multiplies two vectors.
* !#zh 分量相乘。
* @method scaleSelf
* @param {Vec2} vector
* @return {Vec2} returns this
* @chainable
* @example
* var v = cc.v2(10, 10);
* v.scaleSelf(cc.v2(5, 5));// return Vec2 {x: 50, y: 50};
*/
proto.scaleSelf = function (vector) {
this.x *= vector.x;
this.y *= vector.y;
return this;
};
/**
* !#en Multiplies two vectors, and returns the new result.
* !#zh 分量相乘,并返回新的结果。
* @method scale
* @param {Vec2} vector
* @param {Vec2} [out] - optional, the receiving vector
* @return {Vec2} the result
* @example
* var v = cc.v2(10, 10);
* v.scale(cc.v2(5, 5)); // return Vec2 {x: 50, y: 50};
* var v1;
* v.scale(cc.v2(5, 5), v1); // return Vec2 {x: 50, y: 50};
*/
proto.scale = function (vector, out) {
out = out || new Vec2();
out.x = this.x * vector.x;
out.y = this.y * vector.y;
return out;
};
/**
* !#en Divides by a number. If you want to save result to another vector, use div() instead.
* !#zh 向量除法。如果你想结果保存到另一个向量,可使用 div() 代替。
* @method divSelf
* @param {Vec2} vector
* @return {Vec2} returns this
* @chainable
* @example
* var v = cc.v2(10, 10);
* v.divSelf(5); // return Vec2 {x: 2, y: 2};
*/
proto.divSelf = function (num) {
this.x /= num;
this.y /= num;
return this;
};
/**
* !#en Divides by a number, and returns the new result.
* !#zh 向量除法,并返回新的结果。
* @method div
* @param {Vec2} vector
* @param {Vec2} [out] - optional, the receiving vector
* @return {Vec2} the result
* @example
* var v = cc.v2(10, 10);
* v.div(5); // return Vec2 {x: 2, y: 2};
* var v1;
* v.div(5, v1); // return Vec2 {x: 2, y: 2};
*/
proto.div = function (num, out) {
out = out || new Vec2();
out.x = this.x / num;
out.y = this.y / num;
return out;
};
/**
* !#en Negates the components. If you want to save result to another vector, use neg() instead.
* !#zh 向量取反。如果你想结果保存到另一个向量,可使用 neg() 代替。
* @method negSelf
* @return {Vec2} returns this
* @chainable
* @example
* var v = cc.v2(10, 10);
* v.negSelf(); // return Vec2 {x: -10, y: -10};
*/
proto.negSelf = function () {
this.x = -this.x;
this.y = -this.y;
return this;
};
/**
* !#en Negates the components, and returns the new result.
* !#zh 返回取反后的新向量。
* @method neg
* @param {Vec2} [out] - optional, the receiving vector
* @return {Vec2} the result
* @example
* var v = cc.v2(10, 10);
* var v1;
* v.neg(v1); // return Vec2 {x: -10, y: -10};
*/
proto.neg = function (out) {
out = out || new Vec2();
out.x = -this.x;
out.y = -this.y;
return out;
};
/**
* !#en Dot product
* !#zh 当前向量与指定向量进行点乘。
* @method dot
* @param {Vec2} [vector]
* @return {number} the result
* @example
* var v = cc.v2(10, 10);
* v.dot(cc.v2(5, 5)); // return 100;
*/
proto.dot = function (vector) {
return this.x * vector.x + this.y * vector.y;
};
/**
* !#en Cross product
* !#zh 当前向量与指定向量进行叉乘。
* @method cross
* @param {Vec2} [vector]
* @return {number} the result
* @example
* var v = cc.v2(10, 10);
* v.cross(cc.v2(5, 5)); // return 0;
*/
proto.cross = function (vector) {
return this.y * vector.x - this.x * vector.y;
};
/**
* !#en Returns the length of this vector.
* !#zh 返回该向量的长度。
* @method mag
* @return {number} the result
* @example
* var v = cc.v2(10, 10);
* v.mag(); // return 14.142135623730951;
*/
proto.mag = function () {
return Math.sqrt(this.x * this.x + this.y * this.y);
};
/**
* !#en Returns the squared length of this vector.
* !#zh 返回该向量的长度平方。
* @method magSqr
* @return {number} the result
* @example
* var v = cc.v2(10, 10);
* v.magSqr(); // return 200;
*/
proto.magSqr = function () {
return this.x * this.x + this.y * this.y;
};
/**
* !#en Make the length of this vector to 1.
* !#zh 向量归一化,让这个向量的长度为 1。
* @method normalizeSelf
* @return {Vec2} returns this
* @chainable
* @example
* var v = cc.v2(10, 10);
* v.normalizeSelf(); // return Vec2 {x: 0.7071067811865475, y: 0.7071067811865475};
*/
proto.normalizeSelf = function () {
var magSqr = this.x * this.x + this.y * this.y;
if (magSqr === 1.0)
return this;
},
/**
* !#en TODO
* !#zh 当前的向量是否与指定的向量相等。
* @method equals
* @param {Vec2} other
* @return {Boolean}
*/
equals: function (other) {
return other && this.x === other.x && this.y === other.y;
},
/**
* !#en TODO
* !#zh 转换为方便阅读的字符串。
* @method toString
* @return {string}
*/
toString: function () {
return "(" +
this.x.toFixed(2) + ", " +
this.y.toFixed(2) + ")"
;
},
/**
* !#en TODO
* !#zh 线性插值。
* @method lerp
* @param {Vec2} to
* @param {number} ratio - the interpolation coefficient
* @param {Vec2} [out] - optional, the receiving vector
* @return {Vec2}
*/
lerp: function (to, ratio, out) {
out = out || new Vec2();
var x = this.x;
var y = this.y;
out.x = x + (to.x - x) * ratio;
out.y = y + (to.y - y) * ratio;
return out;
},
/**
* !#en Adds this vector. If you want to save result to another vector, use add() instead.
* !#zh 向量加法。如果你想保存结果到另一个向量,使用 add() 代替。
* @method addSelf
* @param {Vec2} vector
* @return {Vec2} returns this
* @chainable
* @example
* var v = cc.v2(10, 10);
* v.addSelf(cc.v2(5, 5));// return Vec2 {x: 15, y: 15};
*/
addSelf: function (vector) {
this.x += vector.x;
this.y += vector.y;
return this;
},
/**
* !#en Adds two vectors, and returns the new result.
* !#zh 向量加法,并返回新结果。
* @method add
* @param {Vec2} vector
* @param {Vec2} [out] - optional, the receiving vector
* @return {Vec2} the result
* @example
* var v = cc.v2(10, 10);
* v.add(cc.v2(5, 5)); // return Vec2 {x: 15, y: 15};
* var v1;
* v.add(cc.v2(5, 5), v1); // return Vec2 {x: 15, y: 15};
*/
add: function (vector, out) {
out = out || new Vec2();
out.x = this.x + vector.x;
out.y = this.y + vector.y;
return out;
},
/**
* !#en Subtracts one vector from this. If you want to save result to another vector, use sub() instead.
* !#zh 向量减法。如果你想保存结果到另一个向量,可使用 sub() 代替。
* @method subSelf
* @param {Vec2} vector
* @return {Vec2} returns this
* @chainable
* @example
* var v = cc.v2(10, 10);
* v.subSelf(cc.v2(5, 5));// return Vec2 {x: 5, y: 5};
*/
subSelf: function (vector) {
this.x -= vector.x;
this.y -= vector.y;
return this;
},
/**
* !#en Subtracts one vector from this, and returns the new result.
* !#zh 向量减法,并返回新结果。
* @method sub
* @param {Vec2} vector
* @param {Vec2} [out] - optional, the receiving vector
* @return {Vec2} the result
* @example
* var v = cc.v2(10, 10);
* v.sub(cc.v2(5, 5)); // return Vec2 {x: 5, y: 5};
* var v1;
* v.sub(cc.v2(5, 5), v1); // return Vec2 {x: 5, y: 5};
*/
sub: function (vector, out) {
out = out || new Vec2();
out.x = this.x - vector.x;
out.y = this.y - vector.y;
return out;
},
/**
* !#en Multiplies this by a number. If you want to save result to another vector, use mul() instead.
* !#zh 缩放当前向量。如果你想结果保存到另一个向量,可使用 mul() 代替。
* @method mulSelf
* @param {number} num
* @return {Vec2} returns this
* @chainable
* @example
* var v = cc.v2(10, 10);
* v.mulSelf(5);// return Vec2 {x: 50, y: 50};
*/
mulSelf: function (num) {
this.x *= num;
this.y *= num;
return this;
},
/**
* !#en Multiplies by a number, and returns the new result.
* !#zh 缩放当前向量,并返回新结果。
* @method mul
* @param {number} num
* @param {Vec2} [out] - optional, the receiving vector
* @return {Vec2} the result
* @example
* var v = cc.v2(10, 10);
* v.mul(5); // return Vec2 {x: 50, y: 50};
* var v1;
* v.mul(5, v1); // return Vec2 {x: 50, y: 50};
*/
mul: function (num, out) {
out = out || new Vec2();
out.x = this.x * num;
out.y = this.y * num;
return out;
},
/**
* !#en Multiplies two vectors.
* !#zh 分量相乘。
* @method scaleSelf
* @param {Vec2} vector
* @return {Vec2} returns this
* @chainable
* @example
* var v = cc.v2(10, 10);
* v.scaleSelf(cc.v2(5, 5));// return Vec2 {x: 50, y: 50};
*/
scaleSelf: function (vector) {
this.x *= vector.x;
this.y *= vector.y;
return this;
},
/**
* !#en Multiplies two vectors, and returns the new result.
* !#zh 分量相乘,并返回新的结果。
* @method scale
* @param {Vec2} vector
* @param {Vec2} [out] - optional, the receiving vector
* @return {Vec2} the result
* @example
* var v = cc.v2(10, 10);
* v.scale(cc.v2(5, 5)); // return Vec2 {x: 50, y: 50};
* var v1;
* v.scale(cc.v2(5, 5), v1); // return Vec2 {x: 50, y: 50};
*/
scale: function (vector, out) {
out = out || new Vec2();
out.x = this.x * vector.x;
out.y = this.y * vector.y;
return out;
},
/**
* !#en Divides by a number. If you want to save result to another vector, use div() instead.
* !#zh 向量除法。如果你想结果保存到另一个向量,可使用 div() 代替。
* @method divSelf
* @param {Vec2} vector
* @return {Vec2} returns this
* @chainable
* @example
* var v = cc.v2(10, 10);
* v.divSelf(5); // return Vec2 {x: 2, y: 2};
*/
divSelf: function (num) {
this.x /= num;
this.y /= num;
return this;
},
/**
* !#en Divides by a number, and returns the new result.
* !#zh 向量除法,并返回新的结果。
* @method div
* @param {Vec2} vector
* @param {Vec2} [out] - optional, the receiving vector
* @return {Vec2} the result
* @example
* var v = cc.v2(10, 10);
* v.div(5); // return Vec2 {x: 2, y: 2};
* var v1;
* v.div(5, v1); // return Vec2 {x: 2, y: 2};
*/
div: function (num, out) {
out = out || new Vec2();
out.x = this.x / num;
out.y = this.y / num;
return out;
},
/**
* !#en Negates the components. If you want to save result to another vector, use neg() instead.
* !#zh 向量取反。如果你想结果保存到另一个向量,可使用 neg() 代替。
* @method negSelf
* @return {Vec2} returns this
* @chainable
* @example
* var v = cc.v2(10, 10);
* v.negSelf(); // return Vec2 {x: -10, y: -10};
*/
negSelf: function () {
this.x = -this.x;
this.y = -this.y;
return this;
},
/**
* !#en Negates the components, and returns the new result.
* !#zh 返回取反后的新向量。
* @method neg
* @param {Vec2} [out] - optional, the receiving vector
* @return {Vec2} the result
* @example
* var v = cc.v2(10, 10);
* var v1;
* v.neg(v1); // return Vec2 {x: -10, y: -10};
*/
neg: function (out) {
out = out || new Vec2();
out.x = -this.x;
out.y = -this.y;
return out;
},
/**
* !#en Dot product
* !#zh 当前向量与指定向量进行点乘。
* @method dot
* @param {Vec2} [vector]
* @return {number} the result
* @example
* var v = cc.v2(10, 10);
* v.dot(cc.v2(5, 5)); // return 100;
*/
dot: function (vector) {
return this.x * vector.x + this.y * vector.y;
},
/**
* !#en Cross product
* !#zh 当前向量与指定向量进行叉乘。
* @method cross
* @param {Vec2} [vector]
* @return {number} the result
* @example
* var v = cc.v2(10, 10);
* v.cross(cc.v2(5, 5)); // return 0;
*/
cross: function (vector) {
return this.y * vector.x - this.x * vector.y;
},
/**
* !#en Returns the length of this vector.
* !#zh 返回该向量的长度。
* @method mag
* @return {number} the result
* @example
* var v = cc.v2(10, 10);
* v.mag(); // return 14.142135623730951;
*/
mag: function () {
return Math.sqrt(this.x * this.x + this.y * this.y);
},
/**
* !#en Returns the squared length of this vector.
* !#zh 返回该向量的长度平方。
* @method magSqr
* @return {number} the result
* @example
* var v = cc.v2(10, 10);
* v.magSqr(); // return 200;
*/
magSqr: function () {
return this.x * this.x + this.y * this.y;
},
/**
* !#en Make the length of this vector to 1.
* !#zh 向量归一化,让这个向量的长度为 1。
* @method normalizeSelf
* @return {Vec2} returns this
* @chainable
* @example
* var v = cc.v2(10, 10);
* v.normalizeSelf(); // return Vec2 {x: 0.7071067811865475, y: 0.7071067811865475};
*/
normalizeSelf: function () {
var magSqr = this.x * this.x + this.y * this.y;
if (magSqr === 1.0)
return this;
if (magSqr === 0.0) {
console.warn("Can't normalize zero vector");
return this;
}
var invsqrt = 1.0 / Math.sqrt(magSqr);
this.x *= invsqrt;
this.y *= invsqrt;
return this;
},
/**
* !#en
* Returns this vector with a magnitude of 1.<br/>
* <br/>
* Note that the current vector is unchanged and a new normalized vector is returned. If you want to normalize the current vector, use normalizeSelf function.
* !#zh
* 返回归一化后的向量。<br/>
* <br/>
* 注意,当前向量不变,并返回一个新的归一化向量。如果你想来归一化当前向量,可使用 normalizeSelf 函数。
* @method normalize
* @param {Vec2} [out] - optional, the receiving vector
* @return {Vec2} result
* var v = cc.v2(10, 10);
* v.normalize(); // return Vec2 {x: 0.7071067811865475, y: 0.7071067811865475};
*/
normalize: function (out) {
out = out || new Vec2();
out.x = this.x;
out.y = this.y;
out.normalizeSelf();
return out;
},
/**
* !#en Get angle in radian between this and vector.
* !#zh 夹角的弧度。
* @method angle
* @param {Vec2} vector
* @return {number} from 0 to Math.PI
*/
angle: function (vector) {
var magSqr1 = this.magSqr();
var magSqr2 = vector.magSqr();
if (magSqr1 === 0 || magSqr2 === 0) {
console.warn("Can't get angle between zero vector");
return 0.0;
}
var dot = this.dot(vector);
var theta = dot / (Math.sqrt(magSqr1 * magSqr2));
theta = cc.clampf(theta, -1.0, 1.0);
return Math.acos(theta);
},
/**
* !#en Get angle in radian between this and vector with direction.
* !#zh 带方向的夹角的弧度。
* @method signAngle
* @param {Vec2} vector
* @return {number} from -MathPI to Math.PI
*/
signAngle: function (vector) {
// NOTE: this algorithm will return 0.0 without signed if vectors are parallex
// var angle = this.angle(vector);
// var cross = this.cross(vector);
// return Math.sign(cross) * angle;
return Math.atan2(this.y, this.x) - Math.atan2(vector.y, vector.x);
},
/**
* !#en rotate
* !#zh 返回旋转给定弧度后的新向量。
* @method rotate
* @param {number} radians
* @param {Vec2} [out] - optional, the receiving vector
* @return {Vec2} the result
*/
rotate: function (radians, out) {
out = out || new Vec2();
out.x = this.x;
out.y = this.y;
return out.rotateSelf(radians);
},
/**
* !#en rotate self
* !#zh 按指定弧度旋转向量。
* @method rotateSelf
* @param {number} radians
* @return {Vec2} returns this
* @chainable
*/
rotateSelf: function (radians) {
var sin = Math.sin(radians);
var cos = Math.cos(radians);
var x = this.x;
this.x = cos * x - sin * this.y;
this.y = sin * x + cos * this.y;
if (magSqr === 0.0) {
console.warn("Can't normalize zero vector");
return this;
}
//_serialize: function () {
// return [this.x, this.y];
//},
//_deserialize: function (data) {
// this.x = data[0];
// this.y = data[1];
//}
});
var invsqrt = 1.0 / Math.sqrt(magSqr);
this.x *= invsqrt;
this.y *= invsqrt;
return this;
};
/**
* !#en
* Returns this vector with a magnitude of 1.<br/>
* <br/>
* Note that the current vector is unchanged and a new normalized vector is returned. If you want to normalize the current vector, use normalizeSelf function.
* !#zh
* 返回归一化后的向量。<br/>
* <br/>
* 注意,当前向量不变,并返回一个新的归一化向量。如果你想来归一化当前向量,可使用 normalizeSelf 函数。
* @method normalize
* @param {Vec2} [out] - optional, the receiving vector
* @return {Vec2} result
* var v = cc.v2(10, 10);
* v.normalize(); // return Vec2 {x: 0.7071067811865475, y: 0.7071067811865475};
*/
proto.normalize = function (out) {
out = out || new Vec2();
out.x = this.x;
out.y = this.y;
out.normalizeSelf();
return out;
};
/**
* !#en Get angle in radian between this and vector.
* !#zh 夹角的弧度。
* @method angle
* @param {Vec2} vector
* @return {number} from 0 to Math.PI
*/
proto.angle = function (vector) {
var magSqr1 = this.magSqr();
var magSqr2 = vector.magSqr();
if (magSqr1 === 0 || magSqr2 === 0) {
console.warn("Can't get angle between zero vector");
return 0.0;
}
var dot = this.dot(vector);
var theta = dot / (Math.sqrt(magSqr1 * magSqr2));
theta = cc.clampf(theta, -1.0, 1.0);
return Math.acos(theta);
};
/**
* !#en Get angle in radian between this and vector with direction.
* !#zh 带方向的夹角的弧度。
* @method signAngle
* @param {Vec2} vector
* @return {number} from -MathPI to Math.PI
*/
proto.signAngle = function (vector) {
// NOTE: this algorithm will return 0.0 without signed if vectors are parallex
// var angle = this.angle(vector);
// var cross = this.cross(vector);
// return Math.sign(cross) * angle;
return Math.atan2(this.y, this.x) - Math.atan2(vector.y, vector.x);
};
/**
* !#en rotate
* !#zh 返回旋转给定弧度后的新向量。
* @method rotate
* @param {number} radians
* @param {Vec2} [out] - optional, the receiving vector
* @return {Vec2} the result
*/
proto.rotate = function (radians, out) {
out = out || new Vec2();
out.x = this.x;
out.y = this.y;
return out.rotateSelf(radians);
};
/**
* !#en rotate self
* !#zh 按指定弧度旋转向量。
* @method rotateSelf
* @param {number} radians
* @return {Vec2} returns this
* @chainable
*/
proto.rotateSelf = function (radians) {
var sin = Math.sin(radians);
var cos = Math.cos(radians);
var x = this.x;
this.x = cos * x - sin * this.y;
this.y = sin * x + cos * this.y;
return this;
};
//_serialize: function () {
// return [this.x, this.y];
//},
//_deserialize: function (data) {
// this.x = data[0];
// this.y = data[1];
//}
// static
File diff suppressed because it is too large Load Diff
@@ -30,98 +30,97 @@ cc.DrawNode.CanvasRenderCmd = function(renderableObject){
this._blendFunc = null;
};
cc.DrawNode.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype);
cc.DrawNode.CanvasRenderCmd.prototype.constructor = cc.DrawNode.CanvasRenderCmd;
cc.js.mixin( cc.DrawNode.CanvasRenderCmd.prototype, {
rendering: function (ctx, scaleX, scaleY) {
var wrapper = ctx || cc._renderContext, context = wrapper.getContext(), node = this._node;
var alpha = node._displayedOpacity / 255;
if (alpha === 0)
return;
var proto = cc.DrawNode.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype);
proto.constructor = cc.DrawNode.CanvasRenderCmd;
wrapper.setTransform(this._worldTransform, scaleX, scaleY);
proto.rendering = function (ctx, scaleX, scaleY) {
var wrapper = ctx || cc._renderContext, context = wrapper.getContext(), node = this._node;
var alpha = node._displayedOpacity / 255;
if (alpha === 0)
return;
//context.save();
wrapper.setGlobalAlpha(alpha);
if ((this._blendFunc && (this._blendFunc.src === cc.macro.SRC_ALPHA) && (this._blendFunc.dst === cc.macro.ONE)))
wrapper.setCompositeOperation('lighter'); //todo: need refactor
var locBuffer = this._buffer;
for (var i = 0, len = locBuffer.length; i < len; i++) {
var element = locBuffer[i];
switch (element.type) {
case cc.DrawNode.TYPE_DOT:
this._drawDot(wrapper, element, scaleX, scaleY);
break;
case cc.DrawNode.TYPE_SEGMENT:
this._drawSegment(wrapper, element, scaleX, scaleY);
break;
case cc.DrawNode.TYPE_POLY:
this._drawPoly(wrapper, element, scaleX, scaleY);
break;
}
wrapper.setTransform(this._worldTransform, scaleX, scaleY);
//context.save();
wrapper.setGlobalAlpha(alpha);
if ((this._blendFunc && (this._blendFunc.src === cc.macro.SRC_ALPHA) && (this._blendFunc.dst === cc.macro.ONE)))
wrapper.setCompositeOperation('lighter'); //todo: need refactor
var locBuffer = this._buffer;
for (var i = 0, len = locBuffer.length; i < len; i++) {
var element = locBuffer[i];
switch (element.type) {
case cc.DrawNode.TYPE_DOT:
this._drawDot(wrapper, element, scaleX, scaleY);
break;
case cc.DrawNode.TYPE_SEGMENT:
this._drawSegment(wrapper, element, scaleX, scaleY);
break;
case cc.DrawNode.TYPE_POLY:
this._drawPoly(wrapper, element, scaleX, scaleY);
break;
}
//context.restore(); //todo It can be reserve
},
_drawDot: function (wrapper, element, scaleX, scaleY) {
var locColor = element.fillColor, locPos = element.verts[0], locRadius = element.lineWidth;
var ctx = wrapper.getContext();
wrapper.setFillStyle("rgba(" + (0 | locColor.r) + "," + (0 | locColor.g) + "," + (0 | locColor.b) + "," + locColor.a / 255 + ")");
ctx.beginPath();
ctx.arc(locPos.x, -locPos.y, locRadius, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
},
_drawSegment: function (wrapper, element, scaleX, scaleY) {
var locColor = element.lineColor;
var locFrom = element.verts[0], locTo = element.verts[1];
var locLineWidth = element.lineWidth, locLineCap = element.lineCap;
var ctx = wrapper.getContext();
wrapper.setStrokeStyle("rgba(" + (0 | locColor.r) + "," + (0 | locColor.g) + "," + (0 | locColor.b) + "," + locColor.a / 255 + ")");
ctx.lineWidth = locLineWidth * scaleX;
ctx.beginPath();
ctx.lineCap = locLineCap;
ctx.moveTo(locFrom.x, -locFrom.y);
ctx.lineTo(locTo.x, -locTo.y);
ctx.stroke();
},
_drawPoly: function (wrapper, element, scaleX, scaleY) {
var locVertices = element.verts, locLineCap = element.lineCap;
if (locVertices == null)
return;
var locFillColor = element.fillColor, locLineWidth = element.lineWidth;
var locLineColor = element.lineColor, locIsClosePolygon = element.isClosePolygon;
var locIsFill = element.isFill, locIsStroke = element.isStroke;
var ctx = wrapper.getContext();
var firstPoint = locVertices[0];
ctx.lineCap = locLineCap;
if (locFillColor)
wrapper.setFillStyle("rgba(" + (0 | locFillColor.r) + "," + (0 | locFillColor.g) + ","
+ (0 | locFillColor.b) + "," + locFillColor.a / 255 + ")");
if (locLineWidth)
ctx.lineWidth = locLineWidth * scaleX;
if (locLineColor)
wrapper.setStrokeStyle("rgba(" + (0 | locLineColor.r) + "," + (0 | locLineColor.g) + ","
+ (0 | locLineColor.b) + "," + locLineColor.a / 255 + ")");
ctx.beginPath();
ctx.moveTo(firstPoint.x, -firstPoint.y);
for (var i = 1, len = locVertices.length; i < len; i++)
ctx.lineTo(locVertices[i].x, -locVertices[i].y);
if (locIsClosePolygon)
ctx.closePath();
if (locIsFill)
ctx.fill();
if (locIsStroke)
ctx.stroke();
}
});
//context.restore(); //todo It can be reserve
};
proto._drawDot = function (wrapper, element, scaleX, scaleY) {
var locColor = element.fillColor, locPos = element.verts[0], locRadius = element.lineWidth;
var ctx = wrapper.getContext();
wrapper.setFillStyle("rgba(" + (0 | locColor.r) + "," + (0 | locColor.g) + "," + (0 | locColor.b) + "," + locColor.a / 255 + ")");
ctx.beginPath();
ctx.arc(locPos.x, -locPos.y, locRadius, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
};
proto._drawSegment = function (wrapper, element, scaleX, scaleY) {
var locColor = element.lineColor;
var locFrom = element.verts[0], locTo = element.verts[1];
var locLineWidth = element.lineWidth, locLineCap = element.lineCap;
var ctx = wrapper.getContext();
wrapper.setStrokeStyle("rgba(" + (0 | locColor.r) + "," + (0 | locColor.g) + "," + (0 | locColor.b) + "," + locColor.a / 255 + ")");
ctx.lineWidth = locLineWidth * scaleX;
ctx.beginPath();
ctx.lineCap = locLineCap;
ctx.moveTo(locFrom.x, -locFrom.y);
ctx.lineTo(locTo.x, -locTo.y);
ctx.stroke();
};
proto._drawPoly = function (wrapper, element, scaleX, scaleY) {
var locVertices = element.verts, locLineCap = element.lineCap;
if (locVertices == null)
return;
var locFillColor = element.fillColor, locLineWidth = element.lineWidth;
var locLineColor = element.lineColor, locIsClosePolygon = element.isClosePolygon;
var locIsFill = element.isFill, locIsStroke = element.isStroke;
var ctx = wrapper.getContext();
var firstPoint = locVertices[0];
ctx.lineCap = locLineCap;
if (locFillColor)
wrapper.setFillStyle("rgba(" + (0 | locFillColor.r) + "," + (0 | locFillColor.g) + ","
+ (0 | locFillColor.b) + "," + locFillColor.a / 255 + ")");
if (locLineWidth)
ctx.lineWidth = locLineWidth * scaleX;
if (locLineColor)
wrapper.setStrokeStyle("rgba(" + (0 | locLineColor.r) + "," + (0 | locLineColor.g) + ","
+ (0 | locLineColor.b) + "," + locLineColor.a / 255 + ")");
ctx.beginPath();
ctx.moveTo(firstPoint.x, -firstPoint.y);
for (var i = 1, len = locVertices.length; i < len; i++)
ctx.lineTo(locVertices[i].x, -locVertices[i].y);
if (locIsClosePolygon)
ctx.closePath();
if (locIsFill)
ctx.fill();
if (locIsStroke)
ctx.stroke();
};
+48
View File
@@ -0,0 +1,48 @@
// Based on https://github.com/substack/browser-pack/blob/master/prelude.js
// modules are defined as an array
// [ module function, map of requireuires ]
//
// map of requireuires is short require name -> numeric require
//
// anything defined in a previous bundle is accessed via the
// orig method which is the requireuire for previous bundles
(function outer (modules, cache, entry) {
// Save the require from previous bundle to this closure if any
var previousRequire = typeof require == "function" && require;
function newRequire(name, jumped){
var module = cache[name];
if(!module) {
var moduleData = modules[name];
if(!moduleData) {
// if we cannot find the module within our internal map or
// cache jump to the current global require ie. the last bundle
// that was added to the page.
var currentRequire = typeof require == "function" && require;
if (!jumped && currentRequire) return currentRequire(name, true);
// If there are other bundles on this page the require from the
// previous one is saved to 'previousRequire'. Repeat this as
// many times as there are bundles until the module is found or
// we exhaust the require chain.
if (previousRequire) return previousRequire(name, true);
var err = new Error('Cannot find module \'' + name + '\'');
err.code = 'MODULE_NOT_FOUND';
throw err;
}
var exports = {};
module = cache[name] = {exports: exports};
moduleData[0](function(x){
return newRequire(moduleData[1][x] || x);
},module,exports);
}
return module.exports;
}
for(var i=0;i<entry.length;i++) newRequire(entry[i]);
// Override the current require with this new one
return newRequire;
})
+22 -2
View File
@@ -37,6 +37,7 @@ const Sourcemaps = require('gulp-sourcemaps');
const EventStream = require('event-stream');
const Chalk = require('chalk');
const HandleErrors = require('../util/handleErrors');
const Optimizejs = require('gulp-optimize-js');
exports.buildCocosJs = function (sourceFile, outputFile, excludes, callback) {
var outDir = Path.dirname(outputFile);
@@ -59,6 +60,9 @@ exports.buildCocosJs = function (sourceFile, outputFile, excludes, callback) {
bundler = bundler.pipe(Buffer());
bundler = bundler.pipe(Sourcemaps.init({loadMaps: true}));
bundler = bundler.pipe(Minifier(uglifyOption, UglifyHarmony));
bundler = bundler.pipe(Optimizejs({
sourceMap: false
}));
bundler = bundler.pipe(Sourcemaps.write('./', {
sourceRoot: './',
includeContent: true,
@@ -99,9 +103,15 @@ exports.buildCocosJsMin = function (sourceFile, outputFile, excludes, callback,
bundler = bundler.bundle();
bundler = bundler.pipe(Source(outFile));
bundler = bundler.pipe(Buffer());
if (createMap !== false)
if (createMap) {
console.error('Can not use sourcemap with optimize-js');
bundler = bundler.pipe(Sourcemaps.init({loadMaps: true}));
}
bundler = bundler.pipe(Minifier(uglifyOption, UglifyHarmony));
bundler = bundler.pipe(Optimizejs({
sourceMap: false
}));
if (Size) {
bundler = bundler.pipe(rawSize);
bundler = bundler.pipe(zippedSize);
@@ -113,12 +123,13 @@ exports.buildCocosJsMin = function (sourceFile, outputFile, excludes, callback,
this.emit('end');
}));
}
if (createMap !== false)
if (createMap) {
bundler = bundler.pipe(Sourcemaps.write('./', {
sourceRoot: './',
includeContent: true,
addComment: true
}));
}
bundler = bundler.pipe(Gulp.dest(outDir));
return bundler.on('end', callback);
};
@@ -140,6 +151,9 @@ exports.buildPreview = function (sourceFile, outputFile, callback) {
CC_TEST: false,
CC_JSB: false
}), UglifyHarmony))
.pipe(Optimizejs({
sourceMap: false
}))
.pipe(Sourcemaps.write('./', {
sourceRoot: '../',
includeContent: false,
@@ -168,6 +182,9 @@ exports.buildJsb = function (sourceFile, outputFile, jsbSkipModules, callback) {
CC_TEST: false,
CC_JSB: true
}), UglifyHarmony))
.pipe(Optimizejs({
sourceMap: false
}))
.pipe(Gulp.dest(outDir))
.on('end', callback);
};
@@ -191,6 +208,9 @@ exports.buildJsbMin = function (sourceFile, outputFile, jsbSkipModules, callback
CC_TEST: false,
CC_JSB: true
}), UglifyHarmony))
.pipe(Optimizejs({
sourceMap: false
}))
.pipe(Gulp.dest(outDir))
.on('end', callback);
};
+16 -1
View File
@@ -3,6 +3,10 @@
const Path = require('path');
allowReturnOutsideFunctionInBrowserifyTransform();
const Browserify = require('browserify');
const Fs = require('fs');
const preludePath = Path.resolve(__dirname, '../browserify_prelude.js');
const prelude = Fs.readFileSync(preludePath, 'utf8');
exports.uglifyOptions = function (minify, global_defs) {
if (minify) {
@@ -66,7 +70,14 @@ function allowReturnOutsideFunctionInBrowserifyTransform () {
if (typeof parse === 'function') {
if (acorn.parse.name !== 'monkeyPatchedParse') {
acorn.parse = function monkeyPatchedParse(input, options) {
options.allowReturnOutsideFunction = true;
if (options) {
options.allowReturnOutsideFunction = true;
}
else {
options = {
allowReturnOutsideFunction: true
};
}
return parse(input, options);
};
}
@@ -98,6 +109,10 @@ exports.createBundler = function createBundler(entryFiles, babelifyOpt) {
bundleExternal: false, // dont bundle external modules
//standalone: 'engine-framework',
//basedir: tempScriptDir
// define custom prelude to optimize script evaluate time
prelude: prelude,
preludePath: Path.relative(process.cwd(), preludePath),
};
// var presets = [
+4 -3
View File
@@ -26,27 +26,28 @@
"event-stream": "3.3.2",
"fire-fs": "0.2.1",
"gulp": "^3.9.0",
"gulp-babel": "6.1.2",
"gulp-cached": "1.1.0",
"gulp-concat": "2.6.0",
"gulp-babel": "6.1.2",
"gulp-fb": "0.5.1",
"gulp-header": "1.2.2",
"gulp-jshint": "1.11.2",
"gulp-mirror": "0.4.0",
"gulp-optimize-js": "^1.1.0",
"gulp-plumber": "0.6.6",
"gulp-rename": "1.2.2",
"gulp-shell": "0.4.1",
"gulp-size": "2.1.0",
"gulp-sourcemaps": "1.5.2",
"gulp-uglify": "1.5.3",
"uglify-js-harmony": "2.7.5",
"gulp-util": "3.0.6",
"jshint-stylish": "2.1.0",
"multipipe": "0.3.0",
"require-dir": "0.3.0",
"uglify-js-harmony": "2.7.5",
"vinyl": "1.1.0",
"vinyl-buffer": "1.0.0",
"vinyl-source-stream": "1.0.0",
"watchify": "^3.7.0"
}
}
}