diff --git a/crates/avian2d/examples/one_way_platform_2d.rs b/crates/avian2d/examples/one_way_platform_2d.rs index 303f0f3d6..8b7dc4203 100644 --- a/crates/avian2d/examples/one_way_platform_2d.rs +++ b/crates/avian2d/examples/one_way_platform_2d.rs @@ -1,11 +1,17 @@ //! A 2D platformer example with one-way platforms to demonstrate -//! filtering collisions with systems in the `PostProcessCollisions` schedule. +//! contact modification with `CollisionHooks`. //! //! Move with arrow keys, jump with Space and descend through //! platforms by pressing Space while holding the down arrow. +#![allow(clippy::type_complexity)] + use avian2d::{math::*, prelude::*}; -use bevy::{prelude::*, utils::HashSet}; +use bevy::{ + ecs::system::{lifetimeless::Read, SystemParam}, + prelude::*, + utils::HashSet, +}; use examples_common_2d::ExampleCommonPlugin; fn main() { @@ -13,15 +19,17 @@ fn main() { .add_plugins(( DefaultPlugins, ExampleCommonPlugin, - // Add physics plugins and specify a units-per-meter scaling factor, 1 meter = 20 pixels. - // The unit allows the engine to tune its parameters for the scale of the world, improving stability. - PhysicsPlugins::default().with_length_unit(20.0), + PhysicsPlugins::default() + // Specify a units-per-meter scaling factor, 1 meter = 20 pixels. + // The unit allows the engine to tune its parameters for the scale of the world, improving stability. + .with_length_unit(20.0) + // Add our custom collision hooks. + .with_collision_hooks::(), )) .insert_resource(ClearColor(Color::srgb(0.05, 0.05, 0.1))) .insert_resource(Gravity(Vector::NEG_Y * 1000.0)) .add_systems(Startup, setup) .add_systems(Update, (movement, pass_through_one_way_platform)) - .add_systems(PostProcessCollisions, one_way_platform) .run(); } @@ -34,17 +42,21 @@ struct MovementSpeed(Scalar); #[derive(Component)] struct JumpImpulse(Scalar); +// Enable contact modification for one-way platforms with the `ActiveCollisionHooks` component. +// Here we use required components, but you could also add it manually. #[derive(Clone, Eq, PartialEq, Debug, Default, Component)] +#[require(ActiveCollisionHooks(|| ActiveCollisionHooks::MODIFY_CONTACTS))] pub struct OneWayPlatform(HashSet); +/// A component to control how an actor interacts with a one-way platform. #[derive(Copy, Clone, Eq, PartialEq, Debug, Default, Component, Reflect)] pub enum PassThroughOneWayPlatform { #[default] - /// Passes through a `OneWayPlatform` if the contact normal is in line with the platform's local-space up vector + /// Passes through a `OneWayPlatform` if the contact normal is in line with the platform's local-space up vector. ByNormal, - /// Always passes through a `OneWayPlatform`, temporarily set this to allow an actor to jump down through a platform + /// Always passes through a `OneWayPlatform`, temporarily set this to allow an actor to jump down through a platform. Always, - /// Never passes through a `OneWayPlatform` + /// Never passes through a `OneWayPlatform`. Never, } @@ -171,70 +183,70 @@ fn pass_through_one_way_platform( } } -/// Allows entities to pass through [`OneWayPlatform`] entities. -/// -/// Passing through is achieved by removing the collisions between the [`OneWayPlatform`] -/// and the other entity if the entity should pass through. -/// If a [`PassThroughOneWayPlatform`] is present on the non-platform entity, -/// the value of the component dictates the pass-through behaviour. -/// -/// Entities known to be passing through each [`OneWayPlatform`] are stored in the -/// [`OneWayPlatform`]. If an entity is known to be passing through a [`OneWayPlatform`], -/// it is allowed to continue to do so, even if [`PassThroughOneWayPlatform`] has been -/// set to disallow passing through. -/// -/// > Note that this is a very simplistic implementation of one-way -/// > platforms to demonstrate filtering collisions via [`PostProcessCollisions`]. -/// > You will probably want something more robust to implement one-way -/// > platforms properly, or may elect to use a sensor collider for your entities instead, -/// > which means you won't need to filter collisions at all. -/// -/// #### When an entity is known to already be passing through the [`OneWayPlatform`] -/// -/// Any time an entity begins passing through a [`OneWayPlatform`], it is added to the -/// [`OneWayPlatform`]'s set of currently active penetrations, and will be allowed to -/// continue to pass through the platform until it is no longer penetrating the platform. -/// -/// The entity is allowed to continue to pass through the platform as long as at least -/// one contact is penetrating. -/// -/// Once all of the contacts are no longer penetrating the [`OneWayPlatform`], or all contacts -/// have stopped, the entity is forgotten about and the logic falls through to the next part. -/// -/// #### When an entity is NOT known to be passing through the [`OneWayPlatform`] -/// -/// Depending on the setting of [`PassThroughOneWayPlatform`], the entity may be allowed to -/// pass through. -/// -/// If no [`PassThroughOneWayPlatform`] is present, [`PassThroughOneWayPlatform::ByNormal`] is used. -/// -/// [`PassThroughOneWayPlatform`] may be in one of three states: -/// 1. [`PassThroughOneWayPlatform::ByNormal`] -/// - This is the default state -/// - The entity may be allowed to pass through the [`OneWayPlatform`] depending on the contact normal -/// - If all contact normals are in line with the [`OneWayPlatform`]'s local-space up vector, -/// the entity is allowed to pass through -/// 2. [`PassThroughOneWayPlatform::Always`] -/// - The entity will always pass through the [`OneWayPlatform`], regardless of contact normal -/// - This is useful for allowing an entity to jump down through a platform -/// 3. [`PassThroughOneWayPlatform::Never`] -/// - The entity will never pass through the [`OneWayPlatform`], meaning the platform will act -/// as normal hard collision for this entity -/// -/// Even if an entity is changed to [`PassThroughOneWayPlatform::Never`], it will be allowed to pass -/// through a [`OneWayPlatform`] if it is already penetrating the platform. Once it exits the platform, -/// it will no longer be allowed to pass through. -fn one_way_platform( - mut one_way_platforms_query: Query<&mut OneWayPlatform>, +// Define a custom `SystemParam` for our collision hooks. +// It can have read-only access to queries, resources, and other system parameters. +#[derive(SystemParam)] +struct PlatformerCollisionHooks<'w, 's> { + one_way_platforms_query: Query<'w, 's, Read>, + // NOTE: This precludes a `OneWayPlatform` passing through a `OneWayPlatform`. other_colliders_query: Query< - Option<&PassThroughOneWayPlatform>, - (With, Without), // NOTE: This precludes OneWayPlatform passing through a OneWayPlatform + 'w, + 's, + Option>, + (With, Without), >, - mut collisions: ResMut, -) { - // This assumes that Collisions contains empty entries for entities - // that were once colliding but no longer are. - collisions.retain(|contacts| { +} + +// Implement the `CollisionHooks` trait for our custom system parameter. +impl CollisionHooks for PlatformerCollisionHooks<'_, '_> { + // Below is a description of the logic used for one-way platforms. + + /// Allows entities to pass through [`OneWayPlatform`] entities. + /// + /// Passing through is achieved by removing the collisions between the [`OneWayPlatform`] + /// and the other entity if the entity should pass through. + /// If a [`PassThroughOneWayPlatform`] is present on the non-platform entity, + /// the value of the component dictates the pass-through behaviour. + /// + /// Entities known to be passing through each [`OneWayPlatform`] are stored in the + /// [`OneWayPlatform`]. If an entity is known to be passing through a [`OneWayPlatform`], + /// it is allowed to continue to do so, even if [`PassThroughOneWayPlatform`] has been + /// set to disallow passing through. + /// + /// #### When an entity is known to already be passing through the [`OneWayPlatform`] + /// + /// When an entity begins passing through a [`OneWayPlatform`], it is added to the + /// [`OneWayPlatform`]'s set of active penetrations, and will be allowed to continue + /// to pass through until it is no longer penetrating the platform. + /// + /// #### When an entity is *not* known to be passing through the [`OneWayPlatform`] + /// + /// Depending on the setting of [`PassThroughOneWayPlatform`], the entity may be allowed to + /// pass through. + /// + /// If no [`PassThroughOneWayPlatform`] is present, [`PassThroughOneWayPlatform::ByNormal`] is used. + /// + /// [`PassThroughOneWayPlatform`] may be in one of three states: + /// 1. [`PassThroughOneWayPlatform::ByNormal`] + /// - This is the default state + /// - The entity may be allowed to pass through the [`OneWayPlatform`] depending on the contact normal + /// - If all contact normals are in line with the [`OneWayPlatform`]'s local-space up vector, + /// the entity is allowed to pass through + /// 2. [`PassThroughOneWayPlatform::Always`] + /// - The entity will always pass through the [`OneWayPlatform`], regardless of contact normal + /// - This is useful for allowing an entity to jump down through a platform + /// 3. [`PassThroughOneWayPlatform::Never`] + /// - The entity will never pass through the [`OneWayPlatform`], meaning the platform will act + /// as normal hard collision for this entity + /// + /// Even if an entity is changed to [`PassThroughOneWayPlatform::Never`], it will be allowed to pass + /// through a [`OneWayPlatform`] if it is already penetrating the platform. Once it exits the platform, + /// it will no longer be allowed to pass through. + fn modify_contacts(&self, contacts: &mut Contacts, commands: &mut Commands) -> bool { + // This is the contact modification hook, called after collision detection, + // but before constraints are created for the solver. Mutable access to the ECS + // is not allowed, but we can queue commands to perform deferred changes. + // Differentiate between which normal of the manifold we should use enum RelevantNormal { Normal1, @@ -243,11 +255,22 @@ fn one_way_platform( // First, figure out which entity is the one-way platform, and which is the other. // Choose the appropriate normal for pass-through depending on which is which. - let (mut one_way_platform, other_entity, relevant_normal) = - if let Ok(one_way_platform) = one_way_platforms_query.get_mut(contacts.entity1) { - (one_way_platform, contacts.entity2, RelevantNormal::Normal1) - } else if let Ok(one_way_platform) = one_way_platforms_query.get_mut(contacts.entity2) { - (one_way_platform, contacts.entity1, RelevantNormal::Normal2) + let (platform_entity, one_way_platform, other_entity, relevant_normal) = + if let Ok(one_way_platform) = self.one_way_platforms_query.get(contacts.entity1) { + ( + contacts.entity1, + one_way_platform, + contacts.entity2, + RelevantNormal::Normal1, + ) + } else if let Ok(one_way_platform) = self.one_way_platforms_query.get(contacts.entity2) + { + ( + contacts.entity2, + one_way_platform, + contacts.entity1, + RelevantNormal::Normal2, + ) } else { // Neither is a one-way-platform, so accept the collision: // we're done here. @@ -268,17 +291,23 @@ fn one_way_platform( return false; } else { // If it's no longer penetrating us, forget it. - one_way_platform.0.remove(&other_entity); + commands.queue(OneWayPlatformCommand::Remove { + platform_entity, + entity: other_entity, + }); } } - match other_colliders_query.get(other_entity) { + match self.other_colliders_query.get(other_entity) { // Pass-through is set to never, so accept the collision. Ok(Some(PassThroughOneWayPlatform::Never)) => true, // Pass-through is set to always, so always ignore this collision // and register it as an entity that's currently penetrating. Ok(Some(PassThroughOneWayPlatform::Always)) => { - one_way_platform.0.insert(other_entity); + commands.queue(OneWayPlatformCommand::Add { + platform_entity, + entity: other_entity, + }); false } // Default behaviour is "by normal". @@ -297,10 +326,50 @@ fn one_way_platform( } else { // Otherwise, ignore the collision and register // the other entity as one that's currently penetrating. - one_way_platform.0.insert(other_entity); + commands.queue(OneWayPlatformCommand::Add { + platform_entity, + entity: other_entity, + }); false } } } - }); + } +} + +/// A command to add/remove entities to/from the set of entities +/// that are currently in contact with a one-way platform. +enum OneWayPlatformCommand { + Add { + platform_entity: Entity, + entity: Entity, + }, + Remove { + platform_entity: Entity, + entity: Entity, + }, +} + +impl Command for OneWayPlatformCommand { + fn apply(self, world: &mut World) { + match self { + OneWayPlatformCommand::Add { + platform_entity, + entity, + } => { + if let Some(mut platform) = world.get_mut::(platform_entity) { + platform.0.insert(entity); + } + } + + OneWayPlatformCommand::Remove { + platform_entity, + entity, + } => { + if let Some(mut platform) = world.get_mut::(platform_entity) { + platform.0.remove(&entity); + } + } + } + } } diff --git a/src/collision/broad_phase.rs b/src/collision/broad_phase.rs index 6072e8a21..8316a8573 100644 --- a/src/collision/broad_phase.rs +++ b/src/collision/broad_phase.rs @@ -3,11 +3,13 @@ //! //! See [`BroadPhasePlugin`]. +use std::marker::PhantomData; + use crate::prelude::*; use bevy::{ ecs::{ entity::{EntityMapper, MapEntities}, - system::lifetimeless::Read, + system::{lifetimeless::Read, StaticSystemParam, SystemParamItem}, }, prelude::*, }; @@ -19,9 +21,20 @@ use bevy::{ /// Currently, the broad phase uses the [sweep and prune](https://en.wikipedia.org/wiki/Sweep_and_prune) algorithm. /// /// The broad phase systems run in [`PhysicsStepSet::BroadPhase`]. -pub struct BroadPhasePlugin; +/// +/// [`CollisionHooks`] can be provided with generics to apply custom filtering for collision pairs. +pub struct BroadPhasePlugin(PhantomData); + +impl Default for BroadPhasePlugin { + fn default() -> Self { + Self(PhantomData) + } +} -impl Plugin for BroadPhasePlugin { +impl Plugin for BroadPhasePlugin +where + for<'w, 's> SystemParamItem<'w, 's, H>: CollisionHooks, +{ fn build(&self, app: &mut App) { app.init_resource::() .init_resource::(); @@ -49,7 +62,7 @@ impl Plugin for BroadPhasePlugin { ); physics_schedule - .add_systems(collect_collision_pairs.in_set(BroadPhaseSet::CollectCollisions)); + .add_systems(collect_collision_pairs::.in_set(BroadPhaseSet::CollectCollisions)); } } @@ -82,12 +95,6 @@ pub struct BroadCollisionPairs(pub Vec<(Entity, Entity)>); #[reflect(Component)] pub struct AabbIntersections(pub Vec); -/// True if the rigid body should store [`AabbIntersections`]. -type StoreAabbIntersections = bool; - -/// True if the rigid body hasn't moved. -type IsBodyInactive = bool; - /// Entities with [`ColliderAabb`]s sorted along an axis by their extents. #[derive(Resource, Default)] struct AabbIntervals( @@ -96,11 +103,23 @@ struct AabbIntervals( ColliderParent, ColliderAabb, CollisionLayers, - StoreAabbIntersections, - IsBodyInactive, + AabbIntervalFlags, )>, ); +bitflags::bitflags! { + /// Flags for AABB intervals in the broad phase. + #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] + pub struct AabbIntervalFlags: u8 { + /// Set if [`AabbIntersections`] should be stored for this entity. + const STORE_INTERSECTIONS = 1 << 0; + /// Set if the body is sleeping or static. + const IS_INACTIVE = 1 << 1; + /// Set if [`CollisionHooks::filter_pairs`] should be called for this entity. + const CUSTOM_FILTER = 1 << 2; + } +} + impl MapEntities for AabbIntervals { fn map_entities(&mut self, entity_mapper: &mut M) { for interval in self.0.iter_mut() { @@ -117,6 +136,7 @@ fn update_aabb_intervals( &ColliderAabb, Option<&ColliderParent>, Option<&CollisionLayers>, + Option<&ActiveCollisionHooks>, Has, Has, ), @@ -125,10 +145,17 @@ fn update_aabb_intervals( rbs: Query<&RigidBody>, mut intervals: ResMut, ) { - intervals.0.retain_mut( - |(collider_entity, collider_parent, aabb, layers, store_intersections, is_inactive)| { - if let Ok((new_aabb, new_parent, new_layers, new_store_intersections, is_sleeping)) = - aabbs.get(*collider_entity) + intervals + .0 + .retain_mut(|(collider_entity, collider_parent, aabb, layers, flags)| { + if let Ok(( + new_aabb, + new_parent, + new_layers, + hooks, + new_store_intersections, + is_sleeping, + )) = aabbs.get(*collider_entity) { if !new_aabb.min.is_finite() || !new_aabb.max.is_finite() { return false; @@ -140,15 +167,22 @@ fn update_aabb_intervals( let is_static = new_parent.is_some_and(|p| rbs.get(p.get()).is_ok_and(RigidBody::is_static)); - *is_inactive = is_static || is_sleeping; - *store_intersections = new_store_intersections; + + flags.set(AabbIntervalFlags::IS_INACTIVE, is_static || is_sleeping); + flags.set( + AabbIntervalFlags::STORE_INTERSECTIONS, + new_store_intersections, + ); + flags.set( + AabbIntervalFlags::CUSTOM_FILTER, + hooks.is_some_and(|h| h.contains(ActiveCollisionHooks::FILTER_PAIRS)), + ); true } else { false } - }, - ); + }); } type AabbIntervalQueryData = ( @@ -157,6 +191,7 @@ type AabbIntervalQueryData = ( Read, Option>, Option>, + Option>, Has, ); @@ -170,15 +205,23 @@ fn add_new_aabb_intervals( ) { let re_enabled_aabbs = aabbs.iter_many(re_enabled_colliders.read()); let aabbs = added_aabbs.iter().chain(re_enabled_aabbs).map( - |(ent, parent, aabb, rb, layers, store_intersections)| { + |(entity, parent, aabb, rb, layers, hooks, store_intersections)| { + let mut flags = AabbIntervalFlags::empty(); + flags.set(AabbIntervalFlags::STORE_INTERSECTIONS, store_intersections); + flags.set( + AabbIntervalFlags::IS_INACTIVE, + rb.is_some_and(|rb| rb.is_static()), + ); + flags.set( + AabbIntervalFlags::CUSTOM_FILTER, + hooks.is_some_and(|h| h.contains(ActiveCollisionHooks::FILTER_PAIRS)), + ); ( - ent, - parent.map_or(ColliderParent(ent), |p| *p), + entity, + parent.map_or(ColliderParent(entity), |p| *p), *aabb, - // Default to treating collider as immovable/static for filtering unnecessary collision checks layers.map_or(CollisionLayers::default(), |layers| *layers), - rb.map_or(false, |rb| rb.is_static()), - store_intersections, + flags, ) }, ); @@ -186,30 +229,40 @@ fn add_new_aabb_intervals( } /// Collects bodies that are potentially colliding. -fn collect_collision_pairs( +fn collect_collision_pairs( intervals: ResMut, mut broad_collision_pairs: ResMut, mut aabb_intersection_query: Query<&mut AabbIntersections>, -) { + hooks: StaticSystemParam, + mut commands: Commands, +) where + for<'w, 's> SystemParamItem<'w, 's, H>: CollisionHooks, +{ for mut intersections in &mut aabb_intersection_query { intersections.clear(); } - sweep_and_prune( + sweep_and_prune::( intervals, &mut broad_collision_pairs.0, &mut aabb_intersection_query, + &mut hooks.into_inner(), + &mut commands, ); } /// Sorts the entities by their minimum extents along an axis and collects the entity pairs that have intersecting AABBs. /// /// Sweep and prune exploits temporal coherence, as bodies are unlikely to move significantly between two simulation steps. Insertion sort is used, as it is good at sorting nearly sorted lists efficiently. -fn sweep_and_prune( +fn sweep_and_prune( mut intervals: ResMut, broad_collision_pairs: &mut Vec<(Entity, Entity)>, aabb_intersection_query: &mut Query<&mut AabbIntersections>, -) { + hooks: &mut H::Item<'_, '_>, + commands: &mut Commands, +) where + for<'w, 's> SystemParamItem<'w, 's, H>: CollisionHooks, +{ // Sort bodies along the x-axis using insertion sort, a sorting algorithm great for sorting nearly sorted lists. insertion_sort(&mut intervals.0, |a, b| a.2.min.x > b.2.min.x); @@ -217,44 +270,58 @@ fn sweep_and_prune( broad_collision_pairs.clear(); // Find potential collisions by checking for AABB intersections along all axes. - for (i, (ent1, parent1, aabb1, layers1, store_intersections1, inactive1)) in - intervals.0.iter().enumerate() - { - for (ent2, parent2, aabb2, layers2, store_intersections2, inactive2) in - intervals.0.iter().skip(i + 1) - { - // x doesn't intersect; check this first so we can discard as soon as possible + for (i, (entity1, parent1, aabb1, layers1, flags1)) in intervals.0.iter().enumerate() { + for (entity2, parent2, aabb2, layers2, flags2) in intervals.0.iter().skip(i + 1) { + // x doesn't intersect; check this first so we can discard as soon as possible. if aabb2.min.x > aabb1.max.x { break; } - // No collisions between bodies that haven't moved or colliders with incompatible layers or colliders with the same parent - if (*inactive1 && *inactive2) || !layers1.interacts_with(*layers2) || parent1 == parent2 + // No collisions between bodies that haven't moved or colliders with incompatible layers + // or colliders with the same parent. + if flags1 + .intersection(*flags2) + .contains(AabbIntervalFlags::IS_INACTIVE) + || !layers1.interacts_with(*layers2) + || parent1 == parent2 { continue; } - // y doesn't intersect + // y doesn't intersect. if aabb1.min.y > aabb2.max.y || aabb1.max.y < aabb2.min.y { continue; } #[cfg(feature = "3d")] - // z doesn't intersect + // z doesn't intersect. if aabb1.min.z > aabb2.max.z || aabb1.max.z < aabb2.min.z { continue; } - broad_collision_pairs.push((*ent1, *ent2)); + // Apply user-defined filter. + if flags1 + .union(*flags2) + .contains(AabbIntervalFlags::CUSTOM_FILTER) + { + let should_collide = hooks.filter_pairs(*entity1, *entity2, commands); + if !should_collide { + continue; + } + } + + // Create a collision pair. + broad_collision_pairs.push((*entity1, *entity2)); - if *store_intersections1 { - if let Ok(mut intersections) = aabb_intersection_query.get_mut(*ent1) { - intersections.push(*ent2); + // TODO: Handle this more efficiently. + if flags1.contains(AabbIntervalFlags::STORE_INTERSECTIONS) { + if let Ok(mut intersections) = aabb_intersection_query.get_mut(*entity1) { + intersections.push(*entity2); } } - if *store_intersections2 { - if let Ok(mut intersections) = aabb_intersection_query.get_mut(*ent2) { - intersections.push(*ent1); + if flags2.contains(AabbIntervalFlags::STORE_INTERSECTIONS) { + if let Ok(mut intersections) = aabb_intersection_query.get_mut(*entity2) { + intersections.push(*entity1); } } } diff --git a/src/collision/collider/world_query.rs b/src/collision/collider/world_query.rs index 195015780..f0b96033d 100644 --- a/src/collision/collider/world_query.rs +++ b/src/collision/collider/world_query.rs @@ -23,6 +23,7 @@ pub struct ColliderQuery { pub friction: Option<&'static Friction>, pub restitution: Option<&'static Restitution>, pub shape: &'static C, + pub active_hooks: Option<&'static ActiveCollisionHooks>, } impl ColliderQueryItem<'_, C> { @@ -35,4 +36,10 @@ impl ColliderQueryItem<'_, C> { .as_ref() .map_or_else(default, |t| t.0) } + + /// Returns the [`ActiveCollisionHooks`] for the collider. + pub fn active_hooks(&self) -> ActiveCollisionHooks { + self.active_hooks + .map_or(ActiveCollisionHooks::empty(), |h| *h) + } } diff --git a/src/collision/hooks.rs b/src/collision/hooks.rs new file mode 100644 index 000000000..b720be69f --- /dev/null +++ b/src/collision/hooks.rs @@ -0,0 +1,231 @@ +//! Collision hooks for filtering and modifying contacts. +//! +//! See the [`CollisionHooks`] trait for more information. + +use crate::prelude::*; +use bevy::{ecs::system::ReadOnlySystemParam, prelude::*}; + +/// A trait for user-defined hooks that can filter and modify contacts. +/// +/// This can be useful for advanced contact scenarios, such as: +/// +/// - One-way platforms +/// - Conveyor belts +/// - Non-uniform friction and restitution +/// +/// Collision hooks are more flexible than built-in filtering options like [`CollisionLayers`], +/// but can be more complicated to define, and can have slightly more overhead. +/// It is recommended to use hooks only when existing options are not sufficient. +/// +/// Only one set of collision hooks can be defined per broad phase and narrow phase. +/// +/// # Defining Hooks +/// +/// Collision hooks can be defined by implementing the [`CollisionHooks`] trait for a type +/// that implements [`SystemParam`]. The system parameter allows the hooks to do things like +/// access resources, query for components, and perform [spatial queries](crate::spatial_query). +/// +/// Note that mutable access is not allowed for the system parameter, as hooks may be called +/// during parallel iteration. However, access to [`Commands`] is provided for deferred changes. +/// +/// Below is an example of using collision hooks to implement interaction groups and one-way platforms: +/// +/// ``` +#[cfg_attr(feature = "2d", doc = "use avian2d::prelude::*;")] +#[cfg_attr(feature = "3d", doc = "use avian3d::prelude::*;")] +/// use bevy::{ecs::system::SystemParam, prelude::*}; +/// +/// /// A component that groups entities for interactions. Only entities in the same group can collide. +/// #[derive(Component)] +/// struct InteractionGroup(u32); +/// +/// /// A component that marks an entity as a one-way platform. +/// #[derive(Component)] +/// struct OneWayPlatform; +/// +/// // Define a `SystemParam` for the collision hooks. +/// #[derive(SystemParam)] +/// struct MyHooks<'w, 's> { +/// interaction_query: Query<'w, 's, &'static InteractionGroup>, +/// platform_query: Query<'w, 's, &'static Transform, With>, +/// } +/// +/// // Implement the `CollisionHooks` trait. +/// impl CollisionHooks for MyHooks<'_, '_> { +/// fn filter_pairs(&self, entity1: Entity, entity2: Entity, _commands: &mut Commands) -> bool { +/// // Only allow collisions between entities in the same interaction group. +/// // This could be a basic solution for "multiple physics worlds" that don't interact. +/// let Ok([group1, group2]) = self.interaction_query.get_many([entity1, entity2]) else { +/// return true; +/// }; +/// group1.0 == group2.0 +/// } +/// +/// fn modify_contacts(&self, contacts: &mut Contacts, _commands: &mut Commands) -> bool { +/// // Allow entities to pass through the bottom and sides of one-way platforms. +/// // See the `one_way_platform_2d` example for a full implementation. +/// let (entity1, entity2) = (contacts.entity1, contacts.entity2); +/// !is_hitting_top_of_platform(entity1, entity2, &self.platform_query, &contacts) +/// } +/// } +/// # +/// # fn is_hitting_top_of_platform( +/// # entity1: Entity, +/// # entity2: Entity, +/// # platform_query: &Query<&Transform, With>, +/// # contacts: &Contacts, +/// # ) -> bool { +/// # todo!() +/// # } +/// ``` +/// +/// The hooks can then be added to the app using [`PhysicsPlugins::with_collision_hooks`]: +/// +/// ```no_run +#[cfg_attr(feature = "2d", doc = "# use avian2d::prelude::*;")] +#[cfg_attr(feature = "3d", doc = "# use avian3d::prelude::*;")] +/// # use bevy::{ecs::system::SystemParam, prelude::*}; +/// # +/// # #[derive(SystemParam)] +/// # struct MyHooks {} +/// # +/// # // No-op hooks for the example. +/// # impl CollisionHooks for MyHooks {} +/// # +/// fn main() { +/// App::new() +/// .add_plugins(( +/// DefaultPlugins, +/// PhysicsPlugins::default().with_collision_hooks::(), +/// )) +/// .run(); +/// } +/// ``` +/// +/// This is equivalent to manually replacing the default [`BroadPhasePlugin`] and [`NarrowPhasePlugin`] +/// with instances that have the desired hooks provided using generics. +/// +/// [`SystemParam`]: bevy::ecs::system::SystemParam +/// +/// # Activating Hooks +/// +/// Hooks are *only* called for collisions where at least one entity has the [`ActiveCollisionHooks`] component +/// with the corresponding flags set. By default, no hooks are called. +/// +/// ``` +#[cfg_attr(feature = "2d", doc = "# use avian2d::prelude::*;")] +#[cfg_attr(feature = "3d", doc = "# use avian3d::prelude::*;")] +/// # use bevy::prelude::*; +/// # +/// # fn setup(mut commands: Commands) { +/// // Spawn a collider with filtering hooks enabled. +/// commands.spawn((Collider::capsule(0.5, 1.5), ActiveCollisionHooks::FILTER_PAIRS)); +/// +/// // Spawn a collider with both filtering and contact modification hooks enabled. +/// commands.spawn(( +/// Collider::capsule(0.5, 1.5), +/// ActiveCollisionHooks::FILTER_PAIRS | ActiveCollisionHooks::MODIFY_CONTACTS +/// )); +/// +/// // Alternatively, all hooks can be enabled with `ActiveCollisionHooks::all()`. +/// commands.spawn((Collider::capsule(0.5, 1.5), ActiveCollisionHooks::all())); +/// # } +/// ``` +/// +/// # Caveats +/// +/// Collision hooks can access the ECS quite freely, but there are a few limitations: +/// +/// - Only one set of collision hooks can be defined per broad phase and narrow phase. +/// - Only read-only ECS access is allowed for the hook system parameter. Use the provided [`Commands`] for deferred ECS operations. +/// - Note that command execution order is unspecified if the `parallel` feature is enabled. +/// - Access to the [`BroadCollisionPairs`] resource is not allowed inside [`CollisionHooks::filter_pairs`]. +/// Trying to access it will result in a panic. +/// - Access to the [`Collisions`] resource is not allowed inside [`CollisionHooks::modify_contacts`]. +/// Trying to access it will result in a panic. +#[expect(unused_variables)] +pub trait CollisionHooks: ReadOnlySystemParam + Send + Sync { + /// A contact pair filtering hook that determines whether contacts should be computed + /// between `entity1` and `entity2`. If `false` is returned, contacts will not be computed. + /// + /// This is called in the broad phase, before [`Contacts`] have been computed for the pair. + /// + /// The provided [`Commands`] can be used for deferred ECS operations that run after + /// broad phase pairs have been found. + /// + /// # Notes + /// + /// - Only called if at least one entity in the contact pair has [`ActiveCollisionHooks::FILTER_PAIRS`] set. + /// - Only called if at least one entity in the contact pair is not [`RigidBody::Static`] and not [`Sleeping`]. + /// - Access to the [`BroadCollisionPairs`] resource is not allowed in this method. + /// Trying to access it will result in a panic. + fn filter_pairs(&self, entity1: Entity, entity2: Entity, commands: &mut Commands) -> bool { + true + } + + /// A contact modification hook that allows modifying the contacts for a given contact pair. + /// If `false` is returned, the contact pair will be removed. + /// + /// This is called in the narrow phase, after [`Contacts`] have been computed for the pair, + /// but before constraints have been generated for the contact solver. + /// + /// The provided [`Commands`] can be used for deferred ECS operations that run after + /// narrow phase [`Contacts`] have been computed and constraints have been generated. + /// + /// # Notes + /// + /// - Only called if at least one entity in the contact pair has [`ActiveCollisionHooks::MODIFY_CONTACTS`] set. + /// - Only called if at least one entity in the contact pair is not [`RigidBody::Static`] and not [`Sleeping`]. + /// - Impulses stored in `contacts` are from the previous physics tick. + /// - Command execution order is unspecified if the `parallel` feature is enabled. + /// - Access to the [`Collisions`] resource is not allowed in this method. + /// Trying to access it will result in a panic. + fn modify_contacts(&self, contacts: &mut Contacts, commands: &mut Commands) -> bool { + true + } +} + +// No-op implementation for `()` to allow default hooks for plugins. +impl CollisionHooks for () {} + +/// A component with flags indicating which [`CollisionHooks`] should be called for collisions with an entity. +/// +/// Hooks will only be called if either entity in a collision has the corresponding flags set. +/// +/// Default: [`ActiveCollisionHooks::empty()`] +/// +/// # Example +/// +/// ``` +#[cfg_attr(feature = "2d", doc = "# use avian2d::prelude::*;")] +#[cfg_attr(feature = "3d", doc = "# use avian3d::prelude::*;")] +/// # use bevy::prelude::*; +/// # +/// # fn setup(mut commands: Commands) { +/// // Spawn a collider with filtering hooks enabled. +/// commands.spawn((Collider::capsule(0.5, 1.5), ActiveCollisionHooks::FILTER_PAIRS)); +/// +/// // Spawn a collider with both filtering and contact modification hooks enabled. +/// commands.spawn(( +/// Collider::capsule(0.5, 1.5), +/// ActiveCollisionHooks::FILTER_PAIRS | ActiveCollisionHooks::MODIFY_CONTACTS +/// )); +/// +/// // Alternatively, all hooks can be enabled with `ActiveCollisionHooks::all()`. +/// commands.spawn((Collider::capsule(0.5, 1.5), ActiveCollisionHooks::all())); +/// # } +/// ``` +#[repr(transparent)] +#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))] +#[derive(Component, Hash, Clone, Copy, PartialEq, Eq, Debug, Reflect)] +#[reflect(opaque, Hash, PartialEq, Debug)] +pub struct ActiveCollisionHooks(u8); + +bitflags::bitflags! { + impl ActiveCollisionHooks: u8 { + /// Set if [`CollisionHooks::filter_pairs`] should be called for collisions with this entity. + const FILTER_PAIRS = 0b0000_0001; + /// Set if [`CollisionHooks::modify_contacts`] should be called for collisions with this entity. + const MODIFY_CONTACTS = 0b0000_0010; + } +} diff --git a/src/collision/mod.rs b/src/collision/mod.rs index c4d32d5e0..b5d8ae478 100644 --- a/src/collision/mod.rs +++ b/src/collision/mod.rs @@ -22,6 +22,7 @@ pub mod broad_phase; ))] pub mod contact_query; pub mod contact_reporting; +pub mod hooks; pub mod narrow_phase; pub mod collider; @@ -46,16 +47,7 @@ use indexmap::IndexMap; // ========================================== /// A resource that stores all collision pairs. /// -/// Each colliding entity pair is associated with [`Contacts`] that can be accessed and modified -/// using the various associated methods. -/// -/// # Usage -/// -/// [`Collisions`] can be accessed at almost anytime, but for modifying and filtering collisions, -/// it is recommended to use the [`PostProcessCollisions`] schedule. See its documentation -/// for more information. -/// -/// ## Querying Collisions +/// # Querying Collisions /// /// The following methods can be used for querying existing collisions: /// @@ -65,29 +57,13 @@ use indexmap::IndexMap; /// - [`collisions_with_entity`](Self::collisions_with_entity) and /// [`collisions_with_entity_mut`](Self::collisions_with_entity_mut) /// -/// The collisions can be accessed at any time, but modifications to contacts should be performed -/// in the [`PostProcessCollisions`] schedule. Otherwise, the physics solver will use the old contact data. -/// -/// ## Filtering and Removing Collisions -/// -/// The following methods can be used for filtering or removing existing collisions: -/// -/// - [`retain`](Self::retain) -/// - [`remove_collision_pair`](Self::remove_collision_pair) -/// - [`remove_collisions_with_entity`](Self::remove_collisions_with_entity) -/// -/// Collision filtering and removal should be done in the [`PostProcessCollisions`] schedule. -/// Otherwise, the physics solver will use the old contact data. -/// -/// ## Adding New Collisions -/// -/// The following methods can be used for adding new collisions: +/// Collisions can be accessed at almost any time, but modifications to contacts should be performed +/// in the [`PostProcessCollisions`] schedule or in [`CollisionHooks`]. /// -/// - [`insert_collision_pair`](Self::insert_collision_pair) -/// - [`extend`](Self::extend) +/// # Filtering and Modifying Collisions /// -/// The most convenient place for adding new collisions is in the [`PostProcessCollisions`] schedule. -/// Otherwise, the physics solver might not have access to them in time. +/// Advanced collision filtering and modification can be done using [`CollisionHooks`]. +/// See its documentation for more information. /// /// # Implementation Details /// diff --git a/src/collision/narrow_phase.rs b/src/collision/narrow_phase.rs index a112d2183..644a826a9 100644 --- a/src/collision/narrow_phase.rs +++ b/src/collision/narrow_phase.rs @@ -16,7 +16,7 @@ use bevy::{ ecs::{ intern::Interned, schedule::{ExecutorKind, LogLevel, ScheduleBuildSettings, ScheduleLabel}, - system::SystemParam, + system::{StaticSystemParam, SystemParam, SystemParamItem}, }, prelude::*, }; @@ -33,17 +33,17 @@ use bevy::{ /// The plugin takes a collider type. This should be [`Collider`] for /// the vast majority of applications, but for custom collisión backends /// you may use any collider that implements the [`AnyCollider`] trait. -pub struct NarrowPhasePlugin { +pub struct NarrowPhasePlugin { schedule: Interned, /// If `true`, the narrow phase will generate [`ContactConstraint`]s /// and add them to the [`ContactConstraints`] resource. /// /// Contact constraints are used by the [`SolverPlugin`] for solving contacts. generate_constraints: bool, - _phantom: PhantomData, + _phantom: PhantomData<(C, H)>, } -impl NarrowPhasePlugin { +impl NarrowPhasePlugin { /// Creates a [`NarrowPhasePlugin`] with the schedule used for running its systems /// and whether it should generate [`ContactConstraint`]s for the [`ContactConstraints`] resource. /// @@ -59,13 +59,16 @@ impl NarrowPhasePlugin { } } -impl Default for NarrowPhasePlugin { +impl Default for NarrowPhasePlugin { fn default() -> Self { Self::new(PhysicsSchedule, true) } } -impl Plugin for NarrowPhasePlugin { +impl Plugin for NarrowPhasePlugin +where + for<'w, 's> SystemParamItem<'w, 's, H>: CollisionHooks, +{ fn build(&self, app: &mut App) { // For some systems, we only want one instance, even if there are multiple // NarrowPhasePlugin instances with different collider types. @@ -129,7 +132,7 @@ impl Plugin for NarrowPhasePlugin { // Collect contacts into `Collisions`. app.add_systems( self.schedule, - collect_collisions:: + collect_collisions:: .in_set(NarrowPhaseSet::CollectCollisions) // Allowing ambiguities is required so that it's possible // to have multiple collision backends at the same time. @@ -250,12 +253,22 @@ pub enum NarrowPhaseSet { Last, } -fn collect_collisions( +fn collect_collisions( mut narrow_phase: NarrowPhase, broad_collision_pairs: Res, time: Res