
uniform samplerCube cubemap;
uniform sampler2D normalmap;
uniform sampler2D depthBufFront;
uniform sampler2D depthBufBack;
uniform float depthBufWidth;
uniform float depthBufHeight;
uniform vec3 camPos;
uniform int usenormalmap;
uniform float sssScale;

varying vec3 normal;
varying vec4 worldPos;
varying mat3 modelWorld3x3;


void main(void)
{

	vec3 n = normalize(normal);
	if (usenormalmap==1) {
		n = normalize(texture2D(normalmap, vec2(gl_TexCoord[0].x, 1.0-gl_TexCoord[0].y)).xyz*2.0 - 1.0);
		n = vec3(n.x, -n.y, n.z);
		n = normalize(modelWorld3x3 * n);
	}


	vec3 view = normalize(worldPos.xyz - camPos.xyz);

	// fresnel stuff
	float n1 = 1.0; // reflection index of air
	//float n2 = 1.31; // reflection index of ice
	float n2 = 1.1;

	float cos1 = abs(dot(view, n));
	float sin1 = sqrt(1.0 - cos1*cos1);
	float sin2 = n1 * sin1 / n2;
	float cos2 = sqrt(1.0 - sin2*sin2);

	// reflection coefficient
	float R = (n1 * cos1 - n2 * cos2) / (n1 * cos1 + n2 * cos2);
	R *= R;
	//R = 0.5*R+0.5;

	// transmission coefficient
	float T = 1.0 - R;



	float sssx = gl_FragCoord.x / depthBufWidth;
	float sssy = gl_FragCoord.y / depthBufHeight;
	float sss = 1.0 - sssScale*4.0*(texture2D(depthBufFront, vec2(sssx, sssy)).r - texture2D(depthBufBack, vec2(sssx, sssy)).r);
	sss = clamp(sss, 0.0, 1.0);



	vec3 tex1 = -normalize(reflect(view, n));
	vec3 tex2 = normalize(-refract(view, n, n1/n2));


	vec3 lightDir = normalize(vec3(1.0, 0.0, 0.0));
	float l = clamp(dot(lightDir, -n), 0.0, 1.0);



	//gl_FragColor = vec4((n+1.0)*0.5, 1.0);
	//gl_FragColor = textureCube(cubemap, -tex1);
	//gl_FragColor = textureCube(cubemap, -refract(view, normal, n1/n2));


	vec4 col =
		1.0 * (R * textureCube(cubemap, tex1) +
			   T * textureCube(cubemap, tex2))*(1.0-sss*sss*sss*0.5);

	vec4 icol = vec4(0.6,0.8,1.0,1.0);

//	float b = pow(cos1, 3.0);
//	gl_FragColor = vec4(b*col.r*0.8+0.2, b*col.g*0.5+0.5, b*col.b*0.3+0.7, 1.0);
	gl_FragColor = 0.325*icol*(1.0-cos1*cos1)+col*0.25+0.5*col*cos1;// vec4(col.r, b*col.g*0.5+0.5, b*col.b*0.3+0.7, 1.0);

	//sss = sss*(0.85 + 1.85*l*l) + l*l*0.5;

	//sss = sss*(1.0-l) +

	gl_FragColor = vec4( ((1.0-l*l*l)*2.0*sss + l*(1.9+0.7*l))* (gl_FragColor.rgb), 1.0);
//	gl_FragColor = vec4( (clamp((1.0-l*l*1.5)*4.0*sss,0.0,1.0) + l*(0.3+0.7*l))*(gl_FragColor.rgb), 1.0);

//	gl_FragColor = (1.0-sss)*gl_FragColor*(1.0-l)*cos1+icol*(1.0-cos1)*((sss*sss*sss));//vec4( 1.0-sss,1.0-sss,1.0-sss,1.0);
//	gl_FragColor = (1.0-sss)*gl_FragColor+(1.0-0.5*l)*icol*((sss*sss*sss));//vec4( 1.0-sss,1.0-sss,1.0-sss,1.0);

	//gl_FragColor = vec4(n*0.5+0.5, 1.0);
	//gl_FragColor = vec4(n.x*0.5+0.5, 0.0, 0.0, 1.0);

}
