#ifndef SPHERE_H
#define SPHERE_H
#include"hittable.h"
#include"vec3.h"
#include"material.h"
class sphere :public hittable {
public:
sphere() { }
sphere(point3 cen, double r, shared_ptr<material> m) :center(cen), radius(r), mat_ptr(m) { }
virtual bool hit(const ray& r, double t_min, double t_max, hit_record& rec) const override;
public:
point3 center;
double radius;
shared_ptr<material> mat_ptr;
};
// 判斷光纖是否與某個球相交
// 根據推導求得 最終公式為 一元二次函數 A為光纖原點, C為球的原點
// t^2 * dot(b, b) + 2t* dot(b, (A-C)) + dot((A-C), (A-C)) - r^2 = 0
// 求b^2 - 4ac > 0
// 無解返回-1.0, 有解返回解,優先返回小的解
// 令b = 2 * h ,即可进一步化简求根公式。
bool sphere::hit(const ray& r, double t_min, double t_max, hit_record& rec) const {
vec3 oc = r.origin() - center;
double a = dot(r.direction(), r.direction()); // dot(b, b)
double half_b = dot(r.direction(), oc);
double c = dot(oc, oc) - radius * radius;
double discriminant = half_b * half_b - a * c;
if (discriminant > 0) {
double root = sqrt(discriminant);
double t = (-half_b - root) / a;
if (t > t_min && t < t_max) {
rec.t = t;
rec.p = r.at(t);
vec3 outward_normal = (rec.p - center) / radius;
rec.set_face_normal(r, outward_normal);
rec.mat_ptr = mat_ptr;
return true;
}
t = (-half_b + root) / a;
if (t > t_min && t < t_max) {
rec.t = t;
rec.p = r.at(t);
vec3 outward_normal = (rec.p - center) / radius;
rec.set_face_normal(r, outward_normal);
rec.mat_ptr = mat_ptr;
return true;
}
}
return false;
}
#endif // !SPHERE_H
13行的hit函数报使用“override”声明的成员函数不能重写基类成员
26行的hit函数报 已声明 所在行数:26,所属文件:"D:\ONEWEEKPROJECT\ONEWEEKPROJECT\RAYTRACING\RAYTRACING\sphere.h") 不兼容
问题是基类有没有这个hit函数啊?没有的话不能加override
hittable代码发出来
#ifndef HITTABLE_H
#define HITTABLE_H
#include"ray.h"
struct hit_record
{
point3 p; // 交點
vec3 normal; // 法線向量
double t; // 距離
bool front_face;
inline void set_face_normal(const ray& r, const vec3& outward_normal) {
front_face = dot(r.direction(), outward_normal) < 0;
normal = front_face ? outward_normal : -outward_normal;
}
};
class hittable
{
public:
virtual bool hit(const ray& r, double t_min, double t_max, hit_record& rec) const = 0;
};
#endif // !HITTABLE_H