1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
/*!
Defines Action-related functionality. This module includes the ActionBuilder trait and some Composite Actions for utility.
*/
use std::sync::Arc;

use bevy::prelude::*;
#[cfg(feature = "trace")]
use bevy::utils::tracing::trace;

use crate::thinker::{Action, ActionSpan, Actor};

/**
The current state for an Action.
*/
#[derive(Debug, Clone, Component, Eq, PartialEq)]
#[component(storage = "SparseSet")]
pub enum ActionState {
    /**
    Initial state. No action should be performed.
    */
    Init,
    /**
    Action requested. The Action-handling system should start executing this Action ASAP and change the status to the next state.
    */
    Requested,
    /**
    The action has ongoing execution. The associated Thinker will try to keep executing this Action as-is until it changes state or it gets Cancelled.
    */
    Executing,
    /**
    An ongoing Action has been cancelled. The Thinker might set this action for you, so for Actions that execute for longer than a single tick, **you must check whether the Cancelled state was set** and change do either Success or Failure. Thinkers will wait on Cancelled actions to do any necessary cleanup work, so this can hang your AI if you don't look for it.
    */
    Cancelled,
    /**
    The Action was a success. This is used by Composite Actions to determine whether to continue execution.
    */
    Success,
    /**
    The Action failed. This is used by Composite Actions to determine whether to halt execution.
    */
    Failure,
}

impl Default for ActionState {
    fn default() -> Self {
        Self::Init
    }
}

impl ActionState {
    pub fn new() -> Self {
        Self::default()
    }
}

#[derive(Debug, Clone, Eq, PartialEq)]
pub(crate) struct ActionBuilderId;

#[derive(Debug, Clone)]
pub(crate) struct ActionBuilderWrapper(pub Arc<ActionBuilderId>, pub Arc<dyn ActionBuilder>);

impl ActionBuilderWrapper {
    pub fn new(builder: Arc<dyn ActionBuilder>) -> Self {
        ActionBuilderWrapper(Arc::new(ActionBuilderId), builder)
    }
}

/**
Trait that must be defined by types in order to be `ActionBuilder`s. `ActionBuilder`s' job is to spawn new `Action` entities on demand. In general, most of this is already done for you, and the only method you really have to implement is `.build()`.

The `build()` method MUST be implemented for any `ActionBuilder`s you want to define.
*/
pub trait ActionBuilder: std::fmt::Debug + Send + Sync {
    /**

    MUST insert your concrete Action component into the Scorer [`Entity`], using
     `cmd`. You _may_ use `actor`, but it's perfectly normal to just ignore it.

    Note that this method is automatically implemented for any Components that
    implement Clone, so you don't need to define it yourself unless you want
    more complex parameterization of your Actions.

    ### Example

    Using `Clone` (the easy way):

    ```no_run
    #[derive(Debug, Clone, Component)]
    struct MyAction;
    ```

    Implementing it manually:

    ```no_run
    struct MyBuilder;
    #[derive(Debug, Component)]
    struct MyAction;

    impl ActionBuilder for MyBuilder {
        fn build(&self, cmd: &mut Commands, action: Entity, actor: Entity) {
            cmd.entity(action).insert(MyAction);
        }
    }
    ```
    */
    fn build(&self, cmd: &mut Commands, action: Entity, actor: Entity);

    /**
     * A label to display when logging using the Action's tracing span.
     */
    fn label(&self) -> Option<&str> {
        None
    }
}

impl<T> ActionBuilder for T
where
    T: Component + Clone + std::fmt::Debug + Send + Sync,
{
    fn build(&self, cmd: &mut Commands, action: Entity, _actor: Entity) {
        cmd.entity(action).insert(T::clone(self));
    }
}

/**
 * Spawns a new Action Component, using the given ActionBuilder. This is useful when you're doing things like writing composite Actions.
 */
pub fn spawn_action<T: ActionBuilder + ?Sized>(
    builder: &T,
    cmd: &mut Commands,
    actor: Entity,
) -> Entity {
    let action_ent = Action(cmd.spawn().id());
    let span = ActionSpan::new(action_ent.entity(), ActionBuilder::label(builder));
    let _guard = span.span().enter();
    debug!("New Action spawned.");
    cmd.entity(action_ent.entity())
        .insert(Name::new("Action"))
        .insert(ActionState::new())
        .insert(Actor(actor));
    builder.build(cmd, action_ent.entity(), actor);
    std::mem::drop(_guard);
    cmd.entity(action_ent.entity()).insert(span);
    action_ent.entity()
}

/**
[`ActionBuilder`] for the [`Steps`] component. Constructed through `Steps::build()`.
*/
#[derive(Debug)]
pub struct StepsBuilder {
    label: Option<String>,
    steps: Vec<Arc<dyn ActionBuilder>>,
}

impl StepsBuilder {
    /**
     * Sets the logging label for the Action
     */
    pub fn label<S: Into<String>>(mut self, label: S) -> Self {
        self.label = Some(label.into());
        self
    }

    /**
    Adds an action step. Order matters.
    */
    pub fn step(mut self, action_builder: impl ActionBuilder + 'static) -> Self {
        self.steps.push(Arc::new(action_builder));
        self
    }
}

