Extract Intersections into a dedicated file

This commit is contained in:
Savanni D'Gerinel 2024-06-23 15:44:02 -04:00
parent b07925a2c3
commit af75bc20c8
4 changed files with 39 additions and 35 deletions

View File

@ -0,0 +1,35 @@
use std::cmp::Ordering;
use super::Sphere;
#[derive(Clone, Debug, PartialEq)]
pub struct Intersection<'a> {
pub t: f64,
pub object: &'a Sphere,
}
pub struct Intersections<'a>(Vec<Intersection<'a>>);
impl<'a> Intersections<'a> {
pub fn len(&'a self) -> usize {
self.0.len()
}
pub fn hit(&'a self) -> Option<&Intersection<'a>> {
self.0.iter().find(|i| i.t >= 0.)
}
}
impl<'a> std::ops::Index<usize> for Intersections<'a> {
type Output = Intersection<'a>;
fn index(&self, idx: usize) -> &Intersection<'a> {
&self.0[idx]
}
}
impl<'a> From<Vec<Intersection<'a>>> for Intersections<'a> {
fn from(mut v: Vec<Intersection<'a>>) -> Self {
v.sort_by(|l, r| l.t.partial_cmp(&r.t).unwrap_or(Ordering::Equal));
Self(v)
}
}

View File

@ -1,5 +1,6 @@
mod canvas;
mod color;
mod intersections;
mod matrix;
mod point;
mod ray;
@ -9,6 +10,7 @@ mod vector;
pub use canvas::Canvas;
pub use color::Color;
pub use intersections::{Intersections, Intersection};
pub use matrix::Matrix;
pub use point::Point;
pub use ray::Ray;

View File

@ -1,37 +1,4 @@
use crate::types::{Matrix, Point, Sphere, Vector};
use std::cmp::Ordering;
#[derive(Clone, Debug, PartialEq)]
pub struct Intersection<'a> {
t: f64,
object: &'a Sphere,
}
pub struct Intersections<'a>(Vec<Intersection<'a>>);
impl<'a> Intersections<'a> {
pub fn len(&'a self) -> usize {
self.0.len()
}
pub fn hit(&'a self) -> Option<&Intersection<'a>> {
self.0.iter().find(|i| i.t >= 0.)
}
}
impl<'a> std::ops::Index<usize> for Intersections<'a> {
type Output = Intersection<'a>;
fn index(&self, idx: usize) -> &Intersection<'a> {
&self.0[idx]
}
}
impl<'a> From<Vec<Intersection<'a>>> for Intersections<'a> {
fn from(mut v: Vec<Intersection<'a>>) -> Self {
v.sort_by(|l, r| l.t.partial_cmp(&r.t).unwrap_or(Ordering::Equal));
Self(v)
}
}
use super::{Intersection, Intersections, Matrix, Point, Sphere, Vector};
pub struct Ray {
origin: Point,
@ -72,7 +39,7 @@ impl Ray {
pub fn transform(&self, m: Matrix) -> Self {
Self {
origin: &m * self.origin,
direction: m * self.direction,
direction: m * self.direction,
}
}
}