#version 330 core

uniform vec4 params; // x=cube scale, y=grid steps,
uniform vec4 slopePlane;

in vec4 normal[3];
in vec3 viewNormal[3];

layout(triangles) in;
layout(points, max_vertices = 1) out;

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

void main()
{
	//vec3 n = normalize( (viewNormal[0] + viewNormal[1] + viewNormal[2]) / 3.0 );
	float view = -1.0;
	for (int i=0; i < 3; i++)
	{
		view = max(view, dot(viewNormal[0], vec3(0.0, 0.0, 1.0)));
	}
	
	if ( view <= params.w ) return;

	vec3 pos = (gl_in[0].gl_Position.xyz + gl_in[1].gl_Position.xyz + gl_in[2].gl_Position.xyz) / 3.0;
	Out.position.xyz = floor(pos*params.y + vec3(0.5)) / params.y;

	float d = dot(slopePlane.xyz, Out.position.xyz) + slopePlane.w;
	if ( d < 0.0 ) return;

	float scale = abs(params.y - distance(pos, Out.position.xyz)*0.5) / params.y;
	Out.position.w = min(scale * params.x, params.z);
	if ( Out.position.w < params.w ) return;
	Out.normal = (normal[0] + normal[1] + normal[2]) / 3.0;
	gl_Position = Out.position;
	EmitVertex();
	EndPrimitive();
}
