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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
// MIT License
//
// Copyright (c) 2023 Michael H. Phillips
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//

use crate::{
    dcos, dim2, dsin, polyhedron, triangulate2d, triangulate2d_rev, triangulate3d,
    triangulate3d_rev, Faces, Indices, Mt4, Pt2s, Pt3, Pt3s, Scad, ScadOp,
};

/// The points and faces of a polyhedron.
///
/// Polyhedron exists so that meshes can be modified or created
/// in Rust code. It also allows things that are not directly
/// implemented in OpenSCAD like sweep and loft.
#[derive(Clone)]
pub struct Polyhedron {
    pub points: Pt3s,
    pub faces: Faces,
}

impl Polyhedron {
    /// Turn the Polyhedron into a Scad.
    pub fn into_scad(self) -> Scad {
        polyhedron!(self.points, self.faces)
    }

    /// Turn the Polyhedron into a Scad with the given convexity.
    pub fn into_scad_with_convexity(self, convexity: u64) -> Scad {
        polyhedron!(self.points, self.faces, convexity)
    }

    /// Translate the polyhedron.
    pub fn translate(&mut self, point: Pt3) {
        self.points.translate(point);
    }

    /// Apply the matrix to the polyhedron by multiplying the matrix with each point.
    pub fn apply_matrix(&mut self, matrix: &Mt4) {
        self.points.apply_matrix(matrix);
    }

    /// Rotate the polyhedron around the X axis.
    pub fn rotate_x(&mut self, degrees: f64) -> &mut Self {
        self.points.rotate_x(degrees);
        self
    }

    /// Rotate the polyhedron around the Y axis.
    pub fn rotate_y(&mut self, degrees: f64) -> &mut Self {
        self.points.rotate_y(degrees);
        self
    }

    /// Rotate the polyhedron around the Z axis.
    pub fn rotate_z(&mut self, degrees: f64) -> &mut Self {
        self.points.rotate_z(degrees);
        self
    }

    /// Extrude a 2D profile into a polyhedron.
    ///
    /// Most of the time you want the linear_extrude macro instead of this.
    pub fn linear_extrude(points: &Pt2s, height: f64) -> Polyhedron {
        let indices = triangulate2d_rev(points);
        let mut vertices = Pt3s::with_capacity(points.len() * 2);
        for point in points.iter() {
            vertices.push(point.as_pt3(0.0));
        }

        let mut faces = Faces::with_capacity((points.len() - 2) * 2 + points.len());
        for i in (0..indices.len()).step_by(3) {
            faces.push(Indices::from_indices(vec![
                indices[i],
                indices[i + 1],
                indices[i + 2],
            ]));
        }

        let mut end_points = points.iter().map(|p| p.as_pt3(height)).collect();
        vertices.append(&mut end_points);
        let indices = triangulate2d(points);
        for i in (0..indices.len()).step_by(3) {
            faces.push(Indices::from_indices(vec![
                indices[i] + points.len() as u64,
                indices[i + 1] + points.len() as u64,
                indices[i + 2] + points.len() as u64,
            ]));
        }

        for i in 0..points.len() {
            let p0 = i;
            let p1 = (i + 1) % points.len();
            let p2 = (i + 1) % points.len() + points.len();
            let p3 = i + points.len();

            faces.push(Indices::from_indices(vec![
                p0 as u64, p1 as u64, p2 as u64, p3 as u64,
            ]));
        }

        Polyhedron {
            points: vertices,
            faces,
        }
    }

