#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <iostream.h>
#include <stdlib.h>
#include <fstream.h>
#include <math.h>
#include <string.h>

#include <GL/glut.h>
#include "LightField.h"


/******************************************************************************
* Definitions for BMP reader, ReadBMP().
******************************************************************************/
#define HEADER_SIZE 54

/******************************************************************************
* Swap red and blue channels.
******************************************************************************/
void swapRGB(int bufferSize, unsigned char *data)
{
    unsigned char utemp;
    for (int i=0;i<bufferSize;i+=3) {
            utemp = data[i];
            data[i] = data[i+2];
            data[i+2] = utemp;
    }
}

/******************************************************************************
* Get the size of a BMP file. 
******************************************************************************/
void GetSizeBMP(const char *fname, int &xsize, int &ysize)
{
    unsigned char *header;

    FILE *fid;
    fid = fopen(fname, "rb");

    if (fid==NULL)
        cerr << "could not open image file: " << fname << endl;
    assert(fid);

    // initialize the image header
    header = new unsigned char [HEADER_SIZE];
    
    // read the header 
    int numread = fread( header, sizeof(unsigned char ), HEADER_SIZE, fid);
    assert(numread == HEADER_SIZE);
    // cerr << endl;
    // cerr << "header 1: "; for (int i=0;i<14;i++) cerr << (int) header[i] << " ";    cerr << "end\n";
    // cerr << "header 2: "; for (i=14;i<54;i++) cerr << (int) header[i] << " ";    cerr << "end\n";
    
    xsize = 256*header[19] + header[18];
    ysize = 256*header[23] + header[22];
    delete [] header;
    fclose(fid);
}

void GetSizePPM(const char *fname, int &xsize, int &ysize)
{
	FILE* file=fopen(fname,"rb");
	char p6[3];
	fread(p6,3,1,file);
	fscanf(file,"%d",&xsize);
	fscanf(file,"%d",&ysize);
	fclose(file);
}

/******************************************************************************
* Read in a BMP file. The user is responsible for deleting it upon termination. 
******************************************************************************/
void cImage::ReadFromBMP(const char *fname)
{
    int i;
	int xsize, ysize;
    unsigned char *header;

    FILE *fid;
    fid = fopen(fname, "rb");

    if (fid==NULL)
        cerr << "could not open image file: " << fname << endl;
    assert(fid);

    // initialize the image header
    header = new unsigned char [HEADER_SIZE];
    
    // read the header 
    int numread = fread( header, sizeof(unsigned char ), HEADER_SIZE, fid);
    assert(numread == HEADER_SIZE);
    // cerr << endl;
    // cerr << "header 1: "; for (int i=0;i<14;i++) cerr << (int) header[i] << " ";    cerr << "end\n";
    // cerr << "header 2: "; for (i=14;i<54;i++) cerr << (int) header[i] << " ";    cerr << "end\n";
    
    xsize = 256*header[19] + header[18];
    ysize = 256*header[23] + header[22];
    //bitCount = 16*header[29]+header[28];

    //cerr << "Res " << resolution << " " << xSize << "x" << ySize << endl;

    // in BMP format, each scanline has to be aligned with a 32 bit word check
    int misalign = (3*(xsize)) % 4; // between 0 and 3
    int align = (4 - misalign) % 4;

    int dataSize = 3*(xsize)*(ysize);
    
    // initialize the image data
    data = new unsigned char[dataSize];

    // read the data 
    int lineSize = 3*(xsize)+align-3;
    int dataIndex = 0;
    unsigned char *tempbuf = new unsigned char [lineSize];
    for (i=0;i<(ysize);i++) {
        numread = fread(tempbuf, sizeof(unsigned char ), lineSize, fid);
        assert(numread == lineSize);
        for (int j=0;j<3*(xsize);j++) {
            data[dataIndex++] = tempbuf[j];
        }
    }
    // Swap the RGB color from the image
    swapRGB(3*(xsize)*(ysize), data);

    delete [] header;
    fclose(fid);
}

