首先看一下封装好的两个函数:
void HelloWorld::setNodeGray(Node* node) { if (node) { GLProgram* p = new GLProgram(); p->initWithFilenames("gray.vsh","gray.fsh"); p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_POSITION,GLProgram::VERTEX_ATTRIB_POSITION); p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_COLOR,GLProgram::VERTEX_ATTRIB_COLOR); p->bindAttribLocation(GLProgram::ATTRIBUTE_NAME_TEX_COORD,GLProgram::VERTEX_ATTRIB_TEX_COORDS); p->link(); p->updateUniforms(); node->setGLProgram(p); } } void HelloWorld::removeNodeGray(Node* node) { if (node) { std::string str = "ShaderPositionTextureColor_noMVP"; GLProgram * pProgram = ShaderCache::getInstance()->getGLProgram(str); node->setShaderProgram(pProgram); CHECK_GL_ERROR_DEBUG(); } }
那 gray.vsh 和 gray.fsh 又是什么呢?
新建一个文本文件 命名为 gray 并保存为 .vsh 类型,其内容如下:
attribute vec4 a_position; attribute vec2 a_texCoord; attribute vec4 a_color; varying vec4 v_fragmentColor; varying vec2 v_texCoord; void main() { gl_Position = CC_PMatrix * a_position; v_fragmentColor = a_color; v_texCoord = a_texCoord; }
再次新建一个文本文件命名为 gray 并保存为 .fsh类型,其内容如下:
varying vec4 v_fragmentColor; varying vec2 v_texCoord; void main() { vec4 v_orColor = v_fragmentColor * texture2D(CC_Texture0,v_texCoord); float gray = dot(v_orColor.rgb,vec3(0.299,0.587,0.114)); gl_FragColor = vec4(gray,gray,v_orColor.a); }
注意:p->initWithFilenames("gray.vsh","gray.fsh"); 这里对文件引用的路径,我这里直接放到了 Resources 文件夹下
运行效果如下: