engeom 0.5.0

Library for working with geometry with a focus on engineering metrology applications.
Documentation
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
//! Distance queries and measurements on meshes

use super::{Mesh3, MeshSurfPoint};
use crate::common::barycentric::barycentric_point;
use crate::common::points::dist;
use crate::common::{IndexMask, PCoords};
use crate::{Iso3, Plane3, Point3, Result, SurfacePoint3};
use parry3d_f64::query::{PointProjection, PointQueryWithLocation, SplitResult};
use parry3d_f64::shape::TrianglePointLocation;
use std::f64::consts::PI;

impl Mesh3 {
    /// This is an extremely simple closest distance query that returns only the scalar distance
    /// from the mesh to the point. It does not return any information about the face or which
    /// side of the corresponding face normal the point is on.  It will always return a single
    /// zero or positive value, which is the distance from the point to its closest projection on
    /// the mesh.
    ///
    /// # Arguments
    ///
    /// * `point`: the test point to seek the closest distance to
    ///
    /// returns: f64
    pub fn distance_closest_to(&self, point: &impl PCoords<3>) -> f64 {
        let point = Point3::from(point.coords());
        let result = self
            .shape
            .project_local_point_and_get_location(&point, self.is_solid);
        let (projection, _) = result;
        dist(&point, &projection.point)
    }

    /// Get the point and normal of a position on the mesh given a face ID and the barycentric
    /// coordinates of interest within the face.
    ///
    /// If the face ID is invalid or the normal is invalid, an error is returned.
    ///
    /// # Arguments
    ///
    /// * `face_id`: The ID of the face to query.
    /// * `bc`: An array of barycentric coordinates [u, v, w] where u + v + w = 1.0.
    ///
    /// returns: Result<SurfacePoint<3>, Box<dyn Error, Global>>
    pub fn at_barycentric(&self, face_id: u32, bc: [f64; 3]) -> Result<MeshSurfPoint> {
        if face_id >= self.faces().len() as u32 {
            return Err("Invalid face ID".into());
        }

        let face = self.shape.triangle(face_id);
        let at = barycentric_point(&face.a, &face.b, &face.c, bc);
        let normal = face.normal().ok_or("No face normal found")?;
        let sp = SurfacePoint3::new(at, normal);
        Ok(MeshSurfPoint {
            face_index: face_id,
            bc,
            sp,
        })
    }

    /// Find the index of the face that is closest to the given point in local coordinates.
    ///
    /// # Arguments
    ///
    /// * `point`: the test point to seek the closest face to
    ///
    /// returns: u32
    pub fn face_closest_to(&self, point: &impl PCoords<3>) -> u32 {
        let point = Point3::from(point.coords());
        let result = self
            .shape
            .project_local_point_and_get_location(&point, self.is_solid);
        let (_, (tri_id, _)) = result;
        tri_id
    }

    /// Find the closest point on the mesh surface to the specified test point. This method will
    /// return a descriptor which includes the face index, barycentric coordinates, and a
    /// point/normal combination.
    ///
    /// # Arguments
    ///
    /// * `point`: the test point to seek the closest surface point to
    ///
    /// returns: MeshSurfPoint
    pub fn surface_closest_to(&self, point: &impl PCoords<3>) -> MeshSurfPoint {
        let point = Point3::from(point.coords());
        let result = self
            .shape
            .project_local_point_and_get_location(&point, self.is_solid);
        let (projection, (tri_id, location)) = result;
        let triangle = self.shape.triangle(tri_id);
        let normal = triangle.normal().expect("Triangle doesn't have a normal");
        let sp = SurfacePoint3::new(projection.point, normal);
        let bc = location
            .barycentric_coordinates()
            .expect("Barycentric coordinates should be valid");

        MeshSurfPoint {
            face_index: tri_id,
            bc,
            sp,
        }
    }

    /// Find the closest point on the mesh surface to the specified point.
    ///
    /// This returns only the projected position, not the face index, barycentric
    /// coordinates, or surface normal. If the point projects onto an edge or vertex,
    /// the returned position is the nearest point on the mesh surface at that location.
    ///
    /// # Arguments
    ///
    /// * `point` - The test point to project onto the mesh.
    ///
    /// # Returns
    ///
    /// The closest point on the mesh surface to `point`.
    pub fn point_closest_to(&self, point: &impl PCoords<3>) -> Point3 {
        let query = Point3::from(point.coords());
        let (result, _) = self
            .shape
            .project_local_point_and_get_location(&query, self.is_solid);
        result.point
    }

