Play with shaders – black and white – part 1

While developing my game ‘Ice Heroes’, i discovered the shaders with cocos2d. I won’t explain in detail what is it, there is tons of resources about it, but basically, it is a small program used to display an object (http://www.opengl.org/wiki/Shader).

If you have a look at the cocos2d sources, you can see that every node rendered on screen is using a default shader: kCCShader_PositionTextureColor. This program key is set in CCShaderCache.m in loadDefaultShaders. It is composed of a vertex shader (executed on every vertex), and a fragment shader (executed every pixel on screen) – (ccShader_PositionTextureColor_vert.h and ccShader_PositionTextureColor_frag.h). We will use these two files as a template, and see how to modify and use them in order to change the colors of a texture.

Create a new project and modify the HelloWorld.m in order to display a single sprite. Your init should looks like this:

What we did here:
– loaded our fragment/vertex shader files to the sprite shaderprogram, added the 3 attributes position/texcoord/color (we find them in the .fsh and .vsh file, that’s what we will modify later).

– link the shaders and use it.

At this stage, you can run again the project and check if you still see your image.

Now we want to have it black and white. Remember, we talked about the fragment shader (executed on every visible pixel), that’s here where we will make a small operation to change the pixel colors.

The color is a vec4 (r, g, b, a) which we have thanks to: texture2D(u_texture, v_texCoord);

The only thing we need is to change the r g b values with a simple black and white formula, and give it back to the gl_FragColor instead of the normal texture color. Change your blackAndWhite.fsh like this:

Now run your project and you should see your sprite in black and white:

We can imagine a lots of cool effects only with colors, but of course we can create more advanced effects… What you can do is also create a way to change the shaders used for a sprite (for exemple how to easily use the blackAndWhite or the normal colors with a method call or a flag).

The CCShaderCache can store your shader with a key, which you can get back when you need.