#version 330 core

uniform float velocityScale;

in vec3 normal[3];

layout(triangles) in;
//layout(points) in;
layout(points, max_vertices = 16) out;

out block {
	vec4 position;
	vec4 velocity;
} Out;


float rand(in vec2 seed)
{
	return sin(dot(seed, seed.yx) * 1234.0);
}


void main()
{
#if 1
	vec3 n0 = normal[1] - normal[0];
	vec3 n1 = normal[2] - normal[0];
	vec3 e0 = gl_in[1].gl_Position.xyz - gl_in[0].gl_Position.xyz;
	vec3 e1 = gl_in[2].gl_Position.xyz - gl_in[0].gl_Position.xyz;
	float uInc = 1.0 / 3.0; //clamp(length(e0), 1.0, 4.0) / 4.0;
	float vInc = 1.0 / 3.0; //clamp(length(e1), 1.0, 4.0) / 4.0;

	for (float u=0.25; u < 1.0; u+=uInc)
	{
		for (float v=0.25; v < 1.0; v+=vInc)
		{
			Out.position.xyz = gl_in[0].gl_Position.xyz + e0*u + e1*v;
			Out.position.x += rand(Out.position.yz) * 0.25;
			Out.position.z += rand(Out.position.xy) * 0.25;
			Out.position.w = 1.0;
			Out.velocity.xyz = normalize(normal[0] + n0*u + n1*v)*velocityScale;
			Out.velocity.w = 1.0;
			EmitVertex();
			EndPrimitive();
		}
	}
#else
	Out.position.xyz = (gl_in[0].gl_Position.xyz + gl_in[1].gl_Position.xyz + gl_in[2].gl_Position.xyz) / 3.0;
	Out.position.w = 1.0;
	Out.velocity.xyz = normalize( (normal[0] + normal[1] + normal[2]) / 3.0) * velocityScale;
	Out.velocity.w = 1.0;
	gl_Position = Out.position;
	EmitVertex();
	EndPrimitive();
#endif
}
