1use crate::{is_zero, Line, Plane};
2
3use euclid::{
4    approxeq::ApproxEq,
5    default::{Point2D, Point3D, Rect, Transform3D, Vector3D},
6};
7use smallvec::SmallVec;
8
9use std::{iter, mem};
10
11pub struct LineProjection {
13    pub markers: [f64; 4],
15}
16
17impl LineProjection {
18    pub fn get_bounds(&self) -> (f64, f64) {
20        let (mut a, mut b, mut c, mut d) = (
21            self.markers[0],
22            self.markers[1],
23            self.markers[2],
24            self.markers[3],
25        );
26        if a > c {
30            mem::swap(&mut a, &mut c);
31        }
32        if b > d {
33            mem::swap(&mut b, &mut d);
34        }
35        if a > b {
36            mem::swap(&mut a, &mut b);
37        }
38        if c > d {
39            mem::swap(&mut c, &mut d);
40        }
41        if b > c {
42            mem::swap(&mut b, &mut c);
43        }
44        debug_assert!(a <= b && b <= c && c <= d);
45        (a, d)
46    }
47
48    pub fn intersect(&self, other: &Self) -> bool {
50        let span = self.get_bounds();
52        let other_span = other.get_bounds();
53        let left = if span.0 < other_span.0 {
55            span.0
56        } else {
57            other_span.0
58        };
59        let right = if span.1 > other_span.1 {
60            span.1
61        } else {
62            other_span.1
63        };
64        right - left < span.1 - span.0 + other_span.1 - other_span.0
66    }
67}
68
69pub enum Intersection<T> {
71    Coplanar,
73    Outside,
75    Inside(T),
77}
78
79impl<T> Intersection<T> {
80    pub fn is_outside(&self) -> bool {
82        match *self {
83            Intersection::Outside => true,
84            _ => false,
85        }
86    }
87    pub fn is_inside(&self) -> bool {
89        match *self {
90            Intersection::Inside(_) => true,
91            _ => false,
92        }
93    }
94}
95
96#[derive(Debug, PartialEq)]
98pub struct Polygon<A> {
99    pub points: [Point3D<f64>; 4],
101    pub plane: Plane,
103    pub anchor: A,
106}
107
108impl<A: Copy> Clone for Polygon<A> {
109    fn clone(&self) -> Self {
110        Polygon {
111            points: [
112                self.points[0].clone(),
113                self.points[1].clone(),
114                self.points[2].clone(),
115                self.points[3].clone(),
116            ],
117            plane: self.plane.clone(),
118            anchor: self.anchor,
119        }
120    }
121}
122
123impl<A> Polygon<A>
124where
125    A: Copy,
126{
127    pub fn from_points(points: [Point3D<f64>; 4], anchor: A) -> Option<Self> {
130        let edge1 = points[1] - points[0];
131        let edge2 = points[2] - points[0];
132        let edge3 = points[3] - points[0];
133        let edge4 = points[3] - points[1];
134
135        if edge2.square_length() < f64::EPSILON || edge4.square_length() < f64::EPSILON {
136            return None;
137        }
138
139        let normal_rough1 = edge1.cross(edge2);
143        let normal_rough2 = edge2.cross(edge3);
144        let square_length1 = normal_rough1.square_length();
145        let square_length2 = normal_rough2.square_length();
146        let normal = if square_length1 > square_length2 {
147            normal_rough1 / square_length1.sqrt()
148        } else {
149            normal_rough2 / square_length2.sqrt()
150        };
151
152        let offset = -points[0].to_vector().dot(normal);
153
154        Some(Polygon {
155            points,
156            plane: Plane { normal, offset },
157            anchor,
158        })
159    }
160
161    pub fn from_rect(rect: Rect<f64>, anchor: A) -> Self {
163        let min = rect.min();
164        let max = rect.max();
165        Polygon {
166            points: [
167                min.to_3d(),
168                Point3D::new(max.x, min.y, 0.0),
169                max.to_3d(),
170                Point3D::new(min.x, max.y, 0.0),
171            ],
172            plane: Plane {
173                normal: Vector3D::new(0.0, 0.0, 1.0),
174                offset: 0.0,
175            },
176            anchor,
177        }
178    }
179
180    pub fn from_transformed_rect(
182        rect: Rect<f64>,
183        transform: Transform3D<f64>,
184        anchor: A,
185    ) -> Option<Self> {
186        let min = rect.min();
187        let max = rect.max();
188        let points = [
189            transform.transform_point3d(min.to_3d())?,
190            transform.transform_point3d(Point3D::new(max.x, min.y, 0.0))?,
191            transform.transform_point3d(max.to_3d())?,
192            transform.transform_point3d(Point3D::new(min.x, max.y, 0.0))?,
193        ];
194        Self::from_points(points, anchor)
195    }
196
197    pub fn from_transformed_rect_with_inverse(
199        rect: Rect<f64>,
200        transform: &Transform3D<f64>,
201        inv_transform: &Transform3D<f64>,
202        anchor: A,
203    ) -> Option<Self> {
204        let min = rect.min();
205        let max = rect.max();
206        let points = [
207            transform.transform_point3d(min.to_3d())?,
208            transform.transform_point3d(Point3D::new(max.x, min.y, 0.0))?,
209            transform.transform_point3d(max.to_3d())?,
210            transform.transform_point3d(Point3D::new(min.x, max.y, 0.0))?,
211        ];
212
213        let normal_raw = Vector3D::new(inv_transform.m13, inv_transform.m23, inv_transform.m33);
216        let normal_sql = normal_raw.square_length();
217        if normal_sql.approx_eq(&0.0) || transform.m44.approx_eq(&0.0) {
218            None
219        } else {
220            let normal = normal_raw / normal_sql.sqrt();
221            let offset = -Vector3D::new(transform.m41, transform.m42, transform.m43).dot(normal)
222                / transform.m44;
223
224            Some(Polygon {
225                points,
226                plane: Plane { normal, offset },
227                anchor,
228            })
229        }
230    }
231
232    pub fn untransform_point(&self, point: Point3D<f64>) -> Point2D<f64> {
235        let a = self.points[1] - self.points[0];
238        let b = self.points[3] - self.points[0];
239        let c = point - self.points[0];
240        let a2 = a.dot(a);
242        let ab = a.dot(b);
243        let b2 = b.dot(b);
244        let ca = c.dot(a);
245        let cb = c.dot(b);
246        let denom = ab * ab - a2 * b2;
248        let x = ab * cb - b2 * ca;
249        let y = ab * ca - a2 * cb;
250        Point2D::new(x, y) / denom
251    }
252
253    pub fn transform(&self, transform: &Transform3D<f64>) -> Option<Polygon<A>> {
255        let mut points = [Point3D::origin(); 4];
256        for (out, point) in points.iter_mut().zip(self.points.iter()) {
257            let mut homo = transform.transform_point3d_homogeneous(*point);
258            homo.w = homo.w.max(f64::approx_epsilon());
259            *out = homo.to_point3d()?;
260        }
261
262        Polygon::from_points(points, self.anchor)
266    }
267
268    pub fn is_valid(&self) -> bool {
271        let is_planar = self
272            .points
273            .iter()
274            .all(|p| is_zero(self.plane.signed_distance_to(p)));
275        let edges = [
276            self.points[1] - self.points[0],
277            self.points[2] - self.points[1],
278            self.points[3] - self.points[2],
279            self.points[0] - self.points[3],
280        ];
281        let anchor = edges[3].cross(edges[0]);
282        let is_winding = edges
283            .iter()
284            .zip(edges[1..].iter())
285            .all(|(a, &b)| a.cross(b).dot(anchor) >= 0.0);
286        is_planar && is_winding
287    }
288
289    pub fn is_empty(&self) -> bool {
292        (self.points[0] - self.points[2]).square_length() < f64::EPSILON
293            || (self.points[1] - self.points[3]).square_length() < f64::EPSILON
294    }
295
296    pub fn contains(&self, other: &Self) -> bool {
298        self.plane.contains(&other.plane)
300    }
301
302    pub fn project_on(&self, vector: &Vector3D<f64>) -> LineProjection {
305        LineProjection {
306            markers: [
307                vector.dot(self.points[0].to_vector()),
308                vector.dot(self.points[1].to_vector()),
309                vector.dot(self.points[2].to_vector()),
310                vector.dot(self.points[3].to_vector()),
311            ],
312        }
313    }
314
315    pub fn intersect_plane(&self, other: &Plane) -> Intersection<Line> {
317        if other.are_outside(&self.points) {
318            log::debug!("\t\tOutside of the plane");
319            return Intersection::Outside;
320        }
321        match self.plane.intersect(&other) {
322            Some(line) => Intersection::Inside(line),
323            None => {
324                log::debug!("\t\tCoplanar");
325                Intersection::Coplanar
326            }
327        }
328    }
329
330    pub fn intersect(&self, other: &Self) -> Intersection<Line> {
332        if self.plane.are_outside(&other.points) || other.plane.are_outside(&self.points) {
333            log::debug!("\t\tOne is completely outside of the other");
334            return Intersection::Outside;
335        }
336        match self.plane.intersect(&other.plane) {
337            Some(line) => {
338                let self_proj = self.project_on(&line.dir);
339                let other_proj = other.project_on(&line.dir);
340                if self_proj.intersect(&other_proj) {
341                    Intersection::Inside(line)
342                } else {
343                    log::debug!("\t\tProjection is outside");
345                    Intersection::Outside
346                }
347            }
348            None => {
349                log::debug!("\t\tCoplanar");
350                Intersection::Coplanar
351            }
352        }
353    }
354
355    fn split_impl(
356        &mut self,
357        first: (usize, Point3D<f64>),
358        second: (usize, Point3D<f64>),
359    ) -> (Option<Self>, Option<Self>) {
360        log::debug!("\t\tReached complex case [{}, {}]", first.0, second.0);
363        let base = first.0;
364        assert!(base < self.points.len());
365        match second.0 - first.0 {
366            1 => {
367                let other1 = Polygon {
369                    points: [
370                        first.1,
371                        second.1,
372                        self.points[(base + 2) & 3],
373                        self.points[base],
374                    ],
375                    ..self.clone()
376                };
377                let other2 = Polygon {
379                    points: [
380                        self.points[(base + 2) & 3],
381                        self.points[(base + 3) & 3],
382                        self.points[base],
383                        self.points[base],
384                    ],
385                    ..self.clone()
386                };
387                self.points = [first.1, self.points[(base + 1) & 3], second.1, second.1];
389                (Some(other1), Some(other2))
390            }
391            2 => {
392                let other = Polygon {
394                    points: [
395                        first.1,
396                        self.points[(base + 1) & 3],
397                        self.points[(base + 2) & 3],
398                        second.1,
399                    ],
400                    ..self.clone()
401                };
402                self.points = [
404                    first.1,
405                    second.1,
406                    self.points[(base + 3) & 3],
407                    self.points[base],
408                ];
409                (Some(other), None)
410            }
411            3 => {
412                let other1 = Polygon {
414                    points: [
415                        first.1,
416                        self.points[(base + 1) & 3],
417                        self.points[(base + 3) & 3],
418                        second.1,
419                    ],
420                    ..self.clone()
421                };
422                let other2 = Polygon {
424                    points: [
425                        self.points[(base + 1) & 3],
426                        self.points[(base + 2) & 3],
427                        self.points[(base + 3) & 3],
428                        self.points[(base + 3) & 3],
429                    ],
430                    ..self.clone()
431                };
432                self.points = [first.1, second.1, self.points[base], self.points[base]];
434                (Some(other1), Some(other2))
435            }
436            _ => panic!("Unexpected indices {} {}", first.0, second.0),
437        }
438    }
439
440    #[deprecated(note = "Use split_with_normal instead")]
443    pub fn split(&mut self, line: &Line) -> (Option<Self>, Option<Self>) {
444        log::debug!("\tSplitting");
445        if !is_zero(self.plane.normal.dot(line.dir))
447            || !is_zero(self.plane.signed_distance_to(&line.origin))
448        {
449            log::debug!(
450                "\t\tDoes not belong to the plane, normal dot={:?}, origin distance={:?}",
451                self.plane.normal.dot(line.dir),
452                self.plane.signed_distance_to(&line.origin)
453            );
454            return (None, None);
455        }
456        let mut cuts = [None; 4];
458        for ((&b, &a), cut) in self
459            .points
460            .iter()
461            .cycle()
462            .skip(1)
463            .zip(self.points.iter())
464            .zip(cuts.iter_mut())
465        {
466            if let Some(t) = line.intersect_edge(a..b) {
467                if t >= 0.0 && t < 1.0 {
468                    *cut = Some(a + (b - a) * t);
469                }
470            }
471        }
472
473        let first = match cuts.iter().position(|c| c.is_some()) {
474            Some(pos) => pos,
475            None => return (None, None),
476        };
477        let second = match cuts[first + 1..].iter().position(|c| c.is_some()) {
478            Some(pos) => first + 1 + pos,
479            None => return (None, None),
480        };
481        self.split_impl(
482            (first, cuts[first].unwrap()),
483            (second, cuts[second].unwrap()),
484        )
485    }
486
487    pub fn split_with_normal(
492        &mut self,
493        line: &Line,
494        normal: &Vector3D<f64>,
495    ) -> (Option<Self>, Option<Self>) {
496        log::debug!("\tSplitting with normal");
497        let mut sides = [0.0; 4];
499        let (mut cut_positive, mut cut_negative) = (None, None);
500        for (side, point) in sides.iter_mut().zip(&self.points) {
501            *side = normal.dot(*point - line.origin);
502        }
503        for (i, ((&side1, point1), (&side0, point0))) in sides[1..]
505            .iter()
506            .chain(iter::once(&sides[0]))
507            .zip(self.points[1..].iter().chain(iter::once(&self.points[0])))
508            .zip(sides.iter().zip(&self.points))
509            .enumerate()
510        {
511            let cut = if side0 < 0.0 && side1 >= 0.0 {
513                &mut cut_positive
514            } else if side0 > 0.0 && side1 <= 0.0 {
515                &mut cut_negative
516            } else {
517                continue;
518            };
519            let point =
529                (*point0 * side1.abs() + point1.to_vector() * side0.abs()) / (side0 - side1).abs();
530            if cut.is_some() {
531                log::warn!("Splitting failed due to precision issues: {:?}", sides);
535                break;
536            }
537            *cut = Some((i, point));
538        }
539        if let (Some(first), Some(mut second)) = (cut_positive, cut_negative) {
541            if second.0 < first.0 {
542                second.0 += 4;
543            }
544            self.split_impl(first, second)
545        } else {
546            (None, None)
547        }
548    }
549
550    pub fn cut(
554        &self,
555        poly: &Self,
556        front: &mut SmallVec<[Polygon<A>; 2]>,
557        back: &mut SmallVec<[Polygon<A>; 2]>,
558    ) -> PlaneCut {
559        let (intersection, dist) = match self.plane.intersect(&poly.plane) {
561            None => {
562                let ndot = self.plane.normal.dot(poly.plane.normal);
563                let dist = self.plane.offset - ndot * poly.plane.offset;
564                (Intersection::Coplanar, dist)
565            }
566            Some(_) if self.plane.are_outside(&poly.points[..]) => {
567                let dist = self.plane.signed_distance_sum_to(&poly);
569                (Intersection::Outside, dist)
570            }
571            Some(line) => {
572                (Intersection::Inside(line), 0.0)
574            }
575        };
576
577        match intersection {
578            Intersection::Coplanar if is_zero(dist) => PlaneCut::Sibling,
582            Intersection::Coplanar | Intersection::Outside => {
583                if dist > 0.0 {
584                    front.push(poly.clone());
585                } else {
586                    back.push(poly.clone());
587                }
588
589                PlaneCut::Cut
590            }
591            Intersection::Inside(line) => {
592                let mut poly = poly.clone();
593                let (res_add1, res_add2) = poly.split_with_normal(&line, &self.plane.normal);
594
595                for sub in iter::once(poly)
596                    .chain(res_add1)
597                    .chain(res_add2)
598                    .filter(|p| !p.is_empty())
599                {
600                    let dist = self.plane.signed_distance_sum_to(&sub);
601                    if dist > 0.0 {
602                        front.push(sub)
603                    } else {
604                        back.push(sub)
605                    }
606                }
607
608                PlaneCut::Cut
609            }
610        }
611    }
612
613    pub fn is_aligned(&self, other: &Self) -> bool {
615        self.plane.normal.dot(other.plane.normal) > 0.0
616    }
617}
618
619#[derive(Debug, PartialEq)]
623pub enum PlaneCut {
624    Sibling,
626    Cut,
630}
631
632#[test]
633fn test_split_precision() {
634    let mut polygon = Polygon::<()> {
636        points: [
637            Point3D::new(300.0102, 150.00958, 0.0),
638            Point3D::new(606.0, 306.0, 0.0),
639            Point3D::new(300.21954, 150.11946, 0.0),
640            Point3D::new(300.08844, 150.05064, 0.0),
641        ],
642        plane: Plane {
643            normal: Vector3D::zero(),
644            offset: 0.0,
645        },
646        anchor: (),
647    };
648    let line = Line {
649        origin: Point3D::new(3.0690663, -5.8472385, 0.0),
650        dir: Vector3D::new(0.8854436, 0.46474677, -0.0),
651    };
652    let normal = Vector3D::new(0.46474662, -0.8854434, -0.0006389789);
653    polygon.split_with_normal(&line, &normal);
654}