//--------------------------------------------------------
// COMP 238 Programming Assignemt 2 - stochastic ray tracer
// Adrian Ilie
//--------------------------------------------------------

#include "raytracer.h"
#include <math.h>
#include <fstream>
#include <iostream>
#include <stdlib.h>

#define PI 3.1415926535897932384626433832795
#define MAX_TREE_DEPTH 3
#define EPSILON 1e-3
#define AIR_REFRACTION_INDEX 0.999
#define NUM_LIGHT_SAMPLES 10
#define MAX_COLOR_DIFFERENCE 0.1
#define NUM_RAY_SAMPLES 4
#define AA_PERTURBATION 0.4
#define NUM_REFL_SAMPLES 4
#define BR_PERTURBATION 0.5
#define NUM_BLUR_SAMPLES 4
#define MB_PERTURBATION 0.1
//#define ANTI_ALIAS
//#define BLURRED_REFLECTION
//#define MOTION_BLUR

double random(double interval)//pseud random number generator
{
	int r=rand();
	return double(r) / RAND_MAX * interval - interval;
}

double sign(double no)
{
	if(no>0) return 1;
		else return -1;
}

//--------------------------------------------------------
// Point class
//--------------------------------------------------------
cPoint::cPoint()
{
	X = Y = Z = 0.0;
}

cPoint::cPoint(double vX, double vY, double vZ)
{
	X = vX;
	Y = vY;
	Z = vZ;
}

double cPoint::Distance(const cPoint& p) const
{
	return sqrt( (p.X - X)*(p.X - X) + (p.Y - Y)*(p.Y - Y) + (p.Z - Z)*(p.Z - Z) );
}

bool cPoint::operator==(cPoint& p) const
{
	return ( X == p.X )&&( Y == p.Y )&&( Z == p.Z );
}

//--------------------------------------------------------
// Vector class
//--------------------------------------------------------
cVector::cVector()
{
	I = J = K = 0.0;
}

cVector::cVector(const cPoint& p1, const cPoint& p2)
{
	I = p2.X - p1.X;
	J = p2.Y - p1.Y;
	K = p2.Z - p1.Z;
}

cVector::cVector(double vI, double vJ, double vK)
{
	I = vI;
	J = vJ;
	K = vK;
}

cVector cVector::Normalize() const
{
	double m = Magnitude();
	if (m != 0)return cVector(I/m, J/m, K/m);
	else return cVector(0.0, 0.0, 0.0);
}

double cVector::DotProd(const cVector& v) const
{
	return I*v.I + J*v.J + K*v.K;
}

cVector cVector::CrossProd(const cVector& v) const
{
	return cVector(J*v.K - v.J*K, -1.0*(I*v.K - v.I*K), I*v.J - v.I*J);
}

cVector cVector::operator+ (cVector v) const
{
	return cVector(I + v.I, J + v.J, K + v.K);
}

cVector cVector::operator- (cVector v) const
{
	return cVector(I - v.I, J - v.J, K - v.K);
}

cPoint cVector::operator+ (cPoint p) const
{
	return cPoint(I + p.X, J + p.Y, K + p.Z);
}

cVector cVector::operator* (double s) const
{
	return cVector(I*s, J*s, K*s);
}

cPoint cVector::VectorToPoint() const
{
	return cPoint(I,J,K);
}

double cVector::Magnitude() const
{
	return sqrt(I*I + J*J + K*K);
}

//--------------------------------------------------------
// Color class
//--------------------------------------------------------
double clamp01(double d)
{
	if (d<0)d=0;
	if (d>1)d=1;
	return d;
}

cColor::cColor(double vR, double vG, double vB)
{
//	R = clamp01(vR);
//	G = clamp01(vG);
//	B = clamp01(vB);
	R = vR;
	G = vG;
	B = vB;
}

cColor cColor::operator* (double s) const//multiply by scalar
{
	return cColor(R*s, G*s, B*s);
}

cColor cColor::operator/ (double s) const//divide by scalar
{
	return cColor(R/s, G/s, B/s);
}

cColor cColor::operator+ (const cColor& c) const
{
	return cColor(R+c.R,G+c.G,B+c.B);
}

cColor cColor::operator* (const cColor& c) const
{
	return cColor(R*c.R,G*c.G,B*c.B);
}

unsigned char cColor::bR() const
{
	return DoubleToByte(R);
}
unsigned char cColor::bG() const
{
	return DoubleToByte(G);
}
unsigned char cColor::bB() const
{
	return DoubleToByte(B);
}

