// realistic.cc
#include <fstream>
#include <cstring>
#include <iostream>
using namespace std;
#include "camera.h"
#include "paramset.h"
#include "film.h"

//#define DEBUG

// Declarations
struct LensBall{
	float oz;
	float radius, radius2, invRadius;
	float stop, stop2;
	float nRight, nLeft, nRatio, nRatio2;
	bool isStop;
	bool isNInward;
};
float finvsqrtf(float number) {
    long i;
    float x, y;
    const float f = 1.5F;
    x  = number * 0.5F;
    y  = number;
    i  = * ( long * ) &y;
    i  = 0x5f3759df - ( i >> 1 );
    y  = * ( float * ) &i;
    y  = y * ( f - ( x * y * y ) );
    y  = y * ( f - ( x * y * y ) );
    return y;
}

float fsqrtf(float number) {
    long i;
    float x, y;
    const float f = 1.5F;
    x  = number * 0.5F;
    y  = number;
    i  = * ( long * ) &y;
    i  = 0x5f3759df - ( i >> 1 );
    y  = * ( float * ) &i;
    y  = y * ( f - ( x * y * y ) );
    y  = y * ( f - ( x * y * y ) );
    return number * y;
}

class RealisticCamera : public Camera {
public:
  RealisticCamera(const Transform &world2cam,
		  float hither, float yon, float sopen,
		  float sclose, float filmdistance, float aperture_diameter, string specfile,
		  float filmdiag, Film *film);
  ~RealisticCamera();
  float GenerateRay(const Sample &sample, Ray *) const;
  
private:
	bool ParseCameraParameter(const string cameraFile);

	float focalDistance;
	float lensRadius;
	float totalLength;
	int lensNumber;
	LensBall *lensBall;
	Transform CameraToScreen, WorldToScreen, RasterToCamera;
	Transform ScreenToRaster, RasterToScreen;
};
RealisticCamera::RealisticCamera(const Transform &world2cam,
				 float hither, float yon, 
				 float sopen, float sclose, 
				 float filmdistance, float aperture_diameter, string specfile, 
				 float filmdiag, Film *f)
	: Camera(world2cam, hither, yon, sopen, sclose, f) 
{
	focalDistance = filmdistance;
	if(!ParseCameraParameter(specfile)){
		cerr << "Parse camera parameter file " << specfile << " failed" << endl;
		exit(1);
	}
	// Use filmdiag to calculate the sensor plane (in the real size)
	float diag = sqrtf(float(film->xResolution*film->xResolution + film->yResolution*film->yResolution));
	float rx = film->xResolution/(2*diag);
	float ry = film->yResolution/(2*diag);
	float Screen[4];
	Screen[0] = float(-filmdiag*rx);
	Screen[1] = -Screen[0];
	Screen[2] = float(-filmdiag*ry);
	Screen[3] = -Screen[2];
	// Calculate the transformation matrices
	hither = 0;
	CameraToScreen = Scale(1.f, 1.f, 1.f / (yon-hither)) * 
					Translate(Vector(0.f, 0.f, totalLength));
	WorldToScreen = CameraToScreen*WorldToCamera;
	ScreenToRaster = Scale(float(film->xResolution), float(film->yResolution), 1.f) *
					Scale(1.f / (Screen[1] - Screen[0]), 1.f / (Screen[2] - Screen[3]), 1.f) *
					Translate(Vector(-Screen[0], -Screen[3], 0.f));
	RasterToScreen = Scale(-1.f, -1.f, 1.f)*ScreenToRaster.GetInverse();
	RasterToCamera = CameraToScreen.GetInverse() * RasterToScreen;
}

float RealisticCamera::GenerateRay(const Sample &sample, Ray *ray) const {	
	float lensU, lensV, c22, r2;
	Point Pras(sample.imageX, sample.imageY, 0.f);
	Point Pcamera;
	Vector D0; 
	RasterToCamera(Pras, &Pcamera);
	// Sample point on the final lens surface
	ConcentricSampleDisk(sample.lensU, sample.lensV, &lensU, &lensV);
	lensU *= lensRadius;
	lensV *= lensRadius;
	D0.x = lensU - Pcamera.x;
	D0.y = lensV - Pcamera.y;
	D0.z = focalDistance - Pcamera.z;
	D0 = Normalize(D0);
	// Set ray time value
	if(ShutterOpen != ShutterClose) ray->time = Lerp(sample.time, ShutterOpen, ShutterClose);
	else ray->time = 0;

get_new_sample:
	ray->o = Pcamera;
	ray->d = D0;
	// Calaulate cos^4(theta) weighting term
	float weighting = ray->d.z*ray->d.z;;
	weighting = weighting*weighting;
	// Trace the ray through the lens system
	float B, C, D, t0;
	float c1, c2;
	Point P;
	Vector dst, N, T, I;
	for(int i = 0; i < lensNumber; i++){
		LensBall *lens = &lensBall[i];
		if(lens->isStop){
			// Calculate the intersection
			float t = (lens->oz - ray->o.z)/ray->d.z;
			float x = ray->o.x + t*ray->d.x;
			float y = ray->o.y + t*ray->d.y;
			// Check if the ray is inside the stop
			r2 = x*x + y*y;
			if(r2 > lens->stop2) goto leave_sampling;
		}
		else{
			// Calculate the intersection
			dst.x = ray->o.x;
			dst.y = ray->o.y;
			dst.z = ray->o.z - lens->oz;
			B = dst.x*ray->d.x + dst.y*ray->d.y + dst.z*ray->d.z;
			C = dst.x*dst.x + dst.y*dst.y + dst.z*dst.z - lens->radius2;
			D = B*B - C;
			if(D < 0.f) goto leave_sampling;
			// Calculate the normal at the intersection
			if(lens->isNInward){
				t0 = -B - fsqrtf(D);
				P = ray->o + t0*ray->d;
				if(P.x*P.x + P.y*P.y > lens->stop2)
					goto leave_sampling;
				N.x = P.x*lens->invRadius;
				N.y = P.y*lens->invRadius;
				N.z = (P.z-lens->oz)*lens->invRadius;
			}
			else{
				t0 = -B + fsqrtf(D);
				P = ray->o + t0*ray->d;
				if(P.x*P.x + P.y*P.y > lens->stop2)
					goto leave_sampling;
				N.x = -P.x*lens->invRadius;
				N.y = -P.y*lens->invRadius;
				N.z = -(P.z-lens->oz)*lens->invRadius;
			}
			// Calculate the refracted ray
			I = ray->d;
			c1 = -(N.x*I.x + N.y*I.y + N.z*I.z);
			c22 = 1 - lens->nRatio2*(1 - c1*c1);
			if(c22 < 0.f) goto leave_sampling;
			c2 = sqrtf(c22);
			Vector T = lens->nRatio*I + (lens->nRatio * c1 - c2)*N;
			// Update the ray origin and direction
			ray->d = T;
			ray->o = P;
			// Update the weighting if necessary
		}
	}
	// Post processing the ray
	ray->mint = ClipHither;
	ray->maxt = (ClipYon - ClipHither) / ray->d.z;
	CameraToWorld(*ray, ray);
	return weighting;
leave_sampling:
	return 0.f;
}

