diff --git a/DebugInfos.js b/DebugInfos.js
index d6a8252f29..1ca71b29f9 100644
--- a/DebugInfos.js
+++ b/DebugInfos.js
@@ -621,6 +621,10 @@ if (CC_DEBUG) {
"8301": "Camera does not support Canvas Mode.", //cc.Camera.enabled
// AudioEngine: 8400
"8400": "Wrong type arguments, 'filePath' must be a String.", // cc.audioEngine.play
+
+ // New Renderer 10000
+ "9000": "Stencil manager does not support level bigger than %d in this device.",
+ "9001": "Stencil manager is already empty, cannot pop any mask",
};
cc._LogInfos = logs;
}
diff --git a/cocos2d/clipping-nodes/CCClippingNode.js b/cocos2d/clipping-nodes/CCClippingNode.js
deleted file mode 100644
index 3b735f8387..0000000000
--- a/cocos2d/clipping-nodes/CCClippingNode.js
+++ /dev/null
@@ -1,230 +0,0 @@
-/****************************************************************************
- Copyright (c) 2008-2010 Ricardo Quesada
- Copyright (c) 2011-2012 cocos2d-x.org
- Copyright (c) 2013-2014 Chukong Technologies Inc.
- Copyright (c) 2012 Pierre-David Bélanger
-
- http://www.cocos2d-x.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-
-
-/**
- *
- * cc.ClippingNode is a subclass of ccsg.Node.
- * It draws its content (children) clipped using a stencil.
- * The stencil is an other ccsg.Node that will not be drawn.
- * The clipping is done using the alpha part of the stencil (adjusted with an alphaThreshold).
- *
- * @class
- * @extends _ccsg.Node
- * @param {_ccsg.Node} [stencil=null]
- *
- * @property {Number} alphaThreshold - Threshold for alpha value.
- * @property {Boolean} inverted - Indicate whether in inverted mode.
- * @property {_ccsg.Node} stencil - he ccsg.Node to use as a stencil to do the clipping.
- */
-cc.ClippingNode = _ccsg.Node.extend(/** @lends cc.ClippingNode# */{
- inverted: false,
- _alphaThreshold: 0,
-
- _stencil: null,
- _className: "ClippingNode",
-
- _originStencilProgram: null,
-
- /**
- * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * @param {_ccsg.Node} [stencil=null]
- */
- ctor: function (stencil) {
- stencil = stencil || null;
- _ccsg.Node.prototype.ctor.call(this);
- this._stencil = stencil;
- if (stencil) {
- this._originStencilProgram = stencil.getShaderProgram();
- }
- this.alphaThreshold = 1;
- this.inverted = false;
- this._renderCmd.initStencilBits();
- },
-
- /**
- *
- * Event callback that is invoked every time when node enters the 'stage'.
- * If the CCNode enters the 'stage' with a transition, this event is called when the transition starts.
- * During onEnter you can't access a "sister/brother" node.
- * If you override onEnter, you must call its parent's onEnter function with this._super().
- *
- * @function
- */
- onEnter: function () {
- _ccsg.Node.prototype.onEnter.call(this);
- if (this._stencil)
- this._stencil.performRecursive(_ccsg.Node.performType.onEnter);
- },
-
- /**
- *
- * Event callback that is invoked when the node enters in the 'stage'.
- * If the node enters the 'stage' with a transition, this event is called when the transition finishes.
- * If you override onEnterTransitionDidFinish, you shall call its parent's onEnterTransitionDidFinish with this._super()
- *
- * @function
- */
- onEnterTransitionDidFinish: function () {
- _ccsg.Node.prototype.onEnterTransitionDidFinish.call(this);
- if (this._stencil)
- this._stencil.performRecursive(_ccsg.Node.performType.onEnterTransitionDidFinish);
- },
-
- /**
- *
- * callback that is called every time the node leaves the 'stage'.
- * If the node leaves the 'stage' with a transition, this callback is called when the transition starts.
- * If you override onExitTransitionDidStart, you shall call its parent's onExitTransitionDidStart with this._super()
- *
- * @function
- */
- onExitTransitionDidStart: function () {
- if (this._stencil) {
- this._stencil.performRecursive(_ccsg.Node.performType.onExitTransitionDidStart);
- }
- _ccsg.Node.prototype.onExitTransitionDidStart.call(this);
- },
-
- /**
- *
- * callback that is called every time the node leaves the 'stage'.
- * If the node leaves the 'stage' with a transition, this callback is called when the transition finishes.
- * During onExit you can't access a sibling node.
- * If you override onExit, you shall call its parent's onExit with this._super().
- *
- * @function
- */
- onExit: function () {
- if (this._stencil) {
- this._stencil.performRecursive(_ccsg.Node.performType.onExit);
- }
- _ccsg.Node.prototype.onExit.call(this);
- },
-
- visit: function (parent) {
- this._renderCmd.clippingVisit(parent && parent._renderCmd);
- },
-
- _visitChildren: function () {
- if (this._reorderChildDirty) {
- this.sortAllChildren();
- }
- var children = this._children, child;
- for (var i = 0, len = children.length; i < len; i++) {
- child = children[i];
- if (child && child._visible) {
- child.visit(this);
- }
- }
- this._renderCmd._dirtyFlag = 0;
- },
-
- /**
- *
- * The alpha threshold.
- * The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold.
- * Should be a float between 0 and 1.
- * This default to 1 (so alpha test is disabled).
- *
- * @return {Number}
- */
- getAlphaThreshold: function () {
- return this._alphaThreshold;
- },
-
- /**
- * set alpha threshold.
- * @param {Number} alphaThreshold
- */
- setAlphaThreshold: function (alphaThreshold) {
- if (alphaThreshold === 1 && alphaThreshold !== this._alphaThreshold) {
- // should reset program used by _stencil
- this._renderCmd.resetProgramByStencil();
- }
- this._alphaThreshold = alphaThreshold;
- },
-
- /**
- *
- * Inverted. If this is set to YES,
- * the stencil is inverted, so the content is drawn where the stencil is NOT drawn.
- * This default to NO.
- *
- * @return {Boolean}
- */
- isInverted: function () {
- return this.inverted;
- },
-
- /**
- * set whether or not invert of stencil
- * @param {Boolean} inverted
- */
- setInverted: function (inverted) {
- this.inverted = inverted;
- },
-
- /**
- * The ccsg.Node to use as a stencil to do the clipping.
- * The stencil node will be retained. This default to nil.
- * @return {_ccsg.Node}
- */
- getStencil: function () {
- return this._stencil;
- },
-
- /**
- * Set stencil.
- * @function
- * @param {_ccsg.Node} stencil
- */
- setStencil: function (stencil) {
- if(this._stencil === stencil)
- return;
-
- if (stencil)
- this._originStencilProgram = stencil.getShaderProgram();
-
- this._renderCmd.setStencil(stencil);
- },
-
- _createRenderCmd: function(){
- if(cc._renderType === cc.game.RENDER_TYPE_CANVAS)
- return new cc.ClippingNode.CanvasRenderCmd(this);
- else
- return new cc.ClippingNode.WebGLRenderCmd(this);
- }
-});
-
-cc.ClippingNode.stencilBits = -1;
-
-var _p = cc.ClippingNode.prototype;
-
-// Extended properties
-cc.defineGetterSetter(_p, "stencil", _p.getStencil, _p.setStencil);
-cc.defineGetterSetter(_p, "alphaThreshold", _p.getAlphaThreshold, _p.setAlphaThreshold);
diff --git a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js
deleted file mode 100644
index 016459275f..0000000000
--- a/cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js
+++ /dev/null
@@ -1,106 +0,0 @@
-/****************************************************************************
- 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.
- ****************************************************************************/
-
-require('../shape-nodes/CCDrawNode');
-
-//-------------------------- ClippingNode's canvas render cmd --------------------------------
-cc.ClippingNode.CanvasRenderCmd = function(renderable){
- this._rootCtor(renderable);
- this._needDraw = false;
-
- this._rendererClipCmd = new cc.CustomRenderCmd(this, this._drawStencilCommand);
- this._rendererRestoreCmd = new cc.CustomRenderCmd(this, this._restoreCmdCallback);
-};
-var proto = cc.ClippingNode.CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype);
-proto.constructor = cc.ClippingNode.CanvasRenderCmd;
-
-proto.resetProgramByStencil = function () {};
-
-proto.initStencilBits = function(){};
-
-proto.setStencil = function(stencil){
- if(stencil == null)
- return;
-
- this._node._stencil = stencil;
-
- if (!(stencil instanceof cc.DrawNode)) {
- cc.errorID(6300);
- }
-};
-
-proto._restoreCmdCallback = function (ctx) {
- var wrapper = ctx || cc._renderContext;
- wrapper.restore();
-};
-
-proto._drawStencilCommand = function (ctx, scaleX, scaleY) {
- var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
- wrapper.save();
- context.beginPath(); //save for clip
- wrapper.setTransform(this._worldTransform, scaleX, scaleY);
-
- //draw elements
- var stencilBuffer = this._node._stencil._buffer;
- for(var index = 0; index < stencilBuffer.length; ++index) {
- var vertices = stencilBuffer[index].verts;
- if(vertices.length < 3) continue;
- context.moveTo(vertices[0].x, -vertices[0].y);
- for(var vIndex = 1; vIndex < vertices.length; ++vIndex) {
- context.lineTo(vertices[vIndex].x, -vertices[vIndex].y);
- }
- }
- //end draw elements
- context.clip();
-};
-
-proto.clippingVisit = function (parentCmd) {
- var node = this._node;
- parentCmd = parentCmd || this.getParentRenderCmd();
- this._propagateFlagsDown(parentCmd);
- // quick return if not visible
- if (!node._visible)
- return;
-
- if (parentCmd)
- this._curLevel = parentCmd._curLevel + 1;
-
- this._syncStatus(parentCmd);
- if (node._stencil) {
- cc.renderer.pushRenderCommand(this._rendererClipCmd);
- }
- var children = node._children;
-
- var i, len = children.length;
- if (len > 0) {
- node.sortAllChildren();
- for (i = 0; i < len; i++)
- children[i].visit(node);
- }
-
- if (node._stencil) {
- cc.renderer.pushRenderCommand(this._rendererRestoreCmd);
- }
- this._dirtyFlag = 0;
-};
diff --git a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js b/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js
deleted file mode 100644
index cacd2629e7..0000000000
--- a/cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js
+++ /dev/null
@@ -1,249 +0,0 @@
-/****************************************************************************
- 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.
- ****************************************************************************/
-
-require('../core/CCDrawingPrimitives');
-
-// ------------------------------- ClippingNode's WebGL render cmd ------------------------------
-function setProgram (node, program) {
- node.shaderProgram = program;
-
- var children = node.children;
- if (!children)
- return;
-
- for (var i = 0; i < children.length; i++)
- setProgram(children[i], program);
-}
-
-var _currentState = {
- stencilEnabled: false,
- depthWriteMask: true
-};
-
-cc.ClippingNode.WebGLRenderCmd = function(renderable){
- this._rootCtor(renderable);
- this._needDraw = false;
-
- this._beforeVisitCmd = new cc.CustomRenderCmd(this, this._onBeforeVisit);
- this._afterDrawStencilCmd = new cc.CustomRenderCmd(this, this._onAfterDrawStencil);
- this._afterVisitCmd = new cc.CustomRenderCmd(this, this._onAfterVisit);
-
- this._previousState = null;
- this._state = {
- stencilEnabled: true,
- stencilWriteMask: 0,
- depthWriteMask: false,
- stencilFunc: 0,
- stencilRef: 0,
- stencilValueMask: 0
- };
-};
-
-var proto = cc.ClippingNode.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype);
-proto.constructor = cc.ClippingNode.WebGLRenderCmd;
-
-cc.ClippingNode.WebGLRenderCmd._init_once = null;
-cc.ClippingNode.WebGLRenderCmd._visit_once = null;
-cc.ClippingNode.WebGLRenderCmd._layer = -1;
-
-proto.initStencilBits = function () {
- // get (only once) the number of bits of the stencil buffer
- cc.ClippingNode.WebGLRenderCmd._init_once = true;
- if (cc.ClippingNode.WebGLRenderCmd._init_once) {
- cc.ClippingNode.stencilBits = cc._renderContext.getParameter(cc._renderContext.STENCIL_BITS);
- if (cc.ClippingNode.stencilBits <= 0)
- cc.logID(6301);
- cc.ClippingNode.WebGLRenderCmd._init_once = false;
- }
-};
-
-proto.transform = function (parentCmd, recursive) {
- var node = this._node;
- this.originTransform(parentCmd, recursive);
- if (node._stencil) {
- node._stencil._renderCmd.transform(this, true);
- node._stencil._dirtyFlag &= ~_ccsg.Node._dirtyFlags.transformDirty;
- }
-};
-
-proto.clippingVisit = function (parentCmd) {
- var node = this._node;
- parentCmd = parentCmd || this.getParentRenderCmd();
- this.visit(parentCmd);
-
- // if stencil buffer disabled
- if (cc.ClippingNode.stencilBits < 1) {
- // draw everything, as if there where no stencil
- node._visitChildren();
- return;
- }
-
- if (!node._stencil || !node._stencil.visible) {
- if (node.inverted)
- node._visitChildren(); // draw everything
- return;
- }
-
- if (cc.ClippingNode.WebGLRenderCmd._layer + 1 === cc.ClippingNode.stencilBits) {
- cc.ClippingNode.WebGLRenderCmd._visit_once = true;
- if (cc.ClippingNode.WebGLRenderCmd._visit_once) {
- cc.logID(6302, cc.ClippingNode.stencilBits);
- cc.ClippingNode.WebGLRenderCmd._visit_once = false;
- }
- // draw everything, as if there were no stencil
- node._visitChildren();
- return;
- }
-
- cc.renderer.pushRenderCommand(this._beforeVisitCmd);
-
- node._stencil.visit(node);
-
- cc.renderer.pushRenderCommand(this._afterDrawStencilCmd);
-
- // draw (according to the stencil test func) this node and its children
- var locChildren = node._children;
- if (locChildren && locChildren.length > 0) {
- var childLen = locChildren.length;
- node.sortAllChildren();
- // draw children zOrder < 0
- for (var i = 0; i < childLen; i++) {
- locChildren[i].visit(node);
- }
- }
-
- cc.renderer.pushRenderCommand(this._afterVisitCmd);
-
- this._dirtyFlag = 0;
-};
-
-proto.setStencil = function(stencil){
- var node = this._node;
- if(node._stencil)
- node._stencil._parent = null;
- node._stencil = stencil;
- if(node._stencil)
- node._stencil._parent = node;
-};
-
-proto._drawFullScreenQuadClearStencil = function () {
- // draw a fullscreen solid rectangle to clear the stencil buffer
- var projStack = cc.math.projection_matrix_stack;
- projStack.push();
- projStack.top.identity();
-
- var modelViewStack = cc.math.modelview_matrix_stack;
- modelViewStack.push();
- modelViewStack.top.identity();
-
- cc._drawingUtil.drawSolidRect(cc.p(-1, -1), cc.p(1, 1), cc.color(255, 255, 255, 255));
-
- projStack.pop();
-
- modelViewStack.pop();
-};
-
-// should reset program used by _stencil
-proto.resetProgramByStencil = function () {
- var node = this._node;
- if (node._stencil) {
- var program = node._originStencilProgram;
- setProgram(node._stencil, program);
- }
-};
-
-proto._onBeforeVisit = function(ctx){
- var gl = ctx || cc._renderContext, node = this._node;
- cc.ClippingNode.WebGLRenderCmd._layer++;
-
- // mask of the current layer (ie: for layer 3: 00000100)
- var mask_layer = 0x1 << cc.ClippingNode.WebGLRenderCmd._layer;
- // mask of all layers less than the current (ie: for layer 3: 00000011)
- var mask_layer_l = mask_layer - 1;
- // mask of all layers less than or equal to the current (ie: for layer 3: 00000111)
- var mask_layer_le = mask_layer | mask_layer_l;
- // manually save the stencil state
- this._previousState = _currentState;
-
- // enable stencil use
- gl.enable(gl.STENCIL_TEST);
- gl.stencilMask(mask_layer);
-
- gl.depthMask(false);
-
- gl.stencilFunc(gl.NEVER, mask_layer, mask_layer);
- gl.stencilOp(!this._node.inverted ? gl.ZERO : gl.REPLACE, gl.KEEP, gl.KEEP);
-
- this._drawFullScreenQuadClearStencil();
-
- gl.stencilFunc(gl.NEVER, mask_layer, mask_layer);
- gl.stencilOp(!this._node.inverted ? gl.REPLACE : gl.ZERO, gl.KEEP, gl.KEEP);
-
- if (node.alphaThreshold < 1) { //TODO desktop
- var program = cc.shaderCache.programForKey(cc.macro.SHADER_POSITION_TEXTURECOLORALPHATEST);
- // set our alphaThreshold
- cc.gl.useProgram(program.getProgram());
- program.setUniformLocationWith1f(cc.macro.UNIFORM_ALPHA_TEST_VALUE_S, node.alphaThreshold);
- program.setUniformLocationWithMatrix4fv(cc.macro.UNIFORM_MVMATRIX_S, cc.renderer.mat4Identity.mat);
- setProgram(node._stencil, program);
- }
-
- // Save the current stencil states
- this._state.stencilWriteMask = mask_layer;
- this._state.stencilRef = this._state.stencilValueMask = mask_layer_le;
- this._state.stencilFunc = gl.NEVER;
-
- _currentState = this._state;
-};
-
-proto._onAfterDrawStencil = function (ctx) {
- var gl = ctx || cc._renderContext;
- gl.depthMask(this._previousState.depthWriteMask);
-
- gl.stencilFunc(gl.EQUAL, this._state.stencilRef, this._state.stencilValueMask);
- gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
-
- this._state.stencilFunc = gl.EQUAL;
-};
-
-proto._onAfterVisit = function (ctx) {
- var gl = ctx || cc._renderContext;
-
- var state = this._previousState;
- if (!state.stencilEnabled) {
- gl.disable(gl.STENCIL_TEST);
- }
- else {
- gl.stencilFunc(state.stencilFunc, state.stencilRef, state.stencilValueMask);
- gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP);
- gl.stencilMask(state.stencilWriteMask);
- }
-
- // restore _currentState, so self states won't affect other nodes any longer
- _currentState = this._previousState;
- this._previousState = null;
-
- // we are done using this layer, decrement
- cc.ClippingNode.WebGLRenderCmd._layer--;
-};
diff --git a/cocos2d/core/components/CCMask.js b/cocos2d/core/components/CCMask.js
index e5fd93a8e1..44ae3bc13a 100644
--- a/cocos2d/core/components/CCMask.js
+++ b/cocos2d/core/components/CCMask.js
@@ -23,12 +23,10 @@
THE SOFTWARE.
****************************************************************************/
-require('../../clipping-nodes/CCClippingNode');
-require('../../clipping-nodes/CCClippingNodeCanvasRenderCmd');
-require('../../clipping-nodes/CCClippingNodeWebGLRenderCmd');
-
-require('../../shape-nodes/CCDrawNode');
-
+const renderEngine = require('../renderer/render-engine');
+const gfx = renderEngine.gfx;
+const StencilMaterial = renderEngine.StencilMaterial;
+const RenderComponent = require('./CCRenderComponent');
const affineTrans = require('../value-types/CCAffineTransform');
var _trans = affineTrans.make();
@@ -69,7 +67,7 @@ const SEGEMENTS_MAX = 10000;
*/
var Mask = cc.Class({
name: 'cc.Mask',
- extends: cc.Component,
+ extends: RenderComponent,
editor: CC_EDITOR && {
menu: 'i18n:MAIN_MENU.component.renderers/Mask',
@@ -78,9 +76,9 @@ var Mask = cc.Class({
},
properties: {
- _clippingStencil: {
+ _spriteFrame: {
default: null,
- serializable: false,
+ type: cc.SpriteFrame
},
/**
@@ -98,7 +96,15 @@ var Mask = cc.Class({
},
set: function (value) {
this._type = value;
- this._refreshStencil();
+ if (this._type !== MaskType.IMAGE_STENCIL) {
+ this.spriteFrame = null;
+ this.alphaThreshold = 0;
+ }
+ if (this._renderData) {
+ this._renderData.uvDirty = true;
+ this._renderData.vertDirty = true;
+ }
+ this._updateMaterial();
},
type: MaskType,
tooltip: CC_DEV && 'i18n:COMPONENT.mask.type',
@@ -114,12 +120,27 @@ var Mask = cc.Class({
* mask.spriteFrame = newSpriteFrame;
*/
spriteFrame: {
- default: null,
type: cc.SpriteFrame,
tooltip: CC_DEV && 'i18n:COMPONENT.mask.spriteFrame',
- notify: function () {
- this._refreshStencil();
- }
+ get: function () {
+ return this._spriteFrame;
+ },
+ set: function (value) {
+ var lastSprite = this._spriteFrame;
+ if (CC_EDITOR) {
+ if ((lastSprite && lastSprite._uuid) === (value && value._uuid)) {
+ return;
+ }
+ }
+ else {
+ if (lastSprite === value) {
+ return;
+ }
+ }
+ this._spriteFrame = value;
+ this._applySpriteFrame(lastSprite);
+ },
+ type: cc.SpriteFrame,
},
/**
@@ -127,17 +148,20 @@ var Mask = cc.Class({
* The alpha threshold.(Not supported Canvas Mode)
* The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold.
* Should be a float between 0 and 1.
- * This default to 1 (so alpha test is disabled).
+ * This default to 0 (so alpha test is disabled).
+ * When it's set to 1, the stencil will discard all pixels, nothing will be shown,
+ * In previous version, it act as if the alpha test is disabled, which is incorrect.
* !#zh
* Alpha 阈值(不支持 Canvas 模式)
* 只有当模板的像素的 alpha 大于 alphaThreshold 时,才会绘制内容。
- * 该数值 0 ~ 1 之间的浮点数,默认值为 1(因此禁用 alpha)
+ * 该数值 0 ~ 1 之间的浮点数,默认值为 0(因此禁用 alpha 测试)
+ * 当被设置为 1 时,会丢弃所有蒙版像素,所以不会显示任何内容,在之前的版本中,设置为 1 等同于 0,这种效果其实是不正确的
* @property alphaThreshold
* @type {Number}
- * @default 1
+ * @default 0
*/
alphaThreshold: {
- default: 1,
+ default: 0,
type: cc.Float,
range: [0, 1, 0.1],
slide: true,
@@ -147,7 +171,9 @@ var Mask = cc.Class({
cc.warnID(4201);
return;
}
- this._sgNode.setAlphaThreshold(this.alphaThreshold);
+ if (this._frontMaterial) {
+ this._frontMaterial.alphaThreshold = this.alphaThreshold;
+ }
}
},
@@ -167,25 +193,24 @@ var Mask = cc.Class({
cc.warnID(4202);
return;
}
- this._sgNode.setInverted(this.inverted);
}
},
/**
+ * TODO: remove segments, not supported by graphics
* !#en The segements for ellipse mask.
* !#zh 椭圆遮罩的曲线细分数
* @property segements
* @type {Number}
* @default 64
*/
- _segements: 64,
+ _segments: 64,
segements: {
get: function () {
- return this._segements;
+ return this._segments;
},
set: function (value) {
- this._segements = cc.clampf(value, SEGEMENTS_MIN, SEGEMENTS_MAX);
- this._refreshStencil();
+ this._segments = cc.clampf(value, SEGEMENTS_MIN, SEGEMENTS_MAX);
},
tooltip: CC_DEV && 'i18n:COMPONENT.mask.segements',
},
@@ -211,10 +236,61 @@ var Mask = cc.Class({
}
},
- _initSgNode: function () {},
+ _onTextureLoaded: function (event) {
+ // Mark render data dirty
+ if (this._renderData) {
+ this._renderData.uvDirty = true;
+ this._renderData.vertDirty = true;
+ }
+ // Reactivate material
+ if (this.enabledInHierarchy) {
+ this._updateMaterial();
+ }
+ },
- _createSgNode: function () {
- return new cc.ClippingNode();
+ _applySpriteFrame: function (oldFrame) {
+ if (oldFrame && oldFrame.off) {
+ oldFrame.off('load', this._onTextureLoaded, this);
+ }
+ var spriteFrame = this._spriteFrame;
+ if (spriteFrame) {
+ if (spriteFrame.textureLoaded) {
+ this._onTextureLoaded(null);
+ }
+ else {
+ spriteFrame.once('load', this._onTextureLoaded, this);
+ spriteFrame.ensureLoadTexture();
+ }
+ }
+ },
+
+ _updateMaterial: function () {
+ // cannot be activated if texture not loaded yet
+ if (this._type === MaskType.IMAGE_STENCIL && (!this.spriteFrame || !this.spriteFrame.textureLoaded)) {
+ return;
+ }
+
+ // Init material
+ if (!this._material) {
+ this._frontMaterial = new StencilMaterial();
+ this._endMaterial = new StencilMaterial();
+ this._material = this._frontMaterial;
+ }
+
+ // Reset material
+ if (this._type === MaskType.IMAGE_STENCIL) {
+ var texture = this.spriteFrame.getTexture();
+ this._frontMaterial.useTexture = true;
+ this._frontMaterial.texture = texture.getImpl();
+ this._frontMaterial.alphaThreshold = this.alphaThreshold;
+ this._endMaterial.useTexture = true;
+ this._endMaterial.texture = texture.getImpl();
+ this._endMaterial.alphaThreshold = this.alphaThreshold;
+ }
+ else {
+ this._frontMaterial.useTexture = false;
+ this._endMaterial.useTexture = false;
+ }
},
_hitTest: function (point) {
@@ -244,101 +320,15 @@ var Mask = cc.Class({
},
onEnable: function () {
- if (this.spriteFrame) {
- this.spriteFrame.ensureLoadTexture();
- }
- this._refreshStencil();
- this.node.on('size-changed', this._refreshStencil, this);
- this.node.on('anchor-changed', this._refreshStencil, this);
+ this._super();
+ this._updateMaterial();
},
- onDisable: function () {
- this.node.off('size-changed', this._refreshStencil, this);
- this.node.off('anchor-changed', this._refreshStencil, this);
+ onDisable () {
+ this._super();
+ this._frontMaterial = null;
+ this._endMaterial = null;
},
-
- _calculateCircle: function (center, radius, segements) {
- var polies =[];
- var anglePerStep = Math.PI * 2 / segements;
- for(var step = 0; step < segements; ++ step) {
- polies.push(cc.v2(radius.x * Math.cos(anglePerStep * step) + center.x,
- radius.y * Math.sin(anglePerStep * step) + center.y));
- }
-
- return polies;
- },
-
- _refreshStencil: function () {
- // Check whether the conditions are met
- if (this.type === MaskType.IMAGE_STENCIL &&
- cc._renderType !== cc.game.RENDER_TYPE_WEBGL && !CC_JSB) {
- cc.warnID(4200);
- return;
- }
-
- var contentSize = this.node.getContentSize();
- var anchorPoint = this.node.getAnchorPoint();
- var stencil = this._clippingStencil;
- if (this._type === MaskType.IMAGE_STENCIL) {
- var isSgSprite = stencil instanceof cc.Scale9Sprite;
- if (!isSgSprite || stencil._spriteFrame !== this.spriteFrame) {
- stencil = new cc.Scale9Sprite();
- stencil.setSpriteFrame(this.spriteFrame);
- this._sgNode.setStencil(stencil);
- }
- stencil.setContentSize(contentSize);
- stencil.setAnchorPoint(anchorPoint);
- this._sgNode.setAlphaThreshold(this.alphaThreshold);
- }
- else {
- var isDrawNode = stencil instanceof cc.DrawNode;
- if (!isDrawNode) {
- stencil = new cc.DrawNode();
- if (CC_JSB) {
- stencil.retain();
- }
- this._sgNode.setStencil(stencil);
- }
- var width = contentSize.width;
- var height = contentSize.height;
- var x = - width * anchorPoint.x;
- var y = - height * anchorPoint.y;
- var color = cc.color(255, 255, 255, 0);
- stencil.clear();
- if (this._type === MaskType.RECT) {
- var rectangle = [cc.v2(x, y),
- cc.v2(x + width, y),
- cc.v2(x + width, y + height),
- cc.v2(x, y + height)];
- stencil.drawPoly(rectangle, color, 0, color);
- }
- else if (this._type === MaskType.ELLIPSE) {
- var center = cc.v2(x + width / 2, y + height / 2);
- var radius = {
- x: width / 2,
- y: height / 2
- };
- stencil.drawPoly(this._calculateCircle(center, radius, this._segements), color, 0, color);
- }
- }
- this._sgNode.setInverted(this.inverted);
- this._clippingStencil = stencil;
- if (!CC_JSB) {
- cc.renderer.childrenOrderDirty = true;
- }
- }
});
-if (CC_JSB) {
- // override onDestroy
- Mask.prototype.__superOnDestroy = Base.prototype.onDestroy;
- Mask.prototype.onDestroy = function () {
- this.__superOnDestroy();
- if (this._clippingStencil) {
- this._clippingStencil.release();
- this._clippingStencil = null;
- }
- };
-}
-
cc.Mask = module.exports = Mask;
diff --git a/cocos2d/core/components/CCRenderComponent.js b/cocos2d/core/components/CCRenderComponent.js
index 1bcc6f7997..9a61faa021 100644
--- a/cocos2d/core/components/CCRenderComponent.js
+++ b/cocos2d/core/components/CCRenderComponent.js
@@ -25,6 +25,8 @@
const Component = require('./CCComponent');
const defaultVertexFormat = require('../renderer/vertex-format');
+const renderEngine = require('../renderer/render-engine');
+const RenderData = renderEngine.RenderData;
/**
* !#en
@@ -51,6 +53,19 @@ var RenderComponent = cc.Class({
this._toPostHandle = false;
},
+ onEnable () {
+ this.node._renderComponent = this;
+ },
+
+ onDisable () {
+ this.node._renderComponent = null;
+ this._material = null;
+ if (this._renderData) {
+ RenderData.free(this._renderData);
+ this._renderData = null;
+ }
+ },
+
getEffect () {
if (this._material) {
return this._material.effect;
diff --git a/cocos2d/core/components/CCSprite.js b/cocos2d/core/components/CCSprite.js
index d50df6bf0d..378c7f37f6 100644
--- a/cocos2d/core/components/CCSprite.js
+++ b/cocos2d/core/components/CCSprite.js
@@ -268,7 +268,7 @@ var Sprite = cc.Class({
if (value !== this._fillType) {
if (value === FillType.RADIAL || this._fillType === FillType.RADIAL) {
RenderData.free(this._renderData);
- this._renderData = null;
+ this._renderData = null;
}
else if (this._renderData) {
this._renderData.uvDirty = true;
@@ -474,15 +474,8 @@ var Sprite = cc.Class({
},
onEnable: function () {
+ this._super();
this._activateMaterial();
- this.node._renderComponent = this;
- },
-
- onDisable: function () {
- RenderData.free(this._renderData);
- this._material = null;
- this._renderData = null;
- this.node._renderComponent = null;
},
_activateMaterial: function () {
@@ -557,6 +550,7 @@ var Sprite = cc.Class({
// Mark render data dirty
if (this._renderData) {
this._renderData.uvDirty = true;
+ this._renderData.vertDirty = true;
}
// Reactivate material
if (this.enabledInHierarchy) {
@@ -566,7 +560,6 @@ var Sprite = cc.Class({
},
_applySpriteFrame: function (oldFrame) {
- var sgNode = this._sgNode;
if (oldFrame && oldFrame.off) {
oldFrame.off('load', this._onTextureLoaded, this);
}
diff --git a/cocos2d/core/renderer/assemblers/graphics/graphics-assembler.js b/cocos2d/core/renderer/assemblers/graphics/graphics-assembler.js
index 7d75e9921e..138aad2435 100644
--- a/cocos2d/core/renderer/assemblers/graphics/graphics-assembler.js
+++ b/cocos2d/core/renderer/assemblers/graphics/graphics-assembler.js
@@ -39,7 +39,7 @@ let graphicsAssembler = {
updateRenderData (graphics) {
// Create render data if needed
if (!graphics._renderData) {
- graphics._renderData = new RenderData();
+ graphics._renderData = RenderData.alloc();
}
let renderData = graphics._renderData;
@@ -84,7 +84,7 @@ let graphicsAssembler = {
stroke (graphics) {
if (!graphics._renderData) {
- graphics._renderData = new RenderData();
+ graphics._renderData = RenderData.alloc();
}
this._curColor = graphics._strokeColor._val;
@@ -97,7 +97,7 @@ let graphicsAssembler = {
fill (graphics) {
if (!graphics._renderData) {
- graphics._renderData = new RenderData();
+ graphics._renderData = RenderData.alloc();
}
this._curColor = graphics._fillColor._val;
diff --git a/cocos2d/core/renderer/assemblers/index.js b/cocos2d/core/renderer/assemblers/index.js
index 774f81978e..7be5b4381d 100644
--- a/cocos2d/core/renderer/assemblers/index.js
+++ b/cocos2d/core/renderer/assemblers/index.js
@@ -1,4 +1,5 @@
require('./sprite-assembler');
+require('./mask-assembler');
require('./motion-streak-assembler');
require('./graphics/graphics-assembler');
require('./label/label-assembler');
\ No newline at end of file
diff --git a/cocos2d/core/renderer/assemblers/mask-assembler.js b/cocos2d/core/renderer/assemblers/mask-assembler.js
new file mode 100644
index 0000000000..512543447f
--- /dev/null
+++ b/cocos2d/core/renderer/assemblers/mask-assembler.js
@@ -0,0 +1,136 @@
+const StencilManager = require('../stencil-manager');
+const spriteUtil = require('./sprite-assembler').simpleRenderUtil;
+const Node = require('../../CCNode');
+const Graphics = require('../../graphics/graphics');
+const Mask = require('../../components/CCMask');
+const renderEngine = require('../render-engine');
+const RenderData = renderEngine.RenderData;
+
+let _stencilMgr = StencilManager.sharedManager;
+let _color = cc.color(255, 255, 255, 0);
+let _graphicsNode = new Node();
+let _graphics = _graphicsNode.addComponent(Graphics);
+_graphics.lineWidth = 0;
+
+let maskFrontAssembler = {
+ update (mask) {
+ let renderData = mask._renderData;
+ if (renderData.vertDirty) {
+ // Share render data with graphics content
+ _graphics._renderData = renderData;
+ _graphics.clear(false);
+ let width = renderData._width;
+ let height = renderData._height;
+ let x = -width * renderData._pivotX;
+ let y = -height * renderData._pivotY;
+ if (mask._type === Mask.Type.RECT) {
+ _graphics.rect(x, y, width, height);
+ }
+ else if (mask._type === Mask.Type.ELLIPSE) {
+ let cx = x + width / 2,
+ cy = y + height / 2,
+ rx = width / 2,
+ ry = height / 2;
+ _graphics.ellipse(cx, cy, rx, ry);
+ }
+ _graphics.fill();
+ }
+ },
+
+ updateRenderData (mask) {
+ if (!mask._renderData) {
+ if (mask._type === Mask.Type.IMAGE_STENCIL) {
+ mask._renderData = spriteUtil.createData(mask);
+ }
+ else {
+ mask._renderData = RenderData.alloc();
+ }
+ }
+ let renderData = mask._renderData;
+ let size = mask.node._contentSize;
+ let anchor = mask.node._anchorPoint;
+ renderData.updateSizeNPivot(size.width, size.height, anchor.x, anchor.y);
+
+ mask._material = mask._frontMaterial;
+ if (mask._type === Mask.Type.IMAGE_STENCIL) {
+ if (mask.spriteFrame) {
+ renderData.dataLength = 4;
+ spriteUtil.update(mask);
+ }
+ else {
+ mask._material = null;
+ }
+ }
+ else {
+ this.update(mask);
+ }
+ },
+
+ fillVertexBuffer (mask, index, vbuf, uintbuf) {
+ // Invalid state
+ if (mask._type === Mask.Type.IMAGE_STENCIL && !mask.spriteFrame) {
+ return;
+ }
+ // HACK: Must push mask after batch, so we can only put this logic in fillVertexBuffer or fillIndexBuffer
+ _stencilMgr.pushMask(mask);
+
+ if (mask._type === Mask.Type.IMAGE_STENCIL) {
+ spriteUtil.fillVertexBuffer(mask, index, vbuf, uintbuf);
+ }
+ else {
+ // Share node for correct global matrix
+ _graphics.node = mask.node;
+ _graphics._renderData = mask._renderData;
+ Graphics._assembler.fillVertexBuffer(_graphics, index, vbuf, uintbuf);
+ }
+ },
+ fillIndexBuffer (mask, offset, vertexId, ibuf) {
+ if (mask._type === Mask.Type.IMAGE_STENCIL) {
+ if (mask.spriteFrame) {
+ spriteUtil.fillIndexBuffer(mask, offset, vertexId, ibuf);
+ }
+ }
+ else {
+ Graphics._assembler.fillIndexBuffer(_graphics, offset, vertexId, ibuf);
+ }
+ }
+}
+
+let maskEndAssembler = {
+ updateRenderData (mask) {
+ if (mask._type === Mask.Type.IMAGE_STENCIL && !mask.spriteFrame) {
+ mask._material = null;
+ }
+ else {
+ mask._material = mask._endMaterial;
+ }
+ },
+
+ fillVertexBuffer (mask, index, vbuf, uintbuf) {
+ // Invalid state
+ if (mask._type === Mask.Type.IMAGE_STENCIL && !mask.spriteFrame) {
+ return;
+ }
+ // HACK: Must pop mask after batch, so we can only put this logic in fillVertexBuffer or fillIndexBuffer
+ _stencilMgr.popMask();
+
+ if (mask._type === Mask.Type.IMAGE_STENCIL) {
+ spriteUtil.fillVertexBuffer(mask, index, vbuf, uintbuf);
+ }
+ else {
+ // Share node for correct global matrix
+ _graphics.node = mask.node;
+ _graphics._renderData = mask._renderData;
+ Graphics._assembler.fillVertexBuffer(_graphics, index, vbuf, uintbuf);
+ }
+ },
+ fillIndexBuffer: maskFrontAssembler.fillIndexBuffer
+}
+
+Mask._assembler = maskFrontAssembler;
+Mask._postAssembler = maskEndAssembler;
+
+module.exports = {
+ front: maskFrontAssembler,
+ end: maskEndAssembler
+}
\ No newline at end of file
diff --git a/cocos2d/core/renderer/assemblers/sprite-assembler.js b/cocos2d/core/renderer/assemblers/sprite-assembler.js
index 0b3c7abeae..120f6104ea 100644
--- a/cocos2d/core/renderer/assemblers/sprite-assembler.js
+++ b/cocos2d/core/renderer/assemblers/sprite-assembler.js
@@ -116,28 +116,44 @@ let simpleRenderUtil = {
updateVerts (sprite) {
let renderData = sprite._renderData,
data = renderData._data,
- frame = sprite.spriteFrame,
- width, height;
+ cw = renderData._width,
+ ch = renderData._height,
+ appx = renderData._pivotX * cw,
+ appy = renderData._pivotY * ch,
+ l, b, r, t;
if (sprite.trim) {
- width = frame._rect.width;
- height = frame._rect.height;
+ l = -appx;
+ b = -appy;
+ r = cw - appx;
+ t = ch - appy;
}
else {
- width = frame._originalSize.width;
- height = frame._originalSize.height;
+ let frame = sprite.spriteFrame,
+ ow = frame._originalSize.width,
+ oh = frame._originalSize.height,
+ rw = frame._rect.width,
+ rh = frame._rect.height,
+ offset = frame._offset,
+ scaleX = cw / ow,
+ scaleY = ch / oh;
+ let trimLeft = offset.x + (ow - rw) / 2;
+ let trimRight = offset.x - (ow - rw) / 2;
+ let trimBottom = offset.y + (oh - rh) / 2;
+ let trimTop = offset.y - (oh - rh) / 2;
+ l = trimLeft * scaleX - appx;
+ b = trimBottom * scaleY - appy;
+ r = cw + trimRight * scaleX - appx;
+ t = ch + trimTop * scaleY - appy;
}
-
- let appx = renderData._pivotX * width,
- appy = renderData._pivotY * height;
- data[0].x = -appx;
- data[0].y = -appy;
- data[1].x = width - appx;
- data[1].y = -appy;
- data[2].x = -appx;
- data[2].y = height - appy;
- data[3].x = width - appx;
- data[3].y = height - appy;
+ data[0].x = l;
+ data[0].y = b;
+ data[1].x = r;
+ data[1].y = b;
+ data[2].x = l;
+ data[2].y = t;
+ data[3].x = r;
+ data[3].y = t;
renderData.vertDirty = false;
},
@@ -995,6 +1011,11 @@ let filledRenderUtil = {
// Inline all type switch to avoid jit deoptimization during inlined function change
var spriteAssembler = {
+ simpleRenderUtil: simpleRenderUtil,
+ slicedRenderUtil: slicedRenderUtil,
+ tiledRenderUtil: tiledRenderUtil,
+ filledRenderUtil: filledRenderUtil,
+
updateRenderData (sprite) {
// Create render data if needed
if (!sprite._renderData) {
diff --git a/cocos2d/core/renderer/render-component-walker.js b/cocos2d/core/renderer/render-component-walker.js
index ec8a4a8d09..081ae9b067 100644
--- a/cocos2d/core/renderer/render-component-walker.js
+++ b/cocos2d/core/renderer/render-component-walker.js
@@ -23,9 +23,10 @@
THE SOFTWARE.
****************************************************************************/
+const macro = require('../platform/CCMacro');
const renderEngine = require('./render-engine');
const defaultVertexFormat = require('./vertex-format');
-const macro = require('../platform/CCMacro');
+const StencilManager = require('./stencil-manager');
const gfx = renderEngine.gfx;
const RecyclePool = renderEngine.RecyclePool;
const InputAssembler = renderEngine.InputAssembler;
@@ -40,6 +41,7 @@ var _queue = null;
var RenderComponentWalker = function (device, renderScene) {
this._renderScene = renderScene;
this._device = device;
+ this._stencilMgr = StencilManager.sharedManager;
// Buffers
let verts = new Float32Array(MAX_VERTEX * FLOATS_PER_VERT);
@@ -167,6 +169,9 @@ RenderComponentWalker.prototype = {
ia._indexBuffer = ib;
ia._start = 0;
ia._count = indiceCount;
+
+ // Check stencil state and modify pass
+ this._stencilMgr.handleEffect(effect);
// Generate model
let model = this._modelPool.add();
@@ -201,7 +206,7 @@ RenderComponentWalker.prototype = {
_checkBatchBroken (vertexFormat, currEffect, vertexOffset, indiceOffset, needNewBuf) {
let vertexCount = vertexOffset - this._vOffset,
indiceCount = indiceOffset - this._iOffset;
- if (vertexFormat && currEffect) {
+ if (vertexFormat && currEffect && vertexCount > 0 && indiceCount > 0) {
this._flush(vertexFormat, currEffect, vertexCount, indiceCount);
if (needNewBuf) {
this._switchBuffer();
@@ -224,13 +229,13 @@ RenderComponentWalker.prototype = {
uintVerts = this._uintVerts,
indices = this._indices,
currEffect = null,
- vertexFormat = null,
vertexOffset = this._vOffset,
indiceOffset = this._iOffset,
vertexId = 0,
needNewBuf = false,
- broken = false;
- comp = null,
+ broken = false,
+ comp = this._queue[0],
+ prevComp = null,
effect = null,
assembler = null,
data = null;
@@ -247,8 +252,7 @@ RenderComponentWalker.prototype = {
comp._toPostHandle = true;
}
}
- effect = comp.getEffect();
- if (!assembler || !effect) {
+ if (!assembler) {
continue;
}
@@ -256,11 +260,12 @@ RenderComponentWalker.prototype = {
assembler.updateRenderData(comp);
data = comp._renderData;
+ // Must get effect after updateRenderData, material maybe modified during updateRenderData
+ effect = comp.getEffect();
// breaking batch
needNewBuf = (vertexOffset + data.vertexCount > MAX_VERTEX) || (indiceOffset + data.indiceCount > MAX_INDICE);
- if (currEffect != effect || needNewBuf) {
- vertexFormat = comp._vertexFormat;
- broken = this._checkBatchBroken(vertexFormat, currEffect, vertexOffset, indiceOffset, needNewBuf);
+ if (prevComp && currEffect != effect || needNewBuf) {
+ broken = this._checkBatchBroken(prevComp._vertexFormat, currEffect, vertexOffset, indiceOffset, needNewBuf);
if (broken) {
vertexOffset = this._vOffset;
indiceOffset = this._iOffset;
@@ -272,17 +277,22 @@ RenderComponentWalker.prototype = {
}
currEffect = effect;
}
+ // Init effect
+ else if (!currEffect) {
+ currEffect = effect;
+ }
vertexId = vertexOffset - this._vOffset;
assembler.fillVertexBuffer(comp, vertexOffset, verts, uintVerts);
assembler.fillIndexBuffer(comp, indiceOffset, vertexId, indices);
-
+
vertexOffset += data.vertexCount;
indiceOffset += data.indiceCount;
+ prevComp = comp;
}
// last batch
- this._checkBatchBroken(comp && comp._vertexFormat, currEffect, vertexOffset, indiceOffset, false);
+ this._checkBatchBroken(prevComp && prevComp._vertexFormat, currEffect, vertexOffset, indiceOffset, false);
this._queue.length = 0;
},
diff --git a/cocos2d/core/renderer/render-engine.js b/cocos2d/core/renderer/render-engine.js
index 780b3f006b..d7cc5d24bc 100644
--- a/cocos2d/core/renderer/render-engine.js
+++ b/cocos2d/core/renderer/render-engine.js
@@ -7314,6 +7314,11 @@ module.exports = (function () {
LIGHT_POINT: 1,
LIGHT_SPOT: 2,
+ // shadows
+ SHADOW_NONE: 0,
+ SHADOW_HARD: 1,
+ SHADOW_SOFT: 2,
+
// parameter type
PARAM_INT: 0,
PARAM_INT2: 1,
@@ -7774,9 +7779,9 @@ module.exports = (function () {
return;
}
- let gl = this.device.gl;
+ let gl = this._device._gl;
gl.deleteBuffer(this._glID);
- this.device._stats.ib -= this.bytes;
+ this._device._stats.ib -= this.bytes;
this._glID = -1;
}
@@ -7853,9 +7858,9 @@ module.exports = (function () {
return;
}
- let gl = this.device.gl;
+ let gl = this._device._gl;
gl.deleteBuffer(this._glID);
- this.device._stats.vb -= this.bytes;
+ this._device._stats.vb -= this.bytes;
this._glID = -1;
}
@@ -8107,10 +8112,10 @@ module.exports = (function () {
return;
}
- let gl = this.device.gl;
+ let gl = this._device._gl;
gl.deleteTexture(this._glID);
- this.device._stats.tex -= this.bytes;
+ this._device._stats.tex -= this.bytes;
this._glID = -1;
}
}
@@ -10655,9 +10660,12 @@ module.exports = (function () {
this._matViewProj = mat4.create();
this._matInvViewProj = mat4.create();
- // stages
+ // stages & framebuffer
this._stages = [];
this._cullingByID = false;
+ this._framebuffer = null;
+
+ this._shadowLight = null; // TODO: should not refer light in view.
}
getForward(out) {
@@ -10675,11 +10683,37 @@ module.exports = (function () {
}
}
+ const _forward = vec3.new(0, 0, -1);
+
let _m4_tmp$1 = mat4.create();
let _m3_tmp = mat3.create();
- const _forward = vec3.new(0, 0, -1);
let _transformedLightDirection = vec3.create();
+ // compute light viewProjMat for shadow.
+ function _computeSpotLightViewProjMatrix(light, outView, outProj) {
+ // view matrix
+ light._node.getWorldRT(outView);
+ mat4.invert(outView, outView);
+
+ // proj matrix
+ mat4.perspective(outProj, light._spotAngle * light._spotAngleScale, 1, light._shadowMinDepth, light._shadowMaxDepth);
+ }
+
+ function _computeDirectionalLightViewProjMatrix(light, outView, outProj) {
+ // view matrix
+ light._node.getWorldRT(outView);
+ mat4.invert(outView, outView);
+
+ // TODO: should compute directional light frustum based on rendered meshes in scene.
+ // proj matrix
+ let halfSize = light._shadowFustumSize / 2;
+ mat4.ortho(outProj, -halfSize, halfSize, -halfSize, halfSize, light._shadowMinDepth, light._shadowMaxDepth);
+ }
+
+ function _computePointLightViewProjMatrix(light, outView, outProj) {
+ // TODO:
+ }
+
class Light {
constructor() {
this._poolID = -1;
@@ -10700,23 +10734,40 @@ module.exports = (function () {
this._positionUniform = new Float32Array(3);
this._colorUniform = new Float32Array([this._color.r * this._intensity, this._color.g * this._intensity, this._color.b * this._intensity]);
this._spotUniform = new Float32Array([Math.cos(this._spotAngle * 0.5), this._spotExp]);
+
+ // shadow params
+ this._shadowType = enums.SHADOW_NONE;
+ this._shadowFrameBuffer = null;
+ this._shadowMap = null;
+ this._shadowMapDirty = false;
+ this._shadowDepthBuffer = null;
+ this._shadowResolution = 1024;
+ this._shadowBias = 0.00005;
+ this._shadowDarkness = 1;
+ this._shadowMinDepth = 1;
+ this._shadowMaxDepth = 1000;
+ this._shadowDepthScale = 50; // maybe need to change it if the distance between shadowMaxDepth and shadowMinDepth is small.
+ this._frustumEdgeFalloff = 0; // used by directional and spot light.
+ this._viewProjMatrix = mat4.create();
+ this._spotAngleScale = 1; // used for spot light.
+ this._shadowFustumSize = 80; // used for directional light.
}
setNode(node) {
this._node = node;
}
- set color(val) {
- color3.copy(this._color, val);
- this._colorUniform[0] = val.r * this._intensity;
- this._colorUniform[1] = val.g * this._intensity;
- this._colorUniform[2] = val.b * this._intensity;
+ setColor(r, g, b) {
+ color3.set(this._color, r, g, b);
+ this._colorUniform[0] = r * this._intensity;
+ this._colorUniform[1] = g * this._intensity;
+ this._colorUniform[2] = b * this._intensity;
}
get color() {
return this._color;
}
- set intensity(val) {
+ setIntensity(val) {
this._intensity = val;
this._colorUniform[0] = val * this._color.r;
this._colorUniform[1] = val * this._color.g;
@@ -10726,14 +10777,14 @@ module.exports = (function () {
return this._intensity;
}
- set type(tpe) {
+ setType(tpe) {
this._type = tpe;
}
get type() {
return this._type;
}
- set spotAngle(val) {
+ setSpotAngle(val) {
this._spotAngle = val;
this._spotUniform[0] = Math.cos(this._spotAngle * 0.5);
}
@@ -10741,7 +10792,7 @@ module.exports = (function () {
return this._spotAngle;
}
- set spotExp(val) {
+ setSpotExp(val) {
this._spotExp = val;
this._spotUniform[1] = val;
}
@@ -10749,13 +10800,133 @@ module.exports = (function () {
return this._spotExp;
}
- set range(tpe) {
+ setRange(tpe) {
this._range = tpe;
}
get range() {
return this._range;
}
+ setShadowType(type) {
+ if (this._shadowType === enums.SHADOW_NONE && type !== enums.SHADOW_NONE) {
+ this._shadowMapDirty = true;
+ }
+ this._shadowType = type;
+ }
+ get shadowType() {
+ return this._shadowType;
+ }
+
+ get shadowMap() {
+ return this._shadowMap;
+ }
+
+ get viewProjMatrix() {
+ return this._viewProjMatrix;
+ }
+
+ setShadowResolution(val) {
+ if (this._shadowResolution !== val) {
+ this._shadowMapDirty = true;
+ }
+ this._shadowResolution = val;
+ }
+ get shadowResolution() {
+ return this._shadowResolution;
+ }
+
+ setShadowBias(val) {
+ this._shadowBias = val;
+ }
+ get shadowBias() {
+ return this._shadowBias;
+ }
+
+ setShadowDarkness(val) {
+ this._shadowDarkness = val;
+ }
+ get shadowDarkness() {
+ return this._shadowDarkness;
+ }
+
+ setShadowMinDepth(val) {
+ this._shadowMinDepth = val;
+ }
+ get shadowMinDepth() {
+ if (this._type === enums.LIGHT_DIRECTIONAL) {
+ return 1.0;
+ }
+ return this._shadowMinDepth;
+ }
+
+ setShadowMaxDepth(val) {
+ this._shadowMaxDepth = val;
+ }
+ get shadowMaxDepth() {
+ if (this._type === enums.LIGHT_DIRECTIONAL) {
+ return 1.0;
+ }
+ return this._shadowMaxDepth;
+ }
+
+ setShadowDepthScale(val) {
+ this._shadowDepthScale = val;
+ }
+ get shadowDepthScale() {
+ return this._shadowDepthScale;
+ }
+
+ setFrustumEdgeFalloff(val) {
+ this._frustumEdgeFalloff = val;
+ }
+ get frustumEdgeFalloff() {
+ return this._frustumEdgeFalloff;
+ }
+
+ extractView(out, stages) {
+ // TODO: view should not handle light.
+ out._shadowLight = this;
+
+ // rect
+ out._rect.x = 0;
+ out._rect.y = 0;
+ out._rect.w = this._shadowResolution;
+ out._rect.h = this._shadowResolution;
+
+ // clear opts
+ color4.set(out._color, 1, 1, 1, 1);
+ out._depth = 1;
+ out._stencil = 1;
+ out._clearFlags = enums.CLEAR_COLOR | enums.CLEAR_DEPTH;
+
+ // stages & framebuffer
+ out._stages = stages;
+ out._framebuffer = this._shadowFrameBuffer;
+
+ // view projection matrix
+ switch(this._type) {
+ case enums.LIGHT_SPOT:
+ _computeSpotLightViewProjMatrix(this, out._matView, out._matProj);
+ break;
+
+ case enums.LIGHT_DIRECTIONAL:
+ _computeDirectionalLightViewProjMatrix(this, out._matView, out._matProj);
+ break;
+
+ case enums.LIGHT_POINT:
+ _computePointLightViewProjMatrix(this, out._matView, out._matProj);
+ break;
+
+ default:
+ console.warn('shadow of this light type is not supported');
+ }
+
+ // view-projection
+ mat4.mul(out._matViewProj, out._matProj, out._matView);
+ this._viewProjMatrix = out._matViewProj;
+ mat4.invert(out._matInvViewProj, out._matViewProj);
+ }
+
_updateLightPositionAndDirection() {
this._node.getWorldMatrix(_m4_tmp$1);
mat3.fromMat4(_m3_tmp, _m4_tmp$1);
@@ -10767,8 +10938,47 @@ module.exports = (function () {
pos[2] = _m4_tmp$1.m14;
}
- update() {
+ _generateShadowMap(device) {
+ this._shadowMap = new gfx.Texture2D(device, {
+ width: this._shadowResolution,
+ height: this._shadowResolution,
+ format: gfx.TEXTURE_FMT_RGBA8,
+ wrapS: gfx.WRAP_CLAMP,
+ wrapT: gfx.WRAP_CLAMP,
+ });
+ this._shadowDepthBuffer = new gfx.RenderBuffer(device,
+ gfx.RB_FMT_D16,
+ this._shadowResolution,
+ this._shadowResolution
+ );
+ this._shadowFrameBuffer = new gfx.FrameBuffer(device, this._shadowResolution, this._shadowResolution, {
+ colors: [this._shadowMap],
+ depth: this._shadowDepthBuffer,
+ });
+ }
+
+ _destroyShadowMap() {
+ if (this._shadowMap) {
+ this._shadowMap.destroy();
+ this._shadowDepthBuffer.destroy();
+ this._shadowFrameBuffer.destroy();
+ this._shadowMap = null;
+ this._shadowDepthBuffer = null;
+ this._shadowFrameBuffer = null;
+ }
+ }
+
+ update(device) {
this._updateLightPositionAndDirection();
+
+ if (this._shadowType === enums.SHADOW_NONE) {
+ this._destroyShadowMap();
+ } else if (this._shadowMapDirty) {
+ this._destroyShadowMap();
+ this._generateShadowMap(device);
+ this._shadowMapDirty = false;
+ }
+
}
}
@@ -10792,6 +11002,10 @@ module.exports = (function () {
this._stencil = 1;
this._clearFlags = enums.CLEAR_COLOR | enums.CLEAR_DEPTH;
+ // stages & framebuffer
+ this._stages = [];
+ this._framebuffer = null;
+
// projection properties
this._near = 0.01;
this._far = 1000.0;
@@ -10803,7 +11017,32 @@ module.exports = (function () {
// ortho properties
this._orthoHeight = 10;
- this._stages = [];
+ }
+
+ setNode(node) {
+ this._node = node;
+ }
+
+ setType(type) {
+ this._projection = type;
+ }
+
+ setFov(fov) {
+ this._fov = fov;
+ }
+
+ setNear(near) {
+ this._near = near;
+ }
+ getNear() {
+ return this._near;
+ }
+
+ setFar(far) {
+ this._far = far;
+ }
+ getFar() {
+ return this._far;
}
setColor(r, g, b, a) {
@@ -10822,10 +11061,6 @@ module.exports = (function () {
this._clearFlags = flags;
}
- setNode(node) {
- this._node = node;
- }
-
/**
* @param {Number} x - [0,1]
* @param {Number} y - [0,1]
@@ -10843,6 +11078,10 @@ module.exports = (function () {
this._stages = stages;
}
+ setFramebuffer(framebuffer) {
+ this._framebuffer = framebuffer;
+ }
+
extractView(out, width, height) {
// rect
out._rect.x = this._rect.x * width;
@@ -10856,6 +11095,10 @@ module.exports = (function () {
out._stencil = this._stencil;
out._clearFlags = this._clearFlags;
+ // stages & framebuffer
+ out._stages = this._stages;
+ out._framebuffer = this._framebuffer;
+
// view matrix
this._node.getWorldRT(out._matView);
mat4.invert(out._matView, out._matView);
@@ -10881,9 +11124,6 @@ module.exports = (function () {
// view-projection
mat4.mul(out._matViewProj, out._matProj, out._matView);
mat4.invert(out._matInvViewProj, out._matViewProj);
-
- // stages
- out._stages = this._stages;
}
screenToWorld(out, screenPos, width, height) {
@@ -12357,623 +12597,6 @@ module.exports = (function () {
}
}
- /*!
- * mustache.js - Logic-less {{mustache}} templates with JavaScript
- * http://github.com/janl/mustache.js
- */
-
- let mustache = {};
-
- var objectToString = Object.prototype.toString;
- var isArray = Array.isArray || function isArrayPolyfill(object) {
- return objectToString.call(object) === '[object Array]';
- };
-
- function isFunction(object) {
- return typeof object === 'function';
- }
-
- /**
- * More correct typeof string handling array
- * which normally returns typeof 'object'
- */
- function typeStr(obj) {
- return isArray(obj) ? 'array' : typeof obj;
- }
-
- function escapeRegExp(string) {
- return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&');
- }
-
- /**
- * Null safe way of checking whether or not an object,
- * including its prototype, has a given property
- */
- function hasProperty(obj, propName) {
- return obj != null && typeof obj === 'object' && (propName in obj);
- }
-
- // Workaround for https://issues.apache.org/jira/browse/COUCHDB-577
- // See https://github.com/janl/mustache.js/issues/189
- var regExpTest = RegExp.prototype.test;
- function testRegExp(re, string) {
- return regExpTest.call(re, string);
- }
-
- var nonSpaceRe = /\S/;
- function isWhitespace(string) {
- return !testRegExp(nonSpaceRe, string);
- }
-
- var entityMap = {
- '&': '&',
- '<': '<',
- '>': '>',
- '"': '"',
- "'": ''',
- '/': '/',
- '`': '`',
- '=': '='
- };
-
- function escapeHtml(string) {
- return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap(s) {
- return entityMap[s];
- });
- }
-
- var whiteRe = /\s*/;
- var spaceRe = /\s+/;
- var equalsRe = /\s*=/;
- var curlyRe = /\s*\}/;
- var tagRe = /#|\^|\/|>|\{|&|=|!/;
-
- /**
- * Breaks up the given `template` string into a tree of tokens. If the `tags`
- * argument is given here it must be an array with two string values: the
- * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of
- * course, the default is to use mustaches (i.e. mustache.tags).
- *
- * A token is an array with at least 4 elements. The first element is the
- * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag
- * did not contain a symbol (i.e. {{myValue}}) this element is "name". For
- * all text that appears outside a symbol this element is "text".
- *
- * The second element of a token is its "value". For mustache tags this is
- * whatever else was inside the tag besides the opening symbol. For text tokens
- * this is the text itself.
- *
- * The third and fourth elements of the token are the start and end indices,
- * respectively, of the token in the original template.
- *
- * Tokens that are the root node of a subtree contain two more elements: 1) an
- * array of tokens in the subtree and 2) the index in the original template at
- * which the closing tag for that section begins.
- */
- function parseTemplate(template, tags) {
- if (!template)
- return [];
-
- var sections = []; // Stack to hold section tokens
- var tokens = []; // Buffer to hold the tokens
- var spaces = []; // Indices of whitespace tokens on the current line
- var hasTag = false; // Is there a {{tag}} on the current line?
- var nonSpace = false; // Is there a non-space char on the current line?
-
- // Strips all whitespace tokens array for the current line
- // if there was a {{#tag}} on it and otherwise only space.
- function stripSpace() {
- if (hasTag && !nonSpace) {
- while (spaces.length)
- delete tokens[spaces.pop()];
- } else {
- spaces = [];
- }
-
- hasTag = false;
- nonSpace = false;
- }
-
- var openingTagRe, closingTagRe, closingCurlyRe;
- function compileTags(tagsToCompile) {
- if (typeof tagsToCompile === 'string')
- tagsToCompile = tagsToCompile.split(spaceRe, 2);
-
- if (!isArray(tagsToCompile) || tagsToCompile.length !== 2)
- throw new Error('Invalid tags: ' + tagsToCompile);
-
- openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*');
- closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1]));
- closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1]));
- }
-
- compileTags(tags || mustache.tags);
-
- var scanner = new Scanner(template);
-
- var start, type, value, chr, token, openSection;
- while (!scanner.eos()) {
- start = scanner.pos;
-
- // Match any text between tags.
- value = scanner.scanUntil(openingTagRe);
-
- if (value) {
- for (var i = 0, valueLength = value.length; i < valueLength; ++i) {
- chr = value.charAt(i);
-
- if (isWhitespace(chr)) {
- spaces.push(tokens.length);
- } else {
- nonSpace = true;
- }
-
- tokens.push(['text', chr, start, start + 1]);
- start += 1;
-
- // Check for whitespace on the current line.
- if (chr === '\n')
- stripSpace();
- }
- }
-
- // Match the opening tag.
- if (!scanner.scan(openingTagRe))
- break;
-
- hasTag = true;
-
- // Get the tag type.
- type = scanner.scan(tagRe) || 'name';
- scanner.scan(whiteRe);
-
- // Get the tag value.
- if (type === '=') {
- value = scanner.scanUntil(equalsRe);
- scanner.scan(equalsRe);
- scanner.scanUntil(closingTagRe);
- } else if (type === '{') {
- value = scanner.scanUntil(closingCurlyRe);
- scanner.scan(curlyRe);
- scanner.scanUntil(closingTagRe);
- type = '&';
- } else {
- value = scanner.scanUntil(closingTagRe);
- }
-
- // Match the closing tag.
- if (!scanner.scan(closingTagRe))
- throw new Error('Unclosed tag at ' + scanner.pos);
-
- token = [type, value, start, scanner.pos];
- tokens.push(token);
-
- if (type === '#' || type === '^') {
- sections.push(token);
- } else if (type === '/') {
- // Check section nesting.
- openSection = sections.pop();
-
- if (!openSection)
- throw new Error('Unopened section "' + value + '" at ' + start);
-
- if (openSection[1] !== value)
- throw new Error('Unclosed section "' + openSection[1] + '" at ' + start);
- } else if (type === 'name' || type === '{' || type === '&') {
- nonSpace = true;
- } else if (type === '=') {
- // Set the tags for the next time around.
- compileTags(value);
- }
- }
-
- // Make sure there are no open sections when we're done.
- openSection = sections.pop();
-
- if (openSection)
- throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos);
-
- return nestTokens(squashTokens(tokens));
- }
-
- /**
- * Combines the values of consecutive text tokens in the given `tokens` array
- * to a single token.
- */
- function squashTokens(tokens) {
- var squashedTokens = [];
-
- var token, lastToken;
- for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
- token = tokens[i];
-
- if (token) {
- if (token[0] === 'text' && lastToken && lastToken[0] === 'text') {
- lastToken[1] += token[1];
- lastToken[3] = token[3];
- } else {
- squashedTokens.push(token);
- lastToken = token;
- }
- }
- }
-
- return squashedTokens;
- }
-
- /**
- * Forms the given array of `tokens` into a nested tree structure where
- * tokens that represent a section have two additional items: 1) an array of
- * all tokens that appear in that section and 2) the index in the original
- * template that represents the end of that section.
- */
- function nestTokens(tokens) {
- var nestedTokens = [];
- var collector = nestedTokens;
- var sections = [];
-
- var token, section;
- for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
- token = tokens[i];
-
- switch (token[0]) {
- case '#':
- case '^':
- collector.push(token);
- sections.push(token);
- collector = token[4] = [];
- break;
- case '/':
- section = sections.pop();
- section[5] = token[2];
- collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens;
- break;
- default:
- collector.push(token);
- }
- }
-
- return nestedTokens;
- }
-
- /**
- * A simple string scanner that is used by the template parser to find
- * tokens in template strings.
- */
- function Scanner(string) {
- this.string = string;
- this.tail = string;
- this.pos = 0;
- }
-
- /**
- * Returns `true` if the tail is empty (end of string).
- */
- Scanner.prototype.eos = function eos() {
- return this.tail === '';
- };
-
- /**
- * Tries to match the given regular expression at the current position.
- * Returns the matched text if it can match, the empty string otherwise.
- */
- Scanner.prototype.scan = function scan(re) {
- var match = this.tail.match(re);
-
- if (!match || match.index !== 0)
- return '';
-
- var string = match[0];
-
- this.tail = this.tail.substring(string.length);
- this.pos += string.length;
-
- return string;
- };
-
- /**
- * Skips all text until the given regular expression can be matched. Returns
- * the skipped string, which is the entire tail if no match can be made.
- */
- Scanner.prototype.scanUntil = function scanUntil(re) {
- var index = this.tail.search(re), match;
-
- switch (index) {
- case -1:
- match = this.tail;
- this.tail = '';
- break;
- case 0:
- match = '';
- break;
- default:
- match = this.tail.substring(0, index);
- this.tail = this.tail.substring(index);
- }
-
- this.pos += match.length;
-
- return match;
- };
-
- /**
- * Represents a rendering context by wrapping a view object and
- * maintaining a reference to the parent context.
- */
- function Context(view, parentContext) {
- this.view = view;
- this.cache = { '.': this.view };
- this.parent = parentContext;
- }
-
- /**
- * Creates a new context using the given view with this context
- * as the parent.
- */
- Context.prototype.push = function push(view) {
- return new Context(view, this);
- };
-
- /**
- * Returns the value of the given name in this context, traversing
- * up the context hierarchy if the value is absent in this context's view.
- */
- Context.prototype.lookup = function lookup(name) {
- var cache = this.cache;
-
- var value;
- if (cache.hasOwnProperty(name)) {
- value = cache[name];
- } else {
- var context = this, names, index, lookupHit = false;
-
- while (context) {
- if (name.indexOf('.') > 0) {
- value = context.view;
- names = name.split('.');
- index = 0;
-
- /**
- * Using the dot notion path in `name`, we descend through the
- * nested objects.
- *
- * To be certain that the lookup has been successful, we have to
- * check if the last object in the path actually has the property
- * we are looking for. We store the result in `lookupHit`.
- *
- * This is specially necessary for when the value has been set to
- * `undefined` and we want to avoid looking up parent contexts.
- **/
- while (value != null && index < names.length) {
- if (index === names.length - 1)
- lookupHit = hasProperty(value, names[index]);
-
- value = value[names[index++]];
- }
- } else {
- value = context.view[name];
- lookupHit = hasProperty(context.view, name);
- }
-
- if (lookupHit)
- break;
-
- context = context.parent;
- }
-
- cache[name] = value;
- }
-
- if (isFunction(value))
- value = value.call(this.view);
-
- return value;
- };
-
- /**
- * A Writer knows how to take a stream of tokens and render them to a
- * string, given a context. It also maintains a cache of templates to
- * avoid the need to parse the same template twice.
- */
- function Writer() {
- this.cache = {};
- }
-
- /**
- * Clears all cached templates in this writer.
- */
- Writer.prototype.clearCache = function clearCache() {
- this.cache = {};
- };
-
- /**
- * Parses and caches the given `template` and returns the array of tokens
- * that is generated from the parse.
- */
- Writer.prototype.parse = function parse(template, tags) {
- var cache = this.cache;
- var tokens = cache[template];
-
- if (tokens == null)
- tokens = cache[template] = parseTemplate(template, tags);
-
- return tokens;
- };
-
- /**
- * High-level method that is used to render the given `template` with
- * the given `view`.
- *
- * The optional `partials` argument may be an object that contains the
- * names and templates of partials that are used in the template. It may
- * also be a function that is used to load partial templates on the fly
- * that takes a single argument: the name of the partial.
- */
- Writer.prototype.render = function render(template, view, partials) {
- var tokens = this.parse(template);
- var context = (view instanceof Context) ? view : new Context(view);
- return this.renderTokens(tokens, context, partials, template);
- };
-
- /**
- * Low-level method that renders the given array of `tokens` using
- * the given `context` and `partials`.
- *
- * Note: The `originalTemplate` is only ever used to extract the portion
- * of the original template that was contained in a higher-order section.
- * If the template doesn't use higher-order sections, this argument may
- * be omitted.
- */
- Writer.prototype.renderTokens = function renderTokens(tokens, context, partials, originalTemplate) {
- var buffer = '';
-
- var token, symbol, value;
- for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) {
- value = undefined;
- token = tokens[i];
- symbol = token[0];
-
- if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate);
- else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate);
- else if (symbol === '>') value = this.renderPartial(token, context, partials, originalTemplate);
- else if (symbol === '&') value = this.unescapedValue(token, context);
- else if (symbol === 'name') value = this.escapedValue(token, context);
- else if (symbol === 'text') value = this.rawValue(token);
-
- if (value !== undefined)
- buffer += value;
- }
-
- return buffer;
- };
-
- Writer.prototype.renderSection = function renderSection(token, context, partials, originalTemplate) {
- var self = this;
- var buffer = '';
- var value = context.lookup(token[1]);
-
- // This function is used to render an arbitrary template
- // in the current context by higher-order sections.
- function subRender(template) {
- return self.render(template, context, partials);
- }
-
- if (!value) return;
-
- if (isArray(value)) {
- for (var j = 0, valueLength = value.length; j < valueLength; ++j) {
- buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate);
- }
- } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') {
- buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate);
- } else if (isFunction(value)) {
- if (typeof originalTemplate !== 'string')
- throw new Error('Cannot use higher-order sections without the original template');
-
- // Extract the portion of the original template that the section contains.
- value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender);
-
- if (value != null)
- buffer += value;
- } else {
- buffer += this.renderTokens(token[4], context, partials, originalTemplate);
- }
- return buffer;
- };
-
- Writer.prototype.renderInverted = function renderInverted(token, context, partials, originalTemplate) {
- var value = context.lookup(token[1]);
-
- // Use JavaScript's definition of falsy. Include empty arrays.
- // See https://github.com/janl/mustache.js/issues/186
- if (!value || (isArray(value) && value.length === 0))
- return this.renderTokens(token[4], context, partials, originalTemplate);
- };
-
- Writer.prototype.renderPartial = function renderPartial(token, context, partials) {
- if (!partials) return;
-
- var value = isFunction(partials) ? partials(token[1]) : partials[token[1]];
- if (value != null)
- return this.renderTokens(this.parse(value), context, partials, value);
- };
-
- Writer.prototype.unescapedValue = function unescapedValue(token, context) {
- var value = context.lookup(token[1]);
- if (value != null)
- return value;
- };
-
- Writer.prototype.escapedValue = function escapedValue(token, context) {
- var value = context.lookup(token[1]);
- if (value != null)
- return mustache.escape(value);
- };
-
- Writer.prototype.rawValue = function rawValue(token) {
- return token[1];
- };
-
- mustache.name = 'mustache.js';
- mustache.version = '2.3.0';
- mustache.tags = ['{{', '}}'];
-
- // All high-level mustache.* functions use this writer.
- var defaultWriter = new Writer();
-
- /**
- * Clears all cached templates in the default writer.
- */
- mustache.clearCache = function clearCache() {
- return defaultWriter.clearCache();
- };
-
- /**
- * Parses and caches the given template in the default writer and returns the
- * array of tokens it contains. Doing this ahead of time avoids the need to
- * parse templates on the fly as they are rendered.
- */
- mustache.parse = function parse(template, tags) {
- return defaultWriter.parse(template, tags);
- };
-
- /**
- * Renders the `template` with the given `view` and `partials` using the
- * default writer.
- */
- mustache.render = function render(template, view, partials) {
- if (typeof template !== 'string') {
- throw new TypeError('Invalid template! Template should be a "string" ' +
- 'but "' + typeStr(template) + '" was given as the first ' +
- 'argument for mustache#render(template, view, partials)');
- }
-
- return defaultWriter.render(template, view, partials);
- };
-
- // This is here for backwards compatibility with 0.4.x.,
- /*eslint-disable */ // eslint wants camel cased function name
- mustache.to_html = function to_html(template, view, partials, send) {
- /*eslint-enable*/
-
- var result = mustache.render(template, view, partials);
-
- if (isFunction(send)) {
- send(result);
- } else {
- return result;
- }
- };
-
- // Export the escaping function so that the user may override it.
- // See https://github.com/janl/mustache.js/issues/244
- mustache.escape = escapeHtml;
-
- // Export these mainly for testing, but also for advanced usage.
- mustache.Scanner = Scanner;
- mustache.Context = Context;
- mustache.Writer = Writer;
-
var builtinChunks = {
'skinning.vert': 'attribute vec4 a_weights;\nattribute vec4 a_joints;\nuniform sampler2D u_jointsTexture;\nuniform float u_jointsTextureSize;\nmat4 getBoneMatrix(const in float i) {\n float size = u_jointsTextureSize;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(u_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(u_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(u_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(u_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w\n ;\n}',
'unpack-normal.frag': 'vec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}',
@@ -12982,8 +12605,8 @@ module.exports = (function () {
var builtinTemplates = [
{
name: 'simple',
- vert: '\nattribute vec3 a_position;\nuniform mat4 model;\nuniform mat4 viewProj;\n{{#useTexture}}\n attribute vec2 a_uv0;\n varying vec2 uv0;\n{{/useTexture}}\nvoid main () {\n vec4 pos = viewProj * model * vec4(a_position, 1);\n {{#useTexture}}\n uv0 = a_uv0;\n {{/useTexture}}\n gl_Position = pos;\n}',
- frag: '\n{{#useTexture}}\n uniform sampler2D texture;\n varying vec2 uv0;\n{{/useTexture}}\n{{#useColor}}\n uniform vec4 color;\n{{/useColor}}\nvoid main () {\n vec4 o = vec4(1, 1, 1, 1);\n {{#useTexture}}\n o *= texture2D(texture, uv0);\n {{/useTexture}}\n {{#useColor}}\n o *= color;\n {{/useColor}}\n if (!gl_FrontFacing) {\n o.rgb *= 0.5;\n }\n gl_FragColor = o;\n}',
+ vert: '\nattribute vec3 a_position;\nuniform mat4 model;\nuniform mat4 viewProj;\n#ifdef useTexture\n attribute vec2 a_uv0;\n varying vec2 uv0;\n#endif\nvoid main () {\n vec4 pos = viewProj * model * vec4(a_position, 1);\n #ifdef useTexture\n uv0 = a_uv0;\n #endif\n gl_Position = pos;\n}',
+ frag: '\n#ifdef useTexture\n uniform sampler2D texture;\n varying vec2 uv0;\n#endif\n#ifdef useColor\n uniform vec4 color;\n#endif\nvoid main () {\n vec4 o = vec4(1, 1, 1, 1);\n #ifdef useTexture\n o *= texture2D(texture, uv0);\n #endif\n #ifdef useColor\n o *= color;\n #endif\n if (!gl_FrontFacing) {\n o.rgb *= 0.5;\n }\n gl_FragColor = o;\n}',
options: [
{ name: 'useTexture', },
{ name: 'useColor', },
@@ -12993,6 +12616,48 @@ module.exports = (function () {
let _shdID = 0;
+ function _generateDefines(options) {
+ let defines = [];
+ for (let opt in options) {
+ if (options[opt] === true) {
+ defines.push(`#define ${opt}`);
+ }
+ }
+ return defines.join('\n');
+ }
+
+ function _replaceMacroNums(string, options) {
+ let cache = {};
+ let tmp = string;
+ for (let opt in options) {
+ if (Number.isInteger(options[opt])) {
+ cache[opt] = options[opt];
+ }
+ }
+ for (let opt in cache) {
+ let reg = new RegExp(opt, 'g');
+ tmp = tmp.replace(reg, cache[opt]);
+ }
+ return tmp;
+ }
+
+ function _unrollLoops(string) {
+ let pattern = /#pragma for (\w+) in range\(\s*(\d+)\s*,\s*(\d+)\s*\)([\s\S]+?)#pragma endFor/g;
+ function replace(match, index, begin, end, snippet) {
+ let unroll = '';
+ let parsedBegin = parseInt(begin);
+ let parsedEnd = parseInt(end);
+ if (parsedBegin.isNaN || parsedEnd.isNaN) {
+ console.error('Unroll For Loops Error: begin and end of range must be an int num.');
+ }
+ for (let i = parsedBegin; i < parsedEnd; ++i) {
+ unroll += snippet.replace(new RegExp(`{${index}}`, 'g'), i);
+ }
+ return unroll;
+ }
+ return string.replace(pattern, replace);
+ }
+
class ProgramLib {
/**
* @param {gfx.Device} device
@@ -13072,10 +12737,6 @@ module.exports = (function () {
vert = this._precision + vert;
frag = this._precision + frag;
- // pre-parse the vs and fs template to speed up `mustache.render()` method
- mustache.parse(vert);
- mustache.parse(frag);
-
// store it
this._templates[name] = {
id,
@@ -13119,8 +12780,11 @@ module.exports = (function () {
// get template
let tmpl = this._templates[name];
- let vert = mustache.render(tmpl.vert, options, this._chunks);
- let frag = mustache.render(tmpl.frag, options, this._chunks);
+ let customDef = _generateDefines(options) + '\n';
+ let vert = _replaceMacroNums(tmpl.vert, options);
+ vert = customDef + _unrollLoops(vert);
+ let frag = _replaceMacroNums(tmpl.frag, options);
+ frag = customDef + _unrollLoops(frag);
program = new gfx.Program(this._device, {
vert,
@@ -13436,6 +13100,7 @@ module.exports = (function () {
[enums.PARAM_TEXTURE_CUBE]: opts.defaultTextureCube,
};
this._stage2fn = {};
+ this._usedTextureUnits = 0;
this._viewPools = new RecyclePool(() => {
return new View();
@@ -13466,6 +13131,22 @@ module.exports = (function () {
}, 16);
}
+ _resetTextuerUnit() {
+ this._usedTextureUnits = 0;
+ }
+
+ _allocTextuerUnit() {
+ const device = this._device;
+
+ let unit = this._usedTextureUnits;
+ if (unit >= device._caps.maxTextureUnits) {
+ console.warn(`Trying to use ${unit} texture units while this GPU supports only ${device._caps.maxTextureUnits}`);
+ }
+
+ this._usedTextureUnits += 1;
+ return unit;
+ }
+
_registerStage(name, fn) {
this._stage2fn[name] = fn;
}
@@ -13482,6 +13163,9 @@ module.exports = (function () {
_render(view, scene) {
const device = this._device;
+ // setup framebuffer
+ device.setFrameBuffer(view._framebuffer);
+
// setup viewport
device.setViewport(
view._rect.x,
@@ -13603,7 +13287,6 @@ module.exports = (function () {
// }
// set technique uniforms
- let slot = 0;
for (let i = 0; i < technique._parameters.length; ++i) {
let prop = technique._parameters[i];
let param = effect.getValue(prop.name);
@@ -13632,13 +13315,11 @@ module.exports = (function () {
}
let slots = _int64_pool.add();
for (let index = 0; index < param.length; ++index) {
- slots[index] = slot + index;
+ slots[index] = this._allocTextuerUnit();
}
device.setTextureArray(prop.name, param, slots);
- slot = slot + prop.size;
} else {
- device.setTexture(prop.name, param, slot);
- ++slot;
+ device.setTexture(prop.name, param, this._allocTextuerUnit());
}
} else {
let convertedValue;
@@ -13742,6 +13423,8 @@ module.exports = (function () {
// draw pass
device.draw(ia._start, count);
+
+ this._resetTextuerUnit();
}
}
}
@@ -13805,13 +13488,14 @@ module.exports = (function () {
// draw it
for (let i = 0; i < items.length; ++i) {
let item = items.data[i];
- var ia = item.ia;
- var vb = ia._vertexBuffer;
- var ib = ia._indexBuffer;
- if (vb && ib) {
- vb.update(0, vb._data);
- ib.update(0, ib._data);
- }
+
+ // Update vertex buffer and index buffer
+ let ia = item.ia;
+ let vb = ia._vertexBuffer;
+ let ib = ia._indexBuffer;
+ vb.update(0, vb._data);
+ ib.update(0, ib._data);
+
this._draw(item);
}
}
@@ -14068,11 +13752,12 @@ module.exports = (function () {
var templates = [
{
name: 'sprite',
- vert: 'uniform mat4 viewProj;\nattribute vec3 a_position;\nattribute vec4 a_color;\nvarying lowp vec4 v_fragmentColor;\n{{#useModel}}\nuniform mat4 model;\n{{/useModel}}\n{{#useTexture}}\nattribute vec2 a_uv0;\nvarying vec2 uv0;\n{{/useTexture}}\nvoid main () {\n vec4 pos = viewProj{{#useModel}} * model{{/useModel}} * vec4(a_position, 1);\n v_fragmentColor = a_color;\n \n {{#useTexture}}\n uv0 = a_uv0;\n {{/useTexture}}\n gl_Position = pos;\n}',
- frag: '{{#useTexture}}\nuniform sampler2D texture;\nvarying vec2 uv0;\n{{/useTexture}}\nvarying vec4 v_fragmentColor;\nvoid main () {\n vec4 o = v_fragmentColor;\n {{#useTexture}}\n o *= texture2D(texture, uv0);\n {{/useTexture}}\n gl_FragColor = o;\n}',
+ vert: 'uniform mat4 viewProj;\nattribute vec3 a_position;\nattribute vec4 a_color;\nvarying lowp vec4 v_fragmentColor;\n#ifdef useModel\n uniform mat4 model;\n#endif\n#ifdef useTexture\n attribute vec2 a_uv0;\n varying vec2 uv0;\n#endif\nvoid main () {\n vec4 pos;\n #ifdef useModel\n pos = model * vec4(a_position, 1);\n #else\n pos = vec4(a_position, 1);\n #endif\n pos = viewProj * pos;\n v_fragmentColor = a_color;\n \n #ifdef useTexture\n uv0 = a_uv0;\n #endif\n gl_Position = pos;\n}',
+ frag: '#ifdef useTexture\n uniform sampler2D texture;\n varying vec2 uv0;\n#endif\n#ifdef alphaTest\n uniform float alphaThreshold;\n#endif\nvarying vec4 v_fragmentColor;\nvoid main () {\n vec4 o = v_fragmentColor;\n #ifdef useTexture\n o *= texture2D(texture, uv0);\n #endif\n #ifdef alphaTest\n if (o.a <= alphaThreshold)\n discard;\n #endif\n gl_FragColor = o;\n}',
options: [
{ name: 'useTexture', },
{ name: 'useModel', },
+ { name: 'alphaTest', },
],
},
];
@@ -14174,6 +13859,7 @@ module.exports = (function () {
x: 0, y: 0, w: 1, h: 1
};
this._stages = [];
+ this._framebuffer = null;
// matrix
this._matView = mat4.create();
@@ -14207,6 +13893,10 @@ module.exports = (function () {
this._stages = stages;
}
+ setFramebuffer(framebuffer) {
+ this._framebuffer = framebuffer;
+ }
+
setNode (node) {
this._node = node;
// view matrix
@@ -14270,8 +13960,7 @@ module.exports = (function () {
x: 0.0,
y: 0.0,
u: 0.0,
- v: 0.0,
- color: 0
+ v: 0.0
};
}, 128);
@@ -14366,6 +14055,34 @@ module.exports = (function () {
}
}
+ class MaterialUtil {
+ constructor () {
+ this._cache = {};
+ }
+
+ get (key) {
+ return this._cache[key];
+ }
+
+ register (key, material) {
+ if (key === undefined || this._cache[key]) {
+ console.warn("Material key is invalid or already exists");
+ }
+ else if (!material instanceof Material) {
+ console.warn("Invalid Material");
+ }
+ else {
+ this._cache[key] = material;
+ }
+ }
+
+ unregister (key) {
+ if (key !== undefined) {
+ delete this._cache[key];
+ }
+ }
+ }
+
class SpriteMaterial extends Material {
constructor() {
super(false);
@@ -14398,6 +14115,7 @@ module.exports = (function () {
[
{ name: 'useTexture', value: true },
{ name: 'useModel', value: false },
+ { name: 'alphaTest', value: false },
]
);
@@ -14437,31 +14155,86 @@ module.exports = (function () {
}
}
- class MaterialUtil {
- constructor () {
- this._cache = {};
+ class StencilMaterial extends Material {
+ constructor() {
+ super(false);
+
+ this._pass = new renderer.Pass('sprite');
+ this._pass.setDepth(false, false);
+ this._pass.setCullMode(gfx.CULL_NONE);
+ this._pass.setBlend(
+ gfx.BLEND_FUNC_ADD,
+ gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA,
+ gfx.BLEND_FUNC_ADD,
+ gfx.BLEND_SRC_ALPHA, gfx.BLEND_ONE_MINUS_SRC_ALPHA
+ );
+
+ let mainTech = new renderer.Technique(
+ ['transparent'],
+ [
+ { name: 'texture', type: renderer.PARAM_TEXTURE_2D },
+ { name: 'alphaThreshold', type: renderer.PARAM_FLOAT },
+ ],
+ [
+ this._pass
+ ]
+ );
+
+ this._effect = new renderer.Effect(
+ [
+ mainTech,
+ ],
+ {},
+ [
+ { name: 'useTexture', value: true },
+ { name: 'useModel', value: false },
+ { name: 'alphaTest', value: true },
+ ]
+ );
+
+ this._mainTech = mainTech;
}
- get (key) {
- return this._cache[key];
+ get effect () {
+ return this._effect;
+ }
+
+ get useTexture () {
+ this._effect.getOption('useTexture', val);
}
- register (key, material) {
- if (key === undefined || this._cache[key]) {
- console.warn("Material key is invalid or already exists");
- }
- else if (!material instanceof Material) {
- console.warn("Invalid Material");
- }
- else {
- this._cache[key] = material;
- }
+ set useTexture (val) {
+ this._effect.setOption('useTexture', val);
}
- unregister (key) {
- if (key !== undefined) {
- delete this._cache[key];
+ get texture () {
+ return this._effect.getValue('texture');
+ }
+
+ set texture (val) {
+ this._effect.setValue('texture', val);
+ }
+
+ get alphaThreshold () {
+ return this._effect.getValue('alphaThreshold');
+ }
+
+ set alphaThreshold (val) {
+ this._effect.setValue('alphaThreshold', val);
+ }
+
+ clone () {
+ let originValues = this._effect._values,
+ values = {};
+ for (let name in originValues) {
+ let value = originValues[name];
+ values[name] = value[name];
}
+ let copy = new StencilMaterial(values);
+ copy.useTexture = this.useTexture;
+ copy.texture = this.texture;
+ copy.alphaThreshold = this.alphaThreshold;
+ return copy;
}
}
@@ -14493,6 +14266,7 @@ module.exports = (function () {
// materials
SpriteMaterial,
+ StencilMaterial,
// shaders
shaders,
diff --git a/cocos2d/core/renderer/stencil-manager.js b/cocos2d/core/renderer/stencil-manager.js
new file mode 100644
index 0000000000..2170d72c4e
--- /dev/null
+++ b/cocos2d/core/renderer/stencil-manager.js
@@ -0,0 +1,134 @@
+const Enums = require('../platform/CCEnum');
+const gfx = require('./render-engine').gfx;
+
+// Stage types
+var Stage = cc.Enum({
+ // Stencil disabled
+ DISABLED: 0,
+ // Entering a new level, should handle new stencil
+ ENTER_LEVEL: 1,
+ // In stencil
+ ENABLED: 2,
+ // Exiting a level, should restore old stencil or disable
+ EXIT_LEVEL: 3,
+});
+
+function StencilManager () {
+ // todo: 8 is least Stencil depth supported by webGL device, it could be adjusted to vendor implementation value
+ this._maxLevel = 8;
+ // Current mask
+ this._maskStack = [];
+ // Current stage of process, DISABLED, ENTER_LEVEL, ENABLED, EXIT_LEVEL
+ this.stage = Stage.DISABLED;
+}
+
+StencilManager.prototype = {
+ constructor: StencilManager,
+
+ handleEffect (effect) {
+ let technique = effect.getTechnique('transparent');
+ if (this.stage === Stage.DISABLED) {
+ this.stage = Stage.DISABLED;
+ for (let i = 0; i < technique._passes.length; ++i) {
+ let pass = technique._passes[i];
+ pass._stencilTest = false;
+ }
+ return;
+ }
+
+ let mask, func, ref, stencilMask, writeMask, failOp,
+ zFailOp = gfx.STENCIL_OP_KEEP,
+ zPassOp = gfx.STENCIL_OP_KEEP;
+
+ if (this.stage === Stage.ENABLED) {
+ func = gfx.DS_FUNC_EQUAL;
+ mask = this._maskStack[this._maskStack.length - 1];
+ if (mask.inverted) {
+ ref = this.getInvertedRef();
+ stencilMask = this.getStencilRef();
+ }
+ else {
+ ref = this.getStencilRef();
+ stencilMask = ref;
+ }
+ failOp = gfx.STENCIL_OP_KEEP;
+ writeMask = 0;
+ }
+ else {
+ func = gfx.DS_FUNC_NEVER;
+ failOp = gfx.STENCIL_OP_REPLACE;
+
+ if (this.stage === Stage.ENTER_LEVEL) {
+ this.stage = Stage.ENABLED;
+ // Fill stencil mask
+ ref = this.getStencilRef();
+ stencilMask = this.getWriteMask();
+ writeMask = stencilMask;
+ }
+ else if (this.stage === Stage.EXIT_LEVEL) {
+ // Pop mask after getting the correct stencil mask
+ if (this._maskStack.length === 0) {
+ this.stage = Stage.DISABLED;
+ }
+ else {
+ this.stage = Stage.ENABLED;
+ }
+ // Clear stencil mask
+ ref = 0;
+ stencilMask = this.getExitWriteMask();
+ writeMask = stencilMask;
+ }
+ }
+
+ for (let i = 0; i < technique._passes.length; ++i) {
+ let pass = technique._passes[i];
+ pass.setStencilFront(func, ref, stencilMask, failOp, zFailOp, zPassOp, writeMask);
+ pass.setStencilBack(func, ref, stencilMask, failOp, zFailOp, zPassOp, writeMask);
+ }
+ },
+
+ pushMask (mask) {
+ if (this._maskStack.length + 1 > this._maxLevel) {
+ cc.errorID(9000, this._maxLevel);
+ }
+ this._maskStack.push(mask);
+ this.stage = Stage.ENTER_LEVEL;
+ },
+
+ popMask () {
+ if (this._maskStack.length === 0) {
+ cc.errorID(9001);
+ }
+ this._maskStack.pop();
+ this.stage = Stage.EXIT_LEVEL;
+ },
+
+ getWriteMask () {
+ return 0x01 << (this._maskStack.length - 1);
+ },
+
+ getExitWriteMask () {
+ return 0x01 << this._maskStack.length;
+ },
+
+ getStencilRef () {
+ let result = 0;
+ for (let i = 0; i < this._maskStack.length; ++i) {
+ result += (0x01 << i);
+ }
+ return result;
+ },
+
+ getInvertedRef () {
+ let result = 0;
+ for (let i = 0; i < this._maskStack.length - 1; ++i) {
+ result += (0x01 << i);
+ }
+ return result;
+ }
+};
+
+StencilManager.sharedManager = new StencilManager();
+StencilManager.Stage = Stage;
+
+module.exports = StencilManager;
\ No newline at end of file
diff --git a/cocos2d/core/value-types/CCColor.js b/cocos2d/core/value-types/CCColor.js
index 0876acdbc2..ac1f4fded6 100644
--- a/cocos2d/core/value-types/CCColor.js
+++ b/cocos2d/core/value-types/CCColor.js
@@ -249,7 +249,7 @@ var Color = (function () {
* @return {Number} red value.
*/
proto.getR = function () {
- return (this._val & 0xff000000) >>> 24;
+ return this._val & 0x000000ff;
};
/**
* !#en Sets red value and return the current color object
@@ -272,7 +272,7 @@ var Color = (function () {
* @return {Number} green value.
*/
proto.getG = function () {
- return (this._val & 0x00ff0000) >> 16;
+ return (this._val & 0x0000ff00) >> 8;
};
/**
* !#en Sets green value and return the current color object
@@ -295,7 +295,7 @@ var Color = (function () {
* @return {Number} blue value.
*/
proto.getB = function () {
- return (this._val & 0x0000ff00) >> 8;
+ return (this._val & 0x00ff0000) >> 16;
};
/**
* !#en Sets blue value and return the current color object
@@ -318,7 +318,7 @@ var Color = (function () {
* @return {Number} alpha value.
*/
proto.getA = function () {
- return this._val & 0x000000ff;
+ return (this._val & 0xff000000) >>> 24;
};
/**
* !#en Sets alpha value and return the current color object
@@ -331,7 +331,7 @@ var Color = (function () {
* color.setA(0); // Color {r: 0, g: 0, b: 0, a: 0}
*/
proto.setA = function (alpha) {
- this._val = ((this._val & 0x00ffffff) | (~~alpha<<24) >>> 0) >>> 0;
+ this._val = ((this._val & 0x00ffffff) | ((~~alpha << 24) >>> 0)) >>> 0;
return this;
};
diff --git a/gulp/tasks/engine.js b/gulp/tasks/engine.js
index 94f7c87de4..5a84007a70 100644
--- a/gulp/tasks/engine.js
+++ b/gulp/tasks/engine.js
@@ -62,9 +62,6 @@ var jsbSkipModules = [
'../../cocos2d/core/graphics/helper.js',
'../../cocos2d/audio/CCAudio',
'../../cocos2d/shape-nodes/CCDrawNode.js',
- '../../cocos2d/clipping-nodes/CCClippingNode.js',
- '../../cocos2d/clipping-nodes/CCClippingNodeCanvasRenderCmd.js',
- '../../cocos2d/clipping-nodes/CCClippingNodeWebGLRenderCmd.js',
'../../cocos2d/particle/CCSGParticleSystem.js',
'../../cocos2d/particle/CCSGParticleSystemCanvasRenderCmd.js',
'../../cocos2d/particle/CCSGParticleSystemWebGLRenderCmd.js',
@@ -75,8 +72,6 @@ var jsbSkipModules = [
'../../cocos2d/tilemap/CCSGTMXLayer.js',
'../../cocos2d/tilemap/CCTMXLayerCanvasRenderCmd.js',
'../../cocos2d/tilemap/CCTMXLayerWebGLRenderCmd.js',
- '../../cocos2d/motion-streak/CCSGMotionStreak.js',
- '../../cocos2d/motion-streak/CCSGMotionStreakWebGLRenderCmd.js',
'../../cocos2d/render-texture/CCRenderTexture.js',
'../../cocos2d/render-texture/CCRenderTextureCanvasRenderCmd.js',
'../../cocos2d/render-texture/CCRenderTextureWebGLRenderCmd.js',