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

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

#if defined(GEONORMALMAP) || defined(GEONORMALMAP09)
uniform sampler2D	chu_tGeoNormalmap;
uniform vec3		chu_vGeoNormalmapLight;
#endif

#ifdef CONST_COLOR
uniform	vec4		chu_vColor;
#endif

#ifdef ALPHA_TEST
uniform	float		chu_fAlphaTestValue;
#endif

// ------- INTERPOLATORS (SHADER INPUTS) -------
#if defined(GEONORMALMAP) || defined(GEONORMALMAP09)
varying vec2		v_vHeightmapUV;
#endif

#if defined(TEXTURE0)
varying vec2		v_vTexCoord;
#endif

#ifdef VERTEX_COLOR
varying vec4		v_vColor;
#endif

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

// 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 = v_vColor*chu_vColor;
	#error blbost
#elif defined(CONST_COLOR)
	vColorF = chu_vColor;
#elif defined(VERTEX_COLOR)
	vColorF = v_vColor;
#else
#undef INCOMING_FRAGMENT
#endif

// texture fragment
#define TEXTURE_FRAGMENT
#ifdef TEXTURE0
	vColorT = texture2D(chu_tAmbient, v_vTexCoord);
#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(v_vTexCoord.x,v_vTexCoord.y,0,1);
		#else
			vColorV = vColorT;
			//vColorV = vec4(v_vTexCoord.x,v_vTexCoord.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 <= chu_fAlphaTestValue)
	{
		discard;
	}
#endif

#if defined(GEONORMALMAP) || defined(GEONORMALMAP09)
	vec3 vNormal = texture2D(chu_tGeoNormalmap, v_vHeightmapUV).xyz;
	float d = dot((vNormal - 0.5)*2.0, chu_vGeoNormalmapLight);
	// cartoon style shading
	//float dd[11] = float[11](-1.0, -0.4, -0.3, -0.2, -0.2, 0.0, 0.1, 0.2, 0.3, 0.6, 1.0);
	//for (int i = 0; i < 10; i++)
	//{
	//	if (d >= dd[i] && d <= dd[i + 1])
	//	{
	//		d = dd[i];
	//		break;
	//	}
	//}
	vColorV.rgb *= (1.0 - 0.5*d);
#endif

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

	gl_FragColor = vColorV;
}
