#ifdef GL_ES
precision mediump float;
#else
#define highp
#define mediump
#define lowp
#endif

#if defined(CONST_COLOR) && defined(VERTEX_COLOR)
// "const color" handled in vertex shader
#undef CONST_COLOR
#endif

// ------- UNIFORMS (SHADER CONSTS) -------
#ifdef TEXTURE0
uniform sampler2D	uniTexture0;
#endif

#ifdef GEONORMALMAP
uniform sampler2D	uniHeightmapTexture;
uniform vec3		uniHeightmapLight;
#endif

#ifdef CONST_COLOR
uniform	vec4		uniColor;
#endif

#ifdef ALPHA_TEST
uniform	float		uniAlphaTestValue;
#endif

// ------- INTERPOLATORS (SHADER INPUTS) -------
#ifdef GEONORMALMAP
varying vec2		varHeightmapUV;
#endif

#ifdef TEXTURE0
varying vec2		varTex0UV;
#endif

#ifdef VERTEX_COLOR
varying vec4		varColor;
#endif

// ------- FUNCTIONS ------- 

//vec3 PerturbNormal(vec3 surf_norm, vec3 vGrad)
//{
//	return vSurfGrad = vGrad - surf_norm*dot(surf_norm, vGrad);
//}


// suffix:
// F - incoming fragment
// T - texture fragment
// V - produced value

void main(void)
{
	vec4 vColorF;
	vec4 vColorT;
	vec4 vColorV;

// incoming fragment
#define INCOMING_FRAGMENT
#if defined(CONST_COLOR) && defined(VERTEX_COLOR)
	//vColorF = varColor*uniColor;
	#error blbost
#elif defined(CONST_COLOR)
	vColorF = uniColor;
#elif defined(VERTEX_COLOR)
	vColorF = varColor;
#else
#undef INCOMING_FRAGMENT
#endif

// texture fragment
#define TEXTURE_FRAGMENT
#ifdef TEXTURE0
	vColorT = texture2D(uniTexture0, varTex0UV);
#else
#undef TEXTURE_FRAGMENT
#endif

// modulate
#if defined(TEXTURE_FRAGMENT)
	#ifdef TEXTURE0_ALPHA
		#ifdef INCOMING_FRAGMENT
			vColorV.rgb = vColorF.rgb;
			vColorV.a = vColorF.a*vColorT.a;
			//vColorV = vec4(1,0,0,1);
		#else
			#error incoming fragment required
		#endif
	#else
		#ifdef INCOMING_FRAGMENT
			vColorV = vColorF*vColorT;
			//vColorV = vec4(1,0,0,1);
			//vColorV = vec4(varTex0UV.x,varTex0UV.y,0,1);
		#else
			vColorV = vColorT;
			//vColorV = vec4(varTex0UV.x,varTex0UV.y,0,1);
		#endif
	#endif
#elif defined(INCOMING_FRAGMENT)
	vColorV = vColorF;
#else
	#error neither incoming nor texture fragment defined
#endif

#ifdef ALPHA_TEST
	if (vColorV.a <= uniAlphaTestValue)
	{
		discard;
	}
#endif

#ifdef GEONORMALMAP
	vec3 vNormal = texture2D(uniHeightmapTexture, varHeightmapUV).xyz;
	float d = dot((vNormal - 0.5)*2.0, uniHeightmapLight);
	vColorV.rgb *= (1.0 - d);
#endif

#ifdef GRAYSCALE
	vColorV.rgb = vec3(dot(vColorV.rgb, vec3(0.3, 0.59, 0.11)));
#endif

	gl_FragColor = vColorV;
};