0

Is there a way, possibly a ccBlendFunc, that will allow me to dynamically color sprites without affecting the pure white (255, 255, 255), pure black (0, 0, 0), and purely transparent (alpha=255) pixels?

Using the default blend function and setting sprite.color on a CCSprite will re-color the white pixels to whatever value is ccColor3B value is specified, and that is undesirable for me.

stackunderflow
  • 754
  • 7
  • 18

1 Answers1

1

Use a shader. If you are using cocos2d version 2.1, start with ccShader_PositionTextureColor_frag (used by CCSprite to render textures, and other classes), copied here

#ifdef GL_ES    
    precision lowp float;   
#endif

varying vec4 v_fragmentColor;
varying vec2 v_texCoord;
uniform sampler2D CC_Texture0;

void main()
{
    gl_FragColor = v_fragmentColor * texture2D(CC_Texture0, v_texCoord);
}

You want to change that line in main() to skip the fragments you want to skip. CCSprite writes the 'sprite.color' property into v_fragmentColor (look at the code , there are 'premultiplied alpha' variants). You want to modify the v_fragmentColor when texture2D(CC_Texture0, v_texCoord).a == 0, and other circumstances.

I would extend CCSprite to use this new shader (ie avoid toying directly with the shaders builtin to cocos2d, have your own trial and error place). Once you have the shader doing what you want, add the logic in your class to place the new shader program in CCShaderCache, and retrieve it from there.

YvesLeBorg
  • 9,070
  • 8
  • 35
  • 48
  • Thanks a lot for this, I've managed to get it to color sprites and ignore the fragments that are white/black/transparent. I've basically just added a simple conditional to the shader you mentioned - will that affect drawing performance much or should it be pretty negligible? – stackunderflow Nov 09 '13 at 20:24
  • nope ... in any event THIS shader is used for every other sprite. Yours add a simple 'if' on some of the sprites .... background noise really if you consider the load on the GPU. 12 hours total to get up and running with a shader !!! kudos :) – YvesLeBorg Nov 09 '13 at 20:56
  • It turns out my conditional shader for this is not a suitable solution. This shader is to be used for the majority of the sprites in the game and performance was abysmal on the iPhone 4. OpenGL ES profiling indicated that the conditional in the shader was very inefficient but I'm not sure how else to accomplish this. And I know nearly nothing about shaders -- typically a conditional like that requires very little computing time -- but GLSL is evidently different in that regard. – stackunderflow Jan 04 '14 at 07:04