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
//          Copyright Eadf (github.com/eadf) 2021.
// Distributed under the Boost Software License, Version 1.0.
//    (See accompanying file LICENSE_1_0.txt or copy at
//          http://www.boost.org/LICENSE_1_0.txt)

// See http://www.boost.org for updates, documentation, and revision history of C++ code.

// Ported from C++ boost 1.76.0 to Rust in 2020/2021 by Eadf (github.com/eadf)

//! A Sync version of the output data.
//! See <https://www.boost.org/doc/libs/1_76_0/libs/polygon/doc/voronoi_diagram.htm> for diagram description.

use crate::diagram as VD;
use crate::BvError;
pub use crate::{InputType, OutputType};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Sync version of the boostvoronoi::Diagram struct.
/// This is useful when traversing the diagram in a multi threaded environment.
///
/// It also comes in an optional `serde` flavor.
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[derive(Default, Debug)]
pub struct SyncDiagram<F: OutputType> {
    cells_: Vec<VD::Cell>,         // indexed by CellIndex
    vertices_: Vec<VD::Vertex<F>>, // indexed by VertexIndex
    edges_: Vec<VD::Edge>,         // indexed by EdgeIndex
}

impl<F: OutputType> SyncDiagram<F> {
    pub fn new(cells: Vec<VD::Cell>, vertices: Vec<VD::Vertex<F>>, edges: Vec<VD::Edge>) -> Self {
        Self {
            cells_: cells,
            vertices_: vertices,
            edges_: edges,
        }
    }

    /// Returns a reference to the list of cells
    #[inline]
    pub fn cells(&self) -> &Vec<VD::Cell> {
        &self.cells_
    }

