Cocos2dx3. X shader sets the image to gray
1 OpenGL ES shader
The opengl es coloring tool contains two files:. fsh and. vsh. These two files can generate executable programs and GPU interaction after being compiled and linked. Attribute is transmitted from the outside, and each vertex has these two attributes, so it is also called vertex attribute ). Varying variables are used to transmit data between vertex shader and fragment shader.
. Vsh is a vertex shader. It is used for vertex calculation to understand the position of the control vertex. In this file, we usually input the position of the current vertex and the coordinate of the texture. Create a gray. vsh file.
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. shader is the segment shader. Here I can re-calculate each pixel.
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, gray, v_orColor.a);}
Put the two files in the resource folder.
2. gray images
void HelloWorld::sprAddGray(Sprite * sprite){if (sprite){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();sprite->setShaderProgram(p);}}
3. Restore Images
void HelloWorld::sprRemoveGray(CCSprite * sprite){if (sprite !=NULL){std::string str = ShaderPositionTextureColor_noMVP;CCGLProgram * pProgram = CCShaderCache::sharedShaderCache()->programForKey(str);sprite ->setShaderProgram(pProgram);CHECK_GL_ERROR_DEBUG();} }
4. Running Effect
The code of the response button in the program is as follows to form a gray and color chart.
void HelloWorld::onBtnColorChange(Ref* MyRef){static int idx = 0;if (idx % 2 == 0){sprAddGray(m_spr);}else{sprRemoveGray(m_spr);}idx++;}