#include "inc/uniforms.glsl"
#include "inc/utils.glsl"
#line 3 1

#ifdef VERTEX
#line 1 4
#include "inc/pate_vert_io.glsl"

uniform float p_rotation;

void main()
{
	//normal = (viewMatrix*modelMatrix) * normal;
	
	ex_Color = vec4(in_Normal, 1.0);
	//ex_Normal = normalize(normalMatrix * in_Normal.xyz);
	//mat3 normalmat = transpose((inverse(mat3(modelMatrix))));
	
	ex_UV = in_UV.xy;
	
	float dist = length(in_Position);
	float alpha = p_beat*1.0*p_rotation + 1.0;
	
	//mat2 rot = mat2(cos(alpha), sin(alpha), -sin(alpha), cos(alpha));
	mat3 rot = mat3(cos(alpha), sin(alpha), 0.0, -sin(alpha), cos(alpha), 0.0, 0.0, 0.0, 1.0);
	//rot *= (1.2 + sin(in_Position.x)) * 0.5;
	
	vec4 world = modelMatrix*in_Position;
	world.xyz = rot * world.xyz;
	//world.xz = rot * world.xz;
	ex_Position = (viewMatrix)*world;
	gl_Position = (viewProjectMatrix)*world;
	
	mat3 normalmat = normalMatrix*rot;
	ex_Normal = normalize(normalmat * in_Normal.xyz);

	//ex_Position = (viewMatrix*modelMatrix)*in_Position;
	//gl_Position = (projectionMatrix*viewMatrix*modelMatrix)*in_Position;
}


#endif


#ifdef FRAGMENT
#line 1 6
#include "inc/pate_frag_io.glsl"
#line 26

void main()
{
	float dist = length(ex_Position.xyz - vec3(0.0, 4.0, -10.0));
	vec2 uv = ex_UV.xy * vec2(1.0, 3.2);
	vec4 sampld = texture(tex, uv);
	vec3 col = sampld.rgb;

	if (sampld.a <= ALPHA_TEST_THRESHOLD) {
		discard;
	}
	
	out_Color = vec4(vec3(1.0), 1.0);
	
	out_Position = ex_Position.xyz;

	vec2 d_uv_x = dFdx(uv),
		 d_uv_y = dFdy(uv);
	
	vec3 dp_x = dFdx(ex_Position.xyz),
		 dp_y = dFdy(ex_Position.xyz);

	vec3 dp_du = dp_x * d_uv_x.x + dp_y * d_uv_y.x,
		 dp_dv = dp_x * d_uv_x.y + dp_y * d_uv_y.y;

	//vec3 orig_normal = normalize(-cross(dp_du, dp_dv));//normalize(ex_Normal);
	vec3 orig_normal = normalize(ex_Normal);

	// orthonormalize
	dp_du = normalize(dp_du - dot(dp_du, orig_normal) * orig_normal);
	dp_dv = normalize(dp_dv - dot(dp_dv, orig_normal) * orig_normal);

	mat3 tangent_to_world = mat3(dp_du, dp_dv, orig_normal);

	vec3 normal_sample = texture(emitMap, uv).xyz;
	vec3 tangent_space_normal = normalize(normal_sample*2.0-vec3(1.0));
	vec3 nor = normalize(tangent_to_world * tangent_space_normal);
	
	out_Normal = compressv3(nor);
	//out_Color = vec4(nor*.5+vec3(.5), 1.0);
	out_Material = vec4(0.00, scaleSpecular(50.0), 0.02, 0.0);
	//out_Material.x = 1.0;
}

#endif
