use bevy::prelude::*;
use crate::actions::{Action, ScoredAction};
use crate::action_state::ActionState;
use crate::types;
use crate::events;
#[derive(Component, Debug)]
pub struct ActionTracker(pub ScoredAction);
#[derive(Component, Debug)]
pub struct ActionTrackerOwningAI {
pub owner_ai: crate::types::EntityIdentifier
}
#[derive(Component, Debug)]
pub struct ActionTrackerState(pub ActionState);
impl ActionTrackerState {
pub fn ready() -> Self {
Self(ActionState::Ready)
}
pub fn queued() -> Self {
Self(ActionState::Queued)
}
pub fn get_state(&self) -> &ActionState {
&self.0
}
pub fn set_state(&mut self, state: ActionState) -> &mut Self {
self.0 = state;
self
}
}
#[derive(Debug)]
pub enum TimeInstantActionTracker {
Virtual(core::time::Duration),
Real(core::time::Duration),
VirtualAndReal((core::time::Duration, core::time::Duration)),
}
#[derive(Component, Debug)]
pub struct ActionTrackerCreationTimer {
pub creation_time: TimeInstantActionTracker,
}
#[derive(Component, Debug, Default)]
pub struct ActionTrackerRuntimeTimer {
pub start_time: Option<TimeInstantActionTracker>,
pub end_time: Option<TimeInstantActionTracker>,
}
#[derive(Component, Debug, Default)]
pub struct ActionTrackerTickTimer {
pub last_tick_time: Option<TimeInstantActionTracker>,
}
#[derive(Component)]
pub struct ActionTrackerTicks;
#[derive(Debug, Clone)]
pub struct ActionTrackerSpawnConfig {
track_owner_ai: bool,
use_ticker: bool,
use_create_timer: bool,
use_runtime_timer: bool,
use_tick_timer: bool,
}
impl ActionTrackerSpawnConfig {
pub fn builder() -> ActionTrackerSpawnConfigBuilder {
ActionTrackerSpawnConfigBuilder::default()
}
}
#[derive(Default, Debug, Clone)]
pub struct ActionTrackerSpawnConfigBuilder {
track_owner_ai: Option<bool>,
use_ticker: Option<bool>,
use_timers: Option<bool>,
use_create_timer: Option<bool>,
use_runtime_timer: Option<bool>,
use_tick_timer: Option<bool>,
}
impl ActionTrackerSpawnConfigBuilder {
pub fn build(self) -> ActionTrackerSpawnConfig {
let track_owner_ai = self.track_owner_ai.unwrap_or(true);
let use_ticker = self.use_ticker.unwrap_or(false);
let use_timers = self.use_timers.unwrap_or(false);
let use_create_timer = self.use_create_timer.unwrap_or(use_timers);
let use_runtime_timer = self.use_runtime_timer.unwrap_or(use_timers);
let use_tick_timer = self.use_tick_timer.unwrap_or(use_ticker && use_timers);
ActionTrackerSpawnConfig {
track_owner_ai,
use_ticker,
use_create_timer,
use_runtime_timer,
use_tick_timer,
}
}
pub fn new() -> Self {
self::default()
}
pub fn set_track_owner_ai(mut self, val: bool) -> Self {
self.track_owner_ai = Some(val); self
}
pub fn set_use_ticker(mut self, val: bool) -> Self {
self.use_ticker = Some(val); self
}
pub fn set_use_timers(mut self, val: bool) -> Self {
self.use_timers = Some(val); self
}
pub fn set_use_create_timer(mut self, val: bool) -> Self {
self.use_create_timer = Some(val); self
}
pub fn set_use_runtime_timer(mut self, val: bool) -> Self {
self.use_runtime_timer = Some(val); self
}
pub fn set_use_tick_timer(mut self, val: bool) -> Self {
self.use_tick_timer = Some(val); self
}
pub fn from_reference_config(config: &ActionTrackerSpawnConfig) -> Self {
Self {
track_owner_ai: Some(config.track_owner_ai),
use_ticker: Some(config.use_ticker),
use_create_timer: Some(config.use_create_timer),
use_runtime_timer: Some(config.use_runtime_timer),
use_tick_timer: Some(config.use_tick_timer),
..Default::default()
}
}
}
impl Into<ActionTrackerSpawnConfig> for ActionTrackerSpawnConfigBuilder {
fn into(self) -> ActionTrackerSpawnConfig {
self.build()
}
}
impl From<&ActionTrackerSpawnConfig> for ActionTrackerSpawnConfigBuilder {
fn from(value: &ActionTrackerSpawnConfig) -> Self {
Self::from_reference_config(value)
}
}
#[derive(EntityEvent)]
pub struct ActionTrackerSpawnRequested {
pub entity: types::AiEntity,
pub action: ScoredAction,
pub tracker_config: Option<ActionTrackerSpawnConfig>,
}
impl ActionTrackerSpawnRequested {
pub fn new(entity: Entity, action: ScoredAction, config: Option<ActionTrackerSpawnConfig>) -> Self {
#[cfg(feature = "logging")]
bevy::log::debug!(
"ActionTrackerSpawnRequested::new(): Creating a new ActionTrackerSpawnRequested event for Entity {:?} w/ Action {:?}",
entity, action
);
Self {
entity: entity,
action: action,
tracker_config: config,
}
}
pub fn with_library_defaults(entity: Entity, action: ScoredAction) -> Self {
Self::new(entity, action, None)
}
pub fn with_config(entity: Entity, action: ScoredAction, config: ActionTrackerSpawnConfig) -> Self {
Self::new(entity, action, Some(config))
}
pub fn with_config_builder(
entity: Entity,
action: ScoredAction,
builder: &mut dyn FnMut(ActionTrackerSpawnConfigBuilder) -> Option<ActionTrackerSpawnConfig>,
) -> Self {
Self::new(
entity,
action,
builder(ActionTrackerSpawnConfig::builder())
)
}
}
#[derive(EntityEvent)]
pub struct ActionTrackerSpawnedForTargetAI {
pub entity: Entity,
pub action_tracker: Entity,
}
pub fn actiontracker_triggered_spawner(
trigger: On<ActionTrackerSpawnRequested>,
mut commands: Commands,
game_timer: Res<Time>,
real_timer: Res<Time<Real>>,
) {
let event = trigger.event();
let owner_ai = event.entity;
match commands.get_entity(owner_ai) {
Err(_err) => {
#[cfg(feature = "logging")]
bevy::log::warn!(
"Attempted to spawn an ActionTracker for an AI Entity ({:?}) that no longer exists - {:?}",
owner_ai, _err
)
}
Ok(mut ai_cmds) => {
ai_cmds.insert((
ActionTracker(event.action.clone()),
ActionTrackerState::ready(),
));
let spawn_config = match &event.tracker_config {
Some(config) => config,
None => &ActionTrackerSpawnConfig::builder().build()
};
if spawn_config.track_owner_ai {
ai_cmds.insert(ActionTrackerOwningAI {
owner_ai: event.entity.into()
});
}
if spawn_config.use_ticker {
ai_cmds.insert(ActionTrackerTicks);
}
if spawn_config.use_create_timer {
let virtual_spawn_time = game_timer.elapsed();
let real_spawn_time = real_timer.elapsed();
ai_cmds.insert(ActionTrackerCreationTimer {
creation_time: TimeInstantActionTracker::VirtualAndReal((virtual_spawn_time, real_spawn_time))
});
}
if spawn_config.use_runtime_timer {
ai_cmds.insert(ActionTrackerRuntimeTimer::default());
}
if spawn_config.use_tick_timer {
ai_cmds.insert(ActionTrackerTickTimer::default());
}
ai_cmds.trigger(|atracker| ActionTrackerSpawnedForTargetAI {
entity: owner_ai,
action_tracker: atracker,
});
}
}
}
#[derive(EntityEvent)]
pub struct ActionTrackerDespawnRequested {
entity: Entity,
}
pub fn actiontracker_triggered_despawner(
event: On<ActionTrackerDespawnRequested>,
mut commands: Commands,
) {
let _ = commands.get_entity(event.entity).and_then(|mut e| Ok(e.despawn()));
}
pub fn actiontracker_done_cleanup_system(
query: Query<(Entity, &ActionTracker, &ActionTrackerState)>,
mut commands: Commands,
) {
for (entity, _tracker, state) in query.iter() {
let is_done = match state.0 {
ActionState::Succeeded => true,
ActionState::Failed => true,
ActionState::Cancelled => true,
_ => false,
};
#[cfg(feature = "logging")]
bevy::log::debug!("ActionTrackerCleanup: {:?} is in state {:?} (done: {:?}).", _tracker.0.action.name, state.0, is_done);
if is_done {
#[cfg(feature = "logging")]
bevy::log::info!(
"ActionTrackerCleanup: Action {:?} of AI {:?} finished, cleaning up the Tracker",
_tracker.0.action.name, entity
);
commands.trigger(ActionTrackerDespawnRequested {
entity: entity
});
}
}
}
#[derive(Default, Resource)]
pub struct UserDefaultActionTrackerSpawnConfig {
pub config: Option<ActionTrackerSpawnConfig>
}
impl UserDefaultActionTrackerSpawnConfig {
pub fn with_config_builder<F: FnOnce(ActionTrackerSpawnConfigBuilder) -> ActionTrackerSpawnConfigBuilder>(
&mut self,
builder: F
) -> &mut Self {
let config_builder = match &self.config {
None => ActionTrackerSpawnConfigBuilder::new(),
Some(preexisting) => ActionTrackerSpawnConfigBuilder::from_reference_config(preexisting)
};
let configured = builder(config_builder);
let built = configured.build();
self.config = Some(built);
self
}
}
pub fn create_tracker_for_picked_action(
trigger: On<crate::events::AiActionPicked>,
mut commands: Commands,
user_default_config_resource: Res<UserDefaultActionTrackerSpawnConfig>,
) {
let event = trigger.event();
let action = Action {
name: event.action_name.clone(),
action_key: event.action_key.clone(),
context: event.action_context.clone(),
};
let scored_action = ScoredAction {
action: action,
score: event.action_score,
};
let user_config = user_default_config_resource.config.clone();
commands.trigger(
ActionTrackerSpawnRequested::new(
event.entity,
scored_action,
user_config,
)
);
}
fn tick_based_action_tracker_handler(
mut query: Query<(
Entity,
&ActionTracker,
Option<&mut ActionTrackerState>,
Option<&mut ActionTrackerTickTimer>
), With<ActionTrackerTicks>>,
mut dispatch_writer: MessageWriter<events::AiActionDispatchToUserCode>,
game_timer: Res<Time>,
real_timer: Res<Time<Real>>,
) {
#[cfg(feature = "logging")]
bevy::log::debug!(
"tick_based_action_tracker_handler - Running...",
);
for (ai, tracker, maybe_state, tick_timer) in query.iter_mut() {
let should_process = maybe_state.as_ref().map(|state| state.0.should_process()).unwrap_or(true);
if !should_process {
#[cfg(feature = "logging")]
bevy::log::debug!(
"tick_based_action_tracker_handler - AI {:?}: Skipping processing for Action(Tracker) {:?} - {:?}",
ai, tracker.0.action.name, maybe_state
);
continue;
}
#[cfg(feature = "logging")]
bevy::log::debug!(
"tick_based_action_tracker_handler: processing Action(Tracker) {:?} for {:?} - {:?}",
tracker.0.action.name, ai, maybe_state
);
if let Some(mut tick_timer_included) = tick_timer {
let current_time_game = game_timer.elapsed();
let current_time_real = real_timer.elapsed();
let new_value = TimeInstantActionTracker::VirtualAndReal((
current_time_game, current_time_real
));
tick_timer_included.last_tick_time = Some(new_value);
}
let message = events::AiActionDispatchToUserCode::new(
ai,
tracker.0.action.action_key.to_owned(),
tracker.0.action.name.to_owned(),
tracker.0.action.context,
tracker.0.score
);
dispatch_writer.write(message);
}
}
pub struct TickBasedActionTrackerPlugin;
impl Plugin for TickBasedActionTrackerPlugin {
fn build(&self, app: &mut App) {
app
.add_systems(
FixedPostUpdate,
tick_based_action_tracker_handler
)
;
}
}