Merge pull request #2329 from pandamicro/next

Review Director, remove kazmath & shaders
This commit is contained in:
pandamicro
2018-02-09 11:03:36 +08:00
committed by GitHub
43 changed files with 130 additions and 7289 deletions
+1
View File
@@ -54,6 +54,7 @@ if (CC_DEBUG) {
"1213": "loadScene: Failed to load scene '%s' because '%s' is already loading", //loadScene
"1214": "loadScene: Can not load the scene '%s' because it was not in the build settings before playing.", //loadScene
"1215": "Failed to preload '%s', %s", //preloadScene
"1216": "Director.runSceneImmediate: scene is not valid",
//Array: 1300
"1300": "element type is wrong!", //verifyType
//deprecated: 1400
+116 -415
View File
@@ -33,8 +33,6 @@ const EventListeners = require('./event/event-listeners');
const renderer = require('./renderer');
const eventManager = require('./event-manager');
cc.g_NumberOfDraws = 0;
//----------------------------------------------------------------------------------------------------------------------
/**
@@ -110,30 +108,17 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
var self = this;
EventTarget.call(self);
self._landscape = false;
self._nextDeltaTimeZero = false;
// paused?
self._paused = false;
// purge?
self._purgeDirectorInNextLoop = false;
self._sendCleanupToScene = false;
self._animationInterval = 0.0;
self._oldAnimationInterval = 0.0;
self._projection = 0;
// projection delegate if "Custom" projection is used
self._projectionDelegate = null;
self._contentScaleFactor = 1.0;
self._winSizeInPoints = null;
self._openGLView = null;
// scenes
self._scenesStack = null;
self._nextScene = null;
self._loadingScene = '';
self._runningScene = null; // The root of rendering scene graph
// The entity-component scene
self._scene = null;
// FPS
@@ -141,8 +126,6 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
self._lastUpdate = Date.now();
self._deltaTime = 0.0;
self._dirtyRegion = null;
// Scheduler for user registration update
self._scheduler = null;
// Scheduler for life-cycle methods in component
@@ -159,18 +142,12 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
init: function () {
this._oldAnimationInterval = this._animationInterval = 1.0 / cc.defaultFPS;
this._scenesStack = [];
// Set default projection (3D)
this._projection = cc.Director.PROJECTION_DEFAULT;
this._projectionDelegate = null;
this._totalFrames = 0;
this._lastUpdate = Date.now();
this._paused = false;
this._purgeDirectorInNextLoop = false;
this._winSizeInPoints = cc.size(0, 0);
this._openGLView = null;
this._contentScaleFactor = 1.0;
this._scheduler = new cc.Scheduler();
if (cc.ActionManager) {
@@ -238,19 +215,14 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
calculateDeltaTime: function () {
var now = Date.now();
if (this._nextDeltaTimeZero) {
this._deltaTime = 0;
this._nextDeltaTimeZero = false;
} else {
this._deltaTime = (now - this._lastUpdate) / 1000;
if ((cc.game.config[cc.game.CONFIG_KEY.debugMode] > 0) && (this._deltaTime > 1))
this._deltaTime = 1 / 60.0;
}
this._deltaTime = (now - this._lastUpdate) / 1000;
if ((cc.game.config[cc.game.CONFIG_KEY.debugMode] > 0) && (this._deltaTime > 1))
this._deltaTime = 1 / 60.0;
this._lastUpdate = now;
},
/*
/**
* !#en
* Converts a view coordinate to an WebGL coordinate<br/>
* Useful to convert (multi) touches coordinates to the current layout (portrait or landscape)<br/>
@@ -259,6 +231,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
* @method convertToGL
* @param {Vec2} uiPoint
* @return {Vec2}
* @deprecated
*/
convertToGL: function (uiPoint) {
var container = cc.game.container;
@@ -280,6 +253,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
* @method convertToUI
* @param {Vec2} glPoint
* @return {Vec2}
* @deprecated
*/
convertToUI: function (glPoint) {
var container = cc.game.container;
@@ -299,43 +273,14 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
return uiPoint;
},
_visitScene: function () {
if (this._runningScene) {
var renderer = cc.rendererWebGL;
if (renderer.childrenOrderDirty) {
// update the whole scene
renderer.clearRenderCommands();
cc.rendererWebGL.assignedZ = 0;
this._runningScene._renderCmd._curLevel = 0; //level start from 0;
this._runningScene.visit();
renderer.resetFlag();
}
else if (renderer.transformDirty()) {
// only need to update transformPool
renderer.transform();
}
}
},
/**
* End the life of director in the next frame
* @method end
*/
end: function () {
this._purgeDirectorInNextLoop = true;
},
/*
* !#en
* Returns the size in pixels of the surface. It could be different than the screen size.<br/>
* High-res devices might have a higher surface size than the screen size.
* !#zh 获取内容缩放比例。
* @method getContentScaleFactor
* @return {Number}
*/
getContentScaleFactor: function () {
return this._contentScaleFactor;
},
/**
* !#en
* Returns the size of the WebGL view in points.<br/>
@@ -362,19 +307,16 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
* @deprecated
*/
getWinSizeInPixels: function () {
return cc.size(this._winSizeInPoints.width * this._contentScaleFactor, this._winSizeInPoints.height * this._contentScaleFactor);
return cc.size(this._winSizeInPoints.width, this._winSizeInPoints.height);
},
/**
* getVisibleSize/getVisibleOrigin move to CCDirectorWebGL/CCDirectorCanvas
* getZEye move to CCDirectorWebGL
*/
/**
* !#en Returns the visible size of the running scene.
* !#zh 获取运行场景的可见大小。
* @method getVisibleSize
* @see cc.visibleRect
* @return {Size}
* @deprecated
*/
getVisibleSize: null,
@@ -382,18 +324,12 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
* !#en Returns the visible origin of the running scene.
* !#zh 获取视图在游戏内容中的坐标原点。
* @method getVisibleOrigin
* @see cc.visibleRect
* @return {Vec2}
* @deprecated
*/
getVisibleOrigin: null,
/*
* !#en Returns the z eye, only available in WebGL mode.
* !#zh 获取 Z eye,只有在WebGL的模式下可用。
* @method getZEye
* @return {Number}
*/
getZEye: null,
/**
* !#en Pause the director's ticker, only involve the game logic execution.
* It won't pause the rendering process nor the event manager.
@@ -413,28 +349,55 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
this._paused = true;
},
/*
* !#en
* Suspends the execution of the running scene, pushing it on the stack of suspended scenes.<br/>
* The new scene will be executed.<br/>
* Try to avoid big stacks of pushed scenes to reduce memory allocation.<br/>
* ONLY call it if there is a running scene.
* !#zh
* 暂停当前运行的场景,压入到暂停的场景栈中。<br/>
* 新场景将被执行。 <br/>
* 尽量避免压入大场景,以减少内存分配。 <br/>
* 只能在有运行场景时调用它。
* @method pushScene
* @param {Scene} scene
* @deprecated
*/
pushScene: function (scene) {
},
/*
* Pops out a scene from the queue.<br/>
* This scene will replace the running one.<br/>
* The running scene will be deleted. If there are no more scenes in the stack the execution is terminated.<br/>
* ONLY call it if there is a running scene.
* @deprecated
*/
popScene: function () {
cc.assertID(this._runningScene, 1204);
this._scenesStack.pop();
var c = this._scenesStack.length;
if (c === 0)
this.end();
else {
this._sendCleanupToScene = true;
this._nextScene = this._scenesStack[c - 1];
}
},
/**
* Pops out all scenes from the queue until the root scene in the queue. <br/>
* This scene will replace the running one. <br/>
* Internally it will call "popToSceneStackLevel(1)".
* @deprecated
*/
popToRootScene: function () {},
/**
* Pops out all scenes from the queue until it reaches "level". <br/>
* If level is 0, it will end the director. <br/>
* If level is 1, it will pop all scenes until it reaches to root scene. <br/>
* If level is <= than the current stack level, it won't do anything.
* @param {Number} level
* @deprecated
*/
popToSceneStackLevel: function (level) {},
/**
* Removes cached all cocos2d cached data.
* @deprecated
*/
purgeCachedData: function () {
cc.loader.releaseAll();
@@ -454,21 +417,9 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
if (eventManager)
eventManager.setEnabled(false);
// don't release the event handlers
// They are needed in case the director is run again
cc.renderer.clear();
if (this._runningScene) {
// this._runningScene.performRecursive(_ccsg.Node.performType.onExitTransitionDidStart);
// this._runningScene.performRecursive(_ccsg.Node.performType.onExit);
// this._runningScene.performRecursive(_ccsg.Node.performType.cleanup);
}
this._runningScene = null;
this._nextScene = null;
// remove all objects, but don't release it.
// runScene might be executed after 'end'.
this._scenesStack.length = 0;
this._scene = null;
this.stopAnimation();
@@ -511,30 +462,6 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
this.startAnimation();
},
/*
* !#en
* Suspends the execution of the running scene, pushing it on the stack of suspended scenes.<br/>
* The new scene will be executed.<br/>
* Try to avoid big stacks of pushed scenes to reduce memory allocation.<br/>
* ONLY call it if there is a running scene.
* !#zh
* 暂停当前运行的场景,压入到暂停的场景栈中。<br/>
* 新场景将被执行。 <br/>
* 尽量避免压入大场景,以减少内存分配。 <br/>
* 只能在有运行场景时调用它。
* @method pushScene
* @param {Scene} scene
*/
pushScene: function (scene) {
cc.assertID(scene, 1205);
this._sendCleanupToScene = false;
this._scenesStack.push(scene);
this._nextScene = scene;
},
/**
* !#en
* Run a scene. Replaces the running scene with a new one or enter the first scene.<br/>
@@ -546,11 +473,11 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
* @param {Function} [onLaunched] - The function invoked at the scene after launch.
*/
runSceneImmediate: function (scene, onBeforeLoadScene, onLaunched) {
if (scene instanceof cc.Scene) {
CC_BUILD && CC_DEBUG && console.time('InitScene');
scene._load(); // ensure scene initialized
CC_BUILD && CC_DEBUG && console.timeEnd('InitScene');
}
cc.assertID(scene instanceof cc.Scene, 1216);
CC_BUILD && CC_DEBUG && console.time('InitScene');
scene._load(); // ensure scene initialized
CC_BUILD && CC_DEBUG && console.timeEnd('InitScene');
// detach persist nodes
var game = cc.game;
@@ -592,52 +519,34 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
this.emit(cc.Director.EVENT_BEFORE_SCENE_LAUNCH, scene);
// Run an Entity Scene
if (scene instanceof cc.Scene) {
this._scene = scene;
this._scene = scene;
// Re-attach or replace persist nodes
CC_BUILD && CC_DEBUG && console.time('AttachPersist');
for (let i = 0; i < persistNodeList.length; i++) {
let node = persistNodeList[i];
var existNode = scene.getChildByUuid(node.uuid);
if (existNode) {
// scene also contains the persist node, select the old one
var index = existNode.getSiblingIndex();
existNode._destroyImmediate();
scene.insertChild(node, index);
}
else {
node.parent = scene;
}
// Re-attach or replace persist nodes
CC_BUILD && CC_DEBUG && console.time('AttachPersist');
for (let i = 0; i < persistNodeList.length; i++) {
let node = persistNodeList[i];
var existNode = scene.getChildByUuid(node.uuid);
if (existNode) {
// scene also contains the persist node, select the old one
var index = existNode.getSiblingIndex();
existNode._destroyImmediate();
scene.insertChild(node, index);
}
else {
node.parent = scene;
}
CC_BUILD && CC_DEBUG && console.timeEnd('AttachPersist');
CC_BUILD && CC_DEBUG && console.time('Activate');
scene._activate();
CC_BUILD && CC_DEBUG && console.timeEnd('Activate');
}
CC_BUILD && CC_DEBUG && console.timeEnd('AttachPersist');
CC_BUILD && CC_DEBUG && console.time('Activate');
scene._activate();
CC_BUILD && CC_DEBUG && console.timeEnd('Activate');
// Run or replace rendering scene
if ( !this._runningScene ) {
//start scene
this.pushScene(scene);
this.startAnimation();
}
else {
//replace scene
var i = this._scenesStack.length;
this._scenesStack[Math.max(i - 1, 0)] = scene;
this._sendCleanupToScene = true;
this._nextScene = scene;
}
if (this._nextScene) {
this.setNextScene();
}
//start scene
this.startAnimation();
if (onLaunched) {
onLaunched(null, scene);
}
//cc.renderer.clear();
this.emit(cc.Director.EVENT_AFTER_SCENE_LAUNCH, scene);
},
@@ -654,10 +563,10 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
*/
runScene: function (scene, onBeforeLoadScene, onLaunched) {
cc.assertID(scene, 1205);
if (scene instanceof cc.Scene) {
// ensure scene initialized
scene._load();
}
cc.assertID(scene instanceof cc.Scene, 1216);
// ensure scene initialized
scene._load();
// Delay run / replace scene to the end of the frame
this.once(cc.Director.EVENT_AFTER_UPDATE, function () {
@@ -864,17 +773,6 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
this._deltaTime = 0;
},
/**
* The size in pixels of the surface. It could be different than the screen size.<br/>
* High-res devices might have a higher surface size than the screen size.
* @param {Number} scaleFactor
*/
setContentScaleFactor: function (scaleFactor) {
if (scaleFactor !== this._contentScaleFactor) {
this._contentScaleFactor = scaleFactor;
}
},
/**
* !#en
* Enables or disables WebGL depth test.<br/>
@@ -884,7 +782,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
* @param {Boolean} on
* @deprecated
*/
setDepthTest: null,
setDepthTest: function () {},
/**
* !#en
@@ -905,79 +803,6 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
clearColor.a / 255
);
},
/**
* Sets the default values based on the CCConfiguration info
*/
setDefaultValues: function () {
},
/**
* Sets whether next delta time equals to zero
* @param {Boolean} nextDeltaTimeZero
*/
setNextDeltaTimeZero: function (nextDeltaTimeZero) {
this._nextDeltaTimeZero = nextDeltaTimeZero;
},
/**
* Starts the registered next scene
*/
setNextScene: function () {
// var runningIsTransition = false, newIsTransition = false;
// if (cc.TransitionScene) {
// runningIsTransition = this._runningScene ? this._runningScene instanceof cc.TransitionScene : false;
// newIsTransition = this._nextScene ? this._nextScene instanceof cc.TransitionScene : false;
// }
// // If it is not a transition, call onExit/cleanup
// if (!newIsTransition) {
// var locRunningScene = this._runningScene;
// if (locRunningScene) {
// locRunningScene.performRecursive(_ccsg.Node.performType.onExitTransitionDidStart);
// locRunningScene.performRecursive(_ccsg.Node.performType.onExit);
// }
// // issue #709. the root node (scene) should receive the cleanup message too
// // otherwise it might be leaked.
// if (this._sendCleanupToScene && locRunningScene)
// locRunningScene.performRecursive(_ccsg.Node.performType.cleanup);
// }
this._runningScene = this._nextScene;
this._nextScene = null;
// if ((!runningIsTransition) && (this._runningScene !== null)) {
// this._runningScene.performRecursive(_ccsg.Node.performType.onEnter);
// this._runningScene.performRecursive(_ccsg.Node.performType.onEnterTransitionDidFinish);
// }
},
/**
* Returns the cc.director delegate.
* @return {cc.DirectorDelegate}
*/
getDelegate: function () {
return this._projectionDelegate;
},
/**
* Sets the cc.director delegate. It shall implement the CCDirectorDelegate protocol
* @return {cc.DirectorDelegate}
*/
setDelegate: function (delegate) {
this._projectionDelegate = delegate;
},
/*
* !#en
* Sets the view, where everything is rendered, do not call this function.<br/>
* Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js.
* !#zh 设置 GLView。
* @method setOpenGLView
* @param {View} openGLView
*/
setOpenGLView: null,
/**
* !#en
@@ -985,65 +810,20 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
* Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js.
* !#zh 设置 OpenGL 投影。
* @method setProjection
* @param {Number} projection
* @param {Number}
* @deprecated
*/
setProjection: null,
setProjection: function () {},
/**
* !#en
* Update the view port.<br/>
* Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js.
* !#zh 设置视窗(请不要主动调用这个接口,除非你知道你在做什么)。
* @method setViewport
*/
setViewport: null,
/*
* !#en
* Get the View, where everything is rendered.<br/>
* Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js.
* !#zh
* 获取 GLView。
* @method getOpenGLView
* @return {View}
*/
getOpenGLView: null,
/**
* !#en
* Sets an OpenGL projection.<br/>
* Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js.
* Gets an OpenGL projection.
* !#zh 获取 OpenGL 投影。
* @method getProjection
* @return {Number}
* @deprecated
*/
getProjection: null,
/**
* !#en
* Enables/disables OpenGL alpha blending.<br/>
* Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js.
* !#zh 启用/禁用 透明度融合。
* @method setAlphaBlending
* @param {Boolean} on
*/
setAlphaBlending: null,
/**
* !#en
* Returns whether or not the replaced scene will receive the cleanup message.<br/>
* If the new scene is pushed, then the old scene won't receive the "cleanup" message.<br/>
* If the new scene replaces the old one, the it will receive the "cleanup" message.
* !#zh
* 更换场景时是否接收清理消息。<br>
* 如果新场景是采用 push 方式进入的,那么旧的场景将不会接收到 “cleanup” 消息。<br/>
* 如果新场景取代旧的场景,它将会接收到 “cleanup” 消息。</br>
* @method isSendCleanupToScene
* @return {Boolean}
*/
isSendCleanupToScene: function () {
return this._sendCleanupToScene;
},
getProjection: function () {},
/**
* !#en
@@ -1053,9 +833,10 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
* @method getRunningScene
* @private
* @return {Scene}
* @deprecated
*/
getRunningScene: function () {
return this._runningScene;
return null;
},
/**
@@ -1081,6 +862,26 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
return this._animationInterval;
},
/**
* !#en Returns the delta time since last frame.
* !#zh 获取上一帧的 “delta time”。
* @method getDeltaTime
* @return {Number}
*/
getDeltaTime: function () {
return this._deltaTime;
},
/**
* !#en Returns how many frames were called since the director started.
* !#zh 获取 director 启动以来游戏运行的总帧数。
* @method getTotalFrames
* @return {Number}
*/
getTotalFrames: function () {
return this._totalFrames;
},
/**
* !#en Returns whether or not to display the FPS informations.
* !#zh 获取是否显示 FPS 信息。
@@ -1104,16 +905,6 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
}
},
/**
* !#en Returns whether next delta time equals to zero.
* !#zh 返回下一个 “delta time” 是否等于零。
* @method isNextDeltaTimeZero
* @return {Boolean}
*/
isNextDeltaTimeZero: function () {
return this._nextDeltaTimeZero;
},
/**
* !#en Returns whether or not the Director is paused.
* !#zh 是否处于暂停状态。
@@ -1124,60 +915,6 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
return this._paused;
},
/**
* !#en Returns how many frames were called since the director started.
* !#zh 获取 director 启动以来游戏运行的总帧数。
* @method getTotalFrames
* @return {Number}
*/
getTotalFrames: function () {
return this._totalFrames;
},
/**
* Pops out all scenes from the queue until the root scene in the queue. <br/>
* This scene will replace the running one. <br/>
* Internally it will call "popToSceneStackLevel(1)".
*/
popToRootScene: function () {
this.popToSceneStackLevel(1);
},
/**
* Pops out all scenes from the queue until it reaches "level". <br/>
* If level is 0, it will end the director. <br/>
* If level is 1, it will pop all scenes until it reaches to root scene. <br/>
* If level is <= than the current stack level, it won't do anything.
* @param {Number} level
*/
popToSceneStackLevel: function (level) {
cc.assertID(this._runningScene, 1203);
var locScenesStack = this._scenesStack;
var c = locScenesStack.length;
if (c === 0) {
this.end();
return;
}
// current level or lower -> nothing
if (level > c)
return;
// pop stack until reaching desired level
while (c > level) {
var current = locScenesStack.pop();
// if (current.running) {
// current.performRecursive(_ccsg.Node.performType.onExitTransitionDidStart);
// current.performRecursive(_ccsg.Node.performType.onExit);
// }
// current.performRecursive(_ccsg.Node.performType.cleanup);
c--;
}
this._nextScene = locScenesStack[locScenesStack.length - 1];
this._sendCleanupToScene = true;
},
/**
* !#en Returns the cc.Scheduler associated with this director.
* !#zh 获取和 director 相关联的 cc.Scheduler。
@@ -1252,37 +989,18 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
getPhysicsManager: function () {
return this._physicsManager;
},
/**
* !#en Returns the delta time since last frame.
* !#zh 获取上一帧的 “delta time”。
* @method getDeltaTime
* @return {Number}
*/
getDeltaTime: function () {
return this._deltaTime;
},
});
// Event target
cc.js.addon(cc.Director.prototype, EventTarget.prototype);
/**
* !#en The event projection changed of cc.Director.
* !#zh cc.Director 投影变化的事件。
* @event cc.Director.EVENT_PROJECTION_CHANGED
* @param {Event.EventCustom} event
* @example
* cc.director.on(cc.Director.EVENT_PROJECTION_CHANGED, function(event) {
* cc.log("Projection changed.");
* });
*/
/**
* !#en The event projection changed of cc.Director.
* !#zh cc.Director 投影变化的事件。
* @property {String} EVENT_PROJECTION_CHANGED
* @readonly
* @static
* @deprecated
*/
cc.Director.EVENT_PROJECTION_CHANGED = "director_projection_changed";
@@ -1426,8 +1144,8 @@ cc.DisplayLinkDirector = cc.Director.extend(/** @lends cc.Director# */{
* Starts Animation
*/
startAnimation: function () {
this._nextDeltaTimeZero = true;
this.invalid = false;
this._lastUpdate = Date.now();
},
/**
@@ -1451,13 +1169,9 @@ cc.DisplayLinkDirector = cc.Director.extend(/** @lends cc.Director# */{
this.emit(cc.Director.EVENT_BEFORE_VISIT);
// update the scene
// this._visitScene();
this.emit(cc.Director.EVENT_AFTER_VISIT);
// Render
cc.g_NumberOfDraws = 0;
// cc.rendererWebGL.clear();
// cc.rendererWebGL.rendering(cc._renderContext);
renderer.render(this._scene);
this._totalFrames++;
@@ -1487,22 +1201,11 @@ cc.DisplayLinkDirector = cc.Director.extend(/** @lends cc.Director# */{
// Destroy entities that have been removed recently
cc.Object._deferredDestroy();
}
/* to avoid flickr, nextScene MUST be here: after tick and before draw.
XXX: Which bug is this one. It seems that it can't be reproduced with v0.9 */
if (this._nextScene) {
this.setNextScene();
}
this.emit(cc.Director.EVENT_BEFORE_VISIT);
// update the scene
// this._visitScene();
this.emit(cc.Director.EVENT_AFTER_VISIT);
// Render
cc.g_NumberOfDraws = 0;
// cc.rendererWebGL.clear();
// cc.rendererWebGL.rendering(cc._renderContext);
renderer.render(this._scene);
this._totalFrames++;
@@ -1561,12 +1264,6 @@ cc.Director._getInstance = function () {
return cc.Director.sharedDirector;
};
/**
* Default fps is 60
* @type {Number}
*/
cc.defaultFPS = 60;
//Possible OpenGL projections used by director
/**
@@ -1575,6 +1272,7 @@ cc.defaultFPS = 60;
* @default 0
* @readonly
* @static
* @deprecated
*/
cc.Director.PROJECTION_2D = 0;
@@ -1584,6 +1282,7 @@ cc.Director.PROJECTION_2D = 0;
* @default 1
* @readonly
* @static
* @deprecated
*/
cc.Director.PROJECTION_3D = 1;
@@ -1593,6 +1292,7 @@ cc.Director.PROJECTION_3D = 1;
* @default 3
* @readonly
* @static
* @deprecated
*/
cc.Director.PROJECTION_CUSTOM = 3;
@@ -1602,5 +1302,6 @@ cc.Director.PROJECTION_CUSTOM = 3;
* @default cc.Director.PROJECTION_2D
* @readonly
* @static
* @deprecated
*/
cc.Director.PROJECTION_DEFAULT = cc.Director.PROJECTION_2D;
+1 -2
View File
@@ -387,8 +387,7 @@ var game = {
* @type {Director}
*/
cc.director = cc.Director._getInstance();
if (cc.director.setOpenGLView)
cc.director.setOpenGLView(cc.view);
/**
* !#en cc.winSize is the alias object for the size of the current game window.
* !#zh cc.winSize 为当前的游戏窗口的大小。
-239
View File
@@ -1368,233 +1368,6 @@ cc.macro = {
DENSITYDPI_MEDIUM: 'medium-dpi',
DENSITYDPI_LOW: 'low-dpi',
// ------------------- vertex attrib flags -----------------------------
/**
* @property VERTEX_ATTRIB_FLAG_NONE
* @type {Number}
*/
VERTEX_ATTRIB_FLAG_NONE: 0,
/**
* @property VERTEX_ATTRIB_FLAG_POSITION
* @type {Number}
*/
VERTEX_ATTRIB_FLAG_POSITION: 1 << 0,
/**
* @property VERTEX_ATTRIB_FLAG_COLOR
* @type {Number}
*/
VERTEX_ATTRIB_FLAG_COLOR: 1 << 1,
/**
* @property VERTEX_ATTRIB_FLAG_TEX_COORDS
* @type {Number}
*/
VERTEX_ATTRIB_FLAG_TEX_COORDS: 1 << 2,
/**
* @property VERTEX_ATTRIB_FLAG_POS_COLOR_TEX
* @type {Number}
*/
VERTEX_ATTRIB_FLAG_POS_COLOR_TEX: ( (1 << 0) | (1 << 1) | (1 << 2) ),
/**
* GL server side states
* @property GL_ALL
* @type {Number}
*/
GL_ALL: 0,
//-------------Vertex Attributes-----------
/**
* @property VERTEX_ATTRIB_POSITION
* @type {Number}
*/
VERTEX_ATTRIB_POSITION: 0,
/**
* @property VERTEX_ATTRIB_COLOR
* @type {Number}
*/
VERTEX_ATTRIB_COLOR: 1,
/**
* @property VERTEX_ATTRIB_TEX_COORDS
* @type {Number}
*/
VERTEX_ATTRIB_TEX_COORDS: 2,
/**
* @property VERTEX_ATTRIB_MAX
* @type {Number}
*/
VERTEX_ATTRIB_MAX: 3,
//------------Uniforms------------------
/**
* @property UNIFORM_PMATRIX
* @type {Number}
*/
UNIFORM_PMATRIX: 0,
/**
* @property UNIFORM_MVMATRIX
* @type {Number}
*/
UNIFORM_MVMATRIX: 1,
/**
* @property UNIFORM_MVPMATRIX
* @type {Number}
*/
UNIFORM_MVPMATRIX: 2,
/**
* @property UNIFORM_TIME
* @type {Number}
*/
UNIFORM_TIME: 3,
/**
* @property UNIFORM_SINTIME
* @type {Number}
*/
UNIFORM_SINTIME: 4,
/**
* @property UNIFORM_COSTIME
* @type {Number}
*/
UNIFORM_COSTIME: 5,
/**
* @property UNIFORM_RANDOM01
* @type {Number}
*/
UNIFORM_RANDOM01: 6,
/**
* @property UNIFORM_SAMPLER
* @type {Number}
*/
UNIFORM_SAMPLER: 7,
/**
* @property UNIFORM_MAX
* @type {Number}
*/
UNIFORM_MAX: 8,
//------------Shader Name---------------
/**
* @property SHADER_POSITION_TEXTURECOLOR
* @type {String}
*/
SHADER_POSITION_TEXTURECOLOR: "ShaderPositionTextureColor",
/**
* @property SHADER_SPRITE_POSITION_TEXTURECOLOR
* @type {String}
*/
SHADER_SPRITE_POSITION_TEXTURECOLOR: "ShaderSpritePositionTextureColor",
/**
* @property SHADER_POSITION_TEXTURECOLORALPHATEST
* @type {String}
*/
SHADER_POSITION_TEXTURECOLORALPHATEST: "ShaderPositionTextureColorAlphaTest",
/**
* @property SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST
* @type {String}
*/
SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST: "ShaderSpritePositionTextureColorAlphaTest",
/**
* @property SHADER_POSITION_COLOR
* @type {String}
*/
SHADER_POSITION_COLOR: "ShaderPositionColor",
/**
* @property SHADER_SPRITE_POSITION_COLOR
* @type {String}
*/
SHADER_SPRITE_POSITION_COLOR: "ShaderSpritePositionColor",
/**
* @property SHADER_POSITION_TEXTURE
* @type {String}
*/
SHADER_POSITION_TEXTURE: "ShaderPositionTexture",
/**
* @property SHADER_POSITION_TEXTURE_UCOLOR
* @type {String}
*/
SHADER_POSITION_TEXTURE_UCOLOR: "ShaderPositionTexture_uColor",
/**
* @property SHADER_POSITION_TEXTUREA8COLOR
* @type {String}
*/
SHADER_POSITION_TEXTUREA8COLOR: "ShaderPositionTextureA8Color",
/**
* @property SHADER_POSITION_UCOLOR
* @type {String}
*/
SHADER_POSITION_UCOLOR: "ShaderPosition_uColor",
/**
* @property SHADER_POSITION_LENGTHTEXTURECOLOR
* @type {String}
*/
SHADER_POSITION_LENGTHTEXTURECOLOR: "ShaderPositionLengthTextureColor",
//------------uniform names----------------
/**
* @property UNIFORM_PMATRIX_S
* @type {String}
*/
UNIFORM_PMATRIX_S: "CC_PMatrix",
/**
* @property UNIFORM_MVMATRIX_S
* @type {String}
*/
UNIFORM_MVMATRIX_S: "CC_MVMatrix",
/**
* @property UNIFORM_MVPMATRIX_S
* @type {String}
*/
UNIFORM_MVPMATRIX_S: "CC_MVPMatrix",
/**
* @property UNIFORM_TIME_S
* @type {String}
*/
UNIFORM_TIME_S: "CC_Time",
/**
* @property UNIFORM_SINTIME_S
* @type {String}
*/
UNIFORM_SINTIME_S: "CC_SinTime",
/**
* @property UNIFORM_COSTIME_S
* @type {String}
*/
UNIFORM_COSTIME_S: "CC_CosTime",
/**
* @property UNIFORM_RANDOM01_S
* @type {String}
*/
UNIFORM_RANDOM01_S: "CC_Random01",
/**
* @property UNIFORM_SAMPLER_S
* @type {String}
*/
UNIFORM_SAMPLER_S: "CC_Texture0",
/**
* @property UNIFORM_ALPHA_TEST_VALUE_S
* @type {String}
*/
UNIFORM_ALPHA_TEST_VALUE_S: "CC_alpha_value",
//------------Attribute names--------------
/**
* @property ATTRIBUTE_NAME_COLOR
* @type {String}
*/
ATTRIBUTE_NAME_COLOR: "a_color",
/**
* @property ATTRIBUTE_NAME_POSITION
* @type {String}
*/
ATTRIBUTE_NAME_POSITION: "a_position",
/**
* @property ATTRIBUTE_NAME_TEX_COORD
* @type {String}
*/
ATTRIBUTE_NAME_TEX_COORD: "a_texCoord",
/**
* default size for font size
* @property ITEM_SIZE
@@ -2016,18 +1789,6 @@ cc.nodeDrawSetup = function (node) {
*/
// };
/**
* <p>
* Increments the GL Draws counts by one.<br/>
* The number of calls per frame are displayed on the screen when the CCDirector's stats are enabled.<br/>
* </p>
* @param {Number} addNumber
* @method incrementGLDraws
*/
cc.incrementGLDraws = function (addNumber) {
cc.g_NumberOfDraws += addNumber;
};
/**
* Check webgl error.Error will be shown in console if exists.
* @method checkGLErrorDebug
-509
View File
@@ -1,509 +0,0 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The software or tools in this License Agreement are licensed, not sold.
Chukong Aipu reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// Internal variables
// Batching general informations
var _batchedInfo = {
// The batched texture, all batching element should have the same texture
texture: null,
// The batched blend source, all batching element should have the same blend source
blendSrc: null,
// The batched blend destination, all batching element should have the same blend destination
blendDst: null,
// The batched shader, all batching element should have the same shader
shader: null
},
_batchBroken = false,
_indexBuffer = null,
_vertexBuffer = null,
// Total vertex size
_maxVertexSize = 0,
// Current batching vertex size
_batchingSize = 0,
// Current batching index size
_indexSize = 0,
// Float size per vertex
_sizePerVertex = 6,
// buffer data and views
_vertexData = null,
_vertexDataSize = 0,
_vertexDataF32 = null,
_vertexDataUI32 = null,
_indexData = null,
_prevIndexSize = 0,
_pureQuad = true,
_IS_IOS = false;
// Inspired from @Heishe's gotta-batch-them-all branch
// https://github.com/Talisca/cocos2d-html5/commit/de731f16414eb9bcaa20480006897ca6576d362c
function updateBuffer (numVertex) {
var gl = cc._renderContext;
// Update index buffer size
if (_indexBuffer) {
var indexCount = Math.ceil(numVertex / 4) * 6;
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _indexBuffer);
_indexData = new Uint16Array(indexCount);
var currentQuad = 0;
for (var i = 0, len = indexCount; i < len; i += 6) {
_indexData[i] = currentQuad + 0;
_indexData[i + 1] = currentQuad + 1;
_indexData[i + 2] = currentQuad + 2;
_indexData[i + 3] = currentQuad + 1;
_indexData[i + 4] = currentQuad + 2;
_indexData[i + 5] = currentQuad + 3;
currentQuad += 4;
}
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, _indexData, gl.DYNAMIC_DRAW);
}
// Update vertex buffer size
if (_vertexBuffer) {
_vertexDataSize = numVertex * _sizePerVertex;
var byteLength = _vertexDataSize * 4;
_vertexData = new ArrayBuffer(byteLength);
_vertexDataF32 = new Float32Array(_vertexData);
_vertexDataUI32 = new Uint32Array(_vertexData);
// Init buffer data
gl.bindBuffer(gl.ARRAY_BUFFER, _vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, _vertexDataF32, gl.DYNAMIC_DRAW);
}
// Downsize by 200 to avoid vertex data overflow
_maxVertexSize = numVertex - 200;
}
// Inspired from @Heishe's gotta-batch-them-all branch
// https://github.com/Talisca/cocos2d-html5/commit/de731f16414eb9bcaa20480006897ca6576d362c
function initQuadBuffer (numVertex) {
var gl = cc._renderContext;
if (_indexBuffer === null) {
// TODO do user need to release the memory ?
_vertexBuffer = gl.createBuffer();
_indexBuffer = gl.createBuffer();
}
updateBuffer(numVertex);
}
var VertexType = cc.Enum({
QUAD : 0,
TRIANGLE : 1,
CUSTOM: 2
});
cc.rendererWebGL = {
mat4Identity: null,
childrenOrderDirty: true,
assignedZ: 0,
assignedZStep: 1/100,
VertexType: VertexType,
_transformNodePool: [], //save nodes transform dirty
_renderCmds: [], //save renderer commands
_isCacheToBufferOn: false, //a switch that whether cache the rendererCmd to cacheToCanvasCmds
_cacheToBufferCmds: {}, // an array saves the renderer commands need for cache to other canvas
_cacheInstanceIds: [],
_currentID: 0,
_clearColor: {r: 0, g: 0, b: 0, a: 1}, //background color,default BLACK
init: function () {
var gl = cc._renderContext;
gl.disable(gl.CULL_FACE);
gl.disable(gl.DEPTH_TEST);
this._initExtensions([
'OES_element_index_uint'
]);
this.mat4Identity = new cc.math.Matrix4();
this.mat4Identity.identity();
initQuadBuffer(cc.macro.BATCH_VERTEX_COUNT);
if (cc.sys.os === cc.sys.OS_IOS) {
_IS_IOS = true;
}
},
_initExtensions: function (extensions) {
this._extensions = this._extensions || {};
for (var i = 0; i < extensions.length; ++i) {
var name = extensions[i];
try {
var ext = gl.getExtension(name);
if (ext) {
this._extensions[name] = ext;
}
} catch (e) {
cc.error(e);
}
}
},
getVertexSize: function () {
return _maxVertexSize;
},
getRenderCmd: function (renderableObject) {
//TODO Add renderCmd pool here
return renderableObject._createRenderCmd();
},
_turnToCacheMode: function (renderTextureID) {
this._isCacheToBufferOn = true;
renderTextureID = renderTextureID || 0;
if (!this._cacheToBufferCmds[renderTextureID]) {
this._cacheToBufferCmds[renderTextureID] = [];
}
else {
this._cacheToBufferCmds[renderTextureID].length = 0;
}
if (this._cacheInstanceIds.indexOf(renderTextureID) === -1) {
this._cacheInstanceIds.push(renderTextureID);
}
this._currentID = renderTextureID;
},
_turnToNormalMode: function () {
this._isCacheToBufferOn = false;
},
_removeCache: function (instanceID) {
instanceID = instanceID || this._currentID;
var cmds = this._cacheToBufferCmds[instanceID];
if (cmds) {
cmds.length = 0;
delete this._cacheToBufferCmds[instanceID];
}
var locIDs = this._cacheInstanceIds;
cc.js.array.remove(locIDs, instanceID);
},
/**
* drawing all renderer command to cache canvas' context
* @param {Number} [renderTextureId]
*/
_renderingToBuffer: function (renderTextureId) {
renderTextureId = renderTextureId || this._currentID;
var locCmds = this._cacheToBufferCmds[renderTextureId];
var ctx = cc._renderContext;
this.rendering(ctx, locCmds);
this._removeCache(renderTextureId);
var locIDs = this._cacheInstanceIds;
if (locIDs.length === 0)
this._isCacheToBufferOn = false;
else
this._currentID = locIDs[locIDs.length - 1];
},
//reset renderer's flag
resetFlag: function () {
if (this.childrenOrderDirty) {
this.childrenOrderDirty = false;
}
this._transformNodePool.length = 0;
},
//update the transform data
transform: function () {
var locPool = this._transformNodePool;
//sort the pool
locPool.sort(this._sortNodeByLevelAsc);
//transform node
var i, len, cmd;
for (i = 0, len = locPool.length; i < len; i++) {
cmd = locPool[i];
cmd.updateStatus();
}
locPool.length = 0;
},
transformDirty: function () {
return this._transformNodePool.length > 0;
},
_sortNodeByLevelAsc: function (n1, n2) {
return n1._curLevel - n2._curLevel;
},
pushDirtyNode: function (node) {
//if (this._transformNodePool.indexOf(node) === -1)
this._transformNodePool.push(node);
},
clearRenderCommands: function () {
// Copy previous command list for late check in rendering
this._renderCmds.length = 0;
},
clear: function () {
var gl = cc._renderContext;
gl.clearColor(this._clearColor.r, this._clearColor.g, this._clearColor.b, this._clearColor.a);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
},
setDepthTest: function (enable){
var gl = cc._renderContext;
if(enable){
gl.clearDepth(1.0);
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
}
else{
gl.disable(gl.DEPTH_TEST);
}
},
pushRenderCommand: function (cmd) {
if(!cmd.rendering && !cmd.uploadData)
return;
if (this._isCacheToBufferOn) {
var currentId = this._currentID, locCmdBuffer = this._cacheToBufferCmds;
var cmdList = locCmdBuffer[currentId];
if (cmdList.indexOf(cmd) === -1)
cmdList.push(cmd);
} else {
this._renderCmds.push(cmd);
}
},
_increaseBatchingSize: function (increment, vertexType, indices) {
vertexType = vertexType || VertexType.QUAD;
var i, curr;
switch (vertexType) {
case VertexType.QUAD:
for (i = 0; i < increment; i += 4) {
curr = _batchingSize + i;
_indexData[_indexSize++] = curr + 0;
_indexData[_indexSize++] = curr + 1;
_indexData[_indexSize++] = curr + 2;
_indexData[_indexSize++] = curr + 1;
_indexData[_indexSize++] = curr + 2;
_indexData[_indexSize++] = curr + 3;
}
break;
case VertexType.TRIANGLE:
_pureQuad = false;
for (i = 0; i < increment; i += 3) {
curr = _batchingSize + i;
_indexData[_indexSize++] = curr + 0;
_indexData[_indexSize++] = curr + 1;
_indexData[_indexSize++] = curr + 2;
}
break;
case VertexType.CUSTOM:
// CUSTOM type increase the indices data
_pureQuad = false;
var len = indices.length;
for (i = 0; i < len; i++) {
_indexData[_indexSize++] = _batchingSize + indices[i];
}
break;
default:
return;
}
_batchingSize += increment;
},
_updateBatchedInfo: function (texture, blendFunc, shaderProgram) {
if (texture !== _batchedInfo.texture ||
blendFunc.src !== _batchedInfo.blendSrc ||
blendFunc.dst !== _batchedInfo.blendDst ||
shaderProgram !== _batchedInfo.shader) {
// Draw batched elements
this._batchRendering();
// Update _batchedInfo
_batchedInfo.texture = texture;
_batchedInfo.blendSrc = blendFunc.src;
_batchedInfo.blendDst = blendFunc.dst;
_batchedInfo.shader = shaderProgram;
return true;
}
else {
return false;
}
},
_breakBatch: function () {
_batchBroken = true;
},
_uploadBufferData: function (cmd) {
if (_batchingSize >= _maxVertexSize) {
this._batchRendering();
}
// Check batching
var node = cmd._node;
var texture = cmd._texture || node._texture || (node._spriteFrame && node._spriteFrame._texture);
var blendSrc = node._blendFunc.src;
var blendDst = node._blendFunc.dst;
var shader = cmd._shaderProgram;
if (_batchBroken ||
_batchedInfo.texture !== texture ||
_batchedInfo.blendSrc !== blendSrc ||
_batchedInfo.blendDst !== blendDst ||
_batchedInfo.shader !== shader) {
// Draw batched elements
this._batchRendering();
// Update _batchedInfo
_batchedInfo.texture = texture;
_batchedInfo.blendSrc = blendSrc;
_batchedInfo.blendDst = blendDst;
_batchedInfo.shader = shader;
_batchBroken = false;
}
// Upload vertex data
var len = cmd.uploadData(_vertexDataF32, _vertexDataUI32, _batchingSize * _sizePerVertex);
if (len > 0) {
var i, curr, type = cmd.vertexType || VertexType.QUAD;
switch (type) {
case VertexType.QUAD:
for (i = 0; i < len; i += 4) {
curr = _batchingSize + i;
_indexData[_indexSize++] = curr + 0;
_indexData[_indexSize++] = curr + 1;
_indexData[_indexSize++] = curr + 2;
_indexData[_indexSize++] = curr + 1;
_indexData[_indexSize++] = curr + 2;
_indexData[_indexSize++] = curr + 3;
}
break;
case VertexType.TRIANGLE:
_pureQuad = false;
for (i = 0; i < len; i += 3) {
curr = _batchingSize + i;
_indexData[_indexSize++] = curr + 0;
_indexData[_indexSize++] = curr + 1;
_indexData[_indexSize++] = curr + 2;
}
break;
case VertexType.CUSTOM:
_pureQuad = false;
if (cmd.uploadIndexData) {
_indexSize += cmd.uploadIndexData(_indexData, _indexSize, _batchingSize);
}
break;
default:
return;
}
_batchingSize += len;
}
},
_batchRendering: function () {
if (_batchingSize === 0 || !_batchedInfo.texture) {
return;
}
var gl = cc._renderContext;
var texture = _batchedInfo.texture;
var shader = _batchedInfo.shader;
var uploadAll = _batchingSize > _maxVertexSize * 0.5;
if (shader) {
shader.use();
shader._updateProjectionUniform();
}
cc.gl.blendFunc(_batchedInfo.blendSrc, _batchedInfo.blendDst);
cc.gl.bindTexture2DN(0, texture); // = cc.gl.bindTexture2D(texture);
gl.bindBuffer(gl.ARRAY_BUFFER, _vertexBuffer);
// upload the vertex data to the gl buffer
if (uploadAll) {
gl.bufferData(gl.ARRAY_BUFFER, _vertexDataF32, gl.DYNAMIC_DRAW);
}
else {
var view = _vertexDataF32.subarray(0, _batchingSize * _sizePerVertex);
gl.bufferData(gl.ARRAY_BUFFER, view, gl.DYNAMIC_DRAW);
}
gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_POSITION);
gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_COLOR);
gl.enableVertexAttribArray(cc.macro.VERTEX_ATTRIB_TEX_COORDS);
gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_POSITION, 3, gl.FLOAT, false, 24, 0);
gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_COLOR, 4, gl.UNSIGNED_BYTE, true, 24, 12);
gl.vertexAttribPointer(cc.macro.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 24, 16);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, _indexBuffer);
if (!_prevIndexSize || !_pureQuad || _indexSize > _prevIndexSize) {
if (uploadAll) {
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, _indexData, gl.DYNAMIC_DRAW);
}
else {
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, _indexData.subarray(0, _indexSize), gl.DYNAMIC_DRAW);
}
}
gl.drawElements(gl.TRIANGLES, _indexSize, gl.UNSIGNED_SHORT, 0);
cc.g_NumberOfDraws++;
if (_pureQuad) {
_prevIndexSize = _indexSize;
}
else {
_prevIndexSize = 0;
_pureQuad = true;
}
_batchingSize = 0;
_indexSize = 0;
},
/**
* drawing all renderer command to context (default is cc._renderContext)
* @param {WebGLRenderingContext} [ctx=cc._renderContext]
*/
rendering: function (ctx, cmds) {
var locCmds = cmds || this._renderCmds,
i, len, cmd,
context = ctx || cc._renderContext;
// Reset buffer and texture for rendering
context.bindBuffer(context.ARRAY_BUFFER, null);
cc.gl.bindTexture2DN(0, null);
for (i = 0, len = locCmds.length; i < len; ++i) {
cmd = locCmds[i];
if (!cmd._needDraw) continue;
if (cmd.uploadData) {
this._uploadBufferData(cmd);
}
else {
if (_batchingSize > 0) {
this._batchRendering();
}
cmd.rendering(context);
}
}
this._batchRendering();
_batchedInfo.texture = null;
}
};
@@ -119,8 +119,8 @@ let tmxAssembler = js.addon({
let maptw = comp._mapTileSize.width,
mapth = comp._mapTileSize.height,
tilew = comp._tileset._tileSize.width / cc.director._contentScaleFactor,
tileh = comp._tileset._tileSize.height / cc.director._contentScaleFactor,
tilew = comp._tileset._tileSize.width,
tileh = comp._tileset._tileSize.height,
extw = tilew - maptw,
exth = tileh - mapth,
winw = cc.winSize.width,
+8
View File
@@ -65,6 +65,7 @@ module.exports = {
device: null,
scene: null,
materialUtil: null,
drawCalls: 0,
_walker: null,
_cameraNode: null,
_camera: null,
@@ -120,11 +121,18 @@ module.exports = {
},
render (ecScene) {
this.drawCalls = 0;
if (ecScene) {
// walk entity component scene to generate models
this._walker.visit(ecScene);
this.drawCalls = this.scene.getModelCount();
// Render models in renderer scene
this._forward.render(this.scene);
}
},
clear () {
this._walker.reset();
this._forward._reset();
}
};
+2 -1
View File
@@ -25,6 +25,7 @@
var PStats = require('../../../external/pstats/pstats');
var macro = require('../platform/CCMacro');
var renderer = require('../renderer');
var _fps = document.createElement('div');
_fps.id = 'fps';
@@ -50,7 +51,7 @@ function afterVisit () {
function afterDraw () {
stats('render').end();
stats('draws').value = cc.g_NumberOfDraws;
stats('draws').value = renderer.drawCalls;
stats('frame').end();
stats('fps').frame();
stats().tick();
-76
View File
@@ -1,76 +0,0 @@
/**
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
Copyright (c) 2008, Luke Benstead.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var _useSIMD = false;
var mat4Proto = cc.math.Matrix4.prototype;
var mat4Inverse = mat4Proto.inverse;
var mat4IsIdentity = mat4Proto.isIdentity;
var mat4Transpose = mat4Proto.transpose;
var mat4Multiply = mat4Proto.multiply;
var mat4GetMat4MultiplyValue = mat4Proto.getMat4MultiplyValue;
var mat4AssignFrom = mat4Proto.assignFrom;
var mat4Equals = mat4Proto.equals;
var mat4LookAt = mat4Proto.lookAt;
var vec3Proto = cc.math.Vec3.prototype;
var vec3TransformCoord = vec3Proto.transformCoord;
function _isEnabledSIMD () {
return _useSIMD;
}
function _enableSIMD (enable) {
if(typeof(SIMD) === 'undefined')
return;
if (enable) {
mat4Proto.inverse = mat4Proto.inverseSIMD;
mat4Proto.isIdentity = mat4Proto.isIdentitySIMD;
mat4Proto.transpose = mat4Proto.transposeSIMD;
mat4Proto.multiply = mat4Proto.multiplySIMD;
mat4Proto.getMat4MultiplyValue = mat4Proto.getMat4MultiplyValueSIMD;
mat4Proto.assignFrom = mat4Proto.assignFromSIMD;
mat4Proto.equals = mat4Proto.equalsSIMD;
mat4Proto.lookAt = mat4Proto.lookAtSIMD;
vec3Proto.transformCoord = vec3Proto.transformCoordSIMD;
} else {
mat4Proto.inverse = mat4Inverse;
mat4Proto.isIdentity = mat4IsIdentity;
mat4Proto.transpose = mat4Transpose;
mat4Proto.multiply = mat4Multiply;
mat4Proto.getMat4MultiplyValue = mat4GetMat4MultiplyValue;
mat4Proto.assignFrom = mat4AssignFrom;
mat4Proto.equals = mat4Equals;
mat4Proto.lookAt = mat4LookAt;
vec3Proto.transformCoord = vec3TransformCoord;
}
_useSIMD = enable;
}
cc.defineGetterSetter(cc.sys, "useSIMD", _isEnabledSIMD, _enableSIMD);
-78
View File
@@ -1,78 +0,0 @@
/**
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
Copyright (c) 2008, Luke Benstead.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* A structure that represents an axis-aligned bounding box.
* cc.kmAABB => cc.math.AABB
*/
cc.math.AABB = function (min, max) {
/** The max corner of the box */
this.min = min || new cc.math.Vec3();
/** The min corner of the box */
this.max = max || new cc.math.Vec3();
};
/**
* Returns true if point is in the specified AABB, returns false otherwise.
* @param {cc.math.Vec3} point
* @returns {boolean}
*/
cc.math.AABB.prototype.containsPoint = function (point) {
return (point.x >= this.min.x && point.x <= this.max.x &&
point.y >= this.min.y && point.y <= this.max.y &&
point.z >= this.min.z && point.z <= this.max.z);
};
/**
* Returns true if point is in the specified AABB, returns
* false otherwise.
*/
cc.math.AABB.containsPoint = function (pPoint, pBox) {
return (pPoint.x >= pBox.min.x && pPoint.x <= pBox.max.x &&
pPoint.y >= pBox.min.y && pPoint.y <= pBox.max.y &&
pPoint.z >= pBox.min.z && pPoint.z <= pBox.max.z);
};
/**
* Assigns aabb to current AABB object
* @param {cc.math.AABB} aabb
*/
cc.math.AABB.prototype.assignFrom = function(aabb){
this.min.assignFrom(aabb.min);
this.max.assignFrom(aabb.max);
};
/**
* Assigns pIn to pOut, returns pOut.
*/
cc.math.AABB.assign = function (pOut, pIn) { //cc.kmAABBAssign
pOut.min.assignFrom(pIn.min);
pOut.max.assignFrom(pIn.max);
return pOut;
};
-83
View File
@@ -1,83 +0,0 @@
/**
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
Copyright (c) 2008, Luke Benstead.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* The stack of cc.math.Matrix4
* @param {cc.math.Matrix4} [top]
* @param {Array} [stack]
*
*/
cc.math.Matrix4Stack = function(top, stack) {
this.top = top;
this.stack = stack || [];
this.lastUpdated = 0;
//this._matrixPool = []; // use pool in next version
};
var proto = cc.math.Matrix4Stack.prototype;
proto.initialize = function() { //cc.km_mat4_stack_initialize
this.stack.length = 0;
this.top = null;
};
proto.push = function(item) {
item = item || this.top;
this.stack.push(this.top);
this.top = new cc.math.Matrix4(item);
//this.top = this._getFromPool(item);
this.update();
};
proto.pop = function() {
//this._putInPool(this.top);
this.top = this.stack.pop();
this.update();
};
proto.update = function () {
this.lastUpdated ++;
};
proto.release = function(){
this.stack = null;
this.top = null;
this._matrixPool = null;
};
proto._getFromPool = function (item) {
var pool = this._matrixPool;
if (pool.length === 0)
return new cc.math.Matrix4(item);
var ret = pool.pop();
ret.assignFrom(item);
return ret;
};
proto._putInPool = function(matrix){
this._matrixPool.push(matrix);
};
-175
View File
@@ -1,175 +0,0 @@
/**
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
Copyright (c) 2008, Luke Benstead.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var math = cc.math;
math.KM_GL_MODELVIEW = 0x1700;
math.KM_GL_PROJECTION = 0x1701;
math.KM_GL_TEXTURE = 0x1702;
math.modelview_matrix_stack = new math.Matrix4Stack();
math.projection_matrix_stack = new math.Matrix4Stack();
math.texture_matrix_stack = new math.Matrix4Stack();
cc.current_stack = null;
var initialized = false;
var lazyInitialize = function () {
if (!initialized) {
var identity = new math.Matrix4(); //Temporary identity matrix
//Initialize all 3 stacks
math.modelview_matrix_stack.initialize();
math.projection_matrix_stack.initialize();
math.texture_matrix_stack.initialize();
cc.current_stack = math.modelview_matrix_stack;
initialized = true;
identity.identity();
//Make sure that each stack has the identity matrix
math.modelview_matrix_stack.push(identity);
math.projection_matrix_stack.push(identity);
math.texture_matrix_stack.push(identity);
}
};
lazyInitialize();
math.glFreeAll = function () {
//Clear the matrix stacks
math.modelview_matrix_stack.release();
math.modelview_matrix_stack = null;
math.projection_matrix_stack.release();
math.projection_matrix_stack = null;
math.texture_matrix_stack.release();
math.texture_matrix_stack = null;
//Delete the matrices
initialized = false; //Set to uninitialized
cc.current_stack = null; //Set the current stack to point nowhere
};
math.glPushMatrix = function () {
cc.current_stack.push(cc.current_stack.top);
cc.current_stack.update();
};
math.glPushMatrixWitMat4 = function (saveMat) {
cc.current_stack.stack.push(cc.current_stack.top);
saveMat.assignFrom(cc.current_stack.top);
cc.current_stack.top = saveMat;
cc.current_stack.update();
};
math.glPopMatrix = function () {
//No need to lazy initialize, you shouldnt be popping first anyway!
cc.current_stack.top = cc.current_stack.stack.pop();
cc.current_stack.update();
};
math.glMatrixMode = function (mode) {
//lazyInitialize();
switch (mode) {
case math.KM_GL_MODELVIEW:
cc.current_stack = math.modelview_matrix_stack;
break;
case math.KM_GL_PROJECTION:
cc.current_stack = math.projection_matrix_stack;
break;
case math.KM_GL_TEXTURE:
cc.current_stack = math.texture_matrix_stack;
break;
default:
throw new Error(cc._getError(7908)); //TODO: Proper error handling
break;
}
};
math.glLoadIdentity = function () {
//lazyInitialize();
cc.current_stack.top.identity(); //Replace the top matrix with the identity matrix
cc.current_stack.update();
};
math.glLoadMatrix = function (pIn) {
//lazyInitialize();
cc.current_stack.top.assignFrom(pIn);
cc.current_stack.update();
};
math.glMultMatrix = function (pIn) {
//lazyInitialize();
cc.current_stack.top.multiply(pIn);
cc.current_stack.update();
};
var tempMatrix = new math.Matrix4(); //an internal matrix
math.glTranslatef = function (x, y, z) {
//Create a rotation matrix using translation
var translation = math.Matrix4.createByTranslation(x, y, z, tempMatrix);
//Multiply the rotation matrix by the current matrix
cc.current_stack.top.multiply(translation);
cc.current_stack.update();
};
var tempVector3 = new math.Vec3();
math.glRotatef = function (angle, x, y, z) {
tempVector3.fill(x, y, z);
//Create a rotation matrix using the axis and the angle
var rotation = math.Matrix4.createByAxisAndAngle(tempVector3, cc.degreesToRadians(angle), tempMatrix);
//Multiply the rotation matrix by the current matrix
cc.current_stack.top.multiply(rotation);
cc.current_stack.update();
};
math.glScalef = function (x, y, z) {
var scaling = math.Matrix4.createByScale(x, y, z, tempMatrix);
cc.current_stack.top.multiply(scaling);
cc.current_stack.update();
};
math.glGetMatrix = function (mode, pOut) {
//lazyInitialize();
switch (mode) {
case math.KM_GL_MODELVIEW:
pOut.assignFrom(math.modelview_matrix_stack.top);
break;
case math.KM_GL_PROJECTION:
pOut.assignFrom(math.projection_matrix_stack.top);
break;
case math.KM_GL_TEXTURE:
pOut.assignFrom(math.texture_matrix_stack.top);
break;
default:
throw new Error(cc._getError(7908)); //TODO: Proper error handling
break;
}
};
-12
View File
@@ -1,12 +0,0 @@
require('./utility');
require('./vec2');
require('./vec3');
require('./vec4');
require('./ray2');
require('./mat3');
require('./mat4');
require('./plane');
require('./quaternion');
require('./aabb');
require('./gl/mat4stack');
require('./gl/matrix');
-337
View File
@@ -1,337 +0,0 @@
/**
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
Copyright (c) 2008, Luke Benstead.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
if (!(CC_EDITOR && Editor.isMainProcess)) {
window.Uint16Array = window.Uint16Array || window.Array;
window.Float32Array = window.Float32Array || window.Array;
}
cc.math.Matrix3 = function(mat3) {
if (mat3 && mat3.mat) {
this.mat = new Float32Array(mat3.mat);
} else {
this.mat = new Float32Array(9);
}
};
var proto = cc.math.Matrix3.prototype;
proto.fill = function(mat3) { //cc.kmMat3Fill
var mat = this.mat, matIn = mat3.mat;
mat[0] = matIn[0];
mat[1] = matIn[1];
mat[2] = matIn[2];
mat[3] = matIn[3];
mat[4] = matIn[4];
mat[5] = matIn[5];
mat[6] = matIn[6];
mat[7] = matIn[7];
mat[8] = matIn[8];
return this;
};
proto.adjugate = function(){ //= cc.kmMat3Adjugate
var mat = this.mat;
var m0 = mat[0], m1 = mat[1], m2 = mat[2], m3 = mat[3], m4 = mat[4],
m5 = mat[5], m6 = mat[6], m7 = mat[7], m8 = mat[8];
mat[0] = m4 * m8 - m5 * m7;
mat[1] = m2 * m7 - m1 * m8;
mat[2] = m1 * m5 - m2 * m4;
mat[3] = m5 * m6 - m3 * m8;
mat[4] = m0 * m8 - m2 * m6;
mat[5] = m2 * m3 - m0 * m5;
mat[6] = m3 * m7 - m4 * m6;
// XXX: pIn.mat[9] is invalid!
//mat[7] = m1 * m6 - pIn.mat[9] * m7;
mat[8] = m0 * m4 - m1 * m3;
return this;
};
proto.identity = function() { //cc.kmMat3Identity
var mat = this.mat;
mat[1] = mat[2] = mat[3] =
mat[5] = mat[6] = mat[7] = 0;
mat[0] = mat[4] = mat[8] = 1.0;
return this;
};
var tmpMatrix = new cc.math.Matrix3(); // internal matrix
proto.inverse = function(determinate){ //cc.kmMat3Inverse
if (determinate === 0.0)
return this;
tmpMatrix.assignFrom(this);
var detInv = 1.0 / determinate;
this.adjugate();
this.multiplyScalar(detInv);
return this;
};
proto.isIdentity = function(){ //= cc.kmMat3IsIdentity
var mat = this.mat;
return (mat[0] === 1 && mat[1] === 0 && mat[2] === 0
&& mat[3] === 0 && mat[4] === 1 && mat[5] === 0
&& mat[6] === 0 && mat[7] === 0 && mat[8] === 1);
};
proto.transpose = function(){ // cc.kmMat3Transpose
var mat = this.mat;
var m1 = mat[1], m2 = mat[2], m3 = mat[3], m5 = mat[5],
m6 = mat[6], m7 = mat[7];
// m0 = mat[0],m8 = mat[8], m4 = mat[4];
//mat[0] = m0;
//mat[8] = m8;
//mat[4] = m4
mat[1] = m3;
mat[2] = m6;
mat[3] = m1;
mat[5] = m7;
mat[6] = m2;
mat[7] = m5;
return this;
};
proto.determinant = function(){
var mat = this.mat;
/*
calculating the determinant following the rule of sarus,
| 0 3 6 | 0 3 |
m = | 1 4 7 | 1 4 |
| 2 5 8 | 2 5 |
now sum up the products of the diagonals going to the right (i.e. 0,4,8)
and substract the products of the other diagonals (i.e. 2,4,6)
*/
var output = mat[0] * mat[4] * mat[8] + mat[1] * mat[5] * mat[6] + mat[2] * mat[3] * mat[7];
output -= mat[2] * mat[4] * mat[6] + mat[0] * mat[5] * mat[7] + mat[1] * mat[3] * mat[8];
return output;
};
proto.multiply = function(mat3){
var m1 = this.mat, m2 = mat3.mat;
var a0 = m1[0], a1 = m1[1], a2 = m1[2], a3 = m1[3], a4 = m1[4], a5 = m1[5],
a6 = m1[6], a7 = m1[7], a8 = m1[8];
var b0 = m2[0], b1 = m2[1], b2 = m2[2], b3 = m2[3], b4 = m2[4], b5 = m2[5],
b6 = m2[6], b7 = m2[7], b8 = m2[8];
m1[0] = a0 * b0 + a3 * b1 + a6 * b2;
m1[1] = a1 * b0 + a4 * b1 + a7 * b2;
m1[2] = a2 * b0 + a5 * b1 + a8 * b2;
m1[3] = a2 * b0 + a5 * b1 + a8 * b2;
m1[4] = a1 * b3 + a4 * b4 + a7 * b5;
m1[5] = a2 * b3 + a5 * b4 + a8 * b5;
m1[6] = a0 * b6 + a3 * b7 + a6 * b8;
m1[7] = a1 * b6 + a4 * b7 + a7 * b8;
m1[8] = a2 * b6 + a5 * b7 + a8 * b8;
return this;
};
proto.multiplyScalar = function(factor) {
var mat = this.mat;
mat[0] *= factor;
mat[1] *= factor;
mat[2] *= factor;
mat[3] *= factor;
mat[4] *= factor;
mat[5] *= factor;
mat[6] *= factor;
mat[7] *= factor;
mat[8] *= factor;
return this;
};
cc.math.Matrix3.rotationAxisAngle = function(axis, radians) { //cc.kmMat3RotationAxisAngle
var rcos = Math.cos(radians), rsin = Math.sin(radians);
var retMat = new cc.math.Matrix3();
var mat = retMat.mat;
mat[0] = rcos + axis.x * axis.x * (1 - rcos);
mat[1] = axis.z * rsin + axis.y * axis.x * (1 - rcos);
mat[2] = -axis.y * rsin + axis.z * axis.x * (1 - rcos);
mat[3] = -axis.z * rsin + axis.x * axis.y * (1 - rcos);
mat[4] = rcos + axis.y * axis.y * (1 - rcos);
mat[5] = axis.x * rsin + axis.z * axis.y * (1 - rcos);
mat[6] = axis.y * rsin + axis.x * axis.z * (1 - rcos);
mat[7] = -axis.x * rsin + axis.y * axis.z * (1 - rcos);
mat[8] = rcos + axis.z * axis.z * (1 - rcos);
return retMat;
};
proto.assignFrom = function(matIn){ // cc.kmMat3Assign
if(this === matIn) {
cc.logID(7900);
return this;
}
var mat = this.mat, m2 = matIn.mat;
mat[0] = m2[0];
mat[1] = m2[1];
mat[2] = m2[2];
mat[3] = m2[3];
mat[4] = m2[4];
mat[5] = m2[5];
mat[6] = m2[6];
mat[7] = m2[7];
mat[8] = m2[8];
return this;
};
proto.equals = function(mat3) {
if (this === mat3)
return true;
var EPSILON = cc.math.EPSILON,m1 = this.mat, m2 = mat3.mat;
for (var i = 0; i < 9; ++i) {
if (!(m1[i] + EPSILON > m2[i] && m1[i] - EPSILON < m2[i]))
return false;
}
return true;
};
cc.math.Matrix3.createByRotationX = function(radians) {
var retMat = new cc.math.Matrix3(), mat = retMat.mat;
mat[0] = 1.0;
mat[1] = 0.0;
mat[2] = 0.0;
mat[3] = 0.0;
mat[4] = Math.cos(radians);
mat[5] = Math.sin(radians);
mat[6] = 0.0;
mat[7] = -Math.sin(radians);
mat[8] = Math.cos(radians);
return retMat;
};
cc.math.Matrix3.createByRotationY = function(radians) {
/*
| cos(A) 0 sin(A) |
M = | 0 1 0 |
| -sin(A) 0 cos(A) |
*/
var retMat = new cc.math.Matrix3(), mat = retMat.mat;
mat[0] = Math.cos(radians);
mat[1] = 0.0;
mat[2] = -Math.sin(radians);
mat[3] = 0.0;
mat[4] = 1.0;
mat[5] = 0.0;
mat[6] = Math.sin(radians);
mat[7] = 0.0;
mat[8] = Math.cos(radians);
return retMat;
};
cc.math.Matrix3.createByRotationZ = function(radians) {
/*
| cos(A) -sin(A) 0 |
M = | sin(A) cos(A) 0 |
| 0 0 1 |
*/
var retMat = new cc.math.Matrix3(), mat = retMat.mat;
mat[0] = Math.cos(radians);
mat[1] = -Math.sin(radians);
mat[2] = 0.0;
mat[3] = Math.sin(radians);
mat[4] = Math.cos(radians);
mat[5] = 0.0;
mat[6] = 0.0;
mat[7] = 0.0;
mat[8] = 1.0;
return retMat;
};
cc.math.Matrix3.createByRotation = function(radians) {
/*
| cos(A) -sin(A) 0 |
M = | sin(A) cos(A) 0 |
| 0 0 1 |
*/
var retMat = new cc.math.Matrix3(), mat = retMat.mat;
mat[0] = Math.cos(radians);
mat[1] = Math.sin(radians);
mat[2] = 0.0;
mat[3] = -Math.sin(radians);
mat[4] = Math.cos(radians);
mat[5] = 0.0;
mat[6] = 0.0;
mat[7] = 0.0;
mat[8] = 1.0;
return retMat;
};
cc.math.Matrix3.createByScale = function(x, y) {
var ret = new cc.math.Matrix3();
ret.identity();
ret.mat[0] = x;
ret.mat[4] = y;
return ret;
};
cc.math.Matrix3.createByTranslation = function(x, y){
var ret = new cc.math.Matrix3();
ret.identity();
ret.mat[6] = x;
ret.mat[7] = y;
return ret;
};
cc.math.Matrix3.createByQuaternion = function(quaternion) { //cc.kmMat3RotationQuaternion
if(!quaternion)
return null;
var ret = new cc.math.Matrix3(), mat = ret.mat;
// First row
mat[0] = 1.0 - 2.0 * (quaternion.y * quaternion.y + quaternion.z * quaternion.z);
mat[1] = 2.0 * (quaternion.x * quaternion.y - quaternion.w * quaternion.z);
mat[2] = 2.0 * (quaternion.x * quaternion.z + quaternion.w * quaternion.y);
// Second row
mat[3] = 2.0 * (quaternion.x * quaternion.y + quaternion.w * quaternion.z);
mat[4] = 1.0 - 2.0 * (quaternion.x * quaternion.x + quaternion.z * quaternion.z);
mat[5] = 2.0 * (quaternion.y * quaternion.z - quaternion.w * quaternion.x);
// Third row
mat[6] = 2.0 * (quaternion.x * quaternion.z - quaternion.w * quaternion.y);
mat[7] = 2.0 * (quaternion.y * quaternion.z + quaternion.w * quaternion.x);
mat[8] = 1.0 - 2.0 * (quaternion.x * quaternion.x + quaternion.y * quaternion.y);
return ret;
};
proto.rotationToAxisAngle = function() { //cc.kmMat3RotationToAxisAngle
return cc.math.Quaternion.rotationMatrix(this).toAxisAndAngle();
}
File diff suppressed because it is too large Load Diff
-424
View File
@@ -1,424 +0,0 @@
/**
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
Copyright (c) 2008, Luke Benstead.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
var proto = cc.math.Matrix4.prototype;
cc.math.mat4InverseSIMD = function (pOut, pM) {
pOut = pM.inverseSIMD();
return pOut;
};
proto.inverseSIMD = function(){
var inv = new cc.math.Matrix4();
var src = this.mat;
var dest = inv.mat;
var src0, src1, src2, src3;
var row0, row1, row2, row3;
var tmp1;
var minor0, minor1, minor2, minor3;
var det;
// Load the 4 rows
var src0 = SIMD.float32x4.load(src, 0);
var src1 = SIMD.float32x4.load(src, 4);
var src2 = SIMD.float32x4.load(src, 8);
var src3 = SIMD.float32x4.load(src, 12);
// Transpose the source matrix. Sort of. Not a true transpose operation
tmp1 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
row1 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
row0 = SIMD.float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
row1 = SIMD.float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
tmp1 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
row3 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
row2 = SIMD.float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
row3 = SIMD.float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
// ----
tmp1 = SIMD.float32x4.mul(row2, row3);
tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
minor0 = SIMD.float32x4.mul(row1, tmp1);
minor1 = SIMD.float32x4.mul(row0, tmp1);
tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
minor0 = SIMD.float32x4.sub(SIMD.float32x4.mul(row1, tmp1), minor0);
minor1 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor1);
minor1 = SIMD.float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
// ----
tmp1 = SIMD.float32x4.mul(row1, row2);
tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor0);
minor3 = SIMD.float32x4.mul(row0, tmp1);
tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row3, tmp1));
minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor3);
minor3 = SIMD.float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
// ----
tmp1 = SIMD.float32x4.mul(SIMD.float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
row2 = SIMD.float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
minor0 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor0);
minor2 = SIMD.float32x4.mul(row0, tmp1);
tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
minor0 = SIMD.float32x4.sub(minor0, SIMD.float32x4.mul(row2, tmp1));
minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row0, tmp1), minor2);
minor2 = SIMD.float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
// ----
tmp1 = SIMD.float32x4.mul(row0, row1);
tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor2);
minor3 = SIMD.float32x4.sub(SIMD.float32x4.mul(row2, tmp1), minor3);
tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
minor2 = SIMD.float32x4.sub(SIMD.float32x4.mul(row3, tmp1), minor2);
minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row2, tmp1));
// ----
tmp1 = SIMD.float32x4.mul(row0, row3);
tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row2, tmp1));
minor2 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor2);
tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row2, tmp1), minor1);
minor2 = SIMD.float32x4.sub(minor2, SIMD.float32x4.mul(row1, tmp1));
// ----
tmp1 = SIMD.float32x4.mul(row0, row2);
tmp1 = SIMD.float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
minor1 = SIMD.float32x4.add(SIMD.float32x4.mul(row3, tmp1), minor1);
minor3 = SIMD.float32x4.sub(minor3, SIMD.float32x4.mul(row1, tmp1));
tmp1 = SIMD.float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
minor1 = SIMD.float32x4.sub(minor1, SIMD.float32x4.mul(row3, tmp1));
minor3 = SIMD.float32x4.add(SIMD.float32x4.mul(row1, tmp1), minor3);
// Compute determinant
det = SIMD.float32x4.mul(row0, minor0);
det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
det = SIMD.float32x4.add(SIMD.float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
tmp1 = SIMD.float32x4.reciprocalApproximation(det);
det = SIMD.float32x4.sub(SIMD.float32x4.add(tmp1, tmp1), SIMD.float32x4.mul(det, SIMD.float32x4.mul(tmp1, tmp1)));
det = SIMD.float32x4.swizzle(det, 0, 0, 0, 0);
// Compute final values by multiplying with 1/det
minor0 = SIMD.float32x4.mul(det, minor0);
minor1 = SIMD.float32x4.mul(det, minor1);
minor2 = SIMD.float32x4.mul(det, minor2);
minor3 = SIMD.float32x4.mul(det, minor3);
SIMD.float32x4.store(dest, 0, minor0);
SIMD.float32x4.store(dest, 4, minor1);
SIMD.float32x4.store(dest, 8, minor2);
SIMD.float32x4.store(dest, 12, minor3);
return inv;
};
var identityMatrix = new cc.math.Matrix4().identity();
proto.isIdentitySIMD = function () {
var inx4 = SIMD.float32x4.load(this.mat, 0);
var identityx4 = SIMD.float32x4.load(identityMatrix.mat, 0);
var ret = SIMD.float32x4.equal(inx4, identityx4);
if(ret.signMask === 0x00)
return false;
inx4 = SIMD.float32x4.load(this.mat, 4);
identityx4 = SIMD.float32x4.load(identityMatrix.mat, 4);
ret = SIMD.float32x4.equal(inx4, identityx4);
if(ret.signMask === 0x00)
return false;
inx4 = SIMD.float32x4.load(this.mat, 8);
identityx4 = SIMD.float32x4.load(identityMatrix.mat, 8);
ret = SIMD.float32x4.equal(inx4, identityx4);
if(ret.signMask === 0x00)
return false;
inx4 = SIMD.float32x4.load(this.mat, 12);
identityx4 = SIMD.float32x4.load(identityMatrix.mat, 12);
ret = SIMD.float32x4.equal(inx4, identityx4);
if(ret.signMask === 0x00)
return false;
return true;
};
proto.transposeSIMD = function () {
var outArr = this.mat, inArr = this.mat;
var src0 = SIMD.float32x4.load(inArr, 0);
var src1 = SIMD.float32x4.load(inArr, 4);
var src2 = SIMD.float32x4.load(inArr, 8);
var src3 = SIMD.float32x4.load(inArr, 12);
var dst0;
var dst1;
var dst2;
var dst3;
var tmp01;
var tmp23;
tmp01 = SIMD.float32x4.shuffle(src0, src1, 0, 1, 4, 5);
tmp23 = SIMD.float32x4.shuffle(src2, src3, 0, 1, 4, 5);
dst0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
dst1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
tmp01 = SIMD.float32x4.shuffle(src0, src1, 2, 3, 6, 7);
tmp23 = SIMD.float32x4.shuffle(src2, src3, 2, 3, 6, 7);
dst2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
dst3 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
SIMD.float32x4.store(outArr, 0, dst0);
SIMD.float32x4.store(outArr, 4, dst1);
SIMD.float32x4.store(outArr, 8, dst2);
SIMD.float32x4.store(outArr, 12, dst3);
return this;
};
cc.math.mat4MultiplySIMD = function (pOut, pM1, pM2) {
pOut = new cc.math.Matrix4(pM1);
return pOut.multiplySIMD(pM2);
};
proto.multiplySIMD = function(mat4) {
var a = this.mat;
var b = mat4.mat;
var out = this.mat;
var a0 = SIMD.float32x4.load(a,0);
var a1 = SIMD.float32x4.load(a,4);
var a2 = SIMD.float32x4.load(a,8);
var a3 = SIMD.float32x4.load(a,12);
var b0 = SIMD.float32x4.load(b, 0);
SIMD.float32x4.store(out, 0, SIMD.float32x4.add(
SIMD.float32x4.mul(
SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0),
SIMD.float32x4.add(
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1),
SIMD.float32x4.add(
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2),
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
var b1 = SIMD.float32x4.load(b, 4);
SIMD.float32x4.store(out, 4, SIMD.float32x4.add(
SIMD.float32x4.mul(
SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0),
SIMD.float32x4.add(
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1),
SIMD.float32x4.add(
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2),
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
var b2 = SIMD.float32x4.load(b, 8);
SIMD.float32x4.store(out, 8, SIMD.float32x4.add(
SIMD.float32x4.mul(
SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0),
SIMD.float32x4.add(
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1),
SIMD.float32x4.add(
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2),
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
var b3 = SIMD.float32x4.load(b, 12);
SIMD.float32x4.store(out, 12, SIMD.float32x4.add(
SIMD.float32x4.mul(
SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0),
SIMD.float32x4.add(
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1),
SIMD.float32x4.add(
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2),
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
return this;
};
cc.math.getMat4MultiplyValueSIMD = function (pM1, pM2) {
var mat = new cc.math.Matrix4(pM1);
return mat.multiplySIMD(pM2);
};
cc.math.mat4AssignSIMD = function (pOut, pIn) {
if(pOut == pIn) {
cc.logID(7905);//TODO: ADD SIMD?
return pOut;
}
return pOut.assignFromSIMD(pIn);
};
proto.assignFromSIMD = function (mat4) {
if(this == mat4) {
cc.logID(7906);//TODO: ADD SIMD?
return this;
}
var outArr = this.mat;
var inArr = mat4.mat;
SIMD.float32x4.store(outArr, 0, SIMD.float32x4.load(inArr, 0));
SIMD.float32x4.store(outArr, 4, SIMD.float32x4.load(inArr, 4));
SIMD.float32x4.store(outArr, 8, SIMD.float32x4.load(inArr, 8));
SIMD.float32x4.store(outArr, 12, SIMD.float32x4.load(inArr, 12));
return this;
};
proto.equalsSIMD = function (mat4) {
if(this === mat4){
cc.logID(7907);
return true;
}
var m10 = SIMD.float32x4.load(this.mat, 0);
var m20 = SIMD.float32x4.load(mat4.mat, 0);
var epsilon = SIMD.float32x4.splat(cc.math.EPSILON);
var ret = SIMD.float32x4.lessThanOrEqual(SIMD.float32x4.abs(SIMD.float32x4.sub(m10, m20)), epsilon);
if (ret.signMask === 0)
return false;
var m11 = SIMD.float32x4.load(this.mat, 4);
var m21 = SIMD.float32x4.load(mat4.mat, 4);
ret = SIMD.float32x4.lessThanOrEqual(SIMD.float32x4.abs(SIMD.float32x4.sub(m11, m21)), epsilon);
if (ret.signMask === 0)
return false;
var m12 = SIMD.float32x4.load(this.mat, 8);
var m22 = SIMD.float32x4.load(mat4.mat, 8);
ret = SIMD.float32x4.lessThanOrEqual(SIMD.float32x4.abs(SIMD.float32x4.sub(m12, m22)), epsilon);
if (ret.signMask === 0)
return false;
var m13 = SIMD.float32x4.load(this.mat, 12);
var m23 = SIMD.float32x4.load(mat4.mat, 12);
ret = SIMD.float32x4.lessThanOrEqual(SIMD.float32x4.abs(SIMD.float32x4.sub(m13, m23)), epsilon);
if (ret.signMask === 0)
return false;
return true;
};
cc.math.mat4LookAtSIMD = function (pOut, pEye, pCenter, pUp) {
return pOut.lookAtSIMD(pEye, pCenter, pUp);
};
proto.lookAtSIMD = function(eyeVec, centerVec, upVec) {
var out = this.mat;
var center = SIMD.float32x4(centerVec.x, centerVec.y, centerVec.z, 0.0);
var eye = SIMD.float32x4(eyeVec.x, eyeVec.y, eyeVec.z, 0.0);
var up = SIMD.float32x4(upVec.x, upVec.y, upVec.z, 0.0);
// cc.math.Vec3Subtract(f, pCenter, pEye);
var f = SIMD.float32x4.sub(center, eye);
// cc.math.Vec3Normalize(f, f);
var tmp = SIMD.float32x4.mul(f, f);
tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
f = SIMD.float32x4.mul(f, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
// cc.math.Vec3Assign(up, pUp);
// cc.math.Vec3Normalize(up, up);
tmp = SIMD.float32x4.mul(up, up);
tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
up = SIMD.float32x4.mul(up, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
// cc.math.Vec3Cross(s, f, up);
var s = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 1, 2, 0, 3), SIMD.float32x4.swizzle(up, 2, 0, 1, 3)),
SIMD.float32x4.mul(SIMD.float32x4.swizzle(f, 2, 0, 1, 3), SIMD.float32x4.swizzle(up, 1, 2, 0, 3)));
// cc.math.Vec3Normalize(s, s);
tmp = SIMD.float32x4.mul(s, s);
tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
// cc.math.Vec3Cross(u, s, f);
var u = SIMD.float32x4.sub(SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 1, 2, 0, 3), SIMD.float32x4.swizzle(f, 2, 0, 1, 3)),
SIMD.float32x4.mul(SIMD.float32x4.swizzle(s, 2, 0, 1, 3), SIMD.float32x4.swizzle(f, 1, 2, 0, 3)));
// cc.math.Vec3Normalize(s, s);
tmp = SIMD.float32x4.mul(s, s);
tmp = SIMD.float32x4.add(tmp, SIMD.float32x4.add(SIMD.float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.float32x4.swizzle(tmp, 2, 0, 1, 3)));
s = SIMD.float32x4.mul(s, SIMD.float32x4.reciprocalSqrtApproximation(tmp));
//cc.math.mat4Identity(pOut);
//pOut.mat[0] = s.x;
//pOut.mat[4] = s.y;
//pOut.mat[8] = s.z;
//pOut.mat[1] = u.x;
//pOut.mat[5] = u.y;
//pOut.mat[9] = u.z;
//pOut.mat[2] = -f.x;
//pOut.mat[6] = -f.y;
//pOut.mat[10] = -f.z;
var zero = SIMD.float32x4.splat(0.0);
f = SIMD.float32x4.neg(f);
var tmp01 = SIMD.float32x4.shuffle(s, u, 0, 1, 4, 5);
var tmp23 = SIMD.float32x4.shuffle(f, zero, 0, 1, 4, 5);
var a0 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
var a1 = SIMD.float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
var tmp01 = SIMD.float32x4.shuffle(s, u, 2, 3, 6, 7);
var tmp23 = SIMD.float32x4.shuffle(f, zero, 2, 3, 6, 7);
var a2 = SIMD.float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
var a3 = SIMD.float32x4(0.0, 0.0, 0.0, 1.0);
// cc.math.mat4Translation(translate, -pEye.x, -pEye.y, -pEye.z);
var b0 = SIMD.float32x4(1.0, 0.0, 0.0, 0.0);
var b1 = SIMD.float32x4(0.0, 1.0, 0.0, 0.0);
var b2 = SIMD.float32x4(0.0, 0.0, 1.0, 0.0);
var b3 = SIMD.float32x4.neg(eye);
b3 = SIMD.float32x4.withW(b3, 1.0);
// cc.math.mat4Multiply(pOut, pOut, translate);
SIMD.float32x4.store(out, 0, SIMD.float32x4.add(
SIMD.float32x4.mul(
SIMD.float32x4.swizzle(b0, 0, 0, 0, 0), a0),
SIMD.float32x4.add(
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 1, 1, 1, 1), a1),
SIMD.float32x4.add(
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 2, 2, 2, 2), a2),
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b0, 3, 3, 3, 3), a3)))));
SIMD.float32x4.store(out, 4, SIMD.float32x4.add(
SIMD.float32x4.mul(
SIMD.float32x4.swizzle(b1, 0, 0, 0, 0), a0),
SIMD.float32x4.add(
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 1, 1, 1, 1), a1),
SIMD.float32x4.add(
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 2, 2, 2, 2), a2),
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b1, 3, 3, 3, 3), a3)))));
SIMD.float32x4.store(out, 8, SIMD.float32x4.add(
SIMD.float32x4.mul(
SIMD.float32x4.swizzle(b2, 0, 0, 0, 0), a0),
SIMD.float32x4.add(
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 1, 1, 1, 1), a1),
SIMD.float32x4.add(
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 2, 2, 2, 2), a2),
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b2, 3, 3, 3, 3), a3)))));
SIMD.float32x4.store(out, 12, SIMD.float32x4.add(
SIMD.float32x4.mul(
SIMD.float32x4.swizzle(b3, 0, 0, 0, 0), a0),
SIMD.float32x4.add(
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 1, 1, 1, 1), a1),
SIMD.float32x4.add(
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 2, 2, 2, 2), a2),
SIMD.float32x4.mul(SIMD.float32x4.swizzle(b3, 3, 3, 3, 3), a3)))));
return this;
};
-128
View File
@@ -1,128 +0,0 @@
/**
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
Copyright (c) 2008, Luke Benstead.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
cc.math.Plane = function (a, b, c, d) {
if (a && b === undefined) {
this.a = a.a;
this.b = a.b;
this.c = a.c;
this.d = a.d;
} else {
this.a = a || 0;
this.b = b || 0;
this.c = c || 0;
this.d = d || 0;
}
};
var proto = cc.math.Plane.prototype;
cc.math.Plane.LEFT = 0;
cc.math.Plane.RIGHT = 1;
cc.math.Plane.BOTTOM = 2;
cc.math.Plane.TOP = 3;
cc.math.Plane.NEAR = 4;
cc.math.Plane.FAR = 5;
cc.math.Plane.POINT_INFRONT_OF_PLANE = 0;
cc.math.Plane.POINT_BEHIND_PLANE = 1;
cc.math.Plane.POINT_ON_PLANE = 2;
proto.dot = function(vec4){ //cc.kmPlaneDot
return (this.a * vec4.x + this.b * vec4.y + this.c * vec4.z + this.d * vec4.w);
};
proto.dotCoord = function(vec3) { //=cc.kmPlaneDotCoord
return (this.a * vec3.x + this.b * vec3.y + this.c * vec3.z + this.d);
};
proto.dotNormal = function(vec3) { //=cc.kmPlaneDotNormal
return (this.a * vec3.x + this.b * vec3.y + this.c * vec3.z);
};
cc.math.Plane.fromPointNormal = function(vec3, normal) { //cc.kmPlaneFromPointNormal
/*
Planea = Nx
Planeb = Ny
Planec = Nz
Planed = −N⋅P
*/
return new cc.math.Plane(normal.x, normal.y, normal.z, -normal.dot(vec3));
};
cc.math.Plane.fromPoints = function(vec1, vec2, vec3) { //cc.kmPlaneFromPoints
/*
v = (B − A) × (C − A)
n = 1⁄|v| v
Outa = nx
Outb = ny
Outc = nz
Outd = −n⋅A
*/
var v1 = new cc.math.Vec3(vec2), v2 = new cc.math.Vec3(vec3), plane = new cc.math.Plane();
v1.subtract(vec1); //Create the vectors for the 2 sides of the triangle
v2.subtract(vec1);
v1.cross(v2); // Use the cross product to get the normal
v1.normalize(); //Normalize it and assign to pOut.m_N
plane.a = v1.x;
plane.b = v1.y;
plane.c = v1.z;
plane.d = v1.scale(-1.0).dot(vec1);
return plane;
};
proto.normalize = function(){ //cc.kmPlaneNormalize
var n = new cc.math.Vec3(this.a, this.b, this.c), l = 1.0 / n.length(); //Get 1/length
n.normalize(); //Normalize the vector and assign to pOut
this.a = n.x;
this.b = n.y;
this.c = n.z;
this.d = this.d * l; //Scale the D value and assign to pOut
return this;
};
proto.classifyPoint = function(vec3) {
// This function will determine if a point is on, in front of, or behind
// the plane. First we store the dot product of the plane and the point.
var distance = this.a * vec3.x + this.b * vec3.y + this.c * vec3.z + this.d;
// Simply put if the dot product is greater than 0 then it is infront of it.
// If it is less than 0 then it is behind it. And if it is 0 then it is on it.
if(distance > 0.001)
return cc.math.Plane.POINT_INFRONT_OF_PLANE;
if(distance < -0.001)
return cc.math.Plane.POINT_BEHIND_PLANE;
return cc.math.Plane.POINT_ON_PLANE;
};
-443
View File
@@ -1,443 +0,0 @@
/**
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
Copyright (c) 2008, Luke Benstead.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* The Quaternion class
* @param {Number|cc.math.Quaternion} [x=0]
* @param {Number} [y=0]
* @param {Number} [z=0]
* @param {Number} [w=0]
*
*/
cc.math.Quaternion = function (x, y, z, w) {
if (x && y === undefined) {
this.x = x.x;
this.y = x.y;
this.z = x.z;
this.w = x.w;
} else {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
this.w = w || 0;
}
};
var proto = cc.math.Quaternion.prototype;
/**
* Sets the conjugate of quaternion to self
* @param {cc.math.Quaternion} quaternion
*/
proto.conjugate = function (quaternion) { //= cc.kmQuaternionConjugate
this.x = -quaternion.x;
this.y = -quaternion.y;
this.z = -quaternion.z;
this.w = quaternion.w;
return this;
};
/**
* Returns the dot product of the current quaternion and parameter quaternion
* @param quaternion
* @returns {number}
*/
proto.dot = function(quaternion) { // = cc.kmQuaternionDot
// A dot B = B dot A = AtBt + AxBx + AyBy + AzBz
return (this.w * quaternion.w + this.x * quaternion.x + this.y * quaternion.y + this.z * quaternion.z);
};
/**
* Returns the exponential of the quaternion, this function doesn't implemented.
* @returns {cc.math.Quaternion}
*/
proto.exponential = function(){ //=cc.kmQuaternionExp
return this;
};
/**
* Makes the current quaternion an identity quaternion
*/
proto.identity = function(){ //=cc.kmQuaternionIdentity
this.x = 0.0;
this.y = 0.0;
this.z = 0.0;
this.w = 1.0;
return this;
};
/**
* Inverses the value of current Quaternion
*/
proto.inverse = function(){ //=cc.kmQuaternionInverse
var len = this.length();
if (Math.abs(len) > cc.math.EPSILON) {
this.x = 0.0;
this.y = 0.0;
this.z = 0.0;
this.w = 0.0;
return this;
}
///Get the conjugute and divide by the length
this.conjugate(this).scale(1.0 / len);
return this;
};
/**
* Returns true if the quaternion is an identity quaternion
* @returns {boolean}
*/
proto.isIdentity = function(){ //=cc.kmQuaternionIsIdentity
return (this.x === 0.0 && this.y === 0.0 && this.z === 0.0 && this.w === 1.0);
};
/**
* Returns the length of the quaternion
* @returns {number}
*/
proto.length = function() { //=cc.kmQuaternionLength
return Math.sqrt(this.lengthSq());
};
/**
* Returns the length of the quaternion squared (prevents a sqrt)
* @returns {number}
*/
proto.lengthSq = function() { //=cc.kmQuaternionLengthSq
return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w;
};
/**
* Uses current quaternion multiplies other quaternion.
* @param {cc.math.Quaternion} quaternion
* @returns {cc.math.Quaternion}
*/
proto.multiply = function(quaternion) { //cc.kmQuaternionMultiply
var x = this.x, y = this.y, z = this.z, w = this.w;
this.w = w * quaternion.w - x * quaternion.x - y * quaternion.y - z * quaternion.z;
this.x = w * quaternion.x + x * quaternion.w + y * quaternion.z - z * quaternion.y;
this.y = w * quaternion.y + y * quaternion.w + z * quaternion.x - x * quaternion.z;
this.z = w * quaternion.z + z * quaternion.w + x * quaternion.y - y * quaternion.x;
return this;
};
/**
* Normalizes a quaternion
* @returns {cc.math.Quaternion}
*/
proto.normalize = function(){ //=cc.kmQuaternionNormalize
var length = this.length();
if (Math.abs(length) <= cc.math.EPSILON)
throw new Error(cc._getError(7909));
this.scale(1.0 / length);
return this;
};
/**
* Rotates a quaternion around an axis and an angle
* @param {cc.math.Vec3} axis
* @param {Number} angle
*/
proto.rotationAxis = function(axis, angle){ //cc.kmQuaternionRotationAxis
var rad = angle * 0.5, scale = Math.sin(rad);
this.w = Math.cos(rad);
this.x = axis.x * scale;
this.y = axis.y * scale;
this.z = axis.z * scale;
return this;
};
/**
* Creates a quaternion from a rotation matrix
* @param mat3
* @returns {*}
*/
cc.math.Quaternion.rotationMatrix = function (mat3) { //cc.kmQuaternionRotationMatrix
if (!mat3)
return null;
var x, y, z, w;
var m4x4 = [], mat = mat3.mat, scale = 0.0;
/* 0 3 6
1 4 7
2 5 8
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15*/
m4x4[0] = mat[0];
m4x4[1] = mat[3];
m4x4[2] = mat[6];
m4x4[4] = mat[1];
m4x4[5] = mat[4];
m4x4[6] = mat[7];
m4x4[8] = mat[2];
m4x4[9] = mat[5];
m4x4[10] = mat[8];
m4x4[15] = 1;
var pMatrix = m4x4[0];
var diagonal = pMatrix[0] + pMatrix[5] + pMatrix[10] + 1;
if (diagonal > cc.math.EPSILON) {
// Calculate the scale of the diagonal
scale = Math.sqrt(diagonal) * 2;
// Calculate the x, y, x and w of the quaternion through the respective equation
x = ( pMatrix[9] - pMatrix[6] ) / scale;
y = ( pMatrix[2] - pMatrix[8] ) / scale;
z = ( pMatrix[4] - pMatrix[1] ) / scale;
w = 0.25 * scale;
} else {
// If the first element of the diagonal is the greatest value
if (pMatrix[0] > pMatrix[5] && pMatrix[0] > pMatrix[10]) {
// Find the scale according to the first element, and double that value
scale = Math.sqrt(1.0 + pMatrix[0] - pMatrix[5] - pMatrix[10]) * 2.0;
// Calculate the x, y, x and w of the quaternion through the respective equation
x = 0.25 * scale;
y = (pMatrix[4] + pMatrix[1] ) / scale;
z = (pMatrix[2] + pMatrix[8] ) / scale;
w = (pMatrix[9] - pMatrix[6] ) / scale;
}
// Else if the second element of the diagonal is the greatest value
else if (pMatrix[5] > pMatrix[10]) {
// Find the scale according to the second element, and double that value
scale = Math.sqrt(1.0 + pMatrix[5] - pMatrix[0] - pMatrix[10]) * 2.0;
// Calculate the x, y, x and w of the quaternion through the respective equation
x = (pMatrix[4] + pMatrix[1] ) / scale;
y = 0.25 * scale;
z = (pMatrix[9] + pMatrix[6] ) / scale;
w = (pMatrix[2] - pMatrix[8] ) / scale;
} else {
// Else the third element of the diagonal is the greatest value
// Find the scale according to the third element, and double that value
scale = Math.sqrt(1.0 + pMatrix[10] - pMatrix[0] - pMatrix[5]) * 2.0;
// Calculate the x, y, x and w of the quaternion through the respective equation
x = (pMatrix[2] + pMatrix[8] ) / scale;
y = (pMatrix[9] + pMatrix[6] ) / scale;
z = 0.25 * scale;
w = (pMatrix[4] - pMatrix[1] ) / scale;
}
}
return new cc.math.Quaternion(x, y, z, w);
};
/**
* Create a quaternion from yaw, pitch and roll
* @param yaw
* @param pitch
* @param roll
* @returns {cc.math.Quaternion}
*/
cc.math.Quaternion.rotationYawPitchRoll = function (yaw, pitch, roll) { //cc.kmQuaternionRotationYawPitchRoll
var ex, ey, ez; // temp half euler angles
var cr, cp, cy, sr, sp, sy, cpcy, spsy; // temp vars in roll,pitch yaw
ex = cc.degreesToRadians(pitch) / 2.0; // convert to rads and half them
ey = cc.degreesToRadians(yaw) / 2.0;
ez = cc.degreesToRadians(roll) / 2.0;
cr = Math.cos(ex);
cp = Math.cos(ey);
cy = Math.cos(ez);
sr = Math.sin(ex);
sp = Math.sin(ey);
sy = Math.sin(ez);
cpcy = cp * cy;
spsy = sp * sy;
var ret = new cc.math.Quaternion();
ret.w = cr * cpcy + sr * spsy;
ret.x = sr * cpcy - cr * spsy;
ret.y = cr * sp * cy + sr * cp * sy;
ret.z = cr * cp * sy - sr * sp * cy;
ret.normalize();
return ret;
};
/**
* Interpolate with other quaternions
* @param {cc.math.Quaternion} quaternion
* @param {Number} t
* @returns {cc.math.Quaternion}
*/
proto.slerp = function(quaternion, t) { //=cc.kmQuaternionSlerp
if (this.x === quaternion.x && this.y === quaternion.y && this.z === quaternion.z && this.w === quaternion.w) {
return this;
}
var ct = this.dot(quaternion), theta = Math.acos(ct), st = Math.sqrt(1.0 - cc.math.square(ct));
var stt = Math.sin(t * theta) / st, somt = Math.sin((1.0 - t) * theta) / st;
var temp2 = new cc.math.Quaternion(quaternion);
this.scale(somt);
temp2.scale(stt);
this.add(temp2);
return this;
};
/**
* Get the axis and angle of rotation from a quaternion
* @returns {{axis: cc.math.Vec3, angle: number}}
*/
proto.toAxisAndAngle = function(){ //=cc.kmQuaternionToAxisAngle
var tempAngle; // temp angle
var scale; // temp vars
var retAngle, retAxis = new cc.math.Vec3();
tempAngle = Math.acos(this.w);
scale = Math.sqrt(cc.math.square(this.x) + cc.math.square(this.y) + cc.math.square(this.z));
if (((scale > -cc.math.EPSILON) && scale < cc.math.EPSILON)
|| (scale < 2 * Math.PI + cc.math.EPSILON && scale > 2 * Math.PI - cc.math.EPSILON)) { // angle is 0 or 360 so just simply set axis to 0,0,1 with angle 0
retAngle = 0.0;
retAxis.x = 0.0;
retAxis.y = 0.0;
retAxis.z = 1.0;
} else {
retAngle = tempAngle * 2.0; // angle in radians
retAxis.x = this.x / scale;
retAxis.y = this.y / scale;
retAxis.z = this.z / scale;
retAxis.normalize();
}
return {axis: retAxis, angle: retAngle};
};
/**
* Scale a quaternion
* @param {Number} scale
*/
proto.scale = function(scale) { //cc.kmQuaternionScale
this.x *= scale;
this.y *= scale;
this.z *= scale;
this.w *= scale;
return this;
};
/**
* Assign current quaternion value from a quaternion.
* @param {cc.math.Quaternion} quaternion
* @returns {cc.math.Quaternion} current quaternion
*/
proto.assignFrom = function(quaternion){ //=cc.kmQuaternionAssign
this.x = quaternion.x;
this.y = quaternion.y;
this.z = quaternion.z;
this.w = quaternion.w;
return this;
};
/**
* Adds other quaternion
* @param {cc.math.Quaternion} quaternion
* @returns {cc.math.Quaternion}
*/
proto.add = function(quaternion) { //cc.kmQuaternionAdd
this.x += quaternion.x;
this.y += quaternion.y;
this.z += quaternion.z;
this.w += quaternion.w;
return this;
};
/**
* <p>
* Adapted from the OGRE engine! <br/>
* Gets the shortest arc quaternion to rotate this vector to the destination vector. <br/>
* @remarks <br/>
* If you call this with a destination vector that is close to the inverse <br/>
* of this vector, we will rotate 180 degrees around the 'fallbackAxis' <br/>
* (if specified, or a generated axis if not) since in this case ANY axis of rotation is valid.
* </p>
* @param {cc.math.Vec3} vec1
* @param {cc.math.Vec3} vec2
* @param {cc.math.Vec3} fallback
* @returns {cc.math.Quaternion}
*/
cc.math.Quaternion.rotationBetweenVec3 = function(vec1, vec2, fallback) { //cc.kmQuaternionRotationBetweenVec3
var v1 = new cc.math.Vec3(vec1), v2 = new cc.math.Vec3(vec2);
v1.normalize();
v2.normalize();
var a = v1.dot(v2), quaternion = new cc.math.Quaternion();
if (a >= 1.0) {
quaternion.identity();
return quaternion;
}
if (a < (1e-6 - 1.0)) {
if (Math.abs(fallback.lengthSq()) < cc.math.EPSILON) {
quaternion.rotationAxis(fallback, Math.PI);
} else {
var axis = new cc.math.Vec3(1.0, 0.0, 0.0);
axis.cross(vec1);
//If axis is zero
if (Math.abs(axis.lengthSq()) < cc.math.EPSILON) {
axis.fill(0.0, 1.0, 0.0);
axis.cross(vec1);
}
axis.normalize();
quaternion.rotationAxis(axis, Math.PI);
}
} else {
var s = Math.sqrt((1 + a) * 2), invs = 1 / s;
v1.cross(v2);
quaternion.x = v1.x * invs;
quaternion.y = v1.y * invs;
quaternion.z = v1.z * invs;
quaternion.w = s * 0.5;
quaternion.normalize();
}
return quaternion;
};
/**
* Current quaternion multiplies a vec3
* @param {cc.math.Vec3} vec
* @returns {cc.math.Vec3}
*/
proto.multiplyVec3 = function(vec){ //=cc.kmQuaternionMultiplyVec3
var x = this.x, y = this.y, z = this.z, retVec = new cc.math.Vec3(vec);
var uv = new cc.math.Vec3(x, y, z), uuv = new cc.math.Vec3(x, y, z);
uv.cross(vec);
uuv.cross(uv);
uv.scale((2.0 * q.w));
uuv.scale(2.0);
retVec.add(uv);
retVec.add(uuv);
return retVec;
};
-138
View File
@@ -1,138 +0,0 @@
/**
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
Copyright (c) 2008, Luke Benstead.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
cc.math.Ray2 = function (start, dir) { // = cc.kmRay2
this.start = start || new cc.math.Vec2();
this.dir = dir || new cc.math.Vec2();
};
cc.math.Ray2.prototype.fill = function (px, py, vx, vy) { // = cc.kmRay2Fill
this.start.x = px;
this.start.y = py;
this.dir.x = vx;
this.dir.y = vy;
};
cc.math.Ray2.prototype.intersectLineSegment = function (p1, p2, intersection) { // = cc.kmRay2IntersectLineSegment
var x1 = this.start.x, y1 = this.start.y;
var x2 = this.start.x + this.dir.x, y2 = this.start.y + this.dir.y;
var x3 = p1.x, y3 = p1.y;
var x4 = p2.x, y4 = p2.y;
var denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
var ua, x, y;
//If denom is zero, the lines are parallel
if (denom > -cc.math.EPSILON && denom < cc.math.EPSILON)
return false;
ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denom;
//var ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denom;
x = x1 + ua * (x2 - x1);
y = y1 + ua * (y2 - y1);
if (x < Math.min(p1.x, p2.x) - cc.math.EPSILON ||
x > Math.max(p1.x, p2.x) + cc.math.EPSILON ||
y < Math.min(p1.y, p2.y) - cc.math.EPSILON ||
y > Math.max(p1.y, p2.y) + cc.math.EPSILON) {
//Outside of line
//printf("Outside of line, %f %f (%f %f)(%f, %f)\n", x, y, p1.x, p1.y, p2.x, p2.y);
return false;
}
if (x < Math.min(x1, x2) - cc.math.EPSILON ||
x > Math.max(x1, x2) + cc.math.EPSILON ||
y < Math.min(y1, y2) - cc.math.EPSILON ||
y > Math.max(y1, y2) + cc.math.EPSILON) {
//printf("Outside of ray, %f %f (%f %f)(%f, %f)\n", x, y, x1, y1, x2, y2);
return false;
}
intersection.x = x;
intersection.y = y;
return true;
};
function calculate_line_normal(p1, p2, normalOut){
var tmp = new cc.math.Vec2(p2);
tmp.subtract(p1);
normalOut.x = -tmp.y;
normalOut.y = tmp.x;
normalOut.normalize();
//TODO: should check that the normal is pointing out of the triangle
}
cc.math.Ray2.prototype.intersectTriangle = function(p1, p2, p3, intersection, normal_out){
var intersect = new cc.math.Vec2(), final_intersect = new cc.math.Vec2();
var normal = new cc.math.Vec2(), distance = 10000.0, intersected = false;
var this_distance;
if(this.intersectLineSegment(p1, p2, intersect)) {
intersected = true;
this_distance = intersect.subtract(this.start).length();
if(this_distance < distance) {
final_intersect.x = intersect.x;
final_intersect.y = intersect.y;
distance = this_distance;
calculate_line_normal(p1, p2, normal);
}
}
if(this.intersectLineSegment(p2, p3, intersect)) {
intersected = true;
this_distance = intersect.subtract(this.start).length();
if(this_distance < distance) {
final_intersect.x = intersect.x;
final_intersect.y = intersect.y;
distance = this_distance;
calculate_line_normal(p2, p3, normal);
}
}
if(this.intersectLineSegment(p3, p1, intersect)) {
intersected = true;
this_distance = intersect.subtract(this.start).length();
if(this_distance < distance) {
final_intersect.x = intersect.x;
final_intersect.y = intersect.y;
distance = this_distance;
calculate_line_normal(p3, p1, normal);
}
}
if(intersected) {
intersection.x = final_intersect.x;
intersection.y = final_intersect.y;
if(normal_out) {
normal_out.x = normal.x;
normal_out.y = normal.y;
}
}
return intersected;
};
-139
View File
@@ -1,139 +0,0 @@
// SIMD Kernel Benchmark Harness
// Author: Peter Jensen
function Benchmark (config) {
this.config = config;
this.initOk = true; // Initialize all properties used on a Benchmark object
this.cleanupOk = true;
this.useAutoIterations = true;
this.autoIterations = 0;
this.actualIterations = 0;
this.simdTime = 0;
this.nonSimdTime = 0;
}
function Benchmarks () {
this.benchmarks = [];
}
Benchmarks.prototype.add = function (benchmark) {
this.benchmarks.push (benchmark);
return this.benchmarks.length - 1;
};
Benchmarks.prototype.runOne = function (benchmark) {
function timeKernel(kernel, iterations) {
var start, stop;
start = Date.now();
kernel(iterations);
stop = Date.now();
return stop - start;
}
function computeIterations() {
var desiredRuntime = 1000; // milliseconds for longest running kernel
var testIterations = 10; // iterations used to determine time for desiredRuntime
// Make the slowest kernel run for at least 500ms
var simdTime = timeKernel(benchmark.config.kernelSimd, testIterations);
var nonSimdTime = timeKernel(benchmark.config.kernelNonSimd, testIterations);
var maxTime = simdTime > nonSimdTime ? simdTime : nonSimdTime;
while (maxTime < 500) {
testIterations *= 2;
simdTime = timeKernel(benchmark.config.kernelSimd, testIterations);
nonSimdTime = timeKernel(benchmark.config.kernelNonSimd, testIterations);
maxTime = simdTime > nonSimdTime ? simdTime : nonSimdTime;
}
maxTime = simdTime > nonSimdTime ? simdTime : nonSimdTime;
// Compute iteration count for 1 second run of slowest kernel
var iterations = Math.ceil(desiredRuntime * testIterations / maxTime);
return iterations;
}
// Initialize the kernels and check the correctness status
if (!benchmark.config.kernelInit()) {
benchmark.initOk = false;
return false;
}
// Determine how many iterations to use.
if (benchmark.useAutoIterations) {
benchmark.autoIterations = computeIterations();
benchmark.actualIterations = benchmark.autoIterations;
}
else {
benchmark.actualIterations = benchmark.config.kernelIterations;
}
// Run the SIMD kernel
benchmark.simdTime = timeKernel(benchmark.config.kernelSimd, benchmark.actualIterations);
// Run the non-SIMD kernel
benchmark.nonSimdTime = timeKernel(benchmark.config.kernelNonSimd, benchmark.actualIterations);
// Do the final sanity check
if (!benchmark.config.kernelCleanup()) {
benchmark.cleanupOk = false;
return false;
}
return true;
};
Benchmarks.prototype.report = function (benchmark, outputFunctions) {
function fillRight(str, width) {
str += ""; // make sure it's a string
while (str.length < width) {
str += " ";
}
return str;
}
function fillLeft(str, width) {
str += ""; // make sure it's a string
while (str.length < width) {
str = " " + str;
}
return str;
}
if (!benchmark.initOk) {
outputFunctions.notifyError(fillRight(benchmark.config.kernelName + ": ", 23) + "FAILED INIT");
return;
}
if (!benchmark.cleanupOk) {
outputFunctions.notifyError(fillRight(benchmark.config.kernelName + ": ", 23) + "FAILED CLEANUP");
return;
}
var ratio = benchmark.nonSimdTime / benchmark.simdTime;
ratio = ratio.toFixed(2);
outputFunctions.notifyResult(
fillRight(benchmark.config.kernelName + ": ", 23) +
"Iterations(" + fillLeft(benchmark.actualIterations, 10) + ")" +
", SIMD(" + fillLeft(benchmark.simdTime + "ms)", 8) +
", Non-SIMD(" + fillLeft(benchmark.nonSimdTime + "ms)", 8) +
", Speedup(" + ratio + ")");
outputFunctions.timeData.labels.push(benchmark.config.kernelName);
outputFunctions.timeData.datasets[0].data.push(benchmark.simdTime);
outputFunctions.timeData.datasets[1].data.push(benchmark.nonSimdTime);
outputFunctions.speedupData.labels.push(benchmark.config.kernelName);
outputFunctions.speedupData.datasets[0].data.push(ratio);
};
Benchmarks.prototype.runAll = function (outputFunctions, useAutoIterations) {
if (typeof useAutoIterations === "undefined") {
useAutoIterations = false;
}
for (var i = 0, n = this.benchmarks.length; i < n; ++i) {
var benchmark = this.benchmarks[i];
benchmark.useAutoIterations = useAutoIterations;
this.runOne(benchmark);
this.report(benchmark, outputFunctions);
}
};
var benchmarks = new Benchmarks ();
-44
View File
@@ -1,44 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Kazmath SIMD benchmarks</title>
</head>
<link href="http://cdn.bootcss.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<body>
<h1 align="center" id="head">Running benchmarks...</h1>
<div sytle="padding: 10px">
<div style="width: 50%;float: left">
<h2 align="center" id="time"></h2>
<canvas id="canvasTime"></canvas>
</div>
<div style="width: 50%;float: left">
<h2 align="center" id="speedup"></h2>
<canvas id="canvasSpeedup"></canvas>
</div>
</div>
<div id='echo'></div>
<script>
var cc = cc || {};
</script>
<script src="../utility.js"></script>
<script src="../vec3.js"></script>
<script src="../vec4.js"></script>
<script src="../mat4.js"></script>
<script src="../vec3SIMD.js"></script>
<script src="../mat4SIMD.js"></script>
<script src="base.js"></script>
<script src="kernel-template.js"></script>
<script src="kmMat4Multiply.js"></script>
<script src="kmMat4Assign.js"></script>
<script src="kmMat4AreEqual.js"></script>
<script src="kmMat4Inverse.js"></script>
<script src="kmMat4IsIdentity.js"></script>
<script src="kmMat4Transpose.js"></script>
<script src="kmMat4LookAt.js"></script>
<script src="kmVec3TransformCoord.js"></script>
<script src="http://cdn.bootcss.com/Chart.js/1.0.2/Chart.min.js"></script>
<!-- Execute -->
<script src="run_browser.js"></script>
</body>
</html>
@@ -1,64 +0,0 @@
// Kernel template
// Author: Peter Jensen
(function () {
// Kernel configuration
var kernelConfig = {
kernelName: "Test",
kernelInit: init,
kernelCleanup: cleanup,
kernelSimd: simd,
kernelNonSimd: nonSimd,
kernelIterations: 100000000
};
// Hook up to the harness
benchmarks.add (new Benchmark (kernelConfig));
// Kernel Initializer
function init () {
// Do initial sanity check and initialize data for the kernels.
// The sanity check should verify that the simd and nonSimd results
// are the same.
// It is recommended to do minimal object creation in the kernels
// themselves. If global data needs to be initialized, here would
// be the place to do it.
// If the sanity checks fails the kernels will not be executed
// Returns:
// true: First run (unoptimized) of the kernels passed
// false: First run (unoptimized) of the kernels failed
return simd (1) === nonSimd (1);
}
// Kernel Cleanup
function cleanup () {
// Do final sanity check and perform cleanup.
// This function is called when all the kernel iterations have been
// executed, so they should be in their final optimized version. The
// sanity check done during initialization will probably be of the
// initial unoptimized version.
// Returns:
// true: Last run (optimized) of the kernels passed
// false: last run (optimized) of the kernels failed
return simd (1) === nonSimd (1);
}
// SIMD version of the kernel
function simd (n) {
var s = 0;
for (var i = 0; i < n; ++i) {
s += i;
}
return s;
}
// Non SIMD version of the kernel
function nonSimd (n) {
var s = 0;
for (var i = 0; i < n; ++i) {
s += i;
}
return s;
}
} ());
@@ -1,77 +0,0 @@
// kmMat4AreEqual
(function () {
// Kernel configuration
var kernelConfig = {
kernelName: "kmMat4AreEqual",
kernelInit: init,
kernelCleanup: cleanup,
kernelSimd: simd,
kernelNonSimd: nonSimd,
kernelIterations: 10000
};
// Hook up to the harness
benchmarks.add(new Benchmark(kernelConfig));
// Benchmark data, initialization and kernel functions
var T1 = new cc.math.Matrix4();
var T2 = new cc.math.Matrix4();
var T1x4 = new cc.math.Matrix4();
var T2x4 = new cc.math.Matrix4();
var areEqual, areEqualSIMD;
function equals(A, B) {
for (var i = 0; i < 16; ++i) {
if (A[i] != B[i])
return false;
}
return true;
}
function init() {
T1.mat[0] = 1.0;
T1.mat[5] = 1.0;
T1.mat[10] = 1.0;
T1.mat[15] = 1.0;
T2.mat[0] = 1.0;
T2.mat[5] = 1.0;
T2.mat[10] = 1.0;
T2.mat[15] = 1.0;
T1x4.mat[0] = 1.0;
T1x4.mat[5] = 1.0;
T1x4.mat[10] = 1.0;
T1x4.mat[15] = 1.0;
T2x4.mat[0] = 1.0;
T2x4.mat[5] = 1.0;
T2x4.mat[10] = 1.0;
T2x4.mat[15] = 1.0;
nonSimd(1);
simd(1);
return equals(T1.mat, T1x4.mat) && equals(T2.mat, T2x4.mat) && (areEqual === areEqualSIMD);
}
function cleanup() {
return init(); // Sanity checking before and after are the same
}
function nonSimd(n) {
for (var i = 0; i < n; i++) {
areEqual = T1.equals(T2);
}
}
function simd(n) {
for (var i = 0; i < n; i++) {
areEqualSIMD = T1x4.equalsSIMD(T2x4);
}
}
} ());
@@ -1,68 +0,0 @@
// kmMat4Assign
(function () {
// Kernel configuration
var kernelConfig = {
kernelName: "kmMat4Assign",
kernelInit: init,
kernelCleanup: cleanup,
kernelSimd: simd,
kernelNonSimd: nonSimd,
kernelIterations: 10000
};
// Hook up to the harness
benchmarks.add(new Benchmark(kernelConfig));
// Benchmark data, initialization and kernel functions
var T1 = new cc.math.Matrix4();
var T2 = new cc.math.Matrix4();
var T1x4 = new cc.math.Matrix4();
var T2x4 = new cc.math.Matrix4();
function equals(A, B) {
for (var i = 0; i < 16; ++i) {
if (A[i] != B[i])
return false;
}
return true;
}
function init() {
T1.mat[0] = 1.0;
T1.mat[5] = 1.0;
T1.mat[10] = 1.0;
T1.mat[15] = 1.0;
T1x4.mat[0] = 1.0;
T1x4.mat[5] = 1.0;
T1x4.mat[10] = 1.0;
T1x4.mat[15] = 1.0;
nonSimd(1);
simd(1);
return equals(T1.mat, T1x4.mat) && equals(T2.mat, T2x4.mat);
}
function cleanup() {
return init(); // Sanity checking before and after are the same
}
function nonSimd(n) {
for (var i = 0; i < n; i++) {
//cc.math.mat4Assign(T2, T1);
T2.assignFrom(T1);
}
}
function simd(n) {
for (var i = 0; i < n; i++) {
//cc.math.mat4AssignSIMD(T2x4, T1x4);
T2x4.assignFromSIMD(T1x4);
}
}
} ());
@@ -1,116 +0,0 @@
// kmMat4Inverse
(function () {
// Kernel configuration
var kernelConfig = {
kernelName: "kmMat4Inverse",
kernelInit: init,
kernelCleanup: cleanup,
kernelSimd: simd,
kernelNonSimd: nonSimd,
kernelIterations: 10000
};
// Hook up to the harness
benchmarks.add(new Benchmark(kernelConfig));
// Benchmark data, initialization and kernel functions
var src = new cc.math.Matrix4();
var dst = new cc.math.Matrix4();
var srcx4 = new cc.math.Matrix4();
var dstx4 = new cc.math.Matrix4();
var ident = new Float32Array(
[1,0,0,0,
0,1,0,0,
0,0,1,0,
0,0,0,1]);
function equals(A, B) {
for (var i = 0; i < 16; ++i) {
if (Math.abs (A[i] - B[i]) > 5)
return false;
}
return true;
}
function initMatrix(matrix) {
// These values were chosen somewhat randomly, but they will at least yield a solution.
matrix [0] = 0; matrix[1] = 1; matrix[2] = 2; matrix[3] = 3;
matrix [4] = -1; matrix[5] = -2; matrix[6] = -3; matrix[7] = -4;
matrix [8] = 0; matrix[9] = 0; matrix[10] = 2; matrix[11] = 3;
matrix [12] = -1; matrix[13] = -2; matrix[14] = 0; matrix[15] = -4;
}
function mulMatrix(dst, op1, op2) {
for (var r = 0; r < 4; ++r) {
for (var c = 0; c < 4; ++c) {
var ri = 4*r;
dst[ri + c] = op1[ri]*op2[c] + op1[ri+1]*op2[c+4] + op1[ri+2]*op2[c+8] + op1[ri+3]*op2[c+12];
}
}
}
function printMatrix(matrix, str) {
print('--------matrix ' + str + '----------');
for (var r = 0; r < 4; ++r) {
var str = "";
var ri = r*4;
for (var c = 0; c < 4; ++c) {
var value = matrix[ri + c];
str += " " + value.toFixed(2);
}
print(str);
}
}
function checkMatrix(src, dst) {
// when multiplied with the src matrix it should yield the identity matrix
var tmp = new Float32Array(16);
mulMatrix(tmp, src, dst);
for (var i = 0; i < 16; ++i) {
if (Math.abs (tmp[i] - ident[i]) > 0.00001) {
return false;
}
}
return true;
}
function init() {
initMatrix(src.mat);
// printMatrix(src);
nonSimd(1);
// printMatrix(dst);
if (!checkMatrix(src.mat, dst.mat)) {
return false;
}
initMatrix(srcx4.mat);
simd(1);
// printMatrix(dst);
if (!checkMatrix(srcx4.mat, dstx4.mat)) {
return false;
}
return true;
}
function cleanup() {
return init(); // Sanity checking before and after are the same
}
function nonSimd(n) {
for (var i = 0; i < n; i++) {
//cc.math.mat4Inverse(dst, src);
dst = src.inverse();
}
}
function simd(n) {
for (var i = 0; i < n; i++) {
//cc.math.mat4InverseSIMD(dstx4, srcx4);
dstx4 = srcx4.inverseSIMD();
}
}
} ());
@@ -1,65 +0,0 @@
// kmMat4IsIdentity
(function () {
// Kernel configuration
var kernelConfig = {
kernelName: "kmMat4IsIdentity",
kernelInit: init,
kernelCleanup: cleanup,
kernelSimd: simd,
kernelNonSimd: nonSimd,
kernelIterations: 10000
};
// Hook up to the harness
benchmarks.add(new Benchmark(kernelConfig));
// Benchmark data, initialization and kernel functions
var T1 = new cc.math.Matrix4();
var T1x4 = new cc.math.Matrix4();
var isIdentity, isIdentitySIMD;
function equals(A, B) {
for (var i = 0; i < 16; ++i) {
if (A[i] != B[i])
return false;
}
return true;
}
function init() {
T1.mat[0] = 1.0;
T1.mat[5] = 1.0;
T1.mat[10] = 1.0;
T1.mat[15] = 1.0;
T1x4.mat[0] = 1.0;
T1x4.mat[5] = 1.0;
T1x4.mat[10] = 1.0;
T1x4.mat[15] = 1.0;
nonSimd(1);
simd(1);
return equals(T1.mat, T1x4.mat) && (isIdentity === isIdentitySIMD);
}
function cleanup() {
return init(); // Sanity checking before and after are the same
}
function nonSimd(n) {
for (var i = 0; i < n; i++) {
isIdentity = T1.isIdentity();
}
}
function simd(n) {
for (var i = 0; i < n; i++) {
isIdentitySIMD = T1x4.isIdentitySIMD();
}
}
} ());
@@ -1,94 +0,0 @@
// kmMat4LookAt
(function () {
// Kernel configuration
var kernelConfig = {
kernelName: "kmMat4LookAt",
kernelInit: init,
kernelCleanup: cleanup,
kernelSimd: simd,
kernelNonSimd: nonSimd,
kernelIterations: 10000
};
// Hook up to the harness
benchmarks.add(new Benchmark(kernelConfig));
// Benchmark data, initialization and kernel functions
var eye = new cc.math.Vec3(), center = new cc.math.Vec3(), up = new cc.math.Vec3();
var T1 = new cc.math.Matrix4();
var eye1 = new cc.math.Vec3(), center1 = new cc.math.Vec3(), up1 = new cc.math.Vec3();
var T1x4 = new cc.math.Matrix4();
function printMatrix(matrix) {
print('--------matrix----------');
for (var r = 0; r < 4; ++r) {
var str = "";
var ri = r*4;
for (var c = 0; c < 4; ++c) {
var value = matrix[ri + c];
str += " " + value.toFixed(2);
}
print(str);
}
}
function equals(A, B) {
for (var i = 0; i < 16; ++i) {
if (Math.abs (A[i] - B[i]) > 0.001) {
return false;
}
}
return true;
}
function init() {
eye.fill(0, 1, 2);
center.fill(2, 1, 0);
up.fill(1, 1, 1);
eye1.fill(0, 1, 2);
center1.fill(2, 1, 0);
up1.fill(1, 1, 1);
/*
eye1.data[0] = 0;
eye1.data[1] = 1;
eye1.data[2] = 2;
center1.data[0] = 2;
center1.data[1] = 1;
center1.data[2] = 0;
up1.data[0] = 1;
up1.data[1] = 1;
up1.data[2] = 1;
*/
nonSimd(1);
//printMatrix(T1.mat);
simd(1);
//printMatrix(T1x4.mat);
return equals(T1.mat, T1x4.mat);
}
function cleanup() {
return init(); // Sanity checking before and after are the same
}
function nonSimd(n) {
for (var i = 0; i < n; i++) {
//cc.math.mat4LookAt(T1, eye, center, up);
T1.lookAt(eye, center, up);
}
}
function simd(n) {
for (var i = 0; i < n; i++) {
//cc.math.mat4LookAtSIMD(T1x4, eye1, center1, up1);
T1x4.lookAtSIMD(eye1, center1, up1);
}
}
} ());
@@ -1,74 +0,0 @@
// kmMat4Multiply
(function () {
// Kernel configuration
var kernelConfig = {
kernelName: "kmMat4Multiply",
kernelInit: init,
kernelCleanup: cleanup,
kernelSimd: simd,
kernelNonSimd: nonSimd,
kernelIterations: 10000
};
// Hook up to the harness
benchmarks.add(new Benchmark(kernelConfig));
// Benchmark data, initialization and kernel functions
var T1 = new cc.math.Matrix4();
var T2 = new cc.math.Matrix4();
var T1x4 = new cc.math.Matrix4();
var T2x4 = new cc.math.Matrix4();
function equals(A, B) {
for (var i = 0; i < 16; ++i) {
if (A[i] != B[i])
return false;
}
return true;
}
function init() {
T1.mat[0] = 1.0;
T1.mat[5] = 1.0;
T1.mat[10] = 1.0;
T1.mat[15] = 1.0;
T2.mat[0] = 1.0;
T2.mat[5] = 1.0;
T2.mat[10] = 1.0;
T2.mat[15] = 1.0;
T1x4.mat[0] = 1.0;
T1x4.mat[5] = 1.0;
T1x4.mat[10] = 1.0;
T1x4.mat[15] = 1.0;
T2x4.mat[0] = 1.0;
T2x4.mat[5] = 1.0;
T2x4.mat[10] = 1.0;
T2x4.mat[15] = 1.0;
nonSimd(1);
simd(1);
return equals(T1.mat, T1x4.mat) && equals(T2.mat, T2x4.mat);
}
function cleanup() {
return init(); // Sanity checking before and after are the same
}
function nonSimd(n) {
for (var i = 0; i < n; i++) {
T1.multiply(T2);
}
}
function simd(n) {
for (var i = 0; i < n; i++) {
T1x4.multiplySIMD(T2x4);
}
}
} ());
@@ -1,82 +0,0 @@
// kmMat4Transpose
(function () {
// Kernel configuration
var kernelConfig = {
kernelName: "kmMat4Transpose",
kernelInit: init,
kernelCleanup: cleanup,
kernelSimd: simd,
kernelNonSimd: nonSimd,
kernelIterations: 10000
};
// Hook up to the harness
benchmarks.add(new Benchmark(kernelConfig));
// Benchmark data, initialization and kernel functions
var T1 = new cc.math.Matrix4();
var T2 = new cc.math.Matrix4();
var T1x4 = new cc.math.Matrix4();
var T2x4 = new cc.math.Matrix4();
function equals(A, B) {
for (var i = 0; i < 16; ++i) {
if (A[i] != B[i])
return false;
}
return true;
}
function printMatrix(matrix) {
print('--------matrix----------');
for (var r = 0; r < 4; ++r) {
var str = "";
var ri = r*4;
for (var c = 0; c < 4; ++c) {
var value = matrix[ri + c];
str += " " + value.toFixed(2);
}
print(str);
}
}
function init() {
T1.mat [0] = 0; T1.mat[1] = 1; T1.mat[2] = 2; T1.mat[3] = 3;
T1.mat [4] = -1; T1.mat[5] = -2; T1.mat[6] = -3; T1.mat[7] = -4;
T1.mat [8] = 0; T1.mat[9] = 0; T1.mat[10] = 2; T1.mat[11] = 3;
T1.mat [12] = -1; T1.mat[13] = -2; T1.mat[14] = 0; T1.mat[15] = -4;
T1x4.mat [0] = 0; T1x4.mat[1] = 1; T1x4.mat[2] = 2; T1x4.mat[3] = 3;
T1x4.mat [4] = -1; T1x4.mat[5] = -2; T1x4.mat[6] = -3; T1x4.mat[7] = -4;
T1x4.mat [8] = 0; T1x4.mat[9] = 0; T1x4.mat[10] = 2; T1x4.mat[11] = 3;
T1x4.mat [12] = -1; T1x4.mat[13] = -2; T1x4.mat[14] = 0; T1x4.mat[15] = -4;
nonSimd(1);
//printMatrix(T2.mat);
simd(1);
//printMatrix(T2x4.mat);
return equals(T1.mat, T1x4.mat) && equals(T2.mat, T2x4.mat);
}
function cleanup() {
return init(); // Sanity checking before and after are the same
}
function nonSimd(n) {
for (var i = 0; i < n; i++) {
T2 = T1.transpose();
//T1.transpose();
}
}
function simd(n) {
for (var i = 0; i < n; i++) {
T2x4 = T1x4.transposeSIMD();
//T1x4.transposeSIMD();
}
}
} ());
@@ -1,65 +0,0 @@
// kmVec3TransformCoord
(function () {
// Kernel configuration
var kernelConfig = {
kernelName: "kmVec3TransformCoord",
kernelInit: init,
kernelCleanup: cleanup,
kernelSimd: simd,
kernelNonSimd: nonSimd,
kernelIterations: 10000
};
// Hook up to the harness
benchmarks.add(new Benchmark(kernelConfig));
// Benchmark data, initialization and kernel functions
var V = new cc.math.Vec3();
var T = new cc.math.Matrix4();
var Out = new cc.math.Vec3();
var Vx4 = new cc.math.Vec3();
var Tx4 = new cc.math.Matrix4();
var Outx4 = new cc.math.Vec3();
function init() {
T.mat[0] = 1.0;
T.mat[5] = 1.0;
T.mat[10] = 1.0;
T.mat[15] = 1.0;
V.fill(0.0, 1.0, 0.0);
Tx4.mat[0] = 1.0;
Tx4.mat[5] = 1.0;
Tx4.mat[10] = 1.0;
Tx4.mat[15] = 1.0;
Vx4.fill(0.0, 1.0, 0.0);
nonSimd(1);
simd(1);
//console.log(V);
//console.log(Vx4);
return V.equals(Vx4);
}
function cleanup() {
return init(); // Sanity checking before and after are the same
}
function nonSimd(n) {
for (var i = 0; i < n; i++) {
V.transformCoord(T);
}
}
function simd(n) {
for (var i = 0; i < n; i++) {
Vx4.transformCoordSIMD(Tx4);
}
}
} ());
-40
View File
@@ -1,40 +0,0 @@
"use strict";
var cc = {};
load ('base.js');
load ('../utility.js');
load ('../vec3.js');
load ('../vec4.js');
load ('../mat4.js');
load ('../vec3SIMD.js');
load ('../mat4SIMD.js');
// load individual benchmarks
load ('kernel-template.js');
load ('kmMat4Multiply.js');
load ('kmMat4Assign.js');
load ('kmMat4AreEqual.js');
load ('kmMat4Inverse.js');
load ('kmMat4IsIdentity.js');
load ('kmMat4Transpose.js');
load ('kmMat4LookAt.js');
load ('kmVec3TransformCoord.js');
function printResult (str) {
print (str);
}
function printError (str) {
print (str);
}
function printScore (str) {
print (str);
}
benchmarks.runAll ({notifyResult: printResult,
notifyError: printError,
notifyScore: printScore},
true);
@@ -1,80 +0,0 @@
var echo = document.getElementById('echo');
function printResult(str) {
console.log(str);
echo.innerHTML += str + '<br>';
}
function printError(str) {
console.log(str);
echo.innerHTML += str + '<br>';
}
function printScore(str) {
console.log(str);
echo.innerHTML += str + '<br>';
}
var timeData = {
labels: [],
datasets: [
{
labels: 'Non-SIMD',
fillColor: "rgba(220,220,220,0.5)",
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: []
},
{
labels: 'SIMD',
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: []
}
]
};
var speedupData ={
labels: [],
datasets: [
{
labels: 'SIMD',
fillColor: "rgba(151,187,205,0.5)",
strokeColor: "rgba(151,187,205,0.8)",
highlightFill: "rgba(151,187,205,0.75)",
highlightStroke: "rgba(151,187,205,1)",
data: []
}
]
};
window.onload = function() {
if (typeof(SIMD) === 'undefined') {
var head = document.getElementById('head');
head.innerHTML = 'SIMD is not implemented in your browser, stops.';
return;
}
console.log('Running benchmarks.');
benchmarks.runAll({notifyResult: printResult,
notifyError: printError,
notifyScore: printScore,
timeData: timeData,
speedupData: speedupData}, true);
document.getElementById('head').innerHTML = 'Results';
document.getElementById('time').innerHTML = 'Time';
document.getElementById('speedup').innerHTML = 'Speedup';
var ctx1 = document.getElementById("canvasTime").getContext("2d");
window.Bar1 = new Chart(ctx1).Bar(timeData, {
scaleLabel: "<%=value%>ms",
responsive: true
});
var ctx2 = document.getElementById("canvasSpeedup").getContext("2d");
window.Bar2 = new Chart(ctx2).Bar(speedupData, {
scaleLabel: " <%=value%>",
responsive: true
});
console.log('Benchmarks completed.');
};
-54
View File
@@ -1,54 +0,0 @@
/**
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
Copyright (c) 2008, Luke Benstead.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* <p>The main namespace of Cocos2d-html5's math library, <br/>
* all math core classes, functions, properties and constants are defined in this namespace</p>
* @namespace
* @name cc.math
*/
cc.math = cc.math || {};
//cc.kmPIOver180 = 0.017453; please use cc.macro.RAD
//cc.kmPIUnder180 = 57.295779; please use cc.macro.DEG
cc.math.EPSILON = 1.0 / 64.0; //cc.kmEpsilon
/**
* Returns the square of s (e.g. s*s)
* @param {Number} s
*/
cc.math.square = function(s){
return s*s;
};
cc.math.almostEqual = function(lhs,rhs){
return (lhs + cc.math.EPSILON > rhs && lhs - cc.math.EPSILON < rhs);
};
-111
View File
@@ -1,111 +0,0 @@
/**
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
Copyright (c) 2008, Luke Benstead.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
cc.math.Vec2 = function (x, y) {
if(y === undefined){
this.x = x.x;
this.y = x.y;
}else{
this.x = x || 0;
this.y = y || 0;
}
};
var proto = cc.math.Vec2.prototype;
proto.fill = function(x, y){ // = cc.kmVec2Fill
this.x = x;
this.y = y;
};
proto.length = function(){ // = cc.kmVec2Length
return Math.sqrt(cc.math.square(this.x) + cc.math.square(this.y));
};
proto.lengthSq = function(){ // = cc.kmVec2LengthSq
return cc.math.square(this.x) + cc.math.square(this.y);
};
proto.normalize = function(){ // = cc.kmVec2Normalize
var l = 1.0 / this.length();
this.x *= l;
this.y *= l;
return this;
};
cc.math.Vec2.add = function (pOut, pV1, pV2) { // = cc.kmVec2Add
pOut.x = pV1.x + pV2.x;
pOut.y = pV1.y + pV2.y;
return pOut
};
proto.add = function(vec){ // = cc.kmVec2Add
this.x += vec.x;
this.y += vec.y;
return this;
};
proto.dot = function (vec) { //cc.kmVec2Dot
return this.x * vec.x + this.y * vec.y;
};
cc.math.Vec2.subtract = function (pOut, pV1, pV2) { // = cc.kmVec2Subtract
pOut.x = pV1.x - pV2.x;
pOut.y = pV1.y - pV2.y;
return pOut;
};
proto.subtract = function(vec){ // = cc.kmVec2Subtract
this.x -= vec.x;
this.y -= vec.y;
return this;
};
proto.transform = function (mat3) { // = cc.kmVec2Transform
var x = this.x, y = this.y;
this.x = x * mat3.mat[0] + y * mat3.mat[3] + mat3.mat[6];
this.y = x * mat3.mat[1] + y * mat3.mat[4] + mat3.mat[7];
return this;
};
cc.math.Vec2.scale = function (pOut, pIn, s) { // = cc.kmVec2Scale
pOut.x = pIn.x * s;
pOut.y = pIn.y * s;
return pOut;
};
proto.scale = function(s) { // = cc.kmVec2Scale
this.x *= s;
this.y *= s;
return this;
};
proto.equals = function (vec) { // = cc.kmVec2AreEqual
return (this.x < vec.x + cc.math.EPSILON && this.x > vec.x - cc.math.EPSILON) &&
(this.y < vec.y + cc.math.EPSILON && this.y > vec.y - cc.math.EPSILON);
};
-189
View File
@@ -1,189 +0,0 @@
/**
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
Copyright (c) 2008, Luke Benstead.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
cc.math.Vec3 = cc.math.Vec3 = function (x, y, z) {
if(x && y === undefined){
this.x = x.x;
this.y = x.y;
this.z = x.z;
} else {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
}
};
cc.math.vec3 = function(x, y, z){
return new cc.math.Vec3(x, y, z);
};
var proto = cc.math.Vec3.prototype;
proto.fill = function (x, y, z) { // =cc.math.Vec3Fill
if (x && y === undefined) {
this.x = x.x;
this.y = x.y;
this.z = x.z;
} else {
this.x = x;
this.y = y;
this.z = z;
}
return this;
};
proto.length = function () { //=cc.math.Vec3Length
return Math.sqrt(cc.math.square(this.x) + cc.math.square(this.y) + cc.math.square(this.z));
};
proto.lengthSq = function () { //=cc.math.Vec3LengthSq
return cc.math.square(this.x) + cc.math.square(this.y) + cc.math.square(this.z)
};
proto.normalize = function () { //= cc.math.Vec3Normalize
var l = 1.0 / this.length();
this.x *= l;
this.y *= l;
this.z *= l;
return this;
};
proto.cross = function (vec3) { //= cc.math.Vec3Cross
var x = this.x, y = this.y, z = this.z;
this.x = (y * vec3.z) - (z * vec3.y);
this.y = (z * vec3.x) - (x * vec3.z);
this.z = (x * vec3.y) - (y * vec3.x);
return this;
};
proto.dot = function (vec) { //= cc.math.Vec3Dot
return ( this.x * vec.x + this.y * vec.y + this.z * vec.z );
};
proto.add = function(vec){ //= cc.math.Vec3Add
this.x += vec.x;
this.y += vec.y;
this.z += vec.z;
return this;
};
proto.subtract = function (vec) { // = cc.math.Vec3Subtract
this.x -= vec.x;
this.y -= vec.y;
this.z -= vec.z;
return this;
};
proto.transform = function (mat4) { // = cc.math.Vec3Transform
var x = this.x, y = this.y, z = this.z, mat = mat4.mat;
this.x = x * mat[0] + y * mat[4] + z * mat[8] + mat[12];
this.y = x * mat[1] + y * mat[5] + z * mat[9] + mat[13];
this.z = x * mat[2] + y * mat[6] + z * mat[10] + mat[14];
return this;
};
proto.transformNormal = function(mat4){
/*
a = (Vx, Vy, Vz, 0)
b = (a×M)T
Out = (bx, by, bz)
*/
//Omits the translation, only scaling + rotating
var x = this.x, y = this.y, z = this.z, mat = mat4.mat;
this.x = x * mat[0] + y * mat[4] + z * mat[8];
this.y = x * mat[1] + y * mat[5] + z * mat[9];
this.z = x * mat[2] + y * mat[6] + z * mat[10];
return this;
};
proto.transformCoord = function(mat4){ // = cc.math.Vec3TransformCoord
/*
a = (Vx, Vy, Vz, 1)
b = (a×M)T
Out = 1⁄bw(bx, by, bz)
*/
var v = new cc.math.Vec4(this.x, this.y, this.z, 1.0);
v.transform(mat4);
this.x = v.x / v.w;
this.y = v.y / v.w;
this.z = v.z / v.w;
return this;
};
proto.scale = function(scale){ // = cc.math.Vec3Scale
this.x *= scale;
this.y *= scale;
this.z *= scale;
return this;
};
proto.equals = function(vec){ // = cc.math.Vec3AreEqual
var EPSILON = cc.math.EPSILON;
return (this.x < (vec.x + EPSILON) && this.x > (vec.x - EPSILON)) &&
(this.y < (vec.y + EPSILON) && this.y > (vec.y - EPSILON)) &&
(this.z < (vec.z + EPSILON) && this.z > (vec.z - EPSILON));
};
proto.inverseTransform = function(mat4){ //= cc.math.Vec3InverseTransform
var mat = mat4.mat;
var v1 = new cc.math.Vec3(this.x - mat[12], this.y - mat[13], this.z - mat[14]);
this.x = v1.x * mat[0] + v1.y * mat[1] + v1.z * mat[2];
this.y = v1.x * mat[4] + v1.y * mat[5] + v1.z * mat[6];
this.z = v1.x * mat[8] + v1.y * mat[9] + v1.z * mat[10];
return this;
};
proto.inverseTransformNormal = function(mat4){ // = cc.math.Vec3InverseTransformNormal
var x = this.x, y = this.y, z = this.z, mat = mat4.mat;
this.x = x * mat[0] + y * mat[1] + z * mat[2];
this.y = x * mat[4] + y * mat[5] + z * mat[6];
this.z = x * mat[8] + y * mat[9] + z * mat[10];
return this;
};
proto.assignFrom = function(vec){
if(!vec)
return this;
this.x = vec.x;
this.y = vec.y;
this.z = vec.z;
return this;
};
cc.math.Vec3.zero = function(vec){ // = cc.math.Vec3Zero
vec.x = vec.y = vec.z = 0.0;
return vec;
};
proto.toTypeArray = function(){ //cc.math.Vec3ToTypeArray
var tyArr = new Float32Array(3);
tyArr[0] = this.x;
tyArr[1] = this.y;
tyArr[2] = this.z;
return tyArr;
};
-51
View File
@@ -1,51 +0,0 @@
/**
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
Copyright (c) 2008, Luke Benstead.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
require('./vec3');
var proto = cc.math.Vec3.prototype;
proto.transformCoordSIMD = function(mat4){
var vec = SIMD.float32x4(this.x, this.y, this.z, 0.0);
var mat0 = SIMD.float32x4.load(mat4.mat, 0);
var mat1 = SIMD.float32x4.load(mat4.mat, 4);
var mat2 = SIMD.float32x4.load(mat4.mat, 8);
var mat3 = SIMD.float32x4.load(mat4.mat, 12);
//cc.kmVec4Transform(v, inV,pM);
var out = SIMD.float32x4.add(
SIMD.float32x4.add(SIMD.float32x4.mul(mat0, SIMD.float32x4.swizzle(vec, 0, 0, 0, 0)),
SIMD.float32x4.mul(mat1, SIMD.float32x4.swizzle(vec, 1, 1, 1, 1))),
SIMD.float32x4.add(SIMD.float32x4.mul(mat2, SIMD.float32x4.swizzle(vec, 2, 2, 2, 2)),
mat3));
out = SIMD.float32x4.div(out, SIMD.float32x4.swizzle(out, 3, 3, 3, 3));
this.fill(out);
return this;
};
-153
View File
@@ -1,153 +0,0 @@
/**
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
Copyright (c) 2008, Luke Benstead.
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
cc.math.Vec4 = function (x, y, z, w) {
if (x && y === undefined) {
this.x = x.x;
this.y = x.y;
this.z = x.z;
this.w = x.w;
} else {
this.x = x || 0;
this.y = y || 0;
this.z = z || 0;
this.w = w || 0;
}
};
var proto = cc.math.Vec4.prototype;
proto.fill = function (x, y, z, w) { //=cc.kmVec4Fill
if (x && y === undefined) {
this.x = x.x;
this.y = x.y;
this.z = x.z;
this.w = x.w;
} else {
this.x = x;
this.y = y;
this.z = z;
this.w = w;
}
};
proto.add = function(vec) { //cc.kmVec4Add
if(!vec)
return this;
this.x += vec.x;
this.y += vec.y;
this.z += vec.z;
this.w += vec.w;
return this;
};
proto.dot = function(vec){ //cc.kmVec4Dot
return ( this.x * vec.x + this.y * vec.y + this.z * vec.z + this.w * vec.w );
};
proto.length = function(){ //=cc.kmVec4Length
return Math.sqrt(cc.math.square(this.x) + cc.math.square(this.y) + cc.math.square(this.z) + cc.math.square(this.w));
};
proto.lengthSq = function(){ //=cc.kmVec4LengthSq
return cc.math.square(this.x) + cc.math.square(this.y) + cc.math.square(this.z) + cc.math.square(this.w);
};
proto.lerp = function(vec, t){ //= cc.kmVec4Lerp
//not implemented
return this;
};
proto.normalize = function() { // cc.kmVec4Normalize
var l = 1.0 / this.length();
this.x *= l;
this.y *= l;
this.z *= l;
this.w *= l;
return this;
};
proto.scale = function(scale){ //= cc.kmVec4Scale
/// Scales a vector to the required length. This performs a Normalize before multiplying by S.
this.normalize();
this.x *= scale;
this.y *= scale;
this.z *= scale;
this.w *= scale;
return this;
};
proto.subtract = function(vec) {
this.x -= vec.x;
this.y -= vec.y;
this.z -= vec.z;
this.w -= vec.w;
};
proto.transform = function(mat4) {
var x = this.x, y = this.y, z = this.z, w = this.w, mat = mat4.mat;
this.x = x * mat[0] + y * mat[4] + z * mat[8] + w * mat[12];
this.y = x * mat[1] + y * mat[5] + z * mat[9] + w * mat[13];
this.z = x * mat[2] + y * mat[6] + z * mat[10] + w * mat[14];
this.w = x * mat[3] + y * mat[7] + z * mat[11] + w * mat[15];
return this;
};
cc.math.Vec4.transformArray = function(vecArray, mat4){
var retArray = [];
for (var i = 0; i < vecArray.length; i++) {
var selVec = new cc.math.Vec4(vecArray[i]);
selVec.transform(mat4);
retArray.push(selVec);
}
return retArray;
};
proto.equals = function(vec){ //=cc.kmVec4AreEqual
var EPSILON = cc.math.EPSILON;
return (this.x < vec.x + EPSILON && this.x > vec.x - EPSILON) &&
(this.y < vec.y + EPSILON && this.y > vec.y - EPSILON) &&
(this.z < vec.z + EPSILON && this.z > vec.z - EPSILON) &&
(this.w < vec.w + EPSILON && this.w > vec.w - EPSILON);
};
proto.assignFrom = function(vec) { //= cc.kmVec4Assign
this.x = vec.x;
this.y = vec.y;
this.z = vec.z;
this.w = vec.w;
return this;
};
proto.toTypeArray = function(){ //cc.kmVec4ToTypeArray
var tyArr = new Float32Array(4);
tyArr[0] = this.x;
tyArr[1] = this.y;
tyArr[2] = this.z;
tyArr[3] = this.w;
return tyArr;
};
-796
View File
@@ -1,796 +0,0 @@
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
Copyright 2011 Jeff Lamarche
Copyright 2012 Goffredo Marocchi
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
var macro = cc.macro;
var math = cc.math;
/**
* Class that implements a WebGL program
* @class
* @extends cc._Class
*/
cc.GLProgram = cc._Class.extend(/** @lends cc.GLProgram# */{
// Uniform cache
_updateUniformLocation: function (location) {
if (!location)
return false;
var updated;
var element = this._hashForUniforms[location];
if (!element) {
element = [
arguments[1],
arguments[2],
arguments[3],
arguments[4]
];
this._hashForUniforms[location] = element;
updated = true;
} else {
updated = false;
var count = arguments.length-1;
for (var i = 0; i < count; ++i) {
if (arguments[i+1] !== element[i]) {
element[i] = arguments[i+1];
updated = true;
}
}
}
return updated;
},
_description: function () {
return "<CCGLProgram = " + this.toString() + " | Program = " + this._programObj.toString() + ", VertexShader = " +
this._vertShader.toString() + ", FragmentShader = " + this._fragShader.toString() + ">";
},
_compileShader: function (shader, type, source) {
if (!source || !shader)
return false;
var preStr = cc.GLProgram._isHighpSupported() ? "precision highp float;\n" : "precision mediump float;\n";
source = preStr
+ "uniform mat4 CC_PMatrix;\n"
+ "uniform mat4 CC_MVMatrix;\n"
+ "uniform mat4 CC_MVPMatrix;\n"
+ "uniform vec4 CC_Time;\n"
+ "uniform vec4 CC_SinTime;\n"
+ "uniform vec4 CC_CosTime;\n"
+ "uniform vec4 CC_Random01;\n"
+ "uniform sampler2D CC_Texture0;\n"
+ "//CC INCLUDES END\n" + source;
this._glContext.shaderSource(shader, source);
this._glContext.compileShader(shader);
var status = this._glContext.getShaderParameter(shader, this._glContext.COMPILE_STATUS);
if (!status) {
cc.logID(8100, this._glContext.getShaderSource(shader));
if (type === this._glContext.VERTEX_SHADER)
cc.log("cocos2d: \n" + this.vertexShaderLog());
else
cc.log("cocos2d: \n" + this.fragmentShaderLog());
}
return ( status === true );
},
/**
* Create a cc.GLProgram object
* @param {String} vShaderFileName
* @param {String} fShaderFileName
* @returns {cc.GLProgram}
*/
ctor: function (vShaderFileName, fShaderFileName, glContext) {
this._uniforms = {};
this._hashForUniforms = {};
this._glContext = glContext || cc._renderContext;
this._programObj = null;
this._vertShader = null;
this._fragShader = null;
this._usesTime = false;
this._projectionUpdated = -1;
vShaderFileName && fShaderFileName && this.init(vShaderFileName, fShaderFileName);
},
/**
* destroy program
*/
destroyProgram: function () {
this._vertShader = null;
this._fragShader = null;
this._uniforms = null;
this._hashForUniforms = null;
this._glContext.deleteProgram(this._programObj);
},
/**
* Initializes the cc.GLProgram with a vertex and fragment with string
* @param {String} vertShaderStr
* @param {String} fragShaderStr
* @return {Boolean}
*/
initWithVertexShaderByteArray: function (vertShaderStr, fragShaderStr) {
var locGL = this._glContext;
this._programObj = locGL.createProgram();
this._projectionUpdated = -1;
this._vertShader = null;
this._fragShader = null;
if (vertShaderStr) {
this._vertShader = locGL.createShader(locGL.VERTEX_SHADER);
if (!this._compileShader(this._vertShader, locGL.VERTEX_SHADER, vertShaderStr)) {
cc.logID(8101);
}
}
// Create and compile fragment shader
if (fragShaderStr) {
this._fragShader = locGL.createShader(locGL.FRAGMENT_SHADER);
if (!this._compileShader(this._fragShader, locGL.FRAGMENT_SHADER, fragShaderStr)) {
cc.logID(8102);
}
}
if (this._vertShader)
locGL.attachShader(this._programObj, this._vertShader);
if (this._fragShader)
locGL.attachShader(this._programObj, this._fragShader);
for (var key in this._hashForUniforms) {
delete this._hashForUniforms[key];
}
if (CC_DEV)
cc.checkGLErrorDebug();
return true;
},
/**
* Initializes the cc.GLProgram with a vertex and fragment with string
* @param {String} vertShaderStr
* @param {String} fragShaderStr
* @return {Boolean}
*/
initWithString: function (vertShaderStr, fragShaderStr) {
return this.initWithVertexShaderByteArray(vertShaderStr, fragShaderStr);
},
/**
* Initializes the CCGLProgram with a vertex and fragment with contents of filenames
* @param {String} vShaderFilename
* @param {String} fShaderFileName
* @return {Boolean}
*/
initWithVertexShaderFilename: function (vShaderFilename, fShaderFileName) {
var vertexSource = cc.loader.getRes(vShaderFilename);
if (!vertexSource) throw new Error(cc._getError(8106, vShaderFilename));
var fragmentSource = cc.loader.getRes(fShaderFileName);
if (!fragmentSource) throw new Error(cc._getError(8106, fShaderFileName));
return this.initWithVertexShaderByteArray(vertexSource, fragmentSource);
},
/**
* Initializes the CCGLProgram with a vertex and fragment with contents of filenames
* @param {String} vShaderFilename
* @param {String} fShaderFileName
* @return {Boolean}
*/
init: function (vShaderFilename, fShaderFileName) {
return this.initWithVertexShaderFilename(vShaderFilename, fShaderFileName);
},
/**
* It will add a new attribute to the shader
* @param {String} attributeName
* @param {Number} index
*/
addAttribute: function (attributeName, index) {
this._glContext.bindAttribLocation(this._programObj, index, attributeName);
},
/**
* links the glProgram
* @return {Boolean}
*/
link: function () {
if(!this._programObj) {
cc.logID(8103);
return false;
}
this._glContext.linkProgram(this._programObj);
if (this._vertShader)
this._glContext.deleteShader(this._vertShader);
if (this._fragShader)
this._glContext.deleteShader(this._fragShader);
this._vertShader = null;
this._fragShader = null;
if (cc.game.config[cc.game.CONFIG_KEY.debugMode]) {
var status = this._glContext.getProgramParameter(this._programObj, this._glContext.LINK_STATUS);
if (!status) {
cc.logID(8104, this._glContext.getProgramInfoLog(this._programObj));
cc.gl.deleteProgram(this._programObj);
this._programObj = null;
return false;
}
}
return true;
},
/**
* it will call gl.useProgram()
*/
use: function () {
cc.gl.useProgram(this._programObj);
},
/**
* It will create 4 uniforms:
* cc.macro.UNIFORM_PMATRIX
* cc.macro.UNIFORM_MVMATRIX
* cc.macro.UNIFORM_MVPMATRIX
* cc.macro.UNIFORM_SAMPLER
*/
updateUniforms: function () {
this._uniforms[macro.UNIFORM_PMATRIX] = this._glContext.getUniformLocation(this._programObj, macro.UNIFORM_PMATRIX_S);
this._uniforms[macro.UNIFORM_MVMATRIX] = this._glContext.getUniformLocation(this._programObj, macro.UNIFORM_MVMATRIX_S);
this._uniforms[macro.UNIFORM_MVPMATRIX] = this._glContext.getUniformLocation(this._programObj, macro.UNIFORM_MVPMATRIX_S);
this._uniforms[macro.UNIFORM_TIME] = this._glContext.getUniformLocation(this._programObj, macro.UNIFORM_TIME_S);
this._uniforms[macro.UNIFORM_SINTIME] = this._glContext.getUniformLocation(this._programObj, macro.UNIFORM_SINTIME_S);
this._uniforms[macro.UNIFORM_COSTIME] = this._glContext.getUniformLocation(this._programObj, macro.UNIFORM_COSTIME_S);
this._usesTime = (this._uniforms[macro.UNIFORM_TIME] != null || this._uniforms[macro.UNIFORM_SINTIME] != null || this._uniforms[macro.UNIFORM_COSTIME] != null);
this._uniforms[macro.UNIFORM_RANDOM01] = this._glContext.getUniformLocation(this._programObj, macro.UNIFORM_RANDOM01_S);
this._uniforms[macro.UNIFORM_SAMPLER] = this._glContext.getUniformLocation(this._programObj, macro.UNIFORM_SAMPLER_S);
this.use();
// Since sample most probably won't change, set it to 0 now.
this.setUniformLocationWith1i(this._uniforms[macro.UNIFORM_SAMPLER], 0);
},
_addUniformLocation: function (name) {
var location = this._glContext.getUniformLocation(this._programObj, name);
this._uniforms[name] = location;
},
/**
* calls retrieves the named uniform location for this shader program.
* @param {String} name
* @returns {Number}
*/
getUniformLocationForName: function (name) {
if (!name)
throw new Error(cc._getError(8107));
if (!this._programObj)
throw new Error(cc._getError(8108));
var location = this._uniforms[name] || this._glContext.getUniformLocation(this._programObj, name);
return location;
},
/**
* get uniform MVP matrix
* @returns {WebGLUniformLocation}
*/
getUniformMVPMatrix: function () {
return this._uniforms[macro.UNIFORM_MVPMATRIX];
},
/**
* get uniform sampler
* @returns {WebGLUniformLocation}
*/
getUniformSampler: function () {
return this._uniforms[macro.UNIFORM_SAMPLER];
},
/**
* calls glUniform1i only if the values are different than the previous call for this same shader program.
* @param {WebGLUniformLocation} location
* @param {Number} i1
*/
setUniformLocationWith1i: function (location, i1) {
var gl = this._glContext;
if (typeof location === 'string') {
var updated = this._updateUniformLocation(location, i1);
if (updated) {
var locObj = this.getUniformLocationForName(location);
gl.uniform1i(locObj, i1);
}
}
else {
gl.uniform1i(location, i1);
}
},
/**
* calls glUniform2i only if the values are different than the previous call for this same shader program.
* @param {WebGLUniformLocation} location
* @param {Number} i1
* @param {Number} i2
*/
setUniformLocationWith2i: function (location, i1, i2) {
var gl = this._glContext;
if (typeof location === 'string') {
var updated = this._updateUniformLocation(location, i1, i2);
if (updated) {
var locObj = this.getUniformLocationForName(location);
gl.uniform2i(locObj, i1, i2);
}
}
else {
gl.uniform2i(location, i1, i2);
}
},
/**
* calls glUniform3i only if the values are different than the previous call for this same shader program.
* @param {WebGLUniformLocation} location
* @param {Number} i1
* @param {Number} i2
* @param {Number} i3
*/
setUniformLocationWith3i: function (location, i1, i2, i3) {
var gl = this._glContext;
if (typeof location === 'string') {
var updated = this._updateUniformLocation(location, i1, i2, i3);
if (updated) {
var locObj = this.getUniformLocationForName(location);
gl.uniform3i(locObj, i1, i2, i3);
}
}
else {
gl.uniform3i(location, i1, i2, i3);
}
},
/**
* calls glUniform4i only if the values are different than the previous call for this same shader program.
* @param {WebGLUniformLocation} location
* @param {Number} i1
* @param {Number} i2
* @param {Number} i3
* @param {Number} i4
*/
setUniformLocationWith4i: function (location, i1, i2, i3, i4) {
var gl = this._glContext;
if (typeof location === 'string') {
var updated = this._updateUniformLocation(location, i1, i2, i3, i4);
if (updated) {
var locObj = this.getUniformLocationForName(location);
gl.uniform4i(locObj, i1, i2, i3, i4);
}
}
else {
gl.uniform4i(location, i1, i2, i3, i4);
}
},
/**
* calls glUniform2iv only if the values are different than the previous call for this same shader program.
* @param {WebGLUniformLocation} location
* @param {Int32Array} intArray
* @param {Number} numberOfArrays
*/
setUniformLocationWith2iv: function (location, intArray) {
var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location;
this._glContext.uniform2iv(locObj, intArray);
},
/**
* calls glUniform3iv only if the values are different than the previous call for this same shader program.
* @param {WebGLUniformLocation} location
* @param {Int32Array} intArray
* @param {Number} numberOfArrays
*/
setUniformLocationWith3iv:function(location, intArray){
var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location;
this._glContext.uniform3iv(locObj, intArray);
},
/**
* calls glUniform4iv only if the values are different than the previous call for this same shader program.
* @param {WebGLUniformLocation} location
* @param {Int32Array} intArray
*/
setUniformLocationWith4iv:function(location, intArray){
var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location;
this._glContext.uniform4iv(locObj, intArray);
},
/**
* calls glUniform1i only if the values are different than the previous call for this same shader program.
* @param {WebGLUniformLocation} location
* @param {Number} i1
*/
setUniformLocationI32: function (location, i1) {
this.setUniformLocationWith1i(location, i1);
},
/**
* calls glUniform1f only if the values are different than the previous call for this same shader program.
* @param {WebGLUniformLocation} location
* @param {Number} f1
*/
setUniformLocationWith1f: function (location, f1) {
var gl = this._glContext;
if (typeof location === 'string') {
var updated = this._updateUniformLocation(location, f1);
if (updated) {
var locObj = this.getUniformLocationForName(location);
gl.uniform1f(locObj, f1);
}
}
else {
gl.uniform1f(location, f1);
}
},
/**
* calls glUniform2f only if the values are different than the previous call for this same shader program.
* @param {WebGLUniformLocation} location
* @param {Number} f1
* @param {Number} f2
*/
setUniformLocationWith2f: function (location, f1, f2) {
var gl = this._glContext;
if (typeof location === 'string') {
var updated = this._updateUniformLocation(location, f1, f2);
if (updated) {
var locObj = this.getUniformLocationForName(location);
gl.uniform2f(locObj, f1, f2);
}
}
else {
gl.uniform2f(location, f1, f2);
}
},
/**
* calls glUniform3f only if the values are different than the previous call for this same shader program.
* @param {WebGLUniformLocation} location
* @param {Number} f1
* @param {Number} f2
* @param {Number} f3
*/
setUniformLocationWith3f: function (location, f1, f2, f3) {
var gl = this._glContext;
if (typeof location === 'string') {
var updated = this._updateUniformLocation(location, f1, f2, f3);
if (updated) {
var locObj = this.getUniformLocationForName(location);
gl.uniform3f(locObj, f1, f2, f3);
}
}
else {
gl.uniform3f(location, f1, f2, f3);
}
},
/**
* calls glUniform4f only if the values are different than the previous call for this same shader program.
* @param {WebGLUniformLocation} location
* @param {Number} f1
* @param {Number} f2
* @param {Number} f3
* @param {Number} f4
*/
setUniformLocationWith4f: function (location, f1, f2, f3, f4) {
var gl = this._glContext;
if (typeof location === 'string') {
var updated = this._updateUniformLocation(location, f1, f2, f3, f4);
if (updated) {
var locObj = this.getUniformLocationForName(location);
gl.uniform4f(locObj, f1, f2, f3, f4);
}
}
else {
gl.uniform4f(location, f1, f2, f3, f4);
}
},
/**
* calls glUniform2fv only if the values are different than the previous call for this same shader program.
* @param {WebGLUniformLocation} location
* @param {Float32Array} floatArray
*/
setUniformLocationWith2fv: function (location, floatArray) {
var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location;
this._glContext.uniform2fv(locObj, floatArray);
},
/**
* calls glUniform3fv only if the values are different than the previous call for this same shader program.
* @param {WebGLUniformLocation} location
* @param {Float32Array} floatArray
*/
setUniformLocationWith3fv: function (location, floatArray) {
var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location;
this._glContext.uniform3fv(locObj, floatArray);
},
/**
* calls glUniform4fv only if the values are different than the previous call for this same shader program.
* @param {WebGLUniformLocation} location
* @param {Float32Array} floatArray
*/
setUniformLocationWith4fv: function (location, floatArray) {
var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location;
this._glContext.uniform4fv(locObj, floatArray);
},
/**
* calls glUniformMatrix3fv only if the values are different than the previous call for this same shader
* @param {WebGLUniformLocation} location
* @param {Float32Array} matrixArray
*/
setUniformLocationWithMatrix3fv: function (location, matrixArray) {
var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location;
this._glContext.uniformMatrix3fv(locObj, false, matrixArray);
},
/**
* calls glUniformMatrix4fv only if the values are different than the previous call for this same shader program.
* @param {WebGLUniformLocation} location
* @param {Float32Array} matrixArray
*/
setUniformLocationWithMatrix4fv: function (location, matrixArray) {
var locObj = typeof location === 'string' ? this.getUniformLocationForName(location) : location;
this._glContext.uniformMatrix4fv(locObj, false, matrixArray);
},
setUniformLocationF32: function (p1, p2, p3, p4, p5) {
'use strict';
switch (arguments.length) {
case 0:
case 1:
return;
case 2:
this.setUniformLocationWith1f(p1, p2);
break;
case 3:
this.setUniformLocationWith2f(p1, p2, p3);
break;
case 4:
this.setUniformLocationWith3f(p1, p2, p3, p4);
break;
case 5:
this.setUniformLocationWith4f(p1, p2, p3, p4, p5);
break;
}
},
/**
* will update the builtin uniforms if they are different than the previous call for this same shader program.
*/
setUniformsForBuiltins: function () {
var matrixP = new math.Matrix4();
var matrixMV = new math.Matrix4();
var matrixMVP = new math.Matrix4();
math.glGetMatrix(math.KM_GL_PROJECTION, matrixP);
math.glGetMatrix(math.KM_GL_MODELVIEW, matrixMV);
math.mat4Multiply(matrixMVP, matrixP, matrixMV);
this.setUniformLocationWithMatrix4fv(this._uniforms[macro.UNIFORM_PMATRIX], matrixP.mat, 1);
this.setUniformLocationWithMatrix4fv(this._uniforms[macro.UNIFORM_MVMATRIX], matrixMV.mat, 1);
this.setUniformLocationWithMatrix4fv(this._uniforms[macro.UNIFORM_MVPMATRIX], matrixMVP.mat, 1);
if (this._usesTime) {
var director = cc.director;
// This doesn't give the most accurate global time value.
// Cocos2D doesn't store a high precision time value, so this will have to do.
// Getting Mach time per frame per shader using time could be extremely expensive.
var time = director.getTotalFrames() * director.getAnimationInterval();
this.setUniformLocationWith4f(this._uniforms[macro.UNIFORM_TIME], time / 10.0, time, time * 2, time * 4);
this.setUniformLocationWith4f(this._uniforms[macro.UNIFORM_SINTIME], time / 8.0, time / 4.0, time / 2.0, Math.sin(time));
this.setUniformLocationWith4f(this._uniforms[macro.UNIFORM_COSTIME], time / 8.0, time / 4.0, time / 2.0, Math.cos(time));
}
if (this._uniforms[macro.UNIFORM_RANDOM01] !== -1)
this.setUniformLocationWith4f(this._uniforms[macro.UNIFORM_RANDOM01], Math.random(), Math.random(), Math.random(), Math.random());
},
_setUniformsForBuiltinsForRenderer: function (node) {
if(!node || !node._renderCmd)
return;
var matrixP = new math.Matrix4();
//var matrixMV = new math.Matrix4();
var matrixMVP = new math.Matrix4();
math.glGetMatrix(math.KM_GL_PROJECTION, matrixP);
//math.glGetMatrix(math.KM_GL_MODELVIEW, node._stackMatrix);
math.mat4Multiply(matrixMVP, matrixP, node._renderCmd._stackMatrix);
this.setUniformLocationWithMatrix4fv(this._uniforms[macro.UNIFORM_PMATRIX], matrixP.mat, 1);
this.setUniformLocationWithMatrix4fv(this._uniforms[macro.UNIFORM_MVMATRIX], node._renderCmd._stackMatrix.mat, 1);
this.setUniformLocationWithMatrix4fv(this._uniforms[macro.UNIFORM_MVPMATRIX], matrixMVP.mat, 1);
if (this._usesTime) {
var director = cc.director;
// This doesn't give the most accurate global time value.
// Cocos2D doesn't store a high precision time value, so this will have to do.
// Getting Mach time per frame per shader using time could be extremely expensive.
var time = director.getTotalFrames() * director.getAnimationInterval();
this.setUniformLocationWith4f(this._uniforms[macro.UNIFORM_TIME], time / 10.0, time, time * 2, time * 4);
this.setUniformLocationWith4f(this._uniforms[macro.UNIFORM_SINTIME], time / 8.0, time / 4.0, time / 2.0, Math.sin(time));
this.setUniformLocationWith4f(this._uniforms[macro.UNIFORM_COSTIME], time / 8.0, time / 4.0, time / 2.0, Math.cos(time));
}
if (this._uniforms[macro.UNIFORM_RANDOM01] !== -1)
this.setUniformLocationWith4f(this._uniforms[macro.UNIFORM_RANDOM01], Math.random(), Math.random(), Math.random(), Math.random());
},
/**
* will update the MVP matrix on the MVP uniform if it is different than the previous call for this same shader program.
*/
setUniformForModelViewProjectionMatrix: function () {
this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_MVPMATRIX], false,
math.getMat4MultiplyValue(math.projection_matrix_stack.top, math.modelview_matrix_stack.top));
},
setUniformForModelViewProjectionMatrixWithMat4: function (swapMat4) {
math.mat4Multiply(swapMat4, math.projection_matrix_stack.top, math.modelview_matrix_stack.top);
this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_MVPMATRIX], false, swapMat4.mat);
},
setUniformForModelViewAndProjectionMatrixWithMat4: function () {
this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_MVMATRIX], false, math.modelview_matrix_stack.top.mat);
this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_PMATRIX], false, math.projection_matrix_stack.top.mat);
},
_setUniformForMVPMatrixWithMat4: function(modelViewMatrix){
if(!modelViewMatrix)
throw new Error(cc._getError(8109));
this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_MVMATRIX], false, modelViewMatrix.mat);
this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_PMATRIX], false, math.projection_matrix_stack.top.mat);
},
_updateProjectionUniform: function () {
var stack = math.projection_matrix_stack;
if (stack.lastUpdated !== this._projectionUpdated) {
this._glContext.uniformMatrix4fv(this._uniforms[macro.UNIFORM_PMATRIX], false, stack.top.mat);
this._projectionUpdated = stack.lastUpdated;
}
},
/**
* returns the vertexShader error log
* @return {String}
*/
vertexShaderLog: function () {
return this._glContext.getShaderInfoLog(this._vertShader);
},
/**
* returns the vertexShader error log
* @return {String}
*/
getVertexShaderLog: function () {
return this._glContext.getShaderInfoLog(this._vertShader);
},
/**
* returns the fragmentShader error log
* @returns {String}
*/
getFragmentShaderLog: function () {
return this._glContext.getShaderInfoLog(this._vertShader);
},
/**
* returns the fragmentShader error log
* @return {String}
*/
fragmentShaderLog: function () {
return this._glContext.getShaderInfoLog(this._fragShader);
},
/**
* returns the program error log
* @return {String}
*/
programLog: function () {
return this._glContext.getProgramInfoLog(this._programObj);
},
/**
* returns the program error log
* @return {String}
*/
getProgramLog: function () {
return this._glContext.getProgramInfoLog(this._programObj);
},
/**
* reload all shaders, this function is designed for android <br/>
* when opengl context lost, so don't call it.
*/
reset: function () {
this._vertShader = null;
this._fragShader = null;
this._uniforms.length = 0;
// it is already deallocated by android
//cc.gl.deleteProgram(m_uProgram);
this._glContext.deleteProgram(this._programObj);
this._programObj = null;
// Purge uniform hash
for (var key in this._hashForUniforms) {
this._hashForUniforms[key].length = 0;
delete this._hashForUniforms[key];
}
},
/**
* get WebGLProgram object
* @return {WebGLProgram}
*/
getProgram: function () {
return this._programObj;
},
/**
* Currently JavaScript Bindings (JSB), in some cases, needs to use retain and release. This is a bug in JSB,
* and the ugly workaround is to use retain/release. So, these 2 methods were added to be compatible with JSB.
* This is a hack, and should be removed once JSB fixes the retain/release bug
*/
retain: function () {
},
release: function () {
}
});
cc.GLProgram._highpSupported = null;
cc.GLProgram._isHighpSupported = function () {
var ctx = cc._renderContext;
if (ctx.getShaderPrecisionFormat && cc.GLProgram._highpSupported == null) {
var highp = ctx.getShaderPrecisionFormat(ctx.FRAGMENT_SHADER, ctx.HIGH_FLOAT);
cc.GLProgram._highpSupported = highp.precision !== 0;
}
return cc.GLProgram._highpSupported;
};
-265
View File
@@ -1,265 +0,0 @@
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
var _currentProjectionMatrix = -1;
var macro = cc.macro;
var ENABLE_GL_STATE_CACHE = macro.ENABLE_GL_STATE_CACHE;
var MAX_ACTIVETEXTURE = 0,
_currentShaderProgram = 0,
_currentBoundTexture = null,
_blendingSource = 0,
_blendingDest = 0,
_GLServerState = 0;
if (ENABLE_GL_STATE_CACHE) {
MAX_ACTIVETEXTURE = 16;
_currentShaderProgram = -1;
_currentBoundTexture = new Array(MAX_ACTIVETEXTURE);
_blendingSource = -1;
_blendingDest = -1;
_GLServerState = 0;
}
// GL State Cache functions
cc.gl = {};
/*
* Invalidates the GL state cache.<br/>
* If cc.macro.ENABLE_GL_STATE_CACHE it will reset the GL state cache.
* @function
*/
cc.gl.invalidateStateCache = function () {
cc.math.glFreeAll();
_currentProjectionMatrix = -1;
if (ENABLE_GL_STATE_CACHE) {
_currentShaderProgram = -1;
for (var i = 0; i < MAX_ACTIVETEXTURE; i++) {
_currentBoundTexture[i] = null;
}
_blendingSource = -1;
_blendingDest = -1;
_GLServerState = 0;
}
};
/*
* Uses the GL program in case program is different than the current one.<br/>
* If cc.macro.ENABLE_GL_STATE_CACHE is disabled, it will use glContext.useProgram() directly.
* @function
* @param {WebGLProgram} program
*/
cc.gl.useProgram = ENABLE_GL_STATE_CACHE ? function (program) {
if (program !== _currentShaderProgram) {
_currentShaderProgram = program;
cc._renderContext.useProgram(program);
}
} : function (program) {
cc._renderContext.useProgram(program);
};
/*
* Deletes the GL program. If it is the one that is being used, it invalidates it.<br/>
* If cc.macro.ENABLE_GL_STATE_CACHE is disabled, it will use gl.deleteProgram() directly.
* @function
* @param {WebGLProgram} program
*/
cc.gl.deleteProgram = function (program) {
if (ENABLE_GL_STATE_CACHE) {
if (program === _currentShaderProgram)
_currentShaderProgram = -1;
}
gl.deleteProgram(program);
};
/**
* @function
* @param {Number} sfactor
* @param {Number} dfactor
*/
cc.gl.setBlending = function (sfactor, dfactor) {
var gl = cc._renderContext;
if ((sfactor === gl.ONE) && (dfactor === gl.ZERO)) {
gl.disable(gl.BLEND);
} else {
gl.enable(gl.BLEND);
gl.blendFunc(sfactor,dfactor);
//TODO need fix for WebGL
// gl.blendFuncSeparate(sfactor, dfactor, sfactor, dfactor);
}
};
/*
* Uses a blending function in case it not already used.<br/>
* If cc.macro.ENABLE_GL_STATE_CACHE is disabled, it will use glContext.blendFunc() directly.
* @function
* @param {Number} sfactor
* @param {Number} dfactor
*/
cc.gl.blendFunc = ENABLE_GL_STATE_CACHE ? function (sfactor, dfactor) {
if ((sfactor !== _blendingSource) || (dfactor !== _blendingDest)) {
_blendingSource = sfactor;
_blendingDest = dfactor;
cc.gl.setBlending(sfactor, dfactor);
}
} : cc.gl.setBlending;
/**
* @function
* @param {Number} sfactor
* @param {Number} dfactor
*/
cc.gl.blendFuncForParticle = function(sfactor, dfactor) {
if ((sfactor !== _blendingSource) || (dfactor !== _blendingDest)) {
_blendingSource = sfactor;
_blendingDest = dfactor;
var ctx = cc._renderContext;
if ((sfactor === ctx.ONE) && (dfactor === ctx.ZERO)) {
ctx.disable(ctx.BLEND);
} else {
ctx.enable(ctx.BLEND);
// TODO need fix for WebGL
// DO NOT TOUCH THIS, YOU MAY NOT BE ABLE TO FIX EVERYTHING
ctx.blendFuncSeparate(ctx.SRC_ALPHA, dfactor, sfactor, dfactor);
}
}
};
/**
* Resets the blending mode back to the cached state in case you used glBlendFuncSeparate() or glBlendEquation().<br/>
* If cc.macro.ENABLE_GL_STATE_CACHE is disabled, it will just set the default blending mode using GL_FUNC_ADD.
* @function
*/
cc.gl.blendResetToCache = function () {
var ctx = cc._renderContext;
ctx.blendEquation(ctx.FUNC_ADD);
if (ENABLE_GL_STATE_CACHE)
cc.gl.setBlending(_blendingSource, _blendingDest);
else
cc.gl.setBlending(ctx.BLEND_SRC, ctx.BLEND_DST);
};
/**
* sets the projection matrix as dirty
* @function
*/
cc.gl.setProjectionMatrixDirty = function () {
_currentProjectionMatrix = -1;
};
/**
* If the texture is not already bound, it binds it.<br/>
* If cc.macro.ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly.
* @function
* @param {Texture2D} texture
*/
cc.gl.bindTexture2D = function (texture) {
cc.gl.bindTexture2DN(0, texture);
};
/**
* If the texture is not already bound to a given unit, it binds it.<br/>
* If cc.macro.ENABLE_GL_STATE_CACHE is disabled, it will call glBindTexture() directly.
* @function
* @param {Number} textureUnit
* @param {Texture2D} texture
*/
cc.gl.bindTexture2DN = ENABLE_GL_STATE_CACHE ? function (textureUnit, texture) {
if (_currentBoundTexture[textureUnit] === texture)
return;
_currentBoundTexture[textureUnit] = texture;
var ctx = cc._renderContext;
ctx.activeTexture(ctx.TEXTURE0 + textureUnit);
if(texture)
ctx.bindTexture(ctx.TEXTURE_2D, texture._glID);
else
ctx.bindTexture(ctx.TEXTURE_2D, null);
} : function (textureUnit, texture) {
var ctx = cc._renderContext;
ctx.activeTexture(ctx.TEXTURE0 + textureUnit);
if(texture)
ctx.bindTexture(ctx.TEXTURE_2D, texture._glID);
else
ctx.bindTexture(ctx.TEXTURE_2D, null);
};
/**
* It will delete a given texture. If the texture was bound, it will invalidate the cached. <br/>
* If cc.macro.ENABLE_GL_STATE_CACHE is disabled, it will call glDeleteTextures() directly.
* @function
* @param {Texture2D} texture
*/
cc.gl.deleteTexture2D = function (texture) {
cc.gl.deleteTexture2DN(0, texture);
};
/**
* It will delete a given texture. If the texture was bound, it will invalidate the cached for the given texture unit.<br/>
* If cc.macro.ENABLE_GL_STATE_CACHE is disabled, it will call glDeleteTextures() directly.
* @function
* @param {Number} textureUnit
* @param {Texture2D} texture
*/
cc.gl.deleteTexture2DN = function (textureUnit, texture) {
if (ENABLE_GL_STATE_CACHE) {
if (texture === _currentBoundTexture[ textureUnit ])
_currentBoundTexture[ textureUnit ] = null;
}
cc._renderContext.deleteTexture(texture._glID);
};
/**
* It will enable / disable the server side GL states.<br/>
* If cc.macro.ENABLE_GL_STATE_CACHE is disabled, it will call glEnable() directly.
* @function
* @param {Number} flags
*/
cc.gl.enable = function (flags) {
if (ENABLE_GL_STATE_CACHE) {
/*var enabled;
*/
/* GL_BLEND */
/*
if ((enabled = (flags & cc.GL_BLEND)) != (_GLServerState & cc.GL_BLEND)) {
if (enabled) {
cc._renderContext.enable(cc._renderContext.BLEND);
_GLServerState |= cc.GL_BLEND;
} else {
cc._renderContext.disable(cc._renderContext.BLEND);
_GLServerState &= ~cc.GL_BLEND;
}
}*/
} else {
/*if ((flags & cc.GL_BLEND))
cc._renderContext.enable(cc._renderContext.BLEND);
else
cc._renderContext.disable(cc._renderContext.BLEND);*/
}
};
-265
View File
@@ -1,265 +0,0 @@
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2014 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
var shaders = cc.PresetShaders;
var macro = cc.macro;
/**
* cc.shaderCache is a singleton object that stores manages GL shaders
* @class
* @name cc.shaderCache
*/
cc.shaderCache = /** @lends cc.shaderCache# */{
/**
* Position Texture Color shader
* @public
* @constant
* @type {Number}
*/
TYPE_POSITION_TEXTURECOLOR: 0,
/**
* Position Texture Color alpha test
* @public
* @constant
* @type {Number}
*/
TYPE_POSITION_TEXTURECOLOR_ALPHATEST: 1,
/**
* Position, Color shader
* @public
* @constant
* @type {Number}
*/
TYPE_POSITION_COLOR: 2,
/**
* Position Texture shader
* @public
* @constant
* @type {Number}
*/
TYPE_POSITION_TEXTURE: 3,
/**
* Position, Texture attribs, 1 Color as uniform shader
* @public
* @constant
* @type {Number}
*/
TYPE_POSITION_TEXTURE_UCOLOR: 4,
/**
* Position Texture A8 Color shader
* @public
* @constant
* @type {Number}
*/
TYPE_POSITION_TEXTURE_A8COLOR: 5,
/**
* Position and 1 color passed as a uniform (to similate glColor4ub )
* @public
* @constant
* @type {Number}
*/
TYPE_POSITION_UCOLOR: 6,
/**
* @public
* @constant
* @type {Number}
*/
TYPE_POSITION_LENGTH_TEXTURECOLOR: 7,
/**
* Sprite Position Texture Color shader
* @public
* @constant
* @type {Number}
*/
TYPE_SPRITE_POSITION_TEXTURECOLOR: 8,
/**
* Sprite Position Texture Color alpha shader
* @public
* @constant
* @type {Number}
*/
TYPE_SPRITE_POSITION_TEXTURECOLOR_ALPHATEST: 9,
/**
* @public
* @constant
* @type {Number}
*/
TYPE_SPRITE_POSITION_COLOR: 10,
/**
* @public
* @constant
* @type {Number}
*/
TYPE_MAX: 10,
_programs: {},
_init: function () {
this.loadDefaultShaders();
return true;
},
_loadDefaultShader: function (program, type) {
switch (type) {
case macro.SHADER_POSITION_TEXTURECOLOR:
program.initWithVertexShaderByteArray(shaders.POSITION_TEXTURE_COLOR_VERT, shaders.POSITION_TEXTURE_COLOR_FRAG);
program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION);
program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR);
program.addAttribute(macro.ATTRIBUTE_NAME_TEX_COORD, macro.VERTEX_ATTRIB_TEX_COORDS);
break;
case macro.SHADER_SPRITE_POSITION_TEXTURECOLOR:
program.initWithVertexShaderByteArray(shaders.SPRITE_POSITION_TEXTURE_COLOR_VERT, shaders.POSITION_TEXTURE_COLOR_FRAG);
program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION);
program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR);
program.addAttribute(macro.ATTRIBUTE_NAME_TEX_COORD, macro.VERTEX_ATTRIB_TEX_COORDS);
break;
case macro.SHADER_POSITION_TEXTURECOLORALPHATEST:
program.initWithVertexShaderByteArray(shaders.POSITION_TEXTURE_COLOR_VERT, shaders.POSITION_TEXTURE_COLOR_ALPHATEST_FRAG);
program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION);
program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR);
program.addAttribute(macro.ATTRIBUTE_NAME_TEX_COORD, macro.VERTEX_ATTRIB_TEX_COORDS);
break;
case macro.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST:
program.initWithVertexShaderByteArray(shaders.SPRITE_POSITION_TEXTURE_COLOR_VERT, shaders.POSITION_TEXTURE_COLOR_ALPHATEST_FRAG);
program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION);
program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR);
program.addAttribute(macro.ATTRIBUTE_NAME_TEX_COORD, macro.VERTEX_ATTRIB_TEX_COORDS);
break;
case macro.SHADER_POSITION_COLOR:
program.initWithVertexShaderByteArray(shaders.POSITION_COLOR_VERT, shaders.POSITION_COLOR_FRAG);
program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION);
program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR);
break;
case macro.SHADER_SPRITE_POSITION_COLOR:
program.initWithVertexShaderByteArray(shaders.SPRITE_POSITION_COLOR_VERT, shaders.POSITION_COLOR_FRAG);
program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION);
program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR);
break;
case macro.SHADER_POSITION_TEXTURE:
program.initWithVertexShaderByteArray(shaders.POSITION_TEXTURE_VERT, shaders.POSITION_TEXTURE_FRAG);
program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION);
program.addAttribute(macro.ATTRIBUTE_NAME_TEX_COORD, macro.VERTEX_ATTRIB_TEX_COORDS);
break;
case macro.SHADER_POSITION_TEXTURE_UCOLOR:
program.initWithVertexShaderByteArray(shaders.POSITION_TEXTURE_UCOLOR_VERT, shaders.POSITION_TEXTURE_UCOLOR_FRAG);
program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION);
program.addAttribute(macro.ATTRIBUTE_NAME_TEX_COORD, macro.VERTEX_ATTRIB_TEX_COORDS);
break;
case macro.SHADER_POSITION_TEXTUREA8COLOR:
program.initWithVertexShaderByteArray(shaders.POSITION_TEXTURE_A8COLOR_VERT, shaders.POSITION_TEXTURE_A8COLOR_FRAG);
program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION);
program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR);
program.addAttribute(macro.ATTRIBUTE_NAME_TEX_COORD, macro.VERTEX_ATTRIB_TEX_COORDS);
break;
case macro.SHADER_POSITION_UCOLOR:
program.initWithVertexShaderByteArray(shaders.POSITION_UCOLOR_VERT, shaders.POSITION_UCOLOR_FRAG);
program.addAttribute("aVertex", macro.VERTEX_ATTRIB_POSITION);
break;
case macro.SHADER_POSITION_LENGTHTEXTURECOLOR:
program.initWithVertexShaderByteArray(shaders.POSITION_COLOR_LENGTH_TEXTURE_VERT, shaders.POSITION_COLOR_LENGTH_TEXTURE_FRAG);
program.addAttribute(macro.ATTRIBUTE_NAME_POSITION, macro.VERTEX_ATTRIB_POSITION);
program.addAttribute(macro.ATTRIBUTE_NAME_TEX_COORD, macro.VERTEX_ATTRIB_TEX_COORDS);
program.addAttribute(macro.ATTRIBUTE_NAME_COLOR, macro.VERTEX_ATTRIB_COLOR);
break;
default:
cc.logID(8105);
return;
}
program.link();
program.updateUniforms();
//cc.checkGLErrorDebug();
},
_reloadShader: function (type) {
var program = this.programForKey(type);
program.reset();
this._loadDefaultShader(program, type);
},
/**
* loads the default shaders
*/
loadDefaultShaders: function () {
},
/**
* reload the default shaders
*/
reloadDefaultShaders: function () {
// reset all default programs and reload them
this._reloadShader(macro.SHADER_POSITION_TEXTURECOLOR);
this._reloadShader(macro.SHADER_SPRITE_POSITION_TEXTURECOLOR);
this._reloadShader(macro.SHADER_POSITION_TEXTURECOLORALPHATEST);
this._reloadShader(macro.SHADER_SPRITE_POSITION_TEXTURECOLORALPHATEST);
this._reloadShader(macro.SHADER_POSITION_COLOR);
this._reloadShader(macro.SHADER_POSITION_TEXTURE);
this._reloadShader(macro.SHADER_POSITION_TEXTURE_UCOLOR);
this._reloadShader(macro.SHADER_POSITION_TEXTUREA8COLOR);
this._reloadShader(macro.SHADER_POSITION_UCOLOR);
},
/**
* returns a GL program for a given key
* @param {String} key
*/
programForKey: function (key) {
if (!this._programs[key]) {
var program = new cc.GLProgram();
this._loadDefaultShader(program, key);
this._programs[key] = program;
}
return this._programs[key];
},
/**
* returns a GL program for a shader name
* @param {String} shaderName
* @return {cc.GLProgram}
*/
getProgram: function (shaderName) {
return this.programForKey(shaderName);
},
/**
* adds a CCGLProgram to the cache for a given name
* @param {cc.GLProgram} program
* @param {String} key
*/
addProgram: function (program, key) {
this._programs[key] = program;
}
};
-297
View File
@@ -1,297 +0,0 @@
/****************************************************************************
Copyright (c) 2008-2010 Ricardo Quesada
Copyright (c) 2011-2012 cocos2d-x.org
Copyright (c) 2013-2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
//-----------------------Shader_Position_uColor Shader Source--------------------------
/**
* Predefined propertys
* @class PresetShaders
* @readonly
* @type {Object}
* @static
* @namespace cc
*/
cc.PresetShaders = {
/**
* @property POSITION_UCOLOR_FRAG
* @type {String}
*/
POSITION_UCOLOR_FRAG : "precision lowp float;\n"
+ "varying vec4 v_fragmentColor;\n"
+ "void main()\n"
+ "{\n"
+ "gl_FragColor = v_fragmentColor;\n"
+ "}",
/**
* @property POSITION_UCOLOR_VERT
* @type {String}
*/
POSITION_UCOLOR_VERT : "attribute vec4 a_position;\n"
+ "uniform vec4 u_color;\n"
+ "uniform float u_pointSize;\n"
+ "varying lowp vec4 v_fragmentColor;\n"
+ "void main(void)\n"
+ "{\n"
+ "gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position;\n"
+ "gl_PointSize = u_pointSize;\n"
+ "v_fragmentColor = u_color;\n"
+ "}",
//---------------------Shader_PositionColor Shader Source-----------------------
/**
* @property POSITION_COLOR_FRAG
* @type {String}
*/
POSITION_COLOR_FRAG : "precision lowp float;\n"
+ "varying vec4 v_fragmentColor;\n"
+ "void main()\n"
+ "{\n"
+ "gl_FragColor = v_fragmentColor;\n"
+ "}",
/**
* @property POSITION_COLOR_VERT
* @type {String}
*/
POSITION_COLOR_VERT : "attribute vec4 a_position;\n"
+ "attribute vec4 a_color;\n"
+ "varying lowp vec4 v_fragmentColor;\n"
+ "void main()\n"
+ "{\n"
+ "gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position;\n"
+ "v_fragmentColor = a_color;\n"
+ "}",
/**
* @property SPRITE_POSITION_COLOR_VERT
* @type {String}
*/
SPRITE_POSITION_COLOR_VERT : "attribute vec4 a_position;\n"
+ "attribute vec4 a_color;\n"
+ "varying lowp vec4 v_fragmentColor;\n"
+ "void main()\n"
+ "{\n"
+ "gl_Position = CC_PMatrix * a_position;\n"
+ "v_fragmentColor = a_color;\n"
+ "}",
// --------------------- Shader_PositionColorLengthTexture Shader source------------------------
/**
* @property POSITION_COLOR_LENGTH_TEXTURE_FRAG
* @type {String}
*/
POSITION_COLOR_LENGTH_TEXTURE_FRAG :
"//#extension GL_OES_standard_derivatives : enable\n"
+ "varying mediump vec4 v_color;\n"
+ "varying mediump vec2 v_texcoord;\n"
+ "void main()\n"
+ "{\n"
+ "//#if defined GL_OES_standard_derivatives\n"
+ "//gl_FragColor=v_color*smoothstep(0.0, length(fwidth(v_texcoord)), 1.0-length(v_texcoord));\n"
+ "//#else\n"
+ "gl_FragColor = v_color * step(0.0, 1.0 - length(v_texcoord));\n"
+ "//#endif\n"
+ "}",
/**
* @property POSITION_COLOR_LENGTH_TEXTURE_VERT
* @type {String}
*/
POSITION_COLOR_LENGTH_TEXTURE_VERT : "attribute mediump vec4 a_position;\n"
+ "attribute mediump vec2 a_texcoord;\n"
+ "attribute mediump vec4 a_color;\n"
+ "varying mediump vec4 v_color;\n"
+ "varying mediump vec2 v_texcoord;\n"
+ "void main()\n"
+ "{\n"
+ "v_color = a_color;\n"//vec4(a_color.rgb*a_color.a, a_color.a);
+ "v_texcoord = a_texcoord;\n"
+ "gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position;\n"
+ "}",
// ----------------------Shader_PositionTexture Shader Source-------------------------------------
/**
* @property POSITION_TEXTURE_FRAG
* @type {String}
*/
POSITION_TEXTURE_FRAG : "precision lowp float;\n"
+ "varying vec2 v_texCoord;\n"
+ "void main()\n"
+ "{\n"
+ "gl_FragColor = texture2D(CC_Texture0, v_texCoord);\n"
+ "}",
/**
* @property POSITION_TEXTURE_VERT
* @type {String}
*/
POSITION_TEXTURE_VERT : "attribute vec4 a_position;\n"
+ "attribute vec2 a_texCoord;\n"
+ "varying mediump vec2 v_texCoord;\n"
+ "void main()\n"
+ "{\n"
+ "gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position;\n"
+ "v_texCoord = a_texCoord;\n"
+ "}",
// ------------------------Shader_PositionTexture_uColor Shader Source-------------------------------
/**
* @property POSITION_TEXTURE_UCOLOR_FRAG
* @type {String}
*/
POSITION_TEXTURE_UCOLOR_FRAG : "precision lowp float;\n"
+ "uniform vec4 u_color;\n"
+ "varying vec2 v_texCoord;\n"
+ "void main()\n"
+ "{\n"
+ "gl_FragColor=texture2D(CC_Texture0, v_texCoord) * u_color;\n"
+ "}",
/**
* @property POSITION_TEXTURE_UCOLOR_VERT
* @type {String}
*/
POSITION_TEXTURE_UCOLOR_VERT : "attribute vec4 a_position;\n"
+ "attribute vec2 a_texCoord;\n"
+ "varying mediump vec2 v_texCoord;\n"
+ "void main()\n"
+ "{\n"
+ "gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position;\n"
+ "v_texCoord = a_texCoord;\n"
+ "}",
//---------------------Shader_PositionTextureA8Color Shader source-------------------------------
/**
* @property POSITION_TEXTURE_A8COLOR_FRAG
* @type {String}
*/
POSITION_TEXTURE_A8COLOR_FRAG : "precision lowp float;\n"
+ "varying vec4 v_fragmentColor;\n"
+ "varying vec2 v_texCoord;\n"
+ "void main()\n"
+ "{\n"
+ "gl_FragColor = vec4(v_fragmentColor.rgb,\n"// RGB from uniform
+ "v_fragmentColor.a * texture2D(CC_Texture0, v_texCoord).a);\n"// A from texture and uniform
+ "}",
/**
* @property POSITION_TEXTURE_A8COLOR_VERT
* @type {String}
*/
POSITION_TEXTURE_A8COLOR_VERT : "attribute vec4 a_position;\n"
+ "attribute vec2 a_texCoord;\n"
+ "attribute vec4 a_color;\n"
+ "varying lowp vec4 v_fragmentColor;\n"
+ "varying mediump vec2 v_texCoord;\n"
+ "void main()\n"
+ "{\n"
+ "gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position;\n"
+ "v_fragmentColor = a_color;\n"
+ "v_texCoord = a_texCoord;\n"
+ "}",
// ------------------------Shader_PositionTextureColor Shader source------------------------------------
/**
* @property POSITION_TEXTURE_COLOR_FRAG
* @type {String}
*/
POSITION_TEXTURE_COLOR_FRAG : "precision lowp float;\n"
+ "varying vec4 v_fragmentColor;\n"
+ "varying vec2 v_texCoord;\n"
+ "void main()\n"
+ "{\n"
+ "gl_FragColor = v_fragmentColor * texture2D(CC_Texture0, v_texCoord);\n"
+ "}",
/**
* @property POSITION_TEXTURE_COLOR_VERT
* @type {String}
*/
POSITION_TEXTURE_COLOR_VERT : "attribute vec4 a_position;\n"
+ "attribute vec2 a_texCoord;\n"
+ "attribute vec4 a_color;\n"
+ "varying lowp vec4 v_fragmentColor;\n"
+ "varying mediump vec2 v_texCoord;\n"
+ "void main()\n"
+ "{\n"
+ "gl_Position = (CC_PMatrix * CC_MVMatrix) * a_position;\n"
+ "v_fragmentColor = a_color;\n"
+ "v_texCoord = a_texCoord;\n"
+ "}",
/**
* @property SPRITE_POSITION_TEXTURE_COLOR_VERT
* @type {String}
*/
SPRITE_POSITION_TEXTURE_COLOR_VERT : "attribute vec4 a_position;\n"
+ "attribute vec2 a_texCoord;\n"
+ "attribute vec4 a_color;\n"
+ "varying lowp vec4 v_fragmentColor;\n"
+ "varying mediump vec2 v_texCoord;\n"
+ "void main()\n"
+ "{\n"
+ "gl_Position = CC_PMatrix * a_position;\n"
+ "v_fragmentColor = a_color;\n"
+ "v_texCoord = a_texCoord;\n"
+ "}",
//-----------------------Shader_PositionTextureColorAlphaTest_frag Shader Source----------------------------
/**
* @property POSITION_TEXTURE_COLOR_ALPHATEST_FRAG
* @type {String}
*/
POSITION_TEXTURE_COLOR_ALPHATEST_FRAG : "precision lowp float;\n"
+ "varying vec4 v_fragmentColor;\n"
+ "varying vec2 v_texCoord;\n"
+ "uniform float CC_alpha_value;\n"
+ "void main()\n"
+ "{\n"
+ "vec4 texColor=texture2D(CC_Texture0, v_texCoord);\n"
+ "if(texColor.a <= CC_alpha_value)\n"
+ " discard; \n"
+ "gl_FragColor=texColor*v_fragmentColor;\n"
+ "}",
//-----------------------ShaderEx_SwitchMask_frag Shader Source----------------------------
/**
* @property EX_SWITCHMASK_FRAG
* @type {String}
*/
EX_SWITCHMASK_FRAG : "precision lowp float;\n"
+ "varying vec4 v_fragmentColor;\n"
+ "varying vec2 v_texCoord;\n"
+ "uniform sampler2D u_texture;\n"
+ "uniform sampler2D u_mask;\n"
+ "void main()\n"
+ "{\n"
+ "vec4 texColorc=texture2D(u_texture, v_texCoord);\n"
+ "vec4 maskColor=texture2D(u_mask, v_texCoord);\n"
+ "vec4 finalColor=vec4(texColor.r, texColor.g, texColor.b, maskColor.a*texColor.a);\n"
+ "gl_FragColor=v_fragmentColor*finalColor;\n"
+ "}"
};
-29
View File
@@ -1,29 +0,0 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Chukong Aipu reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
require('./CCShaders');
require('./CCShaderCache');
require('./CCGLProgram');
require('./CCGLStateCache');
-2
View File
@@ -168,7 +168,6 @@ if (!(CC_EDITOR && Editor.isMainProcess)) {
require('./polyfill/typescript');
}
require('./cocos2d/kazmath');
require('./cocos2d/core/predefine');
_global.ccs = {};
@@ -177,7 +176,6 @@ _global.cp = {};
// LOAD COCOS2D ENGINE CODE
if (!(CC_EDITOR && Editor.isMainProcess)) {
require('./cocos2d/shaders');
require('./CCBoot');
require('./cocos2d');
}