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 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717
use super::*;
/// Represents data for setting up a physics shape
#[allow(missing_docs)] // TODO: Remove
#[derive(Clone, Debug)]
pub enum PhysicsShapeDesc {
/// A box centered at `center` with a half size of `half_size`
Box {
center: Vec3,
half_size: Vec3,
rotation: Quat,
},
/// A sphere centered at `center` with a radius of `radius` (radius must be larger than zero)
Sphere { center: Vec3, radius: f32 },
/// A capsule spanning from `pos0` to `pos1` with a radius of `radius` at its ends (radius must be larger than zero)
Capsule { pos0: Vec3, pos1: Vec3, radius: f32 },
}
/// Represents a set of physics shapes
///
/// Used with the `Physics` component to create more complex physics shapes
/// by combining primitive shapes.
#[derive(Debug, Clone, PartialEq)]
pub struct CompoundPhysicsShape {
data: WorldData,
}
#[allow(dead_code)]
impl CompoundPhysicsShape {
/// Creates a new `CompoundPhysicsShape`. This creates a data object in the host that can be shared
/// for multiple entities. Spheres and capsules must have a radius larger than zero.
pub fn new<Iter>(descs: Iter) -> Self
where
Iter: Iterator<Item = PhysicsShapeDesc>,
{
let mut boxes = vec![];
let mut spheres = vec![];
let mut capsules = vec![];
for desc in descs {
match desc {
PhysicsShapeDesc::Box {
center,
half_size,
rotation,
} => {
// Allow zero-side boxes?
boxes.push(ffi::PhysicsShapeBox {
center: center.into(),
half_size: half_size.into(),
rotation: rotation.into(),
});
}
PhysicsShapeDesc::Sphere { center, radius } => {
if radius.is_finite() && radius > 0.0 {
spheres.push(ffi::PhysicsShapeSphere {
center: center.into(),
radius,
});
} else {
log::warn!("Sphere with invalid radius {} skipped", radius);
}
}
PhysicsShapeDesc::Capsule { pos0, pos1, radius } => {
if radius.is_finite() && radius > 0.0 {
capsules.push(ffi::PhysicsShapeCapsule {
pos0: pos0.into(),
pos1: pos1.into(),
radius,
});
} else {
log::warn!("Capsule with invalid radius {} skipped", radius);
}
}
}
}
let data_desc = ffi::CompoundPhysicsShape {
num_boxes: boxes.len() as u32,
boxes_ptr: (boxes.as_ptr().cast::<ffi::PhysicsShapeBox>()) as u32,
num_spheres: spheres.len() as u32,
spheres_ptr: (spheres.as_ptr().cast::<ffi::PhysicsShapeSphere>()) as u32,
num_capsules: capsules.len() as u32,
capsules_ptr: (capsules.as_ptr().cast::<ffi::PhysicsShapeCapsule>()) as u32,
};
let data = WorldData::create_struct(ffi::CreateDataType::CompoundPhysicsShape, &data_desc);
Self { data }
}
/// Sets a debug name of this data object. Useful for debugging memory usage and leaks.
pub fn set_debug_name(&self, name: &str) {
self.data.set_debug_name(name);
}
}
impl ValueConverterTrait<CompoundPhysicsShape> for ValueConverter {
fn into_value(v: CompoundPhysicsShape) -> Value {
<Self as ValueConverterTrait<WorldData>>::into_value(v.data)
}
fn from_value(v: &Value) -> CompoundPhysicsShape {
CompoundPhysicsShape {
data: <Self as ValueConverterTrait<WorldData>>::from_value(v),
}
}
}
/// Used to describe what physics shape the `Physics` component should use.
#[derive(Debug, Clone, PartialEq)]
pub enum PhysicsShape {
/// A sphere physics shape configured from the `Bounds` bounding sphere.
Sphere,
/// A box physics shape configured from the `Bounds` bounding box.
Box,
/// A capsule physics shape configured from the `Bounds` bounding box.
Capsule,
/// A mesh physics shape. Can only be used for static or kinematic physics objects.
Mesh,
/// A compound physics shape of multiple `PhysicsShapeDesc` described primitives.
Compound(CompoundPhysicsShape),
/// The convex hull of a mesh, can be used for any type of physics object.
ConvexMesh,
}
impl PhysicsShape {
#[allow(missing_docs)]
pub fn as_ffi(&self) -> ffi::PhysicsShape {
match self {
Self::Sphere => ffi::PhysicsShape::Sphere,
Self::Box => ffi::PhysicsShape::Box,
Self::Capsule => ffi::PhysicsShape::Capsule,
Self::Mesh => ffi::PhysicsShape::Mesh,
Self::Compound(_) => ffi::PhysicsShape::Compound,
Self::ConvexMesh => ffi::PhysicsShape::ConvexMesh,
}
}
}
/// Physics component.
///
/// Use to turn on and off physics processing and to set up physical properties and movement of an object.
pub struct Physics {
id: Entity,
}
impl std::fmt::Debug for Physics {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Physics")
.field("entity", &self.id.name())
.field("velocity", &self.velocity().get())
.field("angular_velocity", &self.angular_velocity().get())
.field("mass", &self.mass().get())
.field("center_of_mass", &self.center_of_mass().get())
.field("mass_rotation", &self.mass_rotation().get())
.field("inertia_tensor", &self.inertia_tensor().get())
.field("linear_damping", &self.linear_damping().get())
.field("angular_damping", &self.angular_damping().get())
.field(
"solver_position_iterations",
&self.solver_position_iterations().get(),
)
.field(
"solver_velocity_iterations",
&self.solver_velocity_iterations().get(),
)
.finish_non_exhaustive()
}
}
impl Physics {
/// Turns on physics processing for this mesh, as a dynamic entity.
///
/// The layer set in `Layer` component, if any, will be used for collisions.
///
/// It will also remove the transform parent, if set.
/// Note: Density is in kg/m3, so a value of 1000.0 is appropriate for water, maybe 700 for wood, 8000 for steel.
pub fn enable_dynamic(&self, density: f32, shape: PhysicsShape) {
if shape == PhysicsShape::Mesh || density <= 0.0 {
panic!(
"Calling enable_dynamic on mesh shapes or when not having density set is invalid"
);
}
World::set_entity_value(
self.id,
ffi::ComponentType::Physics,
ffi::Physics::PhysxDensity.into(),
&Value::from_f32(density),
);
World::set_entity_value(
self.id,
ffi::ComponentType::Physics,
ffi::Physics::PhysxDynamicEnable.into(),
&Value::from_bool(true),
);
World::set_entity_value(
self.id,
ffi::ComponentType::Physics,
ffi::Physics::PhysxKinematic.into(),
&Value::from_bool(false),
);
World::set_entity_value(
self.id,
ffi::ComponentType::Physics,
ffi::Physics::PhysxShape.into(),
&Value::from_i64(shape.as_ffi() as i64),
);
if let PhysicsShape::Compound(data) = shape {
self.compound_shape().set(data);
}
World::set_entity_value(
self.id,
ffi::ComponentType::Physics,
ffi::Physics::PhysxEnable.into(),
&Value::from_bool(true),
);
World::create_body_immediate(self.id);
}
/// Enables physics processing, as a static entity which will not move as a result of physics.
///
/// The layer set in `Layer` component, if any, will be used for collisions.
///
/// Can use mesh collision. Suitable for environments.
pub fn enable_static(&self, shape: PhysicsShape) {
World::set_entity_value(
self.id,
ffi::ComponentType::Physics,
ffi::Physics::PhysxDynamicEnable.into(),
&Value::from_bool(false),
);
World::set_entity_value(
self.id,
ffi::ComponentType::Physics,
ffi::Physics::PhysxKinematic.into(),
&Value::from_bool(false),
);
World::set_entity_value(
self.id,
ffi::ComponentType::Physics,
ffi::Physics::PhysxShape.into(),
&Value::from_i64(shape.as_ffi() as i64),
);
if let PhysicsShape::Compound(data) = shape {
self.compound_shape().set(data);
}
World::set_entity_value(
self.id,
ffi::ComponentType::Physics,
ffi::Physics::PhysxEnable.into(),
&Value::from_bool(true),
);
World::create_body_immediate(self.id);
}
/// Enables physics processing, as a kinematic entity which can be explicitly moved.
///
/// The layer set in `Layer` component, if any, will be used for collisions.
///
/// Kinematic entities are also regarded as dynamic, but do not disable the use of directly
/// setting the position and rotation of the `Transform` component. Parenting is allowed.
/// Suitable for stuff like elevators, moving platforms etc.
pub fn enable_kinematic(&self, shape: PhysicsShape) {
World::set_entity_value(
self.id,
ffi::ComponentType::Physics,
ffi::Physics::PhysxDynamicEnable.into(),
&Value::from_bool(true),
);
World::set_entity_value(
self.id,
ffi::ComponentType::Physics,
ffi::Physics::PhysxKinematic.into(),
&Value::from_bool(true),
);
World::set_entity_value(
self.id,
ffi::ComponentType::Physics,
ffi::Physics::PhysxShape.into(),
&Value::from_i64(shape.as_ffi() as i64),
);
if let PhysicsShape::Compound(data) = shape {
self.compound_shape().set(data);
}
World::set_entity_value(
self.id,
ffi::ComponentType::Physics,
ffi::Physics::PhysxEnable.into(),
&Value::from_bool(true),
);
World::create_body_immediate(self.id);
}
/// Checks if physics processing is enabled for this entity
///
/// This is enabled by default but can be disabled with [`Physics::disable`]
pub fn is_enabled(&self) -> bool {
World::get_entity_value(
self.id,
ffi::ComponentType::Physics,
ffi::Physics::PhysxEnable.into(),
)
.as_bool()
}
/// Disables physics processing for this entity.
///
/// Note: If you used dynamic physics, any transform parent set will have been removed
/// so you need to restore it (and whatever parent relative transform you had) yourself.
pub fn disable(&self) {
World::set_entity_value(
self.id,
ffi::ComponentType::Physics,
ffi::Physics::PhysxEnable.into(),
&Value::from_bool(false),
);
}
/// Applies a physics force or torque to the center of an entity.
///
/// This does nothing unless `Physics::enable` has been
/// called for this entity.
///
/// To instantly move a physics object, use `add_force` with `force_type` set to `Forcetype::Teleport` and `force_mode`
/// set to `ForceMode::Force`.
///
/// Simplified wrapper for `EntityMessenger::physics_force_at_request`.
pub fn add_force(&self, force_type: ForceType, force_mode: ForceMode, vector: Vec3) {
EntityMessenger::get()
.global_queue()
.physics_force_at_request(
self.id,
force_type,
force_mode,
Space::World,
Space::Local,
vector,
Vec3::ZERO,
);
}
/// Applies a physics force or torque at a point of an entity.
///
/// This does nothing unless `Physics::enable` has been
/// called for this entity.
///
/// Torques ignore the pos parameter, but work in either `force_space`.
/// To instantly move a physics object, use `add_force` with `force_type` set to `Forcetype::Teleport` and `force_mode`
/// set to `ForceMode::Force`.
/// To replicate `add_force`, set `force_space` to `Space::World`, `pos_space` to `Space::Local`, and `pos` to `Vec3::ZERO`.
///
/// Wraps `EntityMessenger::physics_force_request_at`.
pub fn add_force_at(
&self,
force_type: ForceType,
force_mode: ForceMode,
force_space: Space,
pos_space: Space,
vector: Vec3,
pos: Vec3,
) {
EntityMessenger::get()
.global_queue()
.physics_force_at_request(
self.id,
force_type,
force_mode,
force_space,
pos_space,
vector,
pos,
);
}
impl_world_accessor!(
/// Lets you check the current rigid body mode of this entity.
///
/// Note that it will not return a value until a frame has passed since the initial creation.
Physics,
RigidBodyMode,
RigidBodyMode,
rigid_body_mode,
ValueAccessorRead
);
impl_world_accessor!(
/// Returns a `ValueAccessor` for the current world-space linear velocity of the entity.
///
/// Writing is possible but not recommended, it's better to use forces whenever possible.
Physics,
Velocity,
Vec3,
velocity,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// Returns a `ValueAccessor` for the current world-space angular velocity of the entity.
///
/// The returned vector is pointing along the axis of rotation, with its length representing the
/// speed of rotation.
///
/// Writing is possible but not recommended, it's better to use forces/torques whenever possible.
Physics,
AngularVelocity,
Vec3,
angular_velocity,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// Returns a `ValueAccessor` for the dynamic friction of the entity.
///
/// Range 0..1. Default: 0.5.
///
/// Dynamic friction is applied when the two touching objects are in motion relative to each other.
/// 1.0 means that the friction force is equal to the normal force, but there are materials with
/// higher friction coefficients.
/// This will currently only be applied the next time you enable physics on the entity - it can't
/// be dynamically updated yet. In simulation, the friction used is a combination of the friction
/// properties of the two touching entities.
Physics,
PhysxDynamicFriction,
f32,
dynamic_friction,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// Returns a `ValueAccessor` for the static friction of the entity.
///
/// Range is 0 and upwards. Default: 0.5.
///
/// Static friction is applied when the two touching objects are still relative to each other.
/// 1.0 means that the friction force is equal to the normal force, but there are materials with
/// higher friction coefficients.
/// This will currently only be applied the next time you enable physics on the entity - it can't
/// be dynamically updated yet. In simulation, the friction used is a combination of the friction
/// properties of the two touching entities.
Physics,
PhysxStaticFriction,
f32,
static_friction,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// Returns a `ValueAccessor` for the restitution (bounciness) of the entity.
///
/// Range 0..1. Default: 0.6.
///
/// This will currently only be applied the next time you enable physics on the entity - it can't
/// be dynamically updated yet. Note that the actual restitution is a combination of the restitution
/// of the two touching objects. So if you want a ball to bounce indefinitely, both the ball and the
/// ground needs to have restitution 1.0 (not recommended, does not look realistic).
Physics,
PhysxRestitution,
f32,
restitution,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// Returns a `ValueAccessor` for the `create_sleeping` flag of the entity.
///
/// If this flag is set before `enable_dynamic` is called, the rigid body will be created in a sleeping state.
Physics,
PhysxCreateSleeping,
bool,
create_sleeping,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// Returns a `ValueAccessor` for the `sleeping` flag of the entity.
///
/// If this flag is set before `enable_dynamic` is called, it will not affect the rigid body.
/// Only applies to dynamic rigid bodies.
Physics,
PhysxSleeping,
bool,
sleeping,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// Returns a `ValueAccessor` for the `sleep_threshold` flag of the entity.
///
/// If this value is set before `enable_dynamic` is called, it will not affect the rigid body.
/// Only applies to dynamic rigid bodies.
Physics,
PhysxSleepThreshold,
f32,
sleep_threshold,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// Returns a `ValueAccessor` for the `gravity_enabled` flag of the entity.
///
/// If this flag is set to false before `enable_dynamic` is called, global gravity does not affect the rigid body.
/// Only applies to dynamic rigid bodies.
Physics,
PhysxGravityEnabled,
bool,
gravity_enabled,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// Returns a `ValueAccessor` for the `collision_events_mask` of the entity.
///
/// Setups which collisions (layers) against this entity should generate events,
/// Defaults to 0, but if set to 0 will be set to !0u64 on the first call to EntityMessenger::listen_collisions, which means
/// that all collisions will generate messages.
/// Note: It is a bit mask of `Layer` bits. Setup which layer an entity belongs to by adding a `Layer` component and set its layer bits.
Physics,
PhysxCollisionEventsMask,
u64,
collision_events_mask,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// Returns a `ValueAccessor` for the `DynamicLockFlags` of the entity.
///
/// Used to set/get the flags.
/// Can be used to lock a dynamic rigid body. Both its translation (Linear) and rotation (Angular).
Physics,
PhysxDynamicLockFlags,
DynamicLockFlags,
dynamic_lock_flags,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// Returns a `ValueAccessor` for the compound physics shape of the physics component. Will only be used when the physics component is enabled.
Physics,
PhysxCompoundShape,
CompoundPhysicsShape,
compound_shape,
ValueAccessorDataReadWrite
);
impl_world_accessor!(
/// Returns a `ValueAccessor` for the computed mass of the physics component.
///
/// NOTE: Cannot be accessed until you have called `enable_dynamic`!
Physics,
Mass,
f32,
mass,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// Returns a `ValueAccessor` for the computed center of mass of the physics component.
///
/// NOTE: Cannot be accessed until you have called `enable_dynamic`!
Physics,
CenterOfMass,
Vec3,
center_of_mass,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// Returns a `ValueAccessor` for the rotation of the mass space specified by the center_of_mass. Together they set up the space in which the inertia tensor is specified.
///
/// NOTE: Cannot be accessed until you have called `enable_dynamic`!
Physics,
MassRotation,
Quat,
mass_rotation,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// Returns a `ValueAccessor` for the diagonal inertia tensor in "mass space"
///
/// NOTE: Cannot be accessed until you have called `enable_dynamic`!
Physics,
InertiaTensor,
Vec3,
inertia_tensor,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// Returns a `ValueAccessor` for the linear damping coefficient. 0 means no damping.
Physics,
LinearDamping,
f32,
linear_damping,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// Returns a `ValueAccessor` for the angular damping coefficient. 0 means no damping.
Physics,
AngularDamping,
f32,
angular_damping,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// Returns a `ValueAccessor` for the trigger_volume property.
///
/// A trigger shape can send collision messages, but doesn't physically collide with things.
Physics,
TriggerVolume,
bool,
trigger_volume,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// The number of iterations the solver will run to try to solve positions. Default is 4.
Physics,
SolverPositionIterations,
u64,
solver_position_iterations,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// The number of iterations the solver will run to try to solve velocity. Default is 1.
Physics,
SolverVelocityIterations,
u64,
solver_velocity_iterations,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// The friction combine mode of the material of this entity. Default is Average.
///
/// Note: The actual combine mode is the max of the combine modes of the two entities touching!
/// This means that Max > Multiply > Min > Average in terms of priority.
Physics,
FrictionCombineMode,
CombineMode,
friction_combine_mode,
ValueAccessorReadWrite
);
impl_world_accessor!(
/// The restitution combine mode of the material of this entity. Default is Average.
///
/// Note: The actual combine mode is the max of the combine modes of the two entities touching!
/// This means that Max > Multiply > Min > Average in terms of priority.
Physics,
RestitutionCombineMode,
CombineMode,
restitution_combine_mode,
ValueAccessorReadWrite
);
/// Returns a Vec of collision messages for this entity.
///
/// If this entity hasn't been setup to listen for collisions it will be.
pub fn collisions(&self) -> Option<Vec<ffi::OnCollision>> {
EntityMessenger::get().collisions(self.entity())
}
/// Returns a Vec of trigger messages for this entity.
pub fn triggers(&self) -> Option<Vec<ffi::OnTrigger>> {
EntityMessenger::get().triggers(self.entity())
}
/// Returns whether this entity is currently physically in contact with a specific other entity.
pub fn in_contact_with(&self, other: Entity) -> bool {
ffi::v3::entities_in_contact(self.entity().as_ffi(), other.as_ffi())
}
/// Returns a list of other entities this entity is currently in contact with.
pub fn contact_entities(&self) -> Vec<Entity> {
let count = ffi::v3::entity_contact_count(self.entity().as_ffi());
if count > 0 {
let mut v = vec![ffi::ENTITY_HANDLE_INVALID; count as usize];
let second_count =
ffi::v3::retrieve_entities_in_contact(self.entity().as_ffi(), &mut v);
assert_eq!(second_count, count);
v.iter()
.map(|entity| Entity::from_ffi(*entity))
.collect::<Vec<Entity>>()
} else {
vec![]
}
}
}
impl_world_component!(Physics);