bevy_rapier2d/geometry/shape_views/triangle.rs
1use crate::math::{Real, Vect};
2use rapier::parry::shape::Triangle;
3
4/// Read-only access to the properties of a triangle.
5#[derive(Copy, Clone)]
6pub struct TriangleView<'a> {
7 /// The raw shape from Rapier.
8 pub raw: &'a Triangle,
9}
10
11macro_rules! impl_ref_methods(
12 ($View: ident) => {
13 impl<'a> $View<'a> {
14 /// The triangle first point.
15 pub fn a(&self) -> Vect {
16 self.raw.a.into()
17 }
18
19 /// The triangle second point.
20 pub fn b(&self) -> Vect {
21 self.raw.b.into()
22 }
23
24 /// The triangle third point.
25 pub fn c(&self) -> Vect {
26 self.raw.c.into()
27 }
28
29 /// Reference to an array containing the three vertices of this triangle.
30 #[inline]
31 pub fn vertices(&self) -> [Vect; 3] {
32 let vtx = self.raw.vertices();
33 [vtx[0].into(), vtx[1].into(), vtx[2].into()]
34 }
35
36 /// The normal of this triangle assuming it is oriented ccw.
37 ///
38 /// The normal points such that it is collinear to `AB × AC` (where `×` denotes the cross
39 /// product).
40 #[cfg(feature = "dim3")]
41 #[inline]
42 pub fn normal(&self) -> Option<Vect> {
43 self.raw.normal().map(|n| (*n).into())
44 }
45
46 /// A vector normal of this triangle.
47 ///
48 /// The vector points such that it is collinear to `AB × AC` (where `×` denotes the cross
49 /// product).
50 #[cfg(feature = "dim3")]
51 #[inline]
52 pub fn scaled_normal(&self) -> Vect {
53 self.raw.scaled_normal().into()
54 }
55
56 /// The area of this triangle.
57 #[inline]
58 pub fn area(&self) -> Real {
59 self.raw.area()
60 }
61
62 /// The geometric center of this triangle.
63 #[inline]
64 pub fn center(&self) -> Vect {
65 self.raw.center().into()
66 }
67
68 /// The perimeter of this triangle.
69 #[inline]
70 pub fn perimeter(&self) -> Real {
71 self.raw.perimeter()
72 }
73
74 /// The circumcircle of this triangle.
75 pub fn circumcircle(&self) -> (Vect, Real) {
76 let (center, radius) = self.raw.circumcircle();
77 (center.into(), radius)
78 }
79 }
80 }
81);
82
83impl_ref_methods!(TriangleView);
84
85/// Read-write access to the properties of a triangle.
86pub struct TriangleViewMut<'a> {
87 /// The raw shape from Rapier.
88 pub raw: &'a mut Triangle,
89}
90
91impl_ref_methods!(TriangleViewMut);
92
93impl TriangleViewMut<'_> {
94 /// Set the first point of the segment.
95 pub fn set_a(&mut self, a: Vect) {
96 self.raw.a = a.into();
97 }
98
99 /// Set the second point of the segment.
100 pub fn set_b(&mut self, b: Vect) {
101 self.raw.b = b.into();
102 }
103
104 /// Set the third point of the segment.
105 pub fn set_c(&mut self, c: Vect) {
106 self.raw.c = c.into();
107 }
108}