void cImage::ReadFromPPM(const char *fname)
{
	FILE* file=fopen(fname,"rb");
	char p6[3];
	int colors,iWidth,iHeight,numread,size;
	fread(p6,3,1,file);
	fscanf(file,"%d",&iWidth);
	fscanf(file,"%d",&iHeight);
	fscanf(file,"%d",&colors);
	size = iWidth * iHeight * 3;
	data = (unsigned char *)malloc(size);
	fread(data,1,1,file);//skip a byte
	numread = fread(data,sizeof(unsigned char),size,file);
	assert(numread == size);
	fclose(file);
}

void cImage::ReadFromFile(const char *fname)
{
	if (strstr(fname,".ppm")) ReadFromPPM(fname);
	else ReadFromBMP(fname);
}

//--------------------------------------------------------
// 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);
}

//--------------------------------------------------------
// Light Field class
//--------------------------------------------------------
cLightField::cLightField(char *filename)
{
	ifstream f;
	f.open(filename);
	if (!f.is_open())
	{	cerr << "Cannot read file " << filename << endl;
		exit(1);
	}

	cerr << "Reading model file " << filename << endl;

	char buffer[255];

	f >> buffer;//version
	f >> buffer;//2.0
	f >> buffer;//UseTextureCompression
	f >> buffer;//DXT1
	f >> buffer;//DataCameraFocalLength
	f >> dataFocalLength;
	f >> buffer;//DesiredCameraFocalLength
	f >> desiredFocalLength;
	f >> buffer;//DesiredCameraPosition
	f >> buffer;//x
	f >> buffer;//y
	f >> buffer;//z
	f >> buffer;//SuggestedFocalPlaneZMin
	f >> buffer;//v
	f >> buffer;//SuggestedFocalPlaneZMax
	f >> buffer;//v
	f >> buffer;//SuggestedFocalPlaneZValue
	f >> buffer;//v
	f >> buffer;//uvWidth
	f >> uvWidth;
	cerr << "uvWidth " << uvWidth << endl;
	f >> buffer;//uvHeight
	f >> uvHeight;
	cerr << "uvHeight " << uvHeight << endl;

	int x,y;
	f >> buffer;//file
	f >> x;
	f >> y;
	f >> buffer;//name
	if (strstr(buffer,".bmp")) 
	{
		GetSizeBMP(buffer,stWidth,stHeight);
		imageRowSize = stWidth+1;
	}
	else
	{
		GetSizePPM(buffer,stWidth,stHeight);
		imageRowSize = stWidth;
	}

	images = new cImage[uvWidth*uvHeight];

	for (int i=0; i<uvWidth*uvHeight; i++)
	{
		images[(x+y*uvWidth)].ReadFromFile(buffer);
		cerr << "*";
		if (i<uvWidth*uvHeight-1)
		{
			f >> buffer;//file
			f >> x;
			f >> y;
			f >> buffer;//name
		}
	}
	f.close();

	cerr << endl << "Done reading images" << endl;

	camWidth = 256;
	camHeight = 256;
	fb = (unsigned char *)malloc(camWidth*camHeight*3);

	//double ratioFromFile=desiredFocalLength/dataFocalLength;//ratio
	//dataFocalLength=stWidth/2;//assume 90 degrees FOV in data cameras
	//desiredFocalLength=dataFocalLength*ratioFromFile;
	camFOV=45;
	Eye.X=0;
	Eye.Y=0;
	Eye.Z=-dataFocalLength/2;


	W2=camWidth/2.0;
	H2=camHeight/2.0;
	uvW2=uvWidth/2.0;
	uvH2=uvHeight/2.0;
	stW2=stWidth/2.0;
	stH2=stHeight/2.0;

	Normal = cVector(0,0,-1);//normal on planes towards camera
	uvPoint=cPoint(-uvW2,-uvH2,0);
	stPoint=cPoint(-stW2,-stH2,dataFocalLength);

	lookAt=cVector(0,0,0);
	upVector=cVector(0,1,0);

	distanceBetweenCameras=4;
	frameNo = 0;

	SetupCamera();
}

