Add CycleBuilder

This commit is contained in:
Hanno Braun 2022-04-01 18:47:45 +02:00
parent 354f374dd7
commit a1ab761705
2 changed files with 46 additions and 2 deletions

View File

@ -5,7 +5,7 @@ use crate::{
shape::{Handle, Shape, ValidationResult},
};
use super::{Edge, Vertex};
use super::{Cycle, Edge, Vertex};
/// API for building a [`Vertex`]
pub struct VertexBuilder<'r> {
@ -93,3 +93,42 @@ impl<'r> EdgeBuilder<'r> {
Ok(edge)
}
}
/// API for building a [`Cycle`]
pub struct CycleBuilder<'r> {
shape: &'r mut Shape,
}
impl<'r> CycleBuilder<'r> {
/// Construct a new instance of `CycleBuilder`
pub fn new(shape: &'r mut Shape) -> Self {
Self { shape }
}
/// Build a polygon from a list of points
pub fn polygon(
self,
points: impl IntoIterator<Item = impl Into<Point<3>>>,
) -> ValidationResult<Cycle> {
// A polygon is closed, so we need to add the first point at the end
// again, for the next step.
let mut points: Vec<_> = points.into_iter().map(Into::into).collect();
if let Some(point) = points.first().cloned() {
points.push(point);
}
let mut edges = Vec::new();
for ab in points.windows(2) {
// Can't panic, as we passed `2` to `windows`.
//
// Can be cleaned up, once `array_windows` is stable.
let points = [ab[0], ab[1]];
let edge =
Edge::build(self.shape).line_segment_from_points(points)?;
edges.push(edge);
}
self.shape.insert(Cycle { edges })
}
}

View File

@ -5,7 +5,7 @@ use crate::{
shape::{Handle, Shape},
};
use super::{vertices::Vertex, EdgeBuilder};
use super::{builder::CycleBuilder, vertices::Vertex, EdgeBuilder};
/// A cycle of connected edges
///
@ -29,6 +29,11 @@ pub struct Cycle {
}
impl Cycle {
/// Build a cycle using the [`CycleBuilder`] API
pub fn build(shape: &mut Shape) -> CycleBuilder {
CycleBuilder::new(shape)
}
/// Access the edges that this cycle refers to
///
/// This is a convenience method that saves the caller from dealing with the