common/
hittable_list.rs

1use crate::ray::Ray;
2use crate::hittable::{HitRecord, Hittable};
3
4/// A collection of `Hittable` objects tested together.
5pub struct HittableList {
6    /// The list of hittable objects.
7    pub objects: Vec<Box<dyn Hittable>>,
8}
9
10impl HittableList {
11    /// Creates an empty `HittableList`.
12    pub fn new() -> Self {
13        HittableList { objects: Vec::new() }
14    }
15
16    /// Appends `object` to the list.
17    pub fn add(&mut self, object: Box<dyn Hittable>) {
18        self.objects.push(object);
19    }
20}
21
22impl Hittable for HittableList {
23    fn hit(&self, r: &Ray, t_min: f64, t_max: f64) -> Option<HitRecord> {
24        let mut closest_so_far = t_max;
25        let mut result = None;
26        for object in &self.objects {
27            if let Some(rec) = object.hit(r, t_min, closest_so_far) {
28                closest_so_far = rec.t;
29                result = Some(rec);
30            }
31        }
32        result
33    }
34}