
/*
 * pbrt source code Copyright(c) 1998-2004 Matt Pharr and Greg Humphreys
 *
 * All Rights Reserved.
 * For educational use only; commercial use expressly forbidden.
 * NO WARRANTY, express or implied, for this software.
 * (See file License.txt for complete license)
 */

// sphere.cpp*
#include "shape.h"
#include "mc.h"

// Added by Chia-Kai Liang
#include <iostream>
using std::cout;
using std::endl;
#define USE_SHPERE_GEO 0
#define USE_FAST_SQRT  1

// Add a fast sqrtf from Quake III code
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;
}

// Sphere Declarations
class Sphere: public Shape {
public:
	// Sphere Public Methods
	Sphere(const Transform &o2w, bool ro, float rad,
	       float zmin, float zmax, float phiMax);
	BBox ObjectBound() const;
	bool Intersect(const Ray &ray, float *tHit,
	               DifferentialGeometry *dg) const;
	bool IntersectP(const Ray &ray) const;
	float Area() const;
	Point Sphere::Sample(float u1, float u2, Normal *ns) const {
		Point p = Point(0,0,0) + radius *
			UniformSampleSphere(u1, u2);
		*ns = Normalize(ObjectToWorld(Normal(p.x, p.y, p.z)));
		if (reverseOrientation) *ns *= -1.f;
		return ObjectToWorld(p);
	}
	Point Sphere::Sample(const Point &p,
			float u1, float u2, Normal *ns) const {
		// Compute coordinate system for sphere sampling
		Point Pcenter = ObjectToWorld(Point(0,0,0));
		Vector wc = Normalize(Pcenter - p);
		Vector wcX, wcY;
		CoordinateSystem(wc, &wcX, &wcY);
		// Sample uniformly on sphere if \pt is inside it
		if (DistanceSquared(p, Pcenter) - radius*radius < 1e-4f)
			return Sample(u1, u2, ns);
		// Sample sphere uniformly inside subtended cone
#if(USE_FAST_SQRT)
		float cosThetaMax = fsqrtf(max(0.f, 1.f - radius*radius /
			DistanceSquared(p, Pcenter)));
#else
		float cosThetaMax = sqrtf(max(0.f, 1.f - radius*radius /
			DistanceSquared(p, Pcenter)));
#endif			
		DifferentialGeometry dgSphere;
		float thit;
		Point ps;
		Ray r(p,
		      UniformSampleCone(u1, u2, cosThetaMax, wcX, wcY, wc));
		if (!Intersect(r, &thit, &dgSphere)) {
			ps = Pcenter - radius * wc;
		} else {
			ps = r(thit);
		}
		*ns = Normal(Normalize(ps - Pcenter));
		if (reverseOrientation) *ns *= -1.f;
		return ps;
	}
	float Sphere::Pdf(const Point &p, const Vector &wi) const {
		Point Pcenter = ObjectToWorld(Point(0,0,0));
		// Return uniform weight if point inside sphere
		if (DistanceSquared(p, Pcenter) - radius*radius < 1e-4f)
			return Shape::Pdf(p, wi);
		// Compute general sphere weight
#if(USE_FAST_SQRT)
		float cosThetaMax = fsqrtf(max(0.f, 1.f - radius*radius /
			DistanceSquared(p, Pcenter)));
#else
		float cosThetaMax = sqrtf(max(0.f, 1.f - radius*radius /
			DistanceSquared(p, Pcenter)));
#endif
		return UniformConePdf(cosThetaMax);
	}
private:
	// Sphere Private Data
	float radius;
	// Begin added by Chia-Kai Liang
	float r2;
	// End added by Chia-Kai Liang
	float phiMax;
	float zmin, zmax;
	float thetaMin, thetaMax;
};
// Sphere Method Definitions
Sphere::Sphere(const Transform &o2w, bool ro, float rad,
               float z0, float z1, float pm)
	: Shape(o2w, ro) {
	radius = rad;
	// Begin added by Chia-Kai Liang
	r2   = radius*radius;
	// End added by Chia-Kai Liang
	zmin = Clamp(min(z0, z1), -radius, radius);
	zmax = Clamp(max(z0, z1), -radius, radius);
	thetaMin = acosf(Clamp(zmin/radius, -1.f, 1.f));
	thetaMax = acosf(Clamp(zmax/radius, -1.f, 1.f));
	phiMax = Radians(Clamp(pm, 0.0f, 360.0f));
}
BBox Sphere::ObjectBound() const {
	return BBox(Point(-radius, -radius, zmin),
		Point(radius,  radius, zmax));
}
#if (USE_SHPERE_GEO)
bool Sphere::Intersect(const Ray &r, float *tHit,
		DifferentialGeometry *dg) const {
	float phi;
	Point phit;
	
	// Transform _Ray_ to object space
	Ray ray;
	WorldToObject(r, &ray);
	// Compute the flag
	float o2 = ray.o.x*ray.o.x + ray.o.y*ray.o.y + ray.o.z*ray.o.z;
	//float r2 = radius*radius;
	float s2, t2, s;
	float d_norm2, d_norm;
	float invd_norm, invd_norm2;
	float t0, t1, thit;
	float tca = -(ray.o.x*ray.d.x + ray.o.y*ray.d.y + ray.o.z*ray.d.z);	
	if(o2 > r2){
		if(tca < 0)
			return false;
		d_norm2 = ray.d.x*ray.d.x + ray.d.y*ray.d.y + ray.d.z*ray.d.z;
		//d_norm = sqrtf(d_norm2);			
		invd_norm2 = 1.f/d_norm2;
#if(USE_FAST_SQRT)
		invd_norm = fsqrtf(invd_norm2);
#else
		invd_norm = sqrtf(invd_norm2);
#endif
		t2 = tca*tca*invd_norm2;
		s2 = r2 - o2 + t2;
		if(s2 < 0)
			return false;
#if(USE_FAST_SQRT)
		s = fsqrtf(s2)*invd_norm;
#else
		s = sqrtf(s2)*invd_norm;
#endif
		t0 = tca*invd_norm2 - s;
		if(t0 > ray.maxt)			
			return false;
		if(t0 < ray.mint){
			t1 = tca*invd_norm2 + s;
			if(t1 < ray.mint)
				return false;
			else
				thit = t1;			
		}
		else
			thit = t0;
	}
	else{//(o2 < r2)
		d_norm2 = ray.d.x*ray.d.x + ray.d.y*ray.d.y + ray.d.z*ray.d.z;
		//d_norm = sqrtf(d_norm2);
		invd_norm2 = 1.f/d_norm2;
#if(USE_FAST_SQRT)
		invd_norm = fsqrtf(invd_norm2);
#else
		invd_norm = sqrtf(invd_norm2);
#endif
		t2 = tca*tca*invd_norm2;
		s2 = r2 - o2 + t2;
#if(USE_FAST_SQRT)
		s = fsqrtf(s2)*invd_norm;
#else
		s = sqrtf(s2)*invd_norm;
#endif
		t1 = tca*invd_norm2 + s;
		if(t1 < ray.mint || t1 > ray.maxt)
			return false;
		thit = t1;
	}
	// Compute sphere hit position and $\phi$
	phit = ray(thit);
	phi = atan2f(phit.y, phit.x);
	if (phi < 0.) phi += 2.f*M_PI;
	// Test sphere intersection against clipping parameters
	if (phit.z < zmin || phit.z > zmax || phi > phiMax) {
		if (thit == t1) return false;
		if (t1 > ray.maxt) return false;
		thit = t1;
		// Compute sphere hit position and $\phi$
		phit = ray(thit);
		phi = atan2f(phit.y, phit.x);
		if (phi < 0.) phi += 2.f*M_PI;
		if (phit.z < zmin || phit.z > zmax || phi > phiMax)
			return false;
	}
	// Find parametric representation of sphere hit
	float u = phi / phiMax;
	float theta = acosf(phit.z / radius);
	float v = (theta - thetaMin) / (thetaMax - thetaMin);
	// Compute sphere \dpdu and \dpdv
#if(USE_FAST_SQRT)
	float zradius = fsqrtf(phit.x*phit.x + phit.y*phit.y);
#else
	float zradius = sqrtf(phit.x*phit.x + phit.y*phit.y);
#endif
	float invzradius = 1.f / zradius;
	float cosphi = phit.x * invzradius;
	float sinphi = phit.y * invzradius;
	Vector dpdu(-phiMax * phit.y, phiMax * phit.x, 0);
	Vector dpdv = (thetaMax-thetaMin) *
		Vector(phit.z * cosphi, phit.z * sinphi,
			-radius * sinf(theta));
	// Compute sphere \dndu and \dndv
	Vector d2Pduu = -phiMax * phiMax * Vector(phit.x,phit.y,0);
	Vector d2Pduv = (thetaMax - thetaMin) *
	                 phit.z * phiMax *
	                 Vector(-sinphi, cosphi, 0.);
	Vector d2Pdvv = -(thetaMax - thetaMin) *
	                 (thetaMax - thetaMin) *
	                 Vector(phit.x, phit.y, phit.z);
	// Compute coefficients for fundamental forms
	float E = Dot(dpdu, dpdu);
	float F = Dot(dpdu, dpdv);
	float G = Dot(dpdv, dpdv);
	Vector N = Normalize(Cross(dpdu, dpdv));
	float e = Dot(N, d2Pduu);
	float f = Dot(N, d2Pduv);
	float g = Dot(N, d2Pdvv);
	// Compute \dndu and \dndv from fundamental form coefficients
	float invEGF2 = 1.f / (E*G - F*F);
	Vector dndu = (f*F - e*G) * invEGF2 * dpdu +
		(e*F - f*E) * invEGF2 * dpdv;
	Vector dndv = (g*F - f*G) * invEGF2 * dpdu +
		(f*F - g*E) * invEGF2 * dpdv;
	// Initialize _DifferentialGeometry_ from parametric information
	*dg = DifferentialGeometry(ObjectToWorld(phit),
	                           ObjectToWorld(dpdu),
							   ObjectToWorld(dpdv),
	                           ObjectToWorld(dndu),
							   ObjectToWorld(dndv),
	                           u, v, this);
	// Update _tHit_ for quadric intersection
	*tHit = thit;
	return true;
}
bool Sphere::IntersectP(const Ray &r) const {
	float phi;
	Point phit;
	// Transform _Ray_ to object space
	Ray ray;
	WorldToObject(r, &ray);
	// Compute the flag
	float o2 = ray.o.x*ray.o.x + ray.o.y*ray.o.y + ray.o.z*ray.o.z;
	//float r2 = radius*radius;
	float s2, t2, s;	
	float d_norm2, d_norm;
	float invd_norm, invd_norm2;
	float t0, t1, thit;
	float tca = -(ray.o.x*ray.d.x + ray.o.y*ray.d.y + ray.o.z*ray.d.z);
	
	if(o2 > r2){
		if(tca < 0)
			return false;
		d_norm2 = ray.d.x*ray.d.x + ray.d.y*ray.d.y + ray.d.z*ray.d.z;
		//d_norm = sqrtf(d_norm2);
		invd_norm2 = 1.f/d_norm2;
#if(USE_FAST_SQRT)
		invd_norm = fsqrtf(invd_norm2);
#else
		invd_norm = sqrtf(invd_norm2);
#endif
		t2 = tca*tca*invd_norm2;
		s2 = r2 - o2 + t2;		
		if(s2 < 0)
			return false;
#if(USE_FAST_SQRT)
		s = fsqrtf(s2)*invd_norm;
#else
		s = sqrtf(s2)*invd_norm;
#endif
		t0 = tca*invd_norm2 - s;
		if(t0 > ray.maxt)			
			return false;
		if(t0 < ray.mint){
			t1 = tca*invd_norm2 + s;
			if(t1 < ray.mint)
				return false;
			else
				thit = t1;
		}
		else
			thit = t0;
	}
	else{//(o2 < r2)
		d_norm2 = ray.d.x*ray.d.x + ray.d.y*ray.d.y + ray.d.z*ray.d.z;
		//d_norm = sqrtf(d_norm2);
		invd_norm2 = 1.f/d_norm2;
#if(USE_FAST_SQRT)
		invd_norm = fsqrtf(invd_norm2);
#else
		invd_norm = sqrtf(invd_norm2);
#endif
		t2 = tca*tca*invd_norm2;
		s2 = r2 - o2 + t2;
#if(USE_FAST_SQRT)
		s = fsqrtf(s2)*invd_norm;
#else
		s = sqrtf(s2)*invd_norm;
#endif
		t1 = tca*invd_norm2 + s;
		if(t1 < ray.mint || t1 > ray.maxt)
			return false;
		thit = t1;
	}
	// Compute sphere hit position and $\phi$
	phit = ray(thit);
	phi = atan2f(phit.y, phit.x);
	if (phi < 0.) phi += 2.f*M_PI;
	// Test sphere intersection against clipping parameters
	if (phit.z < zmin || phit.z > zmax || phi > phiMax) {
		if (thit == t1)	return false;
		if (t1 > ray.maxt)	return false;
		thit = t1;
		// Compute sphere hit position and $\phi$
		phit = ray(thit);
		phi = atan2f(phit.y, phit.x);
		if (phi < 0.) phi += 2.f*M_PI;
		if (phit.z < zmin || phit.z > zmax || phi > phiMax)
			return false;
	}
	return true;
}
#else
bool Sphere::Intersect(const Ray &r, float *tHit,
		DifferentialGeometry *dg) const {
	float phi;
	Point phit;
	// Transform _Ray_ to object space
	Ray ray;
	WorldToObject(r, &ray);
	// Compute quadratic sphere coefficients
	float A = ray.d.x*ray.d.x + ray.d.y*ray.d.y +
	          ray.d.z*ray.d.z;
	float B = 2 * (ray.d.x*ray.o.x + ray.d.y*ray.o.y +
				   ray.d.z*ray.o.z);
	float C = ray.o.x*ray.o.x + ray.o.y*ray.o.y +
			  ray.o.z*ray.o.z - radius*radius;
	// Solve quadratic equation for _t_ values
	float t0, t1;
	if (!Quadratic(A, B, C, &t0, &t1))
		return false;
	// Compute intersection distance along ray
	if (t0 > ray.maxt || t1 < ray.mint)
		return false;
	float thit = t0;
	if (t0 < ray.mint) {
		thit = t1;
		if (thit > ray.maxt) return false;
	}
	// Compute sphere hit position and $\phi$
	phit = ray(thit);
	phi = atan2f(phit.y, phit.x);
	if (phi < 0.) phi += 2.f*M_PI;
	// Test sphere intersection against clipping parameters
	if (phit.z < zmin || phit.z > zmax || phi > phiMax) {
		if (thit == t1) return false;
		if (t1 > ray.maxt) return false;
		thit = t1;
		// Compute sphere hit position and $\phi$
		phit = ray(thit);
		phi = atan2f(phit.y, phit.x);
		if (phi < 0.) phi += 2.f*M_PI;
		if (phit.z < zmin || phit.z > zmax || phi > phiMax)
			return false;
	}
	// Find parametric representation of sphere hit
	float u = phi / phiMax;
	float theta = acosf(phit.z / radius);
	float v = (theta - thetaMin) / (thetaMax - thetaMin);
	// Compute sphere \dpdu and \dpdv
	float zradius = sqrtf(phit.x*phit.x + phit.y*phit.y);
	float invzradius = 1.f / zradius;
	float cosphi = phit.x * invzradius;
	float sinphi = phit.y * invzradius;
	Vector dpdu(-phiMax * phit.y, phiMax * phit.x, 0);
	Vector dpdv = (thetaMax-thetaMin) *
		Vector(phit.z * cosphi, phit.z * sinphi,
			-radius * sinf(theta));
	// Compute sphere \dndu and \dndv
	Vector d2Pduu = -phiMax * phiMax * Vector(phit.x,phit.y,0);
	Vector d2Pduv = (thetaMax - thetaMin) *
	                 phit.z * phiMax *
	                 Vector(-sinphi, cosphi, 0.);
	Vector d2Pdvv = -(thetaMax - thetaMin) *
	                 (thetaMax - thetaMin) *
	                 Vector(phit.x, phit.y, phit.z);
	// Compute coefficients for fundamental forms
	float E = Dot(dpdu, dpdu);
	float F = Dot(dpdu, dpdv);
	float G = Dot(dpdv, dpdv);
	Vector N = Normalize(Cross(dpdu, dpdv));
	float e = Dot(N, d2Pduu);
	float f = Dot(N, d2Pduv);
	float g = Dot(N, d2Pdvv);
	// Compute \dndu and \dndv from fundamental form coefficients
	float invEGF2 = 1.f / (E*G - F*F);
	Vector dndu = (f*F - e*G) * invEGF2 * dpdu +
		(e*F - f*E) * invEGF2 * dpdv;
	Vector dndv = (g*F - f*G) * invEGF2 * dpdu +
		(f*F - g*E) * invEGF2 * dpdv;
	// Initialize _DifferentialGeometry_ from parametric information
	*dg = DifferentialGeometry(ObjectToWorld(phit),
	                           ObjectToWorld(dpdu),
							   ObjectToWorld(dpdv),
	                           ObjectToWorld(dndu),
							   ObjectToWorld(dndv),
	                           u, v, this);
	// Update _tHit_ for quadric intersection
	*tHit = thit;
	return true;
}

