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
use std::sync::{Arc, Mutex};

use bevy::ecs::entity::Entity;

use crate::{Node, NodeGen, nullable_access::NullableWorldAccess, NodeResult};
use super::ResultConverter;


/// Invert the result of the child.
pub struct Invert {
    delegate: Arc<ResultConverter>,
}
impl Node for Invert {
    fn run(self: Arc<Self>, world: Arc<Mutex<NullableWorldAccess>>, entity: Entity) -> Box<dyn NodeGen> {
        self.delegate.clone().run(world, entity)
    }
}
impl Invert {
    pub fn new(child: Arc<dyn Node>) -> Arc<Self> {
        Arc::new(Self {
            delegate: ResultConverter::new(child, |res| !res)
        })
    }
}

/// Returns the specified result whatever the child returns.
pub struct ForceResult {
    delegate: Arc<ResultConverter>,
}
impl Node for ForceResult {
    fn run(self: Arc<Self>, world: Arc<Mutex<NullableWorldAccess>>, entity: Entity) -> Box<dyn NodeGen> {
        self.delegate.clone().run(world, entity)
    }
}
impl ForceResult {
    pub fn new(child: Arc<dyn Node>, result: NodeResult) -> Arc<Self> {
        Arc::new(Self {
            delegate: ResultConverter::new(child, move |_| result.into())
        })
    }
}


#[cfg(test)]
mod tests {
    use crate::tester_util::*;

    #[test]
    fn test_invert() {
        let mut app = App::new();
        app.add_plugins((BehaviorTreePlugin::default(), TesterPlugin));
        let task = TesterTask::<0>::new(1, TaskState::Success);
        let converter = Invert::new(task);
        let tree = BehaviorTree::new(converter);
        let entity = app.world.spawn(tree).id();
        app.update();
        app.update();
        let tree = app.world.get::<BehaviorTree>(entity).unwrap();
        assert!(
            tree.result.unwrap() == NodeResult::Failure,
            "Invert should match the result. found: {:?}", tree.result.unwrap() 
        );
    }

    #[test]
    fn test_force_result() {
        let mut app = App::new();
        app.add_plugins((BehaviorTreePlugin::default(), TesterPlugin));
        let task = TesterTask::<0>::new(1, TaskState::Success);
        let converter = ForceResult::new(task, NodeResult::Failure);
        let tree = BehaviorTree::new(converter);
        let entity = app.world.spawn(tree).id();
        app.update();
        app.update();
        let tree = app.world.get::<BehaviorTree>(entity).unwrap();
        assert!(
            tree.result.unwrap() == NodeResult::Failure,
            "ForceResult should match the result. found: {:?}", tree.result.unwrap() 
        );
    }

}