    /// Extrude a 2D profile into a polyhedron.
    ///
    /// Most of the time you want the rotate_extrude macro instead of this.
    pub fn rotate_extrude(profile: &Pt2s, degrees: f64, segments: usize) -> Self {
        assert!(degrees >= 0.0 && degrees <= 360.0);
        assert!(segments >= 3);
        let not_closed = degrees != 360.0;
        let profile: Pt3s =
            Pt3s::from_pt3s(profile.iter().map(|p| Pt3::new(p.x, 0.0, p.y)).collect());
        let profile_len = profile.len();
        let a = degrees / segments as f64;
        let mut points = profile.clone();
        let mut faces = Faces::new();

        if not_closed {
            // triangulate the starting face
            let triangles = triangulate3d(&profile, Pt3::new(0.0, -1.0, 0.0));
            for i in (0..triangles.len()).step_by(3) {
                faces.push(Indices::from_indices(vec![
                    triangles[i] as u64,
                    triangles[i + 1] as u64,
                    triangles[i + 2] as u64,
                ]));
            }
        }

        for segment in 1..segments {
            let s = dsin(a * segment as f64);
            let c = dcos(a * segment as f64);
            for p in 0..profile_len {
                points.push(Pt3::new(profile[p].x * c, profile[p].x * s, profile[p].z));
                let p0 = (segment - 1) * profile_len + p;
                let p1 = (segment - 1) * profile_len + ((p + 1) % profile_len);
                let p2 = segment * profile_len + ((p + 1) % profile_len);
                let p3 = segment * profile_len + p;
                faces.push(Indices::from_indices(vec![
                    p0 as u64, p1 as u64, p2 as u64, p3 as u64,
                ]));
            }
        }

        if not_closed {
            let s = dsin(a * segments as f64);
            let c = dcos(a * segments as f64);
            for p in 0..profile_len {
                points.push(Pt3::new(profile[p].x * c, profile[p].x * s, profile[p].z));
                let p0 = (segments - 1) * profile_len + p;
                let p1 = (segments - 1) * profile_len + ((p + 1) % profile_len);
                let p2 = segments * profile_len + ((p + 1) % profile_len);
                let p3 = segments * profile_len + p;
                faces.push(Indices::from_indices(vec![
                    p0 as u64, p1 as u64, p2 as u64, p3 as u64,
                ]));
            }
            let nml = Pt3::new(0.0, -1.0, 0.0).rotated_z(degrees + 180.0);
            let triangles = triangulate3d_rev(&profile, nml);
            for i in (0..triangles.len()).step_by(3) {
                faces.push(Indices::from_indices(vec![
                    triangles[i] as u64 + (segments * profile_len) as u64,
                    triangles[i + 1] as u64 + (segments * profile_len) as u64,
                    triangles[i + 2] as u64 + (segments * profile_len) as u64,
                ]));
            }
        } else {
            for p in 0..profile_len {
                let p0 = (segments - 1) * profile_len + p;
                let p1 = (segments - 1) * profile_len + ((p + 1) % profile_len);
                let p2 = (p + 1) % profile_len;
                let p3 = p;
                faces.push(Indices::from_indices(vec![
                    p0 as u64, p1 as u64, p2 as u64, p3 as u64,
                ]));
            }
        }
        Polyhedron { points, faces }
    }

    /// Create a Polyhedron by connecting two 2D profiles.
    ///
    /// The profiles need to have the same number of vertices.
    pub fn loft(lower_profile: &Pt2s, upper_profile: &Pt2s, height: f64) -> Self {
        if lower_profile.len() != upper_profile.len() {
            panic!(
                "lower and upper profile lengths differ, lower len = {} and upper len = {}",
                lower_profile.len(),
                upper_profile.len()
            );
        }
        let n_pts = lower_profile.len();
        let mut points = Pt3s::with_capacity(n_pts * 2);
        for pt in lower_profile.iter() {
            points.push(pt.as_pt3(0.0));
        }
        for pt in upper_profile.iter() {
            points.push(pt.as_pt3(height));
        }

        let mut faces = Faces::with_capacity((n_pts - 2) * 2 + n_pts);
        let indices = triangulate2d_rev(lower_profile);
        for i in (0..indices.len()).step_by(3) {
            faces.push(Indices::from_indices(vec![
                indices[i],
                indices[i + 1],
                indices[i + 2],
            ]));
        }

        let indices = triangulate2d(upper_profile);
        for i in (0..indices.len()).step_by(3) {
            faces.push(Indices::from_indices(vec![
                indices[i] + n_pts as u64,
                indices[i + 1] + n_pts as u64,
                indices[i + 2] + n_pts as u64,
            ]));
        }

        for i in 0..n_pts {
            faces.push(Indices::from_indices(vec![
                i as u64,
                ((i + 1) % n_pts) as u64,
                ((i + 1) % n_pts + n_pts) as u64,
                (i + n_pts) as u64,
            ]));
        }

        Polyhedron { points, faces }
    }