unsigned char cColor::DoubleToByte(double d) const
{
	return (unsigned char)(clamp01(d)*255.0);
}

//--------------------------------------------------------
// Light class
//--------------------------------------------------------
cLight::cLight(const double x, const double y, const double z, const double r, const double g, const double b) : Point(x, y, z), Color(r, g, b)
{
	Type = string("Point");
}

cColor cLight::Contribution(const cRay& r, const cShape* s, const cPoint& p)
{
	cColor diffuse = cColor(0.0, 0.0, 0.0);
	cColor specular = cColor(0.0, 0.0, 0.0);
	cVector N, L, V, R;
	double NdotL, RdotV;
		
	N = s->Normal(p, Point);//normal on surface at intersection point
	L = cVector(p, Point);//ray form intersection point to light
	L = L.Normalize();//ray to light normalized
	NdotL = N.DotProd(L);//normal dot ray to light

	if (NdotL < 0) return diffuse;//light behind surface, return zero
	
	if (s->texture == NULL)	
	{
		if (s->surface!=NULL)
			diffuse = s->surface->Diffuse * NdotL;
	}
	else diffuse = s->Texture(p) * NdotL;

	R = s->Reflect(p, cRay(Point, p)).Direction.Normalize();//ray to light reflected
	V = r.Direction.Normalize() * -1.0;//incident ray reversed
	RdotV = R.DotProd(V);
	if (RdotV >= 0.0)//get specular highlight	
		if (s->surface!=NULL)
			specular = s->surface->Specular * pow(RdotV, s->surface->SpecularPower) * s->surface->Reflectivity;

	return Color * (diffuse + specular);
}

//--------------------------------------------------------
// Extended Light class
//--------------------------------------------------------
cExtendedLight::cExtendedLight(const double x, const double y, const double z, const double r, const double g, const double b, const double rad) : cLight(x, y, z, r, g, b)
{
	radius = rad;
	Type = string("Extended");
}

//--------------------------------------------------------
// Ray class
//--------------------------------------------------------
cRay::cRay(const cPoint& p, const cVector& v): Direction(v), Origin(p){};

cRay::cRay(const cPoint& p1, const cPoint& p2): Direction(cVector(p1,p2)), Origin(p1){};

//--------------------------------------------------------
// Shape class (abstract)
//--------------------------------------------------------
cShape::cShape()
{
	surface = NULL;
	texture = NULL;
}

cRay cShape::Reflect(const cPoint& p, const cRay& r) const
{
	cRay reflected;
	cVector V = r.Direction.Normalize();
	cVector N = Normal(p, r.Origin );
	double NdotV = N.DotProd(V);
	if ( NdotV < 0.0 )
		N = N * -1.0;//flip the normal

	reflected.Origin = p;
	reflected.Direction = r.Direction.Normalize() + N * (2 * NdotV);

	return reflected;
}

cRay cShape::Refract(const cPoint& p, const cRay& r) const
{
	cRay refracted;
	cVector normal = Normal(p, r.Origin );
	double RdotN = normal.DotProd(r.Direction * -1.0);
	double n1,n2;
	if ( normal.DotProd(r.Direction.Normalize()) > 0.0 )
	{
		normal = normal * -1.0;//flip the normal
		RdotN = -RdotN;
		n1 = surface->RefractionIndex;
		n2 = AIR_REFRACTION_INDEX;
	}
	else
	{
		n2 = surface->RefractionIndex;
		n1 = AIR_REFRACTION_INDEX;
	}

	refracted.Origin = p;
	refracted.Direction = (r.Direction.Normalize() + (normal * RdotN)) * (n1 / n2) -
		(normal * sqrt(1.0 - n1*n1*(1-RdotN*RdotN)/(n2*n2)));

	return refracted;
}

//--------------------------------------------------------
// Sphere class
//--------------------------------------------------------
cSphere::cSphere(double r, double x, double y, double z) : Center(cPoint(x,y,z)), Radius(r)
{
	Type = string("Sphere");
}

bool cSphere::Intersect(const cRay& r, cPoint& p) const
{
	cVector EO(r.Origin, Center);	
	cVector E(cPoint(0,0,0), r.Origin); // E = vector from origin to ray origin
	cVector V = r.Direction.Normalize();
	double v = V.DotProd(EO);
	if (v < 0) return false;
	{
		double t = Radius*Radius + v*v - EO.DotProd(EO);
		if (t < 0) return false;
		else
		{
			cVector P = E + V*(v-sqrt(t));
			p = P.VectorToPoint();
			return true;
		}
	}
}

