stackbt_behavior_tree 0.1.1

Behavior Trees for StackBT
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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
use behavior_tree_node::{BehaviorTreeNode, NodeResult, Statepoint};
use std::marker::PhantomData;

pub struct GuardFailure<N>(pub N); 

/// A node guard predicate. 
pub trait NodeGuard {
    /// Type of the input to take. 
    type Input;
    /// Type of the nonterminal to take. 
    type Nonterminal;
    /// Given references to the input taken and the nonterminal returned, 
    /// determine whether to keep running the node (true) or end its 
    /// execution prematurely (false). 
    fn test(&Self::Input, &Self::Nonterminal) -> bool;
}

/// Guard wrapper for a node, which, if the guard condition fails, causes an 
/// abnormal exit of the node. 
pub struct GuardedNode<N, G> where
    N: BehaviorTreeNode,
    G: NodeGuard<Input=N::Input, Nonterminal=N::Nonterminal>
{
    node: N,
    _exists_tuple: PhantomData<G>
}

impl<N, G> GuardedNode<N, G> where 
    N: BehaviorTreeNode,
    G: NodeGuard<Input=N::Input, Nonterminal=N::Nonterminal>
{
    /// Create a new guarded node. 
    pub fn new(node: N) -> GuardedNode<N, G> {
        GuardedNode {
            node: node,
            _exists_tuple: PhantomData
        }
    }

    /// Create a new guarded node, using, using a dummy object to supply the 
    /// type of the node guard. 
    pub fn with(_type_helper: G, node: N) -> GuardedNode<N, G> {
        GuardedNode {
            node: node,
            _exists_tuple: PhantomData
        }
    }
}

impl<N, G> Default for GuardedNode<N, G> where 
    N: BehaviorTreeNode + Default,
    G: NodeGuard<Input=N::Input, Nonterminal=N::Nonterminal>
{
    fn default() -> GuardedNode<N, G> {
        GuardedNode::new(N::default())
    }
}

impl<N, G> BehaviorTreeNode for GuardedNode<N, G> where
    N: BehaviorTreeNode,
    G: NodeGuard<Input=N::Input, Nonterminal=N::Nonterminal>
{
    type Input = N::Input;
    type Nonterminal = N::Nonterminal;
    type Terminal = Result<N::Terminal, GuardFailure<N::Nonterminal>>;

    #[inline]
    fn step(self, input: &N::Input) -> NodeResult<N::Nonterminal, 
        Self::Terminal, Self> 
    {
        match self.node.step(input) {
            NodeResult::Nonterminal(n, m) => {
                if G::test(input, &n) {
                    NodeResult::Nonterminal(n, GuardedNode::new(m))
                } else {
                    NodeResult::Terminal(Result::Err(GuardFailure(n)))
                }
            },
            NodeResult::Terminal(t) => NodeResult::Terminal(
                Result::Ok(t)
            )
        }
    }
}

/// Enumeration of the possible decisions of a StepControl controller.
pub enum StepDecision {
    /// Don't step the machine. 
    Pause, 
    /// Step the machine as normal. 
    Play, 
    /// Dispose the current machine, and initialize a new one in its place. 
    Reset, 
    /// Reset the machine, and then subsequently step it. 
    ResetPlay
}

/// Step controller for a node. 
pub trait StepControl {
    /// Type of the input to take. 
    type Input;
    /// Given a reference to the input, determine whether to pause, play, 
    /// and/or reset the enclosed node before it starts. 
    fn controlled_step(&Self::Input) -> StepDecision;
}

/// Nonterminal enum for a step-controlled node. 
pub enum StepCtrlNonterm<I> {
    /// The node was stepped as normal, perhaps after resetting it. 
    Stepped(I),
    /// The node was paused, and maybe reset. 
    Paused
}

/// A step-controlling wrapper for a node, which may pause, step, and/or 
/// reset a node depending on inputs, before the node goes forward. 
pub struct StepControlledNode<N, S> where 
    N: BehaviorTreeNode + Default,
    S: StepControl<Input=N::Input>
{
    node: N,
    _exists_tuple: PhantomData<S>
}

impl<N, S> StepControlledNode<N, S> where 
    N: BehaviorTreeNode + Default,
    S: StepControl<Input=N::Input>
{
    /// Create a new step controlled node. 
    pub fn new(node: N) -> StepControlledNode<N, S> {
        StepControlledNode {
            node: node,
            _exists_tuple: PhantomData
        }
    }

    /// Create a new step controlled node, using, using a dummy object to 
    /// supply the type of the step controller.  
    pub fn with(_type_assist: S, node: N) -> StepControlledNode<N, S> {
        StepControlledNode {
            node: node,
            _exists_tuple: PhantomData
        }
    }
}

