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
//! Cycle approximation
//!
//! See [`CycleApprox`].

use std::ops::Deref;

use fj_math::Segment;

use crate::objects::{Cycle, Surface};

use super::{
    edge::{HalfEdgeApprox, HalfEdgeApproxCache},
    Approx, ApproxPoint, Tolerance,
};

impl Approx for (&Cycle, &Surface) {
    type Approximation = CycleApprox;
    type Cache = HalfEdgeApproxCache;

    fn approx_with_cache(
        self,
        tolerance: impl Into<Tolerance>,
        cache: &mut Self::Cache,
    ) -> Self::Approximation {
        let (cycle, surface) = self;
        let tolerance = tolerance.into();

        let half_edges = cycle
            .half_edges()
            .iter()
            .map(|edge| {
                (edge.deref(), surface).approx_with_cache(tolerance, cache)
            })
            .collect();

        CycleApprox { half_edges }
    }
}

/// An approximation of a [`Cycle`]
#[derive(Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct CycleApprox {
    /// The approximated half-edges that make up the approximated cycle
    pub half_edges: Vec<HalfEdgeApprox>,
}

impl CycleApprox {
    /// Compute the points that approximate the cycle
    pub fn points(&self) -> Vec<ApproxPoint<2>> {
        let mut points = Vec::new();

        for approx in &self.half_edges {
            points.extend(approx.points.iter().copied());
        }

        if let Some(point) = points.first() {
            points.push(*point);
        }

        points
    }

    /// Construct the segments that approximate the cycle
    pub fn segments(&self) -> Vec<Segment<3>> {
        let mut segments = Vec::new();

        for segment in self.points().windows(2) {
            // This can't panic, as we passed `2` to `windows`. Can be cleaned
            // up, once `array_windows` is stable.
            let segment = [&segment[0], &segment[1]];

            segments
                .push(Segment::from(segment.map(|point| point.global_form)));
        }

        segments
    }
}