#version 330 core

uniform sampler2D diffuse;
uniform sampler2D specular;
uniform sampler2D bumpmap;
uniform float MorphFactor; // 0..1

in vec2 pos_zw;
in vec3 normal;
in vec3 ec_pos;
in vec4 uv_offset;
in float blend;

layout (location = 0) out vec4 diffuse_specular;
layout (location = 1) out vec4 normal_depth;

#include <geometry_include.frag>
#include <tangentspace_include.frag>

void main()
{
	vec2 morph_uv = vec2(cos(MorphFactor*uv_offset.z+uv_offset.x*32.0), 0.0)*MorphFactor*uv_offset.y*0.25;
	morph_uv = clamp(morph_uv, -1.0/3.0, 1.0/3.0);

	vec4 diff = mix(texture(diffuse, uv_offset.xy+morph_uv), texture(diffuse, uv_offset.zw+morph_uv), blend);
	if ( diff.a < 0.5 ) discard;

	vec3 t, b;
	per_fragment_tangent_space(ec_pos, uv_offset.xy, t, b);

	vec3 bump = normalize(texture2D(bumpmap, uv_offset.xy).xyz*2.0 - vec3(1.0));

	mat3 mr = mat3(t, b, normalize(normal));
	vec3 n = mr * bump;

	diffuse_specular.rgb = vec3(diff.rgb);
	diffuse_specular.a = texture(specular, uv_offset.xy).r;

	normal_depth.xyz = normalize(n);
	normal_depth.w = pos_zw.x/pos_zw.y;
}