    pub fn project_with_max_dist(
        &self,
        point: &impl PCoords<3>,
        max_dist: f64,
    ) -> Option<(PointProjection, u32, TrianglePointLocation)> {
        // TODO: Needs test coverage
        let point = Point3::from(point.coords());
        self.shape
            .project_local_point_and_get_location_with_max_dist(&point, self.is_solid, max_dist)
            .map(|(prj, (id, loc))| (prj, id, loc))
    }

    /// Given a test point, return its projection onto the mesh *if and only if* it is within the
    /// given distance tolerance from the mesh and the angle between the normal of the triangle and
    /// the +/- vector from the triangle to the point is less than the given angle tolerance.
    ///
    /// When a test point projects onto to the face of a triangle, the vector from the triangle
    /// point to the test point will be parallel to the triangle normal, by definition.  The angle
    /// tolerance will come into effect when the test point projects to an edge or vertex.  This
    /// will happen occasionally when the test point is near an edge with two triangles that reflex
    /// away from the point, and it will happen when the test point is beyond the edge of the mesh.
    ///
    /// A point lying on the surface itself always passes the angle test. Its offset from the
    /// projection is rounding noise with an arbitrary direction, so the angle is meaningless there.
    ///
    /// # Arguments
    ///
    /// * `point`: the test point to project onto the mesh
    /// * `max_dist`: the maximum search distance from the test point to find a projection
    /// * `max_angle`: the max allowable angle deviation between the mesh normal at the projection
    ///   and the vector from the projection to the test point
    /// * `transform`: an optional transform to apply to the test point before projecting it onto
    ///   the mesh
    ///
    /// returns: Option<(PointProjection, u32, TrianglePointLocation)>
    pub fn project_with_tol(
        &self,
        point: &impl PCoords<3>,
        max_dist: f64,
        max_angle: f64,
        transform: Option<&Iso3>,
    ) -> Option<(PointProjection, u32, TrianglePointLocation)> {
        let point = Point3::from(point.coords());
        let point = if let Some(transform) = transform {
            transform * point
        } else {
            point
        };

        let result = self
            .shape
            .project_local_point_and_get_location_with_max_dist(&point, self.is_solid, max_dist);
        if let Some((prj, (id, loc))) = result {
            let local = point - prj.point;
            let triangle = self.shape.triangle(id);
            if let Some(normal) = triangle.normal() {
                // At rounding level the offset has no meaningful direction, so the angle test is
                // skipped rather than allowed to reject a point which is on the surface.
                let on_surface = local.norm() <= 1.0e-12 * point.coords.norm().max(1.0);
                let angle = normal.angle(&local).abs();
                if on_surface || angle < max_angle || angle > PI - max_angle {
                    Some((prj, id, loc))
                } else {
                    None
                }
            } else {
                None
            }
        } else {
            None
        }
    }

    /// Find which of the given points project onto the mesh within the given distance and angle
    /// tolerances.
    ///
    /// The returned mask is indexed by **the given `points` slice**, not by the mesh's own points
    /// or faces, and so has the same length as `points`.
    ///
    /// # Arguments
    ///
    /// * `points`: the points to test
    /// * `max_dist`: the furthest a point may be from the mesh and still be kept
    /// * `max_angle`: the largest angle allowed between the point's direction of approach and the
    ///   surface normal at its projection
    /// * `transform`: an optional transform applied to each point before it is projected
    ///
    /// returns: `IndexMask` over `points`, set where the point is within tolerance of the mesh
    pub fn find_points_in_tol(
        &self,
        points: &[Point3],
        max_dist: f64,
        max_angle: f64,
        transform: Option<&Iso3>,
    ) -> IndexMask {
        // TODO: Needs test coverage
        let mut result = IndexMask::new(points.len(), false);
        for (i, point) in points.iter().enumerate() {
            if self
                .project_with_tol(point, max_dist, max_angle, transform)
                .is_some()
            {
                result.set(i, true);
            }
        }
        result
    }

