axiolid_reference/
polygon.rs1use axiolid_contracts::{GeomError, GeomResult, Sign};
7use axiolid_core::{Point2, Scalar};
8
9use crate::orient2d;
10
11pub fn signed_area2(ring: &[Point2]) -> Scalar {
13 let mut acc = 0.0;
14 for i in 0..ring.len() {
15 let a = ring[i];
16 let b = ring[(i + 1) % ring.len()];
17 acc += a.x * b.y - b.x * a.y;
18 }
19 acc
20}
21
22pub fn ring_orientation(ring: &[Point2]) -> Option<Sign> {
24 if ring.len() < 3 {
25 return None;
26 }
27 match signed_area2(ring) {
28 a if a > 0.0 => Some(Sign::Positive),
29 a if a < 0.0 => Some(Sign::Negative),
30 _ => None,
31 }
32}
33
34fn sign_of(a: Point2, b: Point2, c: Point2) -> Sign {
39 orient2d(a, b, c)
40 .sign()
41 .expect("orient2d escalates to exact arithmetic and always certifies")
42}
43
44fn blocks_ear(a: Point2, b: Point2, c: Point2, p: Point2) -> bool {
51 let s1 = sign_of(a, b, p);
52 let s2 = sign_of(b, c, p);
53 let s3 = sign_of(c, a, p);
54 s1 != Sign::Negative && s2 != Sign::Negative && s3 != Sign::Negative
55}
56
57fn is_ear(ring: &[Point2], indices: &[usize], at: usize) -> bool {
59 let n = indices.len();
60 let (ia, ib, ic) = (
61 indices[(at + n - 1) % n],
62 indices[at],
63 indices[(at + 1) % n],
64 );
65 let (a, b, c) = (ring[ia], ring[ib], ring[ic]);
66
67 if sign_of(a, b, c) != Sign::Positive {
70 return false;
71 }
72
73 !indices
80 .iter()
81 .filter(|&&idx| idx != ia && idx != ib && idx != ic)
82 .map(|&idx| ring[idx])
83 .filter(|q| *q != a && *q != b && *q != c)
84 .any(|q| blocks_ear(a, b, c, q))
85}
86
87pub fn triangulate_simple(ring: &[Point2]) -> GeomResult<Vec<[u32; 3]>> {
92 if ring.len() < 3 {
93 return Err(GeomError::Degenerate(format!(
94 "ring has {} vertices, need at least 3",
95 ring.len()
96 )));
97 }
98 let mut indices: Vec<usize> = (0..ring.len()).collect();
99 let mut out = Vec::with_capacity(ring.len().saturating_sub(2));
100
101 let mut at = 0usize;
105 let mut guard = 0usize;
106 while indices.len() > 3 {
107 if guard > indices.len() {
108 return Err(GeomError::Degenerate(
109 "no ear found; polygon is self-intersecting or degenerate".to_owned(),
110 ));
111 }
112 if is_ear(ring, &indices, at % indices.len()) {
113 let n = indices.len();
114 let cur = at % n;
115 out.push([
116 indices[(cur + n - 1) % n] as u32,
117 indices[cur] as u32,
118 indices[(cur + 1) % n] as u32,
119 ]);
120 indices.remove(cur);
121 at = cur;
122 guard = 0;
123 } else {
124 at += 1;
125 guard += 1;
126 }
127 }
128 let (a, b, c) = (ring[indices[0]], ring[indices[1]], ring[indices[2]]);
131 if sign_of(a, b, c) != Sign::Positive {
132 return Err(GeomError::Degenerate(
133 "final triangle is not positively wound; polygon is self-intersecting or degenerate"
134 .to_owned(),
135 ));
136 }
137 out.push([indices[0] as u32, indices[1] as u32, indices[2] as u32]);
138 Ok(out)
139}