geo_offset/
edge.rs

1use geo_types::CoordFloat;
2
3type Point<F> = geo_types::Coord<F>;
4
5/// This enumeration contains error cases for edges manipulation.
6#[derive(Debug, Copy, Clone, PartialEq)]
7pub enum EdgeError {
8    /// This error can be produced if normals of an edge of null length are computed.
9    VerticesOverlap,
10}
11
12#[derive(Debug, Copy, Clone, PartialEq)]
13pub struct Edge<F: CoordFloat> {
14    pub current: Point<F>,
15    pub next: Point<F>,
16}
17
18impl<F: CoordFloat> Edge<F> {
19    pub fn new(current: &Point<F>, next: &Point<F>) -> Self {
20        Self {
21            current: *current,
22            next: *next,
23        }
24    }
25
26    pub fn new_with_offset(current: &Point<F>, next: &Point<F>, dx: F, dy: F) -> Self {
27        Self {
28            current: (current.x + dx, current.y + dy).into(),
29            next: (next.x + dx, next.y + dy).into(),
30        }
31    }
32
33    pub fn inwards_normal(&self) -> Result<Point<F>, EdgeError> {
34        let dx = self.next.x - self.current.x;
35        let dy = self.next.y - self.current.y;
36        let edge_length = (dx * dx + dy * dy).sqrt();
37        let x = -dy / edge_length;
38        let y = dx / edge_length;
39
40        if x.is_finite() && y.is_finite() {
41            Ok((x, y).into())
42        } else {
43            Err(EdgeError::VerticesOverlap)
44        }
45    }
46
47    pub fn outwards_normal(&self) -> Result<Point<F>, EdgeError> {
48        let inwards = self.inwards_normal()?;
49        Ok((-inwards.x, -inwards.y).into())
50    }
51
52    pub fn with_offset(&self, dx: F, dy: F) -> Self {
53        Self::new_with_offset(&self.current, &self.next, dx, dy)
54    }
55
56    pub fn inverse_with_offset(&self, dx: F, dy: F) -> Self {
57        Self::new_with_offset(&self.next, &self.current, dx, dy)
58    }
59
60    pub fn inverse(&self) -> Self {
61        Self::new(&self.next, &self.current)
62    }
63}