#version 150

uniform sampler2D t0, t1, ts, td, tbs;
uniform float z_near, z_far;
uniform mat4 mat_proj;
uniform vec3 cam_aim, cam_pos;

in vec3 view_dir;

const float _pe = 2.4e-7;

void main(void) {
	ivec2 tc = ivec2(gl_FragCoord.xy);
	vec4 v0 = texelFetch(t0, tc, 0), v1 = texelFetch(t1, tc, 0), vs = texelFetch(ts, tc, 0);
	vec3 sp = vec3(qgl_FragTexture.xy, v0.w);
	vec2 tsp;
	vec4 pos;
	float z = texelFetch(td, tc, 0).r;
	z = z + z - 1;
	z = ((_pe - 2.) * z_near) / (z + _pe - 1.); // infinite depth
	pos.w = 1;
	pos.xyz = view_dir * z;
	pos.z = -pos.z;
	vec4 spos = pos;
	vec4 tpos;

	vec3 dc = v0.rgb, n = v1.xyz;
	vec3 vd = normalize(view_dir);
	vec3 rn = reflect(vd, n);
	//rn.z += 1.;
	float coeff = clamp(1. - (dot(vec3(0,0,1), n)), 0, 1);
	coeff = coeff*coeff;
	/*coeff = coeff*coeff;
	coeff = coeff*coeff;
	coeff = coeff*coeff;*/
	float reflectivity = 0.;
	float specularity = modf(v1.w, reflectivity);

	rn.z = -rn.z;
	int i = 0;
	vec4 tv0;
	float l = z_far * 0.5;
	pos.xyz += rn * l;
	float cz;
	for (i = 0; i < 24; ++i) {
		tpos = mat_proj * pos;
		tsp = -(tpos.xy / tpos.w) / 2. + 0.5;
		cz = texture(td, tsp).r;
		cz = cz + cz - 1;
		cz = ((_pe - 2.) * z_near) / (cz + _pe - 1.); // infinite depth
		l *= 0.5;
		pos.xyz += rn * (step(pos.z, cz) * 2. - 1.) * l;
	}

	vec2 ess = abs(tsp - vec2(0.5, 0.5)) - vec2(0.3, 0.3);
	ess = clamp(ess, vec2(0, 0), vec2(0.2, 0.2));
	ess = smoothstep(vec2(0.2, 0.2), vec2(0, 0), ess);
	coeff *= min(ess.x, ess.y);
	vec4 pr_pos = mat_proj * pos, pr_spos = mat_proj * spos;
	pr_pos.xyz /= pr_pos.w;
	pr_spos.xyz /= pr_spos.w;
	float blur = step(0., coeff) * length(pr_pos.xyz - pr_spos.xyz) * (1. - specularity);
	vec3 rvs = texture(ts, tsp).rgb;

	qgl_FragData[0] = vec4(rvs.rgb, coeff / 1.1 + clamp(round(blur * 10), 0, 1000));
	//qgl_FragData[0] = vec4(rvs.rgb, cz/5);
	//qgl_FragData[0].rgb = vec3(tpos/10);
}
