forked from dimforge/bevy_rapier
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathevents.rs
233 lines (214 loc) · 8.25 KB
/
events.rs
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
use crate::math::{Real, Vect};
use bevy::prelude::{Entity, Event};
use rapier::dynamics::RigidBodySet;
use rapier::geometry::{
ColliderHandle, ColliderSet, CollisionEvent as RapierCollisionEvent, CollisionEventFlags,
ContactForceEvent as RapierContactForceEvent, ContactPair,
};
use rapier::pipeline::EventHandler;
use std::collections::HashMap;
use std::sync::RwLock;
#[cfg(doc)]
use crate::prelude::ActiveEvents;
/// Events occurring when two colliders start or stop colliding
///
/// This will only get triggered if the entity has the
/// [`ActiveEvents::COLLISION_EVENTS`] flag enabled.
#[derive(Event, Copy, Clone, Debug, PartialEq, Eq)]
pub enum CollisionEvent {
/// Event occurring when two colliders start colliding
Started(Entity, Entity, CollisionEventFlags),
/// Event occurring when two colliders stop colliding
Stopped(Entity, Entity, CollisionEventFlags),
}
/// Event occurring when the sum of the magnitudes of the contact forces
/// between two colliders exceed a threshold ([`ContactForceEventThreshold`]).
///
/// This will only get triggered if the entity has the
/// [`ActiveEvents::CONTACT_FORCE_EVENTS`] flag enabled.
#[derive(Event, Copy, Clone, Debug, PartialEq)]
pub struct ContactForceEvent {
/// The first collider involved in the contact.
pub collider1: Entity,
/// The second collider involved in the contact.
pub collider2: Entity,
/// The sum of all the forces between the two colliders.
pub total_force: Vect,
/// The sum of the magnitudes of each force between the two colliders.
///
/// Note that this is **not** the same as the magnitude of `self.total_force`.
/// Here we are summing the magnitude of all the forces, instead of taking
/// the magnitude of their sum.
pub total_force_magnitude: Real,
/// The world-space (unit) direction of the force with strongest magnitude.
pub max_force_direction: Vect,
/// The magnitude of the largest force at a contact point of this contact pair.
pub max_force_magnitude: Real,
}
// TODO: it may be more efficient to use crossbeam channel.
// However crossbeam channels cause a Segfault (I have not
// investigated how to reproduce this exactly to open an
// issue).
/// A set of queues collecting events emitted by the physics engine.
pub(crate) struct EventQueue<'a> {
// Used ot retrieve the entity of colliders that have been removed from the simulation
// since the last physics step.
pub deleted_colliders: &'a HashMap<ColliderHandle, Entity>,
pub collision_events: RwLock<Vec<CollisionEvent>>,
pub contact_force_events: RwLock<Vec<ContactForceEvent>>,
}
impl<'a> EventQueue<'a> {
fn collider2entity(&self, colliders: &ColliderSet, handle: ColliderHandle) -> Entity {
colliders
.get(handle)
.map(|co| Entity::from_bits(co.user_data as u64))
.or_else(|| self.deleted_colliders.get(&handle).copied())
.expect("Internal error: entity not found for collision event.")
}
}
impl<'a> EventHandler for EventQueue<'a> {
fn handle_collision_event(
&self,
_bodies: &RigidBodySet,
colliders: &ColliderSet,
event: RapierCollisionEvent,
_: Option<&ContactPair>,
) {
let event = match event {
RapierCollisionEvent::Started(h1, h2, flags) => {
let e1 = self.collider2entity(colliders, h1);
let e2 = self.collider2entity(colliders, h2);
CollisionEvent::Started(e1, e2, flags)
}
RapierCollisionEvent::Stopped(h1, h2, flags) => {
let e1 = self.collider2entity(colliders, h1);
let e2 = self.collider2entity(colliders, h2);
CollisionEvent::Stopped(e1, e2, flags)
}
};
if let Ok(mut events) = self.collision_events.write() {
events.push(event);
}
}
fn handle_contact_force_event(
&self,
dt: Real,
_bodies: &RigidBodySet,
colliders: &ColliderSet,
contact_pair: &ContactPair,
total_force_magnitude: Real,
) {
let rapier_event =
RapierContactForceEvent::from_contact_pair(dt, contact_pair, total_force_magnitude);
let event = ContactForceEvent {
collider1: self.collider2entity(colliders, rapier_event.collider1),
collider2: self.collider2entity(colliders, rapier_event.collider2),
total_force: rapier_event.total_force.into(),
total_force_magnitude: rapier_event.total_force_magnitude,
max_force_direction: rapier_event.max_force_direction.into(),
max_force_magnitude: rapier_event.max_force_magnitude,
};
if let Ok(mut events) = self.contact_force_events.write() {
events.push(event);
}
}
}
#[cfg(test)]
mod test {
use bevy::time::TimePlugin;
use systems::tests::HeadlessRenderPlugin;
use crate::{plugin::*, prelude::*};
#[cfg(feature = "dim3")]
fn cuboid(hx: Real, hy: Real, hz: Real) -> Collider {
Collider::cuboid(hx, hy, hz)
}
#[cfg(feature = "dim2")]
fn cuboid(hx: Real, hy: Real, _hz: Real) -> Collider {
Collider::cuboid(hx, hy)
}
#[test]
pub fn events_received() {
return main();
use bevy::prelude::*;
#[derive(Resource, Reflect)]
pub struct EventsSaver<E: Event> {
pub events: Vec<E>,
}
impl<E: Event> Default for EventsSaver<E> {
fn default() -> Self {
Self {
events: Default::default(),
}
}
}
pub fn save_events<E: Event + Clone>(
mut events: EventReader<E>,
mut saver: ResMut<EventsSaver<E>>,
) {
for event in events.read() {
saver.events.push(event.clone());
}
}
fn run_test(app: &mut App) {
app.add_systems(PostUpdate, save_events::<CollisionEvent>)
.add_systems(PostUpdate, save_events::<ContactForceEvent>)
.init_resource::<EventsSaver<CollisionEvent>>()
.init_resource::<EventsSaver<ContactForceEvent>>();
// while app.plugins_state() == bevy::app::PluginsState::Adding {
// #[cfg(not(target_arch = "wasm32"))]
// bevy::tasks::tick_global_task_pools_on_main_thread();
// }
// app.finish();
// app.cleanup();
let mut time = app.world_mut().get_resource_mut::<Time<Virtual>>().unwrap();
time.set_relative_speed(1000f32);
for _ in 0..300 {
// FIXME: advance by set durations to avoid being at the mercy of the CPU.
app.update();
}
let saved_collisions = app
.world()
.get_resource::<EventsSaver<CollisionEvent>>()
.unwrap();
assert!(saved_collisions.events.len() > 0);
let saved_contact_forces = app
.world()
.get_resource::<EventsSaver<CollisionEvent>>()
.unwrap();
assert!(saved_contact_forces.events.len() > 0);
}
/// Adapted from events example
fn main() {
let mut app = App::new();
app.add_plugins((
HeadlessRenderPlugin,
TransformPlugin,
TimePlugin,
RapierPhysicsPlugin::<NoUserData>::default(),
))
.add_systems(Startup, setup_physics);
run_test(&mut app);
}
pub fn setup_physics(mut commands: Commands) {
/*
* Ground
*/
commands.spawn((
TransformBundle::from(Transform::from_xyz(0.0, -1.2, 0.0)),
cuboid(4.0, 1.0, 1.0),
));
commands.spawn((
TransformBundle::from(Transform::from_xyz(0.0, 5.0, 0.0)),
cuboid(4.0, 1.5, 1.0),
Sensor,
));
commands.spawn((
TransformBundle::from(Transform::from_xyz(0.0, 13.0, 0.0)),
RigidBody::Dynamic,
cuboid(0.5, 0.5, 0.5),
ActiveEvents::COLLISION_EVENTS,
ContactForceEventThreshold(30.0),
));
}
}
}