Debian Codegraph @

third_party/rust/plane-split/src/polygon.rs

raw
1 use crate::{is_zero, Line, Plane};
2
3 use euclid::{
4 approxeq::ApproxEq,
5 default::{Point2D, Point3D, Rect, Transform3D, Vector3D},
6 };
7 use smallvec::SmallVec;
8
9 use std::{iter, mem};
10
11 /// The projection of a `Polygon` on a line.
12 pub struct LineProjection {
13 /// Projected value of each point in the polygon.
14 pub markers: [f64; 4],
15 }
16
17 impl LineProjection {
18 /// Get the min/max of the line projection markers.
19 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 // bitonic sort of 4 elements
27 // we could not just use `min/max` since they require `Ord` bound
28 //TODO: make it nicer
29 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 /// Check intersection with another line projection.
49 pub fn intersect(&self, other: &Self) -> bool {
50 // compute the bounds of both line projections
51 let span = self.get_bounds();
52 let other_span = other.get_bounds();
53 // compute the total footprint
54 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 // they intersect if the footprint is smaller than the sum
65 right - left < span.1 - span.0 + other_span.1 - other_span.0
66 }
67 }
68
69 /// Polygon intersection results.
70 pub enum Intersection<T> {
71 /// Polygons are coplanar, including the case of being on the same plane.
72 Coplanar,
73 /// Polygon planes are intersecting, but polygons are not.
74 Outside,
75 /// Polygons are actually intersecting.
76 Inside(T),
77 }
78
79 impl<T> Intersection<T> {
80 /// Return true if the intersection is completely outside.
81 pub fn is_outside(&self) -> bool {
82 match *self {
83 Intersection::Outside => true,
84 _ => false,
85 }
86 }
87 /// Return true if the intersection cuts the source polygon.
88 pub fn is_inside(&self) -> bool {
89 match *self {
90 Intersection::Inside(_) => true,
91 _ => false,
92 }
93 }
94 }
95
96 /// A convex polygon with 4 points lying on a plane.
97 #[derive(Debug, PartialEq)]
98 pub struct Polygon<A> {
99 /// Points making the polygon.
100 pub points: [Point3D<f64>; 4],
101 /// A plane describing polygon orientation.
102 pub plane: Plane,
103 /// A simple anchoring index to allow association of the
104 /// produced split polygons with the original one.
105 pub anchor: A,
106 }
107
108 impl<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
123 impl<A> Polygon<A>
124 where
125 A: Copy,
126 {
127 /// Construct a polygon from points that are already transformed.
128 /// Return None if the polygon doesn't contain any space.
129 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 // one of them can be zero for redundant polygons produced by plane splitting
140 //Note: this would be nicer if we used triangles instead of quads in the first place...
141 // see https://github.com/servo/plane-split/issues/17
142 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 /// Construct a polygon from a non-transformed rectangle.
162 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 /// Construct a polygon from a rectangle with 3D transform.
181 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 /// Construct a polygon from a rectangle with an invertible 3D transform.
198 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 // Compute the normal directly from the transformation. This guarantees consistent polygons
214 // generated from various local rectanges on the same geometry plane.
215 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 /// Bring a point into the local coordinate space, returning
233 /// the 2D normalized coordinates.
234 pub fn untransform_point(&self, point: Point3D<f64>) -> Point2D<f64> {
235 //debug_assert!(self.contains(point));
236 // get axises and target vector
237 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 // get pair-wise dot products
241 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 // compute the final coordinates
247 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 /// Transform a polygon by an affine transform (preserving straight lines).
254 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 //Note: this code path could be more efficient if we had inverse-transpose
263 //let n4 = transform.transform_point4d(&Point4D::new(0.0, 0.0, T::one(), 0.0));
264 //let normal = Point3D::new(n4.x, n4.y, n4.z);
265 Polygon::from_points(points, self.anchor)
266 }
267
268 /// Check if all the points are indeed placed on the plane defined by
269 /// the normal and offset, and the winding order is consistent.
270 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 /// Check if the polygon doesn't contain any space. This may happen
290 /// after a sequence of splits, and such polygons should be discarded.
291 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 /// Check if this polygon contains another one.
297 pub fn contains(&self, other: &Self) -> bool {
298 //TODO: actually check for inside/outside
299 self.plane.contains(&other.plane)
300 }
301
302 /// Project this polygon onto a 3D vector, returning a line projection.
303 /// Note: we can think of it as a projection to a ray placed at the origin.
304 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 /// Compute the line of intersection with an infinite plane.
316 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 /// Compute the line of intersection with another polygon.
331 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 // projections on the line don't intersect
344 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 //TODO: can be optimized for when the polygon has a redundant 4th vertex
361 //TODO: can be simplified greatly if only working with triangles
362 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 // rect between the cut at the diagonal
368 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 // triangle on the near side of the diagonal
378 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 // triangle being cut out
388 self.points = [first.1, self.points[(base + 1) & 3], second.1, second.1];
389 (Some(other1), Some(other2))
390 }
391 2 => {
392 // rect on the far side
393 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 // rect on the near side
403 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 // rect between the cut at the diagonal
413 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 // triangle on the far side of the diagonal
423 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 // triangle being cut out
433 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 /// Split the polygon along the specified `Line`.
441 /// Will do nothing if the line doesn't belong to the polygon plane.
442 #[deprecated(note = "Use split_with_normal instead")]
443 pub fn split(&mut self, line: &Line) -> (Option<Self>, Option<Self>) {
444 log::debug!("\tSplitting");
445 // check if the cut is within the polygon plane first
446 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 // compute the intersection points for each edge
457 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 /// Split the polygon along the specified `Line`, with a normal to the split line provided.
488 /// This is useful when called by the plane splitter, since the other plane's normal
489 /// forms the side direction here, and figuring out the actual line of split isn't needed.
490 /// Will do nothing if the line doesn't belong to the polygon plane.
491 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 // figure out which side of the split does each point belong to
498 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 // compute the edge intersection points
504 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 // figure out if an edge between 0 and 1 needs to be cut
512 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 // compute the cut point by weighting the opposite distances
520 //
521 // Note: this algorithm is designed to not favor one end of the edge over the other.
522 // The previous approach of calling `intersect_edge` sometimes ended up with "t" ever
523 // slightly outside of [0, 1] range, since it was computing it relative to the first point only.
524 //
525 // Given that we are intersecting two straight lines, the triangles on both
526 // sides of intersection are alike, so distances along the [point0, point1] line
527 // are proportional to the side vector lengths we just computed: (side0, side1).
528 let point =
529 (*point0 * side1.abs() + point1.to_vector() * side0.abs()) / (side0 - side1).abs();
530 if cut.is_some() {
531 // We don't expect that the direction changes more than once, unless
532 // the polygon is close to redundant, and we hit precision issues when
533 // computing the sides.
534 log::warn!("Splitting failed due to precision issues: {:?}", sides);
535 break;
536 }
537 *cut = Some((i, point));
538 }
539 // form new polygons
540 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 /// Cut a polygon with another one.
551 ///
552 /// Write the resulting polygons in `front` and `back` if the polygon needs to be split.
553 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 //Note: we treat `self` as a plane, and `poly` as a concrete polygon here
560 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 //Note: we can't start with `are_outside` because it's subject to FP precision
568 let dist = self.plane.signed_distance_sum_to(&poly);
569 (Intersection::Outside, dist)
570 }
571 Some(line) => {
572 //Note: distance isn't relevant here
573 (Intersection::Inside(line), 0.0)
574 }
575 };
576
577 match intersection {
578 //Note: we deliberately make the comparison wider than just with T::epsilon().
579 // This is done to avoid mistakenly ordering items that should be on the same
580 // plane but end up slightly different due to the floating point precision.
581 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 /// Returns whether both polygon's planes are parallel.
614 pub fn is_aligned(&self, other: &Self) -> bool {
615 self.plane.normal.dot(other.plane.normal) > 0.0
616 }
617 }
618
619 /// The result of a polygon being cut by a plane.
620 /// The "cut" here is an attempt to classify a plane as being
621 /// in front or in the back of another one.
622 #[derive(Debug, PartialEq)]
623 pub enum PlaneCut {
624 /// The planes are one the same geometrical plane.
625 Sibling,
626 /// Planes are different, thus we can either determine that
627 /// our plane is completely in front/back of another one,
628 /// or split it into these sub-groups.
629 Cut,
630 }
631
632 #[test]
633 fn test_split_precision() {
634 // regression test for https://bugzilla.mozilla.org/show_bug.cgi?id=1678454
635 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 }