bool Sphere::IntersectP(const Ray &r) const {
	float phi;
	Point phit;
	// Transform _Ray_ to object space
	Ray ray;
	WorldToObject(r, &ray);
	// Compute quadratic sphere coefficients
	float A = ray.d.x*ray.d.x + ray.d.y*ray.d.y +
	          ray.d.z*ray.d.z;
	float B = 2 * (ray.d.x*ray.o.x + ray.d.y*ray.o.y +
				   ray.d.z*ray.o.z);
	float C = ray.o.x*ray.o.x + ray.o.y*ray.o.y +
			  ray.o.z*ray.o.z - radius*radius;
	// Solve quadratic equation for _t_ values
	float t0, t1;
	if (!Quadratic(A, B, C, &t0, &t1))
		return false;
	// Compute intersection distance along ray
	if (t0 > ray.maxt || t1 < ray.mint)
		return false;
	float thit = t0;
	if (t0 < ray.mint) {
		thit = t1;
		if (thit > ray.maxt) return false;
	}
	// Compute sphere hit position and $\phi$
	phit = ray(thit);
	phi = atan2f(phit.y, phit.x);
	if (phi < 0.) phi += 2.f*M_PI;
	// Test sphere intersection against clipping parameters
	if (phit.z < zmin || phit.z > zmax || phi > phiMax) {
		if (thit == t1) return false;
		if (t1 > ray.maxt) return false;
		thit = t1;
		// Compute sphere hit position and $\phi$
		phit = ray(thit);
		phi = atan2f(phit.y, phit.x);
		if (phi < 0.) phi += 2.f*M_PI;
		if (phit.z < zmin || phit.z > zmax || phi > phiMax)
			return false;
	}
	return true;
}
#endif
float Sphere::Area() const {
	return phiMax * radius * (zmax-zmin);
}
extern "C" DLLEXPORT
	Shape *CreateShape(const Transform &o2w,
					   bool reverseOrientation,
					   const ParamSet &params) {
	float radius = params.FindOneFloat("radius", 1.f);
	float zmin = params.FindOneFloat("zmin", -radius);
	float zmax = params.FindOneFloat("zmax", radius);
	float phimax = params.FindOneFloat("phimax", 360.f);
	return new Sphere(o2w, reverseOrientation, radius,
		zmin, zmax, phimax);
}
