cocos2d-js Shader系列4:Shader、GLProgram在jsb(native、手机)和html5之间的兼容问题。cocos2d-js框架各种坑。
为了让jsb也能顺利跑起滤镜效果,在手机侧折腾了2天,因为每次在真机上运行总要耗那么半分钟,而且偶尔还遇到apk文件无法删除导致运行失败的情况。
这个调试起来,实在让人烦躁加沮丧。
还好,测试上百轮,翻jsb代码+各种猜测实验之后,终于顺利的把前3个系列的例子都通通在Android上跑起来了,也算是把兼容问题调通了。
如下图所示,右上角的小图是多纹理效果,通过扩展cc.Node自行控制绘制顶点实现的;下方的两个小图是普通的cc.Sprite,对其加入了shaderProgram
总结一下,这里有几个坑:
1、一些html5跑得很顺利的接口(包括出现在官方例子中)在JSB中并没有实现或绑定错误。
bool JSB_glUniform1f(JSContext *cx, uint32_t argc, jsval *vp) {
JSB_PRECONDITION2( argc == , cx, false, "Invalid number of arguments" );
jsval *argvp = JS_ARGV(cx,vp);
bool ok = true;
int32_t arg0; int32_t arg1; ok &= jsval_to_int32( cx, *argvp++, &arg0 );
ok &= jsval_to_int32( cx, *argvp++, &arg1 );
JSB_PRECONDITION2(ok, cx, false, "Error processing arguments"); GLfloat arg1a = (GLfloat)arg1;
CCLOG("UNIFORM, %f", arg1a); //调试加入的代码,输出0.0000。实际传入的是0.9
glUniform1f((GLint)arg0 , (GLfloat)arg1 );
JS_SET_RVAL(cx, vp, JSVAL_VOID);
return true;
}
varying vec2 v_texCoord;
void main()
{
vec4 texColor = texture2D(CC_Texture0, v_texCoord);
float gray = texColor.r * 0.299 + texColor.g * 0.587 + texColor.b * 0.114;
gl_FragColor = vec4(gray,gray,gray,);
}
4、jsb中,如果刚新建glprogram就设置gl的uniform参数,之后可能会发现参数没生效。原因可能是该Node/sprite在初始化的时候把glprogram重置过,丢掉了参数。
sprite.scheduleUpdate();
sprite.update = function(){
program.use();
program.setUniformsForBuiltins();
var degreeLocation = program.getUniformLocationForName("u_degree");
gl.uniform1f( degreeLocation, degree);
};
完整代码:
var trace = function() {
cc.log(Array.prototype.join.call(arguments, ", "));
}; var Filter = { DEFAULT_VERTEX_SHADER:
"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"
+ "}", GRAY_SCALE_FRAGMENT_SHADER:
"varying vec2 v_texCoord; \n"
//+ "uniform sampler2D CC_Texture0; \n" //cocos2d 3.0jsb 3.1jsb/html5开始自动加入这个属性,不需要手工声明
+ "void main() \n"
+ "{ \n"
+ " vec4 texColor = texture2D(CC_Texture0, v_texCoord); \n"
+ " float gray = texColor.r * 0.299 + texColor.g * 0.587 + texColor.b * 0.114; \n"
+ " gl_FragColor = vec4(gray,gray,gray,1); \n"
+ "}", SEPIA_FRAGMENT_SHADER:
"varying vec2 v_texCoord; \n"
//+ "uniform sampler2D CC_Texture0; \n"
+ "uniform float u_degree; \n"
+ "void main() \n"
+ "{ \n"
+ " vec4 texColor = texture2D(CC_Texture0, v_texCoord); \n"
+ " float r = texColor.r * 0.393 + texColor.g * 0.769 + texColor.b * 0.189; \n"
+ " float g = texColor.r * 0.349 + texColor.g * 0.686 + texColor.b * 0.168; \n"
+ " float b = texColor.r * 0.272 + texColor.g * 0.534 + texColor.b * 0.131; \n"
+ " gl_FragColor = mix(texColor, vec4(r, g, b, texColor.a), float(u_degree)); \n"
+ "}", programs:{}, /**
* 灰度
* @param sprite
*/
grayScale: function (sprite) {
var program = Filter.programs["grayScale"];
if(!program){
program = new cc.GLProgram();
program.retain(); //jsb需要retain一下,否则会被回收了
program.initWithString(Filter.DEFAULT_VERTEX_SHADER, Filter.GRAY_SCALE_FRAGMENT_SHADER);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); //cocos会做初始化的工作
program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
program.link();
program.updateUniforms();
Filter.programs["grayScale"] = program;
}
gl.useProgram(program.getProgram());
sprite.shaderProgram = program;
}, /**
* 造旧
* @param sprite
* @param degree 旧的程度 0~1
*/
sepia: function (sprite, degree) {
var program = Filter.programs["sepia"+degree];
if(!program){
program = new cc.GLProgram();
program.retain();
program.initWithString(Filter.DEFAULT_VERTEX_SHADER, Filter.SEPIA_FRAGMENT_SHADER);
program.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION); //cocos会做初始化的工作
program.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
program.link();
program.updateUniforms(); /*
这两句只在html5中有效,在jsb中失效。原因可能是native版本绘制sprite前把这个glprogram重置了,丢掉了参数。
var degreeLocation = program.getUniformLocationForName("u_degree");
gl.uniform1f(degreeLocation, degree);
*/ Filter.programs["sepia"+degree] = program;
}
gl.useProgram(program.getProgram());
sprite.shaderProgram = program; sprite.scheduleUpdate();
sprite.update = function(){
program.use();
program.setUniformsForBuiltins();
var degreeLocation = program.getUniformLocationForName("u_degree");
gl.uniform1f( degreeLocation, degree); //这个函数由于jsb实现有问题,在手机侧实际只能传递整数,需要注意。html5是正常的。
}; } }; cc.GLNode = cc.GLNode || cc.Node.extend({
ctor:function(){
this._super();
this.init();
},
_initRendererCmd:function(){
this._rendererCmd = new cc.CustomRenderCmdWebGL(this, function(){
cc.kmGLMatrixMode(cc.KM_GL_MODELVIEW);
cc.kmGLPushMatrix();
cc.kmGLLoadMatrix(this._stackMatrix); this.draw(); cc.kmGLPopMatrix();
});
}
}); var ShaderLayer = cc.Layer.extend({
sprite:null,
ctor:function () {
this._super();
if( 'opengl' in cc.sys.capabilities ) {
var node1 = new cc.Sprite("res/item_2.png");
var node2 = new cc.Sprite("res/item_3.png");
this.addChild(node1,11);
this.addChild(node2,12);
node1.x = 500;
node2.x = 200;
node1.y = node2.y = 130;
Filter.grayScale(node1);
Filter.sepia(node2, 1); var glnode = new cc.GLNode();
this.addChild(glnode,1);
this.glnode = glnode;
var winSize = cc.director.getWinSize();
glnode.x = winSize.width/2;
glnode.y = winSize.height/2;
glnode.width = 128;
glnode.height = 128;
glnode.anchorX = 0.5;
glnode.anchorY = 0.5; var MULTI_TEXTURES_FRAGMENT_SHADER =
"precision lowp float; \n"
+ "varying vec2 v_texCoord; \n"
+ "uniform sampler2D tex0; \n" //为了避免跟自动加入的CC_Texture0冲突,改名
+ "uniform sampler2D tex1; \n"
+ "void main() \n"
+ "{ \n"
+ " vec4 color1 = texture2D(tex0, v_texCoord); \n"
+ " vec4 color2 = texture2D(tex1, v_texCoord); \n"
+ " gl_FragColor = vec4(color1.r*color2.r, color1.g*color2.g, color1.b*color2.b, color1.a*color2.a); \n"
+ "}";
var DEFAULT_VERTEX_SHADER =
"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"
+ "}";
this.shader = new cc.GLProgram();
this.shader.retain();
this.shader.initWithString(DEFAULT_VERTEX_SHADER, MULTI_TEXTURES_FRAGMENT_SHADER);
this.shader.addAttribute(cc.ATTRIBUTE_NAME_POSITION, cc.VERTEX_ATTRIB_POSITION);
this.shader.addAttribute(cc.ATTRIBUTE_NAME_TEX_COORD, cc.VERTEX_ATTRIB_TEX_COORDS);
this.shader.link();
this.shader.updateUniforms(); //绑定位置,这个是cocos封装后必须做的事。详细可以看代码
this.initGL();
var p = this.shader.getProgram();
this.tex1Location = gl.getUniformLocation(p, "tex0"); //如果frag shader最终没有用某个uniform,该uniform会被优化删掉
this.tex2Location = gl.getUniformLocation(p, "tex1"); glnode.draw = function() {
this.shader.use(); //使用这个shader来绘制,封装了gl的use。跟指定glnode.shaderProgram类似
this.shader.setUniformsForBuiltins(); //设置坐标系变换 gl.activeTexture(gl.TEXTURE0); //webgl中一共32个,可以看cocos2d列的常量
gl.bindTexture(gl.TEXTURE_2D, this.tex1.getName());
gl.uniform1i(this.tex1Location, 0); //把CC_Texture0指向gl.TEXTURE0
gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, this.tex2.getName());
gl.uniform1i(this.tex2Location, 1);
cc.glEnableVertexAttribs( cc.VERTEX_ATTRIB_FLAG_TEX_COORDS | cc.VERTEX_ATTRIB_FLAG_POSITION); //实际对gl的api做了封装,增加了这两个属性的位置映射。用于vertexAttribPointer // Draw fullscreen Square
gl.bindBuffer(gl.ARRAY_BUFFER, this.squareVertexPositionBuffer);
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, this.squareVertexTextureBuffer);
gl.vertexAttribPointer(cc.VERTEX_ATTRIB_TEX_COORDS, 2, gl.FLOAT, false, 0, 0);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4); gl.activeTexture(gl.TEXTURE1);
gl.bindTexture(gl.TEXTURE_2D, null); //使用完必须置为空,否则影响其他node
gl.activeTexture(gl.TEXTURE0); //另外必须设置回第0个,否则cocos2d框架中如果没有显示设置第0个,就会错误使用了上边的TEXTURE1
gl.bindTexture(gl.TEXTURE_2D, null);
gl.bindBuffer(gl.ARRAY_BUFFER, null); }.bind(this);
}
}, initGL:function() {
var tex1 = cc.textureCache.addImage("res/item_2.png");
var tex2 = cc.textureCache.addImage("res/item_3.png");
this.tex1 = tex1;
this.tex2 = tex2;
//
// Square
//
var squareVertexPositionBuffer = this.squareVertexPositionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexPositionBuffer);
var vertices = [
128, 128,
0, 128,
128, 0,
0, 0
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
var squareVertexTextureBuffer = this.squareVertexTextureBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexTextureBuffer);
var texcoords = [
0, 0,
1, 0,
0, 1,
1, 1
];
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(texcoords), gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, null);
}
}); var HelloWorldScene = cc.Scene.extend({
onEnter:function () {
this._super();
var layer = new ShaderLayer();
this.addChild(layer); cc.eventManager.addListener({
event: cc.EventListener.KEYBOARD,
onKeyReleased: function(keyCode, event) {
if (keyCode == cc.KEY.back) {
cc.director.end();
}
}}, this);
}
});
cocos2d-js Shader系列4:Shader、GLProgram在jsb(native、手机)和html5之间的兼容问题。cocos2d-js框架各种坑。的更多相关文章
- JS组件系列——BootstrapTable+KnockoutJS实现增删改查解决方案(二)
前言:上篇 JS组件系列——BootstrapTable+KnockoutJS实现增删改查解决方案(一) 介绍了下knockout.js的一些基础用法,由于篇幅的关系,所以只能分成两篇,望见谅!昨天就 ...
- cocos2d-js Shader系列3:多重纹理 multiple textures multiple samplers
上一篇,我们学习了怎么便捷的控制sprite的颜色,而这个都是默认一个texture的,如果要实现类似mask的效果,或者更个性化的多纹理效果,怎么实现呢? 这就是这一节需要介绍的内容. 例如上图的效 ...
- cocos2d-js Shader系列2:在cc.Sprite上使用Shader(黑白、灰度、造旧效果)
在Sprite中使用Shader做特殊的颜色处理比较简单,只需要把Shader程序绑定到Sprite上即可: sprite.shaderProgram = alphaTestShader; Cocos ...
- cocos2d-js Shader系列1:cocos2d-js Shader和OpenGL ES2.0
cocos2d的Shader也就是差不多直接跟GPU打交道了,跟Flash的Stage3D(AGAL)类似,不过没有AGAL这么恶心,不需要直接编写汇编语言.而Fragment Shader又跟Fla ...
- Three.js粒子特效,shader渲染初探(一篇非常详细的介绍)
Three.js粒子特效,shader渲染初探 转载来源:https://juejin.im/post/5b0ace63f265da0db479270a 这大概是个序 关于Three.js,网上有不多 ...
- JS组件系列——BootstrapTable+KnockoutJS实现增删改查解决方案(一)
前言:出于某种原因,需要学习下Knockout.js,这个组件很早前听说过,但一直没尝试使用,这两天学习了下,觉得它真心不错,双向绑定的机制简直太爽了.今天打算结合bootstrapTable和Kno ...
- JS组件系列——BootstrapTable 行内编辑解决方案:x-editable
前言:之前介绍bootstrapTable组件的时候有提到它的行内编辑功能,只不过为了展示功能,将此一笔带过了,罪过罪过!最近项目里面还是打算将行内编辑用起来,于是再次研究了下x-editable组件 ...
- JS组件系列——BootstrapTable+KnockoutJS实现增删改查解决方案(四):自定义T4模板快速生成页面
前言:上篇介绍了下ko增删改查的封装,确实节省了大量的js代码.博主是一个喜欢偷懒的人,总觉得这些基础的增删改查效果能不能通过一个什么工具直接生成页面效果,啥代码都不用写了,那该多爽.于是研究了下T4 ...
- JS组件系列——BootstrapTable+KnockoutJS实现增删改查解决方案(三):两个Viewmodel搞定增删改查
前言:之前博主分享过knockoutJS和BootstrapTable的一些基础用法,都是写基础应用,根本谈不上封装,仅仅是避免了html控件的取值和赋值,远远没有将MVVM的精妙展现出来.最近项目打 ...
随机推荐
- 代码实现Android5.0的下拉刷新效果
如图所示,实现类似与gmail的下拉刷新. 项目地址:https://github.com/stormzhang/SwipeRefreshLayoutDemo 一.在xml文件中定义 这个控件在sup ...
- 《RESTful Web APIs中文版》
<RESTful Web APIs中文版> 基本信息 原书名:RESTful Web APIs 原出版社: O'Reilly Media 作者: Leonard Richardson ...
- Caffe SSD AttributeError: 'module' object has no attribute 'LabelMap'
caffe ssd 错误描述: AttributeError: 'module' object has no attribute 'LabelMap' SSD from caffe.proto imp ...
- 概率校准与Brier分数
1.再提逻辑回归 前面已经讲过了逻辑回归,这里不再细讲,只是简单的说一个函数,主要是方便大家更好的理解概率校准. 在逻辑回归中,用的最多的就是sigmod函数,这个函数的作用就是把无限大或者无限小的数 ...
- Host-Only模式
Host-Only模式 在Host-Only模式下,虚拟网络是一个全封闭的网络,它唯一能够访问的就是主机.其实Host-Only网络和NAT网络很相似,不同的地方就是Host-Only网络没有NAT服 ...
- dict扩展munch,支持yaml文件
安装:pip install munch 用法参考:https://github.com/Infinidat/munch Munch is a dictionary that supports att ...
- VS2010新建Web网站与新建Web应用程序的区别 (转)
在Visual Studio 2010中,除了可以使用“创建Web应用程序”的方式来构建自己的Web项目之外,还可以通过创建“Web网站”的方式来构建Web项其中,Web网站的创建方法:打开Visua ...
- [leetcode]Regular Expression Matching @ Python
原题地址:https://oj.leetcode.com/problems/regular-expression-matching/ 题意: Implement regular expression ...
- [leetcode]Multiply Strings @ Python
原题地址:https://oj.leetcode.com/problems/multiply-strings/ 题意: Given two numbers represented as strings ...
- 门罗币(MONERO)钱包生成教程
一.下载钱包 钱包下载地址:https://getmonero.org/downloads/(如果下载缓慢请使用下载工具下载) 二.图形界面钱包生成 解压运行monero-wallet-gui.exe ...