Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/ray.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Generic rays

use core::convert::TryFrom;
use core::fmt;
use std::marker::PhantomData;

Expand All @@ -9,6 +10,7 @@ use cgmath::{Point2, Point3};
use cgmath::{Vector2, Vector3};

use crate::traits::{Continuous, ContinuousTransformed, Discrete, DiscreteTransformed};
use crate::Line;

/// A generic ray starting at `origin` and extending infinitely in
/// `direction`.
Expand Down Expand Up @@ -141,3 +143,33 @@ where
.map(|p| transform.transform_point(p))
}
}

impl<S, V, P> TryFrom<&Line<S, V, P>> for Ray<S, P, V>
where
S: BaseFloat,
V: InnerSpace + VectorSpace<Scalar = S>,
P: EuclideanSpace<Scalar = S, Diff = V> + cgmath::UlpsEq + cgmath::AbsDiffEq<Epsilon = S>,
{
type Error = ();

#[inline]
/// Converts an euclidean Line into an euclidean Ray. The created ray will inherit the origin
/// and direction of the line. This conversion will fail if the line describes a single point.
///```
/// use collision::{Line3,Ray};
/// use cgmath::Point3;
/// use std::convert::TryFrom;
/// let line: Line3<f32> = Line3::new(Point3::new(1f32, 2., 3.), Point3::new(5f32, 56., 6.));
/// assert!(Ray::try_from(&line).is_ok());
///```
fn try_from(l: &Line<S, V, P>) -> Result<Self, Self::Error> {
if l.dest
.ulps_eq(&l.origin, S::epsilon(), S::default_max_ulps())
{
// Can't build a ray from a single point
Err(())
} else {
Ok(Self::new(l.origin, (l.dest - l.origin).normalize()))
}
}
}
30 changes: 30 additions & 0 deletions tests/ray.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
use cgmath::assert_ulps_eq;
use cgmath::{InnerSpace, Point2, Point3};
use collision::{Line2, Line3, Ray, Ray2, Ray3};
use std::convert::TryFrom;

#[test]
fn test_ray_from_line_2d() {
let line = Line2::new(Point2::new(1f32, 2.), Point2::new(3f32, 4.));
assert!(Ray::try_from(&line).is_ok());
if let Ok(ray) = Ray2::try_from(&line) {
assert_ulps_eq!(ray.origin, &line.origin);
assert_ulps_eq!(ray.direction, (&line.dest - &line.origin).normalize());
}
// A single point should not create a Ray
let line = Line2::new(Point2::new(1., 2.), Point2::new(1., 2.));
assert!(!Ray::try_from(&line).is_ok());
}

#[test]
fn test_ray_from_line_3d() {
let line: Line3<f32> = Line3::new(Point3::new(1f32, 2., 3.), Point3::new(5f32, 56., 6.));
assert!(Ray::try_from(&line).is_ok());
if let Ok(ray) = Ray3::try_from(&line) {
assert_ulps_eq!(ray.origin, &line.origin);
assert_ulps_eq!(ray.direction, (&line.dest - &line.origin).normalize());
}
// A single point should not create a Ray
let line = Line2::new(Point2::new(1., 2.), Point2::new(1., 2.));
assert!(!Ray::try_from(&line).is_ok());
}