//--------------------------------------------------------
// COMP 236 Programming Assignemt 4 - simple ray tracer
// Adrian Ilie
//--------------------------------------------------------

#include "raytracer.h"
#include <math.h>
#include <fstream>
#include <iostream>
#include <stdlib.h>

//--------------------------------------------------------
// 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();
	return cVector(I/m, J/m, K/m);
}

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);
}

cColor cColor::operator* (double s) const//multiply 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);
}

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() : Point(0,0,0)
{
	Intensity = 0.1;
}

cLight::cLight(const cPoint& p) : Point(p)
{
	Intensity = 0.1;
}

//--------------------------------------------------------
// 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()
{
	Ambient = Diffuse = 0.5;
	SpecularSize = 50;
}

cRay cShape::Reflect(const cPoint& p, const cRay& r) const
{
	cRay reflected;
	cVector normal = Normal(p, cPoint() );
	if ( normal.DotProd(r.Direction.Normalize()) < 0.0 )
		normal * -1.0;

	reflected.Origin = p;
	reflected.Direction = normal*2.0 - r.Direction.Normalize();

	return reflected;
}

//--------------------------------------------------------
// Sphere class
//--------------------------------------------------------
cSphere::cSphere(cPoint p, double r) : Center(p)
{
	Radius = r;
}

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;
	V = V.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);
	return (radius.Normalize());
}

//--------------------------------------------------------
// Tracer class
//--------------------------------------------------------
cTracer::cTracer() : Background(0.5,0.5,0.5), Ambient(0.01,0.01,0.01), Eye(0,0,0)
{
	AmbientIntensity = 0.2;
	FileName = "t.ppm";
	Shapes = new cShapeList;
	Lights = new cLightList;
}

cTracer::~cTracer()
{
	delete Shapes;
	delete Lights;
}

void cTracer::Trace()
{
	cRay rEye(Eye,cVector(0,0,1));
	cColor color;
	int x, y;
	ofstream file(FileName.c_str(),ios::binary);
	file << "P6 " << Width << " " << Height << " 255" << '\n';
	rEye.Direction.K = (u.K + v.K + o.K);
	for (y = -Height/2; y < Height/2; y++)
	{
		printf("%d\n",y);
		rEye.Direction.J = (u.J + v.J + o.J) * y / Height;
		for (x = -Width/2 ; x < Width/2; x++)
		{
			rEye.Direction.I = (u.I + v.I + o.I) * x / Width;
			color = Cast(rEye);
			file << (unsigned char)color.bR() << (unsigned char)color.bG() << (unsigned char)color.bB();
		}
	}
}

cColor cTracer::Cast(const cRay& r)
{
	cShape* sClosest;
	cPoint pIntersect;
	sClosest = Query(r, pIntersect);
	if (sClosest == NULL) return Background+Ambient*AmbientIntensity;
	else return sClosest->Color * Shade(sClosest, pIntersect) + Ambient * sClosest->Ambient * AmbientIntensity;
}

double cTracer::Shade(const cShape* s, const cPoint& p)
{
	double intensity, specular;
	cRay r; // the ray that goes from the intersection point to the light sources
	double dot;
	cShape* sClosest;
	cPoint pIntersect;
	r.Origin = p;
	cRay rReverse;
	intensity = 0;
	cLightListIterator iLights = Lights->begin();
	while ( iLights != Lights->end() ) // for each light
	{
		r.Direction = cVector(p,(*iLights)->Point);
		rReverse.Origin = (*iLights)->Point;
		rReverse.Direction = cVector(rReverse.Origin,p);
		sClosest = Query(rReverse, pIntersect);
		cVector vNormal = s->Normal(p, (*iLights)->Point);
		if ((sClosest == NULL) ||
		   ((sClosest == s)))// && (r.Direction.DotProd(vNormal) >= 0.0 ) ) )
		{//gets light from the current light source	
			dot = vNormal.DotProd(r.Direction.Normalize()) * (*iLights)->Intensity;
			if (dot < 0.0) dot = 0.0;
			//dot=abs(dot);
			intensity += dot;
			//if ( r.Direction.DotProd(s->Normal(p, (*iLights)->Point)) >= 0.0 )
			{//get specular highlight
				specular = ComputeSpecular(s, p, *iLights);
				intensity += specular;
			}
		}
		iLights++;
	};
	return clamp01(intensity);
}

cShape* cTracer::Query(const cRay& r, cPoint& p)
{
	cShape* sClosest = NULL;
	cPoint pIntersect;
	double closest_distance = 999999;
	double intersect_distance;
	cShapeListIterator iShapes = Shapes->begin();
	while ( iShapes != Shapes->end() )
	{
		if ( (*iShapes)->Intersect( r, pIntersect ) )
		{
			intersect_distance =  pIntersect.Distance(r.Origin);
			if (intersect_distance < closest_distance)
			{
				p = pIntersect;
				sClosest = *iShapes;
				closest_distance = intersect_distance;
			}
		}
		iShapes++;
	}
	return sClosest;
}

double cTracer::ComputeSpecular(const cShape* s, const cPoint& p, const cLight* l)
{
	cRay r = s->Reflect(p,cRay(p, l->Point));
	cVector eye(p, Eye);
	cVector reflected = r.Direction.Normalize();
	eye = eye.Normalize();
	double dot = eye.DotProd(reflected);
	int i;
	double intensity = 1;
	for(i = 1; i<s->SpecularSize; i++) intensity *= dot;
	return clamp01(intensity * l->Intensity);
}

