ncollide3d/query/contact/
contact_ball_convex_polyhedron.rs

1use crate::math::{Isometry, Point};
2use crate::query::Contact;
3use crate::shape::{Ball, FeatureId, Shape};
4use na::{self, RealField, Unit};
5
6/// Contact between a ball and a convex polyhedron.
7///
8/// This function panics if the input shape does not implement
9/// both the ConvexPolyhedron and PointQuery traits.
10#[inline]
11pub fn contact_ball_convex_polyhedron<N: RealField + Copy>(
12    ball_center1: &Point<N>,
13    ball1: &Ball<N>,
14    m2: &Isometry<N>,
15    shape2: &(impl Shape<N> + ?Sized),
16    prediction: N,
17) -> Option<Contact<N>> {
18    // NOTE: this code is mostly taken from the narrow-phase's BallConvexPolyhedronManifoldGenerator
19    // after removal of all the code related to contact kinematics because it is not needed here
20    // TODE: is there a way to refactor this to avoid duplication?.
21    let poly2 = shape2
22        .as_convex_polyhedron()
23        .expect("The input shape does not implement the ConvexPolyhedron trait.");
24    let pt_query2 = shape2
25        .as_point_query()
26        .expect("The input shape does not implement the PointQuery trait.");
27
28    let (proj, f2) = pt_query2.project_point_with_feature(m2, &ball_center1);
29    let world2 = proj.point;
30    let dpt = world2 - ball_center1;
31
32    let depth;
33    let normal;
34    if let Some((dir, dist)) = Unit::try_new_and_get(dpt, N::default_epsilon()) {
35        if proj.is_inside {
36            depth = dist + ball1.radius;
37            normal = -dir;
38        } else {
39            depth = -dist + ball1.radius;
40            normal = dir;
41        }
42    } else {
43        if f2 == FeatureId::Unknown {
44            // We cant do anything more at this point.
45            return None;
46        }
47
48        depth = ball1.radius;
49        normal = -poly2.feature_normal(f2);
50    }
51
52    if depth >= -prediction {
53        let world1 = ball_center1 + normal.into_inner() * ball1.radius;
54        return Some(Contact::new(world1, world2, normal, depth));
55    }
56
57    None
58}
59
60/// Contact between a convex polyhedron and a ball.
61///
62/// This function panics if the input shape does not implement
63/// both the ConvexPolyhedron and PointQuery traits.
64#[inline]
65pub fn contact_convex_polyhedron_ball<N: RealField + Copy>(
66    m1: &Isometry<N>,
67    poly1: &(impl Shape<N> + ?Sized),
68    ball_center2: &Point<N>,
69    ball2: &Ball<N>,
70    prediction: N,
71) -> Option<Contact<N>> {
72    let mut res = contact_ball_convex_polyhedron(ball_center2, ball2, m1, poly1, prediction);
73    if let Some(c) = &mut res {
74        c.flip()
75    }
76    res
77}