varying vec2 texCoord;
uniform samplerCube envMap;
varying mat3 toTheWorldSpace;
uniform float eta;

bool intersect(vec3 rdir, vec3 pos, vec3 boxmin, vec3 boxmax, out float tnear, out float tfar)
{
  vec3 invR = 1.0 / rdir;
  //finner treffpunkter for alle 6 plan
  vec3 tbot = invR * (boxmin - pos);
  vec3 ttop = invR * (boxmax - pos);
  
  //finner min/max for alle par av parallelle plan
  vec3 tmin = min(ttop,tbot);
  vec3 tmax = max(ttop,tbot);
  
  //finner største tmin og minst tmax
  vec2 t0 = max(tmin.xx,tmin.yz);
  tnear = max(t0.x,t0.y);
  t0 = min(tmax.xx, tmax.yz);
  tfar = min(t0.x,t0.y);
  return tnear <= tfar;
  
}

vec3 normalGet(vec3 hitPoint)
{

 float epsilol = 0.01;
 vec3 lolNorm = vec3(0.0,0.0,0.0);
  if( hitPoint.y > (-75.0 - epsilol) && hitPoint.y < (-75.0 + epsilol) )
 {
	lolNorm.y=-1.0;
 }
 
 if( hitPoint.y > (75.0 - epsilol) && hitPoint.y < (75.0 + epsilol) )
 {
	lolNorm.y=1.0;
 }
 
 if( hitPoint.x > (-75.0 - epsilol) && hitPoint.x < (-75.0 + epsilol) )
 {
	lolNorm.x=-1.0;
 }
 
 if( hitPoint.x > (75.0 - epsilol) && hitPoint.x < (75.0 + epsilol) )
 {
	lolNorm.x=1.0;
 }
 
 if( hitPoint.z > (-75.0 - epsilol) && hitPoint.z < (-75.0 + epsilol) )
 {
	lolNorm.z=-1.0;
 }
 
 if( hitPoint.z > (75.0 - epsilol) && hitPoint.z < (75.0 + epsilol) )
 {
	lolNorm.z=1.0;
 }
  //we flip the normals, since we're INSIDE the box.
  lolNorm *=-1.0;
 lolNorm = toTheWorldSpace*lolNorm;

 return normalize(lolNorm);
}

varying vec3 norm;
varying vec3 eyeVec;
varying vec3 lightVec;
varying vec3 p0;


void main()
{
vec3 boxMin = vec3(-75.0,-75.0,-75.0);
vec3 boxMax = vec3(75.0,75.0,75.0);

vec3 bumpNorm = norm;
bumpNorm = normalize(bumpNorm);
vec3 envCol1 = textureCube(envMap,reflect(normalize(eyeVec),bumpNorm)).rgb;

vec3 refractedVec = refract(normalize(eyeVec),bumpNorm,eta);

float tNear;
float tFar;

float fressy = ((1.0 - eta)*(1.0 - eta))/((1.0 + eta)*(1.0 + eta));
float superFres = fressy + (1.0 - fressy)*pow((1.0-dot(normalize(-eyeVec),bumpNorm)),5.0);

if(refractedVec != vec3(0.0,0.0,0.0))
for(int i=0; i < 2; i++)
 {
  intersect(normalize(refractedVec),p0,boxMin,boxMax,tNear,tFar);
  vec3 p1 = p0 + refractedVec*tFar;
  vec3 newNorm = normalGet(p1);
  vec3 newRefr = refract(refractedVec,newNorm,1.0/eta);
  if(newRefr == vec3(0.0,0.0,0.0))
  {
   
   //reflect and re-do
   refractedVec = reflect(refractedVec,newNorm);
  
  }
  else
  {
    refractedVec = newRefr;
	break;
  }
 }
else
{
 superFres = 0.0;
}
vec3 envCol2 = textureCube(envMap,refractedVec).rgb;
//superFres = clamp(superFres,0.0,1.0);
vec3 p0Col = mix(envCol1,envCol2,superFres);
gl_FragColor = vec4(p0Col ,1.0);

}