#version 330 core

uniform mat4 ModelViewProjectionMatrix;
uniform mat4 ModelViewMatrixInverse;
uniform mat3 NormalMatrix;
uniform samplerBuffer hexagon_data;
uniform float time;

in vec3 POSITION;
in vec3 NORMAL;
in vec2 TEXCOORD;

out vec3 normal;
out vec2 uv;
out vec2 uv2;
out vec2 pos_zw;
out float intensity;

#include <hexagons/transformations_include.vert>

void main()
{
	vec4 hex = texelFetch(hexagon_data, gl_InstanceID);

	vec3 pos = POSITION;
	vec3 n = NORMAL;
	intensity = 0.15;

	float len = length(hex.xy*vec2(1.0/3.0, 1.0));
	float y_off = sin( (time + len)*0.5 )*0.3;
	if ( hex.w > 0.0 )
	{
		float t = time - hex.w;
		float k = smoothstep(0.0, 1.0, t) - smoothstep(0.0, 1.0, t - 10.0);
		y_off += k;
		intensity = min(0.15 + k*hex.z, 1.0);

		float angle = k*3.14;
		if ( 1 == (gl_InstanceID & 1)  ) rotateAroundZ(pos, n, angle);
		else rotateAroundX(pos, n, angle);
	}

	pos.x += hex.x;
	pos.y += y_off;
	pos.z += hex.y;

	uv = TEXCOORD;
	uv2 = pos.xz*vec2(1.0/192.0, 1.0/55.5) + vec2(0.5);
	normal = NormalMatrix * n;

	vec4 proj_pos = ModelViewProjectionMatrix * vec4(pos, 1.0);
	pos_zw = proj_pos.zw;
	gl_Position = proj_pos;
}
