#version 400 core

uniform sampler2D colorTexture0;
uniform sampler2D colorTexture1;
uniform sampler2D colorTexture2;
uniform sampler2D colorTexture3;
uniform sampler2D AlphaMap;
uniform sampler2D normalTexture;

uniform int selfShading;

in Vertex
{
	vec3 viewDir;
	vec3 lightDir;
    vec3 color;
    vec2 texCoord;
	vec4 fogParam;
}
vertex;

in float H;

layout (location =0) out vec4 color;

void main ()
{
    vec3 meshNormal = texture (normalTexture, vertex.texCoord).xyz * 2 - vec3 (1, 1, 1);
    vec3 normal = normalize (meshNormal);
    vec3 viewDir = normalize (vertex.viewDir);
    vec3 lightDir = normalize (vertex.lightDir);
	vec3 reflection = reflect (lightDir, normal);
	
	// Calculate self shading (flat shading)
	float dotVN = dot (viewDir, normal);
    float sin2VN = 1 - dotVN * dotVN;
	float diffuse = 0;
	float specular = 0;
	
	if (selfShading == 1)
	{
		diffuse = 0.6 * sin2VN * sin2VN + 0.2;
	}
	else
	{
		/* calculate basic phong lighting */
		diffuse = clamp(dot(normal, lightDir), 0.0, 1.0);
		specular = pow(clamp(dot(reflection, viewDir), 0.0, 1.0), 4);
	}
	
	
	// Repeat the base texture
	vec2 UVRepeat = vertex.texCoord.st;
	UVRepeat.s *= 150;
	UVRepeat.t *= 150;
		

	vec4 colorMix = vec4 (1,1,1,1);	
	vec4 grass = texture (colorTexture0, UVRepeat * 6.0);
	vec4 dirt = texture (colorTexture1, UVRepeat);
	vec4 rock = texture (colorTexture2, UVRepeat);
	vec4 snow = texture (colorTexture3, UVRepeat );
	
	
	vec4 blend = texture (AlphaMap, vertex.texCoord);
	
	grass = mix (dirt, grass, blend.r);
	rock = mix (grass, rock, blend.g);
	snow = mix (rock, snow, blend.b);
	
	colorMix = snow;
	colorMix = colorMix * 1.72 - 0.4;
	if (selfShading == 1)
	{
		color = mix( 1.2 * vec4((diffuse + specular) * vertex.color, 1) * colorMix, vertex.fogParam, vertex.fogParam.w);
	}
	else
	{
		color = vec4(diffuse * vertex.color, 1) * colorMix;
	}
}


