#ifdef OPENGL_ES
#ifdef GL_FRAGMENT_PRECISION_HIGH
precision highp float;
#else
precision mediump float;
#endif
#else
precision mediump float;
#endif

///////////////////////////////////////////////////////////
// Uniforms
uniform sampler2D u_texture;
uniform vec3 u_red;
uniform vec3 u_green;
uniform vec3 u_blue;
uniform vec3 u_pivot;
uniform vec3 u_mask;
uniform vec3 u_alphablend;
uniform float u_nega;
uniform float u_grayscale;
uniform float u_alphauniformly;

///////////////////////////////////////////////////////////
// Varyings
varying vec2 v_texCoord;
varying vec4 v_color;


void main()
{
	float red = dot(texture2D(u_texture, v_texCoord).rgb, u_red);
	float green = dot(texture2D(u_texture, v_texCoord).rgb, u_green);
	float blue = dot(texture2D(u_texture, v_texCoord).rgb, u_blue);
	vec4 buf;
	float alphablend;
	float gray;

	if ( u_alphauniformly < 0 ) {

		alphablend = dot(texture2D(u_texture, v_texCoord).rgb, u_alphablend);

	} else {

		alphablend = u_alphauniformly;

	}

	//	ここまででalphablendの値が決定しないとバグる
	//	floatでとりあえず宣言しておかないといけない

	if ( u_grayscale < 0 ) {

		//RGBA

		if( u_pivot == 0 && u_nega == 0 ) {

			buf = vec4(red, green, blue, alphablend);

		} else {

			if( u_nega == 0 ){

				buf = vec4(u_pivot.r+red, u_pivot.g+green, u_pivot.b+blue, alphablend);

			}

			if( u_nega == 1 ) {

				buf = vec4(u_pivot.r-red, u_pivot.g-green, u_pivot.b-blue, alphablend);

			}

			if( u_nega == 2 ) {

				buf = vec4(1+u_pivot.r-red, 1+u_pivot.g-green, 1+u_pivot.b-blue, alphablend);

			}

		}

	} else {

		//	Grayscale

		gray = dot(texture2D(u_texture, v_texCoord).rgb, vec3(u_grayscale, u_grayscale, u_grayscale));

		if( u_pivot == 0 && u_nega == 0 ) {

			buf = vec4(gray, gray, gray, alphablend);

		} else {
			if( u_nega == 0 ){

				buf = vec4(u_pivot.r+gray, u_pivot.g+gray, u_pivot.b+gray, alphablend);

			}
			if( u_nega == 1 ) {

				buf = vec4(u_pivot.r-gray, u_pivot.g-gray, u_pivot.b-gray, alphablend);

			}
			if( u_nega == 2 ) {

				buf = vec4(1+u_pivot.r-gray, 1+u_pivot.g-gray, 1+u_pivot.b-gray, alphablend);

			}
		
		}

	}

	//	Mask
	if ( u_mask.r > 0 ) {

		buf.r = red * u_mask.r;

	}

	if ( u_mask.g > 0 ) {

		buf.g = green * u_mask.g;

	}

	if  (u_mask.b > 0 ) {

		buf.b = blue * u_mask.b;

	}

	gl_FragColor = buf;

}