impl<N, S> Default for StepControlledNode<N, S> where 
    N: BehaviorTreeNode + Default,
    S: StepControl<Input=N::Input>
{
    fn default() -> StepControlledNode<N, S> {
        StepControlledNode::new(N::default())
    }
}

impl<N, S> BehaviorTreeNode for StepControlledNode<N, S> where 
    N: BehaviorTreeNode + Default,
    S: StepControl<Input=N::Input>
{
    type Input = N::Input;
    type Nonterminal = StepCtrlNonterm<N::Nonterminal>;
    type Terminal = N::Terminal;
    
    #[inline]
    fn step(self, input: &N::Input) -> NodeResult<Self::Nonterminal, 
        N::Terminal, Self> 
    {
        match S::controlled_step(input) {
            StepDecision::Pause => {
                NodeResult::Nonterminal(StepCtrlNonterm::Paused, self)
            },
            StepDecision::Play => {
                match self.node.step(input) {
                    NodeResult::Nonterminal(n, m) => {
                        NodeResult::Nonterminal(
                            StepCtrlNonterm::Stepped(n), 
                            Self::new(m)
                        )
                    },
                    NodeResult::Terminal(t) => NodeResult::Terminal(t)
                }
            },
            StepDecision::Reset => {
                NodeResult::Nonterminal(StepCtrlNonterm::Paused, Self::default())
            },
            StepDecision::ResetPlay => {
                let mut new_machine = N::default();
                match new_machine.step(input) {
                    NodeResult::Nonterminal(n, m) => {
                        NodeResult::Nonterminal(
                            StepCtrlNonterm::Stepped(n), 
                            Self::new(m)
                        )
                    },
                    NodeResult::Terminal(t) => NodeResult::Terminal(t)
                }
            }
        }
    }
}

pub enum PostResetNonterm<N, T> {
    /// The node was not reset. 
    NoReset(N),
    /// The node was reset from a nonterminal state. 
    ManualReset(N),
    /// The node was reset from a terminal state. 
    EndReset(T)
}

/// A post-resetting wrapper for a node, which after a node plays, may 
/// or may not reset that node. 
pub trait PostResetControl {
    /// Type of the input to take. 
    type Input;
    /// Type of the nonterminal to take. 
    type Nonterminal;
    /// Type of the terminal to take. 
    type Terminal;
    /// Given a reference to the input and a statepoint corresponding to the 
    /// enclosed node's state, return whether to reset it (true) or not 
    /// (false) after it runs. 
    fn do_reset(&Self::Input, Statepoint<&Self::Nonterminal, 
        &Self::Terminal>) -> bool;
}

/// A post-run resetting wrapper for a node, which may reset a node after 
/// it runs. 
pub struct PostResetNode<N, P> where 
    N: BehaviorTreeNode + Default,
    P: PostResetControl<Input=N::Input, Nonterminal=N::Nonterminal, 
        Terminal=N::Terminal>
{
    node: N,
    _exists_tuple: PhantomData<P>
}

impl<N, P> PostResetNode<N, P> where 
    N: BehaviorTreeNode + Default,
    P: PostResetControl<Input=N::Input, Nonterminal=N::Nonterminal, 
        Terminal=N::Terminal>
{
    /// Create a new step controlled node. 
    pub fn new(node: N) -> PostResetNode<N, P> {
        PostResetNode {
            node: node,
            _exists_tuple: PhantomData
        }
    }

    /// Create a new step controlled node, using a dummy object to supply the 
    /// type of the reset controller. 
    pub fn with(_type_assist: P, node: N) -> PostResetNode<N, P> {
        PostResetNode {
            node: node,
            _exists_tuple: PhantomData
        }
    }
}


impl<N, P> Default for PostResetNode<N, P> where 
    N: BehaviorTreeNode + Default,
    P: PostResetControl<Input=N::Input, Nonterminal=N::Nonterminal, 
        Terminal=N::Terminal>
{
    fn default() -> PostResetNode<N, P> {
        PostResetNode::new(N::default())
    }
}