void cTracer::AddShape(cShape* s)
{
	Shapes->push_back(s);
}
void cTracer::AddLight(cLight* l)
{
	Lights->push_back(l);
}


double rand2()
{
	int r=rand();
	return r*1000/RAND_MAX;
}

//--------------------------------------------------------
// main
//--------------------------------------------------------
void main()
{
	cTracer* rt = new cTracer();
	int i;
	char buf[20];
	
	rt->Width = 400;
	rt->Height = 400;
	rt->fov = 60;
	rt->Eye = cPoint(0,0,0);

	rt->look = cVector(0,0,50);
	rt->up = cVector(0,-1,0);
	rt->u = rt->look.CrossProd(rt->up);
	rt->u = rt->u.Normalize();
	rt->v = rt->look.CrossProd(rt->u);
	rt->v = rt->v.Normalize();
	rt->o = rt->look.Normalize() * (rt->Width/2*tan(rt->fov*3.1415926535897932384626433832795/360.0)) - 
		(rt->u * (rt->Width/2)) - (rt->v * (rt->Height/2));

	cLight *l = NULL;
	cSphere *s;/*,*s1,*s2,*s3;

//avi animation
	l = new cLight(cPoint(0,-1000,0));
	l->Intensity = 0.4;
	rt->AddLight(l);

	l = new cLight(cPoint(0,1000,0));
	l->Intensity = 0.4;
	rt->AddLight(l);

	l = new cLight(cPoint(-1000,0,0));
	l->Intensity = 0.4;
	rt->AddLight(l);

	l = new cLight(cPoint(1000,0,0));
	l->Intensity = 0.4;
	rt->AddLight(l);

	l = new cLight(cPoint(1000,1000,500));
	l->Intensity = 0.4;
	rt->AddLight(l);

	s = new cSphere(cPoint(0,0,200),40);
	s->Color = cColor(1,0,0);
	rt->AddShape(s);

	s1 = new cSphere(cPoint(60,0,200),10);
	s1->Color = cColor(1,1,0);
	rt->AddShape(s1);

	s2 = new cSphere(cPoint(60,0,200),10);
	s2->Color = cColor(1,1,0);
	rt->AddShape(s2);

	s3 = new cSphere(cPoint(60,0,200),10);
	s3->Color = cColor(1,1,0);
	rt->AddShape(s3);

	double angle;
	for(i=0; i<360; i+=10)
	{
		angle = i*3.1415926535897932384626433832795/180;
		s1->Center=cPoint(70*sin(angle),70*cos(angle),200);
		s2->Center=cPoint(70*sin(angle),0,200-70*cos(angle));
		s3->Center=cPoint(0,70*cos(angle),200-70*sin(angle));
		rt->FileName.assign("picture");
		rt->FileName.append(itoa(i,buf,10));
		rt->FileName.append(".ppm");
		rt->Trace();
		printf("%d\n",i);
	}
*/

/*
//still frame - 7 spheres
	l = new cLight(cPoint(0,-1000,0));
	l->Intensity = 0.4;
	rt->AddLight(l);

	l = new cLight(cPoint(0,1000,0));
	l->Intensity = 0.4;
	rt->AddLight(l);

	l = new cLight(cPoint(-1000,0,0));
	l->Intensity = 0.4;
	rt->AddLight(l);

	l = new cLight(cPoint(1000,0,0));
	l->Intensity = 0.4;
	rt->AddLight(l);

	l = new cLight(cPoint(1000,1000,500));
	l->Intensity = 0.4;
	rt->AddLight(l);

	s = new cSphere(cPoint(60,40,200),20);
	s->Color = cColor(1,1,0);
	rt->AddShape(s);

	s = new cSphere(cPoint(-50,-70,200),20);
	s->Color = cColor(1,0,1);
	rt->AddShape(s);

	s = new cSphere(cPoint(0,0,400),60);
	s->Color = cColor(1,0,0);
	rt->AddShape(s);

	s = new cSphere(cPoint(40,-50,200),40);
	s->Color = cColor(0,1,1);
	rt->AddShape(s);

	s = new cSphere(cPoint(-40,50,200),35);
	s->Color = cColor(0,1,0);
	rt->AddShape(s);

	s = new cSphere(cPoint(-40,-50,300),70);
	s->Color = cColor(0,0,1);
	rt->AddShape(s);

	s = new cSphere(cPoint(-40,-40,200),30);
	s->Color = cColor(0,1,0.5);
	rt->AddShape(s);

	rt->FileName = "screenshot.ppm";
	rt->Trace();
*/
//still frame - 100 spheres
	
	l = new cLight(cPoint(0,-1000,0));
	l->Intensity = 0.6;
	rt->AddLight(l);

	l = new cLight(cPoint(0,1000,0));
	l->Intensity = 0.6;
	rt->AddLight(l);

	l = new cLight(cPoint(-1000,0,0));
	l->Intensity = 0.6;
	rt->AddLight(l);

	l = new cLight(cPoint(1000,0,0));
	l->Intensity = 0.6;
	rt->AddLight(l);

	l = new cLight(cPoint(1000,1000,500));
	l->Intensity = 0.6;
	rt->AddLight(l);

	
	for (i=1; i<100; i++)
	{
		s = new cSphere(cPoint(rand2()/5-100,rand2()/5-100,200+rand2()/10),rand2()/35);
		s->Color = cColor(rand2()/1000,rand2()/1000,rand2()/1000);
		rt->AddShape(s);
	}

	rt->FileName = "screenshot100.ppm";
	rt->Trace();
	delete rt;
}