impl ActionBuilder for StepsBuilder {
    fn label(&self) -> Option<&str> {
        self.label.as_deref()
    }

    fn build(&self, cmd: &mut Commands, action: Entity, actor: Entity) {
        if let Some(step) = self.steps.get(0) {
            let child_action = spawn_action(step.as_ref(), cmd, actor);
            cmd.entity(action)
                .insert(Name::new("Steps Action"))
                .insert(Steps {
                    active_step: 0,
                    active_ent: Action(child_action),
                    steps: self.steps.clone(),
                })
                .push_children(&[child_action]);
        }
    }
}

/**
Composite Action that executes a series of steps in sequential order, as long as each step results in a `Success`ful [`ActionState`].

### Example

```ignore
Thinker::build()
    .when(
        MyScorer,
        Steps::build()
            .step(MyAction)
            .step(MyNextAction)
        )
```
*/
#[derive(Component, Debug)]
pub struct Steps {
    steps: Vec<Arc<dyn ActionBuilder>>,
    active_step: usize,
    active_ent: Action,
}

impl Steps {
    /**
    Construct a new [`StepsBuilder`] to define the steps to take.
    */
    pub fn build() -> StepsBuilder {
        StepsBuilder {
            steps: Vec::new(),
            label: None,
        }
    }
}

/**
System that takes care of executing any existing [`Steps`] Actions.
*/
pub fn steps_system(
    mut cmd: Commands,
    mut steps_q: Query<(Entity, &Actor, &mut Steps, &ActionSpan)>,
    mut states: Query<&mut ActionState>,
) {
    use ActionState::*;
    for (seq_ent, Actor(actor), mut steps_action, _span) in steps_q.iter_mut() {
        let active_ent = steps_action.active_ent.entity();
        let current_state = states.get_mut(seq_ent).unwrap().clone();
        #[cfg(feature = "trace")]
        let _guard = _span.span().enter();
        match current_state {
            Requested => {
                // Begin at the beginning
                #[cfg(feature = "trace")]
                trace!(
                    "Initializing StepsAction and requesting first step: {:?}",
                    active_ent
                );
                *states.get_mut(active_ent).unwrap() = Requested;
                *states.get_mut(seq_ent).unwrap() = Executing;
            }
            Executing => {
                let mut step_state = states.get_mut(active_ent).unwrap();
                match *step_state {
                    Init => {
                        // Request it! This... should not really happen? But just in case I'm missing something... :)
                        *step_state = Requested;
                    }
                    Executing | Requested => {
                        // do nothing. Everything's running as it should.
                    }
                    Cancelled => {
                        // Wait for the step to wrap itself up, and we'll decide what to do at that point.
                    }
                    Failure => {
                        // Fail ourselves
                        #[cfg(feature = "trace")]
                        trace!("Step {:?} failed. Failing entire StepsAction.", active_ent);
                        let step_state = step_state.clone();
                        let mut seq_state = states.get_mut(seq_ent).expect("idk");
                        *seq_state = step_state;
                        cmd.entity(steps_action.active_ent.entity())
                            .despawn_recursive();
                    }
                    Success if steps_action.active_step == steps_action.steps.len() - 1 => {
                        // We're done! Let's just be successful
                        #[cfg(feature = "trace")]
                        trace!("StepsAction completed all steps successfully.");
                        let step_state = step_state.clone();
                        let mut seq_state = states.get_mut(seq_ent).expect("idk");
                        *seq_state = step_state;
                        cmd.entity(steps_action.active_ent.entity())
                            .despawn_recursive();
                    }
                    Success => {
                        #[cfg(feature = "trace")]
                        trace!("Step succeeded, but there's more steps. Spawning next action.");
                        // Deactivate current step and go to the next step
                        cmd.entity(steps_action.active_ent.entity())
                            .despawn_recursive();

                        steps_action.active_step += 1;
                        let step_builder = steps_action.steps[steps_action.active_step].clone();
                        let step_ent = spawn_action(step_builder.as_ref(), &mut cmd, *actor);
                        #[cfg(feature = "trace")]
                        trace!("Spawned next step: {:?}", step_ent);
                        cmd.entity(seq_ent).push_children(&[step_ent]);
                        steps_action.active_ent = Action(step_ent);
                    }
                }
            }
            Cancelled => {
                // Cancel current action
                #[cfg(feature = "trace")]
                trace!("StepsAction has been cancelled. Cancelling current step {:?} before finalizing.", active_ent);
                let mut step_state = states.get_mut(active_ent).expect("oops");
                if *step_state == Requested || *step_state == Executing {
                    *step_state = Cancelled;
                } else if *step_state == Failure || *step_state == Success {
                    *states.get_mut(seq_ent).unwrap() = step_state.clone();
                }
            }
            Init | Success | Failure => {
                // Do nothing.
            }
        }
    }
}

/**
[`ActionBuilder`] for the [`Concurrently`] component. Constructed through `Concurrently::build()`.
*/
#[derive(Debug)]
pub struct ConcurrentlyBuilder {
    actions: Vec<Arc<dyn ActionBuilder>>,
    label: Option<String>,
}

