// Based on https://github.com/SFML/SFML/wiki/Source:-Radial-Gradient-Shader by Hapax

uniform vec4 lightColour;
uniform vec2 lightPos;
uniform vec2 lightSize;
uniform float lightEmission;
uniform float lightAngle;
uniform int lightType; // 0 = ellipse, 1 = half ellipse, 2 = cone, 3 = double cone

uniform float windowHeight;

vec2 rotate(vec2 pos, float angle, vec2 centre)
{
	float c = cos(angle);
	float s = sin(angle);
    return vec2(
		c * (pos.x - centre.x) + s * (pos.y - centre.y) + centre.x,
		c * (pos.y - centre.y) - s * (pos.x - centre.x) + centre.y
    );
}

void main()
{
	vec2 lightPosFlipped = vec2(lightPos.x, windowHeight - lightPos.y);
	vec2 pos = (rotate(gl_FragCoord.xy, radians(-lightAngle), lightPosFlipped) - lightPosFlipped) / (lightSize * 0.5);
	float radiusNormalised = sqrt(dot(pos, pos));

	// calculate current angle
	float fragAngle = degrees(atan(pos.x, pos.y));

	// clamp angle
	while (fragAngle < 0)
		fragAngle += 360;
	while (fragAngle > 360)
		fragAngle -= 360;

	// handle light
	bool isLit = (radiusNormalised < 1.0);
	if (isLit)
	{
		// ellipse needs no checks

		// half ellipse
		if (lightType == 1 && (fragAngle < 270 && fragAngle > 90))
		{
			isLit = false;
		}

		// cone
		if (lightType == 2 && (fragAngle < 330 && fragAngle > 30))
		{
			isLit = false;
		}

		// double cone
		if (lightType == 3 && ((fragAngle > 210 && fragAngle < 330) || (fragAngle > 30 && fragAngle < 150)))
		{
			isLit = false;
		}
	}

	if (isLit)
	{
		float emission = lightEmission * 0.5;
		gl_FragColor = mix(lightColour, gl_Color, (radiusNormalised - emission) / (1 - emission));
	}
	else
	{
		gl_FragColor = gl_Color;
	}
}