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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
//! Intersection between faces and points in 2D

use fj_math::Point;

use crate::{
    objects::{Face, HalfEdge, Vertex},
    storage::Handle,
};

use super::{
    ray_segment::RaySegmentIntersection, HorizontalRayToTheRight, Intersect,
};

impl Intersect for (&Handle<Face>, &Point<2>) {
    type Intersection = FacePointIntersection;

    fn intersect(self) -> Option<Self::Intersection> {
        let (face, point) = self;

        let ray = HorizontalRayToTheRight { origin: *point };

        let mut num_hits = 0;

        for cycle in face.all_cycles() {
            // We need to properly detect the ray passing the boundary at the
            // "seam" of the polygon, i.e. the vertex between the last and the
            // first segment. The logic in the loop properly takes care of that,
            // as long as we initialize the `previous_hit` variable with the
            // result of the last segment.
            let mut previous_hit = cycle
                .half_edges()
                .last()
                .cloned()
                .and_then(|edge| (&ray, &edge).intersect());

            for half_edge in cycle.half_edges() {
                let hit = (&ray, half_edge).intersect();

                let count_hit = match (hit, previous_hit) {
                    (
                        Some(RaySegmentIntersection::RayStartsOnSegment),
                        _,
                    ) => {
                        // If the ray starts on the boundary of the face,
                        // there's nothing to else check.
                        return Some(FacePointIntersection::PointIsOnEdge(
                            half_edge.clone()
                        ));
                    }
                    (Some(RaySegmentIntersection::RayStartsOnOnFirstVertex), _) => {
                        let vertex = half_edge.vertices()[0].clone();
                        return Some(
                            FacePointIntersection::PointIsOnVertex(vertex)
                        );
                    }
                    (Some(RaySegmentIntersection::RayStartsOnSecondVertex), _) => {
                        let vertex = half_edge.vertices()[1].clone();
                        return Some(
                            FacePointIntersection::PointIsOnVertex(vertex)
                        );
                    }
                    (Some(RaySegmentIntersection::RayHitsSegment), _) => {
                        // We're hitting a segment right-on. Clear case.
                        true
                    }
                    (
                        Some(RaySegmentIntersection::RayHitsUpperVertex),
                        Some(RaySegmentIntersection::RayHitsLowerVertex),
                    )
                    | (
                        Some(RaySegmentIntersection::RayHitsLowerVertex),
                        Some(RaySegmentIntersection::RayHitsUpperVertex),
                    ) => {
                        // If we're hitting a vertex, only count it if we've hit
                        // the other kind of vertex right before.
                        //
                        // That means, we're passing through the polygon
                        // boundary at where two edges touch. Depending on the
                        // order in which edges are checked, we're seeing this
                        // as a hit to one edge's lower/upper vertex, then the
                        // other edge's opposite vertex.
                        //
                        // If we're seeing two of the same vertices in a row,
                        // we're not actually passing through the polygon
                        // boundary. Then we're just touching a vertex without
                        // passing through anything.
                        true
                    }
                    (Some(RaySegmentIntersection::RayHitsSegmentAndAreParallel), _) => {
                        // A parallel edge must be completely ignored. Its
                        // presence won't change anything, so we can treat it as
                        // if it wasn't there, and its neighbors were connected
                        // to each other.
                        continue;
                    }
                    _ => {
                        // Any other case is not a valid hit.
                        false
                    }
                };

                if count_hit {
                    num_hits += 1;
                }

                previous_hit = hit;
            }
        }

        if num_hits % 2 == 1 {
            Some(FacePointIntersection::PointIsInsideFace)
        } else {
            None
        }
    }
}

/// The intersection between a face and a point
#[allow(clippy::large_enum_variant)]
#[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub enum FacePointIntersection {
    /// The point is inside of the face
    PointIsInsideFace,

    /// The point is coincident with an edge
    PointIsOnEdge(Handle<HalfEdge>),

    /// The point is coincident with a vertex
    PointIsOnVertex(Handle<Vertex>),
}

#[cfg(test)]
mod tests {
    use fj_math::Point;
    use pretty_assertions::assert_eq;

    use crate::{
        algorithms::intersect::{face_point::FacePointIntersection, Intersect},
        builder::FaceBuilder,
        insert::Insert,
        iter::ObjectIters,
        partial::{PartialFace, PartialObject},
        services::Services,
    };

    #[test]
    fn point_is_outside_face() {
        let mut services = Services::new();

        let surface = services.objects.surfaces.xy_plane();
        let mut face = PartialFace::default();
        face.update_exterior_as_polygon(
            surface,
            [[0., 0.], [1., 1.], [0., 2.]],
        );
        let face = face
            .build(&mut services.objects)
            .insert(&mut services.objects);
        let point = Point::from([2., 1.]);

        let intersection = (&face, &point).intersect();
        assert_eq!(intersection, None);
    }

