varying vec2 		texcoord,
					alphacoord;
uniform sampler2D 	dif0,
					bmp0;
uniform sampler2D 	lmask;
uniform vec2		fresnel0;
//uniform vec4		dcolor0;
uniform vec2		//dscale0,
					bscale0;
uniform vec2		dofs0,
					bofs0;
varying float		fadeAlpha;
varying mat3		TBN;

uniform float 		reflMul;
					
vec2 encode (vec3 n)
{
	n=normalize(n);
    float f = sqrt(8.0*n.z+8.0);
    return n.xy / f + 0.5;
}

float blend1D(float f1, float f2, float a1, float a2, float alpha)
{
	float depth=0.2;
	float ma=max(a1+(1.0-alpha),a2+alpha)-depth;
	
	float b1=max(a1 + (1.0-alpha) - ma,0.0);
	float b2=max(a2 + alpha - ma,0.0);
	
	return (f1*b1 + f2*b2)/(b1+b2);
}

void main()
{

	vec4 	fbcolor;
	vec3	fnormal;
	vec2	ffresnel;
			
	float colorAlpha=texture2D(dif0,texcoord.st).a;	
	float alpha1=clamp(texture2D(lmask,alphacoord.st).a*fadeAlpha,0.0,1.0);
	float alpha=blend1D(0.0, 1.0, 0.8, colorAlpha, alpha1);
	alpha=mix(alpha,alpha1,0.5);
	
	fbcolor=texture2D(bmp0,texcoord.st*bscale0+bofs0);
	fnormal.xy=(fbcolor.xy*2.0-1.0);
	fnormal.z=sqrt(1.0-fnormal.x*fnormal.x-fnormal.y*fnormal.y);
	ffresnel.y=fresnel0.y*fbcolor.z;
	ffresnel.x=fresnel0.x;//*fbcolor.a;
	
	// normal
	gl_FragData[0].xy=encode(TBN*fnormal)*alpha;
	gl_FragData[0].z=ffresnel.x*alpha;
	gl_FragData[0].a=alpha;
	
	// mat
	gl_FragData[1].r=0.0;
	gl_FragData[1].g=ffresnel.y*alpha;
	gl_FragData[1].b=0.0;
	gl_FragData[1].a=alpha;
}
