bevy_heavy/dim2/
impls.rs

1use super::{ComputeMassProperties2d, MassProperties2d};
2use bevy_math::{
3    ops,
4    primitives::{
5        Annulus, Arc2d, Capsule2d, Circle, CircularSector, CircularSegment, ConvexPolygon, Ellipse,
6        Line2d, Measured2d, Plane2d, Polyline2d, Rectangle, RegularPolygon, Rhombus, Segment2d,
7        Triangle2d,
8    },
9    FloatPow, Vec2,
10};
11
12impl ComputeMassProperties2d for Circle {
13    #[inline]
14    fn mass(&self, density: f32) -> f32 {
15        self.area() * density
16    }
17
18    #[inline]
19    fn unit_angular_inertia(&self) -> f32 {
20        self.radius.squared() / 2.0
21    }
22
23    #[inline]
24    fn center_of_mass(&self) -> Vec2 {
25        Vec2::ZERO
26    }
27}
28
29impl ComputeMassProperties2d for CircularSector {
30    #[inline]
31    fn mass(&self, density: f32) -> f32 {
32        self.area() * density
33    }
34
35    #[inline]
36    fn unit_angular_inertia(&self) -> f32 {
37        0.5 * ops::powf(self.radius(), 4.0) * self.angle()
38    }
39
40    #[inline]
41    fn center_of_mass(&self) -> Vec2 {
42        let angle = self.angle();
43        let y = 2.0 * self.radius() * ops::sin(angle) / (3.0 * angle);
44        Vec2::new(0.0, y)
45    }
46}
47
48impl ComputeMassProperties2d for CircularSegment {
49    #[inline]
50    fn mass(&self, density: f32) -> f32 {
51        self.area() * density
52    }
53
54    #[inline]
55    fn unit_angular_inertia(&self) -> f32 {
56        let angle = self.angle();
57        let (sin, cos) = ops::sin_cos(angle);
58        ops::powf(self.radius(), 4.0) / 4.0 * (angle - sin + 2.0 / 3.0 * sin * (1.0 - cos) / 2.0)
59    }
60
61    #[inline]
62    fn center_of_mass(&self) -> Vec2 {
63        let y = self.radius() * ops::sin(self.half_angle()).cubed()
64            / (6.0 * self.half_angle() - ops::sin(self.angle()));
65        Vec2::new(0.0, y)
66    }
67}
68
69impl ComputeMassProperties2d for Ellipse {
70    #[inline]
71    fn mass(&self, density: f32) -> f32 {
72        self.area() * density
73    }
74
75    #[inline]
76    fn unit_angular_inertia(&self) -> f32 {
77        self.half_size.length_squared() / 4.0
78    }
79
80    #[inline]
81    fn center_of_mass(&self) -> Vec2 {
82        Vec2::ZERO
83    }
84}
85
86impl ComputeMassProperties2d for Annulus {
87    #[inline]
88    fn mass(&self, density: f32) -> f32 {
89        self.area() * density
90    }
91
92    #[inline]
93    fn unit_angular_inertia(&self) -> f32 {
94        0.5 * (self.outer_circle.radius.squared() + self.inner_circle.radius.squared())
95    }
96
97    #[inline]
98    fn center_of_mass(&self) -> Vec2 {
99        Vec2::ZERO
100    }
101}
102
103impl ComputeMassProperties2d for Triangle2d {
104    #[inline]
105    fn mass(&self, density: f32) -> f32 {
106        self.area() * density
107    }
108
109    #[inline]
110    fn unit_angular_inertia(&self) -> f32 {
111        // Adapted from Box2D: https://github.com/erincatto/box2d/blob/411acc32eb6d4f2e96fc70ddbdf01fe5f9b16230/src/collision/b2_polygon_shape.cpp#L274
112
113        // Note: The center of mass is used here, unlike in Box2D's or Parry's version.
114        let center_of_mass = self.center_of_mass();
115        let com_a = self.vertices[1] - center_of_mass;
116        let com_c = self.vertices[2] - center_of_mass;
117
118        (com_a.length_squared() + com_a.dot(com_c) + com_c.length_squared()) / 6.0
119    }
120
121    #[inline]
122    fn center_of_mass(&self) -> Vec2 {
123        (self.vertices[0] + self.vertices[1] + self.vertices[2]) / 3.0
124    }
125
126    #[inline]
127    fn mass_properties(&self, density: f32) -> MassProperties2d {
128        let area = self.area();
129        let center_of_mass = self.center_of_mass();
130
131        if area < f32::EPSILON {
132            return MassProperties2d::new(0.0, 0.0, center_of_mass);
133        }
134
135        let mass = area * density;
136
137        MassProperties2d::new(mass, self.angular_inertia(mass), center_of_mass)
138    }
139}
140
141impl ComputeMassProperties2d for Rectangle {
142    #[inline]
143    fn mass(&self, density: f32) -> f32 {
144        self.area() * density
145    }
146
147    #[inline]
148    fn unit_angular_inertia(&self) -> f32 {
149        self.half_size.length_squared() / 3.0
150    }
151
152    #[inline]
153    fn center_of_mass(&self) -> Vec2 {
154        Vec2::ZERO
155    }
156}
157
158impl ComputeMassProperties2d for Rhombus {
159    #[inline]
160    fn mass(&self, density: f32) -> f32 {
161        self.area() * density
162    }
163
164    #[inline]
165    fn unit_angular_inertia(&self) -> f32 {
166        self.half_diagonals.length_squared() / 12.0
167    }
168
169    #[inline]
170    fn center_of_mass(&self) -> Vec2 {
171        Vec2::ZERO
172    }
173}
174
175impl ComputeMassProperties2d for RegularPolygon {
176    #[inline]
177    fn mass(&self, density: f32) -> f32 {
178        self.area() * density
179    }
180
181    #[inline]
182    fn unit_angular_inertia(&self) -> f32 {
183        let half_external_angle = core::f32::consts::PI / self.sides as f32;
184        self.circumradius().squared() / 6.0 * (1.0 + 2.0 * ops::cos(half_external_angle).squared())
185    }
186
187    #[inline]
188    fn center_of_mass(&self) -> Vec2 {
189        Vec2::ZERO
190    }
191}
192
193impl ComputeMassProperties2d for Capsule2d {
194    #[inline]
195    fn mass(&self, density: f32) -> f32 {
196        let area = self.radius * (core::f32::consts::PI * self.radius + 4.0 * self.half_length);
197        area * density
198    }
199
200    #[inline]
201    fn unit_angular_inertia(&self) -> f32 {
202        // The rectangle and hemicircle parts
203        let rectangle = Rectangle {
204            half_size: Vec2::new(self.radius, self.half_length),
205        };
206        let rectangle_height = rectangle.half_size.y * 2.0;
207        let circle = Circle::new(self.radius);
208
209        // Areas
210        let rectangle_area = rectangle.area();
211        let circle_area = circle.area();
212
213        // Masses
214        let density = 1.0 / (rectangle_area + circle_area);
215        let rectangle_mass = rectangle_area * density;
216        let circle_mass = circle_area * density;
217
218        // Principal inertias
219        let rectangle_inertia = rectangle.angular_inertia(rectangle_mass);
220        let circle_inertia = circle.angular_inertia(circle_mass);
221
222        // Total inertia
223        let mut capsule_inertia = rectangle_inertia + circle_inertia;
224
225        // Compensate for the hemicircles being away from the rotation axis using the parallel axis theorem.
226        capsule_inertia += (rectangle_height.squared() * 0.25
227            + rectangle_height * self.radius * 3.0 / 8.0)
228            * circle_mass;
229
230        capsule_inertia
231    }
232
233    #[inline]
234    fn center_of_mass(&self) -> Vec2 {
235        Vec2::ZERO
236    }
237
238    #[inline]
239    fn mass_properties(&self, density: f32) -> MassProperties2d {
240        // The rectangle and hemicircle parts
241        let rectangle = Rectangle {
242            half_size: Vec2::new(self.radius, self.half_length),
243        };
244        let rectangle_height = rectangle.half_size.y * 2.0;
245        let circle = Circle::new(self.radius);
246
247        // Areas
248        let rectangle_area = rectangle.area();
249        let circle_area = circle.area();
250
251        // Masses
252        let rectangle_mass = rectangle_area * density;
253        let circle_mass = circle_area * density;
254
255        // Principal inertias
256        let rectangle_inertia = rectangle.angular_inertia(rectangle_mass);
257        let circle_inertia = circle.angular_inertia(circle_mass);
258
259        // Total inertia
260        let mut capsule_inertia = rectangle_inertia + circle_inertia;
261
262        // Compensate for the hemicircles being away from the rotation axis using the parallel axis theorem.
263        capsule_inertia += (rectangle_height.squared() * 0.25
264            + rectangle_height * self.radius * 3.0 / 8.0)
265            * circle_mass;
266
267        MassProperties2d::new(rectangle_mass + circle_mass, capsule_inertia, Vec2::ZERO)
268    }
269}
270
271impl ComputeMassProperties2d for ConvexPolygon {
272    #[inline]
273    fn mass(&self, density: f32) -> f32 {
274        convex_polygon_mass(self.vertices(), density)
275    }
276
277    #[inline]
278    fn unit_angular_inertia(&self) -> f32 {
279        convex_polygon_unit_angular_inertia(self.vertices())
280    }
281
282    #[inline]
283    fn center_of_mass(&self) -> Vec2 {
284        convex_polygon_area_and_center_of_mass(self.vertices()).1
285    }
286
287    #[inline]
288    fn mass_properties(&self, density: f32) -> MassProperties2d {
289        convex_polygon_mass_properties(self.vertices(), density)
290    }
291}
292
293/// Computes the mass of a convex polygon defined by its vertices and density.
294///
295/// No checks are performed to ensure the polygon is convex.
296#[inline]
297pub fn convex_polygon_mass(vertices: &[Vec2], density: f32) -> f32 {
298    let geometric_center =
299        vertices.iter().fold(Vec2::ZERO, |acc, vtx| acc + *vtx) / vertices.len() as f32;
300
301    // Initialize polygon area.
302    let mut area = 0.0;
303
304    // Create a peekable iterator over the polygon vertices.
305    let mut iter = vertices.iter().peekable();
306    let Some(first) = iter.peek().copied().copied() else {
307        return 0.0;
308    };
309
310    // Iterate through vertices, computing the sum of the areas of triangles.
311    // Each triangle is formed by the current vertex, next vertex, and the geometric center of the polygon.
312    while let Some(vertex) = iter.next() {
313        let (a, b, c) = (
314            *vertex,
315            iter.peek().copied().copied().unwrap_or(first),
316            geometric_center,
317        );
318        let tri_area = Triangle2d::new(a, b, c).area();
319        area += tri_area;
320    }
321
322    area * density
323}
324
325/// Computes the unit angular inertia of a convex polygon defined by its vertices.
326///
327/// No checks are performed to ensure the polygon is convex.
328#[inline]
329pub fn convex_polygon_unit_angular_inertia(vertices: &[Vec2]) -> f32 {
330    // The polygon is assumed to be convex.
331    let (area, center_of_mass) = convex_polygon_area_and_center_of_mass(vertices);
332
333    if area < f32::EPSILON {
334        return 0.0;
335    }
336
337    // Initialize polygon inertia.
338    let mut inertia = 0.0;
339
340    // Create a peekable iterator over the polygon vertices.
341    let mut iter = vertices.iter().peekable();
342    let first = **iter.peek().unwrap();
343
344    // Iterate through vertices, computing the sum of the areas of triangles.
345    // Each triangle is formed by the current vertex, next vertex, and the geometric center of the polygon.
346    while let Some(vertex) = iter.next() {
347        let triangle = Triangle2d::new(
348            *vertex,
349            iter.peek().copied().copied().unwrap_or(first),
350            center_of_mass,
351        );
352        inertia += triangle.unit_angular_inertia() * triangle.area();
353    }
354
355    inertia / area
356}
357
358/// Computes the mass properties of a convex polygon defined by its vertices and density.
359///
360/// No checks are performed to ensure the polygon is convex.
361#[inline]
362pub fn convex_polygon_mass_properties(vertices: &[Vec2], density: f32) -> MassProperties2d {
363    // The polygon is assumed to be convex.
364    let (area, center_of_mass) = convex_polygon_area_and_center_of_mass(vertices);
365
366    if area < f32::EPSILON {
367        return MassProperties2d::new(0.0, 0.0, center_of_mass);
368    }
369
370    // Initialize polygon inertia.
371    let mut inertia = 0.0;
372
373    // Create a peekable iterator over the polygon vertices.
374    let mut iter = vertices.iter().peekable();
375    let first = **iter.peek().unwrap();
376
377    // Iterate through vertices, computing the sum of the areas of triangles.
378    // Each triangle is formed by the current vertex, next vertex, and the geometric center of the polygon.
379    while let Some(vertex) = iter.next() {
380        let triangle = Triangle2d::new(
381            *vertex,
382            iter.peek().copied().copied().unwrap_or(first),
383            center_of_mass,
384        );
385        inertia += triangle.unit_angular_inertia() * triangle.area();
386    }
387
388    MassProperties2d::new(area * density, inertia * density, center_of_mass)
389}
390
391/// Computes the area and center of mass of a convex polygon defined by its vertices.
392///
393/// No checks are performed to ensure the polygon is convex.
394#[inline]
395pub fn convex_polygon_area_and_center_of_mass(vertices: &[Vec2]) -> (f32, Vec2) {
396    let geometric_center =
397        vertices.iter().fold(Vec2::ZERO, |acc, vtx| acc + *vtx) / vertices.len() as f32;
398
399    // Initialize polygon area and center.
400    let mut area = 0.0;
401    let mut center = Vec2::ZERO;
402
403    // Create a peekable iterator over the polygon vertices.
404    let mut iter = vertices.iter().peekable();
405    let Some(first) = iter.peek().copied().copied() else {
406        return (0.0, Vec2::ZERO);
407    };
408
409    // Iterate through vertices, computing the sum of the areas and centers of triangles.
410    // Each triangle is formed by the current vertex, next vertex, and the geometric center of the polygon.
411    while let Some(vertex) = iter.next() {
412        let (a, b, c) = (
413            *vertex,
414            iter.peek().copied().copied().unwrap_or(first),
415            geometric_center,
416        );
417        let tri_area = Triangle2d::new(a, b, c).area();
418        let tri_center = (a + b + c) / 3.0;
419
420        area += tri_area;
421        center += tri_center * tri_area;
422    }
423
424    if area < f32::EPSILON {
425        (area, geometric_center)
426    } else {
427        (area, center / area)
428    }
429}
430
431macro_rules! impl_zero_mass_properties_2d {
432    ($($shape:ty),*) => {
433        $(
434            impl ComputeMassProperties2d for $shape {
435                #[inline]
436                fn mass(&self, _density: f32) -> f32 {
437                    0.0
438                }
439
440                #[inline]
441                fn unit_angular_inertia(&self) -> f32 {
442                    0.0
443                }
444
445                #[inline]
446                fn angular_inertia(&self, _mass: f32) -> f32 {
447                    0.0
448                }
449
450                #[inline]
451                fn center_of_mass(&self) -> Vec2 {
452                    Vec2::ZERO
453                }
454
455                #[inline]
456                fn mass_properties(&self, _density: f32) -> MassProperties2d {
457                    MassProperties2d::ZERO
458                }
459            }
460        )*
461    };
462}
463
464impl_zero_mass_properties_2d!(Arc2d);
465impl_zero_mass_properties_2d!(Plane2d);
466impl_zero_mass_properties_2d!(Line2d);
467impl_zero_mass_properties_2d!(Segment2d);
468impl_zero_mass_properties_2d!(Polyline2d);
469
470#[cfg(test)]
471mod tests {
472    use alloc::vec::Vec;
473
474    use approx::assert_relative_eq;
475    use bevy_math::ShapeSample;
476    use rand::SeedableRng;
477
478    use super::*;
479
480    macro_rules! test_shape {
481        ($test_name:tt, $shape:expr) => {
482            #[test]
483            fn $test_name() {
484                let shape = $shape;
485
486                // Sample enough points to have a close enough point cloud representation of the shape.
487                let mut rng = rand_chacha::ChaCha8Rng::from_seed(Default::default());
488                let points = (0..1_000_000)
489                    .map(|_| shape.sample_interior(&mut rng))
490                    .collect::<Vec<_>>();
491
492                // Compute the mass properties to test.
493                let density = 2.0;
494                let mass = shape.mass(density);
495                let angular_inertia = shape.angular_inertia(mass);
496                let center_of_mass = shape.center_of_mass();
497
498                // First, test that the individually computed properties match the full properties.
499                let mass_props = shape.mass_properties(density);
500                assert_relative_eq!(mass, mass_props.mass);
501                assert_relative_eq!(angular_inertia, mass_props.angular_inertia);
502                assert_relative_eq!(center_of_mass, mass_props.center_of_mass);
503
504                // Estimate the expected mass properties using the point cloud.
505                // Note: We could also approximate the mass using Monte Carlo integration.
506                //       This would require point containment checks.
507                let expected = MassProperties2d::from_point_cloud(&points, mass);
508
509                assert_relative_eq!(mass, expected.mass);
510                assert_relative_eq!(angular_inertia, expected.angular_inertia, epsilon = 0.1);
511                assert_relative_eq!(center_of_mass, expected.center_of_mass, epsilon = 0.01);
512            }
513        };
514    }
515
516    // TODO: Test randomized shape definitions.
517
518    test_shape!(circle, Circle::new(2.0));
519    // test_shape!(circular_sector, CircularSector::new(2.0, TAU));
520    // test_shape!(circular_segment, CircularSegment::new(2.0, TAU));
521    // test_shape!(ellipse, Ellipse::new(2.0, 1.0));
522    test_shape!(annulus, Annulus::new(1.0, 2.0));
523    test_shape!(
524        triangle,
525        Triangle2d::new(
526            Vec2::new(8.0, 6.0),
527            Vec2::new(2.0, 0.0),
528            Vec2::new(6.0, 2.0)
529        )
530    );
531    test_shape!(rectangle, Rectangle::new(2.0, 1.0));
532    // test_shape!(rhombus, Rhombus::new(2.0, 1.0));
533    // test_shape!(regular_polygon, RegularPolygon::new(2.0, 6));
534    // test_shape!(polygon, Polygon::new([Vec2::ZERO, Vec2::X, Vec2::Y]));
535    test_shape!(capsule, Capsule2d::new(1.0, 0.25));
536}