#version 330 core

uniform mat4 ProjectionMatrix;
uniform vec3 XAxis;
uniform vec3 YAxis;

in vec3 gs_light_params[1]; // radius
in vec3 gs_light_color[1];

out vec4 light_pos;
out vec3 color;

layout(points) in;
layout(triangle_strip, max_vertices = 4) out;

#define EMIT_VERTEX(VTX) \
	light_pos = lpos; \
	color = gs_light_color[0]; \
	gl_Position = vec4(VTX); \
	EmitVertex()

void main()
{
	float radius = gs_light_params[0].x*1.5;
	if ( radius <= 0.0 ) return;

	vec3 wpos = gl_in[0].gl_Position.xyz;
	vec4 lpos = vec4(wpos, gs_light_params[0].x);

	vec4 corners[4];
	corners[0] = ProjectionMatrix * vec4(wpos + (XAxis + YAxis)*radius, 1.0);
	corners[1] = ProjectionMatrix * vec4(wpos + (YAxis - XAxis)*radius, 1.0);
	corners[2] = ProjectionMatrix * vec4(wpos + (XAxis - YAxis)*radius, 1.0);
	corners[3] = ProjectionMatrix * vec4(wpos + (-XAxis - YAxis)*radius, 1.0);

	for (int i=0; i < 4; i++)
	{
		light_pos = lpos;
		color = gs_light_color[0];

		vec4 vpos = corners[i] / abs(corners[i].w);
		vpos.zw = vec2(1.0);
		vpos.xy = clamp(vpos.xy, -1.0, 1.0);
		gl_Position = vpos;
		EmitVertex();
	}
	EndPrimitive();
}
