Rewrite hittable list hit method using iter magic

The loop can go away completely and be replaced with an iterator. Yay
for Rust iterators!
This commit is contained in:
2023-09-23 13:26:42 -07:00
parent 4be7ba54bb
commit 7c43c3fb82

View File

@@ -30,19 +30,15 @@ impl Hittable {
pub fn hit(&self, r: Ray, t_min: f32, t_max: f32) -> Option<HitRecord> { pub fn hit(&self, r: Ray, t_min: f32, t_max: f32) -> Option<HitRecord> {
match self { match self {
Hittable::HittableList { hittables } => { Hittable::HittableList { hittables } => {
let mut might_return: Option<HitRecord> = None; hittables.iter()
let mut hit_anything = false; .map( |obj| -> Option<HitRecord> {
let mut nearest_t = t_max; obj.hit(r, t_min, t_max)
for item in hittables { }).filter(|obj| obj.is_some())
if let Some(record) = item.hit(r, t_min, nearest_t){ .min_by(|lhs, rhs| {
hit_anything = true; let lhs = lhs.as_ref().unwrap();
nearest_t = record.t; let rhs = rhs.as_ref().unwrap();
might_return = Some(record); lhs.t.partial_cmp(&rhs.t).expect("Couldn't compare??")
} }).unwrap_or(None)
}
if hit_anything{
return might_return;
} else { return None; }
} }
Hittable::Sphere { center, radius, material } => { Hittable::Sphere { center, radius, material } => {