rsrt_cpu/src/sphere.rs

39 lines
1.2 KiB
Rust

extern crate vec3;
use super::object::Object;
use super::ray::Ray;
pub struct Sphere {}
fn return_min(root1: f64, root2: f64) -> Option<f64> {
if root1 < root2 && root1 > 0. {
Some(root1)
} else if root2 < root1 && root2 > 0. {
Some(root2)
} else {
None
}
}
impl Object for Sphere {
fn get_intersection(&self, ray: Ray) -> Option<f64> {
let a = ray.direction[0].powi(2) + ray.direction[1].powi(2) + ray.direction[2].powi(2);
let b = (2. * ray.origin[0] * ray.direction[0])
+ (2. * ray.origin[1] * ray.direction[1])
+ (2. * ray.origin[2] * ray.direction[2]);
let c = ray.origin[0].powi(2) + ray.origin[1].powi(2) + ray.origin[2].powi(2) - 1.;
let delta = b * b - 4. * a * c;
if delta > 0. {
let root1 = ((-1. * b - delta.sqrt()) / (a + a)) - 0.00001;
let root2 = ((-1. * b + delta.sqrt()) / (a + a)) - 0.00001;
return_min(root1, root2)
} else {
None
}
}
fn get_normal(&self, n: [f64; 3]) -> [f64; 3] {
let scalar = (n[0].powi(2) + n[1].powi(2) + n[2].powi(2)).sqrt();
[n[0] / scalar, n[1] / scalar, n[2] / scalar]
}
}