-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsphere.cpp
43 lines (40 loc) · 1.26 KB
/
sphere.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include "sphere.h"
#include "ray.h"
#include "cmath"
#include "utils.h"
#include <QDebug>
Sphere::Sphere(QVector3D center, qreal rad):
center_(center),
rad_(rad)
{
}
Geometry::RayQueryResults Sphere::getIntersectionInfo(Ray &ray) const
{
Geometry::RayQueryResults results;
//A=1, so no need to calculate
qreal B = 2*(ray.getDirection().x() * (ray.getStartPoint().x() - center_.x()) + ray.getDirection().y() * (ray.getStartPoint().y() - center_.y()) + ray.getDirection().z() * (ray.getStartPoint().z() - center_.z()));
qreal C = pow(ray.getStartPoint().x() - center_.x(),2) + pow(ray.getStartPoint().y() - center_.y(),2) + pow(ray.getStartPoint().z() - center_.z(),2) - pow(rad_,2);
qreal disc = pow(B,2) - 4*C;
if(disc>0)
{
results.hit = true;
qreal t1 = (-B - sqrt(disc))/2;
qreal t2 = (-B + sqrt(disc))/2;
results.distance = utils::min(t1,t2);
if(results.distance<0)
{
results.distance = utils::max(t1,t2);
if(results.distance<0)
{
results.hit = false;
}
}
}
return results;
}
QVector3D Sphere::getNormal(QVector3D &point) const
{
QVector3D normal = point-center_;
normal.normalize();
return normal;
}