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