uniform sampler2D 	colorTex,
					normalTex,
					matTex,
					posTex;
//uniform samplerCube	ambientCube;
uniform samplerCube	envCube;
varying vec2 		texcoord;
uniform vec4		ambientColor;
uniform vec3		WTM0,
					WTM1,
					WTM2;			
varying vec2		VPOS;
uniform mat4		eyeToWorld;
uniform vec3		campos;
uniform	float		reflMul;

vec4 decode(vec4 enc)
{
    vec2 fenc = enc.xy*4.0-2.0;
    float f = dot(fenc,fenc);
    float g = sqrt(1.0-f/4.0);
    vec4 n;
    n.xy = fenc.xy*g;
    n.z = 1.0-f/2.0;
	n.w=enc.w;
    return n;
}

void main()
{
	vec4 finalcolor=vec4(0.0,0.0,0.0,0.0);

	vec4 ambient = texture2D(colorTex,texcoord.st);
	vec4 normal = decode(texture2D(normalTex,texcoord.st));
	vec4 pos;
	pos.z = texture2D(posTex,texcoord.st).r;
	vec4 mat = texture2D(matTex,texcoord.st);
	
	pos.xy=VPOS.xy*-pos.z;
	pos.w=1.0;
	pos=eyeToWorld*pos;
	
		vec4 N=eyeToWorld*vec4(normal.xyz,0.0);
		
		vec4 diffuse = textureCubeLod(envCube,-N.xyz,6.0);

		vec3 vdir=normalize(campos-pos.xyz);
		vec3 reflection = reflect(vdir,N.xyz);
		vec4 specular = textureCubeLod(envCube,reflection.xyz,(1.0-mat.y)*7.0);
		
	finalcolor = ambientColor*mix(ambient*diffuse,specular*reflMul,mat.y); //(ambientColor*ambient*diffuse)*(1.0-mat.y)+specular*ambientColor*reflMul*mat.y;
	gl_FragColor=max(finalcolor,0.0);
}