impl ConcurrentlyBuilder {
    /**
     * Sets the logging label for the Action
     */
    pub fn label<S: Into<String>>(mut self, label: S) -> Self {
        self.label = Some(label.into());
        self
    }

    /**
    Add an action to execute. Order does not matter.
    */
    pub fn push(mut self, action_builder: impl ActionBuilder + 'static) -> Self {
        self.actions.push(Arc::new(action_builder));
        self
    }
}

impl ActionBuilder for ConcurrentlyBuilder {
    fn label(&self) -> Option<&str> {
        self.label.as_deref()
    }

    fn build(&self, cmd: &mut Commands, action: Entity, actor: Entity) {
        let children: Vec<Entity> = self
            .actions
            .iter()
            .map(|action| spawn_action(action.as_ref(), cmd, actor))
            .collect();
        cmd.entity(action)
            .insert(Name::new("Concurrent Action"))
            .push_children(&children[..])
            .insert(Concurrently {
                actions: children.into_iter().map(Action).collect(),
            });
    }
}

/**
Composite Action that executes a number of Actions concurrently, as long as they all result in a `Success`ful [`ActionState`].

### Example

```ignore
Thinker::build()
    .when(
        MyScorer,
        Concurrent::build()
            .push(MyAction)
            .push(MyOtherAction)
        )
```
*/
#[derive(Component, Debug)]
pub struct Concurrently {
    actions: Vec<Action>,
}

impl Concurrently {
    /**
    Construct a new [`ConcurrentlyBuilder`] to define the actions to take.
    */
    pub fn build() -> ConcurrentlyBuilder {
        ConcurrentlyBuilder {
            actions: Vec::new(),
            label: None,
        }
    }
}

/**
System that takes care of executing any existing [`Concurrently`] Actions.
*/
pub fn concurrent_system(
    concurrent_q: Query<(Entity, &Concurrently, &ActionSpan)>,
    mut states_q: Query<&mut ActionState>,
) {
    use ActionState::*;
    for (seq_ent, concurrent_action, _span) in concurrent_q.iter() {
        let current_state = states_q.get_mut(seq_ent).expect("uh oh").clone();
        #[cfg(feature = "trace")]
        let _guard = _span.span.enter();
        match current_state {
            Requested => {
                #[cfg(feature = "trace")]
                trace!(
                    "Initializing Concurrently action with {} children.",
                    concurrent_action.actions.len()
                );
                // Begin at the beginning
                let mut current_state = states_q.get_mut(seq_ent).expect("uh oh");
                *current_state = Executing;
                for action in concurrent_action.actions.iter() {
                    let child_ent = action.entity();
                    let mut child_state = states_q.get_mut(child_ent).expect("uh oh");
                    *child_state = Requested;
                }
            }
            Executing => {
                let mut all_success = true;
                let mut failed_idx = None;
                for (idx, action) in concurrent_action.actions.iter().enumerate() {
                    let child_ent = action.entity();
                    let mut child_state = states_q.get_mut(child_ent).expect("uh oh");
                    match *child_state {
                        Failure => {
                            failed_idx = Some(idx);
                            all_success = false;
                            #[cfg(feature = "trace")]
                            trace!("Concurrently action has failed. Cancelling all other actions that haven't completed yet.");
                        }
                        Success => {}
                        _ => {
                            all_success = false;
                            if failed_idx.is_some() {
                                *child_state = Cancelled;
                            }
                        }
                    }
                }
                if all_success {
                    let mut state_var = states_q.get_mut(seq_ent).expect("uh oh");
                    *state_var = Success;
                } else if let Some(idx) = failed_idx {
                    for action in concurrent_action.actions.iter().take(idx) {
                        let child_ent = action.entity();
                        let mut child_state = states_q.get_mut(child_ent).expect("uh oh");
                        match *child_state {
                            Failure | Success => {}
                            _ => {
                                *child_state = Cancelled;
                            }
                        }
                    }
                    let mut state_var = states_q.get_mut(seq_ent).expect("uh oh");
                    *state_var = Cancelled;
                }
            }
            Cancelled => {
                // Cancel all actions
                let mut all_done = true;
                let mut any_failed = false;
                for action in concurrent_action.actions.iter() {
                    let child_ent = action.entity();
                    let mut child_state = states_q.get_mut(child_ent).expect("uh oh");
                    match *child_state {
                        Init | Success => {
                            // Do nothing
                        }
                        Failure => {
                            any_failed = true;
                        }
                        _ => {
                            all_done = false;
                            *child_state = Cancelled;
                        }
                    }
                }
                if all_done {
                    let mut state_var = states_q.get_mut(seq_ent).expect("uh oh");
                    if any_failed {
                        #[cfg(feature = "trace")]
                        trace!("Concurrently action has failed due to failed children.");
                        *state_var = Failure;
                    } else {
                        #[cfg(feature = "trace")]
                        trace!("All Concurrently children have completed Successfully.");
                        *state_var = Success;
                    }
                }
            }
            Init | Success | Failure => {
                // Do nothing.
            }
        }
    }
}