#version 330 core

uniform sampler2D bumpmap;
uniform sampler2D base;
uniform sampler2D diffuse;
uniform sampler2D flow;
uniform sampler2D foam;
uniform float time;
uniform float height;

in vec3 normal;
in vec3 ec_pos;
in vec2 uv;
in vec2 uv2;
in vec3 offset_y;
in vec2 pos_zw;

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

#include <tangentspace_include.frag>

void main()
{
	const vec3 diff = vec3(53.f/255.0, 62.0/255.0, 93.0/255.0);
	const vec3 refr = vec3(53.f/255.0, 62.0/255.0, 93.0/255.0);
	const vec3 refl = vec3(83.f/255.0, 92.0/255.0, 113.0/255.0)*0.5;
	const vec3 ld = vec3(0.0, 0.0, 1.0);
	
	// pseudo water flow
	vec3 f = texture(flow, uv*0.0625).rgb;
	vec2 flow_uv = f.rg*2.0 - vec2(1.0);
	float flow_offset0 = mod(time, 1.0);
	float flow_offset1 = mod(time + 0.5, 1.0);
	float cycle_offset = f.b;

	float phase0 = cycle_offset*0.5 + flow_offset0;
	float phase1 = cycle_offset*0.5 + flow_offset1;

	// make waves
	vec3 bump0 = texture(bumpmap, uv - flow_uv*phase0).rgb*2.0 - vec3(1.0);
	vec3 bump1 = texture(bumpmap, uv - flow_uv*phase1).rgb*2.0 - vec3(1.0);
	vec3 bump2 = texture(bumpmap, uv*16.0+offset_y.xy).rgb*2.0 - vec3(1.0);
	float k = abs( 0.5 - flow_offset0 ) / 0.5;
	vec3 n = normalize(mix(bump0, bump1, k) + bump2*0.25);

	// fake lighting
	float lit = pow(max(dot(n, ld), 0.0), 5.0);
	
	//vec3 r = normalize(refract(vec3(0.0,0.0,-1.0), n, 0.33));
	vec3 r = normalize(refract(vec3(0.0,0.0,-1.0), n, 1.0));
	float rf = pow(max(dot(r, ld), 0.0), 1.0);

	vec3 r2 = normalize( reflect(vec3(0.0,0.0,-1.0), n) );
	float rf2 = pow(max(dot(r2, ld), 0.0), 32.0);

	// water overlay
	float ref_scale = smoothstep(0.0, 0.15, uv.x) * (1.0 - smoothstep(0.9, 1.0, uv.x));
	vec3 r3 = reflect(vec3(0.0, 0.0, 1.0), n);

	//float uv_scale = (offset_y.z - 6.0);
	//float uv_scale = max(offset_y.z - 6.0, 0.0);
	float uv_scale = max(offset_y.z - height, 0.0);
	vec2 refr_uv = r3.xy*(1.0/64.0)*uv_scale;
	vec2 refl_uv = r2.xy*(1.0/64.0)*uv_scale;

	vec4 grnd_refr = texture(diffuse, uv + refr_uv*ref_scale);
	vec4 grnd = texture(diffuse, uv + refl_uv*ref_scale);

	// ground
	float darkness = 1.0 - pow((offset_y.z - 7.0)/3.0, 3.0);
	darkness = max(darkness - sin(uv.x*3.14)*0.9, 0.0);

	vec4 btm_refr = texture(base, uv2 + refr_uv*ref_scale)*darkness;
	vec4 btm = texture(base, uv2 + refl_uv*ref_scale)*darkness;

	grnd_refr.rgb = mix(btm_refr.rgb, grnd_refr.rgb, grnd_refr.a);
	grnd.rgb = mix(btm.rgb, grnd.rgb, grnd.a);

	// color pixel
	vec3 fm = texture(foam, uv*2.0 + refr_uv).rrr;

	vec3 water = diff*lit + refr*rf + refl*rf2 + fm*rf2;

	float alpha = clamp(lit + rf + rf2, 0.2, 1.0);// * grnd.a;

	diffuse_specular.rgb = mix(mix(grnd.rgb, grnd_refr.rgb, lit), + water, alpha*0.25);
	diffuse_specular.a = alpha;

	vec3 t, b, nn;
	nn = normalize(normal);
	per_fragment_tangent_space(ec_pos, uv, t, b);
	mat3 mr = mat3(t, b, nn);
	n = mr * n;

	normal_depth.rgb = mix(nn, n, 0.125);
	normal_depth.a = pos_zw.x / pos_zw.y;
}
