#version 150

//#extension GL_ARB_conservative_depth: enable
//layout(depth_less) out float gl_FragDepth;

in vec3 src_normal, normal, binormal;//, et;
in vec4 pos, ppos;
in float fogCoord, FC, C;
in mat3 TBN;

uniform bool acc_fog;
uniform vec2 dt;
uniform float z_far, z_near;

const vec3 luma = vec3(0.299, 0.587, 0.114);

void main(void) {
	//float z = pos.w;//((z_near / (z_near-z_far)) * z_far) / (pos.w - (z_far / (z_far-z_near)));
	//float logz = log(pos.w * C + 1.) * FC;
	vec4 dc = qgl_FragColor;
	vec2 tc = qgl_FragTexture.xy;
	float hei = dot(texture(qgl_Material.map_relief.map, tc * qgl_Material.map_relief.scale).rgb, luma) * qgl_Material.map_relief.amount + qgl_Material.map_relief.offset;

	vec3 n, dn, bn;
	dn = texture(qgl_Material.map_normal.map, tc * qgl_Material.map_normal.scale).rgb - vec3(0.5, 0.5, 1.);
	dn = dn * qgl_Material.map_normal.amount + qgl_Material.map_normal.offset;
	dn.y = -dn.y;
	dn = TBN * dn;
	//dn.z = 0;
	n = normalize(qgl_NormalMatrix * (normal + dn));
	bn = normalize(qgl_NormalMatrix * binormal);
	//n = dn;

	dc *= texture(qgl_Material.map_diffuse.map, tc * qgl_Material.map_diffuse.scale) * qgl_Material.map_diffuse.amount + qgl_Material.map_diffuse.offset;

	vec4 spec = texture(qgl_Material.map_specular.map, tc * qgl_Material.map_specular.scale) * qgl_Material.map_specular.amount + qgl_Material.map_specular.offset;
	spec *= qgl_Material.color_specular;
	float specularity = dot(texture(qgl_Material.map_specularity.map, tc * qgl_Material.map_specularity.scale).rgb, luma) * qgl_Material.map_specularity.amount + qgl_Material.map_specularity.offset;
	specularity = clamp(specularity, 0.05, 0.99);
	float reflectivity = qgl_Material.reflectivity;//dot(texture(qgl_Material.map_specularity.map, tc).rgb, luma) * qgl_Material.map_specularity.amount + qgl_Material.map_specularity.offset;
	reflectivity = clamp(reflectivity, 0., 1.);
	vec4 self = texture(qgl_Material.map_self_illumination.map, tc * qgl_Material.map_self_illumination.scale) * qgl_Material.map_self_illumination.amount + qgl_Material.map_self_illumination.offset;
	self *= qgl_Material.color_self_illumination;

	vec3 speed = pos.xyz/pos.w - ppos.xyz/ppos.w;
	//speed /= abs(pos.z);

	//gl_FragDepth = logz;
	qgl_FragData[0] = vec4(dc.rgb, 0.);
	qgl_FragData[1] = vec4(n.xyz, specularity + round(reflectivity * 100));
	qgl_FragData[2] = vec4(spec.rgb, hei);
	qgl_FragData[3] = vec4(self.rgb, bn.x);
	qgl_FragData[4] = vec4(speed.xy, bn.yz);

	//gl_FragData[0] = vec4(et.xyz, pos.w);
	//gl_FragDepth = gl_FragCoord.z - clamp(hei / pos.z / pos.z / (abs(n.z) + 1), -0.01, 0.01);
	/*vec4 dp = pos;
	dp.x = floor(dp.w / 255.) / 255.;
	dp.w -= dp.x * 65025;
	dp.y = floor(dp.w) / 255.;
	dp.w -= dp.y * 255.;
	dp.z = fract(dp.w);*/
	//dp.x = dp.w;
	//dp.w = (gl_FrontMaterial.specular.r + gl_FrontMaterial.specular.g + gl_FrontMaterial.specular.b) / 3. / 25.5;
	//gl_FragData[2] = dp;
	//gl_FragData[3] = vec4(light_model / 255., 0, 0, 0);
}