cVector cSphere::Normal(const cPoint& p1, const cPoint& p2) const
{
	cVector radius(Center, p1);//p1 on surface
	if (Center.Distance(p2) - Center.Distance(p1) <= EPSILON)//p2 second intersection with sphere or inside
		radius = radius * -1.0;//reverse it
	return (radius.Normalize());
}

cColor cSphere::Texture(const cPoint& p) const
{
	cColor color(1,1,1);//neutral

	cVector Vn, Vp, Ve;
	double u, v, theta;

	Vp = cVector(Center, p).Normalize();//to point
	Vn = cVector(Center, cPoint(Center.X, Center.Y, Center.Z+1)).Normalize();//to North Pole
	Ve = cVector(Center, cPoint(Center.X-1, Center.Y-1, Center.Z)).Normalize();//to Equator
	
	double phi = acos( -Vn.DotProd(Vp));

    v = 1 - phi / PI;

    theta = (acos(Vp.DotProd(Ve) / sin(phi))) / (2 * PI) ;
    if ( Vp.DotProd(Vn.CrossProd(Ve)) > 0 ) u = theta;
     else u = 1 - theta;

	color = texture->getPixel(u * texture->Width, v * texture->Height );
	
	return color;
}

//--------------------------------------------------------
// Plane class
//--------------------------------------------------------
cPlane::cPlane(double x, double y, double z, double nx, double ny, double nz)
{
	Point = cPoint(x, y, z);
	Normal2 = cVector(nx, ny, nz).Normalize();
	Type = string("Plane");
}

cPlane::~cPlane()
{}

bool cPlane::Intersect(const cRay& r, cPoint& p) const
{
	
	cVector nray = r.Direction.Normalize();
	if ( Normal2.DotProd(nray) > 0.0 )
		return false;//going in opposite direction

	cVector PU (r.Origin, Point);

	double t = Normal2.DotProd(PU) / Normal2.DotProd(r.Direction);
	p =  (r.Direction * t) + r.Origin;//intersect ray with plane

	return true; 
}

cVector cPlane::Normal(const cPoint& p1, const cPoint& p2) const
{
	return Normal2;
}

cColor cPlane::Texture(const cPoint& p) const
{
	cColor color(1,1,1);//not implemented
	return color;
}

//--------------------------------------------------------
// Triangle class
//--------------------------------------------------------
cTriangle::cTriangle(double v1x, double v1y, double v1z,
					 double v2x, double v2y, double v2z,
					 double v3x, double v3y, double v3z):
					 A(v1x, v1y, v1z),
					 B(v2x, v2y, v2z),
					 C(v3x, v3y, v3z)
{
	Type = string("Triangle");
	nA = nB = nC = cVector(0,0,0);
	uA = 0; vA = 0;
	uB = 0; vB = 0;
	uB = 0; vB = 0;
	double tmp, a, b, c;
	cColor color(1,1,1);//neutral
    AB = cVector(B, A);
	AC = cVector(C, A);
	BC = cVector(C, B);

	mAB = AB.Magnitude();
	mAC = AC.Magnitude();
	mBC = BC.Magnitude();

	a = mAB;
	b = mBC;
	c = mAC;
    if (b > a) {tmp = a; a = b; b = tmp;}
    if (c > a) {tmp = a; a = c; c = tmp;}
    if (c > b) {tmp = b; b = c; c = tmp;}
    areaABC = sqrt((a+(b+c))*(c-(a-b))*(c+(a-b))*(a+(b-c)))/4;
}

cTriangle::~cTriangle()
{
}

bool cTriangle::Intersect(const cRay& r, cPoint& p) const
{
	
	cVector normal = Normal(A, r.Origin);
	cVector nray = r.Direction.Normalize();
	if ( normal.DotProd(nray) > 0.0 )
		return false;//going in opposite direction

	cVector BU(r.Origin, B);

	double t = normal.DotProd(BU) / normal.DotProd(r.Direction);
	cPoint pt =  (r.Direction * t) + r.Origin;//intersect ray with plane

	cVector pA(A, pt);
	cVector pB(B, pt);
	cVector pC(C, pt);

	//point on same side of 3 lines
	double test1 = ((AB*(-1)).CrossProd(pA)).DotProd(normal);
	double test2 = ((BC*(-1)).CrossProd(pB)).DotProd(normal);
	double test3 = (AC.CrossProd(pC)).DotProd(normal);

	if ((test1 > 0 && test2 > 0 && test3 > 0) || (test1 < 0 && test2 < 0 && test3 < 0))
	{
		p = pt;
		return true; 
	}
	else
		return false;
}

