#version 330 core

uniform mat4 ModelViewMatrix;
uniform mat4 WorldMatrix;
uniform mat4 ModelViewProjectionMatrix;
uniform mat4 ProjectionMatrix;

layout(triangles) in;
layout(triangle_strip, max_vertices = 24) out;

out vec3 ec_pos;
out vec2 pos_zw;
out vec2 uv;


#define EMIT_VERTEX(VTX, UV) \
	uv = UV; \
	ec_pos = VTX; \
	gl_Position = ProjectionMatrix * vec4(VTX, 1.0); \
	pos_zw = gl_Position.zw; \
	EmitVertex()

#define MAKE_QUAD(A, B, C, D) \
	EMIT_VERTEX(view[A], vec2(1.0, 0.0)); \
	EMIT_VERTEX(view[B], vec2(0.0, 0.0)); \
	EMIT_VERTEX(view[D], vec2(1.0, 1.0)); \
	EMIT_VERTEX(view[C], vec2(0.0, 1.0)); \
	EndPrimitive()

vec3 cube_vertices[8] = vec3[](
	vec3( 1.0,  1.0, -1.0),
	vec3(-1.0,  1.0, -1.0),
	vec3(-1.0, -1.0, -1.0),
	vec3( 1.0, -1.0, -1.0),
	vec3( 1.0,  1.0,  1.0),
	vec3(-1.0,  1.0,  1.0),
	vec3(-1.0, -1.0,  1.0),
	vec3( 1.0, -1.0,  1.0)
);


void main()
{
	const float grid_size = 5.0;
	vec3 center = (gl_in[0].gl_Position.xyz + gl_in[1].gl_Position.xyz + gl_in[2].gl_Position.xyz) * (1.0/3.0);

	float size = distance(gl_in[0].gl_Position.xyz, center);
	size = min(size, distance(gl_in[1].gl_Position.xyz, center));
	size = min(size, distance(gl_in[2].gl_Position.xyz, center)) * 0.5;
	if ( size > 0.3 ) return;

	//vec3 wcenter = vec3(WorldMatrix * vec4(center, 1.0));
	//vec3 grid_center = wcenter - (floor(wcenter*grid_size) / grid_size);
	vec3 grid_center = center - (floor(center*grid_size) / grid_size);

	center += grid_center;

	vec3 view[8];
	for (int i=0; i < 8; i++)
	{
		vec3 offset = cube_vertices[i] * size;
		vec4 pos = vec4(center + offset, 1.0);
		view[i] = vec3(ModelViewMatrix * pos);
	}

	MAKE_QUAD(3,2,1,0);
	MAKE_QUAD(4,5,6,7);
	MAKE_QUAD(6,5,1,2);
	MAKE_QUAD(7,3,0,4);
	MAKE_QUAD(5,4,0,1);
	MAKE_QUAD(7,6,2,3);
}
