use crate::base::Vec2;
use crate::shape::Edge;
use crate::shape::Point;
pub use crate::traits::DType;
use crate::traits::TryBoundingBox;
use std::iter::FromIterator;
use std::slice::Iter;
use num_traits::Num;
use num_traits::{Float, NumCast};
use std::ops::Sub;
use super::Rect;
#[derive(Clone, PartialEq, Eq, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Path<T> {
pub points: PointList<T>,
pub width: T,
pub path_type: PathEndType<T>,
}
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum PathEndType<T> {
Flat,
Extended(T, T),
Round,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct PointList<T> {
pub points: Vec<Point<T>>,
}
impl<T> PointList<T> {
pub fn len(&self) -> usize {
self.points.len()
}
pub fn is_empty(&self) -> bool {
self.points.is_empty()
}
}
impl<T: Copy> PointList<T> {
pub fn new<I>(i: I) -> Self
where
I: Into<Self>,
{
i.into()
}
pub fn iter(&self) -> Iter<Point<T>> {
self.points.iter()
}
pub fn edges(&self) -> impl Iterator<Item = Edge<T>> + '_ {
self.iter()
.zip(self.iter().skip(1))
.map(|(a, b)| Edge::new(a, b))
}
pub fn edges_reversed(&self) -> impl Iterator<Item = Edge<T>> + '_ {
self.iter()
.rev()
.zip(self.iter().rev().skip(1))
.map(|(a, b)| Edge::new(a, b))
}
}
impl<T: Copy + Sub<Output = T> + NumCast> PointList<T> {
pub fn path_length<F: Float>(&self) -> F {
self.iter()
.zip(self.iter().skip(1))
.map(|(a, b)| a.distance(b))
.fold(F::zero(), |a, b| a + b)
}
}
impl<I, T, P> From<I> for PointList<T>
where
T: Copy,
I: IntoIterator<Item = P>,
Point<T>: From<P>,
{
fn from(iter: I) -> Self {
let points: Vec<Point<T>> = iter.into_iter().map(|x| x.into()).collect();
PointList { points }
}
}
impl<T, P> FromIterator<P> for PointList<T>
where
T: Copy,
P: Into<Point<T>>,
{
fn from_iter<I>(iter: I) -> Self
where
I: IntoIterator<Item = P>,
{
let points: Vec<Point<T>> = iter.into_iter().map(|x| x.into()).collect();
PointList { points }
}
}
impl<T: Copy + PartialOrd + Num> TryBoundingBox<T> for Path<T>
where
T: Copy + PartialOrd,
{
fn try_bounding_box(&self) -> Option<Rect<T>> {
let bbox = self.points.try_bounding_box();
let _1 = T::one();
let _2 = _1 + _1;
bbox.map(|bbox| {
let (p1, p2) = (bbox.lower_left(), bbox.upper_right());
let w_half = (self.width + _1) / _2;
let width = Vec2::new(w_half, w_half);
Rect::new(p1 - width, p2 + width)
})
}
}
impl<T> TryBoundingBox<T> for PointList<T>
where
T: Copy + PartialOrd,
{
fn try_bounding_box(&self) -> Option<Rect<T>> {
if self.points.is_empty() {
None
} else {
let mut x_min = self.points[0].x;
let mut x_max = x_min;
let mut y_min = self.points[0].y;
let mut y_max = y_min;
for p in self.iter().skip(1) {
let (x, y) = p.into();
if x < x_min {
x_min = x;
}
if x > x_max {
x_max = x;
}
if y < y_min {
y_min = y;
}
if y > y_max {
y_max = y;
}
}
Some(Rect::new((x_min, y_min), (x_max, y_max)))
}
}
}