cVector cTriangle::Normal(const cPoint& p1, const cPoint& p2) const
{
	cVector normal = AB.CrossProd(BC*(-1)).Normalize();	

	// get the plane normal facing the right way:
	cVector triangle_to_off_surface_point = cVector(A, p2 );
	triangle_to_off_surface_point.Normalize();
	if ( normal.DotProd(triangle_to_off_surface_point) < 0.0 )
	{
		normal = normal * -1.0;
	}

	return (normal);
}

cColor cTriangle::Texture(const cPoint& p) const
{
	double AP = p.Distance(A);
	double BP = p.Distance(B);
	double CP = p.Distance(C);
	double tmp, areaAPB, areaAPC, a, b, c, u, v, beta, gamma;
	cColor color(1,1,1);//neutral

	a = mAB;
	b = AP;
	c = BP;
//    if (b > a) {tmp = a; a = b; b = tmp;}//always false
//    if (c > a) {tmp = a; a = c; c = tmp;}//always false
    if (c > b) {tmp = b; b = c; c = tmp;}
    areaAPB = sqrt((a+(b+c))*(c-(a-b))*(c+(a-b))*(a+(b-c)))/4;

	a = mAC;
	b = AP;
	c = CP;
//    if (b > a) {tmp = a; a = b; b = tmp;}//always false
//    if (c > a) {tmp = a; a = c; c = tmp;}//always false
    if (c > b) {tmp = b; b = c; c = tmp;}
    areaAPC = sqrt((a+(b+c))*(c-(a-b))*(c+(a-b))*(a+(b-c)))/4;

	//barycentric coordinates
	beta = areaAPB / areaABC;
	gamma = areaAPC / areaABC;

	u = uA + beta*(uB - uA) + gamma*(uC - uA);
	v = vA + beta*(vB - vA) + gamma*(vC - vA);

	color = texture->getPixel(u * texture->Width, v * texture->Height );
	
	return color;
}

//--------------------------------------------------------
// Surface class
//--------------------------------------------------------
cSurface::cSurface() : Ambient(0,0,0), Diffuse(0,0,0), Specular(0,0,0)
{
	SpecularPower = 1;
	Transparency = 0;
	Reflectivity = 1;
	RefractionIndex = AIR_REFRACTION_INDEX;
}


//--------------------------------------------------------
// Image class
//--------------------------------------------------------
cImage::cImage(int width, int height)
{
	data = (unsigned char *)malloc(width * height * 3);
	Width = width;
	Height = height;
}

cColor cImage::getPixel(const int x, const int y)
{
	int offset = (y * Width + x) * 3;
	return cColor(data[offset]/255.0, data[offset + 1]/255.0, data[offset + 2]/255.0);
}

void cImage::setPixel(const int x, const int y, const cColor& c)
{
	int offset = (y * Width + x) * 3;
	data[offset] = c.bR();
	data[offset + 1] = c.bG();
	data[offset + 2] = c.bB();
}

void cImage::SaveToPPM(string filename)
{
	cColor color;
	ofstream file(filename.c_str(),ios::binary);
	file << "P6 " << Width << " " << Height << " 255" << '\n';
	for (int y = 0; y < Height; y++)
		for (int x = 0; x < Width; x++)
		{
			color = getPixel(x, y);
			file << (unsigned char)color.bR() << (unsigned char)color.bG() << (unsigned char)color.bB();		
		}
	file.close();
}

void cImage::LoadFromPPM(string filename)
{
	cColor color;
	FILE* file=fopen(filename.c_str(),"rb");
	char p6[3];
	int colors;
	fread(p6,3,1,file);
	fscanf(file,"%d",&Width);
	fscanf(file,"%d",&Height);
	fscanf(file,"%d",&colors);
	if (data) free(data);
	data = (unsigned char *)malloc(Width * Height * 3);
	fread(data,1,1,file);//skip a byte
	fread(data,Width * Height * 3,1,file);
	fclose(file);
}