    /// Split the mesh by a plane into the portions on the negative and positive sides.
    ///
    /// If the plane intersects the mesh, the result contains two new meshes:
    /// - `Pair(negative, positive)` when the mesh is cut into two parts
    /// - `Negative` when the entire mesh lies on the negative side of the plane
    /// - `Positive` when the entire mesh lies on the positive side of the plane
    ///
    /// The returned meshes are newly constructed from the split triangle meshes and are not
    /// solid.
    ///
    /// # Attributes
    ///
    /// The cut introduces new points along the plane and re-triangulates the faces it crosses, and
    /// `parry3d` gives no mapping from the result back to the original. There is therefore no
    /// correct value to carry any attribute forward with, so a mesh which has any is refused unless
    /// the caller says the loss is acceptable.
    ///
    /// Note that `Negative` and `Positive` mean the plane missed the mesh entirely, so nothing is
    /// rebuilt and nothing would have been lost. The check still runs, because whether the plane
    /// intersects is not something the caller can be expected to know in advance, and an operation
    /// which silently kept the attributes on one path and dropped them on another would be worse
    /// than one which is consistent.
    ///
    /// # Arguments
    ///
    /// * `plane`: the plane used to split the mesh
    /// * `allow_attribute_loss`: accept the loss of every attribute this mesh carries
    ///
    /// # Returns
    ///
    /// A `SplitResult<Mesh3>` describing how the mesh relates to the plane.
    pub fn split(&self, plane: &Plane3, allow_attribute_loss: bool) -> Result<SplitResult<Mesh3>> {
        self.check_attribute_loss("a plane split", allow_attribute_loss)?;

        let result = self.shape.local_split(&plane.normal, plane.d, 1.0e-6);
        Ok(match result {
            SplitResult::Pair(a, b) => {
                let mesh_a = Mesh3::from_trimesh(a, false);
                let mesh_b = Mesh3::from_trimesh(b, false);
                SplitResult::Pair(mesh_a, mesh_b)
            }
            SplitResult::Negative => SplitResult::Negative,
            SplitResult::Positive => SplitResult::Positive,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::geom3::Mesh3;
    use crate::tests::stanford_bun_4;
    use approx::assert_relative_eq;
    use parry3d_f64::na::Vector3;

    #[test]
    fn distance_closest_to_unit_box_face() {
        let mesh = Mesh3::create_box(1.0, 1.0, 1.0, false);
        let point = Point3::new(1.5, 0.0, 0.0);

        let distance = mesh.distance_closest_to(&point);
        let closest = mesh.point_closest_to(&point);

        assert_relative_eq!(distance, 1.0, epsilon = 1.0e-12);
        assert_relative_eq!(closest, Point3::new(0.5, 0.0, 0.0), epsilon = 1.0e-12);
    }

    #[test]
    fn distance_closest_to_unit_box_edge() {
        let mesh = Mesh3::create_box(1.0, 1.0, 1.0, false);
        let point = Point3::new(1.5, 1.5, 0.0);

        let distance = mesh.distance_closest_to(&point);
        let closest = mesh.point_closest_to(&point);

        assert_relative_eq!(distance, 2.0_f64.sqrt(), epsilon = 1.0e-12);
        assert_relative_eq!(closest, Point3::new(0.5, 0.5, 0.0), epsilon = 1.0e-12);
    }

    #[test]
    fn distance_closest_to_unit_box_corner_vertex() {
        let mesh = Mesh3::create_box(1.0, 1.0, 1.0, false);
        let point = Point3::new(1.5, 1.5, 1.5);

        let distance = mesh.distance_closest_to(&point);
        let closest = mesh.point_closest_to(&point);

        assert_relative_eq!(distance, 3.0_f64.sqrt(), epsilon = 1.0e-12);
        assert_relative_eq!(closest, Point3::new(0.5, 0.5, 0.5), epsilon = 1.0e-12);
    }

    #[test]
    fn closest_to_matches_brute_force_on_unit_box() {
        let mesh = Mesh3::create_box(1.0, 1.0, 1.0, false);
        let eps = 1.0e-12;

        for (face_index, face) in mesh.faces().iter().enumerate() {
            let face_index = face_index as u32;
            let a = mesh.points()[face[0] as usize];
            let b = mesh.points()[face[1] as usize];
            let c = mesh.points()[face[2] as usize];

            let centroid = Point3::from((a.coords + b.coords + c.coords) / 3.0);
            let normal = mesh.tri_mesh().triangle(face_index).normal().unwrap();

            let edge1 = b - a;
            let edge2 = c - a;
            let tangent = if edge1.norm_squared() > eps {
                edge1.normalize()
            } else {
                edge2.normalize()
            };
            let bitangent = normal.cross(&tangent).normalize();

            // Sample points across the face plane and slightly off the surface on both sides.
            for u in [-0.40, -0.20, 0.0, 0.20, 0.40] {
                for v in [-0.40, -0.20, 0.0, 0.20, 0.40] {
                    for n in [-0.25, 0.0, 0.25] {
                        let query =
                            centroid + tangent * u + bitangent * v + normal.into_inner() * n;

                        let brute = brute_force_closest(&query, &mesh);

                        // Check the closest face
                        let closest_face = mesh.face_closest_to(&query);
                        assert!(
                            brute.iter().any(|(id, _)| *id == closest_face),
                            "face_closest_to returned face {} for query {:?}, but brute force found {:?}",
                            closest_face,
                            query,
                            brute.iter().map(|(id, _)| *id).collect::<Vec<_>>()
                        );

                        // Check the closest surface
                        let closest_surf = mesh.surface_closest_to(&query);
                        assert!(
                            brute.iter().any(|(id, _)| *id == closest_surf.face_index),
                            "surface_closest_to returned face {} for query {:?}, but brute force found {:?}",
                            closest_surf.face_index,
                            query,
                            brute.iter().map(|(id, _)| *id).collect::<Vec<_>>()
                        );
                        let cp = brute
                            .iter()
                            .find(|(id, _)| *id == closest_surf.face_index)
                            .unwrap()
                            .1;
                        assert_relative_eq!(cp, closest_surf.sp.point, epsilon = 1.0e-12);
                        let abc = mesh
                            .at_barycentric(closest_surf.face_index, closest_surf.bc)
                            .unwrap();
                        assert_relative_eq!(cp, abc.sp.point, epsilon = 1.0e-12);
                        assert_relative_eq!(
                            abc.sp.normal,
                            closest_surf.sp.normal,
                            epsilon = 1.0e-12
                        );
                    }
                }
            }
        }
    }

    #[test]
    fn project_with_tol_accepts_the_surface_and_rejects_beyond_the_edge() {
        let mesh = Mesh3::create_box(2.0, 2.0, 2.0, false);
        let max_angle = std::f64::consts::PI / 4.0;

        // Above a face, within distance.
        let (prj, _, _) = mesh
            .project_with_tol(&Point3::new(0.3, -0.2, 1.05), 0.1, max_angle, None)
            .expect("above the +z face");
        assert_relative_eq!(prj.point, Point3::new(0.3, -0.2, 1.0), epsilon = 1e-12);

        // On the face itself, where the offset from the projection is rounding noise.
        assert!(
            mesh.project_with_tol(&Point3::new(0.3, -0.2, 1.0), 0.1, max_angle, None)
                .is_some()
        );

        // Too far away.
        assert!(
            mesh.project_with_tol(&Point3::new(0.3, -0.2, 1.2), 0.1, max_angle, None)
                .is_none()
        );

        // Off the edge of the box at the height of the +z face: the projection lands on the edge
        // at a right angle to both adjacent normals.
        assert!(
            mesh.project_with_tol(&Point3::new(1.05, -0.2, 1.05), 0.2, max_angle, None)
                .is_none()
        );

        // A transform moves the point before projecting.
        let shift = Iso3::translation(0.0, 0.0, -0.5);
        assert!(
            mesh.project_with_tol(&Point3::new(0.3, -0.2, 1.55), 0.1, max_angle, Some(&shift))
                .is_some()
        );
    }

    #[test]
    fn at_barycentric_matches_face_vertices_and_center() {
        let mesh = stanford_bun_4();

        for (face_id, face) in mesh.faces().iter().enumerate() {
            let face_id = face_id as u32;
            let a = mesh.points()[face[0] as usize];
            let b = mesh.points()[face[1] as usize];
            let c = mesh.points()[face[2] as usize];

            let expected_normal = mesh.tri_mesh().triangle(face_id).normal().unwrap();

            let vertex_cases = [
                ([1.0, 0.0, 0.0], a),
                ([0.0, 1.0, 0.0], b),
                ([0.0, 0.0, 1.0], c),
                (
                    [1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0],
                    Point3::from((a.coords + b.coords + c.coords) / 3.0),
                ),
            ];

            for (bc, expected_point) in vertex_cases {
                let sp = mesh.at_barycentric(face_id, bc).unwrap();

                assert_eq!(sp.face_index, face_id);
                assert_relative_eq!(sp.bc[0], bc[0], epsilon = 1.0e-12);
                assert_relative_eq!(sp.bc[1], bc[1], epsilon = 1.0e-12);
                assert_relative_eq!(sp.bc[2], bc[2], epsilon = 1.0e-12);
                assert_relative_eq!(sp.point(), expected_point, epsilon = 1.0e-12);
                assert_relative_eq!(
                    sp.normal().into_inner(),
                    expected_normal.into_inner(),
                    epsilon = 1.0e-12
                );
            }
        }
    }

    #[test]
    fn check_brute_force_closest_edge() {
        let mesh = Mesh3::create_box(1.0, 1.0, 1.0, false);
        let point = Point3::new(1.5, 1.5, 0.0);

        let results = brute_force_closest(&point, &mesh);
        assert_eq!(results.len(), 2);
        for (_, p) in results.iter() {
            assert_relative_eq!(*p, Point3::new(0.5, 0.5, 0.0), epsilon = 1.0e-12);
        }
    }

    #[test]
    fn check_brute_force_closest_face() {
        let mesh = Mesh3::create_box(1.0, 1.0, 1.0, false);
        let point = Point3::new(0.33, 0.0, 0.51);

        let results = brute_force_closest(&point, &mesh);
        assert_eq!(results.len(), 1);
        for (_, p) in results.iter() {
            assert_relative_eq!(*p, Point3::new(0.33, 0.0, 0.5), epsilon = 1.0e-12);
        }
    }

    fn brute_force_closest(query_point: &Point3, mesh: &Mesh3) -> Vec<(u32, Point3)> {
        let mut closest: Vec<(u32, Point3)> = Vec::new();
        let mut best_dist = f64::INFINITY;

        for (face_index, face) in mesh.faces().iter().enumerate() {
            let a = mesh.points()[face[0] as usize];
            let b = mesh.points()[face[1] as usize];
            let c = mesh.points()[face[2] as usize];

            let closest_point = manual_closest_point_on_triangle(a, b, c, *query_point);
            let dist = dist(&closest_point, query_point);

            if dist + f64::EPSILON < best_dist {
                best_dist = dist;
                closest.clear();
                closest.push((face_index as u32, closest_point));
            } else if (dist - best_dist).abs() <= f64::EPSILON {
                closest.push((face_index as u32, closest_point));
            }
        }

        closest
    }
    #[test]
    fn split_unit_box_through_center_yields_two_nonempty_parts() -> Result<()> {
        let mesh = Mesh3::create_box(1.0, 1.0, 1.0, false);
        let plane = Plane3::yz();

        match mesh.split(&plane, false)? {
            SplitResult::Pair(negative, positive) => {
                assert!(!negative.faces().is_empty());
                assert!(!positive.faces().is_empty());

                for vertex in negative.points() {
                    assert!(vertex.x <= 1.0e-12);
                }
                for vertex in positive.points() {
                    assert!(vertex.x >= -1.0e-12);
                }
            }
            _ => panic!("expected mesh to split into two parts"),
        }

        Ok(())
    }

    #[test]
    fn split_unit_box_with_plane_outside_returns_positive_side() -> Result<()> {
        let mesh = Mesh3::create_box(1.0, 1.0, 1.0, false);
        let plane = Plane3::new(Vector3::x_axis(), -2.0);

        match mesh.split(&plane, false)? {
            SplitResult::Positive => {}
            _ => panic!("expected whole mesh on positive side"),
        }

        Ok(())
    }

    #[test]
    fn split_unit_box_with_plane_outside_returns_negative_side() -> Result<()> {
        let mesh = Mesh3::create_box(1.0, 1.0, 1.0, false);
        let plane = Plane3::new(Vector3::x_axis(), 2.0);

        match mesh.split(&plane, false)? {
            SplitResult::Negative => {}
            _ => panic!("expected whole mesh on negative side"),
        }

        Ok(())
    }

    fn manual_closest_point_on_triangle(a: Point3, b: Point3, c: Point3, p: Point3) -> Point3 {
        let ab = b - a;
        let ac = c - a;
        let ap = p - a;

        let d1 = ab.dot(&ap);
        let d2 = ac.dot(&ap);
        if d1 <= 0.0 && d2 <= 0.0 {
            return a;
        }

        let bp = p - b;
        let d3 = ab.dot(&bp);
        let d4 = ac.dot(&bp);
        if d3 >= 0.0 && d4 <= d3 {
            return b;
        }

        let vc = d1 * d4 - d3 * d2;
        if vc <= 0.0 && d1 >= 0.0 && d3 <= 0.0 {
            let v = d1 / (d1 - d3);
            return a + ab * v;
        }

        let cp = p - c;
        let d5 = ab.dot(&cp);
        let d6 = ac.dot(&cp);
        if d6 >= 0.0 && d5 <= d6 {
            return c;
        }

        let vb = d5 * d2 - d1 * d6;
        if vb <= 0.0 && d2 >= 0.0 && d6 <= 0.0 {
            let w = d2 / (d2 - d6);
            return a + ac * w;
        }

        let va = d3 * d6 - d5 * d4;
        if va <= 0.0 && (d4 - d3) >= 0.0 && (d5 - d6) >= 0.0 {
            let bc = c - b;
            let w = (d4 - d3) / ((d4 - d3) + (d5 - d6));
            return b + bc * w;
        }

        let denom = 1.0 / (va + vb + vc);
        let v = vb * denom;
        let w = vc * denom;
        a + ab * v + ac * w
    }
}