#include "Sphere.h"

bool Sphere::intersected(Ray& ray) {
    double A = ray.GetDirection().sqNorm();
    double B = ray.GetDirection() % (ray.GetOrigin() - cnt) * 2;
    double C = (ray.GetOrigin() - cnt).sqNorm() - r*r;

    float disc = (B*B-4*A*C); 
    if(disc<0) return false;

    disc = sqrt(disc);
    double t1 = (-B-disc)/(2*A);
    double t2 = (-B+disc)/(2*A);

    assert(t2>=t1);

    if(t2<=0) return false;

    ray.Parameter() = (t1<=0)? t2 : t1;
    //    cout << "ray " << ray << " intersected with sphere " << (*this) << endl;
    return true;
}


ostream& operator<< (ostream& os, const Sphere& sphere) {
    os << "Sphere center at " << sphere.cnt << "\t with radius of " << sphere.r << endl;
    return os;
}

