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
use std::collections::VecDeque;

use fj_interop::ext::ArrayExt;

use crate::{
    geometry::path::SurfacePath,
    objects::{Cycle, HalfEdge, Surface},
    partial::{MaybeSurfacePath, Partial, PartialCycle, PartialFace},
};

use super::{CycleBuilder, HalfEdgeBuilder, ObjectArgument, SurfaceBuilder};

/// Builder API for [`PartialFace`]
pub trait FaceBuilder {
    /// Connect the face to another face at the provided half-edges
    ///
    /// Assumes that the provided half-edges, once translated into local
    /// equivalents of this face, will not form a cycle.
    ///
    /// Returns the local equivalents of the provided half-edges and, as the
    /// last entry, an additional half-edge that closes the cycle.
    fn connect_to_open_edges<O>(
        &mut self,
        edges: O,
    ) -> O::SizePlusOne<Partial<HalfEdge>>
    where
        O: ObjectArgument<Partial<HalfEdge>>;

    /// Connect the face to another face at the provided half-edges
    ///
    /// Assumes that the provided half-edges, once translated into local
    /// equivalents of this face, form a cycle.
    ///
    /// Returns the local equivalents of the provided half-edges.
    fn connect_to_closed_edges<O>(
        &mut self,
        edges: O,
    ) -> O::SameSize<Partial<HalfEdge>>
    where
        O: ObjectArgument<Partial<HalfEdge>>;

    /// Add an interior cycle
    fn add_interior(&mut self) -> Partial<Cycle>;

    /// Update the face's surface as a plane
    ///
    /// The plane geometry is inferred from three of the face's vertices. Also
    /// infers any undefined `SurfaceVertex` positions.
    ///
    /// # Panics
    ///
    /// Assumes that the face exterior has exactly three vertices to use. Panics
    /// otherwise. This is a temporary limitation, not a fundamental one. It
    /// could be overcome with some more work.
    fn update_surface_as_plane(&mut self) -> Partial<Surface>;

    /// Infer any undefined curves in the face
    fn infer_curves(&mut self);
}

impl FaceBuilder for PartialFace {
    fn connect_to_open_edges<O>(
        &mut self,
        edges: O,
    ) -> O::SizePlusOne<Partial<HalfEdge>>
    where
        O: ObjectArgument<Partial<HalfEdge>>,
    {
        // We need to create the additional half-edge last, but at the same time
        // need to provide it to the `map_plus_one` method first. Really no
        // choice but to create them all in one go, as we do here.
        let mut half_edges = VecDeque::new();
        for _ in 0..edges.num_objects() {
            half_edges.push_back(self.exterior.write().add_half_edge());
        }
        let additional_half_edge = self.exterior.write().add_half_edge();

        edges.map_plus_one(additional_half_edge, |other| {
            let mut this = half_edges.pop_front().expect(
                "Pushed correct number of half-edges; should be able to pop",
            );
            this.write().update_from_other_edge(&other);
            this
        })
    }

    fn connect_to_closed_edges<O>(
        &mut self,
        edges: O,
    ) -> O::SameSize<Partial<HalfEdge>>
    where
        O: ObjectArgument<Partial<HalfEdge>>,
    {
        edges.map(|other| {
            let mut this = self.exterior.write().add_half_edge();
            this.write().update_from_other_edge(&other);
            this
        })
    }

    fn add_interior(&mut self) -> Partial<Cycle> {
        let cycle = Partial::from_partial(PartialCycle {
            surface: self.exterior.read().surface.clone(),
            ..Default::default()
        });
        self.interiors.push(cycle.clone());
        cycle
    }

    fn update_surface_as_plane(&mut self) -> Partial<Surface> {
        let mut exterior = self.exterior.write();
        let mut vertices = exterior.half_edges.iter().map(|half_edge| {
            let [vertex, _] = &half_edge.read().vertices;
            vertex.1.clone()
        });

        let vertices = {
            let array = [
                vertices.next().expect("Expected exactly three vertices"),
                vertices.next().expect("Expected exactly three vertices"),
                vertices.next().expect("Expected exactly three vertices"),
            ];

            assert!(
                vertices.next().is_none(),
                "Expected exactly three vertices"
            );

            array
        };
        let points = vertices.each_ref_ext().map(|vertex| {
            vertex
                .read()
                .global_form
                .read()
                .position
                .expect("Need global position to infer plane")
        });

        let points_surface =
            exterior.surface.write().update_as_plane_from_points(points);

        for (mut surface_vertex, point) in vertices.zip_ext(points_surface) {
            surface_vertex.write().position = Some(point);
        }

        exterior.surface.clone()
    }

    fn infer_curves(&mut self) {
        for half_edge in &mut self.exterior.write().half_edges {
            let mut half_edge = half_edge.write();

            let mut curve = half_edge.curve.clone();
            let mut curve = curve.write();

            if let Some(path) = &mut curve.path {
                match path {
                    MaybeSurfacePath::Defined(_) => {
                        // Path is already defined. Nothing to infer.
                    }
                    MaybeSurfacePath::UndefinedCircle => todo!(
                        "Inferring undefined circles is not supported yet"
                    ),
                    MaybeSurfacePath::UndefinedLine => {
                        let points_surface =
                            half_edge.vertices.each_ref_ext().map(|vertex| {
                                vertex.1.read().position.expect(
                                    "Can't infer curve without surface points",
                                )
                            });
                        let (line, points_curve) =
                            SurfacePath::line_from_points(points_surface);

                        *path = MaybeSurfacePath::Defined(line);
                        for (vertex, point) in half_edge
                            .vertices
                            .each_mut_ext()
                            .zip_ext(points_curve)
                        {
                            vertex.0 = Some(point);
                        }
                    }
                }
            }
        }
    }
}