Skip to main content

cranium_core/
action_runtime.rs

1/* 
2This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. 
3If a copy of the MPL was not distributed with this file, 
4You can obtain one at https://mozilla.org/MPL/2.0/. 
5*/
6//! The lifecycle of an AI Action - how it starts, runs, and finishes.
7
8use bevy::prelude::*;
9
10use crate::actions::{Action, ScoredAction};
11use crate::action_state::ActionState;
12use crate::types;
13use crate::events;
14
15
16// Action Execution
17/// A Component that makes this Entity track an AI Action, i.e. store and expose 
18/// data about some Action's execution (e.g. 'Is this still running?' or 'How long ago did it start?') 
19/// across (potentially) multiple frames and/or serde operations.
20/// 
21/// This is the 'master'/'root' marker for tracking Actions - all code within this library will assume 
22/// anything without this Component does not track anything, and anything that has any of the extension
23/// Component also has this Component.
24#[derive(Component, Debug)]
25pub struct ActionTracker(pub ScoredAction);
26
27
28/// An 'extension' Component for ActionTracker Bundles.
29/// 
30/// Adds tracking of the AI Entity that 'owns' the tracked Action. 
31/// 
32/// Bear in mind that Bevy Entities are just Very Fancy IDs; the 
33/// Entity tracked by this Component may no longer be valid - you 
34/// should verify it yourself where necessary.
35/// 
36/// This is primarily intended for tying back Actions to AIs performing them 
37/// and for cancelling any Actions without an associated AI owner.
38#[derive(Component, Debug)]
39pub struct ActionTrackerOwningAI {
40    pub owner_ai: crate::types::EntityIdentifier
41}
42
43
44/// An 'extension' Component for ActionTracker Bundles.
45/// 
46/// Adds Action state tracking to the ActionTracker.
47/// In this context, state is roughly the 'lifecycle' of an Action: 
48/// Pending -> Running -> Terminal (Successful/Failed/Cancelled/etc.).
49/// 
50/// This is a very handy piece of information. 
51/// You can query it for your Actions to do setup work for Pending or 
52/// skip processing for Terminal states, in your UI code to visualize
53/// the state of the current behavior or provide a 'Cancel Action' button...
54/// You might also (correctly) guess it powers some of the Action lifecycle Events.
55#[derive(Component, Debug)]
56pub struct ActionTrackerState(pub ActionState);
57
58impl ActionTrackerState {
59    pub fn ready() -> Self {
60        Self(ActionState::Ready)
61    }
62
63    pub fn queued() -> Self {
64        Self(ActionState::Queued)
65    }
66
67    pub fn get_state(&self) -> &ActionState {
68        &self.0
69    }
70
71    pub fn set_state(&mut self, state: ActionState) -> &mut Self {
72        self.0 = state;
73        self
74    }
75}
76
77/// Helper; wraps how we store time for tracking Action runtime timining.
78#[derive(Debug)]
79pub enum TimeInstantActionTracker {
80    Virtual(core::time::Duration),
81    Real(core::time::Duration),
82    VirtualAndReal((core::time::Duration, core::time::Duration)),
83}
84
85/// An 'extension' Component for ActionTracker Bundles.
86/// Adds Action time metadata tracking to the ActionTracker for creation time.
87/// 
88/// This is separate and different from the START time. 
89/// An Action 'Start' is when the execution begins, 'Created' is when the task gets planned.
90/// 
91/// The primary use-case for this is timeouts and cleanup, especially when combined with other 
92/// ActionTracker timers - e.g. if an Action was queued up a year ago and it still hasn't finished, 
93/// it is most likely a zombie job that should be terminated. 
94/// 
95/// However, as with all of these, use it as you wish, it's a building block.
96#[derive(Component, Debug)]
97pub struct ActionTrackerCreationTimer {
98    pub creation_time: TimeInstantActionTracker,
99}
100
101/// An 'extension' Component for ActionTracker Bundles. 
102/// Adds Action time metadata tracking to the ActionTracker 
103/// for Start and End times of the Action's *execution*.
104/// 
105/// Note that both of these are Option<T>! 
106/// 
107/// Most obviously, an End time of None means the Action is still pending or running. 
108/// You can tell which one it is by the Start time - None means it's pending, i.e. did not start yet.
109/// 
110/// The primary purpose of this component is for timeouts to kill tasks that
111/// got stuck in limbo or did not get cleaned up properly for some reason and the like, 
112/// but will almost certainly be handy for UIs and/or Action logic itself as well.
113/// 
114/// However, as with all of these, use it as you wish, it's a building block.
115#[derive(Component, Debug, Default)]
116pub struct ActionTrackerRuntimeTimer {
117    pub start_time: Option<TimeInstantActionTracker>,
118    pub end_time: Option<TimeInstantActionTracker>,
119}
120
121/// An 'extension' Component for ActionTracker Bundles. 
122/// Adds Action time metadata tracking to the ActionTracker 
123/// for tracking when the ActionTracker was last 'ticked' 
124/// (processed by a system that implements Actually Doing the Action).
125/// 
126/// The timer value is Optioned; None indicates the ActionTracker has never been ticked.
127/// 
128/// This Component makes most sense paired with the ActionTrackerTicks Component 
129/// which indicates that this ActionTracker CAN ever be ticked at all.
130/// 
131/// This is not a hard dependency though. In some cases, it might be useful to add and remove 
132/// the 'ticking' to an Action dynamically (e.g. as a LOD optimization), so this link is NOT 
133/// enforced by the library on purpose.
134/// 
135/// You are also free to (ab)use this timer by manually updating it in your Observers whenever 
136/// you do anything with the tracked Action in a more event-driven Action implementation as well.
137/// 
138/// The first purpose of this timer is to detect Action garbage - trackers that 
139/// had been created, but are not doing any meaningful work to progress to completion.
140/// 
141/// The second purpose of this timer is to provide a nice way to get time deltas for 
142/// 'sparsely' ticked Actions, e.g. event-driven or when reloaded from a savefile.
143/// 
144/// However, as with all of these, use it as you wish, it's a building block.
145#[derive(Component, Debug, Default)]
146pub struct ActionTrackerTickTimer {
147    pub last_tick_time: Option<TimeInstantActionTracker>,
148}
149
150
151/// An 'extension' Component for ActionTracker Bundles.
152/// 
153/// Indicates that this tracker should be processed by a System that   
154/// runs some sort of 'tick' logic for the associated Action. 
155/// 
156/// For example, a MoveTo<pos> Action might move a unit by one grid square, 
157/// or one turn's worth of moves, or whatever.
158/// 
159/// This may be implemented as a function call, a signal emit, both, or whatever else;
160/// it's entirely your call as a library user to write your Systems how you want 'em.
161/// 
162/// This Component is entirely optional - if you don't use it, you can just 
163/// catch Events for Action start/end and handle the execution asynchronously 
164/// in your game code's 'native' systems (e.g. just set a destination for your 
165/// Movement system in an Observer and let it figure out the specifics itself).
166#[derive(Component)]
167pub struct ActionTrackerTicks;
168
169
170#[derive(Debug, Clone)]
171pub struct ActionTrackerSpawnConfig {
172    track_owner_ai: bool, 
173    use_ticker: bool,
174    use_create_timer: bool,
175    use_runtime_timer: bool,
176    use_tick_timer: bool,
177}
178
179impl ActionTrackerSpawnConfig {
180    pub fn builder() -> ActionTrackerSpawnConfigBuilder {
181        ActionTrackerSpawnConfigBuilder::default()
182    }
183}
184
185/// Builder pattern for ActionTrackerSpawnConfig
186#[derive(Default, Debug, Clone)]
187pub struct ActionTrackerSpawnConfigBuilder {
188    track_owner_ai: Option<bool>, 
189    use_ticker: Option<bool>,
190    use_timers: Option<bool>,
191    use_create_timer: Option<bool>,
192    use_runtime_timer: Option<bool>,
193    use_tick_timer: Option<bool>,
194}
195
196impl ActionTrackerSpawnConfigBuilder {
197    pub fn build(self) -> ActionTrackerSpawnConfig {
198        let track_owner_ai = self.track_owner_ai.unwrap_or(true);
199        let use_ticker = self.use_ticker.unwrap_or(false);
200        let use_timers = self.use_timers.unwrap_or(false);
201        let use_create_timer = self.use_create_timer.unwrap_or(use_timers);
202        let use_runtime_timer = self.use_runtime_timer.unwrap_or(use_timers);
203        let use_tick_timer = self.use_tick_timer.unwrap_or(use_ticker && use_timers);
204
205        ActionTrackerSpawnConfig {
206            track_owner_ai,
207            use_ticker,
208            use_create_timer,
209            use_runtime_timer,
210            use_tick_timer,
211        }
212    }
213
214    pub fn new() -> Self {
215        self::default()
216    }
217
218    pub fn set_track_owner_ai(mut self, val: bool) -> Self {
219        self.track_owner_ai = Some(val); self
220    }
221
222    pub fn set_use_ticker(mut self, val: bool) -> Self {
223        self.use_ticker = Some(val); self
224    }
225
226    pub fn set_use_timers(mut self, val: bool) -> Self {
227        self.use_timers = Some(val); self
228    }
229
230    pub fn set_use_create_timer(mut self, val: bool) -> Self {
231        self.use_create_timer = Some(val); self
232    }
233
234    pub fn set_use_runtime_timer(mut self, val: bool) -> Self {
235        self.use_runtime_timer = Some(val); self
236    }
237
238    pub fn set_use_tick_timer(mut self, val: bool) -> Self {
239        self.use_tick_timer = Some(val); self
240    }
241
242    /// Creates a new builder using an existing config as a starting point.
243    /// This means the values are preconfigured to match the existing config, 
244    /// but you can modify them freely before turning this into a new config.
245    pub fn from_reference_config(config: &ActionTrackerSpawnConfig) -> Self {
246        Self {
247            track_owner_ai: Some(config.track_owner_ai),
248            use_ticker: Some(config.use_ticker),
249            use_create_timer: Some(config.use_create_timer),
250            use_runtime_timer: Some(config.use_runtime_timer),
251            use_tick_timer: Some(config.use_tick_timer),
252            ..Default::default()
253        }
254    }
255}
256
257
258impl Into<ActionTrackerSpawnConfig> for ActionTrackerSpawnConfigBuilder {
259    fn into(self) -> ActionTrackerSpawnConfig {
260        self.build()
261    }
262}
263
264impl From<&ActionTrackerSpawnConfig> for ActionTrackerSpawnConfigBuilder {
265    fn from(value: &ActionTrackerSpawnConfig) -> Self {
266        Self::from_reference_config(value)
267    }
268}
269
270/// An Event representing some system asking the library to track an Action.
271/// You could DIY it, but using this Event should cover typical usecases for ya.
272#[derive(EntityEvent)]
273pub struct ActionTrackerSpawnRequested {
274    /// NOTE: The entity here is intended to be the AIController.
275    ///       EntityEvent API sadly doesn't let us rename that for clarity.
276    pub entity: types::AiEntity, 
277    pub action: ScoredAction, 
278    pub tracker_config: Option<ActionTrackerSpawnConfig>,
279}
280
281impl ActionTrackerSpawnRequested {
282    /// Create a new ActionTracker spawn request.
283    pub fn new(entity: Entity, action: ScoredAction, config: Option<ActionTrackerSpawnConfig>) -> Self {
284        #[cfg(feature = "logging")]
285        bevy::log::debug!(
286            "ActionTrackerSpawnRequested::new(): Creating a new ActionTrackerSpawnRequested event for Entity {:?} w/ Action {:?}", 
287            entity, action
288        );
289
290        Self {
291            entity: entity, 
292            action: action,
293            tracker_config: config,
294        }
295    }
296
297    /// Create a new ActionTracker spawn request, with whatever defaults the library picked for you. 
298    pub fn with_library_defaults(entity: Entity, action: ScoredAction) -> Self {
299        Self::new(entity, action, None)
300    }
301
302    /// Create a new ActionTracker spawn request with a specified config.
303    pub fn with_config(entity: Entity, action: ScoredAction, config: ActionTrackerSpawnConfig) -> Self {
304        Self::new(entity, action, Some(config))
305    }
306
307    /// Create a new ActionTracker spawn request, allowing the config to be built 
308    /// by evaluating a specified callback on the ActionTrackerSpawnConfigBuilder.
309    /// 
310    /// Kind of like the `Option::or_else()` API and the like, lazy evaluation.
311    /// 
312    /// Mainly a syntax sugar API so you don't have to create a Builder yourself.
313    pub fn with_config_builder(
314        entity: Entity, 
315        action: ScoredAction, 
316        builder: &mut dyn FnMut(ActionTrackerSpawnConfigBuilder) -> Option<ActionTrackerSpawnConfig>,
317    ) -> Self {
318        Self::new(
319            entity, 
320            action, 
321            builder(ActionTrackerSpawnConfig::builder())
322        )
323    }
324}
325
326/// An Event notifying Observers that a new ActionTracker has been created for an AI.
327#[derive(EntityEvent)]
328pub struct ActionTrackerSpawnedForTargetAI {
329    /// This is the owning AI Entity
330    pub entity: Entity,
331
332    /// This is the created ActionTracker Entity
333    pub action_tracker: Entity,
334}
335
336/// Event handler for spawning ActionTrackers for Actions, 
337/// triggered by an ActionTrackerSpawnRequested Event.
338pub fn actiontracker_triggered_spawner(
339    trigger: On<ActionTrackerSpawnRequested>,
340    mut commands: Commands,
341    game_timer: Res<Time>,
342    real_timer: Res<Time<Real>>,
343) {
344    let event = trigger.event();
345    let owner_ai = event.entity;
346
347    match commands.get_entity(owner_ai) {
348        Err(_err) => {
349            #[cfg(feature = "logging")]
350            bevy::log::warn!(
351                "Attempted to spawn an ActionTracker for an AI Entity ({:?}) that no longer exists - {:?}",
352                owner_ai, _err
353            )
354        }
355
356        Ok(mut ai_cmds) => {
357            ai_cmds.insert((
358                ActionTracker(event.action.clone()),
359                ActionTrackerState::ready(),
360            ));
361
362            let spawn_config = match &event.tracker_config {
363                Some(config) => config,
364                None => &ActionTrackerSpawnConfig::builder().build()
365            };
366
367            if spawn_config.track_owner_ai {
368                ai_cmds.insert(ActionTrackerOwningAI {
369                    owner_ai: event.entity.into()
370                });
371            }
372
373            if spawn_config.use_ticker {
374                // Add ticking to this ActionTracker.
375                // The Component for this is just a marker, pretty trivial.
376                ai_cmds.insert(ActionTrackerTicks);
377            }
378
379            // Add timing components.
380            // 
381            // For now we'll use unwrapped elapsed Durations for this as a standard.
382            // Real time in particular may span DAYS for reloads, so wrapping it may cause serious artifacts.
383            // Duration is u64-based; you may get issues if you leave your game running for 585 billion years.
384            if spawn_config.use_create_timer {
385                let virtual_spawn_time = game_timer.elapsed();
386                let real_spawn_time = real_timer.elapsed();
387
388                ai_cmds.insert(ActionTrackerCreationTimer {
389                    creation_time: TimeInstantActionTracker::VirtualAndReal((virtual_spawn_time, real_spawn_time))
390                });
391            }
392
393            if spawn_config.use_runtime_timer {
394                // The Action hasn't started yet, so they will both be None for now.
395                ai_cmds.insert(ActionTrackerRuntimeTimer::default());
396            }
397
398            if spawn_config.use_tick_timer {
399                // The Action hasn't been ticked, so starts as None.
400                ai_cmds.insert(ActionTrackerTickTimer::default());
401            }
402
403            // Send a friendly PSA that we have created this Entity for downstream users to hook into.
404            ai_cmds.trigger(|atracker| ActionTrackerSpawnedForTargetAI { 
405                entity: owner_ai,
406                action_tracker: atracker,
407            });
408        }
409    }
410}
411
412
413/// An Event representing some system asking the library to stop tracking an Action.
414/// This will usually happen when the Action has reached some terminal state.
415/// You could DIY it, but using this Event should cover typical usecases for ya.
416#[derive(EntityEvent)]
417pub struct ActionTrackerDespawnRequested {
418    entity: Entity, 
419}
420
421/// A frankly pretty trivial callback that deletes ActionTrackers that were requested to be cleaned up.
422/// As each Tracker is its own unique Entity, this will clean up the whole bundle (including optional modules).
423/// 
424/// If you want to invoke callbacks on success/failure/etc., this should happen BEFORE this event is raised.
425pub fn actiontracker_triggered_despawner(
426    event: On<ActionTrackerDespawnRequested>,
427    mut commands: Commands,
428) {
429    let _ = commands.get_entity(event.entity).and_then(|mut e| Ok(e.despawn()));
430}
431
432pub fn actiontracker_done_cleanup_system(
433    query: Query<(Entity, &ActionTracker, &ActionTrackerState)>, 
434    mut commands: Commands, 
435) {
436    // #[cfg(feature = "logging")]
437    // bevy::log::debug!("Processing ActionTracker cleanup...");
438
439    for (entity, _tracker, state) in query.iter() {
440        let is_done = match state.0 {
441            ActionState::Succeeded => true,
442            ActionState::Failed => true,
443            ActionState::Cancelled => true,
444            _ => false,
445        };
446
447        #[cfg(feature = "logging")]
448        bevy::log::debug!("ActionTrackerCleanup: {:?} is in state {:?} (done: {:?}).", _tracker.0.action.name, state.0, is_done);
449
450        if is_done {
451            #[cfg(feature = "logging")]
452            bevy::log::info!(
453                "ActionTrackerCleanup: Action {:?} of AI {:?} finished, cleaning up the Tracker", 
454                _tracker.0.action.name, entity
455            );
456            commands.trigger(ActionTrackerDespawnRequested {
457                entity: entity
458            });
459        }
460    }
461}
462
463
464/// A resource that allows you to specify the global defaults for all ActionTrackers.
465/// 
466/// If you have a 'house style' for your AI Action implementation, this can save you 
467/// a lot of boilerplate.
468/// 
469/// Note that you can still always override this config for individual exceptional cases.
470/// 
471/// The provided [`with_config_builder()`] method allows you to conveniently customize the 
472/// resource by passing a closure that can mutate the ActionTrackerSpawnConfigBuilder.
473#[derive(Default, Resource)]
474pub struct UserDefaultActionTrackerSpawnConfig {
475    pub config: Option<ActionTrackerSpawnConfig>
476}
477
478impl UserDefaultActionTrackerSpawnConfig {
479    /// Convenience function for setting up your user default config.
480    /// 
481    /// Creates a new Config Builder seeded with current config values (or defaults, if none set up), 
482    /// then passes it over to the provided FnOnce closure for you to mutate away as you pleas before 
483    /// returning the configured result. 
484    /// 
485    /// The builder then builds and stores the configuration for you.
486    pub fn with_config_builder<F: FnOnce(ActionTrackerSpawnConfigBuilder) -> ActionTrackerSpawnConfigBuilder>(
487        &mut self, 
488        builder: F
489    ) -> &mut Self {
490        let config_builder = match &self.config {
491            None => ActionTrackerSpawnConfigBuilder::new(),
492            Some(preexisting) => ActionTrackerSpawnConfigBuilder::from_reference_config(preexisting) 
493        };
494        let configured = builder(config_builder);
495        let built = configured.build();
496        self.config = Some(built);
497        self
498    }
499}
500
501/// A batteries-included solution for creating ActionTrackers for your Actions.
502/// 
503/// Event-driven; responds to AiActionPicked events
504pub fn create_tracker_for_picked_action(
505    trigger: On<crate::events::AiActionPicked>,
506    mut commands: Commands,
507    user_default_config_resource: Res<UserDefaultActionTrackerSpawnConfig>,
508) {
509    let event = trigger.event();
510
511    let action = Action {
512        name: event.action_name.clone(),
513        action_key: event.action_key.clone(),
514        context: event.action_context.clone(),
515    };
516
517    let scored_action = ScoredAction {
518        action: action,
519        score: event.action_score,
520    };
521
522    let user_config = user_default_config_resource.config.clone();
523
524    commands.trigger(
525        ActionTrackerSpawnRequested::new(
526            event.entity,
527            scored_action, 
528            user_config,
529        )
530    );
531}
532
533/// A System that processes and updates `ActionTrackers` to trigger `Actions`.
534/// 
535/// This particular implementation uses tick-based [`Action`] processing.
536fn tick_based_action_tracker_handler(
537    mut query: Query<(
538        Entity,
539        &ActionTracker, 
540        Option<&mut ActionTrackerState>, 
541        Option<&mut ActionTrackerTickTimer>
542    ), With<ActionTrackerTicks>>,
543    mut dispatch_writer: MessageWriter<events::AiActionDispatchToUserCode>,
544    game_timer: Res<Time>,
545    real_timer: Res<Time<Real>>,
546) {
547    #[cfg(feature = "logging")]
548    bevy::log::debug!(
549        "tick_based_action_tracker_handler - Running...", 
550    );
551
552    for (ai, tracker, maybe_state, tick_timer) in query.iter_mut() {
553        let should_process = maybe_state.as_ref().map(|state| state.0.should_process()).unwrap_or(true);
554        
555        if !should_process {
556            #[cfg(feature = "logging")]
557            bevy::log::debug!(
558                "tick_based_action_tracker_handler - AI {:?}: Skipping processing for Action(Tracker) {:?} - {:?}", 
559                ai, tracker.0.action.name, maybe_state
560            );
561            continue;
562        }
563
564        #[cfg(feature = "logging")]
565        bevy::log::debug!(
566            "tick_based_action_tracker_handler: processing Action(Tracker) {:?} for {:?} - {:?}", 
567            tracker.0.action.name, ai, maybe_state
568        );
569
570        if let Some(mut tick_timer_included) = tick_timer {
571            let current_time_game = game_timer.elapsed();
572            let current_time_real = real_timer.elapsed();
573
574            let new_value = TimeInstantActionTracker::VirtualAndReal((
575                current_time_game, current_time_real
576            ));
577
578            tick_timer_included.last_tick_time = Some(new_value);
579        }
580
581        let message = events::AiActionDispatchToUserCode::new(
582            ai, 
583            tracker.0.action.action_key.to_owned(), 
584            tracker.0.action.name.to_owned(), 
585            tracker.0.action.context, 
586            tracker.0.score
587        );
588
589        dispatch_writer.write(message);
590    }
591}
592
593/// Sets up the application to use 'ticker'-style Actions backed by ActionTrackers. 
594/// 
595/// The application will process all running ActionTrackers with 'ticked' Actions 
596/// and trigger whichever ActionHandler function you have registered for a registry 
597/// key matching the processed Action's own key/ 
598/// 
599/// These in turn should trigger your own Events you wired your Action implementations 
600/// to observe, or some equivalent alternative dispatch implementation method like Messages.
601/// 
602/// Any picked Actions whose key cannot be resolved to a registered ActionHandler 
603/// mapping will be skipped and will not process, nor will any Action in a 
604/// terminal state (i.e. - success, failure, cancelled, etc.)
605/// 
606/// This is a separate plugin, as you may or may not want to use this particular 
607/// implementation style for your own applications.
608pub struct TickBasedActionTrackerPlugin;
609
610impl Plugin for TickBasedActionTrackerPlugin {
611    fn build(&self, app: &mut App) {
612        app
613        .add_systems(
614            FixedPostUpdate, 
615            tick_based_action_tracker_handler
616        )
617        ;
618    }
619}
620
621
622// #[cfg(test)]
623// mod tests {
624//     #[test]
625//     fn test_run_action() {}
626// }