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