Skip to main content

lib_jsl_geometry/dim_2/
polygon_face2d.rs

1//! Concrete polygon face type built from two-dimensional points.
2
3use lib_jsl_core::ErrorsJSL;
4use crate::common::{
5    GeometricPrimitive, GeometricPrimitive2D, GeometryMeasure, HasCentroid, HasEdges,
6    HasMeasure, HasVertices, IsPlane, PointId,
7};
8use crate::one_d::IsLine;
9use crate::tables::SharedGeometryTable;
10use crate::transformation_traits::{CanMirror, CanRotate, CanShear, CanTranslate};
11use crate::two_d::transform_support::{reflect_point_across_plane_2d, rotate_point_around_anchor_2d};
12use crate::two_d::{
13    FreeVector2D, HasOrientation, IsPolygon, Line2D, Plane2D, CoordinateVector2D, Triangle2D,
14    UnitVector2D, Orientation2D,
15};
16use std::collections::{HashMap, HashSet};
17use std::fmt::{self, Display, Formatter};
18use std::hash::{Hash, Hasher};
19
20/// Concrete 2D polygon face backed by ordered point ids.
21#[derive(Debug, Clone)]
22#[cfg_attr(feature = "serde", derive(serde::Serialize))]
23pub struct PolygonFace2D {
24    vertex_ids: Vec<PointId>,
25    #[cfg_attr(feature = "serde", serde(skip_serializing))]
26    vertex_table: SharedGeometryTable<PointId, CoordinateVector2D>,
27}
28
29impl PartialEq for PolygonFace2D {
30    fn eq(&self, other: &Self) -> bool {
31        self.vertex_ids == other.vertex_ids
32    }
33}
34
35impl Eq for PolygonFace2D {}
36
37impl Hash for PolygonFace2D {
38    fn hash<H: Hasher>(&self, state: &mut H) {
39        self.vertex_ids.hash(state);
40    }
41}
42
43impl PolygonFace2D {
44    /// Creates a polygon face from ordered point ids and a shared point table.
45    pub fn new(vertex_ids: Vec<PointId>, vertex_table: SharedGeometryTable<PointId, CoordinateVector2D>) -> Self {
46        Self {
47            vertex_ids,
48            vertex_table,
49        }
50    }
51
52    /// Decomposes the polygon into a fan of triangles rooted at the first vertex.
53    pub fn triangulate(&self) -> Vec<Triangle2D> {
54        if self.vertex_ids.len() < 3 {
55            return Vec::new();
56        }
57        let root = self.vertex_ids[0];
58        (1..self.vertex_ids.len() - 1)
59            .map(|index| {
60                Triangle2D::new(
61                    root,
62                    self.vertex_ids[index],
63                    self.vertex_ids[index + 1],
64                    self.vertex_table.clone(),
65                )
66            })
67            .collect()
68    }
69
70    /// Composes a polygon from a set of triangles that share a common boundary.
71    pub fn from_triangles(triangles: &[Triangle2D]) -> Result<Self, ErrorsJSL> {
72        if triangles.is_empty() {
73            return Err(ErrorsJSL::Message("cannot compose polygon from an empty triangle set".to_string()));
74        }
75
76        let vertex_table = triangles[0].vertex_table().clone();
77        let mut boundary_counts: HashMap<(u64, u64), usize> = HashMap::new();
78        let mut boundary_direction: HashMap<(u64, u64), (PointId, PointId)> = HashMap::new();
79
80        for triangle in triangles {
81            let triangle_table = triangle.vertex_table().clone();
82            if !std::rc::Rc::ptr_eq(&vertex_table, &triangle_table) {
83                return Err(ErrorsJSL::Message("all triangles must share the same vertex table".to_string()));
84            }
85
86            let ids: Vec<_> = triangle.vertex_ids().collect();
87            for (head, tail) in [(ids[0], ids[1]), (ids[1], ids[2]), (ids[2], ids[0])] {
88                let key = (head.0.min(tail.0), head.0.max(tail.0));
89                *boundary_counts.entry(key).or_insert(0) += 1;
90                boundary_direction.entry(key).or_insert((head, tail));
91            }
92        }
93
94        let boundary_edges: Vec<_> = boundary_counts
95            .iter()
96            .filter(|(_, count)| **count == 1)
97            .filter_map(|(key, _)| boundary_direction.get(key).copied())
98            .collect();
99
100        if boundary_edges.len() < 3 {
101            return Err(ErrorsJSL::Message("triangle set does not expose a valid polygon boundary".to_string()));
102        }
103
104        let mut adjacency: HashMap<PointId, Vec<PointId>> = HashMap::new();
105        for (head, tail) in &boundary_edges {
106            adjacency.entry(*head).or_default().push(*tail);
107            adjacency.entry(*tail).or_default().push(*head);
108        }
109
110        if adjacency.values().any(|neighbors| neighbors.len() != 2) {
111            return Err(ErrorsJSL::Message("triangle set does not form a single closed polygon boundary".to_string()));
112        }
113
114        let start = adjacency
115            .keys()
116            .min_by_key(|id| id.0)
117            .copied()
118            .ok_or_else(|| "failed to determine polygon boundary start".to_string())?;
119
120        let mut ordered = vec![start];
121        let mut previous = None;
122        let mut current = start;
123
124        loop {
125            let neighbors = adjacency
126                .get(&current)
127                .ok_or_else(|| "missing boundary adjacency entry".to_string())?;
128            let next = neighbors
129                .iter()
130                .copied()
131                .find(|candidate| Some(*candidate) != previous)
132                .ok_or_else(|| "failed to walk polygon boundary".to_string())?;
133
134            if next == start {
135                break;
136            }
137            if ordered.contains(&next) {
138                return Err(ErrorsJSL::Message("triangle set boundary is self-intersecting or duplicated".to_string()));
139            }
140
141            ordered.push(next);
142            previous = Some(current);
143            current = next;
144        }
145
146        let desired_orientation = triangles[0].orientation();
147        let candidate = Self::new(ordered.clone(), vertex_table.clone());
148        if desired_orientation != Orientation2D::Collinear
149            && candidate.orientation() != desired_orientation
150        {
151            let mut reversed = vec![ordered[0]];
152            reversed.extend(ordered[1..].iter().rev().copied());
153            ordered = reversed;
154        }
155
156        Ok(Self::new(ordered, vertex_table))
157    }
158
159    fn resolved_points(&self) -> Option<Vec<CoordinateVector2D>> {
160        self.vertex_ids
161            .iter()
162            .map(|id| self.get_vertex(id))
163            .collect::<Option<Vec<_>>>()
164    }
165
166    fn unique_vertex_ids(&self) -> Vec<PointId> {
167        let mut seen = HashSet::new();
168        self.vertex_ids.iter().copied().filter(|id| seen.insert(*id)).collect()
169    }
170}
171
172impl Display for PolygonFace2D {
173    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
174        write!(f, "PolygonFace2D(vertices={:?})", self.vertex_ids)
175    }
176}
177
178impl GeometricPrimitive for PolygonFace2D {}
179impl GeometricPrimitive2D for PolygonFace2D {}
180
181impl<'a> HasVertices<'a> for PolygonFace2D {
182    type Vertex = CoordinateVector2D;
183    type VertexTable = SharedGeometryTable<PointId, CoordinateVector2D>;
184
185    fn vertex_table(&self) -> &Self::VertexTable {
186        &self.vertex_table
187    }
188
189    fn vertex_table_mut(&mut self) -> &mut Self::VertexTable {
190        &mut self.vertex_table
191    }
192
193    fn set_vertex_table(&mut self, table: &'a mut Self::VertexTable) {
194        self.vertex_table = table.clone();
195    }
196}
197
198impl HasEdges for PolygonFace2D {
199    type Edge = Line2D;
200
201    fn edge_count(&self) -> usize {
202        self.vertex_ids.len().saturating_sub(1).max((self.vertex_ids.len() >= 3) as usize)
203    }
204
205    fn edge(&self, index: usize) -> Option<Self::Edge> {
206        if self.vertex_ids.len() < 2 {
207            return None;
208        }
209        let count = self.vertex_ids.len();
210        if index >= count {
211            return None;
212        }
213        let head = self.vertex_ids[index];
214        let tail = self.vertex_ids[(index + 1) % count];
215        Some(Line2D::new(head, tail, self.vertex_table.clone()))
216    }
217}
218
219impl HasCentroid for PolygonFace2D {
220    type Point = CoordinateVector2D;
221
222    fn centroid(&self) -> Self::Point {
223        if let Some(points) = self.resolved_points() {
224            let count = points.len() as GeometryMeasure;
225            let sum = points
226                .into_iter()
227                .fold(CoordinateVector2D::new(0.0, 0.0), |acc, point| acc + point);
228            sum / count
229        } else {
230            CoordinateVector2D::new(0.0, 0.0)
231        }
232    }
233}
234
235impl HasMeasure for PolygonFace2D {
236    fn measure(&self) -> GeometryMeasure {
237        self.area()
238    }
239}
240
241impl HasOrientation for PolygonFace2D {
242    fn orientation(&self) -> Orientation2D {
243        let Some(points) = self.resolved_points() else {
244            return Orientation2D::Collinear;
245        };
246        if points.len() < 3 {
247            return Orientation2D::Collinear;
248        }
249        let signed_area = points
250            .iter()
251            .enumerate()
252            .map(|(i, a)| {
253                let b = points[(i + 1) % points.len()];
254                a.x() * b.y() - b.x() * a.y()
255            })
256            .sum::<GeometryMeasure>();
257        if signed_area > 0.0 {
258            Orientation2D::CounterClockwise
259        } else if signed_area < 0.0 {
260            Orientation2D::Clockwise
261        } else {
262            Orientation2D::Collinear
263        }
264    }
265}
266
267impl CanTranslate for PolygonFace2D {
268    type Point = CoordinateVector2D;
269
270    fn translate<'a, L>(&mut self, translation_vector: &L)
271    where
272        L: IsLine<'a, Self::Point>,
273    {
274        let (Some(head), Some(tail)) = (translation_vector.head(), translation_vector.tail()) else {
275            return;
276        };
277        let delta = FreeVector2D::new(tail.x() - head.x(), tail.y() - head.y());
278        for point_id in self.unique_vertex_ids() {
279            if let Some(mut point) = self.get_vertex(&point_id) {
280                point = point + delta;
281                let _ = self.insert_vertex(point_id, point);
282            }
283        }
284    }
285}
286
287impl CanRotate for PolygonFace2D {
288    type Point = CoordinateVector2D;
289
290    fn rotate<'a, L>(&mut self, axis: &L, angle_radians: GeometryMeasure)
291    where
292        L: IsLine<'a, Self::Point>,
293    {
294        let Some(origin) = axis.head() else {
295            return;
296        };
297        for point_id in self.unique_vertex_ids() {
298            if let Some(point) = self.get_vertex(&point_id) {
299                let rotated = rotate_point_around_anchor_2d(point, origin, angle_radians);
300                let _ = self.insert_vertex(point_id, rotated);
301            }
302        }
303    }
304}
305
306impl CanShear for PolygonFace2D {
307    type Point = CoordinateVector2D;
308
309    fn shear<'a, L>(&mut self, shear_line: &L)
310    where
311        L: IsLine<'a, Self::Point>,
312    {
313        let factor = shear_line.length();
314        for point_id in self.unique_vertex_ids() {
315            if let Some(mut point) = self.get_vertex(&point_id) {
316                let coords = point.cartesian_components();
317                point = CoordinateVector2D::from_cartesian_components(
318                    [coords[0] + factor * coords[1], coords[1]],
319                    point.coordinate_system(),
320                );
321                let _ = self.insert_vertex(point_id, point);
322            }
323        }
324    }
325}
326
327impl CanMirror for PolygonFace2D {
328    type Point = CoordinateVector2D;
329    type Normal = UnitVector2D;
330
331    fn mirror<P>(&mut self, mirror_plane: &P)
332    where
333        P: IsPlane<Point = Self::Point, Normal = Self::Normal>,
334    {
335        for point_id in self.unique_vertex_ids() {
336            if let Some(point) = self.get_vertex(&point_id) {
337                let reflected = reflect_point_across_plane_2d(point, mirror_plane.point(), mirror_plane.normal());
338                let _ = self.insert_vertex(point_id, reflected);
339            }
340        }
341    }
342}
343
344impl<'a> IsPolygon<'a, CoordinateVector2D, UnitVector2D> for PolygonFace2D {
345    fn vertex_ids(&self) -> Box<dyn Iterator<Item = PointId> + '_> {
346        Box::new(self.vertex_ids.iter().copied())
347    }
348
349    fn set_vertex_id(&mut self, index: usize, point_id: PointId) -> Result<(), ErrorsJSL> {
350        if let Some(slot) = self.vertex_ids.get_mut(index) {
351            *slot = point_id;
352            Ok(())
353        } else {
354            Err(ErrorsJSL::Message(format!("vertex index {} is out of bounds", index)))
355        }
356    }
357
358    fn normal(&self) -> UnitVector2D {
359        match self.orientation() {
360            Orientation2D::Clockwise => UnitVector2D::new(0.0, -1.0),
361            Orientation2D::CounterClockwise => UnitVector2D::new(0.0, 1.0),
362            Orientation2D::Collinear => UnitVector2D::new(0.0, 1.0),
363        }
364    }
365
366    fn perimeter(&self) -> GeometryMeasure {
367        (0..self.vertex_ids.len())
368            .filter_map(|index| self.edge(index))
369            .map(|edge| edge.length())
370            .sum()
371    }
372
373    fn area(&self) -> GeometryMeasure {
374        let Some(points) = self.resolved_points() else {
375            return 0.0;
376        };
377        if points.len() < 3 {
378            return 0.0;
379        }
380        points
381            .iter()
382            .enumerate()
383            .map(|(i, a)| {
384                let b = points[(i + 1) % points.len()];
385                a.x() * b.y() - b.x() * a.y()
386            })
387            .sum::<GeometryMeasure>()
388            .abs()
389            / 2.0
390    }
391
392    fn plane(&self) -> impl IsPlane<Point = CoordinateVector2D, Normal = UnitVector2D> {
393        Plane2D::new(self.centroid(), self.normal())
394    }
395}