    #[inline]
    /// Returns an edge iterator, the edges will all originate at the same vertex as 'edge_id'.
    /// 'edge_id' will be the first edge returned by the iterator.
    pub fn edge_rot_next_iterator(&self, edge_id: VD::EdgeIndex) -> EdgeRotNextIterator<'_, F> {
        EdgeRotNextIterator::new(self, edge_id)
    }

    #[inline]
    /// Returns a pointer to the rotation next edge
    /// over the starting point of the half-edge.
    pub fn edge_rot_next(&self, edge_id: VD::EdgeIndex) -> Result<VD::EdgeIndex, BvError> {
        let prev_id = self.edge_get(edge_id)?.prev()?;
        self.edge_get(prev_id)?.twin()
    }

    #[inline]
    /// Returns a pointer to the rotation next edge
    /// over the starting point of the half-edge.
    /// This method returns None at any error
    fn edge_rot_next_no_err(&self, edge_id: Option<VD::EdgeIndex>) -> Option<VD::EdgeIndex> {
        self.edges_
            .get(self.edges_.get(edge_id?.0)?.prev_()?.0)?
            .twin_()
    }

    #[inline]
    /// Returns a pointer to the rotation previous edge
    /// over the starting point of the half-edge.
    pub fn edge_rot_prev(&self, edge_id: VD::EdgeIndex) -> Result<VD::EdgeIndex, BvError> {
        self.edge_get(self.edge_get(edge_id)?.twin()?)?.next()
    }

    /// Returns the next edge or an error
    #[inline]
    pub fn edge_get_next(&self, edge_id: VD::EdgeIndex) -> Result<VD::EdgeIndex, BvError> {
        self.edge_get(edge_id)?.next()
    }

    /// Returns the previous edge or an BvError if it does not exist
    #[inline]
    pub fn edge_get_prev(&self, edge_id: VD::EdgeIndex) -> Result<VD::EdgeIndex, BvError> {
        self.edge_get(edge_id)?.prev_().ok_or_else(|| {
            BvError::ValueError(format!(
                "The edge id {} does not have a prev edge",
                edge_id.0
            ))
        })
    }

    /// Returns the twin edge or a BvError if it does not exists
    #[inline]
    pub fn edge_get_twin(&self, edge_id: VD::EdgeIndex) -> Result<VD::EdgeIndex, BvError> {
        self.edge_get(edge_id)?.twin_().ok_or_else(|| {
            BvError::ValueError(format!("The edge id {} does not have a twin", edge_id.0))
        })
    }

    /// Returns true if the edge is finite (segment, parabolic arc).
    /// Returns false if the edge is infinite (ray, line).
    #[inline]
    pub fn edge_is_finite(&self, edge_id: VD::EdgeIndex) -> Result<bool, BvError> {
        Ok(self.edge_get_vertex0(edge_id)?.is_some() && self.edge_get_vertex1(edge_id)?.is_some())
    }

    /// Returns true if the edge is infinite (ray, line).
    /// Returns false if the edge is finite (segment, parabolic arc).
    #[inline]
    pub fn edge_is_infinite(&self, edge_id: VD::EdgeIndex) -> Result<bool, BvError> {
        Ok(!self.edge_is_finite(edge_id)?)
    }

    pub fn edges(&self) -> &Vec<VD::Edge> {
        &self.edges_
    }

    #[inline]
    pub fn edge_get(&self, edge_id: VD::EdgeIndex) -> Result<&VD::Edge, BvError> {
        self.edges_
            .get(edge_id.0)
            .ok_or_else(|| BvError::IdError(format!("The edge id {} does not exists", edge_id.0)))
    }

    #[inline]
    pub fn edge_get_mut(&mut self, edge_id: VD::EdgeIndex) -> Result<&mut VD::Edge, BvError> {
        self.edges_
            .get_mut(edge_id.0)
            .ok_or_else(|| BvError::IdError(format!("The edge id {} does not exists", edge_id.0)))
    }

    /// Returns the optional vertex0 of the edge
    #[inline]
    pub fn edge_get_vertex0(
        &self,
        edge_id: VD::EdgeIndex,
    ) -> Result<Option<VD::VertexIndex>, BvError> {
        Ok(self.edge_get(edge_id)?.vertex0())
    }

    /// Returns the optional vertex1 of the edge
    #[inline]
    pub fn edge_get_vertex1(
        &self,
        edge_id: VD::EdgeIndex,
    ) -> Result<Option<VD::VertexIndex>, BvError> {
        self.edge_get_vertex0(self.edge_get(edge_id)?.twin()?)
    }

    #[inline]
    pub fn cell_get(&self, cell_id: VD::CellIndex) -> Result<&VD::Cell, BvError> {
        self.cells_
            .get(cell_id.0)
            .ok_or_else(|| BvError::IdError(format!("The cell id {} does not exists", cell_id.0)))
    }

    #[inline]
    /// Returns a reference to all of the vertices
    pub fn vertices(&self) -> &Vec<VD::Vertex<F>> {
        &self.vertices_
    }

    #[inline]
    /// Returns a reference to a vertex
    pub fn vertex_get(&self, vertex_id: VD::VertexIndex) -> Result<&VD::Vertex<F>, BvError> {
        self.vertices_.get(vertex_id.0).ok_or_else(|| {
            BvError::IdError(format!("The vertex id {} does not exists", vertex_id.0))
        })
    }

    #[inline]
    /// Returns a mutable reference to a vertex
    pub fn vertex_get_mut(
        &mut self,
        vertex_id: VD::VertexIndex,
    ) -> Result<&mut VD::Vertex<F>, BvError> {
        self.vertices_.get_mut(vertex_id.0).ok_or_else(|| {
            BvError::IdError(format!("The vertex id {} does not exists", vertex_id.0))
        })
    }
}

/// Iterator over edges pointing away from the vertex indicated by the initial edge.
pub struct EdgeRotNextIterator<'s, F: OutputType> {
    diagram_: &'s SyncDiagram<F>,
    starting_edge_: VD::EdgeIndex,
    next_edge_: Option<VD::EdgeIndex>,
}

impl<'s, F: OutputType> EdgeRotNextIterator<'s, F> {
    pub(crate) fn new(diagram: &'s SyncDiagram<F>, starting_edge: VD::EdgeIndex) -> Self {
        Self {
            diagram_: diagram,
            starting_edge_: starting_edge,
            next_edge_: Some(starting_edge),
        }
    }
}

impl<'s, F: OutputType> Iterator for EdgeRotNextIterator<'s, F> {
    type Item = VD::EdgeIndex;
    fn next(&mut self) -> Option<VD::EdgeIndex> {
        let rv = self.next_edge_;
        let new_next_edge = self.diagram_.edge_rot_next_no_err(self.next_edge_);
        self.next_edge_ = if let Some(nne) = new_next_edge {
            if nne.0 == self.starting_edge_.0 {
                // Break the loop when we see the starting edge again
                None
            } else {
                new_next_edge
            }
        } else {
            None
        };
        rv
    }
}