-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSphere.cpp
34 lines (30 loc) · 1.12 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
//
// Created by debowin on 10/10/17.
//
#include "Sphere.h"
#include <cmath>
Sphere::Sphere(const Vector3D ¢er, float r, Material m) : center(center), r(r), Surface(m) {}
const Vector3D &Sphere::getPosition() const {
return center;
}
float Sphere::getR() const {
return r;
}
HitInfo *Sphere::intersect(Ray ray, float tMin, float tMax) {
double discriminant = pow(ray.getDirection()*(ray.getOrigin()-getPosition()), 2)
- (ray.getOrigin()-getPosition()) * (ray.getOrigin()-getPosition()) + getR() * getR();
if(discriminant < 0)
return nullptr;
float t1 = -ray.getDirection() * (ray.getOrigin()-getPosition()) + std::sqrt((float)discriminant);
float t2 = -ray.getDirection() * (ray.getOrigin()-getPosition()) - std::sqrt((float)discriminant);
if(t1 > t2)
std::swap(t1, t2);
if(t1<tMin || t1 > tMax){
t1 = t2;
if(t1<tMin || t1 > tMax)
return nullptr;
}
Vector3D p = ray.getOrigin() + ray.getDirection()*t1;
Vector3D normal = p-center;
return new HitInfo(material, t1, normalize(normal), p, normalize(ray.getDirection()));
}