moonshine_behavior/events.rs
1use std::marker::PhantomData;
2
3use bevy_app::prelude::*;
4use bevy_ecs::prelude::*;
5
6use moonshine_kind::prelude::*;
7
8use crate::transition::TransitionError;
9use crate::Behavior;
10
11pub struct BehaviorEventsPlugin<T: Behavior>(PhantomData<T>);
12
13impl<T: Behavior> Default for BehaviorEventsPlugin<T> {
14 fn default() -> Self {
15 Self(PhantomData)
16 }
17}
18
19impl<T: Behavior> Plugin for BehaviorEventsPlugin<T> {
20 fn build(&self, app: &mut App) {
21 app.add_event::<BehaviorEvent<T>>();
22 }
23}
24
25pub type BehaviorEvents<'w, 's, T> = EventReader<'w, 's, BehaviorEvent<T>>;
26pub type BehaviorEventsMut<'w, T> = EventWriter<'w, BehaviorEvent<T>>;
27
28/// An event sent during [`transition`](crate::transition::transition) to signal [`Behavior`] changes.
29///
30/// # Usage
31///
32/// Each successful transition results in either a [`Start`](BehaviorEvent::Start),
33/// [`Pause`](BehaviorEvent::Pause), [`Resume`](BehaviorEvent::Resume), or [`Stop`](BehaviorEvent::Stop) event.
34///
35/// Most events carry the [`Instance`](crate::Instance) and index of the associated behavior.
36///
37/// This index maybe used with a [`BehaviorRef`](crate::BehaviorRefItem) or [`BehaviorMut`](crate::BehaviorMutItem)
38/// to access a specific instance of the behavior.
39///
40/// The index can be used to distinguish between different states if:
41/// - More than one variation of the same state exists in the stack, or
42/// - Multiple transitions have ocurred since the last query.
43#[derive(Event, Debug, PartialEq)]
44pub enum BehaviorEvent<T: Behavior> {
45 /// Sent when a behavior is started.
46 Start {
47 /// The instance which is running the new behavior.
48 instance: Instance<T>,
49 /// The index of the new behavior.
50 index: usize,
51 },
52 /// Sent when a behavior is paused.
53 Pause {
54 /// The instance which paused this behavior.
55 instance: Instance<T>,
56 /// The index of the paused behavior.
57 index: usize,
58 },
59 /// Sent when a behavior is resumed.
60 Resume {
61 /// The instance which resumed this behavior.
62 instance: Instance<T>,
63 /// The index of the resumed behavior.
64 index: usize,
65 },
66 Stop {
67 /// The instance which stopped this behavior.
68 instance: Instance<T>,
69 /// The stopped behavior.
70 behavior: T,
71 },
72 /// Sent when a behavior transition fails.
73 Error {
74 /// The instance which failed to transition.
75 instance: Instance<T>,
76 /// Reason for the failure.
77 error: TransitionError<T>,
78 },
79}