    /// Sweeps a 2D profile along a path of 3D points to make a polyhedron.
    ///
    /// If closed is true then twist_degrees should be a multiple of 360.
    pub fn sweep(profile: &Pt2s, path: &Pt3s, twist_degrees: f64, closed: bool) -> Self {
        let profile = Pt3s::from_pt3s(profile.iter().map(|p| p.as_pt3(0.0)).collect());
        let profile_len = profile.len();
        let path_len = path.len();
        let mut points = Pt3s::new();
        let mut faces = Faces::new();
        let twist_angle = if closed {
            twist_degrees / path.len() as f64
        } else {
            twist_degrees / (path.len() - 1) as f64
        };

        let m = if closed {
            Mt4::look_at_matrix_lh(path[path.len() - 1], path[1], Pt3::new(0.0, 0.0, 1.0))
        } else {
            Mt4::look_at_matrix_lh(path[0], path[1], Pt3::new(0.0, 0.0, 1.0))
        };
        for p in profile.iter() {
            points.push((m * p.as_pt4(1.0)).as_pt3() + path[0]);
        }
        if !closed {
            let indices = triangulate3d_rev(&profile, path[1] - path[0]);
            for i in (0..indices.len()).step_by(3) {
                faces.push(Indices::from_indices(vec![
                    indices[i],
                    indices[i + 1],
                    indices[i + 2],
                ]));
            }
        }

        for path_index in 1..path_len - 1 {
            let m = Mt4::look_at_matrix_lh(
                path[path_index - 1],
                path[path_index + 1],
                Pt3::new(0.0, 0.0, 1.0),
            );
            for profile_index in 0..profile_len {
                let point = profile[profile_index].rotated_z(twist_angle * path_index as f64);
                points.push((m * point.as_pt4(0.0)).as_pt3() + path[path_index]);
                let p0 = (path_index - 1) * profile_len + profile_index;
                let p1 = (path_index - 1) * profile_len + ((profile_index + 1) % profile_len);
                let p2 = path_index * profile_len + ((profile_index + 1) % profile_len);
                let p3 = path_index * profile_len + profile_index;
                faces.push(Indices::from_indices(vec![
                    p0 as u64, p1 as u64, p2 as u64, p3 as u64,
                ]));
            }
        }

        let m = if closed {
            Mt4::look_at_matrix_lh(path[path_len - 2], path[0], Pt3::new(0.0, 0.0, 1.0))
        } else {
            Mt4::look_at_matrix_lh(
                path[path_len - 2],
                path[path_len - 1],
                Pt3::new(0.0, 0.0, 1.0),
            )
        };
        let mut last_points = Pt3s::with_capacity(profile_len);
        for profile_index in 0..profile_len {
            let point = profile[profile_index].rotated_z(twist_angle * (path_len - 1) as f64);
            let p = (m * point.as_pt4(0.0)).as_pt3() + path[path_len - 1];
            points.push(p);
            last_points.push(p);
            let p0 = (path_len - 2) * profile_len + profile_index;
            let p1 = (path_len - 2) * profile_len + ((profile_index + 1) % profile_len);
            let p2 = (path_len - 1) * profile_len + ((profile_index + 1) % profile_len);
            let p3 = (path_len - 1) * profile_len + profile_index;
            faces.push(Indices::from_indices(vec![
                p0 as u64, p1 as u64, p2 as u64, p3 as u64,
            ]));
        }

        if !closed {
            let indices = triangulate3d(&last_points, path[path_len - 1] - path[path_len - 2]);
            for i in (0..indices.len()).step_by(3) {
                faces.push(Indices::from_indices(vec![
                    indices[i] + points.len() as u64 - profile_len as u64,
                    indices[i + 1] + points.len() as u64 - profile_len as u64,
                    indices[i + 2] + points.len() as u64 - profile_len as u64,
                ]));
            }
        } else {
            for profile_index in 0..profile_len {
                let p0 = (path_len - 1) * profile_len + profile_index;
                let p1 = (path_len - 1) * profile_len + ((profile_index + 1) % profile_len);
                let p2 = (profile_index + 1) % profile_len;
                let p3 = profile_index;
                faces.push(Indices::from_indices(vec![
                    p0 as u64, p1 as u64, p2 as u64, p3 as u64,
                ]));
            }
        }

        Self { points, faces }
    }

    /// Create a cylinder polyhedron.
    pub fn cylinder(radius: f64, height: f64, segments: u64) -> Self {
        Self::linear_extrude(&dim2::circle(radius, segments), height)
    }
}

/// Yeilds the points of a quadratic bezier.
///
/// If you want to use a Viewer use QuadraticBezier3D struct instead.
pub fn quadratic_bezier(start: Pt3, control: Pt3, end: Pt3, segments: u64) -> Pt3s {
    let delta = 1.0 / segments as f64;
    let mut points = Pt3s::new();
    for i in 0..(segments + 1) {
        let t = i as f64 * delta;
        points.push(start * (1.0 - t) * (1.0 - t) + control * t * (1.0 - t) * 2.0 + end * t * t);
    }
    points
}

