Make sure you have seen the SHADER BASICS tutorial because we will be building off of things we have already learned.
vertex to fragment
More components
samplers and textures
varying vec2 v_vTexcoord;
varying vec4 v_vColour;
void main()
{
vec4 Color = texture2D( gm_BaseTexture, v_vTexcoord );
gl_FragColor = vec4( vec3(Color.r+Color.g+Color.b)/3.0, Color.a);
}
So what this code does is it sets "Color" to the texture color. Then gl_FragColor is set so that the red, green and blue values are averaged while the alpha is still set to the textures alpha.
The result should look like this:
This black and white shader is alright, but not very precise. That is because some colors are brighter than the average. To get the proper values we'll try this:
varying vec2 v_vTexcoord;
varying vec4 v_vColour;
void main()
{
vec4 Color = texture2D( gm_BaseTexture, v_vTexcoord );
vec3 lum = vec3(0.299, 0.587, 0.114);
gl_FragColor = vec4( vec3(dot( Color.rgb, lum)), Color.a);
}
This is the result:
The function "dot()" gets the dot product of two vectors. The reason we do this is because some colors are brighter then others (green is the brightess while blue is the darkest). The dot product makes sure the green is brighter then red and red is brighter then blue. So it basically is a short way to type:
gl_FragColor = vec4( vec3( Color.r * lum.r+Color.g * lum.g+Color.b * lum.b), Color.a);
That fixes the brightness.
DOWNLOAD EXAMPLE