avian2d/dynamics/solver/islands/
sleeping.rs

1//! Sleeping and waking for [`PhysicsIsland`](super::PhysicsIsland)s.
2//!
3//! See [`IslandSleepingPlugin`].
4
5use bevy::{
6    app::{App, Plugin},
7    ecs::{
8        entity::Entity,
9        entity_disabling::Disabled,
10        error::Result,
11        lifecycle::{HookContext, Insert, Replace},
12        observer::On,
13        query::{Changed, Has, Or, With, Without},
14        resource::Resource,
15        schedule::{
16            IntoScheduleConfigs,
17            common_conditions::{resource_changed, resource_exists},
18        },
19        system::{
20            Command, Commands, Local, ParamSet, Query, Res, ResMut, SystemChangeTick, SystemState,
21            lifetimeless::{SQuery, SResMut},
22        },
23        world::{DeferredWorld, Mut, Ref, World},
24    },
25    prelude::{Deref, DerefMut},
26    time::Time,
27};
28
29use crate::{
30    data_structures::bit_vec::BitVec,
31    dynamics::solver::{
32        constraint_graph::ConstraintGraph,
33        islands::{BodyIslandNode, IslandId, PhysicsIslands},
34        joint_graph::JointGraph,
35        solver_body::SolverBody,
36    },
37    prelude::*,
38    schedule::{LastPhysicsTick, is_changed_after_tick},
39};
40
41/// A plugin for managing sleeping and waking of [`PhysicsIsland`](super::PhysicsIsland)s.
42pub struct IslandSleepingPlugin;
43
44impl Plugin for IslandSleepingPlugin {
45    fn build(&self, app: &mut App) {
46        app.init_resource::<AwakeIslandBitVec>();
47        app.init_resource::<TimeToSleep>();
48
49        // Insert `SleepThreshold` and `SleepTimer` for each `SolverBody`.
50        app.register_required_components::<SolverBody, SleepThreshold>();
51        app.register_required_components::<SolverBody, SleepTimer>();
52
53        // Set up cached system states for sleeping and waking bodies or islands.
54        let cached_system_state1 = CachedBodySleepingSystemState(SystemState::new(app.world_mut()));
55        let cached_system_state2 =
56            CachedIslandSleepingSystemState(SystemState::new(app.world_mut()));
57        let cached_system_state3 = CachedIslandWakingSystemState(SystemState::new(app.world_mut()));
58        app.insert_resource(cached_system_state1);
59        app.insert_resource(cached_system_state2);
60        app.insert_resource(cached_system_state3);
61
62        // Set up hooks to automatically sleep/wake islands when `Sleeping` is added/removed.
63        app.world_mut()
64            .register_component_hooks::<Sleeping>()
65            .on_add(sleep_on_add_sleeping)
66            .on_remove(wake_on_remove_sleeping);
67
68        app.add_observer(wake_on_replace_rigid_body);
69        app.add_observer(wake_on_enable_rigid_body);
70
71        app.add_systems(
72            PhysicsSchedule,
73            (
74                update_sleeping_states,
75                wake_islands_with_sleeping_disabled,
76                wake_on_changed,
77                wake_all_islands.run_if(resource_changed::<Gravity>),
78                sleep_islands,
79            )
80                .chain()
81                .run_if(resource_exists::<PhysicsIslands>)
82                .in_set(PhysicsStepSystems::Sleeping),
83        );
84    }
85}
86
87fn sleep_on_add_sleeping(mut world: DeferredWorld, ctx: HookContext) {
88    let Some(body_island) = world.get::<BodyIslandNode>(ctx.entity) else {
89        return;
90    };
91
92    let island_id = body_island.island_id;
93
94    // Check if the island is already sleeping.
95    if let Some(island) = world
96        .get_resource::<PhysicsIslands>()
97        .and_then(|islands| islands.get(island_id))
98        && island.is_sleeping
99    {
100        return;
101    }
102
103    world.commands().queue_silenced(SleepBody(ctx.entity));
104}
105
106fn wake_on_remove_sleeping(mut world: DeferredWorld, ctx: HookContext) {
107    let Some(body_island) = world.get::<BodyIslandNode>(ctx.entity) else {
108        return;
109    };
110
111    let island_id = body_island.island_id;
112
113    // Check if the island is already awake.
114    if let Some(island) = world
115        .get_resource::<PhysicsIslands>()
116        .and_then(|islands| islands.get(island_id))
117        && !island.is_sleeping
118    {
119        return;
120    }
121
122    world.commands().queue_silenced(WakeBody(ctx.entity));
123}
124
125fn wake_on_replace_rigid_body(
126    trigger: On<Replace, RigidBody>,
127    mut commands: Commands,
128    query: Query<&BodyIslandNode>,
129) {
130    let Ok(body_island) = query.get(trigger.entity) else {
131        return;
132    };
133
134    commands.queue(WakeIslands(vec![body_island.island_id]));
135}
136
137fn wake_on_enable_rigid_body(
138    trigger: On<Insert, BodyIslandNode>,
139    mut commands: Commands,
140    mut query: Query<
141        (&BodyIslandNode, &mut SleepTimer, Has<Sleeping>),
142        Or<(With<Disabled>, Without<Disabled>)>,
143    >,
144) {
145    let Ok((body_island, mut sleep_timer, is_sleeping)) = query.get_mut(trigger.entity) else {
146        return;
147    };
148
149    if is_sleeping {
150        commands.entity(trigger.entity).try_remove::<Sleeping>();
151    }
152
153    // Reset the sleep timer and wake up the island.
154    if sleep_timer.0 > 0.0 {
155        sleep_timer.0 = 0.0;
156        commands.queue(WakeIslands(vec![body_island.island_id]));
157    }
158}
159
160/// A bit vector that stores which islands are kept awake and which are allowed to sleep.
161#[derive(Resource, Default, Deref, DerefMut)]
162pub(crate) struct AwakeIslandBitVec(pub(crate) BitVec);
163
164fn wake_islands_with_sleeping_disabled(
165    mut awake_island_bit_vec: ResMut<AwakeIslandBitVec>,
166    mut query: Query<
167        (&BodyIslandNode, &mut SleepTimer),
168        Or<(
169            With<SleepingDisabled>,
170            With<Disabled>,
171            With<RigidBodyDisabled>,
172        )>,
173    >,
174) {
175    // Wake up all islands that have a body with `SleepingDisabled`.
176    for (body_island, mut sleep_timer) in &mut query {
177        awake_island_bit_vec.set_and_grow(body_island.island_id.0 as usize);
178
179        // Reset the sleep timer.
180        sleep_timer.0 = 0.0;
181    }
182}
183
184fn update_sleeping_states(
185    mut awake_island_bit_vec: ResMut<AwakeIslandBitVec>,
186    mut islands: ResMut<PhysicsIslands>,
187    mut query: Query<
188        (
189            &mut SleepTimer,
190            &SleepThreshold,
191            &SolverBody,
192            &BodyIslandNode,
193        ),
194        (Without<Sleeping>, Without<SleepingDisabled>),
195    >,
196    length_unit: Res<PhysicsLengthUnit>,
197    time_to_sleep: Res<TimeToSleep>,
198    time: Res<Time>,
199) {
200    let length_unit_squared = length_unit.0 * length_unit.0;
201    let delta_secs = time.delta_secs();
202
203    islands.split_candidate_sleep_timer = 0.0;
204
205    // TODO: This would be nice to do in parallel.
206    for (mut sleep_timer, sleep_threshold, solver_body, island_data) in query.iter_mut() {
207        let lin_vel_squared = solver_body.linear_velocity.length_squared();
208        #[cfg(feature = "2d")]
209        let ang_vel_squared = solver_body.angular_velocity * solver_body.angular_velocity;
210        #[cfg(feature = "3d")]
211        let ang_vel_squared = solver_body.angular_velocity.length_squared();
212
213        // Keep signs.
214        let lin_threshold_squared = sleep_threshold.linear * sleep_threshold.linear.abs();
215        let ang_threshold_squared = sleep_threshold.angular * sleep_threshold.angular.abs();
216
217        if lin_vel_squared < length_unit_squared * lin_threshold_squared as Scalar
218            && ang_vel_squared < ang_threshold_squared as Scalar
219        {
220            // Increment the sleep timer.
221            sleep_timer.0 += delta_secs;
222        } else {
223            // Reset the sleep timer if the body is moving.
224            sleep_timer.0 = 0.0;
225        }
226
227        if sleep_timer.0 < time_to_sleep.0 {
228            // Keep the island awake.
229            awake_island_bit_vec.set_and_grow(island_data.island_id.0 as usize);
230        } else if let Some(island) = islands.get(island_data.island_id)
231            && island.constraints_removed > 0
232        {
233            // The body wants to sleep, but its island needs splitting first.
234            if sleep_timer.0 > islands.split_candidate_sleep_timer {
235                // This island is now the sleepiest candidate for splitting.
236                islands.split_candidate = Some(island_data.island_id);
237                islands.split_candidate_sleep_timer = sleep_timer.0;
238            }
239        }
240    }
241}
242
243fn sleep_islands(
244    mut awake_island_bit_vec: ResMut<AwakeIslandBitVec>,
245    mut islands: ResMut<PhysicsIslands>,
246    mut commands: Commands,
247    mut sleep_buffer: Local<Vec<IslandId>>,
248    mut wake_buffer: Local<Vec<IslandId>>,
249) {
250    // Clear the buffers.
251    sleep_buffer.clear();
252    wake_buffer.clear();
253
254    // Sleep islands that are not in the awake bit vector.
255    for island in islands.iter_mut() {
256        if awake_island_bit_vec.get(island.id.0 as usize) {
257            if island.is_sleeping {
258                wake_buffer.push(island.id);
259            }
260        } else if !island.is_sleeping && island.constraints_removed == 0 {
261            // The island does not have a pending split, so it can go to sleep.
262            sleep_buffer.push(island.id);
263        }
264    }
265
266    // Sleep islands.
267    let sleep_buffer = sleep_buffer.clone();
268    commands.queue(|world: &mut World| {
269        SleepIslands(sleep_buffer).apply(world);
270    });
271
272    // Wake islands.
273    let wake_buffer = wake_buffer.clone();
274    commands.queue(|world: &mut World| {
275        WakeIslands(wake_buffer).apply(world);
276    });
277
278    // Reset the awake island bit vector.
279    awake_island_bit_vec.set_bit_count_and_clear(islands.len());
280}
281
282#[derive(Resource)]
283struct CachedBodySleepingSystemState(
284    SystemState<(
285        SQuery<&'static mut BodyIslandNode, Or<(With<Disabled>, Without<Disabled>)>>,
286        SQuery<&'static RigidBodyColliders>,
287        SResMut<PhysicsIslands>,
288        SResMut<ContactGraph>,
289        SResMut<JointGraph>,
290    )>,
291);
292
293/// A [`Command`] that forces a [`RigidBody`] and its [`PhysicsIsland`][super::PhysicsIsland] to be [`Sleeping`].
294pub struct SleepBody(pub Entity);
295
296impl Command<Result> for SleepBody {
297    fn apply(self, world: &mut World) -> Result {
298        if let Ok(entity) = world.get_entity(self.0) {
299            if let Some(island_id) = entity.get::<BodyIslandNode>().map(|node| node.island_id) {
300                world.try_resource_scope(|world, mut state: Mut<CachedBodySleepingSystemState>| {
301                    let (
302                        mut body_islands,
303                        body_colliders,
304                        mut islands,
305                        mut contact_graph,
306                        mut joint_graph,
307                    ) = state.0.get_mut(world);
308
309                    let Some(island) = islands.get_mut(island_id) else {
310                        return;
311                    };
312
313                    // The island must be split before it can be woken up.
314                    // Note that this is expensive.
315                    if island.constraints_removed > 0 {
316                        islands.split_island(
317                            island_id,
318                            &mut body_islands,
319                            &body_colliders,
320                            &mut contact_graph,
321                            &mut joint_graph,
322                        );
323                    }
324
325                    // The ID of the body's island might have changed due to the split,
326                    // so we need to retrieve it again.
327                    let island_id = body_islands.get(self.0).map(|node| node.island_id).unwrap();
328
329                    // Sleep the island.
330                    SleepIslands(vec![island_id]).apply(world);
331                });
332                Ok(())
333            } else {
334                Err(format!(
335                    "Tried to sleep entity {:?} that is not a body or does not belong to an island",
336                    self.0
337                )
338                .into())
339            }
340        } else {
341            Err(format!("Tried to sleep entity {:?} that does not exist", self.0).into())
342        }
343    }
344}
345
346#[derive(Resource)]
347struct CachedIslandSleepingSystemState(
348    SystemState<(
349        SQuery<(
350            &'static BodyIslandNode,
351            &'static mut SleepTimer,
352            Option<&'static RigidBodyColliders>,
353        )>,
354        SResMut<PhysicsIslands>,
355        SResMut<ContactGraph>,
356        SResMut<ConstraintGraph>,
357    )>,
358);
359
360/// A [`Command`] that makes the [`PhysicsIsland`](super::PhysicsIsland)s with the given IDs sleep if they are not already sleeping.
361pub struct SleepIslands(pub Vec<IslandId>);
362
363impl Command for SleepIslands {
364    fn apply(self, world: &mut World) {
365        world.try_resource_scope(|world, mut state: Mut<CachedIslandSleepingSystemState>| {
366            let (bodies, mut islands, mut contact_graph, mut constraint_graph) =
367                state.0.get_mut(world);
368
369            let mut bodies_to_sleep = Vec::<(Entity, Sleeping)>::new();
370
371            for island_id in self.0 {
372                if let Some(island) = islands.get_mut(island_id) {
373                    if island.is_sleeping {
374                        // The island is already sleeping, no need to sleep it again.
375                        return;
376                    }
377
378                    island.is_sleeping = true;
379
380                    let mut body = island.head_body;
381
382                    while let Some(entity) = body {
383                        let Ok((body_island, _, colliders)) = bodies.get(entity) else {
384                            body = None;
385                            continue;
386                        };
387
388                        // Transfer the contact pairs to the sleeping set, and remove the body from the constraint graph.
389                        if let Some(colliders) = colliders {
390                            for collider in colliders {
391                                contact_graph.sleep_entity_with(collider, |graph, contact_pair| {
392                                    // Remove touching contacts from the constraint graph.
393                                    if !contact_pair.is_touching()
394                                        || !contact_pair.generates_constraints()
395                                    {
396                                        return;
397                                    }
398                                    let contact_edge = graph
399                                    .get_edge_mut_by_id(contact_pair.contact_id)
400                                    .unwrap_or_else(|| {
401                                        panic!(
402                                            "Contact edge with id {:?} not found in contact graph.",
403                                            contact_pair.contact_id
404                                        )
405                                    });
406                                    if let (Some(body1), Some(body2)) =
407                                        (contact_pair.body1, contact_pair.body2)
408                                    {
409                                        for _ in 0..contact_edge.constraint_handles.len() {
410                                            constraint_graph.pop_manifold(
411                                                &mut graph.edges,
412                                                contact_pair.contact_id,
413                                                body1,
414                                                body2,
415                                            );
416                                        }
417                                    }
418                                });
419                            }
420                        }
421
422                        bodies_to_sleep.push((entity, Sleeping));
423                        body = body_island.next;
424                    }
425                }
426            }
427
428            // Batch insert `Sleeping` to the bodies.
429            world.insert_batch(bodies_to_sleep);
430        });
431    }
432}
433
434#[derive(Resource)]
435struct CachedIslandWakingSystemState(
436    SystemState<(
437        SQuery<(
438            &'static BodyIslandNode,
439            &'static mut SleepTimer,
440            Option<&'static RigidBodyColliders>,
441        )>,
442        SResMut<PhysicsIslands>,
443        SResMut<ContactGraph>,
444        SResMut<ConstraintGraph>,
445    )>,
446);
447
448/// A [`Command`] that wakes up a [`RigidBody`] and its [`PhysicsIsland`](super::PhysicsIsland) if it is [`Sleeping`].
449pub struct WakeBody(pub Entity);
450
451impl Command<Result> for WakeBody {
452    fn apply(self, world: &mut World) -> Result {
453        if let Ok(entity) = world.get_entity(self.0) {
454            if let Some(body_island) = entity.get::<BodyIslandNode>() {
455                WakeIslands(vec![body_island.island_id]).apply(world);
456                Ok(())
457            } else {
458                Err(format!(
459                    "Tried to wake entity {:?} that is not a body or does not belong to an island",
460                    self.0
461                )
462                .into())
463            }
464        } else {
465            Err(format!("Tried to wake entity {:?} that does not exist", self.0).into())
466        }
467    }
468}
469
470/// A [`Command`] that wakes up the [`PhysicsIsland`](super::PhysicsIsland)s with the given IDs if they are sleeping.
471pub struct WakeIslands(pub Vec<IslandId>);
472
473impl Command for WakeIslands {
474    fn apply(self, world: &mut World) {
475        world.try_resource_scope(|world, mut state: Mut<CachedIslandWakingSystemState>| {
476            let (mut bodies, mut islands, mut contact_graph, mut constraint_graph) =
477                state.0.get_mut(world);
478
479            let mut bodies_to_wake = Vec::<Entity>::new();
480
481            for island_id in self.0 {
482                if let Some(island) = islands.get_mut(island_id) {
483                    if !island.is_sleeping {
484                        // The island is not sleeping, no need to wake it up.
485                        continue;
486                    }
487
488                    island.is_sleeping = false;
489
490                    let mut body = island.head_body;
491
492                    while let Some(entity) = body {
493                        let Ok((body_island, mut sleep_timer, colliders)) = bodies.get_mut(entity)
494                        else {
495                            body = None;
496                            continue;
497                        };
498
499                        // Transfer the contact pairs to the awake set, and add touching contacts to the constraint graph.
500                        if let Some(colliders) = colliders {
501                            for collider in colliders {
502                                contact_graph.wake_entity_with(collider, |graph, contact_pair| {
503                                    // Add touching contacts to the constraint graph.
504                                    if !contact_pair.is_touching()
505                                        || !contact_pair.generates_constraints()
506                                    {
507                                        return;
508                                    }
509                                    let contact_edge = graph
510                                    .get_edge_mut_by_id(contact_pair.contact_id)
511                                    .unwrap_or_else(|| {
512                                        panic!(
513                                            "Contact edge with id {:?} not found in contact graph.",
514                                            contact_pair.contact_id
515                                        )
516                                    });
517                                    for _ in contact_pair.manifolds.iter() {
518                                        constraint_graph.push_manifold(contact_edge, contact_pair);
519                                    }
520                                });
521                            }
522                        }
523
524                        bodies_to_wake.push(entity);
525                        body = body_island.next;
526                        sleep_timer.0 = 0.0;
527                    }
528                }
529            }
530
531            // Remove `Sleeping` from the bodies.
532            bodies_to_wake.into_iter().for_each(|entity| {
533                world.entity_mut(entity).remove::<Sleeping>();
534            });
535        });
536    }
537}
538
539#[cfg(feature = "2d")]
540type ConstantForceChanges = Or<(
541    Changed<ConstantForce>,
542    Changed<ConstantTorque>,
543    Changed<ConstantLinearAcceleration>,
544    Changed<ConstantAngularAcceleration>,
545    Changed<ConstantLocalForce>,
546    Changed<ConstantLocalLinearAcceleration>,
547)>;
548#[cfg(feature = "3d")]
549type ConstantForceChanges = Or<(
550    Changed<ConstantForce>,
551    Changed<ConstantTorque>,
552    Changed<ConstantLinearAcceleration>,
553    Changed<ConstantAngularAcceleration>,
554    Changed<ConstantLocalForce>,
555    Changed<ConstantLocalTorque>,
556    Changed<ConstantLocalLinearAcceleration>,
557    Changed<ConstantLocalAngularAcceleration>,
558)>;
559
560/// Removes the [`Sleeping`] component from sleeping bodies when properties like
561/// position, rotation, velocity and external forces are changed by the user.
562fn wake_on_changed(
563    mut query: ParamSet<(
564        // These could've been changed by physics too.
565        // We need to ignore non-user changes.
566        Query<
567            (
568                Ref<Position>,
569                Ref<Rotation>,
570                Ref<LinearVelocity>,
571                Ref<AngularVelocity>,
572                Ref<SleepTimer>,
573                &BodyIslandNode,
574            ),
575            (
576                With<Sleeping>,
577                Or<(
578                    Changed<Position>,
579                    Changed<Rotation>,
580                    Changed<LinearVelocity>,
581                    Changed<AngularVelocity>,
582                    Changed<SleepTimer>,
583                )>,
584            ),
585        >,
586        // These are not modified by the physics engine
587        // and don't need special handling.
588        Query<&BodyIslandNode, Or<(ConstantForceChanges, Changed<GravityScale>)>>,
589    )>,
590    mut awake_island_bit_vec: ResMut<AwakeIslandBitVec>,
591    last_physics_tick: Res<LastPhysicsTick>,
592    system_tick: SystemChangeTick,
593) {
594    let this_run = system_tick.this_run();
595
596    for (pos, rot, lin_vel, ang_vel, sleep_timer, body_island) in &query.p0() {
597        if is_changed_after_tick(pos, last_physics_tick.0, this_run)
598            || is_changed_after_tick(rot, last_physics_tick.0, this_run)
599            || is_changed_after_tick(lin_vel, last_physics_tick.0, this_run)
600            || is_changed_after_tick(ang_vel, last_physics_tick.0, this_run)
601            || is_changed_after_tick(sleep_timer, last_physics_tick.0, this_run)
602        {
603            awake_island_bit_vec.set_and_grow(body_island.island_id.0 as usize);
604        }
605    }
606
607    for body_island in &query.p1() {
608        awake_island_bit_vec.set_and_grow(body_island.island_id.0 as usize);
609    }
610}
611
612/// Wakes up all sleeping [`PhysicsIsland`](super::PhysicsIsland)s. Triggered automatically when [`Gravity`] is changed.
613fn wake_all_islands(mut commands: Commands, islands: Res<PhysicsIslands>) {
614    let sleeping_islands: Vec<IslandId> = islands
615        .iter()
616        .filter_map(|island| island.is_sleeping.then_some(island.id))
617        .collect();
618
619    if !sleeping_islands.is_empty() {
620        commands.queue(WakeIslands(sleeping_islands));
621    }
622}