//////////// // // sphere.hpp // // basic sphere object // #ifndef _SPHERE_ #define _SPHERE_ #include "object.hpp" class sphere : public object { public: Vec3f cent; // center of sphere float rad; // sphere radius sphere() {} void set(Vec3f c, float r, Vec3f a, Vec3f d, Vec3f s, Vec3f t, float m) { cent = c; rad = r; Ia = a; kd = d; ks = s; kt = t; M = m; } sphere(Vec3f c, float r, Vec3f a, Vec3f d, Vec3f s, Vec3f t, float m) { set(c,r,a,d,s,t,m); } int getIntersect(Vec3f &start, Vec3f &dir, float *time) { // equation is t = -B +- sqrt(B^2-4C) / 2 Vec3f temp; // float B = 2 * ( dir * ( start - cent ) ); // float C = (start - cent).LengthSqr() - (rad*rad); temp = start; // faster? temp -= cent; float B = 2 * ( dir * temp ); float C = temp.LengthSqr() - (rad*rad); float inner = B*B - 4*C; // inside the sqrt if (inner < 0.0) return(0); *time = ( -B - (float)sqrt(inner) ) / 2.0; //first try with - if (*time > 0.01) //avoid accidents return (1); else *time = ( -B + (float)sqrt(inner) ) / 2.0; //next try with + if (*time > 0.01) return (1); else return (0); } Vec3f getNormal(Vec3f hitPt) { Vec3f norm; norm = hitPt; norm -= cent; norm.Normalize(); return norm; } }; #endif