Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
bevyengine
GitHub Repository: bevyengine/bevy
Path: blob/main/crates/bevy_state/src/commands.rs
9368 views
1
use bevy_ecs::{system::Commands, world::World};
2
use log::debug;
3
4
use crate::state::{FreelyMutableState, NextState};
5
6
/// Extension trait for [`Commands`] adding `bevy_state` helpers.
7
pub trait CommandsStatesExt {
8
/// Sets the next state the app should move to.
9
///
10
/// Internally this schedules a command that updates the [`NextState<S>`](crate::prelude::NextState)
11
/// resource with `state`.
12
///
13
/// Note that commands introduce sync points to the ECS schedule, so modifying `NextState`
14
/// directly may be more efficient depending on your use-case.
15
fn set_state<S: FreelyMutableState>(&mut self, state: S);
16
17
/// Sets the next state the app should move to, skipping any state transitions if the next state is the same as the current state.
18
///
19
/// Internally this schedules a command that updates the [`NextState<S>`](crate::prelude::NextState)
20
/// resource with `state`.
21
///
22
/// Note that commands introduce sync points to the ECS schedule, so modifying `NextState`
23
/// directly may be more efficient depending on your use-case.
24
fn set_state_if_neq<S: FreelyMutableState>(&mut self, state: S);
25
}
26
27
impl CommandsStatesExt for Commands<'_, '_> {
28
fn set_state<S: FreelyMutableState>(&mut self, state: S) {
29
self.queue(move |w: &mut World| {
30
let mut next = w.resource_mut::<NextState<S>>();
31
if let NextState::PendingIfNeq(prev) = &*next {
32
debug!("overwriting next state {prev:?} with {state:?}");
33
}
34
next.set(state);
35
});
36
}
37
38
fn set_state_if_neq<S: FreelyMutableState>(&mut self, state: S) {
39
self.queue(move |w: &mut World| {
40
let mut next = w.resource_mut::<NextState<S>>();
41
if let NextState::PendingIfNeq(prev) = &*next
42
&& *prev != state
43
{
44
debug!("overwriting next state {prev:?} with {state:?} if not equal");
45
}
46
next.set_if_neq(state);
47
});
48
}
49
}
50
51