//--------------------------------------------------------
// Tracer class
//--------------------------------------------------------
cTracer::cTracer() : Background(0.5,0.5,0.5), Eye(1,1,1), lookAt(0,0,0),upVector(0,0,1)
{
	fov = 45;
	FileName = "t.ppm";
	Shapes = new cShapeList;
	Lights = new cLightList;
	Surfaces = new cSurfaceList;
	Images = new cImageList;
}

cTracer::~cTracer()
{
	delete Shapes;
	delete Lights;
	delete Surfaces;
	delete img;
}

void cTracer::Trace()
{
	cRay rEye(Eye,cVector(0,0,0));
	cColor color, previous = cColor(0, 0, 0), diff;
	float x, y, dx, dy;
	int l = 0, c;
	for (y = -Height/2 + 0.5; y < Height/2; y++)
	{
		dy = y / Height;
		c = 0;
		for (x = -Width/2 + 0.5; x < Width/2; x++)
		{
			dx = x / Width;
			rEye.Direction.K = u.K * dx + v.K * dy + o.K;
			rEye.Direction.J = u.J * dx + v.J * dy + o.J;
			rEye.Direction.I = u.I * dx + v.I * dy + o.I;
			color = Cast(rEye, 0);

			#ifdef MOTION_BLUR
			cShape* moving = GetLastShape();
			cColor samples[NUM_BLUR_SAMPLES];
			cPoint center = ((cSphere*) moving)->Center;//store value
			double pert, totalweight=0;
			pert = -MB_PERTURBATION/2;
			for (int i=0; i<NUM_BLUR_SAMPLES; i++)
			{
				((cSphere*) moving)->Center.X = center.X + pert;
				((cSphere*) moving)->Center.Y = center.Y - pert;
				samples[i] = Cast(rEye, 0);
				totalweight ++; // weigh all samples equally
				pert += MB_PERTURBATION/NUM_BLUR_SAMPLES;
			}

			previous = color * 0.2;//20% the central sample (old)
			totalweight *= 1.25;//80% the new samples, 100%=80%*1.25

			for(i=0; i<NUM_BLUR_SAMPLES; i++)
				previous = previous + (samples[i] / totalweight);

			((cSphere*) moving)->Center = center;//restore value

			color = previous;
			#endif

			img->setPixel(c,l,color);
			if(c>0)
			{
				previous = img->getPixel(c-1, l);
				if((color.R-previous.R)*(color.R-previous.R)+
				  (color.R-previous.R)*(color.R-previous.R)+
				  (color.R-previous.R)*(color.R-previous.R)>MAX_COLOR_DIFFERENCE)
				{
					AntiAlias(x, y, c, l);
					AntiAlias(x-1, y, c-1, l);
				}
			}
			if(l>0)
			{
				previous = img->getPixel(c,l-1);;
				color = img->getPixel(c,l);
				if((color.R-previous.R)*(color.R-previous.R)+
				  (color.R-previous.R)*(color.R-previous.R)+
				  (color.R-previous.R)*(color.R-previous.R)>MAX_COLOR_DIFFERENCE)
				     AntiAlias(x, y-1, c, l-1);
			}
			c++;//column counter
			if (c%10==0)printf("*");
		}
		l++;//line counter
		printf(" %d\n",l);
	}
	img->SaveToPPM(FileName);
}

cColor cTracer::Cast(const cRay& r, int treeDepth)
{
	cShape *sClosest;
	cPoint pIntersect;
	cColor color = Background;
	if (treeDepth > MAX_TREE_DEPTH) return color;//background

	sClosest = Query(r, pIntersect);
	if (sClosest != NULL)
	{
		color = Shade(r, sClosest, pIntersect)
		        + Reflect(r, sClosest, pIntersect, treeDepth)
				+ Refract(r, sClosest, pIntersect, treeDepth);

	}

	return color;
}

