meshlite/
mesh.rs

1use cgmath::Point3;
2use cgmath::Vector3;
3use cgmath::prelude::*;
4use cgmath::Matrix4;
5use std::option::Option;
6use std::io;
7use std::vec::Vec;
8use std::collections::HashMap;
9use std::collections::HashSet;
10use fnv::FnvHashSet;
11use fnv::FnvHashMap;
12use iterator::FaceHalfedgeIterator;
13use iterator::FaceIterator;
14use util::*;
15use smallvec::SmallVec;
16use std::ops::Add;
17use std::ops::AddAssign;
18use std::f32;
19
20pub type Id = usize;
21
22// Optimized for quad meshes, since that is very common in high-poly models
23// during editing. By subdividing some lower resolution model, pure quad models
24// are produced. It could be worth tweaking this constant for other use-cases
25// though, triangulation will create more halfedges for many vertices and would
26// benefit from a higher number, but that would consume more memory for all
27// meshes which would not be ideal. It could be worth having completely separate
28// implementations for quad, tri and polygon meshes at later time? Or maybe use
29// generics and/or macros to specialize some parts of the implementation?
30const VERTEX_HALFEDGE_INLINE_COUNT: usize = 4;
31
32#[derive(Debug)]
33pub struct Vertex {
34    pub id: Id,
35    pub position: Point3<f32>,
36
37    /// This is at the time of writing used as a set but is implemented using a
38    /// SmallVec. Finding or implementing something like a "SmallSet" could
39    /// provide a better API.
40    pub halfedges: SmallVec<[Id; VERTEX_HALFEDGE_INLINE_COUNT]>,
41
42    pub prev: Id,
43    pub next: Id,
44    pub alive: bool,
45    pub source: i32,
46}
47
48#[derive(Debug)]
49pub struct Face {
50    pub id: Id,
51    pub halfedge: Id,
52    pub prev: Id,
53    pub next: Id,
54    pub alive: bool,
55}
56
57#[derive(Debug)]
58pub struct Halfedge {
59    pub id: Id,
60    pub vertex: Id,
61    pub face: Id,
62    pub prev: Id,
63    pub next: Id,
64    pub opposite: Id,
65    pub alive: bool,
66}
67
68#[derive(Hash, Eq, PartialEq, Debug, Clone)]
69pub struct Point3Key {
70    x: u32,
71    y: u32,
72    z: u32,
73}
74
75impl Point3Key {
76    pub fn new(point: Point3<f32>) -> Self {
77        Point3Key {
78            x: (point.x * 1000.0).round() as u32,
79            y: (point.y * 1000.0).round() as u32,
80            z: (point.z * 1000.0).round() as u32,
81        }
82    }
83}
84
85#[derive(Hash, Eq, PartialEq, Debug, Clone)]
86pub struct EdgeEndpoints {
87    pub low: Id,
88    pub high: Id,
89}
90
91impl EdgeEndpoints {
92    pub fn new(first: Id, second: Id) -> Self {
93        if first < second {
94            EdgeEndpoints {
95                low: first,
96                high: second
97            }
98        } else {
99            EdgeEndpoints {
100                low: second,
101                high: first
102            }
103        }
104    }
105}
106
107pub type FacePair = EdgeEndpoints;
108
109#[derive(Debug)]
110pub struct Mesh {
111    pub vertices: Vec<Vertex>,
112    pub vertex_count: usize,
113    pub faces: Vec<Face>,
114    pub face_count: usize,
115    pub halfedges: Vec<Halfedge>,
116    pub halfedge_count: usize,
117    pub edges: FnvHashMap<EdgeEndpoints, Id>
118}
119
120impl Mesh {
121    pub fn new() -> Self {
122        Mesh {
123            vertices: Vec::new(),
124            vertex_count: 0,
125            faces: Vec::new(),
126            face_count: 0,
127            halfedges: Vec::new(),
128            halfedge_count: 0,
129            edges: FnvHashMap::default()
130        }
131    }
132
133    pub fn vertex(&self, id: Id) -> Option<&Vertex> {
134        if 0 == id {
135            return None;
136        }
137        {
138            let vertex = &self.vertices[id - 1];
139            if !vertex.alive {
140                return None;
141            }
142        }
143        Some(&self.vertices[id - 1])
144    }
145
146    pub fn vertex_mut(&mut self, id: Id) -> Option<&mut Vertex> {
147        if 0 == id {
148            return None;
149        }
150        {
151            let vertex = &self.vertices[id - 1];
152            if !vertex.alive {
153                return None;
154            }
155        }
156        Some(&mut self.vertices[id - 1])
157    }
158
159    pub fn peek_same_halfedge(&self, any_paired_id: Id) -> Id {
160        let halfedge = self.halfedge(any_paired_id).unwrap();
161        if halfedge.opposite > 0 && halfedge.opposite < any_paired_id {
162            return halfedge.opposite;
163        }
164        any_paired_id
165    }
166
167    pub fn edge_center(&self, id: Id) -> Point3<f32> {
168        let halfedge = self.halfedge(id).unwrap();
169        let next = self.halfedge(halfedge.next).unwrap();
170        Point3::midpoint(self.vertex(halfedge.vertex).unwrap().position,
171            self.vertex(next.vertex).unwrap().position)
172    }
173
174    pub fn face_center(&self, id: Id) -> Point3<f32> {
175        let face = self.face(id).unwrap();
176        let mut points = SmallVec::<[Point3<f32>; 4]>::new();
177        for halfedge_id in FaceHalfedgeIterator::new(self, face.halfedge) {
178            let halfedge = self.halfedge(halfedge_id).unwrap();
179            let vertex = self.vertex(halfedge.vertex).unwrap();
180            points.push(vertex.position);
181        }
182        Point3::centroid(&points)
183    }
184
185    pub fn face_norm(&self, id: Id) -> Vector3<f32> {
186        let face = self.face(id).unwrap();
187        let mut points = Vec::new();
188        for halfedge_id in FaceHalfedgeIterator::new(self, face.halfedge) {
189            let halfedge = self.halfedge(halfedge_id).unwrap();
190            let vertex = self.vertex(halfedge.vertex).unwrap();
191            points.push(vertex.position);
192        }
193        if points.len() < 3 {
194            return Vector3::zero();
195        } else if points.len() == 3 {
196            return norm(points[0], points[1], points[2]);
197        }
198        let mut total = Vector3::zero();
199        for i in 0..points.len() {
200            let n = norm(points[i], points[(i + 1) % points.len()], points[(i + 2) % points.len()]);
201            total += n;
202        }
203        total.normalize()
204    }
205
206    pub fn face(&self, id: Id) -> Option<&Face> {
207        if 0 == id {
208            return None;
209        }
210        {
211            let face = &self.faces[id - 1];
212            if !face.alive {
213                return None;
214            }
215        }
216        Some(&self.faces[id - 1])
217    }
218
219    pub fn face_adj_id(&self, id: Id) -> Option<Id> {
220        self.face(id)
221            .and_then(|f: &Face| self.halfedge(f.halfedge))
222            .and_then(|h: &Halfedge| self.halfedge(h.opposite))
223            .and_then(|o: &Halfedge| if 0 != o.face { Some(o.face) } else { None })
224    }
225
226    pub fn face_adj(&self, id: Id) -> Option<&Face> {
227        self.face_adj_id(id).and_then(|id: Id| self.face(id))
228    }
229
230    pub fn halfedge_next_id(&self, id: Id) -> Option<Id> {
231        self.halfedge(id)
232            .and_then(|h: &Halfedge| if 0 != h.next { Some(h.next) } else { None })
233    }
234
235    pub fn halfedge_prev_id(&self, id: Id) -> Option<Id> {
236        self.halfedge(id)
237            .and_then(|h: &Halfedge| if 0 != h.prev { Some(h.prev) } else { None })
238    }
239
240    pub fn halfedge_opposite_id(&self, id: Id) -> Option<Id> {
241        self.halfedge(id)
242            .and_then(|h: &Halfedge| if 0 != h.opposite { Some(h.opposite) } else { None })
243    }
244
245    pub fn face_first_halfedge_id(&self, id: Id) -> Option<Id> {
246        self.face(id)
247            .and_then(|f: &Face| if 0 != f.halfedge { Some(f.halfedge) } else { None })
248    }
249
250    pub fn halfedge_start_vertex_id(&self, id: Id) -> Option<Id> {
251        self.halfedge(id)
252            .and_then(|h: &Halfedge| if 0 != h.vertex { Some(h.vertex) } else { None })
253    }
254
255    pub fn halfedge_face_id(&self, id: Id) -> Option<Id> {
256        self.halfedge(id)
257            .and_then(|h: &Halfedge| if 0 != h.face { Some(h.face) } else { None })
258    }
259
260    pub fn halfedge_opposite_face_id(&self, id: Id) -> Option<Id> {
261        let opposite_id = self.halfedge_opposite_id(id);
262        if opposite_id.is_none() {
263            return None;
264        }
265        self.halfedge_face_id(opposite_id.unwrap())
266    }
267
268    pub fn halfedge_direct(&self, id: Id) -> Vector3<f32> {
269        let begin_pos = self.halfedge_start_vertex(id).unwrap().position;
270        let end_pos = self.halfedge_start_vertex(self.halfedge_next_id(id).unwrap()).unwrap().position;
271        end_pos - begin_pos
272    }
273
274    pub fn set_halfedge_start_vertex_id(&mut self, halfedge_id: Id, vertex_id: Id) {
275        self.halfedge_mut(halfedge_id).unwrap().vertex = vertex_id;
276    }
277
278    pub fn halfedge_start_vertex_mut(&mut self, id: Id) -> Option<&mut Vertex> {
279        let vertex_id = self.halfedge_start_vertex_id(id)?;
280        self.vertex_mut(vertex_id)
281    }
282
283    pub fn halfedge_start_vertex(&self, id: Id) -> Option<&Vertex> {
284        let vertex_id = self.halfedge_start_vertex_id(id)?;
285        self.vertex(vertex_id)
286    }
287
288    pub fn set_halfedge_opposite_id(&mut self, halfedge_id: Id, opposite_id: Id) {
289        let halfedge = self.halfedge_mut(halfedge_id);
290        if halfedge.is_none() {
291            return;
292        }
293        halfedge.unwrap().opposite = opposite_id;
294    }
295
296    fn remove_halfedges_from_edges(&mut self, halfedges: &Vec<Id>) {
297        for &halfedge_id in halfedges {
298            let opposite = self.halfedge_opposite_id(halfedge_id);
299            let next_halfedge_id = self.halfedge_next_id(halfedge_id).unwrap();
300            let endpoints = EdgeEndpoints::new(self.halfedge_start_vertex_id(halfedge_id).unwrap(), 
301                self.halfedge_start_vertex_id(next_halfedge_id).unwrap());
302            if let Some(&id) = self.edges.get(&endpoints) {
303                if id == halfedge_id {
304                    if !opposite.is_none() {
305                        *self.edges.get_mut(&endpoints).unwrap() = opposite.unwrap();
306                    } else {
307                        self.edges.remove(&endpoints);
308                    }
309                }
310            }
311        }
312    }
313
314    pub fn halfedge_start_vertex_alt_halfedge_id(&self, halfedge_id: Id) -> Option<Id> {
315        let opposite = self.halfedge_opposite_id(halfedge_id);
316        if !opposite.is_none() {
317            let next_id = self.halfedge_next_id(opposite.unwrap());
318            if next_id.is_some() {
319                return next_id;
320            }
321        }
322        let prev = self.halfedge_prev_id(halfedge_id);
323        if !prev.is_none() {
324            return self.halfedge_opposite_id(prev.unwrap());
325        }
326        None
327    }
328
329    pub fn remove_face(&mut self, id: Id) {
330        let halfedge_collection = FaceHalfedgeIterator::new(self, self.face_first_halfedge_id(id).unwrap()).into_vec();
331        self.remove_halfedges_from_edges(&halfedge_collection);
332        for &halfedge_id in halfedge_collection.iter() {
333            let vertex_count_need_reduce = {
334                let vertex = self.halfedge_start_vertex_mut(halfedge_id).unwrap();
335                for i in 0..vertex.halfedges.len() {
336                    if halfedge_id == vertex.halfedges[i] {
337                        vertex.halfedges.remove(i);
338                        break;
339                    }
340                }
341                if vertex.halfedges.is_empty() {
342                    vertex.alive = false;
343                    true
344                } else {
345                    false
346                }
347            };
348            if vertex_count_need_reduce {
349                self.vertex_count -= 1;
350            }
351        }
352        for &halfedge_id in halfedge_collection.iter() {
353            let opposite = self.halfedge_opposite_id(halfedge_id);
354            if !opposite.is_none() {
355                self.set_halfedge_opposite_id(opposite.unwrap(), 0);
356            }
357            self.halfedge_mut(halfedge_id).unwrap().alive = false;
358            self.halfedge_count -= 1;
359        }
360        self.face_mut(id).unwrap().alive = false;
361        self.face_count -= 1;
362    }
363
364    pub fn face_mut(&mut self, id: Id) -> Option<&mut Face> {
365        if 0 == id {
366            return None;
367        }
368        {
369            let face = &self.faces[id - 1];
370            if !face.alive {
371                return None;
372            }
373        }
374        Some(&mut self.faces[id - 1])
375    }
376
377    pub fn halfedge(&self, id: Id) -> Option<&Halfedge> {
378        if 0 == id {
379            return None;
380        }
381        {
382            let halfedge = &self.halfedges[id - 1];
383            if !halfedge.alive {
384                return None;
385            }
386        }
387        Some(&self.halfedges[id - 1])
388    }
389
390    pub fn halfedge_mut(&mut self, id: Id) -> Option<&mut Halfedge> {
391        if 0 == id {
392            return None;
393        }
394        {
395            let halfedge = &self.halfedges[id - 1];
396            if !halfedge.alive {
397                return None;
398            }
399        }
400        Some(&mut self.halfedges[id - 1])
401    }
402
403    pub fn add_vertex(&mut self, position: Point3<f32>) -> usize {
404        let new_id = self.vertices.len() + 1;
405        self.vertices.push(Vertex {
406            id: new_id,
407            halfedges: SmallVec::<[Id; VERTEX_HALFEDGE_INLINE_COUNT]>::new(),
408            prev: 0,
409            next: 0,
410            position : position,
411            alive: true,
412            source: -1,
413        });
414        self.vertex_count += 1;
415        new_id
416    }
417
418    pub fn add_halfedge(&mut self) -> Id {
419        let new_id = self.halfedges.len() + 1;
420        self.halfedges.push(Halfedge {
421            id: new_id,
422            vertex: 0,
423            face: 0,
424            prev: 0,
425            next: 0,
426            opposite: 0,
427            alive: true,
428        });
429        self.halfedge_count += 1;
430        new_id
431    }
432
433    pub fn pair_halfedges(&mut self, first: Id, second: Id) {
434        self.halfedge_mut(first).unwrap().opposite = second;
435        self.halfedge_mut(second).unwrap().opposite = first;
436    }
437
438    pub fn unpair_halfedges(&mut self, first: Id, second: Id) {
439        self.halfedge_mut(first).unwrap().opposite = 0;
440        self.halfedge_mut(second).unwrap().opposite = 0;
441    }
442
443    pub fn link_halfedges(&mut self, first: Id, second: Id) {
444        self.halfedge_mut(first).unwrap().next = second;
445        self.halfedge_mut(second).unwrap().prev = first;
446        let endpoints = EdgeEndpoints::new(self.halfedge(first).unwrap().vertex,
447            self.halfedge(second).unwrap().vertex);
448        match self.edges.get(&endpoints) {
449            Some(&halfedge) => self.pair_halfedges(first, halfedge),
450            _ => {
451                self.edges.insert(endpoints, first);
452            }
453        };
454    }
455
456    pub fn add_face(&mut self) -> Id {
457        let new_id = self.faces.len() + 1;
458        self.faces.push(Face {
459            id: new_id,
460            halfedge: 0,
461            prev: 0,
462            next: 0,
463            alive: true,
464        });
465        self.face_count += 1;
466        new_id
467    }
468
469    pub fn add_linked_vertices(&mut self, linked_vertices: &mut HashMap<Id, Id>) -> Id {
470        if linked_vertices.len() == 0 {
471            return 0;
472        }
473        let (&first_id, _) = linked_vertices.iter().next().unwrap();
474        let mut vert = first_id;
475        let mut visited_sets = FnvHashSet::default();
476        let mut added_vertices = Vec::new();
477        added_vertices.push(first_id);
478        visited_sets.insert(first_id);
479        //println!("first_id {:?}", first_id);
480        while linked_vertices.contains_key(&vert) && linked_vertices[&vert] != first_id {
481            vert = linked_vertices[&vert];
482            //println!("vert {:?}", vert);
483            if visited_sets.contains(&vert) {
484                //println!("visited_sets.contains {:?}", vert);
485                return 0;
486            }
487            visited_sets.insert(vert);
488            added_vertices.push(vert);
489        }
490        for vert_id in added_vertices.iter() {
491            linked_vertices.remove(vert_id);
492        }
493        self.add_vertices(added_vertices)
494    }
495
496    pub fn add_vertices(&mut self, added_vertices : Vec<Id>) -> Id {
497        assert!(added_vertices.len() < 1000);
498        if added_vertices.is_empty() {
499            return 0;
500        }
501        let mut added_halfedges : Vec<(Id, Id)> = Vec::new();
502        for i in 0..added_vertices.len() {
503            if self.vertex(added_vertices[i]).is_none() {
504                return 0;
505            }
506        }
507        for i in 0..added_vertices.len() {
508            added_halfedges.push((self.add_halfedge(), added_vertices[i]));
509        }
510        self.add_halfedges_and_vertices(&added_halfedges)
511    }
512
513    pub fn add_positions(&mut self, added_positions : Vec<Point3<f32>>) -> Id {
514        if added_positions.is_empty() {
515            return 0;
516        }
517        let mut added_vertices : Vec<Id> = Vec::new();
518        for i in 0..added_positions.len() {
519            added_vertices.push(self.add_vertex(added_positions[i]));
520        }
521        self.add_vertices(added_vertices)
522    }
523
524    pub fn add_halfedges_and_vertices(&mut self, added_halfedges: &[(Id, Id)]) -> Id {
525        assert!(added_halfedges.len() < 1000);
526        if added_halfedges.is_empty() {
527            return 0;
528        }
529        let added_face_id = self.add_face();
530        for &(added_halfedge_id, added_vertex_id) in added_halfedges.iter() {
531            {
532                let vert = self.vertex_mut(added_vertex_id).unwrap();
533                let halfedges = &mut vert.halfedges;
534                if !halfedges.contains(&added_halfedge_id) {
535                    halfedges.push(added_halfedge_id);
536                }
537            }
538            self.halfedge_mut(added_halfedge_id).unwrap().face = added_face_id;
539            self.halfedge_mut(added_halfedge_id).unwrap().vertex = added_vertex_id;
540        }
541        self.face_mut(added_face_id).unwrap().halfedge = added_halfedges[0].0;
542        for i in 0..added_halfedges.len() {
543            let first = added_halfedges[i].0;
544            let second = added_halfedges[(i + 1) % added_halfedges.len()].0;
545            self.link_halfedges(first, second);
546        }
547        added_face_id
548    }
549
550    pub fn extrude_halfedges(&mut self, halfedges: &Vec<Id>, normal: Vector3<f32>, amount: f32) {
551        let mut downside_halfedges: Vec<Id> = Vec::new();
552        let mut downside_vertices: Vec<Id> = Vec::new();
553        let direct = normal * amount;
554        let mut need_fill_downside = false;
555        for &halfedge_id in halfedges {
556            let opposite = self.halfedge_opposite_id(halfedge_id);
557            if opposite.is_none() {
558                let old_position = {
559                    let mut vertex = self.halfedge_start_vertex_mut(halfedge_id).unwrap();
560                    let position = vertex.position;
561                    vertex.position += direct;
562                    position
563                };
564                downside_vertices.push(self.add_vertex(old_position));
565                downside_halfedges.push(self.add_halfedge());
566                need_fill_downside = true;
567            } else {
568                let old_vertex_id = self.halfedge_start_vertex_id(halfedge_id).unwrap();
569                let copy_position = self.halfedge_start_vertex(halfedge_id).unwrap().position;
570                let copy_vertex = self.add_vertex(copy_position);
571                {
572                    let vertex_count_need_reduce = {
573                        let vertex = self.halfedge_start_vertex_mut(old_vertex_id).unwrap();
574                        for i in 0..vertex.halfedges.len() {
575                            if vertex.halfedges[i] == halfedge_id {
576                                vertex.halfedges.remove(i);
577                                break;
578                            }
579                        }
580                        if vertex.halfedges.is_empty() {
581                            vertex.alive = false;
582                            true
583                        } else {
584                            false
585                        }
586                    };
587                    if vertex_count_need_reduce {
588                        self.vertex_count -= 1;
589                    }
590                }
591                self.set_halfedge_start_vertex_id(halfedge_id, copy_vertex);
592                self.unpair_halfedges(halfedge_id, opposite.unwrap());
593                downside_vertices.push(old_vertex_id);
594                downside_halfedges.push(opposite.unwrap());
595            }
596        }
597        for i in 0..halfedges.len() {
598            let halfedge_id = halfedges[i];
599            let i_next = (i + 1) % halfedges.len();
600            let next_halfedge_id = halfedges[i_next];
601            let mut added_halfedges : Vec<(Id, Id)> = Vec::new();
602            let left_bottom = downside_vertices[i];
603            let right_bottom = downside_vertices[i_next];
604            let right_top = self.halfedge_start_vertex_id(next_halfedge_id).unwrap();
605            let left_top = self.halfedge_start_vertex_id(halfedge_id).unwrap();
606            added_halfedges.push((self.add_halfedge(), left_bottom));
607            added_halfedges.push((self.add_halfedge(), right_bottom));
608            added_halfedges.push((self.add_halfedge(), right_top));
609            added_halfedges.push((self.add_halfedge(), left_top));
610            self.add_halfedges_and_vertices(&added_halfedges);
611        }
612        if need_fill_downside {
613            let mut added_halfedges : Vec<(Id, Id)> = Vec::new();
614            for i in 0..halfedges.len() {
615                let j = (halfedges.len() - i) % halfedges.len();
616                added_halfedges.push((downside_halfedges[j], downside_vertices[j]));
617            }
618            self.add_halfedges_and_vertices(&added_halfedges);
619        }
620    }
621
622    pub fn extrude_face(&mut self, face_id: Id, normal: Vector3<f32>, amount: f32) -> &mut Self {
623        let mut new_halfedges : Vec<Id> = Vec::new();
624        for halfedge_id in FaceHalfedgeIterator::new(self, face_id) {
625            new_halfedges.push(halfedge_id);
626        }
627        self.extrude_halfedges(&new_halfedges, normal, amount);
628        self
629    }
630
631    pub fn add_plane(&mut self, width: f32, depth: f32) -> Id {
632        let x = width / 2.0;
633        let y = depth / 2.0;
634        let points = vec![Point3 {x: -x, y: -y, z: 0.0},
635            Point3 {x: x, y: -y, z: 0.0},
636            Point3 {x: x, y: y, z: 0.0},
637            Point3 {x: -x, y: y, z: 0.0}];
638        let mut added_halfedges : Vec<(Id, Id)> = Vec::new();
639        for i in 0..points.len() {
640            added_halfedges.push((self.add_halfedge(), self.add_vertex(points[i])));
641        }
642        self.add_halfedges_and_vertices(&added_halfedges)
643    }
644
645    pub fn transform(&mut self, mat: &Matrix4<f32>) -> &mut Self {
646        for vertex in self.vertices.iter_mut() {
647            vertex.position = mat.transform_point(vertex.position);
648        }
649        self
650    }
651
652    pub fn translate(&mut self, x: f32, y: f32, z: f32) -> &mut Self {
653        let mat = Matrix4::from_translation(Vector3::new(x, y, z));
654        self.transform(&mat)
655    }
656
657    pub fn scale(&mut self, value: f32) -> &mut Self {
658        let mat = Matrix4::from_scale(value);
659        self.transform(&mat)
660    }
661
662    pub fn weld(&self) -> Self {
663        let mut new_mesh = Mesh::new();
664        let mut vertices_set : HashMap<Point3Key, Id> = HashMap::new();
665        for face_id in FaceIterator::new(&self) {
666            let face = self.face(face_id).unwrap();
667            let mut key_set : HashSet<Point3Key> = HashSet::new();
668            let mut positions : Vec<(Point3<f32>, i32)> = Vec::new();
669            for halfedge_id in FaceHalfedgeIterator::new(&self, face.halfedge) {
670                let vertex = self.halfedge_start_vertex(halfedge_id).unwrap();
671                let key = Point3Key::new(vertex.position);
672                if key_set.contains(&key) {
673                    continue;
674                }
675                key_set.insert(key);
676                positions.push((vertex.position, vertex.source));
677            }
678            if positions.len() < 3 {
679                continue;
680            }
681            let mut added_vertices : Vec<Id> = Vec::new();
682            for &(pos, source) in positions.iter() {
683                let key = Point3Key::new(pos);
684                let new_vert_id = *vertices_set.entry(key).or_insert_with(|| {
685                    let new_added_vert_id = new_mesh.add_vertex(pos);
686                    new_mesh.vertex_mut(new_added_vert_id).unwrap().source = source;
687                    new_added_vert_id
688                });
689                added_vertices.push(new_vert_id);
690            }
691            new_mesh.add_vertices(added_vertices);
692        }
693        new_mesh
694    }
695
696    pub fn add_mesh(&mut self, other: &Mesh) {
697        let mut vertices_set : HashMap<Id, Id> = HashMap::new();
698        for face_id in FaceIterator::new(&other) {
699            let face = other.face(face_id).unwrap();
700            let mut added_halfedges : Vec<(Id, Id)> = Vec::new();
701            for halfedge_id in FaceHalfedgeIterator::new(&other, face.halfedge) {
702                let vertex = other.halfedge_start_vertex(halfedge_id).unwrap();
703                let key = vertex.id;
704                if let Some(&new_vertex_id) = vertices_set.get(&key) {
705                    added_halfedges.push((self.add_halfedge(), new_vertex_id));
706                } else {
707                    let new_vertex_id = self.add_vertex(vertex.position);
708                    self.vertex_mut(new_vertex_id).unwrap().source = vertex.source;
709                    vertices_set.insert(key, new_vertex_id);
710                    added_halfedges.push((self.add_halfedge(), new_vertex_id));
711                }
712            }
713            self.add_halfedges_and_vertices(&added_halfedges);
714        }
715    }
716
717    pub fn flip_mesh(&self) -> Mesh {
718        let mut new_mesh = Mesh::new();
719        let mut new_vert_map = HashMap::new();
720        for face_id in FaceIterator::new(self) {
721            let mut verts = Vec::new();
722            for halfedge_id in FaceHalfedgeIterator::new(self, self.face_first_halfedge_id(face_id).unwrap()) {
723                let old_vert = self.halfedge_start_vertex(halfedge_id).unwrap();
724                let new_vert_id = new_vert_map.entry(old_vert.id).or_insert_with(|| {
725                    let new_added_vert_id = new_mesh.add_vertex(old_vert.position);
726                    new_mesh.vertex_mut(new_added_vert_id).unwrap().source = old_vert.source;
727                    new_added_vert_id
728                });
729                verts.push(*new_vert_id);
730            }
731            let mut added_halfedges : Vec<(Id, Id)> = Vec::new();
732            for new_vert_id in verts.iter().rev() {
733                added_halfedges.push((new_mesh.add_halfedge(), *new_vert_id));
734            }
735            new_mesh.add_halfedges_and_vertices(&added_halfedges);
736        }
737        new_mesh
738    }
739
740    pub fn split_mesh_by_other(&self, other: &Mesh) -> (Mesh, Mesh) {
741        let mut inner_mesh = Mesh::new();
742        let mut outter_mesh = Mesh::new();
743        inner_mesh.add_mesh(self);
744        for face_id in FaceIterator::new(other) {
745            let norm = other.face_norm(face_id);
746            let point = other.halfedge_start_vertex(other.face_first_halfedge_id(face_id).unwrap()).unwrap().position;
747            let (sub_front, sub_back) = inner_mesh.split_mesh_by_plane(point, norm, false);
748            inner_mesh = sub_back;
749            outter_mesh.add_mesh(&sub_front);
750        }
751        (outter_mesh, inner_mesh)
752    }
753
754    pub fn union_convex_mesh(&self, other: &Mesh) -> Mesh {
755        let (other_outter, _) = other.split_mesh_by_other(self);
756        let (my_outter, _) = self.split_mesh_by_other(other);
757        let mesh = other_outter + my_outter;
758        mesh.weld().fix_tjunction().combine_adj_faces()
759    }
760
761    pub fn diff_convex_mesh(&self, other: &Mesh) -> Mesh {
762        let (_, other_inner) =  other.split_mesh_by_other(self);
763        let (my_outter, _) = self.split_mesh_by_other(other);
764        let mesh = other_inner.flip_mesh() + my_outter;
765        mesh.weld().fix_tjunction().combine_adj_faces()
766    }
767
768    pub fn intersect_convex_mesh(&self, other: &Mesh) -> Mesh {
769        let (_, other_inner) =  other.split_mesh_by_other(self);
770        let (_, my_inner) = self.split_mesh_by_other(other);
771        let mesh = other_inner + my_inner;
772        mesh.weld().fix_tjunction().combine_adj_faces()
773    }
774
775    pub fn split_mesh_by_plane(&self, pt_on_plane: Point3<f32>, norm: Vector3<f32>, fill_cut: bool) -> (Mesh, Mesh) { 
776        let mut vert_side_map : HashMap<Id, PointSide> = HashMap::new();
777        for face_id in FaceIterator::new(self) {
778            for halfedge_id in FaceHalfedgeIterator::new(self, self.face_first_halfedge_id(face_id).unwrap()) {
779                let vert = self.halfedge_start_vertex(halfedge_id).unwrap();
780                vert_side_map.entry(vert.id).or_insert(point_side_on_plane(vert.position, pt_on_plane, norm));
781            }
782        }
783        let mut front_mesh = Mesh::new();
784        let mut back_mesh = Mesh::new();
785        let mut front_vert_map : HashMap<Id, Id> = HashMap::new();
786        let mut back_vert_map : HashMap<Id, Id> = HashMap::new();
787        let mut intersect_map : HashMap<EdgeEndpoints, SegmentPlaneIntersect> = HashMap::new();
788        let mut front_intersect_map : HashMap<EdgeEndpoints, Id> = HashMap::new();
789        let mut back_intersect_map : HashMap<EdgeEndpoints, Id> = HashMap::new();
790        let mut front_cut_map : HashMap<Id, Id> = HashMap::new();
791        let mut back_cut_map : HashMap<Id, Id> = HashMap::new();
792        for face_id in FaceIterator::new(self) {
793            let mut front_new_verts = Vec::new();
794            let mut back_new_verts = Vec::new();
795            let mut front_new_vert_set = HashSet::new();
796            let mut back_new_vert_set = HashSet::new();
797            let mut front_intersects = vec![0, 0];
798            let mut back_intersects = vec![0, 0];
799            for halfedge_id in FaceHalfedgeIterator::new(self, self.face_first_halfedge_id(face_id).unwrap()) {
800                let from_vert_id = self.halfedge_start_vertex_id(halfedge_id).unwrap();
801                let to_vert_id = self.halfedge_start_vertex_id(self.halfedge_next_id(halfedge_id).unwrap()).unwrap();
802                let from_is_front = vert_side_map[&from_vert_id] != PointSide::Back;
803                let to_is_front = vert_side_map[&to_vert_id] != PointSide::Back;
804                let from_is_back = vert_side_map[&from_vert_id] != PointSide::Front;
805                let to_is_back = vert_side_map[&to_vert_id] != PointSide::Front;
806                let edge = EdgeEndpoints::new(from_vert_id, to_vert_id);
807                if from_is_front {
808                    let new_vert_id = *front_vert_map.entry(from_vert_id).or_insert_with(|| {
809                        front_mesh.add_vertex(self.vertex(from_vert_id).unwrap().position)
810                    });
811                    if front_new_vert_set.insert(new_vert_id) {
812                        front_new_verts.push(new_vert_id);
813                    }
814                }
815                if from_is_back {
816                    let new_vert_id = *back_vert_map.entry(from_vert_id).or_insert_with(|| {
817                        back_mesh.add_vertex(self.vertex(from_vert_id).unwrap().position)
818                    });
819                    if back_new_vert_set.insert(new_vert_id) {
820                        back_new_verts.push(new_vert_id);
821                    }
822                }
823                if (from_is_front && to_is_back) || (from_is_back && to_is_front) {
824                    let intersect = intersect_map.entry(edge.clone()).or_insert_with(|| {
825                        let p0 = self.vertex(from_vert_id).unwrap().position;
826                        let p1 = self.vertex(to_vert_id).unwrap().position;
827                        intersect_of_segment_and_plane(p0, p1, pt_on_plane, norm)
828                    });
829                    if let SegmentPlaneIntersect::Intersection(intersect_pt) = *intersect {
830                        if from_is_front || to_is_front {
831                            let new_vert_id = *front_intersect_map.entry(edge.clone()).or_insert_with(|| {
832                                front_mesh.add_vertex(intersect_pt)
833                            });
834                            if front_new_vert_set.insert(new_vert_id) {
835                                front_new_verts.push(new_vert_id);
836                            }
837                            if from_is_front {
838                                front_intersects[0] = new_vert_id;
839                            }
840                            if to_is_front {
841                                front_intersects[1] = new_vert_id;
842                            }
843                        }
844                        if from_is_back || to_is_back {
845                            let new_vert_id = *back_intersect_map.entry(edge.clone()).or_insert_with(|| {
846                                back_mesh.add_vertex(intersect_pt)
847                            });
848                            if back_new_vert_set.insert(new_vert_id) {
849                                back_new_verts.push(new_vert_id);
850                            }
851                            if from_is_front {
852                                back_intersects[0] = new_vert_id;
853                            }
854                            if to_is_front {
855                                back_intersects[1] = new_vert_id;
856                            }
857                        }
858                    }
859                }
860                if to_is_front {
861                    let new_vert_id = *front_vert_map.entry(to_vert_id).or_insert_with(|| {
862                        front_mesh.add_vertex(self.vertex(to_vert_id).unwrap().position)
863                    });
864                    if front_new_vert_set.insert(new_vert_id) {
865                        front_new_verts.push(new_vert_id);
866                    }
867                }
868                if to_is_back {
869                    let new_vert_id = *back_vert_map.entry(to_vert_id).or_insert_with(|| {
870                        back_mesh.add_vertex(self.vertex(to_vert_id).unwrap().position)
871                    });
872                    if back_new_vert_set.insert(new_vert_id) {
873                        back_new_verts.push(new_vert_id);
874                    }
875                }
876            }
877            if front_new_verts.len() >= 3 {
878                front_mesh.add_vertices(front_new_verts);
879            }
880            if back_new_verts.len() >= 3 {
881                back_mesh.add_vertices(back_new_verts);
882            }
883            if front_intersects[0] > 0 && front_intersects[1] > 0 {
884                front_cut_map.insert(front_intersects[1], front_intersects[0]);
885            }
886            if back_intersects[0] > 0 && back_intersects[1] > 0 {
887                back_cut_map.insert(back_intersects[0], back_intersects[1]);
888            }
889        }
890        if fill_cut {
891            if front_cut_map.len() >= 3 {
892                while front_mesh.add_linked_vertices(&mut front_cut_map) > 0 {};
893            }
894            if back_cut_map.len() >= 3 {
895                while back_mesh.add_linked_vertices(&mut back_cut_map) > 0 {};
896            }
897        }
898        (front_mesh, back_mesh)
899    }
900
901    fn split_halfedge(&mut self, halfedge_id: Id, vertex_id: Id) -> Id {
902        let (face_id, next_halfedge_id) = {
903            let halfedge = self.halfedge(halfedge_id).unwrap();
904            (halfedge.face, halfedge.next)
905        };
906        let new_halfedge_id = self.add_halfedge();
907        {
908            let new_halfedge = self.halfedge_mut(new_halfedge_id).unwrap();
909            new_halfedge.vertex = vertex_id;
910            new_halfedge.face = face_id;
911        }
912        self.link_halfedges(new_halfedge_id, next_halfedge_id);
913        self.link_halfedges(halfedge_id, new_halfedge_id);
914        new_halfedge_id
915    }
916
917    pub fn fix_tjunction(&mut self) -> &mut Self {
918        let mut may_broken_halfedges = Vec::new();
919        for face_id in FaceIterator::new(self) {
920            for halfedge_id in FaceHalfedgeIterator::new(self, self.face_first_halfedge_id(face_id).unwrap()) {
921                if self.halfedge_opposite_id(halfedge_id).is_none() {
922                    may_broken_halfedges.push(halfedge_id);
923                }
924            }
925        }
926        let mut i = 0;
927        'outer: while i < may_broken_halfedges.len() {
928            'inner: for j in 0..may_broken_halfedges.len() {
929                let long_id = may_broken_halfedges[i];
930                let short_id = may_broken_halfedges[j];
931                if long_id == short_id {
932                    continue;
933                }
934                if !self.halfedge_opposite_id(long_id).is_none() {
935                    continue;
936                }
937                let long_begin = self.halfedge_start_vertex(long_id).unwrap().position;
938                let long_end = self.halfedge_start_vertex(self.halfedge_next_id(long_id).unwrap()).unwrap().position;
939                
940                let (short_begin_pos, short_begin_vert_id) = {
941                    let vert = self.halfedge_start_vertex(short_id).unwrap();
942                    (vert.position, vert.id)
943                };
944                if is_point_on_segment(short_begin_pos, long_begin, long_end) {
945                    may_broken_halfedges.push(self.split_halfedge(long_id, short_begin_vert_id));
946                    continue 'outer;
947                }
948
949                let (short_end_pos, short_end_vert_id) = {
950                    let vert = self.halfedge_start_vertex(self.halfedge_next_id(short_id).unwrap()).unwrap();
951                    (vert.position, vert.id)
952                };
953                if is_point_on_segment(short_end_pos, long_begin, long_end) {
954                    may_broken_halfedges.push(self.split_halfedge(long_id, short_end_vert_id));
955                    continue 'outer;
956                }
957            }
958            i += 1;
959        }
960        self
961    }
962
963    pub fn remove_extra_vertices(&self) -> Self {
964        let from_mesh = self;
965        let mut to_mesh = Mesh::new();
966        let mut extra_vertices : HashSet<Id> = HashSet::new();
967        for (_, &halfedge_id) in from_mesh.edges.iter() {
968            let vert_id = from_mesh.halfedge_start_vertex_id(halfedge_id).unwrap();
969            let prev_id = from_mesh.halfedge_prev_id(halfedge_id).unwrap();
970            let prev_opposite_id = from_mesh.halfedge_opposite_id(prev_id);
971            let opposite_id = from_mesh.halfedge_opposite_id(halfedge_id);
972            if opposite_id.is_none() && prev_opposite_id.is_none() {
973                extra_vertices.insert(vert_id);
974            } else if let Some(opposite_id_val) = opposite_id {
975                if from_mesh.halfedge_next_id(opposite_id_val) == prev_opposite_id {
976                    extra_vertices.insert(vert_id);
977                }
978            }
979        }
980        let mut new_vert_map : HashMap<Id, Id> = HashMap::new();
981        for face_id in FaceIterator::new(from_mesh) {
982            let mut added_vertices : Vec<Id> = Vec::new();
983            for halfedge_id in FaceHalfedgeIterator::new(from_mesh, from_mesh.face_first_halfedge_id(face_id).unwrap()) {
984                let vert_id = from_mesh.halfedge_start_vertex_id(halfedge_id).unwrap();
985                if extra_vertices.contains(&vert_id) {
986                    continue;
987                }
988                let new_vert_id = *new_vert_map.entry(vert_id).or_insert_with(|| {
989                    let new_added_vertex_id = to_mesh.add_vertex(from_mesh.vertex(vert_id).unwrap().position);
990                    to_mesh.vertex_mut(new_added_vertex_id).unwrap().source = from_mesh.vertex(vert_id).unwrap().source;
991                    new_added_vertex_id
992                });
993                added_vertices.push(new_vert_id);
994            }
995            to_mesh.add_vertices(added_vertices);
996        }
997        to_mesh
998    }
999
1000    pub fn combine_coplanar_faces(&self) -> Self {
1001        let from_mesh = self;
1002        let mut to_mesh = Mesh::new();
1003        let mut coplanar_edges = HashSet::new();
1004        let mut coplanar_faces = HashSet::new();
1005        let mut coplanar_halfedge_link : HashMap<Id, Id> = HashMap::new();
1006        let mut face_norm_map : HashMap<Id, Vector3<f32>> = HashMap::new();
1007        for (edge, &halfedge_id) in from_mesh.edges.iter() {
1008            let face_id = from_mesh.halfedge_face_id(halfedge_id).unwrap();
1009            let face_norm = *face_norm_map.entry(face_id).or_insert_with(|| from_mesh.face_norm(face_id));
1010            if let Some(opposite_id) = from_mesh.halfedge_opposite_id(halfedge_id) {
1011                let opposite_face_id = from_mesh.halfedge_face_id(opposite_id).unwrap();
1012                let opposite_face_norm = *face_norm_map.entry(opposite_face_id).or_insert_with(|| from_mesh.face_norm(opposite_face_id));
1013                if almost_eq(face_norm, opposite_face_norm) {
1014                    let prev_id = from_mesh.halfedge_prev_id(halfedge_id);
1015                    let next_id = from_mesh.halfedge_next_id(halfedge_id);
1016                    let opposite_prev_id = from_mesh.halfedge_prev_id(opposite_id);
1017                    let opposite_next_id = from_mesh.halfedge_next_id(opposite_id);
1018                    if prev_id.is_none() || next_id.is_none() || opposite_prev_id.is_none() || opposite_next_id.is_none() {
1019                        continue;
1020                    }
1021                    let mut dir1 = from_mesh.halfedge_direct(prev_id.unwrap()).normalize().cross(from_mesh.halfedge_direct(opposite_next_id.unwrap()).normalize());
1022                    let mut dir2 = from_mesh.halfedge_direct(opposite_prev_id.unwrap()).normalize().cross(from_mesh.halfedge_direct(next_id.unwrap()).normalize());
1023                    if dir1.is_zero() {
1024                        dir1 = face_norm;
1025                    }
1026                    if dir2.is_zero() {
1027                        dir2 = face_norm;
1028                    }
1029                    if dir1.dot(dir2) < 0.0 {
1030                        continue;
1031                    }
1032                    coplanar_halfedge_link.insert(halfedge_id, opposite_id);
1033                    coplanar_halfedge_link.insert(opposite_id, halfedge_id);
1034                    coplanar_edges.insert(edge);
1035                    coplanar_faces.insert(face_id);
1036                    coplanar_faces.insert(opposite_face_id);
1037                }
1038            }
1039        }
1040        let mut new_vert_map : HashMap<Id, Id> = HashMap::new();
1041        for face_id in FaceIterator::new(from_mesh) {
1042            if !coplanar_faces.contains(&face_id) {
1043                let mut added_vertices : Vec<Id> = Vec::new();
1044                for halfedge_id in FaceHalfedgeIterator::new(from_mesh, from_mesh.face_first_halfedge_id(face_id).unwrap()) {
1045                    let vert_id = from_mesh.halfedge_start_vertex_id(halfedge_id).unwrap();
1046                    let new_vert_id = *new_vert_map.entry(vert_id).or_insert_with(|| {
1047                        let new_added_vert_id = to_mesh.add_vertex(from_mesh.vertex(vert_id).unwrap().position);
1048                        to_mesh.vertex_mut(new_added_vert_id).unwrap().source = from_mesh.vertex(vert_id).unwrap().source;
1049                        new_added_vert_id
1050                    });
1051                    added_vertices.push(new_vert_id);
1052                }
1053                to_mesh.add_vertices(added_vertices);
1054            }
1055        }
1056        let mut used_halfedges : HashSet<Id> = HashSet::new();
1057        for face_id in FaceIterator::new(from_mesh) {
1058            if coplanar_faces.contains(&face_id) {
1059                for halfedge_id in FaceHalfedgeIterator::new(from_mesh, from_mesh.face_first_halfedge_id(face_id).unwrap()) {
1060                    if coplanar_halfedge_link.contains_key(&halfedge_id) {
1061                        continue;
1062                    }
1063                    if used_halfedges.contains(&halfedge_id) {
1064                        continue;
1065                    }
1066                    used_halfedges.insert(halfedge_id);
1067                    let mut loop_halfedge_id = halfedge_id;
1068                    let mut loop_back = false;
1069                    let mut loop_halfedges : Vec<Id> = Vec::new();
1070                    for _i in 0..100 {
1071                        if coplanar_halfedge_link.contains_key(&loop_halfedge_id) {
1072                            loop_halfedge_id = from_mesh.halfedge_next_id(coplanar_halfedge_link[&loop_halfedge_id]).unwrap();
1073                        } else {
1074                            loop_halfedges.push(loop_halfedge_id);
1075                            loop_halfedge_id = from_mesh.halfedge_next_id(loop_halfedge_id).unwrap();
1076                        }
1077                        if halfedge_id == loop_halfedge_id {
1078                            loop_back = true;
1079                            break;
1080                        }
1081                    }
1082                    if loop_back && loop_halfedges.len() >= 3 {
1083                        let mut added_vertices : Vec<Id> = Vec::new();
1084                        for &loop_halfedge_id in loop_halfedges.iter() {
1085                            used_halfedges.insert(loop_halfedge_id);
1086                            let vert_id = from_mesh.halfedge_start_vertex_id(loop_halfedge_id).unwrap();
1087                            let new_vert_id = *new_vert_map.entry(vert_id).or_insert_with(|| {
1088                                let new_added_vert_id = to_mesh.add_vertex(from_mesh.vertex(vert_id).unwrap().position);
1089                                to_mesh.vertex_mut(new_added_vert_id).unwrap().source = from_mesh.vertex(vert_id).unwrap().source;
1090                                new_added_vert_id
1091                            });
1092                            added_vertices.push(new_vert_id);
1093                        }
1094                        to_mesh.add_vertices(added_vertices);
1095                    }
1096                }
1097            }
1098        }
1099        to_mesh.remove_extra_vertices().weld()
1100    }
1101
1102    pub fn combine_adj_faces_round(&self) -> (bool, Self) {
1103        let from_mesh = self;
1104        let mut to_mesh = Mesh::new();
1105        let mut ignore_faces = HashSet::new();
1106        let mut new_vert_map : HashMap<Id, Id> = HashMap::new();
1107        let mut ignore_vert_ids : HashSet<Id> = HashSet::new();
1108        let mut pending_old_verts : Vec<Vec<Id>> = Vec::new();
1109        let mut face_pair_map : HashSet<FacePair> = HashSet::new();
1110        for (_, &halfedge_id) in from_mesh.edges.iter() {
1111            let face_id = from_mesh.halfedge_face_id(halfedge_id).unwrap();
1112            if ignore_faces.contains(&face_id) {
1113                continue;
1114            }
1115            if let Some(opposite_id) = from_mesh.halfedge_opposite_id(halfedge_id) {
1116                let opposite_face_id = from_mesh.halfedge_face_id(opposite_id).unwrap();
1117                if ignore_faces.contains(&opposite_face_id) {
1118                    continue;
1119                }
1120                let prev_id = from_mesh.halfedge_prev_id(halfedge_id).unwrap();
1121                let next_id = from_mesh.halfedge_next_id(halfedge_id).unwrap();
1122                let opposite_prev_id = from_mesh.halfedge_prev_id(opposite_id).unwrap();
1123                let opposite_next_id = from_mesh.halfedge_next_id(opposite_id).unwrap();
1124                if !almost_eq(from_mesh.halfedge_direct(prev_id).normalize(), from_mesh.halfedge_direct(opposite_next_id).normalize()) {
1125                    continue;
1126                }
1127                if !almost_eq(from_mesh.halfedge_direct(opposite_prev_id).normalize(), from_mesh.halfedge_direct(next_id).normalize()) {
1128                    continue;
1129                }
1130                let first_face_id = from_mesh.halfedge_opposite_face_id(prev_id);
1131                let second_face_id = from_mesh.halfedge_opposite_face_id(opposite_next_id);
1132                if (first_face_id == second_face_id) || 
1133                        (!first_face_id.is_none() && !second_face_id.is_none() && 
1134                            face_pair_map.contains(&FacePair::new(first_face_id.unwrap(), second_face_id.unwrap()))) {
1135                    ignore_vert_ids.insert(from_mesh.halfedge_start_vertex_id(halfedge_id).unwrap());
1136                }
1137                let first_face_id = from_mesh.halfedge_opposite_face_id(opposite_prev_id);
1138                let second_face_id = from_mesh.halfedge_opposite_face_id(next_id);
1139                if (first_face_id == second_face_id) || 
1140                        (!first_face_id.is_none() && !second_face_id.is_none() && 
1141                            face_pair_map.contains(&FacePair::new(first_face_id.unwrap(), second_face_id.unwrap()))) {
1142                    ignore_vert_ids.insert(from_mesh.halfedge_start_vertex_id(opposite_id).unwrap());
1143                }
1144                ignore_faces.insert(face_id);
1145                ignore_faces.insert(opposite_face_id);
1146                face_pair_map.insert(FacePair::new(face_id, opposite_face_id));
1147                let mut old_vertices = Vec::new();
1148                let mut loop_id = next_id;
1149                while loop_id != halfedge_id {
1150                    old_vertices.push(from_mesh.halfedge_start_vertex_id(loop_id).unwrap());
1151                    loop_id = from_mesh.halfedge_next_id(loop_id).unwrap();
1152                }
1153                loop_id = opposite_next_id;
1154                while loop_id != opposite_id {
1155                    old_vertices.push(from_mesh.halfedge_start_vertex_id(loop_id).unwrap());
1156                    loop_id = from_mesh.halfedge_next_id(loop_id).unwrap();
1157                }
1158                pending_old_verts.push(old_vertices);
1159            }
1160        }
1161        for face_id in FaceIterator::new(from_mesh) {
1162            if ignore_faces.contains(&face_id) {
1163                continue;
1164            }
1165            let mut old_vertices = Vec::new();
1166            for halfedge_id in FaceHalfedgeIterator::new(from_mesh, from_mesh.face_first_halfedge_id(face_id).unwrap()) {
1167                old_vertices.push(from_mesh.halfedge_start_vertex_id(halfedge_id).unwrap());
1168            }
1169            pending_old_verts.push(old_vertices);
1170        }
1171        for verts in pending_old_verts.iter() {
1172            let mut added_vertices = Vec::new();
1173            for old_vert_id in verts.iter() {
1174                if !ignore_vert_ids.contains(old_vert_id) {
1175                    let new_vert_id = new_vert_map.entry(*old_vert_id).or_insert_with(|| {
1176                        let new_added_vert_id = to_mesh.add_vertex(from_mesh.vertex(*old_vert_id).unwrap().position);
1177                        to_mesh.vertex_mut(new_added_vert_id).unwrap().source = from_mesh.vertex(*old_vert_id).unwrap().source;
1178                        new_added_vert_id
1179                    });
1180                    added_vertices.push(*new_vert_id);
1181                }
1182            }
1183            to_mesh.add_vertices(added_vertices);
1184        }
1185        (!ignore_faces.is_empty(), to_mesh)
1186    }
1187
1188    pub fn combine_adj_faces(&self) -> Self {
1189        let mut from_mesh = self.clone();
1190        let mut combined = true;
1191        let mut to_mesh = Mesh::new();
1192        while combined {
1193            let (sub_combined, sub_to_mesh) = from_mesh.combine_adj_faces_round();
1194            combined = sub_combined;
1195            from_mesh = sub_to_mesh.clone();
1196            to_mesh = sub_to_mesh;
1197        }
1198        to_mesh
1199    }
1200
1201    pub fn trim(&self, normalize: bool) -> Self {
1202        let mut to_mesh = Mesh::new();
1203        to_mesh.add_mesh(self);
1204        let mut x_low = f32::MAX;
1205        let mut x_high = f32::MIN;
1206        let mut y_low = f32::MAX;
1207        let mut y_high = f32::MIN;
1208        let mut z_low = f32::MAX;
1209        let mut z_high = f32::MIN;
1210        for vert in self.vertices.iter() {
1211            if vert.position.x < x_low {
1212                x_low = vert.position.x;
1213            } else if vert.position.x > x_high {
1214                x_high = vert.position.x;
1215            }
1216            if vert.position.y < y_low {
1217                y_low = vert.position.y;
1218            } else if vert.position.y > y_high {
1219                y_high = vert.position.y;
1220            }
1221            if vert.position.z < z_low {
1222                z_low = vert.position.z;
1223            } else if vert.position.z > z_high {
1224                z_high = vert.position.z;
1225            }
1226        }
1227        let x_middle = (x_high + x_low) / 2.0;
1228        let y_middle = (y_high + y_low) / 2.0;
1229        let z_middle = (z_high + z_low) / 2.0;
1230        if normalize {
1231            let x_size = x_high - x_low;
1232            let y_size = y_high - y_low;
1233            let z_size = z_high - z_low;
1234            let mut long_size = y_size;
1235            if x_size > long_size {
1236                long_size = x_size;
1237            }
1238            if z_size > long_size {
1239                long_size = z_size;
1240            }
1241            for vert in to_mesh.vertices.iter_mut() {
1242                vert.position.x = (vert.position.x - x_middle) / long_size;
1243                vert.position.y = (vert.position.y - y_middle) / long_size;
1244                vert.position.z = (vert.position.z - z_middle) / long_size;
1245            }
1246        } else {
1247            for vert in to_mesh.vertices.iter_mut() {
1248                vert.position.x -= x_middle;
1249                vert.position.y -= y_middle;
1250                vert.position.z -= z_middle;
1251            }
1252        }
1253        to_mesh
1254    }
1255
1256    // The test method (V + F - E = 2) describled by Tobias Gurdan from
1257    // https://gamedev.stackexchange.com/questions/61878/how-check-if-an-arbitrary-given-mesh-is-a-single-closed-mesh
1258    pub fn is_triangulated_mesh_manifold(&self) -> bool {
1259        let mut edges : HashSet<EdgeEndpoints> = HashSet::new();
1260        let mut verts : HashSet<Id> = HashSet::new();
1261        let mut faces : HashSet<Id> = HashSet::new();
1262        for face_id in FaceIterator::new(self) {
1263            let mut face_verts = Vec::new();
1264            for halfedge_id in FaceHalfedgeIterator::new(self, self.face_first_halfedge_id(face_id).unwrap()) {
1265                let vert_id = self.halfedge_start_vertex_id(halfedge_id);
1266                if vert_id.is_none() {
1267                    return false;
1268                }
1269                let opposite_id = self.halfedge_opposite_id(halfedge_id);
1270                if opposite_id.is_none() {
1271                    return false;
1272                }
1273                face_verts.push(vert_id.unwrap());
1274            }
1275            if face_verts.len() < 3 {
1276                return false;
1277            } else {
1278                for i in 0..face_verts.len() {
1279                    let first_vert_id = face_verts[i];
1280                    let second_vert_id = face_verts[(i + 1) % face_verts.len()];
1281                    let key = EdgeEndpoints::new(first_vert_id, second_vert_id);
1282                    edges.insert(key);
1283                }
1284                verts.extend(face_verts.iter().cloned());
1285            }
1286            faces.insert(face_id);
1287        }
1288        verts.len() as isize + faces.len() as isize - edges.len() as isize == 2
1289    }
1290
1291    pub fn broken_face_set(&self) -> HashSet<Id> {
1292        let mut broken_face_set = HashSet::new();
1293        let mut endpoints : HashMap<EdgeEndpoints, Vec<Id>> = HashMap::new();
1294        for face_id in FaceIterator::new(self) {
1295            let mut verts = Vec::new();
1296            for halfedge_id in FaceHalfedgeIterator::new(self, self.face_first_halfedge_id(face_id).unwrap()) {
1297                let vert_id = self.halfedge_start_vertex_id(halfedge_id);
1298                if vert_id.is_none() {
1299                    broken_face_set.insert(face_id);
1300                    break;
1301                }
1302                verts.push(vert_id.unwrap());
1303            }
1304            if verts.len() < 3 {
1305                broken_face_set.insert(face_id);
1306            } else {
1307                for i in 0..verts.len() {
1308                    let first_vert_id = verts[i];
1309                    let second_vert_id = verts[(i + 1) % verts.len()];
1310                    let key = EdgeEndpoints::new(first_vert_id, second_vert_id);
1311                    endpoints.entry(key).or_insert(Vec::new()).push(face_id);
1312                }
1313            }
1314        }
1315        for (_key, face_list) in endpoints {
1316            if face_list.len() != 2 {
1317                for face_id in face_list {
1318                    broken_face_set.insert(face_id);
1319                }
1320            }
1321        }
1322        broken_face_set
1323    }
1324
1325    pub fn mirror_in_x(&self, center_x: f32) -> Self {
1326        let mut new_mesh = Mesh::new();
1327        new_mesh.add_mesh(self);
1328        for vert in new_mesh.vertices.iter_mut() {
1329            vert.position.x = center_x - vert.position.x;
1330        }
1331        new_mesh.flip_mesh()
1332    }
1333
1334    pub fn mirror_in_z(&self, center_z: f32) -> Self {
1335        let mut new_mesh = Mesh::new();
1336        new_mesh.add_mesh(self);
1337        for vert in new_mesh.vertices.iter_mut() {
1338            vert.position.z = center_z - vert.position.z;
1339        }
1340        new_mesh.flip_mesh()
1341    }
1342
1343    pub fn fix_hole(&self) -> Self {
1344        let mut new_mesh = Mesh::new();
1345        let mut border_map : HashMap<Id, Id> = HashMap::new();
1346        new_mesh.add_mesh(self);
1347        {
1348            for face_id in FaceIterator::new(&new_mesh) {
1349                for halfedge_id in FaceHalfedgeIterator::new(&new_mesh, new_mesh.face_first_halfedge_id(face_id).unwrap()) {
1350                    if new_mesh.halfedge_opposite_id(halfedge_id).is_none() {
1351                        let next_halfedge_id = new_mesh.halfedge_next_id(halfedge_id);
1352                        if next_halfedge_id.is_some() {
1353                            let vertex_id = new_mesh.halfedge_start_vertex_id(halfedge_id);
1354                            let next_vertex_id = new_mesh.halfedge_start_vertex_id(next_halfedge_id.unwrap());
1355                            if vertex_id.is_some() && next_vertex_id.is_some() {
1356                                border_map.insert(next_vertex_id.unwrap(), vertex_id.unwrap());
1357                            }
1358                        }
1359                    }
1360                }
1361            }
1362        }
1363        while new_mesh.add_linked_vertices(&mut border_map) > 0 {};
1364        new_mesh
1365    }
1366
1367    pub fn smooth(&mut self, factor: f32, limit_vertices: Option<&HashSet<usize>>) {
1368        let mut neighbor_position_sum_map : HashMap<Id, (Point3<f32>, usize)> = HashMap::new();
1369        let mut face_norm_map : HashMap<Id, Vector3<f32>> = HashMap::new();
1370        for face_id in FaceIterator::new(self) {
1371            for halfedge_id in FaceHalfedgeIterator::new(self, self.face_first_halfedge_id(face_id).unwrap()) {
1372                let from_vert = self.halfedge_start_vertex(halfedge_id);
1373                if from_vert.is_some() {
1374                    let next_halfedge_id = self.halfedge_next_id(halfedge_id);
1375                    if next_halfedge_id.is_some() {
1376                        let to_vert = self.halfedge_start_vertex(next_halfedge_id.unwrap());
1377                        if to_vert.is_some() {
1378                            if limit_vertices.is_none() || limit_vertices.unwrap().contains(&to_vert.unwrap().id) {
1379                                let item = &mut neighbor_position_sum_map.entry(to_vert.unwrap().id).or_insert((Point3 {x:0.0, y:0.0, z:0.0}, 0));
1380                                item.0 += from_vert.unwrap().position.to_vec();
1381                                item.1 += 1;
1382                                face_norm_map.entry(face_id).or_insert_with(|| self.face_norm(face_id));
1383                            }
1384                        }
1385                    }
1386                }
1387            }
1388        }
1389        let self_factor = 1.0 - factor;
1390        let mut old_position_map: HashMap<Id, Point3<f32>> = HashMap::new();
1391        for vert in self.vertices.iter_mut() {
1392            match neighbor_position_sum_map.get(&vert.id) {
1393                Some(&sum_and_count) => {
1394                    if sum_and_count.1 > 0 {
1395                        let old_position = vert.position;
1396                        old_position_map.entry(vert.id).or_insert(old_position);
1397                        vert.position = (sum_and_count.0 / sum_and_count.1 as f32) * factor + old_position.to_vec() * self_factor;
1398                    }
1399                },
1400                _ => {}
1401            }
1402        }
1403        let mut change_back_pairs : Vec<(Id, Point3<f32>)> = Vec::new();
1404        for (face_id, face_normal) in face_norm_map {
1405            if face_normal.dot(self.face_norm(face_id)) <= 0.0 {
1406                for halfedge_id in FaceHalfedgeIterator::new(self, self.face_first_halfedge_id(face_id).unwrap()) {
1407                    let from_vert = self.halfedge_start_vertex(halfedge_id);
1408                    if from_vert.is_some() {
1409                        match old_position_map.get(&from_vert.unwrap().id) {
1410                            Some(&old_position) => {
1411                                change_back_pairs.push((from_vert.unwrap().id, old_position));
1412                            },
1413                            _ => {}
1414                        }
1415                    }
1416                }
1417            }
1418        }
1419        for (vert_id, old_position) in change_back_pairs {
1420            self.vertex_mut(vert_id).unwrap().position = old_position;
1421        }
1422    }
1423}
1424
1425impl Add for Mesh {
1426    type Output = Mesh;
1427
1428    fn add(self, other: Mesh) -> Mesh {
1429        let mut new_mesh = Mesh::new();
1430        new_mesh.add_mesh(&self);
1431        new_mesh.add_mesh(&other);
1432        new_mesh
1433    }
1434}
1435
1436impl AddAssign for Mesh {
1437    fn add_assign(&mut self, other: Mesh) {
1438        self.add_mesh(&other);
1439    }
1440}
1441
1442pub trait Export {
1443    fn export(&self, filename: &str) -> io::Result<()>;
1444}
1445
1446pub trait Import {
1447    fn import(&mut self, filename: &str) -> io::Result<()>;
1448}
1449
1450impl Clone for Mesh {
1451    fn clone(&self) -> Self {
1452        let mut mesh = Mesh::new();
1453        mesh.add_mesh(self);
1454        mesh
1455    }
1456}