    #[test]
    fn ray_hits_vertex_while_passing_outside() {
        let mut services = Services::new();

        let surface = services.objects.surfaces.xy_plane();
        let mut face = PartialFace::default();
        face.update_exterior_as_polygon(
            surface,
            [[0., 0.], [2., 1.], [0., 2.]],
        );
        let face = face
            .build(&mut services.objects)
            .insert(&mut services.objects);
        let point = Point::from([1., 1.]);

        let intersection = (&face, &point).intersect();
        assert_eq!(
            intersection,
            Some(FacePointIntersection::PointIsInsideFace)
        );
    }

    #[test]
    fn ray_hits_vertex_at_cycle_seam() {
        let mut services = Services::new();

        let surface = services.objects.surfaces.xy_plane();
        let mut face = PartialFace::default();
        face.update_exterior_as_polygon(
            surface,
            [[4., 2.], [0., 4.], [0., 0.]],
        );
        let face = face
            .build(&mut services.objects)
            .insert(&mut services.objects);
        let point = Point::from([1., 2.]);

        let intersection = (&face, &point).intersect();
        assert_eq!(
            intersection,
            Some(FacePointIntersection::PointIsInsideFace)
        );
    }

    #[test]
    fn ray_hits_vertex_while_staying_inside() {
        let mut services = Services::new();

        let surface = services.objects.surfaces.xy_plane();
        let mut face = PartialFace::default();
        face.update_exterior_as_polygon(
            surface,
            [[0., 0.], [2., 1.], [3., 0.], [3., 4.]],
        );
        let face = face
            .build(&mut services.objects)
            .insert(&mut services.objects);
        let point = Point::from([1., 1.]);

        let intersection = (&face, &point).intersect();
        assert_eq!(
            intersection,
            Some(FacePointIntersection::PointIsInsideFace)
        );
    }

    #[test]
    fn ray_hits_parallel_edge_and_leaves_face_at_vertex() {
        let mut services = Services::new();

        let surface = services.objects.surfaces.xy_plane();
        let mut face = PartialFace::default();
        face.update_exterior_as_polygon(
            surface,
            [[0., 0.], [2., 1.], [3., 1.], [0., 2.]],
        );
        let face = face
            .build(&mut services.objects)
            .insert(&mut services.objects);
        let point = Point::from([1., 1.]);

        let intersection = (&face, &point).intersect();
        assert_eq!(
            intersection,
            Some(FacePointIntersection::PointIsInsideFace)
        );
    }

    #[test]
    fn ray_hits_parallel_edge_and_does_not_leave_face_there() {
        let mut services = Services::new();

        let surface = services.objects.surfaces.xy_plane();
        let mut face = PartialFace::default();
        face.update_exterior_as_polygon(
            surface,
            [[0., 0.], [2., 1.], [3., 1.], [4., 0.], [4., 5.]],
        );
        let face = face
            .build(&mut services.objects)
            .insert(&mut services.objects);
        let point = Point::from([1., 1.]);

        let intersection = (&face, &point).intersect();
        assert_eq!(
            intersection,
            Some(FacePointIntersection::PointIsInsideFace)
        );
    }

    #[test]
    fn point_is_coincident_with_edge() {
        let mut services = Services::new();

        let surface = services.objects.surfaces.xy_plane();
        let mut face = PartialFace::default();
        face.update_exterior_as_polygon(
            surface,
            [[0., 0.], [2., 0.], [0., 1.]],
        );
        let face = face
            .build(&mut services.objects)
            .insert(&mut services.objects);
        let point = Point::from([1., 0.]);

        let intersection = (&face, &point).intersect();

        let edge = face
            .half_edge_iter()
            .find(|edge| {
                let [a, b] = edge.vertices();
                a.global_form().position() == Point::from([0., 0., 0.])
                    && b.global_form().position() == Point::from([2., 0., 0.])
            })
            .unwrap();
        assert_eq!(
            intersection,
            Some(FacePointIntersection::PointIsOnEdge(edge.clone()))
        );
    }

    #[test]
    fn point_is_coincident_with_vertex() {
        let mut services = Services::new();

        let surface = services.objects.surfaces.xy_plane();
        let mut face = PartialFace::default();
        face.update_exterior_as_polygon(
            surface,
            [[0., 0.], [1., 0.], [0., 1.]],
        );
        let face = face
            .build(&mut services.objects)
            .insert(&mut services.objects);
        let point = Point::from([1., 0.]);

        let intersection = (&face, &point).intersect();

        let vertex = face
            .vertex_iter()
            .find(|vertex| {
                vertex.global_form().position() == Point::from([1., 0., 0.])
            })
            .unwrap();
        assert_eq!(
            intersection,
            Some(FacePointIntersection::PointIsOnVertex(vertex.clone()))
        );
    }
}