use crate::Point;
use crate::numeric::{CONTRACTION, FusedProduct, difference_of_products, fused, sum_of_products};
pub const INTERSECTION_EPSILON: f64 = 1.0e-30;
pub fn cross_product(a: Point, b: Point, p: Point) -> f64 {
difference_of_products(p.x - b.x, b.y - a.y, p.y - b.y, b.x - a.x)
}
pub fn calc_intersection(a: Point, b: Point, c: Point, d: Point) -> Option<Point> {
calc_intersection_fusing(FusedProduct::First, a, b, c, d)
}
pub fn calc_intersection_fusing(
numerator: FusedProduct,
a: Point,
b: Point,
c: Point,
d: Point,
) -> Option<Point> {
let num =
CONTRACTION.difference_of_products(numerator, a.y - c.y, d.x - c.x, a.x - c.x, d.y - c.y);
let den = difference_of_products(b.x - a.x, d.y - c.y, b.y - a.y, d.x - c.x);
if den.abs() < INTERSECTION_EPSILON {
return None;
}
let r = num / den;
Some(Point::new(
fused(r, b.x - a.x, a.x),
fused(r, b.y - a.y, a.y),
))
}
pub fn calc_distance(a: Point, b: Point) -> f64 {
let dx = b.x - a.x;
let dy = b.y - a.y;
sum_of_products(dx, dx, dy, dy).sqrt()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn intersection() {
let p = Point::new;
assert_eq!(
calc_intersection(p(0.0, 0.0), p(2.0, 2.0), p(0.0, 2.0), p(2.0, 0.0)),
Some(p(1.0, 1.0))
);
assert_eq!(
calc_intersection(p(0.0, 0.0), p(1.0, 0.0), p(0.0, 1.0), p(1.0, 1.0)),
None
);
}
#[test]
fn sides_and_distances() {
let p = Point::new;
assert!(cross_product(p(0.0, 0.0), p(1.0, 0.0), p(0.5, 1.0)) < 0.0);
assert!(cross_product(p(0.0, 0.0), p(1.0, 0.0), p(0.5, -1.0)) > 0.0);
assert_eq!(cross_product(p(0.0, 0.0), p(1.0, 0.0), p(3.0, 0.0)), 0.0);
assert_eq!(calc_distance(p(1.0, 1.0), p(4.0, 5.0)), 5.0);
}
}