Skip to main content

avian2d/collision/collider/parry/
primitives2d.rs

1use crate::{
2    ToRealPrecision,
3    math::{self, RVector, Real},
4};
5
6use super::{Collider, IntoCollider, ToF32Precision};
7use bevy::prelude::{Deref, DerefMut};
8use bevy_math::prelude::*;
9use bevy_shape::*;
10use parry::{
11    mass_properties::MassProperties,
12    math::Pose,
13    query::{
14        PointQuery, RayCast, details::local_ray_intersection_with_support_map_with_params,
15        gjk::VoronoiSimplex, point::local_point_projection_on_support_map,
16    },
17    shape::{
18        FeatureId, PackedFeatureId, PolygonalFeature, PolygonalFeatureMap, Shape, SharedShape,
19        SubShapeId, SupportMap,
20    },
21};
22
23const PI: Real = core::f64::consts::PI as Real;
24const TAU: Real = core::f64::consts::TAU as Real;
25const FRAC_PI_2: Real = core::f64::consts::FRAC_PI_2 as Real;
26
27impl IntoCollider<Collider> for Circle {
28    fn collider(&self) -> Collider {
29        Collider::circle(self.radius)
30    }
31}
32
33impl IntoCollider<Collider> for Ellipse {
34    fn collider(&self) -> Collider {
35        Collider::from(SharedShape::new(EllipseColliderShape(*self)))
36    }
37}
38
39/// An ellipse shape that can be stored in a [`SharedShape`] for an ellipse [`Collider`].
40///
41/// This wrapper is required to allow implementing the necessary traits from [`parry`]
42/// for Bevy's [`Ellipse`] type.
43#[derive(Clone, Copy, Debug, Deref, DerefMut)]
44pub struct EllipseColliderShape(pub Ellipse);
45
46impl SupportMap for EllipseColliderShape {
47    #[inline]
48    fn local_support_point(&self, direction: RVector) -> RVector {
49        let [a, b] = self.half_size.real().to_array();
50        let denom = (direction.x.powi(2) * a * a + direction.y.powi(2) * b * b).sqrt();
51        RVector::new(a * a * direction.x / denom, b * b * direction.y / denom)
52    }
53}
54
55impl Shape for EllipseColliderShape {
56    fn clone_dyn(&self) -> Box<dyn Shape> {
57        Box::new(*self)
58    }
59
60    fn scale_dyn(
61        &self,
62        scale: RVector,
63        _num_subdivisions: u32,
64    ) -> Option<Box<dyn parry::shape::Shape>> {
65        let half_size = scale.f32() * self.half_size;
66        Some(Box::new(EllipseColliderShape(Ellipse::new(
67            half_size.x,
68            half_size.y,
69        ))))
70    }
71
72    fn compute_local_aabb(&self) -> parry::bounding_volume::Aabb {
73        let aabb = self.aabb_2d(Isometry2d::IDENTITY);
74        parry::bounding_volume::Aabb::new(aabb.min.real(), aabb.max.real())
75    }
76
77    fn compute_aabb(&self, position: &Pose) -> parry::bounding_volume::Aabb {
78        let isometry = math::pose_to_isometry(position);
79        let aabb = self.aabb_2d(isometry);
80        parry::bounding_volume::Aabb::new(aabb.min.real(), aabb.max.real())
81    }
82
83    fn compute_local_bounding_sphere(&self) -> parry::bounding_volume::BoundingSphere {
84        let sphere = self.bounding_circle(Isometry2d::IDENTITY);
85        parry::bounding_volume::BoundingSphere::new(sphere.center.real(), sphere.radius().real())
86    }
87
88    fn compute_bounding_sphere(&self, position: &Pose) -> parry::bounding_volume::BoundingSphere {
89        let isometry = math::pose_to_isometry(position);
90        let sphere = self.bounding_circle(isometry);
91        parry::bounding_volume::BoundingSphere::new(sphere.center.real(), sphere.radius().real())
92    }
93
94    fn clone_box(&self) -> Box<dyn Shape> {
95        Box::new(*self)
96    }
97
98    fn mass_properties(&self, density: Real) -> MassProperties {
99        let volume = self.area().real();
100        let mass = volume * density;
101        let inertia = mass * self.half_size.length_squared().real() / 4.0;
102        MassProperties::new(RVector::ZERO, mass, inertia)
103    }
104
105    fn is_convex(&self) -> bool {
106        true
107    }
108
109    fn shape_type(&self) -> parry::shape::ShapeType {
110        parry::shape::ShapeType::Custom
111    }
112
113    fn as_typed_shape(&self) -> parry::shape::TypedShape<'_> {
114        parry::shape::TypedShape::Custom(self)
115    }
116
117    fn ccd_thickness(&self) -> Real {
118        self.half_size.max_element().real()
119    }
120
121    fn ccd_angular_thickness(&self) -> Real {
122        core::f64::consts::PI.real()
123    }
124
125    fn as_support_map(&self) -> Option<&dyn SupportMap> {
126        Some(self as &dyn SupportMap)
127    }
128}
129
130impl RayCast for EllipseColliderShape {
131    fn cast_local_ray_and_get_normal(
132        &self,
133        ray: &parry::query::Ray,
134        max_toi: Real,
135        solid: bool,
136    ) -> Option<parry::query::RayIntersection> {
137        local_ray_intersection_with_support_map_with_params(
138            self,
139            &mut VoronoiSimplex::new(),
140            ray,
141            max_toi,
142            solid,
143        )
144    }
145}
146
147impl PointQuery for EllipseColliderShape {
148    fn project_local_point(&self, pt: RVector, solid: bool) -> parry::query::PointProjection {
149        local_point_projection_on_support_map(self, &mut VoronoiSimplex::new(), pt, solid)
150    }
151
152    fn project_local_point_and_get_feature(
153        &self,
154        pt: RVector,
155    ) -> (parry::query::PointProjection, parry::shape::FeatureId) {
156        (self.project_local_point(pt, false), FeatureId::Unknown)
157    }
158}
159
160impl IntoCollider<Collider> for Plane2d {
161    fn collider(&self) -> Collider {
162        let vec = self.normal.perp() * 100_000.0 / 2.0;
163        Collider::segment(-vec, vec)
164    }
165}
166
167impl IntoCollider<Collider> for Line2d {
168    fn collider(&self) -> Collider {
169        let vec = self.direction * 100_000.0 / 2.0;
170        Collider::segment(-vec, vec)
171    }
172}
173
174impl IntoCollider<Collider> for Segment2d {
175    fn collider(&self) -> Collider {
176        let (point1, point2) = (self.point1(), self.point2());
177        Collider::segment(point1, point2)
178    }
179}
180
181impl IntoCollider<Collider> for Triangle2d {
182    fn collider(&self) -> Collider {
183        Collider::triangle(self.vertices[0], self.vertices[1], self.vertices[2])
184    }
185}
186
187impl IntoCollider<Collider> for Rectangle {
188    fn collider(&self) -> Collider {
189        Collider::from(SharedShape::cuboid(
190            self.half_size.x.real(),
191            self.half_size.y.real(),
192        ))
193    }
194}
195
196impl IntoCollider<Collider> for Polygon {
197    fn collider(&self) -> Collider {
198        let vertices = self.vertices.iter().map(|v| v.real()).collect::<Vec<_>>();
199        let indices = (0..self.vertices.len() as u32 - 1)
200            .map(|i| [i, i + 1])
201            .collect::<Vec<_>>();
202        Collider::convex_decomposition(&vertices, &indices)
203    }
204}
205
206impl IntoCollider<Collider> for ConvexPolygon {
207    fn collider(&self) -> Collider {
208        let vertices = self.vertices().iter().map(|v| v.real()).collect();
209        Collider::convex_polyline(vertices).unwrap()
210    }
211}
212
213impl IntoCollider<Collider> for RegularPolygon {
214    fn collider(&self) -> Collider {
215        Collider::from(SharedShape::new(RegularPolygonColliderShape(*self)))
216    }
217}
218
219/// A regular polygon shape that can be stored in a [`SharedShape`] for a regular polygon [`Collider`].
220///
221/// This wrapper is required to allow implementing the necessary traits from [`parry`]
222/// for Bevy's [`RegularPolygon`] type.
223#[derive(Clone, Copy, Debug, Deref, DerefMut)]
224pub struct RegularPolygonColliderShape(pub RegularPolygon);
225
226impl SupportMap for RegularPolygonColliderShape {
227    #[inline]
228    fn local_support_point(&self, direction: RVector) -> RVector {
229        // TODO: For polygons with a small number of sides, maybe just iterating
230        //       through the vertices and comparing dot products is faster?
231
232        let external_angle = self.external_angle_radians().real();
233        let circumradius = self.circumradius().real();
234
235        // Counterclockwise
236        let angle_from_top = if direction.x < 0.0 {
237            -direction.angle_to(RVector::Y)
238        } else {
239            TAU - direction.angle_to(RVector::Y)
240        };
241
242        // How many rotations of `external_angle` correspond to the vertex closest to the support direction.
243        let n = (angle_from_top / external_angle).round() % self.sides as Real;
244
245        // Rotate by an additional 90 degrees so that the first vertex is always at the top.
246        let target_angle = n * external_angle + FRAC_PI_2;
247
248        // Compute the vertex corresponding to the target angle on the unit circle.
249        circumradius * RVector::from_angle(target_angle)
250    }
251}
252
253impl PolygonalFeatureMap for RegularPolygonColliderShape {
254    #[inline]
255    fn local_support_feature(&self, direction: RVector, out_feature: &mut PolygonalFeature) {
256        let external_angle = self.external_angle_radians().real();
257        let circumradius = self.circumradius().real();
258
259        // Counterclockwise
260        let angle_from_top = if direction.x < 0.0 {
261            -direction.angle_to(RVector::Y)
262        } else {
263            TAU - direction.angle_to(RVector::Y)
264        };
265
266        // How many rotations of `external_angle` correspond to the vertices.
267        let n_unnormalized = angle_from_top / external_angle;
268        let n1 = n_unnormalized.floor() % self.sides as Real;
269        let n2 = n_unnormalized.ceil() % self.sides as Real;
270
271        // Rotate by an additional 90 degrees so that the first vertex is always at the top.
272        let target_angle1 = n1 * external_angle + FRAC_PI_2;
273        let target_angle2 = n2 * external_angle + FRAC_PI_2;
274
275        // Compute the vertices corresponding to the target angle on the unit circle.
276        let vertex1 = circumradius * RVector::from_angle(target_angle1);
277        let vertex2 = circumradius * RVector::from_angle(target_angle2);
278
279        *out_feature = PolygonalFeature {
280            vertices: [vertex1, vertex2],
281            vids: [
282                PackedFeatureId::vertex(n1 as u32),
283                PackedFeatureId::vertex(n2 as u32),
284            ],
285            fid: PackedFeatureId::face(n1 as u32),
286            num_vertices: 2,
287        };
288    }
289}
290
291impl Shape for RegularPolygonColliderShape {
292    fn clone_dyn(&self) -> Box<dyn Shape> {
293        Box::new(*self)
294    }
295
296    fn scale_dyn(
297        &self,
298        scale: RVector,
299        _num_subdivisions: u32,
300    ) -> Option<Box<dyn parry::shape::Shape>> {
301        let circumradius = scale.f32() * self.circumradius();
302        Some(Box::new(RegularPolygonColliderShape(RegularPolygon::new(
303            circumradius.length(),
304            self.sides,
305        ))))
306    }
307
308    fn compute_local_aabb(&self) -> parry::bounding_volume::Aabb {
309        let aabb = self.aabb_2d(Isometry2d::IDENTITY);
310        parry::bounding_volume::Aabb::new(aabb.min.real(), aabb.max.real())
311    }
312
313    fn compute_aabb(&self, position: &Pose) -> parry::bounding_volume::Aabb {
314        let isometry = math::pose_to_isometry(position);
315        let aabb = self.aabb_2d(isometry);
316        parry::bounding_volume::Aabb::new(aabb.min.real(), aabb.max.real())
317    }
318
319    fn compute_local_bounding_sphere(&self) -> parry::bounding_volume::BoundingSphere {
320        let sphere = self.bounding_circle(Isometry2d::IDENTITY);
321        parry::bounding_volume::BoundingSphere::new(sphere.center.real(), sphere.radius().real())
322    }
323
324    fn compute_bounding_sphere(&self, position: &Pose) -> parry::bounding_volume::BoundingSphere {
325        let isometry = math::pose_to_isometry(position);
326        let sphere = self.bounding_circle(isometry);
327        parry::bounding_volume::BoundingSphere::new(sphere.center.real(), sphere.radius().real())
328    }
329
330    fn clone_box(&self) -> Box<dyn Shape> {
331        Box::new(*self)
332    }
333
334    fn mass_properties(&self, density: Real) -> MassProperties {
335        let volume = self.area().real();
336        let mass = volume * density;
337
338        let half_external_angle = PI / self.sides as Real;
339        let angular_inertia = mass * self.circumradius().real().powi(2) / 6.0
340            * (1.0 + 2.0 * half_external_angle.cos().powi(2));
341
342        MassProperties::new(RVector::ZERO, mass, angular_inertia)
343    }
344
345    fn is_convex(&self) -> bool {
346        true
347    }
348
349    fn shape_type(&self) -> parry::shape::ShapeType {
350        parry::shape::ShapeType::Custom
351    }
352
353    fn as_typed_shape(&self) -> parry::shape::TypedShape<'_> {
354        parry::shape::TypedShape::Custom(self)
355    }
356
357    fn ccd_thickness(&self) -> Real {
358        self.circumradius().real()
359    }
360
361    fn ccd_angular_thickness(&self) -> Real {
362        core::f64::consts::PI.real() - self.internal_angle_radians().real()
363    }
364
365    fn as_support_map(&self) -> Option<&dyn SupportMap> {
366        Some(self as &dyn SupportMap)
367    }
368
369    fn as_polygonal_feature_map(&self) -> Option<(&dyn PolygonalFeatureMap, Real)> {
370        Some((self as &dyn PolygonalFeatureMap, 0.0))
371    }
372
373    fn feature_normal_at_point(
374        &self,
375        _subshape: SubShapeId,
376        feature: FeatureId,
377        _point: RVector,
378    ) -> Option<RVector> {
379        match feature {
380            FeatureId::Face(id) => {
381                let external_angle = self.external_angle_radians().real();
382                let normal_angle = id as Real * external_angle - external_angle * 0.5 + FRAC_PI_2;
383                Some(RVector::from_angle(normal_angle))
384            }
385            FeatureId::Vertex(id) => {
386                let external_angle = self.external_angle_radians().real();
387                let normal_angle = id as Real * external_angle + FRAC_PI_2;
388                Some(RVector::from_angle(normal_angle))
389            }
390            _ => None,
391        }
392    }
393}
394
395impl RayCast for RegularPolygonColliderShape {
396    fn cast_local_ray_and_get_normal(
397        &self,
398        ray: &parry::query::Ray,
399        max_toi: Real,
400        solid: bool,
401    ) -> Option<parry::query::RayIntersection> {
402        local_ray_intersection_with_support_map_with_params(
403            self,
404            &mut VoronoiSimplex::new(),
405            ray,
406            max_toi,
407            solid,
408        )
409    }
410}
411
412impl PointQuery for RegularPolygonColliderShape {
413    fn project_local_point(&self, pt: RVector, solid: bool) -> parry::query::PointProjection {
414        local_point_projection_on_support_map(self, &mut VoronoiSimplex::new(), pt, solid)
415    }
416
417    fn project_local_point_and_get_feature(
418        &self,
419        pt: RVector,
420    ) -> (parry::query::PointProjection, parry::shape::FeatureId) {
421        (self.project_local_point(pt, false), FeatureId::Unknown)
422    }
423}
424
425impl IntoCollider<Collider> for Capsule2d {
426    fn collider(&self) -> Collider {
427        Collider::capsule(self.radius, 2.0 * self.half_length)
428    }
429}