cColor cTracer::Shade(const cRay& r, const cShape* s, const cPoint& p)
{
	cColor intensity(0,0,0);
	if (s->surface!=NULL) intensity = s->surface->Ambient;

	cColor contribution;

	cRay rReverse; //the ray that goes from intersection point to light sources
	cShape* sClosest; //closest shape on that ray
	cPoint pIntersect; //intersection point on that shape
	cLight* current;//current light
		
	cLightListIterator iLights = Lights->begin();
	while ( iLights != Lights->end() ) // for each light
	{
		current = (*iLights);

		rReverse.Origin = p;
		rReverse.Direction = cVector(rReverse.Origin, current->Point);
		sClosest = Query(rReverse, pIntersect);//any objects on path to light source?
		contribution = current->Contribution(r, s, p);

		if (current->Type=="Extended")//extended light source
			contribution = contribution * RaysToLight(s, p, current);

		if ((sClosest!=NULL)&&(sClosest->surface!=NULL)) intensity = intensity + contribution * sClosest->surface->Transparency;//light comes to p through sClosest (may be s itself)
			else intensity = intensity + contribution;//light comes to p directly
	
		iLights++;
	};
	return intensity;
}

cColor cTracer::Reflect(const cRay& r, const cShape* sClosest, const cPoint& pIntersect, int treedepth)
{
	cColor center, samples[NUM_REFL_SAMPLES], color(0,0,0);
	double totalweight=0, weights[NUM_REFL_SAMPLES], px, py, pz, dist;
	cVector newdir, diff, old;
	
	if (sClosest->surface==NULL) return color;//no surface properties, return zero
	if (sClosest->surface->Reflectivity == 0.0) return color;//return zero
	else
	{
		cRay rReflected = sClosest->Reflect(pIntersect, r);
		old = rReflected.Direction.Normalize();//normalize before perturbing

		center = Cast(rReflected, treedepth + 1);

		#ifdef BLURRED_REFLECTION
		for(int i=0; i<NUM_RAY_SAMPLES; i++)
		{
			px = random(BR_PERTURBATION);
			py = random(BR_PERTURBATION);
			pz = random(BR_PERTURBATION);
			newdir = cVector(px, py, pz);
			rReflected.Direction = old + newdir;//add the perturbation
			rReflected.Direction = rReflected.Direction.Normalize();//renormalize
			diff = rReflected.Direction - old;
			dist = diff.Magnitude();
			samples[i] = Cast(rReflected, treedepth + 2);//cheat a little, otherwise it takes too long ;)
			weights[i] = 1/dist;//inverse proportional to distance
			totalweight += weights[i];
		}

		color = center * 0.6;//60% the central sample
		totalweight *= 2.5;//40% the new samples, 100%=40%*2.5

		for(i=0; i<NUM_RAY_SAMPLES; i++)
			color = color + (samples[i] * (weights[i]/totalweight));//the rest, 10% for each ray
		#else
		color = center;
		#endif

		return color * sClosest->surface->Specular * sClosest->surface->Reflectivity;
	}
}

cColor cTracer::Refract(const cRay& r, const cShape* sClosest, const cPoint& pIntersect, int treedepth)
{
	if (sClosest->surface==NULL) return cColor(0,0,0);
	if (sClosest->surface->Transparency == 0.0) return cColor(0,0,0);
	else
	{
		cRay rRefracted = sClosest->Refract(pIntersect, r);
		return Cast(rRefracted, treedepth + 1) * sClosest->surface->Transparency;
	}
}

cShape* cTracer::Query(const cRay& r, cPoint& p)
{
	cShape* sClosest = NULL;
	cPoint pIntersect;
	double closest = 999999;
	double intersect;
	cShapeListIterator iShapes = Shapes->begin();

	while ( iShapes != Shapes->end() )
	{
		if ( (*iShapes)->Intersect( r, pIntersect ) )
		{
			intersect = pIntersect.Distance(r.Origin);
			if ((intersect < closest)&&(intersect >= EPSILON))
			{
				p = pIntersect;
				sClosest = *iShapes;
				closest = intersect;
			}
		}
		iShapes++;
	}

	return sClosest;
}

void cTracer::AddShape(cShape* s)
{
	Shapes->push_back(s);
}

void cTracer::AddLight(cLight* l)
{
	Lights->push_back(l);
}

void cTracer::AddSurface(cSurface* s)
{
	Surfaces->push_back(s);
}

void cTracer::AddImage(cImage* i)
{
	Images->push_back(i);
}

cSurface* cTracer::GetLastSurface()
{
	cSurface* su;
	cSurfaceListIterator iSurfaces = Surfaces->begin();
	while ( iSurfaces != Surfaces->end() )
	{
		su = * iSurfaces;
		iSurfaces++;
	}
	return su;
}

