latest changes
This commit is contained in:
42
src/sphere.rs
Normal file
42
src/sphere.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
use crate::hittable::*;
|
||||
use crate::vec3::*;
|
||||
|
||||
struct Sphere {
|
||||
center: Point3,
|
||||
radius: f64
|
||||
}
|
||||
|
||||
impl Sphere {
|
||||
pub fn new(center: Point3, radius: f64) -> Self {
|
||||
Sphere {center, radius}
|
||||
}
|
||||
}
|
||||
|
||||
impl Hittable for Sphere {
|
||||
fn hit(&self, r: &crate::ray::Ray, t_min: f64, t_max: f64, rec: &mut HitRecord) -> bool {
|
||||
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 discriminant = half_b*half_b - a*c;
|
||||
if discriminant < 0.0 { return false; }
|
||||
let sqrtd = discriminant.sqrt();
|
||||
|
||||
// Find the nearest root that lies in the acceptable range
|
||||
let mut root = (-half_b - sqrtd) / a;
|
||||
if root < t_min || t_max < root {
|
||||
root = (-half_b + sqrtd) / a;
|
||||
if root < t_min || t_max < root {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user