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
use std;

use cgmath::prelude::*;
extern crate cgmath;
type Float3 = cgmath::Vector3<f64>;

use material::Material;
use ray::Ray;

#[derive(Copy, Clone)]
pub struct Sphere {
    pub radius: f64,
    pub position: Float3,
    pub material: Material,
}

impl Sphere {
    // Spawn a new sphere
    pub fn new(radius: f64, position: Float3, material: Material) -> Sphere {
        Sphere {
            radius: radius,
            position: position,
            material: material,
        }
    }

    // Ray-Sphere Intersection
    pub fn intersect(self, ray: Ray) -> f64 {
        let op: Float3 = self.position - ray.origin;
        let b: f64 = op.dot(ray.direction);
        let det_sqrd: f64 = b * b - op.dot(op) + self.radius * self.radius;

        if det_sqrd > 0.0 {
            let det = det_sqrd.sqrt();
            if b - det > 0.0 {
                b - det
            } else if b + det > 0.0 {
                b + det
            } else {
                std::f64::INFINITY
            }
        } else {
            std::f64::INFINITY
        }
    }
}