#version 120

uniform sampler2D texture0;
uniform sampler2D texture1;
uniform sampler2D texture2;
uniform float colorThreshold = 0.8;
uniform float time = 1.0;
uniform vec2 circleDeform = vec2(0.015,0.015);

uniform float territory1 = 0.0;
uniform float territory2 = 0.0;
uniform float territory3 = 0.0;
uniform float territory4 = 0.0;


vec4 drawTerritory(vec4 spread, vec2 uv, vec2 position, float radius)
{
	if (spread.a > 0 || radius <= 0)
	{
		return vec4(0,0,0,0);
	}

	vec2 deformUv = uv;
	deformUv.x += sin(uv.y*time+time)*circleDeform.x;
	deformUv.y += cos(uv.x*time+time)*circleDeform.y;

	float distance = length(position - deformUv);
	float circleDistance = distance - radius;
	circleDistance = circleDistance;
	vec4 outputColor = vec4(0,0,0,0);
	if (circleDistance < radius)
	{
		float naziRed = 221/255.;
		vec4 color = vec4(naziRed,0,0,1);
		float swastikaSize = 0.05;
		float swastikaMultiplier = 9;
		if (length(position - uv) < swastikaSize)
		{
			uv = uv*10+position;
			vec4 tex2 = texture2D(texture2, uv);
			color = vec4(tex2.r,tex2.g,tex2.b,1);
		}
		outputColor = color;
	}

	return outputColor;
}

void main()
{
	vec2 uv = gl_TexCoord[0].xy;
	vec4 tex0 = texture2D(texture0, uv);
	vec4 tex1 = texture2D(texture1, uv);
	vec4 color = tex0;

	float gray = (tex0.r+tex0.g+tex0.b)/3;
	if (gray > colorThreshold)
	{
		color = vec4(tex1.r,tex1.g,tex1.b,tex0.a);
	}
	
	vec4 spread = vec4(0,0,0,0);
	spread += drawTerritory(spread, uv, vec2(0.41,0.41), territory1);
	spread += drawTerritory(spread, uv, vec2(0.14,0.135), territory2);
	spread += drawTerritory(spread, uv, vec2(0.775,0.225), territory3);
	spread += drawTerritory(spread, uv, vec2(0.41,0.775), territory4);

	if (spread.a > 0)
	{
		color = vec4(spread.r,spread.g,spread.b,color.a);
	}

	gl_FragColor = color * gl_Color;
}