impl <N, P> BehaviorTreeNode for PostResetNode<N, P> where 
    N: BehaviorTreeNode + Default,
    P: PostResetControl<Input=N::Input, Nonterminal=N::Nonterminal, 
        Terminal=N::Terminal>
{
    type Input = N::Input;
    type Nonterminal = PostResetNonterm<N::Nonterminal, N::Terminal>;
    type Terminal = N::Terminal;

    #[inline]
    fn step(self, input: &N::Input) -> NodeResult<Self::Nonterminal, 
        N::Terminal, Self> 
    {
        match self.node.step(input) {
            NodeResult::Nonterminal(v, n) => {
                if P::do_reset(input, Statepoint::Nonterminal(&v)) {
                    NodeResult::Nonterminal(
                        PostResetNonterm::ManualReset(v), 
                        Self::default()
                    )
                } else {
                    NodeResult::Nonterminal(
                        PostResetNonterm::NoReset(v), 
                        Self::new(n)
                    )
                }
            },
            NodeResult::Terminal(t) => {
                if P::do_reset(input, Statepoint::Terminal(&t)) {
                    NodeResult::Nonterminal(
                        PostResetNonterm::EndReset(t),
                        Self::default()
                    )
                } else {
                    NodeResult::Terminal(t)
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use stackbt_automata_impl::ref_state_machine::ReferenceTransition;
    use base_nodes::{WaitCondition, PredicateWait};
    use behavior_tree_node::{BehaviorTreeNode, NodeResult, Statepoint};
    use control_wrappers::{NodeGuard, StepControl, StepDecision, PostResetControl};

    struct Echoer;

    impl WaitCondition for Echoer {
        type Input = i64;
        type Nonterminal = i64;
        type Terminal = i64;
        fn do_end(input: &i64) -> Statepoint<i64, i64> {
            if *input > 0 {
                Statepoint::Nonterminal(*input)
            } else {
                Statepoint::Terminal(*input)
            }
        }
    }

    struct MagGuard;

    impl NodeGuard for MagGuard {
        type Input = i64;
        type Nonterminal = i64;
        fn test(input: &i64, _whocares: &i64) -> bool {
            *input > 5
        }
    }

    #[test]
    fn guarded_node_test() {
        use control_wrappers::{GuardedNode, GuardFailure};
        let base_node = PredicateWait::with(Echoer);
        let wrapped_node = GuardedNode::with(MagGuard, base_node);
        let wrapped_node_1 = match wrapped_node.step(&7) {
            NodeResult::Nonterminal(v, m) => {
                assert_eq!(v, 7);
                m
            },
            NodeResult::Terminal(_) => unreachable!("Expected nonterminal state")
        };
        match wrapped_node_1.step(&4) {
            NodeResult::Nonterminal(_, _) => unreachable!("Expected terminal state"),
            NodeResult::Terminal(x) => {
                match x {
                    Result::Err(GuardFailure(x)) => {
                        assert_eq!(x, 4)
                    },
                    Result::Ok(_) => unreachable!("Expected guard failure")
                }
            }
        };
    }

    struct MagicPlayer;

    impl StepControl for MagicPlayer {
        type Input = i64;
        fn controlled_step(input: &i64) -> StepDecision {
            match *input {
                -1 =>  StepDecision::Pause,
                -2 => StepDecision::Reset,
                7 => StepDecision::ResetPlay,
                _ => StepDecision::Play
            }
        }
    }

    #[derive(Copy, Clone)]
    enum Ratchet {
        Zero,
        One,
        Two,
        Three
    }

    impl Default for Ratchet {
        fn default() -> Ratchet {
            Ratchet::Zero
        }
    }

    impl ReferenceTransition for Ratchet {
        type Input = i64;
        type Action = Statepoint<i64, ()>;

        fn step(self, input: &i64) -> (Statepoint<i64, ()>, Self) {
            match self {
                Ratchet::Zero => match input {
                    3 => (Statepoint::Nonterminal(3), Ratchet::Three),
                    2 => (Statepoint::Nonterminal(2), Ratchet::Two),
                    1 => (Statepoint::Nonterminal(1), Ratchet::One),
                    _ => (Statepoint::Nonterminal(0), Ratchet::Zero)
                },
                Ratchet::One => match input {
                    3 => (Statepoint::Nonterminal(3), Ratchet::Three),
                    2 => (Statepoint::Nonterminal(2), Ratchet::Two),
                    _ => (Statepoint::Nonterminal(1), Ratchet::One)
                },
                Ratchet::Two => match input {
                    3 => (Statepoint::Nonterminal(3), Ratchet::Three),
                    _ => (Statepoint::Nonterminal(2), Ratchet::Two),
                },
                Ratchet::Three => (Statepoint::Terminal(()), Ratchet::Three)
            }
        }
    }

    #[test]
    fn step_control_test() {
        use control_wrappers::{StepControlledNode, StepCtrlNonterm};
        use base_nodes::MachineWrapper;
        use stackbt_automata_impl::ref_state_machine::RefStateMachine;
        let machine = RefStateMachine::new(Ratchet::Zero);
        let base_node = MachineWrapper::new(machine);
        let wrapped_node = StepControlledNode::with(MagicPlayer, base_node);
        let wrapped_node_1 = match wrapped_node.step(&-1) {
            NodeResult::Nonterminal(v, m) => {
                match v {
                    StepCtrlNonterm::Paused => (),
                    _ => unreachable!("Node was paused")
                };
                m
            },
            _ => unreachable!("Expected nonterminal transition"),
        };
        let wrapped_node_2 = match wrapped_node_1.step(&2) {
            NodeResult::Terminal(_) => unreachable!("Expected nonterminal transition"),
            NodeResult::Nonterminal(v, m) => {
                match v {
                    StepCtrlNonterm::Stepped(x) => assert_eq!(x, 2),
                    _ => unreachable!("Node was played"),
                };
                m
            }
        };
        let wrapped_node_3 = match wrapped_node_2.step(&-2) {
            NodeResult::Nonterminal(v, m) => {
                match v {
                    StepCtrlNonterm::Paused => (),
                    _ => unreachable!("Node was reset")
                };
                m
            },
            _ => unreachable!("Expected nonterminal transition"),
        };
        let wrapped_node_4 = match wrapped_node_3.step(&2) {
            NodeResult::Nonterminal(v, m) => {
                match v {
                    StepCtrlNonterm::Paused => unreachable!("Node was played"),
                    StepCtrlNonterm::Stepped(x) => assert_eq!(x, 2)
                };
                m
            },
            _ => unreachable!("Expected nonterminal transition"),
        };
        match wrapped_node_4.step(&7) {
            NodeResult::Nonterminal(v, _) => {
                match v {
                    StepCtrlNonterm::Paused => unreachable!("Node was played"),
                    StepCtrlNonterm::Stepped(x) => assert_eq!(x, 0)
                };
            },
            _ => unreachable!("Expected nonterminal transition"),
        };
    }

    struct Resetter;

    impl PostResetControl for Resetter {
        type Input = i64;
        type Nonterminal = i64;
        type Terminal = ();

        fn do_reset(input: &i64, _output: Statepoint<&i64, &()>) -> bool {
            *input == -5 || *input == 5
        }
    }

    #[test]
    fn post_reset_test() {
        use control_wrappers::{PostResetNode, PostResetNonterm};
        use base_nodes::MachineWrapper;
        use stackbt_automata_impl::ref_state_machine::RefStateMachine;
        let machine = RefStateMachine::new(Ratchet::Zero);
        let base_node = MachineWrapper::new(machine);
        let wrapped_node = PostResetNode::with(Resetter, base_node);
        let wrapped_node_1 = match wrapped_node.step(&1) {
            NodeResult::Nonterminal(v, n) => {
                match v {
                    PostResetNonterm::NoReset(val) => assert_eq!(val, 1),
                    _ => unreachable!("Node was not reset")
                };
                n
            },
            _ => unreachable!("Expected nonterminal transition")
        };
        let wrapped_node_2 = match wrapped_node_1.step(&5) {
            NodeResult::Nonterminal(v, n) => {
                match v {
                    PostResetNonterm::ManualReset(val) => assert_eq!(val, 1),
                    _ => unreachable!("Node was not reset")
                };
                n
            },
            _ => unreachable!("Expected nonterminal transition")
        };
        let wrapped_node_3 = match wrapped_node_2.step(&0) {
            NodeResult::Nonterminal(v, n) => {
                match v {
                    PostResetNonterm::NoReset(val) => assert_eq!(val, 0),
                    _ => unreachable!("Node was manually reset")
                };
                n
            },
            _ => unreachable!("Expected nonterminal transition")
        };
        let wrapped_node_4 = match wrapped_node_3.step(&3) {
            NodeResult::Nonterminal(v, n) => {
                match v {
                    PostResetNonterm::NoReset(val) => assert_eq!(val, 3),
                    _ => unreachable!("Node was end reset")
                };
                n
            },
            _ => unreachable!("Expected nonterminal transition")
        };
        let wrapped_node_5 = match wrapped_node_4.step(&5) {
            NodeResult::Nonterminal(v, n) => {
                match v {
                    PostResetNonterm::EndReset(val) => assert_eq!(val, ()),
                    _ => unreachable!("Node was end reset")
                };
                n
            },
            _ => unreachable!("Expected nonterminal transition")
        };
        let wrapped_node_6 = match wrapped_node_5.step(&3) {
            NodeResult::Nonterminal(v, n) => {
                match v {
                    PostResetNonterm::NoReset(val) => assert_eq!(val, 3),
                    _ => unreachable!("Node was end reset")
                };
                n
            },
            _ => unreachable!("Expected nonterminal transition")
        };
        match wrapped_node_6.step(&3) {
            NodeResult::Terminal(()) => (),
            _ => unreachable!("Expected terminal transition")
        };
    }
}