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
use fj_math::{Point, Scalar};

use crate::{
    objects::{Cycle, HalfEdge},
    storage::Handle,
};

use super::{Validate, ValidationConfig, ValidationError};

impl Validate for Cycle {
    fn validate_with_config(
        &self,
        config: &ValidationConfig,
        errors: &mut Vec<ValidationError>,
    ) {
        CycleValidationError::check_half_edge_connections(self, config, errors);
    }
}

/// [`Cycle`] validation failed
#[derive(Clone, Debug, thiserror::Error)]
pub enum CycleValidationError {
    /// [`Cycle`]'s edges are not connected
    #[error(
        "Adjacent `HalfEdge`s are not connected\n\
        - End position of first `HalfEdge`: {end_of_first:?}\n\
        - Start position of second `HalfEdge`: {start_of_second:?}\n\
        - Distance between vertices: {distance}\n\
        - `HalfEdge`s: {half_edges:#?}"
    )]
    HalfEdgesNotConnected {
        /// The end position of the first [`HalfEdge`]
        end_of_first: Point<2>,

        /// The start position of the second [`HalfEdge`]
        start_of_second: Point<2>,

        /// The distance between the two vertices
        distance: Scalar,

        /// The edges
        half_edges: [Handle<HalfEdge>; 2],
    },
}

impl CycleValidationError {
    fn check_half_edge_connections(
        cycle: &Cycle,
        config: &ValidationConfig,
        errors: &mut Vec<ValidationError>,
    ) {
        for (first, second) in cycle.half_edges().pairs() {
            let end_of_first = {
                let [_, end] = first.boundary().inner;
                first.path().point_from_path_coords(end)
            };
            let start_of_second = second.start_position();

            let distance = (end_of_first - start_of_second).magnitude();

            if distance > config.identical_max_distance {
                errors.push(
                    Self::HalfEdgesNotConnected {
                        end_of_first,
                        start_of_second,
                        distance,
                        half_edges: [first.clone(), second.clone()],
                    }
                    .into(),
                );
            }
        }
    }
}

#[cfg(test)]
mod tests {

    use crate::{
        assert_contains_err,
        objects::{Cycle, HalfEdge},
        operations::{
            build::{BuildCycle, BuildHalfEdge},
            insert::Insert,
            update::UpdateCycle,
        },
        services::Services,
        validate::{cycle::CycleValidationError, Validate, ValidationError},
    };

    #[test]
    fn edges_connected() -> anyhow::Result<()> {
        let mut services = Services::new();

        let valid =
            Cycle::polygon([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0]], &mut services);

        valid.validate_and_return_first_error()?;

        let disconnected = {
            let edges = [
                HalfEdge::line_segment(
                    [[0., 0.], [1., 0.]],
                    None,
                    &mut services,
                ),
                HalfEdge::line_segment(
                    [[0., 0.], [1., 0.]],
                    None,
                    &mut services,
                ),
            ];
            let edges = edges.map(|edge| edge.insert(&mut services));

            Cycle::empty().add_half_edges(edges)
        };

        assert_contains_err!(
            disconnected,
            ValidationError::Cycle(
                CycleValidationError::HalfEdgesNotConnected { .. }
            )
        );

        Ok(())
    }
}