parry3d/query/split/split_segment.rs
1use crate::math::{Real, Vector, VectorExt};
2use crate::query::SplitResult;
3use crate::shape::Segment;
4
5impl Segment {
6 /// Splits this segment along the given canonical axis.
7 ///
8 /// This will split the segment by a plane with a normal with it’s `axis`-th component set to 1.
9 /// The splitting plane is shifted wrt. the origin by the `bias` (i.e. it passes through the point
10 /// equal to `normal * bias`).
11 ///
12 /// # Result
13 /// Returns the result of the split. The first shape returned is the piece lying on the negative
14 /// half-space delimited by the splitting plane. The second shape returned is the piece lying on the
15 /// positive half-space delimited by the splitting plane.
16 pub fn canonical_split(&self, axis: usize, bias: Real, epsilon: Real) -> SplitResult<Self> {
17 // TODO: optimize this.
18 self.local_split(Vector::ith(axis, 1.0), bias, epsilon)
19 }
20
21 /// Splits this segment by a plane identified by its normal `local_axis` and
22 /// the `bias` (i.e. the plane passes through the point equal to `normal * bias`).
23 pub fn local_split(&self, local_axis: Vector, bias: Real, epsilon: Real) -> SplitResult<Self> {
24 self.local_split_and_get_intersection(local_axis, bias, epsilon)
25 .0
26 }
27
28 /// Split a segment with a plane.
29 ///
30 /// This returns the result of the splitting operation, as well as
31 /// the intersection point (and barycentric coordinate of this point)
32 /// with the plane. The intersection point is `None` if the plane is
33 /// parallel or near-parallel to the segment.
34 pub fn local_split_and_get_intersection(
35 &self,
36 local_axis: Vector,
37 bias: Real,
38 epsilon: Real,
39 ) -> (SplitResult<Self>, Option<(Vector, Real)>) {
40 let dir = self.b - self.a;
41 let a = bias - local_axis.dot(self.a);
42 let b = local_axis.dot(dir);
43 let bcoord = a / b;
44 let dir_norm = dir.length();
45
46 if relative_eq!(b, 0.0)
47 || bcoord * dir_norm <= epsilon
48 || bcoord * dir_norm >= dir_norm - epsilon
49 {
50 if a >= 0.0 {
51 (SplitResult::Negative, None)
52 } else {
53 (SplitResult::Positive, None)
54 }
55 } else {
56 let intersection = self.a + dir * bcoord;
57 let s1 = Segment::new(self.a, intersection);
58 let s2 = Segment::new(intersection, self.b);
59 if a >= 0.0 {
60 (SplitResult::Pair(s1, s2), Some((intersection, bcoord)))
61 } else {
62 (SplitResult::Pair(s2, s1), Some((intersection, bcoord)))
63 }
64 }
65 }
66}