Skip to main content

section_properties/
mesh.rs

1//! Mesh generation and FEM analysis core.
2//!
3//! Provides triangular mesh generation (ear clipping, Delaunay) and
4//! linear elastic FEM solver for section analysis.
5
6pub(crate) mod fem;
7pub mod fem_analysis;
8pub mod triangulation;
9
10pub use fem_analysis::{
11    FemCompositeAnalysis, FemGeometricProperties, FemSectionAnalysis, FemWarpingProperties,
12    PropertyComparison, StressPlotData, StressPost,
13};
14pub use triangulation::{Triangle, Triangulation, triangulate_polygon, triangulate_section};
15
16/// Mesh density control for automated sizing based on section bounding box.
17pub use crate::mesh::triangulation::MeshControl;
18/// Create mesh params from control and section dimensions.
19pub use crate::mesh::triangulation::mesh_params_from_control;
20
21use crate::geometry::Point;
22use crate::section::Section;
23use crate::section_library::CompositeSection;
24
25/// 2D triangular mesh for a section.
26#[derive(Debug, Clone)]
27pub struct Mesh {
28    /// Nodal coordinates
29    pub nodes: Vec<Point>,
30    /// Element connectivity (3 node indices per triangle, CCW)
31    pub elements: Vec<[usize; 3]>,
32    /// Material index per element
33    pub element_materials: Vec<usize>,
34    /// Boundary nodes (for applying BCs)
35    pub boundary_nodes: Vec<usize>,
36    /// Hole boundary nodes (for internal boundaries)
37    pub hole_boundary_nodes: Vec<Vec<usize>>,
38}
39
40impl Mesh {
41    /// Create an empty mesh.
42    pub fn new() -> Self {
43        Self {
44            nodes: Vec::new(),
45            elements: Vec::new(),
46            element_materials: Vec::new(),
47            boundary_nodes: Vec::new(),
48            hole_boundary_nodes: Vec::new(),
49        }
50    }
51
52    /// Number of nodes.
53    pub fn n_nodes(&self) -> usize {
54        self.nodes.len()
55    }
56
57    /// Number of elements.
58    pub fn n_elements(&self) -> usize {
59        self.elements.len()
60    }
61
62    /// Get node coordinates.
63    pub fn node(&self, index: usize) -> Point {
64        self.nodes[index]
65    }
66
67    /// Get element connectivity.
68    pub fn element(&self, index: usize) -> [usize; 3] {
69        self.elements[index]
70    }
71
72    /// Get element centroid.
73    pub fn element_centroid(&self, index: usize) -> Point {
74        let elem = self.elements[index];
75        let p1 = self.nodes[elem[0]];
76        let p2 = self.nodes[elem[1]];
77        let p3 = self.nodes[elem[2]];
78        Point::new((p1.x + p2.x + p3.x) / 3.0, (p1.y + p2.y + p3.y) / 3.0)
79    }
80
81    /// Get element area.
82    pub fn element_area(&self, index: usize) -> f64 {
83        let elem = self.elements[index];
84        let p1 = self.nodes[elem[0]];
85        let p2 = self.nodes[elem[1]];
86        let p3 = self.nodes[elem[2]];
87        0.5 * ((p2.x - p1.x) * (p3.y - p1.y) - (p3.x - p1.x) * (p2.y - p1.y)).abs()
88    }
89
90    /// Compute mesh quality metrics.
91    pub fn quality_metrics(&self) -> MeshQuality {
92        let mut min_angle = f64::MAX;
93        let mut max_angle = f64::MIN;
94        let mut min_area = f64::MAX;
95        let mut max_area = f64::MIN;
96        let mut aspect_ratios = Vec::new();
97
98        for i in 0..self.n_elements() {
99            let elem = self.elements[i];
100            let p1 = self.nodes[elem[0]];
101            let p2 = self.nodes[elem[1]];
102            let p3 = self.nodes[elem[2]];
103
104            // Edge lengths
105            let a = ((p2.x - p3.x).powi(2) + (p2.y - p3.y).powi(2)).sqrt();
106            let b = ((p3.x - p1.x).powi(2) + (p3.y - p1.y).powi(2)).sqrt();
107            let c = ((p1.x - p2.x).powi(2) + (p1.y - p2.y).powi(2)).sqrt();
108
109            // Angles using law of cosines
110            let angles = [
111                ((b * b + c * c - a * a) / (2.0 * b * c)).acos(),
112                ((a * a + c * c - b * b) / (2.0 * a * c)).acos(),
113                ((a * a + b * b - c * c) / (2.0 * a * b)).acos(),
114            ];
115
116            for &angle in &angles {
117                min_angle = min_angle.min(angle);
118                max_angle = max_angle.max(angle);
119            }
120
121            // Area
122            let area = 0.5 * ((p2.x - p1.x) * (p3.y - p1.y) - (p3.x - p1.x) * (p2.y - p1.y)).abs();
123            min_area = min_area.min(area);
124            max_area = max_area.max(area);
125
126            // Aspect ratio (longest edge / shortest altitude)
127            let s = (a + b + c) / 2.0;
128            let area_heron = (s * (s - a) * (s - b) * (s - c)).max(0.0).sqrt();
129            let h_min = 2.0 * area_heron / a.max(b).max(c);
130            let aspect = a.max(b).max(c) / h_min;
131            aspect_ratios.push(aspect);
132        }
133
134        MeshQuality {
135            min_angle: min_angle.to_degrees(),
136            max_angle: max_angle.to_degrees(),
137            min_area,
138            max_area,
139            avg_aspect_ratio: aspect_ratios.iter().sum::<f64>() / aspect_ratios.len() as f64,
140            max_aspect_ratio: aspect_ratios.iter().fold(0.0, |a, &b| a.max(b)),
141        }
142    }
143}
144
145impl Default for Mesh {
146    fn default() -> Self {
147        Self::new()
148    }
149}
150
151/// Mesh quality metrics.
152#[derive(Debug, Clone, Copy)]
153pub struct MeshQuality {
154    pub min_angle: f64,
155    pub max_angle: f64,
156    pub min_area: f64,
157    pub max_area: f64,
158    pub avg_aspect_ratio: f64,
159    pub max_aspect_ratio: f64,
160}
161
162/// Mesh generation parameters.
163#[derive(Debug, Clone, Copy)]
164pub struct MeshParams {
165    /// Target element size (approximate edge length)
166    pub target_size: f64,
167    /// Maximum element size
168    pub max_size: f64,
169    /// Minimum element size
170    pub min_size: f64,
171    /// Quality threshold (0-1, higher = better quality)
172    pub quality_threshold: f64,
173    /// Whether to use Delaunay refinement
174    pub use_delaunay: bool,
175    /// Maximum refinement iterations
176    pub max_iterations: usize,
177    /// Maximum number of tri3 nodes the uniform refine step may create.
178    /// (The internal cap is `max_nodes / 4` tri3 nodes, to bound the FEM mesh
179    /// size for thin-walled sections whose uniform refinement would otherwise
180    /// explode and make the direct solver impractically slow.)
181    pub max_nodes: usize,
182}
183
184impl Default for MeshParams {
185    fn default() -> Self {
186        Self {
187            target_size: 0.01,
188            max_size: 0.02,
189            min_size: 0.001,
190            quality_threshold: 0.3,
191            use_delaunay: true,
192            max_iterations: 10,
193            max_nodes: 20000,
194        }
195    }
196}
197
198/// Generate mesh from a Section (outer boundary + holes).
199pub fn mesh_section(section: &Section, params: MeshParams) -> Mesh {
200    triangulate_section(section, params)
201}
202
203/// Generate mesh from a CompositeSection (multi-material).
204pub fn mesh_composite_section(composite: &CompositeSection, params: MeshParams) -> Mesh {
205    // For composite sections, we need to handle multiple materials
206    // For now, use the outer boundary and assign materials based on material groups
207    let mut mesh = triangulate_section(
208        &Section::new(composite.outer.clone(), composite.holes.clone()),
209        params,
210    );
211
212    // Assign material indices to elements based on centroid location
213    // This is a simplified approach - full implementation would use proper material regions
214    mesh.element_materials = vec![0; mesh.n_elements()];
215
216    mesh
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222    use crate::geometry::Point;
223
224    #[test]
225    fn mesh_quality_metrics() {
226        let mut mesh = Mesh::new();
227        mesh.nodes = vec![
228            Point::new(0.0, 0.0),
229            Point::new(1.0, 0.0),
230            Point::new(0.0, 1.0),
231            Point::new(1.0, 1.0),
232        ];
233        mesh.elements = vec![[0, 1, 2], [1, 3, 2]];
234
235        let quality = mesh.quality_metrics();
236        assert!(quality.min_angle > 0.0);
237        assert!(quality.max_angle <= 180.0);
238    }
239}