Skip to main content

mesh_graph/
iter.rs

1use tracing::error;
2
3use crate::{HalfedgeId, MeshGraph};
4
5/// Iterator over some halfedges
6pub struct CircularHalfedgesIterator<'a> {
7    start_halfedge: Option<HalfedgeId>,
8    mesh_graph: &'a MeshGraph,
9    current_halfedge: Option<HalfedgeId>,
10    get_next_halfedge: fn(HalfedgeId, &'a MeshGraph) -> Option<HalfedgeId>,
11    max_count: usize,
12    next_idx: usize,
13}
14
15impl<'a> CircularHalfedgesIterator<'a> {
16    pub fn new(
17        start_halfedge: Option<HalfedgeId>,
18        mesh_graph: &'a MeshGraph,
19        get_next_halfedge: fn(HalfedgeId, &'a MeshGraph) -> Option<HalfedgeId>,
20        max_count: usize,
21    ) -> Self {
22        Self {
23            start_halfedge,
24            mesh_graph,
25            current_halfedge: None,
26            get_next_halfedge,
27            max_count,
28            next_idx: 0,
29        }
30    }
31
32    pub fn empty(mesh_graph: &'a MeshGraph) -> Self {
33        Self {
34            start_halfedge: None,
35            mesh_graph,
36            current_halfedge: None,
37            get_next_halfedge: |_, _| None,
38            max_count: 0,
39            next_idx: 0,
40        }
41    }
42}
43
44impl<'a> Iterator for CircularHalfedgesIterator<'a> {
45    type Item = HalfedgeId;
46
47    fn next(&mut self) -> Option<Self::Item> {
48        if let Some(current_halfedge) = self.current_halfedge {
49            self.current_halfedge = (self.get_next_halfedge)(current_halfedge, self.mesh_graph);
50            self.next_idx += 1;
51
52            if self.current_halfedge == self.start_halfedge {
53                return None;
54            }
55        } else {
56            self.current_halfedge = self.start_halfedge;
57            self.next_idx += 1;
58        }
59
60        if self.next_idx > self.max_count {
61            error!("Maximum count reached. In a valid mesh graph this should not happen.");
62            return None;
63        }
64
65        self.current_halfedge
66    }
67}