#version 330

precision highp float;

uniform sampler2D GameOfLife;
uniform float TrackTime;

smooth in vec2 vTexCoord;

out vec4 Color;

vec4 HSVAtoRGBA(vec4 HSVA);
float rand(vec2 co);
float mysinStep(float T1, float T2, float V1, float V2, float curT);

void main(void)
{
	vec4 times = vec4(7730.1, 1921.693, 240.212,34633.802); //Aufteilung: Offset, Dauer eines Zyklus, Dauer eines Klanges (1/8 eines Zyklus, 4 Töne pro Zyklus), Start des Übergangs zur nächsten Scene
	float GOLstate = texture(GameOfLife, vTexCoord).r;
	float vValue = 0.1;
	
	float curRandBorder = 0.975;
	if(GOLstate > 0.8 && rand(vTexCoord*vec2(mod(TrackTime, times.y))) > curRandBorder)
		vValue = 1.0;

	if(TrackTime > times.w+times.y) {
		vValue = mysinStep(times.w+times.y, times.w+2.0*times.y, vValue, 0.0, TrackTime);
	}
	
	Color = HSVAtoRGBA(vec4(210.0/360.0, 0.85, vValue, GOLstate));
}

float mysinStep(float T1, float T2, float V1, float V2, float curT) {
	float PI = 3.1415926535;
	float curSin = 0.5*sin(PI*(((curT-T1)/(T2-T1))-0.5))+0.5;
	float curV = curSin*(V2-V1)+V1;
	return curV;
}

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;
}