added metals and dielectrics

This commit is contained in:
2023-02-02 09:41:11 +01:00
parent 72fb4ce3fd
commit 32cb8b4554
7 changed files with 145 additions and 42 deletions

View File

@@ -9,20 +9,22 @@ pub struct Sphere<'a> {
}
impl Sphere<'_> {
pub fn new<T: Material>(center: Point3, radius: f64, mat_ptr: &T) -> Self {
pub fn new<T: Material>(center: Point3, radius: f64, mat_ptr: &'static T) -> Self {
Sphere {center, radius, mat_ptr}
}
}
impl Hittable for Sphere<'_> {
fn hit(&mut self, r: &crate::ray::Ray, t_min: f64, t_max: f64, rec: &mut HitRecord) -> bool {
fn hit(&mut self, r: &crate::ray::Ray, t_min: f64, t_max: f64) -> Option<HitRecord> {
let oc = r.origin() - self.center;
let a = r.direction().length_squared();
let half_b = oc.dot(&r.direction());
let c = oc.length_squared() - self.radius*self.radius;
let c = oc.length_squared() - self.radius * self.radius;
let discriminant = half_b*half_b - a*c;
if discriminant < 0.0 { return false; }
let discriminant = half_b * half_b - a * c;
if discriminant < 0.0 {
return None;
}
let sqrtd = discriminant.sqrt();
// Find the nearest root that lies in the acceptable range
@@ -30,16 +32,26 @@ impl Hittable for Sphere<'_> {
if root < t_min || t_max < root {
root = (-half_b + sqrtd) / a;
if root < t_min || t_max < root {
return false;
return None;
}
}
rec.t = root;
rec.p = r.at(rec.t);
let outward_normal = (rec.p - self.center) / self.radius;
rec.set_face_normal(r, &outward_normal);
rec.mat_ptr = self.mat_ptr;
let p = r.at(root);
let outward_normal = (p - self.center) / self.radius;
let front_face = r.direction().dot(&outward_normal) < 0.0;
return true;
let outward_normal = if front_face {
outward_normal
} else {
outward_normal * -1.0
};
Some(HitRecord {
t: root,
p: p,
normal: outward_normal,
front_face,
mat_ptr: self.mat_ptr,
})
}
}