mesh_geometry/metrics/
polygon.rs1use crate::{Float, Point2};
21
22pub fn polygon_area<T: Float>(verts: &[Point2<T>]) -> T {
25 let n = verts.len();
26 assert!(n >= 3, "polygon_area requires ≥3 vertices");
27 let mut sum = T::zero();
28 for i in 0..n {
29 let a = verts[i];
30 let b = verts[(i + 1) % n];
31 sum = sum + (a.x * b.y - b.x * a.y);
32 }
33 (sum * T::from(0.5).unwrap()).abs()
34}
35
36pub fn polygon_centroid<T: Float>(verts: &[Point2<T>]) -> Point2<T> {
38 let n = verts.len();
39 assert!(n >= 3, "polygon_centroid requires ≥3 vertices");
40 let mut a_twice = T::zero();
41 let mut cx = T::zero();
42 let mut cy = T::zero();
43 for i in 0..n {
44 let xi = verts[i].x;
45 let yi = verts[i].y;
46 let xj = verts[(i + 1) % n].x;
47 let yj = verts[(i + 1) % n].y;
48 let cross = xi * yj - xj * yi;
49 a_twice = a_twice + cross;
50 cx = cx + (xi + xj) * cross;
51 cy = cy + (yi + yj) * cross;
52 }
53 let a = a_twice * T::from(0.5).unwrap();
54 let factor = T::one() / (T::from(6.0).unwrap() * a);
55 Point2::new(cx * factor, cy * factor)
56}