#include "headers.h"

double dot_product(xyz *a,xyz *b)
{
	double d;
	d=(a->x*b->x)+(a->y*b->y)+(a->z*b->z);
	return(d);
}

void cross_product(xyz *o,xyz *a,xyz *b)
{

	o->x = (a->y * b->z) - (a->z * b->y);
	o->y = (a->z * b->x) - (a->x * b->z);
	o->z = (a->x * b->y) - (a->y * b->x);


}

xyz refraction(double n1,double n2,xyz *ray,xyz *normal)
{
	double ci,n,t;
	xyz refract;
	ci=dot_product(ray,normal);
//adjusts the normal and ci according to whether the normal faces towards or away from the incident ray

if(ci<=0)
	{
		ci=-ci;
	}
	n=n1/n2;
	t=n*n*(1-(ci*ci));

	//condition for total internal reflection
	if(t>1.0)
	{
    return(reflection(ray,normal));
	}

	refract.x=n*ray->x+((n*ci)-sqrt(1.0-t))*normal->x;
	refract.y=n*ray->y+((n*ci)-sqrt(1.0-t))*normal->y;
	refract.z=n*ray->z+((n*ci)-sqrt(1.0-t))*normal->z;
	refract.normalize();

	return(refract);
}

	xyz reflection(xyz *ray,xyz *normal)

	{
		double k;
		xyz reflect;
	k= -2.0 * dot_product(ray,normal);
	reflect.x=k* normal->x + ray->x;
	reflect.y=k* normal->y + ray->y;
	reflect.z=k* normal->z + ray->z;
	reflect.normalize();
	return(reflect);
	}

	double fresnel(double n1,double n2,xyz *ray,xyz *normal)
	{
		double r0,r;
			r0 = ((n1-n2)*(n1-n2))/((n1+n2)*(n1+n2));
			double temp =1 + dot_product(ray,normal);
			r = r0 + (1 - r0) * pow(temp,4);
			return(r);
	}