cSurface* cTracer::GetSurfaceByName(char *sn)
{
	cSurfaceListIterator iSurfaces = Surfaces->begin();
	cSurface* su = NULL;
	while ( iSurfaces != Surfaces->end() )
	{
		if ( strcmp((*iSurfaces)->name.c_str(), sn) == 0 ) su = *iSurfaces;
		iSurfaces++;
	}
	if (su)	return su;
	else 
	{
		fprintf(stderr,"Cannot find surface %s\n",sn);
		exit(1);
	}
}

cImage* cTracer::GetLastImage()
{
	cImage* im;
	cImageListIterator iImages = Images->begin();
	while ( iImages != Images->end() )
	{
		im = * iImages;
		iImages++;
	}
	return im;
}

cImage* cTracer::GetImageByName(char *in)
{
	cImageListIterator iImages = Images->begin();
	cImage* im = NULL;
	while ( iImages != Images->end() )
	{
		if ( strcmp((*iImages)->name.c_str(), in) == 0 ) im = *iImages;
		iImages++;
	}
	if (im)	return im;
	else 
	{
		fprintf(stderr,"Cannot find Image %s\n",in);
		exit(1);
	}
}

cShape* cTracer::GetLastShape()
{ 
	cShape* su;
	cShapeListIterator iShapes = Shapes->begin();
	while ( iShapes != Shapes->end() )
	{
		su = * iShapes;
		iShapes++;
	}
	return su;
}

void cTracer::ApplySurface(cShape* sh, char* sn)
{
	cSurface* su = GetSurfaceByName(sn);
	sh->surface = su;
}

void cTracer::ApplyImage(cShape* sh, char* in)
{
	cImage* im = GetImageByName(in);
	sh->texture = im;
}

void cTracer::SetupCamera()
{
	// setup u, v and o from lookAt and upVector
	cVector look = lookAt - cVector(Eye.X, Eye.Y, Eye.Z);
	u = look.CrossProd(upVector).Normalize();
	v = look.CrossProd(u).Normalize();
	o = look.Normalize() * (0.5 / tan((fov*PI/180.0) / 2));
}

double cTracer::RaysToLight(const cShape* s, const cPoint& p, const cLight* l)//for "extended" lights
{
	cPoint sampled;//point inside light source
	cRay rReverse;//ray from p to sampled point on light
	cShape* sClosest;//closest shape on that ray
	cPoint pIntersect;//intersection point on ray (not used here)
	double numRays = 0;
	cExtendedLight* el = (cExtendedLight*)l;
		
	for (int i=0; i<NUM_LIGHT_SAMPLES; i++)
	{
		sampled = cPoint(el->Point.X+random(el->radius), el->Point.Y+random(el->radius), el->Point.Z+random(el->radius));//point sampled on light

		rReverse.Origin = p;
		rReverse.Direction = cVector(rReverse.Origin, sampled);
		sClosest = Query(rReverse, pIntersect);//any objects on path to light source?

		if ((sClosest==NULL)||(sClosest==s))//no other objects on path to sampled point
			numRays ++;//= sampled.Distance(el->Point)/el->radius;//attenuation with distance to center
	}
	return numRays / NUM_LIGHT_SAMPLES;//weigh all samples equally
}

void cTracer::AntiAlias(const double x, const double y, const int c, const int l)
{
#ifdef ANTI_ALIAS
	cRay rEye(Eye,cVector(0,0,0));
	double dx, dy, px, py, dist, totalweight=0, weights[NUM_RAY_SAMPLES];
	cColor color, samples[NUM_RAY_SAMPLES];
	cColor old = img->getPixel(c, l);
	for(int i=0; i<NUM_RAY_SAMPLES; i++)
	{
		px = random(AA_PERTURBATION);
		py = random(AA_PERTURBATION);
		dist = sqrt(px*px + py*py);
		dy = (y+py) / Height;
		dx = (x+px) / Width;
		rEye.Direction.K = u.K * dx + v.K * dy + o.K;
		rEye.Direction.J = u.J * dx + v.J * dy + o.J;
		rEye.Direction.I = u.I * dx + v.I * dy + o.I;
		samples[i] = Cast(rEye, 0);
		weights[i] = 1/dist;//inverse proportional to distance
		totalweight += weights[i];
	}

	color = old * 0.6;//60% the central sample (old)
	totalweight *= 2.5;//40% the new samples, 100%=40%*2.5

	for(i=0; i<NUM_RAY_SAMPLES; i++)
		color = color + (samples[i] * (weights[i]/totalweight));

	img->setPixel(c, l, color);
#endif
}
