1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
use crate::float_types::Real;
use crate::mesh::Mesh;
use crate::mesh::polygon::Polygon;
use crate::mesh::vertex::Vertex;
use nalgebra::Point3;
use std::collections::HashMap;
use std::fmt::Debug;
impl<S: Clone + Debug + Send + Sync> Mesh<S> {
/// **Mathematical Foundation: True Laplacian Mesh Smoothing with Global Connectivity**
///
/// Implements proper discrete Laplacian smoothing using global mesh connectivity:
///
/// ## **Discrete Laplacian Operator**
/// For each vertex v with neighbors N(v):
/// ```text
/// L(v) = (1/|N(v)|) · Σ(n∈N(v)) (n - v)
/// ```
///
/// ## **Global Connectivity Benefits**
/// - **Proper Neighborhoods**: Uses actual mesh connectivity, not just polygon edges
/// - **Uniform Weighting**: Each neighbor contributes equally to smoothing
/// - **Boundary Detection**: Automatically detects and preserves mesh boundaries
/// - **Volume Preservation**: Better volume preservation than local smoothing
///
/// ## **Algorithm Improvements**
/// - **Epsilon-based Vertex Matching**: Robust floating-point coordinate handling
/// - **Manifold Preservation**: Ensures mesh topology is maintained
/// - **Feature Detection**: Can preserve sharp features based on neighbor count
pub fn laplacian_smooth(
&self,
lambda: Real,
iterations: usize,
preserve_boundaries: bool,
) -> Mesh<S> {
let (vertex_map, adjacency) = self.build_connectivity();
let mut smoothed_polygons = self.polygons.clone();
for iteration in 0..iterations {
// Build current vertex position mapping
let mut current_positions: HashMap<usize, Point3<Real>> = HashMap::new();
for polygon in &smoothed_polygons {
for vertex in &polygon.vertices {
// Find the global index for this position (with tolerance)
for (pos, idx) in &vertex_map.position_to_index {
if (vertex.pos - pos).norm() < vertex_map.epsilon {
current_positions.insert(*idx, vertex.pos);
break;
}
}
}
}
// Compute Laplacian for each vertex
let mut laplacian_updates: HashMap<usize, Point3<Real>> = HashMap::new();
for (&vertex_idx, neighbors) in &adjacency {
if let Some(¤t_pos) = current_positions.get(&vertex_idx) {
// Check if this is a boundary vertex
if preserve_boundaries && neighbors.len() < 4 {
// Boundary vertex - skip smoothing
laplacian_updates.insert(vertex_idx, current_pos);
continue;
}
// Compute neighbor average
let mut neighbor_sum = Point3::origin();
let mut valid_neighbors = 0;
for &neighbor_idx in neighbors {
if let Some(&neighbor_pos) = current_positions.get(&neighbor_idx) {
neighbor_sum += neighbor_pos.coords;
valid_neighbors += 1;
}
}
if valid_neighbors > 0 {
let neighbor_avg = neighbor_sum / valid_neighbors as Real;
let laplacian = neighbor_avg - current_pos;
let new_pos = current_pos + laplacian * lambda;
laplacian_updates.insert(vertex_idx, new_pos);
} else {
laplacian_updates.insert(vertex_idx, current_pos);
}
}
}
// Apply updates to mesh vertices
for polygon in &mut smoothed_polygons {
for vertex in &mut polygon.vertices {
// Find the global index for this vertex
for (pos, idx) in &vertex_map.position_to_index {
if (vertex.pos - pos).norm() < vertex_map.epsilon {
if let Some(&new_pos) = laplacian_updates.get(idx) {
vertex.pos = new_pos;
}
break;
}
}
}
// Recompute polygon plane and normals after smoothing
polygon.set_new_normal();
}
// Progress feedback for long smoothing operations
if iterations > 10 && iteration % (iterations / 10) == 0 {
eprintln!(
"Smoothing progress: {}/{} iterations",
iteration + 1,
iterations
);
}
}
Mesh::from_polygons(&smoothed_polygons, self.metadata.clone())
}
/// **Mathematical Foundation: Taubin Mesh Smoothing**
///
/// Implements Taubin's feature-preserving mesh smoothing algorithm, which reduces
/// shrinkage compared to standard Laplacian smoothing.
///
/// ## **Taubin's Algorithm**
/// This method involves two steps per iteration:
/// 1. **Shrinking Step**: Apply standard Laplacian smoothing with a positive factor `lambda`.
/// `v' = v + λ * L(v)`
/// 2. **Inflating Step**: Apply a second Laplacian step with a negative factor `mu`.
/// `v'' = v' + μ * L(v')`
///
/// Typically, `0 < λ < -μ`. A common choice is `mu = -λ / (1 - λ)`.
/// This combination effectively smooths the mesh while minimizing volume loss.
///
/// Returns a new, smoothed CSG object.
pub fn taubin_smooth(
&self,
lambda: Real,
mu: Real,
iterations: usize,
preserve_boundaries: bool,
) -> Mesh<S> {
let (vertex_map, adjacency) = self.build_connectivity();
let mut smoothed_polygons = self.polygons.clone();
for _ in 0..iterations {
// --- Lambda (shrinking) pass ---
let mut current_positions: HashMap<usize, Point3<Real>> = HashMap::new();
for polygon in &smoothed_polygons {
for vertex in &polygon.vertices {
for (pos, idx) in &vertex_map.position_to_index {
if (vertex.pos - pos).norm() < vertex_map.epsilon {
current_positions.insert(*idx, vertex.pos);
break;
}
}
}
}
let mut updates: HashMap<usize, Point3<Real>> = HashMap::new();
for (&vertex_idx, neighbors) in &adjacency {
if let Some(¤t_pos) = current_positions.get(&vertex_idx) {
if preserve_boundaries && neighbors.len() < 4 {
updates.insert(vertex_idx, current_pos);
continue;
}
let mut neighbor_sum = Point3::origin();
let mut valid_neighbors = 0;
for &neighbor_idx in neighbors {
if let Some(&neighbor_pos) = current_positions.get(&neighbor_idx) {
neighbor_sum += neighbor_pos.coords;
valid_neighbors += 1;
}
}
if valid_neighbors > 0 {
let neighbor_avg = neighbor_sum / valid_neighbors as Real;
let laplacian = neighbor_avg - current_pos;
updates.insert(vertex_idx, current_pos + laplacian * lambda);
}
}
}
for polygon in &mut smoothed_polygons {
for vertex in &mut polygon.vertices {
for (pos, idx) in &vertex_map.position_to_index {
if (vertex.pos - pos).norm() < vertex_map.epsilon {
if let Some(&new_pos) = updates.get(idx) {
vertex.pos = new_pos;
}
break;
}
}
}
}
// --- Mu (inflating) pass ---
current_positions.clear();
for polygon in &smoothed_polygons {
for vertex in &polygon.vertices {
for (pos, idx) in &vertex_map.position_to_index {
if (vertex.pos - pos).norm() < vertex_map.epsilon {
current_positions.insert(*idx, vertex.pos);
break;
}
}
}
}
updates.clear();
for (&vertex_idx, neighbors) in &adjacency {
if let Some(¤t_pos) = current_positions.get(&vertex_idx) {
if preserve_boundaries && neighbors.len() < 4 {
updates.insert(vertex_idx, current_pos);
continue;
}
let mut neighbor_sum = Point3::origin();
let mut valid_neighbors = 0;
for &neighbor_idx in neighbors {
if let Some(&neighbor_pos) = current_positions.get(&neighbor_idx) {
neighbor_sum += neighbor_pos.coords;
valid_neighbors += 1;
}
}
if valid_neighbors > 0 {
let neighbor_avg = neighbor_sum / valid_neighbors as Real;
let laplacian = neighbor_avg - current_pos;
updates.insert(vertex_idx, current_pos + laplacian * mu);
}
}
}
for polygon in &mut smoothed_polygons {
for vertex in &mut polygon.vertices {
for (pos, idx) in &vertex_map.position_to_index {
if (vertex.pos - pos).norm() < vertex_map.epsilon {
if let Some(&new_pos) = updates.get(idx) {
vertex.pos = new_pos;
}
break;
}
}
}
}
}
// Final pass to recompute normals
for polygon in &mut smoothed_polygons {
polygon.set_new_normal();
}
Mesh::from_polygons(&smoothed_polygons, self.metadata.clone())
}
/// **Mathematical Foundation: Adaptive Mesh Refinement**
///
/// Intelligently refine mesh based on geometric criteria:
///
/// ## **Refinement Criteria**
/// - **Quality threshold**: Refine triangles with quality score < threshold
/// - **Size variation**: Refine where edge lengths vary significantly
/// - **Curvature**: Refine high-curvature regions (based on normal variation)
/// - **Feature detection**: Preserve sharp edges and corners
///
/// ## **Refinement Strategy**
/// 1. **Quality-based**: Subdivide poor-quality triangles
/// 2. **Size-based**: Subdivide triangles larger than target size
/// 3. **Curvature-based**: Subdivide where surface curves significantly
///
/// This provides better mesh quality compared to uniform subdivision.
pub fn adaptive_refine(
&self,
quality_threshold: Real,
max_edge_length: Real,
curvature_threshold_deg: Real,
) -> Mesh<S> {
let qualities = self.analyze_triangle_quality();
let (mut vertex_map, _adjacency) = self.build_connectivity();
let mut refined_polygons = Vec::new();
let mut polygon_map: HashMap<usize, Vec<usize>> = HashMap::new();
for (poly_idx, poly) in self.polygons.iter().enumerate() {
for vertex in &poly.vertices {
let v_idx = vertex_map.get_or_create_index(vertex.pos);
polygon_map.entry(v_idx).or_default().push(poly_idx);
}
}
for (i, polygon) in self.polygons.iter().enumerate() {
let mut should_refine = false;
// Quality and edge length check
if i < qualities.len() {
let quality = &qualities[i];
if quality.quality_score < quality_threshold
|| Self::max_edge_length(&polygon.vertices) > max_edge_length
{
should_refine = true;
}
}
// Curvature check
if !should_refine {
'edge_loop: for edge in polygon.edges() {
let v1_idx = vertex_map.get_or_create_index(edge.0.pos);
let v2_idx = vertex_map.get_or_create_index(edge.1.pos);
if let (Some(p1_indices), Some(p2_indices)) =
(polygon_map.get(&v1_idx), polygon_map.get(&v2_idx))
{
for &p1_idx in p1_indices {
if p1_idx == i {
continue;
}
for &p2_idx in p2_indices {
if p1_idx == p2_idx {
let other_poly = &self.polygons[p1_idx];
let angle = Self::dihedral_angle(polygon, other_poly);
if angle > curvature_threshold_deg.to_radians() {
should_refine = true;
break 'edge_loop;
}
}
}
}
}
}
}
if should_refine {
let subdivided = polygon.subdivide_triangles(1.try_into().unwrap());
for triangle in subdivided {
let vertices = triangle.to_vec();
refined_polygons.push(Polygon::new(vertices, polygon.metadata.clone()));
}
} else {
refined_polygons.push(polygon.clone());
}
}
Mesh::from_polygons(&refined_polygons, self.metadata.clone())
}
/// Calculate maximum edge length in a polygon
fn max_edge_length(vertices: &[Vertex]) -> Real {
if vertices.len() < 2 {
return 0.0;
}
let mut max_length: Real = 0.0;
for i in 0..vertices.len() {
let j = (i + 1) % vertices.len();
let edge_length = (vertices[j].pos - vertices[i].pos).norm();
max_length = max_length.max(edge_length);
}
max_length
}
/// **Mathematical Foundation: Feature-Preserving Mesh Optimization**
///
/// Remove poor-quality triangles while preserving important geometric features:
///
/// ## **Quality-Based Filtering**
/// Remove triangles that meet criteria:
/// - **Sliver triangles**: min_angle < threshold (typically 5°)
/// - **Needle triangles**: aspect_ratio > threshold (typically 20)
/// - **Small triangles**: area < threshold
///
/// ## **Feature Preservation**
/// - **Sharp edges**: Preserve edges with large dihedral angles
/// - **Boundaries**: Maintain mesh boundaries
/// - **Topology**: Ensure mesh remains manifold
///
/// Returns cleaned mesh with improved triangle quality.
pub fn remove_poor_triangles(&self, min_quality: Real) -> Mesh<S> {
let qualities = self.analyze_triangle_quality();
let mut filtered_polygons = Vec::new();
for (i, polygon) in self.polygons.iter().enumerate() {
let keep_triangle = if i < qualities.len() {
let quality = &qualities[i];
quality.quality_score >= min_quality
&& quality.area > Real::EPSILON
&& quality.min_angle > (5.0 as Real).to_radians()
&& quality.aspect_ratio < 20.0
} else {
true // Keep if we can't assess quality
};
if keep_triangle {
filtered_polygons.push(polygon.clone());
}
}
Mesh::from_polygons(&filtered_polygons, self.metadata.clone())
}
}