1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
use super::{Point, PointLocation};
use crate::{Error, Orientation, PolygonScalar, TotalOrd};
use claims::debug_assert_ok;
use num_traits::*;
use rand::distributions::uniform::SampleUniform;
use rand::Rng;

// FIXME: Support n-dimensional triangles?
#[derive(Debug, Clone)]
pub struct Triangle<T>([Point<T, 2>; 3]);

impl<T> Triangle<T>
where
  T: PolygonScalar,
{
  pub fn new(pts: [Point<T, 2>; 3]) -> Result<Triangle<T>, Error> {
    let triangle = Triangle(pts);
    triangle.validate()?;
    Ok(triangle)
  }

  pub fn new_ccw(mut pts: [Point<T, 2>; 3]) -> Triangle<T> {
    match Point::orient(&pts[0], &pts[1], &pts[2]) {
      Orientation::CounterClockWise => Triangle(pts),
      Orientation::ClockWise => {
        pts.swap(0, 2);
        Triangle(pts)
      }
      Orientation::CoLinear => panic!("Cannot orient colinear points."),
    }
  }

  pub fn validate(&self) -> Result<(), Error> {
    self.view().validate()
  }

  // O(1)
  pub fn locate(&self, pt: &Point<T, 2>) -> PointLocation {
    self.view().locate(pt)
  }

  pub fn view(&'_ self) -> TriangleView<'_, T> {
    TriangleView([&self.0[0], &self.0[1], &self.0[2]])
  }
}

pub struct TriangleView<'a, T>([&'a Point<T, 2>; 3]);

impl<'a, T> TriangleView<'a, T>
where
  T: PolygonScalar,
{
  // O(1)
  pub fn new(pts: [&'a Point<T, 2>; 3]) -> Result<TriangleView<'a, T>, Error> {
    let triangle = TriangleView(pts);
    triangle.validate()?;
    Ok(triangle)
  }

  pub fn new_ccw(pts: [&'a Point<T, 2>; 3]) -> TriangleView<'a, T> {
    match Point::orient(pts[0], pts[1], pts[2]) {
      Orientation::CounterClockWise => TriangleView(pts),
      Orientation::ClockWise => TriangleView([pts[2], pts[1], pts[0]]),
      Orientation::CoLinear => panic!("Cannot orient colinear points."),
    }
  }

  pub fn new_unchecked(pts: [&'a Point<T, 2>; 3]) -> TriangleView<'a, T> {
    TriangleView(pts)
  }

  // O(1)
  pub fn validate(&self) -> Result<(), Error> {
    if self.orientation() != Orientation::CounterClockWise {
      Err(Error::ClockWiseViolation)
    } else {
      Ok(())
    }
  }

  pub fn orientation(&self) -> Orientation {
    let arr = &self.0;
    Point::orient(arr[0], arr[1], arr[2])
  }

  // O(1)
  pub fn locate(&self, pt: &Point<T, 2>) -> PointLocation {
    use Orientation::*;
    debug_assert_ok!(self.validate());
    let [a, b, c] = self.0;
    let ab = Point::orient(a, b, pt);
    let bc = Point::orient(b, c, pt);
    let ca = Point::orient(c, a, pt);
    if ab == ClockWise || bc == ClockWise || ca == ClockWise {
      PointLocation::Outside
    } else if ab == CoLinear || bc == CoLinear || ca == CoLinear {
      PointLocation::OnBoundary
    } else {
      PointLocation::Inside
    }
  }

  pub fn signed_area<F>(&self) -> F
  where
    T: PolygonScalar + Into<F>,
    F: NumOps<F, F> + FromPrimitive + Clone,
  {
    self.signed_area_2x::<F>() / F::from_usize(2).unwrap()
  }

  pub fn signed_area_2x<F>(&self) -> F
  where
    T: PolygonScalar + Into<F>,
    F: NumOps<F, F> + Clone,
  {
    let [a, b, c] = self.0;
    let ax = a.x_coord().clone().into();
    let ay = a.y_coord().clone().into();
    let bx = b.x_coord().clone().into();
    let by = b.y_coord().clone().into();
    let cx = c.x_coord().clone().into();
    let cy = c.y_coord().clone().into();
    ax.clone() * by.clone() - bx.clone() * ay.clone() + bx * cy.clone() - cx.clone() * by + cx * ay
      - ax * cy
    // x1*y2 - x2*y1 +
    // x2*y3 - x3*y2 +
    // x3*y1 - x1*y3
  }

  pub fn bounding_box(&self) -> (Point<T, 2>, Point<T, 2>) {
    let min_x = self.0[0]
      .x_coord()
      .total_min(self.0[1].x_coord())
      .total_min(self.0[2].x_coord())
      .clone();
    let max_x = self.0[0]
      .x_coord()
      .total_max(self.0[1].x_coord())
      .total_max(self.0[2].x_coord())
      .clone();
    let min_y = self.0[0]
      .y_coord()
      .total_min(self.0[1].y_coord())
      .total_min(self.0[2].y_coord())
      .clone();
    let max_y = self.0[0]
      .y_coord()
      .total_max(self.0[1].y_coord())
      .total_max(self.0[2].y_coord())
      .clone();
    (Point::new([min_x, min_y]), Point::new([max_x, max_y]))
  }

  pub fn rejection_sampling<R>(&self, rng: &mut R) -> Point<T, 2>
  where
    R: Rng + ?Sized,
    T: SampleUniform,
  {
    let (min, max) = self.bounding_box();
    loop {
      let [min_x, min_y] = min.array.clone();
      let [max_x, max_y] = max.array.clone();
      let x = rng.gen_range(min_x..=max_x);
      let y = rng.gen_range(min_y..=max_y);
      let pt = Point::new([x, y]);
      if self.locate(&pt) != PointLocation::Outside {
        return pt;
      }
    }
  }

  // sampleTriangle :: (RandomGen g, Random r, Fractional r, Ord r) => Triangle 2 p r -> Rand g (Point 2 r)
  // sampleTriangle (Triangle v1 v2 v3) = do
  //   a' <- getRandomR (0, 1)
  //   b' <- getRandomR (0, 1)
  //   let (a, b) = if a' + b' > 1 then (1 - a', 1 - b') else (a', b')
  //   return $ v1^.core .+^ a*^u .+^ b*^v
  //   where
  //     u = v2^.core .-. v1^.core
  //     v = v3^.core .-. v1^.core
}