bool RealisticCamera::ParseCameraParameter(const string cameraFile){
	char *line = new char[256];
	const char *cameraFilename = cameraFile.c_str();
	ifstream fin;
	fin.open(cameraFilename, ios::in);
	if(!fin) return false;
	// Read the parameters as front to rear order
	vector<float> radiusV;
	vector<float> axposV;
	vector<float> NV;
	vector<float> apertureV;
	lensNumber = 0;
	totalLength = focalDistance;
	float rad, axpos, N, aperture;
	fin.getline(line, 256);
	while(!fin.eof()){
		if(!(line[0] == '#')){
			char *token;
			token = strtok(line, "\t");			
			rad = float(atof(token));
			token = strtok(NULL, "\t");
			axpos = float(atof(token));
			token = strtok(NULL, "\t");
			N = float(atof(token));
			if(N == 0.f)
				N = 1.f;
			token = strtok(NULL, "\t");
			aperture = float(atof(token));
			radiusV.push_back(rad);
			axposV.push_back(axpos);
			NV.push_back(N);
			apertureV.push_back(aperture);
			lensNumber++;
			totalLength += axpos;
		}
		fin.getline(line, 256);
	}
	fin.close();
	delete []line;
	// Calculte the meaningful parameters
	axposV[lensNumber-1] = focalDistance;
	lensBall = new LensBall[lensNumber];
	float t_total = -totalLength;
	int j = 0;
	for(int i = lensNumber-1; i>=0; i--){		
		t_total += axposV[i];
		// The origin.z of the lensBall
		lensBall[j].oz = t_total - radiusV[i];
		// The radius
		lensBall[j].radius = fabs(radiusV[i]);
		lensBall[j].radius2 = lensBall[j].radius*lensBall[j].radius;
		lensBall[j].invRadius = 1.f/lensBall[j].radius;
		if(radiusV[i] < 0)
			lensBall[j].isNInward = true;
		else 
			lensBall[j].isNInward = false;
		// The half aperture (stop)
		lensBall[j].stop = apertureV[i]/2.f;
		lensBall[j].stop2 = lensBall[j].stop*lensBall[j].stop;
		// N
		lensBall[j].nRight = NV[i];
		if(i == 0) lensBall[j].nLeft = 1.f;
		else lensBall[j].nLeft = NV[i-1];
		lensBall[j].nRatio = lensBall[j].nRight/lensBall[j].nLeft;
		lensBall[j].nRatio2 = lensBall[j].nRatio*lensBall[j].nRatio;

		if(lensBall[j].radius == 0.f)
			lensBall[j].isStop = true;
		else
			lensBall[j].isStop = false;
		j++;
	}
	lensRadius = this->lensBall[this->lensNumber-1].stop;
	return true;
}
RealisticCamera::~RealisticCamera(){
	if(lensNumber != 0)
		delete []lensBall;
}
extern "C" DLLEXPORT Camera *CreateCamera(const ParamSet &params,
		const Transform &world2cam, Film *film) {
	// Extract common camera parameters from \use{ParamSet}
	float hither = max(1e-7f, params.FindOneFloat("hither", 1e-8f));
	float yon = min(params.FindOneFloat("yon", 1e30f), 1e30f);
	float shutteropen = params.FindOneFloat("shutteropen", -1);
	float shutterclose = params.FindOneFloat("shutterclose", -1);

	// Realistic camera-specific parameters
	string specfile = params.FindOneString("specfile", "");
	float filmdistance = params.FindOneFloat("filmdistance", 70.0); // about 70 mm default to film
 	float fstop = params.FindOneFloat("aperture_diameter", 1.0);
	float filmdiag = params.FindOneFloat("filmdiag", 35.0);

	Assert(hither != -1 && yon != -1 && shutteropen != -1 &&
		shutterclose != -1 && filmdistance!= -1);
	if (specfile == "") {
	    Severe( "No lens spec file supplied!\n" );
	}
	return new RealisticCamera(world2cam, hither, yon,
				   shutteropen, shutterclose, filmdistance, fstop, 
				   specfile, filmdiag, film);
}
