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
use crate::{Angle, Bounds, Polygon, Pt2D};

// Deliberately not serializable
/// A tessellated polygon, ready for rendering.
#[derive(Clone)]
pub struct Tessellation {
    /// These points aren't in any meaningful order. It's not generally possible to reconstruct a
    /// `Polygon` from this.
    points: Vec<Pt2D>,
    /// Groups of three indices make up the triangles
    indices: Vec<u16>,
}

#[derive(Clone, Debug)]
pub struct Triangle {
    pub pt1: Pt2D,
    pub pt2: Pt2D,
    pub pt3: Pt2D,
}

impl From<Polygon> for Tessellation {
    fn from(polygon: Polygon) -> Self {
        Self {
            points: polygon.points,
            indices: polygon.indices,
        }
    }
}

impl From<geo::Polygon> for Tessellation {
    fn from(poly: geo::Polygon) -> Self {
        let (exterior, mut interiors) = poly.into_inner();
        interiors.insert(0, exterior);

        let geojson_style: Vec<Vec<Vec<f64>>> = interiors
            .into_iter()
            .map(|ring| {
                ring.into_inner()
                    .into_iter()
                    .map(|pt| vec![pt.x, pt.y])
                    .collect()
            })
            .collect();
        let (vertices, holes, dims) = earcutr::flatten(&geojson_style);
        let indices = earcutr::earcut(&vertices, &holes, dims);

        let points = vertices
            .chunks(2)
            .map(|pair| Pt2D::new(pair[0], pair[1]))
            .collect();

        Self::new(points, indices)
    }
}

impl Tessellation {
    pub fn new(points: Vec<Pt2D>, indices: Vec<usize>) -> Self {
        Tessellation {
            points,
            indices: downsize(indices),
        }
    }

    /// The `points` are not necessarily a `Ring`, which has strict requirements about no duplicate
    /// points. We can render various types of invalid polygon.
    pub fn from_ring(points: Vec<Pt2D>) -> Self {
        assert!(points.len() >= 3);

        let mut vertices = Vec::new();
        for pt in &points {
            vertices.push(pt.x());
            vertices.push(pt.y());
        }
        let indices = downsize(earcutr::earcut(&vertices, &Vec::new(), 2));

        Self { points, indices }
    }

    /// Returns (points, indices) for rendering
    pub fn consume(self) -> (Vec<Pt2D>, Vec<u16>) {
        (self.points, self.indices)
    }

    pub fn triangles(&self) -> Vec<Triangle> {
        let mut triangles: Vec<Triangle> = Vec::new();
        for slice in self.indices.chunks_exact(3) {
            triangles.push(Triangle {
                pt1: self.points[slice[0] as usize],
                pt2: self.points[slice[1] as usize],
                pt3: self.points[slice[2] as usize],
            });
        }
        triangles
    }

    pub fn get_bounds(&self) -> Bounds {
        Bounds::from(&self.points)
    }

    pub fn center(&self) -> Pt2D {
        self.get_bounds().center()
    }

    fn transform<F: Fn(&Pt2D) -> Pt2D>(&mut self, f: F) {
        for pt in &mut self.points {
            *pt = f(pt);
        }
    }

    pub fn translate(&mut self, dx: f64, dy: f64) {
        self.transform(|pt| pt.offset(dx, dy));
    }

    pub fn scale(&mut self, factor: f64) {
        self.transform(|pt| Pt2D::new(pt.x() * factor, pt.y() * factor));
    }

    pub fn scale_xy(&mut self, x_factor: f64, y_factor: f64) {
        self.transform(|pt| Pt2D::new(pt.x() * x_factor, pt.y() * y_factor))
    }

    pub fn rotate(&mut self, angle: Angle) {
        self.rotate_around(angle, self.center())
    }

    pub fn rotate_around(&mut self, angle: Angle, pivot: Pt2D) {
        self.transform(|pt| {
            let origin_pt = Pt2D::new(pt.x() - pivot.x(), pt.y() - pivot.y());
            let (sin, cos) = angle.normalized_radians().sin_cos();
            Pt2D::new(
                pivot.x() + origin_pt.x() * cos - origin_pt.y() * sin,
                pivot.y() + origin_pt.y() * cos + origin_pt.x() * sin,
            )
        })
    }

    /// Equivalent to `self.scale(scale).translate(translate_x, translate_y).rotate_around(rotate,
    /// pivot)`, but modifies the polygon in-place and is faster.
    pub fn inplace_multi_transform(
        &mut self,
        scale: f64,
        translate_x: f64,
        translate_y: f64,
        rotate: Angle,
        pivot: Pt2D,
    ) {
        let (sin, cos) = rotate.normalized_radians().sin_cos();

        for pt in &mut self.points {
            // Scale
            let x = scale * pt.x();
            let y = scale * pt.y();
            // Translate
            let x = x + translate_x;
            let y = y + translate_y;
            // Rotate
            let origin_pt = Pt2D::new(x - pivot.x(), y - pivot.y());
            *pt = Pt2D::new(
                pivot.x() + origin_pt.x() * cos - origin_pt.y() * sin,
                pivot.y() + origin_pt.y() * cos + origin_pt.x() * sin,
            );
        }
    }

    pub fn union(self, other: Self) -> Self {
        let mut points = self.points;
        let mut indices = self.indices;
        let offset = points.len() as u16;
        points.extend(other.points);
        for idx in other.indices {
            indices.push(offset + idx);
        }
        Self { points, indices }
    }

    pub fn union_all(mut list: Vec<Self>) -> Self {
        let mut result = list.pop().unwrap();
        for p in list {
            result = result.union(p);
        }
        result
    }
}

pub fn downsize(input: Vec<usize>) -> Vec<u16> {
    let mut output = Vec::new();
    for x in input {
        if let Ok(x) = u16::try_from(x) {
            output.push(x);
        } else {
            panic!("{} can't fit in u16, some polygon is too huge", x);
        }
    }
    output
}