bevy/crates/bevy_state/src/state_scoped_events.rs
AlephCubed 6c003ef794
Loosen add_state_scoped_event trait bound. (#19401)
Fixes #18623, allowing `add_state_scoped_event` to work with computed
states.

As a side note, should state scoped events be updated to match the
recently changed [state scoped
entities](https://github.com/bevyengine/bevy/blob/main/release-content/migration-guides/rename_StateScoped.md)?
2025-05-29 21:37:53 +00:00

113 lines
3.3 KiB
Rust

use alloc::vec::Vec;
use core::marker::PhantomData;
use bevy_app::{App, SubApp};
use bevy_ecs::{
event::{Event, EventReader, Events},
resource::Resource,
system::Commands,
world::World,
};
use bevy_platform::collections::HashMap;
use crate::state::{OnExit, StateTransitionEvent, States};
fn clear_event_queue<E: Event>(w: &mut World) {
if let Some(mut queue) = w.get_resource_mut::<Events<E>>() {
queue.clear();
}
}
#[derive(Resource)]
struct StateScopedEvents<S: States> {
cleanup_fns: HashMap<S, Vec<fn(&mut World)>>,
}
impl<S: States> StateScopedEvents<S> {
fn add_event<E: Event>(&mut self, state: S) {
self.cleanup_fns
.entry(state)
.or_default()
.push(clear_event_queue::<E>);
}
fn cleanup(&self, w: &mut World, state: S) {
let Some(fns) = self.cleanup_fns.get(&state) else {
return;
};
for callback in fns {
(*callback)(w);
}
}
}
impl<S: States> Default for StateScopedEvents<S> {
fn default() -> Self {
Self {
cleanup_fns: HashMap::default(),
}
}
}
fn cleanup_state_scoped_event<S: States>(
mut c: Commands,
mut transitions: EventReader<StateTransitionEvent<S>>,
) {
let Some(transition) = transitions.read().last() else {
return;
};
if transition.entered == transition.exited {
return;
}
let Some(exited) = transition.exited.clone() else {
return;
};
c.queue(move |w: &mut World| {
w.resource_scope::<StateScopedEvents<S>, ()>(|w, events| {
events.cleanup(w, exited);
});
});
}
fn add_state_scoped_event_impl<E: Event, S: States>(
app: &mut SubApp,
_p: PhantomData<E>,
state: S,
) {
if !app.world().contains_resource::<StateScopedEvents<S>>() {
app.init_resource::<StateScopedEvents<S>>();
}
app.add_event::<E>();
app.world_mut()
.resource_mut::<StateScopedEvents<S>>()
.add_event::<E>(state.clone());
app.add_systems(OnExit(state), cleanup_state_scoped_event::<S>);
}
/// Extension trait for [`App`] adding methods for registering state scoped events.
pub trait StateScopedEventsAppExt {
/// Adds an [`Event`] that is automatically cleaned up when leaving the specified `state`.
///
/// Note that event cleanup is ordered ambiguously relative to [`DespawnOnEnterState`](crate::prelude::DespawnOnEnterState)
/// and [`DespawnOnExitState`](crate::prelude::DespawnOnExitState) entity
/// cleanup and the [`OnExit`] schedule for the target state. All of these (state scoped
/// entities and events cleanup, and `OnExit`) occur within schedule [`StateTransition`](crate::prelude::StateTransition)
/// and system set `StateTransitionSystems::ExitSchedules`.
fn add_state_scoped_event<E: Event>(&mut self, state: impl States) -> &mut Self;
}
impl StateScopedEventsAppExt for App {
fn add_state_scoped_event<E: Event>(&mut self, state: impl States) -> &mut Self {
add_state_scoped_event_impl(self.main_mut(), PhantomData::<E>, state);
self
}
}
impl StateScopedEventsAppExt for SubApp {
fn add_state_scoped_event<E: Event>(&mut self, state: impl States) -> &mut Self {
add_state_scoped_event_impl(self, PhantomData::<E>, state);
self
}
}