#version 330

precision highp float;

uniform sampler2D greatGOL;
uniform float TrackTime;

smooth in vec2 vTexCoord;
flat in vec4 PositionValues;//Aufteilung: x1[0,64], z1[0,64], texResultHeight[0,1], Height1
flat in vec4 randRahmen;
in float onTop;

out vec4 vColor;

float rand(vec2 co);
vec4 HSVAtoRGBA(vec4 HSVA);

void main(void)
{
	vec2 times = vec2(38477.188,3843.386);//Aufteilung: Offset bis Anfang, Takt
	float curHeight = PositionValues.z*PositionValues.w;//Aktuelle Höhe[0,Height1]
	vec2 myTexCoord = vec2(vTexCoord.s, curHeight*vTexCoord.t)*vec2(1.0/4.0)+vec2(rand(PositionValues.xy)-mod(rand(PositionValues.xy), 1.0/4.0), rand(PositionValues.yx)-mod(rand(PositionValues.yx), 1.0/8.0));
	vColor = randRahmen;
	
	float Takt = (mod(TrackTime-times.x, times.y)/times.y)*(-1.0)+1.0;

	float cellsX = 64.0;
	float cellsY = 64.0;

	float bb = 0.005625, bf = 0.01;
	float bbV = 0.003625, bfV = 0.012;
    
    float curRand1 = rand(vec2(myTexCoord.s-mod(myTexCoord.s, bb+bf), myTexCoord.t-mod(myTexCoord.t, bbV+bfV)));
	float curRand2 = rand(vec2(myTexCoord.s-mod(myTexCoord.s, (bb+bf)*10), myTexCoord.t-mod(myTexCoord.t, bbV+bfV)));
    
    float curS = (int((myTexCoord.s-mod(myTexCoord.s, bb+bf))/(bb+bf)))/cellsX;
    float curT = (int((myTexCoord.t-mod(myTexCoord.t, bbV+bfV))/(bbV+bfV)))/cellsY;
    float curValue = texture(greatGOL, vec2(curS, curT)).r;
    
	vColor = randRahmen;//Rahmenfarbe
                  
    if(mod(myTexCoord.s+bb/2.0, bb+bf) > bb && mod(myTexCoord.t+bbV/2.0, bbV+bfV) > bbV && onTop < 0.995) {
		vColor = vec4(vec3(max((curRand2*0.15+curRand1*0.2),curValue*0.8)), 1.0); //normale Fensterfarbe zuweisen
		vec3 fromHSV = vec3(1.0,0.663,0.039)*smoothstep(0.5, 1.0, Takt);
		
		if(rand(vec2(myTexCoord.s-mod(myTexCoord.s, bb+bf), myTexCoord.t-mod(myTexCoord.t, bbV+bfV)).yx) > 0.9)//Anteil von 0.1 der Fenster erhalten bunte Farben
			vColor.rgb = max(fromHSV, vColor.rgb);
	}
}

float rand(vec2 co)
{
	return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}

vec4 HSVAtoRGBA(vec4 HSVA)
{
	vec4 RGBAreturner;
	RGBAreturner.a = HSVA.w;
	HSVA.x *= 360.0;
	int hi = int((HSVA.x-mod(HSVA.x, 60.0))/60.0);
	float f = HSVA.x/60.0-hi;
	float p = HSVA.z*(1-HSVA.y);
	float q = HSVA.z*(1-HSVA.y*f);
	float t = HSVA.z*(1-HSVA.y*(1-f));
	
	switch(hi) {
	case 0:
	case 6:
		RGBAreturner.rgb = vec3(HSVA.z, t, p);
		break;
	case 1:
		RGBAreturner.rgb = vec3(q, HSVA.z, p);
		break;
	case 2:
		RGBAreturner.rgb = vec3(p, HSVA.z, t);
		break;
	case 3:
		RGBAreturner.rgb = vec3(p, q, HSVA.z);
		break;
	case 4:
		RGBAreturner.rgb = vec3(t, p, HSVA.z);
		break;
	case 5:
		RGBAreturner.rgb = vec3(HSVA.z, p, q);
		break;
	default:
		RGBAreturner.rgb = vec3(0.0);
		break;
	}
	return RGBAreturner;
}