#version 330 core

uniform mat4 ModelViewMatrix;
uniform mat4 WorldMatrix;
uniform mat4 ModelViewProjectionMatrix;
uniform mat4 ProjectionMatrix;
uniform vec4 aeroplane; // xyz=position, w=radius
uniform float time;

layout(triangles) in;
layout(triangle_strip, max_vertices = 16) 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[C], vec2(1.0, 1.0)); \
	EMIT_VERTEX(view[D], vec2(0.0, 1.0)); \
	EndPrimitive()


vec3 octahedron_vertices[6] = vec3[](
	vec3( 1.0,  0.0,  0.0),
	vec3(-1.0,  0.0,  0.0),
	vec3( 0.0,  1.0,  0.0),
	vec3( 0.0, -1.0,  0.0),
	vec3( 0.0,  0.0,  1.0),
	vec3( 0.0,  0.0, -1.0)
);

void rotate_around_axis(in vec3 axis, in float angle, out mat3 mr)
{
	float c = cos(angle);
	float s = sin(angle);
	float one_minus_c = 1.0 - c;

	mr[0].x = c + one_minus_c*axis.x*axis.x;
	mr[0].y = axis.x*axis.y*one_minus_c - axis.z*s;
	mr[0].z = axis.x*axis.z*one_minus_c + axis.y*s;

	mr[1].x = axis.x*axis.y*one_minus_c + axis.z*s;
	mr[1].y = c + one_minus_c*axis.y*axis.y;
	mr[1].z = axis.y*axis.z*one_minus_c - axis.x*s;

	mr[2].x = axis.x*axis.z*one_minus_c - axis.y*s;
	mr[2].y = axis.y*axis.z*one_minus_c + axis.x*s;
	mr[2].z = c + one_minus_c*axis.z*axis.z;
}

void main()
{
	vec3 center = (gl_in[0].gl_Position.xyz + gl_in[1].gl_Position.xyz + gl_in[2].gl_Position.xyz) * (1.0/3.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 size = length(cross(e0, e1) * 0.5) * 0.25;

	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.75;

	vec3 wcenter = vec3(WorldMatrix * vec4(center, 1.0));
	vec3 dir = wcenter - aeroplane.xyz;
	float len = length(dir);
	dir = normalize(dir);
	float angle = dot(center, vec3(0.5));
	if ( len < aeroplane.w )
	{
		float atten =  pow(1.0 - (len / aeroplane.w), 1.5);
		center += dir * atten*aeroplane.w;
		angle += atten*3.14;
	}

	vec3 axis = normalize(cross(dir, ModelViewMatrix[2].xyz));
	mat3 mr;
	rotate_around_axis(axis, angle, mr);

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

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