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 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
use bevy::prelude::*;
use std::collections::HashMap;
use std::sync::RwLock;
use rapier::prelude::{
CCDSolver, ColliderHandle, ColliderSet, EventHandler, FeatureId, ImpulseJointHandle,
ImpulseJointSet, IntegrationParameters, IslandManager, MultibodyJointHandle, MultibodyJointSet,
NarrowPhase, PhysicsHooks, PhysicsPipeline, QueryFilter as RapierQueryFilter, QueryPipeline,
Ray, Real, RigidBodyHandle, RigidBodySet,
};
use crate::geometry::{Collider, PointProjection, RayIntersection, ShapeCastHit};
use crate::math::{Rot, Vect};
use crate::pipeline::{CollisionEvent, ContactForceEvent, EventQueue, QueryFilter};
use bevy::prelude::{Entity, EventWriter, GlobalTransform, Query};
use crate::control::{CharacterCollision, MoveShapeOptions, MoveShapeOutput};
use crate::dynamics::TransformInterpolation;
use crate::parry::query::details::ShapeCastOptions;
use crate::plugin::configuration::{SimulationToRenderTime, TimestepMode};
use crate::prelude::{CollisionGroups, RapierRigidBodyHandle};
use rapier::control::CharacterAutostep;
use rapier::geometry::DefaultBroadPhase;
/// The Rapier context, containing all the state of the physics engine.
#[cfg_attr(feature = "serde-serialize", derive(Serialize, Deserialize))]
#[derive(Resource)]
pub struct RapierContext {
/// The island manager, which detects what object is sleeping
/// (not moving much) to reduce computations.
pub islands: IslandManager,
/// The broad-phase, which detects potential contact pairs.
pub broad_phase: DefaultBroadPhase,
/// The narrow-phase, which computes contact points, tests intersections,
/// and maintain the contact and intersection graphs.
pub narrow_phase: NarrowPhase,
/// The set of rigid-bodies part of the simulation.
pub bodies: RigidBodySet,
/// The set of colliders part of the simulation.
pub colliders: ColliderSet,
/// The set of impulse joints part of the simulation.
pub impulse_joints: ImpulseJointSet,
/// The set of multibody joints part of the simulation.
pub multibody_joints: MultibodyJointSet,
/// The solver, which handles Continuous Collision Detection (CCD).
pub ccd_solver: CCDSolver,
/// The physics pipeline, which advance the simulation step by step.
#[cfg_attr(feature = "serde-serialize", serde(skip))]
pub pipeline: PhysicsPipeline,
/// The query pipeline, which performs scene queries (ray-casting, point projection, etc.)
pub query_pipeline: QueryPipeline,
/// The integration parameters, controlling various low-level coefficient of the simulation.
pub integration_parameters: IntegrationParameters,
#[cfg_attr(feature = "serde-serialize", serde(skip))]
pub(crate) event_handler: Option<Box<dyn EventHandler>>,
// For transform change detection.
#[cfg_attr(feature = "serde-serialize", serde(skip))]
pub(crate) last_body_transform_set: HashMap<RigidBodyHandle, GlobalTransform>,
// NOTE: these maps are needed to handle despawning.
#[cfg_attr(feature = "serde-serialize", serde(skip))]
pub(crate) entity2body: HashMap<Entity, RigidBodyHandle>,
#[cfg_attr(feature = "serde-serialize", serde(skip))]
pub(crate) entity2collider: HashMap<Entity, ColliderHandle>,
#[cfg_attr(feature = "serde-serialize", serde(skip))]
pub(crate) entity2impulse_joint: HashMap<Entity, ImpulseJointHandle>,
#[cfg_attr(feature = "serde-serialize", serde(skip))]
pub(crate) entity2multibody_joint: HashMap<Entity, MultibodyJointHandle>,
// This maps the handles of colliders that have been deleted since the last
// physics update, to the entity they was attached to.
#[cfg_attr(feature = "serde-serialize", serde(skip))]
pub(crate) deleted_colliders: HashMap<ColliderHandle, Entity>,
#[cfg_attr(feature = "serde-serialize", serde(skip))]
pub(crate) character_collisions_collector: Vec<rapier::control::CharacterCollision>,
}
impl Default for RapierContext {
fn default() -> Self {
Self {
islands: IslandManager::new(),
broad_phase: DefaultBroadPhase::new(),
narrow_phase: NarrowPhase::new(),
bodies: RigidBodySet::new(),
colliders: ColliderSet::new(),
impulse_joints: ImpulseJointSet::new(),
multibody_joints: MultibodyJointSet::new(),
ccd_solver: CCDSolver::new(),
pipeline: PhysicsPipeline::new(),
query_pipeline: QueryPipeline::new(),
integration_parameters: IntegrationParameters::default(),
event_handler: None,
last_body_transform_set: HashMap::new(),
entity2body: HashMap::new(),
entity2collider: HashMap::new(),
entity2impulse_joint: HashMap::new(),
entity2multibody_joint: HashMap::new(),
deleted_colliders: HashMap::new(),
character_collisions_collector: vec![],
}
}
}
impl RapierContext {
/// If the collider attached to `entity` is attached to a rigid-body, this
/// returns the `Entity` containing that rigid-body.
pub fn collider_parent(&self, entity: Entity) -> Option<Entity> {
self.entity2collider
.get(&entity)
.and_then(|h| self.colliders.get(*h))
.and_then(|co| co.parent())
.and_then(|h| self.rigid_body_entity(h))
}
/// If entity is a rigid-body, this returns the collider `Entity`s attached
/// to that rigid-body.
pub fn rigid_body_colliders(&self, entity: Entity) -> impl Iterator<Item = Entity> + '_ {
self.entity2body()
.get(&entity)
.and_then(|handle| self.bodies.get(*handle))
.map(|body| {
body.colliders()
.iter()
.filter_map(|handle| self.collider_entity(*handle))
})
.into_iter()
.flatten()
}
/// Retrieve the Bevy entity the given Rapier collider (identified by its handle) is attached.
pub fn collider_entity(&self, handle: ColliderHandle) -> Option<Entity> {
Self::collider_entity_with_set(&self.colliders, handle)
}
// Mostly used to avoid borrowing self completely.
pub(crate) fn collider_entity_with_set(
colliders: &ColliderSet,
handle: ColliderHandle,
) -> Option<Entity> {
colliders
.get(handle)
.map(|c| Entity::from_bits(c.user_data as u64))
}
/// Retrieve the Bevy entity the given Rapier rigid-body (identified by its handle) is attached.
pub fn rigid_body_entity(&self, handle: RigidBodyHandle) -> Option<Entity> {
self.bodies
.get(handle)
.map(|c| Entity::from_bits(c.user_data as u64))
}
/// Calls the closure `f` once after converting the given [`QueryFilter`] into a raw `rapier::QueryFilter`.
pub fn with_query_filter<T>(
&self,
filter: QueryFilter,
f: impl FnOnce(RapierQueryFilter) -> T,
) -> T {
Self::with_query_filter_elts(
&self.entity2collider,
&self.entity2body,
&self.colliders,
filter,
f,
)
}
/// Without borrowing the [`RapierContext`], calls the closure `f` once
/// after converting the given [`QueryFilter`] into a raw `rapier::QueryFilter`.
pub fn with_query_filter_elts<T>(
entity2collider: &HashMap<Entity, ColliderHandle>,
entity2body: &HashMap<Entity, RigidBodyHandle>,
colliders: &ColliderSet,
filter: QueryFilter,
f: impl FnOnce(RapierQueryFilter) -> T,
) -> T {
let mut rapier_filter = RapierQueryFilter {
flags: filter.flags,
groups: filter.groups.map(CollisionGroups::into),
exclude_collider: filter
.exclude_collider
.and_then(|c| entity2collider.get(&c).copied()),
exclude_rigid_body: filter
.exclude_rigid_body
.and_then(|b| entity2body.get(&b).copied()),
predicate: None,
};
if let Some(predicate) = filter.predicate {
let wrapped_predicate = |h: ColliderHandle, _: &rapier::geometry::Collider| {
Self::collider_entity_with_set(colliders, h)
.map(predicate)
.unwrap_or(false)
};
rapier_filter.predicate = Some(&wrapped_predicate);
f(rapier_filter)
} else {
f(rapier_filter)
}
}
/// Advance the simulation, based on the given timestep mode.
#[allow(clippy::too_many_arguments)]
pub fn step_simulation(
&mut self,
gravity: Vect,
timestep_mode: TimestepMode,
events: Option<(EventWriter<CollisionEvent>, EventWriter<ContactForceEvent>)>,
hooks: &dyn PhysicsHooks,
time: &Time,
sim_to_render_time: &mut SimulationToRenderTime,
mut interpolation_query: Option<
Query<(&RapierRigidBodyHandle, &mut TransformInterpolation)>,
>,
) {
let event_queue = events.map(|(ce, fe)| EventQueue {
deleted_colliders: &self.deleted_colliders,
collision_events: RwLock::new(ce),
contact_force_events: RwLock::new(fe),
});
let events = self
.event_handler
.as_deref()
.or_else(|| event_queue.as_ref().map(|q| q as &dyn EventHandler))
.unwrap_or(&() as &dyn EventHandler);
match timestep_mode {
TimestepMode::Interpolated {
dt,
time_scale,
substeps,
} => {
self.integration_parameters.dt = dt;
sim_to_render_time.diff += time.delta_seconds();
while sim_to_render_time.diff > 0.0 {
// NOTE: in this comparison we do the same computations we
// will do for the next `while` iteration test, to make sure we
// don't get bit by potential float inaccuracy.
if sim_to_render_time.diff - dt <= 0.0 {
if let Some(interpolation_query) = interpolation_query.as_mut() {
// This is the last simulation step to be executed in the loop
// Update the previous state transforms
for (handle, mut interpolation) in interpolation_query.iter_mut() {
if let Some(body) = self.bodies.get(handle.0) {
interpolation.start = Some(*body.position());
interpolation.end = None;
}
}
}
}
let mut substep_integration_parameters = self.integration_parameters;
substep_integration_parameters.dt = dt / (substeps as Real) * time_scale;
for _ in 0..substeps {
self.pipeline.step(
&gravity.into(),
&substep_integration_parameters,
&mut self.islands,
&mut self.broad_phase,
&mut self.narrow_phase,
&mut self.bodies,
&mut self.colliders,
&mut self.impulse_joints,
&mut self.multibody_joints,
&mut self.ccd_solver,
None,
hooks,
events,
);
}
sim_to_render_time.diff -= dt;
}
}
TimestepMode::Variable {
max_dt,
time_scale,
substeps,
} => {
self.integration_parameters.dt = (time.delta_seconds() * time_scale).min(max_dt);
let mut substep_integration_parameters = self.integration_parameters;
substep_integration_parameters.dt /= substeps as Real;
for _ in 0..substeps {
self.pipeline.step(
&gravity.into(),
&substep_integration_parameters,
&mut self.islands,
&mut self.broad_phase,
&mut self.narrow_phase,
&mut self.bodies,
&mut self.colliders,
&mut self.impulse_joints,
&mut self.multibody_joints,
&mut self.ccd_solver,
None,
hooks,
events,
);
}
}
TimestepMode::Fixed { dt, substeps } => {
self.integration_parameters.dt = dt;
let mut substep_integration_parameters = self.integration_parameters;
substep_integration_parameters.dt = dt / (substeps as Real);
for _ in 0..substeps {
self.pipeline.step(
&gravity.into(),
&substep_integration_parameters,
&mut self.islands,
&mut self.broad_phase,
&mut self.narrow_phase,
&mut self.bodies,
&mut self.colliders,
&mut self.impulse_joints,
&mut self.multibody_joints,
&mut self.ccd_solver,
None,
hooks,
events,
);
}
}
}
}
/// This method makes sure tha the rigid-body positions have been propagated to
/// their attached colliders, without having to perform a srimulation step.
pub fn propagate_modified_body_positions_to_colliders(&mut self) {
self.bodies
.propagate_modified_body_positions_to_colliders(&mut self.colliders);
}
/// Updates the state of the query pipeline, based on the collider positions known
/// from the last timestep or the last call to `self.propagate_modified_body_positions_to_colliders()`.
pub fn update_query_pipeline(&mut self) {
self.query_pipeline.update(&self.bodies, &self.colliders);
}
/// The map from entities to rigid-body handles.
pub fn entity2body(&self) -> &HashMap<Entity, RigidBodyHandle> {
&self.entity2body
}
/// The map from entities to collider handles.
pub fn entity2collider(&self) -> &HashMap<Entity, ColliderHandle> {
&self.entity2collider
}
/// The map from entities to impulse joint handles.
pub fn entity2impulse_joint(&self) -> &HashMap<Entity, ImpulseJointHandle> {
&self.entity2impulse_joint
}
/// The map from entities to multibody joint handles.
pub fn entity2multibody_joint(&self) -> &HashMap<Entity, MultibodyJointHandle> {
&self.entity2multibody_joint
}
/// Attempts to move shape, optionally sliding or climbing obstacles.
///
/// # Parameters
/// * `movement`: the translational movement to apply.
/// * `shape`: the shape to move.
/// * `shape_translation`: the initial position of the shape.
/// * `shape_rotation`: the rotation of the shape.
/// * `shape_mass`: the mass of the shape to be considered by the impulse calculation if
/// `MoveShapeOptions::apply_impulse_to_dynamic_bodies` is set to true.
/// * `options`: configures the behavior of the automatic sliding and climbing.
/// * `filter`: indicates what collider or rigid-body needs to be ignored by the obstacle detection.
/// * `events`: callback run on each obstacle hit by the shape on its path.
#[allow(clippy::too_many_arguments)]
pub fn move_shape(
&mut self,
movement: Vect,
shape: &Collider,
shape_translation: Vect,
shape_rotation: Rot,
shape_mass: Real,
options: &MoveShapeOptions,
filter: QueryFilter,
mut events: impl FnMut(CharacterCollision),
) -> MoveShapeOutput {
let mut scaled_shape = shape.clone();
// TODO: how to set a good number of subdivisions, we don’t have access to the
// RapierConfiguration::scaled_shape_subdivision here.
scaled_shape.set_scale(shape.scale, 20);
let up = options
.up
.try_into()
.expect("The up vector must be non-zero.");
let autostep = options.autostep.map(|autostep| CharacterAutostep {
max_height: autostep.max_height,
min_width: autostep.min_width,
include_dynamic_bodies: autostep.include_dynamic_bodies,
});
let controller = rapier::control::KinematicCharacterController {
up,
offset: options.offset,
slide: options.slide,
autostep,
max_slope_climb_angle: options.max_slope_climb_angle,
min_slope_slide_angle: options.min_slope_slide_angle,
snap_to_ground: options.snap_to_ground,
normal_nudge_factor: options.normal_nudge_factor,
};
self.character_collisions_collector.clear();
// TODO: having to grab all the references to avoid having self in
// the closure is ugly.
let dt = self.integration_parameters.dt;
let colliders = &self.colliders;
let bodies = &mut self.bodies;
let query_pipeline = &self.query_pipeline;
let collisions = &mut self.character_collisions_collector;
collisions.clear();
let result = Self::with_query_filter_elts(
&self.entity2collider,
&self.entity2body,
&self.colliders,
filter,
move |filter| {
let result = controller.move_shape(
dt,
bodies,
colliders,
query_pipeline,
(&scaled_shape).into(),
&(shape_translation, shape_rotation).into(),
movement.into(),
filter,
|c| {
if let Some(collision) =
CharacterCollision::from_raw_with_set(colliders, &c, true)
{
events(collision);
}
collisions.push(c);
},
);
if options.apply_impulse_to_dynamic_bodies {
for collision in &*collisions {
controller.solve_character_collision_impulses(
dt,
bodies,
colliders,
query_pipeline,
(&scaled_shape).into(),
shape_mass,
collision,
filter,
)
}
}
result
},
);
MoveShapeOutput {
effective_translation: result.translation.into(),
grounded: result.grounded,
}
}
/// Find the closest intersection between a ray and a set of collider.
///
/// # Parameters
/// * `ray_origin`: the starting point of the ray to cast.
/// * `ray_dir`: the direction of the ray to cast.
/// * `max_toi`: the maximum time-of-impact that can be reported by this cast. This effectively
/// limits the length of the ray to `ray.dir.norm() * max_toi`. Use `Real::MAX` for an unbounded ray.
/// * `solid`: if this is `true` an impact at time 0.0 (i.e. at the ray origin) is returned if
/// it starts inside of a shape. If this `false` then the ray will hit the shape's boundary
/// even if its starts inside of it.
/// * `filter`: set of rules used to determine which collider is taken into account by this scene query.
pub fn cast_ray(
&self,
ray_origin: Vect,
ray_dir: Vect,
max_toi: Real,
solid: bool,
filter: QueryFilter,
) -> Option<(Entity, Real)> {
let ray = Ray::new(ray_origin.into(), ray_dir.into());
let (h, toi) = self.with_query_filter(filter, move |filter| {
self.query_pipeline.cast_ray(
&self.bodies,
&self.colliders,
&ray,
max_toi,
solid,
filter,
)
})?;
self.collider_entity(h).map(|e| (e, toi))
}
/// Find the closest intersection between a ray and a set of collider.
///
/// # Parameters
/// * `ray_origin`: the starting point of the ray to cast.
/// * `ray_dir`: the direction of the ray to cast.
/// * `max_toi`: the maximum time-of-impact that can be reported by this cast. This effectively
/// limits the length of the ray to `ray.dir.norm() * max_toi`. Use `Real::MAX` for an unbounded ray.
/// * `solid`: if this is `true` an impact at time 0.0 (i.e. at the ray origin) is returned if
/// it starts inside of a shape. If this `false` then the ray will hit the shape's boundary
/// even if its starts inside of it.
/// * `filter`: set of rules used to determine which collider is taken into account by this scene query.
pub fn cast_ray_and_get_normal(
&self,
ray_origin: Vect,
ray_dir: Vect,
max_toi: Real,
solid: bool,
filter: QueryFilter,
) -> Option<(Entity, RayIntersection)> {
let ray = Ray::new(ray_origin.into(), ray_dir.into());
let (h, result) = self.with_query_filter(filter, move |filter| {
self.query_pipeline.cast_ray_and_get_normal(
&self.bodies,
&self.colliders,
&ray,
max_toi,
solid,
filter,
)
})?;
self.collider_entity(h)
.map(|e| (e, RayIntersection::from_rapier(result, ray_origin, ray_dir)))
}
/// Find the all intersections between a ray and a set of collider and passes them to a callback.
///
/// # Parameters
/// * `ray_origin`: the starting point of the ray to cast.
/// * `ray_dir`: the direction of the ray to cast.
/// * `max_toi`: the maximum time-of-impact that can be reported by this cast. This effectively
/// limits the length of the ray to `ray.dir.norm() * max_toi`. Use `Real::MAX` for an unbounded ray.
/// * `solid`: if this is `true` an impact at time 0.0 (i.e. at the ray origin) is returned if
/// it starts inside of a shape. If this `false` then the ray will hit the shape's boundary
/// even if its starts inside of it.
/// * `filter`: set of rules used to determine which collider is taken into account by this scene query.
/// * `callback`: function executed on each collider for which a ray intersection has been found.
/// There is no guarantees on the order the results will be yielded. If this callback returns `false`,
/// this method will exit early, ignore any further raycast.
#[allow(clippy::too_many_arguments)]
pub fn intersections_with_ray(
&self,
ray_origin: Vect,
ray_dir: Vect,
max_toi: Real,
solid: bool,
filter: QueryFilter,
mut callback: impl FnMut(Entity, RayIntersection) -> bool,
) {
let ray = Ray::new(ray_origin.into(), ray_dir.into());
let callback = |h, inter: rapier::prelude::RayIntersection| {
self.collider_entity(h)
.map(|e| callback(e, RayIntersection::from_rapier(inter, ray_origin, ray_dir)))
.unwrap_or(true)
};
self.with_query_filter(filter, move |filter| {
self.query_pipeline.intersections_with_ray(
&self.bodies,
&self.colliders,
&ray,
max_toi,
solid,
filter,
callback,
)
});
}
/// Gets the handle of up to one collider intersecting the given shape.
///
/// # Parameters
/// * `shape_pos` - The position of the shape used for the intersection test.
/// * `shape` - The shape used for the intersection test.
/// * `filter`: set of rules used to determine which collider is taken into account by this scene query.
pub fn intersection_with_shape(
&self,
shape_pos: Vect,
shape_rot: Rot,
shape: &Collider,
filter: QueryFilter,
) -> Option<Entity> {
let scaled_transform = (shape_pos, shape_rot).into();
let mut scaled_shape = shape.clone();
// TODO: how to set a good number of subdivisions, we don’t have access to the
// RapierConfiguration::scaled_shape_subdivision here.
scaled_shape.set_scale(shape.scale, 20);
let h = self.with_query_filter(filter, move |filter| {
self.query_pipeline.intersection_with_shape(
&self.bodies,
&self.colliders,
&scaled_transform,
&*scaled_shape.raw,
filter,
)
})?;
self.collider_entity(h)
}
/// Find the projection of a point on the closest collider.
///
/// # Parameters
/// * `point` - The point to project.
/// * `solid` - If this is set to `true` then the collider shapes are considered to
/// be plain (if the point is located inside of a plain shape, its projection is the point
/// itself). If it is set to `false` the collider shapes are considered to be hollow
/// (if the point is located inside of an hollow shape, it is projected on the shape's
/// boundary).
/// * `filter`: set of rules used to determine which collider is taken into account by this scene query.
pub fn project_point(
&self,
point: Vect,
solid: bool,
filter: QueryFilter,
) -> Option<(Entity, PointProjection)> {
let (h, result) = self.with_query_filter(filter, move |filter| {
self.query_pipeline.project_point(
&self.bodies,
&self.colliders,
&point.into(),
solid,
filter,
)
})?;
self.collider_entity(h)
.map(|e| (e, PointProjection::from_rapier(result)))
}
/// Find all the colliders containing the given point.
///
/// # Parameters
/// * `point` - The point used for the containment test.
/// * `filter`: set of rules used to determine which collider is taken into account by this scene query.
/// * `callback` - A function called with each collider with a shape containing the `point`.
/// If this callback returns `false`, this method will exit early, ignore any
/// further point projection.
pub fn intersections_with_point(
&self,
point: Vect,
filter: QueryFilter,
mut callback: impl FnMut(Entity) -> bool,
) {
#[allow(clippy::redundant_closure)]
// False-positive, we can't move callback, closure becomes `FnOnce`
let callback = |h| self.collider_entity(h).map(|e| callback(e)).unwrap_or(true);
self.with_query_filter(filter, move |filter| {
self.query_pipeline.intersections_with_point(
&self.bodies,
&self.colliders,
&point.into(),
filter,
callback,
)
});
}
/// Find the projection of a point on the closest collider.
///
/// The results include the ID of the feature hit by the point.
///
/// # Parameters
/// * `point` - The point to project.
/// * `solid` - If this is set to `true` then the collider shapes are considered to
/// be plain (if the point is located inside of a plain shape, its projection is the point
/// itself). If it is set to `false` the collider shapes are considered to be hollow
/// (if the point is located inside of an hollow shape, it is projected on the shape's
/// boundary).
/// * `filter`: set of rules used to determine which collider is taken into account by this scene query.
pub fn project_point_and_get_feature(
&self,
point: Vect,
filter: QueryFilter,
) -> Option<(Entity, PointProjection, FeatureId)> {
let (h, proj, fid) = self.with_query_filter(filter, move |filter| {
self.query_pipeline.project_point_and_get_feature(
&self.bodies,
&self.colliders,
&point.into(),
filter,
)
})?;
self.collider_entity(h)
.map(|e| (e, PointProjection::from_rapier(proj), fid))
}
/// Finds all entities of all the colliders with an Aabb intersecting the given Aabb.
#[cfg(not(feature = "headless"))]
pub fn colliders_with_aabb_intersecting_aabb(
&self,
aabb: bevy::render::primitives::Aabb,
mut callback: impl FnMut(Entity) -> bool,
) {
#[cfg(feature = "dim2")]
let scaled_aabb = rapier::prelude::Aabb {
mins: aabb.min().xy().into(),
maxs: aabb.max().xy().into(),
};
#[cfg(feature = "dim3")]
let scaled_aabb = rapier::prelude::Aabb {
mins: aabb.min().into(),
maxs: aabb.max().into(),
};
#[allow(clippy::redundant_closure)]
// False-positive, we can't move callback, closure becomes `FnOnce`
let callback = |h: &ColliderHandle| {
self.collider_entity(*h)
.map(|e| callback(e))
.unwrap_or(true)
};
self.query_pipeline
.colliders_with_aabb_intersecting_aabb(&scaled_aabb, callback);
}
/// Casts a shape at a constant linear velocity and retrieve the first collider it hits.
///
/// This is similar to ray-casting except that we are casting a whole shape instead of just a
/// point (the ray origin). In the resulting `ShapeCastHit`, witness and normal 1 refer to the world
/// collider, and are in world space.
///
/// # Parameters
/// * `shape_pos` - The initial translation of the shape to cast.
/// * `shape_rot` - The rotation of the shape to cast.
/// * `shape_vel` - The constant velocity of the shape to cast (i.e. the cast direction).
/// * `shape` - The shape to cast.
/// * `max_toi` - The maximum time-of-impact that can be reported by this cast. This effectively
/// limits the distance traveled by the shape to `shapeVel.norm() * maxToi`.
/// * `stop_at_penetration` - If the casted shape starts in a penetration state with any
/// collider, two results are possible. If `stop_at_penetration` is `true` then, the
/// result will have a `toi` equal to `start_time`. If `stop_at_penetration` is `false`
/// then the nonlinear shape-casting will see if further motion wrt. the penetration normal
/// would result in tunnelling. If it does not (i.e. we have a separating velocity along
/// that normal) then the nonlinear shape-casting will attempt to find another impact,
/// at a time `> start_time` that could result in tunnelling.
/// * `filter`: set of rules used to determine which collider is taken into account by this scene query.
#[allow(clippy::too_many_arguments)]
pub fn cast_shape(
&self,
shape_pos: Vect,
shape_rot: Rot,
shape_vel: Vect,
shape: &Collider,
options: ShapeCastOptions,
filter: QueryFilter,
) -> Option<(Entity, ShapeCastHit)> {
let scaled_transform = (shape_pos, shape_rot).into();
let mut scaled_shape = shape.clone();
// TODO: how to set a good number of subdivisions, we don’t have access to the
// RapierConfiguration::scaled_shape_subdivision here.
scaled_shape.set_scale(shape.scale, 20);
let (h, result) = self.with_query_filter(filter, move |filter| {
self.query_pipeline.cast_shape(
&self.bodies,
&self.colliders,
&scaled_transform,
&shape_vel.into(),
&*scaled_shape.raw,
options,
filter,
)
})?;
self.collider_entity(h).map(|e| {
(
e,
ShapeCastHit::from_rapier(result, options.compute_impact_geometry_on_penetration),
)
})
}
/* TODO: we need to wrap the NonlinearRigidMotion somehow.
*
/// Casts a shape with an arbitrary continuous motion and retrieve the first collider it hits.
///
/// In the resulting `ShapeCastHit`, witness and normal 1 refer to the world collider, and are
/// in world space.
///
/// # Parameters
/// * `shape_motion` - The motion of the shape.
/// * `shape` - The shape to cast.
/// * `start_time` - The starting time of the interval where the motion takes place.
/// * `end_time` - The end time of the interval where the motion takes place.
/// * `stop_at_penetration` - If the casted shape starts in a penetration state with any
/// collider, two results are possible. If `stop_at_penetration` is `true` then, the
/// result will have a `toi` equal to `start_time`. If `stop_at_penetration` is `false`
/// then the nonlinear shape-casting will see if further motion wrt. the penetration normal
/// would result in tunnelling. If it does not (i.e. we have a separating velocity along
/// that normal) then the nonlinear shape-casting will attempt to find another impact,
/// at a time `> start_time` that could result in tunnelling.
/// * `filter`: set of rules used to determine which collider is taken into account by this scene query.
pub fn nonlinear_cast_shape(
&self,
shape_motion: &NonlinearRigidMotion,
shape: &Collider,
start_time: Real,
end_time: Real,
stop_at_penetration: bool,
filter: QueryFilter,
) -> Option<(Entity, Toi)> {
let scaled_transform = (shape_pos, shape_rot).into();
let mut scaled_shape = shape.clone();
// TODO: how to set a good number of subdivisions, we don’t have access to the
// RapierConfiguration::scaled_shape_subdivision here.
scaled_shape.set_scale(shape.scale, 20);
let (h, result) = self.with_query_filter(filter, move |filter| {
self.query_pipeline.nonlinear_cast_shape(
&self.bodies,
&self.colliders,
shape_motion,
&*scaled_shape.raw,
start_time,
end_time,
stop_at_penetration,
filter,
)
})?;
self.collider_entity(h).map(|e| (e, result))
}
*/
/// Retrieve all the colliders intersecting the given shape.
///
/// # Parameters
/// * `shapePos` - The position of the shape to test.
/// * `shapeRot` - The orientation of the shape to test.
/// * `shape` - The shape to test.
/// * `filter`: set of rules used to determine which collider is taken into account by this scene query.
/// * `callback` - A function called with the entities of each collider intersecting the `shape`.
pub fn intersections_with_shape(
&self,
shape_pos: Vect,
shape_rot: Rot,
shape: &Collider,
filter: QueryFilter,
mut callback: impl FnMut(Entity) -> bool,
) {
let scaled_transform = (shape_pos, shape_rot).into();
let mut scaled_shape = shape.clone();
// TODO: how to set a good number of subdivisions, we don’t have access to the
// RapierConfiguration::scaled_shape_subdivision here.
scaled_shape.set_scale(shape.scale, 20);
#[allow(clippy::redundant_closure)]
// False-positive, we can't move callback, closure becomes `FnOnce`
let callback = |h| self.collider_entity(h).map(|e| callback(e)).unwrap_or(true);
self.with_query_filter(filter, move |filter| {
self.query_pipeline.intersections_with_shape(
&self.bodies,
&self.colliders,
&scaled_transform,
&*scaled_shape.raw,
filter,
callback,
)
});
}
}