-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsphere.h
More file actions
64 lines (54 loc) · 2.17 KB
/
sphere.h
File metadata and controls
64 lines (54 loc) · 2.17 KB
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//
// Created by 13240 on 2025/10/14.
//
#ifndef SIMPLE_SOFTRT_SPHERE_H
#define SIMPLE_SOFTRT_SPHERE_H
#include "hittable.h"
class sphere : public hittable {
public:
// Moving Sphere
sphere(const point3 ¢er1, const point3 ¢er2, double radius,
std::shared_ptr<material> mat)
: center(center1, center2 - center1, 0), radius(std::fmax(radius, 0)), mat(mat){
auto rvec = vec3(radius, radius, radius);
aabb box1 = aabb(center.at(0) - rvec, center.at(0) + rvec);
aabb box2 = aabb(center.at(1) - rvec, center.at(1) + rvec);
bbox = aabb(box1, box2);
}
// Stationary Sphere
sphere(const point3 &static_center, double radius, std::shared_ptr<material> mat)
: center(static_center, vec3(0,0,0)), radius(std::fmax(0, radius)), mat(mat) {
auto rvec = vec3(radius, radius, radius);
bbox = aabb(static_center - rvec, static_center + rvec);
}
bool hit(const ray &r, interval ray_t, hit_record &rec) const override {
point3 current_center = center.at(r.time());
vec3 oc = current_center - r.origin();
auto a = r.direction().length_squared(); // 光线和球体的解析解
auto h = dot(r.direction(), oc);
auto c = oc.length_squared() - radius * radius;
auto discriminant = h * h - a * c;
if (discriminant < 0)
return false;
auto sqrtd = std::sqrt(discriminant);
auto root = (h - sqrtd) / a; // 尝试 第一个解(前表面交点)
if (!ray_t.surrounds(root)) { // t 可能是负的,需要规定 t 的范围
root = (h + sqrtd) / a; // 尝试第二个解
if (!ray_t.surrounds(root))
return false;
}
rec.t = root;
rec.p = r.at(rec.t);
vec3 outward_normal = (rec.p - current_center) / radius;
rec.set_face_normal(r, outward_normal);
rec.mat = mat;
return true;
}
aabb bounding_box() const override { return bbox; }
private:
ray center; // 为了支持motion blur,位置是一个class ray
double radius;
std::shared_ptr<material> mat;
aabb bbox;
};
#endif //SIMPLE_SOFTRT_SPHERE_H