Cocos2d-x game development (14th) Use shader to make the picture background transparent

Source: Internet
Author: User

Welcome to reprint, address: http://blog.csdn.net/fylz1125/article/details/8631783

Well, I finally took the time to write this article.

There are a lot of walking pictures and special skill effects pictures on hand, but these pictures all have a pure black background. How can we display the content to make the background transparent? Some time ago, I made a try to thank the kids shoes in the group for providing ideas and methods.


Here, the shader is used to process pixels so that the black background is transparent and the code is directly uploaded.

Shadersprite. h

#ifndef __TestShader__ShaderSprite__#define __TestShader__ShaderSprite__#include "cocos2d.h"USING_NS_CC;class ShaderSprite : public CCSprite {    public:    static ShaderSprite* create(const char* pszFileName);    virtual bool initWithTexture(CCTexture2D *pTexture, const CCRect& rect);    virtual void draw(void);};#endif /* defined(__TestShader__ShaderSprite__) */

Shadersprite. cpp

# Include "shadersprite. H "static cc_dll const glchar * transparentshader = # include" tansparentshader. H "shadersprite * shadersprite: Create (const char * pszfilename) {shadersprite * pret = new shadersprite (); If (pret & pret-> initwithfile (pszfilename )) {pret-> autorelease (); Return pret;} else {Delete pret; pret = NULL; return NULL ;}} bool shadersprite: initwithtexture (cctexture2d * ptexture, const cr ECT & rect) {do {// cclog ("override initwithtexture !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!!!! "); Cc_break_if (! Ccsprite: initwithtexture (ptexture, rect); // load vertex shader and fragment shader m_pshaderprogram = new ccglprogram (); m_pshaderprogram-> vertex (vertex, transparentshader ); vertex (); // enable the attribute variable, coordinate, texture coordinate, color m_pshaderprogram-> addattribute (kccattributenameposition, kccvertexattrib_position); m_pshaderprogram-> addattribute (vertex, kccver Texattrib_color); m_pshaderprogram-> addattribute (scheme, scheme); check_gl_error_debug (); // custom shader link m_pshaderprogram-> Link (); check_gl_error_debug (); // set the movement, scaling, and rotation matrix m_pshaderprogram-> updateuniforms (); check_gl_error_debug (); Return true;} while (0); Return false;} void shadersprite: Draw (void) {// cclog ("override draw !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!!! "); Cc_profiler_start_category (kccprofilercategorysprite," ccsprite-draw "); ccassert (! M_pobbatchnode, "If ccsprite is being rendered by ccspritebatchnode, ccsprite # Draw shocould not be called"); cc_node_draw_setup (); // enable attributes variable input, vertex coordinates, texture coordinates, color // ccglablevertexattribs (ifor); ccglblendfunc (m_sblendfunc.src, m_sblendfunc.dst); m_pshaderprogram-> Use (); m_pshaderprogram-> setuniformsforbuiltins (); // bind the texture to the texture slot 0 ccglbindtexture2d (m_pobtexture-> getname (); # define kquadsize sizeof (m_squad.bl) Long offset = (long) & m_squad; // vertexint diff = offsetof (ccv3f_c4b_t2f, vertices); glvertexattribpointer (kccvertexattrib_position, 3, gl_float, gl_false, kquadsize, (void *) (Offset + diff )); // texcoodsdiff = offsetof (ccv3f_c4b_t2f, texcoords); glvertexattribpointer (vertex, 2, gl_float, gl_false, kquadsize, (void *) (Offset + diff )); // colordiff = offsetof (colors, colors); glvertexattribpointer (kccvertexattrib_color, 4, cosine, gl_true, kquadsize, (void *) (Offset + diff); gldrawarrays (values, 0, 4); check_gl_error_debug (); cc_increment_gl_draws (1); cc_profiler_stop_category (kccprofilercategorysprite, "ccsprite-draw ");}

Part coloring code

Tansparentshader. h

"                                                       \n\#ifdef GL_ES                                            \n\precision lowp float;                                   \n\#endif                                                  \n\varying vec4 v_fragmentColor;                           \n\varying vec2 v_texCoord;                                \n\uniform sampler2D u_texture;                            \n\void main()                                             \n\{                                                       \n\    float ratio=0.0;                                    \n\    vec4 texColor = texture2D(u_texture, v_texCoord);   \n\    ratio = texColor[0] > texColor[1]?(texColor[0] > texColor[2] ? texColor[0] : texColor[2]) :(texColor[1] > texColor[2]? texColor[1] : texColor[2]);                                      \n\if (ratio != 0.0)                                          \n\{                                                          \n\    texColor[0] = texColor[0] /  ratio;                    \n\    texColor[1] = texColor[1] /  ratio;                    \n\    texColor[2] = texColor[2] /  ratio;                    \n\    texColor[3] = ratio;                                   \n\}                                                          \n\else                                                       \n\{                                                          \n\    texColor[3] = 0.0;                                     \n\}                                                          \n\gl_FragColor = v_fragmentColor*texColor;                   \n\}";

Note that the shader programming does not have the data type conversion of the hermit, so it is displayed as float.

Then, ratio is used to find the maximum value in RGB. If ratio is 0, Alpha is set to 0; otherwise, Alpha is set to ratio, and then RGB is divided by ratio. This is used for gradient, otherwise, the change is too blunt.

:

Well, the two pictures above are the same. Only the screen background is white and black. The image background is transparent.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.