cLightField::~cLightField()
{
	for (int i=0; i<uvWidth*uvHeight; i++)
		images[i].~cImage();
}

double round(double n)
{//round to nearest integer
	double c=ceil(n);
	if (c-n<0.5)return c;
	else return c-1;
}

void cLightField::ComputeImage()
{
	float x,y,dx,dy;
	cVector direction,PU;
	cPoint Intersect;
	double t,NdotDIR;
	double S1,T1,U1,V1,U,V,S,T;//cordinates of curently computed rays
	int l=0,c,screen,offset,index,i;
	int colors[4][3];//holds the color samples
	int color[3];//holds the total color
	double distances[4];
	double totaldistance;//sum of distances for weighting
	int numsamples;//number of samples taken into account
	double U1f,V1f,U1c,V1c;
	double imageOffset = -distanceBetweenCameras*ST2scene;

	for (y=-H2; y<H2; y++)
	{
		dy=y/camHeight;
		c=0;
		for (x=-W2; x<W2; x++)
		{
			memset(fb+(l*camWidth+c)*3,0,3);
			dx = x/camWidth;
			direction.K = u.K * dx + v.K * dy + o.K;
			direction.J = u.J * dx + v.J * dy + o.J;
			direction.I = u.I * dx + v.I * dy + o.I;
			cVector nray = direction.Normalize();
			NdotDIR = Normal.DotProd(direction);
			if ( Normal.DotProd(nray) < 0.0 )
			{
				numsamples = 0;
				totaldistance = 0;

				t = -NdotVE / NdotDIR;
				Intersect = (direction * t) + Eye;//intersect ray with UV plane
				U1 = Intersect.X;
				V1 = Intersect.Y;
				U1f = (U1-floor(U1))*(U1-floor(U1));
				V1f = (V1-floor(V1))*(V1-floor(V1));
				U1c = (ceil(U1)-U1)*(ceil(U1)-U1);
				V1c = (ceil(V1)-V1)*(ceil(V1)-V1);
				t = -(NdotVE + desiredFocalLength) / NdotDIR;
				Intersect = (direction * t) + Eye;//intersect ray with scene plane

				S1 = (-floor(U1)*distanceBetweenCameras - Intersect.X)*ST2scene;
				T1 = (-floor(V1)*distanceBetweenCameras - Intersect.Y)*ST2scene;			
				
				S = round(S1+stW2);//bias to give positive coordinates
				T = round(T1+stH2);

				U = floor(U1+uvW2);//bias to give positive coordinates
				V = floor(V1+uvH2);
				if((U>=0)&&(V>=0)&&(U<uvWidth)&&(V<uvHeight))
				{
					if((S>=0)&&(T>=0)&&(S<stWidth)&&(T<stHeight))
					{
						offset = (S + T * (imageRowSize))*3;
						index = V + U * uvWidth;
						colors[numsamples][0] = images[index].data[offset++];
						colors[numsamples][1] = images[index].data[offset++];
						colors[numsamples][2] = images[index].data[offset];
						distances[numsamples]=1/sqrt(U1f+V1f);
						totaldistance += distances[numsamples];
						numsamples++;
					}
				}

				//S1 = (floor(U1)*distanceBetweenCameras - Intersect.X)*ST2scene;
				//T1 = (ceil(V1)*distanceBetweenCameras - Intersect.Y)*ST2scene;			
				T1 += imageOffset;
				
				//S = round(S1+stW2);//bias to give positive coordinates
				T = round(T1+stH2);

				//U = floor(U1+uvW2);//bias to give positive coordinates
				V++;// = ceil(V1+uvH2);
				if((U>=0)&&(V>=0)&&(U<uvWidth)&&(V<uvHeight))
				{
					if((S>=0)&&(T>=0)&&(S<stWidth)&&(T<stHeight))
					{
						offset = (S + T * (imageRowSize))*3;
						index = V + U * uvWidth;
						colors[numsamples][0] = images[index].data[offset++];
						colors[numsamples][1] = images[index].data[offset++];
						colors[numsamples][2] = images[index].data[offset];
						distances[numsamples]=1/sqrt(U1f+V1c);
						totaldistance += distances[numsamples];
						numsamples++;
					}
				}

				//S1 = (ceil(U1)*distanceBetweenCameras - Intersect.X)*ST2scene;
				S1 += imageOffset;
				//T1 = (ceil(V1)*distanceBetweenCameras - Intersect.Y)*ST2scene;			
				
				S = round(S1+stW2);//bias to give positive coordinates
				//T = round(T1+stH2);

				U++;// = ceil(U1+uvW2);//bias to give positive coordinates
				//V = ceil(V1+uvH2);
				if((U>=0)&&(V>=0)&&(U<uvWidth)&&(V<uvHeight))
				{
					if((S>=0)&&(T>=0)&&(S<stWidth)&&(T<stHeight))
					{
						offset = (S + T * (imageRowSize))*3;
						index = V + U * uvWidth;
						colors[numsamples][0] = images[index].data[offset++];
						colors[numsamples][1] = images[index].data[offset++];
						colors[numsamples][2] = images[index].data[offset];
						distances[numsamples]=1/sqrt(U1c+V1c);
						totaldistance += distances[numsamples];
						numsamples++;
					}
				}

				//S1 = (ceil(U1)*distanceBetweenCameras - Intersect.X)*ST2scene;
				//T1 = (floor(V1)*distanceBetweenCameras - Intersect.Y)*ST2scene;			
				T1 -= imageOffset;
				
				//S = round(S1+stW2);//bias to give positive coordinates
				T = round(T1+stH2);

				//U = ceil(U1+uvW2);//bias to give positive coordinates
				V--;// = floor(V1+uvH2);
				if((U>=0)&&(V>=0)&&(U<uvWidth)&&(V<uvHeight))
				{
					if((S>=0)&&(T>=0)&&(S<stWidth)&&(T<stHeight))
					{
						offset = (S + T * (imageRowSize))*3;
						index = V + U * uvWidth;
						colors[numsamples][0] = images[index].data[offset++];
						colors[numsamples][1] = images[index].data[offset++];
						colors[numsamples][2] = images[index].data[offset];
						distances[numsamples]=1/sqrt(U1c+V1f);
						totaldistance += distances[numsamples];
						numsamples++;
					}
				}

				if (numsamples>0)
				{
					for (i=0; i<3; i++)
						color[i]=0;

					for (int i=0; i<numsamples; i++)
					{
						color[0]+=colors[i][0]*distances[i]/totaldistance;
						color[1]+=colors[i][1]*distances[i]/totaldistance;
						color[2]+=colors[i][2]*distances[i]/totaldistance;
					}
					screen = (l*camWidth+c)*3;
					fb[screen++]=color[0];
					fb[screen++]=color[1];
					fb[screen]=color[2];
				}
			}
			else
				T=0;
			c++;
		}
		l++;
	}
}

void cLightField::SetupCamera()
{
	lookAt = cVector(Eye.X,Eye.Y,0);
	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((camFOV*3.1415926535897932384626433832795 /180.0) / 2));
	vEye = cVector(Eye.X,Eye.Y,Eye.Z);
	NdotVE = Normal.DotProd(vEye);
	ST2scene = dataFocalLength/(desiredFocalLength + Eye.Z);//precomputed
}

void cLightField::SaveToPPM()
{
	char filename[256];
	sprintf(filename,"%d.ppm",frameNo++);
	ofstream file(filename,ios::binary);
	file << "P6 " << (int)camWidth << " " << (int)camHeight << " 255" << '\n';
	for (int x = 0; x < camWidth*camHeight*3; x++)
		file << (unsigned char)fb[x];
	file.close();
}
