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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
use std;
use Traceable;

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

use hit::Hit;
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,
        }
    }
}

impl Traceable for Sphere {
    fn intersect(&self, ray: &Ray, result: &mut Hit) -> bool {
        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 {
            return false;
        } else {
            let det = det_sqrd.sqrt();

            if b - det > 0.0 {
                result.t = b - det;
                result.p = ray.origin + ray.direction * result.t;
                result.n = (self.position - result.p).normalize();
                result.n = if Float3::dot(result.n, ray.direction) < 0.0 {
                    result.n
                } else {
                    result.n * -1.0
                };
                result.material = self.material;

                return true;
            } else if b + det > 0.0 {
                result.t = b + det;
                result.p = ray.origin + ray.direction * result.t;
                result.n = (self.position - result.p).normalize();
                result.n = if Float3::dot(result.n, ray.direction) < 0.0 {
                    result.n
                } else {
                    result.n * -1.0
                };
                result.material = self.material;

                return true;
            }

            return false;
        }
    }
}