use std::{
sync::Arc,
time::{Duration, Instant},
};
use bevy::prelude::*;
use crate::{
actions::{self, ActionBuilder, ActionBuilderWrapper, ActionState},
choices::{Choice, ChoiceBuilder},
pickers::Picker,
scorers::{Score, ScorerBuilder},
};
#[derive(Debug, Clone, Copy)]
pub struct Actor(pub Entity);
#[derive(Debug, Clone, Copy)]
pub(crate) struct ActionEnt(pub Entity);
#[derive(Debug, Clone, Copy)]
pub(crate) struct ScorerEnt(pub Entity);
#[derive(Debug)]
pub struct Thinker {
picker: Arc<dyn Picker>,
otherwise: Option<ActionBuilderWrapper>,
choices: Vec<Choice>,
current_action: Option<(ActionEnt, ActionBuilderWrapper)>,
}
impl Thinker {
pub fn build() -> ThinkerBuilder {
ThinkerBuilder::new()
}
}
#[derive(Debug, Default)]
pub struct ThinkerBuilder {
picker: Option<Arc<dyn Picker>>,
otherwise: Option<ActionBuilderWrapper>,
choices: Vec<ChoiceBuilder>,
}
impl ThinkerBuilder {
pub(crate) fn new() -> Self {
Self {
picker: None,
otherwise: None,
choices: Vec::new(),
}
}
pub fn picker(mut self, picker: impl Picker + 'static) -> Self {
self.picker = Some(Arc::new(picker));
self
}
pub fn when(
mut self,
scorer: impl ScorerBuilder + 'static,
action: impl ActionBuilder + 'static,
) -> Self {
self.choices
.push(ChoiceBuilder::new(Arc::new(scorer), Arc::new(action)));
self
}
pub fn otherwise(mut self, otherwise: impl ActionBuilder + 'static) -> Self {
self.otherwise = Some(ActionBuilderWrapper::new(Arc::new(otherwise)));
self
}
}
impl ActionBuilder for ThinkerBuilder {
fn build(&self, cmd: &mut Commands, action_ent: Entity, actor: Entity) {
let choices = self
.choices
.iter()
.map(|choice| choice.build(cmd, actor, action_ent))
.collect();
cmd.entity(action_ent)
.insert(Transform::default())
.insert(GlobalTransform::default())
.insert(Thinker {
picker: self
.picker
.clone()
.expect("ThinkerBuilder must have a Picker"),
choices,
otherwise: self.otherwise.clone(),
current_action: None,
})
.insert(ActiveThinker(false))
.insert(ActionState::Requested);
}
}
pub fn thinker_component_attach_system(
mut cmd: Commands,
q: Query<(Entity, &ThinkerBuilder), Without<HasThinker>>,
) {
for (entity, thinker_builder) in q.iter() {
let thinker = thinker_builder.attach(&mut cmd, entity);
cmd.entity(entity).insert(HasThinker(thinker));
}
}
pub fn thinker_component_detach_system(
mut cmd: Commands,
q: Query<(Entity, &HasThinker), Without<ThinkerBuilder>>,
) {
for (actor, HasThinker(thinker)) in q.iter() {
cmd.entity(*thinker).despawn_recursive();
cmd.entity(actor).remove::<HasThinker>();
}
}
pub fn actor_gone_cleanup(
mut cmd: Commands,
actors: Query<&ThinkerBuilder>,
q: Query<(Entity, &Actor)>,
) {
for (child, Actor(actor)) in q.iter() {
if actors.get(*actor).is_err() {
cmd.entity(child).despawn_recursive();
}
}
}
#[derive(Debug)]
pub struct HasThinker(Entity);
#[derive(Debug)]
pub struct ActiveThinker(bool);
pub struct ThinkerIterations {
index: usize,
max_duration: Duration,
}
impl ThinkerIterations {
pub fn new(max_duration: Duration) -> Self {
Self {
index: 0,
max_duration,
}
}
}
impl Default for ThinkerIterations {
fn default() -> Self {
Self::new(Duration::from_millis(10))
}
}
pub fn thinker_system(
mut cmd: Commands,
mut iterations: Local<ThinkerIterations>,
mut thinker_q: Query<(Entity, &Actor, &mut Thinker, &ActiveThinker)>,
scores: Query<&Score>,
mut action_states: Query<&mut actions::ActionState>,
) {
let start = Instant::now();
for (thinker_ent, Actor(actor), mut thinker, active_thinker) in
thinker_q.iter_mut().skip(iterations.index)
{
iterations.index += 1;
let thinker_state = action_states
.get_mut(thinker_ent)
.expect("Where is it?")
.clone();
match thinker_state {
ActionState::Init | ActionState::Success | ActionState::Failure => {
if let ActiveThinker(true) = active_thinker {
let mut act_state = action_states.get_mut(thinker_ent).expect("???");
*act_state = ActionState::Requested;
}
}
ActionState::Cancelled => {
if let Some(current) = &mut thinker.current_action {
let state = action_states.get_mut(current.0.0).expect("Couldn't find a component corresponding to the current action. This is definitely a bug.").clone();
match state {
ActionState::Success | ActionState::Failure => {
let mut act_state = action_states.get_mut(thinker_ent).expect("???");
*act_state = state.clone();
let mut state = action_states.get_mut(current.0.0).expect("Couldn't find a component corresponding to the current action. This is definitely a bug.");
*state = ActionState::Init;
thinker.current_action = None;
}
_ => {
let mut state = action_states.get_mut(current.0.0).expect("Couldn't find a component corresponding to the current action. This is definitely a bug.");
*state = ActionState::Cancelled;
}
}
}
}
ActionState::Requested | ActionState::Executing => {
if let Some(choice) = thinker.picker.pick(&thinker.choices, &scores) {
exec_picked_action(
&mut cmd,
thinker_ent,
*actor,
&mut thinker,
&choice.action,
&mut action_states,
);
} else if let Some(default_action_ent) = &thinker.otherwise {
let default_action_ent = default_action_ent.clone();
exec_picked_action(
&mut cmd,
thinker_ent,
*actor,
&mut thinker,
&default_action_ent,
&mut action_states,
);
} else if let Some(current) = &mut thinker.current_action {
let mut state = action_states.get_mut(current.0.0).expect("Couldn't find a component corresponding to the current action. This is definitely a bug.");
match *state {
actions::ActionState::Init
| actions::ActionState::Success
| actions::ActionState::Failure => {
cmd.entity(current.0 .0).despawn_recursive();
thinker.current_action = None;
}
_ => {
*state = ActionState::Cancelled;
}
}
}
}
}
if iterations.index % 500 == 0 && start.elapsed() > iterations.max_duration {
return;
}
}
iterations.index = 0;
}
fn exec_picked_action(
cmd: &mut Commands,
thinker_ent: Entity,
actor: Entity,
thinker: &mut Mut<Thinker>,
picked_action: &ActionBuilderWrapper,
states: &mut Query<&mut ActionState>,
) {
if let Some((action_ent, ActionBuilderWrapper(current_id, _))) = &mut thinker.current_action {
if *current_id != picked_action.0 {
let mut curr_action_state = states.get_mut(action_ent.0).expect("Couldn't find a component corresponding to the current action. This is definitely a bug.");
match *curr_action_state {
ActionState::Executing | ActionState::Requested => {
*curr_action_state = ActionState::Cancelled;
let mut thinker_state = states.get_mut(thinker_ent).expect("Couldn't find a component corresponding to the current action. This is definitely a bug.");
*thinker_state = ActionState::Cancelled;
}
ActionState::Init | ActionState::Success | ActionState::Failure => {
let old_state = curr_action_state.clone();
cmd.entity(action_ent.0).despawn_recursive();
thinker.current_action = Some((
ActionEnt(picked_action.1.attach(cmd, actor)),
picked_action.clone(),
));
let mut thinker_state = states.get_mut(thinker_ent).expect("Couldn't find a component corresponding to the current action. This is definitely a bug.");
*thinker_state = old_state;
}
ActionState::Cancelled => {}
};
} else {
let mut curr_action_state = states.get_mut(action_ent.0).expect("Couldn't find a component corresponding to the current action. This is definitely a bug.");
if *curr_action_state == ActionState::Init {
*curr_action_state = ActionState::Requested;
}
}
} else {
let new_action = picked_action.1.attach(cmd, actor);
thinker.current_action = Some((ActionEnt(new_action), picked_action.clone()));
}
}