1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411
use crate::prelude::*;
use bevy::prelude::*;
#[cfg(feature = "3d")]
use crate::utils::get_rotated_inertia_tensor;
/// The mass of a body.
#[derive(Reflect, Clone, Copy, Component, Debug, Default, Deref, DerefMut, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[reflect(Component)]
pub struct Mass(pub Scalar);
impl Mass {
/// Zero mass.
pub const ZERO: Self = Self(0.0);
}
/// The inverse mass of a body.
#[derive(Reflect, Clone, Copy, Component, Debug, Default, Deref, DerefMut, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[reflect(Component)]
pub struct InverseMass(pub Scalar);
impl InverseMass {
/// Zero inverse mass.
pub const ZERO: Self = Self(0.0);
}
/// The moment of inertia of a body. This represents the torque needed for a desired angular acceleration.
#[cfg(feature = "2d")]
#[derive(Reflect, Clone, Copy, Component, Debug, Default, Deref, DerefMut, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[reflect(Component)]
pub struct Inertia(pub Scalar);
/// The local moment of inertia of the body as a 3x3 tensor matrix.
/// This represents the torque needed for a desired angular acceleration along different axes.
///
/// This is computed in local-space, so the object's orientation is not taken into account.
///
/// To get the world-space version that takes the body's rotation into account,
/// use the associated `rotated` method. Note that this operation is quite expensive, so use it sparingly.
#[cfg(feature = "3d")]
#[derive(Reflect, Clone, Copy, Component, Debug, Deref, DerefMut, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[reflect(Component)]
pub struct Inertia(pub Matrix3);
#[cfg(feature = "3d")]
impl Default for Inertia {
fn default() -> Self {
Self(Matrix3::ZERO)
}
}
impl Inertia {
/// Zero angular inertia.
#[cfg(feature = "2d")]
pub const ZERO: Self = Self(0.0);
/// Zero angular inertia.
#[cfg(feature = "3d")]
pub const ZERO: Self = Self(Matrix3::ZERO);
/// In 2D this does nothing, but it is there for convenience so that
/// you don't have to handle 2D and 3D separately.
#[cfg(feature = "2d")]
#[allow(dead_code)]
pub(crate) fn rotated(&self, _rot: &Rotation) -> Self {
*self
}
/// Returns the inertia tensor's world-space version that takes
/// the body's orientation into account.
#[cfg(feature = "3d")]
pub fn rotated(&self, rot: &Rotation) -> Self {
Self(get_rotated_inertia_tensor(self.0, rot.0))
}
/// Returns the inverted moment of inertia.
#[cfg(feature = "2d")]
pub fn inverse(&self) -> InverseInertia {
InverseInertia(1.0 / self.0)
}
/// Returns the inverted moment of inertia.
#[cfg(feature = "3d")]
pub fn inverse(&self) -> InverseInertia {
InverseInertia(self.0.inverse())
}
/// Computes the inertia of a body with the given mass, shifted by the given offset.
#[cfg(feature = "2d")]
pub fn shifted(&self, mass: Scalar, offset: Vector) -> Scalar {
if mass > 0.0 && mass.is_finite() {
self.0 + offset.length_squared() * mass
} else {
self.0
}
}
/// Computes the inertia of a body with the given mass, shifted by the given offset.
#[cfg(feature = "3d")]
pub fn shifted(&self, mass: Scalar, offset: Vector) -> Matrix3 {
type NaMatrix3 = parry::na::Matrix3<math::Scalar>;
use parry::na::*;
if mass > 0.0 && mass.is_finite() {
let matrix = NaMatrix3::from(self.0);
let offset = Vector::from(offset);
let diagonal_el = offset.norm_squared();
let diagonal_mat = NaMatrix3::from_diagonal_element(diagonal_el);
math::Matrix3::from(matrix + (diagonal_mat + offset * offset.transpose()) * mass)
} else {
self.0
}
}
}
/// The inverse moment of inertia of the body. This represents the inverse of
/// the torque needed for a desired angular acceleration.
#[cfg(feature = "2d")]
#[derive(Reflect, Clone, Copy, Component, Debug, Default, Deref, DerefMut, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[reflect(Component)]
pub struct InverseInertia(pub Scalar);
/// The local inverse moment of inertia of the body as a 3x3 tensor matrix.
/// This represents the inverse of the torque needed for a desired angular acceleration along different axes.
///
/// This is computed in local-space, so the object's orientation is not taken into account.
///
/// To get the world-space version that takes the body's rotation into account,
/// use the associated `rotated` method. Note that this operation is quite expensive, so use it sparingly.
#[cfg(feature = "3d")]
#[derive(Reflect, Clone, Copy, Component, Debug, Deref, DerefMut, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[reflect(Component)]
pub struct InverseInertia(pub Matrix3);
#[cfg(feature = "3d")]
impl Default for InverseInertia {
fn default() -> Self {
InverseInertia(Matrix3::ZERO)
}
}
impl InverseInertia {
/// Zero inverse angular inertia.
#[cfg(feature = "2d")]
pub const ZERO: Self = Self(0.0);
/// Zero inverse angular inertia.
#[cfg(feature = "3d")]
pub const ZERO: Self = Self(Matrix3::ZERO);
/// In 2D this does nothing, but it is there for convenience so that
/// you don't have to handle 2D and 3D separately.
#[cfg(feature = "2d")]
pub fn rotated(&self, _rot: &Rotation) -> Self {
*self
}
/// Returns the inertia tensor's world-space version that takes the body's orientation into account.
#[cfg(feature = "3d")]
pub fn rotated(&self, rot: &Rotation) -> Self {
Self(get_rotated_inertia_tensor(self.0, rot.0))
}
/// Returns the original moment of inertia.
#[cfg(feature = "2d")]
pub fn inverse(&self) -> Inertia {
Inertia(1.0 / self.0)
}
/// Returns the original moment of inertia.
#[cfg(feature = "3d")]
pub fn inverse(&self) -> Inertia {
Inertia(self.0.inverse())
}
}
impl From<Inertia> for InverseInertia {
fn from(inertia: Inertia) -> Self {
inertia.inverse()
}
}
/// The local center of mass of a body.
#[derive(Reflect, Clone, Copy, Component, Debug, Default, Deref, DerefMut, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[reflect(Component)]
pub struct CenterOfMass(pub Vector);
impl CenterOfMass {
/// A center of mass set at the local origin.
pub const ZERO: Self = Self(Vector::ZERO);
}
/// A bundle containing mass properties.
///
/// ## Example
///
/// The easiest way to create a new bundle is to use the [`new_computed`](Self::new_computed) method
/// that computes the mass properties based on a given [`Collider`] and density.
///
/// ```
/// use bevy::prelude::*;
#[cfg_attr(feature = "2d", doc = "use bevy_xpbd_2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use bevy_xpbd_3d::prelude::*;")]
///
/// fn setup(mut commands: Commands) {
/// commands.spawn((
/// RigidBody::Dynamic,
/// MassPropertiesBundle::new_computed(&Collider::ball(0.5), 1.0)
/// ));
/// }
/// ```
#[allow(missing_docs)]
#[derive(Bundle, Debug, Default, Clone, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
pub struct MassPropertiesBundle {
pub mass: Mass,
pub inverse_mass: InverseMass,
pub inertia: Inertia,
pub inverse_inertia: InverseInertia,
pub center_of_mass: CenterOfMass,
}
impl MassPropertiesBundle {
/// Computes the mass properties for a [`Collider`] based on its shape and a given density.
pub fn new_computed(collider: &Collider, density: Scalar) -> Self {
let ColliderMassProperties {
mass,
inverse_mass,
inertia,
inverse_inertia,
center_of_mass,
..
} = collider.mass_properties(density);
Self {
mass,
inverse_mass,
inertia,
inverse_inertia,
center_of_mass,
}
}
}
/// The density of a [`Collider`], 1.0 by default. This is used for computing
/// the [`ColliderMassProperties`] for each collider.
///
/// ## Example
///
/// ```
/// use bevy::prelude::*;
#[cfg_attr(feature = "2d", doc = "use bevy_xpbd_2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use bevy_xpbd_3d::prelude::*;")]
///
/// // Spawn a body with a collider that has a density of 2.5
/// fn setup(mut commands: Commands) {
/// commands.spawn((
/// RigidBody::Dynamic,
/// Collider::ball(0.5),
/// ColliderDensity(2.5),
/// ));
/// }
/// ```
#[derive(Reflect, Clone, Copy, Component, Debug, Deref, DerefMut, PartialEq, PartialOrd)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[reflect(Component)]
pub struct ColliderDensity(pub Scalar);
impl ColliderDensity {
/// The density of the [`Collider`] is zero. It has no mass.
pub const ZERO: Self = Self(0.0);
}
impl Default for ColliderDensity {
fn default() -> Self {
Self(1.0)
}
}
/// An automatically added component that contains the read-only mass properties of a [`Collider`].
/// The density used for computing the mass properties can be configured using the [`ColliderDensity`]
/// component.
///
/// These mass properties will be added to the [rigid body's](RigidBody) actual [`Mass`],
/// [`InverseMass`], [`Inertia`], [`InverseInertia`] and [`CenterOfMass`] components.
///
/// ## Example
///
/// ```no_run
/// use bevy::prelude::*;
#[cfg_attr(feature = "2d", doc = "use bevy_xpbd_2d::prelude::*;")]
#[cfg_attr(feature = "3d", doc = "use bevy_xpbd_3d::prelude::*;")]
///
/// fn main() {
/// App::new()
/// .add_plugins((DefaultPlugins, PhysicsPlugins::default()))
/// .add_systems(Startup, setup)
/// .add_systems(Update, print_collider_masses)
/// .run();
/// }
///
/// fn setup(mut commands: Commands) {
/// commands.spawn(Collider::ball(0.5));
/// }
///
/// fn print_collider_masses(query: Query<&ColliderMassProperties>) {
/// for mass_props in &query {
/// println!("{}", mass_props.mass());
/// }
/// }
/// ```
#[derive(Reflect, Clone, Copy, Component, Debug, PartialEq)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[reflect(Component)]
pub struct ColliderMassProperties {
/// Mass given by collider.
pub(crate) mass: Mass,
/// Inverse mass given by collider.
pub(crate) inverse_mass: InverseMass,
/// Inertia given by collider.
pub(crate) inertia: Inertia,
/// Inverse inertia given by collider.
pub(crate) inverse_inertia: InverseInertia,
/// Local center of mass given by collider.
pub(crate) center_of_mass: CenterOfMass,
}
impl ColliderMassProperties {
/// The collider has no mass.
pub const ZERO: Self = Self {
mass: Mass::ZERO,
inverse_mass: InverseMass(Scalar::INFINITY),
inertia: Inertia::ZERO,
inverse_inertia: InverseInertia::ZERO,
center_of_mass: CenterOfMass::ZERO,
};
/// Computes mass properties from a given [`Collider`] and density.
///
/// Because [`ColliderMassProperties`] is read-only, adding this as a component manually
/// has no effect. The mass properties will be recomputed using the [`ColliderDensity`].
pub fn new(collider: &Collider, density: Scalar) -> Self {
let props = collider.shape_scaled().mass_properties(density);
Self {
mass: Mass(props.mass()),
inverse_mass: InverseMass(props.inv_mass),
#[cfg(feature = "2d")]
inertia: Inertia(props.principal_inertia()),
#[cfg(feature = "3d")]
inertia: Inertia(props.reconstruct_inertia_matrix().into()),
#[cfg(feature = "2d")]
inverse_inertia: InverseInertia(1.0 / props.principal_inertia()),
#[cfg(feature = "3d")]
inverse_inertia: InverseInertia(props.reconstruct_inverse_inertia_matrix().into()),
center_of_mass: CenterOfMass(props.local_com.into()),
}
}
/// Get the [mass](Mass) of the [`Collider`].
pub fn mass(&self) -> Scalar {
self.mass.0
}
/// Get the [inverse mass](InverseMass) of the [`Collider`].
pub fn inverse_mass(&self) -> Scalar {
self.inverse_mass.0
}
/// Get the [inerta](Inertia) of the [`Collider`].
#[cfg(feature = "2d")]
pub fn inertia(&self) -> Scalar {
self.inertia.0
}
/// Get the [inertia tensor](InverseInertia) of the [`Collider`].
#[cfg(feature = "3d")]
pub fn inertia(&self) -> Matrix3 {
self.inertia.0
}
/// Get the [inverse inertia](InverseInertia) of the [`Collider`].
#[cfg(feature = "2d")]
pub fn inverse_inertia(&self) -> Scalar {
self.inverse_inertia.0
}
/// Get the [inverse inertia](InverseInertia) of the [`Collider`].
#[cfg(feature = "3d")]
pub fn inverse_inertia(&self) -> Matrix3 {
self.inverse_inertia.0
}
/// Get the [local center of mass](CenterOfMass) of the [`Collider`].
pub fn center_of_mass(&self) -> Vector {
self.center_of_mass.0
}
}
impl Default for ColliderMassProperties {
fn default() -> Self {
Self::ZERO
}
}