/// Yeilds the points of a cubic bezier.
///
/// If you want to use a Viewer use CubicBezier3D struct instead.
pub fn cubic_bezier(start: Pt3, control1: Pt3, control2: Pt3, end: Pt3, segments: u64) -> Pt3s {
    let delta = 1.0 / segments as f64;
    let mut points = Pt3s::new();
    for i in 0..(segments + 1) {
        let t = i as f64 * delta;
        points.push(
            start * (1.0 - t) * (1.0 - t) * (1.0 - t)
                + control1 * t * (1.0 - t) * (1.0 - t) * 3.0
                + control2 * t * t * (1.0 - t) * 3.0
                + end * t * t * t,
        );
    }
    points
}

/// A 3D quadratic bezier curve.
#[derive(Clone, Copy)]
pub struct QuadraticBezier3D {
    pub start: Pt3,
    pub control: Pt3,
    pub end: Pt3,
    pub segments: u64,
}

impl QuadraticBezier3D {
    /// Create a new QuadraticBezier3D.
    pub fn new(start: Pt3, control: Pt3, end: Pt3, segments: u64) -> Self {
        Self {
            start,
            control,
            end,
            segments,
        }
    }

    /// Yields the points of the curve.
    pub fn gen_points(&self) -> Pt3s {
        quadratic_bezier(self.start, self.control, self.end, self.segments)
    }
}

/// A 3d cubic bezier curve.
#[derive(Clone, Copy)]
pub struct CubicBezier3D {
    pub start: Pt3,
    pub control1: Pt3,
    pub control2: Pt3,
    pub end: Pt3,
    pub segments: u64,
}

impl CubicBezier3D {
    /// Create a CubicBezier3D.
    pub fn new(start: Pt3, control1: Pt3, control2: Pt3, end: Pt3, segments: u64) -> Self {
        Self {
            start,
            control1,
            control2,
            end,
            segments,
        }
    }

    /// Yields the points of the curve.
    pub fn gen_points(&self) -> Pt3s {
        cubic_bezier(
            self.start,
            self.control1,
            self.control2,
            self.end,
            self.segments,
        )
    }
}

/// Multiple cubic bezier curves linked together.
#[derive(Clone)]
pub struct CubicBezierChain3D {
    pub curves: Vec<CubicBezier3D>,
    closed: bool,
}

impl CubicBezierChain3D {
    /// Create the start of the chain.
    pub fn new(start: Pt3, control1: Pt3, control2: Pt3, end: Pt3, segments: u64) -> Self {
        Self {
            curves: vec![CubicBezier3D {
                start,
                control1,
                control2,
                end,
                segments,
            }],
            closed: false,
        }
    }

    /// Add an additional curve to the chain.
    pub fn add(
        &mut self,
        control1_length: f64,
        control2: Pt3,
        end: Pt3,
        segments: u64,
    ) -> &mut Self {
        let chain_end = &self.curves[self.curves.len() - 1];
        self.curves.push(CubicBezier3D {
            start: chain_end.end,
            control1: chain_end.end
                + (chain_end.end - chain_end.control2).normalized() * control1_length,
            control2,
            end,
            segments,
        });
        self
    }

    /// Connect the ends of the chain to form a closed profile.
    pub fn close(
        &mut self,
        control1_length: f64,
        control2: Pt3,
        start_control1_len: f64,
        segments: u64,
    ) {
        self.closed = true;
        self.add(control1_length, control2, self.curves[0].start, segments);
        let chain_end = &self.curves[self.curves.len() - 1];
        self.curves[0].control1 =
            chain_end.end + (chain_end.end - chain_end.control2).normalized() * start_control1_len;
    }

    /// Yields the points of the curve.
    pub fn gen_points(&self) -> Pt3s {
        let mut pts = Pt3s::from_pt3s(vec![Pt3::new(0.0, 0.0, 0.0)]);
        for i in 0..self.curves.len() {
            pts.pop();
            pts.append(&mut cubic_bezier(
                self.curves[i].start,
                self.curves[i].control1,
                self.curves[i].control2,
                self.curves[i].end,
                self.curves[i].segments,
            ));
        }
        if self.closed {
            pts.pop();
        }
        pts
    }
}