Skip to main content

lib_jsl_geometry/dim_3/
volume_mesh3d.rs

1//! Concrete volume mesh type built from three-dimensional tetrahedra.
2//!
3//! [`VolumeMesh3D`] models a tetrahedral volume mesh in the same keyed-table style as the rest of
4//! the concrete geometry graph. The mesh stores ordered tetrahedron ids into a shared tetrahedron
5//! table, and each tetrahedron ultimately resolves back to the shared point table. Boundary
6//! surfaces are materialized into caller-provided face tables so the resulting surface meshes stay
7//! connected to the broader geometry graph.
8
9use lib_jsl_core::ErrorsJSL;
10use crate::common::{
11    Canonicalize, FaceId, GeometricPrimitive, GeometricPrimitive3D, GeometryMeasure, HasCentroid,
12    HasEdges, HasTetrahedra, HasVertices, IsGeometryTable, IsPlane, IsValid, PointId, Repair,
13    TetrahedronId,
14};
15use crate::one_d::IsLine;
16use crate::tables::{HashGeometryTable, SharedGeometryTable};
17use crate::three_d::{
18    FreeVector3D, IsVolumeMesh, Line3D, CoordinateVector3D, PolygonFace3D, SurfaceMesh3D,
19    Tetrahedron3D, Triangle3D, UnitVector3D,
20};
21use crate::transformation_traits::{CanMirror, CanRotate, CanShear, CanTranslate};
22use crate::two_d::{IsPolygon, IsTriangle};
23use std::cell::RefCell;
24use std::collections::{HashMap, HashSet};
25use std::fmt::{self, Display, Formatter};
26use std::hash::{Hash, Hasher};
27use std::rc::Rc;
28
29/// Concrete 3D tetrahedral volume mesh implementation backed by tetrahedron ids.
30#[derive(Debug, Clone)]
31#[cfg_attr(feature = "serde", derive(serde::Serialize))]
32pub struct VolumeMesh3D {
33    tetrahedron_ids: Vec<TetrahedronId>,
34    #[cfg_attr(feature = "serde", serde(skip_serializing))]
35    vertex_table: SharedGeometryTable<PointId, CoordinateVector3D>,
36    #[cfg_attr(feature = "serde", serde(skip_serializing))]
37    tetrahedron_table: SharedGeometryTable<TetrahedronId, Tetrahedron3D>,
38}
39
40impl PartialEq for VolumeMesh3D {
41    fn eq(&self, other: &Self) -> bool {
42        self.tetrahedron_ids == other.tetrahedron_ids
43    }
44}
45
46impl Eq for VolumeMesh3D {}
47
48impl Hash for VolumeMesh3D {
49    fn hash<H: Hasher>(&self, state: &mut H) {
50        self.tetrahedron_ids.hash(state);
51    }
52}
53
54impl VolumeMesh3D {
55    /// Creates a volume mesh from ordered tetrahedron ids and shared point/tetrahedron tables.
56    ///
57    /// Each tetrahedron id is resolved through `tetrahedron_table`, and the tetrahedra in that
58    /// table in turn resolve their vertices through `vertex_table`.
59    pub fn new(
60        tetrahedron_ids: Vec<TetrahedronId>,
61        vertex_table: SharedGeometryTable<PointId, CoordinateVector3D>,
62        tetrahedron_table: SharedGeometryTable<TetrahedronId, Tetrahedron3D>,
63    ) -> Self {
64        Self {
65            tetrahedron_ids,
66            vertex_table,
67            tetrahedron_table,
68        }
69    }
70
71    /// Creates a volume mesh from tetrahedra, inferring the shared point table and building a
72    /// dedicated tetrahedron table with sequential ids.
73    pub fn from_tetrahedra(tetrahedra: Vec<Tetrahedron3D>) -> Result<Self, ErrorsJSL> {
74        let vertex_table = tetrahedra
75            .first()
76            .map(|tetrahedron| tetrahedron.vertex_table().clone())
77            .ok_or_else(|| "cannot compose volume mesh from an empty tetrahedron set".to_string())?;
78
79        for tetrahedron in &tetrahedra {
80            if !Rc::ptr_eq(&vertex_table, tetrahedron.vertex_table()) {
81                return Err(ErrorsJSL::Message("all tetrahedra must share the same vertex table".to_string()));
82            }
83        }
84
85        let tetrahedron_table = Rc::new(RefCell::new(HashGeometryTable::new()));
86        let mut tetrahedron_ids = Vec::with_capacity(tetrahedra.len());
87
88        for (index, tetrahedron) in tetrahedra.into_iter().enumerate() {
89            let tetrahedron_id = TetrahedronId(index as u64 + 1);
90            tetrahedron_table
91                .borrow_mut()
92                .insert(tetrahedron_id, tetrahedron)?;
93            tetrahedron_ids.push(tetrahedron_id);
94        }
95
96        Ok(Self::new(tetrahedron_ids, vertex_table, tetrahedron_table))
97    }
98
99    /// Resolves and returns all tetrahedra in mesh order.
100    pub fn tetrahedra(&self) -> Vec<Tetrahedron3D> {
101        self.tetrahedron_ids
102            .iter()
103            .filter_map(|tetrahedron_id| self.get_tetrahedron(tetrahedron_id))
104            .collect()
105    }
106
107    /// Returns the number of tetrahedra in the mesh.
108    pub fn tetrahedron_count(&self) -> usize {
109        self.tetrahedron_ids.len()
110    }
111
112    /// Resolves and returns a tetrahedron by mesh-local index.
113    pub fn tetrahedron(&self, index: usize) -> Option<Tetrahedron3D> {
114        self.tetrahedron_ids
115            .get(index)
116            .and_then(|tetrahedron_id| self.get_tetrahedron(tetrahedron_id))
117    }
118
119    /// Returns the total enclosed volume of the mesh.
120    pub fn volume(&self) -> GeometryMeasure {
121        self.tetrahedra().iter().map(Tetrahedron3D::volume).sum()
122    }
123
124    /// Returns the total boundary surface area of the mesh.
125    pub fn surface_area(&self) -> GeometryMeasure {
126        self.boundary_triangles()
127            .iter()
128            .map(|triangle| triangle.area())
129            .sum()
130    }
131
132    /// Returns the boundary triangles exposed by the tetrahedral cells.
133    pub fn boundary_triangles(&self) -> Vec<Triangle3D> {
134        let mut counts: HashMap<(u64, u64, u64), (usize, Triangle3D)> = HashMap::new();
135
136        for tetrahedron in self.tetrahedra() {
137            for face in tetrahedron.faces() {
138                let mut key = [face.a_id().0, face.b_id().0, face.c_id().0];
139                key.sort_unstable();
140                let key = (key[0], key[1], key[2]);
141                counts
142                    .entry(key)
143                    .and_modify(|entry| entry.0 += 1)
144                    .or_insert((1, face));
145            }
146        }
147
148        counts
149            .into_values()
150            .filter_map(|(count, triangle)| (count == 1).then_some(triangle))
151            .collect()
152    }
153
154    /// Returns the boundary faces as polygon-face wrappers over the boundary triangles.
155    pub fn boundary_faces(&self) -> Vec<PolygonFace3D> {
156        self.boundary_triangles()
157            .into_iter()
158            .map(|triangle| {
159                PolygonFace3D::new(
160                    vec![triangle.a_id(), triangle.b_id(), triangle.c_id()],
161                    self.vertex_table.clone(),
162                )
163            })
164            .collect()
165    }
166
167    /// Materializes the boundary surface into a shared face table and returns a connected surface mesh.
168    pub fn surface_mesh(
169        &self,
170        face_table: SharedGeometryTable<FaceId, PolygonFace3D>,
171    ) -> Result<SurfaceMesh3D, ErrorsJSL> {
172        let mut face_ids = Vec::new();
173        let next_face_id = face_table
174            .borrow()
175            .iter()
176            .map(|(face_id, _)| face_id.0)
177            .max()
178            .unwrap_or(0)
179            + 1;
180
181        for (index, face) in self.boundary_faces().into_iter().enumerate() {
182            let face_id = FaceId(next_face_id + index as u64);
183            face_table.borrow_mut().insert(face_id, face)?;
184            face_ids.push(face_id);
185        }
186
187        Ok(SurfaceMesh3D::new(face_ids, self.vertex_table.clone(), face_table))
188    }
189
190    fn unique_vertex_ids(&self) -> Vec<PointId> {
191        let mut seen = HashSet::new();
192        self.tetrahedra()
193            .into_iter()
194            .flat_map(|tetrahedron| {
195                [
196                    tetrahedron.a_id(),
197                    tetrahedron.b_id(),
198                    tetrahedron.c_id(),
199                    tetrahedron.d_id(),
200                ]
201            })
202            .filter(|id| seen.insert(*id))
203            .collect()
204    }
205
206    fn resolved_edges(&self) -> Vec<Line3D> {
207        let mut seen = HashSet::new();
208        let mut edges = Vec::new();
209
210        for tetrahedron in self.tetrahedra() {
211            for edge_index in 0..tetrahedron.edge_count() {
212                if let Some(edge) = tetrahedron.edge(edge_index) {
213                    let head = edge.head_id().0.min(edge.tail_id().0);
214                    let tail = edge.head_id().0.max(edge.tail_id().0);
215                    if seen.insert((head, tail)) {
216                        edges.push(edge);
217                    }
218                }
219            }
220        }
221
222        edges
223    }
224}
225
226impl Display for VolumeMesh3D {
227    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
228        write!(f, "VolumeMesh3D(tetrahedra={})", self.tetrahedron_ids.len())
229    }
230}
231
232impl GeometricPrimitive for VolumeMesh3D {}
233impl GeometricPrimitive3D for VolumeMesh3D {}
234
235impl<'a> HasVertices<'a> for VolumeMesh3D {
236    type Vertex = CoordinateVector3D;
237    type VertexTable = SharedGeometryTable<PointId, CoordinateVector3D>;
238
239    fn vertex_table(&self) -> &Self::VertexTable {
240        &self.vertex_table
241    }
242
243    fn vertex_table_mut(&mut self) -> &mut Self::VertexTable {
244        &mut self.vertex_table
245    }
246
247    fn set_vertex_table(&mut self, table: &'a mut Self::VertexTable) {
248        self.vertex_table = table.clone();
249
250        for tetrahedron_id in self.tetrahedron_ids.clone() {
251            if let Some(mut tetrahedron) = self.get_tetrahedron(&tetrahedron_id) {
252                tetrahedron.set_vertex_table(table);
253                let _ = self.insert_tetrahedron(tetrahedron_id, tetrahedron);
254            }
255        }
256    }
257}
258
259impl<'a> HasTetrahedra<'a> for VolumeMesh3D {
260    type Point = CoordinateVector3D;
261    type Normal = UnitVector3D;
262    type Tetrahedron = Tetrahedron3D;
263    type TetrahedronTable = SharedGeometryTable<TetrahedronId, Tetrahedron3D>;
264
265    fn tetrahedron_table(&self) -> &Self::TetrahedronTable {
266        &self.tetrahedron_table
267    }
268
269    fn tetrahedron_table_mut(&mut self) -> &mut Self::TetrahedronTable {
270        &mut self.tetrahedron_table
271    }
272
273    fn set_tetrahedron_table(&mut self, table: &'a mut Self::TetrahedronTable) {
274        self.tetrahedron_table = table.clone();
275    }
276}
277
278impl HasEdges for VolumeMesh3D {
279    type Edge = Line3D;
280
281    fn edge_count(&self) -> usize {
282        self.resolved_edges().len()
283    }
284
285    fn edge(&self, index: usize) -> Option<Self::Edge> {
286        self.resolved_edges().into_iter().nth(index)
287    }
288}
289
290impl HasCentroid for VolumeMesh3D {
291    type Point = CoordinateVector3D;
292
293    fn centroid(&self) -> Self::Point {
294        let total_volume = self.volume();
295        if total_volume <= 1e-6 {
296            return CoordinateVector3D::new(0.0, 0.0, 0.0);
297        }
298
299        let weighted_sum = self.tetrahedra().into_iter().fold(
300            CoordinateVector3D::new(0.0, 0.0, 0.0),
301            |acc, tetrahedron| acc + tetrahedron.centroid() * tetrahedron.volume(),
302        );
303
304        weighted_sum / total_volume
305    }
306}
307
308impl IsValid for VolumeMesh3D {
309    fn is_valid(&self) -> bool {
310        !self.tetrahedron_ids.is_empty()
311            && self
312                .tetrahedron_ids
313                .iter()
314                .all(|tetrahedron_id| self.contains_tetrahedron(tetrahedron_id))
315            && self
316                .tetrahedra()
317                .iter()
318                .all(|tetrahedron| tetrahedron.is_valid())
319    }
320}
321
322impl Repair for VolumeMesh3D {
323    fn repair(&mut self) -> Result<(), ErrorsJSL> {
324        for tetrahedron_id in self.tetrahedron_ids.clone() {
325            let Some(mut tetrahedron) = self.get_tetrahedron(&tetrahedron_id) else {
326                return Err(ErrorsJSL::Message(format!(
327                    "tetrahedron id {:?} is missing from the tetrahedron table",
328                    tetrahedron_id
329                )));
330            };
331            tetrahedron.repair()?;
332            self.insert_tetrahedron(tetrahedron_id, tetrahedron)?;
333        }
334        Ok(())
335    }
336}
337
338impl Canonicalize for VolumeMesh3D {
339    fn canonicalize(&mut self) {
340        for tetrahedron_id in self.tetrahedron_ids.clone() {
341            if let Some(mut tetrahedron) = self.get_tetrahedron(&tetrahedron_id) {
342                tetrahedron.canonicalize();
343                let _ = self.insert_tetrahedron(tetrahedron_id, tetrahedron);
344            }
345        }
346
347        let mut ordered_ids = self
348            .tetrahedron_ids
349            .iter()
350            .copied()
351            .map(|tetrahedron_id| {
352                let sort_key = self
353                    .get_tetrahedron(&tetrahedron_id)
354                    .map(|tetrahedron| {
355                        (
356                            tetrahedron.a_id().0,
357                            tetrahedron.b_id().0,
358                            tetrahedron.c_id().0,
359                            tetrahedron.d_id().0,
360                        )
361                    })
362                    .unwrap_or((u64::MAX, u64::MAX, u64::MAX, u64::MAX));
363                (sort_key, tetrahedron_id)
364            })
365            .collect::<Vec<_>>();
366        ordered_ids.sort_by_key(|(sort_key, _)| *sort_key);
367        self.tetrahedron_ids = ordered_ids
368            .into_iter()
369            .map(|(_, tetrahedron_id)| tetrahedron_id)
370            .collect();
371    }
372}
373
374impl CanTranslate for VolumeMesh3D {
375    type Point = CoordinateVector3D;
376
377    fn translate<'a, L>(&mut self, translation_vector: &L)
378    where
379        L: IsLine<'a, Self::Point>,
380    {
381        let (Some(head), Some(tail)) = (translation_vector.head(), translation_vector.tail()) else {
382            return;
383        };
384        let delta = FreeVector3D::new(tail.x() - head.x(), tail.y() - head.y(), tail.z() - head.z());
385        for point_id in self.unique_vertex_ids() {
386            if let Some(mut point) = self.get_vertex(&point_id) {
387                point = point + delta;
388                let _ = self.insert_vertex(point_id, point);
389            }
390        }
391    }
392}
393
394impl CanRotate for VolumeMesh3D {
395    type Point = CoordinateVector3D;
396
397    fn rotate<'a, L>(&mut self, axis: &L, angle_radians: GeometryMeasure)
398    where
399        L: IsLine<'a, Self::Point>,
400    {
401        let Some(origin) = axis.head() else {
402            return;
403        };
404        let direction = axis.direction();
405        for point_id in self.unique_vertex_ids() {
406            if let Some(point) = self.get_vertex(&point_id) {
407                let rotated = crate::three_d::transform_support::rotate_point_around_axis(
408                    point,
409                    origin,
410                    &direction,
411                    angle_radians,
412                );
413                let _ = self.insert_vertex(point_id, rotated);
414            }
415        }
416    }
417}
418
419impl CanShear for VolumeMesh3D {
420    type Point = CoordinateVector3D;
421
422    fn shear<'a, L>(&mut self, shear_line: &L)
423    where
424        L: IsLine<'a, Self::Point>,
425    {
426        let factor = shear_line.length();
427        for point_id in self.unique_vertex_ids() {
428            if let Some(mut point) = self.get_vertex(&point_id) {
429                let coords = point.cartesian_components();
430                point = CoordinateVector3D::from_cartesian_components(
431                    [coords[0] + factor * coords[1], coords[1], coords[2]],
432                    point.coordinate_system(),
433                );
434                let _ = self.insert_vertex(point_id, point);
435            }
436        }
437    }
438}
439
440impl CanMirror for VolumeMesh3D {
441    type Point = CoordinateVector3D;
442    type Normal = UnitVector3D;
443
444    fn mirror<P>(&mut self, mirror_plane: &P)
445    where
446        P: IsPlane<Point = Self::Point, Normal = Self::Normal>,
447    {
448        for point_id in self.unique_vertex_ids() {
449            if let Some(point) = self.get_vertex(&point_id) {
450                let reflected = crate::three_d::transform_support::reflect_point_across_plane(
451                    point,
452                    mirror_plane.point(),
453                    mirror_plane.normal(),
454                );
455                let _ = self.insert_vertex(point_id, reflected);
456            }
457        }
458    }
459}
460
461impl<'a> IsVolumeMesh<'a, CoordinateVector3D, UnitVector3D> for VolumeMesh3D {
462    fn tetrahedron_ids(&self) -> Box<dyn Iterator<Item = TetrahedronId> + '_> {
463        Box::new(self.tetrahedron_ids.iter().copied())
464    }
465
466    fn set_tetrahedron_id(&mut self, index: usize, tetrahedron_id: TetrahedronId) -> Result<(), ErrorsJSL> {
467        if let Some(slot) = self.tetrahedron_ids.get_mut(index) {
468            *slot = tetrahedron_id;
469            Ok(())
470        } else {
471            Err(ErrorsJSL::Message(format!("tetrahedron index {} is out of bounds", index)))
472        }
473    }
474
475    fn volume(&self) -> GeometryMeasure {
476        VolumeMesh3D::volume(self)
477    }
478}